@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
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** `HH:mm`, 24 h. */
|
|
2
|
+
export type TimeOfDay = string;
|
|
3
|
+
|
|
4
|
+
/** `YYYY-MM-DD`. */
|
|
5
|
+
export type CalendarDate = string;
|
|
6
|
+
|
|
7
|
+
export interface WeeklySlot {
|
|
8
|
+
/** As JavaScript counts it: 0 is Sunday. */
|
|
9
|
+
day: number;
|
|
10
|
+
start: TimeOfDay;
|
|
11
|
+
end: TimeOfDay;
|
|
12
|
+
label?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Replaces the weekly pattern on one date. Without `fullDayClosed` it carries its own hours. */
|
|
16
|
+
export interface DateOverride {
|
|
17
|
+
date: CalendarDate;
|
|
18
|
+
start?: TimeOfDay;
|
|
19
|
+
end?: TimeOfDay;
|
|
20
|
+
fullDayClosed: boolean;
|
|
21
|
+
reason?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Durations are minutes. */
|
|
25
|
+
export interface SchedulingRules {
|
|
26
|
+
breakStart?: TimeOfDay;
|
|
27
|
+
breakEnd?: TimeOfDay;
|
|
28
|
+
minSlotDuration?: number;
|
|
29
|
+
maxPatientsPerHour?: number;
|
|
30
|
+
bufferBetweenAppointments?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface DoctorAvailability {
|
|
34
|
+
version: number;
|
|
35
|
+
weeklySchedule: WeeklySlot[];
|
|
36
|
+
overrides: DateOverride[];
|
|
37
|
+
rules: SchedulingRules;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type AvailabilityErrorType =
|
|
41
|
+
| 'overlap'
|
|
42
|
+
| 'invalid_time'
|
|
43
|
+
| 'end_before_start'
|
|
44
|
+
| 'duplicate_date';
|
|
45
|
+
|
|
46
|
+
export interface AvailabilityError {
|
|
47
|
+
type: AvailabilityErrorType;
|
|
48
|
+
day?: number;
|
|
49
|
+
date?: CalendarDate;
|
|
50
|
+
/** Position in that day's list, when the error belongs to one slot. */
|
|
51
|
+
slotIndex?: number;
|
|
52
|
+
message: string;
|
|
53
|
+
severity: 'error' | 'warning';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Editing keeps the slots of a day that was switched off, so switching it back restores them. */
|
|
57
|
+
export interface DaySchedule {
|
|
58
|
+
isWorking: boolean;
|
|
59
|
+
slots: WeeklySlot[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type WeekSchedule = Record<number, DaySchedule>;
|
|
63
|
+
|
|
64
|
+
export interface AvailabilityTemplate {
|
|
65
|
+
id: string;
|
|
66
|
+
name: string;
|
|
67
|
+
description: string;
|
|
68
|
+
weeklySchedule: WeeklySlot[];
|
|
69
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { isEndAfterStart, isValidDate, isValidTime, timeToMinutes } from './time';
|
|
2
|
+
import type {
|
|
3
|
+
AvailabilityError,
|
|
4
|
+
DateOverride,
|
|
5
|
+
DoctorAvailability,
|
|
6
|
+
SchedulingRules,
|
|
7
|
+
WeeklySlot,
|
|
8
|
+
} from './types';
|
|
9
|
+
|
|
10
|
+
const MIN_SLOT_DURATION = 5;
|
|
11
|
+
|
|
12
|
+
type Problem = Pick<AvailabilityError, 'type' | 'message'>;
|
|
13
|
+
|
|
14
|
+
function problemInHours(start: string, end: string): Problem | null {
|
|
15
|
+
if (!isValidTime(start)) return { type: 'invalid_time', message: `Hora de inicio inválida: ${start}` };
|
|
16
|
+
if (!isValidTime(end)) return { type: 'invalid_time', message: `Hora de fin inválida: ${end}` };
|
|
17
|
+
if (!isEndAfterStart(start, end)) {
|
|
18
|
+
return {
|
|
19
|
+
type: 'end_before_start',
|
|
20
|
+
message: `La hora de fin (${end}) debe ser posterior a la de inicio (${start})`,
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function problemInOverride(override: DateOverride): Problem | null {
|
|
27
|
+
if (!isValidDate(override.date)) return { type: 'invalid_time', message: `Fecha inválida: ${override.date}` };
|
|
28
|
+
if (override.fullDayClosed) return null;
|
|
29
|
+
if (!override.start || !override.end) {
|
|
30
|
+
return { type: 'invalid_time', message: 'Debe especificar hora de inicio y fin, o marcar como día libre' };
|
|
31
|
+
}
|
|
32
|
+
return problemInHours(override.start, override.end);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function problemsInRules(rules: SchedulingRules): AvailabilityError[] {
|
|
36
|
+
const errors: AvailabilityError[] = [];
|
|
37
|
+
const { breakStart, breakEnd, minSlotDuration, maxPatientsPerHour } = rules;
|
|
38
|
+
|
|
39
|
+
if (breakStart && breakEnd) {
|
|
40
|
+
const problem = problemInHours(breakStart, breakEnd);
|
|
41
|
+
if (problem) errors.push({ ...problem, message: `Descanso: ${problem.message}`, severity: 'error' });
|
|
42
|
+
} else if (breakStart || breakEnd) {
|
|
43
|
+
errors.push({
|
|
44
|
+
type: 'invalid_time',
|
|
45
|
+
message: 'Debe especificar tanto inicio como fin del descanso',
|
|
46
|
+
severity: 'warning',
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
if (minSlotDuration !== undefined && minSlotDuration < MIN_SLOT_DURATION) {
|
|
50
|
+
errors.push({
|
|
51
|
+
type: 'invalid_time',
|
|
52
|
+
message: `La duración mínima debe ser al menos ${MIN_SLOT_DURATION} minutos`,
|
|
53
|
+
severity: 'error',
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
if (maxPatientsPerHour !== undefined && maxPatientsPerHour < 1) {
|
|
57
|
+
errors.push({ type: 'invalid_time', message: 'Debe permitir al menos 1 paciente por hora', severity: 'error' });
|
|
58
|
+
}
|
|
59
|
+
return errors;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function slotsOverlap(a: WeeklySlot, b: WeeklySlot): boolean {
|
|
63
|
+
return (
|
|
64
|
+
a.day === b.day &&
|
|
65
|
+
timeToMinutes(a.start) < timeToMinutes(b.end) &&
|
|
66
|
+
timeToMinutes(b.start) < timeToMinutes(a.end)
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function slotsByDay(slots: WeeklySlot[]): Map<number, WeeklySlot[]> {
|
|
71
|
+
const days = new Map<number, WeeklySlot[]>();
|
|
72
|
+
for (const slot of slots) days.set(slot.day, [...(days.get(slot.day) ?? []), slot]);
|
|
73
|
+
return days;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function problemsInDay(day: number, slots: WeeklySlot[]): AvailabilityError[] {
|
|
77
|
+
const errors: AvailabilityError[] = [];
|
|
78
|
+
slots.forEach((slot, slotIndex) => {
|
|
79
|
+
const problem = problemInHours(slot.start, slot.end);
|
|
80
|
+
if (problem) errors.push({ ...problem, day, slotIndex, severity: 'error' });
|
|
81
|
+
slots.slice(0, slotIndex).forEach((earlier) => {
|
|
82
|
+
if (!slotsOverlap(earlier, slot)) return;
|
|
83
|
+
errors.push({
|
|
84
|
+
type: 'overlap',
|
|
85
|
+
day,
|
|
86
|
+
slotIndex,
|
|
87
|
+
message: `Solapamiento detectado: ${earlier.start}-${earlier.end} y ${slot.start}-${slot.end}`,
|
|
88
|
+
severity: 'error',
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
return errors;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function problemsInOverrides(overrides: DateOverride[]): AvailabilityError[] {
|
|
96
|
+
const errors: AvailabilityError[] = [];
|
|
97
|
+
const seen = new Set<string>();
|
|
98
|
+
for (const override of overrides) {
|
|
99
|
+
const { date } = override;
|
|
100
|
+
const problem = problemInOverride(override);
|
|
101
|
+
if (problem) errors.push({ ...problem, date, severity: 'error' });
|
|
102
|
+
if (seen.has(date)) {
|
|
103
|
+
errors.push({ type: 'duplicate_date', date, message: `Fecha duplicada: ${date}`, severity: 'error' });
|
|
104
|
+
}
|
|
105
|
+
seen.add(date);
|
|
106
|
+
}
|
|
107
|
+
return errors;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function validateAvailability(availability: DoctorAvailability): AvailabilityError[] {
|
|
111
|
+
const weekly = [...slotsByDay(availability.weeklySchedule)].flatMap(([day, slots]) => problemsInDay(day, slots));
|
|
112
|
+
return [...weekly, ...problemsInOverrides(availability.overrides), ...problemsInRules(availability.rules)];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function hasBlockingErrors(errors: AvailabilityError[]): boolean {
|
|
116
|
+
return errors.some((error) => error.severity === 'error');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface ScheduleGap {
|
|
120
|
+
day: number;
|
|
121
|
+
from: string;
|
|
122
|
+
to: string;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function findGaps(slots: WeeklySlot[]): ScheduleGap[] {
|
|
126
|
+
return [...slotsByDay(slots)].flatMap(([day, daySlots]) => {
|
|
127
|
+
const sorted = [...daySlots].sort((a, b) => timeToMinutes(a.start) - timeToMinutes(b.start));
|
|
128
|
+
return sorted.slice(1).flatMap((next, i) => {
|
|
129
|
+
const previous = sorted[i];
|
|
130
|
+
return isEndAfterStart(previous.end, next.start) ? [{ day, from: previous.end, to: next.start }] : [];
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { AVAILABILITY_VERSION, DAYS_OF_WEEK, DEFAULT_WORK_END, DEFAULT_WORK_START } from './defaults';
|
|
2
|
+
import { MINUTES_PER_DAY, minutesToTime, timeToMinutes } from './time';
|
|
3
|
+
import type { DateOverride, DoctorAvailability, SchedulingRules, WeeklySlot, WeekSchedule } from './types';
|
|
4
|
+
|
|
5
|
+
const GAP_BEFORE_NEW_SLOT = 60;
|
|
6
|
+
const NEW_SLOT_LENGTH = 4 * 60;
|
|
7
|
+
const SHORTEST_NEW_SLOT = 30;
|
|
8
|
+
const LAST_MINUTE = MINUTES_PER_DAY - 1;
|
|
9
|
+
|
|
10
|
+
export function groupByDay(weeklySchedule: WeeklySlot[]): WeekSchedule {
|
|
11
|
+
return Object.fromEntries(
|
|
12
|
+
DAYS_OF_WEEK.map(({ value }) => {
|
|
13
|
+
const slots = weeklySchedule
|
|
14
|
+
.filter((slot) => slot.day === value)
|
|
15
|
+
.sort((a, b) => timeToMinutes(a.start) - timeToMinutes(b.start));
|
|
16
|
+
return [value, { isWorking: slots.length > 0, slots }];
|
|
17
|
+
}),
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function availabilityFromWeek(
|
|
22
|
+
week: WeekSchedule,
|
|
23
|
+
overrides: DateOverride[],
|
|
24
|
+
rules: SchedulingRules,
|
|
25
|
+
): DoctorAvailability {
|
|
26
|
+
const weeklySchedule = Object.values(week).flatMap((day) => (day.isWorking ? day.slots : []));
|
|
27
|
+
return { version: AVAILABILITY_VERSION, weeklySchedule, overrides, rules };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** `null` when the day has no room left before midnight. */
|
|
31
|
+
export function suggestNextSlot(day: number, existing: WeeklySlot[]): WeeklySlot | null {
|
|
32
|
+
const last = existing[existing.length - 1];
|
|
33
|
+
if (!last) return { day, start: DEFAULT_WORK_START, end: DEFAULT_WORK_END };
|
|
34
|
+
const start = timeToMinutes(last.end) + GAP_BEFORE_NEW_SLOT;
|
|
35
|
+
const end = Math.min(start + NEW_SLOT_LENGTH, LAST_MINUTE);
|
|
36
|
+
if (!(end - start >= SHORTEST_NEW_SLOT)) return null;
|
|
37
|
+
return { day, start: minutesToTime(start), end: minutesToTime(end) };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function weeklyHours(availability: DoctorAvailability): number {
|
|
41
|
+
const minutes = availability.weeklySchedule.reduce(
|
|
42
|
+
(total, slot) => total + timeToMinutes(slot.end) - timeToMinutes(slot.start),
|
|
43
|
+
0,
|
|
44
|
+
);
|
|
45
|
+
return minutes / 60;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function workingDays(availability: DoctorAvailability): number[] {
|
|
49
|
+
return [...new Set(availability.weeklySchedule.map((slot) => slot.day))].sort();
|
|
50
|
+
}
|
package/src/chat/message.ts
CHANGED
|
@@ -1,3 +1,52 @@
|
|
|
1
|
+
import type { AgentPlan } from '../agent/state';
|
|
2
|
+
import type { MessageAuthor, ToolCall } from '../agent/events';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* MessageTrace — the persisted glass-box snapshot of a finished agentic turn.
|
|
6
|
+
*
|
|
7
|
+
* The differentiator is "see the execution, not just the result": during the
|
|
8
|
+
* stream you watch the plan declared and the steps walked, but a folded message
|
|
9
|
+
* historically kept only the answer text (see {@link foldAssistantTurn}). This
|
|
10
|
+
* carries the agentic provenance — the declared plan with its per-step outcomes,
|
|
11
|
+
* the tool calls, the evidence — INTO the durable transcript, so reloading a
|
|
12
|
+
* conversation re-renders the same glass-box the live turn showed.
|
|
13
|
+
*
|
|
14
|
+
* Reuses the live agent contract types verbatim ({@link AgentPlan},
|
|
15
|
+
* {@link ToolCall}); persistence is just a snapshot of the reduced turn state,
|
|
16
|
+
* not a parallel shape. Every field is optional: a plain conversational turn
|
|
17
|
+
* (no plan, no tools) folds to a message with no `trace`, unchanged.
|
|
18
|
+
*/
|
|
19
|
+
export interface MessageTrace {
|
|
20
|
+
/** The declared plan with per-step status/summary/outcome, if the turn planned. */
|
|
21
|
+
plan?: AgentPlan;
|
|
22
|
+
/** The tool calls made during the turn, if any. */
|
|
23
|
+
tools?: ToolCall[];
|
|
24
|
+
/** Evidence references surfaced during the turn, if any. */
|
|
25
|
+
sources?: string[];
|
|
26
|
+
/**
|
|
27
|
+
* The model that actually produced the answer. Provenance, like the plan and
|
|
28
|
+
* the tools — so it lives HERE, not in `metadata`, which persistence drops by
|
|
29
|
+
* design. A "powered by <model>" chip read from `metadata` shows on the live
|
|
30
|
+
* turn and vanishes on reload; read from the trace it survives.
|
|
31
|
+
*/
|
|
32
|
+
model?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* MessageImage — one image attached to a user message (OG118-IMAGE-UPLOAD-1).
|
|
37
|
+
*
|
|
38
|
+
* Base64 by design: the shells are local-first (IndexedDB / JSON records), so
|
|
39
|
+
* the bytes ride inside the message instead of referencing a blob store nobody
|
|
40
|
+
* runs. Producers (the composer) downscale before encoding, so a persisted
|
|
41
|
+
* image stays small enough for the conversation-record size caps.
|
|
42
|
+
*/
|
|
43
|
+
export interface MessageImage {
|
|
44
|
+
/** MIME type of the encoded bytes, e.g. `image/jpeg`, `image/png`. */
|
|
45
|
+
mediaType: string;
|
|
46
|
+
/** Base64-encoded bytes — no `data:` URL prefix. */
|
|
47
|
+
data: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
1
50
|
/**
|
|
2
51
|
* ChatMessage — the material-agnostic shape of one chat message.
|
|
3
52
|
*
|
|
@@ -8,16 +57,46 @@
|
|
|
8
57
|
export interface ChatMessage {
|
|
9
58
|
/** Stable id (optional for transient/streaming messages). */
|
|
10
59
|
id?: string;
|
|
11
|
-
/**
|
|
60
|
+
/** Which side of the conversation the message sits on. */
|
|
12
61
|
role: 'user' | 'assistant';
|
|
13
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* WHO said it — the named speaker, not merely the side. A shell with a persona
|
|
64
|
+
* switch (og118's elementos) must attribute each bubble to the persona that
|
|
65
|
+
* actually produced it, and that attribution has to survive a reload, so it is
|
|
66
|
+
* a first-class field (preserved by `sanitizeConversationMessage`, unlike
|
|
67
|
+
* `metadata`). Optional only for messages authored outside the agent contract;
|
|
68
|
+
* everything {@link foldAssistantTurn}/{@link makeUserMessage} builds has one.
|
|
69
|
+
*/
|
|
70
|
+
author?: MessageAuthor;
|
|
71
|
+
/** The message text. May be empty on an image-only user message. */
|
|
14
72
|
content: string;
|
|
73
|
+
/**
|
|
74
|
+
* Images attached to this message (user messages only) — rendered in the
|
|
75
|
+
* transcript and sent to the model as vision input. Absent on text-only
|
|
76
|
+
* messages, so the plain case stays byte-identical to before.
|
|
77
|
+
*/
|
|
78
|
+
images?: MessageImage[];
|
|
79
|
+
/**
|
|
80
|
+
* Emoji the speaker REACTED to the turn with (assistant messages only). A
|
|
81
|
+
* reaction is a gesture on the message, not part of its text — Discord puts it
|
|
82
|
+
* under the bubble, never inside it — so it is a field, not a line folded into
|
|
83
|
+
* `content`. Comes from the engine's `OutboundTurn` (server-bot F5) via the
|
|
84
|
+
* `result` event, persists like `images` (a reload must not lose the gesture),
|
|
85
|
+
* and is absent on plain turns so those stay byte-identical.
|
|
86
|
+
*/
|
|
87
|
+
reactions?: string[];
|
|
15
88
|
/** Optional model reasoning rendered before the content. */
|
|
16
89
|
thinking?: string | null;
|
|
17
90
|
/** ISO 8601 timestamp. */
|
|
18
91
|
timestamp: string;
|
|
19
92
|
/** App-specific metadata (tone, voice, model, …). */
|
|
20
93
|
metadata?: Record<string, unknown>;
|
|
94
|
+
/**
|
|
95
|
+
* Persisted glass-box snapshot of the agentic turn that produced this message
|
|
96
|
+
* (assistant messages only). Absent for plain conversational turns and all
|
|
97
|
+
* user messages — see {@link MessageTrace}.
|
|
98
|
+
*/
|
|
99
|
+
trace?: MessageTrace;
|
|
21
100
|
}
|
|
22
101
|
|
|
23
102
|
/** Streaming state surfaced by a ChatHook while a response is in flight. */
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* DO NOT EDIT — generado desde contracts/conversation-record.schema.json
|
|
4
|
+
*
|
|
5
|
+
* El schema es LA FUENTE. Este archivo, el Swift de og118-ios y el modelo del
|
|
6
|
+
* servidor derivan de él; ninguno manda sobre los otros. Correr:
|
|
7
|
+
* pnpm --filter @free-intelligence/core gen:record-types
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* El registro persistido de una conversación. ESTE ARCHIVO ES LA FUENTE: TypeScript, Swift y el modelo del servidor se derivan de aquí, ninguno manda sobre los otros. Escrito a mano a propósito — un contrato que vive como tipos de UN lenguaje obliga a los demás consumers a transcribirlo, y cada transcripción diverge: tipar `author` como string en vez del objeto canónico dejó toda conversación de la web vacía en el iPhone, y no modelar `images` hizo que guardar desde el teléfono las borrara.
|
|
12
|
+
*/
|
|
13
|
+
export interface ConversationRecord {
|
|
14
|
+
/**
|
|
15
|
+
* Id estable. Es también el session_id del hilo en el backend.
|
|
16
|
+
*/
|
|
17
|
+
id: string;
|
|
18
|
+
/**
|
|
19
|
+
* Derivado del primer mensaje del usuario, salvo que titleCustom sea true.
|
|
20
|
+
*/
|
|
21
|
+
title: string;
|
|
22
|
+
/**
|
|
23
|
+
* True cuando el usuario renombró. Un título custom NUNCA se re-deriva al persistir.
|
|
24
|
+
*/
|
|
25
|
+
titleCustom?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* ISO 8601.
|
|
28
|
+
*/
|
|
29
|
+
createdAt: string;
|
|
30
|
+
/**
|
|
31
|
+
* ISO 8601 del último cambio.
|
|
32
|
+
*/
|
|
33
|
+
updatedAt: string;
|
|
34
|
+
messages: PersistedMessage[];
|
|
35
|
+
/**
|
|
36
|
+
* Fragmento del último mensaje no vacío, para el sidebar.
|
|
37
|
+
*/
|
|
38
|
+
preview: string;
|
|
39
|
+
/**
|
|
40
|
+
* ISO 8601. Ausente = no fijado. Timestamp y no booleano para que la sección ordene por último-fijado sin un contador aparte.
|
|
41
|
+
*/
|
|
42
|
+
pinnedAt?: string;
|
|
43
|
+
/**
|
|
44
|
+
* ISO 8601. Ausente = activo.
|
|
45
|
+
*/
|
|
46
|
+
archivedAt?: string;
|
|
47
|
+
/**
|
|
48
|
+
* Versión del registro, para migraciones hacia adelante.
|
|
49
|
+
*/
|
|
50
|
+
schemaVersion: number;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Un mensaje TAL COMO SE GUARDA. No es el ChatMessage vivo: `sanitizeConversationMessage` descarta `metadata`, `id` y `thinking` a propósito, así que este contrato tampoco los declara. Lo que sí sobrevive —autoría, imágenes, trace— sobrevive porque es contenido que el usuario vería desaparecer.
|
|
54
|
+
*/
|
|
55
|
+
export interface PersistedMessage {
|
|
56
|
+
/**
|
|
57
|
+
* De qué lado del hilo está el mensaje.
|
|
58
|
+
*/
|
|
59
|
+
role: 'user' | 'assistant';
|
|
60
|
+
/**
|
|
61
|
+
* El texto. Puede ir vacío en un mensaje que sólo lleva imagen.
|
|
62
|
+
*/
|
|
63
|
+
content: string;
|
|
64
|
+
/**
|
|
65
|
+
* ISO 8601.
|
|
66
|
+
*/
|
|
67
|
+
timestamp?: string;
|
|
68
|
+
author?: MessageAuthor;
|
|
69
|
+
images?: MessageImage[];
|
|
70
|
+
trace?: MessageTrace;
|
|
71
|
+
/**
|
|
72
|
+
* Emoji con los que el hablante REACCIONÓ al turno (mensajes de asistente). Es un gesto sobre el mensaje, no parte de su texto: por eso no va doblado en `content`. Viene del motor (server-bot F5 devuelve el OutboundTurn entero) y sobrevive el reload como sobreviven las imágenes.
|
|
73
|
+
*/
|
|
74
|
+
reactions?: string[];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* QUIÉN habló — el hablante nombrado, no sólo el lado. Una burbuja de asistente sin autor atribuye la respuesta a la app misma, y eso es una mentira que el framework no debe poder expresar. Sólo `id` y `name` son load-bearing.
|
|
78
|
+
*/
|
|
79
|
+
export interface MessageAuthor {
|
|
80
|
+
/**
|
|
81
|
+
* Identificador estable del hablante (id de elemento, de persona, 'user').
|
|
82
|
+
*/
|
|
83
|
+
id: string;
|
|
84
|
+
/**
|
|
85
|
+
* Nombre humano que se pinta ('Yodo', 'og118', 'Tú').
|
|
86
|
+
*/
|
|
87
|
+
name: string;
|
|
88
|
+
/**
|
|
89
|
+
* Enriquecimiento opcional: token de avatar.
|
|
90
|
+
*/
|
|
91
|
+
symbol?: string;
|
|
92
|
+
/**
|
|
93
|
+
* Enriquecimiento opcional: chip de procedencia.
|
|
94
|
+
*/
|
|
95
|
+
engine?: string;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Una imagen adjunta a un mensaje del usuario. Base64 por diseño: los shells son local-first, así que los bytes viajan dentro del mensaje en vez de referenciar un blob store que nadie corre.
|
|
99
|
+
*/
|
|
100
|
+
export interface MessageImage {
|
|
101
|
+
/**
|
|
102
|
+
* MIME de los bytes, p. ej. image/jpeg.
|
|
103
|
+
*/
|
|
104
|
+
mediaType: string;
|
|
105
|
+
/**
|
|
106
|
+
* Bytes en base64 — SIN el prefijo data: URL.
|
|
107
|
+
*/
|
|
108
|
+
data: string;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* La foto glass-box del turno agéntico ya terminado. El diferenciador es 'ver la ejecución, no sólo el resultado': sin esto, recargar una conversación pierde el plan y las herramientas que el turno vivo sí mostró. Todo es opcional — un turno conversacional simple dobla sin trace.
|
|
112
|
+
*/
|
|
113
|
+
export interface MessageTrace {
|
|
114
|
+
plan?: AgentPlan;
|
|
115
|
+
tools?: ToolCall[];
|
|
116
|
+
sources?: string[];
|
|
117
|
+
/**
|
|
118
|
+
* El modelo que DE VERDAD produjo la respuesta. Vive aquí y no en metadata, que la persistencia descarta por diseño.
|
|
119
|
+
*/
|
|
120
|
+
model?: string;
|
|
121
|
+
}
|
|
122
|
+
export interface AgentPlan {
|
|
123
|
+
steps: PlanStep[];
|
|
124
|
+
/**
|
|
125
|
+
* Veredicto terminal del plan completo.
|
|
126
|
+
*/
|
|
127
|
+
outcome?: 'completed' | 'failed' | 'cancelled';
|
|
128
|
+
}
|
|
129
|
+
export interface PlanStep {
|
|
130
|
+
label: string;
|
|
131
|
+
status: 'pending' | 'running' | 'done' | 'failed' | 'cancelled';
|
|
132
|
+
summary?: string;
|
|
133
|
+
error?: string;
|
|
134
|
+
/**
|
|
135
|
+
* Anotación libre de note_step.
|
|
136
|
+
*/
|
|
137
|
+
note?: string;
|
|
138
|
+
}
|
|
139
|
+
export interface ToolCall {
|
|
140
|
+
/**
|
|
141
|
+
* Id estable del proveedor; ausente mientras está pendiente.
|
|
142
|
+
*/
|
|
143
|
+
id?: string;
|
|
144
|
+
/**
|
|
145
|
+
* Identificador de la herramienta como la nombró el agente.
|
|
146
|
+
*/
|
|
147
|
+
name: string;
|
|
148
|
+
/**
|
|
149
|
+
* Servidor/namespace de origen; ausente en las builtin.
|
|
150
|
+
*/
|
|
151
|
+
server?: string;
|
|
152
|
+
/**
|
|
153
|
+
* Ausente = pendiente, false = ok, true = falló.
|
|
154
|
+
*/
|
|
155
|
+
isError?: boolean;
|
|
156
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* contracts/conversation-derivations.vectors.json — title, preview, rename and
|
|
3
|
+
* the sidebar's three sections, as a contract both the web and the iPhone obey.
|
|
4
|
+
* The JSON is the source; a red vector here is core drifting from it.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
8
|
+
import { dirname, resolve } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { describe, expect, it } from 'vitest';
|
|
11
|
+
import type { ChatMessage } from '../chat/message';
|
|
12
|
+
import type { ConversationRecord, ConversationSummary } from './record';
|
|
13
|
+
import {
|
|
14
|
+
conversationRenamePatch,
|
|
15
|
+
deriveConversationPreview,
|
|
16
|
+
deriveConversationTitle,
|
|
17
|
+
organizeConversationSummaries,
|
|
18
|
+
} from './helpers';
|
|
19
|
+
|
|
20
|
+
interface Vector {
|
|
21
|
+
name: string;
|
|
22
|
+
kind: 'title' | 'preview' | 'rename' | 'organize';
|
|
23
|
+
input: Record<string, unknown>;
|
|
24
|
+
expect: unknown;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
28
|
+
const contrato = JSON.parse(
|
|
29
|
+
readFileSync(resolve(here, '../../contracts/conversation-derivations.vectors.json'), 'utf8'),
|
|
30
|
+
) as { version: number; vectors: Vector[] };
|
|
31
|
+
|
|
32
|
+
function correr(v: Vector): unknown {
|
|
33
|
+
switch (v.kind) {
|
|
34
|
+
case 'title':
|
|
35
|
+
return deriveConversationTitle(v.input.messages as ChatMessage[]);
|
|
36
|
+
case 'preview':
|
|
37
|
+
return deriveConversationPreview(v.input.messages as ChatMessage[]);
|
|
38
|
+
case 'rename': {
|
|
39
|
+
const base = v.input.record as Pick<ConversationRecord, 'title' | 'titleCustom' | 'messages'>;
|
|
40
|
+
const record = { ...base, id: 'c', createdAt: '', updatedAt: '', preview: '', schemaVersion: 1 };
|
|
41
|
+
const patch = conversationRenamePatch(record, v.input.newTitle as string, '2026-10-17T00:00:00Z');
|
|
42
|
+
return { title: patch.title, titleCustom: patch.titleCustom === true };
|
|
43
|
+
}
|
|
44
|
+
case 'organize': {
|
|
45
|
+
const o = organizeConversationSummaries(v.input.summaries as ConversationSummary[]);
|
|
46
|
+
return {
|
|
47
|
+
pinned: o.pinned.map((s) => s.id),
|
|
48
|
+
active: o.active.map((s) => s.id),
|
|
49
|
+
archived: o.archived.map((s) => s.id),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
describe('conversation-derivations.vectors.json', () => {
|
|
56
|
+
it('declara su versión y trae vectores', () => {
|
|
57
|
+
expect(contrato.version).toBe(1);
|
|
58
|
+
expect(contrato.vectors.length).toBeGreaterThan(0);
|
|
59
|
+
});
|
|
60
|
+
for (const v of contrato.vectors) {
|
|
61
|
+
it(v.name, () => {
|
|
62
|
+
expect(correr(v)).toEqual(v.expect);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
});
|