@deeplake/hivemind 0.6.47 → 0.6.48

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