@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.
Files changed (98) hide show
  1. package/backend/auth/permissions.ts +21 -0
  2. package/backend/bootstrap.ts +18 -1
  3. package/backend/chat/engine-handoff.test.ts +229 -0
  4. package/backend/chat/engine-handoff.ts +439 -0
  5. package/backend/chat/stream-manager.ts +200 -16
  6. package/backend/database/migrations/066_create_memory_graph.ts +369 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/audit-log-queries.test.ts +10 -1
  9. package/backend/database/queries/graph-queries.ts +1764 -0
  10. package/backend/database/queries/index.ts +2 -0
  11. package/backend/database/queries/memory-queue-queries.ts +381 -0
  12. package/backend/database/queries/snapshot-queries.ts +20 -0
  13. package/backend/engine/README.md +45 -2
  14. package/backend/engine/adapters/claude/message-converter.ts +5 -24
  15. package/backend/engine/adapters/copilot/stream.ts +37 -1
  16. package/backend/engine/adapters/pi/models.ts +19 -7
  17. package/backend/engine/adapters/pi/stream.ts +2 -1
  18. package/backend/engine/docs/adapter-contract.md +25 -8
  19. package/backend/engine/docs/adding-an-engine.md +40 -4
  20. package/backend/engine/docs/frontend-and-chat.md +66 -1
  21. package/backend/engine/docs/lessons-learned.md +165 -6
  22. package/backend/engine/docs/quick-reference.md +10 -0
  23. package/backend/engine/docs/stack.md +10 -0
  24. package/backend/engine/docs/websocket-routes.md +15 -1
  25. package/backend/engine/engine-setup.ts +1 -1
  26. package/backend/engine/index.test.ts +186 -0
  27. package/backend/engine/index.ts +117 -71
  28. package/backend/engine/install-recipes.test.ts +105 -0
  29. package/backend/engine/install-recipes.ts +4 -1
  30. package/backend/index.ts +9 -0
  31. package/backend/mcp/internal/config.ts +6 -0
  32. package/backend/mcp/internal/servers/index.ts +2 -0
  33. package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
  34. package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
  35. package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
  36. package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
  37. package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
  38. package/backend/memory/README.md +432 -0
  39. package/backend/memory/bootstrap.ts +101 -0
  40. package/backend/memory/compose.test.ts +198 -0
  41. package/backend/memory/compose.ts +343 -0
  42. package/backend/memory/config.ts +100 -0
  43. package/backend/memory/consolidate.ts +280 -0
  44. package/backend/memory/context.test.ts +321 -0
  45. package/backend/memory/context.ts +451 -0
  46. package/backend/memory/embedding/embedder.test.ts +141 -0
  47. package/backend/memory/embedding/embedder.ts +269 -0
  48. package/backend/memory/embedding/index.ts +17 -0
  49. package/backend/memory/embedding/install.ts +254 -0
  50. package/backend/memory/embedding/paths.ts +101 -0
  51. package/backend/memory/embedding/vector-cache.ts +270 -0
  52. package/backend/memory/extract/episodic.ts +725 -0
  53. package/backend/memory/extract/index.ts +133 -0
  54. package/backend/memory/extract/languages.ts +176 -0
  55. package/backend/memory/extract/scheduler.test.ts +352 -0
  56. package/backend/memory/extract/scheduler.ts +406 -0
  57. package/backend/memory/extract/structural.test.ts +215 -0
  58. package/backend/memory/extract/structural.ts +364 -0
  59. package/backend/memory/index.ts +37 -0
  60. package/backend/memory/indexer.ts +150 -0
  61. package/backend/memory/invalidate.ts +134 -0
  62. package/backend/memory/judge.ts +285 -0
  63. package/backend/memory/maintenance.ts +132 -0
  64. package/backend/memory/model.ts +91 -0
  65. package/backend/memory/notify.ts +102 -0
  66. package/backend/memory/readiness.ts +74 -0
  67. package/backend/memory/redact.test.ts +101 -0
  68. package/backend/memory/redact.ts +133 -0
  69. package/backend/memory/retention.ts +139 -0
  70. package/backend/memory/retrieval.eval.test.ts +301 -0
  71. package/backend/memory/retrieval.test.ts +1023 -0
  72. package/backend/memory/retrieval.ts +707 -0
  73. package/backend/memory/revise.test.ts +693 -0
  74. package/backend/memory/revise.ts +400 -0
  75. package/backend/memory/time.ts +31 -0
  76. package/backend/memory/view.ts +164 -0
  77. package/backend/shipped-runtime-imports.test.ts +228 -0
  78. package/backend/ws/engine/claude/accounts.ts +4 -12
  79. package/backend/ws/engine/codex/accounts.ts +4 -13
  80. package/backend/ws/engine/pty-output.test.ts +37 -0
  81. package/backend/ws/engine/pty-output.ts +43 -0
  82. package/backend/ws/index.ts +5 -1
  83. package/backend/ws/memory/crud.ts +631 -0
  84. package/backend/ws/memory/index.ts +41 -0
  85. package/backend/ws/sessions/crud.ts +10 -0
  86. package/backend/ws/snapshot/restore.ts +38 -4
  87. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  88. package/dist/assets/{index-DYa-GDsb.js → index-BujQYGBm.js} +1 -1
  89. package/dist/assets/{index-B6QGUN03.js → index-DRMOgS9y.js} +1 -1
  90. package/dist/assets/{main-Dznkfxsd.js → main-BrYtWn-4.js} +832 -423
  91. package/dist/assets/main-BrqMMMRX.css +1 -0
  92. package/dist/index.html +2 -2
  93. package/package.json +8 -2
  94. package/shared/types/database/connection.ts +9 -0
  95. package/shared/types/memory.ts +519 -0
  96. package/shared/utils/logger.ts +1 -0
  97. package/dist/assets/main-Dh-MTGNR.css +0 -1
  98. package/shared/utils/anonymous-user.ts +0 -168
