@myrialabs/clopen 0.4.25 → 0.4.27
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/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/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/content.ts +85 -0
- package/backend/ws/snapshot/index.ts +4 -1
- package/backend/ws/snapshot/restore.ts +38 -4
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
- package/dist/assets/{index-KBGloYDk.js → index-BCv5HlPk.js} +1 -1
- package/dist/assets/{index-C4PD7B-x.js → index-BTGcf_Vy.js} +1 -1
- package/dist/assets/main-BrqMMMRX.css +1 -0
- package/dist/assets/main-CgmAFpU3.js +1036 -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-B0AA-88X.js +0 -622
- package/dist/assets/main-OsjA5Ab5.css +0 -1
- package/shared/utils/anonymous-user.ts +0 -168
|
@@ -28,6 +28,14 @@ blueprint for the next engine you add.
|
|
|
28
28
|
`EngineType`; `claude-code`→`claude` is the one exception).
|
|
29
29
|
- `backend/permissions/service.ts`: add the entry to `ENGINE_TYPE_TO_ARTIFACT`
|
|
30
30
|
(+ `ArtifactEngineKey`).
|
|
31
|
+
- `backend/engine/engine-setup.ts`: add the engine's **primary** SDK package
|
|
32
|
+
to `ENGINE_SDK` — the package `checkEngineSetup` probes to decide
|
|
33
|
+
installed / needs-update / ready. It must be the same package as the first
|
|
34
|
+
entry of `ENGINE_PACKAGES` (Stage 7); the compiler only forces the key to
|
|
35
|
+
exist, so `install-recipes.test.ts` cross-checks the value. Point them at
|
|
36
|
+
different packages and readiness starts lying rather than failing.
|
|
37
|
+
- `backend/engine/index.ts`: add the engine's loader to `ENGINE_LOADERS`
|
|
38
|
+
(Stage 2) — a dynamic import, never a static one.
|
|
31
39
|
- `backend/ws/sessions/crud.ts`: add the `'newengine'` literal to the two
|
|
32
40
|
session-engine typebox unions (in addition to the Stage-4 chat/crud ones).
|
|
33
41
|
- [ ] `backend/engine/adapters/newengine/models.ts`: own the catalog. Static
|
|
@@ -139,9 +147,19 @@ mandatory files; optional files use the canonical names from §2.6.
|
|
|
139
147
|
`syncEngineArtifacts(...)` at stream start, and — for a prompt-scoped
|
|
140
148
|
engine — prepend `buildArtifactsPromptContext(...)` to the prompt (from
|
|
141
149
|
`backend/engine/artifact-sync.ts`). Mirror `claude/stream.ts`. See §8.
|
|
142
|
-
- [ ] `backend/engine/index.ts`:
|
|
143
|
-
`
|
|
144
|
-
|
|
150
|
+
- [ ] `backend/engine/index.ts`: add one entry to `ENGINE_LOADERS` —
|
|
151
|
+
`newengine: async () => new (await import('./adapters/newengine')).NewEngineEngine(),`
|
|
152
|
+
— and **do not add a static import**. The registry loads adapters on
|
|
153
|
+
first use precisely so a broken engine cannot take down the other seven
|
|
154
|
+
at boot; a top-level `import { NewEngineEngine } from './adapters/newengine'`
|
|
155
|
+
silently restores that coupling. `backend/engine/index.test.ts` fails if
|
|
156
|
+
any adapter becomes reachable from boot, and also checks that each key
|
|
157
|
+
loads *its own* adapter — mapping a loader to the wrong class
|
|
158
|
+
type-checks cleanly, so nothing but that test catches it. See §10.24.
|
|
159
|
+
If there is a shared subprocess, call `disposeXxxClient()` from
|
|
160
|
+
`disposeAllProjectEngines()`, importing it from the helper module
|
|
161
|
+
(`adapters/newengine/server`) rather than the adapter barrel, so
|
|
162
|
+
shutdown does not drag the engine class into the boot graph.
|
|
145
163
|
- [ ] MCP config (if the SDK accepts a streamable-HTTP MCP URL):
|
|
146
164
|
- [ ] Internal bridge — add `getXxxMcpConfig()` in
|
|
147
165
|
`backend/mcp/internal/config.ts` (reuse `clopen-mcp`; see §10.12).
|
|
@@ -213,7 +231,10 @@ handles the install.
|
|
|
213
231
|
|
|
214
232
|
- [ ] `package.json`: add the engine's SDK package(s) to `devDependencies` at an
|
|
215
233
|
**exact** pinned version — this is the single source of truth for the
|
|
216
|
-
version clopen installs on demand.
|
|
234
|
+
version clopen installs on demand. A package listed in `ENGINE_PACKAGES`
|
|
235
|
+
but missing here does not error: `getRequiredSdkVersion` returns `null`,
|
|
236
|
+
the recipe drops the `@version`, and the user silently installs `@latest`.
|
|
237
|
+
`install-recipes.test.ts` fails on both that and on a floated range.
|
|
217
238
|
- [ ] `backend/engine/install-recipes.ts`:
|
|
218
239
|
- Add `'newengine'` to `ToolId`.
|
|
219
240
|
- Add its package(s) to `ENGINE_PACKAGES` (first entry = the SDK clopen
|
|
@@ -250,6 +271,14 @@ Other auto wiring:
|
|
|
250
271
|
`shared/constants/tool-icons.ts`, which both `ENGINES` and the Stack
|
|
251
272
|
cards reference. Add the SVG **there only** — never inline it a second
|
|
252
273
|
time.
|
|
274
|
+
- [ ] **Declare what the adapter really forwards** in
|
|
275
|
+
`backend/chat/engine-handoff.ts::attachmentSupport` (`ADAPTER_IMAGE` /
|
|
276
|
+
`ADAPTER_DOCUMENT`). These are `Record<EngineType, boolean>`, so a new
|
|
277
|
+
engine won't type-check until both are filled in — deliberately. Answer
|
|
278
|
+
from the adapter's own prompt-building code, **not** from
|
|
279
|
+
`models.ts`: the catalog says what the *model* accepts, this table says
|
|
280
|
+
what the *adapter* actually sends, and they routinely disagree. Getting
|
|
281
|
+
it wrong makes a cross-engine switch silently lose the user's images.
|
|
253
282
|
- [ ] Verify: select engine → model list appears → send message → stream
|
|
254
283
|
runs.
|
|
255
284
|
|
|
@@ -279,6 +308,13 @@ Then the minimum UI scenarios that must pass:
|
|
|
279
308
|
message, and Artifacts → generate from a purpose. These are the two
|
|
280
309
|
paths that break on a stale `providerSlug` and on JSON with trailing
|
|
281
310
|
prose / raw newlines — Claude Code passing proves nothing (§10.16).
|
|
311
|
+
- [ ] **Cross-engine handoff, both directions.** Run a few turns on another
|
|
312
|
+
engine (include a tool call and an image), switch to NewEngine, then ask
|
|
313
|
+
something that can only be answered from the earlier turns — it must
|
|
314
|
+
answer without asking the user to repeat themselves. Then switch back
|
|
315
|
+
and confirm the same. The `chat` debug log prints one
|
|
316
|
+
`Engine handoff <from> → <to>` line per switch with the turn count and
|
|
317
|
+
what was cleared or omitted (§10.23).
|
|
282
318
|
- [ ] Restart Clopen → state survives (account, provider, last-used model
|
|
283
319
|
in chat).
|
|
284
320
|
|
|
@@ -198,6 +198,70 @@ level left over from a different model can never leak into the next request.
|
|
|
198
198
|
`EngineNotReadyError`), the picker renders the same actionable notice as
|
|
199
199
|
Settings, with an **Open Stack** button and a Configure-engine fallback.
|
|
200
200
|
Both are admin-gated.
|
|
201
|
+
- **No engine lock.** The engine is switchable at any point in a session; only
|
|
202
|
+
an in-flight stream disables the trigger. Mid-session switches are handled by
|
|
203
|
+
the cross-engine handoff (§6.2a). `ProfilePicker` is likewise unlocked — the
|
|
204
|
+
backend resolves the effective profile per stream.
|
|
205
|
+
|
|
206
|
+
> **Local picks must mirror onto `sessionState.currentSession`.** The init
|
|
207
|
+
> `$effect` restores engine/model/account/profile from the session object, and
|
|
208
|
+
> it re-runs whenever that object is replaced — which any collaborator's
|
|
209
|
+
> `chat:*-sync` broadcast does. The remote `chat:model-sync` listener already
|
|
210
|
+
> mirrors ("so init $effect won't overwrite on re-render"); the local path must
|
|
211
|
+
> too, because the sender ignores its own broadcast echo. Miss this and a
|
|
212
|
+
> user's pick silently reverts a moment later. `selectEngine`, `selectModel`
|
|
213
|
+
> and `ProfilePicker.select` all call through this mirror.
|
|
214
|
+
|
|
215
|
+
### 6.2a Cross-engine handoff
|
|
216
|
+
|
|
217
|
+
Switching engine mid-conversation is supported. The mechanism lives entirely in
|
|
218
|
+
`backend/chat/engine-handoff.ts` — **no adapter, `AIEngine` or migration
|
|
219
|
+
change**.
|
|
220
|
+
|
|
221
|
+
Continuity is normally delegated to each engine's native session store, and
|
|
222
|
+
those ids are not portable (a Claude session id, a Codex rollout file, an
|
|
223
|
+
OpenCode server session, Cline's in-memory transcript). So when the branch's
|
|
224
|
+
trailing engine differs from the requested one, `stream-manager`:
|
|
225
|
+
|
|
226
|
+
1. **Suppresses `resume`.** `resolveBranchEngine(chatSessionId)` walks back to
|
|
227
|
+
the most recent **non-user** message and reads its `engine.type` (user
|
|
228
|
+
messages carry the *sender's* choice, which is exactly what must not be
|
|
229
|
+
trusted). Falls back to `chat_sessions.engine`, which is reliable because
|
|
230
|
+
`chat:model-sync` persists it at *selection* time, not on send.
|
|
231
|
+
2. **Replays the branch as prompt content** via `buildEngineHandoff(...)`,
|
|
232
|
+
prepended to the **engine prompt only**. The persisted `UserMessage` is
|
|
233
|
+
untouched, so the transcript never reaches the DB or the timeline.
|
|
234
|
+
|
|
235
|
+
**The rule — one rule, no fallback ladder.** Replay verbatim; when the replay
|
|
236
|
+
exceeds the trigger, tool results older than the last N tool uses become a
|
|
237
|
+
placeholder and tool *inputs* are always kept. Both numbers are the shipped
|
|
238
|
+
defaults of Anthropic's [`clear_tool_uses_20250919`](https://platform.claude.com/docs/en/build-with-claude/context-editing)
|
|
239
|
+
context-editing strategy (trigger 100k input tokens, keep 3 tool uses,
|
|
240
|
+
`clear_tool_inputs: false`). Mirroring a measured default beats inventing a
|
|
241
|
+
heuristic — context editing alone reports +29% on agentic benchmarks and an 84%
|
|
242
|
+
token reduction on long tool-heavy runs.
|
|
243
|
+
|
|
244
|
+
> ⚠️ **Do NOT key the replay window on `compact_boundary`.** It looks like the
|
|
245
|
+
> natural boundary and it is not: only the **Claude** adapter ever emits one.
|
|
246
|
+
> OpenCode drops compaction events (`message-converter.ts`, "Skip: … compaction")
|
|
247
|
+
> and Pi disables compaction outright (`compaction: { enabled: false }`). A
|
|
248
|
+
> boundary-based window silently degenerates to "replay everything from message
|
|
249
|
+
> one" on 7 of 8 engines — precisely the unbounded case it was meant to prevent.
|
|
250
|
+
|
|
251
|
+
Two further invariants the builder upholds:
|
|
252
|
+
|
|
253
|
+
- **Exclude the turn's own user message.** It is already saved and *is* the
|
|
254
|
+
branch head by the time the handoff runs, so without `excludeMessageId` the
|
|
255
|
+
transcript ends with a copy of the message the engine is about to answer.
|
|
256
|
+
- **Attachments pass two independent gates** — `modalities.input.image` / `.pdf`
|
|
257
|
+
(what the *model* accepts) **and** an adapter table (what the adapter actually
|
|
258
|
+
forwards). They genuinely differ: Codex, Cursor, Pi and Cline have no document
|
|
259
|
+
path at all, so a PDF handed to them vanishes whatever the catalog claims.
|
|
260
|
+
Unsupported attachments degrade to the same placeholder as cleared tool
|
|
261
|
+
results.
|
|
262
|
+
|
|
263
|
+
After the handoff turn the new engine has minted its own session id, so every
|
|
264
|
+
subsequent turn resumes natively — the cost is paid once per switch.
|
|
201
265
|
|
|
202
266
|
### 6.3 Send path → backend
|
|
203
267
|
|
|
@@ -222,7 +286,8 @@ ws.emit('chat:stream', {
|
|
|
222
286
|
```
|
|
223
287
|
|
|
224
288
|
Backend `chat:stream` then `streamManager.startStream(...)`, which:
|
|
225
|
-
-
|
|
289
|
+
- Awaits `initializeProjectEngine(projectId, engine.type)` — that engine's
|
|
290
|
+
adapter loads on first use, and a failure to load stays with it (§10.24)
|
|
226
291
|
- Persists engine/model/account + `profile_id` + `reasoning_effort` onto the
|
|
227
292
|
`chat_sessions` row so a refresh or a late joiner restores the same setup
|
|
228
293
|
- Calls `engine.streamQuery({ projectPath, prompt, providerSlug: engine.provider, modelId: engine.model.id, reasoningEffort, accountId: engine.account.id !== 0 ? engine.account.id : undefined, mcpContext })`
|
|
@@ -1184,9 +1184,10 @@ Consequences for an adapter:
|
|
|
1184
1184
|
|
|
1185
1185
|
- **Reference SDK types only via `import type`.** A plain `import { Foo } from
|
|
1186
1186
|
'<pkg>'` forces Bun to resolve the package at module-load time — which throws
|
|
1187
|
-
for every user who hasn't installed that engine yet
|
|
1188
|
-
|
|
1189
|
-
at
|
|
1187
|
+
for every user who hasn't installed that engine yet. (It used to crash the
|
|
1188
|
+
whole backend at boot; since the registry loads adapters lazily it now fails
|
|
1189
|
+
only that engine — see §10.24.) `import type` is erased at runtime, so it's
|
|
1190
|
+
safe. Resolve the real module at point of use with
|
|
1190
1191
|
`loadEngineSdk<typeof import('<pkg>')>('newengine', '<pkg>')` from
|
|
1191
1192
|
`backend/engine/sdk-loader.ts` (which does `Bun.resolveSync(pkg, stackDir)` +
|
|
1192
1193
|
dynamic import, cached).
|
|
@@ -1196,12 +1197,37 @@ Consequences for an adapter:
|
|
|
1196
1197
|
because a leftover value import is **invisible in development**: the repo's
|
|
1197
1198
|
own `node_modules` has the devDependency, so `import { query } from
|
|
1198
1199
|
'@qwen-code/sdk'` resolves fine locally and only fails for end users, whose
|
|
1199
|
-
stack dir is the only copy.
|
|
1200
|
-
`stream.ts` (`query`)
|
|
1201
|
-
|
|
1200
|
+
stack dir is the only copy. Three shipped adapters had exactly this — Qwen's
|
|
1201
|
+
`stream.ts` (`query`), OpenCode's `server.ts` (`createOpencodeClient`), and
|
|
1202
|
+
Pi's `models.ts` + `stream.ts` (`clampThinkingLevel`,
|
|
1203
|
+
`getSupportedThinkingLevels`) — all converted after the fact. A plain
|
|
1202
1204
|
`await import('<pkg>')` is the same bug: it resolves from the process's own
|
|
1203
1205
|
paths, not the stack dir. `loadEngineSdk` is the only correct seam.
|
|
1204
1206
|
|
|
1207
|
+
- **It does not even fail consistently for end users — that is why it kept
|
|
1208
|
+
shipping.** A global install resolves a bare specifier by walking up to
|
|
1209
|
+
`~/.bun/install/global/node_modules`, which is **shared by every globally
|
|
1210
|
+
installed package**. So whether the missing SDK crashes depends on what else
|
|
1211
|
+
happens to live in that store: the Pi break was reported as "only on some
|
|
1212
|
+
devices, mostly fresh installs", and reinstalling bun "fixed" it because that
|
|
1213
|
+
rewrites the ambient store rather than the code. Treat "it works on my
|
|
1214
|
+
machine / it works after a reinstall" as *no evidence at all* here. Worse,
|
|
1215
|
+
when the package does happen to be there, the engine silently runs a version
|
|
1216
|
+
clopen never pinned or tested — the version guard only applies to the stack
|
|
1217
|
+
dir path.
|
|
1218
|
+
|
|
1219
|
+
- **The rule is now enforced, because writing it down three times did not
|
|
1220
|
+
work.** `bun run lint` rejects value imports of any `devDependency` from
|
|
1221
|
+
shipped runtime code (`bin/`, `backend/`, `shared/`, `scripts/start.ts`), with
|
|
1222
|
+
the restricted list derived from `package.json` so a newly added engine SDK is
|
|
1223
|
+
covered without touching the config. ESLint cannot see `await import(…)`,
|
|
1224
|
+
so `backend/shipped-runtime-imports.test.ts` walks the shipped module graph
|
|
1225
|
+
with `Bun.Transpiler.scanImports` — the same transpiler that runs the code, so
|
|
1226
|
+
type-only imports are erased exactly as at runtime — and fails on any
|
|
1227
|
+
specifier an end user could not resolve, including an undeclared package or
|
|
1228
|
+
one reaching into files `package.json` `files` does not ship. Both run in CI
|
|
1229
|
+
before `npm publish` (`needs: ci`).
|
|
1230
|
+
|
|
1205
1231
|
- **Loading is version-guarded.** `loadEngineSdk` refuses an SDK whose installed
|
|
1206
1232
|
version ≠ the pinned version, throwing `EngineNotReadyError`
|
|
1207
1233
|
(`reason: 'not-installed' | 'needs-update'`). The stream-manager surfaces that
|
|
@@ -1272,3 +1298,136 @@ costs one effect and buys two things: the value sent with the turn always
|
|
|
1272
1298
|
matches what actually ran (so `MessageEngine.reasoningEffort` in the Raw
|
|
1273
1299
|
view is truthful), and a level valid for the previous model can never
|
|
1274
1300
|
leak into a request for the next one.
|
|
1301
|
+
|
|
1302
|
+
---
|
|
1303
|
+
|
|
1304
|
+
### 10.23 Switching engine mid-session — replay the branch, and distrust "obvious" boundaries
|
|
1305
|
+
|
|
1306
|
+
Continuity is delegated to each engine's native session store, and those
|
|
1307
|
+
ids are not portable: a Claude session id, a Codex rollout file, an
|
|
1308
|
+
OpenCode server session, Cline's in-memory transcript. So a chat that
|
|
1309
|
+
changes engine has nothing for the new engine to resume. Clopen's DB is
|
|
1310
|
+
the only engine-agnostic record of the conversation, which makes
|
|
1311
|
+
**replaying the branch as prompt content** the only mechanism that works
|
|
1312
|
+
for all eight adapters. It lives in `backend/chat/engine-handoff.ts` and
|
|
1313
|
+
needs no adapter, `AIEngine` or migration change.
|
|
1314
|
+
|
|
1315
|
+
**Gate `resume` on the engine that produced the branch, not on the
|
|
1316
|
+
session.** `chat_sessions.engine` names the *currently selected* engine
|
|
1317
|
+
(`chat:model-sync` persists it the moment anyone picks one), which in a
|
|
1318
|
+
switched session is precisely the wrong answer. Walk back to the most
|
|
1319
|
+
recent **non-user** message and read its `engine.type`; user messages
|
|
1320
|
+
carry the sender's choice, not the producer's. Feeding a foreign id to an
|
|
1321
|
+
adapter degrades inconsistently — Codex, Copilot, Pi and Cline catch it
|
|
1322
|
+
and start fresh (silent amnesia), while OpenCode falls back to the raw id
|
|
1323
|
+
against a server that never had it, and Claude passes it straight to the
|
|
1324
|
+
SDK with no existence check.
|
|
1325
|
+
|
|
1326
|
+
**Two boundary assumptions failed here; both looked obvious.**
|
|
1327
|
+
|
|
1328
|
+
1. *"Replay from the last `compact_boundary` — that's what the engine
|
|
1329
|
+
itself was holding."* Only the **Claude** adapter ever emits one.
|
|
1330
|
+
OpenCode explicitly drops compaction events (`message-converter.ts`,
|
|
1331
|
+
"Skip: … compaction") and Pi disables compaction outright
|
|
1332
|
+
(`compaction: { enabled: false }`). On 7 of 8 engines the rule
|
|
1333
|
+
silently becomes "replay everything from message one" — the unbounded
|
|
1334
|
+
case it was supposed to prevent.
|
|
1335
|
+
2. *"No boundary means it all fit in the source engine's window."* Not
|
|
1336
|
+
so. Context editing is explicitly designed around the client keeping
|
|
1337
|
+
full history while the server edits it, so a client-side transcript
|
|
1338
|
+
that is much larger than the engine's live context is the normal
|
|
1339
|
+
case, not an exotic one.
|
|
1340
|
+
|
|
1341
|
+
The window is therefore an **estimated token budget**, which every engine
|
|
1342
|
+
has, rather than a marker only one engine emits.
|
|
1343
|
+
|
|
1344
|
+
**Copy a measured default instead of inventing a heuristic.** The rule is
|
|
1345
|
+
one sentence — replay verbatim; past the trigger, tool results older than
|
|
1346
|
+
the last N tool uses become a placeholder and tool *inputs* are always
|
|
1347
|
+
kept — and both numbers are the shipped defaults of Anthropic's
|
|
1348
|
+
[`clear_tool_uses_20250919`](https://platform.claude.com/docs/en/build-with-claude/context-editing)
|
|
1349
|
+
(trigger 100k input tokens, keep 3 tool uses, `clear_tool_inputs: false`).
|
|
1350
|
+
Tool results are the right thing to drop first because they are
|
|
1351
|
+
re-derivable — the new engine is in the same project directory and can
|
|
1352
|
+
read the file again — and because clearing them is *measured* to help:
|
|
1353
|
+
+29% on agentic benchmarks, 84% token reduction on long tool-heavy runs.
|
|
1354
|
+
Resist adding a fallback ladder on top; a ladder is how a rule becomes
|
|
1355
|
+
unpredictable.
|
|
1356
|
+
|
|
1357
|
+
**Two invariants that are easy to miss:**
|
|
1358
|
+
|
|
1359
|
+
- The turn's own user message is already saved and *is* the branch head
|
|
1360
|
+
when the handoff runs. Without `excludeMessageId` the transcript ends
|
|
1361
|
+
with a verbatim copy of the message the engine is about to answer.
|
|
1362
|
+
- Attachments need **two** gates: `EngineModel.modalities.input` (what
|
|
1363
|
+
the model accepts) and an adapter table (what the adapter forwards).
|
|
1364
|
+
They disagree — Codex, Cursor, Pi and Cline have no document path at
|
|
1365
|
+
all. Copilot forwarded text only until its `blob` attachment support
|
|
1366
|
+
was wired up, silently dropping every image despite `models.ts`
|
|
1367
|
+
advertising `image: !!supports?.vision`.
|
|
1368
|
+
|
|
1369
|
+
Finally: the handoff is prepended to the **engine prompt only**. The
|
|
1370
|
+
persisted `UserMessage` stays clean, so the transcript never reaches the
|
|
1371
|
+
DB or the timeline, and the user sees nothing but a changed engine.
|
|
1372
|
+
|
|
1373
|
+
### 10.24 One adapter must not be able to break every engine
|
|
1374
|
+
|
|
1375
|
+
The registry used to import all eight adapters statically. That made every
|
|
1376
|
+
user's startup depend on every adapter loading cleanly — so when Pi's
|
|
1377
|
+
`stream.ts` carried a value import of `@earendil-works/pi-ai` (§10.21), the
|
|
1378
|
+
symptom was not "Pi is unavailable". It was:
|
|
1379
|
+
|
|
1380
|
+
```
|
|
1381
|
+
Clopen v0.4.26
|
|
1382
|
+
error: Cannot find module '@earendil-works/pi-ai' from
|
|
1383
|
+
'/home/rust/.bun/install/global/node_modules/@myrialabs/clopen/backend/engine/adapters/pi/stream.ts'
|
|
1384
|
+
```
|
|
1385
|
+
|
|
1386
|
+
The process died at boot. Someone who only ever used Claude lost the entire
|
|
1387
|
+
app to an engine they had never selected, with no UI to tell them why.
|
|
1388
|
+
|
|
1389
|
+
`ENGINE_LOADERS` in `backend/engine/index.ts` is now the only reference to an
|
|
1390
|
+
adapter module, and every entry is a dynamic `import()`. Being a total
|
|
1391
|
+
`Record<EngineType, …>`, a new engine will not type-check until its loader is
|
|
1392
|
+
registered — the exhaustiveness the old `switch` needed a runtime `default`
|
|
1393
|
+
branch to approximate.
|
|
1394
|
+
|
|
1395
|
+
Four things that were deliberate, and would each be easy to "improve" back
|
|
1396
|
+
into a bug:
|
|
1397
|
+
|
|
1398
|
+
- **The failed load is not caught.** There is exactly one place that decides
|
|
1399
|
+
what an unusable engine means to the user — `checkEngineSetup`, whose message
|
|
1400
|
+
embeds "Settings → Stack" and renders as a one-click **Open Stack** button
|
|
1401
|
+
(`frontend/components/chat/formatters/ErrorMessage.svelte`). A second
|
|
1402
|
+
handler here would let a broken engine masquerade as a working one. And
|
|
1403
|
+
translating a module-load failure into an install prompt is worse than
|
|
1404
|
+
showing the raw error: it sends people reinstalling for a bug no reinstall
|
|
1405
|
+
can fix, which is exactly how §10.21 stayed alive for three releases.
|
|
1406
|
+
|
|
1407
|
+
- **The cache holds a promise, not an instance.** Creation is async now, so
|
|
1408
|
+
two concurrent callers racing to build two engines for one project would
|
|
1409
|
+
split the abort controller — a cancel that cancels nothing. A failed load is
|
|
1410
|
+
evicted rather than cached, so a user can install the engine in Settings →
|
|
1411
|
+
Stack and retry without restarting the server.
|
|
1412
|
+
|
|
1413
|
+
- **`findProjectEngine` exists so lookups cannot create.** Cancelling a stream
|
|
1414
|
+
and routing an `AskUserQuestion` answer both act on a stream that is already
|
|
1415
|
+
running, so the engine must already exist. The old code called
|
|
1416
|
+
`getProjectEngine` and silently built a fresh instance when it did not —
|
|
1417
|
+
an engine with nothing to cancel and no pending question. Reach for
|
|
1418
|
+
`findProjectEngine` whenever "not there" is a real answer.
|
|
1419
|
+
|
|
1420
|
+
- **`disposeOpenCodeClient` is imported from `adapters/opencode/server`, not
|
|
1421
|
+
the barrel.** Shutdown must release that module's process-wide client
|
|
1422
|
+
singleton, but importing it through `adapters/opencode` would drag
|
|
1423
|
+
`OpenCodeEngine` into the boot graph and undo the whole change. Both paths
|
|
1424
|
+
resolve to the same module instance (ESM caches by resolved path), so the
|
|
1425
|
+
singleton is not duplicated.
|
|
1426
|
+
|
|
1427
|
+
`backend/engine/index.test.ts` is what keeps this true. It walks the eager
|
|
1428
|
+
import closure of `backend/index.ts` — following static imports only, the way
|
|
1429
|
+
the runtime evaluates them — and fails if any adapter's engine class is
|
|
1430
|
+
reachable, so smuggling the import into some other boot-path file is caught
|
|
1431
|
+
too. It also asserts each key loads *its own* adapter: mapping `cursor` to
|
|
1432
|
+
`ClineEngine` type-checks with zero errors and would route a user's chat
|
|
1433
|
+
through the wrong SDK, and nothing but that check catches it.
|
|
@@ -39,10 +39,20 @@
|
|
|
39
39
|
| Reasoning-effort levels a model offers | `EngineModel.capabilities.reasoningControl` built in `<engine>/models.ts` via `toReasoningOptions` (`shared/constants/engines.ts`); §2.4a |
|
|
40
40
|
| Apply the chosen reasoning level to the SDK | `claude/stream.ts` (`thinking` + `effort`), `codex/stream.ts` (`modelReasoningEffort`), `copilot/stream.ts` (`reasoningEffort`), `pi/stream.ts` (`thinkingLevel` + `clampThinkingLevel`), `cursor/stream.ts::buildCursorModelSelection` (`params[]`); §10.22 |
|
|
41
41
|
| Per-session reasoning persistence + collab sync | `chat_sessions.reasoning_effort` (migration `065`), `sessionQueries.updateReasoning`, `chat:reasoning-sync` in `backend/ws/chat/stream.ts` |
|
|
42
|
+
| Switch engine mid-session (carry the conversation) | `backend/chat/engine-handoff.ts::buildEngineHandoff` + `resolveBranchEngine`, wired in `backend/chat/stream-manager.ts` (suppress `resume`, prepend to the engine prompt only); frontend-and-chat §6.2a |
|
|
43
|
+
| Is this SDK session id mine? (engine-aware resume) | `resolveBranchEngine` (backend, authoritative) + the `engine.type` guard in `frontend/services/chat/chat.service.ts`; also `backend/ws/snapshot/restore.ts` when restoring into another engine's region |
|
|
44
|
+
| Which attachments actually survive to an engine | adapter table in `backend/chat/engine-handoff.ts::attachmentSupport` (what the adapter forwards) × `EngineModel.modalities.input` (what the model accepts) — the two disagree |
|
|
45
|
+
| Collab sync of engine/model/account/profile | `chat:model-sync` / `chat:account-sync` / `chat:profile-sync` in `backend/ws/chat/stream.ts`; local picks must ALSO mirror onto `sessionState.currentSession` (frontend-and-chat §6.2) |
|
|
42
46
|
| Error normalisation | `claude/error-handler.ts`, `copilot/error-handler.ts`, `opencode/error-handler.ts`, `qwen/error-handler.ts`, `codex/error-handler.ts` |
|
|
43
47
|
| DB provider/account access | `backend/database/queries/engine-queries.ts` |
|
|
44
48
|
| Host-tool + engine-SDK install recipes | `backend/engine/install-recipes.ts` |
|
|
45
49
|
| On-demand engine-SDK loader (managed dir) | `backend/engine/sdk-loader.ts` (`getStackEnginesDir`, `loadEngineSdk`) |
|
|
50
|
+
| Register a new engine with the registry | `backend/engine/index.ts::ENGINE_LOADERS` — one dynamic `import()` per engine, never a static one (§10.24) |
|
|
51
|
+
| Engine instance that must already exist | `backend/engine/index.ts::findProjectEngine` (sync, `undefined` when absent; cancel + answer routing) |
|
|
52
|
+
| Pre-stream readiness → "Open Stack" button | `backend/engine/engine-setup.ts::checkEngineSetup` (probes `ENGINE_SDK`) + `frontend/components/chat/formatters/ErrorMessage.svelte` |
|
|
53
|
+
| Guard: no devDependency reaches shipped code | `eslint.config.js` (restricted list derived from `package.json`) + `backend/shipped-runtime-imports.test.ts` (catches the `await import()` ESLint cannot see) |
|
|
54
|
+
| Guard: boot loads no adapter; loaders wired right | `backend/engine/index.test.ts` |
|
|
55
|
+
| Guard: every engine SDK declared + pinned exact | `backend/engine/install-recipes.test.ts` (also cross-checks `ENGINE_SDK` against `ENGINE_PACKAGES`) |
|
|
46
56
|
| Streaming install logs | `backend/engine/install-runner.ts` |
|
|
47
57
|
| Fresh-install default engine (auto OpenCode)| `backend/engine/bootstrap-default-engine.ts::ensureDefaultEngineInstalled`, called from `backend/bootstrap.ts::bootstrapAfterDbInit` (startup **and** Clear All Data); §7.8 |
|
|
48
58
|
| Engine + host-tool brand icons (SSOT) | `shared/constants/tool-icons.ts::TOOL_ICONS` (referenced by `ENGINES` and the Stack cards) |
|
|
@@ -130,6 +130,16 @@ Engine SDKs don't need a hand-written resolver. When you add an engine
|
|
|
130
130
|
4. Add the literal to `TOOL_UNION` (`status.ts`, `install.ts`).
|
|
131
131
|
5. Add `<ToolInstallCard tool="newengine" ... />` in `StackSettings.svelte`.
|
|
132
132
|
|
|
133
|
+
Step 2 fails silently if you only do half of it. A package listed in
|
|
134
|
+
`ENGINE_PACKAGES` but absent from `package.json` makes `getRequiredSdkVersion`
|
|
135
|
+
return `null`; `engineInstallArgs` then drops the `@version` and the user
|
|
136
|
+
installs **`@latest`** — and because `loadEngineSdk` only enforces a version
|
|
137
|
+
match when a required version exists, that engine also loses its "Update
|
|
138
|
+
required" state. `install-recipes.test.ts` fails on an undeclared package, on a
|
|
139
|
+
floated range instead of an exact version, and on `ENGINE_SDK`
|
|
140
|
+
(`engine-setup.ts`) naming a different package than the recipe installs — that
|
|
141
|
+
last one would make readiness lie rather than fail.
|
|
142
|
+
|
|
133
143
|
There is no "Check for Updates" for engines — their versions move in lockstep
|
|
134
144
|
with clopen releases, so `version-check.ts` has no update source for them. The
|
|
135
145
|
Stack card instead shows **Update required** whenever the installed version ≠
|
|
@@ -244,7 +244,8 @@ types flow through `$shared`.
|
|
|
244
244
|
```
|
|
245
245
|
|
|
246
246
|
The handler calls `streamManager.startStream(...)`, which then:
|
|
247
|
-
1.
|
|
247
|
+
1. Awaits `initializeProjectEngine(projectId, engine.type)`, which loads that
|
|
248
|
+
engine's adapter on first use (§10.24) — no other engine is touched
|
|
248
249
|
2. Persists the per-session choices that outlive the turn — engine, model,
|
|
249
250
|
account, `profile_id`, `reasoning_effort` — onto the `chat_sessions` row
|
|
250
251
|
(`sessionQueries.updateReasoning`, migration `065`). `undefined` leaves the
|
|
@@ -276,5 +277,18 @@ Every one of these must be declared in **both** the `.on(...)` block and the
|
|
|
276
277
|
`.emit(...)` schema block at the bottom of `backend/ws/chat/stream.ts` — an
|
|
277
278
|
event that is only `.on`'d is received but never broadcast.
|
|
278
279
|
|
|
280
|
+
Two consequences worth internalising:
|
|
281
|
+
|
|
282
|
+
- **These persist at *selection* time, not on send.** `chat:model-sync` writes
|
|
283
|
+
`updateEngineModel` the moment anyone picks an engine, which is why
|
|
284
|
+
`chat_sessions.engine` is a trustworthy "currently selected engine" — and
|
|
285
|
+
equally why it is the *wrong* source for "which engine produced this
|
|
286
|
+
message" (read `engine.type` per message instead; see §10.23).
|
|
287
|
+
- **The sender ignores its own echo**, so a local pick never comes back through
|
|
288
|
+
the listener. Whatever the remote listener does to
|
|
289
|
+
`sessionState.currentSession`, the local path must do too, or the init
|
|
290
|
+
`$effect` restores the pre-pick values the next time that object is replaced.
|
|
291
|
+
See frontend-and-chat §6.2.
|
|
292
|
+
|
|
279
293
|
---
|
|
280
294
|
|
|
@@ -17,7 +17,7 @@ import type { EngineType } from '$shared/types/unified';
|
|
|
17
17
|
import { readEngineSdkVersion, getRequiredSdkVersion } from './sdk-loader';
|
|
18
18
|
|
|
19
19
|
/** Primary SDK package clopen imports for each engine. */
|
|
20
|
-
const ENGINE_SDK: Record<EngineType, string> = {
|
|
20
|
+
export const ENGINE_SDK: Record<EngineType, string> = {
|
|
21
21
|
'claude-code': '@anthropic-ai/claude-agent-sdk',
|
|
22
22
|
opencode: '@opencode-ai/sdk',
|
|
23
23
|
copilot: '@github/copilot-sdk',
|
|
@@ -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
|
+
});
|