@rubytech/create-maxy 1.0.806 → 1.0.808

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.
Files changed (30) hide show
  1. package/package.json +1 -1
  2. package/payload/platform/neo4j/migrations/004-project-admin-agent.ts +247 -0
  3. package/payload/platform/neo4j/migrations/004-prune-alien-accounts.ts +134 -0
  4. package/payload/platform/plugins/admin/skills/onboarding/SKILL.md +2 -0
  5. package/payload/platform/plugins/docs/references/cloudflare.md +1 -0
  6. package/payload/platform/plugins/docs/references/graph.md +42 -0
  7. package/payload/platform/plugins/docs/references/internals.md +3 -1
  8. package/payload/platform/plugins/docs/references/memory-guide.md +4 -0
  9. package/payload/platform/plugins/docs/references/troubleshooting.md +19 -1
  10. package/payload/platform/plugins/memory/mcp/dist/tools/profile-read.d.ts.map +1 -1
  11. package/payload/platform/plugins/memory/mcp/dist/tools/profile-read.js +19 -0
  12. package/payload/platform/plugins/memory/mcp/dist/tools/profile-read.js.map +1 -1
  13. package/payload/platform/templates/agents/admin/IDENTITY.md +4 -1
  14. package/payload/platform/templates/agents/admin/SOUL.md +2 -0
  15. package/payload/server/chunk-CRWLE6BZ.js +3511 -0
  16. package/payload/server/chunk-LSUMH6OF.js +9993 -0
  17. package/payload/server/chunk-V3VLAL7N.js +10009 -0
  18. package/payload/server/chunk-YULDSPAC.js +3484 -0
  19. package/payload/server/client-pool-LXE7RIRT.js +31 -0
  20. package/payload/server/client-pool-N2Y57223.js +31 -0
  21. package/payload/server/maxy-edge.js +5 -4
  22. package/payload/server/neo4j-migrations-HEECOAGK.js +128 -0
  23. package/payload/server/public/assets/admin-MxaCgGHZ.js +352 -0
  24. package/payload/server/public/assets/{graph-CBu0rtrP.js → graph-CDwy6Qw1.js} +1 -1
  25. package/payload/server/public/assets/page-DEyK-lSN.js +50 -0
  26. package/payload/server/public/graph.html +2 -2
  27. package/payload/server/public/index.html +2 -2
  28. package/payload/server/server.js +658 -278
  29. package/payload/server/public/assets/admin-BYsaXlDv.js +0 -352
  30. package/payload/server/public/assets/page-BNM63zsb.js +0 -50
