@free-intelligence/core 1.3.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.
Files changed (41) hide show
  1. package/README.md +1 -0
  2. package/dist/availability/index.d.ts +132 -0
  3. package/dist/availability/index.js +278 -0
  4. package/dist/availability/index.js.map +1 -0
  5. package/dist/index.d.ts +907 -112
  6. package/dist/index.js +448 -9
  7. package/dist/index.js.map +1 -1
  8. package/package.json +31 -2
  9. package/src/agent/conversation-state-vectors.test.ts +125 -0
  10. package/src/agent/conversation-state.test.ts +320 -0
  11. package/src/agent/conversation-state.ts +278 -0
  12. package/src/agent/events.ts +50 -1
  13. package/src/agent/hook.ts +26 -2
  14. package/src/agent/sse-fixture.test.ts +53 -0
  15. package/src/agent/sse.ts +26 -0
  16. package/src/agent/state.test.ts +60 -0
  17. package/src/agent/state.ts +44 -0
  18. package/src/agent/transcript.test.ts +166 -15
  19. package/src/agent/transcript.ts +92 -13
  20. package/src/agent/turn-vectors.test.ts +75 -0
  21. package/src/agent/wire-map.ts +131 -0
  22. package/src/agent/wire.generated.ts +265 -0
  23. package/src/availability/availability.test.ts +130 -0
  24. package/src/availability/defaults.ts +89 -0
  25. package/src/availability/index.ts +6 -0
  26. package/src/availability/time.ts +38 -0
  27. package/src/availability/types.ts +69 -0
  28. package/src/availability/validation.ts +133 -0
  29. package/src/availability/week.ts +50 -0
  30. package/src/chat/message.ts +81 -2
  31. package/src/chat/record.generated.ts +156 -0
  32. package/src/conversation/derivations-vectors.test.ts +65 -0
  33. package/src/conversation/helpers.test.ts +329 -0
  34. package/src/conversation/helpers.ts +248 -3
  35. package/src/conversation/index.ts +17 -0
  36. package/src/conversation/library.ts +12 -0
  37. package/src/conversation/markdown.test.ts +84 -0
  38. package/src/conversation/markdown.ts +67 -0
  39. package/src/conversation/record.ts +29 -1
  40. package/src/copy.generated.ts +19 -0
  41. package/src/index.ts +55 -3
