@myrialabs/clopen 0.4.26 → 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/restore.ts +38 -4
- package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
- package/dist/assets/{index-B6QGUN03.js → index-BCv5HlPk.js} +1 -1
- package/dist/assets/{index-DYa-GDsb.js → index-BTGcf_Vy.js} +1 -1
- package/dist/assets/main-BrqMMMRX.css +1 -0
- package/dist/assets/{main-Dznkfxsd.js → main-CgmAFpU3.js} +835 -426
- 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,439 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-engine conversation handoff.
|
|
3
|
+
*
|
|
4
|
+
* Every engine keeps continuity in its own native session store — a Claude
|
|
5
|
+
* session id, a Codex rollout file, an OpenCode server session, Cline's
|
|
6
|
+
* in-memory transcript. Those ids are not portable, so a session that switches
|
|
7
|
+
* engine mid-conversation has nothing for the new engine to resume from. This
|
|
8
|
+
* module rebuilds the branch from Clopen's own DB and hands it to the new
|
|
9
|
+
* engine as prompt content, so the user can change engine without starting a
|
|
10
|
+
* new chat.
|
|
11
|
+
*
|
|
12
|
+
* ── The rule ──
|
|
13
|
+
* Replay the branch verbatim. When the replay exceeds the trigger threshold,
|
|
14
|
+
* tool results older than the last N tool uses are replaced with a placeholder
|
|
15
|
+
* — tool *inputs* are always kept.
|
|
16
|
+
*
|
|
17
|
+
* Both numbers are the shipped defaults of Anthropic's `clear_tool_uses_20250919`
|
|
18
|
+
* context-editing strategy (trigger 100k input tokens, keep 3 tool uses,
|
|
19
|
+
* `clear_tool_inputs: false`). We mirror them rather than inventing our own
|
|
20
|
+
* because they are measured: context editing alone reports +29% on agentic
|
|
21
|
+
* benchmarks, and an 84% token reduction on long tool-heavy runs while
|
|
22
|
+
* completing tasks that otherwise fail. See
|
|
23
|
+
* https://platform.claude.com/docs/en/build-with-claude/context-editing.
|
|
24
|
+
*
|
|
25
|
+
* Deliberately NOT keyed on `compact_boundary`: only the Claude adapter ever
|
|
26
|
+
* emits one (OpenCode drops compaction events, Pi disables compaction outright),
|
|
27
|
+
* so a boundary-based window would silently degenerate to "replay everything"
|
|
28
|
+
* on 7 of 8 engines.
|
|
29
|
+
*
|
|
30
|
+
* The handoff never touches the timeline: it is prepended to the *engine*
|
|
31
|
+
* prompt only, never to the `UserMessage` that gets persisted and rendered.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
import { messageQueries, sessionQueries } from '../database/queries';
|
|
35
|
+
import { getModelsByEngine } from '$shared/constants/engines';
|
|
36
|
+
import { debug } from '$shared/utils/logger';
|
|
37
|
+
import type {
|
|
38
|
+
EngineType,
|
|
39
|
+
UnifiedMessage,
|
|
40
|
+
UserMessage,
|
|
41
|
+
AssistantMessage,
|
|
42
|
+
ReasoningMessage,
|
|
43
|
+
UserContentBlock,
|
|
44
|
+
ImageBlock,
|
|
45
|
+
DocumentBlock,
|
|
46
|
+
} from '$shared/types/unified';
|
|
47
|
+
|
|
48
|
+
// ============================================================================
|
|
49
|
+
// Tunables — ported from clear_tool_uses_20250919 defaults
|
|
50
|
+
// ============================================================================
|
|
51
|
+
|
|
52
|
+
/** Replay stays fully verbatim below this estimated input-token count. */
|
|
53
|
+
const TRIGGER_TOKENS = 100_000;
|
|
54
|
+
|
|
55
|
+
/** Tool uses whose results survive clearing, counted from the end. */
|
|
56
|
+
const KEEP_TOOL_USES = 3;
|
|
57
|
+
|
|
58
|
+
/** Rough token estimate. Good enough to decide whether clearing is needed. */
|
|
59
|
+
const CHARS_PER_TOKEN = 4;
|
|
60
|
+
|
|
61
|
+
// ============================================================================
|
|
62
|
+
// Intermediate representation
|
|
63
|
+
// ============================================================================
|
|
64
|
+
|
|
65
|
+
type Entry =
|
|
66
|
+
| { kind: 'user'; text: string; attachments: Array<ImageBlock | DocumentBlock> }
|
|
67
|
+
| { kind: 'assistant'; text: string }
|
|
68
|
+
| { kind: 'reasoning'; text: string }
|
|
69
|
+
| { kind: 'tool_use'; id: string; name: string; input: unknown }
|
|
70
|
+
| { kind: 'tool_result'; toolUseId: string; content: string; isError: boolean }
|
|
71
|
+
| { kind: 'compact' };
|
|
72
|
+
|
|
73
|
+
export interface HandoffStats {
|
|
74
|
+
turns: number;
|
|
75
|
+
clearedToolResults: number;
|
|
76
|
+
droppedAttachments: number;
|
|
77
|
+
estimatedTokens: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface HandoffResult {
|
|
81
|
+
/** Blocks to prepend to the engine prompt. Never empty when non-null. */
|
|
82
|
+
blocks: UserContentBlock[];
|
|
83
|
+
stats: HandoffStats;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// ============================================================================
|
|
87
|
+
// Branch inspection
|
|
88
|
+
// ============================================================================
|
|
89
|
+
|
|
90
|
+
function parse(data: string): UnifiedMessage | null {
|
|
91
|
+
try {
|
|
92
|
+
return JSON.parse(data) as UnifiedMessage;
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* The engine that produced the trailing part of this branch, i.e. the engine
|
|
100
|
+
* whose native session a resume would target.
|
|
101
|
+
*
|
|
102
|
+
* Walks back to the most recent NON-user message and reads its `engine.type`.
|
|
103
|
+
* User messages carry the *sending* client's engine choice, which is exactly
|
|
104
|
+
* what we must not trust here. Falls back to `chat_sessions.engine` for legacy
|
|
105
|
+
* rows written before messages carried an engine block — that column is
|
|
106
|
+
* reliable because `chat:model-sync` persists it the moment anyone picks an
|
|
107
|
+
* engine, not only on send.
|
|
108
|
+
*/
|
|
109
|
+
export function resolveBranchEngine(chatSessionId: string): EngineType | null {
|
|
110
|
+
try {
|
|
111
|
+
const head = sessionQueries.getHead(chatSessionId);
|
|
112
|
+
if (head) {
|
|
113
|
+
const chain = messageQueries.getPathToRoot(head);
|
|
114
|
+
for (let i = chain.length - 1; i >= 0; i--) {
|
|
115
|
+
const msg = parse(chain[i].data);
|
|
116
|
+
if (!msg || msg.type === 'user') continue;
|
|
117
|
+
const type = msg.engine?.type;
|
|
118
|
+
if (type) return type as EngineType;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
} catch (error) {
|
|
122
|
+
debug.error('chat', 'Failed to resolve branch engine:', error);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
try {
|
|
126
|
+
const session = sessionQueries.getById(chatSessionId);
|
|
127
|
+
return (session?.engine as EngineType) || null;
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ============================================================================
|
|
134
|
+
// Attachment capability
|
|
135
|
+
// ============================================================================
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Whether the target can actually carry an attachment kind.
|
|
139
|
+
*
|
|
140
|
+
* Two independent gates. The model catalog says what the MODEL accepts; this
|
|
141
|
+
* table says what the ADAPTER actually forwards. They genuinely differ —
|
|
142
|
+
* Codex, Cursor, Pi and Cline have no document path at all, so a PDF handed to
|
|
143
|
+
* them vanishes no matter what the catalog claims. Trusting the catalog alone
|
|
144
|
+
* would silently vaporise history.
|
|
145
|
+
*/
|
|
146
|
+
function attachmentSupport(engine: EngineType, modelId: string): { image: boolean; document: boolean } {
|
|
147
|
+
const ADAPTER_IMAGE: Record<EngineType, boolean> = {
|
|
148
|
+
'claude-code': true,
|
|
149
|
+
opencode: true,
|
|
150
|
+
codex: true,
|
|
151
|
+
cursor: true,
|
|
152
|
+
pi: true,
|
|
153
|
+
cline: true,
|
|
154
|
+
qwen: true,
|
|
155
|
+
copilot: true,
|
|
156
|
+
};
|
|
157
|
+
const ADAPTER_DOCUMENT: Record<EngineType, boolean> = {
|
|
158
|
+
'claude-code': true,
|
|
159
|
+
opencode: true,
|
|
160
|
+
qwen: true,
|
|
161
|
+
copilot: true,
|
|
162
|
+
codex: false,
|
|
163
|
+
cursor: false,
|
|
164
|
+
pi: false,
|
|
165
|
+
cline: false,
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const model = getModelsByEngine(engine).find(m => m.engine.model.id === modelId);
|
|
169
|
+
// Unknown model (catalog not yet populated in this process): trust the
|
|
170
|
+
// adapter gate alone rather than stripping attachments that would work.
|
|
171
|
+
const modelImage = model ? model.modalities.input.image : true;
|
|
172
|
+
const modelDocument = model ? model.modalities.input.pdf : true;
|
|
173
|
+
|
|
174
|
+
return {
|
|
175
|
+
image: ADAPTER_IMAGE[engine] && modelImage,
|
|
176
|
+
document: ADAPTER_DOCUMENT[engine] && modelDocument,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ============================================================================
|
|
181
|
+
// Collection
|
|
182
|
+
// ============================================================================
|
|
183
|
+
|
|
184
|
+
function collect(messages: UnifiedMessage[]): Entry[] {
|
|
185
|
+
const entries: Entry[] = [];
|
|
186
|
+
|
|
187
|
+
for (const msg of messages) {
|
|
188
|
+
// Sub-agent traffic never reaches the root timeline and is already
|
|
189
|
+
// summarised by its parent tool result — replaying it would duplicate
|
|
190
|
+
// the same work in a far more verbose form.
|
|
191
|
+
if (msg.parent?.toolUseId) continue;
|
|
192
|
+
|
|
193
|
+
switch (msg.type) {
|
|
194
|
+
case 'user': {
|
|
195
|
+
const user = msg as UserMessage;
|
|
196
|
+
const texts: string[] = [];
|
|
197
|
+
const attachments: Array<ImageBlock | DocumentBlock> = [];
|
|
198
|
+
let emittedResult = false;
|
|
199
|
+
|
|
200
|
+
for (const block of user.content) {
|
|
201
|
+
if (block.type === 'text') {
|
|
202
|
+
if (block.text.trim()) texts.push(block.text);
|
|
203
|
+
} else if (block.type === 'image' || block.type === 'document') {
|
|
204
|
+
attachments.push(block);
|
|
205
|
+
} else if (block.type === 'tool_result') {
|
|
206
|
+
entries.push({
|
|
207
|
+
kind: 'tool_result',
|
|
208
|
+
toolUseId: block.toolUseId,
|
|
209
|
+
content: block.content,
|
|
210
|
+
isError: block.isError,
|
|
211
|
+
});
|
|
212
|
+
emittedResult = true;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// A tool-result carrier is not a conversational turn; the result
|
|
217
|
+
// entries above already represent it.
|
|
218
|
+
if (emittedResult) break;
|
|
219
|
+
// Synthetic post-compaction summaries ARE worth replaying: they are
|
|
220
|
+
// the engine's own compression of everything before them.
|
|
221
|
+
if (texts.length || attachments.length) {
|
|
222
|
+
entries.push({ kind: 'user', text: texts.join('\n'), attachments });
|
|
223
|
+
}
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
case 'assistant': {
|
|
228
|
+
const assistant = msg as AssistantMessage;
|
|
229
|
+
for (const block of assistant.content) {
|
|
230
|
+
if (block.type === 'text') {
|
|
231
|
+
if (block.text.trim()) entries.push({ kind: 'assistant', text: block.text });
|
|
232
|
+
} else if (block.type === 'tool_use') {
|
|
233
|
+
entries.push({ kind: 'tool_use', id: block.id, name: block.name, input: block.input });
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
case 'reasoning': {
|
|
240
|
+
const reasoning = msg as ReasoningMessage;
|
|
241
|
+
if (reasoning.text.trim()) entries.push({ kind: 'reasoning', text: reasoning.text });
|
|
242
|
+
break;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
case 'compact_boundary':
|
|
246
|
+
entries.push({ kind: 'compact' });
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return entries;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// ============================================================================
|
|
255
|
+
// Rendering
|
|
256
|
+
// ============================================================================
|
|
257
|
+
|
|
258
|
+
function stringifyInput(input: unknown): string {
|
|
259
|
+
try {
|
|
260
|
+
const json = JSON.stringify(input);
|
|
261
|
+
return json ?? String(input);
|
|
262
|
+
} catch {
|
|
263
|
+
return '[uninspectable input]';
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function renderEntries(entries: Entry[], clearedToolUseIds: Set<string>, support: { image: boolean; document: boolean }): {
|
|
268
|
+
lines: string[];
|
|
269
|
+
attachments: Array<ImageBlock | DocumentBlock>;
|
|
270
|
+
droppedAttachments: number;
|
|
271
|
+
} {
|
|
272
|
+
const lines: string[] = [];
|
|
273
|
+
const attachments: Array<ImageBlock | DocumentBlock> = [];
|
|
274
|
+
let droppedAttachments = 0;
|
|
275
|
+
|
|
276
|
+
for (const entry of entries) {
|
|
277
|
+
switch (entry.kind) {
|
|
278
|
+
case 'user': {
|
|
279
|
+
if (entry.text) lines.push(`[user]\n${entry.text}`);
|
|
280
|
+
for (const att of entry.attachments) {
|
|
281
|
+
const supported = att.type === 'image' ? support.image : support.document;
|
|
282
|
+
if (supported) {
|
|
283
|
+
attachments.push(att);
|
|
284
|
+
lines.push(`[user attachment: ${describeAttachment(att)}]`);
|
|
285
|
+
} else {
|
|
286
|
+
droppedAttachments++;
|
|
287
|
+
lines.push(`[user attachment: ${describeAttachment(att)} — not supported by this model, content omitted]`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
case 'assistant':
|
|
293
|
+
lines.push(`[assistant]\n${entry.text}`);
|
|
294
|
+
break;
|
|
295
|
+
case 'reasoning':
|
|
296
|
+
lines.push(`[assistant thinking]\n${entry.text}`);
|
|
297
|
+
break;
|
|
298
|
+
case 'tool_use':
|
|
299
|
+
lines.push(`[tool call: ${entry.name}]\n${stringifyInput(entry.input)}`);
|
|
300
|
+
break;
|
|
301
|
+
case 'tool_result':
|
|
302
|
+
if (clearedToolUseIds.has(entry.toolUseId)) {
|
|
303
|
+
lines.push('[tool result cleared to save context — re-run the tool if you need it]');
|
|
304
|
+
} else {
|
|
305
|
+
lines.push(`[tool result${entry.isError ? ' (error)' : ''}]\n${entry.content}`);
|
|
306
|
+
}
|
|
307
|
+
break;
|
|
308
|
+
case 'compact':
|
|
309
|
+
// The boundary marker comes first, then the engine's own summary as
|
|
310
|
+
// a synthetic user message — that ordering is what message-grouper
|
|
311
|
+
// relies on, so the wording here must match it.
|
|
312
|
+
lines.push('[the previous engine compacted the conversation here; the summary that follows replaced everything above it]');
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return { lines, attachments, droppedAttachments };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function describeAttachment(att: ImageBlock | DocumentBlock): string {
|
|
321
|
+
if (att.type === 'document') return att.title ? `${att.title} (${att.mediaType})` : att.mediaType;
|
|
322
|
+
return att.mediaType;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function estimateTokens(lines: string[]): number {
|
|
326
|
+
let chars = 0;
|
|
327
|
+
for (const line of lines) chars += line.length + 1;
|
|
328
|
+
return Math.ceil(chars / CHARS_PER_TOKEN);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ============================================================================
|
|
332
|
+
// Public API
|
|
333
|
+
// ============================================================================
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Render a branch (already parsed, root → head order) into handoff blocks.
|
|
337
|
+
*
|
|
338
|
+
* Pure: no DB, no registry. `buildEngineHandoff` is the thin DB-reading wrapper
|
|
339
|
+
* around it, which is also what makes the interesting behaviour — clearing,
|
|
340
|
+
* attachment gating, sub-agent filtering — directly testable.
|
|
341
|
+
*/
|
|
342
|
+
export function renderHandoff(
|
|
343
|
+
messages: UnifiedMessage[],
|
|
344
|
+
support: { image: boolean; document: boolean },
|
|
345
|
+
previousEngine: EngineType | null
|
|
346
|
+
): HandoffResult | null {
|
|
347
|
+
const entries = collect(messages);
|
|
348
|
+
if (!entries.length) return null;
|
|
349
|
+
|
|
350
|
+
// First pass: verbatim. Only if that exceeds the trigger do we clear, and
|
|
351
|
+
// then only the tool results outside the most recent KEEP_TOOL_USES.
|
|
352
|
+
const clearedToolUseIds = new Set<string>();
|
|
353
|
+
let render = renderEntries(entries, clearedToolUseIds, support);
|
|
354
|
+
|
|
355
|
+
if (estimateTokens(render.lines) > TRIGGER_TOKENS) {
|
|
356
|
+
const toolUseIds = entries.filter((e): e is Extract<Entry, { kind: 'tool_use' }> => e.kind === 'tool_use').map(e => e.id);
|
|
357
|
+
const kept = new Set(toolUseIds.slice(-KEEP_TOOL_USES));
|
|
358
|
+
for (const id of toolUseIds) {
|
|
359
|
+
if (!kept.has(id)) clearedToolUseIds.add(id);
|
|
360
|
+
}
|
|
361
|
+
render = renderEntries(entries, clearedToolUseIds, support);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const turns = entries.filter(e => e.kind === 'user' || e.kind === 'assistant').length;
|
|
365
|
+
const estimatedTokens = estimateTokens(render.lines);
|
|
366
|
+
|
|
367
|
+
const header = previousEngine
|
|
368
|
+
? `The conversation below happened in this same chat, driven by a different engine (${previousEngine}). You are taking over from it.`
|
|
369
|
+
: 'The conversation below happened earlier in this same chat. You are taking over from it.';
|
|
370
|
+
|
|
371
|
+
const transcript = [
|
|
372
|
+
header,
|
|
373
|
+
'Treat it as your own prior context: it is what you already said, did and learned. Do not greet the user as if this were a new conversation, and do not repeat work that is already done. Anything marked as cleared or omitted can be re-derived with your tools.',
|
|
374
|
+
'',
|
|
375
|
+
'<conversation-transcript>',
|
|
376
|
+
...render.lines,
|
|
377
|
+
'</conversation-transcript>',
|
|
378
|
+
'',
|
|
379
|
+
'The user\'s new message follows.',
|
|
380
|
+
].join('\n');
|
|
381
|
+
|
|
382
|
+
const blocks: UserContentBlock[] = [{ type: 'text', text: transcript }, ...render.attachments];
|
|
383
|
+
|
|
384
|
+
return {
|
|
385
|
+
blocks,
|
|
386
|
+
stats: {
|
|
387
|
+
turns,
|
|
388
|
+
clearedToolResults: clearedToolUseIds.size,
|
|
389
|
+
droppedAttachments: render.droppedAttachments,
|
|
390
|
+
estimatedTokens,
|
|
391
|
+
},
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Build the handoff blocks for a branch, or null when there is nothing to hand
|
|
397
|
+
* over (empty session, unreadable chain).
|
|
398
|
+
*
|
|
399
|
+
* `targetEngine` / `targetModelId` describe the engine the user just switched
|
|
400
|
+
* TO — they decide which attachments can ride along.
|
|
401
|
+
*
|
|
402
|
+
* `excludeMessageId` is the turn's own user message. By the time this runs it
|
|
403
|
+
* has already been saved and IS the branch head, so without excluding it the
|
|
404
|
+
* transcript would end with a verbatim copy of the message the engine is about
|
|
405
|
+
* to be asked to answer.
|
|
406
|
+
*/
|
|
407
|
+
export function buildEngineHandoff(
|
|
408
|
+
chatSessionId: string,
|
|
409
|
+
targetEngine: EngineType,
|
|
410
|
+
targetModelId: string,
|
|
411
|
+
previousEngine: EngineType | null,
|
|
412
|
+
excludeMessageId?: string
|
|
413
|
+
): HandoffResult | null {
|
|
414
|
+
let messages: UnifiedMessage[];
|
|
415
|
+
try {
|
|
416
|
+
const head = sessionQueries.getHead(chatSessionId);
|
|
417
|
+
if (!head) return null;
|
|
418
|
+
messages = messageQueries
|
|
419
|
+
.getPathToRoot(head)
|
|
420
|
+
.filter(row => row.id !== excludeMessageId)
|
|
421
|
+
.map(row => parse(row.data))
|
|
422
|
+
.filter((msg): msg is UnifiedMessage => msg !== null);
|
|
423
|
+
} catch (error) {
|
|
424
|
+
debug.error('chat', 'Engine handoff: failed to read branch:', error);
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
if (!messages.length) return null;
|
|
428
|
+
|
|
429
|
+
return renderHandoff(messages, attachmentSupport(targetEngine, targetModelId), previousEngine);
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Prepend handoff blocks to a prompt, returning a new UserMessage. The original
|
|
434
|
+
* message is left untouched so the persisted/rendered timeline never sees the
|
|
435
|
+
* transcript.
|
|
436
|
+
*/
|
|
437
|
+
export function withHandoff(prompt: UserMessage, blocks: UserContentBlock[]): UserMessage {
|
|
438
|
+
return { ...prompt, content: [...blocks, ...prompt.content] };
|
|
439
|
+
}
|