@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/src/agent/hook.ts CHANGED
@@ -1,4 +1,27 @@
1
1
  import type { AgentTurnState } from './state';
2
+ import type { ChatMessage, MessageImage } from '../chat/message';
3
+
4
+ /**
5
+ * Per-send metadata the conversation layer may hand the transport. Optional and
6
+ * backward-compatible — a transport that ignores it behaves exactly as before.
7
+ */
8
+ export interface AgentSendMeta {
9
+ /**
10
+ * The confirmed conversation so far (prior user/assistant turns, NOT the
11
+ * message being sent). A transport with a stateless/storeless backend replays
12
+ * this for continuity — the og118 canary: the durable transcript lives in the
13
+ * client (IndexedDB), so continuity survives a recycled backend. It is
14
+ * conversational CONTEXT only; the backend re-sanitizes it and never treats it
15
+ * as authorization.
16
+ */
17
+ history?: ChatMessage[];
18
+ /**
19
+ * Images attached to THIS send (OG118-IMAGE-UPLOAD-1) — vision input for the
20
+ * current turn. The transport forwards them to its backend as image content
21
+ * blocks; a transport that ignores `meta` behaves exactly as before.
22
+ */
23
+ images?: MessageImage[];
24
+ }
2
25
 
3
26
  /**
4
27
  * AgentHook — the agentic-turn contract the fi-glass agent panels consume.
@@ -18,8 +41,9 @@ export interface AgentHook {
18
41
  turn: AgentTurnState;
19
42
  /** Whether a turn is actively streaming. */
20
43
  isStreaming: boolean;
21
- /** Start an agentic turn. */
22
- send: (message: string, metadata?: object) => Promise<void>;
44
+ /** Start an agentic turn. `meta.history` lets the conversation layer replay
45
+ * prior turns for continuity on a storeless backend (see {@link AgentSendMeta}). */
46
+ send: (message: string, meta?: AgentSendMeta) => Promise<void>;
23
47
  /** Abort the in-flight turn, if supported. */
24
48
  abort?: () => void;
25
49
  /** Reset the session/turn. */
