-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathopenviking-memory.ts
More file actions
1878 lines (1655 loc) · 61.9 KB
/
openviking-memory.ts
File metadata and controls
1878 lines (1655 loc) · 61.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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* OpenViking Memory Plugin for OpenCode
*
* Exposes OpenViking's semantic memory capabilities as tools for AI agents.
* Supports user profiles, preferences, entities, events, cases, and patterns.
*
* Contributed by: littlelory@convolens.net
* GitHub: https://github.com/convolens
* We are building Enterprise AI assistant for consumer brands,with process awareness and memory,
* Serving product development to pre-launch lifecycle
* Copyright 2026 Convolens.
*/
import type { Hooks, PluginInput } from "@opencode-ai/plugin"
import { tool } from "@opencode-ai/plugin"
import * as fs from "fs"
import * as path from "path"
import { fileURLToPath } from "url"
const z = tool.schema
const pluginFilePath = fileURLToPath(import.meta.url)
const pluginFileDir = path.dirname(pluginFilePath)
// ============================================================================
// Session State Management
// ============================================================================
interface SessionMapping {
ovSessionId: string
createdAt: number
capturedMessages: Set<string> // Track captured message IDs to avoid duplicates
messageRoles: Map<string, "user" | "assistant"> // Track message ID → role mapping
pendingMessages: Map<string, string> // Track message ID → content for messages waiting for completion
sendingMessages: Set<string> // Track message IDs currently being sent to avoid duplicate writes
lastCommitTime?: number
commitInFlight?: boolean
commitTaskId?: string
commitStartedAt?: number
pendingCleanup?: boolean
}
// Persisted format for session mapping (for disk storage)
interface SessionMappingPersisted {
ovSessionId: string
createdAt: number
capturedMessages: string[] // Set → Array
messageRoles: [string, "user" | "assistant"][] // Map → Array of tuples
pendingMessages: [string, string][] // Map → Array of tuples
lastCommitTime?: number
commitInFlight?: boolean
commitTaskId?: string
commitStartedAt?: number
pendingCleanup?: boolean
}
// Session map file format
interface SessionMapFile {
version: 1
sessions: Record<string, SessionMappingPersisted> // opencodeSessionId → mapping
lastSaved: number // timestamp
}
// Map: OpenCode session ID → OpenViking session ID
const sessionMap = new Map<string, SessionMapping>()
// Buffer for messages that arrive before session mapping is established
interface BufferedMessage {
messageId: string
content?: string
role?: "user" | "assistant"
timestamp: number
}
const sessionMessageBuffer = new Map<string, BufferedMessage[]>() // sessionId → messages
const MAX_BUFFERED_MESSAGES_PER_SESSION = 100
const BUFFERED_MESSAGE_TTL_MS = 15 * 60 * 1000
const BUFFER_CLEANUP_INTERVAL_MS = 30 * 1000
let lastBufferCleanupAt = 0
// ============================================================================
// Logging
// ============================================================================
let logFilePath: string | null = null
let pluginDataDir: string | null = null
function ensurePluginDataDir(): string | null {
const pluginDir = pluginFileDir
try {
fs.mkdirSync(pluginDir, { recursive: true })
return pluginDir
} catch (error) {
console.error("Failed to ensure plugin directory:", error)
return null
}
}
function initLogger() {
const pluginDir = ensurePluginDataDir()
if (!pluginDir) return
pluginDataDir = pluginDir
logFilePath = path.join(pluginDir, "openviking-memory.log")
}
function safeStringify(obj: any): any {
if (obj === null || obj === undefined) return obj
if (typeof obj !== "object") return obj
// Handle arrays
if (Array.isArray(obj)) {
return obj.map((item) => safeStringify(item))
}
// Handle objects
const result: any = {}
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const value = obj[key]
if (typeof value === "function") {
result[key] = "[Function]"
} else if (typeof value === "object" && value !== null) {
try {
result[key] = safeStringify(value)
} catch {
result[key] = "[Circular or Non-serializable]"
}
} else {
result[key] = value
}
}
}
return result
}
function log(level: "INFO" | "ERROR" | "DEBUG", toolName: string, message: string, data?: any) {
if (!logFilePath) return
const timestamp = new Date().toISOString()
const logEntry = {
timestamp,
level,
tool: toolName,
message,
...(data && { data: safeStringify(data) }),
}
try {
const logLine = JSON.stringify(logEntry) + "\n"
fs.appendFileSync(logFilePath, logLine, "utf-8")
} catch (error) {
console.error("Failed to write to log file:", error)
}
}
// ============================================================================
// Session Map Persistence
// ============================================================================
let sessionMapPath: string | null = null
function initSessionMapPath() {
const pluginDir = pluginDataDir ?? ensurePluginDataDir()
if (!pluginDir) return
pluginDataDir = pluginDir
sessionMapPath = path.join(pluginDir, "openviking-session-map.json")
}
function serializeSessionMapping(mapping: SessionMapping): SessionMappingPersisted {
return {
ovSessionId: mapping.ovSessionId,
createdAt: mapping.createdAt,
capturedMessages: Array.from(mapping.capturedMessages),
messageRoles: Array.from(mapping.messageRoles.entries()),
pendingMessages: Array.from(mapping.pendingMessages.entries()),
lastCommitTime: mapping.lastCommitTime,
commitInFlight: mapping.commitInFlight,
commitTaskId: mapping.commitTaskId,
commitStartedAt: mapping.commitStartedAt,
pendingCleanup: mapping.pendingCleanup,
}
}
function deserializeSessionMapping(persisted: SessionMappingPersisted): SessionMapping {
return {
ovSessionId: persisted.ovSessionId,
createdAt: persisted.createdAt,
capturedMessages: new Set(persisted.capturedMessages),
messageRoles: new Map(persisted.messageRoles),
pendingMessages: new Map(persisted.pendingMessages),
sendingMessages: new Set(),
lastCommitTime: persisted.lastCommitTime,
commitInFlight: persisted.commitInFlight,
commitTaskId: persisted.commitTaskId,
commitStartedAt: persisted.commitStartedAt,
pendingCleanup: persisted.pendingCleanup,
}
}
async function loadSessionMap(): Promise<void> {
if (!sessionMapPath) return
try {
if (!fs.existsSync(sessionMapPath)) {
log("INFO", "persistence", "No session map file found, starting fresh")
return
}
const content = await fs.promises.readFile(sessionMapPath, "utf-8")
const data: SessionMapFile = JSON.parse(content)
if (data.version !== 1) {
log("ERROR", "persistence", "Unsupported session map version", { version: data.version })
return
}
for (const [opencodeSessionId, persisted] of Object.entries(data.sessions)) {
sessionMap.set(opencodeSessionId, deserializeSessionMapping(persisted))
}
log("INFO", "persistence", "Session map loaded", {
count: sessionMap.size,
last_saved: new Date(data.lastSaved).toISOString()
})
} catch (error: any) {
log("ERROR", "persistence", "Failed to load session map", { error: error.message })
// Backup corrupted file
if (fs.existsSync(sessionMapPath)) {
const backupPath = `${sessionMapPath}.corrupted.${Date.now()}`
await fs.promises.rename(sessionMapPath, backupPath)
log("INFO", "persistence", "Corrupted file backed up", { backup: backupPath })
}
}
}
async function saveSessionMap(): Promise<void> {
if (!sessionMapPath) return
try {
const sessions: Record<string, SessionMappingPersisted> = {}
for (const [opencodeSessionId, mapping] of sessionMap.entries()) {
sessions[opencodeSessionId] = serializeSessionMapping(mapping)
}
const data: SessionMapFile = {
version: 1,
sessions,
lastSaved: Date.now()
}
// Atomic write: temp file + rename
const tempPath = sessionMapPath + '.tmp'
await fs.promises.writeFile(tempPath, JSON.stringify(data, null, 2), "utf-8")
await fs.promises.rename(tempPath, sessionMapPath)
log("DEBUG", "persistence", "Session map saved", { count: sessionMap.size })
} catch (error: any) {
log("ERROR", "persistence", "Failed to save session map", { error: error.message })
}
}
// Debounced save to reduce disk I/O
let saveTimer: NodeJS.Timeout | null = null
function debouncedSaveSessionMap(): void {
if (saveTimer) clearTimeout(saveTimer)
saveTimer = setTimeout(() => {
saveSessionMap().catch(error => {
log("ERROR", "persistence", "Debounced save failed", { error: error.message })
})
}, 300)
}
// ============================================================================
// Configuration
// ============================================================================
interface OpenVikingConfig {
endpoint: string
apiKey: string
enabled: boolean
timeoutMs: number
autoCommit?: {
enabled: boolean
intervalMinutes: number
}
}
// ============================================================================
// API Response Types
// ============================================================================
interface OpenVikingResponse<T = unknown> {
status: string
result?: T
error?: string | { code?: string; message?: string; details?: Record<string, unknown> }
time?: number
usage?: Record<string, number>
}
interface SearchResult {
memories: any[]
resources: any[]
skills: any[]
total: number
query_plan?: string
}
interface CommitResult {
session_id: string
status: string
memories_extracted: number
active_count_updated: number
archived: boolean
task_id?: string
message?: string
stats?: {
total_turns?: number
contexts_used?: number
skills_used?: number
memories_extracted?: number
}
}
interface SessionResult {
session_id: string
}
interface TaskResult {
task_id: string
task_type: string
status: "pending" | "running" | "completed" | "failed"
created_at: number
updated_at: number
resource_id?: string
result?: {
session_id?: string
memories_extracted?: number
archived?: boolean
}
error?: string | null
}
type CommitStartResult =
| { mode: "background"; taskId: string }
| { mode: "completed"; result: CommitResult }
const DEFAULT_CONFIG: OpenVikingConfig = {
endpoint: "http://localhost:1933",
apiKey: "",
enabled: true,
timeoutMs: 30000,
autoCommit: {
enabled: true,
intervalMinutes: 10
}
}
function loadConfig(): OpenVikingConfig {
const configPath = path.join(pluginFileDir, "openviking-config.json")
try {
if (fs.existsSync(configPath)) {
const fileContent = fs.readFileSync(configPath, "utf-8")
const fileConfig = JSON.parse(fileContent)
const config = {
...DEFAULT_CONFIG,
...fileConfig,
autoCommit: fileConfig.autoCommit
? {
...DEFAULT_CONFIG.autoCommit,
...fileConfig.autoCommit,
}
: DEFAULT_CONFIG.autoCommit
? { ...DEFAULT_CONFIG.autoCommit }
: undefined,
}
if (config.autoCommit) {
config.autoCommit.intervalMinutes = getAutoCommitIntervalMinutes(config)
}
// Environment variable takes precedence over config file
if (process.env.OPENVIKING_API_KEY) {
config.apiKey = process.env.OPENVIKING_API_KEY
}
return config
}
} catch (error) {
console.warn(`Failed to load OpenViking config from ${configPath}:`, error)
}
// Check environment variable even if config file doesn't exist
const config = {
...DEFAULT_CONFIG,
autoCommit: DEFAULT_CONFIG.autoCommit
? { ...DEFAULT_CONFIG.autoCommit }
: undefined,
}
if (process.env.OPENVIKING_API_KEY) {
config.apiKey = process.env.OPENVIKING_API_KEY
}
if (config.autoCommit) {
config.autoCommit.intervalMinutes = getAutoCommitIntervalMinutes(config)
}
return config
}
// ============================================================================
// HTTP Client
// ============================================================================
interface HttpRequestOptions {
method: "GET" | "POST" | "PUT" | "DELETE"
endpoint: string
body?: any
timeoutMs?: number
abortSignal?: AbortSignal
}
async function makeRequest<T = any>(config: OpenVikingConfig, options: HttpRequestOptions): Promise<T> {
const url = `${config.endpoint}${options.endpoint}`
const headers: Record<string, string> = {
"Content-Type": "application/json",
}
if (config.apiKey) {
headers["X-API-Key"] = config.apiKey
}
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? config.timeoutMs)
// Chain with tool's abort signal if provided
const signal = options.abortSignal
? AbortSignal.any([options.abortSignal, controller.signal])
: controller.signal
try {
const response = await fetch(url, {
method: options.method,
headers,
body: options.body ? JSON.stringify(options.body) : undefined,
signal,
})
clearTimeout(timeout)
if (!response.ok) {
const errorText = await response.text()
let errorMessage: string
try {
const errorJson = JSON.parse(errorText)
// Handle case where error/message might be objects
const rawError = errorJson.error || errorJson.message
if (typeof rawError === "string") {
errorMessage = rawError
} else if (rawError && typeof rawError === "object") {
errorMessage = JSON.stringify(rawError)
} else {
errorMessage = errorText
}
} catch {
errorMessage = errorText
}
switch (response.status) {
case 401:
case 403:
throw new Error("Authentication failed. Please check API key configuration.")
case 404:
throw new Error(`Resource not found: ${options.endpoint}`)
case 500:
throw new Error(`OpenViking server error: ${errorMessage}`)
default:
throw new Error(`Request failed (${response.status}): ${errorMessage}`)
}
}
return (await response.json()) as T
} catch (error: any) {
clearTimeout(timeout)
if (error.name === "AbortError") {
throw new Error(`Request timeout after ${options.timeoutMs ?? config.timeoutMs}ms`)
}
if (error.message?.includes("fetch failed") || error.code === "ECONNREFUSED") {
throw new Error(
`OpenViking service unavailable at ${config.endpoint}. Please check if the service is running (try: openviking-server).`,
)
}
throw error
}
}
function getResponseErrorMessage(error: OpenVikingResponse["error"]): string {
if (!error) return "Unknown OpenViking error"
if (typeof error === "string") return error
return error.message || error.code || "Unknown OpenViking error"
}
function unwrapResponse<T>(response: OpenVikingResponse<T>): T {
if (!response || typeof response !== "object") {
throw new Error("OpenViking returned an invalid response")
}
if (response.status && response.status !== "ok") {
throw new Error(getResponseErrorMessage(response.error))
}
return response.result as T
}
async function checkServiceHealth(config: OpenVikingConfig): Promise<boolean> {
try {
const response = await fetch(`${config.endpoint}/health`, {
method: "GET",
signal: AbortSignal.timeout(3000),
})
return response.ok
} catch (error: any) {
log("ERROR", "health", "OpenViking health check failed", {
endpoint: config.endpoint,
error: error.message,
})
return false
}
}
// ============================================================================
// Session Lifecycle Helpers
// ============================================================================
function mergeMessageContent(existing: string | undefined, incoming: string): string {
const next = incoming.trim()
if (!next) return existing ?? ""
if (!existing) return next
if (next === existing) return existing
if (next.startsWith(existing)) return next
if (existing.startsWith(next)) return existing
if (next.includes(existing)) return next
if (existing.includes(next)) return existing
return `${existing}\n${next}`.trim()
}
function upsertBufferedMessage(
sessionId: string,
messageId: string,
updates: Partial<Pick<BufferedMessage, "role" | "content">>,
): void {
const now = Date.now()
if (now - lastBufferCleanupAt >= BUFFER_CLEANUP_INTERVAL_MS) {
for (const [bufferedSessionId, bufferedMessages] of sessionMessageBuffer.entries()) {
const freshMessages = bufferedMessages.filter((message) => now - message.timestamp <= BUFFERED_MESSAGE_TTL_MS)
if (freshMessages.length === 0) {
sessionMessageBuffer.delete(bufferedSessionId)
continue
}
if (freshMessages.length !== bufferedMessages.length) {
sessionMessageBuffer.set(bufferedSessionId, freshMessages)
}
}
lastBufferCleanupAt = now
}
const existingBuffer = sessionMessageBuffer.get(sessionId) ?? []
const freshBuffer = existingBuffer.filter((message) => now - message.timestamp <= BUFFERED_MESSAGE_TTL_MS)
let buffered = freshBuffer.find((message) => message.messageId === messageId)
if (!buffered) {
while (freshBuffer.length >= MAX_BUFFERED_MESSAGES_PER_SESSION) {
freshBuffer.shift()
}
buffered = { messageId, timestamp: now }
freshBuffer.push(buffered)
} else {
buffered.timestamp = now
}
if (updates.role) {
buffered.role = updates.role
}
if (updates.content) {
buffered.content = mergeMessageContent(buffered.content, updates.content)
}
sessionMessageBuffer.set(sessionId, freshBuffer)
}
function getAutoCommitIntervalMinutes(config: OpenVikingConfig): number {
const configured = Number(config.autoCommit?.intervalMinutes ?? DEFAULT_CONFIG.autoCommit?.intervalMinutes ?? 10)
if (!Number.isFinite(configured)) {
return DEFAULT_CONFIG.autoCommit?.intervalMinutes ?? 10
}
return Math.max(1, configured)
}
function resolveEventSessionId(event: any): string | undefined {
return event?.properties?.info?.id
?? event?.properties?.sessionID
?? event?.properties?.sessionId
}
/**
* Create or connect to OpenViking session for an OpenCode session
*/
async function ensureOpenVikingSession(
opencodeSessionId: string,
config: OpenVikingConfig,
): Promise<string | null> {
const existingMapping = sessionMap.get(opencodeSessionId)
const knownSessionId = existingMapping?.ovSessionId
if (knownSessionId) {
try {
const response = await makeRequest<OpenVikingResponse<SessionResult>>(config, {
method: "GET",
endpoint: `/api/v1/sessions/${knownSessionId}`,
timeoutMs: 5000,
})
const result = unwrapResponse(response)
if (result) {
log("INFO", "session", "Reconnected to persisted OpenViking session", {
opencode_session: opencodeSessionId,
openviking_session: knownSessionId,
})
return knownSessionId
}
} catch (error: any) {
log("INFO", "session", "Persisted OpenViking session unavailable, creating a new one", {
opencode_session: opencodeSessionId,
openviking_session: knownSessionId,
error: error.message,
})
}
}
try {
const createResponse = await makeRequest<OpenVikingResponse<SessionResult>>(config, {
method: "POST",
endpoint: "/api/v1/sessions",
body: {},
timeoutMs: 5000,
})
const sessionId = unwrapResponse(createResponse)?.session_id
if (!sessionId) {
throw new Error("OpenViking did not return a session_id")
}
log("INFO", "session", "Created new OpenViking session", {
opencode_session: opencodeSessionId,
openviking_session: sessionId,
})
return sessionId
} catch (error: any) {
log("ERROR", "session", "Failed to create OpenViking session", {
opencode_session: opencodeSessionId,
error: error.message,
})
return null
}
}
async function sleep(ms: number, abortSignal?: AbortSignal): Promise<void> {
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
abortSignal?.removeEventListener("abort", onAbort)
resolve()
}, ms)
function onAbort() {
clearTimeout(timer)
reject(new Error("Operation aborted"))
}
abortSignal?.addEventListener("abort", onAbort, { once: true })
})
}
async function findRunningCommitTaskId(
ovSessionId: string,
config: OpenVikingConfig,
): Promise<string | undefined> {
try {
const response = await makeRequest<OpenVikingResponse<TaskResult[]>>(config, {
method: "GET",
endpoint: `/api/v1/tasks?task_type=session_commit&resource_id=${encodeURIComponent(ovSessionId)}&limit=10`,
timeoutMs: 5000,
})
const tasks = unwrapResponse(response) ?? []
const runningTask = tasks.find((task) => task.status === "pending" || task.status === "running")
return runningTask?.task_id
} catch (error: any) {
log("ERROR", "session", "Failed to query running commit tasks", {
openviking_session: ovSessionId,
error: error.message,
})
return undefined
}
}
function clearCommitState(mapping: SessionMapping): void {
mapping.commitInFlight = false
mapping.commitTaskId = undefined
mapping.commitStartedAt = undefined
}
let backgroundCommitSupported: boolean | null = null
const COMMIT_TIMEOUT_MS = 180000
async function detectBackgroundCommitSupport(config: OpenVikingConfig): Promise<boolean> {
if (backgroundCommitSupported !== null) {
return backgroundCommitSupported
}
const headers: Record<string, string> = {}
if (config.apiKey) {
headers["X-API-Key"] = config.apiKey
}
try {
const response = await fetch(`${config.endpoint}/api/v1/tasks?limit=1`, {
method: "GET",
headers,
signal: AbortSignal.timeout(3000),
})
backgroundCommitSupported = response.ok
} catch {
backgroundCommitSupported = false
}
log(
"INFO",
"session",
backgroundCommitSupported
? "Detected background commit API support"
: "Detected legacy synchronous commit API",
{ endpoint: config.endpoint },
)
return backgroundCommitSupported
}
async function finalizeCommitSuccess(
mapping: SessionMapping,
opencodeSessionId: string,
config: OpenVikingConfig,
): Promise<void> {
mapping.lastCommitTime = Date.now()
mapping.capturedMessages.clear()
clearCommitState(mapping)
debouncedSaveSessionMap()
await flushPendingMessages(opencodeSessionId, mapping, config)
if (mapping.pendingCleanup) {
sessionMap.delete(opencodeSessionId)
sessionMessageBuffer.delete(opencodeSessionId)
await saveSessionMap()
log("INFO", "session", "Cleaned up session mapping after commit completion", {
openviking_session: mapping.ovSessionId,
opencode_session: opencodeSessionId,
})
}
}
async function runSynchronousCommit(
mapping: SessionMapping,
opencodeSessionId: string,
config: OpenVikingConfig,
abortSignal?: AbortSignal,
): Promise<CommitResult> {
mapping.commitInFlight = true
mapping.commitTaskId = undefined
mapping.commitStartedAt = Date.now()
debouncedSaveSessionMap()
try {
const response = await makeRequest<OpenVikingResponse<CommitResult>>(config, {
method: "POST",
endpoint: `/api/v1/sessions/${mapping.ovSessionId}/commit`,
timeoutMs: Math.max(config.timeoutMs, COMMIT_TIMEOUT_MS),
abortSignal,
})
const result = unwrapResponse(response)
log("INFO", "session", "OpenViking synchronous commit completed", {
openviking_session: mapping.ovSessionId,
opencode_session: opencodeSessionId,
memories_extracted: result?.memories_extracted ?? 0,
archived: result?.archived ?? false,
})
await finalizeCommitSuccess(mapping, opencodeSessionId, config)
return result
} catch (error: any) {
clearCommitState(mapping)
debouncedSaveSessionMap()
throw error
}
}
async function flushPendingMessages(
opencodeSessionId: string,
mapping: SessionMapping,
config: OpenVikingConfig,
): Promise<void> {
if (mapping.commitInFlight) {
return
}
for (const messageId of Array.from(mapping.pendingMessages.keys())) {
if (mapping.capturedMessages.has(messageId) || mapping.sendingMessages.has(messageId)) {
continue
}
const role = mapping.messageRoles.get(messageId)
const content = mapping.pendingMessages.get(messageId)
if (!role || !content || !content.trim()) {
continue
}
mapping.sendingMessages.add(messageId)
try {
log("DEBUG", "message", "Committing pending message content", {
session_id: opencodeSessionId,
message_id: messageId,
role,
content_length: content.length,
})
const success = await addMessageToSession(
mapping.ovSessionId,
role,
content,
config
)
if (success) {
const latestContent = mapping.pendingMessages.get(messageId)
if (latestContent && latestContent !== content) {
log("DEBUG", "message", "Message changed during send; keeping latest content pending", {
session_id: opencodeSessionId,
message_id: messageId,
role,
previous_length: content.length,
latest_length: latestContent.length,
})
} else {
mapping.capturedMessages.add(messageId)
mapping.pendingMessages.delete(messageId)
debouncedSaveSessionMap()
log("INFO", "message", `${role} message captured successfully`, {
session_id: opencodeSessionId,
message_id: messageId,
role,
})
}
}
} finally {
mapping.sendingMessages.delete(messageId)
}
}
}
async function startBackgroundCommit(
mapping: SessionMapping,
opencodeSessionId: string,
config: OpenVikingConfig,
abortSignal?: AbortSignal,
): Promise<CommitStartResult | null> {
if (mapping.commitInFlight && mapping.commitTaskId) {
return { mode: "background", taskId: mapping.commitTaskId }
}
const supportsBackgroundCommit = await detectBackgroundCommitSupport(config)
if (!supportsBackgroundCommit) {
try {
const result = await runSynchronousCommit(mapping, opencodeSessionId, config, abortSignal)
return { mode: "completed", result }
} catch (error: any) {
log("ERROR", "session", "Failed to run synchronous commit", {
openviking_session: mapping.ovSessionId,
opencode_session: opencodeSessionId,
error: error.message,
})
return null
}
}
try {
const response = await makeRequest<OpenVikingResponse<CommitResult>>(config, {
method: "POST",
endpoint: `/api/v1/sessions/${mapping.ovSessionId}/commit?wait=false`,
timeoutMs: 5000,
abortSignal,
})
const data = unwrapResponse(response)
const taskId = data?.task_id
if (!taskId) {
throw new Error("OpenViking did not return a background task id")
}
mapping.commitInFlight = true
mapping.commitTaskId = taskId
mapping.commitStartedAt = Date.now()
debouncedSaveSessionMap()
log("INFO", "session", "OpenViking background commit accepted", {
openviking_session: mapping.ovSessionId,
opencode_session: opencodeSessionId,
task_id: taskId,
})
return { mode: "background", taskId }
} catch (error: any) {
if (error.message?.includes("already has a commit in progress")) {
const taskId = await findRunningCommitTaskId(mapping.ovSessionId, config)
if (taskId) {
mapping.commitInFlight = true
mapping.commitTaskId = taskId
mapping.commitStartedAt = mapping.commitStartedAt ?? Date.now()
debouncedSaveSessionMap()
log("INFO", "session", "Recovered existing background commit task", {
openviking_session: mapping.ovSessionId,
opencode_session: opencodeSessionId,
task_id: taskId,
})
return { mode: "background", taskId }
}
}
if (
error.message?.includes("Request timeout") ||
error.message?.includes("background task id")
) {
backgroundCommitSupported = false
try {
const result = await runSynchronousCommit(mapping, opencodeSessionId, config, abortSignal)
return { mode: "completed", result }
} catch (fallbackError: any) {
log("ERROR", "session", "Failed to fall back to synchronous commit", {
openviking_session: mapping.ovSessionId,
opencode_session: opencodeSessionId,
error: fallbackError.message,
})
}
}
log("ERROR", "session", "Failed to start OpenViking background commit", {
openviking_session: mapping.ovSessionId,
opencode_session: opencodeSessionId,
error: error.message,
})
return null
}
}
async function pollCommitTaskOnce(
mapping: SessionMapping,
opencodeSessionId: string,
config: OpenVikingConfig,
): Promise<TaskResult["status"] | "unknown"> {
if (!mapping.commitInFlight) {
return "unknown"
}
if (!mapping.commitTaskId) {
return "running"
}
try {
const response = await makeRequest<OpenVikingResponse<TaskResult>>(config, {
method: "GET",
endpoint: `/api/v1/tasks/${mapping.commitTaskId}`,
timeoutMs: 5000,
})
const task = unwrapResponse(response)
if (task.status === "pending" || task.status === "running") {
return task.status
}
if (task.status === "completed") {
const memoriesExtracted = task.result?.memories_extracted ?? 0
const archived = task.result?.archived ?? false
log("INFO", "session", "OpenViking background commit completed", {
openviking_session: mapping.ovSessionId,
opencode_session: opencodeSessionId,
task_id: task.task_id,
memories_extracted: memoriesExtracted,
archived,
})
await finalizeCommitSuccess(mapping, opencodeSessionId, config)
return task.status
}
log("ERROR", "session", "OpenViking background commit failed", {