@deeplake/hivemind 0.6.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +20 -0
- package/.claude-plugin/plugin.json +19 -0
- package/LICENSE +201 -0
- package/README.md +359 -0
- package/bundle/cli.js +1051 -0
- package/codex/bundle/capture.js +759 -0
- package/codex/bundle/commands/auth-login.js +862 -0
- package/codex/bundle/package.json +1 -0
- package/codex/bundle/pre-tool-use.js +2097 -0
- package/codex/bundle/session-start-setup.js +585 -0
- package/codex/bundle/session-start.js +129 -0
- package/codex/bundle/shell/deeplake-shell.js +69338 -0
- package/codex/bundle/stop.js +673 -0
- package/codex/bundle/wiki-worker.js +266 -0
- package/codex/skills/deeplake-memory/SKILL.md +65 -0
- package/cursor/bundle/capture.js +485 -0
- package/cursor/bundle/commands/auth-login.js +862 -0
- package/cursor/bundle/package.json +1 -0
- package/cursor/bundle/session-end.js +45 -0
- package/cursor/bundle/session-start.js +520 -0
- package/cursor/bundle/shell/deeplake-shell.js +69338 -0
- package/mcp/bundle/package.json +1 -0
- package/mcp/bundle/server.js +24068 -0
- package/openclaw/README.md +89 -0
- package/openclaw/dist/index.js +1714 -0
- package/openclaw/dist/package.json +1 -0
- package/openclaw/openclaw.plugin.json +56 -0
- package/openclaw/package.json +29 -0
- package/openclaw/skills/SKILL.md +61 -0
- package/package.json +69 -0
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// dist/src/utils/stdin.js
|
|
4
|
+
function readStdin() {
|
|
5
|
+
return new Promise((resolve, reject) => {
|
|
6
|
+
let data = "";
|
|
7
|
+
process.stdin.setEncoding("utf-8");
|
|
8
|
+
process.stdin.on("data", (chunk) => data += chunk);
|
|
9
|
+
process.stdin.on("end", () => {
|
|
10
|
+
try {
|
|
11
|
+
resolve(JSON.parse(data));
|
|
12
|
+
} catch (err) {
|
|
13
|
+
reject(new Error(`Failed to parse hook input: ${err}`));
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
process.stdin.on("error", reject);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// dist/src/config.js
|
|
21
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
22
|
+
import { join } from "node:path";
|
|
23
|
+
import { homedir, userInfo } from "node:os";
|
|
24
|
+
function loadConfig() {
|
|
25
|
+
const home = homedir();
|
|
26
|
+
const credPath = join(home, ".deeplake", "credentials.json");
|
|
27
|
+
let creds = null;
|
|
28
|
+
if (existsSync(credPath)) {
|
|
29
|
+
try {
|
|
30
|
+
creds = JSON.parse(readFileSync(credPath, "utf-8"));
|
|
31
|
+
} catch {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const token = process.env.HIVEMIND_TOKEN ?? creds?.token;
|
|
36
|
+
const orgId = process.env.HIVEMIND_ORG_ID ?? creds?.orgId;
|
|
37
|
+
if (!token || !orgId)
|
|
38
|
+
return null;
|
|
39
|
+
return {
|
|
40
|
+
token,
|
|
41
|
+
orgId,
|
|
42
|
+
orgName: creds?.orgName ?? orgId,
|
|
43
|
+
userName: creds?.userName || userInfo().username || "unknown",
|
|
44
|
+
workspaceId: process.env.HIVEMIND_WORKSPACE_ID ?? creds?.workspaceId ?? "default",
|
|
45
|
+
apiUrl: process.env.HIVEMIND_API_URL ?? creds?.apiUrl ?? "https://api.deeplake.ai",
|
|
46
|
+
tableName: process.env.HIVEMIND_TABLE ?? "memory",
|
|
47
|
+
sessionsTableName: process.env.HIVEMIND_SESSIONS_TABLE ?? "sessions",
|
|
48
|
+
memoryPath: process.env.HIVEMIND_MEMORY_PATH ?? join(home, ".deeplake", "memory")
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// dist/src/deeplake-api.js
|
|
53
|
+
import { randomUUID } from "node:crypto";
|
|
54
|
+
import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "node:fs";
|
|
55
|
+
import { join as join3 } from "node:path";
|
|
56
|
+
import { tmpdir } from "node:os";
|
|
57
|
+
|
|
58
|
+
// dist/src/utils/debug.js
|
|
59
|
+
import { appendFileSync } from "node:fs";
|
|
60
|
+
import { join as join2 } from "node:path";
|
|
61
|
+
import { homedir as homedir2 } from "node:os";
|
|
62
|
+
var DEBUG = process.env.HIVEMIND_DEBUG === "1";
|
|
63
|
+
var LOG = join2(homedir2(), ".deeplake", "hook-debug.log");
|
|
64
|
+
function log(tag, msg) {
|
|
65
|
+
if (!DEBUG)
|
|
66
|
+
return;
|
|
67
|
+
appendFileSync(LOG, `${(/* @__PURE__ */ new Date()).toISOString()} [${tag}] ${msg}
|
|
68
|
+
`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// dist/src/utils/sql.js
|
|
72
|
+
function sqlStr(value) {
|
|
73
|
+
return value.replace(/\\/g, "\\\\").replace(/'/g, "''").replace(/\0/g, "").replace(/[\x01-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "");
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// dist/src/deeplake-api.js
|
|
77
|
+
var log2 = (msg) => log("sdk", msg);
|
|
78
|
+
function summarizeSql(sql, maxLen = 220) {
|
|
79
|
+
const compact = sql.replace(/\s+/g, " ").trim();
|
|
80
|
+
return compact.length > maxLen ? `${compact.slice(0, maxLen)}...` : compact;
|
|
81
|
+
}
|
|
82
|
+
function traceSql(msg) {
|
|
83
|
+
const traceEnabled = process.env.HIVEMIND_TRACE_SQL === "1" || process.env.HIVEMIND_DEBUG === "1";
|
|
84
|
+
if (!traceEnabled)
|
|
85
|
+
return;
|
|
86
|
+
process.stderr.write(`[deeplake-sql] ${msg}
|
|
87
|
+
`);
|
|
88
|
+
if (process.env.HIVEMIND_DEBUG === "1")
|
|
89
|
+
log2(msg);
|
|
90
|
+
}
|
|
91
|
+
var RETRYABLE_CODES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
|
|
92
|
+
var MAX_RETRIES = 3;
|
|
93
|
+
var BASE_DELAY_MS = 500;
|
|
94
|
+
var MAX_CONCURRENCY = 5;
|
|
95
|
+
var QUERY_TIMEOUT_MS = Number(process.env.HIVEMIND_QUERY_TIMEOUT_MS ?? 1e4);
|
|
96
|
+
var INDEX_MARKER_TTL_MS = Number(process.env.HIVEMIND_INDEX_MARKER_TTL_MS ?? 6 * 60 * 6e4);
|
|
97
|
+
function sleep(ms) {
|
|
98
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
99
|
+
}
|
|
100
|
+
function isTimeoutError(error) {
|
|
101
|
+
const name = error instanceof Error ? error.name.toLowerCase() : "";
|
|
102
|
+
const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
|
|
103
|
+
return name.includes("timeout") || name === "aborterror" || message.includes("timeout") || message.includes("timed out");
|
|
104
|
+
}
|
|
105
|
+
function isDuplicateIndexError(error) {
|
|
106
|
+
const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();
|
|
107
|
+
return message.includes("duplicate key value violates unique constraint") || message.includes("pg_class_relname_nsp_index") || message.includes("already exists");
|
|
108
|
+
}
|
|
109
|
+
function isSessionInsertQuery(sql) {
|
|
110
|
+
return /^\s*insert\s+into\s+"[^"]+"\s*\(\s*id\s*,\s*path\s*,\s*filename\s*,\s*message\s*,/i.test(sql);
|
|
111
|
+
}
|
|
112
|
+
function isTransientHtml403(text) {
|
|
113
|
+
const body = text.toLowerCase();
|
|
114
|
+
return body.includes("<html") || body.includes("403 forbidden") || body.includes("cloudflare") || body.includes("nginx");
|
|
115
|
+
}
|
|
116
|
+
function getIndexMarkerDir() {
|
|
117
|
+
return process.env.HIVEMIND_INDEX_MARKER_DIR ?? join3(tmpdir(), "hivemind-deeplake-indexes");
|
|
118
|
+
}
|
|
119
|
+
var Semaphore = class {
|
|
120
|
+
max;
|
|
121
|
+
waiting = [];
|
|
122
|
+
active = 0;
|
|
123
|
+
constructor(max) {
|
|
124
|
+
this.max = max;
|
|
125
|
+
}
|
|
126
|
+
async acquire() {
|
|
127
|
+
if (this.active < this.max) {
|
|
128
|
+
this.active++;
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
await new Promise((resolve) => this.waiting.push(resolve));
|
|
132
|
+
}
|
|
133
|
+
release() {
|
|
134
|
+
this.active--;
|
|
135
|
+
const next = this.waiting.shift();
|
|
136
|
+
if (next) {
|
|
137
|
+
this.active++;
|
|
138
|
+
next();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
var DeeplakeApi = class {
|
|
143
|
+
token;
|
|
144
|
+
apiUrl;
|
|
145
|
+
orgId;
|
|
146
|
+
workspaceId;
|
|
147
|
+
tableName;
|
|
148
|
+
_pendingRows = [];
|
|
149
|
+
_sem = new Semaphore(MAX_CONCURRENCY);
|
|
150
|
+
_tablesCache = null;
|
|
151
|
+
constructor(token, apiUrl, orgId, workspaceId, tableName) {
|
|
152
|
+
this.token = token;
|
|
153
|
+
this.apiUrl = apiUrl;
|
|
154
|
+
this.orgId = orgId;
|
|
155
|
+
this.workspaceId = workspaceId;
|
|
156
|
+
this.tableName = tableName;
|
|
157
|
+
}
|
|
158
|
+
/** Execute SQL with retry on transient errors and bounded concurrency. */
|
|
159
|
+
async query(sql) {
|
|
160
|
+
const startedAt = Date.now();
|
|
161
|
+
const summary = summarizeSql(sql);
|
|
162
|
+
traceSql(`query start: ${summary}`);
|
|
163
|
+
await this._sem.acquire();
|
|
164
|
+
try {
|
|
165
|
+
const rows = await this._queryWithRetry(sql);
|
|
166
|
+
traceSql(`query ok (${Date.now() - startedAt}ms, rows=${rows.length}): ${summary}`);
|
|
167
|
+
return rows;
|
|
168
|
+
} catch (e) {
|
|
169
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
170
|
+
traceSql(`query fail (${Date.now() - startedAt}ms): ${summary} :: ${message}`);
|
|
171
|
+
throw e;
|
|
172
|
+
} finally {
|
|
173
|
+
this._sem.release();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
async _queryWithRetry(sql) {
|
|
177
|
+
let lastError;
|
|
178
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
179
|
+
let resp;
|
|
180
|
+
try {
|
|
181
|
+
const signal = AbortSignal.timeout(QUERY_TIMEOUT_MS);
|
|
182
|
+
resp = await fetch(`${this.apiUrl}/workspaces/${this.workspaceId}/tables/query`, {
|
|
183
|
+
method: "POST",
|
|
184
|
+
headers: {
|
|
185
|
+
Authorization: `Bearer ${this.token}`,
|
|
186
|
+
"Content-Type": "application/json",
|
|
187
|
+
"X-Activeloop-Org-Id": this.orgId
|
|
188
|
+
},
|
|
189
|
+
signal,
|
|
190
|
+
body: JSON.stringify({ query: sql })
|
|
191
|
+
});
|
|
192
|
+
} catch (e) {
|
|
193
|
+
if (isTimeoutError(e)) {
|
|
194
|
+
lastError = new Error(`Query timeout after ${QUERY_TIMEOUT_MS}ms`);
|
|
195
|
+
throw lastError;
|
|
196
|
+
}
|
|
197
|
+
lastError = e instanceof Error ? e : new Error(String(e));
|
|
198
|
+
if (attempt < MAX_RETRIES) {
|
|
199
|
+
const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200;
|
|
200
|
+
log2(`query retry ${attempt + 1}/${MAX_RETRIES} (fetch error: ${lastError.message}) in ${delay.toFixed(0)}ms`);
|
|
201
|
+
await sleep(delay);
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
throw lastError;
|
|
205
|
+
}
|
|
206
|
+
if (resp.ok) {
|
|
207
|
+
const raw = await resp.json();
|
|
208
|
+
if (!raw?.rows || !raw?.columns)
|
|
209
|
+
return [];
|
|
210
|
+
return raw.rows.map((row) => Object.fromEntries(raw.columns.map((col, i) => [col, row[i]])));
|
|
211
|
+
}
|
|
212
|
+
const text = await resp.text().catch(() => "");
|
|
213
|
+
const retryable403 = isSessionInsertQuery(sql) && (resp.status === 401 || resp.status === 403 && (text.length === 0 || isTransientHtml403(text)));
|
|
214
|
+
if (attempt < MAX_RETRIES && (RETRYABLE_CODES.has(resp.status) || retryable403)) {
|
|
215
|
+
const delay = BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200;
|
|
216
|
+
log2(`query retry ${attempt + 1}/${MAX_RETRIES} (${resp.status}) in ${delay.toFixed(0)}ms`);
|
|
217
|
+
await sleep(delay);
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
throw new Error(`Query failed: ${resp.status}: ${text.slice(0, 200)}`);
|
|
221
|
+
}
|
|
222
|
+
throw lastError ?? new Error("Query failed: max retries exceeded");
|
|
223
|
+
}
|
|
224
|
+
// ── Writes ──────────────────────────────────────────────────────────────────
|
|
225
|
+
/** Queue rows for writing. Call commit() to flush. */
|
|
226
|
+
appendRows(rows) {
|
|
227
|
+
this._pendingRows.push(...rows);
|
|
228
|
+
}
|
|
229
|
+
/** Flush pending rows via SQL. */
|
|
230
|
+
async commit() {
|
|
231
|
+
if (this._pendingRows.length === 0)
|
|
232
|
+
return;
|
|
233
|
+
const rows = this._pendingRows;
|
|
234
|
+
this._pendingRows = [];
|
|
235
|
+
const CONCURRENCY = 10;
|
|
236
|
+
for (let i = 0; i < rows.length; i += CONCURRENCY) {
|
|
237
|
+
const chunk = rows.slice(i, i + CONCURRENCY);
|
|
238
|
+
await Promise.allSettled(chunk.map((r) => this.upsertRowSql(r)));
|
|
239
|
+
}
|
|
240
|
+
log2(`commit: ${rows.length} rows`);
|
|
241
|
+
}
|
|
242
|
+
async upsertRowSql(row) {
|
|
243
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
244
|
+
const cd = row.creationDate ?? ts;
|
|
245
|
+
const lud = row.lastUpdateDate ?? ts;
|
|
246
|
+
const exists = await this.query(`SELECT path FROM "${this.tableName}" WHERE path = '${sqlStr(row.path)}' LIMIT 1`);
|
|
247
|
+
if (exists.length > 0) {
|
|
248
|
+
let setClauses = `summary = E'${sqlStr(row.contentText)}', mime_type = '${sqlStr(row.mimeType)}', size_bytes = ${row.sizeBytes}, last_update_date = '${lud}'`;
|
|
249
|
+
if (row.project !== void 0)
|
|
250
|
+
setClauses += `, project = '${sqlStr(row.project)}'`;
|
|
251
|
+
if (row.description !== void 0)
|
|
252
|
+
setClauses += `, description = '${sqlStr(row.description)}'`;
|
|
253
|
+
await this.query(`UPDATE "${this.tableName}" SET ${setClauses} WHERE path = '${sqlStr(row.path)}'`);
|
|
254
|
+
} else {
|
|
255
|
+
const id = randomUUID();
|
|
256
|
+
let cols = "id, path, filename, summary, mime_type, size_bytes, creation_date, last_update_date";
|
|
257
|
+
let vals = `'${id}', '${sqlStr(row.path)}', '${sqlStr(row.filename)}', E'${sqlStr(row.contentText)}', '${sqlStr(row.mimeType)}', ${row.sizeBytes}, '${cd}', '${lud}'`;
|
|
258
|
+
if (row.project !== void 0) {
|
|
259
|
+
cols += ", project";
|
|
260
|
+
vals += `, '${sqlStr(row.project)}'`;
|
|
261
|
+
}
|
|
262
|
+
if (row.description !== void 0) {
|
|
263
|
+
cols += ", description";
|
|
264
|
+
vals += `, '${sqlStr(row.description)}'`;
|
|
265
|
+
}
|
|
266
|
+
await this.query(`INSERT INTO "${this.tableName}" (${cols}) VALUES (${vals})`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/** Update specific columns on a row by path. */
|
|
270
|
+
async updateColumns(path, columns) {
|
|
271
|
+
const setClauses = Object.entries(columns).map(([col, val]) => typeof val === "number" ? `${col} = ${val}` : `${col} = '${sqlStr(String(val))}'`).join(", ");
|
|
272
|
+
await this.query(`UPDATE "${this.tableName}" SET ${setClauses} WHERE path = '${sqlStr(path)}'`);
|
|
273
|
+
}
|
|
274
|
+
// ── Convenience ─────────────────────────────────────────────────────────────
|
|
275
|
+
/** Create a BM25 search index on a column. */
|
|
276
|
+
async createIndex(column) {
|
|
277
|
+
await this.query(`CREATE INDEX IF NOT EXISTS idx_${sqlStr(column)}_bm25 ON "${this.tableName}" USING deeplake_index ("${column}")`);
|
|
278
|
+
}
|
|
279
|
+
buildLookupIndexName(table, suffix) {
|
|
280
|
+
return `idx_${table}_${suffix}`.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
281
|
+
}
|
|
282
|
+
getLookupIndexMarkerPath(table, suffix) {
|
|
283
|
+
const markerKey = [
|
|
284
|
+
this.workspaceId,
|
|
285
|
+
this.orgId,
|
|
286
|
+
table,
|
|
287
|
+
suffix
|
|
288
|
+
].join("__").replace(/[^a-zA-Z0-9_.-]/g, "_");
|
|
289
|
+
return join3(getIndexMarkerDir(), `${markerKey}.json`);
|
|
290
|
+
}
|
|
291
|
+
hasFreshLookupIndexMarker(table, suffix) {
|
|
292
|
+
const markerPath = this.getLookupIndexMarkerPath(table, suffix);
|
|
293
|
+
if (!existsSync2(markerPath))
|
|
294
|
+
return false;
|
|
295
|
+
try {
|
|
296
|
+
const raw = JSON.parse(readFileSync2(markerPath, "utf-8"));
|
|
297
|
+
const updatedAt = raw.updatedAt ? new Date(raw.updatedAt).getTime() : NaN;
|
|
298
|
+
if (!Number.isFinite(updatedAt) || Date.now() - updatedAt > INDEX_MARKER_TTL_MS)
|
|
299
|
+
return false;
|
|
300
|
+
return true;
|
|
301
|
+
} catch {
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
markLookupIndexReady(table, suffix) {
|
|
306
|
+
mkdirSync(getIndexMarkerDir(), { recursive: true });
|
|
307
|
+
writeFileSync(this.getLookupIndexMarkerPath(table, suffix), JSON.stringify({ updatedAt: (/* @__PURE__ */ new Date()).toISOString() }), "utf-8");
|
|
308
|
+
}
|
|
309
|
+
async ensureLookupIndex(table, suffix, columnsSql) {
|
|
310
|
+
if (this.hasFreshLookupIndexMarker(table, suffix))
|
|
311
|
+
return;
|
|
312
|
+
const indexName = this.buildLookupIndexName(table, suffix);
|
|
313
|
+
try {
|
|
314
|
+
await this.query(`CREATE INDEX IF NOT EXISTS "${indexName}" ON "${table}" ${columnsSql}`);
|
|
315
|
+
this.markLookupIndexReady(table, suffix);
|
|
316
|
+
} catch (e) {
|
|
317
|
+
if (isDuplicateIndexError(e)) {
|
|
318
|
+
this.markLookupIndexReady(table, suffix);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
log2(`index "${indexName}" skipped: ${e.message}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
/** List all tables in the workspace (with retry). */
|
|
325
|
+
async listTables(forceRefresh = false) {
|
|
326
|
+
if (!forceRefresh && this._tablesCache)
|
|
327
|
+
return [...this._tablesCache];
|
|
328
|
+
const { tables, cacheable } = await this._fetchTables();
|
|
329
|
+
if (cacheable)
|
|
330
|
+
this._tablesCache = [...tables];
|
|
331
|
+
return tables;
|
|
332
|
+
}
|
|
333
|
+
async _fetchTables() {
|
|
334
|
+
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
335
|
+
try {
|
|
336
|
+
const resp = await fetch(`${this.apiUrl}/workspaces/${this.workspaceId}/tables`, {
|
|
337
|
+
headers: {
|
|
338
|
+
Authorization: `Bearer ${this.token}`,
|
|
339
|
+
"X-Activeloop-Org-Id": this.orgId
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
if (resp.ok) {
|
|
343
|
+
const data = await resp.json();
|
|
344
|
+
return {
|
|
345
|
+
tables: (data.tables ?? []).map((t) => t.table_name),
|
|
346
|
+
cacheable: true
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
if (attempt < MAX_RETRIES && RETRYABLE_CODES.has(resp.status)) {
|
|
350
|
+
await sleep(BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * 200);
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
return { tables: [], cacheable: false };
|
|
354
|
+
} catch {
|
|
355
|
+
if (attempt < MAX_RETRIES) {
|
|
356
|
+
await sleep(BASE_DELAY_MS * Math.pow(2, attempt));
|
|
357
|
+
continue;
|
|
358
|
+
}
|
|
359
|
+
return { tables: [], cacheable: false };
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
return { tables: [], cacheable: false };
|
|
363
|
+
}
|
|
364
|
+
/** Create the memory table if it doesn't already exist. Migrate columns on existing tables. */
|
|
365
|
+
async ensureTable(name) {
|
|
366
|
+
const tbl = name ?? this.tableName;
|
|
367
|
+
const tables = await this.listTables();
|
|
368
|
+
if (!tables.includes(tbl)) {
|
|
369
|
+
log2(`table "${tbl}" not found, creating`);
|
|
370
|
+
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`);
|
|
371
|
+
log2(`table "${tbl}" created`);
|
|
372
|
+
if (!tables.includes(tbl))
|
|
373
|
+
this._tablesCache = [...tables, tbl];
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
/** Create the sessions table (uses JSONB for message since every row is a JSON event). */
|
|
377
|
+
async ensureSessionsTable(name) {
|
|
378
|
+
const tables = await this.listTables();
|
|
379
|
+
if (!tables.includes(name)) {
|
|
380
|
+
log2(`table "${name}" not found, creating`);
|
|
381
|
+
await this.query(`CREATE TABLE IF NOT EXISTS "${name}" (id TEXT NOT NULL DEFAULT '', path TEXT NOT NULL DEFAULT '', filename TEXT NOT NULL DEFAULT '', message JSONB, 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 '') USING deeplake`);
|
|
382
|
+
log2(`table "${name}" created`);
|
|
383
|
+
if (!tables.includes(name))
|
|
384
|
+
this._tablesCache = [...tables, name];
|
|
385
|
+
}
|
|
386
|
+
await this.ensureLookupIndex(name, "path_creation_date", `("path", "creation_date")`);
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
// dist/src/utils/session-path.js
|
|
391
|
+
function buildSessionPath(config, sessionId) {
|
|
392
|
+
const workspace = config.workspaceId ?? "default";
|
|
393
|
+
return `/sessions/${config.userName}/${config.userName}_${config.orgName}_${workspace}_${sessionId}.jsonl`;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// dist/src/hooks/cursor/capture.js
|
|
397
|
+
var log3 = (msg) => log("cursor-capture", msg);
|
|
398
|
+
var CAPTURE = process.env.HIVEMIND_CAPTURE !== "false";
|
|
399
|
+
function resolveCwd(input) {
|
|
400
|
+
if (typeof input.cwd === "string" && input.cwd)
|
|
401
|
+
return input.cwd;
|
|
402
|
+
const roots = input.workspace_roots;
|
|
403
|
+
if (Array.isArray(roots) && roots.length > 0 && typeof roots[0] === "string")
|
|
404
|
+
return roots[0];
|
|
405
|
+
return "";
|
|
406
|
+
}
|
|
407
|
+
async function main() {
|
|
408
|
+
if (!CAPTURE)
|
|
409
|
+
return;
|
|
410
|
+
const input = await readStdin();
|
|
411
|
+
const config = loadConfig();
|
|
412
|
+
if (!config) {
|
|
413
|
+
log3("no config");
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
const sessionId = input.conversation_id ?? `cursor-${Date.now()}`;
|
|
417
|
+
const event = input.hook_event_name ?? "";
|
|
418
|
+
const cwd = resolveCwd(input);
|
|
419
|
+
const sessionsTable = config.sessionsTableName;
|
|
420
|
+
const api = new DeeplakeApi(config.token, config.apiUrl, config.orgId, config.workspaceId, sessionsTable);
|
|
421
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
422
|
+
const meta = {
|
|
423
|
+
session_id: sessionId,
|
|
424
|
+
transcript_path: input.transcript_path,
|
|
425
|
+
cwd,
|
|
426
|
+
hook_event_name: event,
|
|
427
|
+
model: input.model,
|
|
428
|
+
timestamp: ts
|
|
429
|
+
};
|
|
430
|
+
let entry = null;
|
|
431
|
+
if (event === "beforeSubmitPrompt" && typeof input.prompt === "string") {
|
|
432
|
+
log3(`user session=${sessionId}`);
|
|
433
|
+
entry = { id: crypto.randomUUID(), ...meta, type: "user_message", content: input.prompt };
|
|
434
|
+
} else if (event === "postToolUse" && typeof input.tool_name === "string") {
|
|
435
|
+
log3(`tool=${input.tool_name} session=${sessionId}`);
|
|
436
|
+
entry = {
|
|
437
|
+
id: crypto.randomUUID(),
|
|
438
|
+
...meta,
|
|
439
|
+
type: "tool_call",
|
|
440
|
+
tool_name: input.tool_name,
|
|
441
|
+
tool_use_id: input.tool_use_id,
|
|
442
|
+
tool_input: JSON.stringify(input.tool_input),
|
|
443
|
+
// Cursor delivers tool_output as a JSON-encoded string already.
|
|
444
|
+
tool_response: typeof input.tool_output === "string" ? input.tool_output : JSON.stringify(input.tool_output)
|
|
445
|
+
};
|
|
446
|
+
} else if (event === "afterAgentResponse" && typeof input.text === "string") {
|
|
447
|
+
log3(`assistant session=${sessionId}`);
|
|
448
|
+
entry = { id: crypto.randomUUID(), ...meta, type: "assistant_message", content: input.text };
|
|
449
|
+
} else if (event === "stop") {
|
|
450
|
+
log3(`stop session=${sessionId} status=${input.status ?? "unknown"}`);
|
|
451
|
+
entry = {
|
|
452
|
+
id: crypto.randomUUID(),
|
|
453
|
+
...meta,
|
|
454
|
+
type: "stop",
|
|
455
|
+
status: input.status,
|
|
456
|
+
loop_count: input.loop_count
|
|
457
|
+
};
|
|
458
|
+
} else {
|
|
459
|
+
log3(`unknown event: ${event}, skipping`);
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
const sessionPath = buildSessionPath(config, sessionId);
|
|
463
|
+
const line = JSON.stringify(entry);
|
|
464
|
+
log3(`writing to ${sessionPath}`);
|
|
465
|
+
const projectName = cwd.split("/").pop() || "unknown";
|
|
466
|
+
const filename = sessionPath.split("/").pop() ?? "";
|
|
467
|
+
const jsonForSql = line.replace(/'/g, "''");
|
|
468
|
+
const insertSql = `INSERT INTO "${sessionsTable}" (id, path, filename, message, author, size_bytes, project, description, agent, creation_date, last_update_date) VALUES ('${crypto.randomUUID()}', '${sqlStr(sessionPath)}', '${sqlStr(filename)}', '${jsonForSql}'::jsonb, '${sqlStr(config.userName)}', ${Buffer.byteLength(line, "utf-8")}, '${sqlStr(projectName)}', '${sqlStr(event)}', 'cursor', '${ts}', '${ts}')`;
|
|
469
|
+
try {
|
|
470
|
+
await api.query(insertSql);
|
|
471
|
+
} catch (e) {
|
|
472
|
+
if (e.message?.includes("permission denied") || e.message?.includes("does not exist")) {
|
|
473
|
+
log3("table missing, creating and retrying");
|
|
474
|
+
await api.ensureSessionsTable(sessionsTable);
|
|
475
|
+
await api.query(insertSql);
|
|
476
|
+
} else {
|
|
477
|
+
throw e;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
log3("capture ok \u2192 cloud");
|
|
481
|
+
}
|
|
482
|
+
main().catch((e) => {
|
|
483
|
+
log3(`fatal: ${e.message}`);
|
|
484
|
+
process.exit(0);
|
|
485
|
+
});
|