@@ -0,0 +1,53 @@
1
+ /**
2
+ * contracts/fixtures/turno-real.sse — a turn captured from the real server.
3
+ *
4
+ * The same bytes the iPhone's harness parses. Fed here in small chunks, the way
5
+ * a network delivers them, through takeSseFrames → fromWireEvent → the reducer:
6
+ * if the server's framing or the contract moves, this goes red before any
7
+ * client does.
8
+ */
9
+
10
+ import { readFileSync } from 'node:fs';
11
+ import { dirname, resolve } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { describe, expect, it } from 'vitest';
14
+ import { applyAgentEvent, initialAgentTurnState } from './state';
15
+ import { takeSseFrames } from './sse';
16
+ import { fromWireEvent } from './wire-map';
17
+ import type { AgentStreamEvent } from './events';
18
+
19
+ const here = dirname(fileURLToPath(import.meta.url));
20
+ const crudo = readFileSync(resolve(here, '../../contracts/fixtures/turno-real.sse'), 'utf8');
21
+
22
+ function enTrozos(texto: string, tamano: number): string[] {
23
+ const payloads: string[] = [];
24
+ let buffer = '';
25
+ for (let i = 0; i < texto.length; i += tamano) {
26
+ buffer += texto.slice(i, i + tamano);
27
+ const corte = takeSseFrames(buffer);
28
+ payloads.push(...corte.payloads);
29
+ buffer = corte.rest;
30
+ }
31
+ const final = takeSseFrames(buffer + '\n\n');
32
+ payloads.push(...final.payloads);
33
+ return payloads;
34
+ }
35
+
36
+ describe('turno-real.sse', () => {
37
+ it('se corta en los mismos 4 frames llegue como llegue', () => {
38
+ const entero = enTrozos(crudo, crudo.length).map((p) => JSON.parse(p).type);
39
+ const goteado = enTrozos(crudo, 7).map((p) => JSON.parse(p).type);
40
+ expect(entero).toEqual(['open', 'text', 'result', 'done']);
41
+ expect(goteado).toEqual(entero);
42
+ });
43
+
44
+ it('reduce al turno que el servidor de verdad contestó', () => {
45
+ const eventos = enTrozos(crudo, 11)
46
+ .map((p) => fromWireEvent(JSON.parse(p)))
47
+ .filter((e): e is AgentStreamEvent => e !== null);
48
+ const estado = eventos.reduce(applyAgentEvent, initialAgentTurnState());
49
+ expect(estado.text).toBe('PONG');
50
+ expect(estado.status).toBe('done');
51
+ expect(estado.meta?.model).toBe('claude-sonnet-4-5');
52
+ });
53
+ });
@@ -0,0 +1,26 @@
1
+ /**
2
+ * SSE framing for the agent stream: cut a growing byte buffer into the `data:`
3
+ * payloads that are complete, and hand back what is still arriving.
4
+ *
5
+ * A frame ends at a blank line; its `data:` lines join with `\n` (the SSE spec),
6
+ * which for the server's one-line frames is the line itself. Every transport
7
+ * (fetch in og118-web, URLSession on the iPhone) used to carry its own copy of
8
+ * this cut; the shared fixture `contracts/fixtures/turno-real.sse` is what each
9
+ * copy must read identically.
10
+ *
11
+ * @param buffer everything received so far that has not been consumed
12
+ * @returns the complete payloads in order, and the unconsumed tail
13
+ */
14
+ export function takeSseFrames(buffer: string): { payloads: string[]; rest: string } {
15
+ const frames = buffer.split('\n\n');
16
+ const rest = frames.pop() ?? '';
17
+ const payloads: string[] = [];
18
+ for (const frame of frames) {
19
+ const data = frame
20
+ .split('\n')
21
+ .filter((line) => line.startsWith('data:'))
22
+ .map((line) => line.slice(5).trim());
23
+ if (data.length > 0) payloads.push(data.join('\n'));
24
+ }
25
+ return { payloads, rest };
26
+ }
@@ -180,3 +180,63 @@ describe('plan_completed / plan_failed — stamp outcome, never lie about step s
180
180
  expect(run({ type: 'plan_failed' }).plan).toBeNull();
181
181
  });
182
182
  });
183
+
184
+ describe('author — the backend names WHO answers', () => {
185
+ it('starts anonymous: a fresh turn has no speaker yet', () => {
186
+ expect(initialAgentTurnState().author).toBeNull();
187
+ });
188
+
189
+ it('binds the announced speaker to the turn', () => {
190
+ const s = run({
191
+ type: 'author',
192
+ author: { id: 'element-053-i-yodo', name: 'Yodo', symbol: 'I', engine: 'Insult' },
193
+ });
194
+ expect(s.author).toEqual({
195
+ id: 'element-053-i-yodo',
196
+ name: 'Yodo',
197
+ symbol: 'I',
198
+ engine: 'Insult',
199
+ });
200
+ });
201
+
202
+ it('survives the rest of the turn (text, plan, result)', () => {
203
+ const s = run(
204
+ { type: 'author', author: { id: 'yodo', name: 'Yodo' } },
205
+ plan3,
206
+ { type: 'text', delta: 'hola' },
207
+ { type: 'result', text: 'hola' },
208
+ );
209
+ expect(s.author?.name).toBe('Yodo');
210
+ expect(s.status).toBe('done');
211
+ });
212
+ });
213
+
214
+ describe('result.reactions — the speaker\'s gesture on the turn (server-bot F5)', () => {
215
+ it('starts empty and lands from the result', () => {
216
+ expect(initialAgentTurnState().reactions).toEqual([]);
217
+ const s = run({ type: 'text', delta: 'Vives en GDL.' }, { type: 'result', text: 'Vives en GDL.', reactions: ['👀'] });
218
+ expect(s.reactions).toEqual(['👀']);
219
+ expect(s.text).toBe('Vives en GDL.');
220
+ });
221
+
222
+ it('a result without reactions keeps what the turn had (an engine without the field changes nothing)', () => {
223
+ const s = run({ type: 'result', text: 'hola' });
224
+ expect(s.reactions).toEqual([]);
225
+ });
226
+
227
+ it('a reaction-only turn settles done with empty text — not an error', () => {
228
+ const s = run({ type: 'result', text: '', reactions: ['👀', '🔥'] });
229
+ expect(s.status).toBe('done');
230
+ expect(s.text).toBe('');
231
+ expect(s.reactions).toEqual(['👀', '🔥']);
232
+ });
233
+ });
234
+
235
+ describe('deferred — released without its answer', () => {
236
+ it('marks the turn and lets it settle empty on done', () => {
237
+ const s = applyAgentEvent(initialAgentTurnState(), { type: 'deferred' });
238
+ expect(s.deferred).toBe(true);
239
+ expect(s.text).toBe('');
240
+ expect(applyAgentEvent(s, { type: 'done' }).status).toBe('done');
241
+ });
242
+ });
@@ -11,6 +11,7 @@ import type {
11
11
  AgentStreamEvent,
12
12
  AgentMeta,
13
13
  GuardRejection,
14
+ MessageAuthor,
14
15
  ToolCall,
15
16
  StepStatus,
16
17
  } from './events';
