@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.
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,84 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { conversationFileName, conversationToMarkdown } from './markdown';
3
+ import type { ConversationRecord } from './record';
4
+
5
+ function record(over: Partial<ConversationRecord> = {}): ConversationRecord {
6
+ return {
7
+ id: 'c1',
8
+ title: 'Fotosíntesis',
9
+ createdAt: '2026-07-28T18:00:00.000Z',
10
+ updatedAt: '2026-07-28T18:05:00.000Z',
11
+ preview: '',
12
+ schemaVersion: 1,
13
+ messages: [
14
+ { id: 'm1', role: 'user', content: '¿Qué es la fotosíntesis?', createdAt: '2026-07-28T18:00:00.000Z' },
15
+ { id: 'm2', role: 'assistant', content: 'Es la cocina de las plantas.', createdAt: '2026-07-28T18:00:10.000Z' },
16
+ ],
17
+ ...over,
18
+ } as unknown as ConversationRecord;
19
+ }
20
+
21
+ describe('conversationToMarkdown', () => {
22
+ it('abre con el título y lleva cada turno con su encabezado', () => {
23
+ const md = conversationToMarkdown(record());
24
+ expect(md).toMatch(/^# Fotosíntesis\n/);
25
+ expect(md).toContain('## Tú\n\n¿Qué es la fotosíntesis?');
26
+ expect(md).toContain('## Asistente\n\nEs la cocina de las plantas.');
27
+ });
28
+
29
+ it('respeta las etiquetas y la procedencia que le dé el shell', () => {
30
+ const md = conversationToMarkdown(record(), {
31
+ labels: { assistant: 'Fénix' },
32
+ source: 'Computadoras públicas de Fénix',
33
+ });
34
+ expect(md).toContain('## Fénix');
35
+ expect(md).toContain('*Computadoras públicas de Fénix*');
36
+ });
37
+
38
+ it('salta los mensajes vacíos — un turno cancelado no deja un hueco', () => {
39
+ const md = conversationToMarkdown(
40
+ record({
41
+ messages: [
42
+ { id: 'm1', role: 'user', content: 'hola', createdAt: '' },
43
+ { id: 'm2', role: 'assistant', content: ' ', createdAt: '' },
44
+ ] as never,
45
+ }),
46
+ );
47
+ expect(md).toContain('## Tú');
48
+ expect(md).not.toContain('## Asistente');
49
+ });
50
+
51
+ it('termina en un solo salto de línea', () => {
52
+ const md = conversationToMarkdown(record());
53
+ expect(md.endsWith('\n')).toBe(true);
54
+ expect(md.endsWith('\n\n')).toBe(false);
55
+ });
56
+
57
+ it('sobrevive a una conversación sin mensajes ni título', () => {
58
+ const md = conversationToMarkdown(record({ title: '', messages: [] }));
59
+ expect(md).toContain('# Conversación');
60
+ });
61
+ });
62
+
63
+ describe('conversationFileName', () => {
64
+ it('quita acentos y deja un nombre plano', () => {
65
+ expect(conversationFileName(record())).toBe('Fotosintesis.md');
66
+ });
67
+
68
+ it('no deja que un título arme rutas ni rompa la descarga', () => {
69
+ const nombre = conversationFileName(record({ title: 'tarea 3/4: química ¿por qué? 🧪' }));
70
+ expect(nombre).not.toContain('/');
71
+ expect(nombre).not.toContain(':');
72
+ expect(nombre).toMatch(/^[\w-]+\.md$/);
73
+ });
74
+
75
+ it('acota el largo y no termina en guion', () => {
76
+ const nombre = conversationFileName(record({ title: 'palabra '.repeat(30) }));
77
+ expect(nombre.length).toBeLessThanOrEqual(64);
78
+ expect(nombre).not.toContain('-.md');
79
+ });
80
+
81
+ it('cae en un nombre usable cuando el título no deja nada', () => {
82
+ expect(conversationFileName(record({ title: '¿¡🧪!?' }))).toBe('conversacion.md');
83
+ });
84
+ });
@@ -0,0 +1,67 @@
1
+ /**
2
+ * conversationToMarkdown — la conversación como un archivo que alguien se lleva.
3
+ *
4
+ * Función pura sobre el record: sin React, sin navegador, sin descarga. Quien
5
+ * quiera entregarlo (un Blob en el browser, un archivo en disco, un adjunto de
6
+ * correo) pone ESA parte; aquí sólo vive la forma del documento, que es lo que
7
+ * se repite en cada shell.
8
+ *
9
+ * Markdown y no PDF ni HTML porque el destino real es seguir trabajando: se
10
+ * pega en un cuaderno digital, se abre en cualquier editor, se lee tal cual en
11
+ * texto plano si no hay nada más a la mano.
12
+ */
13
+
14
+ import type { ChatMessage } from '../chat/message';
15
+ import type { ConversationRecord } from './record';
16
+
17
+ export interface ConversationMarkdownOptions {
18
+ /** Cómo se nombra a cada lado. Default: `Tú` / `Asistente`. */
19
+ labels?: { user?: string; assistant?: string };
20
+ /** Línea de procedencia bajo el título (de dónde salió esta conversación). */
21
+ source?: string;
22
+ }
23
+
24
+ function etiqueta(m: ChatMessage, o: ConversationMarkdownOptions): string {
25
+ if (m.role === 'user') return o.labels?.user ?? 'Tú';
26
+ if (m.role === 'assistant') return o.labels?.assistant ?? 'Asistente';
27
+ return m.role;
28
+ }
29
+
30
+ /** El documento completo, listo para escribir a un archivo `.md`. */
31
+ export function conversationToMarkdown(
32
+ record: ConversationRecord,
33
+ options: ConversationMarkdownOptions = {},
34
+ ): string {
35
+ const partes: string[] = [`# ${record.title || 'Conversación'}`, ''];
36
+
37
+ const fecha = record.createdAt || record.updatedAt;
38
+ if (fecha) partes.push(`*${new Date(fecha).toLocaleString()}*`, '');
39
+ if (options.source) partes.push(`*${options.source}*`, '');
40
+
41
+ for (const m of record.messages) {
42
+ const contenido = (m.content ?? '').trim();
43
+ if (!contenido) continue;
44
+ partes.push(`## ${etiqueta(m, options)}`, '', contenido, '');
45
+ }
46
+
47
+ return `${partes.join('\n').trimEnd()}\n`;
48
+ }
49
+
50
+ /**
51
+ * Un nombre de archivo seguro derivado del título.
52
+ *
53
+ * Los títulos vienen del primer mensaje del usuario, así que traen de todo:
54
+ * `/`, `:`, saltos de línea, emoji. Un nombre sin sanear rompe la descarga en
55
+ * silencio o crea directorios que nadie pidió.
56
+ */
57
+ export function conversationFileName(record: ConversationRecord): string {
58
+ const base = (record.title || 'conversacion')
59
+ .normalize('NFD')
60
+ .replace(/[\u0300-\u036f]/g, '')
61
+ .replace(/[^\w\s-]/g, '')
62
+ .trim()
63
+ .replace(/\s+/g, '-')
64
+ .slice(0, 60)
65
+ .replace(/-+$/, '');
66
+ return `${base || 'conversacion'}.md`;
67
+ }
@@ -14,8 +14,13 @@ import type { ChatMessage } from '../chat/message';
14
14
  export interface ConversationRecord {
15
15
  /** Stable id. Doubles as the backend session_id for the same thread. */
16
16
  id: string;
17
- /** Human-readable title, derived from the first user message. */
17
+ /** Human-readable title. Derived from the first user message unless the user
18
+ * renamed it, in which case `titleCustom` is set and the title is preserved
19
+ * across future message persists. */
18
20
  title: string;
21
+ /** True when the user explicitly renamed this conversation. A custom title is
22
+ * never re-derived from messages on persist. Absent/false ⇒ auto-derived. */
23
+ titleCustom?: boolean;
19
24
  /** ISO 8601 creation timestamp. */
20
25
  createdAt: string;
21
26
  /** ISO 8601 timestamp of the last change. */
@@ -24,6 +29,24 @@ export interface ConversationRecord {
24
29
  messages: ChatMessage[];
25
30
  /** Snippet of the last non-empty message, for the sidebar. */
26
31
  preview: string;
32
+ /** ISO 8601 timestamp of when the user pinned this conversation. Absent ⇒ not
33
+ * pinned. A timestamp (not a boolean) so the pinned section orders by
34
+ * last-pinned first without a separate counter. */
35
+ pinnedAt?: string;
36
+ /** ISO 8601 timestamp of when the user archived this conversation. Absent ⇒
37
+ * active. Archiving is the reversible alternative to delete: the record keeps
38
+ * its messages and moves to the archived section. */
39
+ archivedAt?: string;
40
+ /**
41
+ * The resource (og118: a Project) this conversation was BORN in — the same
42
+ * `projectId` the server stores, so the name matches the wire rather than
43
+ * inventing a client-side alias nobody could grep for.
44
+ *
45
+ * Stamped once, at first persist, and preserved from then on. It is not "the
46
+ * currently selected project": moving the selection later must not silently
47
+ * re-file yesterday's conversations under today's project.
48
+ */
49
+ projectId?: string;
27
50
  /** Schema version of this record, for forward migrations. */
28
51
  schemaVersion: number;
29
52
  }
@@ -35,4 +58,9 @@ export interface ConversationSummary {
35
58
  createdAt: string;
36
59
  updatedAt: string;
37
60
  preview: string;
61
+ pinnedAt?: string;
62
+ archivedAt?: string;
63
+ /** Rides the SUMMARY too: a per-resource list filters the light rows, and
64
+ * pulling full records just to read one field would cost every transcript. */
65
+ projectId?: string;
38
66
  }
@@ -0,0 +1,19 @@
1
+ // DO NOT EDIT — generado desde contracts/copy.json (pnpm gen:copy).
2
+ //
3
+ // Las frases que el substrato posee. Swift deriva del mismo contrato
4
+ // (Copy.generated.swift); ninguna superficie manda sobre la otra.
5
+
6
+ export const COPY = {
7
+ /** Título de un hilo sin mensaje de usuario usable (deriveConversationTitle). */
8
+ conversationDefaultTitle: 'New chat',
9
+ /** Aviso (no error) de un turno diferido: el motor sigue trabajando tras cerrar el stream. */
10
+ turnDeferredNotice: (author: string): string => '{author} sigue escribiendo. Su respuesta aparecerá aquí en cuanto termine.'.split('{author}').join(author),
11
+ /** El aviso cuando la relectura acotada del hilo se agotó sin que llegara la respuesta diferida. */
12
+ turnDeferredTimeout: 'La respuesta tardó más de lo normal. Vuelve a abrir este chat para verla.',
13
+ /** Falla genérica del transporte o del motor, cuando no trae mensaje propio. */
14
+ turnFailed: 'La respuesta falló. Intenta de nuevo.',
15
+ /** El watchdog de inactividad cerró el turno. */
16
+ turnTimeout: 'La respuesta tardó demasiado. Intenta de nuevo.',
17
+ /** El turno cerró sin texto, sin reacción y sin deferred: el silencio es una falla. */
18
+ turnEmpty: 'La respuesta llegó vacía. Intenta de nuevo.',
19
+ } as const;
package/src/index.ts CHANGED
@@ -10,7 +10,7 @@ export type {
10
10
  TranscriptResult,
11
11
  TranscribeContext,
12
12
  } from './voice/adapter';
13
- export type { ChatMessage, ChatStreamingState } from './chat/message';
13
+ export type { ChatMessage, ChatStreamingState, MessageImage, MessageTrace } from './chat/message';
14
14
  export type { ChatHook } from './chat/hook';
15
15
 
16
16
  // Agent-turn contract (Berkelio). Types describe the wire stream + reduced
@@ -22,6 +22,7 @@ export type {
22
22
  ToolCall,
23
23
  GuardRejection,
24
24
  AgentMeta,
25
+ MessageAuthor,
25
26
  } from './agent/events';
26
27
  export type {
27
28
  PlanStep,
@@ -31,8 +32,44 @@ export type {
31
32
  AgentTurnState,
32
33
  } from './agent/state';
33
34
  export { initialAgentTurnState, applyAgentEvent } from './agent/state';
34
- export { makeUserMessage, foldAssistantTurn } from './agent/transcript';
35
- export type { AgentHook } from './agent/hook';
35
+ export { fromWireEvent } from './agent/wire-map';
36
+ export { takeSseFrames } from './agent/sse';
37
+ export { COPY } from './copy.generated';
38
+ export { initialConversationState, applyConversationEvent } from './agent/conversation-state';
39
+ export type {
40
+ ConversationState,
41
+ ConversationEvent,
42
+ TurnFailure,
43
+ TurnNotice,
44
+ UnsentDraft,
45
+ } from './agent/conversation-state';
46
+ export { makeUserMessage, foldAssistantTurn, mergeConversationMessages } from './agent/transcript';
47
+ export type { AgentHook, AgentSendMeta } from './agent/hook';
48
+
49
+ // The RAW WIRE frames, generated from the fi-runner contract (the SSOT lives in
50
+ // apps/packages/fi-runner/fi_runner/events.py). A transport hook parses SSE into
51
+ // these, then maps them to the normalized AgentStreamEvent above. Exported so a
52
+ // consumer's mapEvent types its input instead of guessing at
53
+ // Record<string, unknown> — the guesswork is what let frames drift silently.
54
+ export type {
55
+ AgentStreamEvent as AgentWireEvent,
56
+ OpenEvent as WireOpenEvent,
57
+ ElementEvent as WireElementEvent,
58
+ TextEvent as WireTextEvent,
59
+ ToolCallEvent as WireToolCallEvent,
60
+ ResultEvent as WireResultEvent,
61
+ PlanEvent as WirePlanEvent,
62
+ StepStartedEvent as WireStepStartedEvent,
63
+ StepDoneEvent as WireStepDoneEvent,
64
+ StepNotedEvent as WireStepNotedEvent,
65
+ PlanAmendedEvent as WirePlanAmendedEvent,
66
+ PlanCancelledEvent as WirePlanCancelledEvent,
67
+ PlanCompletedEvent as WirePlanCompletedEvent,
68
+ PlanFailedEvent as WirePlanFailedEvent,
69
+ PlanRejectedEvent as WirePlanRejectedEvent,
70
+ ErrorEvent as WireErrorEvent,
71
+ DoneEvent as WireDoneEvent,
72
+ } from './agent/wire.generated';
36
73
 
37
74
  // Conversation library contract (DD-002B1). Local-first transcript persistence:
38
75
  // record/summary types, the ConversationLibrary storage contract, and pure
@@ -42,13 +79,28 @@ export type {
42
79
  ConversationRecord,
43
80
  ConversationSummary,
44
81
  ConversationLibrary,
82
+ ConversationMetadataPatch,
45
83
  CreateConversationRecordArgs,
84
+ OrganizedConversations,
46
85
  } from './conversation';
47
86
  export {
48
87
  CONVERSATION_SCHEMA_VERSION,
49
88
  createConversationRecord,
50
89
  summarizeConversation,
90
+ organizeConversationSummaries,
91
+ filterConversationSummaries,
51
92
  deriveConversationTitle,
52
93
  deriveConversationPreview,
94
+ resolveConversationTitle,
95
+ renameConversationRecord,
96
+ setConversationPinned,
97
+ setConversationArchived,
98
+ applyConversationMetadataPatch,
99
+ conversationRenamePatch,
100
+ conversationPinPatch,
101
+ conversationArchivePatch,
53
102
  sanitizeConversationMessage,
103
+ conversationToMarkdown,
104
+ conversationFileName,
54
105
  } from './conversation';
106
+ export type { ConversationMarkdownOptions } from './conversation';