@@ -0,0 +1,131 @@
1
+ /**
2
+ * fi-runner wire frame → core {@link AgentStreamEvent}, or null to drop it.
3
+ *
4
+ * The wire is `contracts/agent-events.schema.json`; the app-level event is what
5
+ * {@link applyAgentEvent} reduces. This mapping lived in og118's transport hook
6
+ * and every other consumer of the stream (the iPhone, the next shell) had to
7
+ * rewrite it. It is substrate: one mapping, checked against the same vectors
8
+ * the native client replays (`contracts/agent-turn.vectors.json`).
9
+ *
10
+ * @param frame one decoded SSE `data:` payload
11
+ * @returns the core event, or null for a frame this layer has no use for
12
+ */
13
+ import type { AgentStreamEvent } from './events';
14
+
15
+ type Raw = Record<string, unknown>;
16
+
17
+ function rec(v: unknown): Raw {
18
+ return v && typeof v === 'object' ? (v as Raw) : {};
19
+ }
20
+
21
+ function str(v: unknown, fallback = ''): string {
22
+ return v == null ? fallback : String(v);
23
+ }
24
+
25
+ function nullableStr(v: unknown): string | null {
26
+ return typeof v === 'string' && v.trim() ? v : null;
27
+ }
28
+
29
+ export function fromWireEvent(frame: unknown): AgentStreamEvent | null {
30
+ const ev = rec(frame);
31
+ const data = rec(ev.data);
32
+ switch (ev.type) {
33
+ case 'open':
34
+ return { type: 'open' };
35
+ case 'text':
36
+ return { type: 'text', delta: str(ev.text) };
37
+ case 'element': {
38
+ const el = rec(ev.element);
39
+ const id = str(el.id);
40
+ if (!id) return null;
41
+ return {
42
+ type: 'author',
43
+ author: {
44
+ id,
45
+ name: str(el.name) || str(el.label) || id,
46
+ symbol: (el.symbol as string | null) ?? null,
47
+ engine: (el.engine as string | null) ?? null,
48
+ },
49
+ };
50
+ }
51
+ case 'tool_call': {
52
+ const t = rec(ev.tool ?? ev.call);
53
+ return {
54
+ type: 'tool_call',
55
+ call: {
56
+ id: (t.id as string | null) ?? null,
57
+ name: str(t.name),
58
+ server: (t.server as string | null) ?? null,
59
+ isError: (t.is_error as boolean | null) ?? (t.isError as boolean | null) ?? null,
60
+ },
61
+ };
62
+ }
63
+ case 'plan':
64
+ return { type: 'plan', steps: ((data.steps as unknown[]) ?? []).map((s) => str(s)) };
65
+ case 'plan_rejected':
66
+ return {
67
+ type: 'plan_rejected',
68
+ rejection: {
69
+ reason: str(data.reason),
70
+ matched: (data.matched as Array<{ index: number; label: string }>) ?? [],
71
+ guard: (data.guard as string | null) ?? null,
72
+ },
73
+ };
74
+ case 'step_started':
75
+ return { type: 'step_started', index: Number(data.step_index ?? -1) };
76
+ case 'step_done': {
77
+ const raw = str(data.status, 'done');
78
+ const status = raw === 'failed' ? 'failed' : raw === 'cancelled' ? 'cancelled' : 'done';
79
+ return {
80
+ type: 'step_done',
81
+ index: Number(data.step_index ?? -1),
82
+ status,
83
+ summary: data.summary ? str(data.summary) : undefined,
84
+ error: data.error ? str(data.error) : undefined,
85
+ };
86
+ }
87
+ case 'step_noted':
88
+ return { type: 'step_noted', index: Number(data.step_index ?? -1), note: str(data.note) };
89
+ case 'plan_amended':
90
+ return { type: 'plan_amended', action: data.action === 'replan' ? 'replan' : 'insert' };
91
+ case 'plan_cancelled':
92
+ return { type: 'plan_cancelled', reason: data.reason ? str(data.reason) : undefined };
93
+ case 'plan_completed':
94
+ return {
95
+ type: 'plan_completed',
96
+ completedCount: Number(data.completed_count ?? 0),
97
+ failedCount: Number(data.failed_count ?? 0),
98
+ cancelledCount: Number(data.cancelled_count ?? 0),
99
+ };
100
+ case 'plan_failed':
101
+ return {
102
+ type: 'plan_failed',
103
+ completedCount: Number(data.completed_count ?? 0),
104
+ failedCount: Number(data.failed_count ?? 0),
105
+ cancelledCount: Number(data.cancelled_count ?? 0),
106
+ };
107
+ case 'result': {
108
+ const r = rec(ev.result);
109
+ const model = nullableStr(r.model);
110
+ const reactions = Array.isArray(r.reactions)
111
+ ? r.reactions.map((x) => str(x).trim()).filter(Boolean)
112
+ : [];
113
+ return {
114
+ type: 'result',
115
+ text: str(r.text),
116
+ ...(model ? { meta: { model } } : {}),
117
+ ...(reactions.length > 0 ? { reactions } : {}),
118
+ };
119
+ }
120
+ case 'error':
121
+ return { type: 'error', message: str(ev.message, 'error') };
122
+ case 'ping':
123
+ return { type: 'ping' };
124
+ case 'deferred':
125
+ return { type: 'deferred' };
126
+ case 'done':
127
+ return { type: 'done' };
128
+ default:
129
+ return null;
130
+ }
131
+ }
@@ -0,0 +1,265 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * DO NOT EDIT — generated from the fi-runner event contract.
4
+ *
5
+ * Source of truth: apps/packages/fi-runner/fi_runner/events.py
6
+ * Schema: apps/packages/fi-runner/contracts/agent-events.schema.json
7
+ * Regenerate: pnpm --filter @free-intelligence/core gen:events
8
+ *
9
+ * These are the RAW WIRE frames as fi-runner emits them (snake_case, three
10
+ * envelope shapes). They are NOT the core AgentStreamEvent — that one is the
11
+ * normalized, camelCase contract the reducer consumes. The translation between
12
+ * them lives in the consumer's mapEvent, and now it maps FROM a typed wire
13
+ * frame instead of from `Record<string, unknown>` guesswork.
14
+ */
15
+ /**
16
+ * The fi-runner agent stream contract. Generated from fi_runner/events.py — do not edit by hand.
17
+ */
18
+ export type AgentStreamEvent =
19
+ | OpenEvent
20
+ | ElementEvent
21
+ | TextEvent
22
+ | ToolCallEvent
23
+ | ResultEvent
24
+ | PlanEvent
25
+ | StepStartedEvent
26
+ | StepDoneEvent
27
+ | StepNotedEvent
28
+ | PlanAmendedEvent
29
+ | PlanCancelledEvent
30
+ | PlanCompletedEvent
31
+ | PlanFailedEvent
32
+ | PlanRejectedEvent
33
+ | ErrorEvent
34
+ | PingEvent
35
+ | DeferredEvent
36
+ | DoneEvent;
37
+
38
+ /**
39
+ * First frame of every stream. Carries the id a UI keys concurrent turns on.
40
+ */
41
+ export interface OpenEvent {
42
+ type?: 'open';
43
+ request_id?: string | null;
44
+ }
45
+ /**
46
+ * Announces WHO is answering, before any token arrives.
47
+ */
48
+ export interface ElementEvent {
49
+ type?: 'element';
50
+ element: ElementPayload;
51
+ }
52
+ /**
53
+ * Which persona/element answered this turn.
54
+ *
55
+ * ``label`` is the composed one-liner ("53 · I · Yodo"); the parts ride
56
+ * alongside it so a UI can attribute a bubble without re-parsing that string —
57
+ * ``name`` is the speaker's name, ``symbol`` the avatar token, ``engine`` the
58
+ * persona/engine behind it. Optional: a runner that only knows an id/label
59
+ * still emits a valid frame.
60
+ */
61
+ export interface ElementPayload {
62
+ id: string;
63
+ label: string;
64
+ name?: string | null;
65
+ symbol?: string | null;
66
+ engine?: string | null;
67
+ }
68
+ /**
69
+ * A token delta. Consumers append; they never replace.
70
+ */
71
+ export interface TextEvent {
72
+ type?: 'text';
73
+ text: string;
74
+ }
75
+ export interface ToolCallEvent {
76
+ type?: 'tool_call';
77
+ tool: ToolCallPayload;
78
+ }
79
+ /**
80
+ * One tool invocation, mirroring :class:`fi_runner.backend.ToolCall`.
81
+ *
82
+ * ``input`` may carry PHI and is never placed in telemetry; it stays on the
83
+ * wire only because the glass-box panel renders it for the operator.
84
+ */
85
+ export interface ToolCallPayload {
86
+ name: string;
87
+ server?: string | null;
88
+ input?: {
89
+ [k: string]: unknown;
90
+ } | null;
91
+ id?: string | null;
92
+ is_error?: boolean | null;
93
+ duration_ms?: number | null;
94
+ }
95
+ export interface ResultEvent {
96
+ type?: 'result';
97
+ result: TurnResultPayload;
98
+ }
99
+ /**
100
+ * The settled result of a turn, mirroring :class:`fi_runner.backend.TurnResult`.
101
+ *
102
+ * ``model`` is the model that ACTUALLY ran (the retry loop may escalate to the
103
+ * fallback), so a UI shows the answer's real provenance instead of guessing at
104
+ * the configured default.
105
+ *
106
+ * ``reactions`` are the emoji the speaker put ON the turn (an engine with a
107
+ * reaction channel, like a Discord persona). A gesture, not content: a turn
108
+ * with empty ``text`` and reactions is a settled answer, not an empty one.
109
+ */
110
+ export interface TurnResultPayload {
111
+ text: string;
112
+ usage?: {
113
+ [k: string]: unknown;
114
+ } | null;
115
+ session_id?: string | null;
116
+ model?: string | null;
117
+ guard_outcomes?: {
118
+ [k: string]: unknown;
119
+ };
120
+ tool_calls?: ToolCallPayload[];
121
+ reactions?: string[];
122
+ }
123
+ /**
124
+ * The agent declared its plan. ``steps`` is the checklist a UI renders.
125
+ */
126
+ export interface PlanEvent {
127
+ type?: 'plan';
128
+ data: PlanData;
129
+ }
130
+ export interface PlanData {
131
+ steps: string[];
132
+ session_id?: string | null;
133
+ request_id?: string | null;
134
+ }
135
+ export interface StepStartedEvent {
136
+ type?: 'step_started';
137
+ data: StepStartedData;
138
+ }
139
+ export interface StepStartedData {
140
+ plan_id?: string | null;
141
+ step_index: number;
142
+ request_id?: string | null;
143
+ }
144
+ export interface StepDoneEvent {
145
+ type?: 'step_done';
146
+ data: StepDoneData;
147
+ }
148
+ /**
149
+ * ``summary`` accompanies a ``done`` step; ``error`` a failed/cancelled one.
150
+ */
151
+ export interface StepDoneData {
152
+ plan_id?: string | null;
153
+ step_index: number;
154
+ status: 'done' | 'failed' | 'cancelled';
155
+ summary?: string | null;
156
+ error?: string | null;
157
+ request_id?: string | null;
158
+ }
159
+ export interface StepNotedEvent {
160
+ type?: 'step_noted';
161
+ data: StepNotedData;
162
+ }
163
+ export interface StepNotedData {
164
+ plan_id?: string | null;
165
+ step_index: number;
166
+ note: string;
167
+ request_id?: string | null;
168
+ }
169
+ export interface PlanAmendedEvent {
170
+ type?: 'plan_amended';
171
+ data: PlanAmendedData;
172
+ }
173
+ export interface PlanAmendedData {
174
+ plan_id?: string | null;
175
+ action: 'insert' | 'replan';
176
+ request_id?: string | null;
177
+ }
178
+ export interface PlanCancelledEvent {
179
+ type?: 'plan_cancelled';
180
+ data: PlanCancelledData;
181
+ }
182
+ export interface PlanCancelledData {
183
+ plan_id?: string | null;
184
+ reason?: string;
185
+ request_id?: string | null;
186
+ }
187
+ export interface PlanCompletedEvent {
188
+ type?: 'plan_completed';
189
+ data: PlanTerminalData;
190
+ }
191
+ /**
192
+ * Counters for the terminal plan frame.
193
+ *
194
+ * They default to ``0`` rather than being optional on purpose: a consumer must
195
+ * never receive ``undefined`` here and coerce it silently. The emitter fills
196
+ * real counts whenever the observer ran.
197
+ */
198
+ export interface PlanTerminalData {
199
+ plan_id?: string | null;
200
+ completed_count?: number;
201
+ failed_count?: number;
202
+ cancelled_count?: number;
203
+ request_id?: string | null;
204
+ }
205
+ export interface PlanFailedEvent {
206
+ type?: 'plan_failed';
207
+ data: PlanTerminalData;
208
+ }
209
+ export interface PlanRejectedEvent {
210
+ type?: 'plan_rejected';
211
+ data: PlanRejectedData;
212
+ }
213
+ /**
214
+ * A plan guard refused the declared plan before any step ran.
215
+ */
216
+ export interface PlanRejectedData {
217
+ reason: string;
218
+ matched?: GuardMatch[];
219
+ reinforcement?: string | null;
220
+ guard?: string | null;
221
+ request_id?: string | null;
222
+ }
223
+ export interface GuardMatch {
224
+ index: number;
225
+ label: string;
226
+ [k: string]: unknown;
227
+ }
228
+ /**
229
+ * The turn died. Terminal — no ``done`` follows a fatal error.
230
+ */
231
+ export interface ErrorEvent {
232
+ type?: 'error';
233
+ message: string;
234
+ }
235
+ /**
236
+ * A sign of life while the turn is QUIET.
237
+ *
238
+ * A client's idle watchdog cannot tell "the model is thinking" from "the
239
+ * backend hung" — both look like silence. And silence is normal here: a turn
240
+ * proxied to an external engine emits NOTHING until the whole answer lands
241
+ * (up to the proxy's live wait), while a local turn can think far longer
242
+ * than a token gap.
243
+ * Without this frame the client kills healthy turns and throws away what the
244
+ * user wrote. The ping carries nothing; its arrival IS the signal.
245
+ */
246
+ export interface PingEvent {
247
+ type?: 'ping';
248
+ }
249
+ /**
250
+ * The live turn was released before its answer existed (OG118-EXTERNAL-TURN-1).
251
+ *
252
+ * A proxied engine kept working past the stream's live wait. The answer lands
253
+ * in the conversation record out of band, so the stream ends after this frame
254
+ * with no text: the client folds no bubble and shows a waiting notice until
255
+ * the thread refreshes. Carries nothing; its arrival is the signal.
256
+ */
257
+ export interface DeferredEvent {
258
+ type?: 'deferred';
259
+ }
260
+ /**
261
+ * Last frame of a healthy stream.
262
+ */
263
+ export interface DoneEvent {
264
+ type?: 'done';
265
+ }
@@ -0,0 +1,130 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ AVAILABILITY_TEMPLATES,
4
+ availabilityFromWeek,
5
+ emptyAvailability,
6
+ findGaps,
7
+ groupByDay,
8
+ hasBlockingErrors,
9
+ isValidDate,
10
+ suggestNextSlot,
11
+ toCalendarDate,
12
+ validateAvailability,
13
+ weeklyHours,
14
+ workingDays,
15
+ type DoctorAvailability,
16
+ } from './index';
17
+
18
+ const availability = (changes: Partial<DoctorAvailability>): DoctorAvailability => ({
19
+ ...emptyAvailability(),
20
+ ...changes,
21
+ });
22
+ const types = (changes: Partial<DoctorAvailability>) =>
23
+ validateAvailability(availability(changes)).map((error) => error.type);
24
+
25
+ describe('validateAvailability', () => {
26
+ it('accepts every shipped template', () => {
27
+ for (const { weeklySchedule } of AVAILABILITY_TEMPLATES) expect(types({ weeklySchedule })).toEqual([]);
28
+ });
29
+
30
+ it('points an overlap at the later slot of that day', () => {
31
+ const errors = validateAvailability(
32
+ availability({
33
+ weeklySchedule: [
34
+ { day: 1, start: '09:00', end: '12:00' },
35
+ { day: 1, start: '11:59', end: '14:00' },
36
+ ],
37
+ }),
38
+ );
39
+ expect(errors).toMatchObject([{ type: 'overlap', day: 1, slotIndex: 1 }]);
40
+ });
41
+
42
+ it('lets slots touch, and lets different days share hours', () => {
43
+ expect(
44
+ types({
45
+ weeklySchedule: [
46
+ { day: 1, start: '09:00', end: '12:00' },
47
+ { day: 1, start: '12:00', end: '14:00' },
48
+ { day: 2, start: '09:00', end: '12:00' },
49
+ ],
50
+ }),
51
+ ).toEqual([]);
52
+ });
53
+
54
+ it.each([
55
+ ['9:00', '12:00', 'invalid_time'],
56
+ ['09:00', '24:00', 'invalid_time'],
57
+ ['', '12:00', 'invalid_time'],
58
+ ['12:00', '12:00', 'end_before_start'],
59
+ ])('rejects %s-%s as %s', (start, end, type) => {
60
+ expect(types({ weeklySchedule: [{ day: 1, start, end }] })).toEqual([type]);
61
+ });
62
+
63
+ it('requires hours on an open override and a real, unique date', () => {
64
+ expect(types({ overrides: [{ date: '2026-12-24', fullDayClosed: false }] })).toEqual(['invalid_time']);
65
+ expect(types({ overrides: [{ date: '2026-02-31', fullDayClosed: true }] })).toEqual(['invalid_time']);
66
+ expect(
67
+ types({
68
+ overrides: [
69
+ { date: '2026-12-25', fullDayClosed: true },
70
+ { date: '2026-12-25', fullDayClosed: true },
71
+ ],
72
+ }),
73
+ ).toEqual(['duplicate_date']);
74
+ });
75
+
76
+ it('treats half a break as a warning and a reversed break as an error', () => {
77
+ const half = validateAvailability(availability({ rules: { breakStart: '13:00' } }));
78
+ expect(half).toMatchObject([{ severity: 'warning' }]);
79
+ expect(hasBlockingErrors(half)).toBe(false);
80
+ expect(hasBlockingErrors(validateAvailability(availability({ rules: { breakStart: '14:00', breakEnd: '13:00' } })))).toBe(true);
81
+ });
82
+
83
+ it('bounds the numeric rules', () => {
84
+ expect(types({ rules: { minSlotDuration: 4 } })).toEqual(['invalid_time']);
85
+ expect(types({ rules: { maxPatientsPerHour: 0 } })).toEqual(['invalid_time']);
86
+ });
87
+ });
88
+
89
+ describe('the week being edited', () => {
90
+ it('round-trips, sorting each day and dropping the days switched off', () => {
91
+ const week = groupByDay([
92
+ { day: 1, start: '16:00', end: '20:00' },
93
+ { day: 1, start: '09:00', end: '13:00' },
94
+ { day: 2, start: '09:00', end: '13:00' },
95
+ ]);
96
+ week[2].isWorking = false;
97
+ expect(availabilityFromWeek(week, [], {}).weeklySchedule).toEqual([
98
+ { day: 1, start: '09:00', end: '13:00' },
99
+ { day: 1, start: '16:00', end: '20:00' },
100
+ ]);
101
+ });
102
+
103
+ it('suggests a slot after the last one, stops at midnight and gives up without room', () => {
104
+ const after = (end: string) => suggestNextSlot(1, [{ day: 1, start: '08:00', end }]);
105
+ expect(suggestNextSlot(1, [])).toEqual({ day: 1, start: '09:00', end: '18:00' });
106
+ expect(after('13:00')).toEqual({ day: 1, start: '14:00', end: '18:00' });
107
+ expect(after('21:00')).toEqual({ day: 1, start: '22:00', end: '23:59' });
108
+ expect(after('22:45')).toBeNull();
109
+ expect(after('')).toBeNull();
110
+ });
111
+
112
+ it('measures the week', () => {
113
+ const split = availability({ weeklySchedule: AVAILABILITY_TEMPLATES[3].weeklySchedule });
114
+ expect(weeklyHours(split)).toBe(40);
115
+ expect(workingDays(split)).toEqual([1, 2, 3, 4, 5]);
116
+ expect(findGaps(split.weeklySchedule)[0]).toEqual({ day: 1, from: '13:00', to: '16:00' });
117
+ });
118
+ });
119
+
120
+ describe('dates', () => {
121
+ it('rejects days that do not exist', () => {
122
+ expect(isValidDate('2028-02-29')).toBe(true);
123
+ expect(isValidDate('2026-02-29')).toBe(false);
124
+ expect(isValidDate('2026-2-9')).toBe(false);
125
+ });
126
+
127
+ it('reads the local day even late in the evening', () => {
128
+ expect(toCalendarDate(new Date(2026, 10, 25, 23, 30))).toBe('2026-11-25');
129
+ });
130
+ });
@@ -0,0 +1,89 @@
1
+ import type { AvailabilityTemplate, DoctorAvailability, SchedulingRules, WeeklySlot } from './types';
2
+
3
+ export const AVAILABILITY_VERSION = 1;
4
+
5
+ export const DAYS_OF_WEEK = [
6
+ { value: 0, label: 'Domingo', short: 'Dom', abbr: 'D' },
7
+ { value: 1, label: 'Lunes', short: 'Lun', abbr: 'L' },
8
+ { value: 2, label: 'Martes', short: 'Mar', abbr: 'M' },
9
+ { value: 3, label: 'Miércoles', short: 'Mié', abbr: 'X' },
10
+ { value: 4, label: 'Jueves', short: 'Jue', abbr: 'J' },
11
+ { value: 5, label: 'Viernes', short: 'Vie', abbr: 'V' },
12
+ { value: 6, label: 'Sábado', short: 'Sáb', abbr: 'S' },
13
+ ] as const;
14
+
15
+ export const WEEKDAYS = [1, 2, 3, 4, 5] as const;
16
+ export const WEEKEND = [0, 6] as const;
17
+
18
+ export const DEFAULT_WORK_START = '09:00';
19
+ export const DEFAULT_WORK_END = '18:00';
20
+ export const DEFAULT_BREAK_START = '13:00';
21
+ export const DEFAULT_BREAK_END = '14:00';
22
+
23
+ export const SLOT_DURATION_CHOICES = [15, 20, 30, 45, 60] as const;
24
+
25
+ export const DEFAULT_RULES: Readonly<SchedulingRules> = {
26
+ minSlotDuration: 15,
27
+ maxPatientsPerHour: 4,
28
+ bufferBetweenAppointments: 5,
29
+ };
30
+
31
+ export const COMMON_EXCEPTION_REASONS = [
32
+ 'Vacaciones',
33
+ 'Día festivo',
34
+ 'Conferencia',
35
+ 'Capacitación',
36
+ 'Cita personal',
37
+ 'Enfermedad',
38
+ 'Emergencia familiar',
39
+ ] as const;
40
+
41
+ export function emptyAvailability(): DoctorAvailability {
42
+ return { version: AVAILABILITY_VERSION, weeklySchedule: [], overrides: [], rules: { ...DEFAULT_RULES } };
43
+ }
44
+
45
+ const everyDay = (days: readonly number[], ...hours: Omit<WeeklySlot, 'day'>[]): WeeklySlot[] =>
46
+ days.flatMap((day) => hours.map((slot) => ({ day, ...slot })));
47
+
48
+ export const AVAILABILITY_TEMPLATES: AvailabilityTemplate[] = [
49
+ {
50
+ id: 'standard-9-5',
51
+ name: 'Estándar 9-18 (L-V)',
52
+ description: '9:00 - 18:00, lunes a viernes, fines de semana libres',
53
+ weeklySchedule: everyDay(WEEKDAYS, { start: '09:00', end: '18:00' }),
54
+ },
55
+ {
56
+ id: 'morning-clinic',
57
+ name: 'Clínica Matutina (L-V)',
58
+ description: '8:00 - 14:00, lunes a viernes',
59
+ weeklySchedule: everyDay(WEEKDAYS, { start: '08:00', end: '14:00' }),
60
+ },
61
+ {
62
+ id: 'afternoon-clinic',
63
+ name: 'Clínica Vespertina (L-V)',
64
+ description: '15:00 - 21:00, lunes a viernes',
65
+ weeklySchedule: everyDay(WEEKDAYS, { start: '15:00', end: '21:00' }),
66
+ },
67
+ {
68
+ id: 'split-shift',
69
+ name: 'Turno Partido (L-V)',
70
+ description: '9:00 - 13:00 y 16:00 - 20:00, lunes a viernes',
71
+ weeklySchedule: everyDay(
72
+ WEEKDAYS,
73
+ { start: '09:00', end: '13:00', label: 'Mañana' },
74
+ { start: '16:00', end: '20:00', label: 'Tarde' },
75
+ ),
76
+ },
77
+ {
78
+ id: 'weekend-doctor',
79
+ name: 'Doctor de Fin de Semana',
80
+ description: '10:00 - 14:00, sábado y domingo',
81
+ weeklySchedule: everyDay(WEEKEND, { start: '10:00', end: '14:00' }),
82
+ },
83
+ {
84
+ id: 'full-week',
85
+ name: 'Semana Completa',
86
+ description: '9:00 - 18:00, todos los días',
87
+ weeklySchedule: everyDay([0, ...WEEKDAYS, 6], { start: '09:00', end: '18:00' }),
88
+ },
89
+ ];
@@ -0,0 +1,6 @@
1
+ /** A professional's weekly hours, date exceptions and booking rules: data and pure functions. */
2
+ export * from './types';
3
+ export * from './defaults';
4
+ export * from './time';
5
+ export * from './validation';
6
+ export * from './week';
@@ -0,0 +1,38 @@
1
+ import type { CalendarDate, TimeOfDay } from './types';
2
+
3
+ export const MINUTES_PER_DAY = 24 * 60;
4
+
5
+ const TIME_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/;
6
+ const DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
7
+
8
+ const twoDigits = (value: number): string => String(value).padStart(2, '0');
9
+
10
+ export function timeToMinutes(time: TimeOfDay): number {
11
+ const [hours, minutes] = time.split(':').map(Number);
12
+ return hours * 60 + minutes;
13
+ }
14
+
15
+ export function minutesToTime(minutes: number): TimeOfDay {
16
+ return `${twoDigits(Math.floor(minutes / 60) % 24)}:${twoDigits(minutes % 60)}`;
17
+ }
18
+
19
+ export function isValidTime(time: string): boolean {
20
+ return TIME_PATTERN.test(time);
21
+ }
22
+
23
+ export function isEndAfterStart(start: TimeOfDay, end: TimeOfDay): boolean {
24
+ return timeToMinutes(end) > timeToMinutes(start);
25
+ }
26
+
27
+ export function isValidDate(date: string): boolean {
28
+ const match = DATE_PATTERN.exec(date);
29
+ if (!match) return false;
30
+ const [year, month, day] = match.slice(1).map(Number);
31
+ const parsed = new Date(Date.UTC(year, month - 1, day));
32
+ return parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;
33
+ }
34
+
35
+ /** Local calendar date; `toISOString` would roll to tomorrow in the evening west of Greenwich. */
36
+ export function toCalendarDate(date: Date): CalendarDate {
37
+ return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;
38
+ }