@@ -51,7 +52,34 @@ export interface AgentTurnState {
51
52
  text: string;
52
53
  /** Evidence references (e.g. source URLs). App-agnostic name. */
53
54
  sources: string[];
55
+ /**
56
+ * Emoji the speaker reacted to the turn with (`result.reactions`). Empty on
57
+ * every turn from an engine without a reaction vocabulary. See
58
+ * `ChatMessage.reactions` for why this is a field and not text.
59
+ */
60
+ reactions: string[];
54
61
  meta: AgentMeta | null;
62
+ /**
63
+ * WHO is answering this turn, once the backend announces it (`author` event).
64
+ * null means the backend never named a speaker — the shell then attributes the
65
+ * turn to the agent's default author, which it must supply. See
66
+ * {@link MessageAuthor}.
67
+ */
68
+ author: MessageAuthor | null;
69
+ /**
70
+ * How many signs of life the backend has sent while the turn was QUIET (bare
71
+ * `ping` frames). A shell's idle watchdog re-arms on this: a healthy turn can
72
+ * be silent for a long time (a proxied engine answers in one shot; a model
73
+ * thinks before its first token), and killing it throws away what the user
74
+ * wrote. A counter, not a timestamp — the reducer stays pure.
75
+ */
76
+ heartbeats: number;
77
+ /**
78
+ * True once the backend released this turn WITHOUT an answer because the
79
+ * engine was still working (`deferred` frame). The answer arrives in the
80
+ * thread out of band; the turn settles empty and a shell shows a waiting notice.
81
+ */
82
+ deferred: boolean;
55
83
  status: AgentTurnStatus;
56
84
  errorMessage?: string;
57
85
  }
@@ -63,7 +91,11 @@ export function initialAgentTurnState(): AgentTurnState {
63
91
  steps: [],
64
92
  text: '',
65
93
  sources: [],
94
+ reactions: [],
66
95
  meta: null,
96
+ author: null,
97
+ heartbeats: 0,
98
+ deferred: false,
67
99
  status: 'thinking',
68
100
  };
69
101
  }
@@ -236,11 +268,23 @@ export function applyAgentEvent(
236
268
  text,
237
269
  plan,
238
270
  sources: event.sources ?? state.sources,
271
+ reactions: event.reactions ?? state.reactions,
239
272
  meta: event.meta ?? state.meta,
240
273
  status: 'done',
241
274
  };
242
275
  }
243
276
 
277
+ case 'author':
278
+ return { ...state, author: event.author };
279
+
280
+ case 'ping':
281
+ // Carries nothing; its ARRIVAL is the payload. A NEW object every time, on
282
+ // purpose: that is what tells a watchdog watching this turn to re-arm.
283
+ return { ...state, heartbeats: state.heartbeats + 1 };
284
+
285
+ case 'deferred':
286
+ return { ...state, deferred: true };
287
+
244
288
  case 'meta':
245
289
  return { ...state, meta: event.meta };
246
290
 
