1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
|
import { and, asc, desc, eq } from "drizzle-orm";
import { db } from "../db";
import {
personalChats,
personalChatMessages,
type PersonalChat,
type PersonalChatMessage,
} from "../db/schema";
import {
isPersonalSemanticEnabled,
searchPersonalSemantic,
type PersonalSemanticHit,
} from "./personal-semantic";
import { getAnthropic, isAiAvailable, MODEL_SONNET } from "./ai-client";
const DEFAULT_TOP_K = 8;
const MAX_SNIPPET_CHARS = 1500;
const TITLE_LIMIT = 80;
const ASSISTANT_REPLY_CAP = 32_000;
export interface PersonalCitation {
file_path: string;
blob_sha: string;
repo_name: string;
}
export interface CreatePersonalChatOpts {
ownerUserId: string;
title?: string | null;
}
export interface PersonalStreamReplyOpts {
chatId: string;
userId: string;
userMessage: string;
onChunk?: (chunk: string) => void;
topK?: number;
}
export type PersonalStreamerFn = (args: {
systemPrompt: string;
userMessage: string;
}) => AsyncIterable<string>;
let _streamerOverride: PersonalStreamerFn | null = null;
export function __setPersonalStreamerForTests(
fn: PersonalStreamerFn | null
): void {
_streamerOverride = fn;
}
export async function createPersonalChat(
opts: CreatePersonalChatOpts
): Promise<PersonalChat | null> {
if (!opts.ownerUserId) return null;
try {
const [row] = await db
.insert(personalChats)
.values({
ownerUserId: opts.ownerUserId,
title: (opts.title || "").slice(0, TITLE_LIMIT) || null,
})
.returning();
return row || null;
} catch (err) {
if (process.env.DEBUG_PERSONAL_CHAT === "1") {
console.error("[personal-chat] createPersonalChat failed:", err);
}
return null;
}
}
export async function appendPersonalUserMessage(
chatId: string,
content: string
): Promise<PersonalChatMessage | null> {
if (!chatId || !content) return null;
try {
const [row] = await db
.insert(personalChatMessages)
.values({
chatId,
role: "user",
content,
citations: [],
tokenCost: 0,
})
.returning();
try {
await db
.update(personalChats)
.set({ updatedAt: new Date() })
.where(eq(personalChats.id, chatId));
} catch {
}
return row || null;
} catch (err) {
if (process.env.DEBUG_PERSONAL_CHAT === "1") {
console.error("[personal-chat] appendPersonalUserMessage failed:", err);
}
return null;
}
}
export async function streamPersonalAssistantReply(
opts: PersonalStreamReplyOpts
): Promise<PersonalChatMessage | null> {
const { chatId, userId, userMessage } = opts;
const topK = Math.max(1, Math.min(opts.topK ?? DEFAULT_TOP_K, 20));
const enabled = await isPersonalSemanticEnabled(userId);
const { citations, contextBlock } = await buildPersonalContext({
userId,
userMessage,
topK,
enabled,
});
const systemPrompt = buildPersonalSystemPrompt({
enabled,
contextBlock,
citationCount: citations.length,
});
let reply = "";
try {
const stream = _streamerOverride
? _streamerOverride({ systemPrompt, userMessage })
: claudeStreamPersonal({ systemPrompt, userMessage });
for await (const chunk of stream) {
if (!chunk) continue;
reply += chunk;
if (opts.onChunk) {
try {
opts.onChunk(chunk);
} catch {
}
}
if (reply.length >= ASSISTANT_REPLY_CAP) break;
}
} catch (err) {
if (process.env.DEBUG_PERSONAL_CHAT === "1") {
console.error("[personal-chat] stream failed:", err);
}
if (!reply) {
reply =
"Sorry — I couldn't reach the AI service to answer that. Please retry in a moment.";
}
}
if (reply.length > ASSISTANT_REPLY_CAP) {
reply = reply.slice(0, ASSISTANT_REPLY_CAP);
}
const tokenCost = Math.ceil(
(systemPrompt.length + userMessage.length + reply.length) / 4
);
try {
const [row] = await db
.insert(personalChatMessages)
.values({
chatId,
role: "assistant",
content: reply,
citations,
tokenCost,
})
.returning();
try {
await db
.update(personalChats)
.set({ updatedAt: new Date() })
.where(eq(personalChats.id, chatId));
} catch {
}
return row || null;
} catch (err) {
if (process.env.DEBUG_PERSONAL_CHAT === "1") {
console.error("[personal-chat] persist assistant failed:", err);
}
return null;
}
}
export async function listPersonalChatsForUser(
ownerUserId: string,
limit = 30
): Promise<PersonalChat[]> {
if (!ownerUserId) return [];
try {
return await db
.select()
.from(personalChats)
.where(eq(personalChats.ownerUserId, ownerUserId))
.orderBy(desc(personalChats.updatedAt))
.limit(Math.max(1, Math.min(limit, 100)));
} catch {
return [];
}
}
export async function listPersonalMessages(
chatId: string
): Promise<PersonalChatMessage[]> {
if (!chatId) return [];
try {
return await db
.select()
.from(personalChatMessages)
.where(eq(personalChatMessages.chatId, chatId))
.orderBy(asc(personalChatMessages.createdAt));
} catch {
return [];
}
}
export async function getPersonalChatForUser(
chatId: string,
ownerUserId: string
): Promise<PersonalChat | null> {
if (!chatId || !ownerUserId) return null;
try {
const [row] = await db
.select()
.from(personalChats)
.where(
and(
eq(personalChats.id, chatId),
eq(personalChats.ownerUserId, ownerUserId)
)
)
.limit(1);
return row || null;
} catch {
return null;
}
}
async function buildPersonalContext(args: {
userId: string;
userMessage: string;
topK: number;
enabled: boolean;
}): Promise<{ citations: PersonalCitation[]; contextBlock: string }> {
if (!args.enabled) {
return { citations: [], contextBlock: "" };
}
let hits: PersonalSemanticHit[] = [];
try {
hits = await searchPersonalSemantic({
userId: args.userId,
query: args.userMessage,
limit: args.topK,
});
} catch {
hits = [];
}
if (!hits.length) {
return { citations: [], contextBlock: "" };
}
const citations: PersonalCitation[] = [];
const sections: string[] = [];
for (const hit of hits) {
const snippet = (hit.snippet || "").slice(0, MAX_SNIPPET_CHARS);
if (!snippet) continue;
citations.push({
file_path: hit.filePath,
blob_sha: hit.blobSha,
repo_name: hit.repoName,
});
sections.push(
`### ${hit.repoName} · ${hit.filePath}\n\`\`\`\n${snippet}\n\`\`\``
);
}
return { citations, contextBlock: sections.join("\n\n") };
}
function buildPersonalSystemPrompt(args: {
enabled: boolean;
contextBlock: string;
citationCount: number;
}): string {
if (!args.enabled) {
return [
"You are Gluecron's personal cross-repo chat assistant.",
"",
"The user has NOT enabled personal cross-repo semantic search.",
"Tell them clearly that you can't see their code until they enable",
"the toggle at /settings (Personal cross-repo semantic index). Do",
"not attempt to answer code-specific questions in this mode.",
].join("\n");
}
const lines = [
"You are Gluecron's personal cross-repo chat assistant.",
"",
"You have access to semantic-index snippets across every repository",
"the user owns or is an accepted collaborator on. Citations name the",
"source repo as `owner/repo`; always include the repo name when you",
"reference a file, e.g. `owner/repo:src/lib/foo.ts`.",
"",
"Most relevant context:",
"",
args.contextBlock || "(no semantic hits — say so plainly)",
"",
"Answer concisely. Prefer code snippets over prose when explaining",
"concrete behaviour. If the grounding context doesn't cover the",
"question, say so rather than guessing.",
];
return lines.join("\n");
}
async function* claudeStreamPersonal(args: {
systemPrompt: string;
userMessage: string;
}): AsyncGenerator<string, void, unknown> {
if (!isAiAvailable()) {
yield "AI is not configured on this Gluecron instance — set ANTHROPIC_API_KEY to enable personal chat.";
return;
}
const client = getAnthropic();
const stream = client.messages.stream({
model: MODEL_SONNET,
max_tokens: 2048,
system: args.systemPrompt,
messages: [{ role: "user", content: args.userMessage }],
});
let inputTokens = 0;
let outputTokens = 0;
for await (const event of stream as AsyncIterable<unknown>) {
const ev = event as Record<string, unknown> | null;
if (ev && typeof ev === "object") {
const msg = (ev as { message?: { usage?: { input_tokens?: number; output_tokens?: number } } }).message;
if (msg && msg.usage) {
if (typeof msg.usage.input_tokens === "number")
inputTokens = msg.usage.input_tokens;
if (typeof msg.usage.output_tokens === "number")
outputTokens = msg.usage.output_tokens;
}
const usage = (ev as { usage?: { input_tokens?: number; output_tokens?: number } }).usage;
if (usage) {
if (typeof usage.input_tokens === "number")
inputTokens = usage.input_tokens;
if (typeof usage.output_tokens === "number")
outputTokens = usage.output_tokens;
}
}
const delta = extractTextDelta(event);
if (delta) yield delta;
}
try {
const { recordAiCost } = await import("./ai-cost-tracker");
await recordAiCost({
model: MODEL_SONNET,
inputTokens,
outputTokens,
category: "chat",
sourceKind: "personal_chat",
});
} catch {
}
}
function extractTextDelta(event: unknown): string {
if (!event || typeof event !== "object") return "";
const e = event as Record<string, unknown>;
if (e.type !== "content_block_delta") return "";
const delta = e.delta as Record<string, unknown> | undefined;
if (!delta) return "";
if (delta.type === "text_delta" && typeof delta.text === "string") {
return delta.text;
}
return "";
}
export const __test = {
buildPersonalContext,
buildPersonalSystemPrompt,
extractTextDelta,
ASSISTANT_REPLY_CAP,
MAX_SNIPPET_CHARS,
};
|