-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathcapture.js
More file actions
executable file
·2172 lines (2124 loc) · 75.9 KB
/
Copy pathcapture.js
File metadata and controls
executable file
·2172 lines (2124 loc) · 75.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
#!/usr/bin/env node
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// dist/src/index-marker-store.js
var index_marker_store_exports = {};
__export(index_marker_store_exports, {
buildIndexMarkerPath: () => buildIndexMarkerPath,
getIndexMarkerDir: () => getIndexMarkerDir,
hasFreshIndexMarker: () => hasFreshIndexMarker,
writeIndexMarker: () => writeIndexMarker
});
import { existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
import { join as join5 } from "node:path";
import { tmpdir } from "node:os";
function getIndexMarkerDir() {
return process.env.HIVEMIND_INDEX_MARKER_DIR ?? join5(tmpdir(), "hivemind-deeplake-indexes");
}
function buildIndexMarkerPath(workspaceId, orgId, table, suffix) {
const markerKey = [workspaceId, orgId, table, suffix].join("__").replace(/[^a-zA-Z0-9_.-]/g, "_");
return join5(getIndexMarkerDir(), `${markerKey}.json`);
}
function hasFreshIndexMarker(markerPath) {
if (!existsSync2(markerPath))
return false;
try {
const raw = JSON.parse(readFileSync4(markerPath, "utf-8"));
const updatedAt = raw.updatedAt ? new Date(raw.updatedAt).getTime() : NaN;
if (!Number.isFinite(updatedAt) || Date.now() - updatedAt > INDEX_MARKER_TTL_MS)
return false;
return true;
} catch {
return false;
}
}
function writeIndexMarker(markerPath) {
mkdirSync3(getIndexMarkerDir(), { recursive: true });
writeFileSync3(markerPath, JSON.stringify({ updatedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
}
var INDEX_MARKER_TTL_MS;
var init_index_marker_store = __esm({
"dist/src/index-marker-store.js"() {
"use strict";
INDEX_MARKER_TTL_MS = Number(process.env.HIVEMIND_INDEX_MARKER_TTL_MS ?? 6 * 60 * 6e4);
}
});
// dist/src/utils/stdin.js
function readStdin() {
return new Promise((resolve2, reject) => {
let data = "";
process.stdin.setEncoding("utf-8");
process.stdin.on("data", (chunk) => data += chunk);
process.stdin.on("end", () => {
try {
resolve2(JSON.parse(data));
} catch (err) {
reject(new Error(`Failed to parse hook input: ${err}`));
}
});
process.stdin.on("error", reject);
});
}
// dist/src/config.js
import { readFileSync, existsSync } from "node:fs";
import { join } from "node:path";
import { homedir, userInfo } from "node:os";
function loadConfig() {
const home = homedir();
const credPath = join(home, ".deeplake", "credentials.json");
let creds = null;
if (existsSync(credPath)) {
try {
creds = JSON.parse(readFileSync(credPath, "utf-8"));
} catch {
return null;
}
}
const token = process.env.HIVEMIND_TOKEN ?? creds?.token;
const orgId = process.env.HIVEMIND_ORG_ID ?? creds?.orgId;
if (!token || !orgId)
return null;
return {
token,
orgId,
orgName: creds?.orgName ?? orgId,
userName: creds?.userName || userInfo().username || "unknown",
workspaceId: process.env.HIVEMIND_WORKSPACE_ID ?? creds?.workspaceId ?? "default",
apiUrl: process.env.HIVEMIND_API_URL ?? creds?.apiUrl ?? "https://api.deeplake.ai",
tableName: process.env.HIVEMIND_TABLE ?? "memory",
sessionsTableName: process.env.HIVEMIND_SESSIONS_TABLE ?? "sessions",
skillsTableName: process.env.HIVEMIND_SKILLS_TABLE ?? "skills",
memoryPath: process.env.HIVEMIND_MEMORY_PATH ?? join(home, ".deeplake", "memory")
};
}
// dist/src/deeplake-api.js
import { randomUUID } from "node:crypto";
// dist/src/utils/debug.js
import { appendFileSync } from "node:fs";
import { join as join2 } from "node:path";
import { homedir as homedir2 } from "node:os";
var LOG = join2(homedir2(), ".deeplake", "hook-debug.log");
function isDebug() {
return process.env.HIVEMIND_DEBUG === "1";
}
function utcTimestamp(d = /* @__PURE__ */ new Date()) {
return d.toISOString().replace("T", " ").slice(0, 19) + " UTC";
}
function log(tag, msg) {
if (!isDebug())
return;
appendFileSync(LOG, `${(/* @__PURE__ */ new Date()).toISOString()} [${tag}] ${msg}
`);
}
// dist/src/utils/sql.js
function sqlStr(value) {
return value.replace(/\\/g, "\\\\").replace(/'/g, "''").replace(/\0/g, "").replace(/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
}
function sqlIdent(name) {
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
throw new Error(`Invalid SQL identifier: ${JSON.stringify(name)}`);
}
return name;
}
// dist/src/embeddings/columns.js
var SUMMARY_EMBEDDING_COL = "summary_embedding";
var MESSAGE_EMBEDDING_COL = "message_embedding";
// dist/src/utils/client-header.js
var DEEPLAKE_CLIENT_HEADER = "X-Deeplake-Client";
function deeplakeClientValue() {
return "hivemind";
}
function deeplakeClientHeader() {
return { [DEEPLAKE_CLIENT_HEADER]: deeplakeClientValue() };
}
// dist/src/notifications/queue.js
import { readFileSync as readFileSync2, writeFileSync, renameSync, mkdirSync, openSync, closeSync, unlinkSync, statSync } from "node:fs";
import { join as join3, resolve } from "node:path";
import { homedir as homedir3 } from "node:os";
import { setTimeout as sleep } from "node:timers/promises";
var log2 = (msg) => log("notifications-queue", msg);
var LOCK_RETRY_MAX = 50;
var LOCK_RETRY_BASE_MS = 5;
var LOCK_STALE_MS = 5e3;
function queuePath() {
return join3(homedir3(), ".deeplake", "notifications-queue.json");
}
function lockPath() {
return `${queuePath()}.lock`;
}
function readQueue() {
try {
const raw = readFileSync2(queuePath(), "utf-8");
const parsed = JSON.parse(raw);
if (!parsed || !Array.isArray(parsed.queue)) {
log2(`queue malformed \u2192 treating as empty`);
return { queue: [] };
}
return { queue: parsed.queue };
} catch {
return { queue: [] };
}
}
function _isQueuePathInsideHome(path, home) {
const r = resolve(path);
const h = resolve(home);
return r.startsWith(h + "/") || r === h;
}
function writeQueue(q) {
const path = queuePath();
const home = resolve(homedir3());
if (!_isQueuePathInsideHome(path, home)) {
throw new Error(`notifications-queue write blocked: ${path} is outside ${home}`);
}
mkdirSync(join3(home, ".deeplake"), { recursive: true, mode: 448 });
const tmp = `${path}.${process.pid}.tmp`;
writeFileSync(tmp, JSON.stringify(q, null, 2), { mode: 384 });
renameSync(tmp, path);
}
async function withQueueLock(fn) {
const path = lockPath();
mkdirSync(join3(homedir3(), ".deeplake"), { recursive: true, mode: 448 });
let fd = null;
for (let attempt = 0; attempt < LOCK_RETRY_MAX; attempt++) {
try {
fd = openSync(path, "wx", 384);
break;
} catch (e) {
const code = e.code;
if (code !== "EEXIST")
throw e;
try {
const age = Date.now() - statSync(path).mtimeMs;
if (age > LOCK_STALE_MS) {
unlinkSync(path);
continue;
}
} catch {
}
const delay = LOCK_RETRY_BASE_MS * (attempt + 1);
await sleep(delay);
}
}
if (fd === null) {
log2(`lock acquisition gave up after ${LOCK_RETRY_MAX} attempts \u2014 proceeding unlocked (last-writer-wins)`);
return fn();
}
try {
return fn();
} finally {
try {
closeSync(fd);
} catch {
}
try {
unlinkSync(path);
} catch {
}
}
}
function sameDedupKey(a, b) {
if (a.id !== b.id)
return false;
return JSON.stringify(a.dedupKey) === JSON.stringify(b.dedupKey);
}
async function enqueueNotification(n) {
await withQueueLock(() => {
const q = readQueue();
if (q.queue.some((existing) => sameDedupKey(existing, n))) {
return;
}
q.queue.push(n);
writeQueue(q);
});
}
// dist/src/commands/auth-creds.js
import { readFileSync as readFileSync3, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2 } from "node:fs";
import { join as join4 } from "node:path";
import { homedir as homedir4 } from "node:os";
function configDir() {
return join4(homedir4(), ".deeplake");
}
function credsPath() {
return join4(configDir(), "credentials.json");
}
function loadCredentials() {
try {
return JSON.parse(readFileSync3(credsPath(), "utf-8"));
} catch {
return null;
}
}
// dist/src/deeplake-api.js
var indexMarkerStorePromise = null;
function getIndexMarkerStore() {
if (!indexMarkerStorePromise)
indexMarkerStorePromise = Promise.resolve().then(() => (init_index_marker_store(), index_marker_store_exports));
return indexMarkerStorePromise;
}
var log3 = (msg) => log("sdk", msg);
function summarizeSql(sql, maxLen = 220) {
const compact = sql.replace(/\s+/g, " ").trim();
return compact.length > maxLen ? `${compact.slice(0, maxLen)}...` : compact;
}
function traceSql(msg) {
const traceEnabled = process.env.HIVEMIND_TRACE_SQL === "1" || process.env.HIVEMIND_DEBUG === "1";
if (!traceEnabled)
return;
process.stderr.write(`[deeplake-sql] ${msg}
`);
if (process.env.HIVEMIND_DEBUG === "1")
log3(msg);
}
var _signalledBalanceExhausted = false;
function maybeSignalBalanceExhausted(status, bodyText) {
if (status !== 402)
return;
if (!bodyText.includes("balance_cents"))
return;
if (_signalledBalanceExhausted)
return;
_signalledBalanceExhausted = true;
log3(`balance exhausted \u2014 enqueuing session-start banner (body=${bodyText.slice(0, 120)})`);
enqueueNotification({
id: "balance-exhausted",
severity: "warn",
transient: true,
title: "Hivemind credits exhausted \u2014 top up to keep capturing",
body: `Sessions are not being saved and memory recall is returning empty. Top up at ${billingUrl()} to restore capture and recall.`,
dedupKey: { reason: "balance-zero" }
}).catch((e) => {
log3(`enqueue balance-exhausted failed: ${e instanceof Error ? e.message : String(e)}`);
});
}
function billingUrl() {
try {
const c = loadCredentials();
if (c?.orgName && c?.workspaceId) {
return `https://deeplake.ai/${encodeURIComponent(c.orgName)}/workspace/${encodeURIComponent(c.workspaceId)}/billing`;
}
} catch {
}
return "https://deeplake.ai";
}
var RETRYABLE_CODES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
var MAX_RETRIES = 3;
var BASE_DELAY_MS = 500;
var MAX_CONCURRENCY = 5;
function getQueryTimeoutMs() {
return Number(process.env.HIVEMIND_QUERY_TIMEOUT_MS ?? 1e4);
}
function sleep2(ms) {
return new Promise((resolve2) => setTimeout(resolve2, ms));
}
function isTimeoutError(error) {
const name = error instanceof Error ? error.name.toLowerCase() : "";
const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
return name.includes("timeout") || name === "aborterror" || message.includes("timeout") || message.includes("timed out");
}
function isDuplicateIndexError(error) {
const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
return message.includes("duplicate key value violates unique constraint") || message.includes("pg_class_relname_nsp_index") || message.includes("already exists");
}
function isSessionInsertQuery(sql) {
return /^\s*insert\s+into\s+"[^"]+"\s*\(\s*id\s*,\s*path\s*,\s*filename\s*,\s*message\s*,/i.test(sql);
}
function isTransientHtml403(text) {
const body = text.toLowerCase();
return body.includes("<html") || body.includes("403 forbidden") || body.includes("cloudflare") || body.includes("nginx");
}
var Semaphore = class {
max;
waiting = [];
active = 0;
constructor(max) {
this.max = max;
}
async acquire() {
if (this.active < this.max) {
this.active++;
return;
}
await new Promise((resolve2) => this.waiting.push(resolve2));
}
release() {
this.active--;
const next = this.waiting.shift();
if (next) {
this.active++;
next();
}
}
};
var DeeplakeApi = class {
token;
apiUrl;
orgId;
workspaceId;
tableName;
_pendingRows = [];
_sem = new Semaphore(MAX_CONCURRENCY);
_tablesCache = null;
constructor(token, apiUrl, orgId, workspaceId, tableName) {
this.token = token;
this.apiUrl = apiUrl;
this.orgId = orgId;
this.workspaceId = workspaceId;
this.tableName = tableName;
}
/** Execute SQL with retry on transient errors and bounded concurrency. */
async query(sql) {
const startedAt = Date.now();
const summary = summarizeSql(sql);
traceSql(`query start: ${summary}`);
await this._sem.acquire();
try {
const rows = await this._queryWithRetry(sql);
traceSql(`query ok (${Date.now() - startedAt}ms, rows=${rows.length}): ${summary}`);
return rows;
} catch (e) {
const message = e instanceof Error ? e.message : String(e);
traceSql(`query fail (${Date.now() - startedAt}ms): ${summary} :: ${message}`);
throw e;
} finally {
this._sem.release();
}
}
async _queryWithRetry(sql) {
let lastError;
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
let resp;
const timeoutMs = getQueryTimeoutMs();
try {
const signal = AbortSignal.timeout(timeoutMs);
resp = await fetch(`${this.apiUrl}/workspaces/${this.workspaceId}/tables/query`, {
method: "POST",
headers: {
Authorization: `Bearer ${this.token}`,
"Content-Type": "application/json",
"X-Activeloop-Org-Id": this.orgId,
...deeplakeClientHeader()
},
signal,
body: JSON.stringify({ query: sql })
});
} catch (e) {
if (isTimeoutError(e)) {
lastError = new Error(`Query timeout after ${timeoutMs}ms`);
throw lastError;
}
lastError = e instanceof Error ? e : new Error(String(e));
if (attempt < MAX_RETRIES) {
const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200;
log3(`query retry ${attempt + 1}/${MAX_RETRIES} (fetch error: ${lastError.message}) in ${delay.toFixed(0)}ms`);
await sleep2(delay);
continue;
}
throw lastError;
}
if (resp.ok) {
const raw = await resp.json();
if (!raw?.rows || !raw?.columns)
return [];
return raw.rows.map((row) => Object.fromEntries(raw.columns.map((col, i) => [col, row[i]])));
}
const text = await resp.text().catch(() => "");
const retryable403 = isSessionInsertQuery(sql) && (resp.status === 401 || resp.status === 403 && (text.length === 0 || isTransientHtml403(text)));
const alreadyExists = resp.status === 500 && isDuplicateIndexError(text);
if (!alreadyExists && attempt < MAX_RETRIES && (RETRYABLE_CODES.has(resp.status) || retryable403)) {
const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200;
log3(`query retry ${attempt + 1}/${MAX_RETRIES} (${resp.status}) in ${delay.toFixed(0)}ms`);
await sleep2(delay);
continue;
}
maybeSignalBalanceExhausted(resp.status, text);
throw new Error(`Query failed: ${resp.status}: ${text.slice(0, 200)}`);
}
throw lastError ?? new Error("Query failed: max retries exceeded");
}
// ── Writes ──────────────────────────────────────────────────────────────────
/** Queue rows for writing. Call commit() to flush. */
appendRows(rows) {
this._pendingRows.push(...rows);
}
/** Flush pending rows via SQL. */
async commit() {
if (this._pendingRows.length === 0)
return;
const rows = this._pendingRows;
this._pendingRows = [];
const CONCURRENCY = 10;
for (let i = 0; i < rows.length; i += CONCURRENCY) {
const chunk = rows.slice(i, i + CONCURRENCY);
await Promise.allSettled(chunk.map((r) => this.upsertRowSql(r)));
}
log3(`commit: ${rows.length} rows`);
}
async upsertRowSql(row) {
const ts = (/* @__PURE__ */ new Date()).toISOString();
const cd = row.creationDate ?? ts;
const lud = row.lastUpdateDate ?? ts;
const exists = await this.query(`SELECT path FROM "${this.tableName}" WHERE path = '${sqlStr(row.path)}' LIMIT 1`);
if (exists.length > 0) {
let setClauses = `summary = E'${sqlStr(row.contentText)}', ${SUMMARY_EMBEDDING_COL} = NULL, mime_type = '${sqlStr(row.mimeType)}', size_bytes = ${row.sizeBytes}, last_update_date = '${lud}'`;
if (row.project !== void 0)
setClauses += `, project = '${sqlStr(row.project)}'`;
if (row.description !== void 0)
setClauses += `, description = '${sqlStr(row.description)}'`;
await this.query(`UPDATE "${this.tableName}" SET ${setClauses} WHERE path = '${sqlStr(row.path)}'`);
} else {
const id = randomUUID();
let cols = `id, path, filename, summary, ${SUMMARY_EMBEDDING_COL}, mime_type, size_bytes, creation_date, last_update_date`;
let vals = `'${id}', '${sqlStr(row.path)}', '${sqlStr(row.filename)}', E'${sqlStr(row.contentText)}', NULL, '${sqlStr(row.mimeType)}', ${row.sizeBytes}, '${cd}', '${lud}'`;
if (row.project !== void 0) {
cols += ", project";
vals += `, '${sqlStr(row.project)}'`;
}
if (row.description !== void 0) {
cols += ", description";
vals += `, '${sqlStr(row.description)}'`;
}
await this.query(`INSERT INTO "${this.tableName}" (${cols}) VALUES (${vals})`);
}
}
/** Update specific columns on a row by path. */
async updateColumns(path, columns) {
const setClauses = Object.entries(columns).map(([col, val]) => typeof val === "number" ? `${col} = ${val}` : `${col} = '${sqlStr(String(val))}'`).join(", ");
await this.query(`UPDATE "${this.tableName}" SET ${setClauses} WHERE path = '${sqlStr(path)}'`);
}
// ── Convenience ─────────────────────────────────────────────────────────────
/** Create a BM25 search index on a column. */
async createIndex(column) {
await this.query(`CREATE INDEX IF NOT EXISTS idx_${sqlStr(column)}_bm25 ON "${this.tableName}" USING deeplake_index ("${column}")`);
}
buildLookupIndexName(table, suffix) {
return `idx_${table}_${suffix}`.replace(/[^a-zA-Z0-9_]/g, "_");
}
async ensureLookupIndex(table, suffix, columnsSql) {
const markers = await getIndexMarkerStore();
const markerPath = markers.buildIndexMarkerPath(this.workspaceId, this.orgId, table, suffix);
if (markers.hasFreshIndexMarker(markerPath))
return;
const indexName = this.buildLookupIndexName(table, suffix);
try {
await this.query(`CREATE INDEX IF NOT EXISTS "${indexName}" ON "${table}" ${columnsSql}`);
markers.writeIndexMarker(markerPath);
} catch (e) {
if (isDuplicateIndexError(e)) {
markers.writeIndexMarker(markerPath);
return;
}
log3(`index "${indexName}" skipped: ${e.message}`);
}
}
/**
* Ensure a vector column exists on the given table.
*
* The previous implementation always issued `ALTER TABLE ADD COLUMN IF NOT
* EXISTS …` on every SessionStart. On a long-running workspace that's
* already migrated, every call returns 500 "Column already exists" — noisy
* in the log and a wasted round-trip. Worse, the very first call after the
* column is genuinely added triggers Deeplake's post-ALTER `vector::at`
* window (~30s) during which subsequent INSERTs fail; minimising the
* number of ALTER calls minimises exposure to that window.
*
* New flow:
* 1. Check the local marker file (mirrors ensureLookupIndex). If fresh,
* return — zero network calls.
* 2. SELECT 1 FROM information_schema.columns WHERE table_name = T AND
* column_name = C. Read-only, idempotent, can't tickle the post-ALTER
* bug. If the column is present → mark + return.
* 3. Only if step 2 says the column is missing, fall back to ALTER ADD
* COLUMN IF NOT EXISTS. Mark on success, also mark if Deeplake reports
* "already exists" (race: another client added it between our SELECT
* and ALTER).
*
* Marker uses the same dir / TTL as ensureLookupIndex so both schema
* caches share an opt-out (HIVEMIND_INDEX_MARKER_DIR) and a TTL knob.
*/
async ensureEmbeddingColumn(table, column) {
await this.ensureColumn(table, column, "FLOAT4[]");
}
/**
* Generic marker-gated column migration. Same SELECT-then-ALTER flow as
* ensureEmbeddingColumn, parameterized by SQL type so it can patch up any
* column that was added to the schema after the table was originally
* created. Used today for `summary_embedding`, `message_embedding`, and
* the `agent` column (added 2026-04-11) — the latter has no fallback if
* a user upgraded over a pre-2026-04-11 table, so every INSERT fails
* with `column "agent" does not exist`.
*/
async ensureColumn(table, column, sqlType) {
const markers = await getIndexMarkerStore();
const markerPath = markers.buildIndexMarkerPath(this.workspaceId, this.orgId, table, `col_${column}`);
if (markers.hasFreshIndexMarker(markerPath))
return;
const colCheck = `SELECT 1 FROM information_schema.columns WHERE table_name = '${sqlStr(table)}' AND column_name = '${sqlStr(column)}' AND table_schema = '${sqlStr(this.workspaceId)}' LIMIT 1`;
const rows = await this.query(colCheck);
if (rows.length > 0) {
markers.writeIndexMarker(markerPath);
return;
}
try {
await this.query(`ALTER TABLE "${table}" ADD COLUMN ${column} ${sqlType}`);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
if (!/already exists/i.test(msg))
throw e;
const recheck = await this.query(colCheck);
if (recheck.length === 0)
throw e;
}
markers.writeIndexMarker(markerPath);
}
/** List all tables in the workspace (with retry). */
async listTables(forceRefresh = false) {
if (!forceRefresh && this._tablesCache)
return [...this._tablesCache];
const { tables, cacheable } = await this._fetchTables();
if (cacheable)
this._tablesCache = [...tables];
return tables;
}
async _fetchTables() {
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
try {
const resp = await fetch(`${this.apiUrl}/workspaces/${this.workspaceId}/tables`, {
headers: {
Authorization: `Bearer ${this.token}`,
"X-Activeloop-Org-Id": this.orgId,
...deeplakeClientHeader()
}
});
if (resp.ok) {
const data = await resp.json();
return {
tables: (data.tables ?? []).map((t) => t.table_name),
cacheable: true
};
}
if (attempt < MAX_RETRIES && RETRYABLE_CODES.has(resp.status)) {
await sleep2(BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200);
continue;
}
return { tables: [], cacheable: false };
} catch {
if (attempt < MAX_RETRIES) {
await sleep2(BASE_DELAY_MS * Math.pow(2, attempt));
continue;
}
return { tables: [], cacheable: false };
}
}
return { tables: [], cacheable: false };
}
/**
* Run a `CREATE TABLE` with an extra outer retry budget. The base
* `query()` already retries 3 times on fetch errors (~3.5s total), but a
* failed CREATE is permanent corruption — every subsequent SELECT against
* the missing table fails. Wrapping in an outer loop with longer backoff
* (2s, 5s, then 10s) gives us ~17s of reach across transient network
* blips before giving up. Failures still propagate; getApi() resets its
* cache on init failure (openclaw plugin) so the next call retries the
* whole init flow.
*/
async createTableWithRetry(sql, label) {
const OUTER_BACKOFFS_MS = [2e3, 5e3, 1e4];
let lastErr = null;
for (let attempt = 0; attempt <= OUTER_BACKOFFS_MS.length; attempt++) {
try {
await this.query(sql);
return;
} catch (err) {
lastErr = err;
const msg = err instanceof Error ? err.message : String(err);
log3(`CREATE TABLE "${label}" attempt ${attempt + 1}/${OUTER_BACKOFFS_MS.length + 1} failed: ${msg}`);
if (attempt < OUTER_BACKOFFS_MS.length) {
await sleep2(OUTER_BACKOFFS_MS[attempt]);
}
}
}
throw lastErr;
}
/** Create the memory table if it doesn't already exist. Migrate columns on existing tables. */
async ensureTable(name) {
const tbl = sqlIdent(name ?? this.tableName);
const tables = await this.listTables();
if (!tables.includes(tbl)) {
log3(`table "${tbl}" not found, creating`);
await this.createTableWithRetry(`CREATE TABLE IF NOT EXISTS "${tbl}" (id TEXT NOT NULL DEFAULT '', path TEXT NOT NULL DEFAULT '', filename TEXT NOT NULL DEFAULT '', summary TEXT NOT NULL DEFAULT '', summary_embedding FLOAT4[], author TEXT NOT NULL DEFAULT '', mime_type TEXT NOT NULL DEFAULT 'text/plain', size_bytes BIGINT NOT NULL DEFAULT 0, project TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL DEFAULT '', plugin_version TEXT NOT NULL DEFAULT '', creation_date TEXT NOT NULL DEFAULT '', last_update_date TEXT NOT NULL DEFAULT '') USING deeplake`, tbl);
log3(`table "${tbl}" created`);
if (!tables.includes(tbl))
this._tablesCache = [...tables, tbl];
}
await this.ensureEmbeddingColumn(tbl, SUMMARY_EMBEDDING_COL);
await this.ensureColumn(tbl, "agent", "TEXT NOT NULL DEFAULT ''");
await this.ensureColumn(tbl, "plugin_version", "TEXT NOT NULL DEFAULT ''");
}
/** Create the sessions table (uses JSONB for message since every row is a JSON event). */
async ensureSessionsTable(name) {
const safe = sqlIdent(name);
const tables = await this.listTables();
if (!tables.includes(safe)) {
log3(`table "${safe}" not found, creating`);
await this.createTableWithRetry(`CREATE TABLE IF NOT EXISTS "${safe}" (id TEXT NOT NULL DEFAULT '', path TEXT NOT NULL DEFAULT '', filename TEXT NOT NULL DEFAULT '', message JSONB, message_embedding FLOAT4[], author TEXT NOT NULL DEFAULT '', mime_type TEXT NOT NULL DEFAULT 'application/json', size_bytes BIGINT NOT NULL DEFAULT 0, project TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL DEFAULT '', plugin_version TEXT NOT NULL DEFAULT '', creation_date TEXT NOT NULL DEFAULT '', last_update_date TEXT NOT NULL DEFAULT '') USING deeplake`, safe);
log3(`table "${safe}" created`);
if (!tables.includes(safe))
this._tablesCache = [...tables, safe];
}
await this.ensureEmbeddingColumn(safe, MESSAGE_EMBEDDING_COL);
await this.ensureColumn(safe, "agent", "TEXT NOT NULL DEFAULT ''");
await this.ensureColumn(safe, "plugin_version", "TEXT NOT NULL DEFAULT ''");
await this.ensureLookupIndex(safe, "path_creation_date", `("path", "creation_date")`);
}
/**
* Create the skills table.
*
* One row per skill version. Workers INSERT a fresh row on every KEEP /
* MERGE rather than UPDATE-ing in place, so the full version history is
* recoverable. Uniqueness in the *current* state is by (project_key, name)
* — newer rows shadow older ones at read time (ORDER BY version DESC).
* This sidesteps the Deeplake UPDATE-coalescing quirk that bit the wiki
* worker.
*/
async ensureSkillsTable(name) {
const safe = sqlIdent(name);
const tables = await this.listTables();
if (!tables.includes(safe)) {
log3(`table "${safe}" not found, creating`);
await this.createTableWithRetry(`CREATE TABLE IF NOT EXISTS "${safe}" (id TEXT NOT NULL DEFAULT '', name TEXT NOT NULL DEFAULT '', project TEXT NOT NULL DEFAULT '', project_key TEXT NOT NULL DEFAULT '', local_path TEXT NOT NULL DEFAULT '', install TEXT NOT NULL DEFAULT 'project', source_sessions TEXT NOT NULL DEFAULT '[]', source_agent TEXT NOT NULL DEFAULT '', scope TEXT NOT NULL DEFAULT 'me', author TEXT NOT NULL DEFAULT '', description TEXT NOT NULL DEFAULT '', trigger_text TEXT NOT NULL DEFAULT '', body TEXT NOT NULL DEFAULT '', version BIGINT NOT NULL DEFAULT 1, created_at TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL DEFAULT '') USING deeplake`, safe);
log3(`table "${safe}" created`);
if (!tables.includes(safe))
this._tablesCache = [...tables, safe];
}
await this.ensureLookupIndex(safe, "project_key_name", `("project_key", "name")`);
}
};
// dist/src/utils/session-path.js
function buildSessionPath(config, sessionId) {
const workspace = config.workspaceId ?? "default";
return `/sessions/${config.userName}/${config.userName}_${config.orgName}_${workspace}_${sessionId}.jsonl`;
}
// dist/src/hooks/summary-state.js
import { readFileSync as readFileSync5, writeFileSync as writeFileSync4, writeSync, mkdirSync as mkdirSync4, renameSync as renameSync2, existsSync as existsSync3, unlinkSync as unlinkSync3, openSync as openSync2, closeSync as closeSync2 } from "node:fs";
import { homedir as homedir5 } from "node:os";
import { join as join6 } from "node:path";
var dlog = (msg) => log("summary-state", msg);
var STATE_DIR = join6(homedir5(), ".claude", "hooks", "summary-state");
var YIELD_BUF = new Int32Array(new SharedArrayBuffer(4));
function statePath(sessionId) {
return join6(STATE_DIR, `${sessionId}.json`);
}
function lockPath2(sessionId) {
return join6(STATE_DIR, `${sessionId}.lock`);
}
function readState(sessionId) {
const p = statePath(sessionId);
if (!existsSync3(p))
return null;
try {
return JSON.parse(readFileSync5(p, "utf-8"));
} catch {
return null;
}
}
function writeState(sessionId, state) {
mkdirSync4(STATE_DIR, { recursive: true });
const p = statePath(sessionId);
const tmp = `${p}.${process.pid}.${Date.now()}.tmp`;
writeFileSync4(tmp, JSON.stringify(state));
renameSync2(tmp, p);
}
function withRmwLock(sessionId, fn) {
mkdirSync4(STATE_DIR, { recursive: true });
const rmwLock = statePath(sessionId) + ".rmw";
const deadline = Date.now() + 2e3;
let fd = null;
while (fd === null) {
try {
fd = openSync2(rmwLock, "wx");
} catch (e) {
if (e.code !== "EEXIST")
throw e;
if (Date.now() > deadline) {
dlog(`rmw lock deadline exceeded for ${sessionId}, reclaiming stale lock`);
try {
unlinkSync3(rmwLock);
} catch (unlinkErr) {
dlog(`stale rmw lock unlink failed for ${sessionId}: ${unlinkErr.message}`);
}
continue;
}
Atomics.wait(YIELD_BUF, 0, 0, 10);
}
}
try {
return fn();
} finally {
closeSync2(fd);
try {
unlinkSync3(rmwLock);
} catch (unlinkErr) {
dlog(`rmw lock cleanup failed for ${sessionId}: ${unlinkErr.message}`);
}
}
}
function bumpTotalCount(sessionId) {
return withRmwLock(sessionId, () => {
const now = Date.now();
const existing = readState(sessionId);
const next = existing ? { ...existing, totalCount: existing.totalCount + 1 } : { lastSummaryAt: now, lastSummaryCount: 0, totalCount: 1 };
writeState(sessionId, next);
return next;
});
}
function loadTriggerConfig() {
const n = Number(process.env.HIVEMIND_SUMMARY_EVERY_N_MSGS ?? "");
const h = Number(process.env.HIVEMIND_SUMMARY_EVERY_HOURS ?? "");
return {
everyNMessages: Number.isInteger(n) && n > 0 ? n : 50,
everyHours: Number.isFinite(h) && h > 0 ? h : 2
};
}
var FIRST_SUMMARY_AT = 10;
function shouldTrigger(state, cfg, now = Date.now()) {
const msgsSince = state.totalCount - state.lastSummaryCount;
if (state.lastSummaryCount === 0 && state.totalCount >= FIRST_SUMMARY_AT)
return true;
if (msgsSince >= cfg.everyNMessages)
return true;
if (msgsSince > 0 && now - state.lastSummaryAt >= cfg.everyHours * 3600 * 1e3)
return true;
return false;
}
function tryAcquireLock(sessionId, maxAgeMs = 10 * 60 * 1e3) {
mkdirSync4(STATE_DIR, { recursive: true });
const p = lockPath2(sessionId);
if (existsSync3(p)) {
try {
const ageMs = Date.now() - parseInt(readFileSync5(p, "utf-8"), 10);
if (Number.isFinite(ageMs) && ageMs < maxAgeMs)
return false;
} catch (readErr) {
dlog(`lock file unreadable for ${sessionId}, treating as stale: ${readErr.message}`);
}
try {
unlinkSync3(p);
} catch (unlinkErr) {
dlog(`could not unlink stale lock for ${sessionId}: ${unlinkErr.message}`);
return false;
}
}
try {
const fd = openSync2(p, "wx");
try {
writeSync(fd, String(Date.now()));
} finally {
closeSync2(fd);
}
return true;
} catch (e) {
if (e.code === "EEXIST")
return false;
throw e;
}
}
function releaseLock(sessionId) {
try {
unlinkSync3(lockPath2(sessionId));
} catch (e) {
if (e?.code !== "ENOENT") {
dlog(`releaseLock unlink failed for ${sessionId}: ${e.message}`);
}
}
}
// dist/src/hooks/spawn-wiki-worker.js
import { spawn, execSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { dirname as dirname2, join as join9 } from "node:path";
import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync6 } from "node:fs";
import { homedir as homedir6, tmpdir as tmpdir2 } from "node:os";
// dist/src/utils/wiki-log.js
import { mkdirSync as mkdirSync5, appendFileSync as appendFileSync2 } from "node:fs";
import { join as join7 } from "node:path";
function makeWikiLogger(hooksDir, filename = "deeplake-wiki.log") {
const path = join7(hooksDir, filename);
return {
path,
log(msg) {
try {
mkdirSync5(hooksDir, { recursive: true });
appendFileSync2(path, `[${utcTimestamp()}] ${msg}
`);
} catch {
}
}
};
}
// dist/src/utils/version-check.js
import { readFileSync as readFileSync6 } from "node:fs";
import { dirname, join as join8 } from "node:path";
function getInstalledVersion(bundleDir, pluginManifestDir) {
try {
const pluginJson = join8(bundleDir, "..", pluginManifestDir, "plugin.json");
const plugin = JSON.parse(readFileSync6(pluginJson, "utf-8"));
if (plugin.version)
return plugin.version;
} catch {
}
try {
const stamp = readFileSync6(join8(bundleDir, "..", ".hivemind_version"), "utf-8").trim();
if (stamp)
return stamp;
} catch {
}
const HIVEMIND_PKG_NAMES = /* @__PURE__ */ new Set([
"hivemind",
"hivemind-codex",
"@deeplake/hivemind",
"@deeplake/hivemind-codex",
"@activeloop/hivemind",
"@activeloop/hivemind-codex"
]);
let dir = bundleDir;
for (let i = 0; i < 5; i++) {
const candidate = join8(dir, "package.json");
try {
const pkg = JSON.parse(readFileSync6(candidate, "utf-8"));
if (HIVEMIND_PKG_NAMES.has(pkg.name) && pkg.version)
return pkg.version;
} catch {
}
const parent = dirname(dir);
if (parent === dir)
break;
dir = parent;
}
return null;
}
// dist/src/hooks/spawn-wiki-worker.js
var HOME = homedir6();
var wikiLogger = makeWikiLogger(join9(HOME, ".claude", "hooks"));
var WIKI_LOG = wikiLogger.path;
var WIKI_PROMPT_TEMPLATE = `You are building a personal wiki from a coding session. Your goal is to extract every piece of knowledge \u2014 entities, decisions, relationships, and facts \u2014 into a structured, searchable wiki entry. Think of this as building a knowledge graph, not writing a summary.
SESSION JSONL path: __JSONL__
SUMMARY FILE to write: __SUMMARY__
SESSION ID: __SESSION_ID__
PROJECT: __PROJECT__
PREVIOUS JSONL OFFSET (lines already processed): __PREV_OFFSET__
CURRENT JSONL LINES: __JSONL_LINES__
Steps:
1. Read the session JSONL at the path above.
- If PREVIOUS JSONL OFFSET > 0, this is a resumed session. Read the existing summary file first,
then focus on lines AFTER the offset for new content. Merge new facts into the existing summary.
- If offset is 0, generate from scratch.
2. Write the summary file at the path above with this EXACT format. The header fields (Source, Project) are pre-filled \u2014 copy them VERBATIM, do NOT replace them with paths from the JSONL content:
# Session __SESSION_ID__
- **Source**: __JSONL_SERVER_PATH__
- **Started**: <extract from JSONL>
- **Ended**: <now>
- **Project**: __PROJECT__
- **JSONL offset**: __JSONL_LINES__
## What Happened
<2-3 dense sentences. What was the goal, what was accomplished, what's left.>
## People
<For each person mentioned: name, role, what they did/said. Format: **Name** \u2014 role \u2014 action>
## Entities
<Every named thing: repos, branches, files, APIs, tools, services, tables, features, bugs.
Format: **entity** (type) \u2014 what was done with it, its current state>
## Decisions & Reasoning
<Every decision made and WHY. Not just "did X" but "did X because Y, considered Z but rejected it because W">
## Key Facts
<Bullet list of atomic facts that could answer future questions. Each fact should stand alone.
Example: "- The memory table uses DELETE+INSERT, not UPDATE (WASM doesn't support upsert)">
## Files Modified
<bullet list: path (new/modified/deleted) \u2014 what changed>
## Open Questions / TODO
<Anything unresolved, blocked, or explicitly deferred>
IMPORTANT: Be exhaustive. Extract EVERY entity, decision, and fact. Future you will search this wiki to answer questions like "who worked on X", "why did we choose Y", "what's the status of Z". If a detail exists in the session, it should be in the wiki.
PRIVACY: Never include absolute filesystem paths (e.g. /home/user/..., /Users/..., C:\\\\...) in the summary. Use only project-relative paths or the project name. The Source and Project fields above are already correct \u2014 do not change them.
LENGTH LIMIT: Keep the total summary under 4000 characters. Be dense and concise \u2014 prioritize facts over prose. If a session is short, the summary should be short too.`;
var wikiLog = wikiLogger.log;
function findClaudeBin() {
try {
return execSync("which claude 2>/dev/null", { encoding: "utf-8" }).trim();
} catch {
return join9(HOME, ".claude", "local", "claude");
}
}
function spawnWikiWorker(opts) {
const { config, sessionId, cwd, bundleDir, reason } = opts;
const projectName = cwd.split("/").pop() || "unknown";
const tmpDir = join9(tmpdir2(), `deeplake-wiki-${sessionId}-${Date.now()}`);
mkdirSync6(tmpDir, { recursive: true });
const pluginVersion = getInstalledVersion(bundleDir, ".claude-plugin") ?? "";
const configFile = join9(tmpDir, "config.json");
writeFileSync5(configFile, JSON.stringify({
apiUrl: config.apiUrl,
token: config.token,
orgId: config.orgId,
workspaceId: config.workspaceId,
memoryTable: config.tableName,
sessionsTable: config.sessionsTableName,
sessionId,