@@ -1,39 +1,190 @@
1
1
  /**
2
- * Tests for the transcript bridge — specifically that model provenance
3
- * survives the fold (turn.meta.model → message.metadata.model) so a shell's
4
- * badge slot has real data after persistence.
2
+ * Tests for the transcript bridge — that provenance survives the fold: model
3
+ * (turn.meta.model → metadata.model), the glass-box trace, and WHO SPOKE
4
+ * (turn.author / the agent's default → message.author), so a shell's transcript
5
+ * can attribute every bubble instead of hardcoding the app's own name.
5
6
  */
6
7
 
7
8
  import { describe, it, expect } from 'vitest';
8
- import { foldAssistantTurn, makeUserMessage } from './transcript';
9
+ import { foldAssistantTurn, makeUserMessage, mergeConversationMessages } from './transcript';
10
+ import type { ChatMessage } from '../chat/message';
9
11
  import { initialAgentTurnState } from './state';
10
12
  import type { AgentTurnState } from './state';
13
+ import type { MessageAuthor } from './events';
14
+
15
+ const OG118: MessageAuthor = { id: 'og118', name: 'og118', symbol: 'og' };
16
+ const YODO: MessageAuthor = {
17
+ id: 'element-053-i-yodo',
18
+ name: 'Yodo',
19
+ symbol: 'I',
20
+ engine: 'Insult',
21
+ };
22
+ const USER: MessageAuthor = { id: 'user', name: 'Tú' };
11
23
 
12
24
  function turnWith(partial: Partial<AgentTurnState>): AgentTurnState {
13
25
  return { ...initialAgentTurnState(), text: 'hola', ...partial };
14
26
  }
15
27
 