@@ -24,5 +24,7 @@ export { instructionQueries } from './instruction-queries';
24
24
  export type { InstructionRow, InstructionScope } from './instruction-queries';
25
25
  export { permissionSetQueries } from './permission-set-queries';
26
26
  export type { PermissionSet, PermissionScope } from './permission-set-queries';
27
+ export { graphQueries, deriveDigest, entityKeyFor, DIGEST_VERSION } from './graph-queries';
28
+ export { memoryQueueQueries, type QueuedExtraction } from './memory-queue-queries';
27
29
  export { profileQueries, PROFILE_ITEM_TYPES } from './profile-queries';
28
30
  export type { ProfileRow, ProfileItemRow, ProfileInput, ProfileItemInput, ProfileItemType } from './profile-queries';
@@ -0,0 +1,381 @@
1
+ /**
2
+ * The memory extraction queue (migration 066).
3
+ *
4
+ * Everything about "which turn is waiting to be summarised, and when" lives
5
+ * here. The scheduler decides timing policy; this decides how that policy is
6
+ * persisted, and it is persisted precisely so that a crash, a restart or a model
7
+ * outage does not quietly cost the user a conversation's worth of memory.
8
+ *
9
+ * The unique index on `session_id` carries real semantics: enqueueing a turn for
10
+ * a session that already has one MERGES into it and keeps the older
11
+ * `user_message_id`. That is the "bank the oldest boundary" rule — the transcript
12
+ * runs from that message to the end of the chain, so the older boundary covers
13
+ * every turn since — expressed as an upsert rather than as branching in the
14
+ * caller.
15
+ */
16
+
17
+ import { getDatabase } from '../index';
18
+ import type { MemoryQueueStatus } from '$shared/types/memory';
19
+
20
+ export interface QueuedExtraction {
21
+ id: number;
22
+ sessionId: string;
23
+ projectId: string;
24
+ projectPath: string;
25
+ userMessageId: string;
26
+ changedPaths: string[];
27
+ deletedPaths: string[];
28
+ injectedMemoryIds: string[];
29
+ attempts: number;
30
+ lastError: string | null;
31
+ status: 'pending' | 'failed';
32
+ readyAt: string;
33
+ createdAt: string;
34
+ /**
35
+ * Bumped every time a turn merges into this row.
36
+ *
37
+ * Read by the runner when it claims an entry and quoted back when it deletes
38
+ * one, so a turn that merged in while the previous was being summarised cannot
39
+ * be thrown away with it. See `remove`.
40
+ */
41
+ revision: number;
42
+ }
43
+
44
+ interface QueueRow {
45
+ id: number;
46
+ session_id: string;
47
+ project_id: string;
48
+ project_path: string;
49
+ user_message_id: string;
50
+ changed_paths: string;
51
+ deleted_paths: string;
52
+ injected_ids: string;
53
+ attempts: number;
54
+ last_error: string | null;
55
+ status: 'pending' | 'failed';
56
+ ready_at: string;
57
+ created_at: string;
58
+ revision: number | null;
59
+ }
60
+
61
+ /** Tolerant of a malformed column: a bad row should cost its paths, not the turn. */
62
+ function parseList(raw: string): string[] {
63
+ try {
64
+ const parsed = JSON.parse(raw);
65
+ return Array.isArray(parsed) ? (parsed as string[]) : [];
66
+ } catch {
67
+ return [];
68
+ }
69
+ }
70
+
71
+ function toEntry(row: QueueRow): QueuedExtraction {
72
+ return {
73
+ id: row.id,
74
+ sessionId: row.session_id,
75
+ projectId: row.project_id,
76
+ projectPath: row.project_path,
77
+ userMessageId: row.user_message_id,
78
+ changedPaths: parseList(row.changed_paths),
79
+ deletedPaths: parseList(row.deleted_paths),
80
+ injectedMemoryIds: parseList(row.injected_ids),
81
+ attempts: row.attempts,
82
+ lastError: row.last_error,
83
+ status: row.status,
84
+ readyAt: row.ready_at,
85
+ createdAt: row.created_at,
86
+ revision: row.revision ?? 0
87
+ };
88
+ }
89
+
90
+ export interface EnqueueInput {
91
+ sessionId: string;
92
+ projectId: string;
93
+ projectPath: string;
94
+ userMessageId: string;
95
+ changedPaths: string[];
96
+ deletedPaths?: string[];
97
+ injectedMemoryIds?: string[];
98
+ /** Seconds from now before this becomes eligible to run. */
99
+ delaySeconds: number;
100
+ }
101
+
102
+ export const memoryQueueQueries = {
103
+ /**
104
+ * Park a turn, or merge it into the one already parked for this session.
105
+ *
106
+ * A merge deliberately keeps the OLDER boundary and unions the path lists,
107
+ * because the eventual extraction reads one transcript covering all of it. It
108
+ * also resets `attempts` and clears the failure: new material is new evidence,
109
+ * and refusing to retry because an earlier version of this span failed would
110
+ * strand the session permanently.
111
+ */
112
+ enqueue(input: EnqueueInput): void {
113
+ const db = getDatabase();
114
+ const existing = db
115
+ .prepare(`SELECT * FROM memory_extraction_queue WHERE session_id = ?`)
116
+ .get(input.sessionId) as QueueRow | null;
117
+
118
+ if (!existing) {
119
+ db.prepare(
120
+ `INSERT INTO memory_extraction_queue (
121
+ session_id, project_id, project_path, user_message_id,
122
+ changed_paths, deleted_paths, injected_ids, ready_at
123
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now', ?))`
124
+ ).run(
125
+ input.sessionId,
126
+ input.projectId,
127
+ input.projectPath,
128
+ input.userMessageId,
129
+ JSON.stringify(input.changedPaths),
130
+ JSON.stringify(input.deletedPaths ?? []),
131
+ JSON.stringify(input.injectedMemoryIds ?? []),
132
+ `+${Math.max(0, Math.round(input.delaySeconds))} seconds`
133
+ );
134
+ return;
135
+ }
136
+
137
+ const merged = toEntry(existing);
138
+ db.prepare(
139
+ `UPDATE memory_extraction_queue
140
+ SET changed_paths = ?, deleted_paths = ?, injected_ids = ?,
141
+ attempts = 0, last_error = NULL, status = 'pending',
142
+ ready_at = datetime('now', ?), updated_at = CURRENT_TIMESTAMP,
143
+ revision = revision + 1
144
+ WHERE id = ?`
145
+ ).run(
146
+ JSON.stringify([...new Set([...merged.changedPaths, ...input.changedPaths])]),
147
+ JSON.stringify([...new Set([...merged.deletedPaths, ...(input.deletedPaths ?? [])])]),
148
+ JSON.stringify([...new Set([...merged.injectedMemoryIds, ...(input.injectedMemoryIds ?? [])])]),
149
+ `+${Math.max(0, Math.round(input.delaySeconds))} seconds`,
150
+ existing.id
151
+ );
152
+ },
153
+
154
+ /**
155
+ * Hold a session's entry while it is streaming — but never past a ceiling.
156
+ *
157
+ * A summary generated mid-answer competes with the answer, so a new stream
158
+ * pushes the pending entry out. The ceiling is what stops that being
159
+ * unbounded: `created_at + maxDeferSeconds` is a hard stop, so a session that
160
+ * never goes quiet is summarised anyway rather than accumulating a span longer
161
+ * than the transcript budget can carry — in which case the head of the span,
162
+ * where the decisions usually are, is what falls off.
163
+ *
164
+ * Entries mid-backoff are left alone: their schedule is a retry policy, not a
165
+ * politeness delay, and pulling it forward would burn attempts.
166
+ */
167
+ deferUntilStreamEnds(sessionId: string, maxDeferSeconds: number): void {
168
+ getDatabase()
169
+ .prepare(
170
+ `UPDATE memory_extraction_queue
171
+ SET ready_at = MIN(datetime('now', '+300 seconds'), datetime(created_at, ?)),
172
+ updated_at = CURRENT_TIMESTAMP
173
+ WHERE session_id = ? AND status = 'pending' AND attempts = 0`
174
+ )
175
+ .run(`+${Math.max(0, Math.round(maxDeferSeconds))} seconds`, sessionId);
176
+ },
177
+
178
+ /**
179
+ * How many entries are due now or imminently.
180
+ *
181
+ * Distinct from "pending", and the difference is what keeps maintenance
182
+ * running: an entry waiting on a condition the user has to fix stays pending
183
+ * indefinitely by design, and treating that as "somebody is working" stood the
184
+ * whole maintenance loop down permanently.
185
+ */
186
+ dueWithin(seconds: number): number {
187
+ return (
188
+ getDatabase()
189
+ .prepare(
190
+ `SELECT COUNT(*) AS c FROM memory_extraction_queue
191
+ WHERE status = 'pending' AND ready_at <= datetime('now', ?)`
192
+ )
193
+ .get(`+${Math.max(0, Math.round(seconds))} seconds`) as { c: number }
194
+ ).c;
195
+ },
196
+
197
+ /**
198
+ * Drop entries whose session no longer exists.
199
+ *
200
+ * Sessions are deleted through several paths and only some of them cancel
201
+ * their extraction; a project being removed takes its sessions with it without
202
+ * this queue ever hearing. Each orphan is a row that can never succeed, is
203
+ * retried forever, and shows in the status counts as work outstanding.
204
+ */
205
+ pruneOrphans(): number {
206
+ const result = getDatabase()
207
+ .prepare(
208
+ `DELETE FROM memory_extraction_queue
209
+ WHERE session_id NOT IN (SELECT id FROM chat_sessions)`
210
+ )
211
+ .run() as { changes?: number };
212
+ return Number(result.changes ?? 0);
213
+ },
214
+
215
+ /** Entries whose time has come, oldest first. */
216
+ due(limit = 5): QueuedExtraction[] {
217
+ const rows = getDatabase()
218
+ .prepare(
219
+ `SELECT * FROM memory_extraction_queue
220
+ WHERE status = 'pending' AND ready_at <= datetime('now')
221
+ ORDER BY ready_at ASC
222
+ LIMIT ?`
223
+ )
224
+ .all(limit) as QueueRow[];
225
+ return rows.map(toEntry);
226
+ },
227
+
228
+ /** Everything queued, regardless of readiness — used by `flush` on shutdown. */
229
+ all(): QueuedExtraction[] {
230
+ const rows = getDatabase()
231
+ .prepare(`SELECT * FROM memory_extraction_queue ORDER BY ready_at ASC`)
232
+ .all() as QueueRow[];
233
+ return rows.map(toEntry);
234
+ },
235
+
236
+ get(sessionId: string): QueuedExtraction | null {
237
+ const row = getDatabase()
238
+ .prepare(`SELECT * FROM memory_extraction_queue WHERE session_id = ?`)
239
+ .get(sessionId) as QueueRow | null;
240
+ return row ? toEntry(row) : null;
241
+ },
242
+
243
+ /**
244
+ * Done with — the turn was summarised, or there was nothing in it to keep.
245
+ *
246
+ * CONDITIONAL on the revision the caller claimed. Extraction runs the moment a
247
+ * turn ends, so another turn can finish and MERGE into this row while it is
248
+ * being summarised; deleting unconditionally would take that turn's boundary
249
+ * and paths with it, silently, on the only write path in the feature. A
250
+ * mismatch means the row has moved on and must stay for the next pass.
251
+ *
252
+ * Returns whether the row was actually removed.
253
+ */
254
+ remove(id: number, revision?: number): boolean {
255
+ const result = (
256
+ revision === undefined
257
+ ? getDatabase().prepare(`DELETE FROM memory_extraction_queue WHERE id = ?`).run(id)
258
+ : getDatabase()
259
+ .prepare(`DELETE FROM memory_extraction_queue WHERE id = ? AND revision = ?`)
260
+ .run(id, revision)
261
+ ) as { changes?: number };
262
+ return Number(result.changes ?? 0) > 0;
263
+ },
264
+
265
+ removeBySession(sessionId: string): void {
266
+ getDatabase().prepare(`DELETE FROM memory_extraction_queue WHERE session_id = ?`).run(sessionId);
267
+ },
268
+
269
+ /**
270
+ * Record a failed attempt and schedule the retry.
271
+ *
272
+ * `countsAsAttempt: false` is for conditions that are not the turn's fault and
273
+ * would never succeed sooner by trying harder — chiefly "no model is
274
+ * configured". Burning attempts on those would mark the entry failed within
275
+ * minutes and lose the turn for a reason the user can fix at their leisure.
276
+ */
277
+ recordFailure(id: number, error: string, delaySeconds: number, options?: { countsAsAttempt?: boolean }): void {
278
+ const counts = options?.countsAsAttempt ?? true;
279
+ getDatabase()
280
+ .prepare(
281
+ `UPDATE memory_extraction_queue
282
+ SET attempts = attempts + ?, last_error = ?,
283
+ ready_at = datetime('now', ?), updated_at = CURRENT_TIMESTAMP
284
+ WHERE id = ?`
285
+ )
286
+ .run(counts ? 1 : 0, error.slice(0, 500), `+${Math.max(1, Math.round(delaySeconds))} seconds`, id);
287
+ },
288
+
289
+ /** Attempts exhausted. Kept rather than deleted, so it stays visible. */
290
+ markFailed(id: number, error: string): void {
291
+ getDatabase()
292
+ .prepare(
293
+ `UPDATE memory_extraction_queue
294
+ SET status = 'failed', last_error = ?, updated_at = CURRENT_TIMESTAMP
295
+ WHERE id = ?`
296
+ )
297
+ .run(error.slice(0, 500), id);
298
+ },
299
+
300
+ /**
301
+ * Put failed entries back in the queue.
302
+ *
303
+ * Called on startup as well as from the UI: a restart usually means something
304
+ * changed — a model was configured, an account re-authenticated, an engine
305
+ * upgraded — and the most common cause of exhaustion is exactly that kind of
306
+ * fixable condition.
307
+ */
308
+ retryFailed(): number {
309
+ const result = getDatabase()
310
+ .prepare(
311
+ `UPDATE memory_extraction_queue
312
+ SET status = 'pending', attempts = 0, ready_at = datetime('now'),
313
+ updated_at = CURRENT_TIMESTAMP
314
+ WHERE status = 'failed'`
315
+ )
316
+ .run() as { changes?: number };
317
+ return Number(result.changes ?? 0);
318
+ },
319
+
320
+ /**
321
+ * Drop entries too old to still be worth summarising.
322
+ *
323
+ * The queue banks a turn until a model can read it, which is right for the
324
+ * hours or days it usually takes someone to configure one. It stops being
325
+ * right at some point: the transcript it points at may have been compacted or
326
+ * paginated away, and a summary of a conversation from six weeks ago is not
327
+ * what the person who finally picks a model is waiting for.
328
+ */
329
+ pruneStale(maxAgeDays: number): number {
330
+ const result = getDatabase()
331
+ .prepare(
332
+ `DELETE FROM memory_extraction_queue
333
+ WHERE julianday('now') - julianday(created_at) > ?`
334
+ )
335
+ .run(maxAgeDays) as { changes?: number };
336
+ return Number(result.changes ?? 0);
337
+ },
338
+
339
+ /** Drop everything queued, for "clear all data" and for tests. */
340
+ clear(): void {
341
+ getDatabase().prepare(`DELETE FROM memory_extraction_queue`).run();
342
+ },
343
+
344
+ /** What the UI shows: how much is waiting, how much is stuck, and why. */
345
+ status(): Omit<MemoryQueueStatus, 'running' | 'modelConfigured'> {
346
+ const db = getDatabase();
347
+ const counts = db
348
+ .prepare(
349
+ `SELECT
350
+ SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) AS pending,
351
+ SUM(CASE WHEN status = 'pending' AND attempts > 0 THEN 1 ELSE 0 END) AS retrying,
352
+ SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed
353
+ FROM memory_extraction_queue`
354
+ )
355
+ .get() as { pending: number | null; retrying: number | null; failed: number | null };
356
+
357
+ const next = db
358
+ .prepare(
359
+ `SELECT ready_at FROM memory_extraction_queue
360
+ WHERE status = 'pending' ORDER BY ready_at ASC LIMIT 1`
361
+ )
362
+ .get() as { ready_at: string } | null;
363
+
364
+ // The most recent error across the queue, whatever its status — one message
365
+ // explains a stalled queue far better than a count does.
366
+ const error = db
367
+ .prepare(
368
+ `SELECT last_error FROM memory_extraction_queue
369
+ WHERE last_error IS NOT NULL ORDER BY updated_at DESC LIMIT 1`
370
+ )
371
+ .get() as { last_error: string } | null;
372
+
373
+ return {
374
+ pending: counts.pending ?? 0,
375
+ retrying: counts.retrying ?? 0,
376
+ failed: counts.failed ?? 0,
377
+ nextAttemptAt: next?.ready_at ?? null,
378
+ lastError: error?.last_error ?? null
379
+ };
380
+ }
381
+ };
@@ -111,6 +111,26 @@ export const snapshotQueries = {
111
111
  /**
112
112
  * Get all snapshots for a session
113
113
  */
114
+ /**
115
+ * The most recent snapshot for a session.
116
+ *
117
+ * Exists because the Memory Graph needs one row per turn and `getBySessionId`
118
+ * returns every snapshot the session ever took, each carrying a full
119
+ * `session_changes` JSON blob. Reading a few hundred of those on every message
120
+ * to look at the last one is the kind of cost that is invisible until a long
121
+ * session makes it obvious.
122
+ */
123
+ getLatestBySessionId(sessionId: string): MessageSnapshot | null {
124
+ const row = getDatabase().prepare(`
125
+ SELECT * FROM message_snapshots
126
+ WHERE session_id = ? AND (is_deleted IS NULL OR is_deleted = 0)
127
+ ORDER BY created_at DESC
128
+ LIMIT 1
129
+ `).get(sessionId) as MessageSnapshot | undefined;
130
+
131
+ return row ?? null;
132
+ },
133
+
114
134
  getBySessionId(sessionId: string): MessageSnapshot[] {
115
135
  const db = getDatabase();
116
136
  const snapshots = db.prepare(`
@@ -27,6 +27,21 @@ stays **agnostic** to the underlying SDK.
27
27
  > services, per-project versioning) is specced in
28
28
  > [`docs/stack-roadmap.md`](../../docs/stack-roadmap.md).
29
29
 
30
+ > **Adapters load on first use, and that rule is now mechanical.** The registry
31
+ > reaches every adapter through `ENGINE_LOADERS` (dynamic `import()`), never a
32
+ > static import, so an engine that fails to load takes only itself down — it
33
+ > used to take the whole backend down at boot, for users who had never touched
34
+ > that engine. The "`import type` only" rule above had been written down since
35
+ > the SDKs were unbundled and was still violated three times (Qwen, OpenCode,
36
+ > Pi), because a value import resolves fine in the repo **and** on any machine
37
+ > whose shared global bun store happens to carry the package. So it is enforced
38
+ > now rather than documented: ESLint rejects value imports of `devDependencies`
39
+ > in shipped code (list derived from `package.json`, so a new engine is covered
40
+ > the moment you add it), and three tests fail on the things types cannot
41
+ > see — an unresolvable shipped import, an adapter reachable from boot, and a
42
+ > loader wired to the wrong engine class. Read **§10.21** and **§10.24** in
43
+ > [lessons-learned](./docs/lessons-learned.md) before touching either.
44
+
30
45
  > **In-process, session-less SDKs are their own category.** Most adapters
31
46
  > wrap a CLI subprocess or an SDK that owns a session store (on disk or via a
32
47
  > server). `cline` is different: `@cline/sdk`'s stateless `Agent` holds **no**
@@ -70,7 +85,7 @@ map, then jump to the area you need.
70
85
  6. [Stack](./docs/stack.md) — registering a host tool or on-demand engine SDK in `install-recipes.ts` + the install runner.
71
86
  7. [Artifacts & Access](./docs/artifacts.md) — the extension layer (Skills, Commands, Subagents, Instructions, Permissions, Profiles, MCP), the capability matrix, and the `artifact-sync.ts` seam adapters call at stream start.
72
87
  8. [Adding a new engine](./docs/adding-an-engine.md) — the end-to-end, stage-by-stage checklist.
73
- 9. [Lessons learned](./docs/lessons-learned.md) — §10 pitfalls (tool name/input canonicalisation, fork session, MCP reuse, auth-blob swap, sub-agent routing, OpenCode v1/v2, structured output, …).
88
+ 9. [Lessons learned](./docs/lessons-learned.md) — §10 pitfalls (tool name/input canonicalisation, fork session, MCP reuse, auth-blob swap, sub-agent routing, OpenCode v1/v2, structured output, cross-engine handoff, …).
74
89
  10. [Quick reference](./docs/quick-reference.md) — "I need X → look in file Y" table.
75
90
 
76
91
  ---
@@ -107,7 +122,10 @@ map, then jump to the area you need.
107
122
  │ ┌──────────────────────────────────────────────────────────────────┐ │
108
123
  │ │ backend/engine/ ← THE LAYER THIS README DOCUMENTS │ │
109
124
  │ │ ────────────────── │ │
110
- │ │ index.ts registry: getEngine / getProjectEngine│ │
125
+ │ │ index.ts registry: ENGINE_LOADERS (lazy) + │ │
126
+ │ │ getEngine / getProjectEngine (async) │ │
127
+ │ │ findProjectEngine (sync, no create) │ │
128
+ │ │ engine-setup.ts pre-stream readiness → Open Stack │ │
111
129
  │ │ types.ts contract: AIEngine │ │
112
130
  │ │ sdk-loader.ts on-demand loader (~/.clopen/stack/…) │ │
113
131
  │ │ install-recipes.ts host-tool + engine-SDK install recipes│ │
@@ -132,6 +150,9 @@ map, then jump to the area you need.
132
150
  │ backend/database/queries/ backend/chat/stream-manager.ts │
133
151
  │ engine-queries.ts routes EngineOutput → DB + WS │
134
152
  │ engine_providers + engine_accounts │
153
+ │ backend/chat/engine-handoff.ts │
154
+ │ replays the branch when the │
155
+ │ session changes engine │
135
156
  └───────────────────────────────────────────────────────────────────────┘
136
157
  ```
137
158
 
@@ -178,6 +199,28 @@ invariants.
178
199
  > login/switch. Do **NOT** propose **per-account** home dirs
179
200
  > (`CODEX_HOME=/foo/account-1/`); that splits session-state, breaks
180
201
  > fork-by-copy, and loses token-refresh persistence. See §10.13.
202
+ > 3. **A session may change engine mid-conversation.** Never assume one
203
+ > session ↔ one engine. `chat_sessions.engine` names the *currently
204
+ > selected* engine, so anything reasoning about "which engine produced
205
+ > this?" must read `engine.type` **per message** — resume-target
206
+ > derivation and checkpoint restore both do. An SDK session id is only
207
+ > meaningful to the engine that minted it; handing one to another engine
208
+ > fails differently on every adapter (silent fresh start on Codex,
209
+ > Copilot, Pi and Cline; an unknown-session error on OpenCode and Claude).
210
+ > Carrying the conversation across is already solved by
211
+ > `backend/chat/engine-handoff.ts` — do **NOT** propose a new adapter
212
+ > method, a portable session format, or per-engine history injection.
213
+ > See §10.23.
214
+ > 4. **Boot must not know about any adapter.** Adding a static
215
+ > `import { XEngine } from './adapters/x'` — to the registry or to anything
216
+ > the boot path reaches — re-couples every user's startup to every engine.
217
+ > There is exactly one place that decides what an unusable engine means to
218
+ > the user (`checkEngineSetup`, surfaced as a chat error with an **Open
219
+ > Stack** button); do **NOT** propose a second one, and do **NOT** wrap the
220
+ > adapter `import()` in a catch that returns a placeholder engine. A broken
221
+ > engine must fail loudly on the engine the user asked for. Translating a
222
+ > module-load failure into an install prompt is worse than the raw message:
223
+ > it sends people reinstalling for a bug no reinstall can fix. See §10.24.
181
224
 
182
225
  ---
183
226
 
@@ -38,7 +38,6 @@ import type {
38
38
  ErrorResultEvent,
39
39
  SystemInitEvent,
40
40
  RateLimitEvent,
41
- NotificationEvent,
42
41
  TokenUsage,
43
42
  StopReason,
44
43
  } from '$shared/types/unified';
@@ -395,27 +394,6 @@ export function convertSystemInit(msg: SDKSystemMessage): SystemInitEvent {
395
394
  };
396
395
  }
397
396
 
398
- /**
399
- * Convert SDKTaskNotificationMessage (terminal background-task event) →
400
- * NotificationEvent. Fires when a backgrounded Agent/teammate finishes
401
- * abnormally (failed | stopped). Successful completion is intentionally
402
- * not surfaced — the result already lands in the conversation, and a
403
- * success toast is just noise. The non-terminal task_started /
404
- * task_progress / task_updated messages are also not surfaced.
405
- */
406
- function convertTaskNotification(
407
- msg: { session_id: string; status: string; summary?: string; task_id: string },
408
- ): NotificationEvent | null {
409
- if (msg.status === 'completed') return null;
410
- return {
411
- type: 'notification',
412
- sessionId: msg.session_id,
413
- level: 'warning',
414
- title: `Background task ${msg.status}`,
415
- message: msg.summary || `Task ${msg.task_id} ${msg.status}`,
416
- };
417
- }
418
-
419
397
  function workflowActivityMessage(
420
398
  msg: { session_id: string; uuid?: string },
421
399
  parentToolUseId: string,
@@ -538,14 +516,17 @@ function* dispatchSdkMessage(msg: SDKMessage, state: StreamConverterState): Gene
538
516
  yield workflowActivityMessage(task, task.tool_use_id, detail);
539
517
  }
540
518
  } else if (subtype === 'task_notification') {
519
+ // Only workflow tasks surface anything, and only inline in the
520
+ // conversation. Backgrounded Agent/Bash tasks stay silent: their
521
+ // outcome already lands in the transcript, so a terminal toast
522
+ // ("Background task failed") is pure noise — a backgrounded
523
+ // `grep` with no match is a non-zero exit, not a problem.
541
524
  const task = msg as unknown as { session_id: string; uuid?: string; task_id: string; tool_use_id?: string; status: string; summary?: string };
542
525
  const parent = task.tool_use_id || state.workflowParents.get(task.task_id);
543
526
  if (parent && state.workflowParents.has(task.task_id)) {
544
527
  yield workflowActivityMessage(task, parent, `Workflow ${task.status}.`);
545
528
  state.workflowParents.delete(task.task_id);
546
529
  }
547
- const note = convertTaskNotification(task);
548
- if (note) yield note;
549
530
  }
550
531
  // task_progress is a repeated heartbeat; real child activity is replayed
551
532
  // from Workflow-owned transcripts. task_updated has no tool_use_id.
@@ -37,6 +37,12 @@ import { fetchCopilotModels } from './models';
37
37
  // it from the SessionConfig field so we don't drift from the SDK.
38
38
  type UserInputResponse = Awaited<ReturnType<NonNullable<SessionConfig['onUserInputRequest']>>>;
39
39
 
40
+ // `MessageOptions` is likewise not re-exported from the SDK root, so derive the
41
+ // attachment element type from `session.send`'s options overload.
42
+ type MessageAttachment = NonNullable<Parameters<CopilotSession['send']>[0] extends string
43
+ ? never
44
+ : NonNullable<Extract<Parameters<CopilotSession['send']>[0], { prompt: string }>['attachments']>>[number];
45
+
40
46
  /**
41
47
  * Map a Copilot permission request to the token the permission policy matches on.
42
48
  * MCP / custom tools carry a `toolName`; everything else is matched by its
@@ -414,7 +420,11 @@ export class CopilotEngine implements AIEngine {
414
420
  const promptText = artifactsContext
415
421
  ? `${artifactsContext}\n\n${extractPromptText(prompt)}`
416
422
  : extractPromptText(prompt);
417
- const sendPromise = session.send({ prompt: promptText }).catch(error => {
423
+ const promptAttachments = extractPromptAttachments(prompt);
424
+ const sendPromise = session.send({
425
+ prompt: promptText,
426
+ ...(promptAttachments.length > 0 && { attachments: promptAttachments }),
427
+ }).catch(error => {
418
428
  debug.error('engine', 'Copilot session.send error:', error);
419
429
  pushEvent({
420
430
  type: 'session.error',
@@ -706,3 +716,29 @@ function extractPromptText(prompt: EngineQueryOptions['prompt']): string {
706
716
  }
707
717
  return parts.join('\n').trim();
708
718
  }
719
+
720
+ /**
721
+ * Image / document blocks → Copilot `blob` attachments.
722
+ *
723
+ * The SDK takes raw base64 in `data` plus a `mimeType` (see its README, "Image
724
+ * Support"), which lines up 1:1 with our unified blocks — no temp files needed,
725
+ * unlike the Codex path. Before this existed the adapter forwarded text only,
726
+ * so every attachment the user added was silently dropped even though
727
+ * `models.ts` advertises `image: !!supports?.vision`.
728
+ */
729
+ function extractPromptAttachments(prompt: EngineQueryOptions['prompt']): MessageAttachment[] {
730
+ const attachments: MessageAttachment[] = [];
731
+ for (const block of prompt.content) {
732
+ if (block.type === 'image') {
733
+ attachments.push({ type: 'blob', data: block.data, mimeType: block.mediaType });
734
+ } else if (block.type === 'document') {
735
+ attachments.push({
736
+ type: 'blob',
737
+ data: block.data,
738
+ mimeType: block.mediaType,
739
+ ...(block.title ? { displayName: block.title } : {}),
740
+ });
741
+ }
742
+ }
743
+ return attachments;
744
+ }
@@ -13,20 +13,32 @@
13
13
  */
14
14
 
15
15
  import type { Api, Model } from '@earendil-works/pi-ai';
16
- import { getSupportedThinkingLevels, clampThinkingLevel } from '@earendil-works/pi-ai';
17
16
  import type { EngineModel, ReasoningControl } from '$shared/types/unified';
18
17
  import { toReasoningOptions } from '$shared/constants/engines';
19
18
  import { debug } from '$shared/utils/logger';
19
+ import { loadEngineSdk } from '$backend/engine/sdk-loader';
20
20
  import { DbCredentialStore, getPiAccounts } from './credential';
21
21
  import { createPiRuntime } from './presets';
22
22
 
23
+ /**
24
+ * The pi-ai thinking-level helpers, loaded on demand. They live in the engine's
25
+ * SDK (installed into the managed stack dir), so they are threaded through as a
26
+ * parameter rather than imported at module scope — a value import here would
27
+ * fail to resolve on any install where Pi has not been installed yet.
28
+ */
29
+ type ThinkingHelpers = Pick<
30
+ typeof import('@earendil-works/pi-ai'),
31
+ 'getSupportedThinkingLevels' | 'clampThinkingLevel'
32
+ >;
33
+
23
34
  export async function fetchPiModels(): Promise<EngineModel[]> {
24
35
  try {
25
36
  const accounts = getPiAccounts();
26
37
  const store = new DbCredentialStore(accounts);
27
38
  const runtime = await createPiRuntime(store);
28
39
  const available = await runtime.getAvailable();
29
- const mapped = available.map(mapPiModel);
40
+ const thinking = await loadEngineSdk<typeof import('@earendil-works/pi-ai')>('pi', '@earendil-works/pi-ai');
41
+ const mapped = available.map(model => mapPiModel(model, thinking));
30
42
  debug.log('engine', `Pi getAvailableModels: ${mapped.length} models across ${accounts.length} account(s)`);
31
43
  return mapped;
32
44
  } catch (error) {
@@ -40,19 +52,19 @@ export async function fetchPiModels(): Promise<EngineModel[]> {
40
52
  * the supported levels per model (`getSupportedThinkingLevels`), so the control
41
53
  * is fully model-driven. Skipped when a model only supports `off` (no reasoning).
42
54
  */
43
- function buildPiReasoningControl(model: Model<Api>): ReasoningControl | undefined {
44
- const levels = getSupportedThinkingLevels(model);
55
+ function buildPiReasoningControl(model: Model<Api>, thinking: ThinkingHelpers): ReasoningControl | undefined {
56
+ const levels = thinking.getSupportedThinkingLevels(model);
45
57
  if (levels.length <= 1) return undefined;
46
- const fallback = model.reasoning ? clampThinkingLevel(model, 'medium') : 'off';
58
+ const fallback = model.reasoning ? thinking.clampThinkingLevel(model, 'medium') : 'off';
47
59
  return {
48
60
  levels: toReasoningOptions(levels),
49
61
  default: fallback,
50
62
  };
51
63
  }
52
64
 
53
- function mapPiModel(model: Model<Api>): EngineModel {
65
+ function mapPiModel(model: Model<Api>, thinking: ThinkingHelpers): EngineModel {
54
66
  const image = model.input.includes('image');
55
- const reasoningControl = buildPiReasoningControl(model);
67
+ const reasoningControl = buildPiReasoningControl(model, thinking);
56
68
  return {
57
69
  engine: {
58
70
  type: 'pi',