@free-intelligence/core 1.2.0 → 1.12.0
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/README.md +1 -0
- package/dist/availability/index.d.ts +132 -0
- package/dist/availability/index.js +278 -0
- package/dist/availability/index.js.map +1 -0
- package/dist/index.d.ts +907 -112
- package/dist/index.js +448 -9
- package/dist/index.js.map +1 -1
- package/package.json +31 -2
- package/src/agent/conversation-state-vectors.test.ts +125 -0
- package/src/agent/conversation-state.test.ts +320 -0
- package/src/agent/conversation-state.ts +278 -0
- package/src/agent/events.ts +50 -1
- package/src/agent/hook.ts +26 -2
- package/src/agent/sse-fixture.test.ts +53 -0
- package/src/agent/sse.ts +26 -0
- package/src/agent/state.test.ts +60 -0
- package/src/agent/state.ts +44 -0
- package/src/agent/transcript.test.ts +166 -15
- package/src/agent/transcript.ts +92 -13
- package/src/agent/turn-vectors.test.ts +75 -0
- package/src/agent/wire-map.ts +131 -0
- package/src/agent/wire.generated.ts +265 -0
- package/src/availability/availability.test.ts +130 -0
- package/src/availability/defaults.ts +89 -0
- package/src/availability/index.ts +6 -0
- package/src/availability/time.ts +38 -0
- package/src/availability/types.ts +69 -0
- package/src/availability/validation.ts +133 -0
- package/src/availability/week.ts +50 -0
- package/src/chat/message.ts +81 -2
- package/src/chat/record.generated.ts +156 -0
- package/src/conversation/derivations-vectors.test.ts +65 -0
- package/src/conversation/helpers.test.ts +329 -0
- package/src/conversation/helpers.ts +248 -3
- package/src/conversation/index.ts +17 -0
- package/src/conversation/library.ts +12 -0
- package/src/conversation/markdown.test.ts +84 -0
- package/src/conversation/markdown.ts +67 -0
- package/src/conversation/record.ts +29 -1
- package/src/copy.generated.ts +19 -0
- package/src/index.ts +55 -3
|
@@ -12,9 +12,19 @@ import {
|
|
|
12
12
|
CONVERSATION_SCHEMA_VERSION,
|
|
13
13
|
createConversationRecord,
|
|
14
14
|
summarizeConversation,
|
|
15
|
+
organizeConversationSummaries,
|
|
16
|
+
filterConversationSummaries,
|
|
15
17
|
deriveConversationTitle,
|
|
16
18
|
deriveConversationPreview,
|
|
19
|
+
resolveConversationTitle,
|
|
20
|
+
renameConversationRecord,
|
|
21
|
+
setConversationPinned,
|
|
22
|
+
setConversationArchived,
|
|
17
23
|
sanitizeConversationMessage,
|
|
24
|
+
applyConversationMetadataPatch,
|
|
25
|
+
conversationRenamePatch,
|
|
26
|
+
conversationPinPatch,
|
|
27
|
+
conversationArchivePatch,
|
|
18
28
|
} from './helpers';
|
|
19
29
|
|
|
20
30
|
const NOW = '2026-06-09T00:00:00.000Z';
|
|
@@ -54,6 +64,54 @@ describe('sanitizeConversationMessage — privacy by structure', () => {
|
|
|
54
64
|
const clean = sanitizeConversationMessage(future);
|
|
55
65
|
expect(Object.keys(clean).sort()).toEqual(['content', 'role', 'timestamp']);
|
|
56
66
|
});
|
|
67
|
+
|
|
68
|
+
it('preserves the glass-box trace (B3-FIGLASS-TRACE-PERSISTENCE-1)', () => {
|
|
69
|
+
const traced: ChatMessage = {
|
|
70
|
+
role: 'assistant',
|
|
71
|
+
content: 'aquí tienes el plan',
|
|
72
|
+
timestamp: NOW,
|
|
73
|
+
trace: {
|
|
74
|
+
plan: { steps: [{ label: 'Investigar', status: 'done' }], outcome: 'completed' },
|
|
75
|
+
tools: [{ id: 't1', name: 'search_documents', server: 'rag', isError: false }],
|
|
76
|
+
sources: ['doc://a'],
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
const clean = sanitizeConversationMessage(traced);
|
|
80
|
+
expect(clean.trace?.plan?.steps).toHaveLength(1);
|
|
81
|
+
expect(clean.trace?.tools?.[0].name).toBe('search_documents');
|
|
82
|
+
expect(clean.trace?.sources).toEqual(['doc://a']);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('still drops metadata even when a trace is present (no secret leak via the new field)', () => {
|
|
86
|
+
const mixed: ChatMessage = {
|
|
87
|
+
role: 'assistant',
|
|
88
|
+
content: 'hola',
|
|
89
|
+
timestamp: NOW,
|
|
90
|
+
metadata: { token: 'Bearer xyz' },
|
|
91
|
+
trace: { sources: ['doc://safe'] },
|
|
92
|
+
};
|
|
93
|
+
const clean = sanitizeConversationMessage(mixed);
|
|
94
|
+
expect('metadata' in clean).toBe(false);
|
|
95
|
+
expect(clean.trace?.sources).toEqual(['doc://safe']);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('preserves attached images with exactly mediaType + data (OG118-IMAGE-UPLOAD-1)', () => {
|
|
99
|
+
const withImage = {
|
|
100
|
+
role: 'user',
|
|
101
|
+
content: 'mira',
|
|
102
|
+
timestamp: NOW,
|
|
103
|
+
images: [{ mediaType: 'image/png', data: 'aGk=', extra: 'dropped' }],
|
|
104
|
+
} as unknown as ChatMessage;
|
|
105
|
+
const clean = sanitizeConversationMessage(withImage);
|
|
106
|
+
expect(clean.images).toEqual([{ mediaType: 'image/png', data: 'aGk=' }]);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('omits the images field when absent or empty (text-only records unchanged)', () => {
|
|
110
|
+
expect('images' in sanitizeConversationMessage(msg('user', 'hola'))).toBe(false);
|
|
111
|
+
expect(
|
|
112
|
+
'images' in sanitizeConversationMessage(msg('user', 'hola', { images: [] })),
|
|
113
|
+
).toBe(false);
|
|
114
|
+
});
|
|
57
115
|
});
|
|
58
116
|
|
|
59
117
|
describe('deriveConversationTitle', () => {
|
|
@@ -152,3 +210,274 @@ describe('summarizeConversation', () => {
|
|
|
152
210
|
});
|
|
153
211
|
});
|
|
154
212
|
});
|
|
213
|
+
|
|
214
|
+
const LATER = '2026-06-10T00:00:00.000Z';
|
|
215
|
+
|
|
216
|
+
describe('renameConversationRecord — user rename', () => {
|
|
217
|
+
it('stores a non-empty title verbatim and marks it custom', () => {
|
|
218
|
+
const rec = createConversationRecord({
|
|
219
|
+
id: 'r1',
|
|
220
|
+
messages: [msg('user', 'derived from this')],
|
|
221
|
+
now: NOW,
|
|
222
|
+
});
|
|
223
|
+
const next = renameConversationRecord(rec, ' My cool chat ', LATER);
|
|
224
|
+
expect(next.title).toBe('My cool chat');
|
|
225
|
+
expect(next.titleCustom).toBe(true);
|
|
226
|
+
expect(next.updatedAt).toBe(LATER);
|
|
227
|
+
expect(next.createdAt).toBe(NOW); // untouched
|
|
228
|
+
expect(rec.titleCustom).toBeUndefined(); // pure: original not mutated
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it('caps a custom title at the title max length', () => {
|
|
232
|
+
const rec = createConversationRecord({ id: 'r2', now: NOW });
|
|
233
|
+
const long = 'x'.repeat(200);
|
|
234
|
+
const next = renameConversationRecord(rec, long, LATER);
|
|
235
|
+
expect(next.title.length).toBe(60);
|
|
236
|
+
expect(next.titleCustom).toBe(true);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it('reverts to the derived title and clears custom on an empty title', () => {
|
|
240
|
+
const rec = renameConversationRecord(
|
|
241
|
+
createConversationRecord({
|
|
242
|
+
id: 'r3',
|
|
243
|
+
messages: [msg('user', 'original question')],
|
|
244
|
+
now: NOW,
|
|
245
|
+
}),
|
|
246
|
+
'renamed',
|
|
247
|
+
LATER,
|
|
248
|
+
);
|
|
249
|
+
expect(rec.titleCustom).toBe(true);
|
|
250
|
+
const reverted = renameConversationRecord(rec, ' ', LATER);
|
|
251
|
+
expect(reverted.title).toBe('original question');
|
|
252
|
+
expect(reverted.titleCustom).toBe(false);
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
describe('resolveConversationTitle — persist preserves a rename', () => {
|
|
257
|
+
it('derives from messages when there is no custom title', () => {
|
|
258
|
+
const messages = [msg('user', 'fresh derive')];
|
|
259
|
+
expect(resolveConversationTitle(messages)).toBe('fresh derive');
|
|
260
|
+
expect(
|
|
261
|
+
resolveConversationTitle(messages, { title: 'old', titleCustom: false }),
|
|
262
|
+
).toBe('fresh derive');
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
it('keeps a custom title instead of re-deriving', () => {
|
|
266
|
+
const messages = [msg('user', 'would derive to this')];
|
|
267
|
+
expect(
|
|
268
|
+
resolveConversationTitle(messages, {
|
|
269
|
+
title: 'User Named It',
|
|
270
|
+
titleCustom: true,
|
|
271
|
+
}),
|
|
272
|
+
).toBe('User Named It');
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
it('falls back to derive when a custom title is blank', () => {
|
|
276
|
+
const messages = [msg('user', 'derive fallback')];
|
|
277
|
+
expect(
|
|
278
|
+
resolveConversationTitle(messages, { title: ' ', titleCustom: true }),
|
|
279
|
+
).toBe('derive fallback');
|
|
280
|
+
});
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
describe('sanitizeConversationMessage — the author survives persistence', () => {
|
|
284
|
+
it('keeps the author (a reloaded thread must still say who spoke)', () => {
|
|
285
|
+
const clean = sanitizeConversationMessage(
|
|
286
|
+
msg('assistant', 'hola', {
|
|
287
|
+
author: { id: 'element-053-i-yodo', name: 'Yodo', symbol: 'I' },
|
|
288
|
+
metadata: { token: 'Bearer xyz' },
|
|
289
|
+
}),
|
|
290
|
+
);
|
|
291
|
+
expect(clean.author).toEqual({ id: 'element-053-i-yodo', name: 'Yodo', symbol: 'I' });
|
|
292
|
+
expect('metadata' in clean).toBe(false);
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
it('omits author when the message has none', () => {
|
|
296
|
+
expect('author' in sanitizeConversationMessage(msg('user', 'hola'))).toBe(false);
|
|
297
|
+
});
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
describe('pin/archive transformers + organize (CONV-ORGANIZE-1)', () => {
|
|
301
|
+
const LATER2 = '2026-07-13T00:00:00.000Z';
|
|
302
|
+
const base = () =>
|
|
303
|
+
createConversationRecord({ id: 'p1', messages: [msg('user', 'hola')], now: NOW });
|
|
304
|
+
|
|
305
|
+
it('pin stamps pinnedAt without touching updatedAt; unpin drops the field', () => {
|
|
306
|
+
const pinned = setConversationPinned(base(), true, LATER2);
|
|
307
|
+
expect(pinned.pinnedAt).toBe(LATER2);
|
|
308
|
+
expect(pinned.updatedAt).toBe(NOW);
|
|
309
|
+
const unpinned = setConversationPinned(pinned, false, LATER2);
|
|
310
|
+
expect('pinnedAt' in unpinned).toBe(false);
|
|
311
|
+
expect(unpinned.updatedAt).toBe(NOW);
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
it('archive stamps archivedAt and clears the pin; unarchive drops the field', () => {
|
|
315
|
+
const pinned = setConversationPinned(base(), true, LATER2);
|
|
316
|
+
const archived = setConversationArchived(pinned, true, LATER2);
|
|
317
|
+
expect(archived.archivedAt).toBe(LATER2);
|
|
318
|
+
expect('pinnedAt' in archived).toBe(false);
|
|
319
|
+
const restored = setConversationArchived(archived, false, LATER2);
|
|
320
|
+
expect('archivedAt' in restored).toBe(false);
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
it('pinning an archived record lifts it out of the archive', () => {
|
|
324
|
+
const archived = setConversationArchived(base(), true, LATER2);
|
|
325
|
+
const pinned = setConversationPinned(archived, true, LATER2);
|
|
326
|
+
expect('archivedAt' in pinned).toBe(false);
|
|
327
|
+
expect(pinned.pinnedAt).toBe(LATER2);
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
it('summarizeConversation carries the flags only when present', () => {
|
|
331
|
+
const plain = summarizeConversation(base());
|
|
332
|
+
expect('pinnedAt' in plain).toBe(false);
|
|
333
|
+
expect('archivedAt' in plain).toBe(false);
|
|
334
|
+
const pinned = summarizeConversation(setConversationPinned(base(), true, LATER2));
|
|
335
|
+
expect(pinned.pinnedAt).toBe(LATER2);
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
it('organizes into pinned (last-pinned first) / active (recent first) / archived', () => {
|
|
339
|
+
const sum = (
|
|
340
|
+
id: string,
|
|
341
|
+
updatedAt: string,
|
|
342
|
+
extra: { pinnedAt?: string; archivedAt?: string } = {},
|
|
343
|
+
) => ({ id, title: id, createdAt: NOW, updatedAt, preview: '', ...extra });
|
|
344
|
+
const { pinned, active, archived } = organizeConversationSummaries([
|
|
345
|
+
sum('active-old', '2026-07-01T00:00:00.000Z'),
|
|
346
|
+
sum('pin-early', '2026-07-05T00:00:00.000Z', { pinnedAt: '2026-07-10T00:00:00.000Z' }),
|
|
347
|
+
sum('archived-1', '2026-07-09T00:00:00.000Z', { archivedAt: '2026-07-11T00:00:00.000Z' }),
|
|
348
|
+
sum('pin-late', '2026-07-02T00:00:00.000Z', { pinnedAt: '2026-07-12T00:00:00.000Z' }),
|
|
349
|
+
sum('active-new', '2026-07-08T00:00:00.000Z'),
|
|
350
|
+
sum('archived-2', '2026-07-03T00:00:00.000Z', { archivedAt: '2026-07-12T12:00:00.000Z' }),
|
|
351
|
+
]);
|
|
352
|
+
expect(pinned.map((s) => s.id)).toEqual(['pin-late', 'pin-early']);
|
|
353
|
+
expect(active.map((s) => s.id)).toEqual(['active-new', 'active-old']);
|
|
354
|
+
expect(archived.map((s) => s.id)).toEqual(['archived-2', 'archived-1']);
|
|
355
|
+
});
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
describe('filterConversationSummaries (CONV-SEARCH-1)', () => {
|
|
359
|
+
const sum = (id: string, title: string, preview = '') => ({
|
|
360
|
+
id, title, createdAt: NOW, updatedAt: NOW, preview,
|
|
361
|
+
});
|
|
362
|
+
const list = [
|
|
363
|
+
sum('a', 'Sistemas distribuidos', 'la red no es confiable'),
|
|
364
|
+
sum('b', 'Métodos de natación', 'entrenados en 25 metros'),
|
|
365
|
+
sum('c', 'Plan de comidas', 'menú semanal vegano'),
|
|
366
|
+
];
|
|
367
|
+
|
|
368
|
+
it('matches case- and diacritic-insensitively over title and preview', () => {
|
|
369
|
+
expect(filterConversationSummaries(list, 'metodos').map((s) => s.id)).toEqual(['b']);
|
|
370
|
+
expect(filterConversationSummaries(list, 'MENÚ').map((s) => s.id)).toEqual(['c']);
|
|
371
|
+
expect(filterConversationSummaries(list, 'confiable').map((s) => s.id)).toEqual(['a']);
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
it('requires every term to match (AND semantics)', () => {
|
|
375
|
+
expect(filterConversationSummaries(list, 'natacion metros').map((s) => s.id)).toEqual(['b']);
|
|
376
|
+
expect(filterConversationSummaries(list, 'natacion vegano')).toEqual([]);
|
|
377
|
+
});
|
|
378
|
+
|
|
379
|
+
it('returns the input untouched for an empty or whitespace query', () => {
|
|
380
|
+
expect(filterConversationSummaries(list, '')).toBe(list);
|
|
381
|
+
expect(filterConversationSummaries(list, ' ')).toBe(list);
|
|
382
|
+
});
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
describe('metadata patches (CONV-CONCURRENCY-1)', () => {
|
|
386
|
+
const base = createConversationRecord({
|
|
387
|
+
id: 'c1',
|
|
388
|
+
now: '2026-01-01T00:00:00.000Z',
|
|
389
|
+
messages: [{ role: 'user', content: 'hola' }] as ChatMessage[],
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
it('an omitted key leaves the field alone; null clears it', () => {
|
|
393
|
+
const pinned = applyConversationMetadataPatch(base, {
|
|
394
|
+
pinnedAt: '2026-02-01T00:00:00.000Z',
|
|
395
|
+
});
|
|
396
|
+
// A patch that says nothing about the pin must not touch it — this is the
|
|
397
|
+
// distinction a whole-record put cannot make.
|
|
398
|
+
const renamed = applyConversationMetadataPatch(pinned, { title: 'Otro' });
|
|
399
|
+
expect(renamed.pinnedAt).toBe('2026-02-01T00:00:00.000Z');
|
|
400
|
+
expect(renamed.title).toBe('Otro');
|
|
401
|
+
|
|
402
|
+
const unpinned = applyConversationMetadataPatch(pinned, { pinnedAt: null });
|
|
403
|
+
expect('pinnedAt' in unpinned).toBe(false);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
it('pinning clears the archive and does NOT stamp updatedAt', () => {
|
|
407
|
+
const patch = conversationPinPatch(true, '2026-03-01T00:00:00.000Z');
|
|
408
|
+
expect(patch).toEqual({
|
|
409
|
+
pinnedAt: '2026-03-01T00:00:00.000Z',
|
|
410
|
+
archivedAt: null,
|
|
411
|
+
});
|
|
412
|
+
// Organization must not fake content recency in the active list.
|
|
413
|
+
expect(patch.updatedAt).toBeUndefined();
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
it('archiving clears the pin and does NOT stamp updatedAt', () => {
|
|
417
|
+
const patch = conversationArchivePatch(true, '2026-03-01T00:00:00.000Z');
|
|
418
|
+
expect(patch).toEqual({
|
|
419
|
+
archivedAt: '2026-03-01T00:00:00.000Z',
|
|
420
|
+
pinnedAt: null,
|
|
421
|
+
});
|
|
422
|
+
expect(patch.updatedAt).toBeUndefined();
|
|
423
|
+
});
|
|
424
|
+
|
|
425
|
+
it('unpin/unarchive name only their own field', () => {
|
|
426
|
+
expect(conversationPinPatch(false)).toEqual({ pinnedAt: null });
|
|
427
|
+
expect(conversationArchivePatch(false)).toEqual({ archivedAt: null });
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
it('a rename patch marks the title custom and stamps updatedAt', () => {
|
|
431
|
+
const patch = conversationRenamePatch(base, ' Mi chat ', '2026-04-01T00:00:00.000Z');
|
|
432
|
+
expect(patch).toEqual({
|
|
433
|
+
title: 'Mi chat',
|
|
434
|
+
titleCustom: true,
|
|
435
|
+
updatedAt: '2026-04-01T00:00:00.000Z',
|
|
436
|
+
});
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
it('an empty rename reverts to the derived title and clears the flag', () => {
|
|
440
|
+
const patch = conversationRenamePatch(base, ' ', '2026-04-01T00:00:00.000Z');
|
|
441
|
+
expect(patch.titleCustom).toBe(false);
|
|
442
|
+
expect(patch.title).toBe(deriveConversationTitle(base.messages));
|
|
443
|
+
});
|
|
444
|
+
|
|
445
|
+
it('the patch form and the whole-record form agree exactly', () => {
|
|
446
|
+
// The transformers are thin compositions; if they ever drift, the local
|
|
447
|
+
// (apply-then-put) and remote (send-the-delta) paths stop matching.
|
|
448
|
+
const now = '2026-05-01T00:00:00.000Z';
|
|
449
|
+
for (const [whole, patch] of [
|
|
450
|
+
[setConversationPinned(base, true, now), conversationPinPatch(true, now)],
|
|
451
|
+
[setConversationPinned(base, false, now), conversationPinPatch(false, now)],
|
|
452
|
+
[setConversationArchived(base, true, now), conversationArchivePatch(true, now)],
|
|
453
|
+
[renameConversationRecord(base, 'X', now), conversationRenamePatch(base, 'X', now)],
|
|
454
|
+
[renameConversationRecord(base, '', now), conversationRenamePatch(base, '', now)],
|
|
455
|
+
] as const) {
|
|
456
|
+
expect(applyConversationMetadataPatch(base, patch)).toEqual(whole);
|
|
457
|
+
}
|
|
458
|
+
});
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
describe('sanitizeConversationMessage — reactions survive the reload', () => {
|
|
462
|
+
it('keeps the speaker\'s reactions as plain strings', () => {
|
|
463
|
+
const clean = sanitizeConversationMessage({
|
|
464
|
+
role: 'assistant',
|
|
465
|
+
content: '',
|
|
466
|
+
timestamp: '2026-09-28T00:00:00.000Z',
|
|
467
|
+
reactions: ['👀', '🔥'],
|
|
468
|
+
metadata: { token: 'Bearer xyz' },
|
|
469
|
+
});
|
|
470
|
+
expect(clean.reactions).toEqual(['👀', '🔥']);
|
|
471
|
+
expect('metadata' in clean).toBe(false);
|
|
472
|
+
});
|
|
473
|
+
|
|
474
|
+
it('omits the field when there were none', () => {
|
|
475
|
+
const clean = sanitizeConversationMessage({
|
|
476
|
+
role: 'assistant',
|
|
477
|
+
content: 'hola',
|
|
478
|
+
timestamp: '2026-09-28T00:00:00.000Z',
|
|
479
|
+
reactions: [],
|
|
480
|
+
});
|
|
481
|
+
expect('reactions' in clean).toBe(false);
|
|
482
|
+
});
|
|
483
|
+
});
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* reproducible; they fall back to the wall clock only when it is omitted.
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
+
import { COPY } from '../copy.generated';
|
|
16
17
|
import type { ChatMessage } from '../chat/message';
|
|
17
18
|
import type { ConversationRecord, ConversationSummary } from './record';
|
|
18
19
|
|
|
@@ -20,7 +21,7 @@ import type { ConversationRecord, ConversationSummary } from './record';
|
|
|
20
21
|
export const CONVERSATION_SCHEMA_VERSION = 1;
|
|
21
22
|
|
|
22
23
|
/** Fallback title when there is no usable user message yet. */
|
|
23
|
-
const DEFAULT_TITLE =
|
|
24
|
+
const DEFAULT_TITLE = COPY.conversationDefaultTitle;
|
|
24
25
|
const TITLE_MAX = 60;
|
|
25
26
|
const PREVIEW_MAX = 120;
|
|
26
27
|
|
|
@@ -32,14 +33,41 @@ function truncate(text: string, max: number): string {
|
|
|
32
33
|
}
|
|
33
34
|
|
|
34
35
|
/**
|
|
35
|
-
* Reduce a ChatMessage to the
|
|
36
|
-
* timestamp
|
|
36
|
+
* Reduce a ChatMessage to the fields safe to persist: role, author, content,
|
|
37
|
+
* timestamp, plus the glass-box `trace` when present (B3-FIGLASS-TRACE-
|
|
38
|
+
* PERSISTENCE-1).
|
|
39
|
+
*
|
|
40
|
+
* Privacy by structure: `metadata` is DROPPED on purpose — apps stuff secrets
|
|
41
|
+
* there (a `Bearer` token, tool payloads), so it must never reach durable
|
|
42
|
+
* storage. `trace` and `author` are the deliberate exceptions, not holes in that
|
|
43
|
+
* boundary: both carry only non-sensitive, already-user-visible provenance —
|
|
44
|
+
* plan-step labels/summaries (model-authored, rendered live), tool NAMES (core's
|
|
45
|
+
* ToolCall is {id,name,server,isError} — no arguments/payloads), source URLs,
|
|
46
|
+
* and the public name of the persona that spoke. Persisting what the live turn
|
|
47
|
+
* already showed leaks nothing new — and dropping the author would re-anonymize
|
|
48
|
+
* every bubble on reload, which is the bug the contract exists to prevent.
|
|
49
|
+
* Included only when present, so a plain message stays minimal; id, thinking and
|
|
50
|
+
* metadata are still dropped by construction.
|
|
37
51
|
*/
|
|
38
52
|
export function sanitizeConversationMessage(message: ChatMessage): ChatMessage {
|
|
39
53
|
return {
|
|
40
54
|
role: message.role,
|
|
41
55
|
content: message.content,
|
|
42
56
|
timestamp: message.timestamp,
|
|
57
|
+
...(message.author ? { author: message.author } : {}),
|
|
58
|
+
...(message.trace ? { trace: message.trace } : {}),
|
|
59
|
+
// Attached images are user-visible message CONTENT (OG118-IMAGE-UPLOAD-1),
|
|
60
|
+
// not metadata — dropping them would blank the picture on reload the way
|
|
61
|
+
// dropping `author` used to anonymize bubbles. Producers downscale before
|
|
62
|
+
// encoding, so the persisted base64 stays within the record size caps.
|
|
63
|
+
...(message.images && message.images.length > 0
|
|
64
|
+
? { images: message.images.map((i) => ({ mediaType: i.mediaType, data: i.data })) }
|
|
65
|
+
: {}),
|
|
66
|
+
// The speaker's reactions are user-visible too (chips under the bubble);
|
|
67
|
+
// dropping them would strip the gesture on reload. Plain strings, no payload.
|
|
68
|
+
...(message.reactions && message.reactions.length > 0
|
|
69
|
+
? { reactions: message.reactions.map(String) }
|
|
70
|
+
: {}),
|
|
43
71
|
};
|
|
44
72
|
}
|
|
45
73
|
|
|
@@ -95,6 +123,161 @@ export function createConversationRecord(
|
|
|
95
123
|
};
|
|
96
124
|
}
|
|
97
125
|
|
|
126
|
+
/**
|
|
127
|
+
* Resolve the title to stamp when persisting messages: a user-set (custom)
|
|
128
|
+
* title is preserved; otherwise it is derived from the messages. This is the
|
|
129
|
+
* SSOT that keeps `persist` from clobbering a rename on the next message.
|
|
130
|
+
*/
|
|
131
|
+
export function resolveConversationTitle(
|
|
132
|
+
messages: ChatMessage[],
|
|
133
|
+
prev?: { title: string; titleCustom?: boolean },
|
|
134
|
+
): string {
|
|
135
|
+
if (prev?.titleCustom && prev.title.trim() !== '') return prev.title;
|
|
136
|
+
return deriveConversationTitle(messages);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The metadata delta of an organization mutation (rename / pin / archive).
|
|
141
|
+
*
|
|
142
|
+
* These three mutations used to exist only as whole-record transforms, which
|
|
143
|
+
* forced every transport to ship the whole record — and a whole-record write
|
|
144
|
+
* from a device holding a stale copy silently drops the flags it never meant to
|
|
145
|
+
* touch (CONV-CONCURRENCY-1). The delta expresses the same semantics as the
|
|
146
|
+
* SMALLEST thing that changed, so a transport can send just that.
|
|
147
|
+
*
|
|
148
|
+
* `null` means CLEAR the field; an omitted key means LEAVE IT ALONE. That is
|
|
149
|
+
* precisely the distinction a full-record put cannot express — an absent field
|
|
150
|
+
* and a deliberately-cleared one look identical on the wire.
|
|
151
|
+
*/
|
|
152
|
+
export interface ConversationMetadataPatch {
|
|
153
|
+
title?: string;
|
|
154
|
+
titleCustom?: boolean;
|
|
155
|
+
/** ISO timestamp to pin at, or `null` to unpin. */
|
|
156
|
+
pinnedAt?: string | null;
|
|
157
|
+
/** ISO timestamp to archive at, or `null` to unarchive. */
|
|
158
|
+
archivedAt?: string | null;
|
|
159
|
+
/** Only a rename stamps this: pinning/archiving must not fake recency. */
|
|
160
|
+
updatedAt?: string;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Apply a metadata delta to a record. `null` clears the field, an omitted key
|
|
165
|
+
* leaves it untouched. Pure — the single place the merge rule is written, so the
|
|
166
|
+
* local (apply-then-put) and remote (send-the-delta) paths cannot drift.
|
|
167
|
+
*/
|
|
168
|
+
export function applyConversationMetadataPatch(
|
|
169
|
+
record: ConversationRecord,
|
|
170
|
+
patch: ConversationMetadataPatch,
|
|
171
|
+
): ConversationRecord {
|
|
172
|
+
const next: ConversationRecord = { ...record };
|
|
173
|
+
if (patch.title !== undefined) next.title = patch.title;
|
|
174
|
+
if (patch.titleCustom !== undefined) next.titleCustom = patch.titleCustom;
|
|
175
|
+
if (patch.updatedAt !== undefined) next.updatedAt = patch.updatedAt;
|
|
176
|
+
if (patch.pinnedAt !== undefined) {
|
|
177
|
+
if (patch.pinnedAt === null) delete next.pinnedAt;
|
|
178
|
+
else next.pinnedAt = patch.pinnedAt;
|
|
179
|
+
}
|
|
180
|
+
if (patch.archivedAt !== undefined) {
|
|
181
|
+
if (patch.archivedAt === null) delete next.archivedAt;
|
|
182
|
+
else next.archivedAt = patch.archivedAt;
|
|
183
|
+
}
|
|
184
|
+
return next;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* The delta of a user rename. A non-empty title is stored verbatim (trimmed,
|
|
189
|
+
* whitespace-collapsed, capped at TITLE_MAX) and marks the record `titleCustom`
|
|
190
|
+
* so future persists never re-derive it. An empty/whitespace title reverts to
|
|
191
|
+
* the derived title and clears the custom flag (emptyTitlePolicy:
|
|
192
|
+
* revert-to-derived). Needs the record because reverting has to re-derive from
|
|
193
|
+
* its messages.
|
|
194
|
+
*/
|
|
195
|
+
export function conversationRenamePatch(
|
|
196
|
+
record: ConversationRecord,
|
|
197
|
+
rawTitle: string,
|
|
198
|
+
now?: string,
|
|
199
|
+
): ConversationMetadataPatch {
|
|
200
|
+
const trimmed = rawTitle.trim().replace(/\s+/g, ' ');
|
|
201
|
+
const ts = now ?? new Date().toISOString();
|
|
202
|
+
if (trimmed === '') {
|
|
203
|
+
return {
|
|
204
|
+
title: deriveConversationTitle(record.messages),
|
|
205
|
+
titleCustom: false,
|
|
206
|
+
updatedAt: ts,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
return { title: trimmed.slice(0, TITLE_MAX), titleCustom: true, updatedAt: ts };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* The delta of a pin/unpin. Pinning lifts the record out of the archive — a pin
|
|
214
|
+
* is an explicit "keep this in front of me", incompatible with archived.
|
|
215
|
+
* `updatedAt` is deliberately absent: pinning is organization, not content, and
|
|
216
|
+
* must not fake recency in the active list.
|
|
217
|
+
*/
|
|
218
|
+
export function conversationPinPatch(
|
|
219
|
+
pinned: boolean,
|
|
220
|
+
now?: string,
|
|
221
|
+
): ConversationMetadataPatch {
|
|
222
|
+
if (pinned) {
|
|
223
|
+
return { pinnedAt: now ?? new Date().toISOString(), archivedAt: null };
|
|
224
|
+
}
|
|
225
|
+
return { pinnedAt: null };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The delta of an archive/unarchive. Archiving clears any pin (an archived
|
|
230
|
+
* conversation cannot stay in the pinned section). Unarchiving rejoins the
|
|
231
|
+
* active list at the record's own `updatedAt`, which — like pinning — is not
|
|
232
|
+
* touched.
|
|
233
|
+
*/
|
|
234
|
+
export function conversationArchivePatch(
|
|
235
|
+
archived: boolean,
|
|
236
|
+
now?: string,
|
|
237
|
+
): ConversationMetadataPatch {
|
|
238
|
+
if (archived) {
|
|
239
|
+
return { archivedAt: now ?? new Date().toISOString(), pinnedAt: null };
|
|
240
|
+
}
|
|
241
|
+
return { archivedAt: null };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Apply a user rename to a record. Thin composition of the delta and the merge
|
|
246
|
+
* rule above — kept so callers holding a whole record (the local, single-writer
|
|
247
|
+
* path) do not each re-implement it.
|
|
248
|
+
*/
|
|
249
|
+
export function renameConversationRecord(
|
|
250
|
+
record: ConversationRecord,
|
|
251
|
+
rawTitle: string,
|
|
252
|
+
now?: string,
|
|
253
|
+
): ConversationRecord {
|
|
254
|
+
return applyConversationMetadataPatch(
|
|
255
|
+
record,
|
|
256
|
+
conversationRenamePatch(record, rawTitle, now),
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Pin or unpin a record (whole-record form of `conversationPinPatch`). */
|
|
261
|
+
export function setConversationPinned(
|
|
262
|
+
record: ConversationRecord,
|
|
263
|
+
pinned: boolean,
|
|
264
|
+
now?: string,
|
|
265
|
+
): ConversationRecord {
|
|
266
|
+
return applyConversationMetadataPatch(record, conversationPinPatch(pinned, now));
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** Archive or unarchive a record (whole-record form of `conversationArchivePatch`). */
|
|
270
|
+
export function setConversationArchived(
|
|
271
|
+
record: ConversationRecord,
|
|
272
|
+
archived: boolean,
|
|
273
|
+
now?: string,
|
|
274
|
+
): ConversationRecord {
|
|
275
|
+
return applyConversationMetadataPatch(
|
|
276
|
+
record,
|
|
277
|
+
conversationArchivePatch(archived, now),
|
|
278
|
+
);
|
|
279
|
+
}
|
|
280
|
+
|
|
98
281
|
/** Project a record to its light summary — excludes `messages`. */
|
|
99
282
|
export function summarizeConversation(
|
|
100
283
|
record: ConversationRecord,
|
|
@@ -105,5 +288,67 @@ export function summarizeConversation(
|
|
|
105
288
|
createdAt: record.createdAt,
|
|
106
289
|
updatedAt: record.updatedAt,
|
|
107
290
|
preview: record.preview,
|
|
291
|
+
...(record.pinnedAt ? { pinnedAt: record.pinnedAt } : {}),
|
|
292
|
+
...(record.archivedAt ? { archivedAt: record.archivedAt } : {}),
|
|
293
|
+
...(record.projectId ? { projectId: record.projectId } : {}),
|
|
108
294
|
};
|
|
109
295
|
}
|
|
296
|
+
|
|
297
|
+
/** Lowercase + strip diacritics, so "métodos" matches "metodos" (es-MX). */
|
|
298
|
+
function normalizeForSearch(text: string): string {
|
|
299
|
+
return text
|
|
300
|
+
.toLowerCase()
|
|
301
|
+
.normalize('NFD')
|
|
302
|
+
.replace(/[\u0300-\u036f]/g, '');
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Filter summaries by a free-text query over title + preview (CONV-SEARCH-1).
|
|
307
|
+
* Case- and diacritic-insensitive; every whitespace-separated term must match
|
|
308
|
+
* somewhere (AND semantics). An empty/whitespace query returns the input
|
|
309
|
+
* untouched. Pure — feed the result to {@link organizeConversationSummaries}.
|
|
310
|
+
*/
|
|
311
|
+
export function filterConversationSummaries(
|
|
312
|
+
summaries: ConversationSummary[],
|
|
313
|
+
query: string,
|
|
314
|
+
): ConversationSummary[] {
|
|
315
|
+
const terms = normalizeForSearch(query).split(/\s+/).filter(Boolean);
|
|
316
|
+
if (terms.length === 0) return summaries;
|
|
317
|
+
return summaries.filter((s) => {
|
|
318
|
+
const haystack = normalizeForSearch(`${s.title} ${s.preview}`);
|
|
319
|
+
return terms.every((t) => haystack.includes(t));
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** The sidebar's three sections, each already in display order. */
|
|
324
|
+
export interface OrganizedConversations {
|
|
325
|
+
/** Pinned, last-pinned first. */
|
|
326
|
+
pinned: ConversationSummary[];
|
|
327
|
+
/** Neither pinned nor archived, most recently updated first. */
|
|
328
|
+
active: ConversationSummary[];
|
|
329
|
+
/** Archived, most recently archived first. */
|
|
330
|
+
archived: ConversationSummary[];
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* Split summaries into the pinned / active / archived sections every sidebar
|
|
335
|
+
* renders. Pure and total: a summary lands in exactly one section (`archivedAt`
|
|
336
|
+
* wins over a stray `pinnedAt`, though the pin/archive transformers never
|
|
337
|
+
* produce that state). ISO 8601 timestamps sort lexicographically.
|
|
338
|
+
*/
|
|
339
|
+
export function organizeConversationSummaries(
|
|
340
|
+
summaries: ConversationSummary[],
|
|
341
|
+
): OrganizedConversations {
|
|
342
|
+
const pinned: ConversationSummary[] = [];
|
|
343
|
+
const active: ConversationSummary[] = [];
|
|
344
|
+
const archived: ConversationSummary[] = [];
|
|
345
|
+
for (const s of summaries) {
|
|
346
|
+
if (s.archivedAt) archived.push(s);
|
|
347
|
+
else if (s.pinnedAt) pinned.push(s);
|
|
348
|
+
else active.push(s);
|
|
349
|
+
}
|
|
350
|
+
pinned.sort((a, b) => (b.pinnedAt ?? '').localeCompare(a.pinnedAt ?? ''));
|
|
351
|
+
active.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
352
|
+
archived.sort((a, b) => (b.archivedAt ?? '').localeCompare(a.archivedAt ?? ''));
|
|
353
|
+
return { pinned, active, archived };
|
|
354
|
+
}
|
|
@@ -10,12 +10,29 @@
|
|
|
10
10
|
|
|
11
11
|
export type { ConversationRecord, ConversationSummary } from './record';
|
|
12
12
|
export type { ConversationLibrary } from './library';
|
|
13
|
+
export {
|
|
14
|
+
conversationToMarkdown,
|
|
15
|
+
conversationFileName,
|
|
16
|
+
type ConversationMarkdownOptions,
|
|
17
|
+
} from './markdown';
|
|
13
18
|
export {
|
|
14
19
|
CONVERSATION_SCHEMA_VERSION,
|
|
15
20
|
createConversationRecord,
|
|
16
21
|
summarizeConversation,
|
|
22
|
+
organizeConversationSummaries,
|
|
23
|
+
filterConversationSummaries,
|
|
17
24
|
deriveConversationTitle,
|
|
18
25
|
deriveConversationPreview,
|
|
26
|
+
resolveConversationTitle,
|
|
27
|
+
renameConversationRecord,
|
|
28
|
+
setConversationPinned,
|
|
29
|
+
setConversationArchived,
|
|
30
|
+
applyConversationMetadataPatch,
|
|
31
|
+
conversationRenamePatch,
|
|
32
|
+
conversationPinPatch,
|
|
33
|
+
conversationArchivePatch,
|
|
34
|
+
type ConversationMetadataPatch,
|
|
19
35
|
sanitizeConversationMessage,
|
|
20
36
|
type CreateConversationRecordArgs,
|
|
37
|
+
type OrganizedConversations,
|
|
21
38
|
} from './helpers';
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* consumer app (DD-002-LESSON / framework-first-canary).
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
+
import type { ConversationMetadataPatch } from './helpers';
|
|
12
13
|
import type { ConversationRecord, ConversationSummary } from './record';
|
|
13
14
|
|
|
14
15
|
export interface ConversationLibrary {
|
|
@@ -18,6 +19,17 @@ export interface ConversationLibrary {
|
|
|
18
19
|
get(id: string): Promise<ConversationRecord | null>;
|
|
19
20
|
/** Insert or replace a record by its `id`. */
|
|
20
21
|
put(record: ConversationRecord): Promise<void>;
|
|
22
|
+
/**
|
|
23
|
+
* Apply a metadata-only delta (rename / pin / archive) to `id`.
|
|
24
|
+
*
|
|
25
|
+
* OPTIONAL, and duck-typed by callers, because it only earns its keep where
|
|
26
|
+
* more than one writer exists. A single-browser adapter (IndexedDB) has no
|
|
27
|
+
* second writer to race, so `get → transform → put` is already correct there
|
|
28
|
+
* and an extra verb would be ceremony. A shared backend does have one, and
|
|
29
|
+
* there a whole-record put from a stale device silently drops flags it never
|
|
30
|
+
* meant to touch — the delta is what makes that impossible.
|
|
31
|
+
*/
|
|
32
|
+
patch?(id: string, patch: ConversationMetadataPatch): Promise<ConversationRecord | null>;
|
|
21
33
|
/** Remove the record for `id` (no-op if absent). */
|
|
22
34
|
delete(id: string): Promise<void>;
|
|
23
35
|
/** Remove every stored conversation. */
|