@free-intelligence/core 1.3.0 → 1.12.1

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,320 @@
1
+ /**
2
+ * The conversation machine, exercised WITHOUT React.
3
+ *
4
+ * Every rule below used to require mounting a hook and driving a fake transport
5
+ * to observe. They are not React rules — they are conversation rules, and this
6
+ * file is the evidence that moving them into core made them directly testable.
7
+ */
8
+
9
+ import { describe, it, expect } from 'vitest';
10
+ import {
11
+ initialConversationState,
12
+ applyConversationEvent,
13
+ type ConversationState,
14
+ } from './conversation-state';
15
+ import { initialAgentTurnState } from './state';
16
+ import type { AgentTurnState } from './state';
17
+ import type { MessageAuthor } from './events';
18
+
19
+ const AGENT: MessageAuthor = { id: 'og118', name: 'og118', symbol: 'og' };
20
+ const USER: MessageAuthor = { id: 'user', name: 'Tú', symbol: 'Tú' };
21
+
22
+ const send = (s: ConversationState, text: string, images?: { mediaType: string; data: string }[]) =>
23
+ applyConversationEvent(s, { type: 'send', text, images, author: USER, controlled: false });
24
+
25
+ const settledTurn = (text: string): AgentTurnState => ({
26
+ ...initialAgentTurnState(),
27
+ text,
28
+ status: 'done',
29
+ });
30
+
31
+ describe('the optimistic push', () => {
32
+ it('adds the user message and marks the change un-persistable', () => {
33
+ const s = send(initialConversationState(), 'hola');
34
+ expect(s.messages).toHaveLength(1);
35
+ expect(s.messages[0].role).toBe('user');
36
+ expect(s.pending).toBe(true);
37
+ // An optimistic push is NOT a confirmed turn; persisting it would leave a
38
+ // durable lone user message if the turn then failed.
39
+ expect(s.skipPersist).toBe(true);
40
+ });
41
+
42
+ it('a controlled shell gets no optimistic push (its consumer owns the thread)', () => {
43
+ const s = applyConversationEvent(initialConversationState(), {
44
+ type: 'send',
45
+ text: 'hola',
46
+ author: USER,
47
+ controlled: true,
48
+ });
49
+ expect(s.messages).toHaveLength(0);
50
+ expect(s.pending).toBe(true);
51
+ });
52
+
53
+ it('an image-only send is valid — the picture IS the message', () => {
54
+ const s = send(initialConversationState(), '', [{ mediaType: 'image/png', data: 'AAA' }]);
55
+ expect(s.messages).toHaveLength(1);
56
+ expect(s.lastSent?.images).toHaveLength(1);
57
+ });
58
+
59
+ it('a truly empty send is a no-op', () => {
60
+ const before = initialConversationState();
61
+ expect(send(before, ' ')).toBe(before);
62
+ });
63
+ });
64
+
65
+ describe('a failed turn must never cost the user their words', () => {
66
+ it('hands back the TEXT on a transport failure', () => {
67
+ let s = send(initialConversationState(), 'un prompt que me costó escribir');
68
+ s = applyConversationEvent(s, { type: 'turn_failed', controlled: false });
69
+ expect(s.messages).toHaveLength(0);
70
+ expect(s.unsent.text).toBe('un prompt que me costó escribir');
71
+ expect(s.failure?.kind).toBe('stream');
72
+ });
73
+
74
+ it('hands back the IMAGES too — the composer already cleared its drafts', () => {
75
+ const img = { mediaType: 'image/png', data: 'BASE64' };
76
+ let s = send(initialConversationState(), 'mira esto', [img]);
77
+ s = applyConversationEvent(s, { type: 'turn_timeout', controlled: false });
78
+ expect(s.unsent.text).toBe('mira esto');
79
+ expect(s.unsent.images).toEqual([img]);
80
+ });
81
+
82
+ it('reverts on a timeout and refuses to re-arm afterwards', () => {
83
+ let s = send(initialConversationState(), 'hola');
84
+ s = applyConversationEvent(s, { type: 'turn_timeout', controlled: false });
85
+ expect(s.timedOut).toBe(true);
86
+ expect(s.failure?.kind).toBe('timeout');
87
+ const again = applyConversationEvent(s, { type: 'turn_timeout', controlled: false });
88
+ expect(again).toBe(s);
89
+ });
90
+
91
+ it('an app-handled error still REVERTS, it only suppresses the generic banner', () => {
92
+ let s = send(initialConversationState(), 'hola');
93
+ s = applyConversationEvent(s, { type: 'turn_failed', controlled: false, appHandled: true });
94
+ // The words come back either way — the app owning the banner must not cost
95
+ // the user their prompt.
96
+ expect(s.unsent.text).toBe('hola');
97
+ expect(s.failure).toBeNull();
98
+ });
99
+
100
+ it('a new send supersedes a draft still waiting to be recovered', () => {
101
+ let s = send(initialConversationState(), 'primero');
102
+ s = applyConversationEvent(s, { type: 'turn_failed', controlled: false });
103
+ expect(s.unsent.text).toBe('primero');
104
+ s = send(s, 'segundo');
105
+ expect(s.unsent).toEqual({ text: null, images: null });
106
+ });
107
+
108
+ it('clear_unsent drops BOTH channels (a half-clear re-attaches a ghost)', () => {
109
+ let s = send(initialConversationState(), 'con foto', [{ mediaType: 'image/png', data: 'A' }]);
110
+ s = applyConversationEvent(s, { type: 'turn_failed', controlled: false });
111
+ s = applyConversationEvent(s, { type: 'clear_unsent' });
112
+ expect(s.unsent).toEqual({ text: null, images: null });
113
+ });
114
+
115
+ it('retry can replay the whole message, images included', () => {
116
+ const img = { mediaType: 'image/png', data: 'A' };
117
+ let s = send(initialConversationState(), 'con foto', [img]);
118
+ s = applyConversationEvent(s, { type: 'turn_failed', controlled: false });
119
+ expect(s.lastSent).toEqual({ text: 'con foto', images: [img] });
120
+ });
121
+ });
122
+
123
+ describe('the fold', () => {
124
+ it('folds the assistant turn and marks the change persistable', () => {
125
+ let s = send(initialConversationState(), 'hola');
126
+ s = applyConversationEvent(s, {
127
+ type: 'turn_settled',
128
+ turn: settledTurn('qué tal'),
129
+ author: AGENT,
130
+ controlled: false,
131
+ });
132
+ expect(s.messages).toHaveLength(2);
133
+ expect(s.messages[1].role).toBe('assistant');
134
+ expect(s.pending).toBe(false);
135
+ // A settled turn IS confirmed — user + assistant persist together.
136
+ expect(s.skipPersist).toBe(false);
137
+ });
138
+
139
+ it('a controlled shell never folds', () => {
140
+ let s = applyConversationEvent(initialConversationState(), {
141
+ type: 'send',
142
+ text: 'hola',
143
+ author: USER,
144
+ controlled: true,
145
+ });
146
+ s = applyConversationEvent(s, {
147
+ type: 'turn_settled',
148
+ turn: settledTurn('qué tal'),
149
+ author: AGENT,
150
+ controlled: true,
151
+ });
152
+ expect(s.messages).toHaveLength(0);
153
+ });
154
+
155
+ it('a settle with no pending turn changes nothing', () => {
156
+ const s = initialConversationState();
157
+ expect(
158
+ applyConversationEvent(s, {
159
+ type: 'turn_settled',
160
+ turn: settledTurn('x'),
161
+ author: AGENT,
162
+ controlled: false,
163
+ }),
164
+ ).toBe(s);
165
+ });
166
+
167
+ it('an empty-text settle is a failure: the turn reverts and the draft comes back', () => {
168
+ let s = send(initialConversationState(), 'hola');
169
+ s = applyConversationEvent(s, {
170
+ type: 'turn_settled',
171
+ turn: settledTurn(''),
172
+ author: AGENT,
173
+ controlled: false,
174
+ });
175
+ expect(s.messages).toHaveLength(0);
176
+ expect(s.pending).toBe(false);
177
+ expect(s.failure?.kind).toBe('empty');
178
+ expect(s.unsent.text).toBe('hola');
179
+ expect(s.lastSent?.text).toBe('hola');
180
+ });
181
+
182
+ it('a user stop that settles empty keeps the message and raises nothing', () => {
183
+ let s = send(initialConversationState(), 'hola');
184
+ s = applyConversationEvent(s, {
185
+ type: 'turn_settled', turn: settledTurn(''), author: AGENT, controlled: false, stopped: true,
186
+ });
187
+ expect(s.messages).toHaveLength(1);
188
+ expect(s.failure).toBeNull();
189
+ expect(s.pending).toBe(false);
190
+ });
191
+
192
+ it('a controlled shell gets no revert and no failure for an empty settle', () => {
193
+ let s = applyConversationEvent(initialConversationState(), { type: 'send', text: 'hola', author: USER, controlled: true });
194
+ s = applyConversationEvent(s, {
195
+ type: 'turn_settled',
196
+ turn: settledTurn(''),
197
+ author: AGENT,
198
+ controlled: true,
199
+ });
200
+ expect(s.failure).toBeNull();
201
+ expect(s.pending).toBe(false);
202
+ });
203
+ });
204
+
205
+ describe('hydrate + immutability', () => {
206
+ it('switching conversations drops the failure and the pending turn', () => {
207
+ let s = send(initialConversationState(), 'hola');
208
+ s = applyConversationEvent(s, { type: 'turn_failed', controlled: false });
209
+ s = applyConversationEvent(s, { type: 'hydrate', messages: [] });
210
+ expect(s.failure).toBeNull();
211
+ expect(s.pending).toBe(false);
212
+ expect(s.unsent).toEqual({ text: null, images: null });
213
+ expect(s.skipPersist).toBe(true);
214
+ });
215
+
216
+ it('never mutates the state it is given', () => {
217
+ const before = initialConversationState();
218
+ const snapshot = JSON.stringify(before);
219
+ send(before, 'hola');
220
+ expect(JSON.stringify(before)).toBe(snapshot);
221
+ });
222
+
223
+ it('skipPersist is ONE-SHOT: consuming it lets the NEXT change persist', () => {
224
+ // The bug this test exists for: an event that SET the flag instead of
225
+ // clearing it made the shell skip forever, so nothing was ever saved. The
226
+ // fi-glass persistence tests caught it; this is the unit that names it.
227
+ let s = send(initialConversationState(), 'hola');
228
+ expect(s.skipPersist).toBe(true);
229
+ s = applyConversationEvent(s, { type: 'persist_skip_consumed' });
230
+ expect(s.skipPersist).toBe(false);
231
+ // Consuming again is a no-op, not a re-arm.
232
+ expect(applyConversationEvent(s, { type: 'persist_skip_consumed' })).toBe(s);
233
+ });
234
+ });
235
+
236
+ describe('a reaction-only turn is an answer (server-bot F5)', () => {
237
+ it('folds a bubble with empty text and the reactions', () => {
238
+ let s = send(initialConversationState(), 'mira esto');
239
+ s = applyConversationEvent(s, {
240
+ type: 'turn_settled',
241
+ turn: { ...settledTurn(''), reactions: ['👀'] },
242
+ author: AGENT,
243
+ controlled: false,
244
+ });
245
+ expect(s.messages).toHaveLength(2);
246
+ expect(s.messages[1].role).toBe('assistant');
247
+ expect(s.messages[1].content).toBe('');
248
+ expect(s.messages[1].reactions).toEqual(['👀']);
249
+ expect(s.skipPersist).toBe(false);
250
+ });
251
+
252
+ it('a turn with neither text nor reactions folds nothing and fails as empty', () => {
253
+ let s = send(initialConversationState(), 'hola');
254
+ s = applyConversationEvent(s, { type: 'turn_settled', turn: settledTurn(''), author: AGENT, controlled: false });
255
+ expect(s.messages).toHaveLength(0);
256
+ expect(s.failure?.kind).toBe('empty');
257
+ });
258
+ });
259
+
260
+ describe('a deferred turn — the engine kept working past the live wait', () => {
261
+ const YODO: MessageAuthor = { id: 'yodo', name: 'Yodo', symbol: 'I' };
262
+ const deferredTurn = (author: MessageAuthor | null): AgentTurnState => ({
263
+ ...initialAgentTurnState(),
264
+ author,
265
+ deferred: true,
266
+ status: 'done',
267
+ });
268
+ const settle = (s: ConversationState, author: MessageAuthor | null) =>
269
+ applyConversationEvent(s, { type: 'turn_settled', turn: deferredTurn(author), author: AGENT, controlled: false });
270
+
271
+ it('folds no bubble, keeps the user message on screen and raises a notice naming the speaker', () => {
272
+ const s = settle(send(initialConversationState(), 'un mensaje largo'), YODO);
273
+ expect(s.messages.map((m) => m.role)).toEqual(['user']);
274
+ expect(s.pending).toBe(false);
275
+ expect(s.failure).toBeNull();
276
+ expect(s.notice).toEqual({
277
+ kind: 'deferred',
278
+ message: 'Yodo sigue escribiendo. Su respuesta aparecerá aquí en cuanto termine.',
279
+ });
280
+ expect(s.skipPersist).toBe(true);
281
+ });
282
+
283
+ it('names the default author when the backend announced none', () => {
284
+ const s = settle(send(initialConversationState(), 'hola'), null);
285
+ expect(s.notice?.message.startsWith('og118 sigue escribiendo')).toBe(true);
286
+ });
287
+
288
+ it('the notice clears on reload, on the next send, and on dismiss', () => {
289
+ const s = settle(send(initialConversationState(), 'hola'), YODO);
290
+ expect(applyConversationEvent(s, { type: 'hydrate', messages: [] }).notice).toBeNull();
291
+ expect(send(s, 'otra cosa').notice).toBeNull();
292
+ expect(applyConversationEvent(s, { type: 'dismiss_notice' }).notice).toBeNull();
293
+ });
294
+
295
+ it('an empty turn that was NOT deferred raises no notice — it fails instead', () => {
296
+ const empty: AgentTurnState = { ...initialAgentTurnState(), status: 'done' };
297
+ const s = applyConversationEvent(send(initialConversationState(), 'hola'), {
298
+ type: 'turn_settled', turn: empty, author: AGENT, controlled: false,
299
+ });
300
+ expect(s.notice).toBeNull();
301
+ expect(s.failure?.kind).toBe('empty');
302
+ });
303
+ });
304
+
305
+ describe('merge_seed', () => {
306
+ const server = (content: string, timestamp: string) => ({ id: content, role: 'assistant' as const, content, timestamp });
307
+
308
+ it('unions the server thread into a pending turn without settling it', () => {
309
+ const sent = send(initialConversationState(), 'hola');
310
+ const next = applyConversationEvent(sent, { type: 'merge_seed', messages: [server('bg', '2020-01-01T00:00:00.000Z')] });
311
+ expect(next.pending).toBe(true);
312
+ expect(next.skipPersist).toBe(true);
313
+ expect(next.messages.map((m) => m.content)).toEqual(['bg', 'hola']);
314
+ });
315
+
316
+ it('returns the same state when the seed adds nothing', () => {
317
+ const sent = send(initialConversationState(), 'hola');
318
+ expect(applyConversationEvent(sent, { type: 'merge_seed', messages: [...sent.messages] })).toBe(sent);
319
+ });
320
+ });
@@ -0,0 +1,278 @@
1
+ /**
2
+ * ConversationState — the reduced state of a whole agentic CONVERSATION (the
3
+ * thread across turns), plus the pure `applyConversationEvent` reducer that
4
+ * derives it.
5
+ *
6
+ * Sibling of {@link ./state} one level up: `AgentTurnState` reduces the wire
7
+ * events of ONE streaming turn; this reduces the lifecycle of the conversation
8
+ * those turns live in — the optimistic push, the fold, the revert that hands the
9
+ * user's words back, the recoverable-failure banners, persistence bookkeeping.
10
+ *
11
+ * WHY IT MOVED HERE (framework-first-canary, the demotion's mirror): fi-glass's
12
+ * `useAgentConversation` held this logic across 7 `useState` + 10 `useRef` in a
13
+ * 575-line hook, so the rules of the machine — "a failed turn must never cost
14
+ * the user their words", "an optimistic push is not a confirmed turn" — could
15
+ * only be exercised by mounting React and driving a fake transport. They are not
16
+ * React rules; they are conversation rules, identical for every shell. Here they
17
+ * are one value and one function, testable with plain assertions.
18
+ *
19
+ * Pure: no React, no transport, no timers, no I/O. Immutable: every event
20
+ * returns a new state object. Time enters as an EVENT (`turn_timeout`), never as
21
+ * a clock read — same discipline as the turn reducer's heartbeat counter.
22
+ */
23
+
24
+ import type { ChatMessage, MessageImage } from '../chat/message';
25
+ import type { MessageAuthor } from './events';
26
+ import type { AgentTurnState } from './state';
27
+ import { makeUserMessage, foldAssistantTurn, mergeConversationMessages } from './transcript';
28
+ import { COPY } from '../copy.generated';
29
+
30
+ /**
31
+ * A turn that settled WITHOUT its answer because the engine is still working
32
+ * (`AgentTurnState.deferred`). Not a failure: nothing to retry, the answer lands
33
+ * in the thread out of band and the shell shows this until the thread refreshes.
34
+ */
35
+ export interface TurnNotice {
36
+ kind: 'deferred';
37
+ message: string;
38
+ }
39
+
40
+ export function deferredNotice(author: MessageAuthor): TurnNotice {
41
+ return {
42
+ kind: 'deferred',
43
+ message: COPY.turnDeferredNotice(author.name),
44
+ };
45
+ }
46
+
47
+ /** Why a turn failed, in terms a shell can render a recovery banner from. */
48
+ export interface TurnFailure {
49
+ /** `empty` = the turn settled with no text, no reaction and no deferral: silence is a failure. */
50
+ kind: 'stream' | 'timeout' | 'empty';
51
+ message: string;
52
+ }
53
+
54
+ /**
55
+ * What a failed turn hands back so the shell can restore it into the composer.
56
+ * Carries the WHOLE message: returning only the text let a shell re-send a
57
+ * prompt whose images had silently ceased to exist.
58
+ */
59
+ export interface UnsentDraft {
60
+ text: string | null;
61
+ images: MessageImage[] | null;
62
+ }
63
+
64
+ /** The reduced state of the conversation. */
65
+ export interface ConversationState {
66
+ /** The visible thread. */
67
+ messages: ChatMessage[];
68
+ /** Set while an optimistically-pushed turn is still in flight; gates the fold. */
69
+ pending: boolean;
70
+ /** A recoverable turn failure the shell renders instead of a zombie panel. */
71
+ failure: TurnFailure | null;
72
+ /** The last turn was released without its answer; shown until the thread refreshes. */
73
+ notice: TurnNotice | null;
74
+ /** True once a turn timed out; keeps the watchdog from re-arming on it. */
75
+ timedOut: boolean;
76
+ /** What a failed turn handed back, for the shell to restore. */
77
+ unsent: UnsentDraft;
78
+ /** The last send, replayed verbatim by a retry (text AND images). */
79
+ lastSent: { text: string; images?: MessageImage[] } | null;
80
+ /**
81
+ * True when the current `messages` change is NOT a confirmed, settled turn
82
+ * (the mount seed, a conversation switch, the optimistic push). A shell
83
+ * persists only when this is false, so a failed turn never leaves a durable
84
+ * lone user message.
85
+ */
86
+ skipPersist: boolean;
87
+ }
88
+
89
+ export type ConversationEvent =
90
+ /** The user sent. `controlled` shells do not get an optimistic push. */
91
+ | {
92
+ type: 'send';
93
+ text: string;
94
+ images?: MessageImage[];
95
+ author: MessageAuthor;
96
+ controlled: boolean;
97
+ }
98
+ /** The transport finished cleanly. Folds the assistant turn in. */
99
+ /** `stopped`: the USER ended the turn; an empty settle is then a choice, not a failure. */
100
+ | { type: 'turn_settled'; turn: AgentTurnState; author: MessageAuthor; controlled: boolean; stopped?: boolean }
101
+ /**
102
+ * The transport reported failure. `appHandled` means the app renders its own
103
+ * banner for this error class (e.g. a 401 token gate), so the generic
104
+ * recoverable failure is suppressed — the revert still happens either way.
105
+ */
106
+ | { type: 'turn_failed'; message?: string; controlled: boolean; appHandled?: boolean }
107
+ /** The idle watchdog fired. Time as an event keeps the reducer pure. */
108
+ | { type: 'turn_timeout'; controlled: boolean }
109
+ | { type: 'dismiss_failure' }
110
+ | { type: 'dismiss_notice' }
111
+ /** The shell restored `unsent` into its composer. */
112
+ | { type: 'clear_unsent' }
113
+ /** Load a different conversation (or start a fresh one). */
114
+ | { type: 'hydrate'; messages: ChatMessage[] }
115
+ /**
116
+ * The server's copy of THIS thread arrived (a worker appended mid-turn). It is
117
+ * unioned into the live thread; the pending turn is untouched and the merge is not a confirmed turn.
118
+ */
119
+ | { type: 'merge_seed'; messages: ChatMessage[] }
120
+ /**
121
+ * The shell CONSUMED the skip: it saw `skipPersist` and declined to persist
122
+ * this change. One-shot — the flag clears so the NEXT confirmed change
123
+ * persists normally. (Getting this backwards makes the shell skip forever and
124
+ * nothing is ever saved.)
125
+ */
126
+ | { type: 'persist_skip_consumed' };
127
+
128
+ export function initialConversationState(seed: ChatMessage[] = []): ConversationState {
129
+ return {
130
+ messages: seed,
131
+ pending: false,
132
+ failure: null,
133
+ notice: null,
134
+ timedOut: false,
135
+ unsent: { text: null, images: null },
136
+ lastSent: null,
137
+ // The mount seed is not a confirmed turn.
138
+ skipPersist: true,
139
+ };
140
+ }
141
+
142
+ const NO_DRAFT: UnsentDraft = { text: null, images: null };
143
+
144
+ /**
145
+ * Revert the optimistic user message that is still the thread's tail, handing
146
+ * its content back as `unsent`.
147
+ *
148
+ * Reverting used to DESTROY what the user wrote: the message left the thread and
149
+ * existed nowhere else, so a turn the watchdog killed took the prompt with it.
150
+ * Both failure paths (transport error, timeout) route through here so neither can
151
+ * forget — and it hands back the images too, because the composer already cleared
152
+ * its drafts on send.
153
+ */
154
+ function revertOptimistic(state: ConversationState, controlled: boolean): ConversationState {
155
+ // A controlled shell never pushed an optimistic message — nothing to revert.
156
+ if (controlled) return state;
157
+ const last = state.messages[state.messages.length - 1];
158
+ if (last?.role !== 'user') return state;
159
+ return {
160
+ ...state,
161
+ messages: state.messages.slice(0, -1),
162
+ unsent: {
163
+ text: last.content,
164
+ images: last.images && last.images.length > 0 ? last.images : null,
165
+ },
166
+ };
167
+ }
168
+
169
+ /** Pure reducer: apply one conversation event, returning a new state. */
170
+ export function applyConversationEvent(
171
+ state: ConversationState,
172
+ event: ConversationEvent,
173
+ ): ConversationState {
174
+ switch (event.type) {
175
+ case 'send': {
176
+ const text = event.text.trim();
177
+ const images = event.images && event.images.length > 0 ? event.images : undefined;
178
+ // An image-only send is valid (the picture IS the message); a truly empty
179
+ // one is a no-op.
180
+ if (!text && !images) return state;
181
+ const next: ConversationState = {
182
+ ...state,
183
+ pending: true,
184
+ failure: null,
185
+ notice: null,
186
+ timedOut: false,
187
+ // A new send supersedes any draft still waiting to be recovered.
188
+ unsent: NO_DRAFT,
189
+ lastSent: { text, ...(images ? { images } : {}) },
190
+ // The optimistic push is not a confirmed turn.
191
+ skipPersist: true,
192
+ };
193
+ if (event.controlled) return next;
194
+ return {
195
+ ...next,
196
+ messages: [...state.messages, makeUserMessage(text, event.author, images)],
197
+ };
198
+ }
199
+
200
+ case 'turn_settled': {
201
+ if (!state.pending) return state;
202
+ const base = { ...state, pending: false };
203
+ // Controlled shells never fold: the consumer's own thread already holds the
204
+ // turn it mapped from its transport. A turn that said nothing AND made no
205
+ // gesture folds nothing; a reaction-only turn (empty text, `reactions`
206
+ // set — server-bot F5) IS an answer and gets its bubble.
207
+ if (event.controlled || (!event.turn.text && event.turn.reactions.length === 0)) {
208
+ if (event.turn.deferred) {
209
+ return { ...base, notice: deferredNotice(event.turn.author ?? event.author) };
210
+ }
211
+ if (event.controlled) return base;
212
+ // A stop leaves the question on screen, so it is saved: a fresh array lets a thread-keyed shell see it.
213
+ if (event.stopped) return { ...base, messages: [...state.messages], skipPersist: false };
214
+ // Silence is not an answer: a turn that said nothing and made no gesture
215
+ // left the user's message hanging with no sign of what happened.
216
+ return {
217
+ ...revertOptimistic(base, false),
218
+ failure: { kind: 'empty', message: COPY.turnEmpty },
219
+ };
220
+ }
221
+ return {
222
+ ...base,
223
+ messages: [...state.messages, foldAssistantTurn(event.turn, event.author)],
224
+ // A settled turn IS confirmed — this one gets persisted.
225
+ skipPersist: false,
226
+ };
227
+ }
228
+
229
+ case 'turn_failed': {
230
+ if (!state.pending) return state;
231
+ const reverted = revertOptimistic({ ...state, pending: false }, event.controlled);
232
+ // The revert always happens; only the generic banner is suppressed when the
233
+ // app owns this error class.
234
+ if (event.appHandled) return reverted;
235
+ return {
236
+ ...reverted,
237
+ failure: {
238
+ kind: 'stream',
239
+ message: event.message || COPY.turnFailed,
240
+ },
241
+ };
242
+ }
243
+
244
+ case 'turn_timeout': {
245
+ if (!state.pending || state.timedOut) return state;
246
+ return {
247
+ ...revertOptimistic({ ...state, pending: false }, event.controlled),
248
+ timedOut: true,
249
+ failure: { kind: 'timeout', message: COPY.turnTimeout },
250
+ };
251
+ }
252
+
253
+ case 'dismiss_failure':
254
+ return state.failure === null ? state : { ...state, failure: null, timedOut: false };
255
+
256
+ case 'dismiss_notice':
257
+ return state.notice === null ? state : { ...state, notice: null };
258
+
259
+ case 'clear_unsent':
260
+ return state.unsent.text === null && state.unsent.images === null
261
+ ? state
262
+ : { ...state, unsent: NO_DRAFT };
263
+
264
+ case 'hydrate':
265
+ return { ...initialConversationState(event.messages), lastSent: state.lastSent };
266
+
267
+ case 'merge_seed': {
268
+ const messages = mergeConversationMessages(state.messages, event.messages);
269
+ return messages === state.messages ? state : { ...state, messages, skipPersist: true };
270
+ }
271
+
272
+ case 'persist_skip_consumed':
273
+ return state.skipPersist ? { ...state, skipPersist: false } : state;
274
+
275
+ default:
276
+ return state;
277
+ }
278
+ }
@@ -48,6 +48,31 @@ export interface GuardRejection {
48
48
  guard: string | null;
49
49
  }