16
- describe('foldAssistantTurn — model provenance', () => {
17
- it('persists turn.meta.model into metadata.model', () => {
18
- const msg = foldAssistantTurn(
19
- turnWith({ meta: { model: 'gpt-5.2-mini' } }),
20
- );
28
+ describe('foldAssistantTurn — authorship (no text without an author)', () => {
29
+ it('attributes the turn to the speaker the backend announced', () => {
30
+ const msg = foldAssistantTurn(turnWith({ author: YODO }), OG118);
31
+ expect(msg.author).toEqual(YODO);
32
+ });
33
+
34
+ it('falls back to the agent identity when the backend named no speaker', () => {
35
+ const msg = foldAssistantTurn(turnWith({ author: null }), OG118);
36
+ expect(msg.author).toEqual(OG118);
37
+ });
38
+
39
+ it('never folds an assistant message without an author', () => {
40
+ expect(foldAssistantTurn(turnWith({}), OG118).author).toBeDefined();
41
+ });
42
+
43
+ it('the announced speaker WINS over the app default (the og118 bug)', () => {
44
+ // The regression this contract exists for: og118 rendered "og118" on every
45
+ // bubble, so an answer produced by the Yodo element was attributed to the app.
46
+ const msg = foldAssistantTurn(turnWith({ author: YODO }), OG118);
47
+ expect(msg.author?.name).toBe('Yodo');
48
+ expect(msg.author?.name).not.toBe('og118');
49
+ });
50
+ });
51
+
52
+ describe('foldAssistantTurn — model provenance rides the TRACE (it must survive a reload)', () => {
53
+ it('persists turn.meta.model into trace.model', () => {
54
+ const msg = foldAssistantTurn(turnWith({ meta: { model: 'gpt-5.2-mini' } }), OG118);
21
55
  expect(msg.role).toBe('assistant');
22
- expect(msg.metadata).toEqual({ model: 'gpt-5.2-mini' });
56
+ expect(msg.trace?.model).toBe('gpt-5.2-mini');
23
57
  });
24
58
 
25
- it('omits metadata entirely when the turn has no model', () => {
26
- expect(foldAssistantTurn(turnWith({ meta: null })).metadata).toBeUndefined();
59
+ it('never puts the model in metadata (persistence drops it — the badge would vanish)', () => {
60
+ const msg = foldAssistantTurn(turnWith({ meta: { model: 'claude-sonnet-4-6' } }), OG118);
61
+ expect(msg.metadata).toBeUndefined();
62
+ });
63
+
64
+ it('keeps the model on a plain answer (no plan, no tools) — provenance still counts', () => {
65
+ const msg = foldAssistantTurn(turnWith({ meta: { model: 'claude-sonnet-4-6' } }), OG118);
66
+ expect(msg.trace).toEqual({ model: 'claude-sonnet-4-6' });
67
+ });
68
+
69
+ it('omits the trace entirely when the turn has no model and no glass-box', () => {
70
+ expect(foldAssistantTurn(turnWith({ meta: null }), OG118).trace).toBeUndefined();
27
71
  expect(
28
- foldAssistantTurn(turnWith({ meta: { latencyMs: 12 } })).metadata,
72
+ foldAssistantTurn(turnWith({ meta: { latencyMs: 12 } }), OG118).trace,
29
73
  ).toBeUndefined();
30
74
  });
31
75
  });
32
76
 
77
+ describe('foldAssistantTurn — glass-box trace (B3-FIGLASS-TRACE-PERSISTENCE-1)', () => {
78
+ it('snapshots the declared plan, tools and sources into trace', () => {
79
+ const msg = foldAssistantTurn(
80
+ turnWith({
81
+ plan: {
82
+ steps: [
83
+ { label: 'Investigar', status: 'done', summary: 'listo' },
84
+ { label: 'Responder', status: 'done' },
85
+ ],
86
+ outcome: 'completed',
87
+ },
88
+ steps: [{ id: 't1', name: 'search_documents', server: 'rag', isError: false }],
89
+ sources: ['doc://a', 'doc://b'],
90
+ }),
91
+ OG118,
92
+ );
93
+ expect(msg.trace?.plan?.steps).toHaveLength(2);
94
+ expect(msg.trace?.plan?.outcome).toBe('completed');
95
+ expect(msg.trace?.tools).toEqual([
96
+ { id: 't1', name: 'search_documents', server: 'rag', isError: false },
97
+ ]);
98
+ expect(msg.trace?.sources).toEqual(['doc://a', 'doc://b']);
99
+ });
100
+
101
+ it('omits trace entirely for a plain conversational turn (no plan/tools/sources)', () => {
102
+ const msg = foldAssistantTurn(turnWith({ text: '¡Hola! ¿En qué te ayudo?' }), OG118);
103
+ expect(msg.trace).toBeUndefined();
104
+ expect(msg.content).toBe('¡Hola! ¿En qué te ayudo?');
105
+ });
106
+
107
+ it('includes only the non-empty parts of the trace', () => {
108
+ const onlyTools = foldAssistantTurn(
109
+ turnWith({ steps: [{ id: 'x', name: 'fetch', server: null, isError: null }] }),
110
+ OG118,
111
+ );
112
+ expect(onlyTools.trace).toEqual({
113
+ tools: [{ id: 'x', name: 'fetch', server: null, isError: null }],
114
+ });
115
+ expect(onlyTools.trace?.plan).toBeUndefined();
116
+ expect(onlyTools.trace?.sources).toBeUndefined();
117
+ });
118
+
119
+ it('keeps a declared plan with zero settled steps (planning itself is the signal)', () => {
120
+ const msg = foldAssistantTurn(
121
+ turnWith({ plan: { steps: [{ label: 'Paso 1', status: 'pending' }] } }),
122
+ OG118,
123
+ );
124
+ expect(msg.trace?.plan?.steps).toHaveLength(1);
125
+ });
126
+
127
+ it('treats an empty plan (zero steps) as no plan', () => {
128
+ const msg = foldAssistantTurn(turnWith({ plan: { steps: [] } }), OG118);
129
+ expect(msg.trace).toBeUndefined();
130
+ });
131
+ });
132
+
33
133
  describe('makeUserMessage', () => {
34
- it('builds a user message with an ISO timestamp', () => {
35
- const msg = makeUserMessage('hola');
134
+ it('builds an authored user message with an ISO timestamp', () => {
135
+ const msg = makeUserMessage('hola', USER);
36
136
  expect(msg.role).toBe('user');
137
+ expect(msg.author).toEqual(USER);
37
138
  expect(Number.isNaN(new Date(msg.timestamp).getTime())).toBe(false);
38
139
  });
140
+
141
+ it('attaches images when given (OG118-IMAGE-UPLOAD-1)', () => {
142
+ const images = [{ mediaType: 'image/jpeg', data: 'aGk=' }];
143
+ const msg = makeUserMessage('mira esto', USER, images);
144
+ expect(msg.images).toEqual(images);
145
+ });
146
+
147
+ it('omits the images field for empty/absent lists (text-only shape unchanged)', () => {
148
+ expect('images' in makeUserMessage('hola', USER)).toBe(false);
149
+ expect('images' in makeUserMessage('hola', USER, [])).toBe(false);
150
+ });
151
+ });
152
+
153
+ describe('foldAssistantTurn — reactions are a field, never text', () => {
154
+ it('folds the turn\'s reactions onto the message', () => {
155
+ const msg = foldAssistantTurn(turnWith({ reactions: ['👀'] }), OG118);
156
+ expect(msg.reactions).toEqual(['👀']);
157
+ expect(msg.content).toBe('hola');
158
+ expect(msg.content).not.toContain('👀');
159
+ });
160
+
161
+ it('a turn without reactions folds with no field at all (the plain case stays byte-identical)', () => {
162
+ const msg = foldAssistantTurn(turnWith({}), OG118);
163
+ expect('reactions' in msg).toBe(false);
164
+ });
165
+ });
166
+
167
+ describe('mergeConversationMessages', () => {
168
+ const at = (role: ChatMessage['role'], content: string, timestamp: string): ChatMessage => ({
169
+ id: `${role}-${content}`,
170
+ role,
171
+ content,
172
+ timestamp,
173
+ });
174
+
175
+ it('returns the same reference when the source adds nothing', () => {
176
+ const target = [at('user', 'a', '2020-01-01T00:00:00.000Z')];
177
+ expect(mergeConversationMessages(target, [{ ...target[0], id: 'other' }])).toBe(target);
178
+ });
179
+
180
+ it('unions by (role, timestamp, content) and orders by timestamp, stable for ties', () => {
181
+ const target = [at('user', 'a', '2020-01-01T00:00:00.000Z'), at('user', 'c', '2020-01-01T00:00:02.000Z')];
182
+ const source = [at('assistant', 'b', '2020-01-01T00:00:01.000Z'), at('assistant', 'a', '2020-01-01T00:00:00.000Z')];
183
+ expect(mergeConversationMessages(target, source).map((m) => `${m.role}:${m.content}`)).toEqual([
184
+ 'user:a',
185
+ 'assistant:a',
186
+ 'assistant:b',
187
+ 'user:c',
188
+ ]);
189
+ });
39
190
  });
@@ -7,30 +7,109 @@
7
7
  * shell (fi-glass and beyond) can keep a visible transcript without re-deriving
8
8
  * the mapping. Moved here from the og118 consumer (DD-002-LESSON): a reusable
9
9
  * primitive belongs in the framework, not the app wrapper.
10
+ *
11
+ * NO TEXT WITHOUT AN AUTHOR: both helpers take the speaker as a REQUIRED
12
+ * argument. A shell whose user can swap the answering persona must never fold a
13
+ * bubble the transcript cannot attribute — the alternative (an optional author
14
+ * the consumer may forget) is exactly how og118 spent every turn claiming
15
+ * "og118" answered while an element actually did.
10
16
  */
11
17
 
12
- import type { ChatMessage } from '../chat/message';
18
+ import type { ChatMessage, MessageImage, MessageTrace } from '../chat/message';
19
+ import type { MessageAuthor } from './events';
13
20
  import type { AgentTurnState } from './state';
14
21
 
15
- /** A user message, ready to render optimistically the instant the user sends. */
16
- export function makeUserMessage(text: string): ChatMessage {
17
- return { role: 'user', content: text, timestamp: new Date().toISOString() };
22
+ /** A user message, ready to render optimistically the instant the user sends.
23
+ * `images` attaches vision input (OG118-IMAGE-UPLOAD-1); empty/absent folds to
24
+ * the exact text-only shape every existing consumer produces. */
25
+ export function makeUserMessage(
26
+ text: string,
27
+ author: MessageAuthor,
28
+ images?: MessageImage[],
29
+ ): ChatMessage {
30
+ return {
31
+ role: 'user',
32
+ author,
33
+ content: text,
34
+ timestamp: new Date().toISOString(),
35
+ ...(images && images.length > 0 ? { images } : {}),
36
+ };
18
37
  }
19
38
 
20
39
  /**
21
- * Fold a finished turn's answer into an assistant message. Keeps only the
22
- * material-agnostic content (no AgentTurnState snapshot) — a future gate can add
23
- * per-turn glass-box rendering without bloating the ChatMessage contract now.
24
- * Model provenance survives the fold: `turn.meta.model` lands in
25
- * `metadata.model` so a shell's badge slot ("Powered by …") has real data after
26
- * persistence, not just during the live turn.
40
+ * Snapshot the turn's glass-box provenance for persistence (B3-FIGLASS-TRACE-
41
+ * PERSISTENCE-1). Returns undefined for a plain conversational turn with no
42
+ * provenance at all, so those messages fold exactly as before — the trace is
43
+ * opt-in, never bloating the simple case. The declared plan is kept even with
44
+ * zero settled steps (the act of planning is itself the glass-box signal), and
45
+ * the model is kept on its own: a plain answer still knows what produced it.
27
46
  */
28
- export function foldAssistantTurn(turn: AgentTurnState): ChatMessage {
29
- const model = turn.meta?.model;
47
+ function snapshotTrace(turn: AgentTurnState): MessageTrace | undefined {
48
+ const hasPlan = turn.plan != null && turn.plan.steps.length > 0;
49
+ const hasTools = turn.steps.length > 0;
50
+ const hasSources = turn.sources.length > 0;
51
+ const model = turn.meta?.model?.trim() || undefined;
52
+ if (!hasPlan && !hasTools && !hasSources && !model) return undefined;
53
+ return {
54
+ ...(hasPlan ? { plan: turn.plan! } : {}),
55
+ ...(hasTools ? { tools: turn.steps } : {}),
56
+ ...(hasSources ? { sources: turn.sources } : {}),
57
+ ...(model ? { model } : {}),
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Fold a finished turn's answer into an assistant message. The answer text is
63
+ * the message content; the agentic provenance (declared plan + per-step
64
+ * outcomes, tool calls, evidence) is snapshotted into `trace` so the durable
65
+ * transcript re-renders the same glass-box the live turn showed — the "see the
66
+ * execution, not just the result" differentiator survives the fold. A turn with
67
+ * no provenance at all folds with no `trace`, unchanged.
68
+ *
69
+ * Model provenance rides the TRACE, not `metadata`: persistence drops metadata
70
+ * by design (apps stash secrets there), so a model chip read from it showed on
71
+ * the live turn and vanished on reload — a badge that was never once seen after
72
+ * a refresh. It is provenance, and provenance persists.
73
+ *
74
+ * Authorship comes from the turn itself when the backend named a speaker (the
75
+ * `author` event — the resolved persona/element); `defaultAuthor` is the agent's
76
+ * own identity, used when it did not. Required, so the folded message always
77
+ * knows who spoke.
78
+ */
79
+ export function foldAssistantTurn(
80
+ turn: AgentTurnState,
81
+ defaultAuthor: MessageAuthor,
82
+ ): ChatMessage {
83
+ const trace = snapshotTrace(turn);
30
84
  return {
31
85
  role: 'assistant',
86
+ author: turn.author ?? defaultAuthor,
32
87
  content: turn.text,
33
88
  timestamp: new Date().toISOString(),
34
- ...(model ? { metadata: { model } } : {}),
89
+ ...(trace ? { trace } : {}),
90
+ // The speaker's reactions are a gesture on the message, kept as a field so
91
+ // the shell renders chips and a reload keeps them; absent when there were none.
92
+ ...(turn.reactions.length > 0 ? { reactions: turn.reactions } : {}),
35
93
  };
36
94
  }
95
+
96
+ /** Persisted messages carry no id (sanitize drops it); this is what a reload shows. */
97
+ function messageKey(message: ChatMessage): string {
98
+ return `${message.role}\u0000${message.timestamp ?? ''}\u0000${message.content}`;
99
+ }
100
+
101
+ /**
102
+ * Union of two copies of one thread by (role, timestamp, content): every message
103
+ * of `target` plus the ones only `source` has, ordered by timestamp (stable for ties).
104
+ *
105
+ * @returns `target` itself (same reference) when `source` adds nothing.
106
+ */
107
+ export function mergeConversationMessages(target: ChatMessage[], source: ChatMessage[]): ChatMessage[] {
108
+ const known = new Set(target.map(messageKey));
109
+ const missing = source.filter((m) => !known.has(messageKey(m)));
110
+ if (missing.length === 0) return target;
111
+ return [...target, ...missing]
112
+ .map((message, order) => ({ message, order }))
113
+ .sort((a, b) => (a.message.timestamp ?? '').localeCompare(b.message.timestamp ?? '') || a.order - b.order)
114
+ .map(({ message }) => message);
115
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * contracts/agent-turn.vectors.json — the turn machine, as a contract.
3
+ *
4
+ * Each vector is a sequence of WIRE frames and the state both consumers must
5
+ * reach: this reducer (through fromWireEvent) and og118-ios's ChatModel (its
6
+ * harness replays the same file). The JSON is the source; neither language
7
+ * generates it for the other. A vector that fails here is core drifting from
8
+ * the contract, not the contract drifting from core.
9
+ */
10
+
11
+ import { readFileSync } from 'node:fs';
12
+ import { dirname, resolve } from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { describe, expect, it } from 'vitest';
15
+ import { applyAgentEvent, initialAgentTurnState, type AgentTurnState } from './state';
16
+ import { fromWireEvent } from './wire-map';
17
+ import type { AgentStreamEvent } from './events';
18
+
19
+ interface Vector {
20
+ name: string;
21
+ events: unknown[];
22
+ expect: unknown;
23
+ }
24
+
25
+ const here = dirname(fileURLToPath(import.meta.url));
26
+ const contrato = JSON.parse(
27
+ readFileSync(resolve(here, '../../contracts/agent-turn.vectors.json'), 'utf8'),
28
+ ) as { version: number; vectors: Vector[] };
29
+
30
+ function proyectar(s: AgentTurnState) {
31
+ return {
32
+ text: s.text,
33
+ status: s.status,
34
+ deferred: s.deferred,
35
+ reactions: s.reactions,
36
+ author: s.author ? { id: s.author.id, name: s.author.name } : null,
37
+ plan: s.plan
38
+ ? {
39
+ steps: s.plan.steps.map((p) => ({
40
+ label: p.label,
41
+ status: p.status,
42
+ summary: p.summary ?? null,
43
+ error: p.error ?? null,
44
+ note: p.note ?? null,
45
+ })),
46
+ rejection: s.plan.rejection
47
+ ? {
48
+ reason: s.plan.rejection.reason,
49
+ matched: s.plan.rejection.matched.map((m) => m.label),
50
+ guard: s.plan.rejection.guard,
51
+ }
52
+ : null,
53
+ amended: s.plan.amended ?? null,
54
+ outcome: s.plan.outcome ?? null,
55
+ }
56
+ : null,
57
+ };
58
+ }
59
+
60
+ describe('agent-turn.vectors.json', () => {
61
+ it('declara su versión y al menos un vector', () => {
62
+ expect(contrato.version).toBe(1);
63
+ expect(contrato.vectors.length).toBeGreaterThan(0);
64
+ });
65
+
66
+ for (const v of contrato.vectors) {
67
+ it(v.name, () => {
68
+ const eventos = v.events
69
+ .map(fromWireEvent)
70
+ .filter((e): e is AgentStreamEvent => e !== null);
71
+ const estado = eventos.reduce(applyAgentEvent, initialAgentTurnState());
72
+ expect(proyectar(estado)).toEqual(v.expect);
73
+ });
74
+ }
75
+ });