@myrialabs/clopen 0.4.26 → 0.4.28
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 +21 -0
- package/backend/bootstrap.ts +18 -1
- package/backend/chat/engine-handoff.test.ts +229 -0
- package/backend/chat/engine-handoff.ts +439 -0
- package/backend/chat/stream-manager.ts +200 -16
- package/backend/database/migrations/066_create_memory_graph.ts +369 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/audit-log-queries.test.ts +10 -1
- package/backend/database/queries/graph-queries.ts +1764 -0
- package/backend/database/queries/index.ts +2 -0
- package/backend/database/queries/memory-queue-queries.ts +381 -0
- package/backend/database/queries/snapshot-queries.ts +20 -0
- package/backend/engine/README.md +45 -2
- package/backend/engine/adapters/claude/message-converter.ts +5 -24
- package/backend/engine/adapters/copilot/stream.ts +37 -1
- package/backend/engine/adapters/pi/models.ts +19 -7
- package/backend/engine/adapters/pi/stream.ts +2 -1
- package/backend/engine/docs/adapter-contract.md +25 -8
- package/backend/engine/docs/adding-an-engine.md +40 -4
- package/backend/engine/docs/frontend-and-chat.md +66 -1
- package/backend/engine/docs/lessons-learned.md +165 -6
- package/backend/engine/docs/quick-reference.md +10 -0
- package/backend/engine/docs/stack.md +10 -0
- package/backend/engine/docs/websocket-routes.md +15 -1
- package/backend/engine/engine-setup.ts +1 -1
- package/backend/engine/index.test.ts +186 -0
- package/backend/engine/index.ts +117 -71
- package/backend/engine/install-recipes.test.ts +105 -0
- package/backend/engine/install-recipes.ts +4 -1
- package/backend/index.ts +9 -0
- package/backend/mcp/internal/config.ts +6 -0
- package/backend/mcp/internal/servers/index.ts +2 -0
- package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
- package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
- package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
- package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
- package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
- package/backend/memory/README.md +432 -0
- package/backend/memory/bootstrap.ts +101 -0
- package/backend/memory/compose.test.ts +198 -0
- package/backend/memory/compose.ts +343 -0
- package/backend/memory/config.ts +100 -0
- package/backend/memory/consolidate.ts +280 -0
- package/backend/memory/context.test.ts +321 -0
- package/backend/memory/context.ts +451 -0
- package/backend/memory/embedding/embedder.test.ts +141 -0
- package/backend/memory/embedding/embedder.ts +269 -0
- package/backend/memory/embedding/index.ts +17 -0
- package/backend/memory/embedding/install.ts +254 -0
- package/backend/memory/embedding/paths.ts +101 -0
- package/backend/memory/embedding/vector-cache.ts +270 -0
- package/backend/memory/extract/episodic.ts +725 -0
- package/backend/memory/extract/index.ts +133 -0
- package/backend/memory/extract/languages.ts +176 -0
- package/backend/memory/extract/scheduler.test.ts +352 -0
- package/backend/memory/extract/scheduler.ts +406 -0
- package/backend/memory/extract/structural.test.ts +215 -0
- package/backend/memory/extract/structural.ts +364 -0
- package/backend/memory/index.ts +37 -0
- package/backend/memory/indexer.ts +150 -0
- package/backend/memory/invalidate.ts +134 -0
- package/backend/memory/judge.ts +285 -0
- package/backend/memory/maintenance.ts +132 -0
- package/backend/memory/model.ts +91 -0
- package/backend/memory/notify.ts +102 -0
- package/backend/memory/readiness.ts +74 -0
- package/backend/memory/redact.test.ts +101 -0
- package/backend/memory/redact.ts +133 -0
- package/backend/memory/retention.ts +139 -0
- package/backend/memory/retrieval.eval.test.ts +301 -0
- package/backend/memory/retrieval.test.ts +1023 -0
- package/backend/memory/retrieval.ts +707 -0
- package/backend/memory/revise.test.ts +693 -0
- package/backend/memory/revise.ts +400 -0
- package/backend/memory/time.ts +31 -0
- package/backend/memory/view.ts +164 -0
- package/backend/shipped-runtime-imports.test.ts +228 -0
- package/backend/ws/engine/claude/accounts.ts +4 -12
- package/backend/ws/engine/codex/accounts.ts +4 -13
- package/backend/ws/engine/pty-output.test.ts +37 -0
- package/backend/ws/engine/pty-output.ts +43 -0
- package/backend/ws/index.ts +5 -1
- package/backend/ws/memory/crud.ts +631 -0
- package/backend/ws/memory/index.ts +41 -0
- package/backend/ws/sessions/crud.ts +10 -0
- package/backend/ws/snapshot/restore.ts +38 -4
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
- package/dist/assets/{index-DYa-GDsb.js → index-BujQYGBm.js} +1 -1
- package/dist/assets/{index-B6QGUN03.js → index-DRMOgS9y.js} +1 -1
- package/dist/assets/{main-Dznkfxsd.js → main-BrYtWn-4.js} +832 -423
- package/dist/assets/main-BrqMMMRX.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +8 -2
- package/shared/types/database/connection.ts +9 -0
- package/shared/types/memory.ts +519 -0
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-Dh-MTGNR.css +0 -1
- package/shared/utils/anonymous-user.ts +0 -168
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Boot must not load engine adapters.
|
|
3
|
+
*
|
|
4
|
+
* The registry used to import all eight adapters statically, so every user's
|
|
5
|
+
* startup was coupled to every adapter. One of them failing to load — an SDK
|
|
6
|
+
* that isn't installed, a bad module-level expression — killed the whole
|
|
7
|
+
* backend, including for someone who only ever uses Claude. That is how a value
|
|
8
|
+
* import of `@earendil-works/pi-ai` in the Pi adapter turned into "Clopen does
|
|
9
|
+
* not start" for people who had never touched Pi.
|
|
10
|
+
*
|
|
11
|
+
* Adapters are now loaded per engine, on first use. That property is invisible
|
|
12
|
+
* at a glance and easy to undo: one `import { PiEngine } from './adapters/pi'`
|
|
13
|
+
* added for convenience anywhere in the boot path silently restores the old
|
|
14
|
+
* coupling, and nothing would fail until a user's install breaks.
|
|
15
|
+
*
|
|
16
|
+
* So this walks the real thing — the eager import closure of `backend/index.ts`,
|
|
17
|
+
* following static imports only, exactly as the runtime evaluates them — and
|
|
18
|
+
* asserts no adapter's engine class is reachable. Type-only imports are erased
|
|
19
|
+
* by `Bun.Transpiler.scanImports` (the same transpiler that runs the code) and
|
|
20
|
+
* dynamic `import()` is reported separately, so what remains is precisely what
|
|
21
|
+
* boot pays for.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { describe, expect, test } from 'bun:test';
|
|
25
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
26
|
+
import { dirname, relative, resolve } from 'node:path';
|
|
27
|
+
import { ENGINES } from '$shared/constants/engines';
|
|
28
|
+
import { getEngine, findProjectEngine, getProjectEngine } from './index';
|
|
29
|
+
|
|
30
|
+
const REPO_ROOT = resolve(import.meta.dir, '..', '..');
|
|
31
|
+
const ENTRYPOINT = 'backend/index.ts';
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The OpenCode server module holds a process-wide client singleton that
|
|
35
|
+
* shutdown must release, so the registry imports it directly. It deliberately
|
|
36
|
+
* does not pull in the engine class, which is what must stay lazy.
|
|
37
|
+
*/
|
|
38
|
+
const ADAPTER_DIR = 'backend/engine/adapters';
|
|
39
|
+
|
|
40
|
+
const ALIASES: Record<string, string> = { $backend: 'backend', $shared: 'shared' };
|
|
41
|
+
const SUFFIXES = ['', '.ts', '.js', '/index.ts', '/index.js'];
|
|
42
|
+
|
|
43
|
+
/** Repo-relative path a local specifier resolves to, or null. */
|
|
44
|
+
function resolveLocal(fromFile: string, specifier: string): string | null {
|
|
45
|
+
const aliasRoot = specifier.split('/')[0]!;
|
|
46
|
+
const aliased = ALIASES[aliasRoot];
|
|
47
|
+
const target = aliased !== undefined
|
|
48
|
+
? `./${[aliased, ...specifier.split('/').slice(1)].join('/')}`
|
|
49
|
+
: specifier;
|
|
50
|
+
if (!target.startsWith('.')) return null; // bare package — not our source
|
|
51
|
+
|
|
52
|
+
const base = aliased !== undefined ? '.' : fromFile;
|
|
53
|
+
const candidates = target.endsWith('.js') ? [target, `${target.slice(0, -3)}.ts`] : [target];
|
|
54
|
+
|
|
55
|
+
for (const candidate of candidates) {
|
|
56
|
+
for (const suffix of SUFFIXES) {
|
|
57
|
+
const absolute = resolve(REPO_ROOT, dirname(base), candidate + suffix);
|
|
58
|
+
if (existsSync(absolute) && statSync(absolute).isFile()) {
|
|
59
|
+
return relative(REPO_ROOT, absolute);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Every repo file the entrypoint pulls in through static imports alone. */
|
|
67
|
+
function eagerClosure(entry: string): Set<string> {
|
|
68
|
+
const transpiler = new Bun.Transpiler({ loader: 'ts' });
|
|
69
|
+
const seen = new Set<string>([entry]);
|
|
70
|
+
const queue = [entry];
|
|
71
|
+
|
|
72
|
+
while (queue.length) {
|
|
73
|
+
const file = queue.shift()!;
|
|
74
|
+
const source = readFileSync(resolve(REPO_ROOT, file), 'utf8').replace(/^#!.*/, '');
|
|
75
|
+
|
|
76
|
+
for (const { path, kind } of transpiler.scanImports(source)) {
|
|
77
|
+
// Only static imports are evaluated at load; dynamic ones are the point.
|
|
78
|
+
if (kind !== 'import-statement') continue;
|
|
79
|
+
const target = resolveLocal(file, path);
|
|
80
|
+
if (!target || seen.has(target)) continue;
|
|
81
|
+
seen.add(target);
|
|
82
|
+
queue.push(target);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return seen;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
describe('engine registry', () => {
|
|
90
|
+
const closure = eagerClosure(ENTRYPOINT);
|
|
91
|
+
|
|
92
|
+
test('the walk actually reached the backend', () => {
|
|
93
|
+
// Without this, a broken walk would make the assertion below vacuous.
|
|
94
|
+
expect(closure.size).toBeGreaterThan(50);
|
|
95
|
+
expect(closure.has('backend/engine/index.ts')).toBe(true);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('booting loads no engine adapter', () => {
|
|
99
|
+
// An adapter's engine class lives in its barrel and its stream module;
|
|
100
|
+
// sibling modules (credential, presets, the OpenCode server singleton) are
|
|
101
|
+
// plain helpers that WS handlers legitimately import at boot.
|
|
102
|
+
const loaded = [...closure]
|
|
103
|
+
.filter(f => f.startsWith(`${ADAPTER_DIR}/`))
|
|
104
|
+
.filter(f => /\/(index|stream)\.ts$/.test(f))
|
|
105
|
+
.sort();
|
|
106
|
+
|
|
107
|
+
expect(loaded).toEqual([]);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test('the registry reaches adapters only through dynamic imports', () => {
|
|
111
|
+
const transpiler = new Bun.Transpiler({ loader: 'ts' });
|
|
112
|
+
const source = readFileSync(resolve(REPO_ROOT, 'backend/engine/index.ts'), 'utf8');
|
|
113
|
+
const imports = transpiler.scanImports(source);
|
|
114
|
+
|
|
115
|
+
const eagerAdapters = imports
|
|
116
|
+
.filter(i => i.kind === 'import-statement' && i.path.includes('./adapters/'))
|
|
117
|
+
.map(i => i.path)
|
|
118
|
+
.filter(path => path !== './adapters/opencode/server');
|
|
119
|
+
const lazyAdapters = imports.filter(i => i.kind === 'dynamic-import' && i.path.includes('./adapters/'));
|
|
120
|
+
|
|
121
|
+
expect(eagerAdapters).toEqual([]);
|
|
122
|
+
// One loader per engine — a switch back to static imports would empty this.
|
|
123
|
+
expect(lazyAdapters.length).toBe(ENGINES.length);
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
describe('engine loading', () => {
|
|
128
|
+
// Derived from the same list the engine picker renders, so a newly shipped
|
|
129
|
+
// engine is covered here the moment it becomes selectable.
|
|
130
|
+
const engineTypes = ENGINES.map(engine => engine.type);
|
|
131
|
+
|
|
132
|
+
test('every engine loads and is wired to its own adapter', async () => {
|
|
133
|
+
// The loader table is eight hand-written lines of `new (await
|
|
134
|
+
// import(…)).XEngine()`. Mapping a key to the wrong class — 'cursor' to
|
|
135
|
+
// ClineEngine — type-checks perfectly and would silently route a user's
|
|
136
|
+
// chat through the wrong SDK. `name` is each adapter's own declaration of
|
|
137
|
+
// what it is, so comparing it against the key catches exactly that.
|
|
138
|
+
const wrong: string[] = [];
|
|
139
|
+
|
|
140
|
+
for (const type of engineTypes) {
|
|
141
|
+
const engine = await getEngine(type);
|
|
142
|
+
if (engine.name !== type) wrong.push(`${type} loaded ${engine.constructor.name} (name "${engine.name}")`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
expect(wrong).toEqual([]);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test('every engine satisfies the AIEngine contract', async () => {
|
|
149
|
+
const incomplete: string[] = [];
|
|
150
|
+
|
|
151
|
+
for (const type of engineTypes) {
|
|
152
|
+
const engine = await getEngine(type);
|
|
153
|
+
const missing = (['initialize', 'dispose', 'getAvailableModels', 'streamQuery'] as const)
|
|
154
|
+
.filter(method => typeof engine[method] !== 'function');
|
|
155
|
+
if (missing.length) incomplete.push(`${type}: missing ${missing.join(', ')}`);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
expect(incomplete).toEqual([]);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('concurrent callers share one instance', async () => {
|
|
162
|
+
// Loading is async, so an unshared cache would hand two callers two
|
|
163
|
+
// engines for the same project — split abort controllers, a cancel that
|
|
164
|
+
// cancels nothing.
|
|
165
|
+
const [a, b, c] = await Promise.all([
|
|
166
|
+
getProjectEngine('concurrency-probe', 'claude-code'),
|
|
167
|
+
getProjectEngine('concurrency-probe', 'claude-code'),
|
|
168
|
+
getProjectEngine('concurrency-probe', 'claude-code'),
|
|
169
|
+
]);
|
|
170
|
+
|
|
171
|
+
expect(a).toBe(b);
|
|
172
|
+
expect(b).toBe(c);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
test('findProjectEngine never creates an engine', async () => {
|
|
176
|
+
expect(findProjectEngine('find-probe', 'codex')).toBeUndefined();
|
|
177
|
+
|
|
178
|
+
const created = await getProjectEngine('find-probe', 'codex');
|
|
179
|
+
expect(findProjectEngine('find-probe', 'codex')).toBe(created);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test('an unknown engine type is rejected, not silently ignored', async () => {
|
|
183
|
+
// Engine types come from stored settings, so a stale one is reachable.
|
|
184
|
+
expect(getEngine('nope' as never)).rejects.toThrow('Unknown engine type');
|
|
185
|
+
});
|
|
186
|
+
});
|
package/backend/engine/index.ts
CHANGED
|
@@ -12,73 +12,109 @@
|
|
|
12
12
|
* Each project gets its own engine instance so abort controllers,
|
|
13
13
|
* active queries, and session IDs are fully isolated.
|
|
14
14
|
* Cancelling Project A's stream never affects Project B.
|
|
15
|
+
*
|
|
16
|
+
* Adapters are loaded on first use, never at boot. This registry used to import
|
|
17
|
+
* all eight statically, which coupled every user's startup to every adapter: one
|
|
18
|
+
* adapter failing to load — an SDK that isn't installed, a bad module-level
|
|
19
|
+
* expression — took down the whole backend, including for someone who only ever
|
|
20
|
+
* uses Claude. Loading per engine keeps that failure where it belongs, on the
|
|
21
|
+
* engine being asked for, and the existing pre-stream readiness check
|
|
22
|
+
* (`checkEngineSetup`) turns it into an actionable chat error.
|
|
23
|
+
*
|
|
24
|
+
* A load failure is deliberately NOT caught here. There is exactly one place
|
|
25
|
+
* that decides what an unusable engine means to the user, and adding a second
|
|
26
|
+
* one would let a broken engine masquerade as a working one.
|
|
15
27
|
*/
|
|
16
28
|
|
|
17
29
|
import type { AIEngine, EngineType } from './types';
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
import {
|
|
22
|
-
import { QwenEngine } from './adapters/qwen';
|
|
23
|
-
import { PiEngine } from './adapters/pi';
|
|
24
|
-
import { ClineEngine } from './adapters/cline';
|
|
25
|
-
import { CursorEngine } from './adapters/cursor';
|
|
30
|
+
// The one exception to lazy loading: the OpenCode server module holds a
|
|
31
|
+
// process-wide client singleton that shutdown must release. It is imported
|
|
32
|
+
// directly (not via the adapter barrel) so it does not drag in the engine class.
|
|
33
|
+
import { disposeOpenCodeClient } from './adapters/opencode/server';
|
|
26
34
|
import { debug } from '$shared/utils/logger';
|
|
27
35
|
|
|
28
36
|
// ============================================================================
|
|
29
|
-
//
|
|
37
|
+
// Adapter loading
|
|
30
38
|
// ============================================================================
|
|
31
39
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
40
|
+
/**
|
|
41
|
+
* The only reference to an adapter module anywhere in this registry. Being a
|
|
42
|
+
* total `Record<EngineType, …>`, adding an engine will not type-check until its
|
|
43
|
+
* loader is registered here — the exhaustiveness the old `switch` needed a
|
|
44
|
+
* runtime `default` branch to approximate.
|
|
45
|
+
*/
|
|
46
|
+
const ENGINE_LOADERS: Record<EngineType, () => Promise<AIEngine>> = {
|
|
47
|
+
'claude-code': async () => new (await import('./adapters/claude')).ClaudeCodeEngine(),
|
|
48
|
+
opencode: async () => new (await import('./adapters/opencode')).OpenCodeEngine(),
|
|
49
|
+
copilot: async () => new (await import('./adapters/copilot')).CopilotEngine(),
|
|
50
|
+
codex: async () => new (await import('./adapters/codex')).CodexEngine(),
|
|
51
|
+
qwen: async () => new (await import('./adapters/qwen')).QwenEngine(),
|
|
52
|
+
pi: async () => new (await import('./adapters/pi')).PiEngine(),
|
|
53
|
+
cline: async () => new (await import('./adapters/cline')).ClineEngine(),
|
|
54
|
+
cursor: async () => new (await import('./adapters/cursor')).CursorEngine(),
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A cache entry. `pending` is what callers await — sharing it means concurrent
|
|
59
|
+
* callers get one instance rather than racing to build two. `instance` is the
|
|
60
|
+
* settled value, for callers that must read an engine without creating one.
|
|
61
|
+
*/
|
|
62
|
+
interface EngineSlot {
|
|
63
|
+
pending: Promise<AIEngine>;
|
|
64
|
+
instance: AIEngine | null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Get (or start) the cached creation of an engine in the given cache.
|
|
69
|
+
*
|
|
70
|
+
* A failed creation is evicted rather than cached: the usual cause is an engine
|
|
71
|
+
* the user has not installed yet, and they must be able to install it in
|
|
72
|
+
* Settings → Stack and retry without restarting the server.
|
|
73
|
+
*/
|
|
74
|
+
function slotFor(type: EngineType, cache: Map<EngineType, EngineSlot>): EngineSlot {
|
|
75
|
+
const cached = cache.get(type);
|
|
76
|
+
if (cached) return cached;
|
|
77
|
+
|
|
78
|
+
const load = ENGINE_LOADERS[type];
|
|
79
|
+
// Engine types reach us from stored settings, so an unknown one is possible
|
|
80
|
+
// even though the type system rules it out at every call site.
|
|
81
|
+
if (!load) throw new Error(`Unknown engine type: ${type}`);
|
|
82
|
+
|
|
83
|
+
const slot: EngineSlot = {
|
|
84
|
+
instance: null,
|
|
85
|
+
pending: load().then(
|
|
86
|
+
engine => { slot.instance = engine; return engine; },
|
|
87
|
+
error => { cache.delete(type); throw error; }
|
|
88
|
+
),
|
|
89
|
+
};
|
|
90
|
+
cache.set(type, slot);
|
|
91
|
+
return slot;
|
|
53
92
|
}
|
|
54
93
|
|
|
55
94
|
// ============================================================================
|
|
56
95
|
// Global Singletons — for non-streaming operations (models, settings, etc.)
|
|
57
96
|
// ============================================================================
|
|
58
97
|
|
|
59
|
-
const engines = new Map<EngineType,
|
|
98
|
+
const engines = new Map<EngineType, EngineSlot>();
|
|
60
99
|
|
|
61
100
|
/**
|
|
62
101
|
* Get (or create) a global singleton engine instance by type.
|
|
63
102
|
* Use for non-streaming operations only (e.g. models:list).
|
|
64
103
|
*/
|
|
65
|
-
export function getEngine(type: EngineType): AIEngine {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
if (!engine) {
|
|
69
|
-
engine = createEngine(type);
|
|
70
|
-
engines.set(type, engine);
|
|
71
|
-
debug.log('engine', `Global engine instance created: ${type}`);
|
|
72
|
-
}
|
|
104
|
+
export async function getEngine(type: EngineType): Promise<AIEngine> {
|
|
105
|
+
const cached = engines.get(type);
|
|
106
|
+
if (cached) return cached.pending;
|
|
73
107
|
|
|
74
|
-
|
|
108
|
+
const slot = slotFor(type, engines);
|
|
109
|
+
debug.log('engine', `Global engine instance created: ${type}`);
|
|
110
|
+
return slot.pending;
|
|
75
111
|
}
|
|
76
112
|
|
|
77
113
|
/**
|
|
78
114
|
* Initialize a global engine (call this before streaming if you want eager init).
|
|
79
115
|
*/
|
|
80
116
|
export async function initializeEngine(type: EngineType): Promise<AIEngine> {
|
|
81
|
-
const engine = getEngine(type);
|
|
117
|
+
const engine = await getEngine(type);
|
|
82
118
|
if (!engine.isInitialized) {
|
|
83
119
|
await engine.initialize();
|
|
84
120
|
}
|
|
@@ -89,10 +125,10 @@ export async function initializeEngine(type: EngineType): Promise<AIEngine> {
|
|
|
89
125
|
* Dispose a specific global engine and release its resources.
|
|
90
126
|
*/
|
|
91
127
|
export async function disposeEngine(type: EngineType): Promise<void> {
|
|
92
|
-
const
|
|
93
|
-
if (
|
|
94
|
-
await engine.dispose();
|
|
128
|
+
const slot = engines.get(type);
|
|
129
|
+
if (slot) {
|
|
95
130
|
engines.delete(type);
|
|
131
|
+
if (slot.instance) await slot.instance.dispose();
|
|
96
132
|
debug.log('engine', `Global engine disposed: ${type}`);
|
|
97
133
|
}
|
|
98
134
|
}
|
|
@@ -101,9 +137,9 @@ export async function disposeEngine(type: EngineType): Promise<void> {
|
|
|
101
137
|
* Dispose all global engines (used on server shutdown).
|
|
102
138
|
*/
|
|
103
139
|
export async function disposeAllEngines(): Promise<void> {
|
|
104
|
-
for (const [type,
|
|
140
|
+
for (const [type, slot] of engines) {
|
|
105
141
|
try {
|
|
106
|
-
await
|
|
142
|
+
if (slot.instance) await slot.instance.dispose();
|
|
107
143
|
debug.log('engine', `Global engine disposed: ${type}`);
|
|
108
144
|
} catch (error) {
|
|
109
145
|
debug.error('engine', `Error disposing global engine ${type}:`, error);
|
|
@@ -119,36 +155,46 @@ export async function disposeAllEngines(): Promise<void> {
|
|
|
119
155
|
// Per-Project Instances — for streaming (fully isolated per project)
|
|
120
156
|
// ============================================================================
|
|
121
157
|
|
|
122
|
-
/** projectId → (engineType →
|
|
123
|
-
const projectEngines = new Map<string, Map<EngineType,
|
|
158
|
+
/** projectId → (engineType → EngineSlot) */
|
|
159
|
+
const projectEngines = new Map<string, Map<EngineType, EngineSlot>>();
|
|
124
160
|
|
|
125
161
|
/**
|
|
126
162
|
* Get (or create) an engine instance scoped to a specific project.
|
|
127
163
|
* Each project gets its own engine with independent state (abort controllers,
|
|
128
164
|
* active queries, session IDs), ensuring complete stream isolation.
|
|
129
165
|
*/
|
|
130
|
-
export function getProjectEngine(projectId: string, type: EngineType): AIEngine {
|
|
131
|
-
|
|
132
|
-
|
|
166
|
+
export async function getProjectEngine(projectId: string, type: EngineType): Promise<AIEngine> {
|
|
167
|
+
let engines = projectEngines.get(projectId);
|
|
168
|
+
if (!engines) {
|
|
169
|
+
engines = new Map();
|
|
170
|
+
projectEngines.set(projectId, engines);
|
|
133
171
|
}
|
|
134
172
|
|
|
135
|
-
const
|
|
136
|
-
|
|
173
|
+
const cached = engines.get(type);
|
|
174
|
+
if (cached) return cached.pending;
|
|
137
175
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
}
|
|
176
|
+
const slot = slotFor(type, engines);
|
|
177
|
+
debug.log('engine', `Project engine created: ${type} for project ${projectId.slice(0, 8)}`);
|
|
178
|
+
return slot.pending;
|
|
179
|
+
}
|
|
143
180
|
|
|
144
|
-
|
|
181
|
+
/**
|
|
182
|
+
* The engine already created for a project, or undefined.
|
|
183
|
+
*
|
|
184
|
+
* For callers acting on a stream that is already running — cancelling it,
|
|
185
|
+
* routing an answer back into it. Those must never create an engine: a fresh
|
|
186
|
+
* instance has nothing to cancel and no pending question, so building one would
|
|
187
|
+
* only hide the fact that the real engine went missing.
|
|
188
|
+
*/
|
|
189
|
+
export function findProjectEngine(projectId: string, type: EngineType): AIEngine | undefined {
|
|
190
|
+
return projectEngines.get(projectId)?.get(type)?.instance ?? undefined;
|
|
145
191
|
}
|
|
146
192
|
|
|
147
193
|
/**
|
|
148
194
|
* Initialize a project-scoped engine.
|
|
149
195
|
*/
|
|
150
196
|
export async function initializeProjectEngine(projectId: string, type: EngineType): Promise<AIEngine> {
|
|
151
|
-
const engine = getProjectEngine(projectId, type);
|
|
197
|
+
const engine = await getProjectEngine(projectId, type);
|
|
152
198
|
if (!engine.isInitialized) {
|
|
153
199
|
await engine.initialize();
|
|
154
200
|
}
|
|
@@ -161,10 +207,10 @@ export async function initializeProjectEngine(projectId: string, type: EngineTyp
|
|
|
161
207
|
export async function disposeProjectEngine(projectId: string, type: EngineType): Promise<void> {
|
|
162
208
|
const engines = projectEngines.get(projectId);
|
|
163
209
|
if (engines) {
|
|
164
|
-
const
|
|
165
|
-
if (
|
|
166
|
-
await engine.dispose();
|
|
210
|
+
const slot = engines.get(type);
|
|
211
|
+
if (slot) {
|
|
167
212
|
engines.delete(type);
|
|
213
|
+
if (slot.instance) await slot.instance.dispose();
|
|
168
214
|
debug.log('engine', `Project engine disposed: ${type} for project ${projectId.slice(0, 8)}`);
|
|
169
215
|
}
|
|
170
216
|
if (engines.size === 0) {
|
|
@@ -179,9 +225,9 @@ export async function disposeProjectEngine(projectId: string, type: EngineType):
|
|
|
179
225
|
export async function disposeProjectEngines(projectId: string): Promise<void> {
|
|
180
226
|
const engines = projectEngines.get(projectId);
|
|
181
227
|
if (engines) {
|
|
182
|
-
for (const [type,
|
|
228
|
+
for (const [type, slot] of engines) {
|
|
183
229
|
try {
|
|
184
|
-
await
|
|
230
|
+
if (slot.instance) await slot.instance.dispose();
|
|
185
231
|
debug.log('engine', `Project engine disposed: ${type} for project ${projectId.slice(0, 8)}`);
|
|
186
232
|
} catch (error) {
|
|
187
233
|
debug.error('engine', `Error disposing project engine ${type}:`, error);
|
|
@@ -198,15 +244,15 @@ export async function disposeProjectEngines(projectId: string): Promise<void> {
|
|
|
198
244
|
*/
|
|
199
245
|
export async function disposeAllProjectEnginesByType(type: EngineType): Promise<void> {
|
|
200
246
|
for (const [projectId, engines] of projectEngines) {
|
|
201
|
-
const
|
|
202
|
-
if (
|
|
247
|
+
const slot = engines.get(type);
|
|
248
|
+
if (slot) {
|
|
249
|
+
engines.delete(type);
|
|
203
250
|
try {
|
|
204
|
-
await
|
|
251
|
+
if (slot.instance) await slot.instance.dispose();
|
|
205
252
|
debug.log('engine', `Project engine disposed: ${type} for project ${projectId.slice(0, 8)}`);
|
|
206
253
|
} catch (error) {
|
|
207
254
|
debug.error('engine', `Error disposing project engine ${type} for ${projectId.slice(0, 8)}:`, error);
|
|
208
255
|
}
|
|
209
|
-
engines.delete(type);
|
|
210
256
|
}
|
|
211
257
|
if (engines.size === 0) {
|
|
212
258
|
projectEngines.delete(projectId);
|
|
@@ -222,9 +268,9 @@ export async function disposeAllProjectEnginesByType(type: EngineType): Promise<
|
|
|
222
268
|
*/
|
|
223
269
|
async function disposeAllProjectEngines(): Promise<void> {
|
|
224
270
|
for (const [projectId, engines] of projectEngines) {
|
|
225
|
-
for (const [type,
|
|
271
|
+
for (const [type, slot] of engines) {
|
|
226
272
|
try {
|
|
227
|
-
await
|
|
273
|
+
if (slot.instance) await slot.instance.dispose();
|
|
228
274
|
} catch (error) {
|
|
229
275
|
debug.error('engine', `Error disposing project engine ${type} for ${projectId.slice(0, 8)}:`, error);
|
|
230
276
|
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* On-demand engine install integrity
|
|
3
|
+
*
|
|
4
|
+
* Engine SDKs are not bundled. `resolveEngineRecipe` builds a `bun add` for the
|
|
5
|
+
* managed stack dir and pins each package to the version `getRequiredSdkVersion`
|
|
6
|
+
* reads out of package.json — the single source of truth.
|
|
7
|
+
*
|
|
8
|
+
* That pinning is silent when it fails. A package listed in ENGINE_PACKAGES but
|
|
9
|
+
* missing from package.json yields `null`, and `engineInstallArgs` falls back to
|
|
10
|
+
* the bare name, so the user installs `@latest` instead of the version clopen
|
|
11
|
+
* was tested against. Nothing errors; the engine just installs something else.
|
|
12
|
+
* Clopen has already been bitten by a floated version this way (typebox, #362),
|
|
13
|
+
* and the blast radius grows with every engine added.
|
|
14
|
+
*
|
|
15
|
+
* `readEngineSdkVersion` compounds it: `loadEngineSdk` only enforces a version
|
|
16
|
+
* match when a required version exists, so an unpinned package also loses the
|
|
17
|
+
* "needs update" check that would otherwise surface the drift in Settings → Stack.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { describe, expect, test } from 'bun:test';
|
|
21
|
+
import { readFileSync } from 'node:fs';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
import type { EngineType } from '$shared/types/unified';
|
|
24
|
+
import { ENGINE_PACKAGES, type ToolId } from './install-recipes';
|
|
25
|
+
import { ENGINE_SDK } from './engine-setup';
|
|
26
|
+
import { getRequiredSdkVersion } from './sdk-loader';
|
|
27
|
+
|
|
28
|
+
const pkg = JSON.parse(
|
|
29
|
+
readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')
|
|
30
|
+
) as { dependencies?: Record<string, string>; devDependencies?: Record<string, string> };
|
|
31
|
+
|
|
32
|
+
const declared = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
|
|
33
|
+
|
|
34
|
+
/** Every (engine, package) pair clopen installs on demand. */
|
|
35
|
+
const enginePackages = Object.entries(ENGINE_PACKAGES).flatMap(([engine, packages]) =>
|
|
36
|
+
(packages ?? []).map(name => ({ engine, name }))
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
describe('on-demand engine SDKs', () => {
|
|
40
|
+
test('the registry is non-empty', () => {
|
|
41
|
+
// Without this, an emptied registry would make the checks below vacuous.
|
|
42
|
+
expect(enginePackages.length).toBeGreaterThan(0);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test('every engine package is declared in package.json', () => {
|
|
46
|
+
const undeclared = enginePackages
|
|
47
|
+
.filter(({ name }) => declared[name] === undefined)
|
|
48
|
+
.map(({ engine, name }) => `${engine}: "${name}" would install as @latest`);
|
|
49
|
+
|
|
50
|
+
expect(undeclared).toEqual([]);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test('every engine package is pinned to an exact version', () => {
|
|
54
|
+
// A range (^1.2.3) reintroduces the same drift the pin exists to prevent:
|
|
55
|
+
// the published package.json is the only resolution source on a global
|
|
56
|
+
// install, so bun.lock cannot hold the version down for the user.
|
|
57
|
+
const floated = enginePackages
|
|
58
|
+
.filter(({ name }) => !/^\d+\.\d+\.\d+/.test(declared[name] ?? ''))
|
|
59
|
+
.map(({ engine, name }) => `${engine}: "${name}" is "${declared[name]}", not an exact version`);
|
|
60
|
+
|
|
61
|
+
expect(floated).toEqual([]);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test('the readiness check and the installer name the same package', () => {
|
|
65
|
+
// Three registries describe the same fact in different namespaces:
|
|
66
|
+
// ENGINE_SDK (EngineType → the package `checkEngineSetup` probes),
|
|
67
|
+
// ENGINE_PACKAGES (ToolId → what `bun add` installs, first entry being the
|
|
68
|
+
// one clopen imports), and this mapping between the two id spaces.
|
|
69
|
+
//
|
|
70
|
+
// Drift here makes readiness lie rather than fail: the pre-stream check
|
|
71
|
+
// would probe a package nobody installs — reporting an installed engine as
|
|
72
|
+
// missing, or worse, waving through one that cannot load. TypeScript only
|
|
73
|
+
// forces the keys to exist; the values have to be checked.
|
|
74
|
+
const TOOL_FOR_ENGINE: Record<EngineType, ToolId> = {
|
|
75
|
+
'claude-code': 'claude',
|
|
76
|
+
opencode: 'opencode',
|
|
77
|
+
copilot: 'copilot',
|
|
78
|
+
codex: 'codex',
|
|
79
|
+
qwen: 'qwen',
|
|
80
|
+
pi: 'pi',
|
|
81
|
+
cline: 'cline',
|
|
82
|
+
cursor: 'cursor',
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const drift = Object.entries(TOOL_FOR_ENGINE).flatMap(([engine, tool]) => {
|
|
86
|
+
const probed = ENGINE_SDK[engine as EngineType];
|
|
87
|
+
const installed = ENGINE_PACKAGES[tool]?.[0];
|
|
88
|
+
if (installed === undefined) return [`${engine}: no install recipe for tool "${tool}"`];
|
|
89
|
+
return probed === installed
|
|
90
|
+
? []
|
|
91
|
+
: [`${engine}: readiness probes "${probed}" but the recipe installs "${installed}"`];
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
expect(drift).toEqual([]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test('the resolver agrees with package.json', () => {
|
|
98
|
+
// Guards the seam the recipe actually uses — if getRequiredSdkVersion ever
|
|
99
|
+
// stops reading package.json, the checks above would pass while installs
|
|
100
|
+
// silently floated again.
|
|
101
|
+
for (const { name } of enginePackages) {
|
|
102
|
+
expect(getRequiredSdkVersion(name)).toBe(declared[name]!);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
});
|
|
@@ -87,8 +87,11 @@ export interface ToolStatus {
|
|
|
87
87
|
* any extras pin a transitive CLI the SDK would otherwise float (e.g. copilot).
|
|
88
88
|
* Versions are read from package.json (the single source of truth), so an
|
|
89
89
|
* on-demand install always matches the exact version clopen was tested against.
|
|
90
|
+
* Every package listed here must therefore be declared in package.json —
|
|
91
|
+
* `install-recipes.test.ts` enforces that, since an undeclared one would
|
|
92
|
+
* silently install as `@latest`.
|
|
90
93
|
*/
|
|
91
|
-
const ENGINE_PACKAGES: Partial<Record<ToolId, string[]>> = {
|
|
94
|
+
export const ENGINE_PACKAGES: Partial<Record<ToolId, string[]>> = {
|
|
92
95
|
claude: ['@anthropic-ai/claude-agent-sdk'],
|
|
93
96
|
opencode: ['@opencode-ai/sdk'],
|
|
94
97
|
copilot: ['@github/copilot-sdk', '@github/copilot'],
|
package/backend/index.ts
CHANGED
|
@@ -57,6 +57,8 @@ import { sessionCleanupScheduler } from './auth/session-cleanup';
|
|
|
57
57
|
import { uploadTempCleanup } from './http/upload-temp-cleanup';
|
|
58
58
|
import { ws as wsServer } from './utils/ws';
|
|
59
59
|
import { messageRateLimiter } from './ws/message-rate-limiter';
|
|
60
|
+
import { flushEpisodicIngest, stopExtractionRunner } from './memory/extract';
|
|
61
|
+
import { stopMemoryMaintenance } from './memory/maintenance';
|
|
60
62
|
|
|
61
63
|
/** How often (ms) the auth gate re-confirms a connection's session against the DB. */
|
|
62
64
|
const SESSION_REVALIDATE_MS = 15_000;
|
|
@@ -303,6 +305,13 @@ async function gracefulShutdown() {
|
|
|
303
305
|
await closeMcpServer();
|
|
304
306
|
// Cleanup browser preview sessions
|
|
305
307
|
await browserPreviewServiceManager.cleanup();
|
|
308
|
+
// Write out any memory extraction still in flight or held back by a live
|
|
309
|
+
// stream. Bounded, because each entry is a model call with no timeout of its
|
|
310
|
+
// own — and the queue is a table, so whatever is left is picked up on the next
|
|
311
|
+
// start rather than lost.
|
|
312
|
+
stopMemoryMaintenance();
|
|
313
|
+
stopExtractionRunner();
|
|
314
|
+
await flushEpisodicIngest();
|
|
306
315
|
// Dispose all AI engines
|
|
307
316
|
await disposeAllEngines();
|
|
308
317
|
// Close database connection
|
|
@@ -36,6 +36,12 @@ export const mcpServersConfig: Record<ServerName, ServerConfig> = {
|
|
|
36
36
|
// One tool. Every browser capability is an action inside `actions`, so a
|
|
37
37
|
// whole interaction is one call and the agent decides what to batch.
|
|
38
38
|
tools: ["actions"]
|
|
39
|
+
},
|
|
40
|
+
"memory-graph": {
|
|
41
|
+
enabled: true,
|
|
42
|
+
// Same shape: every graph capability is an operation inside `memory`, so
|
|
43
|
+
// recalling a memory and then walking its neighbours is a single call.
|
|
44
|
+
tools: ["memory"]
|
|
39
45
|
}
|
|
40
46
|
};
|
|
41
47
|
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
13
|
import browserAutomation from './browser-automation/index';
|
|
14
|
+
import memoryGraph from './memory-graph/index';
|
|
14
15
|
import { buildServerRegistries } from './helper';
|
|
15
16
|
|
|
16
17
|
// Re-export types and remote server factory
|
|
@@ -25,6 +26,7 @@ export { createRemoteMcpServer } from './helper';
|
|
|
25
26
|
*/
|
|
26
27
|
export const allServers = [
|
|
27
28
|
browserAutomation,
|
|
29
|
+
memoryGraph,
|
|
28
30
|
// Add more servers here...
|
|
29
31
|
] as const;
|
|
30
32
|
|