-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathauth-login.js
More file actions
executable file
·1140 lines (1132 loc) · 43.7 KB
/
Copy pathauth-login.js
File metadata and controls
executable file
·1140 lines (1132 loc) · 43.7 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
// dist/src/commands/auth.js
import { readFileSync, writeFileSync, existsSync, mkdirSync, unlinkSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import { execSync } from "node:child_process";
var CONFIG_DIR = join(homedir(), ".deeplake");
var CREDS_PATH = join(CONFIG_DIR, "credentials.json");
var DEFAULT_API_URL = "https://api.deeplake.ai";
function loadCredentials() {
if (!existsSync(CREDS_PATH))
return null;
try {
return JSON.parse(readFileSync(CREDS_PATH, "utf-8"));
} catch {
return null;
}
}
function saveCredentials(creds) {
if (!existsSync(CONFIG_DIR))
mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
writeFileSync(CREDS_PATH, JSON.stringify({ ...creds, savedAt: (/* @__PURE__ */ new Date()).toISOString() }, null, 2), { mode: 384 });
}
function deleteCredentials() {
if (existsSync(CREDS_PATH)) {
unlinkSync(CREDS_PATH);
return true;
}
return false;
}
async function apiGet(path, token, apiUrl, orgId) {
const headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
};
if (orgId)
headers["X-Activeloop-Org-Id"] = orgId;
const resp = await fetch(`${apiUrl}${path}`, { headers });
if (!resp.ok)
throw new Error(`API ${resp.status}: ${await resp.text().catch(() => "")}`);
return resp.json();
}
async function apiPost(path, body, token, apiUrl, orgId) {
const headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
};
if (orgId)
headers["X-Activeloop-Org-Id"] = orgId;
const resp = await fetch(`${apiUrl}${path}`, { method: "POST", headers, body: JSON.stringify(body) });
if (!resp.ok)
throw new Error(`API ${resp.status}: ${await resp.text().catch(() => "")}`);
return resp.json();
}
async function apiDelete(path, token, apiUrl, orgId) {
const headers = {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
};
if (orgId)
headers["X-Activeloop-Org-Id"] = orgId;
const resp = await fetch(`${apiUrl}${path}`, { method: "DELETE", headers });
if (!resp.ok)
throw new Error(`API ${resp.status}: ${await resp.text().catch(() => "")}`);
}
async function requestDeviceCode(apiUrl = DEFAULT_API_URL) {
const resp = await fetch(`${apiUrl}/auth/device/code`, {
method: "POST",
headers: { "Content-Type": "application/json" }
});
if (!resp.ok)
throw new Error(`Device flow unavailable: HTTP ${resp.status}`);
return resp.json();
}
async function pollForToken(deviceCode, apiUrl = DEFAULT_API_URL) {
const resp = await fetch(`${apiUrl}/auth/device/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ device_code: deviceCode })
});
if (resp.ok)
return resp.json();
if (resp.status === 400) {
const err = await resp.json().catch(() => null);
if (err?.error === "authorization_pending" || err?.error === "slow_down")
return null;
if (err?.error === "expired_token")
throw new Error("Device code expired. Try again.");
if (err?.error === "access_denied")
throw new Error("Authorization denied.");
}
throw new Error(`Token polling failed: HTTP ${resp.status}`);
}
function openBrowser(url) {
try {
const cmd = process.platform === "darwin" ? `open "${url}"` : process.platform === "win32" ? `start "${url}"` : `xdg-open "${url}" 2>/dev/null`;
execSync(cmd, { stdio: "ignore", timeout: 5e3 });
return true;
} catch {
return false;
}
}
async function deviceFlowLogin(apiUrl = DEFAULT_API_URL) {
const code = await requestDeviceCode(apiUrl);
const opened = openBrowser(code.verification_uri_complete);
const msg = [
"\nDeeplake Authentication",
"\u2500".repeat(40),
`
Open this URL: ${code.verification_uri_complete}`,
`Or visit ${code.verification_uri} and enter code: ${code.user_code}`,
opened ? "\nBrowser opened. Waiting for sign in..." : "\nWaiting for sign in..."
].join("\n");
process.stderr.write(msg + "\n");
const interval = Math.max(code.interval || 5, 5) * 1e3;
const deadline = Date.now() + code.expires_in * 1e3;
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, interval));
const result = await pollForToken(code.device_code, apiUrl);
if (result) {
process.stderr.write("\nAuthentication successful!\n");
return { token: result.access_token, expiresIn: result.expires_in };
}
}
throw new Error("Device code expired.");
}
async function listOrgs(token, apiUrl = DEFAULT_API_URL) {
const data = await apiGet("/organizations", token, apiUrl);
return Array.isArray(data) ? data : [];
}
async function switchOrg(orgId, orgName) {
const creds = loadCredentials();
if (!creds)
throw new Error("Not logged in. Run deeplake login first.");
saveCredentials({ ...creds, orgId, orgName });
}
async function listWorkspaces(token, apiUrl = DEFAULT_API_URL, orgId) {
const raw = await apiGet("/workspaces", token, apiUrl, orgId);
const data = raw.data ?? raw;
return Array.isArray(data) ? data : [];
}
async function switchWorkspace(workspaceId) {
const creds = loadCredentials();
if (!creds)
throw new Error("Not logged in. Run deeplake login first.");
saveCredentials({ ...creds, workspaceId });
}
async function inviteMember(username, accessMode, token, orgId, apiUrl = DEFAULT_API_URL) {
await apiPost(`/organizations/${orgId}/members/invite`, { username, access_mode: accessMode }, token, apiUrl, orgId);
}
async function listMembers(token, orgId, apiUrl = DEFAULT_API_URL) {
const data = await apiGet(`/organizations/${orgId}/members`, token, apiUrl, orgId);
return data.members ?? [];
}
async function removeMember(userId, token, orgId, apiUrl = DEFAULT_API_URL) {
await apiDelete(`/organizations/${orgId}/members/${userId}`, token, apiUrl, orgId);
}
async function login(apiUrl = DEFAULT_API_URL) {
const { token: authToken } = await deviceFlowLogin(apiUrl);
const user = await apiGet("/me", authToken, apiUrl);
const userName = user.name || (user.email ? user.email.split("@")[0] : "unknown");
process.stderr.write(`
Logged in as: ${userName}
`);
const orgs = await listOrgs(authToken, apiUrl);
let orgId;
let orgName;
if (orgs.length === 1) {
orgId = orgs[0].id;
orgName = orgs[0].name;
process.stderr.write(`Organization: ${orgName}
`);
} else {
process.stderr.write("\nOrganizations:\n");
orgs.forEach((org, i) => process.stderr.write(` ${i + 1}. ${org.name}
`));
orgId = orgs[0].id;
orgName = orgs[0].name;
process.stderr.write(`
Using: ${orgName}
`);
}
const tokenName = `deeplake-plugin-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}`;
const tokenData = await apiPost("/users/me/tokens", {
name: tokenName,
duration: 365 * 24 * 3600,
organization_id: orgId
}, authToken, apiUrl);
const apiToken = tokenData.token.token;
const creds = {
token: apiToken,
orgId,
orgName,
userName,
workspaceId: "default",
apiUrl,
savedAt: (/* @__PURE__ */ new Date()).toISOString()
};
saveCredentials(creds);
return creds;
}
// dist/src/config.js
import { readFileSync as readFileSync2, existsSync as existsSync2 } from "node:fs";
import { join as join2 } from "node:path";
import { homedir as homedir2, userInfo } from "node:os";
function loadConfig() {
const home = homedir2();
const credPath = join2(home, ".deeplake", "credentials.json");
let creds = null;
if (existsSync2(credPath)) {
try {
creds = JSON.parse(readFileSync2(credPath, "utf-8"));
} catch {
return null;
}
}
const env = process.env;
if (!env.HIVEMIND_TOKEN && env.DEEPLAKE_TOKEN) {
process.stderr.write("[hivemind] DEEPLAKE_* env vars are deprecated; use HIVEMIND_* instead\n");
}
const token = env.HIVEMIND_TOKEN ?? env.DEEPLAKE_TOKEN ?? creds?.token;
const orgId = env.HIVEMIND_ORG_ID ?? env.DEEPLAKE_ORG_ID ?? creds?.orgId;
if (!token || !orgId)
return null;
return {
token,
orgId,
orgName: creds?.orgName ?? orgId,
userName: creds?.userName || userInfo().username || "unknown",
workspaceId: env.HIVEMIND_WORKSPACE_ID ?? env.DEEPLAKE_WORKSPACE_ID ?? creds?.workspaceId ?? "default",
apiUrl: env.HIVEMIND_API_URL ?? env.DEEPLAKE_API_URL ?? creds?.apiUrl ?? "https://api.deeplake.ai",
tableName: env.HIVEMIND_TABLE ?? env.DEEPLAKE_TABLE ?? "memory",
sessionsTableName: env.HIVEMIND_SESSIONS_TABLE ?? env.DEEPLAKE_SESSIONS_TABLE ?? "sessions",
graphNodesTableName: env.HIVEMIND_GRAPH_NODES_TABLE ?? env.DEEPLAKE_GRAPH_NODES_TABLE ?? "graph_nodes",
graphEdgesTableName: env.HIVEMIND_GRAPH_EDGES_TABLE ?? env.DEEPLAKE_GRAPH_EDGES_TABLE ?? "graph_edges",
factsTableName: env.HIVEMIND_FACTS_TABLE ?? env.DEEPLAKE_FACTS_TABLE ?? "memory_facts",
entitiesTableName: env.HIVEMIND_ENTITIES_TABLE ?? env.DEEPLAKE_ENTITIES_TABLE ?? "memory_entities",
factEntityLinksTableName: env.HIVEMIND_FACT_ENTITY_LINKS_TABLE ?? env.DEEPLAKE_FACT_ENTITY_LINKS_TABLE ?? "fact_entity_links",
memoryPath: env.HIVEMIND_MEMORY_PATH ?? env.DEEPLAKE_MEMORY_PATH ?? join2(home, ".deeplake", "memory")
};
}
// dist/src/deeplake-api.js
import { randomUUID } from "node:crypto";
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
import { join as join4 } from "node:path";
import { tmpdir } from "node:os";
// dist/src/utils/debug.js
import { appendFileSync } from "node:fs";
import { join as join3 } from "node:path";
import { homedir as homedir3 } from "node:os";
var DEBUG = (process.env.HIVEMIND_DEBUG ?? process.env.DEEPLAKE_DEBUG) === "1";
var LOG = join3(homedir3(), ".deeplake", "hook-debug.log");
function log(tag, msg) {
if (!DEBUG)
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, "");
}
// dist/src/deeplake-api.js
var log2 = (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 ?? process.env.DEEPLAKE_TRACE_SQL) === "1" || (process.env.HIVEMIND_DEBUG ?? process.env.DEEPLAKE_DEBUG) === "1";
if (!traceEnabled)
return;
process.stderr.write(`[deeplake-sql] ${msg}
`);
const debugFileLog = (process.env.HIVEMIND_DEBUG ?? process.env.DEEPLAKE_DEBUG) === "1";
if (debugFileLog)
log2(msg);
}
var DeeplakeQueryError = class extends Error {
sqlSummary;
status;
responseBody;
sql;
cause;
constructor(message, args = {}) {
super(message);
this.name = "DeeplakeQueryError";
this.sql = args.sql;
this.sqlSummary = args.sql ? summarizeSql(args.sql) : "";
this.status = args.status;
this.responseBody = args.responseBody;
this.cause = args.cause;
}
};
var RETRYABLE_CODES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
var MAX_RETRIES = 3;
var BASE_DELAY_MS = 500;
var MAX_CONCURRENCY = 5;
var QUERY_TIMEOUT_MS = Number(process.env["HIVEMIND_QUERY_TIMEOUT_MS"] ?? process.env["DEEPLAKE_QUERY_TIMEOUT_MS"] ?? 1e4);
var INDEX_MARKER_TTL_MS = Number(process.env["HIVEMIND_INDEX_MARKER_TTL_MS"] ?? 6 * 60 * 6e4);
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, 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");
}
function getIndexMarkerDir() {
return process.env["HIVEMIND_INDEX_MARKER_DIR"] ?? join4(tmpdir(), "hivemind-deeplake-indexes");
}
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((resolve) => this.waiting.push(resolve));
}
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;
try {
const signal = AbortSignal.timeout(QUERY_TIMEOUT_MS);
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
},
signal,
body: JSON.stringify({ query: sql })
});
} catch (e) {
if (isTimeoutError(e)) {
lastError = new DeeplakeQueryError(`Query timeout after ${QUERY_TIMEOUT_MS}ms`, { sql, cause: e });
throw lastError;
}
lastError = e instanceof Error ? new DeeplakeQueryError(e.message, { sql, cause: e }) : new DeeplakeQueryError(String(e), { sql, cause: e });
if (attempt < MAX_RETRIES) {
const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200;
log2(`query retry ${attempt + 1}/${MAX_RETRIES} (fetch error: ${lastError.message}) in ${delay.toFixed(0)}ms`);
await sleep(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)));
if (attempt < MAX_RETRIES && (RETRYABLE_CODES.has(resp.status) || retryable403)) {
const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200;
log2(`query retry ${attempt + 1}/${MAX_RETRIES} (${resp.status}) in ${delay.toFixed(0)}ms`);
await sleep(delay);
continue;
}
throw new DeeplakeQueryError(`Query failed: ${resp.status}: ${text.slice(0, 200)}`, {
sql,
status: resp.status,
responseBody: text.slice(0, 4e3)
});
}
throw lastError ?? new DeeplakeQueryError("Query failed: max retries exceeded", { sql });
}
// ── 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)));
}
log2(`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)}', 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, mime_type, size_bytes, creation_date, last_update_date";
let vals = `'${id}', '${sqlStr(row.path)}', '${sqlStr(row.filename)}', E'${sqlStr(row.contentText)}', '${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}")`);
}
/** Create the standard BM25 summary index for a memory table. */
async createSummaryBm25Index(tableName) {
const table = tableName ?? this.tableName;
const indexName = this.buildLookupIndexName(table, "summary_bm25");
await this.query(`CREATE INDEX IF NOT EXISTS "${indexName}" ON "${table}" USING deeplake_index ("summary")`);
}
/** Ensure the standard BM25 summary index exists, using a local freshness marker to avoid repeated CREATEs. */
async ensureSummaryBm25Index(tableName) {
const table = tableName ?? this.tableName;
const suffix = "summary_bm25";
if (this.hasFreshLookupIndexMarker(table, suffix))
return;
try {
await this.createSummaryBm25Index(table);
this.markLookupIndexReady(table, suffix);
} catch (e) {
if (isDuplicateIndexError(e)) {
this.markLookupIndexReady(table, suffix);
return;
}
throw e;
}
}
buildLookupIndexName(table, suffix) {
return `idx_${table}_${suffix}`.replace(/[^a-zA-Z0-9_]/g, "_");
}
getLookupIndexMarkerPath(table, suffix) {
const markerKey = [
this.workspaceId,
this.orgId,
table,
suffix
].join("__").replace(/[^a-zA-Z0-9_.-]/g, "_");
return join4(getIndexMarkerDir(), `${markerKey}.json`);
}
hasFreshLookupIndexMarker(table, suffix) {
const markerPath = this.getLookupIndexMarkerPath(table, suffix);
if (!existsSync3(markerPath))
return false;
try {
const raw = JSON.parse(readFileSync3(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;
}
}
markLookupIndexReady(table, suffix) {
mkdirSync2(getIndexMarkerDir(), { recursive: true });
writeFileSync2(this.getLookupIndexMarkerPath(table, suffix), JSON.stringify({ updatedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
}
async ensureLookupIndex(table, suffix, columnsSql) {
if (this.hasFreshLookupIndexMarker(table, suffix))
return;
const indexName = this.buildLookupIndexName(table, suffix);
try {
await this.query(`CREATE INDEX IF NOT EXISTS "${indexName}" ON "${table}" ${columnsSql}`);
this.markLookupIndexReady(table, suffix);
} catch (e) {
if (isDuplicateIndexError(e)) {
this.markLookupIndexReady(table, suffix);
return;
}
log2(`index "${indexName}" skipped: ${e.message}`);
}
}
/** 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
}
});
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 sleep(BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200);
continue;
}
return { tables: [], cacheable: false };
} catch {
if (attempt < MAX_RETRIES) {
await sleep(BASE_DELAY_MS * Math.pow(2, attempt));
continue;
}
return { tables: [], cacheable: false };
}
}
return { tables: [], cacheable: false };
}
/** Create the memory table if it doesn't already exist. Migrate columns on existing tables. */
async ensureTable(name) {
const tbl = name ?? this.tableName;
const tables = await this.listTables();
if (!tables.includes(tbl)) {
log2(`table "${tbl}" not found, creating`);
await this.query(`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 '', 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 '', creation_date TEXT NOT NULL DEFAULT '', last_update_date TEXT NOT NULL DEFAULT '') USING deeplake`);
log2(`table "${tbl}" created`);
if (!tables.includes(tbl))
this._tablesCache = [...tables, tbl];
}
}
/** Create the sessions table (one physical row per message/event, with direct search columns). */
async ensureSessionsTable(name) {
const sessionColumns = [
`id TEXT NOT NULL DEFAULT ''`,
`path TEXT NOT NULL DEFAULT ''`,
`filename TEXT NOT NULL DEFAULT ''`,
`message JSONB`,
`session_id TEXT NOT NULL DEFAULT ''`,
`event_type TEXT NOT NULL DEFAULT ''`,
`turn_index BIGINT NOT NULL DEFAULT 0`,
`dia_id TEXT NOT NULL DEFAULT ''`,
`speaker TEXT NOT NULL DEFAULT ''`,
`text TEXT NOT NULL DEFAULT ''`,
`turn_summary TEXT NOT NULL DEFAULT ''`,
`source_date_time TEXT NOT NULL DEFAULT ''`,
`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 ''`,
`creation_date TEXT NOT NULL DEFAULT ''`,
`last_update_date TEXT NOT NULL DEFAULT ''`
];
const tables = await this.listTables();
if (!tables.includes(name)) {
log2(`table "${name}" not found, creating`);
await this.query(`CREATE TABLE IF NOT EXISTS "${name}" (` + sessionColumns.join(", ") + `) USING deeplake`);
log2(`table "${name}" created`);
if (!tables.includes(name))
this._tablesCache = [...tables, name];
}
const alterColumns = [
["session_id", `TEXT NOT NULL DEFAULT ''`],
["event_type", `TEXT NOT NULL DEFAULT ''`],
["turn_index", `BIGINT NOT NULL DEFAULT 0`],
["dia_id", `TEXT NOT NULL DEFAULT ''`],
["speaker", `TEXT NOT NULL DEFAULT ''`],
["text", `TEXT NOT NULL DEFAULT ''`],
["turn_summary", `TEXT NOT NULL DEFAULT ''`],
["source_date_time", `TEXT NOT NULL DEFAULT ''`]
];
for (const [column, ddl] of alterColumns) {
try {
await this.query(`ALTER TABLE "${name}" ADD COLUMN IF NOT EXISTS "${column}" ${ddl}`);
} catch {
}
}
await this.ensureLookupIndex(name, "path_creation_date_turn_index", `("path", "creation_date", "turn_index")`);
}
async ensureGraphNodesTable(name) {
const columns = [
`id TEXT NOT NULL DEFAULT ''`,
`path TEXT NOT NULL DEFAULT ''`,
`filename TEXT NOT NULL DEFAULT ''`,
`node_id TEXT NOT NULL DEFAULT ''`,
`canonical_name TEXT NOT NULL DEFAULT ''`,
`node_type TEXT NOT NULL DEFAULT ''`,
`summary TEXT NOT NULL DEFAULT ''`,
`search_text TEXT NOT NULL DEFAULT ''`,
`aliases TEXT NOT NULL DEFAULT ''`,
`source_session_id TEXT NOT NULL DEFAULT ''`,
`source_session_ids TEXT NOT NULL DEFAULT ''`,
`source_path TEXT NOT NULL DEFAULT ''`,
`source_paths TEXT NOT NULL DEFAULT ''`,
`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 ''`,
`creation_date TEXT NOT NULL DEFAULT ''`,
`last_update_date TEXT NOT NULL DEFAULT ''`
];
const tables = await this.listTables();
if (!tables.includes(name)) {
await this.query(`CREATE TABLE IF NOT EXISTS "${name}" (${columns.join(", ")}) USING deeplake`);
if (!tables.includes(name))
this._tablesCache = [...tables, name];
}
for (const [column, ddl] of [
["source_session_ids", `TEXT NOT NULL DEFAULT ''`],
["source_paths", `TEXT NOT NULL DEFAULT ''`]
]) {
try {
await this.query(`ALTER TABLE "${name}" ADD COLUMN IF NOT EXISTS "${column}" ${ddl}`);
} catch {
}
}
await this.ensureLookupIndex(name, "source_session_id", `("source_session_id")`);
await this.ensureLookupIndex(name, "node_id", `("node_id")`);
}
async ensureGraphEdgesTable(name) {
const columns = [
`id TEXT NOT NULL DEFAULT ''`,
`path TEXT NOT NULL DEFAULT ''`,
`filename TEXT NOT NULL DEFAULT ''`,
`edge_id TEXT NOT NULL DEFAULT ''`,
`source_node_id TEXT NOT NULL DEFAULT ''`,
`target_node_id TEXT NOT NULL DEFAULT ''`,
`relation TEXT NOT NULL DEFAULT ''`,
`summary TEXT NOT NULL DEFAULT ''`,
`evidence TEXT NOT NULL DEFAULT ''`,
`search_text TEXT NOT NULL DEFAULT ''`,
`source_session_id TEXT NOT NULL DEFAULT ''`,
`source_session_ids TEXT NOT NULL DEFAULT ''`,
`source_path TEXT NOT NULL DEFAULT ''`,
`source_paths TEXT NOT NULL DEFAULT ''`,
`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 ''`,
`creation_date TEXT NOT NULL DEFAULT ''`,
`last_update_date TEXT NOT NULL DEFAULT ''`
];
const tables = await this.listTables();
if (!tables.includes(name)) {
await this.query(`CREATE TABLE IF NOT EXISTS "${name}" (${columns.join(", ")}) USING deeplake`);
if (!tables.includes(name))
this._tablesCache = [...tables, name];
}
for (const [column, ddl] of [
["source_session_ids", `TEXT NOT NULL DEFAULT ''`],
["source_paths", `TEXT NOT NULL DEFAULT ''`]
]) {
try {
await this.query(`ALTER TABLE "${name}" ADD COLUMN IF NOT EXISTS "${column}" ${ddl}`);
} catch {
}
}
await this.ensureLookupIndex(name, "source_session_id", `("source_session_id")`);
await this.ensureLookupIndex(name, "source_target_relation", `("source_node_id", "target_node_id", "relation")`);
}
async ensureFactsTable(name) {
const columns = [
`id TEXT NOT NULL DEFAULT ''`,
`path TEXT NOT NULL DEFAULT ''`,
`filename TEXT NOT NULL DEFAULT ''`,
`fact_id TEXT NOT NULL DEFAULT ''`,
`subject_entity_id TEXT NOT NULL DEFAULT ''`,
`subject_name TEXT NOT NULL DEFAULT ''`,
`subject_type TEXT NOT NULL DEFAULT ''`,
`predicate TEXT NOT NULL DEFAULT ''`,
`object_entity_id TEXT NOT NULL DEFAULT ''`,
`object_name TEXT NOT NULL DEFAULT ''`,
`object_type TEXT NOT NULL DEFAULT ''`,
`summary TEXT NOT NULL DEFAULT ''`,
`evidence TEXT NOT NULL DEFAULT ''`,
`search_text TEXT NOT NULL DEFAULT ''`,
`confidence TEXT NOT NULL DEFAULT ''`,
`valid_at TEXT NOT NULL DEFAULT ''`,
`valid_from TEXT NOT NULL DEFAULT ''`,
`valid_to TEXT NOT NULL DEFAULT ''`,
`source_session_id TEXT NOT NULL DEFAULT ''`,
`source_path TEXT NOT NULL DEFAULT ''`,
`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 ''`,
`creation_date TEXT NOT NULL DEFAULT ''`,
`last_update_date TEXT NOT NULL DEFAULT ''`
];
const tables = await this.listTables();
if (!tables.includes(name)) {
await this.query(`CREATE TABLE IF NOT EXISTS "${name}" (${columns.join(", ")}) USING deeplake`);
if (!tables.includes(name))
this._tablesCache = [...tables, name];
}
await this.ensureLookupIndex(name, "fact_id", `("fact_id")`);
await this.ensureLookupIndex(name, "session_predicate", `("source_session_id", "predicate")`);
await this.ensureLookupIndex(name, "subject_object", `("subject_entity_id", "object_entity_id")`);
}
async ensureEntitiesTable(name) {
const columns = [
`id TEXT NOT NULL DEFAULT ''`,
`path TEXT NOT NULL DEFAULT ''`,
`filename TEXT NOT NULL DEFAULT ''`,
`entity_id TEXT NOT NULL DEFAULT ''`,
`canonical_name TEXT NOT NULL DEFAULT ''`,
`entity_type TEXT NOT NULL DEFAULT ''`,
`aliases TEXT NOT NULL DEFAULT ''`,
`summary TEXT NOT NULL DEFAULT ''`,
`search_text TEXT NOT NULL DEFAULT ''`,
`source_session_ids TEXT NOT NULL DEFAULT ''`,
`source_paths TEXT NOT NULL DEFAULT ''`,
`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 ''`,
`creation_date TEXT NOT NULL DEFAULT ''`,
`last_update_date TEXT NOT NULL DEFAULT ''`
];
const tables = await this.listTables();
if (!tables.includes(name)) {
await this.query(`CREATE TABLE IF NOT EXISTS "${name}" (${columns.join(", ")}) USING deeplake`);
if (!tables.includes(name))
this._tablesCache = [...tables, name];
}
await this.ensureLookupIndex(name, "entity_id", `("entity_id")`);
await this.ensureLookupIndex(name, "canonical_name", `("canonical_name")`);
}
async ensureFactEntityLinksTable(name) {
const columns = [
`id TEXT NOT NULL DEFAULT ''`,
`path TEXT NOT NULL DEFAULT ''`,
`filename TEXT NOT NULL DEFAULT ''`,
`link_id TEXT NOT NULL DEFAULT ''`,
`fact_id TEXT NOT NULL DEFAULT ''`,
`entity_id TEXT NOT NULL DEFAULT ''`,
`entity_role TEXT NOT NULL DEFAULT ''`,
`source_session_id TEXT NOT NULL DEFAULT ''`,
`source_path TEXT NOT NULL DEFAULT ''`,
`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 ''`,
`creation_date TEXT NOT NULL DEFAULT ''`,
`last_update_date TEXT NOT NULL DEFAULT ''`
];
const tables = await this.listTables();
if (!tables.includes(name)) {
await this.query(`CREATE TABLE IF NOT EXISTS "${name}" (${columns.join(", ")}) USING deeplake`);
if (!tables.includes(name))
this._tablesCache = [...tables, name];
}
await this.ensureLookupIndex(name, "fact_id", `("fact_id")`);
await this.ensureLookupIndex(name, "entity_id", `("entity_id")`);
await this.ensureLookupIndex(name, "session_entity_role", `("source_session_id", "entity_id", "entity_role")`);
}
};
// dist/src/commands/session-prune.js
import { createInterface } from "node:readline";
function parseArgs(argv) {
let before;
let sessionId;
let all = false;
let yes = false;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--before" && argv[i + 1]) {
before = argv[++i];
} else if (arg === "--session-id" && argv[i + 1]) {
sessionId = argv[++i];
} else if (arg === "--all") {
all = true;
} else if (arg === "--yes" || arg === "-y") {
yes = true;
}
}
return { before, sessionId, all, yes };
}
function confirm(message) {
const rl = createInterface({ input: process.stdin, output: process.stderr });
return new Promise((resolve) => {
rl.question(`${message} [y/N] `, (answer) => {
rl.close();
resolve(answer.trim().toLowerCase() === "y");
});
});
}
function extractSessionId(path) {
const m = path.match(/\/sessions\/[^/]+\/[^/]+_([^.]+)\.jsonl$/);
return m ? m[1] : path.split("/").pop()?.replace(/\.jsonl$/, "") ?? path;
}
async function listSessions(api, sessionsTable, author) {
const rows = await api.query(`SELECT path, COUNT(*) as cnt, MIN(creation_date) as first_event, MAX(creation_date) as last_event, MAX(project) as project FROM "${sessionsTable}" WHERE author = '${sqlStr(author)}' GROUP BY path ORDER BY first_event DESC`);
return rows.map((r) => ({
path: String(r.path),
rowCount: Number(r.cnt),
firstEvent: String(r.first_event),
lastEvent: String(r.last_event),
project: String(r.project ?? "")
}));
}
async function deleteSessions(config, sessionPaths) {
if (sessionPaths.length === 0)
return { sessionsDeleted: 0, summariesDeleted: 0 };
const sessionsApi = new DeeplakeApi(config.token, config.apiUrl, config.orgId, config.workspaceId, config.sessionsTableName);
const memoryApi = new DeeplakeApi(config.token, config.apiUrl, config.orgId, config.workspaceId, config.tableName);
let sessionsDeleted = 0;
let summariesDeleted = 0;
for (const sessionPath of sessionPaths) {
await sessionsApi.query(`DELETE FROM "${config.sessionsTableName}" WHERE path = '${sqlStr(sessionPath)}'`);
sessionsDeleted++;
const sessionId = extractSessionId(sessionPath);
const summaryPath = `/summaries/${config.userName}/${sessionId}.md`;
const existing = await memoryApi.query(`SELECT path FROM "${config.tableName}" WHERE path = '${sqlStr(summaryPath)}' LIMIT 1`);
if (existing.length > 0) {
await memoryApi.query(`DELETE FROM "${config.tableName}" WHERE path = '${sqlStr(summaryPath)}'`);
summariesDeleted++;
}
}
return { sessionsDeleted, summariesDeleted };
}
async function sessionPrune(argv) {
const config = loadConfig();
if (!config) {
console.error("Not logged in. Run: deeplake login");
process.exit(1);
}
const { before, sessionId, all, yes } = parseArgs(argv);
const author = config.userName;
const sessionsApi = new DeeplakeApi(config.token, config.apiUrl, config.orgId, config.workspaceId, config.sessionsTableName);
const sessions = await listSessions(sessionsApi, config.sessionsTableName, author);
if (sessions.length === 0) {
console.log(`No sessions found for author "${author}".`);
return;
}
let targets;
if (sessionId) {
targets = sessions.filter((s) => extractSessionId(s.path) === sessionId);
if (targets.length === 0) {
console.error(`Session not found: ${sessionId}`);
console.error(`
Your sessions:`);
for (const s of sessions.slice(0, 10)) {
console.error(` ${extractSessionId(s.path)} ${s.firstEvent.slice(0, 10)} ${s.project}`);
}
process.exit(1);
}
} else if (before) {
const cutoff = new Date(before);
if (isNaN(cutoff.getTime())) {
console.error(`Invalid date: ${before}`);
process.exit(1);
}
targets = sessions.filter((s) => new Date(s.lastEvent) < cutoff);
} else if (all) {
targets = sessions;
} else {
console.log(`Sessions for "${author}" (${sessions.length} total):
`);
console.log(" Session ID".padEnd(42) + "Date".padEnd(14) + "Events".padEnd(10) + "Project");
console.log(" " + "\u2500".repeat(80));
for (const s of sessions) {
const id = extractSessionId(s.path);
const date = s.firstEvent.slice(0, 10);
console.log(` ${id.padEnd(40)}${date.padEnd(14)}${String(s.rowCount).padEnd(10)}${s.project}`);
}
console.log(`
To delete, use: --all, --before <date>, or --session-id <id>`);
return;
}
if (targets.length === 0) {
console.log("No sessions match the given criteria.");
return;
}
console.log(`Will delete ${targets.length} session(s) for "${author}":
`);
for (const s of targets) {
const id = extractSessionId(s.path);
console.log(` ${id} ${s.firstEvent.slice(0, 10)} ${s.rowCount} events ${s.project}`);
}
console.log();
if (!yes) {
const ok = await confirm("Proceed with deletion?");
if (!ok) {
console.log("Aborted.");
return;
}
}
const { sessionsDeleted, summariesDeleted } = await deleteSessions(config, targets.map((t) => t.path));
console.log(`Deleted ${sessionsDeleted} session(s) and ${summariesDeleted} summary file(s).`);
}
// dist/src/commands/auth-login.js
async function main() {
const args = process.argv.slice(2);
const cmd = args[0] ?? "whoami";
const creds = loadCredentials();
const apiUrl = creds?.apiUrl ?? "https://api.deeplake.ai";
switch (cmd) {
case "login": {
await login(apiUrl);
break;
}
case "whoami": {
if (!creds) {
console.log("Not logged in. Run: node auth-login.js login");