@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
package/dist/index.d.ts CHANGED
@@ -88,77 +88,6 @@ interface VoiceAdapter {
88
88
  transcribe?(chunk: Blob, ctx?: TranscribeContext): Promise<TranscriptResult>;
89
89
  }
90
90
 
91
- /**
92
- * ChatMessage — the material-agnostic shape of one chat message.
93
- *
94
- * Apps may use a richer message type (e.g. aurity's FIMessage with typed
95
- * metadata); ChatHook is generic over the message type and defaults to this.
96
- * Pure data — no React, no styling.
97
- */
98
- interface ChatMessage {
99
- /** Stable id (optional for transient/streaming messages). */
100
- id?: string;
101
- /** Who authored the message. */
102
- role: 'user' | 'assistant';
103
- /** The message text. */
104
- content: string;
105
- /** Optional model reasoning rendered before the content. */
106
- thinking?: string | null;
107
- /** ISO 8601 timestamp. */
108
- timestamp: string;
109
- /** App-specific metadata (tone, voice, model, …). */
110
- metadata?: Record<string, unknown>;
111
- }
112
- /** Streaming state surfaced by a ChatHook while a response is in flight. */
113
- interface ChatStreamingState {
114
- status: 'idle' | 'connecting' | 'streaming' | 'thinking' | 'complete' | 'error' | 'aborted';
115
- content: string;
116
- thinking: string;
117
- isStreaming: boolean;
118
- }
119
-
120
- /**
121
- * ChatHook — the conversation contract the fi-glass shell consumes.
122
- *
123
- * This is the dependency-inversion spine of the chat shell: ChatWidget never
124
- * imports a concrete conversation hook, it consumes this interface. aurity
125
- * implements it with `useFIConversation`; og118 implements its own against its
126
- * backend. A fat contract (state + actions + streaming) → it earns a place in
127
- * core (unlike navigation, which is a plain callback prop).
128
- *
129
- * Generic over:
130
- * - `TMessage` — the message type (aurity passes its FIMessage; default ChatMessage).
131
- * - `TNode` — the UI-slot node type (aurity passes React's ReactNode). Kept
132
- * generic so core stays framework-agnostic (no React import).
133
- */
134
- interface ChatHook<TMessage = ChatMessage, TNode = unknown> {
135
- messages: TMessage[];
136
- loading: boolean;
137
- isTyping: boolean;
138
- loadingInitial?: boolean;
139
- hasMoreMessages?: boolean;
140
- loadingOlder?: boolean;
141
- streamingMessage?: string;
142
- streaming?: ChatStreamingState;
143
- sendMessage: (message: string, metadata?: object) => Promise<void>;
144
- sendMessageStream?: (message: string, metadata?: object) => Promise<void>;
145
- loadOlderMessages?: () => Promise<void>;
146
- clearConversation?: () => void;
147
- getIntroduction?: () => void;
148
- startConversation?: () => Promise<void>;
149
- sendQuickReply?: (reply: string) => Promise<void>;
150
- conversationState?: {
151
- quickReplies?: string[];
152
- actions?: Array<{
153
- type: string;
154
- data: unknown;
155
- }>;
156
- metadata?: Record<string, unknown>;
157
- };
158
- customEmptyState?: TNode;
159
- customQuickReplies?: TNode;
160
- }
161
-
162
91
  /**
163
92
  * AgentStreamEvent — the agent-turn wire contract.
164
93
  *
@@ -207,6 +136,30 @@ interface GuardRejection {
207
136
  /** Guard identifier (app-defined), or null. */
208
137
  guard: string | null;
209
138
  }
139
+ /**
140
+ * MessageAuthor — WHO produced a message. Part of the contract, not app wiring.
141
+ *
142
+ * A shell that lets the user switch the answering persona (og118's elementos,
143
+ * aurity's personas) renders a transcript where every bubble must say who spoke;
144
+ * an assistant bubble with no author silently attributes the answer to the app
145
+ * itself. That is a lie the framework must not be able to express — so the fold
146
+ * ({@link foldAssistantTurn}) and the user capsule ({@link makeUserMessage})
147
+ * both REQUIRE an author, and a turn can rebind it mid-stream via the `author`
148
+ * event (the backend announces the persona it resolved for the turn).
149
+ *
150
+ * Only `id` and `name` are load-bearing; `symbol` and `engine` are optional
151
+ * enrichment a shell may render as an avatar token / provenance chip.
152
+ */
153
+ interface MessageAuthor {
154
+ /** Stable identifier of the speaker (element id, persona id, 'user'). */
155
+ id: string;
156
+ /** Human name shown as the author ("Yodo", "og118", "Tú"). */
157
+ name: string;
158
+ /** Short avatar/badge token ("I", "og"). */
159
+ symbol?: string | null;
160
+ /** The engine/persona behind the answer ("Vultur", "ALICE"). */
161
+ engine?: string | null;
162
+ }
210
163
  /** Per-turn observability. All optional; each app fills what it has. */