50
50
 
51
+ /**
52
+ * MessageAuthor — WHO produced a message. Part of the contract, not app wiring.
53
+ *
54
+ * A shell that lets the user switch the answering persona (og118's elementos,
55
+ * aurity's personas) renders a transcript where every bubble must say who spoke;
56
+ * an assistant bubble with no author silently attributes the answer to the app
57
+ * itself. That is a lie the framework must not be able to express — so the fold
58
+ * ({@link foldAssistantTurn}) and the user capsule ({@link makeUserMessage})
59
+ * both REQUIRE an author, and a turn can rebind it mid-stream via the `author`
60
+ * event (the backend announces the persona it resolved for the turn).
61
+ *
62
+ * Only `id` and `name` are load-bearing; `symbol` and `engine` are optional
63
+ * enrichment a shell may render as an avatar token / provenance chip.
64
+ */
65
+ export interface MessageAuthor {
66
+ /** Stable identifier of the speaker (element id, persona id, 'user'). */
67
+ id: string;
68
+ /** Human name shown as the author ("Yodo", "og118", "Tú"). */
69
+ name: string;
70
+ /** Short avatar/badge token ("I", "og"). */
71
+ symbol?: string | null;
72
+ /** The engine/persona behind the answer ("Vultur", "ALICE"). */
73
+ engine?: string | null;
74
+ }
75
+
51
76
  /** Per-turn observability. All optional; each app fills what it has. */
