forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsurface-session.ts
More file actions
348 lines (320 loc) · 11.6 KB
/
Copy pathsurface-session.ts
File metadata and controls
348 lines (320 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
import { generateAgentId } from "./sqlite-store.js";
import type { AgentExecutionRole, AgentStore, ProviderBoundary } from "./types.js";
export interface SurfaceRef {
surfaceKind: string;
externalRefKind: string;
externalRefId: string;
}
export interface ResolveSurfaceSessionInput {
ownerId: string;
surfaceRef: SurfaceRef;
defaultAdapterId?: string;
executionRole?: AgentExecutionRole;
providerBoundary?: ProviderBoundary;
modelProfile?: string | null;
defaultCwd?: string | null;
executionProfileSource?: "creation" | "child_derivation";
title?: string | null;
}
export interface ResolveSurfaceSessionResult {
conversationId: string;
agentSessionId: string;
}
export interface LegacyMainChatSessionEntry {
chatId: string;
agentSessionId: string;
}
export interface LegacyMainChatSessionImportReceipt {
acceptedEntries: LegacyMainChatSessionEntry[];
importedCount: number;
}
export const LEGACY_MAIN_CHAT_SESSION_COMPATIBILITY = {
owner: "desktop-agent-runtime",
removalCondition: "all supported desktop versions have imported UserDefaults main-chat session aliases",
removeBy: "2026-10-01",
} as const;
const SHARED_CHAT_SURFACES = new Set(["main_chat", "floating_chat", "realtime_voice", "realtime"]);
function sharesChatContinuity(surfaceRef: SurfaceRef): boolean {
return surfaceRef.externalRefKind === "chat" && SHARED_CHAT_SURFACES.has(surfaceRef.surfaceKind);
}
export function surfaceRefKey(surfaceRef: SurfaceRef): string {
return `${surfaceRef.surfaceKind}|${surfaceRef.externalRefKind}|${surfaceRef.externalRefId}`;
}
function isSqliteUniqueConstraintError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
return (
error.message.includes("UNIQUE constraint failed") ||
error.message.includes("SQLITE_CONSTRAINT_UNIQUE")
);
}
function readSurfaceConversation(
store: AgentStore,
input: ResolveSurfaceSessionInput,
): ResolveSurfaceSessionResult | undefined {
const row = store.getOptionalRow(
`SELECT conversation_id, agent_session_id
FROM surface_conversations
WHERE owner_id = ? AND surface_kind = ? AND external_ref_kind = ? AND external_ref_id = ?`,
[
input.ownerId,
input.surfaceRef.surfaceKind,
input.surfaceRef.externalRefKind,
input.surfaceRef.externalRefId,
],
);
if (!row) return undefined;
return {
conversationId: String(row.conversation_id),
agentSessionId: String(row.agent_session_id),
};
}
function readSessionIdByExternalRef(store: AgentStore, input: ResolveSurfaceSessionInput): string | undefined {
const row = store.getOptionalRow(
`SELECT session_id FROM sessions
WHERE owner_id = ? AND external_ref_kind = ? AND external_ref_id = ?`,
[input.ownerId, input.surfaceRef.externalRefKind, input.surfaceRef.externalRefId],
);
return row ? String(row.session_id) : undefined;
}
function readSharedChatMapping(
store: AgentStore,
input: ResolveSurfaceSessionInput,
): ResolveSurfaceSessionResult | undefined {
if (!sharesChatContinuity(input.surfaceRef)) return undefined;
const row = store.getOptionalRow(
`SELECT conversation_id, agent_session_id
FROM surface_conversations
WHERE owner_id = ? AND external_ref_kind = ? AND external_ref_id = ?
AND surface_kind IN ('main_chat', 'floating_chat', 'realtime_voice', 'realtime')
ORDER BY CASE surface_kind
WHEN 'main_chat' THEN 0
WHEN 'floating_chat' THEN 1
WHEN 'realtime_voice' THEN 2
ELSE 3 END,
created_at_ms ASC
LIMIT 1`,
[input.ownerId, input.surfaceRef.externalRefKind, input.surfaceRef.externalRefId],
);
return row ? {
conversationId: String(row.conversation_id),
agentSessionId: String(row.agent_session_id),
} : undefined;
}
function touchSurfaceConversation(store: AgentStore, input: ResolveSurfaceSessionInput, now: number): void {
store.execute(
`UPDATE surface_conversations
SET last_active_at_ms = ?
WHERE owner_id = ? AND surface_kind = ? AND external_ref_kind = ? AND external_ref_id = ?`,
[
now,
input.ownerId,
input.surfaceRef.surfaceKind,
input.surfaceRef.externalRefKind,
input.surfaceRef.externalRefId,
],
);
}
function createSurfaceConversationMapping(
store: AgentStore,
input: ResolveSurfaceSessionInput,
agentSessionId: string,
now: number,
): ResolveSurfaceSessionResult {
const shared = readSharedChatMapping(store, input);
if (shared && shared.agentSessionId !== agentSessionId) {
throw new Error("Shared chat continuity mapping points at a different canonical session");
}
const conversationId = shared?.conversationId ?? generateAgentId("conversation");
try {
store.insertSurfaceConversation({
ownerId: input.ownerId,
surfaceKind: input.surfaceRef.surfaceKind,
externalRefKind: input.surfaceRef.externalRefKind,
externalRefId: input.surfaceRef.externalRefId,
conversationId,
agentSessionId,
createdAtMs: now,
lastActiveAtMs: now,
});
return { conversationId, agentSessionId };
} catch (error) {
if (!isSqliteUniqueConstraintError(error)) throw error;
const mapped = readSurfaceConversation(store, input);
if (!mapped) throw error;
touchSurfaceConversation(store, input, now);
return mapped;
}
}
function recoverResolveSurfaceSessionAfterConflict(
store: AgentStore,
input: ResolveSurfaceSessionInput,
now: number,
error: unknown,
): ResolveSurfaceSessionResult {
if (!isSqliteUniqueConstraintError(error)) throw error;
const mapped = readSurfaceConversation(store, input);
if (mapped) {
touchSurfaceConversation(store, input, now);
return mapped;
}
const existingSessionId = readSessionIdByExternalRef(store, input);
if (!existingSessionId) throw error;
return createSurfaceConversationMapping(store, input, existingSessionId, now);
}
export function resolveSurfaceSession(
store: AgentStore,
input: ResolveSurfaceSessionInput,
nowMs: () => number,
): ResolveSurfaceSessionResult {
return store.withTransaction(() => {
const now = nowMs();
const mapped = readSurfaceConversation(store, input);
if (mapped) {
touchSurfaceConversation(store, input, now);
return mapped;
}
const existingSessionId = readSessionIdByExternalRef(store, input);
if (existingSessionId) {
const resolved = createSurfaceConversationMapping(store, input, existingSessionId, now);
return resolved;
}
try {
const session = store.insertSession({
ownerId: input.ownerId,
surfaceKind: input.surfaceRef.surfaceKind,
externalRefKind: input.surfaceRef.externalRefKind,
externalRefId: input.surfaceRef.externalRefId,
title: input.title ?? null,
defaultAdapterId: input.defaultAdapterId ?? "acp",
executionRole: input.executionRole,
providerBoundary: input.providerBoundary,
modelProfile: input.modelProfile,
defaultCwd: input.defaultCwd,
executionProfileSource: input.executionProfileSource,
});
return createSurfaceConversationMapping(store, input, session.sessionId, now);
} catch (error) {
return recoverResolveSurfaceSessionAfterConflict(store, input, now, error);
}
});
}
function resolveLegacyAgentSessionId(
store: AgentStore,
input: { ownerId: string; surfaceRef: SurfaceRef; legacySessionId: string; defaultAdapterId?: string },
): string {
const existingByRef = readSessionIdByExternalRef(store, {
ownerId: input.ownerId,
surfaceRef: input.surfaceRef,
});
if (existingByRef) return existingByRef;
const sessionRow = store.getOptionalRow(
"SELECT session_id FROM sessions WHERE session_id = ? AND owner_id = ?",
[input.legacySessionId, input.ownerId],
);
if (sessionRow) return String(sessionRow.session_id);
try {
return store.insertSession({
ownerId: input.ownerId,
sessionId: input.legacySessionId,
surfaceKind: input.surfaceRef.surfaceKind,
externalRefKind: input.surfaceRef.externalRefKind,
externalRefId: input.surfaceRef.externalRefId,
defaultAdapterId: input.defaultAdapterId ?? "acp",
}).sessionId;
} catch (error) {
if (!isSqliteUniqueConstraintError(error)) throw error;
const raced = readSessionIdByExternalRef(store, {
ownerId: input.ownerId,
surfaceRef: input.surfaceRef,
});
if (!raced) throw error;
return raced;
}
}
export function importLegacyMainChatSessions(
store: AgentStore,
input: { ownerId: string; entries: LegacyMainChatSessionEntry[] },
nowMs: () => number,
): LegacyMainChatSessionImportReceipt {
const acceptedEntries = input.entries.map((entry) => ({
chatId: typeof entry?.chatId === "string" ? entry.chatId.trim() : "",
agentSessionId: typeof entry?.agentSessionId === "string" ? entry.agentSessionId.trim() : "",
}));
const seenChatIds = new Set<string>();
for (const entry of acceptedEntries) {
if (!entry.chatId || !entry.agentSessionId) {
throw new Error("invalid_legacy_main_chat_session_entry");
}
if (seenChatIds.has(entry.chatId)) {
throw new Error("duplicate_legacy_main_chat_session_entry");
}
seenChatIds.add(entry.chatId);
}
const now = nowMs();
let imported = 0;
for (const entry of acceptedEntries) {
const surfaceRef: SurfaceRef = {
surfaceKind: "main_chat",
externalRefKind: "chat",
externalRefId: entry.chatId,
};
const existing = store.getOptionalRow(
`SELECT conversation_id FROM surface_conversations
WHERE owner_id = ? AND surface_kind = ? AND external_ref_kind = ? AND external_ref_id = ?`,
[input.ownerId, surfaceRef.surfaceKind, surfaceRef.externalRefKind, surfaceRef.externalRefId],
);
if (existing) continue;
const resolvedSessionId = resolveLegacyAgentSessionId(store, {
ownerId: input.ownerId,
surfaceRef,
legacySessionId: entry.agentSessionId,
defaultAdapterId: "acp",
});
const conversationId = generateAgentId("conversation");
try {
store.insertSurfaceConversation({
ownerId: input.ownerId,
surfaceKind: surfaceRef.surfaceKind,
externalRefKind: surfaceRef.externalRefKind,
externalRefId: surfaceRef.externalRefId,
conversationId,
agentSessionId: resolvedSessionId,
createdAtMs: now,
lastActiveAtMs: now,
});
} catch (error) {
if (!isSqliteUniqueConstraintError(error)) throw error;
const mapped = readSurfaceConversation(store, { ownerId: input.ownerId, surfaceRef });
if (mapped) continue;
throw error;
}
imported += 1;
}
return { acceptedEntries, importedCount: imported };
}
export function clearOwnerSurfaceState(store: AgentStore, ownerId: string, nowMs: () => number): {
invalidatedBindingIds: string[];
} {
const now = nowMs();
const sessionRows = store.allRows("SELECT session_id FROM sessions WHERE owner_id = ?", [ownerId]);
const sessionIds = sessionRows.map((row) => String(row.session_id));
if (sessionIds.length === 0) {
return { invalidatedBindingIds: [] };
}
const placeholders = sessionIds.map(() => "?").join(", ");
const bindingRows = store.allRows(
`SELECT binding_id FROM adapter_bindings
WHERE session_id IN (${placeholders}) AND status = 'active'`,
sessionIds,
);
const invalidatedBindingIds = bindingRows.map((row) => String(row.binding_id));
if (invalidatedBindingIds.length > 0) {
store.execute(
`UPDATE adapter_bindings
SET status = 'invalid', invalidated_at_ms = ?, updated_at_ms = ?
WHERE binding_id IN (${invalidatedBindingIds.map(() => "?").join(", ")})`,
[now, now, ...invalidatedBindingIds],
);
}
return { invalidatedBindingIds };
}