forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsurfaceSession.ts
More file actions
463 lines (426 loc) · 14.9 KB
/
Copy pathsurfaceSession.ts
File metadata and controls
463 lines (426 loc) · 14.9 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
// Surface-session resolution — Windows port of the macOS agent runtime's
// surface-session.ts (desktop/macos/agent/src/runtime/surface-session.ts).
//
// Maps a surface reference (surfaceKind + externalRefKind + externalRefId, e.g.
// main_chat/chat/default) to a durable agent session + conversation, creating
// them on first use and recovering deterministically from the partial-unique
// races the store enforces. Also holds the one-time floating_chat -> main_chat
// transcript merge and owner-state teardown.
import { generateAgentId } from './store'
import { executionRoleForSurface, providerBoundaryForAdapter } from './executionPolicy'
import type { AgentExecutionRole, AgentStore, ProviderBoundary } from './types'
export interface SurfaceRef {
surfaceKind: string
externalRefKind: string
externalRefId: string
}
export interface ResolveSurfaceSessionInput {
ownerId: string
surfaceRef: SurfaceRef
defaultAdapterId?: string
executionRole?: AgentExecutionRole
providerBoundary?: ProviderBoundary
title?: string | null
}
export interface ResolveSurfaceSessionResult {
conversationId: string
agentSessionId: string
}
export interface LegacyMainChatSessionEntry {
chatId: string
agentSessionId: string
}
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 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
]
)
}
/**
* The pre-kernel main-chat migration persisted every legacy session as ACP.
* A migrated session that has never created a run or adapter binding has no
* provider-owned execution state yet, so it may safely adopt the active main
* chat route before its first query. Once either exists, the stored provider
* boundary remains immutable and executionPolicy.ts continues to enforce it.
*/
function repairEmptyLegacyMainChatProvider(
store: AgentStore,
input: ResolveSurfaceSessionInput,
resolved: ResolveSurfaceSessionResult,
now: number
): void {
const requestedAdapterId = input.defaultAdapterId?.trim()
if (input.surfaceRef.surfaceKind !== 'main_chat' || !requestedAdapterId) return
const session = store.getOptionalRow(
'SELECT default_adapter_id, provider_boundary FROM sessions WHERE session_id = ?',
[resolved.agentSessionId]
)
if (!session) return
const requestedBoundary = input.providerBoundary ?? providerBoundaryForAdapter(requestedAdapterId)
if (
String(session.default_adapter_id) === requestedAdapterId &&
String(session.provider_boundary) === requestedBoundary
) {
return
}
const hasRun = store.getOptionalRow('SELECT 1 FROM runs WHERE session_id = ? LIMIT 1', [
resolved.agentSessionId
])
const hasBinding = store.getOptionalRow(
'SELECT 1 FROM adapter_bindings WHERE session_id = ? LIMIT 1',
[resolved.agentSessionId]
)
if (hasRun || hasBinding) return
store.execute(
`UPDATE sessions
SET default_adapter_id = ?, provider_boundary = ?, updated_at_ms = ?
WHERE session_id = ?`,
[requestedAdapterId, requestedBoundary, now, resolved.agentSessionId]
)
}
function createSurfaceConversationMapping(
store: AgentStore,
input: ResolveSurfaceSessionInput,
agentSessionId: string,
now: number
): ResolveSurfaceSessionResult {
const 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)
repairEmptyLegacyMainChatProvider(store, input, mapped, now)
return mapped
}
const existingSessionId = readSessionIdByExternalRef(store, input)
if (existingSessionId) {
const resolved = createSurfaceConversationMapping(store, input, existingSessionId, now)
repairEmptyLegacyMainChatProvider(store, input, resolved, 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',
// Derive the role from the surface when the caller does not pin one, for
// the same reason KernelCore.resolveSession does: an unset role must never
// fall back to 'coordinator' on a leaf surface. This is the OTHER door into
// session creation — kernel.resolveSurfaceSession() and
// getVoiceSeedContextForSurface() reach the store through here without
// going through KernelCore.resolveSession, so the guard has to live at both.
executionRole: input.executionRole ?? executionRoleForSurface(input.surfaceRef),
providerBoundary: input.providerBoundary
})
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',
// Same guard: never let an adopted session default to 'coordinator' on a
// leaf surface just because this path did not name a role.
executionRole: executionRoleForSurface(input.surfaceRef)
}).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
): number {
const now = nowMs()
let imported = 0
for (const entry of input.entries) {
const chatId = entry.chatId.trim()
const agentSessionId = entry.agentSessionId.trim()
if (!chatId || !agentSessionId) continue
const surfaceRef: SurfaceRef = {
surfaceKind: 'main_chat',
externalRefKind: 'chat',
externalRefId: 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: 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 imported
}
export interface MergeFloatingChatIntoMainChatResult {
mergedTurns: number
removedFloatingMapping: boolean
}
/** One-time migration: fold legacy floating_chat transcript into main_chat. */
export function mergeFloatingChatIntoMainChat(
store: AgentStore,
input: { ownerId: string; chatId?: string },
nowMs: () => number
): MergeFloatingChatIntoMainChatResult {
const chatId = input.chatId?.trim() || 'default'
const floatingRef: SurfaceRef = {
surfaceKind: 'floating_chat',
externalRefKind: 'chat',
externalRefId: chatId
}
const mainRef: SurfaceRef = {
surfaceKind: 'main_chat',
externalRefKind: 'chat',
externalRefId: chatId
}
const floatingRow = store.getOptionalRow(
`SELECT conversation_id FROM surface_conversations
WHERE owner_id = ? AND surface_kind = ? AND external_ref_kind = ? AND external_ref_id = ?`,
[input.ownerId, floatingRef.surfaceKind, floatingRef.externalRefKind, floatingRef.externalRefId]
)
if (!floatingRow) {
return { mergedTurns: 0, removedFloatingMapping: false }
}
const floatingConversationId = String(floatingRow.conversation_id)
const mainResolved = resolveSurfaceSession(
store,
{ ownerId: input.ownerId, surfaceRef: mainRef },
nowMs
)
const mainConversationId = mainResolved.conversationId
if (floatingConversationId === mainConversationId) {
store.execute(
`DELETE FROM surface_conversations
WHERE owner_id = ? AND surface_kind = ? AND external_ref_kind = ? AND external_ref_id = ?`,
[
input.ownerId,
floatingRef.surfaceKind,
floatingRef.externalRefKind,
floatingRef.externalRefId
]
)
return { mergedTurns: 0, removedFloatingMapping: true }
}
const turns = store.allRows(
`SELECT role, content, created_at_ms, metadata_json
FROM conversation_turns
WHERE conversation_id = ?
ORDER BY created_at_ms ASC`,
[floatingConversationId]
)
let mergedTurns = 0
store.withTransaction(() => {
for (const row of turns) {
store.insertConversationTurn({
conversationId: mainConversationId,
turnId: generateAgentId('turn'),
role: String(row.role) as 'user' | 'assistant',
surfaceKind: 'main_chat',
content: String(row.content),
createdAtMs: Number(row.created_at_ms),
metadataJson: String(row.metadata_json ?? '{}')
})
mergedTurns += 1
}
store.execute(`DELETE FROM conversation_turns WHERE conversation_id = ?`, [
floatingConversationId
])
store.execute(
`DELETE FROM surface_conversations
WHERE owner_id = ? AND surface_kind = ? AND external_ref_kind = ? AND external_ref_id = ?`,
[
input.ownerId,
floatingRef.surfaceKind,
floatingRef.externalRefKind,
floatingRef.externalRefId
]
)
})
return { mergedTurns, removedFloatingMapping: true }
}
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 }
}