@rubytech/create-realagent 1.0.864 → 1.0.866
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/payload/platform/plugins/admin/mcp/dist/__tests__/plugin-read-skill-resolution.test.d.ts +2 -0
- package/payload/platform/plugins/admin/mcp/dist/__tests__/plugin-read-skill-resolution.test.d.ts.map +1 -0
- package/payload/platform/plugins/admin/mcp/dist/__tests__/plugin-read-skill-resolution.test.js +67 -0
- package/payload/platform/plugins/admin/mcp/dist/__tests__/plugin-read-skill-resolution.test.js.map +1 -0
- package/payload/platform/plugins/admin/mcp/dist/index.js +44 -2
- package/payload/platform/plugins/admin/mcp/dist/index.js.map +1 -1
- package/payload/platform/plugins/admin/mcp/dist/skill-resolution.d.ts +17 -0
- package/payload/platform/plugins/admin/mcp/dist/skill-resolution.d.ts.map +1 -0
- package/payload/platform/plugins/admin/mcp/dist/skill-resolution.js +62 -0
- package/payload/platform/plugins/admin/mcp/dist/skill-resolution.js.map +1 -0
- package/payload/platform/plugins/admin/mcp/package.json +4 -2
- package/payload/platform/plugins/admin/mcp/vitest.config.ts +9 -0
- package/payload/platform/plugins/admin/skills/publish-site/SKILL.md +2 -0
- package/payload/platform/plugins/admin/skills/unzip-attachment/SKILL.md +2 -0
- package/payload/platform/templates/agents/admin/IDENTITY.md +1 -0
- package/payload/platform/templates/specialists/agents/content-producer.md +17 -3
- package/payload/server/chunk-FHNFKJZN.js +2143 -0
- package/payload/server/chunk-ND23BDBM.js +11312 -0
- package/payload/server/chunk-TOLLHW7W.js +1155 -0
- package/payload/server/chunk-UXLZ5Z3Y.js +667 -0
- package/payload/server/client-pool-2IUOSYDF.js +34 -0
- package/payload/server/cloudflare-task-tracker-OCFIVXEJ.js +20 -0
- package/payload/server/maxy-edge.js +5 -6
- package/payload/server/public/assets/{admin-CCML_l4E.js → admin-CLp1xGlJ.js} +1 -1
- package/payload/server/public/index.html +1 -1
- package/payload/server/server.js +132 -155
|
@@ -0,0 +1,2143 @@
|
|
|
1
|
+
// app/lib/neo4j-store.ts
|
|
2
|
+
import neo4j from "neo4j-driver";
|
|
3
|
+
import { randomUUID } from "crypto";
|
|
4
|
+
import { spawn } from "child_process";
|
|
5
|
+
import { readFileSync, readdirSync, existsSync, openSync, readSync, closeSync, statSync, rmSync } from "fs";
|
|
6
|
+
import { resolve } from "path";
|
|
7
|
+
|
|
8
|
+
// ../lib/models/src/index.ts
|
|
9
|
+
var OPUS_MODEL = "claude-opus-4-7";
|
|
10
|
+
var SONNET_MODEL = "claude-sonnet-4-6";
|
|
11
|
+
var HAIKU_MODEL = "claude-haiku-4-5";
|
|
12
|
+
var MODEL_CONTEXT_WINDOW = {
|
|
13
|
+
[OPUS_MODEL]: 2e5,
|
|
14
|
+
[SONNET_MODEL]: 2e5,
|
|
15
|
+
[HAIKU_MODEL]: 2e5
|
|
16
|
+
};
|
|
17
|
+
function contextWindow(model) {
|
|
18
|
+
return MODEL_CONTEXT_WINDOW[model] ?? 2e5;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// app/lib/neo4j-store.ts
|
|
22
|
+
var PLATFORM_ROOT = process.env.MAXY_PLATFORM_ROOT ?? resolve(process.cwd(), "..");
|
|
23
|
+
var driver = null;
|
|
24
|
+
function readPassword() {
|
|
25
|
+
if (process.env.NEO4J_PASSWORD) return process.env.NEO4J_PASSWORD;
|
|
26
|
+
const passwordFile = resolve(PLATFORM_ROOT, "config/.neo4j-password");
|
|
27
|
+
try {
|
|
28
|
+
return readFileSync(passwordFile, "utf-8").trim();
|
|
29
|
+
} catch {
|
|
30
|
+
throw new Error(
|
|
31
|
+
`Neo4j password not found. Expected at ${passwordFile} or in NEO4J_PASSWORD env var.`
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function getDriver() {
|
|
36
|
+
if (!driver) {
|
|
37
|
+
const uri = process.env.NEO4J_URI;
|
|
38
|
+
if (!uri) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
"[ui/neo4j-store] NEO4J_URI unset \u2014 refusing to default to bolt://localhost:7687"
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
const user = process.env.NEO4J_USER ?? "neo4j";
|
|
44
|
+
const password = readPassword();
|
|
45
|
+
console.error(`[ui/neo4j-store] resolved neo4j_uri=${uri}`);
|
|
46
|
+
driver = neo4j.driver(uri, neo4j.auth.basic(user, password), {
|
|
47
|
+
maxConnectionPoolSize: 5
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
return driver;
|
|
51
|
+
}
|
|
52
|
+
function getSession() {
|
|
53
|
+
return getDriver().session();
|
|
54
|
+
}
|
|
55
|
+
async function runAdminUserSelfHeal(args) {
|
|
56
|
+
const { selfHealAdminUser } = await import("./adminuser-self-heal-QAWOZ3JV.js");
|
|
57
|
+
return selfHealAdminUser({ driver: getDriver(), ...args });
|
|
58
|
+
}
|
|
59
|
+
process.on("SIGINT", async () => {
|
|
60
|
+
if (driver) {
|
|
61
|
+
await driver.close();
|
|
62
|
+
driver = null;
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
var OLLAMA_URL = process.env.OLLAMA_URL ?? "http://localhost:11434";
|
|
66
|
+
var EMBED_MODEL = process.env.EMBED_MODEL ?? "nomic-embed-text";
|
|
67
|
+
async function embed(text) {
|
|
68
|
+
const res = await fetch(`${OLLAMA_URL}/api/embed`, {
|
|
69
|
+
method: "POST",
|
|
70
|
+
headers: { "Content-Type": "application/json" },
|
|
71
|
+
body: JSON.stringify({ model: EMBED_MODEL, input: text }),
|
|
72
|
+
signal: AbortSignal.timeout(5e3)
|
|
73
|
+
});
|
|
74
|
+
if (!res.ok) {
|
|
75
|
+
const body = await res.text();
|
|
76
|
+
throw new Error(`Ollama embedding failed (${res.status}): ${body}`);
|
|
77
|
+
}
|
|
78
|
+
const data = await res.json();
|
|
79
|
+
return data.embeddings[0];
|
|
80
|
+
}
|
|
81
|
+
var sessionStoreRef = null;
|
|
82
|
+
function setSessionStoreRef(ref) {
|
|
83
|
+
sessionStoreRef = ref;
|
|
84
|
+
}
|
|
85
|
+
function getCachedConversationId(sessionKey) {
|
|
86
|
+
return sessionStoreRef?.get(sessionKey)?.conversationId;
|
|
87
|
+
}
|
|
88
|
+
function cacheConversationId(sessionKey, conversationId) {
|
|
89
|
+
const session = sessionStoreRef?.get(sessionKey);
|
|
90
|
+
if (session) {
|
|
91
|
+
session.conversationId = conversationId;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
var GREETING_DIRECTIVE = "[New session. Greet the visitor.]";
|
|
95
|
+
var DIRECTIVE_PREFIX = "[New session.";
|
|
96
|
+
async function ensureConversation(accountId, agentType, sessionKey, visitorId, agentSlug, userId) {
|
|
97
|
+
const cached = getCachedConversationId(sessionKey);
|
|
98
|
+
if (cached) return { conversationId: cached, created: false };
|
|
99
|
+
const conversationId = randomUUID();
|
|
100
|
+
const channel = sessionKey.startsWith("whatsapp:") ? "whatsapp" : sessionKey.startsWith("telegram:") ? "telegram" : "webchat";
|
|
101
|
+
const conversationSublabel = agentType === "admin" ? "AdminConversation" : "PublicConversation";
|
|
102
|
+
const handlerSlug = agentSlug ?? (agentType === "admin" ? "admin" : null);
|
|
103
|
+
const wantsHandledByEdge = !!handlerSlug;
|
|
104
|
+
const handledByClause = wantsHandledByEdge ? `WITH c, created
|
|
105
|
+
OPTIONAL MATCH (a:Agent {accountId: $accountId, slug: $handlerSlug})
|
|
106
|
+
FOREACH (_ IN CASE WHEN a IS NULL THEN [] ELSE [1] END | MERGE (c)-[:HANDLED_BY]->(a))
|
|
107
|
+
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`;
|
|
108
|
+
const session = getSession();
|
|
109
|
+
try {
|
|
110
|
+
const result = await session.run(
|
|
111
|
+
`OPTIONAL MATCH (existing:Conversation {sessionKey: $sessionKey})
|
|
112
|
+
WITH existing, existing IS NULL AS created
|
|
113
|
+
MERGE (c:Conversation {sessionKey: $sessionKey})
|
|
114
|
+
ON CREATE SET
|
|
115
|
+
c:${conversationSublabel},
|
|
116
|
+
c.conversationId = $conversationId,
|
|
117
|
+
c.accountId = $accountId,
|
|
118
|
+
c.agentType = $agentType,
|
|
119
|
+
c.channel = $channel,
|
|
120
|
+
${visitorId ? "c.visitorId = $visitorId," : ""}
|
|
121
|
+
${agentSlug ? "c.agentSlug = $agentSlug," : ""}
|
|
122
|
+
${userId ? "c.userId = $userId," : ""}
|
|
123
|
+
c.createdAt = datetime(),
|
|
124
|
+
c.updatedAt = datetime()
|
|
125
|
+
ON MATCH SET
|
|
126
|
+
c.updatedAt = datetime()
|
|
127
|
+
${handledByClause}`,
|
|
128
|
+
{
|
|
129
|
+
sessionKey,
|
|
130
|
+
conversationId,
|
|
131
|
+
accountId,
|
|
132
|
+
agentType,
|
|
133
|
+
channel,
|
|
134
|
+
...visitorId ? { visitorId } : {},
|
|
135
|
+
...agentSlug ? { agentSlug } : {},
|
|
136
|
+
...handlerSlug ? { handlerSlug } : {},
|
|
137
|
+
...userId ? { userId } : {}
|
|
138
|
+
}
|
|
139
|
+
);
|
|
140
|
+
const id = result.records[0]?.get("conversationId");
|
|
141
|
+
const created = result.records[0]?.get("created") === true;
|
|
142
|
+
if (id) {
|
|
143
|
+
cacheConversationId(sessionKey, id);
|
|
144
|
+
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}`);
|
|
145
|
+
if (wantsHandledByEdge) {
|
|
146
|
+
const handled = result.records[0]?.get("handledBy");
|
|
147
|
+
const id8 = id.slice(0, 8);
|
|
148
|
+
if (handled === true) {
|
|
149
|
+
console.error(`[agent-graph] handled-by-write conversationId=${id8} slug=${handlerSlug}`);
|
|
150
|
+
} else {
|
|
151
|
+
console.error(`[agent-graph] handled-by-skip reason=no-agent-node conversationId=${id8} slug=${handlerSlug}`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return { conversationId: id ?? null, created };
|
|
156
|
+
} catch (err) {
|
|
157
|
+
console.error(`[persist] ensureConversation failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
158
|
+
return { conversationId: null, created: false };
|
|
159
|
+
} finally {
|
|
160
|
+
await session.close();
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
async function findRecentConversation(visitorId, accountId, agentSlug, maxAgeHours = 24) {
|
|
164
|
+
const session = getSession();
|
|
165
|
+
try {
|
|
166
|
+
const result = await session.run(
|
|
167
|
+
`MATCH (c:Conversation {visitorId: $visitorId, accountId: $accountId, agentType: 'public'})
|
|
168
|
+
WHERE c.agentSlug = $agentSlug
|
|
169
|
+
AND c.updatedAt > datetime() - duration({hours: $maxAgeHours})
|
|
170
|
+
AND NOT c:Trashed
|
|
171
|
+
RETURN c.conversationId AS conversationId, c.sessionKey AS sessionKey
|
|
172
|
+
ORDER BY c.updatedAt DESC
|
|
173
|
+
LIMIT 1`,
|
|
174
|
+
{ visitorId, accountId, agentSlug, maxAgeHours: neo4j.int(maxAgeHours) },
|
|
175
|
+
{ timeout: 2e3 }
|
|
176
|
+
);
|
|
177
|
+
const record = result.records[0];
|
|
178
|
+
if (!record) return null;
|
|
179
|
+
const conversationId = record.get("conversationId");
|
|
180
|
+
const sessionKey = record.get("sessionKey");
|
|
181
|
+
if (!conversationId) return null;
|
|
182
|
+
console.log(`[persist] found recent conversation ${conversationId.slice(0, 8)}\u2026 for visitor ${visitorId.slice(0, 8)}\u2026`);
|
|
183
|
+
return { conversationId, sessionKey };
|
|
184
|
+
} catch (err) {
|
|
185
|
+
console.error(`[persist] findRecentConversation failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
186
|
+
return null;
|
|
187
|
+
} finally {
|
|
188
|
+
await session.close();
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
async function findGroupBySlug(groupSlug, accountId) {
|
|
192
|
+
const session = getSession();
|
|
193
|
+
try {
|
|
194
|
+
const result = await session.run(
|
|
195
|
+
`MATCH (c:Conversation {groupSlug: $groupSlug, accountId: $accountId, type: 'group'})
|
|
196
|
+
WHERE NOT c:Trashed
|
|
197
|
+
RETURN c.conversationId AS conversationId, c.groupName AS groupName, c.agentSlug AS agentSlug`,
|
|
198
|
+
{ groupSlug, accountId },
|
|
199
|
+
{ timeout: 2e3 }
|
|
200
|
+
);
|
|
201
|
+
const record = result.records[0];
|
|
202
|
+
if (!record) return null;
|
|
203
|
+
return {
|
|
204
|
+
conversationId: record.get("conversationId"),
|
|
205
|
+
groupName: record.get("groupName"),
|
|
206
|
+
agentSlug: record.get("agentSlug")
|
|
207
|
+
};
|
|
208
|
+
} catch (err) {
|
|
209
|
+
console.error(`[group] findGroupBySlug failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
210
|
+
return null;
|
|
211
|
+
} finally {
|
|
212
|
+
await session.close();
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async function getGroupParticipants(conversationId) {
|
|
216
|
+
const session = getSession();
|
|
217
|
+
try {
|
|
218
|
+
const result = await session.run(
|
|
219
|
+
`MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {conversationId: $conversationId})
|
|
220
|
+
RETURN p.givenName AS givenName, p.familyName AS familyName,
|
|
221
|
+
r.displayName AS displayName, r.joinedAt AS joinedAt, r.visitorId AS visitorId`,
|
|
222
|
+
{ conversationId }
|
|
223
|
+
);
|
|
224
|
+
return result.records.map((r) => ({
|
|
225
|
+
displayName: r.get("displayName") || r.get("givenName"),
|
|
226
|
+
givenName: r.get("givenName"),
|
|
227
|
+
familyName: r.get("familyName"),
|
|
228
|
+
joinedAt: String(r.get("joinedAt")),
|
|
229
|
+
visitorId: r.get("visitorId")
|
|
230
|
+
}));
|
|
231
|
+
} catch (err) {
|
|
232
|
+
console.error(`[group] getGroupParticipants failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
233
|
+
return [];
|
|
234
|
+
} finally {
|
|
235
|
+
await session.close();
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async function checkGroupMembership(conversationId, visitorId) {
|
|
239
|
+
const session = getSession();
|
|
240
|
+
try {
|
|
241
|
+
const result = await session.run(
|
|
242
|
+
`MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {conversationId: $conversationId})
|
|
243
|
+
WHERE r.visitorId = $visitorId
|
|
244
|
+
RETURN r.displayName AS displayName
|
|
245
|
+
LIMIT 1`,
|
|
246
|
+
{ conversationId, visitorId }
|
|
247
|
+
);
|
|
248
|
+
return result.records[0]?.get("displayName") ?? null;
|
|
249
|
+
} catch (err) {
|
|
250
|
+
console.error(`[group] checkGroupMembership failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
251
|
+
return null;
|
|
252
|
+
} finally {
|
|
253
|
+
await session.close();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
async function bindVisitorToGroup(conversationId, visitorId, personEmail, personPhone) {
|
|
257
|
+
const session = getSession();
|
|
258
|
+
try {
|
|
259
|
+
const result = await session.run(
|
|
260
|
+
`MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {conversationId: $conversationId})
|
|
261
|
+
WHERE ($email IS NOT NULL AND p.email = $email)
|
|
262
|
+
OR ($phone IS NOT NULL AND p.telephone = $phone)
|
|
263
|
+
SET r.visitorId = $visitorId
|
|
264
|
+
RETURN r.displayName AS displayName
|
|
265
|
+
LIMIT 1`,
|
|
266
|
+
{
|
|
267
|
+
conversationId,
|
|
268
|
+
visitorId,
|
|
269
|
+
email: personEmail ?? null,
|
|
270
|
+
phone: personPhone ?? null
|
|
271
|
+
}
|
|
272
|
+
);
|
|
273
|
+
const name = result.records[0]?.get("displayName");
|
|
274
|
+
if (name) {
|
|
275
|
+
console.error(`[group] joined id=${conversationId.slice(0, 8)}\u2026 visitor=${visitorId.slice(0, 8)}\u2026`);
|
|
276
|
+
} else {
|
|
277
|
+
console.error(`[group] auth-denied id=${conversationId.slice(0, 8)}\u2026 visitor=${visitorId.slice(0, 8)}\u2026`);
|
|
278
|
+
}
|
|
279
|
+
return name ? { displayName: name } : null;
|
|
280
|
+
} catch (err) {
|
|
281
|
+
console.error(`[group] bindVisitorToGroup failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
282
|
+
return null;
|
|
283
|
+
} finally {
|
|
284
|
+
await session.close();
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
async function getMessagesSince(conversationId, since, limit = 100) {
|
|
288
|
+
const session = getSession();
|
|
289
|
+
try {
|
|
290
|
+
const result = await session.run(
|
|
291
|
+
`MATCH (m:Message)-[:PART_OF]->(c:Conversation {conversationId: $conversationId})
|
|
292
|
+
WHERE m.createdAt > datetime($since)
|
|
293
|
+
RETURN m.messageId AS messageId, m.role AS role, m.content AS content,
|
|
294
|
+
m.senderName AS senderName, m.senderVisitorId AS senderVisitorId,
|
|
295
|
+
m.createdAt AS createdAt
|
|
296
|
+
ORDER BY m.createdAt ASC
|
|
297
|
+
LIMIT $limit`,
|
|
298
|
+
{ conversationId, since, limit: neo4j.int(limit) },
|
|
299
|
+
{ timeout: 3e3 }
|
|
300
|
+
);
|
|
301
|
+
return result.records.map((r) => ({
|
|
302
|
+
messageId: r.get("messageId"),
|
|
303
|
+
role: r.get("role"),
|
|
304
|
+
content: r.get("content"),
|
|
305
|
+
senderName: r.get("senderName"),
|
|
306
|
+
senderVisitorId: r.get("senderVisitorId"),
|
|
307
|
+
createdAt: String(r.get("createdAt"))
|
|
308
|
+
}));
|
|
309
|
+
} catch (err) {
|
|
310
|
+
console.error(`[group] getMessagesSince failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
311
|
+
return [];
|
|
312
|
+
} finally {
|
|
313
|
+
await session.close();
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
async function getGroupMessagesForContext(conversationId, limit = 50) {
|
|
317
|
+
const session = getSession();
|
|
318
|
+
try {
|
|
319
|
+
const result = await session.run(
|
|
320
|
+
`MATCH (m:Message)-[:PART_OF]->(c:Conversation {conversationId: $conversationId})
|
|
321
|
+
WITH m ORDER BY m.createdAt DESC LIMIT $limit
|
|
322
|
+
RETURN m.role AS role, m.content AS content, m.senderName AS senderName
|
|
323
|
+
ORDER BY m.createdAt ASC`,
|
|
324
|
+
{ conversationId, limit: neo4j.int(limit) }
|
|
325
|
+
);
|
|
326
|
+
return result.records.map((r) => ({
|
|
327
|
+
role: r.get("role"),
|
|
328
|
+
content: r.get("content"),
|
|
329
|
+
senderName: r.get("senderName")
|
|
330
|
+
}));
|
|
331
|
+
} catch (err) {
|
|
332
|
+
console.error(`[group] getGroupMessagesForContext failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
333
|
+
return [];
|
|
334
|
+
} finally {
|
|
335
|
+
await session.close();
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
async function backfillNullUserIdConversations(userId) {
|
|
339
|
+
if (!userId) {
|
|
340
|
+
console.warn(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: skipped \u2014 no userId provided (no Owner in users.json?)`);
|
|
341
|
+
return 0;
|
|
342
|
+
}
|
|
343
|
+
const session = getSession();
|
|
344
|
+
try {
|
|
345
|
+
const result = await session.run(
|
|
346
|
+
`MATCH (c:Conversation {agentType: 'admin'})
|
|
347
|
+
WHERE c.userId IS NULL
|
|
348
|
+
SET c.userId = $userId
|
|
349
|
+
RETURN count(c) AS updated`,
|
|
350
|
+
{ userId }
|
|
351
|
+
);
|
|
352
|
+
const updated = result.records[0]?.get("updated")?.toNumber?.() ?? result.records[0]?.get("updated") ?? 0;
|
|
353
|
+
if (updated > 0) {
|
|
354
|
+
console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: set userId on ${updated} admin conversations`);
|
|
355
|
+
} else {
|
|
356
|
+
console.log(`[session] ${(/* @__PURE__ */ new Date()).toISOString()} backfill: no orphaned admin conversations found`);
|
|
357
|
+
}
|
|
358
|
+
return typeof updated === "number" ? updated : 0;
|
|
359
|
+
} catch (err) {
|
|
360
|
+
console.error(`[session] backfillNullUserIdConversations failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
361
|
+
return 0;
|
|
362
|
+
} finally {
|
|
363
|
+
await session.close();
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
async function createNewAdminConversation(userId, accountId, sessionKey, adminName, preMintedConversationId) {
|
|
367
|
+
if (!userId || !sessionKey || !accountId) {
|
|
368
|
+
console.error(`[admin/conversation-write] schema-violation userId=${userId ? "set" : "EMPTY"} sessionKey=${sessionKey ? "set" : "EMPTY"} accountId=${accountId ? "set" : "EMPTY"}`);
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
const conversationId = preMintedConversationId ?? randomUUID();
|
|
372
|
+
const session = getSession();
|
|
373
|
+
try {
|
|
374
|
+
const result = await session.run(
|
|
375
|
+
`OPTIONAL MATCH (existing:AdminUser {userId: $userId})
|
|
376
|
+
WITH existing IS NULL AS adminUserCreated
|
|
377
|
+
MERGE (au:AdminUser {userId: $userId})
|
|
378
|
+
ON CREATE SET au.accountId = $accountId,
|
|
379
|
+
au.name = COALESCE($adminName, 'Admin'),
|
|
380
|
+
au.createdAt = datetime(),
|
|
381
|
+
au.scope = 'admin'
|
|
382
|
+
CREATE (c:Conversation:AdminConversation {
|
|
383
|
+
conversationId: $conversationId,
|
|
384
|
+
sessionKey: $sessionKey,
|
|
385
|
+
accountId: $accountId,
|
|
386
|
+
agentType: 'admin',
|
|
387
|
+
userId: $userId,
|
|
388
|
+
createdBySource: 'admin-conversation',
|
|
389
|
+
createdAt: datetime(),
|
|
390
|
+
updatedAt: datetime()
|
|
391
|
+
})-[:STARTED_BY]->(au)
|
|
392
|
+
RETURN adminUserCreated`,
|
|
393
|
+
{ conversationId, sessionKey, accountId, userId, adminName: adminName ?? null }
|
|
394
|
+
);
|
|
395
|
+
const adminUserCreated = result.records[0]?.get("adminUserCreated") === true;
|
|
396
|
+
cacheConversationId(sessionKey, conversationId);
|
|
397
|
+
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}`);
|
|
398
|
+
return conversationId;
|
|
399
|
+
} catch (err) {
|
|
400
|
+
console.error(`[session] createNewAdminConversation failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
401
|
+
return null;
|
|
402
|
+
} finally {
|
|
403
|
+
await session.close();
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
var HEX_COLOR_RE = /^#[0-9a-fA-F]{3,8}$/;
|
|
407
|
+
async function fetchBranding(accountId) {
|
|
408
|
+
const session = getSession();
|
|
409
|
+
try {
|
|
410
|
+
const result = await session.run(
|
|
411
|
+
`MATCH (b:LocalBusiness {accountId: $accountId})
|
|
412
|
+
OPTIONAL MATCH (b)-[:HAS_BRAND_ASSET]->(logo:ImageObject {purpose: "logo"})
|
|
413
|
+
OPTIONAL MATCH (b)-[:HAS_BRAND_ASSET]->(icon:ImageObject {purpose: "icon"})
|
|
414
|
+
RETURN b.name AS name,
|
|
415
|
+
b.primaryColor AS primaryColor,
|
|
416
|
+
b.accentColor AS accentColor,
|
|
417
|
+
b.backgroundColor AS backgroundColor,
|
|
418
|
+
b.tagline AS tagline,
|
|
419
|
+
logo.contentUrl AS logoUrl,
|
|
420
|
+
icon.contentUrl AS faviconUrl`,
|
|
421
|
+
{ accountId },
|
|
422
|
+
{ timeout: 2e3 }
|
|
423
|
+
);
|
|
424
|
+
const record = result.records[0];
|
|
425
|
+
if (!record) return null;
|
|
426
|
+
const name = record.get("name");
|
|
427
|
+
if (!name) return null;
|
|
428
|
+
const primaryColor = record.get("primaryColor");
|
|
429
|
+
const accentColor = record.get("accentColor");
|
|
430
|
+
const backgroundColor = record.get("backgroundColor");
|
|
431
|
+
const tagline = record.get("tagline");
|
|
432
|
+
const logoUrl = record.get("logoUrl");
|
|
433
|
+
const faviconUrl = record.get("faviconUrl");
|
|
434
|
+
const hasBranding = primaryColor || accentColor || backgroundColor || tagline || logoUrl || faviconUrl;
|
|
435
|
+
if (!hasBranding) return null;
|
|
436
|
+
const branding = { name };
|
|
437
|
+
if (primaryColor && HEX_COLOR_RE.test(primaryColor)) branding.primaryColor = primaryColor;
|
|
438
|
+
if (accentColor && HEX_COLOR_RE.test(accentColor)) branding.accentColor = accentColor;
|
|
439
|
+
if (backgroundColor && HEX_COLOR_RE.test(backgroundColor)) branding.backgroundColor = backgroundColor;
|
|
440
|
+
if (tagline) branding.tagline = tagline;
|
|
441
|
+
if (logoUrl) branding.logoUrl = logoUrl;
|
|
442
|
+
if (faviconUrl) branding.faviconUrl = faviconUrl;
|
|
443
|
+
console.error(`[branding] resolved for accountId=${accountId.slice(0, 8)}\u2026: primary=${branding.primaryColor ?? "\u2013"} logo=${branding.logoUrl ? "yes" : "no"}`);
|
|
444
|
+
return branding;
|
|
445
|
+
} catch (err) {
|
|
446
|
+
console.error(`[branding] fetchBranding failed for accountId=${accountId.slice(0, 8)}\u2026: ${err instanceof Error ? err.message : String(err)}`);
|
|
447
|
+
return null;
|
|
448
|
+
} finally {
|
|
449
|
+
await session.close();
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
async function persistToolCall(record) {
|
|
453
|
+
const session = getSession();
|
|
454
|
+
try {
|
|
455
|
+
const optionalFields = [
|
|
456
|
+
record.pluginName != null ? ", pluginName: $pluginName" : "",
|
|
457
|
+
record.error != null ? ", error: $error" : "",
|
|
458
|
+
record.subagentType != null ? ", subagentType: $subagentType" : "",
|
|
459
|
+
record.subagentDescription != null ? ", subagentDescription: $subagentDescription" : "",
|
|
460
|
+
record.approvalState != null ? ", approvalState: $approvalState" : "",
|
|
461
|
+
record.originalInput != null ? ", originalInput: $originalInput" : ""
|
|
462
|
+
].join("");
|
|
463
|
+
const res = await session.run(
|
|
464
|
+
`MATCH (c:Conversation {conversationId: $conversationId})
|
|
465
|
+
CREATE (c)-[:HAS_TOOL_CALL]->(tc:ToolCall {
|
|
466
|
+
callId: $callId,
|
|
467
|
+
toolName: $toolName,
|
|
468
|
+
input: $input,
|
|
469
|
+
output: $output,
|
|
470
|
+
isError: $isError,
|
|
471
|
+
agentType: $agentType,
|
|
472
|
+
accountId: $accountId,
|
|
473
|
+
conversationId: $conversationId,
|
|
474
|
+
createdBySource: 'persist-tool-call',
|
|
475
|
+
createdBySession: $conversationId,
|
|
476
|
+
startedAt: datetime($startedAt),
|
|
477
|
+
completedAt: datetime($completedAt)
|
|
478
|
+
${optionalFields}
|
|
479
|
+
})`,
|
|
480
|
+
{
|
|
481
|
+
callId: record.callId,
|
|
482
|
+
toolName: record.toolName,
|
|
483
|
+
input: record.input,
|
|
484
|
+
output: record.output,
|
|
485
|
+
isError: record.isError,
|
|
486
|
+
agentType: record.agentType,
|
|
487
|
+
accountId: record.accountId,
|
|
488
|
+
conversationId: record.conversationId,
|
|
489
|
+
startedAt: record.startedAt,
|
|
490
|
+
completedAt: record.completedAt,
|
|
491
|
+
...record.pluginName != null ? { pluginName: record.pluginName } : {},
|
|
492
|
+
...record.error != null ? { error: record.error } : {},
|
|
493
|
+
...record.subagentType != null ? { subagentType: record.subagentType } : {},
|
|
494
|
+
...record.subagentDescription != null ? { subagentDescription: record.subagentDescription } : {},
|
|
495
|
+
...record.approvalState != null ? { approvalState: record.approvalState } : {},
|
|
496
|
+
...record.originalInput != null ? { originalInput: record.originalInput } : {}
|
|
497
|
+
}
|
|
498
|
+
);
|
|
499
|
+
if (res.summary.counters.updates().nodesCreated === 0) {
|
|
500
|
+
console.error(
|
|
501
|
+
`[persist] tool-call skipped: conversation ${record.conversationId.slice(0, 8)}\u2026 not found for tool=${record.toolName}`
|
|
502
|
+
);
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
console.error(`[persist] tool-call persisted: name=${record.toolName} conversation=${record.conversationId.slice(0, 8)}\u2026${record.approvalState ? ` approval=${record.approvalState}` : ""}`);
|
|
506
|
+
} catch (err) {
|
|
507
|
+
console.error(`[persist] tool-call write failed: name=${record.toolName} error=${err instanceof Error ? err.message : String(err)}`);
|
|
508
|
+
} finally {
|
|
509
|
+
await session.close();
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
var SUMMARY_MAX_LEN = 200;
|
|
513
|
+
var persistMessageLocks = /* @__PURE__ */ new Map();
|
|
514
|
+
async function persistMessage(conversationId, role, content, accountId, tokens, createdAt, sender, components, attachments) {
|
|
515
|
+
if (!content) return null;
|
|
516
|
+
const messageId = randomUUID();
|
|
517
|
+
const summary = role === "user" ? content.slice(0, SUMMARY_MAX_LEN).trim() : "";
|
|
518
|
+
let embedding = null;
|
|
519
|
+
try {
|
|
520
|
+
embedding = await embed(content);
|
|
521
|
+
} catch (err) {
|
|
522
|
+
console.error(`[persist] Embedding failed, storing without: ${err instanceof Error ? err.message : String(err)}`);
|
|
523
|
+
}
|
|
524
|
+
const prev = persistMessageLocks.get(conversationId);
|
|
525
|
+
const waited = prev !== void 0;
|
|
526
|
+
let release;
|
|
527
|
+
const mine = new Promise((resolve2) => {
|
|
528
|
+
release = resolve2;
|
|
529
|
+
});
|
|
530
|
+
const chained = (prev ?? Promise.resolve()).then(() => mine);
|
|
531
|
+
persistMessageLocks.set(conversationId, chained);
|
|
532
|
+
await prev;
|
|
533
|
+
const session = getSession();
|
|
534
|
+
try {
|
|
535
|
+
const result = await session.run(
|
|
536
|
+
`MATCH (c:Conversation {conversationId: $conversationId})
|
|
537
|
+
OPTIONAL MATCH (tail:Message)-[:PART_OF]->(c)
|
|
538
|
+
WHERE NOT (tail)-[:NEXT]->(:Message)
|
|
539
|
+
AND (tail:UserMessage OR tail:AssistantMessage)
|
|
540
|
+
// Task 857 \u2014 sublabel-scope the tail to the agent-path's own sublabels.
|
|
541
|
+
// Without this, a Task-857 :WhatsAppMessage row (no outgoing :NEXT)
|
|
542
|
+
// would be picked as tail and the agent-path would chain
|
|
543
|
+
// :WhatsAppMessage\u2192:UserMessage, crossing the live-channel chain.
|
|
544
|
+
// The live writer's tail predicate is sublabel-scoped to
|
|
545
|
+
// :WhatsAppMessage; this clause is the matching defence on the
|
|
546
|
+
// agent side. Backward-compatible \u2014 pre-Task-857 graphs only carry
|
|
547
|
+
// UserMessage/AssistantMessage sublabels under :Message.
|
|
548
|
+
// Capture whether THIS write's guard will fire. Read c.summary
|
|
549
|
+
// before the SET so the boolean reflects the pre-state, not the
|
|
550
|
+
// post-state \u2014 a false positive otherwise when a new user message
|
|
551
|
+
// happens to equal an already-set summary (verbatim retry, short
|
|
552
|
+
// catchphrase) and fooled a post-state equality check.
|
|
553
|
+
WITH c, tail, (c.summary IS NULL AND $role = 'user' AND $summary <> '') AS summarySetThisWrite
|
|
554
|
+
CREATE (m:Message:${role === "user" ? "UserMessage" : "AssistantMessage"} {
|
|
555
|
+
messageId: $messageId,
|
|
556
|
+
conversationId: $conversationId,
|
|
557
|
+
accountId: $accountId,
|
|
558
|
+
role: $role,
|
|
559
|
+
content: $content,
|
|
560
|
+
createdAt: ${createdAt ? "datetime($createdAt)" : "datetime()"}
|
|
561
|
+
${embedding ? ", embedding: $embedding" : ""}
|
|
562
|
+
${sender ? ", senderVisitorId: $senderVisitorId, senderName: $senderName" : ""}
|
|
563
|
+
${tokens?.inputTokens != null ? ", inputTokens: $inputTokens" : ""}
|
|
564
|
+
${tokens?.outputTokens != null ? ", outputTokens: $outputTokens" : ""}
|
|
565
|
+
${tokens?.cacheReadTokens != null ? ", cacheReadTokens: $cacheReadTokens" : ""}
|
|
566
|
+
${tokens?.cacheCreationTokens != null ? ", cacheCreationTokens: $cacheCreationTokens" : ""}
|
|
567
|
+
})
|
|
568
|
+
SET c.updatedAt = datetime()
|
|
569
|
+
CREATE (m)-[:PART_OF]->(c)
|
|
570
|
+
FOREACH (prev IN CASE WHEN tail IS NULL THEN [] ELSE [tail] END |
|
|
571
|
+
CREATE (prev)-[:NEXT]->(m)
|
|
572
|
+
)
|
|
573
|
+
FOREACH (_ IN CASE WHEN summarySetThisWrite THEN [1] ELSE [] END |
|
|
574
|
+
SET c.summary = $summary
|
|
575
|
+
)
|
|
576
|
+
FOREACH (comp IN $components |
|
|
577
|
+
CREATE (m)-[:HAS_COMPONENT]->(:Component {
|
|
578
|
+
componentId: comp.componentId,
|
|
579
|
+
conversationId: $conversationId,
|
|
580
|
+
accountId: $accountId,
|
|
581
|
+
messageId: $messageId,
|
|
582
|
+
name: comp.name,
|
|
583
|
+
data: comp.data,
|
|
584
|
+
ordinal: comp.ordinal,
|
|
585
|
+
textOffset: comp.textOffset,
|
|
586
|
+
submitted: false,
|
|
587
|
+
createdAt: datetime(),
|
|
588
|
+
// Task 942 \u2014 store the artefact attachmentId on the :Component
|
|
589
|
+
// itself when this is a PERSISTENT_COMPONENTS write whose disk
|
|
590
|
+
// write succeeded. Field is null for non-persistent / mime-skip
|
|
591
|
+
// / disk-fail components. Lets the audit + backfill scripts
|
|
592
|
+
// read the attachmentId directly off the :Component row instead
|
|
593
|
+
// of re-deriving (the live + heal paths use different sources \u2014
|
|
594
|
+
// sha256(block.id) live, componentId-fallback backfill \u2014 and
|
|
595
|
+
// the audit must match either).
|
|
596
|
+
attachmentId: comp.artefactAttachmentId
|
|
597
|
+
})
|
|
598
|
+
)
|
|
599
|
+
// Task 942 \u2014 for PERSISTENT_COMPONENTS whose disk write succeeded
|
|
600
|
+
// (artefactAttachmentId is non-null), MERGE the sibling
|
|
601
|
+
// :KnowledgeDocument projection AND a :HAS_KNOWLEDGE_DOCUMENT edge
|
|
602
|
+
// from the parent :Message in the same Cypher tx. ON CREATE stamps
|
|
603
|
+
// name+encodingFormat from the live render; ON MATCH only bumps
|
|
604
|
+
// updatedAt so a heal-on-resume re-run cannot clobber an operator's
|
|
605
|
+
// subsequent rename via the knowledge-documents API (eng-review \xA72).
|
|
606
|
+
// The edge makes the projection graph-discoverable from the
|
|
607
|
+
// conversation timeline so file-delete-cascade and conversation
|
|
608
|
+
// cleanup can reach it. FOREACH on the filtered list collapses to a
|
|
609
|
+
// no-op when no component has an attachmentId, preserving the
|
|
610
|
+
// text-only-turn fast path.
|
|
611
|
+
FOREACH (kd IN $knowledgeDocs |
|
|
612
|
+
MERGE (k:KnowledgeDocument {accountId: $accountId, attachmentId: kd.attachmentId})
|
|
613
|
+
ON CREATE SET k.name = kd.title,
|
|
614
|
+
k.encodingFormat = kd.mimeType,
|
|
615
|
+
k.createdAt = datetime(),
|
|
616
|
+
k.updatedAt = datetime()
|
|
617
|
+
ON MATCH SET k.updatedAt = datetime()
|
|
618
|
+
MERGE (m)-[:HAS_KNOWLEDGE_DOCUMENT]->(k)
|
|
619
|
+
)
|
|
620
|
+
FOREACH (att IN $attachments |
|
|
621
|
+
CREATE (m)-[:HAS_ATTACHMENT]->(:Attachment {
|
|
622
|
+
attachmentId: att.attachmentId,
|
|
623
|
+
conversationId: $conversationId,
|
|
624
|
+
accountId: $accountId,
|
|
625
|
+
messageId: $messageId,
|
|
626
|
+
filename: att.filename,
|
|
627
|
+
mimeType: att.mimeType,
|
|
628
|
+
sizeBytes: att.sizeBytes,
|
|
629
|
+
storagePath: att.storagePath,
|
|
630
|
+
ordinal: att.ordinal,
|
|
631
|
+
createdAt: datetime()
|
|
632
|
+
})
|
|
633
|
+
)
|
|
634
|
+
RETURN tail.messageId AS prevMessageId,
|
|
635
|
+
summarySetThisWrite,
|
|
636
|
+
size([(m2:Message)-[:PART_OF]->(c) | m2]) AS chainLen`,
|
|
637
|
+
{
|
|
638
|
+
messageId,
|
|
639
|
+
conversationId,
|
|
640
|
+
accountId,
|
|
641
|
+
role,
|
|
642
|
+
content,
|
|
643
|
+
summary,
|
|
644
|
+
...createdAt ? { createdAt } : {},
|
|
645
|
+
...embedding ? { embedding } : {},
|
|
646
|
+
...sender ? { senderVisitorId: sender.visitorId, senderName: sender.displayName } : {},
|
|
647
|
+
...tokens?.inputTokens != null ? { inputTokens: neo4j.int(tokens.inputTokens) } : {},
|
|
648
|
+
...tokens?.outputTokens != null ? { outputTokens: neo4j.int(tokens.outputTokens) } : {},
|
|
649
|
+
...tokens?.cacheReadTokens != null ? { cacheReadTokens: neo4j.int(tokens.cacheReadTokens) } : {},
|
|
650
|
+
...tokens?.cacheCreationTokens != null ? { cacheCreationTokens: neo4j.int(tokens.cacheCreationTokens) } : {},
|
|
651
|
+
components: (components ?? []).map((comp) => ({
|
|
652
|
+
componentId: comp.componentId,
|
|
653
|
+
name: comp.name,
|
|
654
|
+
data: comp.data,
|
|
655
|
+
ordinal: neo4j.int(comp.ordinal),
|
|
656
|
+
textOffset: neo4j.int(comp.textOffset),
|
|
657
|
+
// Task 942 — null for non-persistent / mime-skip / disk-fail
|
|
658
|
+
// components; the FOREACH stamps this directly onto the
|
|
659
|
+
// :Component row so audit + backfill read attachmentId without
|
|
660
|
+
// re-deriving from componentId.
|
|
661
|
+
artefactAttachmentId: comp.artefactAttachmentId ?? null
|
|
662
|
+
})),
|
|
663
|
+
// Task 942 — :KnowledgeDocument MERGE list. One row per
|
|
664
|
+
// PERSISTENT_COMPONENTS component whose disk write succeeded;
|
|
665
|
+
// text-only / mime-skip / disk-fail components are absent so
|
|
666
|
+
// the FOREACH no-ops on them. attachmentId here matches the
|
|
667
|
+
// value the stream-parser stamped after writeAttachment.
|
|
668
|
+
knowledgeDocs: (components ?? []).filter((comp) => typeof comp.artefactAttachmentId === "string").map((comp) => ({
|
|
669
|
+
attachmentId: comp.artefactAttachmentId,
|
|
670
|
+
title: comp.artefactTitle ?? "",
|
|
671
|
+
mimeType: comp.artefactMimeType ?? ""
|
|
672
|
+
})),
|
|
673
|
+
attachments: (attachments ?? []).map((att) => ({
|
|
674
|
+
attachmentId: att.attachmentId,
|
|
675
|
+
filename: att.filename,
|
|
676
|
+
mimeType: att.mimeType,
|
|
677
|
+
sizeBytes: neo4j.int(att.sizeBytes),
|
|
678
|
+
storagePath: att.storagePath,
|
|
679
|
+
ordinal: neo4j.int(att.ordinal)
|
|
680
|
+
}))
|
|
681
|
+
}
|
|
682
|
+
);
|
|
683
|
+
if (result.records.length === 0) {
|
|
684
|
+
console.error(`[persist] Neo4j write skipped \u2014 conversation not found: ${conversationId.slice(0, 8)}\u2026`);
|
|
685
|
+
return null;
|
|
686
|
+
}
|
|
687
|
+
const record = result.records[0];
|
|
688
|
+
const prevMessageId = record.get("prevMessageId") ?? null;
|
|
689
|
+
const summarySetThisWrite = record.get("summarySetThisWrite") === true;
|
|
690
|
+
const chainLenRaw = record.get("chainLen");
|
|
691
|
+
const chainLen = typeof chainLenRaw === "bigint" ? Number(chainLenRaw) : typeof chainLenRaw?.toNumber === "function" ? chainLenRaw.toNumber() : Number(chainLenRaw ?? 0);
|
|
692
|
+
const messageSublabel = role === "user" ? "UserMessage" : "AssistantMessage";
|
|
693
|
+
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}`);
|
|
694
|
+
if (summarySetThisWrite) {
|
|
695
|
+
console.error(`[neo4j-store] conversation-summary-set conversationId=${conversationId.slice(0, 8)}\u2026 len=${summary.length}`);
|
|
696
|
+
}
|
|
697
|
+
const componentList = components ?? [];
|
|
698
|
+
if (componentList.length > 0) {
|
|
699
|
+
const relsCreated = result.summary.counters.updates().relationshipsCreated;
|
|
700
|
+
const expectedComponentEdges = componentList.length;
|
|
701
|
+
const baseEdges = relsCreated - expectedComponentEdges;
|
|
702
|
+
if (baseEdges < 1) {
|
|
703
|
+
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`);
|
|
704
|
+
}
|
|
705
|
+
for (const comp of componentList) {
|
|
706
|
+
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}`);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
const attachmentList = attachments ?? [];
|
|
710
|
+
if (attachmentList.length > 0) {
|
|
711
|
+
const relsCreated = result.summary.counters.updates().relationshipsCreated;
|
|
712
|
+
const expectedAttachmentEdges = attachmentList.length;
|
|
713
|
+
const expectedComponentEdges = (components ?? []).length;
|
|
714
|
+
const baseEdges = relsCreated - expectedComponentEdges - expectedAttachmentEdges;
|
|
715
|
+
if (baseEdges < 1) {
|
|
716
|
+
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`);
|
|
717
|
+
}
|
|
718
|
+
for (const att of attachmentList) {
|
|
719
|
+
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}`);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
console.error(`[persist] ${(/* @__PURE__ */ new Date()).toISOString()} conversationId=${conversationId.slice(0, 8)}\u2026 role=${role} len=${content.length}${sender ? ` sender=${sender.displayName}` : ""}`);
|
|
723
|
+
return messageId;
|
|
724
|
+
} catch (err) {
|
|
725
|
+
console.error(`[persist] Neo4j write failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
726
|
+
return null;
|
|
727
|
+
} finally {
|
|
728
|
+
release();
|
|
729
|
+
if (persistMessageLocks.get(conversationId) === chained) {
|
|
730
|
+
persistMessageLocks.delete(conversationId);
|
|
731
|
+
}
|
|
732
|
+
await session.close();
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
async function setConversationAgentSessionId(conversationId, agentSessionId) {
|
|
736
|
+
const prev = persistMessageLocks.get(conversationId);
|
|
737
|
+
let release;
|
|
738
|
+
const mine = new Promise((resolve2) => {
|
|
739
|
+
release = resolve2;
|
|
740
|
+
});
|
|
741
|
+
const chained = (prev ?? Promise.resolve()).then(() => mine);
|
|
742
|
+
persistMessageLocks.set(conversationId, chained);
|
|
743
|
+
await prev;
|
|
744
|
+
const session = getSession();
|
|
745
|
+
try {
|
|
746
|
+
const result = await session.run(
|
|
747
|
+
`MATCH (c:Conversation {conversationId: $conversationId})
|
|
748
|
+
SET c.agentSessionId = $agentSessionId
|
|
749
|
+
RETURN c.conversationId AS conversationId`,
|
|
750
|
+
{ conversationId, agentSessionId }
|
|
751
|
+
);
|
|
752
|
+
if (result.records.length === 0) {
|
|
753
|
+
console.error(`[persist] agent-session-id convId=${conversationId.slice(0, 8)}\u2026 status=skipped reason=conversation-not-found`);
|
|
754
|
+
return false;
|
|
755
|
+
}
|
|
756
|
+
console.log(`[persist] agent-session-id convId=${conversationId.slice(0, 8)}\u2026 status=ok agentSessionId=${agentSessionId ? agentSessionId.slice(0, 8) + "\u2026" : "null"}`);
|
|
757
|
+
return true;
|
|
758
|
+
} catch (err) {
|
|
759
|
+
console.error(`[persist] agent-session-id convId=${conversationId.slice(0, 8)}\u2026 status=failed error=${err instanceof Error ? err.message : String(err)}`);
|
|
760
|
+
return false;
|
|
761
|
+
} finally {
|
|
762
|
+
release();
|
|
763
|
+
if (persistMessageLocks.get(conversationId) === chained) {
|
|
764
|
+
persistMessageLocks.delete(conversationId);
|
|
765
|
+
}
|
|
766
|
+
await session.close();
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
async function getAgentSessionIdForConversation(conversationId) {
|
|
770
|
+
const session = getSession();
|
|
771
|
+
try {
|
|
772
|
+
const result = await session.run(
|
|
773
|
+
`MATCH (c:Conversation {conversationId: $conversationId})
|
|
774
|
+
RETURN c.agentSessionId AS agentSessionId`,
|
|
775
|
+
{ conversationId }
|
|
776
|
+
);
|
|
777
|
+
const value = result.records[0]?.get("agentSessionId");
|
|
778
|
+
return typeof value === "string" && value.length > 0 ? value : null;
|
|
779
|
+
} catch (err) {
|
|
780
|
+
console.error(`[persist] agent-session-id read failed convId=${conversationId.slice(0, 8)}\u2026 error=${err instanceof Error ? err.message : String(err)}`);
|
|
781
|
+
return null;
|
|
782
|
+
} finally {
|
|
783
|
+
await session.close();
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
async function getRecentMessages(conversationId, limit = 50) {
|
|
787
|
+
const session = getSession();
|
|
788
|
+
try {
|
|
789
|
+
const result = await session.run(
|
|
790
|
+
`MATCH (tail:Message {conversationId: $conversationId})
|
|
791
|
+
WHERE NOT (tail)-[:NEXT]->(:Message)
|
|
792
|
+
WITH tail ORDER BY tail.createdAt DESC LIMIT 1
|
|
793
|
+
MATCH path = (m:Message)-[:NEXT*0..]->(tail)
|
|
794
|
+
WHERE m.conversationId = $conversationId
|
|
795
|
+
AND length(path) < $limit
|
|
796
|
+
WITH m, length(path) AS depthFromTail
|
|
797
|
+
OPTIONAL MATCH (m)-[:HAS_COMPONENT]->(c:Component)
|
|
798
|
+
WITH m, depthFromTail, c ORDER BY c.ordinal ASC
|
|
799
|
+
WITH m, depthFromTail,
|
|
800
|
+
[comp IN collect(c) WHERE comp IS NOT NULL | comp {.*}] AS components
|
|
801
|
+
OPTIONAL MATCH (m)-[:HAS_ATTACHMENT]->(a:Attachment)
|
|
802
|
+
WITH m, depthFromTail, components, a ORDER BY a.ordinal ASC
|
|
803
|
+
WITH m, depthFromTail, components,
|
|
804
|
+
[att IN collect(a) WHERE att IS NOT NULL | att {.*}] AS attachments
|
|
805
|
+
RETURN m.messageId AS messageId, m.role AS role, m.content AS content,
|
|
806
|
+
m.createdAt AS createdAt, components, attachments
|
|
807
|
+
ORDER BY depthFromTail DESC`,
|
|
808
|
+
{ conversationId, limit: neo4j.int(limit) }
|
|
809
|
+
);
|
|
810
|
+
return result.records.map((r) => {
|
|
811
|
+
const rawComponents = r.get("components") ?? [];
|
|
812
|
+
const components = rawComponents.map((c) => ({
|
|
813
|
+
componentId: String(c.componentId ?? ""),
|
|
814
|
+
name: String(c.name ?? ""),
|
|
815
|
+
data: String(c.data ?? ""),
|
|
816
|
+
ordinal: typeof c.ordinal?.toNumber === "function" ? c.ordinal.toNumber() : Number(c.ordinal ?? 0),
|
|
817
|
+
textOffset: typeof c.textOffset?.toNumber === "function" ? c.textOffset.toNumber() : Number(c.textOffset ?? 0),
|
|
818
|
+
submitted: c.submitted === true
|
|
819
|
+
}));
|
|
820
|
+
const rawAttachments = r.get("attachments") ?? [];
|
|
821
|
+
const attachments = rawAttachments.map((a) => ({
|
|
822
|
+
attachmentId: String(a.attachmentId ?? ""),
|
|
823
|
+
filename: String(a.filename ?? ""),
|
|
824
|
+
mimeType: String(a.mimeType ?? ""),
|
|
825
|
+
sizeBytes: typeof a.sizeBytes?.toNumber === "function" ? a.sizeBytes.toNumber() : Number(a.sizeBytes ?? 0),
|
|
826
|
+
storagePath: String(a.storagePath ?? ""),
|
|
827
|
+
ordinal: typeof a.ordinal?.toNumber === "function" ? a.ordinal.toNumber() : Number(a.ordinal ?? 0),
|
|
828
|
+
accountId: String(a.accountId ?? "")
|
|
829
|
+
}));
|
|
830
|
+
return {
|
|
831
|
+
messageId: r.get("messageId"),
|
|
832
|
+
role: r.get("role"),
|
|
833
|
+
content: r.get("content"),
|
|
834
|
+
createdAt: String(r.get("createdAt")),
|
|
835
|
+
components,
|
|
836
|
+
attachments
|
|
837
|
+
};
|
|
838
|
+
});
|
|
839
|
+
} catch (err) {
|
|
840
|
+
console.error(`[persist] getRecentMessages failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
841
|
+
return [];
|
|
842
|
+
} finally {
|
|
843
|
+
await session.close();
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
async function markComponentSubmitted(conversationId, componentName, accountId) {
|
|
847
|
+
const session = getSession();
|
|
848
|
+
try {
|
|
849
|
+
const result = await session.run(
|
|
850
|
+
`MATCH (conv:Conversation {conversationId: $conversationId, accountId: $accountId})
|
|
851
|
+
MATCH (m:Message)-[:PART_OF]->(conv)
|
|
852
|
+
MATCH (m)-[:HAS_COMPONENT]->(c:Component {name: $componentName, accountId: $accountId})
|
|
853
|
+
WHERE c.submitted = false OR c.submitted IS NULL
|
|
854
|
+
WITH c, m ORDER BY m.createdAt DESC, c.ordinal DESC
|
|
855
|
+
LIMIT 1
|
|
856
|
+
SET c.submitted = true, c.submittedAt = datetime()
|
|
857
|
+
RETURN c.componentId AS componentId`,
|
|
858
|
+
{ conversationId, componentName, accountId }
|
|
859
|
+
);
|
|
860
|
+
const componentId = result.records[0]?.get("componentId");
|
|
861
|
+
if (componentId) {
|
|
862
|
+
console.error(`[neo4j-store] component-submitted conversationId=${conversationId.slice(0, 8)}\u2026 name=${componentName} componentId=${componentId.slice(0, 8)}\u2026`);
|
|
863
|
+
return componentId;
|
|
864
|
+
}
|
|
865
|
+
console.error(`[neo4j-store] component-submit-skipped conversationId=${conversationId.slice(0, 8)}\u2026 name=${componentName} reason=no-unsubmitted-match`);
|
|
866
|
+
return null;
|
|
867
|
+
} catch (err) {
|
|
868
|
+
console.error(`[neo4j-store] component-submit-failed conversationId=${conversationId.slice(0, 8)}\u2026 name=${componentName} error=${err instanceof Error ? err.message : String(err)}`);
|
|
869
|
+
return null;
|
|
870
|
+
} finally {
|
|
871
|
+
await session.close();
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
async function verifyConversationOwnership(conversationId, accountId) {
|
|
875
|
+
const session = getSession();
|
|
876
|
+
try {
|
|
877
|
+
const result = await session.run(
|
|
878
|
+
`MATCH (c:Conversation {conversationId: $conversationId, accountId: $accountId})
|
|
879
|
+
RETURN c.conversationId AS id LIMIT 1`,
|
|
880
|
+
{ conversationId, accountId }
|
|
881
|
+
);
|
|
882
|
+
return result.records.length > 0;
|
|
883
|
+
} catch (err) {
|
|
884
|
+
console.error(`[persist] verifyConversationOwnership failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
885
|
+
return false;
|
|
886
|
+
} finally {
|
|
887
|
+
await session.close();
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
async function getConversationOwner(conversationId) {
|
|
891
|
+
const session = getSession();
|
|
892
|
+
try {
|
|
893
|
+
const result = await session.run(
|
|
894
|
+
`MATCH (c:Conversation {conversationId: $conversationId})
|
|
895
|
+
RETURN c.accountId AS accountId, c.userId AS userId LIMIT 1`,
|
|
896
|
+
{ conversationId }
|
|
897
|
+
);
|
|
898
|
+
const record = result.records[0];
|
|
899
|
+
if (!record) return null;
|
|
900
|
+
const accountId = record.get("accountId");
|
|
901
|
+
const userId = record.get("userId");
|
|
902
|
+
if (!accountId) return null;
|
|
903
|
+
return { accountId, userId: userId ?? null };
|
|
904
|
+
} catch (err) {
|
|
905
|
+
console.error(`[persist] getConversationOwner failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
906
|
+
return null;
|
|
907
|
+
} finally {
|
|
908
|
+
await session.close();
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
async function verifyAndGetConversationUpdatedAt(conversationId, accountId) {
|
|
912
|
+
const session = getSession();
|
|
913
|
+
try {
|
|
914
|
+
const result = await session.run(
|
|
915
|
+
`MATCH (c:Conversation {conversationId: $conversationId, accountId: $accountId})
|
|
916
|
+
RETURN toString(c.updatedAt) AS updatedAt LIMIT 1`,
|
|
917
|
+
{ conversationId, accountId }
|
|
918
|
+
);
|
|
919
|
+
const record = result.records[0];
|
|
920
|
+
return record ? record.get("updatedAt") : null;
|
|
921
|
+
} catch (err) {
|
|
922
|
+
console.error(`[persist] verifyAndGetConversationUpdatedAt failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
923
|
+
return null;
|
|
924
|
+
} finally {
|
|
925
|
+
await session.close();
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
async function searchMessages(accountId, queryEmbedding, limit = 10) {
|
|
929
|
+
const session = getSession();
|
|
930
|
+
try {
|
|
931
|
+
const result = await session.run(
|
|
932
|
+
`CALL db.index.vector.queryNodes('message_embedding', $limit, $embedding)
|
|
933
|
+
YIELD node, score
|
|
934
|
+
WHERE node.accountId = $accountId
|
|
935
|
+
RETURN node.messageId AS messageId,
|
|
936
|
+
node.role AS role,
|
|
937
|
+
node.content AS content,
|
|
938
|
+
node.conversationId AS conversationId,
|
|
939
|
+
node.createdAt AS createdAt,
|
|
940
|
+
score
|
|
941
|
+
ORDER BY score DESC
|
|
942
|
+
LIMIT $limit`,
|
|
943
|
+
{ embedding: queryEmbedding, limit: neo4j.int(limit), accountId }
|
|
944
|
+
);
|
|
945
|
+
return result.records.map((r) => ({
|
|
946
|
+
messageId: r.get("messageId"),
|
|
947
|
+
role: r.get("role"),
|
|
948
|
+
content: r.get("content"),
|
|
949
|
+
conversationId: r.get("conversationId"),
|
|
950
|
+
createdAt: String(r.get("createdAt")),
|
|
951
|
+
score: typeof r.get("score") === "number" ? r.get("score") : Number(r.get("score"))
|
|
952
|
+
}));
|
|
953
|
+
} catch (err) {
|
|
954
|
+
console.error(`[persist] searchMessages failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
955
|
+
return [];
|
|
956
|
+
} finally {
|
|
957
|
+
await session.close();
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
var LIST_BACKFILL_CAP = 3;
|
|
961
|
+
async function listAdminSessions(accountId, userId, limit = 20) {
|
|
962
|
+
const session = getSession();
|
|
963
|
+
try {
|
|
964
|
+
const result = await session.run(
|
|
965
|
+
`MATCH (c:Conversation {accountId: $accountId, agentType: 'admin', userId: $userId})
|
|
966
|
+
WHERE NOT c:Trashed
|
|
967
|
+
WITH c
|
|
968
|
+
ORDER BY c.updatedAt DESC
|
|
969
|
+
LIMIT $limit
|
|
970
|
+
CALL {
|
|
971
|
+
WITH c
|
|
972
|
+
OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
|
|
973
|
+
WHERE m.role = 'user'
|
|
974
|
+
AND c.name IS NULL
|
|
975
|
+
AND NOT (m.content STARTS WITH '[New session.')
|
|
976
|
+
AND NOT (m.content STARTS WITH '{"')
|
|
977
|
+
AND size(m.content) >= 4
|
|
978
|
+
RETURN m.content AS content, m.createdAt AS createdAt
|
|
979
|
+
ORDER BY m.createdAt ASC
|
|
980
|
+
LIMIT 1
|
|
981
|
+
}
|
|
982
|
+
RETURN c.conversationId AS conversationId,
|
|
983
|
+
c.name AS name,
|
|
984
|
+
c.updatedAt AS updatedAt,
|
|
985
|
+
c.channel AS channel,
|
|
986
|
+
content AS firstSubstantiveUserMessage`,
|
|
987
|
+
{ accountId, userId, limit: neo4j.int(limit) }
|
|
988
|
+
);
|
|
989
|
+
const rows = result.records.map((r) => ({
|
|
990
|
+
conversationId: r.get("conversationId"),
|
|
991
|
+
name: r.get("name"),
|
|
992
|
+
updatedAt: String(r.get("updatedAt")),
|
|
993
|
+
channel: r.get("channel"),
|
|
994
|
+
firstSubstantiveUserMessage: r.get("firstSubstantiveUserMessage")
|
|
995
|
+
}));
|
|
996
|
+
let backfillsKicked = 0;
|
|
997
|
+
for (const row of rows) {
|
|
998
|
+
if (backfillsKicked >= LIST_BACKFILL_CAP) break;
|
|
999
|
+
if (row.name !== null) continue;
|
|
1000
|
+
const seed = row.firstSubstantiveUserMessage;
|
|
1001
|
+
if (!seed || !isMessageUseful(seed)) continue;
|
|
1002
|
+
backfillsKicked++;
|
|
1003
|
+
autoLabelSession(row.conversationId, seed).catch(() => {
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
return rows.map(({ conversationId, name, updatedAt, channel }) => ({ conversationId, name, updatedAt, channel }));
|
|
1007
|
+
} catch (err) {
|
|
1008
|
+
console.error(`[persist] listAdminSessions failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1009
|
+
return [];
|
|
1010
|
+
} finally {
|
|
1011
|
+
await session.close();
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
async function deleteConversation(conversationId) {
|
|
1015
|
+
const session = getSession();
|
|
1016
|
+
try {
|
|
1017
|
+
const result = await session.run(
|
|
1018
|
+
`MATCH (c:Conversation {conversationId: $conversationId})
|
|
1019
|
+
OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
|
|
1020
|
+
OPTIONAL MATCH (m)-[:HAS_COMPONENT]->(comp:Component)
|
|
1021
|
+
OPTIONAL MATCH (m)-[:HAS_ATTACHMENT]->(att:Attachment)
|
|
1022
|
+
DETACH DELETE att, comp, m, c
|
|
1023
|
+
RETURN count(c) AS deleted`,
|
|
1024
|
+
{ conversationId }
|
|
1025
|
+
);
|
|
1026
|
+
const deleted = result.records[0]?.get("deleted");
|
|
1027
|
+
const count = typeof deleted === "object" && deleted !== null ? Number(deleted) : Number(deleted ?? 0);
|
|
1028
|
+
console.error(`[persist] deleteConversation ${conversationId.slice(0, 8)}\u2026: ${count > 0 ? "deleted" : "not found"}`);
|
|
1029
|
+
return count > 0;
|
|
1030
|
+
} catch (err) {
|
|
1031
|
+
console.error(`[persist] deleteConversation failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1032
|
+
return false;
|
|
1033
|
+
} finally {
|
|
1034
|
+
await session.close();
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
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;
|
|
1038
|
+
var SESSION_LABEL_MSG_CAP = 500;
|
|
1039
|
+
var SESSION_LABEL_TIMEOUT_MS = 15e3;
|
|
1040
|
+
var SESSION_LABEL_MODEL = HAIKU_MODEL;
|
|
1041
|
+
var SESSION_LABEL_MAX_WORDS = 6;
|
|
1042
|
+
var SESSION_LABEL_MAX_ATTEMPTS = 3;
|
|
1043
|
+
var SESSION_LABEL_MAX_STDERR = 2048;
|
|
1044
|
+
function isMessageUseful(message) {
|
|
1045
|
+
const trimmed = message.trim();
|
|
1046
|
+
if (trimmed.length < 4) return false;
|
|
1047
|
+
if (trimmed.startsWith('{"')) return false;
|
|
1048
|
+
if (GENERIC_MESSAGE.test(trimmed)) return false;
|
|
1049
|
+
if (trimmed.startsWith(DIRECTIVE_PREFIX)) return false;
|
|
1050
|
+
return true;
|
|
1051
|
+
}
|
|
1052
|
+
function totalFailures(f) {
|
|
1053
|
+
return f.skip + f.error;
|
|
1054
|
+
}
|
|
1055
|
+
function failureBreakdown(f) {
|
|
1056
|
+
return `skip:${f.skip} error:${f.error}`;
|
|
1057
|
+
}
|
|
1058
|
+
var labelAccumulator = /* @__PURE__ */ new Map();
|
|
1059
|
+
var _spawnOverride = null;
|
|
1060
|
+
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.
|
|
1061
|
+
|
|
1062
|
+
Rules:
|
|
1063
|
+
- Exactly 3 to 6 words
|
|
1064
|
+
- Summarize the user's intent, do not copy verbatim
|
|
1065
|
+
- Capitalize the first word only (sentence case)
|
|
1066
|
+
- No punctuation, no quotes
|
|
1067
|
+
- You MUST always produce a label. Vague, terse, or single-word messages still get a best-effort label (e.g. a one-word "hi" or an emoji becomes "Greeting"; an unintelligible fragment becomes "Unstructured note"). Never abstain.`;
|
|
1068
|
+
async function generateSessionLabel(messages) {
|
|
1069
|
+
const cappedMessages = messages.map((m) => m.slice(0, SESSION_LABEL_MSG_CAP));
|
|
1070
|
+
const userContent = cappedMessages.map((m, i) => `Message ${i + 1}: ${m}`).join("\n");
|
|
1071
|
+
const prompt = `${SESSION_LABEL_SYSTEM}
|
|
1072
|
+
|
|
1073
|
+
${userContent}`;
|
|
1074
|
+
const args = [
|
|
1075
|
+
"--print",
|
|
1076
|
+
"--model",
|
|
1077
|
+
SESSION_LABEL_MODEL,
|
|
1078
|
+
"--max-turns",
|
|
1079
|
+
"1",
|
|
1080
|
+
"--permission-mode",
|
|
1081
|
+
"dontAsk",
|
|
1082
|
+
prompt
|
|
1083
|
+
];
|
|
1084
|
+
return new Promise((resolve2) => {
|
|
1085
|
+
let stdout = "";
|
|
1086
|
+
let stderr = "";
|
|
1087
|
+
const spawnFn = _spawnOverride ?? spawn;
|
|
1088
|
+
const proc = spawnFn("claude", args, {
|
|
1089
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1090
|
+
});
|
|
1091
|
+
proc.stdout?.on("data", (chunk) => {
|
|
1092
|
+
stdout += chunk.toString("utf-8");
|
|
1093
|
+
});
|
|
1094
|
+
proc.stderr?.on("data", (chunk) => {
|
|
1095
|
+
if (stderr.length < SESSION_LABEL_MAX_STDERR) {
|
|
1096
|
+
stderr += chunk.toString("utf-8").slice(0, SESSION_LABEL_MAX_STDERR - stderr.length);
|
|
1097
|
+
}
|
|
1098
|
+
});
|
|
1099
|
+
const timer = setTimeout(() => {
|
|
1100
|
+
proc.kill("SIGTERM");
|
|
1101
|
+
console.error("[persist] autoLabel: haiku subprocess timed out");
|
|
1102
|
+
resolve2(null);
|
|
1103
|
+
}, SESSION_LABEL_TIMEOUT_MS);
|
|
1104
|
+
proc.on("error", (err) => {
|
|
1105
|
+
clearTimeout(timer);
|
|
1106
|
+
console.error(`[persist] autoLabel: subprocess error \u2014 ${err.message}`);
|
|
1107
|
+
resolve2(null);
|
|
1108
|
+
});
|
|
1109
|
+
proc.on("close", (code) => {
|
|
1110
|
+
clearTimeout(timer);
|
|
1111
|
+
if (code !== 0) {
|
|
1112
|
+
console.error(`[persist] autoLabel: subprocess exited code=${code}${stderr ? ` stderr=${stderr.trim().slice(0, 200)}` : ""}`);
|
|
1113
|
+
resolve2(null);
|
|
1114
|
+
return;
|
|
1115
|
+
}
|
|
1116
|
+
const text = stdout.trim();
|
|
1117
|
+
if (!text) {
|
|
1118
|
+
console.error("[persist] autoLabel: haiku returned empty response");
|
|
1119
|
+
resolve2(null);
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
const words = text.split(/\s+/).slice(0, SESSION_LABEL_MAX_WORDS);
|
|
1123
|
+
const label = words.join(" ");
|
|
1124
|
+
console.error(`[persist] autoLabel: haiku response="${label}"`);
|
|
1125
|
+
resolve2(label);
|
|
1126
|
+
});
|
|
1127
|
+
});
|
|
1128
|
+
}
|
|
1129
|
+
async function autoLabelSession(conversationId, userMessage) {
|
|
1130
|
+
if (!conversationId) return;
|
|
1131
|
+
if (!isMessageUseful(userMessage)) {
|
|
1132
|
+
const trimmed = userMessage.trim();
|
|
1133
|
+
const reason = trimmed.startsWith('{"') ? "JSON envelope" : trimmed.startsWith(DIRECTIVE_PREFIX) ? "directive" : GENERIC_MESSAGE.test(trimmed) ? "greeting" : trimmed.length < 4 ? "too short" : "directive";
|
|
1134
|
+
console.error(`[persist] autoLabel: skipped ${conversationId.slice(0, 8)}\u2026 \u2014 ${reason}`);
|
|
1135
|
+
return;
|
|
1136
|
+
}
|
|
1137
|
+
try {
|
|
1138
|
+
const preCheck = getSession();
|
|
1139
|
+
try {
|
|
1140
|
+
const res = await preCheck.run(
|
|
1141
|
+
`MATCH (c:Conversation {conversationId: $conversationId})
|
|
1142
|
+
OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
|
|
1143
|
+
WHERE m.role = 'user'
|
|
1144
|
+
WITH c, count(m) AS userCount
|
|
1145
|
+
RETURN c.name AS name, userCount`,
|
|
1146
|
+
{ conversationId }
|
|
1147
|
+
);
|
|
1148
|
+
const firstRecord = res.records[0];
|
|
1149
|
+
const existingName = firstRecord?.get("name");
|
|
1150
|
+
const userCountRaw = firstRecord?.get("userCount");
|
|
1151
|
+
const userCount = typeof userCountRaw === "object" && userCountRaw !== null ? Number(userCountRaw) : Number(userCountRaw ?? 0);
|
|
1152
|
+
if (existingName) {
|
|
1153
|
+
console.error(`[persist] autoLabel: already named ${conversationId.slice(0, 8)}\u2026 \u2014 skipping`);
|
|
1154
|
+
labelAccumulator.delete(conversationId);
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
if (userCount > 3) {
|
|
1158
|
+
console.error(`[persist] autoLabel: past autolabel window ${conversationId.slice(0, 8)}\u2026 \u2014 userCount=${userCount}, skipping`);
|
|
1159
|
+
labelAccumulator.delete(conversationId);
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
} finally {
|
|
1163
|
+
await preCheck.close();
|
|
1164
|
+
}
|
|
1165
|
+
} catch (err) {
|
|
1166
|
+
console.error(`[persist] autoLabel: pre-check read failed for ${conversationId.slice(0, 8)}\u2026 \u2014 proceeding: ${err instanceof Error ? err.message : String(err)}`);
|
|
1167
|
+
}
|
|
1168
|
+
let entry = labelAccumulator.get(conversationId);
|
|
1169
|
+
if (!entry) {
|
|
1170
|
+
entry = {
|
|
1171
|
+
messages: [],
|
|
1172
|
+
pending: false,
|
|
1173
|
+
failures: { skip: 0, error: 0 }
|
|
1174
|
+
};
|
|
1175
|
+
labelAccumulator.set(conversationId, entry);
|
|
1176
|
+
}
|
|
1177
|
+
if (totalFailures(entry.failures) >= SESSION_LABEL_MAX_ATTEMPTS) {
|
|
1178
|
+
console.error(`[persist] autoLabel: evicted ${conversationId.slice(0, 8)}\u2026 after ${SESSION_LABEL_MAX_ATTEMPTS} failed-attempts (${failureBreakdown(entry.failures)})`);
|
|
1179
|
+
labelAccumulator.delete(conversationId);
|
|
1180
|
+
return;
|
|
1181
|
+
}
|
|
1182
|
+
entry.messages.push(userMessage.trim());
|
|
1183
|
+
if (entry.pending) {
|
|
1184
|
+
console.error(`[persist] autoLabel: accumulated for ${conversationId.slice(0, 8)}\u2026 (pending, ${entry.messages.length} msgs)`);
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
entry.pending = true;
|
|
1188
|
+
try {
|
|
1189
|
+
const label = await generateSessionLabel(entry.messages);
|
|
1190
|
+
if (!label) {
|
|
1191
|
+
entry.failures.skip++;
|
|
1192
|
+
console.error(`[persist] autoLabel: generateSessionLabel returned null for ${conversationId.slice(0, 8)}\u2026 (failures ${failureBreakdown(entry.failures)}, ${entry.messages.length} msgs)`);
|
|
1193
|
+
entry.pending = false;
|
|
1194
|
+
return;
|
|
1195
|
+
}
|
|
1196
|
+
const fullLabel = `${label} \xB7 ${conversationId.slice(0, 8)}`;
|
|
1197
|
+
let embedding = null;
|
|
1198
|
+
try {
|
|
1199
|
+
embedding = await embed(fullLabel);
|
|
1200
|
+
} catch (err) {
|
|
1201
|
+
console.error(`[persist] Conversation embedding failed, labelling without: ${err instanceof Error ? err.message : String(err)}`);
|
|
1202
|
+
}
|
|
1203
|
+
const session = getSession();
|
|
1204
|
+
try {
|
|
1205
|
+
const result = await session.run(
|
|
1206
|
+
`MATCH (c:Conversation {conversationId: $conversationId})
|
|
1207
|
+
WHERE c.name IS NULL
|
|
1208
|
+
WITH c
|
|
1209
|
+
OPTIONAL MATCH (m:Message)-[:PART_OF]->(c)
|
|
1210
|
+
WHERE m.role = 'user'
|
|
1211
|
+
WITH c, count(m) AS userCount
|
|
1212
|
+
WHERE userCount <= 3
|
|
1213
|
+
SET c.name = $label, c.updatedAt = datetime()
|
|
1214
|
+
${embedding ? ", c.embedding = $embedding" : ""}
|
|
1215
|
+
RETURN c.name AS name`,
|
|
1216
|
+
{ conversationId, label: fullLabel, ...embedding ? { embedding } : {} }
|
|
1217
|
+
);
|
|
1218
|
+
if (result.records.length > 0) {
|
|
1219
|
+
console.error(`[persist] autoLabel: commit ${conversationId.slice(0, 8)}\u2026 name="${fullLabel}"${embedding ? " (embedded)" : ""}`);
|
|
1220
|
+
labelAccumulator.delete(conversationId);
|
|
1221
|
+
} else {
|
|
1222
|
+
console.error(`[persist] autoLabel: no-op commit ${conversationId.slice(0, 8)}\u2026 (name already set or userCount>3)`);
|
|
1223
|
+
labelAccumulator.delete(conversationId);
|
|
1224
|
+
}
|
|
1225
|
+
} catch (err) {
|
|
1226
|
+
entry.failures.error++;
|
|
1227
|
+
console.error(`[persist] autoLabelSession failed: ${err instanceof Error ? err.message : String(err)} (failures ${failureBreakdown(entry.failures)})`);
|
|
1228
|
+
} finally {
|
|
1229
|
+
await session.close();
|
|
1230
|
+
}
|
|
1231
|
+
} catch (err) {
|
|
1232
|
+
const currentEntry = labelAccumulator.get(conversationId);
|
|
1233
|
+
if (currentEntry) currentEntry.failures.error++;
|
|
1234
|
+
console.error(`[persist] autoLabel: unexpected error \u2014 ${err instanceof Error ? err.message : String(err)}${currentEntry ? ` (failures ${failureBreakdown(currentEntry.failures)})` : ""}`);
|
|
1235
|
+
} finally {
|
|
1236
|
+
const currentEntry = labelAccumulator.get(conversationId);
|
|
1237
|
+
if (currentEntry) currentEntry.pending = false;
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
async function renameConversation(conversationId, label) {
|
|
1241
|
+
let embedding = null;
|
|
1242
|
+
try {
|
|
1243
|
+
embedding = await embed(label);
|
|
1244
|
+
} catch (err) {
|
|
1245
|
+
console.error(`[persist] manual-label: embedding failed, persisting without: ${err instanceof Error ? err.message : String(err)}`);
|
|
1246
|
+
}
|
|
1247
|
+
const session = getSession();
|
|
1248
|
+
try {
|
|
1249
|
+
await session.run(
|
|
1250
|
+
`MATCH (c:Conversation {conversationId: $conversationId})
|
|
1251
|
+
SET c.name = $label, c.updatedAt = datetime()
|
|
1252
|
+
${embedding ? ", c.embedding = $embedding" : ""}`,
|
|
1253
|
+
{ conversationId, label, ...embedding ? { embedding } : {} }
|
|
1254
|
+
);
|
|
1255
|
+
console.error(`[persist] manual-label: renamed ${conversationId} to "${label}"${embedding ? " (embedded)" : ""}`);
|
|
1256
|
+
} finally {
|
|
1257
|
+
await session.close();
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
var DECAY_THRESHOLD_DAYS = 14;
|
|
1261
|
+
var DECAY_RATE_PER_DAY = 0.05;
|
|
1262
|
+
var INJECTION_THRESHOLD = 0.4;
|
|
1263
|
+
var MAX_SUMMARY_PREFERENCES = 30;
|
|
1264
|
+
async function getUserTimezone(accountId, userId) {
|
|
1265
|
+
const session = getSession();
|
|
1266
|
+
try {
|
|
1267
|
+
const query = userId ? `MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
|
|
1268
|
+
RETURN up.timezone AS timezone` : `MATCH (up:UserProfile {accountId: $accountId})
|
|
1269
|
+
RETURN up.timezone AS timezone ORDER BY up.createdAt LIMIT 1`;
|
|
1270
|
+
const result = await session.run(query, { accountId, userId: userId ?? "" });
|
|
1271
|
+
if (result.records.length === 0) return null;
|
|
1272
|
+
const tz = result.records[0].get("timezone");
|
|
1273
|
+
return tz && tz.trim().length > 0 ? tz : null;
|
|
1274
|
+
} catch (err) {
|
|
1275
|
+
console.error(`[datetime] getUserTimezone failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1276
|
+
return null;
|
|
1277
|
+
} finally {
|
|
1278
|
+
await session.close();
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
async function loadAdminUserName(accountId, userId) {
|
|
1282
|
+
const session = getSession();
|
|
1283
|
+
try {
|
|
1284
|
+
const result = await session.run(
|
|
1285
|
+
`MATCH (au:AdminUser {userId: $userId})-[:OWNS]->(p:Person {accountId: $accountId})
|
|
1286
|
+
RETURN p.givenName AS givenName, p.familyName AS familyName, p.avatar AS avatar
|
|
1287
|
+
LIMIT 1`,
|
|
1288
|
+
{ accountId, userId }
|
|
1289
|
+
);
|
|
1290
|
+
if (result.records.length === 0) {
|
|
1291
|
+
return { source: "fallback", reason: "no-person-node" };
|
|
1292
|
+
}
|
|
1293
|
+
const givenName = result.records[0].get("givenName");
|
|
1294
|
+
const familyName = result.records[0].get("familyName");
|
|
1295
|
+
const avatar = result.records[0].get("avatar");
|
|
1296
|
+
if (!givenName || givenName.trim().length === 0) {
|
|
1297
|
+
return { source: "fallback", reason: "no-givenName" };
|
|
1298
|
+
}
|
|
1299
|
+
const trimmedFamily = familyName && familyName.trim().length > 0 ? familyName.trim() : null;
|
|
1300
|
+
const trimmedAvatar = avatar && avatar.trim().length > 0 ? avatar.trim() : null;
|
|
1301
|
+
const joined = trimmedFamily ? `${givenName.trim()} ${trimmedFamily}` : givenName.trim();
|
|
1302
|
+
return { source: "neo4j", joined, givenName: givenName.trim(), familyName: trimmedFamily, avatar: trimmedAvatar };
|
|
1303
|
+
} catch (err) {
|
|
1304
|
+
console.error(`[admin-identity] loadAdminUserName failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1305
|
+
return { source: "fallback", reason: "neo4j-unreachable" };
|
|
1306
|
+
} finally {
|
|
1307
|
+
await session.close();
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
async function writeAdminUserAndPerson(params) {
|
|
1311
|
+
const { userId, fullName, accountId } = params;
|
|
1312
|
+
const trimmed = fullName.trim();
|
|
1313
|
+
if (!trimmed) {
|
|
1314
|
+
throw new Error("writeAdminUserAndPerson: fullName cannot be empty");
|
|
1315
|
+
}
|
|
1316
|
+
const firstSpace = trimmed.search(/\s/);
|
|
1317
|
+
const givenName = firstSpace === -1 ? trimmed : trimmed.slice(0, firstSpace).trim();
|
|
1318
|
+
const familyName = firstSpace === -1 ? null : trimmed.slice(firstSpace + 1).trim() || null;
|
|
1319
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1320
|
+
const session = getSession();
|
|
1321
|
+
try {
|
|
1322
|
+
const result = await session.run(
|
|
1323
|
+
`MERGE (au:AdminUser {userId: $userId})
|
|
1324
|
+
ON CREATE SET au.name = $fullName, au.createdAt = $now
|
|
1325
|
+
ON MATCH SET au.name = $fullName, au.updatedAt = $now
|
|
1326
|
+
WITH au
|
|
1327
|
+
|
|
1328
|
+
// Case-insensitive Person reuse: same accountId, same givenName, same familyName
|
|
1329
|
+
// (null/empty familyName collapsed to '' so 'Joel' does NOT match 'Joel Smalley').
|
|
1330
|
+
OPTIONAL MATCH (existingPerson:Person {accountId: $accountId})
|
|
1331
|
+
WHERE toLower(existingPerson.givenName) = toLower($givenName)
|
|
1332
|
+
AND coalesce(toLower(existingPerson.familyName), '') = coalesce(toLower($familyName), '')
|
|
1333
|
+
WITH au, existingPerson
|
|
1334
|
+
|
|
1335
|
+
CALL {
|
|
1336
|
+
WITH au, existingPerson
|
|
1337
|
+
WITH au, existingPerson WHERE existingPerson IS NOT NULL
|
|
1338
|
+
MERGE (au)-[:OWNS]->(existingPerson)
|
|
1339
|
+
RETURN existingPerson AS p, true AS reused
|
|
1340
|
+
UNION
|
|
1341
|
+
WITH au, existingPerson
|
|
1342
|
+
WITH au WHERE existingPerson IS NULL
|
|
1343
|
+
CREATE (newPerson:Person {
|
|
1344
|
+
accountId: $accountId,
|
|
1345
|
+
givenName: $givenName,
|
|
1346
|
+
familyName: $familyName,
|
|
1347
|
+
role: 'admin-personal',
|
|
1348
|
+
scope: 'admin',
|
|
1349
|
+
createdAt: $now
|
|
1350
|
+
})
|
|
1351
|
+
MERGE (au)-[:OWNS]->(newPerson)
|
|
1352
|
+
RETURN newPerson AS p, false AS reused
|
|
1353
|
+
}
|
|
1354
|
+
RETURN reused, elementId(p) AS personElementId,
|
|
1355
|
+
p.givenName AS givenName, p.familyName AS familyName`,
|
|
1356
|
+
{ userId, fullName: trimmed, accountId, givenName, familyName, now }
|
|
1357
|
+
);
|
|
1358
|
+
if (result.records.length === 0) {
|
|
1359
|
+
throw new Error("writeAdminUserAndPerson: no record returned");
|
|
1360
|
+
}
|
|
1361
|
+
const record = result.records[0];
|
|
1362
|
+
return {
|
|
1363
|
+
personReused: record.get("reused"),
|
|
1364
|
+
personElementId: record.get("personElementId"),
|
|
1365
|
+
givenName: record.get("givenName"),
|
|
1366
|
+
familyName: record.get("familyName")
|
|
1367
|
+
};
|
|
1368
|
+
} finally {
|
|
1369
|
+
await session.close();
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
var PROFILE_CATEGORIES = [
|
|
1373
|
+
"communication",
|
|
1374
|
+
"scheduling",
|
|
1375
|
+
"decision",
|
|
1376
|
+
"workflow",
|
|
1377
|
+
"content",
|
|
1378
|
+
"interaction"
|
|
1379
|
+
];
|
|
1380
|
+
var PROFILE_FIELD_TEMPLATES = {
|
|
1381
|
+
communication: [
|
|
1382
|
+
"preferredChannel",
|
|
1383
|
+
"quietHours",
|
|
1384
|
+
"responseLatencyExpectation",
|
|
1385
|
+
"formalityLevel",
|
|
1386
|
+
"escalationPath"
|
|
1387
|
+
],
|
|
1388
|
+
scheduling: [
|
|
1389
|
+
"workdayStartTime",
|
|
1390
|
+
"workdayEndTime",
|
|
1391
|
+
"weekendAvailability",
|
|
1392
|
+
"meetingBlockPreference",
|
|
1393
|
+
"focusBlockTiming"
|
|
1394
|
+
],
|
|
1395
|
+
decision: [
|
|
1396
|
+
"riskTolerance",
|
|
1397
|
+
"autonomyBoundary",
|
|
1398
|
+
"evidenceThreshold",
|
|
1399
|
+
"reversibilityPreference",
|
|
1400
|
+
"stakeholderConsultation"
|
|
1401
|
+
],
|
|
1402
|
+
workflow: [
|
|
1403
|
+
"batchingPreference",
|
|
1404
|
+
"taskGranularity",
|
|
1405
|
+
"deepWorkBlocks",
|
|
1406
|
+
"statusUpdateCadence",
|
|
1407
|
+
"toolingChoices"
|
|
1408
|
+
],
|
|
1409
|
+
content: [
|
|
1410
|
+
"outputFormat",
|
|
1411
|
+
"lengthPreference",
|
|
1412
|
+
"citationStyle",
|
|
1413
|
+
"tonality"
|
|
1414
|
+
],
|
|
1415
|
+
interaction: [
|
|
1416
|
+
"addressForm",
|
|
1417
|
+
"humourTolerance",
|
|
1418
|
+
"directnessLevel",
|
|
1419
|
+
"emotionalRegisterPreference"
|
|
1420
|
+
]
|
|
1421
|
+
};
|
|
1422
|
+
var TOTAL_PROFILE_FIELDS = Object.values(PROFILE_FIELD_TEMPLATES).reduce(
|
|
1423
|
+
(n, fs) => n + fs.length,
|
|
1424
|
+
0
|
|
1425
|
+
);
|
|
1426
|
+
function computeAbsentFields(preferences) {
|
|
1427
|
+
const covered = /* @__PURE__ */ new Set();
|
|
1428
|
+
for (const pref of preferences) {
|
|
1429
|
+
const isCovered = pref.notApplicable === true || pref.confidence >= INJECTION_THRESHOLD;
|
|
1430
|
+
if (isCovered) covered.add(`${pref.category}.${pref.key}`);
|
|
1431
|
+
}
|
|
1432
|
+
const absent = [];
|
|
1433
|
+
for (const [category, fields] of Object.entries(PROFILE_FIELD_TEMPLATES)) {
|
|
1434
|
+
for (const field of fields) {
|
|
1435
|
+
const dotted = `${category}.${field}`;
|
|
1436
|
+
if (!covered.has(dotted)) absent.push(dotted);
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
return absent;
|
|
1440
|
+
}
|
|
1441
|
+
var sparseStateLogged = /* @__PURE__ */ new Set();
|
|
1442
|
+
async function loadUserProfile(accountId, userId, conversationId) {
|
|
1443
|
+
console.error(
|
|
1444
|
+
`[profile] loadUserProfile entry accountId=${accountId.slice(0, 8)}\u2026 userId=${userId} conversationId=${conversationId ? `${conversationId.slice(0, 8)}\u2026` : "<none>"}`
|
|
1445
|
+
);
|
|
1446
|
+
const session = getSession();
|
|
1447
|
+
try {
|
|
1448
|
+
const serverTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
1449
|
+
const mergeResult = await session.run(
|
|
1450
|
+
`MATCH (au:AdminUser {userId: $userId})
|
|
1451
|
+
MERGE (au)-[:HAS_PROFILE]->(up:UserProfile {accountId: $accountId, userId: $userId})
|
|
1452
|
+
ON CREATE SET
|
|
1453
|
+
up.createdAt = $now,
|
|
1454
|
+
up.updatedAt = $now,
|
|
1455
|
+
up.profileVersion = 0,
|
|
1456
|
+
up.scope = 'admin',
|
|
1457
|
+
up.timezone = $serverTimezone
|
|
1458
|
+
ON MATCH SET
|
|
1459
|
+
up.timezone = CASE WHEN up.timezone IS NULL OR trim(up.timezone) = '' THEN $serverTimezone ELSE up.timezone END
|
|
1460
|
+
RETURN up.createdAt = $now AS isNew`,
|
|
1461
|
+
{ accountId, userId, now: (/* @__PURE__ */ new Date()).toISOString(), serverTimezone }
|
|
1462
|
+
);
|
|
1463
|
+
if (mergeResult.records.length === 0) {
|
|
1464
|
+
console.error(`[profile] loadUserProfile: AdminUser not found for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 \u2014 profile not created, invariant violated`);
|
|
1465
|
+
return null;
|
|
1466
|
+
}
|
|
1467
|
+
const isNew = mergeResult.records[0].get("isNew");
|
|
1468
|
+
if (isNew) {
|
|
1469
|
+
console.error(`[profile] created new profile: userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 timezone=${serverTimezone}`);
|
|
1470
|
+
}
|
|
1471
|
+
const nowMs = Date.now();
|
|
1472
|
+
const thresholdMs = DECAY_THRESHOLD_DAYS * 24 * 60 * 60 * 1e3;
|
|
1473
|
+
const staleResult = await session.run(
|
|
1474
|
+
`MATCH (up:UserProfile {accountId: $accountId, userId: $userId})-[:HAS_PREFERENCE]->(pref:Preference)
|
|
1475
|
+
WHERE pref.observedAt IS NOT NULL
|
|
1476
|
+
RETURN pref.preferenceId AS preferenceId,
|
|
1477
|
+
pref.observedAt AS observedAt,
|
|
1478
|
+
pref.confidence AS confidence`,
|
|
1479
|
+
{ accountId, userId }
|
|
1480
|
+
);
|
|
1481
|
+
let decayCount = 0;
|
|
1482
|
+
for (const record of staleResult.records) {
|
|
1483
|
+
const observedAt = record.get("observedAt");
|
|
1484
|
+
const confidence = record.get("confidence");
|
|
1485
|
+
const observedMs = new Date(observedAt).getTime();
|
|
1486
|
+
const ageMs = nowMs - observedMs;
|
|
1487
|
+
if (ageMs > thresholdMs && confidence > 0) {
|
|
1488
|
+
const daysPastThreshold = (ageMs - thresholdMs) / (24 * 60 * 60 * 1e3);
|
|
1489
|
+
const decayedConfidence = Math.max(0, confidence - DECAY_RATE_PER_DAY * daysPastThreshold);
|
|
1490
|
+
if (decayedConfidence !== confidence) {
|
|
1491
|
+
await session.run(
|
|
1492
|
+
`MATCH (pref:Preference {preferenceId: $preferenceId, accountId: $accountId})
|
|
1493
|
+
SET pref.confidence = $confidence`,
|
|
1494
|
+
{
|
|
1495
|
+
preferenceId: record.get("preferenceId"),
|
|
1496
|
+
accountId,
|
|
1497
|
+
confidence: decayedConfidence
|
|
1498
|
+
}
|
|
1499
|
+
);
|
|
1500
|
+
decayCount++;
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
const result = await session.run(
|
|
1505
|
+
`MATCH (up:UserProfile {accountId: $accountId, userId: $userId})
|
|
1506
|
+
OPTIONAL MATCH (au:AdminUser {userId: $userId})-[:OWNS]->(p:Person {accountId: $accountId})
|
|
1507
|
+
OPTIONAL MATCH (up)-[:HAS_PREFERENCE]->(pref:Preference)
|
|
1508
|
+
WHERE pref.confidence >= $threshold OR pref.notApplicable = true
|
|
1509
|
+
WITH up, p, pref
|
|
1510
|
+
ORDER BY pref.confidence DESC
|
|
1511
|
+
WITH up, p, collect(pref) AS allPrefs
|
|
1512
|
+
WITH up, p, allPrefs[0..$limit] AS prefs
|
|
1513
|
+
RETURN up, p AS person, prefs`,
|
|
1514
|
+
{ accountId, userId, threshold: INJECTION_THRESHOLD, limit: MAX_SUMMARY_PREFERENCES }
|
|
1515
|
+
);
|
|
1516
|
+
if (result.records.length === 0 || !result.records[0].get("up")) {
|
|
1517
|
+
return null;
|
|
1518
|
+
}
|
|
1519
|
+
const upNode = result.records[0].get("up");
|
|
1520
|
+
const profileProps = { ...upNode.properties };
|
|
1521
|
+
const personNode = result.records[0].get("person");
|
|
1522
|
+
if (personNode?.properties) {
|
|
1523
|
+
if (personNode.properties.givenName !== void 0) profileProps.givenName = personNode.properties.givenName;
|
|
1524
|
+
if (personNode.properties.familyName !== void 0) profileProps.familyName = personNode.properties.familyName;
|
|
1525
|
+
if (personNode.properties.email !== void 0) profileProps.email = personNode.properties.email;
|
|
1526
|
+
if (personNode.properties.telephone !== void 0) profileProps.telephone = personNode.properties.telephone;
|
|
1527
|
+
}
|
|
1528
|
+
const prefNodes = result.records[0].get("prefs");
|
|
1529
|
+
const preferences = prefNodes.map((p) => ({
|
|
1530
|
+
preferenceId: p.properties.preferenceId,
|
|
1531
|
+
category: p.properties.category,
|
|
1532
|
+
key: p.properties.key,
|
|
1533
|
+
value: p.properties.value,
|
|
1534
|
+
confidence: p.properties.confidence,
|
|
1535
|
+
source: p.properties.source,
|
|
1536
|
+
observedAt: p.properties.observedAt,
|
|
1537
|
+
notApplicable: p.properties.notApplicable === true
|
|
1538
|
+
}));
|
|
1539
|
+
const summary = formatProfileSummary(profileProps, preferences);
|
|
1540
|
+
const absentFields = computeAbsentFields(preferences);
|
|
1541
|
+
const fieldCoverageCount = TOTAL_PROFILE_FIELDS - absentFields.length;
|
|
1542
|
+
const presentCategories = new Set(
|
|
1543
|
+
preferences.filter((p) => p.notApplicable === true || p.confidence >= INJECTION_THRESHOLD).map((p) => p.category)
|
|
1544
|
+
);
|
|
1545
|
+
const absentCategories = PROFILE_CATEGORIES.filter((c) => !presentCategories.has(c));
|
|
1546
|
+
const categoryCoverage = PROFILE_CATEGORIES.length - absentCategories.length;
|
|
1547
|
+
console.error(
|
|
1548
|
+
`[profile] loaded for userId=${userId} accountId=${accountId.slice(0, 8)}\u2026 preferences=${preferences.length} fieldCoverage=${fieldCoverageCount}/${TOTAL_PROFILE_FIELDS} categoryCoverage=${categoryCoverage}/${PROFILE_CATEGORIES.length} (decay: ${decayCount} updated)`
|
|
1549
|
+
);
|
|
1550
|
+
const identityKeys = [
|
|
1551
|
+
{ prop: "email", token: "email" },
|
|
1552
|
+
// Schema-canonical name. `phone` is the synonym (rejected at tool
|
|
1553
|
+
// surface); the log uses `telephone` to keep grep aligned with
|
|
1554
|
+
// schema-base.md doctrine the brief enforces.
|
|
1555
|
+
{ prop: "telephone", token: "telephone" },
|
|
1556
|
+
{ prop: "givenName", token: "givenName" },
|
|
1557
|
+
{ prop: "familyName", token: "familyName" },
|
|
1558
|
+
{ prop: "role", token: "role" }
|
|
1559
|
+
];
|
|
1560
|
+
const absentIdentity = identityKeys.filter((k) => {
|
|
1561
|
+
const v = profileProps[k.prop];
|
|
1562
|
+
return typeof v !== "string" || v.trim().length === 0;
|
|
1563
|
+
});
|
|
1564
|
+
const sparseFired = absentCategories.length > 0 || absentFields.length > 0 || absentIdentity.length > 0;
|
|
1565
|
+
if (conversationId && sparseFired) {
|
|
1566
|
+
const dedupeKey = `${accountId}:${userId}:${conversationId}`;
|
|
1567
|
+
if (!sparseStateLogged.has(dedupeKey)) {
|
|
1568
|
+
sparseStateLogged.add(dedupeKey);
|
|
1569
|
+
const FIELDS_LOG_CAP = 10;
|
|
1570
|
+
const absentFieldsTruncated = absentFields.length <= FIELDS_LOG_CAP ? absentFields.join(",") : `${absentFields.slice(0, FIELDS_LOG_CAP).join(",")}+${absentFields.length - FIELDS_LOG_CAP} more`;
|
|
1571
|
+
console.error(
|
|
1572
|
+
`[profile] sparse-state injected accountId=${accountId.slice(0, 8)}\u2026 userId=${userId} conversationId=${conversationId.slice(0, 8)}\u2026 absentCategories=${absentCategories.join(",")} absentFields=${absentFieldsTruncated || "none"} absentIdentity=${absentIdentity.map((k) => k.token).join(",") || "none"}`
|
|
1573
|
+
);
|
|
1574
|
+
}
|
|
1575
|
+
}
|
|
1576
|
+
return summary;
|
|
1577
|
+
} catch (err) {
|
|
1578
|
+
console.error(`[profile] loadUserProfile failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1579
|
+
return null;
|
|
1580
|
+
} finally {
|
|
1581
|
+
await session.close();
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
function formatProfileSummary(profile, preferences) {
|
|
1585
|
+
const givenName = typeof profile.givenName === "string" ? profile.givenName.trim() : "";
|
|
1586
|
+
const familyName = typeof profile.familyName === "string" ? profile.familyName.trim() : "";
|
|
1587
|
+
const joined = familyName ? `${givenName} ${familyName}` : givenName;
|
|
1588
|
+
const name = joined || "Owner";
|
|
1589
|
+
const role = profile.role ? ` (${profile.role})` : "";
|
|
1590
|
+
const tz = profile.timezone ? ` \u2014 ${profile.timezone}` : "";
|
|
1591
|
+
const locale = profile.locale ? `, ${profile.locale}` : "";
|
|
1592
|
+
const expertise = profile.expertise ? `
|
|
1593
|
+
Expertise: ${typeof profile.expertise === "string" ? profile.expertise : JSON.stringify(profile.expertise)}` : "";
|
|
1594
|
+
const lines = [`## About the Owner
|
|
1595
|
+
`];
|
|
1596
|
+
lines.push(`${name}${role}${tz}${locale}${expertise}
|
|
1597
|
+
`);
|
|
1598
|
+
const categories = {};
|
|
1599
|
+
for (const pref of preferences) {
|
|
1600
|
+
if (pref.notApplicable === true) continue;
|
|
1601
|
+
if (!categories[pref.category]) categories[pref.category] = [];
|
|
1602
|
+
categories[pref.category].push(pref);
|
|
1603
|
+
}
|
|
1604
|
+
const categoryLabels = {
|
|
1605
|
+
communication: "Communication",
|
|
1606
|
+
scheduling: "Scheduling",
|
|
1607
|
+
decision: "Decisions",
|
|
1608
|
+
workflow: "Workflow",
|
|
1609
|
+
content: "Content",
|
|
1610
|
+
interaction: "Interaction patterns"
|
|
1611
|
+
};
|
|
1612
|
+
const workCategories = ["communication", "scheduling", "decision", "workflow", "content"];
|
|
1613
|
+
const workPrefs = workCategories.filter((c) => categories[c]);
|
|
1614
|
+
if (workPrefs.length > 0) {
|
|
1615
|
+
lines.push(`### How they work`);
|
|
1616
|
+
for (const cat of workPrefs) {
|
|
1617
|
+
const label = categoryLabels[cat] || cat;
|
|
1618
|
+
const items = categories[cat].map((p) => p.value).join("; ");
|
|
1619
|
+
lines.push(`- ${label}: ${items}`);
|
|
1620
|
+
}
|
|
1621
|
+
lines.push("");
|
|
1622
|
+
}
|
|
1623
|
+
if (categories.interaction) {
|
|
1624
|
+
lines.push(`### Interaction patterns`);
|
|
1625
|
+
for (const pref of categories.interaction) {
|
|
1626
|
+
lines.push(`- ${pref.value}`);
|
|
1627
|
+
}
|
|
1628
|
+
lines.push("");
|
|
1629
|
+
}
|
|
1630
|
+
const identityFields = [
|
|
1631
|
+
{ key: "email", label: "email" },
|
|
1632
|
+
{ key: "telephone", label: "phone" },
|
|
1633
|
+
{ key: "givenName", label: "first name" },
|
|
1634
|
+
{ key: "familyName", label: "last name" },
|
|
1635
|
+
{ key: "role", label: "role" }
|
|
1636
|
+
];
|
|
1637
|
+
const absentIdentity = identityFields.filter((f) => {
|
|
1638
|
+
const v = profile[f.key];
|
|
1639
|
+
return typeof v !== "string" || v.trim().length === 0;
|
|
1640
|
+
});
|
|
1641
|
+
if (absentIdentity.length > 0) {
|
|
1642
|
+
lines.push(`### Identity coverage`);
|
|
1643
|
+
lines.push(`Missing: ${absentIdentity.map((f) => f.label).join(", ")}`);
|
|
1644
|
+
lines.push("");
|
|
1645
|
+
}
|
|
1646
|
+
const absentFields = computeAbsentFields(preferences);
|
|
1647
|
+
if (absentFields.length > 0) {
|
|
1648
|
+
lines.push(`### Coverage`);
|
|
1649
|
+
lines.push(`Missing: ${absentFields.join(", ")}`);
|
|
1650
|
+
lines.push("");
|
|
1651
|
+
}
|
|
1652
|
+
return lines.join("\n");
|
|
1653
|
+
}
|
|
1654
|
+
var MAX_SESSION_TASKS = 20;
|
|
1655
|
+
var MAX_SESSION_PROJECTS = 5;
|
|
1656
|
+
var MAX_RECENT_TOOL_FAILURES = 3;
|
|
1657
|
+
var RECENT_FAILURES_TAIL_BYTES = 10 * 1024;
|
|
1658
|
+
function readRecentToolFailures(accountId, conversationId) {
|
|
1659
|
+
try {
|
|
1660
|
+
const platformRoot = process.env.MAXY_PLATFORM_ROOT ?? resolve(process.cwd(), "..");
|
|
1661
|
+
const logDir = resolve(platformRoot, "..", "data/accounts", accountId, "logs");
|
|
1662
|
+
const logPath = resolve(logDir, `claude-agent-stream-${conversationId}.log`);
|
|
1663
|
+
if (!existsSync(logPath)) {
|
|
1664
|
+
console.error(`[review-tail-skip] path=${logPath} reason=file-missing \u2014 first turn of conversation, subprocess not yet spawned, or log rotated`);
|
|
1665
|
+
return [];
|
|
1666
|
+
}
|
|
1667
|
+
const st = statSync(logPath);
|
|
1668
|
+
const size = st.size;
|
|
1669
|
+
const readBytes = Math.min(size, RECENT_FAILURES_TAIL_BYTES);
|
|
1670
|
+
const position = size - readBytes;
|
|
1671
|
+
const fd = openSync(logPath, "r");
|
|
1672
|
+
try {
|
|
1673
|
+
const buf = Buffer.alloc(readBytes);
|
|
1674
|
+
readSync(fd, buf, 0, readBytes, position);
|
|
1675
|
+
const text = buf.toString("utf-8");
|
|
1676
|
+
const lines = text.split("\n");
|
|
1677
|
+
const matches = [];
|
|
1678
|
+
for (let i = lines.length - 1; i >= 0 && matches.length < MAX_RECENT_TOOL_FAILURES; i--) {
|
|
1679
|
+
const line = lines[i];
|
|
1680
|
+
if (line.includes("[tool-failure-diag]")) {
|
|
1681
|
+
matches.push(line);
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
return matches.reverse();
|
|
1685
|
+
} finally {
|
|
1686
|
+
closeSync(fd);
|
|
1687
|
+
}
|
|
1688
|
+
} catch (err) {
|
|
1689
|
+
console.error(
|
|
1690
|
+
`[session-context] recent-tool-failures read failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1691
|
+
);
|
|
1692
|
+
return [];
|
|
1693
|
+
}
|
|
1694
|
+
}
|
|
1695
|
+
async function loadSessionContext(accountId, conversationId) {
|
|
1696
|
+
const session = getSession();
|
|
1697
|
+
try {
|
|
1698
|
+
const digestResult = await session.run(
|
|
1699
|
+
`MATCH (d:CreativeWork {accountId: $accountId})
|
|
1700
|
+
WHERE d.title STARTS WITH 'Chat Review'
|
|
1701
|
+
RETURN d.title AS title, d.createdAt AS createdAt, d.abstract AS abstract
|
|
1702
|
+
ORDER BY d.createdAt DESC LIMIT 1`,
|
|
1703
|
+
{ accountId }
|
|
1704
|
+
);
|
|
1705
|
+
const tasksResult = await session.run(
|
|
1706
|
+
`MATCH (t:Task {accountId: $accountId})
|
|
1707
|
+
WHERE t.status IN ['pending', 'active']
|
|
1708
|
+
RETURN t.taskId AS taskId, t.name AS name, t.status AS status,
|
|
1709
|
+
t.priority AS priority, t.dueDate AS dueDate
|
|
1710
|
+
ORDER BY
|
|
1711
|
+
CASE t.priority
|
|
1712
|
+
WHEN 'urgent' THEN 0
|
|
1713
|
+
WHEN 'high' THEN 1
|
|
1714
|
+
WHEN 'normal' THEN 2
|
|
1715
|
+
WHEN 'low' THEN 3
|
|
1716
|
+
ELSE 4
|
|
1717
|
+
END,
|
|
1718
|
+
t.createdAt DESC
|
|
1719
|
+
LIMIT $limit`,
|
|
1720
|
+
{ accountId, limit: neo4j.int(MAX_SESSION_TASKS) }
|
|
1721
|
+
);
|
|
1722
|
+
let projectsCount = 0;
|
|
1723
|
+
let projectLines = [];
|
|
1724
|
+
try {
|
|
1725
|
+
const projectsResult = await session.run(
|
|
1726
|
+
`MATCH (p:Project:Task {accountId: $accountId})
|
|
1727
|
+
WHERE p.status IN ['pending', 'active']
|
|
1728
|
+
OPTIONAL MATCH (p)-[:HAS_TASK]->(child:Task)
|
|
1729
|
+
WITH p,
|
|
1730
|
+
count(child) AS totalTasks,
|
|
1731
|
+
count(CASE WHEN child.status = 'completed' THEN 1 END) AS completedTasks,
|
|
1732
|
+
count(CASE WHEN child.dueDate IS NOT NULL
|
|
1733
|
+
AND date(child.dueDate) < date()
|
|
1734
|
+
AND child.status <> 'completed' THEN 1 END) AS overdueTasks,
|
|
1735
|
+
count(CASE WHEN child.status IN ['pending', 'active'] AND EXISTS {
|
|
1736
|
+
MATCH (blocker:Task)-[:BLOCKS]->(child)
|
|
1737
|
+
WHERE blocker.status IN ['pending', 'active']
|
|
1738
|
+
} THEN 1 END) AS blockedTasks
|
|
1739
|
+
RETURN p.name AS name, p.phase AS phase, p.tier AS tier,
|
|
1740
|
+
p.clientRef AS clientRef, p.status AS status,
|
|
1741
|
+
totalTasks, completedTasks, overdueTasks, blockedTasks
|
|
1742
|
+
ORDER BY p.updatedAt DESC
|
|
1743
|
+
LIMIT $limit`,
|
|
1744
|
+
{ accountId, limit: neo4j.int(MAX_SESSION_PROJECTS) }
|
|
1745
|
+
);
|
|
1746
|
+
projectsCount = projectsResult.records.length;
|
|
1747
|
+
if (projectsCount > 0) {
|
|
1748
|
+
projectLines = projectsResult.records.map((r) => {
|
|
1749
|
+
const name = r.get("name") || "Unnamed project";
|
|
1750
|
+
const phase = r.get("phase") || "planning";
|
|
1751
|
+
const tier = r.get("tier") || "standard";
|
|
1752
|
+
const clientRef = r.get("clientRef");
|
|
1753
|
+
const total = typeof r.get("totalTasks") === "number" ? r.get("totalTasks") : r.get("totalTasks")?.toNumber?.() ?? 0;
|
|
1754
|
+
const completed = typeof r.get("completedTasks") === "number" ? r.get("completedTasks") : r.get("completedTasks")?.toNumber?.() ?? 0;
|
|
1755
|
+
const overdue = typeof r.get("overdueTasks") === "number" ? r.get("overdueTasks") : r.get("overdueTasks")?.toNumber?.() ?? 0;
|
|
1756
|
+
const blocked = typeof r.get("blockedTasks") === "number" ? r.get("blockedTasks") : r.get("blockedTasks")?.toNumber?.() ?? 0;
|
|
1757
|
+
let signal;
|
|
1758
|
+
const hasDueDates = overdue > 0 || total > 0;
|
|
1759
|
+
if (!hasDueDates && total === 0) {
|
|
1760
|
+
signal = "grey";
|
|
1761
|
+
} else if (overdue > 1 || blocked > 1) {
|
|
1762
|
+
signal = "red";
|
|
1763
|
+
} else if (overdue > 0 || blocked > 0) {
|
|
1764
|
+
signal = "amber";
|
|
1765
|
+
} else {
|
|
1766
|
+
signal = "green";
|
|
1767
|
+
}
|
|
1768
|
+
const client = clientRef ? ` (${clientRef})` : "";
|
|
1769
|
+
const health = signal !== "grey" ? ` [${signal.toUpperCase()}]` : "";
|
|
1770
|
+
return `- **${name}**${client} \u2014 ${tier}, ${phase}${health}, ${completed}/${total} done${overdue > 0 ? `, ${overdue} overdue` : ""}${blocked > 0 ? `, ${blocked} blocked` : ""}`;
|
|
1771
|
+
});
|
|
1772
|
+
}
|
|
1773
|
+
} catch (projectErr) {
|
|
1774
|
+
console.error(
|
|
1775
|
+
`[session-context] project query failed: ${projectErr instanceof Error ? projectErr.message : String(projectErr)}`
|
|
1776
|
+
);
|
|
1777
|
+
}
|
|
1778
|
+
const sections = [];
|
|
1779
|
+
if (digestResult.records.length > 0) {
|
|
1780
|
+
const rec = digestResult.records[0];
|
|
1781
|
+
const createdAt = rec.get("createdAt");
|
|
1782
|
+
const abstract = rec.get("abstract");
|
|
1783
|
+
if (abstract) {
|
|
1784
|
+
const dateSuffix = createdAt ? ` (${createdAt.slice(0, 10)})` : "";
|
|
1785
|
+
sections.push(`## Recent Public Chat Digest${dateSuffix}
|
|
1786
|
+
${abstract}`);
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
if (tasksResult.records.length > 0) {
|
|
1790
|
+
const taskLines = tasksResult.records.map((r) => {
|
|
1791
|
+
const priority = (r.get("priority") || "normal").toUpperCase();
|
|
1792
|
+
const status = r.get("status");
|
|
1793
|
+
const name = r.get("name");
|
|
1794
|
+
const dueDate = r.get("dueDate");
|
|
1795
|
+
const due = dueDate ? ` due:${dueDate.slice(0, 10)}` : "";
|
|
1796
|
+
const taskId = r.get("taskId");
|
|
1797
|
+
return `- [${priority}] ${status} \u2014 ${name}${due} (${taskId})`;
|
|
1798
|
+
});
|
|
1799
|
+
sections.push(`## Open Tasks (${tasksResult.records.length})
|
|
1800
|
+
${taskLines.join("\n")}`);
|
|
1801
|
+
}
|
|
1802
|
+
let pendingCount = 0;
|
|
1803
|
+
let pendingLines = [];
|
|
1804
|
+
try {
|
|
1805
|
+
const platformRoot = process.env.MAXY_PLATFORM_ROOT ?? resolve(process.cwd(), "..");
|
|
1806
|
+
const pendingDir = resolve(platformRoot, "..", "data/accounts", accountId, "pending-actions");
|
|
1807
|
+
if (existsSync(pendingDir)) {
|
|
1808
|
+
const files = readdirSync(pendingDir).filter((f) => f.endsWith(".json") && !f.startsWith("."));
|
|
1809
|
+
for (const file of files) {
|
|
1810
|
+
try {
|
|
1811
|
+
const raw = readFileSync(resolve(pendingDir, file), "utf-8");
|
|
1812
|
+
const action = JSON.parse(raw);
|
|
1813
|
+
if (action.state === "pending") {
|
|
1814
|
+
const inputSummary = JSON.stringify(action.hookPayload?.tool_input ?? {}).slice(0, 150);
|
|
1815
|
+
pendingLines.push(`- **${action.toolName}** (${action.actionId.slice(0, 8)}\u2026) queued ${action.createdAt?.slice(0, 16) ?? "unknown"}
|
|
1816
|
+
Input: ${inputSummary}`);
|
|
1817
|
+
pendingCount++;
|
|
1818
|
+
}
|
|
1819
|
+
} catch {
|
|
1820
|
+
}
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
} catch (pendingErr) {
|
|
1824
|
+
console.error(
|
|
1825
|
+
`[session-context] pending actions read failed: ${pendingErr instanceof Error ? pendingErr.message : String(pendingErr)}`
|
|
1826
|
+
);
|
|
1827
|
+
}
|
|
1828
|
+
if (pendingCount > 0) {
|
|
1829
|
+
sections.push(`## Pending Actions (${pendingCount})
|
|
1830
|
+
Actions queued for your approval. Use action-approve, action-reject, or action-edit.
|
|
1831
|
+
${pendingLines.join("\n")}`);
|
|
1832
|
+
}
|
|
1833
|
+
if (projectLines.length > 0) {
|
|
1834
|
+
sections.push(`## Active Projects (${projectLines.length})
|
|
1835
|
+
${projectLines.join("\n")}`);
|
|
1836
|
+
}
|
|
1837
|
+
let recentFailuresCount = 0;
|
|
1838
|
+
if (conversationId) {
|
|
1839
|
+
const failureLines = readRecentToolFailures(accountId, conversationId);
|
|
1840
|
+
if (failureLines.length > 0) {
|
|
1841
|
+
recentFailuresCount = failureLines.length;
|
|
1842
|
+
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.";
|
|
1843
|
+
sections.push(`## Recent Tool Failures (${failureLines.length})
|
|
1844
|
+
${guidance}
|
|
1845
|
+
|
|
1846
|
+
${failureLines.map((l) => `- ${l.trim()}`).join("\n")}`);
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
if (sections.length === 0) return null;
|
|
1850
|
+
console.error(
|
|
1851
|
+
`[session-context] Loaded for ${accountId.slice(0, 8)}\u2026: digest=${digestResult.records.length > 0 ? "yes" : "no"}, tasks=${tasksResult.records.length}, projects=${projectsCount}, pendingActions=${pendingCount}, recentFailures=${recentFailuresCount}`
|
|
1852
|
+
);
|
|
1853
|
+
return `<previous-context>
|
|
1854
|
+
${sections.join("\n\n")}
|
|
1855
|
+
</previous-context>`;
|
|
1856
|
+
} catch (err) {
|
|
1857
|
+
console.error(`[session-context] loadSessionContext failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1858
|
+
return null;
|
|
1859
|
+
} finally {
|
|
1860
|
+
await session.close();
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
async function consumeStep7FlagUI(session, accountId) {
|
|
1864
|
+
const accountDir = resolve(PLATFORM_ROOT, "..", "data/accounts", accountId);
|
|
1865
|
+
const flagPath = resolve(accountDir, "onboarding", "step7-complete");
|
|
1866
|
+
if (!existsSync(flagPath)) return false;
|
|
1867
|
+
let completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1868
|
+
try {
|
|
1869
|
+
const raw = readFileSync(flagPath, "utf-8").trim();
|
|
1870
|
+
if (raw) {
|
|
1871
|
+
const parsed = JSON.parse(raw);
|
|
1872
|
+
if (typeof parsed.completedAt === "string") {
|
|
1873
|
+
completedAt = parsed.completedAt;
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
} catch {
|
|
1877
|
+
}
|
|
1878
|
+
const result = await session.run(
|
|
1879
|
+
`MATCH (o:OnboardingState {accountId: $accountId})
|
|
1880
|
+
SET o.step7CompletedAt = CASE WHEN o.step7CompletedAt IS NULL THEN $completedAt ELSE o.step7CompletedAt END,
|
|
1881
|
+
o.currentStep = CASE WHEN 7 > o.currentStep THEN 7 ELSE o.currentStep END,
|
|
1882
|
+
o.updatedAt = $completedAt
|
|
1883
|
+
RETURN count(o) AS updated`,
|
|
1884
|
+
{ accountId, completedAt }
|
|
1885
|
+
);
|
|
1886
|
+
const updatedRaw = result.records[0]?.get("updated");
|
|
1887
|
+
const updated = typeof updatedRaw === "number" ? updatedRaw : updatedRaw && typeof updatedRaw === "object" && "toNumber" in updatedRaw ? updatedRaw.toNumber() : 0;
|
|
1888
|
+
if (updated === 0) {
|
|
1889
|
+
console.log(
|
|
1890
|
+
`[onboarding-flag-consumed] accountId=${accountId.slice(0, 8)}\u2026 step=7 source=filesystem flagPath=${flagPath} skipped=no-node`
|
|
1891
|
+
);
|
|
1892
|
+
return false;
|
|
1893
|
+
}
|
|
1894
|
+
console.log(
|
|
1895
|
+
`[onboarding-flag-consumed] accountId=${accountId.slice(0, 8)}\u2026 step=7 source=filesystem flagPath=${flagPath} completedAt=${completedAt}`
|
|
1896
|
+
);
|
|
1897
|
+
try {
|
|
1898
|
+
rmSync(flagPath);
|
|
1899
|
+
} catch (err) {
|
|
1900
|
+
console.error(
|
|
1901
|
+
`[onboarding-flag-consumed] warn: failed to delete ${flagPath}: ${err instanceof Error ? err.message : String(err)}`
|
|
1902
|
+
);
|
|
1903
|
+
}
|
|
1904
|
+
return true;
|
|
1905
|
+
}
|
|
1906
|
+
async function loadOnboardingStep(accountId) {
|
|
1907
|
+
const session = getSession();
|
|
1908
|
+
try {
|
|
1909
|
+
await consumeStep7FlagUI(session, accountId);
|
|
1910
|
+
const result = await session.run(
|
|
1911
|
+
`MATCH (o:OnboardingState {accountId: $accountId})
|
|
1912
|
+
RETURN o.currentStep AS currentStep`,
|
|
1913
|
+
{ accountId }
|
|
1914
|
+
);
|
|
1915
|
+
if (result.records.length === 0) {
|
|
1916
|
+
return -1;
|
|
1917
|
+
}
|
|
1918
|
+
const raw = result.records[0].get("currentStep");
|
|
1919
|
+
if (typeof raw === "number") return raw;
|
|
1920
|
+
if (raw && typeof raw === "object" && "toNumber" in raw) {
|
|
1921
|
+
return raw.toNumber();
|
|
1922
|
+
}
|
|
1923
|
+
return 0;
|
|
1924
|
+
} catch (err) {
|
|
1925
|
+
console.error(`[onboarding-inject] loadOnboardingStep failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
1926
|
+
return null;
|
|
1927
|
+
} finally {
|
|
1928
|
+
await session.close();
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
var AGENT_FILE_ROLES = [
|
|
1932
|
+
{ filename: "IDENTITY.md", role: "identity" },
|
|
1933
|
+
{ filename: "SOUL.md", role: "soul" },
|
|
1934
|
+
{ filename: "KNOWLEDGE.md", role: "knowledge" },
|
|
1935
|
+
{ filename: "KNOWLEDGE-SUMMARY.md", role: "knowledge-summary" }
|
|
1936
|
+
];
|
|
1937
|
+
var ROLE_TO_EDGE = {
|
|
1938
|
+
identity: "HAS_IDENTITY",
|
|
1939
|
+
soul: "HAS_SOUL",
|
|
1940
|
+
knowledge: "HAS_KNOWLEDGE",
|
|
1941
|
+
"knowledge-summary": "HAS_KNOWLEDGE"
|
|
1942
|
+
};
|
|
1943
|
+
function assertSafeAgentSlug(slug) {
|
|
1944
|
+
if (!slug || slug.includes("/") || slug.includes("\\") || slug.includes("..")) {
|
|
1945
|
+
throw new Error(`[agent-graph] refusing unsafe slug=${JSON.stringify(slug)}`);
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
function agentAttachmentId(accountId, slug, role) {
|
|
1949
|
+
return `agent:${accountId}:${slug}:${role}`;
|
|
1950
|
+
}
|
|
1951
|
+
async function projectAgent(accountId, accountDir, slug) {
|
|
1952
|
+
const start = Date.now();
|
|
1953
|
+
const account8 = accountId.slice(0, 8);
|
|
1954
|
+
try {
|
|
1955
|
+
assertSafeAgentSlug(slug);
|
|
1956
|
+
} catch (err) {
|
|
1957
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1958
|
+
console.error(
|
|
1959
|
+
`[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
|
|
1960
|
+
);
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1963
|
+
const agentDir = resolve(accountDir, "agents", slug);
|
|
1964
|
+
const configPath = resolve(agentDir, "config.json");
|
|
1965
|
+
let config;
|
|
1966
|
+
let presentRoles = [];
|
|
1967
|
+
try {
|
|
1968
|
+
if (!existsSync(configPath)) {
|
|
1969
|
+
console.error(
|
|
1970
|
+
`[agent-graph] project FAILED slug=${slug} account=${account8} error="config.json missing at ${configPath}"`
|
|
1971
|
+
);
|
|
1972
|
+
return;
|
|
1973
|
+
}
|
|
1974
|
+
config = JSON.parse(readFileSync(configPath, "utf-8"));
|
|
1975
|
+
for (const { filename, role } of AGENT_FILE_ROLES) {
|
|
1976
|
+
const filePath = resolve(agentDir, filename);
|
|
1977
|
+
if (!existsSync(filePath)) continue;
|
|
1978
|
+
const body = readFileSync(filePath, "utf-8");
|
|
1979
|
+
presentRoles.push({ role, body, edge: ROLE_TO_EDGE[role] });
|
|
1980
|
+
}
|
|
1981
|
+
} catch (err) {
|
|
1982
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1983
|
+
console.error(
|
|
1984
|
+
`[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
|
|
1985
|
+
);
|
|
1986
|
+
return;
|
|
1987
|
+
}
|
|
1988
|
+
const session = getSession();
|
|
1989
|
+
try {
|
|
1990
|
+
await session.run(
|
|
1991
|
+
`MERGE (a:Agent {accountId: $accountId, slug: $slug})
|
|
1992
|
+
ON CREATE SET a.createdAt = datetime()
|
|
1993
|
+
SET a.displayName = $displayName,
|
|
1994
|
+
a.status = $status,
|
|
1995
|
+
a.model = $model,
|
|
1996
|
+
a.liveMemory = $liveMemory,
|
|
1997
|
+
a.knowledgeKeywords = $knowledgeKeywords,
|
|
1998
|
+
a.role = 'agent',
|
|
1999
|
+
a.updatedAt = datetime()
|
|
2000
|
+
RETURN a.slug AS slug`,
|
|
2001
|
+
{
|
|
2002
|
+
accountId,
|
|
2003
|
+
slug,
|
|
2004
|
+
displayName: config.displayName ?? slug,
|
|
2005
|
+
status: config.status ?? "unknown",
|
|
2006
|
+
model: config.model ?? "",
|
|
2007
|
+
liveMemory: config.liveMemory ?? false,
|
|
2008
|
+
knowledgeKeywords: config.knowledgeKeywords ?? []
|
|
2009
|
+
}
|
|
2010
|
+
);
|
|
2011
|
+
for (const { role, body, edge } of presentRoles) {
|
|
2012
|
+
const attachmentId = agentAttachmentId(accountId, slug, role);
|
|
2013
|
+
await session.run(
|
|
2014
|
+
`MATCH (a:Agent {accountId: $accountId, slug: $slug})
|
|
2015
|
+
MERGE (k:KnowledgeDocument {attachmentId: $attachmentId})
|
|
2016
|
+
ON CREATE SET k.createdAt = datetime()
|
|
2017
|
+
SET k.accountId = $accountId,
|
|
2018
|
+
k.role = $role,
|
|
2019
|
+
k.name = $name,
|
|
2020
|
+
k.text = $text,
|
|
2021
|
+
k.scope = 'admin',
|
|
2022
|
+
k.updatedAt = datetime()
|
|
2023
|
+
MERGE (a)-[:${edge}]->(k)
|
|
2024
|
+
RETURN k.attachmentId AS attachmentId`,
|
|
2025
|
+
{
|
|
2026
|
+
accountId,
|
|
2027
|
+
slug,
|
|
2028
|
+
attachmentId,
|
|
2029
|
+
role,
|
|
2030
|
+
name: `${slug} ${role}`,
|
|
2031
|
+
text: body
|
|
2032
|
+
}
|
|
2033
|
+
);
|
|
2034
|
+
}
|
|
2035
|
+
const usesResult = await session.run(
|
|
2036
|
+
`MATCH (a:Agent {accountId: $accountId, slug: $slug})
|
|
2037
|
+
MATCH (k:KnowledgeDocument {accountId: $accountId})
|
|
2038
|
+
WHERE $slug IN coalesce(k.agents, [])
|
|
2039
|
+
AND NOT k.attachmentId STARTS WITH $namespacePrefix
|
|
2040
|
+
MERGE (a)-[:USES_KNOWLEDGE]->(k)
|
|
2041
|
+
RETURN count(k) AS uses`,
|
|
2042
|
+
{
|
|
2043
|
+
accountId,
|
|
2044
|
+
slug,
|
|
2045
|
+
namespacePrefix: `agent:${accountId}:${slug}:`
|
|
2046
|
+
}
|
|
2047
|
+
);
|
|
2048
|
+
const uses = usesResult.records[0]?.get("uses");
|
|
2049
|
+
const usesCount = typeof uses === "number" ? uses : uses && typeof uses.toNumber === "function" ? uses.toNumber() : 0;
|
|
2050
|
+
const ms = Date.now() - start;
|
|
2051
|
+
console.error(
|
|
2052
|
+
`[agent-graph] project slug=${slug} account=${account8} docs=${presentRoles.length} uses=${usesCount} ms=${ms}`
|
|
2053
|
+
);
|
|
2054
|
+
} catch (err) {
|
|
2055
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2056
|
+
console.error(
|
|
2057
|
+
`[agent-graph] project FAILED slug=${slug} account=${account8} error="${msg}"`
|
|
2058
|
+
);
|
|
2059
|
+
throw err;
|
|
2060
|
+
} finally {
|
|
2061
|
+
await session.close();
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
async function deleteAgentProjection(accountId, slug) {
|
|
2065
|
+
const start = Date.now();
|
|
2066
|
+
const account8 = accountId.slice(0, 8);
|
|
2067
|
+
assertSafeAgentSlug(slug);
|
|
2068
|
+
const session = getSession();
|
|
2069
|
+
try {
|
|
2070
|
+
await session.run(
|
|
2071
|
+
`MATCH (a:Agent {accountId: $accountId, slug: $slug})
|
|
2072
|
+
DETACH DELETE a
|
|
2073
|
+
WITH 1 AS _
|
|
2074
|
+
UNWIND $attachmentIds AS aid
|
|
2075
|
+
OPTIONAL MATCH (k:KnowledgeDocument {accountId: $accountId, attachmentId: aid})
|
|
2076
|
+
WHERE k.attachmentId STARTS WITH $namespacePrefix
|
|
2077
|
+
DETACH DELETE k`,
|
|
2078
|
+
{
|
|
2079
|
+
accountId,
|
|
2080
|
+
slug,
|
|
2081
|
+
namespacePrefix: `agent:${accountId}:${slug}:`,
|
|
2082
|
+
attachmentIds: ["identity", "soul", "knowledge", "knowledge-summary"].map((role) => agentAttachmentId(accountId, slug, role))
|
|
2083
|
+
}
|
|
2084
|
+
);
|
|
2085
|
+
const ms = Date.now() - start;
|
|
2086
|
+
console.error(
|
|
2087
|
+
`[agent-graph] delete slug=${slug} account=${account8} ms=${ms}`
|
|
2088
|
+
);
|
|
2089
|
+
} catch (err) {
|
|
2090
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2091
|
+
console.error(
|
|
2092
|
+
`[agent-graph] delete FAILED slug=${slug} account=${account8} error="${msg}"`
|
|
2093
|
+
);
|
|
2094
|
+
throw err;
|
|
2095
|
+
} finally {
|
|
2096
|
+
await session.close();
|
|
2097
|
+
}
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
export {
|
|
2101
|
+
HAIKU_MODEL,
|
|
2102
|
+
contextWindow,
|
|
2103
|
+
getSession,
|
|
2104
|
+
runAdminUserSelfHeal,
|
|
2105
|
+
embed,
|
|
2106
|
+
setSessionStoreRef,
|
|
2107
|
+
GREETING_DIRECTIVE,
|
|
2108
|
+
ensureConversation,
|
|
2109
|
+
findRecentConversation,
|
|
2110
|
+
findGroupBySlug,
|
|
2111
|
+
getGroupParticipants,
|
|
2112
|
+
checkGroupMembership,
|
|
2113
|
+
bindVisitorToGroup,
|
|
2114
|
+
getMessagesSince,
|
|
2115
|
+
getGroupMessagesForContext,
|
|
2116
|
+
backfillNullUserIdConversations,
|
|
2117
|
+
createNewAdminConversation,
|
|
2118
|
+
fetchBranding,
|
|
2119
|
+
persistToolCall,
|
|
2120
|
+
persistMessage,
|
|
2121
|
+
setConversationAgentSessionId,
|
|
2122
|
+
getAgentSessionIdForConversation,
|
|
2123
|
+
getRecentMessages,
|
|
2124
|
+
markComponentSubmitted,
|
|
2125
|
+
verifyConversationOwnership,
|
|
2126
|
+
getConversationOwner,
|
|
2127
|
+
verifyAndGetConversationUpdatedAt,
|
|
2128
|
+
searchMessages,
|
|
2129
|
+
listAdminSessions,
|
|
2130
|
+
deleteConversation,
|
|
2131
|
+
isMessageUseful,
|
|
2132
|
+
generateSessionLabel,
|
|
2133
|
+
autoLabelSession,
|
|
2134
|
+
renameConversation,
|
|
2135
|
+
getUserTimezone,
|
|
2136
|
+
loadAdminUserName,
|
|
2137
|
+
writeAdminUserAndPerson,
|
|
2138
|
+
loadUserProfile,
|
|
2139
|
+
loadSessionContext,
|
|
2140
|
+
loadOnboardingStep,
|
|
2141
|
+
projectAgent,
|
|
2142
|
+
deleteAgentProjection
|
|
2143
|
+
};
|