@@ -0,0 +1,3484 @@
1
+ // app/lib/claude-agent/client-pool.ts
2
+ import { query } from "@anthropic-ai/claude-agent-sdk";
3
+ import { appendFileSync as appendFileSync2 } from "fs";
4
+ import { resolve as resolvePath } from "path";
5
+
6
+ // app/lib/claude-agent/logging.ts
7
+ import { spawnSync } from "child_process";
8
+ import { resolve } from "path";
9
+ import { platform as osPlatform } from "os";
10
+ import { readFileSync, readdirSync, mkdirSync, createWriteStream, statSync, unlinkSync, renameSync, appendFileSync, existsSync } from "fs";
11
+ import { lookup as dnsLookup } from "dns/promises";
12
+ import { createConnection as netConnect } from "net";
13
+ import { StringDecoder } from "string_decoder";
14
+ var LOG_RETENTION_DAYS = 7;
15
+ var isoTs = () => (/* @__PURE__ */ new Date()).toISOString();
16
+ var BROWSER_TOOL_PREFIXES = [
17
+ "mcp__plugin_playwright_playwright__",
18
+ "mcp__plugin_chrome-devtools-mcp_chrome-devtools__"
19
+ ];
20
+ function isBrowserTool(name) {
21
+ return BROWSER_TOOL_PREFIXES.some((p) => name.startsWith(p));
22
+ }
23
+ var DIAG_HARD_CAP_MS = 5e3;
24
+ var DIAG_DNS_TIMEOUT_MS = 2e3;
25
+ var DIAG_TCP_TIMEOUT_MS = 3e3;
26
+ var DIAG_HTTP_TIMEOUT_MS = 4e3;
27
+ function quoteDiag(value) {
28
+ return JSON.stringify(value);
29
+ }
30
+ function extractUrl(toolName, input) {
31
+ if (input === null || typeof input !== "object") return void 0;
32
+ const obj = input;
33
+ if (toolName === "WebFetch" && typeof obj.url === "string") return obj.url;
34
+ if (isBrowserTool(toolName) && typeof obj.url === "string") return obj.url;
35
+ if (typeof obj.url === "string" && /^https?:\/\//.test(obj.url)) return obj.url;
36
+ return void 0;
37
+ }
38
+ var FULL_REDACT_ENV_VARS = /* @__PURE__ */ new Set(["HTTPS_PROXY", "HTTP_PROXY", "NO_PROXY"]);
39
+ function redactEnvField(name) {
40
+ const value = process.env[name];
41
+ if (!value) return `${name.toLowerCase()}=absent`;
42
+ if (FULL_REDACT_ENV_VARS.has(name)) {
43
+ return `${name.toLowerCase()}=present`;
44
+ }
45
+ const suffix = value.length > 40 ? value.slice(-40) : value;
46
+ return `${name.toLowerCase()}=present suffix=${quoteDiag(suffix)}`;
47
+ }
48
+ async function probeDns(host, family) {
49
+ const label = family === 4 ? "dns_a" : "dns_aaaa";
50
+ const start = Date.now();
51
+ let timer;
52
+ try {
53
+ const result = await Promise.race([
54
+ dnsLookup(host, { family, verbatim: true }),
55
+ new Promise((_, reject) => {
56
+ timer = setTimeout(() => reject(new Error("timeout")), DIAG_DNS_TIMEOUT_MS);
57
+ })
58
+ ]);
59
+ if (timer) clearTimeout(timer);
60
+ const ms = Date.now() - start;
61
+ return `${label}=${result.address} ${label}_ms=${ms}`;
62
+ } catch (err) {
63
+ if (timer) clearTimeout(timer);
64
+ const ms = Date.now() - start;
65
+ const msg = err instanceof Error ? err.message : String(err);
66
+ return `${label}=err ${label}_err=${quoteDiag(msg.slice(0, 60))} ${label}_ms=${ms}`;
67
+ }
68
+ }
69
+ async function probeTcp(host, port) {
70
+ const start = Date.now();
71
+ return new Promise((resolvePromise) => {
72
+ let settled = false;
73
+ const sock = netConnect({ host, port, family: 0 });
74
+ const finish = (result) => {
75
+ if (settled) return;
76
+ settled = true;
77
+ try {
78
+ sock.destroy();
79
+ } catch {
80
+ }
81
+ resolvePromise(result);
82
+ };
83
+ const timer = setTimeout(() => finish(`tcp=timeout tcp_ms=${Date.now() - start}`), DIAG_TCP_TIMEOUT_MS);
84
+ sock.once("connect", () => {
85
+ clearTimeout(timer);
86
+ finish(`tcp=ok tcp_ms=${Date.now() - start}`);
87
+ });
88
+ sock.once("error", (err) => {
89
+ clearTimeout(timer);
90
+ const msg = err instanceof Error ? err.message : String(err);
91
+ finish(`tcp=err tcp_err=${quoteDiag(msg.slice(0, 60))} tcp_ms=${Date.now() - start}`);
92
+ });
93
+ });
94
+ }
95
+ async function probeHttp(url) {
96
+ const start = Date.now();
97
+ const controller = new AbortController();
98
+ const timer = setTimeout(() => controller.abort(), DIAG_HTTP_TIMEOUT_MS);
99
+ try {
100
+ const res = await fetch(url, { method: "HEAD", redirect: "manual", signal: controller.signal });
101
+ clearTimeout(timer);
102
+ return `http_status=${res.status} http_ms=${Date.now() - start}`;
103
+ } catch (err) {
104
+ clearTimeout(timer);
105
+ const msg = err instanceof Error ? err.message : String(err);
106
+ return `http_status=err http_err=${quoteDiag(msg.slice(0, 60))} http_ms=${Date.now() - start}`;
107
+ }
108
+ }
109
+ async function runFailureDiagnostic(toolName, toolInput) {
110
+ const inputKeys = toolInput !== null && typeof toolInput === "object" ? Object.keys(toolInput).join(",") : "";
111
+ const envFields = [
112
+ redactEnvField("HTTPS_PROXY"),
113
+ redactEnvField("HTTP_PROXY"),
114
+ redactEnvField("NO_PROXY"),
115
+ redactEnvField("NODE_OPTIONS")
116
+ ].join(" ");
117
+ const url = extractUrl(toolName, toolInput);
118
+ if (!url) {
119
+ return `diag_url=none input_keys=[${inputKeys}] ${envFields}`;
120
+ }
121
+ let host;
122
+ let port;
123
+ try {
124
+ const parsed = new URL(url);
125
+ host = parsed.hostname;
126
+ port = parsed.port ? Number(parsed.port) : parsed.protocol === "https:" ? 443 : 80;
127
+ } catch {
128
+ return `diag_url=unparseable input_keys=[${inputKeys}] ${envFields}`;
129
+ }
130
+ const probes = Promise.allSettled([
131
+ probeDns(host, 4),
132
+ probeDns(host, 6),
133
+ probeTcp(host, port),
134
+ probeHttp(url)
135
+ ]);
136
+ let capTimer;
137
+ const capped = await Promise.race([
138
+ probes,
139
+ new Promise((resolvePromise) => {
140
+ capTimer = setTimeout(() => resolvePromise("__diag_timeout__"), DIAG_HARD_CAP_MS);
141
+ })
142
+ ]);
143
+ if (capTimer) clearTimeout(capTimer);
144
+ if (capped === "__diag_timeout__") {
145
+ return `diag_host=${host} diag_port=${port} diag_timeout=true input_keys=[${inputKeys}] ${envFields}`;
146
+ }
147
+ const fields = capped.map((r) => r.status === "fulfilled" ? r.value : `probe_err=${quoteDiag(String(r.reason).slice(0, 40))}`).join(" ");
148
+ return `diag_host=${host} diag_port=${port} ${fields} input_keys=[${inputKeys}] ${envFields}`;
149
+ }
150
+ function agentLogStream(name, accountDir, conversationId) {
151
+ if (!conversationId) {
152
+ throw new Error(`agentLogStream: conversationId is required (name=${name}) \u2014 use preConversationLogStream for pre-session events`);
153
+ }
154
+ const logDir = resolve(accountDir, "logs");
155
+ mkdirSync(logDir, { recursive: true });
156
+ purgeOldLogs(logDir, `${name}-`);
157
+ const logPath = resolve(logDir, `${name}-${conversationId}.log`);
158
+ const stream = createWriteStream(logPath, { flags: "a" });
159
+ registerStreamLog(stream, { path: logPath, conversationId, name });
160
+ return stream;
161
+ }
162
+ function preConversationLogStream(name, accountDir) {
163
+ const logDir = resolve(accountDir, "logs");
164
+ mkdirSync(logDir, { recursive: true });
165
+ const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
166
+ purgeOldLogs(logDir, `preconversation-${name}-`);
167
+ const logPath = resolve(logDir, `preconversation-${name}-${date}.log`);
168
+ const stream = createWriteStream(logPath, { flags: "a" });
169
+ registerStreamLog(stream, { path: logPath, conversationId: null, name: `preconversation-${name}` });
170
+ return stream;
171
+ }
172
+ var openStreamLogs = /* @__PURE__ */ new Map();
173
+ function registerStreamLog(stream, entry) {
174
+ openStreamLogs.set(stream, entry);
175
+ stream.once("close", () => {
176
+ openStreamLogs.delete(stream);
177
+ });
178
+ }
179
+ function sigtermFlushStreamLogs(reason, source) {
180
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
181
+ for (const entry of openStreamLogs.values()) {
182
+ const convPart = entry.conversationId ? ` conversationId=${entry.conversationId}` : "";
183
+ const line = `[${ts}] [server-sigterm] reason=${reason}${convPart} name=${entry.name} source=${source}
184
+ `;
185
+ try {
186
+ appendFileSync(entry.path, line);
187
+ } catch (err) {
188
+ const msg = err instanceof Error ? err.message : String(err);
189
+ console.error(`[server-sigterm-flush-err] path=${entry.path} reason=${msg}`);
190
+ }
191
+ }
192
+ }
193
+ function purgeOldLogs(logDir, prefix) {
194
+ const cutoff = Date.now() - LOG_RETENTION_DAYS * 24 * 60 * 60 * 1e3;
195
+ let entries;
196
+ try {
197
+ entries = readdirSync(logDir);
198
+ } catch (err) {
199
+ const msg = err instanceof Error ? err.message : String(err);
200
+ console.error(`[log-purge-err] readdir dir=${logDir} prefix=${prefix} reason=${msg}`);
201
+ return;
202
+ }
203
+ for (const file of entries) {
204
+ if (!file.startsWith(prefix)) continue;
205
+ const filePath = resolve(logDir, file);
206
+ try {
207
+ if (statSync(filePath).mtimeMs < cutoff) unlinkSync(filePath);
208
+ } catch (err) {
209
+ const msg = err instanceof Error ? err.message : String(err);
210
+ console.error(`[log-purge-err] file=${file} reason=${msg}`);
211
+ }
212
+ }
213
+ }
214
+ function preflushStreamLogKey(sessionKey) {
215
+ return `preflush-${sessionKey.slice(0, 12)}`;
216
+ }
217
+ function renameStreamLogsOnFlush(accountDir, sessionKey, conversationId) {
218
+ const STREAM_LOG_NAMES = ["claude-agent-stream", "claude-agent-stderr", "public-agent-stream"];
219
+ const logDir = resolve(accountDir, "logs");
220
+ const preflushSuffix = preflushStreamLogKey(sessionKey);
221
+ const sk8 = sessionKey.slice(0, 8);
222
+ const cid8 = conversationId.slice(0, 8);
223
+ for (const name of STREAM_LOG_NAMES) {
224
+ const fromPath = resolve(logDir, `${name}-${preflushSuffix}.log`);
225
+ const toPath = resolve(logDir, `${name}-${conversationId}.log`);
226
+ let result;
227
+ let reason = "";
228
+ try {
229
+ if (!existsSync(fromPath)) {
230
+ result = "skipped";
231
+ reason = "no-preflush-file";
232
+ } else {
233
+ const targetExisted = existsSync(toPath);
234
+ renameSync(fromPath, toPath);
235
+ for (const entry of openStreamLogs.values()) {
236
+ if (entry.path === fromPath) {
237
+ entry.path = toPath;
238
+ entry.conversationId = conversationId;
239
+ }
240
+ }
241
+ result = "renamed";
242
+ if (targetExisted) reason = "target-existed";
243
+ }
244
+ } catch (err) {
245
+ result = "error";
246
+ reason = err instanceof Error ? err.message : String(err);
247
+ }
248
+ const reasonPart = reason ? ` reason=${JSON.stringify(reason)}` : "";
249
+ console.log(`[stream-log-rename] ${(/* @__PURE__ */ new Date()).toISOString()} sessionKey=${sk8} conversationId=${cid8} name=${name} result=${result}${reasonPart}`);
250
+ if (result === "renamed" && existsSync(fromPath)) {
251
+ console.error(`[stream-log-rename] ${(/* @__PURE__ */ new Date()).toISOString()} outcome=stale-sibling preflush=${JSON.stringify(fromPath)} full=${JSON.stringify(toPath)} reason=${JSON.stringify("rename succeeded but preflush still present")} sessionKey=${sk8} conversationId=${cid8} name=${name}`);
252
+ }
253
+ }
254
+ }
255
+
256
+ // app/lib/claude-agent/session-store.ts
257
+ import { resolve as resolve4 } from "path";
258
+
259
+ // app/lib/neo4j-store.ts
260
+ import neo4j from "neo4j-driver";
261
+ import { randomUUID } from "crypto";
262
+ import { spawn as spawn2 } from "child_process";
263
+ import { readFileSync as readFileSync2, readdirSync as readdirSync2, existsSync as existsSync2, openSync, readSync, closeSync, statSync as statSync2, rmSync } from "fs";
264
+ import { resolve as resolve2 } from "path";
265
+
266
+ // ../lib/models/src/index.ts
267
+ var OPUS_MODEL = "claude-opus-4-7";
268
+ var SONNET_MODEL = "claude-sonnet-4-6";
269
+ var HAIKU_MODEL = "claude-haiku-4-5";
270
+ var MODEL_CONTEXT_WINDOW = {
271
+ [OPUS_MODEL]: 2e5,
272
+ [SONNET_MODEL]: 2e5,
273
+ [HAIKU_MODEL]: 2e5
274
+ };
275
+ function contextWindow(model) {
276
+ return MODEL_CONTEXT_WINDOW[model] ?? 2e5;
277
+ }
278
+
279
+ // app/lib/neo4j-store.ts
280
+ var PLATFORM_ROOT = process.env.MAXY_PLATFORM_ROOT ?? resolve2(process.cwd(), "..");
281
+ var driver = null;
282
+ function readPassword() {
283
+ if (process.env.NEO4J_PASSWORD) return process.env.NEO4J_PASSWORD;
284
+ const passwordFile = resolve2(PLATFORM_ROOT, "config/.neo4j-password");
285
+ try {
286
+ return readFileSync2(passwordFile, "utf-8").trim();
287
+ } catch {
288
+ throw new Error(
289
+ `Neo4j password not found. Expected at ${passwordFile} or in NEO4J_PASSWORD env var.`
290
+ );
291
+ }
292
+ }
293
+ function getDriver() {
294
+ if (!driver) {
295
+ const uri = process.env.NEO4J_URI;
296
+ if (!uri) {
297
+ throw new Error(
298
+ "[ui/neo4j-store] NEO4J_URI unset \u2014 refusing to default to bolt://localhost:7687 (Task 580)"
299
+ );
300
+ }
301
+ const user = process.env.NEO4J_USER ?? "neo4j";
302
+ const password = readPassword();
303
+ console.error(`[ui/neo4j-store] resolved neo4j_uri=${uri}`);
304
+ driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {
305
+ maxConnectionPoolSize: 5
306
+ });
307
+ }
308
+ return driver;
309
+ }
310
+ function getSession() {
311
+ return getDriver().session();
312
+ }
313
+ async function runBootMigrations() {
314
+ const { applyBootMigrations } = await import("./neo4j-migrations-HEECOAGK.js");
315
+ await applyBootMigrations(getDriver(), PLATFORM_ROOT);
316
+ }
317
+ process.on("SIGINT", async () => {
318
+ if (driver) {
319
+ await driver.close();
320
+ driver = null;
321
+ }
322
+ });
323
+ var OLLAMA_URL = process.env.OLLAMA_URL ?? "http://localhost:11434";
324
+ var EMBED_MODEL = process.env.EMBED_MODEL ?? "nomic-embed-text";
325
+ async function embed(text) {
326
+ const res = await fetch(`${OLLAMA_URL}/api/embed`, {
327
+ method: "POST",
328
+ headers: { "Content-Type": "application/json" },
329
+ body: JSON.stringify({ model: EMBED_MODEL, input: text }),
330
+ signal: AbortSignal.timeout(5e3)
331
+ });
332
+ if (!res.ok) {
333
+ const body = await res.text();
334
+ throw new Error(`Ollama embedding failed (${res.status}): ${body}`);
335
+ }
336
+ const data = await res.json();
337
+ return data.embeddings[0];
338
+ }
339
+ var sessionStoreRef = null;
340
+ function setSessionStoreRef(ref) {
341
+ sessionStoreRef = ref;
342
+ }
343
+ function getCachedConversationId(sessionKey) {
344
+ return sessionStoreRef?.get(sessionKey)?.conversationId;
345
+ }
346
+ function cacheConversationId(sessionKey, conversationId) {
347
+ const session = sessionStoreRef?.get(sessionKey);
348
+ if (session) {
349
+ session.conversationId = conversationId;
350
+ }
351
+ }
352
+ var GREETING_DIRECTIVE = "[New session. Greet the visitor.]";
353
+ var DIRECTIVE_PREFIX = "[New session.";
354
+ async function ensureConversation(accountId, agentType, sessionKey, visitorId, agentSlug, userId) {
355
+ const cached = getCachedConversationId(sessionKey);
356
+ if (cached) return { conversationId: cached, created: false };
357
+ const conversationId = randomUUID();
358
+ const channel = sessionKey.startsWith("whatsapp:") ? "whatsapp" : sessionKey.startsWith("telegram:") ? "telegram" : "webchat";
359
+ const conversationSublabel = agentType === "admin" ? "AdminConversation" : "PublicConversation";
360
+ const handlerSlug = agentSlug ?? (agentType === "admin" ? "admin" : null);
361
+ const wantsHandledByEdge = !!handlerSlug;
362
+ const handledByClause = wantsHandledByEdge ? `WITH c, created
363
+ OPTIONAL MATCH (a:Agent {accountId: $accountId, slug: $handlerSlug})
364
+ FOREACH (_ IN CASE WHEN a IS NULL THEN [] ELSE [1] END | MERGE (c)-[:HANDLED_BY]->(a))
365
+ RETURN c.conversationId AS conversationId, created AS created, a IS NOT NULL AS handledBy` : `RETURN c.conversationId AS conversationId, created AS created, false AS handledBy`;
366
+ const session = getSession();
367
+ try {
368
+ const result = await session.run(
369
+ `OPTIONAL MATCH (existing:Conversation {sessionKey: $sessionKey})
370
+ WITH existing, existing IS NULL AS created
371
+ MERGE (c:Conversation {sessionKey: $sessionKey})
372
+ ON CREATE SET
373
+ c:${conversationSublabel},
374
+ c.conversationId = $conversationId,
375
+ c.accountId = $accountId,
376
+ c.agentType = $agentType,
377
+ c.channel = $channel,
378
+ ${visitorId ? "c.visitorId = $visitorId," : ""}
379
+ ${agentSlug ? "c.agentSlug = $agentSlug," : ""}
380
+ ${userId ? "c.userId = $userId," : ""}
381
+ c.createdAt = datetime(),
382
+ c.updatedAt = datetime()
383
+ ON MATCH SET
384
+ c.updatedAt = datetime()
385
+ ${handledByClause}`,
386
+ {
387
+ sessionKey,
388
+ conversationId,
389
+ accountId,
390
+ agentType,
391
+ channel,
392
+ ...visitorId ? { visitorId } : {},
393
+ ...agentSlug ? { agentSlug } : {},
394
+ ...handlerSlug ? { handlerSlug } : {},
395
+ ...userId ? { userId } : {}
396
+ }
397
+ );
398
+ const id = result.records[0]?.get("conversationId");
399
+ const created = result.records[0]?.get("created") === true;
400
+ if (id) {
401
+ cacheConversationId(sessionKey, id);
402
+ console.error(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} conversation attributed: conversationId=${id.slice(0, 8)}\u2026 userId=${userId ?? "none"} ${agentType}/${accountId.slice(0, 8)}\u2026 sublabel=${conversationSublabel}`);
403
+ if (wantsHandledByEdge) {
404
+ const handled = result.records[0]?.get("handledBy");
405
+ const id8 = id.slice(0, 8);
406
+ if (handled === true) {
407
+ console.error(`[agent-graph] handled-by-write conversationId=${id8} slug=${handlerSlug}`);
408
+ } else {
409
+ console.error(`[agent-graph] handled-by-skip reason=no-agent-node conversationId=${id8} slug=${handlerSlug}`);
410
+ }
411
+ }
412
+ }
413
+ return { conversationId: id ?? null, created };
414
+ } catch (err) {
415
+ console.error(`[persist] ensureConversation failed: ${err instanceof Error ? err.message : String(err)}`);
416
+ return { conversationId: null, created: false };
417
+ } finally {
418
+ await session.close();
419
+ }
420
+ }
421
+ async function findRecentConversation(visitorId, accountId, agentSlug, maxAgeHours = 24) {
422
+ const session = getSession();
423
+ try {
424
+ const result = await session.run(
425
+ `MATCH (c:Conversation {visitorId: $visitorId, accountId: $accountId, agentType: 'public'})
426
+ WHERE c.agentSlug = $agentSlug
427
+ AND c.updatedAt > datetime() - duration({hours: $maxAgeHours})
428
+ RETURN c.conversationId AS conversationId, c.sessionKey AS sessionKey
429
+ ORDER BY c.updatedAt DESC
430
+ LIMIT 1`,
431
+ { visitorId, accountId, agentSlug, maxAgeHours: neo4j.int(maxAgeHours) },
432
+ { timeout: 2e3 }
433
+ );
434
+ const record = result.records[0];
435
+ if (!record) return null;
436
+ const conversationId = record.get("conversationId");
437
+ const sessionKey = record.get("sessionKey");
438
+ if (!conversationId) return null;
439
+ console.log(`[persist] found recent conversation ${conversationId.slice(0, 8)}\u2026 for visitor ${visitorId.slice(0, 8)}\u2026`);
440
+ return { conversationId, sessionKey };
441
+ } catch (err) {
442
+ console.error(`[persist] findRecentConversation failed: ${err instanceof Error ? err.message : String(err)}`);
443
+ return null;
444
+ } finally {
445
+ await session.close();
446
+ }
447
+ }
448
+ async function findGroupBySlug(groupSlug, accountId) {
449
+ const session = getSession();
450
+ try {
451
+ const result = await session.run(
452
+ `MATCH (c:Conversation {groupSlug: $groupSlug, accountId: $accountId, type: 'group'})
453
+ RETURN c.conversationId AS conversationId, c.groupName AS groupName, c.agentSlug AS agentSlug`,
454
+ { groupSlug, accountId },
455
+ { timeout: 2e3 }
456
+ );
457
+ const record = result.records[0];
458
+ if (!record) return null;
459
+ return {
460
+ conversationId: record.get("conversationId"),
461
+ groupName: record.get("groupName"),
462
+ agentSlug: record.get("agentSlug")
463
+ };
464
+ } catch (err) {
465
+ console.error(`[group] findGroupBySlug failed: ${err instanceof Error ? err.message : String(err)}`);
466
+ return null;
467
+ } finally {
468
+ await session.close();
469
+ }
470
+ }
471
+ async function getGroupParticipants(conversationId) {
472
+ const session = getSession();
473
+ try {
474
+ const result = await session.run(
475
+ `MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {conversationId: $conversationId})
476
+ RETURN p.givenName AS givenName, p.familyName AS familyName,
477
+ r.displayName AS displayName, r.joinedAt AS joinedAt, r.visitorId AS visitorId`,
478
+ { conversationId }
479
+ );
480
+ return result.records.map((r) => ({
481
+ displayName: r.get("displayName") || r.get("givenName"),
482
+ givenName: r.get("givenName"),
483
+ familyName: r.get("familyName"),
484
+ joinedAt: String(r.get("joinedAt")),
485
+ visitorId: r.get("visitorId")
486
+ }));
487
+ } catch (err) {
488
+ console.error(`[group] getGroupParticipants failed: ${err instanceof Error ? err.message : String(err)}`);
489
+ return [];
490
+ } finally {
491
+ await session.close();
492
+ }
493
+ }
494
+ async function checkGroupMembership(conversationId, visitorId) {
495
+ const session = getSession();
496
+ try {
497
+ const result = await session.run(
498
+ `MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {conversationId: $conversationId})
499
+ WHERE r.visitorId = $visitorId
500
+ RETURN r.displayName AS displayName
501
+ LIMIT 1`,
502
+ { conversationId, visitorId }
503
+ );
504
+ return result.records[0]?.get("displayName") ?? null;
505
+ } catch (err) {
506
+ console.error(`[group] checkGroupMembership failed: ${err instanceof Error ? err.message : String(err)}`);
507
+ return null;
508
+ } finally {
509
+ await session.close();
510
+ }
511
+ }
512
+ async function bindVisitorToGroup(conversationId, visitorId, personEmail, personPhone) {
513
+ const session = getSession();
514
+ try {
515
+ const result = await session.run(
516
+ `MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {conversationId: $conversationId})
517
+ WHERE ($email IS NOT NULL AND p.email = $email)
518
+ OR ($phone IS NOT NULL AND p.telephone = $phone)
519
+ SET r.visitorId = $visitorId
520
+ RETURN r.displayName AS displayName
521
+ LIMIT 1`,
522
+ {
523
+ conversationId,
524
+ visitorId,
525
+ email: personEmail ?? null,
526
+ phone: personPhone ?? null
527
+ }
528
+ );
529
+ const name = result.records[0]?.get("displayName");
530
+ if (name) {
531
+ console.error(`[group] joined id=${conversationId.slice(0, 8)}\u2026 visitor=${visitorId.slice(0, 8)}\u2026`);
532
+ } else {
533
+ console.error(`[group] auth-denied id=${conversationId.slice(0, 8)}\u2026 visitor=${visitorId.slice(0, 8)}\u2026`);
534
+ }
535
+ return name ? { displayName: name } : null;
536
+ } catch (err) {
537
+ console.error(`[group] bindVisitorToGroup failed: ${err instanceof Error ? err.message : String(err)}`);
538
+ return null;
539
+ } finally {
540
+ await session.close();
541
+ }
542
+ }
543
+ async function getMessagesSince(conversationId, since, limit = 100) {
544
+ const session = getSession();
545
+ try {
546
+ const result = await session.run(
547
+ `MATCH (m:Message)-[:PART_OF]->(c:Conversation {conversationId: $conversationId})
548
+ WHERE m.createdAt > datetime($since)
549
+ RETURN m.messageId AS messageId, m.role AS role, m.content AS content,
550
+ m.senderName AS senderName, m.senderVisitorId AS senderVisitorId,
551
+ m.createdAt AS createdAt
552
+ ORDER BY m.createdAt ASC
553
+ LIMIT $limit`,
554
+ { conversationId, since, limit: neo4j.int(limit) },
555
+ { timeout: 3e3 }
556
+ );
557
+ return result.records.map((r) => ({
558
+ messageId: r.get("messageId"),
559
+ role: r.get("role"),
560
+ content: r.get("content"),
561
+ senderName: r.get("senderName"),
562
+ senderVisitorId: r.get("senderVisitorId"),
563
+ createdAt: String(r.get("createdAt"))
564
+ }));
565
+ } catch (err) {
566
+ console.error(`[group] getMessagesSince failed: ${err instanceof Error ? err.message : String(err)}`);
567
+ return [];
568
+ } finally {
569
+ await session.close();
570
+ }
571
+ }
572
+ async function getGroupMessagesForContext(conversationId, limit = 50) {
573
+ const session = getSession();
574
+ try {
575
+ const result = await session.run(
576
+ `MATCH (m:Message)-[:PART_OF]->(c:Conversation {conversationId: $conversationId})
577
+ WITH m ORDER BY m.createdAt DESC LIMIT $limit
578
+ RETURN m.role AS role, m.content AS content, m.senderName AS senderName
579
+ ORDER BY m.createdAt ASC`,
580
+ { conversationId, limit: neo4j.int(limit) }
581
+ );
582
+ return result.records.map((r) => ({
583
+ role: r.get("role"),
584
+ content: r.get("content"),
585
+ senderName: r.get("senderName")
586
+ }));
587
+ } catch (err) {
588
+ console.error(`[group] getGroupMessagesForContext failed: ${err instanceof Error ? err.message : String(err)}`);
589
+ return [];
590
+ } finally {
591
+ await session.close();
592
+ }
593
+ }
594
+ async function backfillNullUserIdConversations(userId) {
595
+ if (!userId) {
596
+ console.warn(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: skipped \u2014 no userId provided (no Owner in users.json?)`);
597
+ return 0;
598
+ }
599
+ const session = getSession();
600
+ try {
601
+ const result = await session.run(
602
+ `MATCH (c:Conversation {agentType: 'admin'})
603
+ WHERE c.userId IS NULL
604
+ SET c.userId = $userId
605
+ RETURN count(c) AS updated`,
606
+ { userId }
607
+ );
608
+ const updated = result.records[0]?.get("updated")?.toNumber?.() ?? result.records[0]?.get("updated") ?? 0;
609
+ if (updated > 0) {
610
+ console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: set userId on ${updated} admin conversations`);
611
+ } else {
612
+ console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: no orphaned admin conversations found`);
613
+ }
614
+ return typeof updated === "number" ? updated : 0;
615
+ } catch (err) {
616
+ console.error(`[session] backfillNullUserIdConversations failed: ${err instanceof Error ? err.message : String(err)}`);
617
+ return 0;
618
+ } finally {
619
+ await session.close();
620
+ }
621
+ }
622
+ async function createNewAdminConversation(userId, accountId, sessionKey, adminName) {
623
+ if (!userId || !sessionKey || !accountId) {
624
+ console.error(`[admin/conversation-write] schema-violation userId=${userId ? "set" : "EMPTY"} sessionKey=${sessionKey ? "set" : "EMPTY"} accountId=${accountId ? "set" : "EMPTY"}`);
625
+ return null;
626
+ }
627
+ const conversationId = randomUUID();
628
+ const session = getSession();
629
+ try {
630
+ const result = await session.run(
631
+ `OPTIONAL MATCH (existing:AdminUser {userId: $userId})
632
+ WITH existing IS NULL AS adminUserCreated
633
+ MERGE (au:AdminUser {userId: $userId})
634
+ ON CREATE SET au.accountId = $accountId,
635
+ au.name = COALESCE($adminName, 'Admin'),
636
+ au.createdAt = datetime(),
637
+ au.scope = 'admin'
638
+ CREATE (c:Conversation:AdminConversation {
639
+ conversationId: $conversationId,
640
+ sessionKey: $sessionKey,
641
+ accountId: $accountId,
642
+ agentType: 'admin',
643
+ userId: $userId,
644
+ createdBySource: 'admin-conversation',
645
+ createdAt: datetime(),
646
+ updatedAt: datetime()
647
+ })-[:STARTED_BY]->(au)
648
+ RETURN adminUserCreated`,
649
+ { conversationId, sessionKey, accountId, userId, adminName: adminName ?? null }
650
+ );
651
+ const adminUserCreated = result.records[0]?.get("adminUserCreated") === true;
652
+ cacheConversationId(sessionKey, conversationId);
653
+ console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} conversation created: conversationId=${conversationId.slice(0, 8)}\u2026 sessionKey=${sessionKey.slice(0, 8)}\u2026 accountId=${accountId.slice(0, 8)}\u2026 userId=${userId} agentType=admin createdBySource=admin-conversation createdAt=set updatedAt=set sublabel=AdminConversation adminUserCreated=${adminUserCreated}`);
654
+ return conversationId;
655
+ } catch (err) {
656
+ console.error(`[session] createNewAdminConversation failed: ${err instanceof Error ? err.message : String(err)}`);
657
+ return null;
658
+ } finally {
659
+ await session.close();
660
+ }
661
+ }
662
+ var HEX_COLOR_RE = /^#[0-9a-fA-F]{3,8}$/;
663
+ async function fetchBranding(accountId) {
664
+ const session = getSession();
665
+ try {
666
+ const result = await session.run(
667
+ `MATCH (b:LocalBusiness {accountId: $accountId})
668
+ OPTIONAL MATCH (b)-[:HAS_BRAND_ASSET]->(logo:ImageObject {purpose: "logo"})
669
+ OPTIONAL MATCH (b)-[:HAS_BRAND_ASSET]->(icon:ImageObject {purpose: "icon"})
670
+ RETURN b.name AS name,
671
+ b.primaryColor AS primaryColor,
672
+ b.accentColor AS accentColor,
673
+ b.backgroundColor AS backgroundColor,
674
+ b.tagline AS tagline,
675
+ logo.contentUrl AS logoUrl,
676
+ icon.contentUrl AS faviconUrl`,
677
+ { accountId },
678
+ { timeout: 2e3 }
679
+ );
680
+ const record = result.records[0];
681
+ if (!record) return null;
682
+ const name = record.get("name");
683
+ if (!name) return null;
684
+ const primaryColor = record.get("primaryColor");
685
+ const accentColor = record.get("accentColor");
686
+ const backgroundColor = record.get("backgroundColor");
687
+ const tagline = record.get("tagline");
688
+ const logoUrl = record.get("logoUrl");
689
+ const faviconUrl = record.get("faviconUrl");
690
+ const hasBranding = primaryColor || accentColor || backgroundColor || tagline || logoUrl || faviconUrl;
691
+ if (!hasBranding) return null;
692
+ const branding = { name };
693
+ if (primaryColor && HEX_COLOR_RE.test(primaryColor)) branding.primaryColor = primaryColor;
694
+ if (accentColor && HEX_COLOR_RE.test(accentColor)) branding.accentColor = accentColor;
695
+ if (backgroundColor && HEX_COLOR_RE.test(backgroundColor)) branding.backgroundColor = backgroundColor;
696
+ if (tagline) branding.tagline = tagline;
697
+ if (logoUrl) branding.logoUrl = logoUrl;
698
+ if (faviconUrl) branding.faviconUrl = faviconUrl;
699
+ console.error(`[branding] resolved for accountId=${accountId.slice(0, 8)}\u2026: primary=${branding.primaryColor ?? "\u2013"} logo=${branding.logoUrl ? "yes" : "no"}`);
700
+ return branding;
701
+ } catch (err) {
702
+ console.error(`[branding] fetchBranding failed for accountId=${accountId.slice(0, 8)}\u2026: ${err instanceof Error ? err.message : String(err)}`);
703
+ return null;
704
+ } finally {
705
+ await session.close();
706
+ }
707
+ }
708
+ async function persistToolCall(record) {
709
+ const session = getSession();
710
+ try {
711
+ const optionalFields = [
712
+ record.pluginName != null ? ", pluginName: $pluginName" : "",
713
+ record.error != null ? ", error: $error" : "",
714
+ record.subagentType != null ? ", subagentType: $subagentType" : "",
715
+ record.subagentDescription != null ? ", subagentDescription: $subagentDescription" : "",
716
+ record.approvalState != null ? ", approvalState: $approvalState" : "",
717
+ record.originalInput != null ? ", originalInput: $originalInput" : ""
718
+ ].join("");
719
+ const res = await session.run(
720
+ `MATCH (c:Conversation {conversationId: $conversationId})
721
+ CREATE (c)-[:HAS_TOOL_CALL]->(tc:ToolCall {
722
+ callId: $callId,
723
+ toolName: $toolName,
724
+ input: $input,
725
+ output: $output,
726
+ isError: $isError,
727
+ agentType: $agentType,
728
+ accountId: $accountId,
729
+ conversationId: $conversationId,
730
+ createdBySource: 'persist-tool-call',
731
+ createdBySession: $conversationId,
732
+ startedAt: datetime($startedAt),
733
+ completedAt: datetime($completedAt)
734
+ ${optionalFields}
735
+ })`,
736
+ {
737
+ callId: record.callId,
738
+ toolName: record.toolName,
739
+ input: record.input,
740
+ output: record.output,
741
+ isError: record.isError,
742
+ agentType: record.agentType,
743
+ accountId: record.accountId,
744
+ conversationId: record.conversationId,
745
+ startedAt: record.startedAt,
746
+ completedAt: record.completedAt,
747
+ ...record.pluginName != null ? { pluginName: record.pluginName } : {},
748
+ ...record.error != null ? { error: record.error } : {},
749
+ ...record.subagentType != null ? { subagentType: record.subagentType } : {},
750
+ ...record.subagentDescription != null ? { subagentDescription: record.subagentDescription } : {},
751
+ ...record.approvalState != null ? { approvalState: record.approvalState } : {},
752
+ ...record.originalInput != null ? { originalInput: record.originalInput } : {}
753
+ }
754
+ );
755
+ if (res.summary.counters.updates().nodesCreated === 0) {
756
+ console.error(
757
+ `[persist] tool-call skipped: conversation ${record.conversationId.slice(0, 8)}\u2026 not found for tool=${record.toolName}`
758
+ );
759
+ return;
760
+ }
761
+ console.error(`[persist] tool-call persisted: name=${record.toolName} conversation=${record.conversationId.slice(0, 8)}\u2026${record.approvalState ? ` approval=${record.approvalState}` : ""}`);
762
+ } catch (err) {
763
+ console.error(`[persist] tool-call write failed: name=${record.toolName} error=${err instanceof Error ? err.message : String(err)}`);
764
+ } finally {
765
+ await session.close();
766
+ }
767
+ }
768
+ var SUMMARY_MAX_LEN = 200;
769
+ var persistMessageLocks = /* @__PURE__ */ new Map();
770
+ async function persistMessage(conversationId, role, content, accountId, tokens, createdAt, sender, components, attachments) {
771
+ if (!content) return null;
772
+ const messageId = randomUUID();
773
+ const summary = role === "user" ? content.slice(0, SUMMARY_MAX_LEN).trim() : "";
774
+ let embedding = null;
775
+ try {
776
+ embedding = await embed(content);
777
+ } catch (err) {
778
+ console.error(`[persist] Embedding failed, storing without: ${err instanceof Error ? err.message : String(err)}`);
779
+ }
780
+ const prev = persistMessageLocks.get(conversationId);
781
+ const waited = prev !== void 0;
782
+ let release;
783
+ const mine = new Promise((resolve5) => {
784
+ release = resolve5;
785
+ });
786
+ const chained = (prev ?? Promise.resolve()).then(() => mine);
787
+ persistMessageLocks.set(conversationId, chained);
788
+ await prev;
789
+ const session = getSession();
790
+ try {
791
+ const result = await session.run(
792
+ `MATCH (c:Conversation {conversationId: $conversationId})
793
+ OPTIONAL MATCH (tail:Message)-[:PART_OF]->(c)
794
+ WHERE NOT (tail)-[:NEXT]->(:Message)
795
+ AND (tail:UserMessage OR tail:AssistantMessage)
796
+ // Task 857 \u2014 sublabel-scope the tail to the agent-path's own sublabels.
797
+ // Without this, a Task-857 :WhatsAppMessage row (no outgoing :NEXT)
798
+ // would be picked as tail and the agent-path would chain
799
+ // :WhatsAppMessage\u2192:UserMessage, crossing the live-channel chain.
800
+ // The live writer's tail predicate is sublabel-scoped to
801
+ // :WhatsAppMessage; this clause is the matching defence on the
802
+ // agent side. Backward-compatible \u2014 pre-Task-857 graphs only carry
803
+ // UserMessage/AssistantMessage sublabels under :Message.
804
+ // Capture whether THIS write's guard will fire. Read c.summary
805
+ // before the SET so the boolean reflects the pre-state, not the
806
+ // post-state \u2014 a false positive otherwise when a new user message
807
+ // happens to equal an already-set summary (verbatim retry, short
808
+ // catchphrase) and fooled a post-state equality check.
809
+ WITH c, tail, (c.summary IS NULL AND $role = 'user' AND $summary <> '') AS summarySetThisWrite
810
+ CREATE (m:Message:${role === "user" ? "UserMessage" : "AssistantMessage"} {
811
+ messageId: $messageId,
812
+ conversationId: $conversationId,
813
+ accountId: $accountId,
814
+ role: $role,
815
+ content: $content,
816
+ createdAt: ${createdAt ? "datetime($createdAt)" : "datetime()"}
817
+ ${embedding ? ", embedding: $embedding" : ""}
818
+ ${sender ? ", senderVisitorId: $senderVisitorId, senderName: $senderName" : ""}
819
+ ${tokens?.inputTokens != null ? ", inputTokens: $inputTokens" : ""}
820
+ ${tokens?.outputTokens != null ? ", outputTokens: $outputTokens" : ""}
821
+ ${tokens?.cacheReadTokens != null ? ", cacheReadTokens: $cacheReadTokens" : ""}
822
+ ${tokens?.cacheCreationTokens != null ? ", cacheCreationTokens: $cacheCreationTokens" : ""}
823
+ })
824
+ SET c.updatedAt = datetime()
825
+ CREATE (m)-[:PART_OF]->(c)
826
+ FOREACH (prev IN CASE WHEN tail IS NULL THEN [] ELSE [tail] END |
827
+ CREATE (prev)-[:NEXT]->(m)
828
+ )
829
+ FOREACH (_ IN CASE WHEN summarySetThisWrite THEN [1] ELSE [] END |
830
+ SET c.summary = $summary
831
+ )
832
+ FOREACH (comp IN $components |
833
+ CREATE (m)-[:HAS_COMPONENT]->(:Component {
834
+ componentId: comp.componentId,
835
+ conversationId: $conversationId,
836
+ accountId: $accountId,
837
+ messageId: $messageId,
838
+ name: comp.name,
839
+ data: comp.data,
840
+ ordinal: comp.ordinal,
841
+ textOffset: comp.textOffset,
842
+ submitted: false,
843
+ createdAt: datetime()
844
+ })
845
+ )
846
+ FOREACH (att IN $attachments |
847
+ CREATE (m)-[:HAS_ATTACHMENT]->(:Attachment {
848
+ attachmentId: att.attachmentId,
849
+ conversationId: $conversationId,
850
+ accountId: $accountId,
851
+ messageId: $messageId,
852
+ filename: att.filename,
853
+ mimeType: att.mimeType,
854
+ sizeBytes: att.sizeBytes,
855
+ storagePath: att.storagePath,
856
+ ordinal: att.ordinal,
857
+ createdAt: datetime()
858
+ })
859
+ )
860
+ RETURN tail.messageId AS prevMessageId,
861
+ summarySetThisWrite,
862
+ size([(m2:Message)-[:PART_OF]->(c) | m2]) AS chainLen`,
863
+ {
864
+ messageId,
865
+ conversationId,
866
+ accountId,
867
+ role,
868
+ content,
869
+ summary,
870
+ ...createdAt ? { createdAt } : {},
871
+ ...embedding ? { embedding } : {},
872
+ ...sender ? { senderVisitorId: sender.visitorId, senderName: sender.displayName } : {},
873
+ ...tokens?.inputTokens != null ? { inputTokens: neo4j.int(tokens.inputTokens) } : {},
874
+ ...tokens?.outputTokens != null ? { outputTokens: neo4j.int(tokens.outputTokens) } : {},
875
+ ...tokens?.cacheReadTokens != null ? { cacheReadTokens: neo4j.int(tokens.cacheReadTokens) } : {},
876
+ ...tokens?.cacheCreationTokens != null ? { cacheCreationTokens: neo4j.int(tokens.cacheCreationTokens) } : {},
877
+ components: (components ?? []).map((comp) => ({
878
+ componentId: comp.componentId,
879
+ name: comp.name,
880
+ data: comp.data,
881
+ ordinal: neo4j.int(comp.ordinal),
882
+ textOffset: neo4j.int(comp.textOffset)
883
+ })),
884
+ attachments: (attachments ?? []).map((att) => ({
885
+ attachmentId: att.attachmentId,
886
+ filename: att.filename,
887
+ mimeType: att.mimeType,
888
+ sizeBytes: neo4j.int(att.sizeBytes),
889
+ storagePath: att.storagePath,
890
+ ordinal: neo4j.int(att.ordinal)
891
+ }))
892
+ }
893
+ );
894
+ if (result.records.length === 0) {
895
+ console.error(`[persist] Neo4j write skipped \u2014 conversation not found: ${conversationId.slice(0, 8)}\u2026`);
896
+ return null;
897
+ }
898
+ const record = result.records[0];
899
+ const prevMessageId = record.get("prevMessageId") ?? null;
900
+ const summarySetThisWrite = record.get("summarySetThisWrite") === true;
901
+ const chainLenRaw = record.get("chainLen");
902
+ const chainLen = typeof chainLenRaw === "bigint" ? Number(chainLenRaw) : typeof chainLenRaw?.toNumber === "function" ? chainLenRaw.toNumber() : Number(chainLenRaw ?? 0);
903
+ const messageSublabel = role === "user" ? "UserMessage" : "AssistantMessage";
904
+ console.error(`[neo4j-store] append-message conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 prev=${prevMessageId ? prevMessageId.slice(0, 8) + "\u2026" : "null"} chainLen=${chainLen} waited=${waited} sublabel=${messageSublabel}`);
905
+ if (summarySetThisWrite) {
906
+ console.error(`[neo4j-store] conversation-summary-set conversationId=${conversationId.slice(0, 8)}\u2026 len=${summary.length}`);
907
+ }
908
+ const componentList = components ?? [];
909
+ if (componentList.length > 0) {
910
+ const relsCreated = result.summary.counters.updates().relationshipsCreated;
911
+ const expectedComponentEdges = componentList.length;
912
+ const baseEdges = relsCreated - expectedComponentEdges;
913
+ if (baseEdges < 1) {
914
+ console.error(`[neo4j-store] persist-component WARN conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 relsCreated=${relsCreated} expected\u2265${1 + expectedComponentEdges} \u2014 component edges may not have been created`);
915
+ }
916
+ for (const comp of componentList) {
917
+ console.error(`[neo4j-store] persist-component conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 componentId=${comp.componentId.slice(0, 8)}\u2026 name=${comp.name} dataLen=${comp.data.length} ordinal=${comp.ordinal} textOffset=${comp.textOffset}`);
918
+ }
919
+ }
920
+ const attachmentList = attachments ?? [];
921
+ if (attachmentList.length > 0) {
922
+ const relsCreated = result.summary.counters.updates().relationshipsCreated;
923
+ const expectedAttachmentEdges = attachmentList.length;
924
+ const expectedComponentEdges = (components ?? []).length;
925
+ const baseEdges = relsCreated - expectedComponentEdges - expectedAttachmentEdges;
926
+ if (baseEdges < 1) {
927
+ console.error(`[neo4j-store] persist-attachment WARN conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 relsCreated=${relsCreated} expected\u2265${1 + expectedComponentEdges + expectedAttachmentEdges} \u2014 attachment edges may not have been created`);
928
+ }
929
+ for (const att of attachmentList) {
930
+ console.error(`[neo4j-store] persist-attachment conversationId=${conversationId.slice(0, 8)}\u2026 messageId=${messageId.slice(0, 8)}\u2026 attachmentId=${att.attachmentId.slice(0, 8)}\u2026 filename=${att.filename} mimeType=${att.mimeType} sizeBytes=${att.sizeBytes} ordinal=${att.ordinal}`);
931
+ }
932
+ }
933
+ console.error(`[persist] ${(/* @__PURE__ */ new Date()).toISOString()} conversationId=${conversationId.slice(0, 8)}\u2026 role=${role} len=${content.length}${sender ? ` sender=${sender.displayName}` : ""}`);
934
+ return messageId;
935
+ } catch (err) {
936
+ console.error(`[persist] Neo4j write failed: ${err instanceof Error ? err.message : String(err)}`);
937
+ return null;
938
+ } finally {
939
+ release();
940
+ if (persistMessageLocks.get(conversationId) === chained) {
941
+ persistMessageLocks.delete(conversationId);
942
+ }
943
+ await session.close();
944
+ }
945
+ }
946
+ async function setConversationAgentSessionId(conversationId, agentSessionId) {
947
+ const prev = persistMessageLocks.get(conversationId);
948
+ let release;
949
+ const mine = new Promise((resolve5) => {
950
+ release = resolve5;
951
+ });
952
+ const chained = (prev ?? Promise.resolve()).then(() => mine);
953
+ persistMessageLocks.set(conversationId, chained);
954
+ await prev;
955
+ const session = getSession();
956
+ try {
957
+ const result = await session.run(
958
+ `MATCH (c:Conversation {conversationId: $conversationId})
959
+ SET c.agentSessionId = $agentSessionId
960
+ RETURN c.conversationId AS conversationId`,
961
+ { conversationId, agentSessionId }
962
+ );
963
+ if (result.records.length === 0) {
964
+ console.error(`[persist] agent-session-id convId=${conversationId.slice(0, 8)}\u2026 status=skipped reason=conversation-not-found`);
965
+ return false;
966
+ }
967
+ console.log(`[persist] agent-session-id convId=${conversationId.slice(0, 8)}\u2026 status=ok agentSessionId=${agentSessionId ? agentSessionId.slice(0, 8) + "\u2026" : "null"}`);
968
+ return true;
969
+ } catch (err) {
970
+ console.error(`[persist] agent-session-id convId=${conversationId.slice(0, 8)}\u2026 status=failed error=${err instanceof Error ? err.message : String(err)}`);
971
+ return false;
972
+ } finally {
973
+ release();
974
+ if (persistMessageLocks.get(conversationId) === chained) {
975
+ persistMessageLocks.delete(conversationId);
976
+ }
977
+ await session.close();
978
+ }
979
+ }
980
+ async function getAgentSessionIdForConversation(conversationId) {
981
+ const session = getSession();
982
+ try {
983
+ const result = await session.run(
984
+ `MATCH (c:Conversation {conversationId: $conversationId})
985
+ RETURN c.agentSessionId AS agentSessionId`,
986
+ { conversationId }
987
+ );
988
+ const value = result.records[0]?.get("agentSessionId");
989
+ return typeof value === "string" && value.length > 0 ? value : null;
990
+ } catch (err) {
991
+ console.error(`[persist] agent-session-id read failed convId=${conversationId.slice(0, 8)}\u2026 error=${err instanceof Error ? err.message : String(err)}`);
992
+ return null;
993
+ } finally {
994
+ await session.close();
995
+ }
996
+ }
997
+ async function getRecentMessages(conversationId, limit = 50) {
998
+ const session = getSession();
999
+ try {
1000
+ const result = await session.run(
1001
+ `MATCH (tail:Message {conversationId: $conversationId})
1002
+ WHERE NOT (tail)-[:NEXT]->(:Message)
1003
+ WITH tail ORDER BY tail.createdAt DESC LIMIT 1
1004
+ MATCH path = (m:Message)-[:NEXT*0..]->(tail)
1005
+ WHERE m.conversationId = $conversationId
1006
+ AND length(path) < $limit
1007
+ WITH m, length(path) AS depthFromTail
1008
+ OPTIONAL MATCH (m)-[:HAS_COMPONENT]->(c:Component)
1009
+ WITH m, depthFromTail, c ORDER BY c.ordinal ASC
1010
+ WITH m, depthFromTail,
1011
+ [comp IN collect(c) WHERE comp IS NOT NULL | comp {.*}] AS components
1012
+ OPTIONAL MATCH (m)-[:HAS_ATTACHMENT]->(a:Attachment)
1013
+ WITH m, depthFromTail, components, a ORDER BY a.ordinal ASC
1014
+ WITH m, depthFromTail, components,
1015
+ [att IN collect(a) WHERE att IS NOT NULL | att {.*}] AS attachments
1016
+ RETURN m.messageId AS messageId, m.role AS role, m.content AS content,
1017
+ m.createdAt AS createdAt, components, attachments
1018
+ ORDER BY depthFromTail DESC`,
1019
+ { conversationId, limit: neo4j.int(limit) }
1020
+ );
1021
+ return result.records.map((r) => {
1022
+ const rawComponents = r.get("components") ?? [];
1023
+ const components = rawComponents.map((c) => ({
1024
+ componentId: String(c.componentId ?? ""),
1025
+ name: String(c.name ?? ""),
1026
+ data: String(c.data ?? ""),
1027
+ ordinal: typeof c.ordinal?.toNumber === "function" ? c.ordinal.toNumber() : Number(c.ordinal ?? 0),
1028
+ textOffset: typeof c.textOffset?.toNumber === "function" ? c.textOffset.toNumber() : Number(c.textOffset ?? 0),
1029
+ submitted: c.submitted === true
1030
+ }));
1031
+ const rawAttachments = r.get("attachments") ?? [];
1032
+ const attachments = rawAttachments.map((a) => ({
1033
+ attachmentId: String(a.attachmentId ?? ""),
1034
+ filename: String(a.filename ?? ""),
1035
+ mimeType: String(a.mimeType ?? ""),
1036
+ sizeBytes: typeof a.sizeBytes?.toNumber === "function" ? a.sizeBytes.toNumber() : Number(a.sizeBytes ?? 0),
1037
+ storagePath: String(a.storagePath ?? ""),
1038
+ ordinal: typeof a.ordinal?.toNumber === "function" ? a.ordinal.toNumber() : Number(a.ordinal ?? 0),
1039
+ accountId: String(a.accountId ?? "")
1040
+ }));
1041
+ return {
1042
+ messageId: r.get("messageId"),
1043
+ role: r.get("role"),
1044
+ content: r.get("content"),
1045
+ createdAt: String(r.get("createdAt")),
1046
+ components,
1047
+ attachments
1048
+ };
1049
+ });
1050
+ } catch (err) {
1051
+ console.error(`[persist] getRecentMessages failed: ${err instanceof Error ? err.message : String(err)}`);
1052
+ return [];
1053
+ } finally {
1054
+ await session.close();
1055
+ }
1056
+ }
1057
+ async function markComponentSubmitted(conversationId, componentName, accountId) {
1058
+ const session = getSession();
1059
+ try {
1060
+ const result = await session.run(
1061
+ `MATCH (conv:Conversation {conversationId: $conversationId, accountId: $accountId})
1062
+ MATCH (m:Message)-[:PART_OF]->(conv)
1063
+ MATCH (m)-[:HAS_COMPONENT]->(c:Component {name: $componentName, accountId: $accountId})
1064
+ WHERE c.submitted = false OR c.submitted IS NULL
1065
+ WITH c, m ORDER BY m.createdAt DESC, c.ordinal DESC
1066
+ LIMIT 1
1067
+ SET c.submitted = true, c.submittedAt = datetime()
1068
+ RETURN c.componentId AS componentId`,
1069
+ { conversationId, componentName, accountId }
1070
+ );
1071
+ const componentId = result.records[0]?.get("componentId");
1072
+ if (componentId) {
1073
+ console.error(`[neo4j-store] component-submitted conversationId=${conversationId.slice(0, 8)}\u2026 name=${componentName} componentId=${componentId.slice(0, 8)}\u2026`);
1074
+ return componentId;
1075
+ }
1076
+ console.error(`[neo4j-store] component-submit-skipped conversationId=${conversationId.slice(0, 8)}\u2026 name=${componentName} reason=no-unsubmitted-match`);
1077
+ return null;
1078
+ } catch (err) {
1079
+ console.error(`[neo4j-store] component-submit-failed conversationId=${conversationId.slice(0, 8)}\u2026 name=${componentName} error=${err instanceof Error ? err.message : String(err)}`);
1080
+ return null;
1081
+ } finally {
1082
+ await session.close();
1083
+ }
1084
+ }
1085
+ async function verifyConversationOwnership(conversationId, accountId) {
1086
+ const session = getSession();
1087
+ try {
1088
+ const result = await session.run(
1089
+ `MATCH (c:Conversation {conversationId: $conversationId, accountId: $accountId})
1090
+ RETURN c.conversationId AS id LIMIT 1`,
1091
+ { conversationId, accountId }
1092
+ );
1093
+ return result.records.length > 0;
1094
+ } catch (err) {
1095
+ console.error(`[persist] verifyConversationOwnership failed: ${err instanceof Error ? err.message : String(err)}`);
1096
+ return false;
1097
+ } finally {
1098
+ await session.close();
1099
+ }
1100
+ }
1101
+ async function verifyAndGetConversationUpdatedAt(conversationId, accountId) {
1102
+ const session = getSession();
1103
+ try {
1104
+ const result = await session.run(
1105
+ `MATCH (c:Conversation {conversationId: $conversationId, accountId: $accountId})
1106
+ RETURN toString(c.updatedAt) AS updatedAt LIMIT 1`,
1107
+ { conversationId, accountId }
1108
+ );
1109
+ const record = result.records[0];
1110
+ return record ? record.get("updatedAt") : null;
1111
+ } catch (err) {
1112
+ console.error(`[persist] verifyAndGetConversationUpdatedAt failed: ${err instanceof Error ? err.message : String(err)}`);
1113
+ return null;
1114
+ } finally {
1115
+ await session.close();
1116
+ }
1117
+ }
1118
+ async function searchMessages(accountId, queryEmbedding, limit = 10) {
1119
+ const session = getSession();
1120
+ try {
1121
+ const result = await session.run(
1122
+ `CALL db.index.vector.queryNodes('message_embedding', $limit, $embedding)
1123
+ YIELD node, score
1124
+ WHERE node.accountId = $accountId
1125
+ RETURN node.messageId AS messageId,
1126
+ node.role AS role,
1127
+ node.content AS content,
1128
+ node.conversationId AS conversationId,
1129
+ node.createdAt AS createdAt,
1130
+ score
1131
+ ORDER BY score DESC
1132
+ LIMIT $limit`,
1133
+ { embedding: queryEmbedding, limit: neo4j.int(limit), accountId }
1134
+ );
1135
+ return result.records.map((r) => ({
1136
+ messageId: r.get("messageId"),
1137
+ role: r.get("role"),
1138
+ content: r.get("content"),
1139
+ conversationId: r.get("conversationId"),
1140
+ createdAt: String(r.get("createdAt")),
1141
+ score: typeof r.get("score") === "number" ? r.get("score") : Number(r.get("score"))
1142
+ }));
1143
+ } catch (err) {
1144
+ console.error(`[persist] searchMessages failed: ${err instanceof Error ? err.message : String(err)}`);
1145
+ return [];
1146
+ } finally {
1147
+ await session.close();
1148
+ }
1149
+ }
1150
+ var LIST_BACKFILL_CAP = 3;
1151
+ async function listAdminSessions(accountId, userId, limit = 20) {
1152
+ const session = getSession();
1153
+ try {
1154
+ const result = await session.run(
1155
+ `MATCH (c:Conversation {accountId: $accountId, agentType: 'admin', userId: $userId})
1156
+ WITH c
1157
+ ORDER BY c.updatedAt DESC
1158
+ LIMIT $limit
1159
+ CALL {
1160
+ WITH c
1161
+ OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
1162
+ WHERE m.role = 'user'
1163
+ AND c.name IS NULL
1164
+ AND NOT (m.content STARTS WITH '[New session.')
1165
+ AND NOT (m.content STARTS WITH '{"')
1166
+ AND size(m.content) >= 4
1167
+ RETURN m.content AS content, m.createdAt AS createdAt
1168
+ ORDER BY m.createdAt ASC
1169
+ LIMIT 1
1170
+ }
1171
+ RETURN c.conversationId AS conversationId,
1172
+ c.name AS name,
1173
+ c.updatedAt AS updatedAt,
1174
+ c.channel AS channel,
1175
+ content AS firstSubstantiveUserMessage`,
1176
+ { accountId, userId, limit: neo4j.int(limit) }
1177
+ );
1178
+ const rows = result.records.map((r) => ({
1179
+ conversationId: r.get("conversationId"),
1180
+ name: r.get("name"),
1181
+ updatedAt: String(r.get("updatedAt")),
1182
+ channel: r.get("channel"),
1183
+ firstSubstantiveUserMessage: r.get("firstSubstantiveUserMessage")
1184
+ }));
1185
+ let backfillsKicked = 0;
1186
+ for (const row of rows) {
1187
+ if (backfillsKicked >= LIST_BACKFILL_CAP) break;
1188
+ if (row.name !== null) continue;
1189
+ const seed = row.firstSubstantiveUserMessage;
1190
+ if (!seed || !isMessageUseful(seed)) continue;
1191
+ backfillsKicked++;
1192
+ autoLabelSession(row.conversationId, seed).catch(() => {
1193
+ });
1194
+ }
1195
+ return rows.map(({ conversationId, name, updatedAt, channel }) => ({ conversationId, name, updatedAt, channel }));
1196
+ } catch (err) {
1197
+ console.error(`[persist] listAdminSessions failed: ${err instanceof Error ? err.message : String(err)}`);
1198
+ return [];
1199
+ } finally {
1200
+ await session.close();
1201
+ }
1202
+ }
1203
+ async function deleteConversation(conversationId) {
1204
+ const session = getSession();
1205
+ try {
1206
+ const result = await session.run(
1207
+ `MATCH (c:Conversation {conversationId: $conversationId})
1208
+ OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
1209
+ OPTIONAL MATCH (m)-[:HAS_COMPONENT]->(comp:Component)
1210
+ OPTIONAL MATCH (m)-[:HAS_ATTACHMENT]->(att:Attachment)
1211
+ DETACH DELETE att, comp, m, c
1212
+ RETURN count(c) AS deleted`,
1213
+ { conversationId }
1214
+ );
1215
+ const deleted = result.records[0]?.get("deleted");
1216
+ const count = typeof deleted === "object" && deleted !== null ? Number(deleted) : Number(deleted ?? 0);
1217
+ console.error(`[persist] deleteConversation ${conversationId.slice(0, 8)}\u2026: ${count > 0 ? "deleted" : "not found"}`);
1218
+ return count > 0;
1219
+ } catch (err) {
1220
+ console.error(`[persist] deleteConversation failed: ${err instanceof Error ? err.message : String(err)}`);
1221
+ return false;
1222
+ } finally {
1223
+ await session.close();
1224
+ }
1225
+ }
1226
+ var GENERIC_MESSAGE = /^(h(i|ello|ey|owdy)|yo|sup|thanks|thank you|ok|okay|yes|no|good\s*(morning|afternoon|evening|night)|greetings|what'?s\s*up)[\s!?.,:;]*$/i;
1227
+ var SESSION_LABEL_MSG_CAP = 500;
1228
+ var SESSION_LABEL_TIMEOUT_MS = 15e3;
1229
+ var SESSION_LABEL_MODEL = HAIKU_MODEL;
1230
+ var SESSION_LABEL_MAX_WORDS = 6;
1231
+ var SESSION_LABEL_MAX_ATTEMPTS = 3;
1232
+ var SESSION_LABEL_MAX_STDERR = 2048;
1233
+ function isMessageUseful(message) {
1234
+ const trimmed = message.trim();
1235
+ if (trimmed.length < 4) return false;
1236
+ if (trimmed.startsWith('{"')) return false;
1237
+ if (GENERIC_MESSAGE.test(trimmed)) return false;
1238
+ if (trimmed.startsWith(DIRECTIVE_PREFIX)) return false;
1239
+ return true;
1240
+ }
1241
+ function totalFailures(f) {
1242
+ return f.skip + f.error;
1243
+ }
1244
+ function failureBreakdown(f) {
1245
+ return `skip:${f.skip} error:${f.error}`;
1246
+ }
1247
+ var labelAccumulator = /* @__PURE__ */ new Map();
1248
+ var _spawnOverride = null;
1249
+ var SESSION_LABEL_SYSTEM = `You are a session labeler. Given the opening messages of a conversation with an AI assistant, produce a concise topic label.
1250
+
1251
+ Rules:
1252
+ - Exactly 3 to 6 words
1253
+ - Summarize the user's intent, do not copy verbatim
1254
+ - Capitalize the first word only (sentence case)
1255
+ - No punctuation, no quotes
1256
+ - If the messages are too vague or meaningless to summarize, respond with exactly: SKIP`;
1257
+ async function generateSessionLabel(messages) {
1258
+ const cappedMessages = messages.map((m) => m.slice(0, SESSION_LABEL_MSG_CAP));
1259
+ const userContent = cappedMessages.map((m, i) => `Message ${i + 1}: ${m}`).join("\n");
1260
+ const prompt = `${SESSION_LABEL_SYSTEM}
1261
+
1262
+ ${userContent}`;
1263
+ const args = [
1264
+ "--print",
1265
+ "--model",
1266
+ SESSION_LABEL_MODEL,
1267
+ "--max-turns",
1268
+ "1",
1269
+ "--permission-mode",
1270
+ "dontAsk",
1271
+ prompt
1272
+ ];
1273
+ return new Promise((resolve5) => {
1274
+ let stdout = "";
1275
+ let stderr = "";
1276
+ const spawnFn = _spawnOverride ?? spawn2;
1277
+ const proc = spawnFn("claude", args, {
1278
+ stdio: ["ignore", "pipe", "pipe"]
1279
+ });
1280
+ proc.stdout?.on("data", (chunk) => {
1281
+ stdout += chunk.toString("utf-8");
1282
+ });
1283
+ proc.stderr?.on("data", (chunk) => {
1284
+ if (stderr.length < SESSION_LABEL_MAX_STDERR) {
1285
+ stderr += chunk.toString("utf-8").slice(0, SESSION_LABEL_MAX_STDERR - stderr.length);
1286
+ }
1287
+ });
1288
+ const timer = setTimeout(() => {
1289
+ proc.kill("SIGTERM");
1290
+ console.error("[persist] autoLabel: haiku subprocess timed out");
1291
+ resolve5(null);
1292
+ }, SESSION_LABEL_TIMEOUT_MS);
1293
+ proc.on("error", (err) => {
1294
+ clearTimeout(timer);
1295
+ console.error(`[persist] autoLabel: subprocess error \u2014 ${err.message}`);
1296
+ resolve5(null);
1297
+ });
1298
+ proc.on("close", (code) => {
1299
+ clearTimeout(timer);
1300
+ if (code !== 0) {
1301
+ console.error(`[persist] autoLabel: subprocess exited code=${code}${stderr ? ` stderr=${stderr.trim().slice(0, 200)}` : ""}`);
1302
+ resolve5(null);
1303
+ return;
1304
+ }
1305
+ const text = stdout.trim();
1306
+ if (!text) {
1307
+ console.error("[persist] autoLabel: haiku returned empty response");
1308
+ resolve5(null);
1309
+ return;
1310
+ }
1311
+ if (text === "SKIP") {
1312
+ console.error("[persist] autoLabel: haiku returned SKIP \u2014 messages too vague");
1313
+ resolve5(null);
1314
+ return;
1315
+ }
1316
+ const words = text.split(/\s+/).slice(0, SESSION_LABEL_MAX_WORDS);
1317
+ const label = words.join(" ");
1318
+ console.error(`[persist] autoLabel: haiku response="${label}"`);
1319
+ resolve5(label);
1320
+ });
1321
+ });
1322
+ }
1323
+ async function autoLabelSession(conversationId, userMessage) {
1324
+ if (!conversationId) return;
1325
+ if (!isMessageUseful(userMessage)) {
1326
+ const trimmed = userMessage.trim();
1327
+ const reason = trimmed.startsWith('{"') ? "JSON envelope" : trimmed.startsWith(DIRECTIVE_PREFIX) ? "directive" : GENERIC_MESSAGE.test(trimmed) ? "greeting" : trimmed.length < 4 ? "too short" : "directive";
1328
+ console.error(`[persist] autoLabel: skipped ${conversationId.slice(0, 8)}\u2026 \u2014 ${reason}`);
1329
+ return;
1330
+ }
1331
+ try {
1332
+ const preCheck = getSession();
1333
+ try {
1334
+ const res = await preCheck.run(
1335
+ `MATCH (c:Conversation {conversationId: $conversationId})
1336
+ OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
1337
+ WHERE m.role = 'user'
1338
+ WITH c, count(m) AS userCount
1339
+ RETURN c.name AS name, userCount`,
1340
+ { conversationId }
1341
+ );
1342
+ const firstRecord = res.records[0];
1343
+ const existingName = firstRecord?.get("name");
1344
+ const userCountRaw = firstRecord?.get("userCount");
1345
+ const userCount = typeof userCountRaw === "object" && userCountRaw !== null ? Number(userCountRaw) : Number(userCountRaw ?? 0);
1346
+ if (existingName) {
1347
+ console.error(`[persist] autoLabel: already named ${conversationId.slice(0, 8)}\u2026 \u2014 skipping`);
1348
+ labelAccumulator.delete(conversationId);
1349
+ return;
1350
+ }
1351
+ if (userCount > 3) {
1352
+ console.error(`[persist] autoLabel: past autolabel window ${conversationId.slice(0, 8)}\u2026 \u2014 userCount=${userCount}, skipping`);
1353
+ labelAccumulator.delete(conversationId);
1354
+ return;
1355
+ }
1356
+ } finally {
1357
+ await preCheck.close();
1358
+ }
1359
+ } catch (err) {
1360
+ console.error(`[persist] autoLabel: pre-check read failed for ${conversationId.slice(0, 8)}\u2026 \u2014 proceeding: ${err instanceof Error ? err.message : String(err)}`);
1361
+ }
1362
+ let entry = labelAccumulator.get(conversationId);
1363
+ if (!entry) {
1364
+ entry = {
1365
+ messages: [],
1366
+ pending: false,
1367
+ failures: { skip: 0, error: 0 }
1368
+ };
1369
+ labelAccumulator.set(conversationId, entry);
1370
+ }
1371
+ if (totalFailures(entry.failures) >= SESSION_LABEL_MAX_ATTEMPTS) {
1372
+ console.error(`[persist] autoLabel: evicted ${conversationId.slice(0, 8)}\u2026 after ${SESSION_LABEL_MAX_ATTEMPTS} failed-attempts (${failureBreakdown(entry.failures)})`);
1373
+ labelAccumulator.delete(conversationId);
1374
+ return;
1375
+ }
1376
+ entry.messages.push(userMessage.trim());
1377
+ if (entry.pending) {
1378
+ console.error(`[persist] autoLabel: accumulated for ${conversationId.slice(0, 8)}\u2026 (pending, ${entry.messages.length} msgs)`);
1379
+ return;
1380
+ }
1381
+ entry.pending = true;
1382
+ try {
1383
+ const label = await generateSessionLabel(entry.messages);
1384
+ if (!label) {
1385
+ entry.failures.skip++;
1386
+ console.error(`[persist] autoLabel: generateSessionLabel returned null for ${conversationId.slice(0, 8)}\u2026 (failures ${failureBreakdown(entry.failures)}, ${entry.messages.length} msgs)`);
1387
+ entry.pending = false;
1388
+ return;
1389
+ }
1390
+ const fullLabel = `${label} \xB7 ${conversationId.slice(0, 8)}`;
1391
+ let embedding = null;
1392
+ try {
1393
+ embedding = await embed(fullLabel);
1394
+ } catch (err) {
1395
+ console.error(`[persist] Conversation embedding failed, labelling without: ${err instanceof Error ? err.message : String(err)}`);
1396
+ }
1397
+ const session = getSession();
1398
+ try {
1399
+ const result = await session.run(
1400
+ `MATCH (c:Conversation {conversationId: $conversationId})
1401
+ WHERE c.name IS NULL
1402
+ WITH c
1403
+ OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
1404
+ WHERE m.role = 'user'
1405
+ WITH c, count(m) AS userCount
1406
+ WHERE userCount <= 3
1407
+ SET c.name = $label, c.updatedAt = datetime()
1408
+ ${embedding ? ", c.embedding = $embedding" : ""}
1409
+ RETURN c.name AS name`,
1410
+ { conversationId, label: fullLabel, ...embedding ? { embedding } : {} }
1411
+ );
1412
+ if (result.records.length > 0) {
1413
+ console.error(`[persist] autoLabel: commit ${conversationId.slice(0, 8)}\u2026 name="${fullLabel}"${embedding ? " (embedded)" : ""}`);
1414
+ labelAccumulator.delete(conversationId);
1415
+ } else {
1416
+ console.error(`[persist] autoLabel: no-op commit ${conversationId.slice(0, 8)}\u2026 (name already set or userCount>3)`);
1417
+ labelAccumulator.delete(conversationId);
1418
+ }
1419
+ } catch (err) {
1420
+ entry.failures.error++;
1421
+ console.error(`[persist] autoLabelSession failed: ${err instanceof Error ? err.message : String(err)} (failures ${failureBreakdown(entry.failures)})`);
1422
+ } finally {
1423
+ await session.close();
1424
+ }
1425
+ } catch (err) {
1426
+ const currentEntry = labelAccumulator.get(conversationId);
1427
+ if (currentEntry) currentEntry.failures.error++;
1428
+ console.error(`[persist] autoLabel: unexpected error \u2014 ${err instanceof Error ? err.message : String(err)}${currentEntry ? ` (failures ${failureBreakdown(currentEntry.failures)})` : ""}`);
1429
+ } finally {
1430
+ const currentEntry = labelAccumulator.get(conversationId);
1431
+ if (currentEntry) currentEntry.pending = false;
1432
+ }
1433
+ }
1434
+ async function renameConversation(conversationId, label) {
1435
+ let embedding = null;
1436
+ try {
1437
+ embedding = await embed(label);
1438
+ } catch (err) {
1439
+ console.error(`[persist] manual-label: embedding failed, persisting without: ${err instanceof Error ? err.message : String(err)}`);
1440
+ }
1441
+ const session = getSession();
1442
+ try {
1443
+ await session.run(
1444
+ `MATCH (c:Conversation {conversationId: $conversationId})
1445
+ SET c.name = $label, c.updatedAt = datetime()
1446
+ ${embedding ? ", c.embedding = $embedding" : ""}`,
1447
+ { conversationId, label, ...embedding ? { embedding } : {} }
1448
+ );
1449
+ console.error(`[persist] manual-label: renamed ${conversationId} to "${label}"${embedding ? " (embedded)" : ""}`);
1450
+ } finally {
1451
+ await session.close();
1452
+ }
1453
+ }
1454
+ var INITIAL_CONFIDENCE = 0.5;
1455
+ var REINFORCEMENT_INCREMENT = 0.15;
1456
+ var DECAY_THRESHOLD_DAYS = 14;
1457
+ var DECAY_RATE_PER_DAY = 0.05;
1458
+ var INJECTION_THRESHOLD = 0.4;
1459
+ var MAX_SUMMARY_PREFERENCES = 30;
1460
+ var VALID_CATEGORIES = /* @__PURE__ */ new Set([
1461
+ "communication",
1462
+ "scheduling",
1463
+ "decision",
1464
+ "workflow",
1465
+ "content",
1466
+ "interaction"
1467
+ ]);
1468
+ async function getUserTimezone(accountId, userId) {
1469
+ const session = getSession();
1470
+ try {
1471
+ const query2 = userId ? `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
1472
+ RETURN up.timezone AS timezone` : `MATCH (up:UserProfile {accountId: $accountId})
1473
+ RETURN up.timezone AS timezone ORDER BY up.createdAt LIMIT 1`;
1474
+ const result = await session.run(query2, { accountId, userId: userId ?? "" });
1475
+ if (result.records.length === 0) return null;
1476
+ const tz = result.records[0].get("timezone");
1477
+ return tz && tz.trim().length > 0 ? tz : null;
1478
+ } catch (err) {
1479
+ console.error(`[datetime] getUserTimezone failed: ${err instanceof Error ? err.message : String(err)}`);
1480
+ return null;
1481
+ } finally {
1482
+ await session.close();
1483
+ }
1484
+ }
1485
+ async function loadAdminUserName(accountId, userId) {
1486
+ const session = getSession();
1487
+ try {
1488
+ const result = await session.run(
1489
+ `MATCH (au:AdminUser {userId: $userId})-[:OWNS]->(p:Person {accountId: $accountId})
1490
+ RETURN p.givenName AS givenName, p.familyName AS familyName, p.avatar AS avatar
1491
+ LIMIT 1`,
1492
+ { accountId, userId }
1493
+ );
1494
+ if (result.records.length === 0) {
1495
+ return { source: "fallback", reason: "no-person-node" };
1496
+ }
1497
+ const givenName = result.records[0].get("givenName");
1498
+ const familyName = result.records[0].get("familyName");
1499
+ const avatar = result.records[0].get("avatar");
1500
+ if (!givenName || givenName.trim().length === 0) {
1501
+ return { source: "fallback", reason: "no-givenName" };
1502
+ }
1503
+ const trimmedFamily = familyName && familyName.trim().length > 0 ? familyName.trim() : null;
1504
+ const trimmedAvatar = avatar && avatar.trim().length > 0 ? avatar.trim() : null;
1505
+ const joined = trimmedFamily ? `${givenName.trim()} ${trimmedFamily}` : givenName.trim();
1506
+ return { source: "neo4j", joined, givenName: givenName.trim(), familyName: trimmedFamily, avatar: trimmedAvatar };
1507
+ } catch (err) {
1508
+ console.error(`[admin-identity] loadAdminUserName failed: ${err instanceof Error ? err.message : String(err)}`);
1509
+ return { source: "fallback", reason: "neo4j-unreachable" };
1510
+ } finally {
1511
+ await session.close();
1512
+ }
1513
+ }
1514
+ async function writeAdminUserAndPerson(params) {
1515
+ const { userId, fullName, accountId } = params;
1516
+ const trimmed = fullName.trim();
1517
+ if (!trimmed) {
1518
+ throw new Error("writeAdminUserAndPerson: fullName cannot be empty");
1519
+ }
1520
+ const firstSpace = trimmed.search(/\s/);
1521
+ const givenName = firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace).trim();
1522
+ const familyName = firstSpace === -1 ? null : trimmed.slice(firstSpace + 1).trim() || null;
1523
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1524
+ const session = getSession();
1525
+ try {
1526
+ const result = await session.run(
1527
+ `MERGE (au:AdminUser {userId: $userId})
1528
+ ON CREATE SET au.name = $fullName, au.createdAt = $now
1529
+ ON MATCH SET au.name = $fullName, au.updatedAt = $now
1530
+ WITH au
1531
+
1532
+ // Case-insensitive Person reuse: same accountId, same givenName, same familyName
1533
+ // (null/empty familyName collapsed to '' so 'Joel' does NOT match 'Joel Smalley').
1534
+ OPTIONAL MATCH (existingPerson:Person {accountId: $accountId})
1535
+ WHERE toLower(existingPerson.givenName) = toLower($givenName)
1536
+ AND coalesce(toLower(existingPerson.familyName), '') = coalesce(toLower($familyName), '')
1537
+ WITH au, existingPerson
1538
+
1539
+ CALL {
1540
+ WITH au, existingPerson
1541
+ WITH au, existingPerson WHERE existingPerson IS NOT NULL
1542
+ MERGE (au)-[:OWNS]->(existingPerson)
1543
+ RETURN existingPerson AS p, true AS reused
1544
+ UNION
1545
+ WITH au, existingPerson
1546
+ WITH au WHERE existingPerson IS NULL
1547
+ CREATE (newPerson:Person {
1548
+ accountId: $accountId,
1549
+ givenName: $givenName,
1550
+ familyName: $familyName,
1551
+ role: 'admin-personal',
1552
+ scope: 'admin',
1553
+ createdAt: $now
1554
+ })
1555
+ MERGE (au)-[:OWNS]->(newPerson)
1556
+ RETURN newPerson AS p, false AS reused
1557
+ }
1558
+ RETURN reused, elementId(p) AS personElementId,
1559
+ p.givenName AS givenName, p.familyName AS familyName`,
1560
+ { userId, fullName: trimmed, accountId, givenName, familyName, now }
1561
+ );
1562
+ if (result.records.length === 0) {
1563
+ throw new Error("writeAdminUserAndPerson: no record returned");
1564
+ }
1565
+ const record = result.records[0];
1566
+ return {
1567
+ personReused: record.get("reused"),
1568
+ personElementId: record.get("personElementId"),
1569
+ givenName: record.get("givenName"),
1570
+ familyName: record.get("familyName")
1571
+ };
1572
+ } finally {
1573
+ await session.close();
1574
+ }
1575
+ }
1576
+ async function loadUserProfile(accountId, userId) {
1577
+ const session = getSession();
1578
+ try {
1579
+ const serverTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
1580
+ const mergeResult = await session.run(
1581
+ `MATCH (au:AdminUser {userId: $userId})
1582
+ MERGE (au)-[:HAS_PROFILE]->(up:UserProfile {accountId: $accountId, userId: $userId})
1583
+ ON CREATE SET
1584
+ up.createdAt = $now,
1585
+ up.updatedAt = $now,
1586
+ up.profileVersion = 0,
1587
+ up.scope = 'admin',
1588
+ up.timezone = $serverTimezone
1589
+ ON MATCH SET
1590
+ up.timezone = CASE WHEN up.timezone IS NULL OR trim(up.timezone) = '' THEN $serverTimezone ELSE up.timezone END
1591
+ RETURN up.createdAt = $now AS isNew`,
1592
+ { accountId, userId, now: (/* @__PURE__ */ new Date()).toISOString(), serverTimezone }
1593
+ );
1594
+ if (mergeResult.records.length === 0) {
1595
+ console.error(`[profile] loadUserProfile: AdminUser not found for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 \u2014 profile not created, invariant violated`);
1596
+ return null;
1597
+ }
1598
+ const isNew = mergeResult.records[0].get("isNew");
1599
+ if (isNew) {
1600
+ console.error(`[profile] created new profile: userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 timezone=${serverTimezone}`);
1601
+ }
1602
+ const nowMs = Date.now();
1603
+ const thresholdMs = DECAY_THRESHOLD_DAYS * 24 * 60 * 60 * 1e3;
1604
+ const staleResult = await session.run(
1605
+ `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})-[:HAS_PREFERENCE]->(pref:Preference)
1606
+ WHERE pref.observedAt IS NOT NULL
1607
+ RETURN pref.preferenceId AS preferenceId,
1608
+ pref.observedAt AS observedAt,
1609
+ pref.confidence AS confidence`,
1610
+ { accountId, userId }
1611
+ );
1612
+ let decayCount = 0;
1613
+ for (const record of staleResult.records) {
1614
+ const observedAt = record.get("observedAt");
1615
+ const confidence = record.get("confidence");
1616
+ const observedMs = new Date(observedAt).getTime();
1617
+ const ageMs = nowMs - observedMs;
1618
+ if (ageMs > thresholdMs && confidence > 0) {
1619
+ const daysPastThreshold = (ageMs - thresholdMs) / (24 * 60 * 60 * 1e3);
1620
+ const decayedConfidence = Math.max(0, confidence - DECAY_RATE_PER_DAY * daysPastThreshold);
1621
+ if (decayedConfidence !== confidence) {
1622
+ await session.run(
1623
+ `MATCH (pref:Preference {preferenceId: $preferenceId, accountId: $accountId})
1624
+ SET pref.confidence = $confidence`,
1625
+ {
1626
+ preferenceId: record.get("preferenceId"),
1627
+ accountId,
1628
+ confidence: decayedConfidence
1629
+ }
1630
+ );
1631
+ decayCount++;
1632
+ }
1633
+ }
1634
+ }
1635
+ const result = await session.run(
1636
+ `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
1637
+ OPTIONAL MATCH (au:AdminUser {userId: $userId})-[:OWNS]->(p:Person {accountId: $accountId})
1638
+ OPTIONAL MATCH (up)-[:HAS_PREFERENCE]->(pref:Preference)
1639
+ WHERE pref.confidence >= $threshold
1640
+ WITH up, p, pref
1641
+ ORDER BY pref.confidence DESC
1642
+ WITH up, p, collect(pref) AS allPrefs
1643
+ WITH up, p, allPrefs[0..$limit] AS prefs
1644
+ RETURN up, p AS person, prefs`,
1645
+ { accountId, userId, threshold: INJECTION_THRESHOLD, limit: MAX_SUMMARY_PREFERENCES }
1646
+ );
1647
+ if (result.records.length === 0 || !result.records[0].get("up")) {
1648
+ return null;
1649
+ }
1650
+ const upNode = result.records[0].get("up");
1651
+ const profileProps = { ...upNode.properties };
1652
+ const personNode = result.records[0].get("person");
1653
+ if (personNode?.properties) {
1654
+ if (personNode.properties.givenName !== void 0) profileProps.givenName = personNode.properties.givenName;
1655
+ if (personNode.properties.familyName !== void 0) profileProps.familyName = personNode.properties.familyName;
1656
+ }
1657
+ const prefNodes = result.records[0].get("prefs");
1658
+ const preferences = prefNodes.map((p) => ({
1659
+ preferenceId: p.properties.preferenceId,
1660
+ category: p.properties.category,
1661
+ key: p.properties.key,
1662
+ value: p.properties.value,
1663
+ confidence: p.properties.confidence,
1664
+ source: p.properties.source,
1665
+ observedAt: p.properties.observedAt
1666
+ }));
1667
+ const summary = formatProfileSummary(profileProps, preferences);
1668
+ console.error(
1669
+ `[profile] loaded for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 preferences=${preferences.length} (decay: ${decayCount} updated)`
1670
+ );
1671
+ return summary;
1672
+ } catch (err) {
1673
+ console.error(`[profile] loadUserProfile failed: ${err instanceof Error ? err.message : String(err)}`);
1674
+ return null;
1675
+ } finally {
1676
+ await session.close();
1677
+ }
1678
+ }
1679
+ function formatProfileSummary(profile, preferences) {
1680
+ const givenName = typeof profile.givenName === "string" ? profile.givenName.trim() : "";
1681
+ const familyName = typeof profile.familyName === "string" ? profile.familyName.trim() : "";
1682
+ const joined = familyName ? `${givenName} ${familyName}` : givenName;
1683
+ const name = joined || "Owner";
1684
+ const role = profile.role ? ` (${profile.role})` : "";
1685
+ const tz = profile.timezone ? ` \u2014 ${profile.timezone}` : "";
1686
+ const locale = profile.locale ? `, ${profile.locale}` : "";
1687
+ const expertise = profile.expertise ? `
1688
+ Expertise: ${typeof profile.expertise === "string" ? profile.expertise : JSON.stringify(profile.expertise)}` : "";
1689
+ const lines = [`## About the Owner
1690
+ `];
1691
+ lines.push(`${name}${role}${tz}${locale}${expertise}
1692
+ `);
1693
+ const categories = {};
1694
+ for (const pref of preferences) {
1695
+ if (!categories[pref.category]) categories[pref.category] = [];
1696
+ categories[pref.category].push(pref);
1697
+ }
1698
+ const categoryLabels = {
1699
+ communication: "Communication",
1700
+ scheduling: "Scheduling",
1701
+ decision: "Decisions",
1702
+ workflow: "Workflow",
1703
+ content: "Content",
1704
+ interaction: "Interaction patterns"
1705
+ };
1706
+ const workCategories = ["communication", "scheduling", "decision", "workflow", "content"];
1707
+ const workPrefs = workCategories.filter((c) => categories[c]);
1708
+ if (workPrefs.length > 0) {
1709
+ lines.push(`### How they work`);
1710
+ for (const cat of workPrefs) {
1711
+ const label = categoryLabels[cat] || cat;
1712
+ const items = categories[cat].map((p) => p.value).join("; ");
1713
+ lines.push(`- ${label}: ${items}`);
1714
+ }
1715
+ lines.push("");
1716
+ }
1717
+ if (categories.interaction) {
1718
+ lines.push(`### Interaction patterns`);
1719
+ for (const pref of categories.interaction) {
1720
+ lines.push(`- ${pref.value}`);
1721
+ }
1722
+ lines.push("");
1723
+ }
1724
+ return lines.join("\n");
1725
+ }
1726
+ var MAX_SESSION_TASKS = 20;
1727
+ var MAX_SESSION_REVIEW_ALERTS = 5;
1728
+ var MAX_SESSION_PROJECTS = 5;
1729
+ var MAX_RECENT_TOOL_FAILURES = 3;
1730
+ var RECENT_FAILURES_TAIL_BYTES = 10 * 1024;
1731
+ function readRecentToolFailures(accountId, conversationId) {
1732
+ try {
1733
+ const platformRoot = process.env.MAXY_PLATFORM_ROOT ?? resolve2(process.cwd(), "..");
1734
+ const logDir = resolve2(platformRoot, "..", "data/accounts", accountId, "logs");
1735
+ const logPath = resolve2(logDir, `claude-agent-stream-${conversationId}.log`);
1736
+ if (!existsSync2(logPath)) {
1737
+ console.error(`[review-tail-skip] path=${logPath} reason=file-missing \u2014 first turn of conversation, subprocess not yet spawned, or log rotated`);
1738
+ return [];
1739
+ }
1740
+ const st = statSync2(logPath);
1741
+ const size = st.size;
1742
+ const readBytes = Math.min(size, RECENT_FAILURES_TAIL_BYTES);
1743
+ const position = size - readBytes;
1744
+ const fd = openSync(logPath, "r");
1745
+ try {
1746
+ const buf = Buffer.alloc(readBytes);
1747
+ readSync(fd, buf, 0, readBytes, position);
1748
+ const text = buf.toString("utf-8");
1749
+ const lines = text.split("\n");
1750
+ const matches = [];
1751
+ for (let i = lines.length - 1; i >= 0 && matches.length < MAX_RECENT_TOOL_FAILURES; i--) {
1752
+ const line = lines[i];
1753
+ if (line.includes("[tool-failure-diag]")) {
1754
+ matches.push(line);
1755
+ }
1756
+ }
1757
+ return matches.reverse();
1758
+ } finally {
1759
+ closeSync(fd);
1760
+ }
1761
+ } catch (err) {
1762
+ console.error(
1763
+ `[session-context] recent-tool-failures read failed: ${err instanceof Error ? err.message : String(err)}`
1764
+ );
1765
+ return [];
1766
+ }
1767
+ }
1768
+ async function loadSessionContext(accountId, conversationId) {
1769
+ const session = getSession();
1770
+ try {
1771
+ const digestResult = await session.run(
1772
+ `MATCH (d:CreativeWork {accountId: $accountId})
1773
+ WHERE d.title STARTS WITH 'Chat Review' OR d.title STARTS WITH 'Review Digest'
1774
+ RETURN d.title AS title, d.createdAt AS createdAt, d.abstract AS abstract
1775
+ ORDER BY d.createdAt DESC LIMIT 1`,
1776
+ { accountId }
1777
+ );
1778
+ const tasksResult = await session.run(
1779
+ `MATCH (t:Task {accountId: $accountId})
1780
+ WHERE t.status IN ['pending', 'active']
1781
+ RETURN t.taskId AS taskId, t.name AS name, t.status AS status,
1782
+ t.priority AS priority, t.dueDate AS dueDate
1783
+ ORDER BY
1784
+ CASE t.priority
1785
+ WHEN 'urgent' THEN 0
1786
+ WHEN 'high' THEN 1
1787
+ WHEN 'normal' THEN 2
1788
+ WHEN 'low' THEN 3
1789
+ ELSE 4
1790
+ END,
1791
+ t.createdAt DESC
1792
+ LIMIT $limit`,
1793
+ { accountId, limit: neo4j.int(MAX_SESSION_TASKS) }
1794
+ );
1795
+ const alertsResult = await session.run(
1796
+ `MATCH (a:ReviewAlert {accountId: $accountId})
1797
+ WHERE a.resolvedAt IS NULL
1798
+ AND (a.suppressedUntil IS NULL OR a.suppressedUntil < datetime())
1799
+ AND a.lastMatchAt > datetime() - duration('P1D')
1800
+ RETURN a.ruleId AS ruleId, a.ruleName AS ruleName, a.lastMatchAt AS lastMatchAt,
1801
+ a.cumulativeMatchCount AS cumulativeMatchCount, a.sampleEvidence AS sampleEvidence,
1802
+ a.suggestedAction AS suggestedAction
1803
+ ORDER BY a.lastMatchAt DESC
1804
+ LIMIT $limit`,
1805
+ { accountId, limit: neo4j.int(MAX_SESSION_REVIEW_ALERTS) }
1806
+ );
1807
+ let projectsCount = 0;
1808
+ let projectLines = [];
1809
+ try {
1810
+ const projectsResult = await session.run(
1811
+ `MATCH (p:Project:Task {accountId: $accountId})
1812
+ WHERE p.status IN ['pending', 'active']
1813
+ OPTIONAL MATCH (p)-[:HAS_TASK]->(child:Task)
1814
+ WITH p,
1815
+ count(child) AS totalTasks,
1816
+ count(CASE WHEN child.status = 'completed' THEN 1 END) AS completedTasks,
1817
+ count(CASE WHEN child.dueDate IS NOT NULL
1818
+ AND date(child.dueDate) < date()
1819
+ AND child.status <> 'completed' THEN 1 END) AS overdueTasks,
1820
+ count(CASE WHEN child.status IN ['pending', 'active'] AND EXISTS {
1821
+ MATCH (blocker:Task)-[:BLOCKS]->(child)
1822
+ WHERE blocker.status IN ['pending', 'active']
1823
+ } THEN 1 END) AS blockedTasks
1824
+ RETURN p.name AS name, p.phase AS phase, p.tier AS tier,
1825
+ p.clientRef AS clientRef, p.status AS status,
1826
+ totalTasks, completedTasks, overdueTasks, blockedTasks
1827
+ ORDER BY p.updatedAt DESC
1828
+ LIMIT $limit`,
1829
+ { accountId, limit: neo4j.int(MAX_SESSION_PROJECTS) }
1830
+ );
1831
+ projectsCount = projectsResult.records.length;
1832
+ if (projectsCount > 0) {
1833
+ projectLines = projectsResult.records.map((r) => {
1834
+ const name = r.get("name") || "Unnamed project";
1835
+ const phase = r.get("phase") || "planning";
1836
+ const tier = r.get("tier") || "standard";
1837
+ const clientRef = r.get("clientRef");
1838
+ const total = typeof r.get("totalTasks") === "number" ? r.get("totalTasks") : r.get("totalTasks")?.toNumber?.() ?? 0;
1839
+ const completed = typeof r.get("completedTasks") === "number" ? r.get("completedTasks") : r.get("completedTasks")?.toNumber?.() ?? 0;
1840
+ const overdue = typeof r.get("overdueTasks") === "number" ? r.get("overdueTasks") : r.get("overdueTasks")?.toNumber?.() ?? 0;
1841
+ const blocked = typeof r.get("blockedTasks") === "number" ? r.get("blockedTasks") : r.get("blockedTasks")?.toNumber?.() ?? 0;
1842
+ let signal;
1843
+ const hasDueDates = overdue > 0 || total > 0;
1844
+ if (!hasDueDates && total === 0) {
1845
+ signal = "grey";
1846
+ } else if (overdue > 1 || blocked > 1) {
1847
+ signal = "red";
1848
+ } else if (overdue > 0 || blocked > 0) {
1849
+ signal = "amber";
1850
+ } else {
1851
+ signal = "green";
1852
+ }
1853
+ const client = clientRef ? ` (${clientRef})` : "";
1854
+ const health = signal !== "grey" ? ` [${signal.toUpperCase()}]` : "";
1855
+ return `- **${name}**${client} \u2014 ${tier}, ${phase}${health}, ${completed}/${total} done${overdue > 0 ? `, ${overdue} overdue` : ""}${blocked > 0 ? `, ${blocked} blocked` : ""}`;
1856
+ });
1857
+ }
1858
+ } catch (projectErr) {
1859
+ console.error(
1860
+ `[session-context] project query failed: ${projectErr instanceof Error ? projectErr.message : String(projectErr)}`
1861
+ );
1862
+ }
1863
+ const sections = [];
1864
+ if (digestResult.records.length > 0) {
1865
+ const rec = digestResult.records[0];
1866
+ const title = rec.get("title");
1867
+ const createdAt = rec.get("createdAt");
1868
+ const abstract = rec.get("abstract");
1869
+ if (abstract) {
1870
+ const dateSuffix = createdAt ? ` (${createdAt.slice(0, 10)})` : "";
1871
+ const heading = title?.startsWith("Review Digest") ? `## Recent Review Digest${dateSuffix}` : `## Recent Public Chat Digest${dateSuffix}`;
1872
+ sections.push(`${heading}
1873
+ ${abstract}`);
1874
+ }
1875
+ }
1876
+ if (tasksResult.records.length > 0) {
1877
+ const taskLines = tasksResult.records.map((r) => {
1878
+ const priority = (r.get("priority") || "normal").toUpperCase();
1879
+ const status = r.get("status");
1880
+ const name = r.get("name");
1881
+ const dueDate = r.get("dueDate");
1882
+ const due = dueDate ? ` due:${dueDate.slice(0, 10)}` : "";
1883
+ const taskId = r.get("taskId");
1884
+ return `- [${priority}] ${status} \u2014 ${name}${due} (${taskId})`;
1885
+ });
1886
+ sections.push(`## Open Tasks (${tasksResult.records.length})
1887
+ ${taskLines.join("\n")}`);
1888
+ }
1889
+ let pendingCount = 0;
1890
+ let pendingLines = [];
1891
+ try {
1892
+ const platformRoot = process.env.MAXY_PLATFORM_ROOT ?? resolve2(process.cwd(), "..");
1893
+ const pendingDir = resolve2(platformRoot, "..", "data/accounts", accountId, "pending-actions");
1894
+ if (existsSync2(pendingDir)) {
1895
+ const files = readdirSync2(pendingDir).filter((f) => f.endsWith(".json") && !f.startsWith("."));
1896
+ for (const file of files) {
1897
+ try {
1898
+ const raw = readFileSync2(resolve2(pendingDir, file), "utf-8");
1899
+ const action = JSON.parse(raw);
1900
+ if (action.state === "pending") {
1901
+ const inputSummary = JSON.stringify(action.hookPayload?.tool_input ?? {}).slice(0, 150);
1902
+ pendingLines.push(`- **${action.toolName}** (${action.actionId.slice(0, 8)}\u2026) queued ${action.createdAt?.slice(0, 16) ?? "unknown"}
1903
+ Input: ${inputSummary}`);
1904
+ pendingCount++;
1905
+ }
1906
+ } catch {
1907
+ }
1908
+ }
1909
+ }
1910
+ } catch (pendingErr) {
1911
+ console.error(
1912
+ `[session-context] pending actions read failed: ${pendingErr instanceof Error ? pendingErr.message : String(pendingErr)}`
1913
+ );
1914
+ }
1915
+ if (pendingCount > 0) {
1916
+ sections.push(`## Pending Actions (${pendingCount})
1917
+ Actions queued for your approval. Use action-approve, action-reject, or action-edit.
1918
+ ${pendingLines.join("\n")}`);
1919
+ }
1920
+ if (projectLines.length > 0) {
1921
+ sections.push(`## Active Projects (${projectLines.length})
1922
+ ${projectLines.join("\n")}`);
1923
+ }
1924
+ if (alertsResult.records.length > 0) {
1925
+ const alertLines = alertsResult.records.map((r) => {
1926
+ const ruleName = r.get("ruleName");
1927
+ const count = r.get("cumulativeMatchCount");
1928
+ const countValue = typeof count === "number" ? count : count?.toNumber?.() ?? 0;
1929
+ const sample = r.get("sampleEvidence") ?? "";
1930
+ const action = r.get("suggestedAction");
1931
+ const shortSample = sample.length > 160 ? sample.slice(0, 160) + "\u2026" : sample;
1932
+ return `- **${ruleName}** (fired ${countValue}\xD7): ${shortSample}
1933
+ \u2192 ${action}`;
1934
+ });
1935
+ sections.push(`## Active Review Alerts (${alertsResult.records.length})
1936
+ ${alertLines.join("\n")}`);
1937
+ }
1938
+ let recentFailuresCount = 0;
1939
+ if (conversationId) {
1940
+ const failureLines = readRecentToolFailures(accountId, conversationId);
1941
+ if (failureLines.length > 0) {
1942
+ recentFailuresCount = failureLines.length;
1943
+ const guidance = "These tool calls failed in the current conversation. Inspect the diagnostic fields before retrying the same tool against the same target \u2014 if you do retry, narrate explicitly why the diagnostic suggests a retry will now succeed. A second identical failure is evidence the path is broken, not evidence another attempt is warranted.";
1944
+ sections.push(`## Recent Tool Failures (${failureLines.length})
1945
+ ${guidance}
1946
+
1947
+ ${failureLines.map((l) => `- ${l.trim()}`).join("\n")}`);
1948
+ }
1949
+ }
1950
+ if (sections.length === 0) return null;
1951
+ console.error(
1952
+ `[session-context] Loaded for ${accountId.slice(0, 8)}\u2026: digest=${digestResult.records.length > 0 ? "yes" : "no"}, tasks=${tasksResult.records.length}, projects=${projectsCount}, reviewAlerts=${alertsResult.records.length}, pendingActions=${pendingCount}, recentFailures=${recentFailuresCount}`
1953
+ );
1954
+ return `<previous-context>
1955
+ ${sections.join("\n\n")}
1956
+ </previous-context>`;
1957
+ } catch (err) {
1958
+ console.error(`[session-context] loadSessionContext failed: ${err instanceof Error ? err.message : String(err)}`);
1959
+ return null;
1960
+ } finally {
1961
+ await session.close();
1962
+ }
1963
+ }
1964
+ async function consumeStep7FlagUI(session, accountId) {
1965
+ const accountDir = resolve2(PLATFORM_ROOT, "..", "data/accounts", accountId);
1966
+ const flagPath = resolve2(accountDir, "onboarding", "step7-complete");
1967
+ if (!existsSync2(flagPath)) return false;
1968
+ let completedAt = (/* @__PURE__ */ new Date()).toISOString();
1969
+ try {
1970
+ const raw = readFileSync2(flagPath, "utf-8").trim();
1971
+ if (raw) {
1972
+ const parsed = JSON.parse(raw);
1973
+ if (typeof parsed.completedAt === "string") {
1974
+ completedAt = parsed.completedAt;
1975
+ }
1976
+ }
1977
+ } catch {
1978
+ }
1979
+ const result = await session.run(
1980
+ `MATCH (o:OnboardingState {accountId: $accountId})
1981
+ SET o.step7CompletedAt = CASE WHEN o.step7CompletedAt IS NULL THEN $completedAt ELSE o.step7CompletedAt END,
1982
+ o.currentStep = CASE WHEN 7 > o.currentStep THEN 7 ELSE o.currentStep END,
1983
+ o.updatedAt = $completedAt
1984
+ RETURN count(o) AS updated`,
1985
+ { accountId, completedAt }
1986
+ );
1987
+ const updatedRaw = result.records[0]?.get("updated");
1988
+ const updated = typeof updatedRaw === "number" ? updatedRaw : updatedRaw && typeof updatedRaw === "object" && "toNumber" in updatedRaw ? updatedRaw.toNumber() : 0;
1989
+ if (updated === 0) {
1990
+ console.log(
1991
+ `[onboarding-flag-consumed] accountId=${accountId.slice(0, 8)}\u2026 step=7 source=filesystem flagPath=${flagPath} skipped=no-node`
1992
+ );
1993
+ return false;
1994
+ }
1995
+ console.log(
1996
+ `[onboarding-flag-consumed] accountId=${accountId.slice(0, 8)}\u2026 step=7 source=filesystem flagPath=${flagPath} completedAt=${completedAt}`
1997
+ );
1998
+ try {
1999
+ rmSync(flagPath);
2000
+ } catch (err) {
2001
+ console.error(
2002
+ `[onboarding-flag-consumed] warn: failed to delete ${flagPath}: ${err instanceof Error ? err.message : String(err)}`
2003
+ );
2004
+ }
2005
+ return true;
2006
+ }
2007
+ async function loadOnboardingStep(accountId) {
2008
+ const session = getSession();
2009
+ try {
2010
+ await consumeStep7FlagUI(session, accountId);
2011
+ const result = await session.run(
2012
+ `MATCH (o:OnboardingState {accountId: $accountId})
2013
+ RETURN o.currentStep AS currentStep`,
2014
+ { accountId }
2015
+ );
2016
+ if (result.records.length === 0) {
2017
+ return -1;
2018
+ }
2019
+ const raw = result.records[0].get("currentStep");
2020
+ if (typeof raw === "number") return raw;
2021
+ if (raw && typeof raw === "object" && "toNumber" in raw) {
2022
+ return raw.toNumber();
2023
+ }
2024
+ return 0;
2025
+ } catch (err) {
2026
+ console.error(`[onboarding-inject] loadOnboardingStep failed: ${err instanceof Error ? err.message : String(err)}`);
2027
+ return null;
2028
+ } finally {
2029
+ await session.close();
2030
+ }
2031
+ }
2032
+ async function writeReflectionPreferences(accountId, userId, conversationId, updates) {
2033
+ if (updates.length === 0) return 0;
2034
+ const session = getSession();
2035
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2036
+ let written = 0;
2037
+ try {
2038
+ const VALID_MODES = /* @__PURE__ */ new Set(["reinforce", "update", "contradict", "merge"]);
2039
+ for (const update of updates) {
2040
+ if (!VALID_CATEGORIES.has(update.category)) {
2041
+ console.error(`[profile-reflection] Skipping invalid category "${update.category}"`);
2042
+ continue;
2043
+ }
2044
+ if (update.mode && !VALID_MODES.has(update.mode)) {
2045
+ console.error(`[profile-reflection] Skipping invalid mode "${update.mode}" for ${update.category}/${update.key}`);
2046
+ continue;
2047
+ }
2048
+ if (!update.value || update.value.trim().length === 0) {
2049
+ console.error(`[profile-reflection] Skipping empty value for ${update.category}/${update.key}`);
2050
+ continue;
2051
+ }
2052
+ try {
2053
+ if (update.mode === "merge" && update.mergeSourceIds?.length) {
2054
+ const txc = session.beginTransaction();
2055
+ try {
2056
+ const sourcesResult = await txc.run(
2057
+ `MATCH (pref:Preference)
2058
+ WHERE pref.preferenceId IN $sourceIds AND pref.accountId = $accountId
2059
+ OPTIONAL MATCH (pref)-[:OBSERVED_IN]->(conv:Conversation)
2060
+ RETURN pref.confidence AS confidence,
2061
+ collect(DISTINCT conv.conversationId) AS convIds`,
2062
+ { sourceIds: update.mergeSourceIds, accountId }
2063
+ );
2064
+ const maxConf = sourcesResult.records.reduce(
2065
+ (max, r) => Math.max(max, r.get("confidence")),
2066
+ INITIAL_CONFIDENCE
2067
+ );
2068
+ const allConvIds = /* @__PURE__ */ new Set();
2069
+ for (const r of sourcesResult.records) {
2070
+ for (const id of r.get("convIds")) {
2071
+ if (id) allConvIds.add(id);
2072
+ }
2073
+ }
2074
+ if (conversationId) allConvIds.add(conversationId);
2075
+ const preferenceId = randomUUID();
2076
+ let embedding2 = null;
2077
+ try {
2078
+ embedding2 = await embed(`${update.category}: ${update.key} \u2014 ${update.value}`);
2079
+ } catch {
2080
+ }
2081
+ const props = {
2082
+ preferenceId,
2083
+ accountId,
2084
+ userId,
2085
+ category: update.category,
2086
+ key: update.key,
2087
+ value: update.value,
2088
+ confidence: maxConf,
2089
+ source: update.source,
2090
+ observedAt: now,
2091
+ createdAt: now,
2092
+ updatedAt: now,
2093
+ scope: "admin"
2094
+ };
2095
+ if (embedding2) props.embedding = embedding2;
2096
+ await txc.run(
2097
+ `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
2098
+ CREATE (pref:Preference $props)
2099
+ CREATE (up)-[:HAS_PREFERENCE]->(pref)`,
2100
+ { accountId, userId, props }
2101
+ );
2102
+ for (const convId of allConvIds) {
2103
+ await txc.run(
2104
+ `MATCH (pref:Preference {preferenceId: $preferenceId})
2105
+ MATCH (conv:Conversation {conversationId: $convId})
2106
+ MERGE (pref)-[:OBSERVED_IN]->(conv)`,
2107
+ { preferenceId, convId }
2108
+ );
2109
+ }
2110
+ await txc.run(
2111
+ `MATCH (pref:Preference)
2112
+ WHERE pref.preferenceId IN $sourceIds AND pref.accountId = $accountId
2113
+ DETACH DELETE pref`,
2114
+ { sourceIds: update.mergeSourceIds, accountId }
2115
+ );
2116
+ await txc.commit();
2117
+ written++;
2118
+ } catch (mergeErr) {
2119
+ await txc.rollback();
2120
+ console.error(`[profile-reflection] Merge failed for ${update.category}/${update.key}: ${mergeErr instanceof Error ? mergeErr.message : String(mergeErr)}`);
2121
+ }
2122
+ continue;
2123
+ }
2124
+ let embedding = null;
2125
+ try {
2126
+ embedding = await embed(`${update.category}: ${update.key} \u2014 ${update.value}`);
2127
+ } catch {
2128
+ }
2129
+ const newPrefId = randomUUID();
2130
+ const mode = update.mode || "reinforce";
2131
+ const mergeParams = {
2132
+ accountId,
2133
+ userId,
2134
+ category: update.category,
2135
+ key: update.key,
2136
+ newPrefId,
2137
+ value: update.value,
2138
+ source: update.source,
2139
+ initialConfidence: INITIAL_CONFIDENCE,
2140
+ increment: REINFORCEMENT_INCREMENT,
2141
+ decrement: 0.3,
2142
+ mode,
2143
+ now
2144
+ };
2145
+ if (embedding) mergeParams.embedding = embedding;
2146
+ const mergeResult = await session.run(
2147
+ `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
2148
+ MERGE (up)-[:HAS_PREFERENCE]->(pref:Preference {accountId: $accountId, userId: $userId, category: $category, key: $key})
2149
+ ON CREATE SET
2150
+ pref.preferenceId = $newPrefId,
2151
+ pref.value = $value,
2152
+ pref.confidence = $initialConfidence,
2153
+ pref.source = $source,
2154
+ pref.observedAt = $now,
2155
+ pref.createdAt = $now,
2156
+ pref.updatedAt = $now,
2157
+ pref.scope = 'admin'
2158
+ ON MATCH SET
2159
+ pref.value = $value,
2160
+ pref.source = $source,
2161
+ pref.confidence = CASE $mode
2162
+ WHEN 'reinforce' THEN CASE WHEN pref.confidence + $increment * (1.0 - pref.confidence) > 1.0 THEN 1.0 ELSE pref.confidence + $increment * (1.0 - pref.confidence) END
2163
+ WHEN 'contradict' THEN CASE WHEN pref.confidence - $decrement < 0.0 THEN 0.0 ELSE pref.confidence - $decrement END
2164
+ ELSE pref.confidence
2165
+ END,
2166
+ pref.observedAt = $now,
2167
+ pref.updatedAt = $now
2168
+ ${embedding ? "SET pref.embedding = $embedding" : ""}
2169
+ RETURN pref.preferenceId AS preferenceId`,
2170
+ mergeParams
2171
+ );
2172
+ const writtenPrefId = mergeResult.records[0]?.get("preferenceId");
2173
+ if (conversationId && writtenPrefId) {
2174
+ await session.run(
2175
+ `MATCH (pref:Preference {preferenceId: $preferenceId, accountId: $accountId})
2176
+ MATCH (conv:Conversation {conversationId: $conversationId})
2177
+ MERGE (pref)-[:OBSERVED_IN]->(conv)`,
2178
+ { preferenceId: writtenPrefId, accountId, conversationId }
2179
+ );
2180
+ }
2181
+ written++;
2182
+ } catch (itemErr) {
2183
+ console.error(`[profile-reflection] Failed to write ${update.category}/${update.key}: ${itemErr instanceof Error ? itemErr.message : String(itemErr)}`);
2184
+ }
2185
+ }
2186
+ if (written > 0) {
2187
+ await session.run(
2188
+ `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
2189
+ SET up.profileVersion = coalesce(up.profileVersion, 0) + 1,
2190
+ up.updatedAt = $now`,
2191
+ { accountId, userId, now }
2192
+ );
2193
+ }
2194
+ console.error(`[profile-reflection] Wrote ${written}/${updates.length} preference updates for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026`);
2195
+ return written;
2196
+ } catch (err) {
2197
+ console.error(`[profile-reflection] writeReflectionPreferences failed: ${err instanceof Error ? err.message : String(err)}`);
2198
+ return written;
2199
+ } finally {
2200
+ await session.close();
2201
+ }
2202
+ }
2203
+ var AGENT_FILE_ROLES = [
2204
+ { filename: "IDENTITY.md", role: "identity" },
2205
+ { filename: "SOUL.md", role: "soul" },
2206
+ { filename: "KNOWLEDGE.md", role: "knowledge" },
2207
+ { filename: "KNOWLEDGE-SUMMARY.md", role: "knowledge-summary" }
2208
+ ];
2209
+ var ROLE_TO_EDGE = {
2210
+ identity: "HAS_IDENTITY",
2211
+ soul: "HAS_SOUL",
2212
+ knowledge: "HAS_KNOWLEDGE",
2213
+ "knowledge-summary": "HAS_KNOWLEDGE"
2214
+ };
2215
+ function assertSafeAgentSlug(slug) {
2216
+ if (!slug || slug.includes("/") || slug.includes("\\") || slug.includes("..")) {
2217
+ throw new Error(`[agent-graph] refusing unsafe slug=${JSON.stringify(slug)}`);
2218
+ }
2219
+ }
2220
+ function agentAttachmentId(accountId, slug, role) {
2221
+ return `agent:${accountId}:${slug}:${role}`;
2222
+ }
2223
+ async function projectAgent(accountId, accountDir, slug) {
2224
+ const start = Date.now();
2225
+ const account8 = accountId.slice(0, 8);
2226
+ try {
2227
+ assertSafeAgentSlug(slug);
2228
+ } catch (err) {
2229
+ const msg = err instanceof Error ? err.message : String(err);
2230
+ console.error(
2231
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
2232
+ );
2233
+ return;
2234
+ }
2235
+ const agentDir = resolve2(accountDir, "agents", slug);
2236
+ const configPath = resolve2(agentDir, "config.json");
2237
+ let config;
2238
+ let presentRoles = [];
2239
+ try {
2240
+ if (!existsSync2(configPath)) {
2241
+ console.error(
2242
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="config.json missing at ${configPath}"`
2243
+ );
2244
+ return;
2245
+ }
2246
+ config = JSON.parse(readFileSync2(configPath, "utf-8"));
2247
+ for (const { filename, role } of AGENT_FILE_ROLES) {
2248
+ const filePath = resolve2(agentDir, filename);
2249
+ if (!existsSync2(filePath)) continue;
2250
+ const body = readFileSync2(filePath, "utf-8");
2251
+ presentRoles.push({ role, body, edge: ROLE_TO_EDGE[role] });
2252
+ }
2253
+ } catch (err) {
2254
+ const msg = err instanceof Error ? err.message : String(err);
2255
+ console.error(
2256
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
2257
+ );
2258
+ return;
2259
+ }
2260
+ const session = getSession();
2261
+ try {
2262
+ await session.run(
2263
+ `MERGE (a:Agent {accountId: $accountId, slug: $slug})
2264
+ ON CREATE SET a.createdAt = datetime()
2265
+ SET a.displayName = $displayName,
2266
+ a.status = $status,
2267
+ a.model = $model,
2268
+ a.liveMemory = $liveMemory,
2269
+ a.knowledgeKeywords = $knowledgeKeywords,
2270
+ a.role = 'agent',
2271
+ a.updatedAt = datetime()
2272
+ RETURN a.slug AS slug`,
2273
+ {
2274
+ accountId,
2275
+ slug,
2276
+ displayName: config.displayName ?? slug,
2277
+ status: config.status ?? "unknown",
2278
+ model: config.model ?? "",
2279
+ liveMemory: config.liveMemory ?? false,
2280
+ knowledgeKeywords: config.knowledgeKeywords ?? []
2281
+ }
2282
+ );
2283
+ for (const { role, body, edge } of presentRoles) {
2284
+ const attachmentId = agentAttachmentId(accountId, slug, role);
2285
+ await session.run(
2286
+ `MATCH (a:Agent {accountId: $accountId, slug: $slug})
2287
+ MERGE (k:KnowledgeDocument {attachmentId: $attachmentId})
2288
+ ON CREATE SET k.createdAt = datetime()
2289
+ SET k.accountId = $accountId,
2290
+ k.role = $role,
2291
+ k.name = $name,
2292
+ k.text = $text,
2293
+ k.scope = 'admin',
2294
+ k.updatedAt = datetime()
2295
+ MERGE (a)-[:${edge}]->(k)
2296
+ RETURN k.attachmentId AS attachmentId`,
2297
+ {
2298
+ accountId,
2299
+ slug,
2300
+ attachmentId,
2301
+ role,
2302
+ name: `${slug} ${role}`,
2303
+ text: body
2304
+ }
2305
+ );
2306
+ }
2307
+ const usesResult = await session.run(
2308
+ `MATCH (a:Agent {accountId: $accountId, slug: $slug})
2309
+ MATCH (k:KnowledgeDocument {accountId: $accountId})
2310
+ WHERE $slug IN coalesce(k.agents, [])
2311
+ AND NOT k.attachmentId STARTS WITH $namespacePrefix
2312
+ MERGE (a)-[:USES_KNOWLEDGE]->(k)
2313
+ RETURN count(k) AS uses`,
2314
+ {
2315
+ accountId,
2316
+ slug,
2317
+ namespacePrefix: `agent:${accountId}:${slug}:`
2318
+ }
2319
+ );
2320
+ const uses = usesResult.records[0]?.get("uses");
2321
+ const usesCount = typeof uses === "number" ? uses : uses && typeof uses.toNumber === "function" ? uses.toNumber() : 0;
2322
+ const ms = Date.now() - start;
2323
+ console.error(
2324
+ `[agent-graph] project slug=${slug} account=${account8} docs=${presentRoles.length} uses=${usesCount} ms=${ms}`
2325
+ );
2326
+ } catch (err) {
2327
+ const msg = err instanceof Error ? err.message : String(err);
2328
+ console.error(
2329
+ `[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
2330
+ );
2331
+ throw err;
2332
+ } finally {
2333
+ await session.close();
2334
+ }
2335
+ }
2336
+ async function deleteAgentProjection(accountId, slug) {
2337
+ const start = Date.now();
2338
+ const account8 = accountId.slice(0, 8);
2339
+ assertSafeAgentSlug(slug);
2340
+ const session = getSession();
2341
+ try {
2342
+ await session.run(
2343
+ `MATCH (a:Agent {accountId: $accountId, slug: $slug})
2344
+ DETACH DELETE a
2345
+ WITH 1 AS _
2346
+ UNWIND $attachmentIds AS aid
2347
+ OPTIONAL MATCH (k:KnowledgeDocument {accountId: $accountId, attachmentId: aid})
2348
+ WHERE k.attachmentId STARTS WITH $namespacePrefix
2349
+ DETACH DELETE k`,
2350
+ {
2351
+ accountId,
2352
+ slug,
2353
+ namespacePrefix: `agent:${accountId}:${slug}:`,
2354
+ attachmentIds: ["identity", "soul", "knowledge", "knowledge-summary"].map((role) => agentAttachmentId(accountId, slug, role))
2355
+ }
2356
+ );
2357
+ const ms = Date.now() - start;
2358
+ console.error(
2359
+ `[agent-graph] delete slug=${slug} account=${account8} ms=${ms}`
2360
+ );
2361
+ } catch (err) {
2362
+ const msg = err instanceof Error ? err.message : String(err);
2363
+ console.error(
2364
+ `[agent-graph] delete FAILED slug=${slug} account=${account8} error="${msg}"`
2365
+ );
2366
+ throw err;
2367
+ } finally {
2368
+ await session.close();
2369
+ }
2370
+ }
2371
+
2372
+ // app/lib/claude-agent/account.ts
2373
+ import { resolve as resolve3 } from "path";
2374
+ import { readFileSync as readFileSync4, readdirSync as readdirSync3, existsSync as existsSync4, statSync as statSync3 } from "fs";
2375
+
2376
+ // ../lib/brand-templating/src/index.ts
2377
+ import { join } from "path";
2378
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
2379
+ var PLACEHOLDER = "{{productName}}";
2380
+ var cachedProductName = null;
2381
+ function brandJsonPath() {
2382
+ const platformRoot = process.env.MAXY_PLATFORM_ROOT;
2383
+ if (!platformRoot) {
2384
+ throw new Error(
2385
+ "[skill-loader] MAXY_PLATFORM_ROOT not set \u2014 cannot resolve brand.json"
2386
+ );
2387
+ }
2388
+ return join(platformRoot, "config", "brand.json");
2389
+ }
2390
+ function getBrandProductName() {
2391
+ if (cachedProductName !== null) return cachedProductName;
2392
+ const path = brandJsonPath();
2393
+ if (!existsSync3(path)) {
2394
+ throw new Error(`[skill-loader] brand.json missing at ${path}`);
2395
+ }
2396
+ let parsed;
2397
+ try {
2398
+ parsed = JSON.parse(readFileSync3(path, "utf-8"));
2399
+ } catch (err) {
2400
+ throw new Error(
2401
+ `[skill-loader] brand.json unreadable at ${path}: ${err instanceof Error ? err.message : String(err)}`
2402
+ );
2403
+ }
2404
+ const value = parsed.productName;
2405
+ if (typeof value !== "string" || value.trim() === "") {
2406
+ throw new Error(
2407
+ `[skill-loader] brand.json at ${path} has missing or empty productName`
2408
+ );
2409
+ }
2410
+ cachedProductName = value;
2411
+ return value;
2412
+ }
2413
+ function substituteBrandPlaceholders(content, sourcePath) {
2414
+ if (!content.includes(PLACEHOLDER)) return content;
2415
+ let productName;
2416
+ try {
2417
+ productName = getBrandProductName();
2418
+ } catch (err) {
2419
+ console.error(
2420
+ `[skill-loader] ERROR: brand.json missing \u2014 cannot resolve productName for skill ${sourcePath}`
2421
+ );
2422
+ throw err;
2423
+ }
2424
+ const occurrences = content.split(PLACEHOLDER).length - 1;
2425
+ const substituted = content.split(PLACEHOLDER).join(productName);
2426
+ console.log(
2427
+ `[skill-loader] brand-substituted productName=${productName} skill=${sourcePath} occurrences=${occurrences}`
2428
+ );
2429
+ return substituted;
2430
+ }
2431
+
2432
+ // app/lib/claude-agent/account.ts
2433
+ var PLATFORM_ROOT2 = process.env.MAXY_PLATFORM_ROOT ?? resolve3(process.cwd(), "..");
2434
+ var ACCOUNTS_DIR = resolve3(PLATFORM_ROOT2, "..", "data/accounts");
2435
+ if (!existsSync4(PLATFORM_ROOT2)) {
2436
+ throw new Error(
2437
+ `PLATFORM_ROOT does not exist: ${PLATFORM_ROOT2}
2438
+ Set the MAXY_PLATFORM_ROOT environment variable to the absolute path of the platform directory.`
2439
+ );
2440
+ }
2441
+ function resolveAccount() {
2442
+ if (!existsSync4(ACCOUNTS_DIR)) return null;
2443
+ const usersFilePath = resolve3(PLATFORM_ROOT2, "config", "users.json");
2444
+ let usersJsonUserId = null;
2445
+ if (existsSync4(usersFilePath)) {
2446
+ try {
2447
+ const raw = readFileSync4(usersFilePath, "utf-8").trim();
2448
+ if (raw) {
2449
+ const users = JSON.parse(raw);
2450
+ if (users.length > 0) {
2451
+ usersJsonUserId = users[0].userId;
2452
+ }
2453
+ }
2454
+ } catch {
2455
+ }
2456
+ }
2457
+ const entries = readdirSync3(ACCOUNTS_DIR, { withFileTypes: true });
2458
+ let fallback = null;
2459
+ for (const entry of entries) {
2460
+ if (!entry.isDirectory()) continue;
2461
+ const configPath = resolve3(ACCOUNTS_DIR, entry.name, "account.json");
2462
+ if (!existsSync4(configPath)) continue;
2463
+ const raw = readFileSync4(configPath, "utf-8");
2464
+ let config;
2465
+ try {
2466
+ config = JSON.parse(raw);
2467
+ } catch {
2468
+ console.error(`[maxy] account.json is corrupt at ${configPath} \u2014 skipping`);
2469
+ continue;
2470
+ }
2471
+ if (!config.adminModel || !config.publicModel) {
2472
+ throw new Error(
2473
+ `[maxy] account.json at ${configPath} is missing required model fields (adminModel / publicModel). Update account.json with valid model identifiers.`
2474
+ );
2475
+ }
2476
+ const result = {
2477
+ accountId: config.accountId,
2478
+ accountDir: resolve3(ACCOUNTS_DIR, entry.name),
2479
+ config
2480
+ };
2481
+ if (usersJsonUserId && config.admins?.some((a) => a.userId === usersJsonUserId)) {
2482
+ return result;
2483
+ }
2484
+ if (!fallback) {
2485
+ fallback = result;
2486
+ }
2487
+ }
2488
+ if (usersJsonUserId && fallback) {
2489
+ console.warn(
2490
+ `[maxy] resolveAccount: no account matches users.json userId ${usersJsonUserId} \u2014 falling back to ${fallback.accountId}`
2491
+ );
2492
+ }
2493
+ return fallback;
2494
+ }
2495
+ function readAgentFile(accountDir, agentName, filename) {
2496
+ const filePath = resolve3(accountDir, "agents", agentName, filename);
2497
+ if (!existsSync4(filePath)) return null;
2498
+ const raw = readFileSync4(filePath, "utf-8");
2499
+ if (filename.endsWith(".md")) {
2500
+ return substituteBrandPlaceholders(raw, filePath);
2501
+ }
2502
+ return raw;
2503
+ }
2504
+ function readIdentity(accountDir, agentName) {
2505
+ return readAgentFile(accountDir, agentName, "IDENTITY.md");
2506
+ }
2507
+ var RESERVED_SLUGS = /* @__PURE__ */ new Set(["admin", "api", "assets", "brand", "bot", "privacy"]);
2508
+ var SLUG_PATTERN = /^[a-z][a-z0-9-]{2,49}$/;
2509
+ function validateAgentSlug(slug) {
2510
+ if (!SLUG_PATTERN.test(slug)) return false;
2511
+ if (RESERVED_SLUGS.has(slug)) return false;
2512
+ return true;
2513
+ }
2514
+ function resolveDefaultAgentSlug(accountDir) {
2515
+ const configPath = resolve3(accountDir, "account.json");
2516
+ if (!existsSync4(configPath)) {
2517
+ console.error("[agent-resolve] account.json not found \u2014 cannot resolve defaultAgent");
2518
+ return null;
2519
+ }
2520
+ let config;
2521
+ try {
2522
+ config = JSON.parse(readFileSync4(configPath, "utf-8"));
2523
+ } catch (err) {
2524
+ console.error("[agent-resolve] failed to read account.json:", err);
2525
+ return null;
2526
+ }
2527
+ if (!config.defaultAgent) {
2528
+ console.error("[agent-resolve] defaultAgent not configured in account.json \u2014 set it via the connect-whatsapp skill");
2529
+ return null;
2530
+ }
2531
+ const agentConfigPath = resolve3(accountDir, "agents", config.defaultAgent, "config.json");
2532
+ if (!existsSync4(agentConfigPath)) {
2533
+ console.error(`[agent-resolve] defaultAgent="${config.defaultAgent}" has no config.json at ${agentConfigPath}`);
2534
+ return null;
2535
+ }
2536
+ return config.defaultAgent;
2537
+ }
2538
+ function estimateTokens(text) {
2539
+ return Math.ceil(text.length / 4);
2540
+ }
2541
+ function resolveAgentConfig(accountDir, agentName) {
2542
+ let model = null;
2543
+ let plugins = null;
2544
+ let status = null;
2545
+ let displayName = null;
2546
+ let image = null;
2547
+ let imageShape = null;
2548
+ let showAgentName = false;
2549
+ let liveMemory = false;
2550
+ let knowledgeKeywords = null;
2551
+ let accessMode = "open";
2552
+ const MAX_KNOWLEDGE_KEYWORDS = 5;
2553
+ const configRaw = readAgentFile(accountDir, agentName, "config.json");
2554
+ if (configRaw) {
2555
+ let parsed;
2556
+ try {
2557
+ parsed = JSON.parse(configRaw);
2558
+ } catch {
2559
+ console.warn(`[agent-config] ${agentName}/config.json: invalid JSON \u2014 using defaults`);
2560
+ parsed = {};
2561
+ }
2562
+ model = typeof parsed.model === "string" ? parsed.model : null;
2563
+ plugins = Array.isArray(parsed.plugins) ? parsed.plugins : null;
2564
+ status = typeof parsed.status === "string" ? parsed.status : null;
2565
+ displayName = typeof parsed.displayName === "string" ? parsed.displayName : null;
2566
+ image = typeof parsed.image === "string" ? parsed.image : null;
2567
+ if (typeof parsed.imageShape === "string" && ["circle", "rounded"].includes(parsed.imageShape)) {
2568
+ imageShape = parsed.imageShape;
2569
+ }
2570
+ if (parsed.showAgentName === true) {
2571
+ showAgentName = true;
2572
+ } else if (parsed.showAgentName === "none") {
2573
+ showAgentName = "none";
2574
+ }
2575
+ if (image || imageShape || showAgentName) {
2576
+ console.log(`[agent-config] ${agentName}: image=${image || "(none)"} imageShape=${imageShape || "(none)"} showAgentName=${showAgentName}`);
2577
+ }
2578
+ if (typeof parsed.accessMode === "string" && ["gated", "paid"].includes(parsed.accessMode)) {
2579
+ accessMode = parsed.accessMode;
2580
+ }
2581
+ if (typeof parsed.liveMemory === "boolean") {
2582
+ liveMemory = parsed.liveMemory;
2583
+ } else if (typeof parsed.liveMemory === "string") {
2584
+ const lower = parsed.liveMemory.toLowerCase();
2585
+ if (lower === "true") {
2586
+ liveMemory = true;
2587
+ console.warn(`[agent-config] ${agentName}: liveMemory is string "true" \u2014 coercing to boolean. Fix the config to use a boolean value.`);
2588
+ } else if (lower === "false") {
2589
+ liveMemory = false;
2590
+ console.warn(`[agent-config] ${agentName}: liveMemory is string "false" \u2014 coercing to boolean. Fix the config to use a boolean value.`);
2591
+ } else {
2592
+ throw new Error(`[agent-config] ${agentName}: liveMemory has invalid string value "${parsed.liveMemory}" \u2014 expected boolean or "true"/"false"`);
2593
+ }
2594
+ } else if (parsed.liveMemory !== void 0 && parsed.liveMemory !== null) {
2595
+ throw new Error(`[agent-config] ${agentName}: liveMemory has invalid type ${typeof parsed.liveMemory} \u2014 expected boolean or "true"/"false"`);
2596
+ }
2597
+ if (Array.isArray(parsed.knowledgeKeywords) && parsed.knowledgeKeywords.length > 0) {
2598
+ const filtered = parsed.knowledgeKeywords.filter((k) => typeof k === "string" && k.trim()).map((k) => k.replace(/,/g, "").trim().toLowerCase()).filter(Boolean);
2599
+ if (filtered.length > MAX_KNOWLEDGE_KEYWORDS) {
2600
+ console.warn(`[agent-config] ${agentName}: knowledgeKeywords has ${filtered.length} entries \u2014 capping at ${MAX_KNOWLEDGE_KEYWORDS}`);
2601
+ }
2602
+ knowledgeKeywords = filtered.length > 0 ? filtered.slice(0, MAX_KNOWLEDGE_KEYWORDS) : null;
2603
+ }
2604
+ }
2605
+ let knowledge = null;
2606
+ let knowledgeBaked = false;
2607
+ const agentDir = resolve3(accountDir, "agents", agentName);
2608
+ const knowledgePath = resolve3(agentDir, "KNOWLEDGE.md");
2609
+ const summaryPath = resolve3(agentDir, "KNOWLEDGE-SUMMARY.md");
2610
+ const hasKnowledge = existsSync4(knowledgePath);
2611
+ const hasSummary = existsSync4(summaryPath);
2612
+ if (hasKnowledge && hasSummary) {
2613
+ const knowledgeMtime = statSync3(knowledgePath).mtimeMs;
2614
+ const summaryMtime = statSync3(summaryPath).mtimeMs;
2615
+ if (summaryMtime >= knowledgeMtime) {
2616
+ knowledge = readFileSync4(summaryPath, "utf-8");
2617
+ } else {
2618
+ console.warn(`[agent-config] ${agentName}: KNOWLEDGE-SUMMARY.md is stale (KNOWLEDGE.md is newer) \u2014 using full knowledge`);
2619
+ knowledge = readFileSync4(knowledgePath, "utf-8");
2620
+ }
2621
+ knowledgeBaked = true;
2622
+ } else if (hasKnowledge) {
2623
+ knowledge = readFileSync4(knowledgePath, "utf-8");
2624
+ knowledgeBaked = true;
2625
+ }
2626
+ let budget = null;
2627
+ const identityRaw = readAgentFile(accountDir, agentName, "IDENTITY.md");
2628
+ const soulRaw = readAgentFile(accountDir, agentName, "SOUL.md");
2629
+ if (identityRaw || soulRaw || knowledge) {
2630
+ const identityTokens = identityRaw ? estimateTokens(identityRaw) : 0;
2631
+ const soulTokens = soulRaw ? estimateTokens(soulRaw) : 0;
2632
+ const knowledgeTokens = knowledge ? estimateTokens(knowledge) : 0;
2633
+ budget = {
2634
+ identity: identityTokens,
2635
+ soul: soulTokens,
2636
+ knowledge: knowledgeTokens,
2637
+ plugins: 0,
2638
+ total: identityTokens + soulTokens + knowledgeTokens
2639
+ };
2640
+ }
2641
+ return { model, plugins, status, displayName, image, imageShape, showAgentName, knowledge, knowledgeBaked, liveMemory, knowledgeKeywords, budget, accessMode };
2642
+ }
2643
+ function getDefaultAccountId() {
2644
+ return resolveAccount()?.accountId ?? null;
2645
+ }
2646
+ function resolveUserAccounts(userId) {
2647
+ if (!existsSync4(ACCOUNTS_DIR)) return [];
2648
+ const results = [];
2649
+ const entries = readdirSync3(ACCOUNTS_DIR, { withFileTypes: true });
2650
+ for (const entry of entries) {
2651
+ if (!entry.isDirectory()) continue;
2652
+ const configPath = resolve3(ACCOUNTS_DIR, entry.name, "account.json");
2653
+ if (!existsSync4(configPath)) continue;
2654
+ let config;
2655
+ try {
2656
+ config = JSON.parse(readFileSync4(configPath, "utf-8"));
2657
+ } catch {
2658
+ console.error(`[session] account.json corrupt at ${configPath} \u2014 skipping`);
2659
+ continue;
2660
+ }
2661
+ const adminEntry = config.admins?.find((a) => a.userId === userId);
2662
+ if (adminEntry) {
2663
+ results.push({
2664
+ accountId: config.accountId,
2665
+ accountDir: resolve3(ACCOUNTS_DIR, entry.name),
2666
+ config,
2667
+ role: adminEntry.role
2668
+ });
2669
+ }
2670
+ }
2671
+ return results;
2672
+ }
2673
+
2674
+ // app/lib/claude-agent/session-store.ts
2675
+ function findFirstSubstantiveUserMessage(turns) {
2676
+ for (const t of turns) {
2677
+ if (t.role !== "user") continue;
2678
+ if (isMessageUseful(t.content)) return t.content;
2679
+ }
2680
+ return null;
2681
+ }
2682
+ var sessionStore = /* @__PURE__ */ new Map();
2683
+ function getSession2(sessionKey) {
2684
+ return sessionStore.get(sessionKey);
2685
+ }
2686
+ setSessionStoreRef(sessionStore);
2687
+ function registerSession(sessionKey, agentType, accountId, agentName, userId, userName, role) {
2688
+ const existing = sessionStore.get(sessionKey);
2689
+ if (existing) {
2690
+ existing.agentType = agentType;
2691
+ existing.accountId = accountId;
2692
+ existing.agentName = agentName ?? existing.agentName;
2693
+ existing.userId = userId ?? existing.userId;
2694
+ existing.userName = userName ?? existing.userName;
2695
+ existing.role = role ?? existing.role;
2696
+ return;
2697
+ }
2698
+ sessionStore.set(sessionKey, { createdAt: Date.now(), agentType, accountId, agentName, userId, userName, role });
2699
+ }
2700
+ function registerResumedSession(sessionKey, accountId, agentName, conversationId, messages) {
2701
+ const messageHistory = messages.map((m) => ({
2702
+ role: m.role,
2703
+ content: m.content,
2704
+ timestamp: m.timestamp ?? Date.now()
2705
+ }));
2706
+ sessionStore.set(sessionKey, {
2707
+ createdAt: Date.now(),
2708
+ agentType: "public",
2709
+ accountId,
2710
+ agentName,
2711
+ conversationId,
2712
+ messageHistory
2713
+ });
2714
+ }
2715
+ function getSessionMessages(sessionKey) {
2716
+ return sessionStore.get(sessionKey)?.messageHistory;
2717
+ }
2718
+ function clearSessionHistory(sessionKey) {
2719
+ const session = sessionStore.get(sessionKey);
2720
+ if (!session) return void 0;
2721
+ const previousConversationId = session.conversationId;
2722
+ session.agentSessionId = void 0;
2723
+ session.pendingCompactionSummary = void 0;
2724
+ session.stalledSubagents = void 0;
2725
+ session.pendingTrimmedMessages = void 0;
2726
+ session.pendingCommitmentOffers = void 0;
2727
+ session.pendingTurns = void 0;
2728
+ return previousConversationId;
2729
+ }
2730
+ function bufferPendingTurn(sessionKey, turn) {
2731
+ const session = sessionStore.get(sessionKey);
2732
+ if (!session) {
2733
+ console.error(`[conversation-gate] bufferPendingTurn: session not found sessionKey=${sessionKey.slice(0, 8)}\u2026`);
2734
+ return;
2735
+ }
2736
+ if (!session.pendingTurns) session.pendingTurns = [];
2737
+ session.pendingTurns.push(turn);
2738
+ console.log(`[conversation-gate] ${(/* @__PURE__ */ new Date()).toISOString()} buffered sessionKey=${sessionKey.slice(0, 8)} role=${turn.role} turnCount=${session.pendingTurns.filter((t) => t.role === "user").length}`);
2739
+ }
2740
+ function getPendingTurnCount(sessionKey) {
2741
+ const buf = sessionStore.get(sessionKey)?.pendingTurns;
2742
+ if (!buf) return 0;
2743
+ let n = 0;
2744
+ for (const t of buf) if (t.role === "user") n++;
2745
+ return n;
2746
+ }
2747
+ function drainPendingTurns(sessionKey) {
2748
+ const session = sessionStore.get(sessionKey);
2749
+ if (!session?.pendingTurns || session.pendingTurns.length === 0) return void 0;
2750
+ const drained = session.pendingTurns;
2751
+ session.pendingTurns = void 0;
2752
+ return drained;
2753
+ }
2754
+ async function maybeFlushConversationBuffer(sessionKey, agentType, accountId) {
2755
+ const sk8 = sessionKey.slice(0, 8);
2756
+ const session = sessionStore.get(sessionKey);
2757
+ if (!session) {
2758
+ console.log(`[admin/conversation-flush] sessionKey=${sk8} agentType=${agentType} result=missing-session`);
2759
+ return null;
2760
+ }
2761
+ if (session.conversationId) {
2762
+ console.log(`[admin/conversation-flush] sessionKey=${sk8} agentType=${agentType} result=already-flushed conversationId=${session.conversationId.slice(0, 8)}`);
2763
+ return { conversationId: session.conversationId, buffered: [] };
2764
+ }
2765
+ const bufferedCount = session.pendingTurns?.length ?? 0;
2766
+ if (bufferedCount === 0) {
2767
+ console.log(`[admin/conversation-flush] sessionKey=${sk8} agentType=${agentType} result=empty-buffer`);
2768
+ return null;
2769
+ }
2770
+ if (session.flushInFlight) return session.flushInFlight;
2771
+ const attempt = (async () => {
2772
+ let conversationId = null;
2773
+ if (agentType === "admin") {
2774
+ const userId = session.userId;
2775
+ if (!userId) {
2776
+ console.error(`[admin/conversation-flush] sessionKey=${sk8} agentType=admin result=missing-userId bufferedCount=${bufferedCount}`);
2777
+ return null;
2778
+ }
2779
+ conversationId = await createNewAdminConversation(userId, accountId, sessionKey, session.userName);
2780
+ } else {
2781
+ conversationId = (await ensureConversation(accountId, "public", sessionKey, void 0, session.agentName, void 0)).conversationId;
2782
+ }
2783
+ if (!conversationId) {
2784
+ console.error(`[admin/conversation-flush] sessionKey=${sk8} agentType=${agentType} result=writer-failed bufferedCount=${bufferedCount}`);
2785
+ return null;
2786
+ }
2787
+ session.conversationId = conversationId;
2788
+ if (agentType === "admin" && session.agentSessionId) {
2789
+ setConversationAgentSessionId(conversationId, session.agentSessionId).catch(() => {
2790
+ });
2791
+ }
2792
+ renameStreamLogsOnFlush(resolve4(ACCOUNTS_DIR, accountId), sessionKey, conversationId);
2793
+ const buffered = drainPendingTurns(sessionKey) ?? [];
2794
+ for (const turn of buffered) {
2795
+ persistMessage(conversationId, turn.role, turn.content, accountId, turn.tokens, turn.timestamp, turn.sender, turn.components, turn.attachments).catch((err) => {
2796
+ console.error(`[admin/conversation-flush] replay persistMessage failed role=${turn.role}: ${err instanceof Error ? err.message : String(err)}`);
2797
+ });
2798
+ }
2799
+ console.log(`[admin/conversation-flush] sessionKey=${sk8} agentType=${agentType} result=ok conversationId=${conversationId.slice(0, 8)} bufferedMessages=${buffered.length}`);
2800
+ return { conversationId, buffered };
2801
+ })();
2802
+ session.flushInFlight = attempt;
2803
+ try {
2804
+ return await attempt;
2805
+ } finally {
2806
+ if (session.flushInFlight === attempt) session.flushInFlight = void 0;
2807
+ }
2808
+ }
2809
+ function isDmChannelSessionKey(sessionKey) {
2810
+ return sessionKey.startsWith("whatsapp:") || sessionKey.startsWith("telegram:");
2811
+ }
2812
+ function getAgentNameForSession(sessionKey) {
2813
+ return sessionStore.get(sessionKey)?.agentName;
2814
+ }
2815
+ function listAdminSessionsInProgress(accountId, userId) {
2816
+ const rows = [];
2817
+ for (const [sessionKey, session] of Array.from(sessionStore.entries())) {
2818
+ if (session.agentType !== "admin") continue;
2819
+ if (session.accountId !== accountId) continue;
2820
+ if (session.userId !== userId) continue;
2821
+ if (session.conversationId) continue;
2822
+ rows.push({ sessionKey, createdAt: session.createdAt });
2823
+ }
2824
+ rows.sort((a, b) => b.createdAt - a.createdAt);
2825
+ return rows;
2826
+ }
2827
+ function validateSession(sessionKey, agentType) {
2828
+ const session = sessionStore.get(sessionKey);
2829
+ if (!session) return { ok: false, reason: "session-not-registered" };
2830
+ if (session.agentType !== agentType) return { ok: false, reason: "agent-type-mismatch" };
2831
+ if (Date.now() - session.createdAt > 24 * 60 * 60 * 1e3) {
2832
+ sessionStore.delete(sessionKey);
2833
+ return { ok: false, reason: "session-expired-age" };
2834
+ }
2835
+ if (session.grantExpiresAt && Date.now() > session.grantExpiresAt) {
2836
+ sessionStore.delete(sessionKey);
2837
+ return { ok: false, reason: "grant-expired" };
2838
+ }
2839
+ return { ok: true };
2840
+ }
2841
+ function storeAgentSessionId(sessionKey, agentSessionId) {
2842
+ const session = sessionStore.get(sessionKey);
2843
+ if (session) {
2844
+ session.agentSessionId = agentSessionId;
2845
+ console.error(`[session-store] storeAgentSessionId sessionKey=${sessionKey.slice(0, 12)}\u2026 sessionId=${agentSessionId.slice(0, 8)}\u2026`);
2846
+ if (session.agentType === "admin" && session.conversationId) {
2847
+ setConversationAgentSessionId(session.conversationId, agentSessionId).catch(() => {
2848
+ });
2849
+ }
2850
+ } else {
2851
+ console.error(`[session-store] storeAgentSessionId SKIPPED \u2014 no session entry sessionKey=${sessionKey.slice(0, 12)}\u2026 sessionId=${agentSessionId.slice(0, 8)}\u2026`);
2852
+ }
2853
+ }
2854
+ function getAgentSessionId(sessionKey) {
2855
+ return sessionStore.get(sessionKey)?.agentSessionId;
2856
+ }
2857
+ function setAgentSessionId(sessionKey, agentSessionId) {
2858
+ const session = sessionStore.get(sessionKey);
2859
+ if (!session) return false;
2860
+ session.agentSessionId = agentSessionId;
2861
+ return true;
2862
+ }
2863
+ function storePendingCompactionSummary(sessionKey, summary) {
2864
+ const session = sessionStore.get(sessionKey);
2865
+ if (session) session.pendingCompactionSummary = summary;
2866
+ }
2867
+ function consumePendingCompactionSummary(sessionKey) {
2868
+ const session = sessionStore.get(sessionKey);
2869
+ if (!session) return void 0;
2870
+ const summary = session.pendingCompactionSummary;
2871
+ delete session.pendingCompactionSummary;
2872
+ return summary;
2873
+ }
2874
+ function getAccountIdForSession(sessionKey) {
2875
+ return sessionStore.get(sessionKey)?.accountId;
2876
+ }
2877
+ function getUserIdForSession(sessionKey) {
2878
+ return sessionStore.get(sessionKey)?.userId;
2879
+ }
2880
+ function getUserNameForSession(sessionKey) {
2881
+ return sessionStore.get(sessionKey)?.userName;
2882
+ }
2883
+ function getRoleForSession(sessionKey) {
2884
+ return sessionStore.get(sessionKey)?.role;
2885
+ }
2886
+ function getConversationIdForSession(sessionKey) {
2887
+ return sessionStore.get(sessionKey)?.conversationId;
2888
+ }
2889
+ function setConversationIdForSession(sessionKey, conversationId) {
2890
+ const session = sessionStore.get(sessionKey);
2891
+ if (!session) return false;
2892
+ session.conversationId = conversationId;
2893
+ return true;
2894
+ }
2895
+ function unregisterSession(sessionKey) {
2896
+ return sessionStore.delete(sessionKey);
2897
+ }
2898
+ function getGroupSlugForSession(sessionKey) {
2899
+ return sessionStore.get(sessionKey)?.groupSlug;
2900
+ }
2901
+ function getVisitorIdForSession(sessionKey) {
2902
+ return sessionStore.get(sessionKey)?.visitorId;
2903
+ }
2904
+ function setGroupContextForSession(sessionKey, context) {
2905
+ const session = sessionStore.get(sessionKey);
2906
+ if (!session) return false;
2907
+ session.groupSlug = context.groupSlug;
2908
+ session.groupName = context.groupName;
2909
+ session.conversationId = context.conversationId;
2910
+ session.visitorId = context.visitorId;
2911
+ session.senderDisplayName = context.senderDisplayName;
2912
+ return true;
2913
+ }
2914
+ function registerGrantSession(sessionKey, accountId, agentName, opts) {
2915
+ sessionStore.set(sessionKey, {
2916
+ createdAt: Date.now(),
2917
+ agentType: "public",
2918
+ accountId,
2919
+ agentName,
2920
+ grantId: opts.grantId,
2921
+ grantExpiresAt: opts.grantExpiresAt,
2922
+ grantStatus: opts.grantStatus,
2923
+ grantDisplayName: opts.grantDisplayName,
2924
+ grantContactValue: opts.grantContactValue,
2925
+ setupRequired: opts.setupRequired
2926
+ });
2927
+ }
2928
+ function getGrantForSession(sessionKey) {
2929
+ const session = sessionStore.get(sessionKey);
2930
+ if (!session?.grantId) return void 0;
2931
+ return {
2932
+ grantId: session.grantId,
2933
+ grantExpiresAt: session.grantExpiresAt,
2934
+ grantStatus: session.grantStatus,
2935
+ grantDisplayName: session.grantDisplayName,
2936
+ grantContactValue: session.grantContactValue,
2937
+ setupRequired: session.setupRequired
2938
+ };
2939
+ }
2940
+ function completeGrantSetup(sessionKey) {
2941
+ const session = sessionStore.get(sessionKey);
2942
+ if (session) {
2943
+ session.setupRequired = false;
2944
+ session.grantStatus = "active";
2945
+ }
2946
+ }
2947
+ function getMessageHistory(sessionKey) {
2948
+ const session = sessionStore.get(sessionKey);
2949
+ if (!session) return [];
2950
+ if (!session.messageHistory) session.messageHistory = [];
2951
+ return session.messageHistory;
2952
+ }
2953
+ function appendMessage(sessionKey, role, content, timestamp) {
2954
+ if (!content) return;
2955
+ const session = sessionStore.get(sessionKey);
2956
+ if (!session) {
2957
+ console.error(`[managed] appendMessage: session not found for key ${sessionKey.slice(0, 8)}\u2026 (store size: ${sessionStore.size})`);
2958
+ return;
2959
+ }
2960
+ if (!session.messageHistory) session.messageHistory = [];
2961
+ session.messageHistory.push({ role, content, timestamp: timestamp ?? Date.now() });
2962
+ }
2963
+ function storePendingTrimmedMessages(sessionKey, messages) {
2964
+ const session = sessionStore.get(sessionKey);
2965
+ if (session) session.pendingTrimmedMessages = messages;
2966
+ }
2967
+ function consumePendingTrimmedMessages(sessionKey) {
2968
+ const session = sessionStore.get(sessionKey);
2969
+ if (!session) return void 0;
2970
+ const messages = session.pendingTrimmedMessages;
2971
+ delete session.pendingTrimmedMessages;
2972
+ return messages;
2973
+ }
2974
+ function storeStalledSubagent(sessionKey, info) {
2975
+ const session = sessionStore.get(sessionKey);
2976
+ if (!session) {
2977
+ console.error(`[stall-recovery] storeStalledSubagent: session not found for key ${sessionKey.slice(0, 8)}\u2026 \u2014 stall context lost`);
2978
+ return;
2979
+ }
2980
+ if (!session.stalledSubagents) session.stalledSubagents = [];
2981
+ session.stalledSubagents.push(info);
2982
+ }
2983
+ function consumeStalledSubagents(sessionKey) {
2984
+ const session = sessionStore.get(sessionKey);
2985
+ if (!session) return void 0;
2986
+ const stalls = session.stalledSubagents;
2987
+ delete session.stalledSubagents;
2988
+ return stalls && stalls.length > 0 ? stalls : void 0;
2989
+ }
2990
+ function setPendingCommitmentOffers(sessionKey, offers) {
2991
+ const session = sessionStore.get(sessionKey);
2992
+ if (session) session.pendingCommitmentOffers = offers;
2993
+ }
2994
+ function getAgentTypeForSession(sessionKey) {
2995
+ return sessionStore.get(sessionKey)?.agentType;
2996
+ }
2997
+ function clearMessageHistory(sessionKey) {
2998
+ const session = sessionStore.get(sessionKey);
2999
+ if (session) session.messageHistory = [];
3000
+ }
3001
+ var clearAgentSessionIdHandlers = [];
3002
+ function onClearAgentSessionId(handler) {
3003
+ clearAgentSessionIdHandlers.push(handler);
3004
+ }
3005
+ function clearAgentSessionId(sessionKey, reason) {
3006
+ const session = sessionStore.get(sessionKey);
3007
+ if (session) {
3008
+ session.agentSessionId = void 0;
3009
+ console.error(`[session-store] clearAgentSessionId sessionKey=${sessionKey.slice(0, 12)}\u2026 reason=${reason}`);
3010
+ } else {
3011
+ console.error(`[session-store] clearAgentSessionId SKIPPED \u2014 no session entry sessionKey=${sessionKey.slice(0, 12)}\u2026 reason=${reason}`);
3012
+ }
3013
+ for (const handler of clearAgentSessionIdHandlers) {
3014
+ try {
3015
+ handler(sessionKey, reason);
3016
+ } catch (err) {
3017
+ console.error(`[session-store] clearAgentSessionId handler threw: ${err instanceof Error ? err.message : String(err)}`);
3018
+ }
3019
+ }
3020
+ }
3021
+
3022
+ // app/lib/claude-agent/client-pool.ts
3023
+ var AsyncQueue = class {
3024
+ buffer = [];
3025
+ resolvers = [];
3026
+ closed = false;
3027
+ push(item) {
3028
+ if (this.closed) return;
3029
+ const resolver = this.resolvers.shift();
3030
+ if (resolver) resolver({ value: item, done: false });
3031
+ else this.buffer.push(item);
3032
+ }
3033
+ close() {
3034
+ if (this.closed) return;
3035
+ this.closed = true;
3036
+ while (this.resolvers.length > 0) {
3037
+ const r = this.resolvers.shift();
3038
+ r({ value: void 0, done: true });
3039
+ }
3040
+ }
3041
+ [Symbol.asyncIterator]() {
3042
+ return {
3043
+ next: () => new Promise((resolve5) => {
3044
+ if (this.buffer.length > 0) {
3045
+ resolve5({ value: this.buffer.shift(), done: false });
3046
+ } else if (this.closed) {
3047
+ resolve5({ value: void 0, done: true });
3048
+ } else {
3049
+ this.resolvers.push(resolve5);
3050
+ }
3051
+ }),
3052
+ return: async () => {
3053
+ this.close();
3054
+ return { value: void 0, done: true };
3055
+ }
3056
+ };
3057
+ }
3058
+ };
3059
+ var clientPool = /* @__PURE__ */ new Map();
3060
+ var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
3061
+ var idleEvictMs = (() => {
3062
+ const v = Number(process.env.CLAUDE_CLIENT_IDLE_MS);
3063
+ return Number.isFinite(v) && v > 0 ? v : DEFAULT_IDLE_MS;
3064
+ })();
3065
+ var ABORT_SDK_TIMEOUT_MS = 2e3;
3066
+ function acquireClient(sessionKey, opts, streamLog) {
3067
+ const existing = clientPool.get(sessionKey);
3068
+ if (existing) {
3069
+ existing.lastUsedAt = Date.now();
3070
+ existing.turnsServed += 1;
3071
+ safeWrite(
3072
+ streamLog,
3073
+ `[${isoTs()}] [client-warm-reuse] sessionKey=${sk(sessionKey)} ageMs=${Date.now() - existing.createdAt} turnsServed=${existing.turnsServed} cachedTokens=${existing.cachedTokensLastTurn}
3074
+ `
3075
+ );
3076
+ return { entry: existing, isCold: false };
3077
+ }
3078
+ const userQueue = new AsyncQueue();
3079
+ const abortController = new AbortController();
3080
+ let q;
3081
+ try {
3082
+ const sdkOptions = opts.buildSdkOptions();
3083
+ q = query({ prompt: userQueue, options: { ...sdkOptions, abortController } });
3084
+ } catch (err) {
3085
+ const reason = err instanceof Error ? err.message : String(err);
3086
+ safeWrite(
3087
+ streamLog,
3088
+ `[${isoTs()}] [client-spawn-error] sessionKey=${sk(sessionKey)} reason=${JSON.stringify(reason.slice(0, 200))}
3089
+ `
3090
+ );
3091
+ throw err;
3092
+ }
3093
+ const entry = {
3094
+ query: q,
3095
+ userQueue,
3096
+ abortController,
3097
+ inflight: null,
3098
+ createdAt: Date.now(),
3099
+ lastUsedAt: Date.now(),
3100
+ turnsServed: 1,
3101
+ resumedFromSessionId: opts.resumedFromSessionId,
3102
+ cachedTokensLastTurn: -1,
3103
+ accountId: opts.accountId,
3104
+ accountDir: opts.accountDir,
3105
+ logKey: opts.logKey
3106
+ };
3107
+ clientPool.set(sessionKey, entry);
3108
+ safeWrite(
3109
+ streamLog,
3110
+ `[${isoTs()}] [client-cold-create] sessionKey=${sk(sessionKey)} resumedFrom=${opts.resumedFromSessionId ?? "none"} createdAtMs=${entry.createdAt}
3111
+ `
3112
+ );
3113
+ return { entry, isCold: true };
3114
+ }
3115
+ function pushUserMessage(entry, content) {
3116
+ const msg = {
3117
+ type: "user",
3118
+ message: { role: "user", content },
3119
+ parent_tool_use_id: null
3120
+ };
3121
+ entry.userQueue.push(msg);
3122
+ }
3123
+ function setInflight(entry, promise) {
3124
+ entry.inflight = promise;
3125
+ promise.finally(() => {
3126
+ if (entry.inflight === promise) entry.inflight = null;
3127
+ }).catch(() => {
3128
+ });
3129
+ }
3130
+ function recordCachedTokens(entry, cachedTokens) {
3131
+ entry.cachedTokensLastTurn = cachedTokens;
3132
+ }
3133
+ function getActiveClient(sessionKey) {
3134
+ return clientPool.get(sessionKey);
3135
+ }
3136
+ function appendAbortLine(entry, line) {
3137
+ const path = resolvePath(entry.accountDir, "logs", `claude-agent-stream-${entry.logKey}.log`);
3138
+ try {
3139
+ appendFileSync2(path, line);
3140
+ } catch {
3141
+ }
3142
+ console.error(line.trimEnd());
3143
+ }
3144
+ async function interruptClient(sessionKey, _streamLog) {
3145
+ void _streamLog;
3146
+ const entry = clientPool.get(sessionKey);
3147
+ if (!entry) return;
3148
+ const startedAt = Date.now();
3149
+ let resolved = false;
3150
+ const timeout = new Promise(
3151
+ (resolve5) => setTimeout(() => resolve5("timeout"), ABORT_SDK_TIMEOUT_MS)
3152
+ );
3153
+ const sdkAbort = entry.query.interrupt().then(() => {
3154
+ resolved = true;
3155
+ return "ok";
3156
+ }).catch((err) => {
3157
+ resolved = true;
3158
+ return { error: err instanceof Error ? err.message : String(err) };
3159
+ });
3160
+ const result = await Promise.race([sdkAbort, timeout]);
3161
+ const durationMs = Date.now() - startedAt;
3162
+ if (result === "timeout" && !resolved) {
3163
+ appendAbortLine(
3164
+ entry,
3165
+ `[${isoTs()}] [client-abort] sessionKey=${sk(sessionKey)} method=signal durationMs=${durationMs}
3166
+ `
3167
+ );
3168
+ evictClient(sessionKey, "abort-signal-fallback", null);
3169
+ return;
3170
+ }
3171
+ if (typeof result === "object" && "error" in result) {
3172
+ appendAbortLine(
3173
+ entry,
3174
+ `[${isoTs()}] [client-abort] sessionKey=${sk(sessionKey)} method=sdk durationMs=${durationMs} error=${JSON.stringify(result.error.slice(0, 120))}
3175
+ `
3176
+ );
3177
+ evictClient(sessionKey, "abort-error", null);
3178
+ return;
3179
+ }
3180
+ appendAbortLine(
3181
+ entry,
3182
+ `[${isoTs()}] [client-abort] sessionKey=${sk(sessionKey)} method=sdk durationMs=${durationMs}
3183
+ `
3184
+ );
3185
+ }
3186
+ function evictClient(sessionKey, reason, streamLog) {
3187
+ const entry = clientPool.get(sessionKey);
3188
+ if (!entry) return false;
3189
+ const ageMs = Date.now() - entry.createdAt;
3190
+ clientPool.delete(sessionKey);
3191
+ try {
3192
+ entry.userQueue.close();
3193
+ } catch {
3194
+ }
3195
+ try {
3196
+ entry.query.close();
3197
+ } catch {
3198
+ }
3199
+ const line = `[${isoTs()}] [client-evict] reason=${reason} sessionKey=${sk(sessionKey)} ageMs=${ageMs} turnsServed=${entry.turnsServed}
3200
+ `;
3201
+ if (streamLog) {
3202
+ safeWrite(streamLog, line);
3203
+ } else {
3204
+ appendAbortLine(entry, line);
3205
+ }
3206
+ return true;
3207
+ }
3208
+ function acquireOneShotClient(sessionKey, opts, streamLog) {
3209
+ const userQueue = new AsyncQueue();
3210
+ const abortController = new AbortController();
3211
+ let q;
3212
+ try {
3213
+ const sdkOptions = opts.buildSdkOptions();
3214
+ q = query({ prompt: userQueue, options: { ...sdkOptions, abortController } });
3215
+ } catch (err) {
3216
+ const reason = err instanceof Error ? err.message : String(err);
3217
+ safeWrite(
3218
+ streamLog,
3219
+ `[${isoTs()}] [client-spawn-error] sessionKey=${sk(sessionKey)} site=compaction-one-shot reason=${JSON.stringify(reason.slice(0, 200))}
3220
+ `
3221
+ );
3222
+ throw err;
3223
+ }
3224
+ const entry = {
3225
+ query: q,
3226
+ userQueue,
3227
+ abortController,
3228
+ inflight: null,
3229
+ createdAt: Date.now(),
3230
+ lastUsedAt: Date.now(),
3231
+ turnsServed: 1,
3232
+ resumedFromSessionId: opts.resumedFromSessionId,
3233
+ cachedTokensLastTurn: -1,
3234
+ accountId: opts.accountId,
3235
+ accountDir: opts.accountDir,
3236
+ logKey: opts.logKey
3237
+ };
3238
+ safeWrite(
3239
+ streamLog,
3240
+ `[${isoTs()}] [client-cold-create] reason=compaction-one-shot sessionKey=${sk(sessionKey)} createdAtMs=${entry.createdAt}
3241
+ `
3242
+ );
3243
+ let evicted = false;
3244
+ const evict = (reason) => {
3245
+ if (evicted) return;
3246
+ evicted = true;
3247
+ const ageMs = Date.now() - entry.createdAt;
3248
+ try {
3249
+ entry.userQueue.close();
3250
+ } catch {
3251
+ }
3252
+ try {
3253
+ entry.query.close();
3254
+ } catch {
3255
+ }
3256
+ safeWrite(
3257
+ streamLog,
3258
+ `[${isoTs()}] [client-evict] reason=${reason} sessionKey=${sk(sessionKey)} ageMs=${ageMs}
3259
+ `
3260
+ );
3261
+ };
3262
+ return { entry, evict };
3263
+ }
3264
+ function recordCrash(sessionKey, reason, streamLog) {
3265
+ const entry = clientPool.get(sessionKey);
3266
+ if (!entry) return;
3267
+ const tail = JSON.stringify(reason.slice(-512));
3268
+ clientPool.delete(sessionKey);
3269
+ try {
3270
+ entry.userQueue.close();
3271
+ } catch {
3272
+ }
3273
+ try {
3274
+ entry.query.close();
3275
+ } catch {
3276
+ }
3277
+ safeWrite(
3278
+ streamLog,
3279
+ `[${isoTs()}] [client-crash] sessionKey=${sk(sessionKey)} reason=${JSON.stringify(reason.slice(0, 80))} tail=${tail}
3280
+ `
3281
+ );
3282
+ }
3283
+ var IDLE_TICK_MS = 6e4;
3284
+ var idleTickHandle = null;
3285
+ function evictIdleTick() {
3286
+ const now = Date.now();
3287
+ for (const [sessionKey, entry] of Array.from(clientPool.entries())) {
3288
+ if (entry.inflight !== null) continue;
3289
+ if (now - entry.lastUsedAt < idleEvictMs) continue;
3290
+ const ageMs = now - entry.createdAt;
3291
+ clientPool.delete(sessionKey);
3292
+ try {
3293
+ entry.userQueue.close();
3294
+ } catch {
3295
+ }
3296
+ try {
3297
+ entry.query.close();
3298
+ } catch {
3299
+ }
3300
+ console.error(
3301
+ `[${isoTs()}] [client-evict] reason=idle sessionKey=${sk(sessionKey)} ageMs=${ageMs} idleMs=${now - entry.lastUsedAt} turnsServed=${entry.turnsServed}`
3302
+ );
3303
+ }
3304
+ }
3305
+ function startIdleEvictTick() {
3306
+ if (idleTickHandle) return;
3307
+ idleTickHandle = setInterval(evictIdleTick, IDLE_TICK_MS);
3308
+ if (idleTickHandle.unref) idleTickHandle.unref();
3309
+ }
3310
+ function stopIdleEvictTick() {
3311
+ if (idleTickHandle) {
3312
+ clearInterval(idleTickHandle);
3313
+ idleTickHandle = null;
3314
+ }
3315
+ }
3316
+ startIdleEvictTick();
3317
+ onClearAgentSessionId((sessionKey, reason) => {
3318
+ const entry = clientPool.get(sessionKey);
3319
+ if (!entry) return;
3320
+ const ageMs = Date.now() - entry.createdAt;
3321
+ clientPool.delete(sessionKey);
3322
+ try {
3323
+ entry.userQueue.close();
3324
+ } catch {
3325
+ }
3326
+ try {
3327
+ entry.query.close();
3328
+ } catch {
3329
+ }
3330
+ console.error(
3331
+ `[${isoTs()}] [client-evict] reason=clearAgentSessionId-${reason} sessionKey=${sk(sessionKey)} ageMs=${ageMs} turnsServed=${entry.turnsServed}`
3332
+ );
3333
+ });
3334
+ function sk(sessionKey) {
3335
+ return sessionKey.length > 12 ? sessionKey.slice(0, 12) + "\u2026" : sessionKey;
3336
+ }
3337
+ function safeWrite(stream, line) {
3338
+ if (!stream || stream.destroyed) return;
3339
+ if (stream.writableEnded) return;
3340
+ try {
3341
+ stream.write(line);
3342
+ } catch {
3343
+ }
3344
+ }
3345
+ function _poolSnapshotForTest() {
3346
+ const now = Date.now();
3347
+ return Array.from(clientPool.entries()).map(([sessionKey, entry]) => ({
3348
+ sessionKey,
3349
+ ageMs: now - entry.createdAt,
3350
+ idleMs: now - entry.lastUsedAt,
3351
+ turnsServed: entry.turnsServed,
3352
+ inflight: entry.inflight !== null
3353
+ }));
3354
+ }
3355
+ function _evictAllForTest(reason = "test-tear-down") {
3356
+ for (const sessionKey of Array.from(clientPool.keys())) {
3357
+ const entry = clientPool.get(sessionKey);
3358
+ if (!entry) continue;
3359
+ clientPool.delete(sessionKey);
3360
+ try {
3361
+ entry.userQueue.close();
3362
+ } catch {
3363
+ }
3364
+ try {
3365
+ entry.query.close();
3366
+ } catch {
3367
+ }
3368
+ }
3369
+ void reason;
3370
+ }
3371
+
3372
+ export {
3373
+ substituteBrandPlaceholders,
3374
+ PLATFORM_ROOT2 as PLATFORM_ROOT,
3375
+ ACCOUNTS_DIR,
3376
+ resolveAccount,
3377
+ readAgentFile,
3378
+ readIdentity,
3379
+ validateAgentSlug,
3380
+ resolveDefaultAgentSlug,
3381
+ resolveAgentConfig,
3382
+ getDefaultAccountId,
3383
+ resolveUserAccounts,
3384
+ HAIKU_MODEL,
3385
+ contextWindow,
3386
+ getSession,
3387
+ runBootMigrations,
3388
+ embed,
3389
+ GREETING_DIRECTIVE,
3390
+ ensureConversation,
3391
+ findRecentConversation,
3392
+ findGroupBySlug,
3393
+ getGroupParticipants,
3394
+ checkGroupMembership,
3395
+ bindVisitorToGroup,
3396
+ getMessagesSince,
3397
+ getGroupMessagesForContext,
3398
+ backfillNullUserIdConversations,
3399
+ fetchBranding,
3400
+ persistToolCall,
3401
+ persistMessage,
3402
+ setConversationAgentSessionId,
3403
+ getAgentSessionIdForConversation,
3404
+ getRecentMessages,
3405
+ markComponentSubmitted,
3406
+ verifyConversationOwnership,
3407
+ verifyAndGetConversationUpdatedAt,
3408
+ searchMessages,
3409
+ listAdminSessions,
3410
+ deleteConversation,
3411
+ generateSessionLabel,
3412
+ autoLabelSession,
3413
+ renameConversation,
3414
+ getUserTimezone,
3415
+ loadAdminUserName,
3416
+ writeAdminUserAndPerson,
3417
+ loadUserProfile,
3418
+ loadSessionContext,
3419
+ loadOnboardingStep,
3420
+ writeReflectionPreferences,
3421
+ projectAgent,
3422
+ deleteAgentProjection,
3423
+ isoTs,
3424
+ isBrowserTool,
3425
+ runFailureDiagnostic,
3426
+ agentLogStream,
3427
+ preConversationLogStream,
3428
+ sigtermFlushStreamLogs,
3429
+ preflushStreamLogKey,
3430
+ findFirstSubstantiveUserMessage,
3431
+ getSession2,
3432
+ registerSession,
3433
+ registerResumedSession,
3434
+ getSessionMessages,
3435
+ clearSessionHistory,
3436
+ bufferPendingTurn,
3437
+ getPendingTurnCount,
3438
+ maybeFlushConversationBuffer,
3439
+ isDmChannelSessionKey,
3440
+ getAgentNameForSession,
3441
+ listAdminSessionsInProgress,
3442
+ validateSession,
3443
+ storeAgentSessionId,
3444
+ getAgentSessionId,
3445
+ setAgentSessionId,
3446
+ storePendingCompactionSummary,
3447
+ consumePendingCompactionSummary,
3448
+ getAccountIdForSession,
3449
+ getUserIdForSession,
3450
+ getUserNameForSession,
3451
+ getRoleForSession,
3452
+ getConversationIdForSession,
3453
+ setConversationIdForSession,
3454
+ unregisterSession,
3455
+ getGroupSlugForSession,
3456
+ getVisitorIdForSession,
3457
+ setGroupContextForSession,
3458
+ registerGrantSession,
3459
+ getGrantForSession,
3460
+ completeGrantSetup,
3461
+ getMessageHistory,
3462
+ appendMessage,
3463
+ storePendingTrimmedMessages,
3464
+ consumePendingTrimmedMessages,
3465
+ storeStalledSubagent,
3466
+ consumeStalledSubagents,
3467
+ setPendingCommitmentOffers,
3468
+ getAgentTypeForSession,
3469
+ clearMessageHistory,
3470
+ clearAgentSessionId,
3471
+ acquireClient,
3472
+ pushUserMessage,
3473
+ setInflight,
3474
+ recordCachedTokens,
3475
+ getActiveClient,
3476
+ interruptClient,
3477
+ evictClient,
3478
+ acquireOneShotClient,
3479
+ recordCrash,
3480
+ startIdleEvictTick,
3481
+ stopIdleEvictTick,
3482
+ _poolSnapshotForTest,
3483
+ _evictAllForTest
3484
+ };