211
164
  interface AgentMeta {
212
165
  requestId?: string | null;
@@ -229,7 +182,7 @@ interface AgentMeta {
229
182
  * from RAG or web-search). Apps extract them however they like (insult_ai parses
230
183
  * a "Receipts" markdown tail in its own hook — app-specific, stays there).
231
184
  */
232
- type AgentStreamEvent = {
185
+ type AgentStreamEvent$1 = {
233
186
  type: 'open';
234
187
  sessionId?: string;
235
188
  requestId?: string;
@@ -274,17 +227,25 @@ type AgentStreamEvent = {
274
227
  } | {
275
228
  type: 'text';
276
229
  delta: string;
230
+ } | {
231
+ type: 'author';
232
+ author: MessageAuthor;
277
233
  } | {
278
234
  type: 'result';
279
235
  text: string;
280
236
  sources?: string[];
281
237
  meta?: AgentMeta;
238
+ reactions?: string[];
282
239
  } | {
283
240
  type: 'meta';
284
241
  meta: AgentMeta;
285
242
  } | {
286
243
  type: 'error';
287
244
  message: string;
245
+ } | {
246
+ type: 'ping';
247
+ } | {
248
+ type: 'deferred';
288
249
  } | {
289
250
  type: 'done';
290
251
  };
@@ -330,7 +291,34 @@ interface AgentTurnState {
330
291
  text: string;
331
292
  /** Evidence references (e.g. source URLs). App-agnostic name. */
332
293
  sources: string[];
294
+ /**
295
+ * Emoji the speaker reacted to the turn with (`result.reactions`). Empty on
296
+ * every turn from an engine without a reaction vocabulary. See
297
+ * `ChatMessage.reactions` for why this is a field and not text.
298
+ */
299
+ reactions: string[];
333
300
  meta: AgentMeta | null;
301
+ /**
302
+ * WHO is answering this turn, once the backend announces it (`author` event).
303
+ * null means the backend never named a speaker — the shell then attributes the
304
+ * turn to the agent's default author, which it must supply. See
305
+ * {@link MessageAuthor}.
306
+ */
307
+ author: MessageAuthor | null;
308
+ /**
309
+ * How many signs of life the backend has sent while the turn was QUIET (bare
310
+ * `ping` frames). A shell's idle watchdog re-arms on this: a healthy turn can
311
+ * be silent for a long time (a proxied engine answers in one shot; a model
312
+ * thinks before its first token), and killing it throws away what the user
313
+ * wrote. A counter, not a timestamp — the reducer stays pure.
314
+ */
315
+ heartbeats: number;
316
+ /**
317
+ * True once the backend released this turn WITHOUT an answer because the
318
+ * engine was still working (`deferred` frame). The answer arrives in the
319
+ * thread out of band; the turn settles empty and a shell shows a waiting notice.
320
+ */
321
+ deferred: boolean;
334
322
  status: AgentTurnStatus;
335
323
  errorMessage?: string;
336
324
  }
@@ -343,7 +331,342 @@ declare function initialAgentTurnState(): AgentTurnState;
343
331
  * transport produces. Unknown/transport-only events (`open`) pass through
344
332
  * untouched.
345
333
  */
346
- declare function applyAgentEvent(state: AgentTurnState, event: AgentStreamEvent): AgentTurnState;
334
+ declare function applyAgentEvent(state: AgentTurnState, event: AgentStreamEvent$1): AgentTurnState;
335
+
336
+ /**
337
+ * MessageTrace — the persisted glass-box snapshot of a finished agentic turn.
338
+ *
339
+ * The differentiator is "see the execution, not just the result": during the
340
+ * stream you watch the plan declared and the steps walked, but a folded message
341
+ * historically kept only the answer text (see {@link foldAssistantTurn}). This
342
+ * carries the agentic provenance — the declared plan with its per-step outcomes,
343
+ * the tool calls, the evidence — INTO the durable transcript, so reloading a
344
+ * conversation re-renders the same glass-box the live turn showed.
345
+ *
346
+ * Reuses the live agent contract types verbatim ({@link AgentPlan},
347
+ * {@link ToolCall}); persistence is just a snapshot of the reduced turn state,
348
+ * not a parallel shape. Every field is optional: a plain conversational turn
349
+ * (no plan, no tools) folds to a message with no `trace`, unchanged.
350
+ */
351
+ interface MessageTrace {
352
+ /** The declared plan with per-step status/summary/outcome, if the turn planned. */
353
+ plan?: AgentPlan;
354
+ /** The tool calls made during the turn, if any. */
355
+ tools?: ToolCall[];
356
+ /** Evidence references surfaced during the turn, if any. */
357
+ sources?: string[];
358
+ /**
359
+ * The model that actually produced the answer. Provenance, like the plan and
360
+ * the tools — so it lives HERE, not in `metadata`, which persistence drops by
361
+ * design. A "powered by <model>" chip read from `metadata` shows on the live
362
+ * turn and vanishes on reload; read from the trace it survives.
363
+ */
364
+ model?: string;
365
+ }
366
+ /**
367
+ * MessageImage — one image attached to a user message (OG118-IMAGE-UPLOAD-1).
368
+ *
369
+ * Base64 by design: the shells are local-first (IndexedDB / JSON records), so
370
+ * the bytes ride inside the message instead of referencing a blob store nobody
371
+ * runs. Producers (the composer) downscale before encoding, so a persisted
372
+ * image stays small enough for the conversation-record size caps.
373
+ */
374
+ interface MessageImage {
375
+ /** MIME type of the encoded bytes, e.g. `image/jpeg`, `image/png`. */
376
+ mediaType: string;
377
+ /** Base64-encoded bytes — no `data:` URL prefix. */
378
+ data: string;
379
+ }
380
+ /**
381
+ * ChatMessage — the material-agnostic shape of one chat message.
382
+ *
383
+ * Apps may use a richer message type (e.g. aurity's FIMessage with typed
384
+ * metadata); ChatHook is generic over the message type and defaults to this.
385
+ * Pure data — no React, no styling.
386
+ */
387
+ interface ChatMessage {
388
+ /** Stable id (optional for transient/streaming messages). */
389
+ id?: string;
390
+ /** Which side of the conversation the message sits on. */
391
+ role: 'user' | 'assistant';
392
+ /**
393
+ * WHO said it — the named speaker, not merely the side. A shell with a persona
394
+ * switch (og118's elementos) must attribute each bubble to the persona that
395
+ * actually produced it, and that attribution has to survive a reload, so it is
396
+ * a first-class field (preserved by `sanitizeConversationMessage`, unlike
397
+ * `metadata`). Optional only for messages authored outside the agent contract;
398
+ * everything {@link foldAssistantTurn}/{@link makeUserMessage} builds has one.
399
+ */
400
+ author?: MessageAuthor;
401
+ /** The message text. May be empty on an image-only user message. */
402
+ content: string;
403
+ /**
404
+ * Images attached to this message (user messages only) — rendered in the
405
+ * transcript and sent to the model as vision input. Absent on text-only
406
+ * messages, so the plain case stays byte-identical to before.
407
+ */
408
+ images?: MessageImage[];
409
+ /**
410
+ * Emoji the speaker REACTED to the turn with (assistant messages only). A
411
+ * reaction is a gesture on the message, not part of its text — Discord puts it
412
+ * under the bubble, never inside it — so it is a field, not a line folded into
413
+ * `content`. Comes from the engine's `OutboundTurn` (server-bot F5) via the
414
+ * `result` event, persists like `images` (a reload must not lose the gesture),
415
+ * and is absent on plain turns so those stay byte-identical.
416
+ */
417
+ reactions?: string[];
418
+ /** Optional model reasoning rendered before the content. */
419
+ thinking?: string | null;
420
+ /** ISO 8601 timestamp. */
421
+ timestamp: string;
422
+ /** App-specific metadata (tone, voice, model, …). */
423
+ metadata?: Record<string, unknown>;
424
+ /**
425
+ * Persisted glass-box snapshot of the agentic turn that produced this message
426
+ * (assistant messages only). Absent for plain conversational turns and all
427
+ * user messages — see {@link MessageTrace}.
428
+ */
429
+ trace?: MessageTrace;
430
+ }
431
+ /** Streaming state surfaced by a ChatHook while a response is in flight. */
432
+ interface ChatStreamingState {
433
+ status: 'idle' | 'connecting' | 'streaming' | 'thinking' | 'complete' | 'error' | 'aborted';
434
+ content: string;
435
+ thinking: string;
436
+ isStreaming: boolean;
437
+ }
438
+
439
+ /**
440
+ * ChatHook — the conversation contract the fi-glass shell consumes.
441
+ *
442
+ * This is the dependency-inversion spine of the chat shell: ChatWidget never
443
+ * imports a concrete conversation hook, it consumes this interface. aurity
444
+ * implements it with `useFIConversation`; og118 implements its own against its
445
+ * backend. A fat contract (state + actions + streaming) → it earns a place in
446
+ * core (unlike navigation, which is a plain callback prop).
447
+ *
448
+ * Generic over:
449
+ * - `TMessage` — the message type (aurity passes its FIMessage; default ChatMessage).
450
+ * - `TNode` — the UI-slot node type (aurity passes React's ReactNode). Kept
451
+ * generic so core stays framework-agnostic (no React import).
452
+ */
453
+ interface ChatHook<TMessage = ChatMessage, TNode = unknown> {
454
+ messages: TMessage[];
455
+ loading: boolean;
456
+ isTyping: boolean;
457
+ loadingInitial?: boolean;
458
+ hasMoreMessages?: boolean;
459
+ loadingOlder?: boolean;
460
+ streamingMessage?: string;
461
+ streaming?: ChatStreamingState;
462
+ sendMessage: (message: string, metadata?: object) => Promise<void>;
463
+ sendMessageStream?: (message: string, metadata?: object) => Promise<void>;
464
+ loadOlderMessages?: () => Promise<void>;
465
+ clearConversation?: () => void;
466
+ getIntroduction?: () => void;
467
+ startConversation?: () => Promise<void>;
468
+ sendQuickReply?: (reply: string) => Promise<void>;
469
+ conversationState?: {
470
+ quickReplies?: string[];
471
+ actions?: Array<{
472
+ type: string;
473
+ data: unknown;
474
+ }>;
475
+ metadata?: Record<string, unknown>;
476
+ };
477
+ customEmptyState?: TNode;
478
+ customQuickReplies?: TNode;
479
+ }
480
+
481
+ /**
482
+ * fi-runner wire frame → core {@link AgentStreamEvent}, or null to drop it.
483
+ *
484
+ * The wire is `contracts/agent-events.schema.json`; the app-level event is what
485
+ * {@link applyAgentEvent} reduces. This mapping lived in og118's transport hook
486
+ * and every other consumer of the stream (the iPhone, the next shell) had to
487
+ * rewrite it. It is substrate: one mapping, checked against the same vectors
488
+ * the native client replays (`contracts/agent-turn.vectors.json`).
489
+ *
490
+ * @param frame one decoded SSE `data:` payload
491
+ * @returns the core event, or null for a frame this layer has no use for
492
+ */
493
+
494
+ declare function fromWireEvent(frame: unknown): AgentStreamEvent$1 | null;
495
+
496
+ /**
497
+ * SSE framing for the agent stream: cut a growing byte buffer into the `data:`
498
+ * payloads that are complete, and hand back what is still arriving.
499
+ *
500
+ * A frame ends at a blank line; its `data:` lines join with `\n` (the SSE spec),
501
+ * which for the server's one-line frames is the line itself. Every transport
502
+ * (fetch in og118-web, URLSession on the iPhone) used to carry its own copy of
503
+ * this cut; the shared fixture `contracts/fixtures/turno-real.sse` is what each
504
+ * copy must read identically.
505
+ *
506
+ * @param buffer everything received so far that has not been consumed
507
+ * @returns the complete payloads in order, and the unconsumed tail
508
+ */
509
+ declare function takeSseFrames(buffer: string): {
510
+ payloads: string[];
511
+ rest: string;
512
+ };
513
+
514
+ declare const COPY: {
515
+ /** Título de un hilo sin mensaje de usuario usable (deriveConversationTitle). */
516
+ readonly conversationDefaultTitle: "New chat";
517
+ /** Aviso (no error) de un turno diferido: el motor sigue trabajando tras cerrar el stream. */
518
+ readonly turnDeferredNotice: (author: string) => string;
519
+ /** El aviso cuando la relectura acotada del hilo se agotó sin que llegara la respuesta diferida. */
520
+ readonly turnDeferredTimeout: "La respuesta tardó más de lo normal. Vuelve a abrir este chat para verla.";
521
+ /** Falla genérica del transporte o del motor, cuando no trae mensaje propio. */
522
+ readonly turnFailed: "La respuesta falló. Intenta de nuevo.";
523
+ /** El watchdog de inactividad cerró el turno. */
524
+ readonly turnTimeout: "La respuesta tardó demasiado. Intenta de nuevo.";
525
+ /** El turno cerró sin texto, sin reacción y sin deferred: el silencio es una falla. */
526
+ readonly turnEmpty: "La respuesta llegó vacía. Intenta de nuevo.";
527
+ };
528
+
529
+ /**
530
+ * ConversationState — the reduced state of a whole agentic CONVERSATION (the
531
+ * thread across turns), plus the pure `applyConversationEvent` reducer that
532
+ * derives it.
533
+ *
534
+ * Sibling of {@link ./state} one level up: `AgentTurnState` reduces the wire
535
+ * events of ONE streaming turn; this reduces the lifecycle of the conversation
536
+ * those turns live in — the optimistic push, the fold, the revert that hands the
537
+ * user's words back, the recoverable-failure banners, persistence bookkeeping.
538
+ *
539
+ * WHY IT MOVED HERE (framework-first-canary, the demotion's mirror): fi-glass's
540
+ * `useAgentConversation` held this logic across 7 `useState` + 10 `useRef` in a
541
+ * 575-line hook, so the rules of the machine — "a failed turn must never cost
542
+ * the user their words", "an optimistic push is not a confirmed turn" — could
543
+ * only be exercised by mounting React and driving a fake transport. They are not
544
+ * React rules; they are conversation rules, identical for every shell. Here they
545
+ * are one value and one function, testable with plain assertions.
546
+ *
547
+ * Pure: no React, no transport, no timers, no I/O. Immutable: every event
548
+ * returns a new state object. Time enters as an EVENT (`turn_timeout`), never as
549
+ * a clock read — same discipline as the turn reducer's heartbeat counter.
550
+ */
551
+
552
+ /**
553
+ * A turn that settled WITHOUT its answer because the engine is still working
554
+ * (`AgentTurnState.deferred`). Not a failure: nothing to retry, the answer lands
555
+ * in the thread out of band and the shell shows this until the thread refreshes.
556
+ */
557
+ interface TurnNotice {
558
+ kind: 'deferred';
559
+ message: string;
560
+ }
561
+ /** Why a turn failed, in terms a shell can render a recovery banner from. */
562
+ interface TurnFailure {
563
+ /** `empty` = the turn settled with no text, no reaction and no deferral: silence is a failure. */
564
+ kind: 'stream' | 'timeout' | 'empty';
565
+ message: string;
566
+ }
567
+ /**
568
+ * What a failed turn hands back so the shell can restore it into the composer.
569
+ * Carries the WHOLE message: returning only the text let a shell re-send a
570
+ * prompt whose images had silently ceased to exist.
571
+ */
572
+ interface UnsentDraft {
573
+ text: string | null;
574
+ images: MessageImage[] | null;
575
+ }
576
+ /** The reduced state of the conversation. */
577
+ interface ConversationState {
578
+ /** The visible thread. */
579
+ messages: ChatMessage[];
580
+ /** Set while an optimistically-pushed turn is still in flight; gates the fold. */
581
+ pending: boolean;
582
+ /** A recoverable turn failure the shell renders instead of a zombie panel. */
583
+ failure: TurnFailure | null;
584
+ /** The last turn was released without its answer; shown until the thread refreshes. */
585
+ notice: TurnNotice | null;
586
+ /** True once a turn timed out; keeps the watchdog from re-arming on it. */
587
+ timedOut: boolean;
588
+ /** What a failed turn handed back, for the shell to restore. */
589
+ unsent: UnsentDraft;
590
+ /** The last send, replayed verbatim by a retry (text AND images). */
591
+ lastSent: {
592
+ text: string;
593
+ images?: MessageImage[];
594
+ } | null;
595
+ /**
596
+ * True when the current `messages` change is NOT a confirmed, settled turn
597
+ * (the mount seed, a conversation switch, the optimistic push). A shell
598
+ * persists only when this is false, so a failed turn never leaves a durable
599
+ * lone user message.
600
+ */
601
+ skipPersist: boolean;
602
+ }
603
+ type ConversationEvent =
604
+ /** The user sent. `controlled` shells do not get an optimistic push. */
605
+ {
606
+ type: 'send';
607
+ text: string;
608
+ images?: MessageImage[];
609
+ author: MessageAuthor;
610
+ controlled: boolean;
611
+ }
612
+ /** The transport finished cleanly. Folds the assistant turn in. */
613
+ /** `stopped`: the USER ended the turn; an empty settle is then a choice, not a failure. */
614
+ | {
615
+ type: 'turn_settled';
616
+ turn: AgentTurnState;
617
+ author: MessageAuthor;
618
+ controlled: boolean;
619
+ stopped?: boolean;
620
+ }
621
+ /**
622
+ * The transport reported failure. `appHandled` means the app renders its own
623
+ * banner for this error class (e.g. a 401 token gate), so the generic
624
+ * recoverable failure is suppressed — the revert still happens either way.
625
+ */
626
+ | {
627
+ type: 'turn_failed';
628
+ message?: string;
629
+ controlled: boolean;
630
+ appHandled?: boolean;
631
+ }
632
+ /** The idle watchdog fired. Time as an event keeps the reducer pure. */
633
+ | {
634
+ type: 'turn_timeout';
635
+ controlled: boolean;
636
+ } | {
637
+ type: 'dismiss_failure';
638
+ } | {
639
+ type: 'dismiss_notice';
640
+ }
641
+ /** The shell restored `unsent` into its composer. */
642
+ | {
643
+ type: 'clear_unsent';
644
+ }
645
+ /** Load a different conversation (or start a fresh one). */
646
+ | {
647
+ type: 'hydrate';
648
+ messages: ChatMessage[];
649
+ }
650
+ /**
651
+ * The server's copy of THIS thread arrived (a worker appended mid-turn). It is
652
+ * unioned into the live thread; the pending turn is untouched and the merge is not a confirmed turn.
653
+ */
654
+ | {
655
+ type: 'merge_seed';
656
+ messages: ChatMessage[];
657
+ }
658
+ /**
659
+ * The shell CONSUMED the skip: it saw `skipPersist` and declined to persist
660
+ * this change. One-shot — the flag clears so the NEXT confirmed change
661
+ * persists normally. (Getting this backwards makes the shell skip forever and
662
+ * nothing is ever saved.)
663
+ */
664
+ | {
665
+ type: 'persist_skip_consumed';
666
+ };
667
+ declare function initialConversationState(seed?: ChatMessage[]): ConversationState;
668
+ /** Pure reducer: apply one conversation event, returning a new state. */
669
+ declare function applyConversationEvent(state: ConversationState, event: ConversationEvent): ConversationState;
347
670
 
348
671
  /**
349
672
  * Transcript bridge — fold the live agentic turn into flat chat messages.
@@ -354,20 +677,66 @@ declare function applyAgentEvent(state: AgentTurnState, event: AgentStreamEvent)
354
677
  * shell (fi-glass and beyond) can keep a visible transcript without re-deriving
355
678
  * the mapping. Moved here from the og118 consumer (DD-002-LESSON): a reusable
356
679
  * primitive belongs in the framework, not the app wrapper.
680
+ *
681
+ * NO TEXT WITHOUT AN AUTHOR: both helpers take the speaker as a REQUIRED
682
+ * argument. A shell whose user can swap the answering persona must never fold a
683
+ * bubble the transcript cannot attribute — the alternative (an optional author
684
+ * the consumer may forget) is exactly how og118 spent every turn claiming
685
+ * "og118" answered while an element actually did.
357
686
  */
358
687
 
359
- /** A user message, ready to render optimistically the instant the user sends. */
360
- declare function makeUserMessage(text: string): ChatMessage;
688
+ /** A user message, ready to render optimistically the instant the user sends.
689
+ * `images` attaches vision input (OG118-IMAGE-UPLOAD-1); empty/absent folds to
690
+ * the exact text-only shape every existing consumer produces. */
691
+ declare function makeUserMessage(text: string, author: MessageAuthor, images?: MessageImage[]): ChatMessage;
692
+ /**
693
+ * Fold a finished turn's answer into an assistant message. The answer text is
694
+ * the message content; the agentic provenance (declared plan + per-step
695
+ * outcomes, tool calls, evidence) is snapshotted into `trace` so the durable
696
+ * transcript re-renders the same glass-box the live turn showed — the "see the
697
+ * execution, not just the result" differentiator survives the fold. A turn with
698
+ * no provenance at all folds with no `trace`, unchanged.
699
+ *
700
+ * Model provenance rides the TRACE, not `metadata`: persistence drops metadata
701
+ * by design (apps stash secrets there), so a model chip read from it showed on
702
+ * the live turn and vanished on reload — a badge that was never once seen after
703
+ * a refresh. It is provenance, and provenance persists.
704
+ *
705
+ * Authorship comes from the turn itself when the backend named a speaker (the
706
+ * `author` event — the resolved persona/element); `defaultAuthor` is the agent's
707
+ * own identity, used when it did not. Required, so the folded message always
708
+ * knows who spoke.
709
+ */
710
+ declare function foldAssistantTurn(turn: AgentTurnState, defaultAuthor: MessageAuthor): ChatMessage;
361
711
  /**
362
- * Fold a finished turn's answer into an assistant message. Keeps only the
363
- * material-agnostic content (no AgentTurnState snapshot) — a future gate can add
364
- * per-turn glass-box rendering without bloating the ChatMessage contract now.
365
- * Model provenance survives the fold: `turn.meta.model` lands in
366
- * `metadata.model` so a shell's badge slot ("Powered by …") has real data after
367
- * persistence, not just during the live turn.
712
+ * Union of two copies of one thread by (role, timestamp, content): every message
713
+ * of `target` plus the ones only `source` has, ordered by timestamp (stable for ties).
714
+ *
715
+ * @returns `target` itself (same reference) when `source` adds nothing.
368
716
  */
369
- declare function foldAssistantTurn(turn: AgentTurnState): ChatMessage;
717
+ declare function mergeConversationMessages(target: ChatMessage[], source: ChatMessage[]): ChatMessage[];
370
718
 
719
+ /**
720
+ * Per-send metadata the conversation layer may hand the transport. Optional and
721
+ * backward-compatible — a transport that ignores it behaves exactly as before.
722
+ */
723
+ interface AgentSendMeta {
724
+ /**
725
+ * The confirmed conversation so far (prior user/assistant turns, NOT the
726
+ * message being sent). A transport with a stateless/storeless backend replays
727
+ * this for continuity — the og118 canary: the durable transcript lives in the
728
+ * client (IndexedDB), so continuity survives a recycled backend. It is
729
+ * conversational CONTEXT only; the backend re-sanitizes it and never treats it
730
+ * as authorization.
731
+ */
732
+ history?: ChatMessage[];
733
+ /**
734
+ * Images attached to THIS send (OG118-IMAGE-UPLOAD-1) — vision input for the
735
+ * current turn. The transport forwards them to its backend as image content
736
+ * blocks; a transport that ignores `meta` behaves exactly as before.
737
+ */
738
+ images?: MessageImage[];
739
+ }
371
740
  /**
372
741
  * AgentHook — the agentic-turn contract the fi-glass agent panels consume.
373
742
  *
@@ -386,14 +755,261 @@ interface AgentHook {
386
755
  turn: AgentTurnState;
387
756
  /** Whether a turn is actively streaming. */
388
757
  isStreaming: boolean;
389
- /** Start an agentic turn. */
390
- send: (message: string, metadata?: object) => Promise<void>;
758
+ /** Start an agentic turn. `meta.history` lets the conversation layer replay
759
+ * prior turns for continuity on a storeless backend (see {@link AgentSendMeta}). */
760
+ send: (message: string, meta?: AgentSendMeta) => Promise<void>;
391
761
  /** Abort the in-flight turn, if supported. */
392
762
  abort?: () => void;
393
763
  /** Reset the session/turn. */
394
764
  reset?: () => void;
395
765
  }
396
766
 
767
+ /**
768
+ * DO NOT EDIT — generated from the fi-runner event contract.
769
+ *
770
+ * Source of truth: apps/packages/fi-runner/fi_runner/events.py
771
+ * Schema: apps/packages/fi-runner/contracts/agent-events.schema.json
772
+ * Regenerate: pnpm --filter @free-intelligence/core gen:events
773
+ *
774
+ * These are the RAW WIRE frames as fi-runner emits them (snake_case, three
775
+ * envelope shapes). They are NOT the core AgentStreamEvent — that one is the
776
+ * normalized, camelCase contract the reducer consumes. The translation between
777
+ * them lives in the consumer's mapEvent, and now it maps FROM a typed wire
778
+ * frame instead of from `Record<string, unknown>` guesswork.
779
+ */
780
+ /**
781
+ * The fi-runner agent stream contract. Generated from fi_runner/events.py — do not edit by hand.
782
+ */
783
+ type AgentStreamEvent = OpenEvent | ElementEvent | TextEvent | ToolCallEvent | ResultEvent | PlanEvent | StepStartedEvent | StepDoneEvent | StepNotedEvent | PlanAmendedEvent | PlanCancelledEvent | PlanCompletedEvent | PlanFailedEvent | PlanRejectedEvent | ErrorEvent | PingEvent | DeferredEvent | DoneEvent;
784
+ /**
785
+ * First frame of every stream. Carries the id a UI keys concurrent turns on.
786
+ */
787
+ interface OpenEvent {
788
+ type?: 'open';
789
+ request_id?: string | null;
790
+ }
791
+ /**
792
+ * Announces WHO is answering, before any token arrives.
793
+ */
794
+ interface ElementEvent {
795
+ type?: 'element';
796
+ element: ElementPayload;
797
+ }
798
+ /**
799
+ * Which persona/element answered this turn.
800
+ *
801
+ * ``label`` is the composed one-liner ("53 · I · Yodo"); the parts ride
802
+ * alongside it so a UI can attribute a bubble without re-parsing that string —
803
+ * ``name`` is the speaker's name, ``symbol`` the avatar token, ``engine`` the
804
+ * persona/engine behind it. Optional: a runner that only knows an id/label
805
+ * still emits a valid frame.
806
+ */
807
+ interface ElementPayload {
808
+ id: string;
809
+ label: string;
810
+ name?: string | null;
811
+ symbol?: string | null;
812
+ engine?: string | null;
813
+ }
814
+ /**
815
+ * A token delta. Consumers append; they never replace.
816
+ */
817
+ interface TextEvent {
818
+ type?: 'text';
819
+ text: string;
820
+ }
821
+ interface ToolCallEvent {
822
+ type?: 'tool_call';
823
+ tool: ToolCallPayload;
824
+ }
825
+ /**
826
+ * One tool invocation, mirroring :class:`fi_runner.backend.ToolCall`.
827
+ *
828
+ * ``input`` may carry PHI and is never placed in telemetry; it stays on the
829
+ * wire only because the glass-box panel renders it for the operator.
830
+ */
831
+ interface ToolCallPayload {
832
+ name: string;
833
+ server?: string | null;
834
+ input?: {
835
+ [k: string]: unknown;
836
+ } | null;
837
+ id?: string | null;
838
+ is_error?: boolean | null;
839
+ duration_ms?: number | null;
840
+ }
841
+ interface ResultEvent {
842
+ type?: 'result';
843
+ result: TurnResultPayload;
844
+ }
845
+ /**
846
+ * The settled result of a turn, mirroring :class:`fi_runner.backend.TurnResult`.
847
+ *
848
+ * ``model`` is the model that ACTUALLY ran (the retry loop may escalate to the
849
+ * fallback), so a UI shows the answer's real provenance instead of guessing at
850
+ * the configured default.
851
+ *
852
+ * ``reactions`` are the emoji the speaker put ON the turn (an engine with a
853
+ * reaction channel, like a Discord persona). A gesture, not content: a turn
854
+ * with empty ``text`` and reactions is a settled answer, not an empty one.
855
+ */
856
+ interface TurnResultPayload {
857
+ text: string;
858
+ usage?: {
859
+ [k: string]: unknown;
860
+ } | null;
861
+ session_id?: string | null;
862
+ model?: string | null;
863
+ guard_outcomes?: {
864
+ [k: string]: unknown;
865
+ };
866
+ tool_calls?: ToolCallPayload[];
867
+ reactions?: string[];
868
+ }
869
+ /**
870
+ * The agent declared its plan. ``steps`` is the checklist a UI renders.
871
+ */
872
+ interface PlanEvent {
873
+ type?: 'plan';
874
+ data: PlanData;
875
+ }
876
+ interface PlanData {
877
+ steps: string[];
878
+ session_id?: string | null;
879
+ request_id?: string | null;
880
+ }
881
+ interface StepStartedEvent {
882
+ type?: 'step_started';
883
+ data: StepStartedData;
884
+ }
885
+ interface StepStartedData {
886
+ plan_id?: string | null;
887
+ step_index: number;
888
+ request_id?: string | null;
889
+ }
890
+ interface StepDoneEvent {
891
+ type?: 'step_done';
892
+ data: StepDoneData;
893
+ }
894
+ /**
895
+ * ``summary`` accompanies a ``done`` step; ``error`` a failed/cancelled one.
896
+ */
897
+ interface StepDoneData {
898
+ plan_id?: string | null;
899
+ step_index: number;
900
+ status: 'done' | 'failed' | 'cancelled';
901
+ summary?: string | null;
902
+ error?: string | null;
903
+ request_id?: string | null;
904
+ }
905
+ interface StepNotedEvent {
906
+ type?: 'step_noted';
907
+ data: StepNotedData;
908
+ }
909
+ interface StepNotedData {
910
+ plan_id?: string | null;
911
+ step_index: number;
912
+ note: string;
913
+ request_id?: string | null;
914
+ }
915
+ interface PlanAmendedEvent {
916
+ type?: 'plan_amended';
917
+ data: PlanAmendedData;
918
+ }
919
+ interface PlanAmendedData {
920
+ plan_id?: string | null;
921
+ action: 'insert' | 'replan';
922
+ request_id?: string | null;
923
+ }
924
+ interface PlanCancelledEvent {
925
+ type?: 'plan_cancelled';
926
+ data: PlanCancelledData;
927
+ }
928
+ interface PlanCancelledData {
929
+ plan_id?: string | null;
930
+ reason?: string;
931
+ request_id?: string | null;
932
+ }
933
+ interface PlanCompletedEvent {
934
+ type?: 'plan_completed';
935
+ data: PlanTerminalData;
936
+ }
937
+ /**
938
+ * Counters for the terminal plan frame.
939
+ *
940
+ * They default to ``0`` rather than being optional on purpose: a consumer must
941
+ * never receive ``undefined`` here and coerce it silently. The emitter fills
942
+ * real counts whenever the observer ran.
943
+ */
944
+ interface PlanTerminalData {
945
+ plan_id?: string | null;
946
+ completed_count?: number;
947
+ failed_count?: number;
948
+ cancelled_count?: number;
949
+ request_id?: string | null;
950
+ }
951
+ interface PlanFailedEvent {
952
+ type?: 'plan_failed';
953
+ data: PlanTerminalData;
954
+ }
955
+ interface PlanRejectedEvent {
956
+ type?: 'plan_rejected';
957
+ data: PlanRejectedData;
958
+ }
959
+ /**
960
+ * A plan guard refused the declared plan before any step ran.
961
+ */
962
+ interface PlanRejectedData {
963
+ reason: string;
964
+ matched?: GuardMatch[];
965
+ reinforcement?: string | null;
966
+ guard?: string | null;
967
+ request_id?: string | null;
968
+ }
969
+ interface GuardMatch {
970
+ index: number;
971
+ label: string;
972
+ [k: string]: unknown;
973
+ }
974
+ /**
975
+ * The turn died. Terminal — no ``done`` follows a fatal error.
976
+ */
977
+ interface ErrorEvent {
978
+ type?: 'error';
979
+ message: string;
980
+ }
981
+ /**
982
+ * A sign of life while the turn is QUIET.
983
+ *
984
+ * A client's idle watchdog cannot tell "the model is thinking" from "the
985
+ * backend hung" — both look like silence. And silence is normal here: a turn
986
+ * proxied to an external engine emits NOTHING until the whole answer lands
987
+ * (up to the proxy's live wait), while a local turn can think far longer
988
+ * than a token gap.
989
+ * Without this frame the client kills healthy turns and throws away what the
990
+ * user wrote. The ping carries nothing; its arrival IS the signal.
991
+ */
992
+ interface PingEvent {
993
+ type?: 'ping';
994
+ }
995
+ /**
996
+ * The live turn was released before its answer existed (OG118-EXTERNAL-TURN-1).
997
+ *
998
+ * A proxied engine kept working past the stream's live wait. The answer lands
999
+ * in the conversation record out of band, so the stream ends after this frame
1000
+ * with no text: the client folds no bubble and shows a waiting notice until
1001
+ * the thread refreshes. Carries nothing; its arrival is the signal.
1002
+ */
1003
+ interface DeferredEvent {
1004
+ type?: 'deferred';
1005
+ }
1006
+ /**
1007
+ * Last frame of a healthy stream.
1008
+ */
1009
+ interface DoneEvent {
1010
+ type?: 'done';
1011
+ }
1012
+
397
1013
  /**
398
1014
  * ConversationRecord — the persisted shape of one local-first conversation.
399
1015
  *
@@ -408,8 +1024,13 @@ interface AgentHook {
408
1024
  interface ConversationRecord {
409
1025
  /** Stable id. Doubles as the backend session_id for the same thread. */
410
1026
  id: string;
411
- /** Human-readable title, derived from the first user message. */
1027
+ /** Human-readable title. Derived from the first user message unless the user
1028
+ * renamed it, in which case `titleCustom` is set and the title is preserved
1029
+ * across future message persists. */
412
1030
  title: string;
1031
+ /** True when the user explicitly renamed this conversation. A custom title is
1032
+ * never re-derived from messages on persist. Absent/false ⇒ auto-derived. */
1033
+ titleCustom?: boolean;
413
1034
  /** ISO 8601 creation timestamp. */
414
1035
  createdAt: string;
415
1036
  /** ISO 8601 timestamp of the last change. */
@@ -418,6 +1039,24 @@ interface ConversationRecord {
418
1039
  messages: ChatMessage[];
419
1040
  /** Snippet of the last non-empty message, for the sidebar. */
420
1041
  preview: string;
1042
+ /** ISO 8601 timestamp of when the user pinned this conversation. Absent ⇒ not
1043
+ * pinned. A timestamp (not a boolean) so the pinned section orders by
1044
+ * last-pinned first without a separate counter. */
1045
+ pinnedAt?: string;
1046
+ /** ISO 8601 timestamp of when the user archived this conversation. Absent ⇒
1047
+ * active. Archiving is the reversible alternative to delete: the record keeps
1048
+ * its messages and moves to the archived section. */
1049
+ archivedAt?: string;
1050
+ /**
1051
+ * The resource (og118: a Project) this conversation was BORN in — the same
1052
+ * `projectId` the server stores, so the name matches the wire rather than
1053
+ * inventing a client-side alias nobody could grep for.
1054
+ *
1055
+ * Stamped once, at first persist, and preserved from then on. It is not "the
1056
+ * currently selected project": moving the selection later must not silently
1057
+ * re-file yesterday's conversations under today's project.
1058
+ */
1059
+ projectId?: string;
421
1060
  /** Schema version of this record, for forward migrations. */
422
1061
  schemaVersion: number;
423
1062
  }
@@ -428,30 +1067,11 @@ interface ConversationSummary {
428
1067
  createdAt: string;
429
1068
  updatedAt: string;
430
1069
  preview: string;
431
- }
432
-
433
- /**
434
- * ConversationLibrary — the storage contract for local-first conversations.
435
- *
436
- * A pure async interface: adapters implement it over IndexedDB (fi-glass), a
437
- * backend, or filesystem (later layers) without core taking a dependency on any
438
- * of them. `list` returns light summaries (cheap); `get` hydrates one full
439
- * record; `put` upserts; `delete`/`clear` remove. Keeping the contract in core
440
- * is what stops a reusable persistence primitive from being trapped in a
441
- * consumer app (DD-002-LESSON / framework-first-canary).
442
- */
443
-
444
- interface ConversationLibrary {
445
- /** All conversations as light summaries, newest `updatedAt` first. */
446
- list(): Promise<ConversationSummary[]>;
447
- /** The full record for `id`, or `null` if none. */
448
- get(id: string): Promise<ConversationRecord | null>;
449
- /** Insert or replace a record by its `id`. */
450
- put(record: ConversationRecord): Promise<void>;
451
- /** Remove the record for `id` (no-op if absent). */
452
- delete(id: string): Promise<void>;
453
- /** Remove every stored conversation. */
454
- clear(): Promise<void>;
1070
+ pinnedAt?: string;
1071
+ archivedAt?: string;
1072
+ /** Rides the SUMMARY too: a per-resource list filters the light rows, and
1073
+ * pulling full records just to read one field would cost every transcript. */
1074
+ projectId?: string;
455
1075
  }
456
1076
 
457
1077
  /**
@@ -472,8 +1092,21 @@ interface ConversationLibrary {
472
1092
  /** Schema version stamped on every record created here. */
473
1093
  declare const CONVERSATION_SCHEMA_VERSION = 1;
474
1094
  /**
475
- * Reduce a ChatMessage to the only fields safe to persist: role, content, and
476
- * timestamp. Drops id, thinking, metadata, and anything else by construction.
1095
+ * Reduce a ChatMessage to the fields safe to persist: role, author, content,
1096
+ * timestamp, plus the glass-box `trace` when present (B3-FIGLASS-TRACE-
1097
+ * PERSISTENCE-1).
1098
+ *
1099
+ * Privacy by structure: `metadata` is DROPPED on purpose — apps stuff secrets
1100
+ * there (a `Bearer` token, tool payloads), so it must never reach durable
1101
+ * storage. `trace` and `author` are the deliberate exceptions, not holes in that
1102
+ * boundary: both carry only non-sensitive, already-user-visible provenance —
1103
+ * plan-step labels/summaries (model-authored, rendered live), tool NAMES (core's
1104
+ * ToolCall is {id,name,server,isError} — no arguments/payloads), source URLs,
1105
+ * and the public name of the persona that spoke. Persisting what the live turn
1106
+ * already showed leaks nothing new — and dropping the author would re-anonymize
1107
+ * every bubble on reload, which is the bug the contract exists to prevent.
1108
+ * Included only when present, so a plain message stays minimal; id, thinking and
1109
+ * metadata are still dropped by construction.
477
1110
  */
478
1111
  declare function sanitizeConversationMessage(message: ChatMessage): ChatMessage;
479
1112
  /** Title from the first non-empty user message; `DEFAULT_TITLE` otherwise. */
@@ -491,7 +1124,169 @@ interface CreateConversationRecordArgs {
491
1124
  }
492
1125
  /** Build a fresh, sanitized record with derived title + preview. */
493
1126
  declare function createConversationRecord(args: CreateConversationRecordArgs): ConversationRecord;
1127
+ /**
1128
+ * Resolve the title to stamp when persisting messages: a user-set (custom)
1129
+ * title is preserved; otherwise it is derived from the messages. This is the
1130
+ * SSOT that keeps `persist` from clobbering a rename on the next message.
1131
+ */
1132
+ declare function resolveConversationTitle(messages: ChatMessage[], prev?: {
1133
+ title: string;
1134
+ titleCustom?: boolean;
1135
+ }): string;
1136
+ /**
1137
+ * The metadata delta of an organization mutation (rename / pin / archive).
1138
+ *
1139
+ * These three mutations used to exist only as whole-record transforms, which
1140
+ * forced every transport to ship the whole record — and a whole-record write
1141
+ * from a device holding a stale copy silently drops the flags it never meant to
1142
+ * touch (CONV-CONCURRENCY-1). The delta expresses the same semantics as the
1143
+ * SMALLEST thing that changed, so a transport can send just that.
1144
+ *
1145
+ * `null` means CLEAR the field; an omitted key means LEAVE IT ALONE. That is
1146
+ * precisely the distinction a full-record put cannot express — an absent field
1147
+ * and a deliberately-cleared one look identical on the wire.
1148
+ */
1149
+ interface ConversationMetadataPatch {
1150
+ title?: string;
1151
+ titleCustom?: boolean;
1152
+ /** ISO timestamp to pin at, or `null` to unpin. */
1153
+ pinnedAt?: string | null;
1154
+ /** ISO timestamp to archive at, or `null` to unarchive. */
1155
+ archivedAt?: string | null;
1156
+ /** Only a rename stamps this: pinning/archiving must not fake recency. */
1157
+ updatedAt?: string;
1158
+ }
1159
+ /**
1160
+ * Apply a metadata delta to a record. `null` clears the field, an omitted key
1161
+ * leaves it untouched. Pure — the single place the merge rule is written, so the
1162
+ * local (apply-then-put) and remote (send-the-delta) paths cannot drift.
1163
+ */
1164
+ declare function applyConversationMetadataPatch(record: ConversationRecord, patch: ConversationMetadataPatch): ConversationRecord;
1165
+ /**
1166
+ * The delta of a user rename. A non-empty title is stored verbatim (trimmed,
1167
+ * whitespace-collapsed, capped at TITLE_MAX) and marks the record `titleCustom`
1168
+ * so future persists never re-derive it. An empty/whitespace title reverts to
1169
+ * the derived title and clears the custom flag (emptyTitlePolicy:
1170
+ * revert-to-derived). Needs the record because reverting has to re-derive from
1171
+ * its messages.
1172
+ */
1173
+ declare function conversationRenamePatch(record: ConversationRecord, rawTitle: string, now?: string): ConversationMetadataPatch;
1174
+ /**
1175
+ * The delta of a pin/unpin. Pinning lifts the record out of the archive — a pin
1176
+ * is an explicit "keep this in front of me", incompatible with archived.
1177
+ * `updatedAt` is deliberately absent: pinning is organization, not content, and
1178
+ * must not fake recency in the active list.
1179
+ */
1180
+ declare function conversationPinPatch(pinned: boolean, now?: string): ConversationMetadataPatch;
1181
+ /**
1182
+ * The delta of an archive/unarchive. Archiving clears any pin (an archived
1183
+ * conversation cannot stay in the pinned section). Unarchiving rejoins the
1184
+ * active list at the record's own `updatedAt`, which — like pinning — is not
1185
+ * touched.
1186
+ */
1187
+ declare function conversationArchivePatch(archived: boolean, now?: string): ConversationMetadataPatch;
1188
+ /**
1189
+ * Apply a user rename to a record. Thin composition of the delta and the merge
1190
+ * rule above — kept so callers holding a whole record (the local, single-writer
1191
+ * path) do not each re-implement it.
1192
+ */
1193
+ declare function renameConversationRecord(record: ConversationRecord, rawTitle: string, now?: string): ConversationRecord;
1194
+ /** Pin or unpin a record (whole-record form of `conversationPinPatch`). */
1195
+ declare function setConversationPinned(record: ConversationRecord, pinned: boolean, now?: string): ConversationRecord;
1196
+ /** Archive or unarchive a record (whole-record form of `conversationArchivePatch`). */
1197
+ declare function setConversationArchived(record: ConversationRecord, archived: boolean, now?: string): ConversationRecord;
494
1198
  /** Project a record to its light summary — excludes `messages`. */
495
1199
  declare function summarizeConversation(record: ConversationRecord): ConversationSummary;
1200
+ /**
1201
+ * Filter summaries by a free-text query over title + preview (CONV-SEARCH-1).
1202
+ * Case- and diacritic-insensitive; every whitespace-separated term must match
1203
+ * somewhere (AND semantics). An empty/whitespace query returns the input
1204
+ * untouched. Pure — feed the result to {@link organizeConversationSummaries}.
1205
+ */
1206
+ declare function filterConversationSummaries(summaries: ConversationSummary[], query: string): ConversationSummary[];
1207
+ /** The sidebar's three sections, each already in display order. */
1208
+ interface OrganizedConversations {
1209
+ /** Pinned, last-pinned first. */
1210
+ pinned: ConversationSummary[];
1211
+ /** Neither pinned nor archived, most recently updated first. */
1212
+ active: ConversationSummary[];
1213
+ /** Archived, most recently archived first. */
1214
+ archived: ConversationSummary[];
1215
+ }
1216
+ /**
1217
+ * Split summaries into the pinned / active / archived sections every sidebar
1218
+ * renders. Pure and total: a summary lands in exactly one section (`archivedAt`
1219
+ * wins over a stray `pinnedAt`, though the pin/archive transformers never
1220
+ * produce that state). ISO 8601 timestamps sort lexicographically.
1221
+ */
1222
+ declare function organizeConversationSummaries(summaries: ConversationSummary[]): OrganizedConversations;
1223
+
1224
+ /**
1225
+ * ConversationLibrary — the storage contract for local-first conversations.
1226
+ *
1227
+ * A pure async interface: adapters implement it over IndexedDB (fi-glass), a
1228
+ * backend, or filesystem (later layers) without core taking a dependency on any
1229
+ * of them. `list` returns light summaries (cheap); `get` hydrates one full
1230
+ * record; `put` upserts; `delete`/`clear` remove. Keeping the contract in core
1231
+ * is what stops a reusable persistence primitive from being trapped in a
1232
+ * consumer app (DD-002-LESSON / framework-first-canary).
1233
+ */
1234
+
1235
+ interface ConversationLibrary {
1236
+ /** All conversations as light summaries, newest `updatedAt` first. */
1237
+ list(): Promise<ConversationSummary[]>;
1238
+ /** The full record for `id`, or `null` if none. */
1239
+ get(id: string): Promise<ConversationRecord | null>;
1240
+ /** Insert or replace a record by its `id`. */
1241
+ put(record: ConversationRecord): Promise<void>;
1242
+ /**
1243
+ * Apply a metadata-only delta (rename / pin / archive) to `id`.
1244
+ *
1245
+ * OPTIONAL, and duck-typed by callers, because it only earns its keep where
1246
+ * more than one writer exists. A single-browser adapter (IndexedDB) has no
1247
+ * second writer to race, so `get → transform → put` is already correct there
1248
+ * and an extra verb would be ceremony. A shared backend does have one, and
1249
+ * there a whole-record put from a stale device silently drops flags it never
1250
+ * meant to touch — the delta is what makes that impossible.
1251
+ */
1252
+ patch?(id: string, patch: ConversationMetadataPatch): Promise<ConversationRecord | null>;
1253
+ /** Remove the record for `id` (no-op if absent). */
1254
+ delete(id: string): Promise<void>;
1255
+ /** Remove every stored conversation. */
1256
+ clear(): Promise<void>;
1257
+ }
1258
+
1259
+ /**
1260
+ * conversationToMarkdown — la conversación como un archivo que alguien se lleva.
1261
+ *
1262
+ * Función pura sobre el record: sin React, sin navegador, sin descarga. Quien
1263
+ * quiera entregarlo (un Blob en el browser, un archivo en disco, un adjunto de
1264
+ * correo) pone ESA parte; aquí sólo vive la forma del documento, que es lo que
1265
+ * se repite en cada shell.
1266
+ *
1267
+ * Markdown y no PDF ni HTML porque el destino real es seguir trabajando: se
1268
+ * pega en un cuaderno digital, se abre en cualquier editor, se lee tal cual en
1269
+ * texto plano si no hay nada más a la mano.
1270
+ */
1271
+
1272
+ interface ConversationMarkdownOptions {
1273
+ /** Cómo se nombra a cada lado. Default: `Tú` / `Asistente`. */
1274
+ labels?: {
1275
+ user?: string;
1276
+ assistant?: string;
1277
+ };
1278
+ /** Línea de procedencia bajo el título (de dónde salió esta conversación). */
1279
+ source?: string;
1280
+ }
1281
+ /** El documento completo, listo para escribir a un archivo `.md`. */
1282
+ declare function conversationToMarkdown(record: ConversationRecord, options?: ConversationMarkdownOptions): string;
1283
+ /**
1284
+ * Un nombre de archivo seguro derivado del título.
1285
+ *
1286
+ * Los títulos vienen del primer mensaje del usuario, así que traen de todo:
1287
+ * `/`, `:`, saltos de línea, emoji. Un nombre sin sanear rompe la descarga en
1288
+ * silencio o crea directorios que nadie pidió.
1289
+ */
1290
+ declare function conversationFileName(record: ConversationRecord): string;
496
1291
 
497
- export { type AgentHook, type AgentMeta, type AgentPlan, type AgentStreamEvent, type AgentTurnState, type AgentTurnStatus, type AudioSource, CONVERSATION_SCHEMA_VERSION, type ChatHook, type ChatMessage, type ChatStreamingState, type ConversationLibrary, type ConversationRecord, type ConversationSummary, type CreateConversationRecordArgs, type GuardLevel, type GuardRejection, type PlanOutcome, type PlanStep, type StepStatus, type ThemeTokens, type ToolCall, type TranscribeContext, type TranscriptResult, type VoiceAdapter, type VoiceOption, applyAgentEvent, createConversationRecord, deriveConversationPreview, deriveConversationTitle, foldAssistantTurn, initialAgentTurnState, makeUserMessage, sanitizeConversationMessage, summarizeConversation };
1292
+ export { type AgentHook, type AgentMeta, type AgentPlan, type AgentSendMeta, type AgentStreamEvent$1 as AgentStreamEvent, type AgentTurnState, type AgentTurnStatus, type AgentStreamEvent as AgentWireEvent, type AudioSource, CONVERSATION_SCHEMA_VERSION, COPY, type ChatHook, type ChatMessage, type ChatStreamingState, type ConversationEvent, type ConversationLibrary, type ConversationMarkdownOptions, type ConversationMetadataPatch, type ConversationRecord, type ConversationState, type ConversationSummary, type CreateConversationRecordArgs, type GuardLevel, type GuardRejection, type MessageAuthor, type MessageImage, type MessageTrace, type OrganizedConversations, type PlanOutcome, type PlanStep, type StepStatus, type ThemeTokens, type ToolCall, type TranscribeContext, type TranscriptResult, type TurnFailure, type TurnNotice, type UnsentDraft, type VoiceAdapter, type VoiceOption, type DoneEvent as WireDoneEvent, type ElementEvent as WireElementEvent, type ErrorEvent as WireErrorEvent, type OpenEvent as WireOpenEvent, type PlanAmendedEvent as WirePlanAmendedEvent, type PlanCancelledEvent as WirePlanCancelledEvent, type PlanCompletedEvent as WirePlanCompletedEvent, type PlanEvent as WirePlanEvent, type PlanFailedEvent as WirePlanFailedEvent, type PlanRejectedEvent as WirePlanRejectedEvent, type ResultEvent as WireResultEvent, type StepDoneEvent as WireStepDoneEvent, type StepNotedEvent as WireStepNotedEvent, type StepStartedEvent as WireStepStartedEvent, type TextEvent as WireTextEvent, type ToolCallEvent as WireToolCallEvent, applyAgentEvent, applyConversationEvent, applyConversationMetadataPatch, conversationArchivePatch, conversationFileName, conversationPinPatch, conversationRenamePatch, conversationToMarkdown, createConversationRecord, deriveConversationPreview, deriveConversationTitle, filterConversationSummaries, foldAssistantTurn, fromWireEvent, initialAgentTurnState, initialConversationState, makeUserMessage, mergeConversationMessages, organizeConversationSummaries, renameConversationRecord, resolveConversationTitle, sanitizeConversationMessage, setConversationArchived, setConversationPinned, summarizeConversation, takeSseFrames };