@myrialabs/clopen 0.4.30 → 0.4.32
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.test.ts +0 -1
- package/backend/auth/permissions.ts +0 -4
- package/backend/chat/stream-manager.ts +28 -12
- package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
- package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/engine/README.md +16 -0
- package/backend/engine/adapters/claude/stream.ts +89 -49
- package/backend/engine/adapters/cline/stream.ts +62 -24
- package/backend/engine/adapters/codex/stream.ts +51 -21
- package/backend/engine/adapters/copilot/stream.ts +96 -52
- package/backend/engine/adapters/cursor/stream.ts +74 -34
- package/backend/engine/adapters/opencode/server.ts +512 -126
- package/backend/engine/adapters/opencode/stream.ts +131 -79
- package/backend/engine/adapters/pi/stream.ts +63 -24
- package/backend/engine/adapters/qwen/stream.ts +91 -58
- package/backend/engine/adapters/run-registry.test.ts +75 -0
- package/backend/engine/adapters/run-registry.ts +63 -0
- package/backend/engine/bootstrap-default-engine.ts +67 -38
- package/backend/engine/config-revision.ts +150 -0
- package/backend/engine/docs/adapter-contract.md +40 -9
- package/backend/engine/docs/adding-an-engine.md +8 -0
- package/backend/engine/docs/frontend-and-chat.md +39 -0
- package/backend/engine/docs/lessons-learned.md +70 -0
- package/backend/engine/docs/quick-reference.md +3 -1
- package/backend/engine/engine-cli.ts +313 -0
- package/backend/engine/engine-setup.ts +40 -3
- package/backend/engine/hot-reload.ts +99 -0
- package/backend/engine/index.ts +96 -24
- package/backend/engine/install-recipes.test.ts +99 -5
- package/backend/engine/install-recipes.ts +47 -11
- package/backend/engine/install-runner.ts +34 -16
- package/backend/engine/stack-project.ts +72 -0
- package/backend/engine/types.ts +17 -5
- package/backend/git/git-executor.ts +22 -3
- package/backend/git/git-service.ts +1 -1
- package/backend/git/nested-repos.test.ts +121 -0
- package/backend/git/nested-repos.ts +301 -0
- package/backend/index.ts +7 -0
- package/backend/snapshot/gitignore.ts +10 -174
- package/backend/utils/path-enrich.ts +2 -0
- package/backend/ws/chat/stream.ts +24 -0
- package/backend/ws/engine/claude/accounts.ts +9 -4
- package/backend/ws/engine/codex/accounts.ts +8 -17
- package/backend/ws/engine/codex/status.ts +10 -17
- package/backend/ws/engine/copilot/accounts.ts +0 -10
- package/backend/ws/engine/cursor/accounts.ts +0 -10
- package/backend/ws/engine/index.ts +17 -2
- package/backend/ws/engine/opencode/providers.ts +0 -52
- package/backend/ws/files/read.ts +1 -1
- package/backend/ws/git/conflict.ts +1 -1
- package/backend/ws/git/diff.ts +1 -1
- package/backend/ws/git/staging.ts +1 -1
- package/backend/ws/git/status.ts +1 -1
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/stack/access.ts +5 -2
- package/dist/assets/{index-DYwQ5bP8.js → index-DSvGoxp2.js} +1 -1
- package/dist/assets/{index-DUc5T21e.js → index-hu17G6tX.js} +1 -1
- package/dist/assets/main-BccclZsC.js +1031 -0
- package/dist/assets/{main-VgdjTBLR.css → main-Ciuw0wF0.css} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/backend/ws/engine/restart.ts +0 -54
- package/dist/assets/main-r0iv2PDz.js +0 -1044
|
@@ -64,12 +64,10 @@ export const ADMIN_ONLY_ROUTES = new Set([
|
|
|
64
64
|
'engine:codex-accounts-rename',
|
|
65
65
|
'engine:codex-account-setup-start',
|
|
66
66
|
'engine:codex-account-setup-cancel',
|
|
67
|
-
'engine:codex-restart',
|
|
68
67
|
'engine:copilot-accounts-add',
|
|
69
68
|
'engine:copilot-accounts-switch',
|
|
70
69
|
'engine:copilot-accounts-delete',
|
|
71
70
|
'engine:copilot-accounts-rename',
|
|
72
|
-
'engine:copilot-restart',
|
|
73
71
|
'engine:qwen-accounts-add',
|
|
74
72
|
'engine:qwen-accounts-switch',
|
|
75
73
|
'engine:qwen-accounts-delete',
|
|
@@ -98,9 +96,7 @@ export const ADMIN_ONLY_ROUTES = new Set([
|
|
|
98
96
|
'engine:opencode-account-switch',
|
|
99
97
|
'engine:opencode-account-delete',
|
|
100
98
|
'engine:opencode-account-rename',
|
|
101
|
-
'engine:opencode-server-restart',
|
|
102
99
|
'engine:opencode-models-dev-fetch',
|
|
103
|
-
'engine:restart-all',
|
|
104
100
|
// Tunnel — remote/local management mutates global Cloudflare credentials,
|
|
105
101
|
// cloudflared auth, and ingress rules. Quick Tunnel is ephemeral and stays
|
|
106
102
|
// open. Read-only routes (status, *-list, ingress, auth-status) stay open so
|
|
@@ -33,7 +33,7 @@ import type {
|
|
|
33
33
|
} from '$shared/types/unified';
|
|
34
34
|
import type { EngineType } from '$shared/types/unified';
|
|
35
35
|
import type { DatabaseMessage } from '$shared/types/database/schema';
|
|
36
|
-
import {
|
|
36
|
+
import { initializeProjectEngine, type AIEngine } from '../engine';
|
|
37
37
|
import { messageQueries, projectQueries, sessionQueries } from '../database/queries';
|
|
38
38
|
import { snapshotService } from '../snapshot/snapshot-service';
|
|
39
39
|
import { snapshotQueries } from '../database/queries/snapshot-queries';
|
|
@@ -71,6 +71,17 @@ export interface StreamState {
|
|
|
71
71
|
error?: string;
|
|
72
72
|
abortController?: AbortController;
|
|
73
73
|
streamPromise?: Promise<void>;
|
|
74
|
+
/**
|
|
75
|
+
* The engine instance actually running this stream.
|
|
76
|
+
*
|
|
77
|
+
* Pinned rather than looked up by (projectId, engineType), because the cache
|
|
78
|
+
* behind that lookup is now replaced whenever engine config changes. Looking
|
|
79
|
+
* it up again would hand back the REPLACEMENT: an instance with no query to
|
|
80
|
+
* cancel and no pending question to answer, so Stop would do nothing and an
|
|
81
|
+
* AskUserQuestion answer would go nowhere — and only for users unlucky enough
|
|
82
|
+
* to have changed a setting while a chat was running.
|
|
83
|
+
*/
|
|
84
|
+
engineInstance?: AIEngine;
|
|
74
85
|
sdkSessionId?: string;
|
|
75
86
|
preStreamSessionId?: string | null;
|
|
76
87
|
hasCompactBoundary?: boolean;
|
|
@@ -661,6 +672,7 @@ class StreamManager extends EventEmitter {
|
|
|
661
672
|
if (chatSessionId) deferEpisodicIngest(chatSessionId);
|
|
662
673
|
|
|
663
674
|
const engine = await initializeProjectEngine(projectId, requestEngine.type);
|
|
675
|
+
streamState.engineInstance = engine;
|
|
664
676
|
|
|
665
677
|
if ((streamState.status as string) === 'cancelled' || streamState.abortController?.signal.aborted) {
|
|
666
678
|
debug.log('chat', 'Stream cancelled during engine initialization, skipping query');
|
|
@@ -815,7 +827,7 @@ class StreamManager extends EventEmitter {
|
|
|
815
827
|
// exact fix (Stack to install/update, Engines to sign in). Thrown here
|
|
816
828
|
// so the processStream catch surfaces it as a chat error, which the
|
|
817
829
|
// ErrorMessage renderer turns into a one-click action.
|
|
818
|
-
const setupIssue = checkEngineSetup(requestEngine.type, requestEngine.account.id);
|
|
830
|
+
const setupIssue = await checkEngineSetup(requestEngine.type, requestEngine.account.id);
|
|
819
831
|
if (setupIssue) throw new Error(setupIssue.message);
|
|
820
832
|
|
|
821
833
|
// Stream EngineOutput events through the engine adapter
|
|
@@ -1391,10 +1403,10 @@ class StreamManager extends EventEmitter {
|
|
|
1391
1403
|
return false;
|
|
1392
1404
|
}
|
|
1393
1405
|
|
|
1394
|
-
// The stream is live, so
|
|
1395
|
-
//
|
|
1396
|
-
|
|
1397
|
-
const engine =
|
|
1406
|
+
// The stream is live, so it is holding the engine that owns the pending
|
|
1407
|
+
// question. Use that one — a replacement instance holds no question to
|
|
1408
|
+
// answer, and a fresh one would not even be the same process.
|
|
1409
|
+
const engine = streamState.engineInstance;
|
|
1398
1410
|
|
|
1399
1411
|
if (!engine?.resolveUserAnswer) {
|
|
1400
1412
|
debug.warn('chat', 'resolveUserAnswer: Engine does not support resolveUserAnswer');
|
|
@@ -1523,17 +1535,21 @@ class StreamManager extends EventEmitter {
|
|
|
1523
1535
|
debug.log('mcp', `✅ Auto-released MCP tabs for session ${streamState.chatSessionId.slice(0, 8)} on stream cancellation`);
|
|
1524
1536
|
}
|
|
1525
1537
|
|
|
1526
|
-
//
|
|
1527
|
-
// engine.cancel() stops the SDK
|
|
1538
|
+
// Stop this stream's run on the engine, with a bounded timeout.
|
|
1539
|
+
// engine.cancel() stops the SDK work (Claude Code: close() kills subprocess,
|
|
1528
1540
|
// OpenCode: aborts controller + HTTP abort to server). If cancel() hangs
|
|
1529
1541
|
// (e.g. unresponsive SDK), the timeout ensures we always proceed to emit
|
|
1530
1542
|
// events and update presence — preventing infinite loader on the frontend.
|
|
1531
|
-
|
|
1543
|
+
//
|
|
1544
|
+
// The abortController identifies WHICH run to stop. One engine instance is
|
|
1545
|
+
// shared by every chat session of a project, so an untargeted cancel stops
|
|
1546
|
+
// whichever run the instance happened to have on hand — cancelling one chat
|
|
1547
|
+
// would kill another chat of the same project mid-answer.
|
|
1532
1548
|
try {
|
|
1533
|
-
const engine =
|
|
1534
|
-
if (engine
|
|
1549
|
+
const engine = streamState.engineInstance;
|
|
1550
|
+
if (engine && streamState.abortController) {
|
|
1535
1551
|
await Promise.race([
|
|
1536
|
-
engine.cancel(),
|
|
1552
|
+
engine.cancel(streamState.abortController),
|
|
1537
1553
|
new Promise<void>(resolve => setTimeout(resolve, 5000))
|
|
1538
1554
|
]);
|
|
1539
1555
|
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The revision counter is the only thing that notices a config edit now.
|
|
3
|
+
*
|
|
4
|
+
* Removing the "Restart Server" button removed the manual way to make an edit
|
|
5
|
+
* take effect, so a trigger that silently stops firing is no longer a small bug —
|
|
6
|
+
* it is config that never applies, with nothing in the UI to work around it. The
|
|
7
|
+
* two properties worth pinning down are that watched writes DO bump (or the
|
|
8
|
+
* feature is dead) and that bookkeeping writes DON'T (or every unrelated update
|
|
9
|
+
* respawns a server).
|
|
10
|
+
*
|
|
11
|
+
* Runs against a real in-memory SQLite rather than a mocked handle: the whole
|
|
12
|
+
* mechanism IS the SQL, and a mock that returns what the test expects would
|
|
13
|
+
* assert nothing about whether `UPDATE OF` scopes the way it is supposed to.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { describe, expect, test } from 'bun:test';
|
|
17
|
+
import { Database } from 'bun:sqlite';
|
|
18
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
19
|
+
import { up } from './068_create_engine_config_revision';
|
|
20
|
+
|
|
21
|
+
/** Only the columns the triggers name — enough to exercise them faithfully. */
|
|
22
|
+
function freshDb(): Database {
|
|
23
|
+
const db = new Database(':memory:');
|
|
24
|
+
db.exec(`
|
|
25
|
+
CREATE TABLE mcp_servers (
|
|
26
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
27
|
+
slug TEXT NOT NULL,
|
|
28
|
+
name TEXT NOT NULL,
|
|
29
|
+
transport TEXT NOT NULL DEFAULT 'stdio',
|
|
30
|
+
command TEXT,
|
|
31
|
+
args TEXT NOT NULL DEFAULT '[]',
|
|
32
|
+
env TEXT NOT NULL DEFAULT '{}',
|
|
33
|
+
url TEXT,
|
|
34
|
+
headers TEXT NOT NULL DEFAULT '{}',
|
|
35
|
+
is_enabled INTEGER NOT NULL DEFAULT 1,
|
|
36
|
+
config_schema TEXT,
|
|
37
|
+
oauth TEXT,
|
|
38
|
+
tool_overrides TEXT,
|
|
39
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
40
|
+
)
|
|
41
|
+
`);
|
|
42
|
+
db.exec(`
|
|
43
|
+
CREATE TABLE engine_accounts (
|
|
44
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
45
|
+
provider_id INTEGER NOT NULL,
|
|
46
|
+
name TEXT NOT NULL,
|
|
47
|
+
credential TEXT NOT NULL,
|
|
48
|
+
is_active INTEGER NOT NULL DEFAULT 0
|
|
49
|
+
)
|
|
50
|
+
`);
|
|
51
|
+
up(db as unknown as DatabaseConnection);
|
|
52
|
+
return db;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function revision(db: Database): number {
|
|
56
|
+
return (db.prepare('SELECT revision FROM engine_config_revision WHERE id = 1').get() as { revision: number }).revision;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
describe('engine config revision triggers', () => {
|
|
60
|
+
test('installing, toggling and removing a connector each bump the revision', () => {
|
|
61
|
+
const db = freshDb();
|
|
62
|
+
const start = revision(db);
|
|
63
|
+
|
|
64
|
+
db.exec(`INSERT INTO mcp_servers (slug, name, transport) VALUES ('playwright', 'Playwright', 'stdio')`);
|
|
65
|
+
const afterInsert = revision(db);
|
|
66
|
+
expect(afterInsert).toBeGreaterThan(start);
|
|
67
|
+
|
|
68
|
+
db.exec(`UPDATE mcp_servers SET is_enabled = 0 WHERE slug = 'playwright'`);
|
|
69
|
+
const afterToggle = revision(db);
|
|
70
|
+
expect(afterToggle).toBeGreaterThan(afterInsert);
|
|
71
|
+
|
|
72
|
+
db.exec(`DELETE FROM mcp_servers WHERE slug = 'playwright'`);
|
|
73
|
+
expect(revision(db)).toBeGreaterThan(afterToggle);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test('a refreshed OAuth token bumps, because it changes the header the connector is spawned with', () => {
|
|
77
|
+
const db = freshDb();
|
|
78
|
+
db.exec(`INSERT INTO mcp_servers (slug, name, transport) VALUES ('linear', 'Linear', 'http')`);
|
|
79
|
+
const before = revision(db);
|
|
80
|
+
|
|
81
|
+
db.exec(`UPDATE mcp_servers SET oauth = '{"access_token":"new"}' WHERE slug = 'linear'`);
|
|
82
|
+
expect(revision(db)).toBeGreaterThan(before);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('bookkeeping columns do NOT bump — otherwise every unrelated write respawns a server', () => {
|
|
86
|
+
const db = freshDb();
|
|
87
|
+
db.exec(`INSERT INTO mcp_servers (slug, name, transport) VALUES ('github', 'GitHub', 'http')`);
|
|
88
|
+
const before = revision(db);
|
|
89
|
+
|
|
90
|
+
// `created_at` is not in the trigger's UPDATE OF list.
|
|
91
|
+
db.exec(`UPDATE mcp_servers SET created_at = '2020-01-01 00:00:00' WHERE slug = 'github'`);
|
|
92
|
+
expect(revision(db)).toBe(before);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
test('switching the active account bumps, renaming it does not', () => {
|
|
96
|
+
const db = freshDb();
|
|
97
|
+
db.exec(`INSERT INTO engine_accounts (provider_id, name, credential, is_active) VALUES (1, 'Work', 'sk-a', 1)`);
|
|
98
|
+
db.exec(`INSERT INTO engine_accounts (provider_id, name, credential, is_active) VALUES (1, 'Personal', 'sk-b', 0)`);
|
|
99
|
+
const before = revision(db);
|
|
100
|
+
|
|
101
|
+
db.exec(`UPDATE engine_accounts SET is_active = 1 WHERE name = 'Personal'`);
|
|
102
|
+
const afterSwitch = revision(db);
|
|
103
|
+
expect(afterSwitch).toBeGreaterThan(before);
|
|
104
|
+
|
|
105
|
+
// A display name is not part of any engine's spawn config.
|
|
106
|
+
db.exec(`UPDATE engine_accounts SET name = 'Personal (old)' WHERE name = 'Personal'`);
|
|
107
|
+
expect(revision(db)).toBe(afterSwitch);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('a watched table that does not exist yet is skipped, not fatal', () => {
|
|
111
|
+
// freshDb() creates two of the ten watched tables; `up()` already ran over
|
|
112
|
+
// the rest without throwing, and the counter is still usable.
|
|
113
|
+
const db = freshDb();
|
|
114
|
+
expect(revision(db)).toBeGreaterThan(0);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
test('the counter cannot grow a second row', () => {
|
|
118
|
+
const db = freshDb();
|
|
119
|
+
expect(() => db.exec(`INSERT INTO engine_config_revision (id, revision) VALUES (2, 1)`)).toThrow();
|
|
120
|
+
});
|
|
121
|
+
});
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
2
|
+
import { debug } from '$shared/utils/logger';
|
|
3
|
+
|
|
4
|
+
export const description = 'Create engine_config_revision counter + triggers that bump it on any engine-affecting config write';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A single counter that goes up whenever anything an engine bakes at start-up
|
|
8
|
+
* changes.
|
|
9
|
+
*
|
|
10
|
+
* This exists because the "Restart Server" button was removed. That button was
|
|
11
|
+
* a manual cache-invalidation lever: Open Code spawns `opencode serve` with its
|
|
12
|
+
* MCP set, provider list and agent registry frozen into the process, so editing
|
|
13
|
+
* any of them left the running server serving stale config until somebody
|
|
14
|
+
* noticed and pressed restart. With no button left, nothing may depend on a
|
|
15
|
+
* human noticing.
|
|
16
|
+
*
|
|
17
|
+
* The counter is maintained by TRIGGERS rather than by a `bumpConfig()` helper
|
|
18
|
+
* called from the write paths. A helper is one `git grep` away from being
|
|
19
|
+
* forgotten by the next feature that adds a config table, and the failure mode
|
|
20
|
+
* of forgetting it is invisible — config that silently never applies, with no
|
|
21
|
+
* button to work around it. A trigger cannot be forgotten by code that does not
|
|
22
|
+
* know it exists.
|
|
23
|
+
*
|
|
24
|
+
* Triggers are scoped with `UPDATE OF <columns>` on purpose. A blanket
|
|
25
|
+
* `AFTER UPDATE` would fire on bookkeeping columns (timestamps, usage counters)
|
|
26
|
+
* and bump the revision for writes that change nothing an engine reads, costing
|
|
27
|
+
* a needless config rebuild on every one of them.
|
|
28
|
+
*
|
|
29
|
+
* The revision is only ever a cache-invalidation SIGNAL. What actually decides
|
|
30
|
+
* whether a server is respawned is the hash of the config content itself (see
|
|
31
|
+
* `backend/engine/adapters/opencode/server.ts`), so a bump that turns out not to
|
|
32
|
+
* change any baked value — toggling a connector off and back on, editing a
|
|
33
|
+
* permission rule that is enforced per-prompt rather than at boot — costs one
|
|
34
|
+
* rebuild and reuses the running server.
|
|
35
|
+
*/
|
|
36
|
+
|
|
37
|
+
/** Tables whose rows feed engine start-up config, with the columns that matter. */
|
|
38
|
+
const WATCHED: { table: string; columns: string[] }[] = [
|
|
39
|
+
// MCP connectors: baked into every engine's server/session config.
|
|
40
|
+
// `oauth` is included because a refreshed token changes the Authorization
|
|
41
|
+
// header the connector is spawned with.
|
|
42
|
+
{
|
|
43
|
+
table: 'mcp_servers',
|
|
44
|
+
columns: ['slug', 'name', 'transport', 'command', 'args', 'env', 'url', 'headers', 'is_enabled', 'config_schema', 'oauth', 'tool_overrides'],
|
|
45
|
+
},
|
|
46
|
+
// Providers + accounts: Open Code receives these as OPENCODE_CONFIG_CONTENT
|
|
47
|
+
// and env vars at spawn; every other engine reads them per turn.
|
|
48
|
+
{
|
|
49
|
+
table: 'engine_providers',
|
|
50
|
+
columns: ['slug', 'name', 'npm', 'api_url', 'options', 'is_enabled'],
|
|
51
|
+
},
|
|
52
|
+
// Deliberately NOT `name` — renaming an account changes no baked value.
|
|
53
|
+
{
|
|
54
|
+
table: 'engine_accounts',
|
|
55
|
+
columns: ['provider_id', 'credential', 'is_active'],
|
|
56
|
+
},
|
|
57
|
+
{ table: 'skills', columns: ['slug', 'name', 'description', 'is_enabled'] },
|
|
58
|
+
{ table: 'commands', columns: ['slug', 'name', 'description', 'argument_hint', 'is_enabled', 'model_by_engine'] },
|
|
59
|
+
{ table: 'subagents', columns: ['slug', 'name', 'description', 'is_enabled', 'model_by_engine', 'tools_by_engine'] },
|
|
60
|
+
{ table: 'instructions', columns: ['scope', 'project_id', 'content', 'is_enabled'] },
|
|
61
|
+
{ table: 'permission_sets', columns: ['scope', 'project_id', 'engine', 'allow', 'deny', 'profile_id'] },
|
|
62
|
+
{ table: 'profiles', columns: ['slug', 'name'] },
|
|
63
|
+
{ table: 'profile_items', columns: ['profile_id', 'artifact_type', 'ref'] },
|
|
64
|
+
];
|
|
65
|
+
|
|
66
|
+
const BUMP = `UPDATE engine_config_revision SET revision = revision + 1, updated_at = datetime('now') WHERE id = 1;`;
|
|
67
|
+
|
|
68
|
+
export const up = (db: DatabaseConnection): void => {
|
|
69
|
+
debug.log('migration', 'Creating engine_config_revision table...');
|
|
70
|
+
|
|
71
|
+
// Single-row table. The CHECK makes that a schema guarantee rather than a
|
|
72
|
+
// convention the triggers have to trust.
|
|
73
|
+
db.exec(`
|
|
74
|
+
CREATE TABLE IF NOT EXISTS engine_config_revision (
|
|
75
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
76
|
+
revision INTEGER NOT NULL DEFAULT 1,
|
|
77
|
+
updated_at DATETIME NOT NULL DEFAULT (datetime('now'))
|
|
78
|
+
)
|
|
79
|
+
`);
|
|
80
|
+
db.exec(`INSERT OR IGNORE INTO engine_config_revision (id, revision) VALUES (1, 1)`);
|
|
81
|
+
|
|
82
|
+
for (const { table, columns } of WATCHED) {
|
|
83
|
+
// A watched table may legitimately be absent on an old database that never
|
|
84
|
+
// ran the migration creating it; skipping keeps this migration total.
|
|
85
|
+
const exists = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`).get(table);
|
|
86
|
+
if (!exists) {
|
|
87
|
+
debug.warn('migration', `engine_config_revision: table ${table} not present, skipping its triggers`);
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
db.exec(`
|
|
92
|
+
CREATE TRIGGER IF NOT EXISTS trg_engine_config_rev_${table}_ins
|
|
93
|
+
AFTER INSERT ON ${table} BEGIN ${BUMP} END
|
|
94
|
+
`);
|
|
95
|
+
db.exec(`
|
|
96
|
+
CREATE TRIGGER IF NOT EXISTS trg_engine_config_rev_${table}_del
|
|
97
|
+
AFTER DELETE ON ${table} BEGIN ${BUMP} END
|
|
98
|
+
`);
|
|
99
|
+
db.exec(`
|
|
100
|
+
CREATE TRIGGER IF NOT EXISTS trg_engine_config_rev_${table}_upd
|
|
101
|
+
AFTER UPDATE OF ${columns.join(', ')} ON ${table} BEGIN ${BUMP} END
|
|
102
|
+
`);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
debug.log('migration', `engine_config_revision created with triggers on ${WATCHED.length} tables`);
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export const down = (db: DatabaseConnection): void => {
|
|
109
|
+
debug.log('migration', 'Dropping engine_config_revision...');
|
|
110
|
+
for (const { table } of WATCHED) {
|
|
111
|
+
db.exec(`DROP TRIGGER IF EXISTS trg_engine_config_rev_${table}_ins`);
|
|
112
|
+
db.exec(`DROP TRIGGER IF EXISTS trg_engine_config_rev_${table}_del`);
|
|
113
|
+
db.exec(`DROP TRIGGER IF EXISTS trg_engine_config_rev_${table}_upd`);
|
|
114
|
+
}
|
|
115
|
+
db.exec('DROP TABLE IF EXISTS engine_config_revision');
|
|
116
|
+
debug.log('migration', 'engine_config_revision dropped');
|
|
117
|
+
};
|
|
@@ -66,6 +66,7 @@ import * as migration064 from './064_create_messages_fts';
|
|
|
66
66
|
import * as migration065 from './065_add_session_reasoning_effort';
|
|
67
67
|
import * as migration066 from './066_create_memory_graph';
|
|
68
68
|
import * as migration067 from './067_add_memory_graph_layout';
|
|
69
|
+
import * as migration068 from './068_create_engine_config_revision';
|
|
69
70
|
|
|
70
71
|
// Export all migrations in order
|
|
71
72
|
export const migrations = [
|
|
@@ -470,6 +471,12 @@ export const migrations = [
|
|
|
470
471
|
description: migration067.description,
|
|
471
472
|
up: migration067.up,
|
|
472
473
|
down: migration067.down
|
|
474
|
+
},
|
|
475
|
+
{
|
|
476
|
+
id: '068',
|
|
477
|
+
description: migration068.description,
|
|
478
|
+
up: migration068.up,
|
|
479
|
+
down: migration068.down
|
|
473
480
|
}
|
|
474
481
|
];
|
|
475
482
|
|
package/backend/engine/README.md
CHANGED
|
@@ -66,6 +66,22 @@ stays **agnostic** to the underlying SDK.
|
|
|
66
66
|
> capture the SDK's real runtime shapes with a throwaway script rather than
|
|
67
67
|
> trusting its `.d.ts`.
|
|
68
68
|
|
|
69
|
+
> **One instance, many streams.** `getProjectEngine` hands the same adapter
|
|
70
|
+
> instance to every chat session of a project, and Clopen lets those sessions
|
|
71
|
+
> stream at the same time. So per-stream state — abort controller, SDK query or
|
|
72
|
+
> session, session id, pooled server, parked questions — belongs to a **run**,
|
|
73
|
+
> held in the adapter's `EngineRuns` registry
|
|
74
|
+
> ([`adapters/run-registry.ts`](./adapters/run-registry.ts)), never in an
|
|
75
|
+
> instance field. `cancel(owner)` and `interrupt(owner)` take the run to stop
|
|
76
|
+
> and the parameter is required; stopping everything is `dispose()`'s job.
|
|
77
|
+
> Storing a stream's handles on the instance is not a style question — it made
|
|
78
|
+
> Stop in one chat abort another chat of the same project, made `isActive`
|
|
79
|
+
> report idle while a stream was still running (so engine retirement disposed it
|
|
80
|
+
> mid-answer), and leaked a pooled OpenCode server hold per overwritten stream.
|
|
81
|
+
> Read **§10.26** in [lessons-learned](./docs/lessons-learned.md) and invariant 2
|
|
82
|
+
> in [adapter-contract](./docs/adapter-contract.md) before adding state to an
|
|
83
|
+
> adapter class.
|
|
84
|
+
|
|
69
85
|
> **Background parent tools are a streaming category of their own.** `Agent`
|
|
70
86
|
> receives nested activity from the SDK stream, while Claude's `Workflow`
|
|
71
87
|
> writes agent transcripts to JSONL files outside that stream. Both must obey
|
|
@@ -36,6 +36,7 @@ import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
|
|
|
36
36
|
import { artifactFilter } from '$backend/profiles';
|
|
37
37
|
import { resolvePermissionsFromDb, isToolAllowed, hasAnyRestriction, syncPermissions } from '$backend/permissions';
|
|
38
38
|
import type { AIEngine, EngineQueryOptions } from '../../types';
|
|
39
|
+
import { EngineRuns } from '../run-registry';
|
|
39
40
|
import type { EngineModel } from '$shared/types/unified';
|
|
40
41
|
import { CLAUDE_CODE_MODELS } from './models';
|
|
41
42
|
|
|
@@ -46,6 +47,20 @@ interface PendingUserAnswer {
|
|
|
46
47
|
resolve: (result: PermissionResult) => void;
|
|
47
48
|
removeAbortListener: () => void;
|
|
48
49
|
input: Record<string, unknown>;
|
|
50
|
+
/** The run that asked — cancelling one run must not abandon another's questions. */
|
|
51
|
+
run: ClaudeRun;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* One stream in flight on this instance. This engine instance is shared by every
|
|
56
|
+
* chat session of a project, so the SDK query has to be held per run: a single
|
|
57
|
+
* field holds only the most recently started stream, and cancelling any chat
|
|
58
|
+
* would then close another chat's query.
|
|
59
|
+
*/
|
|
60
|
+
interface ClaudeRun {
|
|
61
|
+
/** Identity of the run — the controller the caller passed to streamQuery. */
|
|
62
|
+
controller: AbortController;
|
|
63
|
+
query: Query | null;
|
|
49
64
|
}
|
|
50
65
|
|
|
51
66
|
/** Merge the SDK stream with Workflow transcript polling without blocking either producer. */
|
|
@@ -78,8 +93,7 @@ class EventQueue<T> {
|
|
|
78
93
|
export class ClaudeCodeEngine implements AIEngine {
|
|
79
94
|
readonly name = 'claude-code' as const;
|
|
80
95
|
private _isInitialized = false;
|
|
81
|
-
private
|
|
82
|
-
private activeQuery: Query | null = null;
|
|
96
|
+
private runs = new EngineRuns<ClaudeRun>();
|
|
83
97
|
private pendingUserAnswers = new Map<string, PendingUserAnswer>();
|
|
84
98
|
|
|
85
99
|
get isInitialized(): boolean {
|
|
@@ -87,7 +101,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
87
101
|
}
|
|
88
102
|
|
|
89
103
|
get isActive(): boolean {
|
|
90
|
-
return this.
|
|
104
|
+
return this.runs.isActive;
|
|
91
105
|
}
|
|
92
106
|
|
|
93
107
|
async initialize(): Promise<void> {
|
|
@@ -101,7 +115,8 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
101
115
|
}
|
|
102
116
|
|
|
103
117
|
async dispose(): Promise<void> {
|
|
104
|
-
|
|
118
|
+
// Shutdown/retirement: every run on this instance goes.
|
|
119
|
+
await this.stopRuns(this.runs.all());
|
|
105
120
|
this.pendingUserAnswers.clear();
|
|
106
121
|
this._isInitialized = false;
|
|
107
122
|
}
|
|
@@ -140,10 +155,9 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
140
155
|
debug.log('chat', "Claude Code - Stream Query");
|
|
141
156
|
debug.log('chat', { prompt });
|
|
142
157
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
const streamController = this.activeController;
|
|
158
|
+
const streamController = abortController || new AbortController();
|
|
159
|
+
const run: ClaudeRun = { controller: streamController, query: null };
|
|
160
|
+
this.runs.add(run);
|
|
147
161
|
|
|
148
162
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
149
163
|
|
|
@@ -244,6 +258,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
244
258
|
canUseToolOptions.signal.addEventListener('abort', onAbort, { once: true });
|
|
245
259
|
|
|
246
260
|
this.pendingUserAnswers.set(canUseToolOptions.toolUseID, {
|
|
261
|
+
run,
|
|
247
262
|
resolve: (result: PermissionResult) => {
|
|
248
263
|
canUseToolOptions.signal.removeEventListener('abort', onAbort);
|
|
249
264
|
resolve(result);
|
|
@@ -289,7 +304,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
289
304
|
...(maxTurns && { maxTurns }),
|
|
290
305
|
...(includePartialMessages && { includePartialMessages }),
|
|
291
306
|
forwardSubagentText: true,
|
|
292
|
-
abortController:
|
|
307
|
+
abortController: streamController,
|
|
293
308
|
...(Object.keys(mcpServers).length > 0 && { mcpServers }),
|
|
294
309
|
...(allowedMcpTools.length > 0 && { allowedTools: allowedMcpTools })
|
|
295
310
|
};
|
|
@@ -306,7 +321,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
306
321
|
options: sdkOptions,
|
|
307
322
|
});
|
|
308
323
|
|
|
309
|
-
|
|
324
|
+
run.query = queryInstance;
|
|
310
325
|
|
|
311
326
|
// Per-query stateful converter so block-stop reasoning tracking persists
|
|
312
327
|
// across the stream of SDK messages.
|
|
@@ -335,9 +350,9 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
335
350
|
const observedVersion = workflowTranscripts.changeVersion;
|
|
336
351
|
for (const output of await workflowTranscripts.drain()) events.push(output);
|
|
337
352
|
|
|
338
|
-
if (
|
|
353
|
+
if (streamController.signal.aborted) break;
|
|
339
354
|
if (sdkStreamDone && !await workflowTranscripts.hasActiveWorkflows()) break;
|
|
340
|
-
await workflowTranscripts.waitForChange(observedVersion,
|
|
355
|
+
await workflowTranscripts.waitForChange(observedVersion, streamController.signal);
|
|
341
356
|
}
|
|
342
357
|
// The terminal status event is authoritative; drain once more for writes
|
|
343
358
|
// already queued by the filesystem before closing the merged stream.
|
|
@@ -363,62 +378,87 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
363
378
|
} catch (error) {
|
|
364
379
|
handleStreamError(error);
|
|
365
380
|
} finally {
|
|
366
|
-
|
|
367
|
-
|
|
381
|
+
// Retire THIS run only — a concurrent stream of another chat session in
|
|
382
|
+
// the same project is still using the instance.
|
|
383
|
+
this.forgetRun(run);
|
|
368
384
|
}
|
|
369
385
|
}
|
|
370
386
|
|
|
371
387
|
/**
|
|
372
|
-
*
|
|
388
|
+
* Drop a finished run and the questions only it could have answered.
|
|
373
389
|
*/
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
// already killed the subprocess, this write throws "Operation aborted" as
|
|
379
|
-
// an unhandled error, crashing the server. By removing listeners and not
|
|
380
|
-
// resolving, the promises are safely abandoned when close() terminates the
|
|
381
|
-
// process and the async generator completes.
|
|
382
|
-
for (const [, pending] of this.pendingUserAnswers) {
|
|
383
|
-
pending.removeAbortListener();
|
|
390
|
+
private forgetRun(run: ClaudeRun): void {
|
|
391
|
+
this.runs.remove(run);
|
|
392
|
+
for (const [toolUseId, pending] of this.pendingUserAnswers) {
|
|
393
|
+
if (pending.run === run) this.pendingUserAnswers.delete(toolUseId);
|
|
384
394
|
}
|
|
385
|
-
|
|
395
|
+
run.query = null;
|
|
396
|
+
}
|
|
386
397
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
398
|
+
/**
|
|
399
|
+
* Cancel the run whose AbortController is `owner`, and only that run.
|
|
400
|
+
*/
|
|
401
|
+
async cancel(owner: AbortController): Promise<void> {
|
|
402
|
+
await this.stopRuns(this.runs.select(owner));
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* Tear down the given runs. `cancel` passes the one run it was asked to
|
|
407
|
+
* stop; `dispose` passes them all. Nothing else may reach this.
|
|
408
|
+
*/
|
|
409
|
+
private async stopRuns(targets: ClaudeRun[]): Promise<void> {
|
|
410
|
+
for (const run of targets) {
|
|
411
|
+
// Remove abort listeners from this run's pending AskUserQuestion promises
|
|
412
|
+
// WITHOUT resolving them. Resolving causes the SDK to call
|
|
413
|
+
// handleControlRequest → write() to send the permission result to the
|
|
414
|
+
// subprocess. If close() has already killed the subprocess, this write
|
|
415
|
+
// throws "Operation aborted" as an unhandled error, crashing the server.
|
|
416
|
+
// By removing listeners and not resolving, the promises are safely
|
|
417
|
+
// abandoned when close() terminates the process and the async generator
|
|
418
|
+
// completes. Questions parked by OTHER runs stay put — their subprocess
|
|
419
|
+
// is still alive and still waiting for an answer.
|
|
420
|
+
for (const [, pending] of this.pendingUserAnswers) {
|
|
421
|
+
if (pending.run === run) pending.removeAbortListener();
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// Use close() to forcefully terminate the query process and clean up
|
|
425
|
+
// all resources (docs: "Forcefully ends the query and cleans up all
|
|
426
|
+
// resources"). Unlike interrupt() which can hang indefinitely when the
|
|
427
|
+
// subprocess is unresponsive, close() is synchronous and guaranteed to
|
|
428
|
+
// complete — making cancel deterministic.
|
|
429
|
+
if (run.query && typeof run.query.close === 'function') {
|
|
430
|
+
try {
|
|
431
|
+
run.query.close();
|
|
432
|
+
} catch {
|
|
433
|
+
// Ignore close errors — process may already be dead
|
|
434
|
+
}
|
|
397
435
|
}
|
|
398
|
-
}
|
|
399
436
|
|
|
400
|
-
|
|
401
|
-
this.
|
|
437
|
+
if (!run.controller.signal.aborted) run.controller.abort();
|
|
438
|
+
this.forgetRun(run);
|
|
402
439
|
}
|
|
403
|
-
this.activeController = null;
|
|
404
|
-
this.activeQuery = null;
|
|
405
440
|
}
|
|
406
441
|
|
|
407
442
|
/**
|
|
408
|
-
* Interrupt
|
|
443
|
+
* Interrupt a run (soft stop). Targeted like `cancel`.
|
|
409
444
|
*/
|
|
410
|
-
async interrupt(): Promise<void> {
|
|
411
|
-
|
|
412
|
-
|
|
445
|
+
async interrupt(owner: AbortController): Promise<void> {
|
|
446
|
+
const targets = this.runs.select(owner);
|
|
447
|
+
for (const run of targets) {
|
|
448
|
+
if (run.query && typeof run.query.interrupt === 'function') {
|
|
449
|
+
await run.query.interrupt();
|
|
450
|
+
}
|
|
413
451
|
}
|
|
414
452
|
}
|
|
415
453
|
|
|
416
454
|
/**
|
|
417
|
-
* Change permission mode for
|
|
455
|
+
* Change permission mode for one run's query.
|
|
418
456
|
*/
|
|
419
|
-
async setPermissionMode(mode: PermissionMode): Promise<void> {
|
|
420
|
-
|
|
421
|
-
|
|
457
|
+
async setPermissionMode(mode: PermissionMode, owner: AbortController): Promise<void> {
|
|
458
|
+
for (const run of this.runs.select(owner)) {
|
|
459
|
+
if (run.query && typeof run.query.setPermissionMode === 'function') {
|
|
460
|
+
await run.query.setPermissionMode(mode);
|
|
461
|
+
}
|
|
422
462
|
}
|
|
423
463
|
}
|
|
424
464
|
|