52
77
  export interface AgentMeta {
53
78
  requestId?: string | null;
@@ -115,7 +140,31 @@ export type AgentStreamEvent =
115
140
  }
116
141
  | { type: 'tool_call'; call: ToolCall }
117
142
  | { type: 'text'; delta: string }
118
- | { type: 'result'; text: string; sources?: string[]; meta?: AgentMeta }
143
+ // The backend resolved WHO answers this turn (a persona/element the user
144
+ // selected). Emitted before the first text delta, so the live bubble is
145
+ // attributed from its first character — not re-labelled after the fold.
146
+ | { type: 'author'; author: MessageAuthor }
147
+ // `reactions`: emoji the speaker put ON the turn (an engine with a reaction
148
+ // vocabulary — server-bot's personas emit `[REACT:]`, which the engine parses
149
+ // out of the text and returns structured, F5). A gesture, not content: the
150
+ // shell renders it as reaction chips under the bubble, never as text.
151
+ | {
152
+ type: 'result';
153
+ text: string;
154
+ sources?: string[];
155
+ meta?: AgentMeta;
156
+ reactions?: string[];
157
+ }
119
158
  | { type: 'meta'; meta: AgentMeta }
120
159
  | { type: 'error'; message: string }
160
+ // A sign of life while the turn is QUIET. An idle watchdog cannot tell
161
+ // "thinking" from "hung" — both are silence — and silence is NORMAL here: a
162
+ // turn proxied to an external engine emits nothing until the whole answer
163
+ // lands. The ping carries nothing; its ARRIVAL is the signal, and the reducer
164
+ // stamps it so a watchdog watching the turn re-arms.
165
+ | { type: 'ping' }
166
+ // The backend released this turn WITHOUT its answer: a proxied engine kept
167
+ // working past the stream's live wait and the answer lands in the thread out
168
+ // of band. The stream ends empty; the shell shows a waiting notice instead.
169
+ | { type: 'deferred' }
121
170
  | { type: 'done' };