@free-intelligence/core 1.2.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/availability/index.d.ts +132 -0
- package/dist/availability/index.js +278 -0
- package/dist/availability/index.js.map +1 -0
- package/dist/index.d.ts +907 -112
- package/dist/index.js +448 -9
- package/dist/index.js.map +1 -1
- package/package.json +31 -2
- package/src/agent/conversation-state-vectors.test.ts +125 -0
- package/src/agent/conversation-state.test.ts +320 -0
- package/src/agent/conversation-state.ts +278 -0
- package/src/agent/events.ts +50 -1
- package/src/agent/hook.ts +26 -2
- package/src/agent/sse-fixture.test.ts +53 -0
- package/src/agent/sse.ts +26 -0
- package/src/agent/state.test.ts +60 -0
- package/src/agent/state.ts +44 -0
- package/src/agent/transcript.test.ts +166 -15
- package/src/agent/transcript.ts +92 -13
- package/src/agent/turn-vectors.test.ts +75 -0
- package/src/agent/wire-map.ts +131 -0
- package/src/agent/wire.generated.ts +265 -0
- package/src/availability/availability.test.ts +130 -0
- package/src/availability/defaults.ts +89 -0
- package/src/availability/index.ts +6 -0
- package/src/availability/time.ts +38 -0
- package/src/availability/types.ts +69 -0
- package/src/availability/validation.ts +133 -0
- package/src/availability/week.ts +50 -0
- package/src/chat/message.ts +81 -2
- package/src/chat/record.generated.ts +156 -0
- package/src/conversation/derivations-vectors.test.ts +65 -0
- package/src/conversation/helpers.test.ts +329 -0
- package/src/conversation/helpers.ts +248 -3
- package/src/conversation/index.ts +17 -0
- package/src/conversation/library.ts +12 -0
- package/src/conversation/markdown.test.ts +84 -0
- package/src/conversation/markdown.ts +67 -0
- package/src/conversation/record.ts +29 -1
- package/src/copy.generated.ts +19 -0
- package/src/index.ts +55 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/state.ts","../src/agent/transcript.ts","../src/conversation/helpers.ts"],"sourcesContent":["/**\n * AgentTurnState — the reduced state the fi-glass agent panels render, plus the\n * pure `applyAgentEvent` reducer that derives it from the wire stream.\n *\n * The reducer is pure (no React, no transport, no I/O) so every app reuses the\n * same event→state logic and only supplies the transport that produces the\n * AgentStreamEvent stream. Immutable: every event returns a new state object.\n */\n\nimport type {\n AgentStreamEvent,\n AgentMeta,\n GuardRejection,\n ToolCall,\n StepStatus,\n} from './events';\n\n/** One step of the declared plan, enriched with live status. */\nexport interface PlanStep {\n label: string;\n status: StepStatus;\n summary?: string;\n error?: string;\n /** Free-text annotation from note_step (carried by the step_noted event). */\n note?: string;\n}\n\n/** Terminal verdict of a whole plan (finalize_plan / cancel_plan). */\nexport type PlanOutcome = 'completed' | 'failed' | 'cancelled';\n\n/** The agent's declared plan. Guard-as-quality: rejection is woven in here. */\nexport interface AgentPlan {\n steps: PlanStep[];\n /** Set when a guard blocks; cleared when a fresh plan is declared. */\n rejection?: GuardRejection | null;\n /**\n * Set when the agent restructures the plan mid-turn (plan_amended). 'replan'\n * is then followed by a fresh `plan` event that reseeds steps and clears this.\n */\n amended?: 'insert' | 'replan' | null;\n /** Terminal plan verdict once finalize_plan / cancel_plan settles it. */\n outcome?: PlanOutcome | null;\n}\n\nexport type AgentTurnStatus = 'thinking' | 'streaming' | 'done' | 'error';\n\n/** The full reduced state of one agentic turn. */\nexport interface AgentTurnState {\n plan: AgentPlan | null;\n steps: ToolCall[];\n text: string;\n /** Evidence references (e.g. source URLs). App-agnostic name. */\n sources: string[];\n meta: AgentMeta | null;\n status: AgentTurnStatus;\n errorMessage?: string;\n}\n\n/** A fresh, empty turn — call at the start of each agentic turn. */\nexport function initialAgentTurnState(): AgentTurnState {\n return {\n plan: null,\n steps: [],\n text: '',\n sources: [],\n meta: null,\n status: 'thinking',\n };\n}\n\n/**\n * Pure reducer: apply one wire event to the turn state, returning a new state.\n *\n * Mirrors the universal turn lifecycle; an app's hook feeds it the events its\n * transport produces. Unknown/transport-only events (`open`) pass through\n * untouched.\n */\nexport function applyAgentEvent(\n state: AgentTurnState,\n event: AgentStreamEvent\n): AgentTurnState {\n // Bump 'thinking' → 'streaming' on the first sign of activity; never regress\n // a settled ('done'/'error') turn. Mirrors the original's status moves but is\n // guarded against out-of-order events.\n const streamingStatus: AgentTurnStatus =\n state.status === 'thinking' ? 'streaming' : state.status;\n\n switch (event.type) {\n case 'open':\n return state;\n\n case 'plan':\n // A fresh plan seeds N steps as 'pending' (index i ↔ step i) and clears\n // any prior guard rejection (the agent is re-declaring).\n return {\n ...state,\n plan: {\n steps: event.steps.map((label) => ({ label, status: 'pending' })),\n rejection: null,\n amended: null,\n outcome: null,\n },\n status: streamingStatus,\n };\n\n case 'plan_rejected':\n return state.plan\n ? { ...state, plan: { ...state.plan, rejection: event.rejection } }\n : { ...state, plan: { steps: [], rejection: event.rejection } };\n\n case 'step_started': {\n if (!state.plan) return state;\n const idx = event.index;\n if (idx < 0 || idx >= state.plan.steps.length) return state; // bounds guard\n // Catch-up sweep: starting step N implies steps 0..N-1 finished, even if\n // their step_done events were dropped (SSE is lossy). Then mark N running.\n const steps = state.plan.steps.map((s, i) => {\n if (i < idx && (s.status === 'pending' || s.status === 'running')) {\n return { ...s, status: 'done' as const };\n }\n if (i === idx) return { ...s, status: 'running' as const };\n return s;\n });\n return { ...state, plan: { ...state.plan, steps } };\n }\n\n case 'step_done': {\n if (!state.plan) return state;\n const idx = event.index;\n if (idx < 0 || idx >= state.plan.steps.length) return state; // bounds guard\n const steps = state.plan.steps.map((s, i) => {\n if (i !== idx) return s; // mutate exactly step N — no off-by-one\n const patch: PlanStep = { ...s, status: event.status };\n // 'done' carries a summary; 'failed'/'cancelled' carry a reason in error.\n if (event.status === 'done') {\n if (event.summary) patch.summary = event.summary;\n } else if (event.error) {\n patch.error = event.error;\n }\n return patch;\n });\n return { ...state, plan: { ...state.plan, steps } };\n }\n\n case 'step_noted': {\n // Annotate exactly step N with a free-text note; never touches status.\n if (!state.plan) return state;\n const idx = event.index;\n if (idx < 0 || idx >= state.plan.steps.length) return state; // bounds guard\n const steps = state.plan.steps.map((s, i) =>\n i === idx ? { ...s, note: event.note } : s\n );\n return { ...state, plan: { ...state.plan, steps } };\n }\n\n case 'plan_amended':\n // Record that the plan was restructured. For 'replan' the new steps land\n // in a following `plan` event (which clears this flag); here we only set\n // the badge signal — the amended event carries no steps to apply.\n return state.plan\n ? { ...state, plan: { ...state.plan, amended: event.action } }\n : state;\n\n case 'plan_cancelled': {\n // The whole plan was abandoned. Settle still-open steps as 'cancelled'\n // (NOT 'done' — distinct from the `result` close-out sweep, which only\n // touches pending/running and would wrongly mark these done if it ran\n // after us). Already-settled steps keep their terminal status.\n if (!state.plan) return state;\n const steps = state.plan.steps.map((s) =>\n s.status === 'pending' || s.status === 'running'\n ? { ...s, status: 'cancelled' as const }\n : s\n );\n return { ...state, plan: { ...state.plan, steps, outcome: 'cancelled' } };\n }\n\n case 'plan_completed':\n // Terminal verdict. Per-step statuses already reflect reality (each\n // step_done settled them); we only stamp the plan-level outcome. The\n // wire counts are derivable from steps[].status, so we don't store them.\n return state.plan\n ? { ...state, plan: { ...state.plan, outcome: 'completed' } }\n : state;\n\n case 'plan_failed':\n // Plan failed (>=1 step failed). Leave step statuses as settled — a\n // failed plan can still have done steps — and stamp the outcome.\n return state.plan\n ? { ...state, plan: { ...state.plan, outcome: 'failed' } }\n : state;\n\n case 'tool_call': {\n // Dedupe-on-arrival by id (DELIBERATE divergence from the original's\n // append + replace-at-result, since the contract's `result` carries no\n // tool_calls). id == null = still pending → append.\n const existing =\n event.call.id != null\n ? state.steps.findIndex((c) => c.id === event.call.id)\n : -1;\n const steps =\n existing >= 0\n ? state.steps.map((c, i) => (i === existing ? event.call : c))\n : [...state.steps, event.call];\n return { ...state, steps, status: streamingStatus };\n }\n\n case 'text':\n // CONCATENATE deltas (never replace) — the streaming bug that compiles\n // identically but only shows the last fragment at runtime.\n return {\n ...state,\n text: state.text + event.delta,\n status: streamingStatus,\n };\n\n case 'result': {\n // Never wipe a non-empty streamed accumulation with an empty result.text\n // (the agent ran tools but composed no final response). Note: app-specific\n // dedupe/source-extraction stays in the app's hook, which emits\n // `sources` already extracted.\n const text = event.text.trim() ? event.text : state.text;\n // Close any plan steps left open when the turn settles.\n const plan = state.plan\n ? {\n ...state.plan,\n steps: state.plan.steps.map((s) =>\n s.status === 'pending' || s.status === 'running'\n ? { ...s, status: 'done' as const }\n : s\n ),\n }\n : state.plan;\n return {\n ...state,\n text,\n plan,\n sources: event.sources ?? state.sources,\n meta: event.meta ?? state.meta,\n status: 'done',\n };\n }\n\n case 'meta':\n return { ...state, meta: event.meta };\n\n case 'error':\n return { ...state, status: 'error', errorMessage: event.message };\n\n case 'done':\n return state.status === 'thinking' || state.status === 'streaming'\n ? { ...state, status: 'done' }\n : state;\n\n default:\n return state;\n }\n}\n","/**\n * Transcript bridge — fold the live agentic turn into flat chat messages.\n *\n * Pure, framework-agnostic (no React, no transport). The agent contract models\n * ONE live turn (AgentTurnState); a conversation surface needs the thread as a\n * flat list. These two helpers bridge `AgentTurnState` → `ChatMessage` so any\n * shell (fi-glass and beyond) can keep a visible transcript without re-deriving\n * the mapping. Moved here from the og118 consumer (DD-002-LESSON): a reusable\n * primitive belongs in the framework, not the app wrapper.\n */\n\nimport type { ChatMessage } from '../chat/message';\nimport type { AgentTurnState } from './state';\n\n/** A user message, ready to render optimistically the instant the user sends. */\nexport function makeUserMessage(text: string): ChatMessage {\n return { role: 'user', content: text, timestamp: new Date().toISOString() };\n}\n\n/**\n * Fold a finished turn's answer into an assistant message. Keeps only the\n * material-agnostic content (no AgentTurnState snapshot) — a future gate can add\n * per-turn glass-box rendering without bloating the ChatMessage contract now.\n * Model provenance survives the fold: `turn.meta.model` lands in\n * `metadata.model` so a shell's badge slot (\"Powered by …\") has real data after\n * persistence, not just during the live turn.\n */\nexport function foldAssistantTurn(turn: AgentTurnState): ChatMessage {\n const model = turn.meta?.model;\n return {\n role: 'assistant',\n content: turn.text,\n timestamp: new Date().toISOString(),\n ...(model ? { metadata: { model } } : {}),\n };\n}\n","/**\n * Conversation helpers — pure, deterministic primitives for building and\n * summarizing ConversationRecords. No React, no browser, no transport.\n *\n * Privacy by structure: `sanitizeConversationMessage` builds a NEW message with\n * exactly the allowed subset (role / content / timestamp). Any other field a\n * ChatMessage may carry now or later — `id`, `thinking`, `metadata`, a future\n * tool payload or token — is dropped by construction, not by an allow/deny list\n * someone must remember to update. The initial privacy guarantee is the\n * restriction, not PII heuristics.\n *\n * Determinism: helpers that stamp a time accept an optional `now` so tests are\n * reproducible; they fall back to the wall clock only when it is omitted.\n */\n\nimport type { ChatMessage } from '../chat/message';\nimport type { ConversationRecord, ConversationSummary } from './record';\n\n/** Schema version stamped on every record created here. */\nexport const CONVERSATION_SCHEMA_VERSION = 1;\n\n/** Fallback title when there is no usable user message yet. */\nconst DEFAULT_TITLE = 'New chat';\nconst TITLE_MAX = 60;\nconst PREVIEW_MAX = 120;\n\n/** Collapse whitespace and truncate to `max` chars with an ellipsis. Pure. */\nfunction truncate(text: string, max: number): string {\n const t = text.trim().replace(/\\s+/g, ' ');\n if (t.length <= max) return t;\n return `${t.slice(0, Math.max(0, max - 1)).trimEnd()}…`;\n}\n\n/**\n * Reduce a ChatMessage to the only fields safe to persist: role, content, and\n * timestamp. Drops id, thinking, metadata, and anything else by construction.\n */\nexport function sanitizeConversationMessage(message: ChatMessage): ChatMessage {\n return {\n role: message.role,\n content: message.content,\n timestamp: message.timestamp,\n };\n}\n\n/** Title from the first non-empty user message; `DEFAULT_TITLE` otherwise. */\nexport function deriveConversationTitle(\n messages: ChatMessage[],\n max: number = TITLE_MAX,\n): string {\n const firstUser = messages.find(\n (m) => m.role === 'user' && m.content.trim() !== '',\n );\n if (!firstUser) return DEFAULT_TITLE;\n return truncate(firstUser.content, max) || DEFAULT_TITLE;\n}\n\n/** Preview from the last non-empty message of any role; `''` otherwise. */\nexport function deriveConversationPreview(\n messages: ChatMessage[],\n max: number = PREVIEW_MAX,\n): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].content.trim() !== '') {\n return truncate(messages[i].content, max);\n }\n }\n return '';\n}\n\n/** Arguments for {@link createConversationRecord}. */\nexport interface CreateConversationRecordArgs {\n /** Stable id (doubles as the backend session_id). */\n id: string;\n /** Initial thread; sanitized before storing. Default: empty. */\n messages?: ChatMessage[];\n /** ISO timestamp to stamp createdAt/updatedAt. Default: now. */\n now?: string;\n}\n\n/** Build a fresh, sanitized record with derived title + preview. */\nexport function createConversationRecord(\n args: CreateConversationRecordArgs,\n): ConversationRecord {\n const now = args.now ?? new Date().toISOString();\n const messages = (args.messages ?? []).map(sanitizeConversationMessage);\n return {\n id: args.id,\n title: deriveConversationTitle(messages),\n createdAt: now,\n updatedAt: now,\n messages,\n preview: deriveConversationPreview(messages),\n schemaVersion: CONVERSATION_SCHEMA_VERSION,\n };\n}\n\n/** Project a record to its light summary — excludes `messages`. */\nexport function summarizeConversation(\n record: ConversationRecord,\n): ConversationSummary {\n return {\n id: record.id,\n title: record.title,\n createdAt: record.createdAt,\n updatedAt: record.updatedAt,\n preview: record.preview,\n };\n}\n"],"mappings":";AA2DO,SAAS,wBAAwC;AACtD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,CAAC;AAAA,IACR,MAAM;AAAA,IACN,SAAS,CAAC;AAAA,IACV,MAAM;AAAA,IACN,QAAQ;AAAA,EACV;AACF;AASO,SAAS,gBACd,OACA,OACgB;AAIhB,QAAM,kBACJ,MAAM,WAAW,aAAa,cAAc,MAAM;AAEpD,UAAQ,MAAM,MAAM;AAAA,IAClB,KAAK;AACH,aAAO;AAAA,IAET,KAAK;AAGH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,MAAM;AAAA,UACJ,OAAO,MAAM,MAAM,IAAI,CAAC,WAAW,EAAE,OAAO,QAAQ,UAAU,EAAE;AAAA,UAChE,WAAW;AAAA,UACX,SAAS;AAAA,UACT,SAAS;AAAA,QACX;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IAEF,KAAK;AACH,aAAO,MAAM,OAC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,0BAA0B,QAAQ;AAAA,IAC3C,eAAe;AAAA,EACjB;AACF;AAGO,SAAS,sBACd,QACqB;AACrB,SAAO;AAAA,IACL,IAAI,OAAO;AAAA,IACX,OAAO,OAAO;AAAA,IACd,WAAW,OAAO;AAAA,IAClB,WAAW,OAAO;AAAA,IAClB,SAAS,OAAO;AAAA,EAClB;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/agent/state.ts","../src/agent/wire-map.ts","../src/agent/sse.ts","../src/copy.generated.ts","../src/agent/transcript.ts","../src/agent/conversation-state.ts","../src/conversation/markdown.ts","../src/conversation/helpers.ts"],"sourcesContent":["/**\n * AgentTurnState — the reduced state the fi-glass agent panels render, plus the\n * pure `applyAgentEvent` reducer that derives it from the wire stream.\n *\n * The reducer is pure (no React, no transport, no I/O) so every app reuses the\n * same event→state logic and only supplies the transport that produces the\n * AgentStreamEvent stream. Immutable: every event returns a new state object.\n */\n\nimport type {\n AgentStreamEvent,\n AgentMeta,\n GuardRejection,\n MessageAuthor,\n ToolCall,\n StepStatus,\n} from './events';\n\n/** One step of the declared plan, enriched with live status. */\nexport interface PlanStep {\n label: string;\n status: StepStatus;\n summary?: string;\n error?: string;\n /** Free-text annotation from note_step (carried by the step_noted event). */\n note?: string;\n}\n\n/** Terminal verdict of a whole plan (finalize_plan / cancel_plan). */\nexport type PlanOutcome = 'completed' | 'failed' | 'cancelled';\n\n/** The agent's declared plan. Guard-as-quality: rejection is woven in here. */\nexport interface AgentPlan {\n steps: PlanStep[];\n /** Set when a guard blocks; cleared when a fresh plan is declared. */\n rejection?: GuardRejection | null;\n /**\n * Set when the agent restructures the plan mid-turn (plan_amended). 'replan'\n * is then followed by a fresh `plan` event that reseeds steps and clears this.\n */\n amended?: 'insert' | 'replan' | null;\n /** Terminal plan verdict once finalize_plan / cancel_plan settles it. */\n outcome?: PlanOutcome | null;\n}\n\nexport type AgentTurnStatus = 'thinking' | 'streaming' | 'done' | 'error';\n\n/** The full reduced state of one agentic turn. */\nexport interface AgentTurnState {\n plan: AgentPlan | null;\n steps: ToolCall[];\n text: string;\n /** Evidence references (e.g. source URLs). App-agnostic name. */\n sources: string[];\n /**\n * Emoji the speaker reacted to the turn with (`result.reactions`). Empty on\n * every turn from an engine without a reaction vocabulary. See\n * `ChatMessage.reactions` for why this is a field and not text.\n */\n reactions: string[];\n meta: AgentMeta | null;\n /**\n * WHO is answering this turn, once the backend announces it (`author` event).\n * null means the backend never named a speaker — the shell then attributes the\n * turn to the agent's default author, which it must supply. See\n * {@link MessageAuthor}.\n */\n author: MessageAuthor | null;\n /**\n * How many signs of life the backend has sent while the turn was QUIET (bare\n * `ping` frames). A shell's idle watchdog re-arms on this: a healthy turn can\n * be silent for a long time (a proxied engine answers in one shot; a model\n * thinks before its first token), and killing it throws away what the user\n * wrote. A counter, not a timestamp — the reducer stays pure.\n */\n heartbeats: number;\n /**\n * True once the backend released this turn WITHOUT an answer because the\n * engine was still working (`deferred` frame). The answer arrives in the\n * thread out of band; the turn settles empty and a shell shows a waiting notice.\n */\n deferred: boolean;\n status: AgentTurnStatus;\n errorMessage?: string;\n}\n\n/** A fresh, empty turn — call at the start of each agentic turn. */\nexport function initialAgentTurnState(): AgentTurnState {\n return {\n plan: null,\n steps: [],\n text: '',\n sources: [],\n reactions: [],\n meta: null,\n author: null,\n heartbeats: 0,\n deferred: false,\n status: 'thinking',\n };\n}\n\n/**\n * Pure reducer: apply one wire event to the turn state, returning a new state.\n *\n * Mirrors the universal turn lifecycle; an app's hook feeds it the events its\n * transport produces. Unknown/transport-only events (`open`) pass through\n * untouched.\n */\nexport function applyAgentEvent(\n state: AgentTurnState,\n event: AgentStreamEvent\n): AgentTurnState {\n // Bump 'thinking' → 'streaming' on the first sign of activity; never regress\n // a settled ('done'/'error') turn. Mirrors the original's status moves but is\n // guarded against out-of-order events.\n const streamingStatus: AgentTurnStatus =\n state.status === 'thinking' ? 'streaming' : state.status;\n\n switch (event.type) {\n case 'open':\n return state;\n\n case 'plan':\n // A fresh plan seeds N steps as 'pending' (index i ↔ step i) and clears\n // any prior guard rejection (the agent is re-declaring).\n return {\n ...state,\n plan: {\n steps: event.steps.map((label) => ({ label, status: 'pending' })),\n rejection: null,\n amended: null,\n outcome: null,\n },\n status: streamingStatus,\n };\n\n case 'plan_rejected':\n return state.plan\n ? { ...state, plan: { ...state.plan, rejection: event.rejection } }\n : { ...state, plan: { steps: [], rejection: event.rejection } };\n\n case 'step_started': {\n if (!state.plan) return state;\n const idx = event.index;\n if (idx < 0 || idx >= state.plan.steps.length) return state; // bounds guard\n // Catch-up sweep: starting step N implies steps 0..N-1 finished, even if\n // their step_done events were dropped (SSE is lossy). Then mark N running.\n const steps = state.plan.steps.map((s, i) => {\n if (i < idx && (s.status === 'pending' || s.status === 'running')) {\n return { ...s, status: 'done' as const };\n }\n if (i === idx) return { ...s, status: 'running' as const };\n return s;\n });\n return { ...state, plan: { ...state.plan, steps } };\n }\n\n case 'step_done': {\n if (!state.plan) return state;\n const idx = event.index;\n if (idx < 0 || idx >= state.plan.steps.length) return state; // bounds guard\n const steps = state.plan.steps.map((s, i) => {\n if (i !== idx) return s; // mutate exactly step N — no off-by-one\n const patch: PlanStep = { ...s, status: event.status };\n // 'done' carries a summary; 'failed'/'cancelled' carry a reason in error.\n if (event.status === 'done') {\n if (event.summary) patch.summary = event.summary;\n } else if (event.error) {\n patch.error = event.error;\n }\n return patch;\n });\n return { ...state, plan: { ...state.plan, steps } };\n }\n\n case 'step_noted': {\n // Annotate exactly step N with a free-text note; never touches status.\n if (!state.plan) return state;\n const idx = event.index;\n if (idx < 0 || idx >= state.plan.steps.length) return state; // bounds guard\n const steps = state.plan.steps.map((s, i) =>\n i === idx ? { ...s, note: event.note } : s\n );\n return { ...state, plan: { ...state.plan, steps } };\n }\n\n case 'plan_amended':\n // Record that the plan was restructured. For 'replan' the new steps land\n // in a following `plan` event (which clears this flag); here we only set\n // the badge signal — the amended event carries no steps to apply.\n return state.plan\n ? { ...state, plan: { ...state.plan, amended: event.action } }\n : state;\n\n case 'plan_cancelled': {\n // The whole plan was abandoned. Settle still-open steps as 'cancelled'\n // (NOT 'done' — distinct from the `result` close-out sweep, which only\n // touches pending/running and would wrongly mark these done if it ran\n // after us). Already-settled steps keep their terminal status.\n if (!state.plan) return state;\n const steps = state.plan.steps.map((s) =>\n s.status === 'pending' || s.status === 'running'\n ? { ...s, status: 'cancelled' as const }\n : s\n );\n return { ...state, plan: { ...state.plan, steps, outcome: 'cancelled' } };\n }\n\n case 'plan_completed':\n // Terminal verdict. Per-step statuses already reflect reality (each\n // step_done settled them); we only stamp the plan-level outcome. The\n // wire counts are derivable from steps[].status, so we don't store them.\n return state.plan\n ? { ...state, plan: { ...state.plan, outcome: 'completed' } }\n : state;\n\n case 'plan_failed':\n // Plan failed (>=1 step failed). Leave step statuses as settled — a\n // failed plan can still have done steps — and stamp the outcome.\n return state.plan\n ? { ...state, plan: { ...state.plan, outcome: 'failed' } }\n : state;\n\n case 'tool_call': {\n // Dedupe-on-arrival by id (DELIBERATE divergence from the original's\n // append + replace-at-result, since the contract's `result` carries no\n // tool_calls). id == null = still pending → append.\n const existing =\n event.call.id != null\n ? state.steps.findIndex((c) => c.id === event.call.id)\n : -1;\n const steps =\n existing >= 0\n ? state.steps.map((c, i) => (i === existing ? event.call : c))\n : [...state.steps, event.call];\n return { ...state, steps, status: streamingStatus };\n }\n\n case 'text':\n // CONCATENATE deltas (never replace) — the streaming bug that compiles\n // identically but only shows the last fragment at runtime.\n return {\n ...state,\n text: state.text + event.delta,\n status: streamingStatus,\n };\n\n case 'result': {\n // Never wipe a non-empty streamed accumulation with an empty result.text\n // (the agent ran tools but composed no final response). Note: app-specific\n // dedupe/source-extraction stays in the app's hook, which emits\n // `sources` already extracted.\n const text = event.text.trim() ? event.text : state.text;\n // Close any plan steps left open when the turn settles.\n const plan = state.plan\n ? {\n ...state.plan,\n steps: state.plan.steps.map((s) =>\n s.status === 'pending' || s.status === 'running'\n ? { ...s, status: 'done' as const }\n : s\n ),\n }\n : state.plan;\n return {\n ...state,\n text,\n plan,\n sources: event.sources ?? state.sources,\n reactions: event.reactions ?? state.reactions,\n meta: event.meta ?? state.meta,\n status: 'done',\n };\n }\n\n case 'author':\n return { ...state, author: event.author };\n\n case 'ping':\n // Carries nothing; its ARRIVAL is the payload. A NEW object every time, on\n // purpose: that is what tells a watchdog watching this turn to re-arm.\n return { ...state, heartbeats: state.heartbeats + 1 };\n\n case 'deferred':\n return { ...state, deferred: true };\n\n case 'meta':\n return { ...state, meta: event.meta };\n\n case 'error':\n return { ...state, status: 'error', errorMessage: event.message };\n\n case 'done':\n return state.status === 'thinking' || state.status === 'streaming'\n ? { ...state, status: 'done' }\n : state;\n\n default:\n return state;\n }\n}\n","/**\n * fi-runner wire frame → core {@link AgentStreamEvent}, or null to drop it.\n *\n * The wire is `contracts/agent-events.schema.json`; the app-level event is what\n * {@link applyAgentEvent} reduces. This mapping lived in og118's transport hook\n * and every other consumer of the stream (the iPhone, the next shell) had to\n * rewrite it. It is substrate: one mapping, checked against the same vectors\n * the native client replays (`contracts/agent-turn.vectors.json`).\n *\n * @param frame one decoded SSE `data:` payload\n * @returns the core event, or null for a frame this layer has no use for\n */\nimport type { AgentStreamEvent } from './events';\n\ntype Raw = Record<string, unknown>;\n\nfunction rec(v: unknown): Raw {\n return v && typeof v === 'object' ? (v as Raw) : {};\n}\n\nfunction str(v: unknown, fallback = ''): string {\n return v == null ? fallback : String(v);\n}\n\nfunction nullableStr(v: unknown): string | null {\n return typeof v === 'string' && v.trim() ? v : null;\n}\n\nexport function fromWireEvent(frame: unknown): AgentStreamEvent | null {\n const ev = rec(frame);\n const data = rec(ev.data);\n switch (ev.type) {\n case 'open':\n return { type: 'open' };\n case 'text':\n return { type: 'text', delta: str(ev.text) };\n case 'element': {\n const el = rec(ev.element);\n const id = str(el.id);\n if (!id) return null;\n return {\n type: 'author',\n author: {\n id,\n name: str(el.name) || str(el.label) || id,\n symbol: (el.symbol as string | null) ?? null,\n engine: (el.engine as string | null) ?? null,\n },\n };\n }\n case 'tool_call': {\n const t = rec(ev.tool ?? ev.call);\n return {\n type: 'tool_call',\n call: {\n id: (t.id as string | null) ?? null,\n name: str(t.name),\n server: (t.server as string | null) ?? null,\n isError: (t.is_error as boolean | null) ?? (t.isError as boolean | null) ?? null,\n },\n };\n }\n case 'plan':\n return { type: 'plan', steps: ((data.steps as unknown[]) ?? []).map((s) => str(s)) };\n case 'plan_rejected':\n return {\n type: 'plan_rejected',\n rejection: {\n reason: str(data.reason),\n matched: (data.matched as Array<{ index: number; label: string }>) ?? [],\n guard: (data.guard as string | null) ?? null,\n },\n };\n case 'step_started':\n return { type: 'step_started', index: Number(data.step_index ?? -1) };\n case 'step_done': {\n const raw = str(data.status, 'done');\n const status = raw === 'failed' ? 'failed' : raw === 'cancelled' ? 'cancelled' : 'done';\n return {\n type: 'step_done',\n index: Number(data.step_index ?? -1),\n status,\n summary: data.summary ? str(data.summary) : undefined,\n error: data.error ? str(data.error) : undefined,\n };\n }\n case 'step_noted':\n return { type: 'step_noted', index: Number(data.step_index ?? -1), note: str(data.note) };\n case 'plan_amended':\n return { type: 'plan_amended', action: data.action === 'replan' ? 'replan' : 'insert' };\n case 'plan_cancelled':\n return { type: 'plan_cancelled', reason: data.reason ? str(data.reason) : undefined };\n case 'plan_completed':\n return {\n type: 'plan_completed',\n completedCount: Number(data.completed_count ?? 0),\n failedCount: Number(data.failed_count ?? 0),\n cancelledCount: Number(data.cancelled_count ?? 0),\n };\n case 'plan_failed':\n return {\n type: 'plan_failed',\n completedCount: Number(data.completed_count ?? 0),\n failedCount: Number(data.failed_count ?? 0),\n cancelledCount: Number(data.cancelled_count ?? 0),\n };\n case 'result': {\n const r = rec(ev.result);\n const model = nullableStr(r.model);\n const reactions = Array.isArray(r.reactions)\n ? r.reactions.map((x) => str(x).trim()).filter(Boolean)\n : [];\n return {\n type: 'result',\n text: str(r.text),\n ...(model ? { meta: { model } } : {}),\n ...(reactions.length > 0 ? { reactions } : {}),\n };\n }\n case 'error':\n return { type: 'error', message: str(ev.message, 'error') };\n case 'ping':\n return { type: 'ping' };\n case 'deferred':\n return { type: 'deferred' };\n case 'done':\n return { type: 'done' };\n default:\n return null;\n }\n}\n","/**\n * SSE framing for the agent stream: cut a growing byte buffer into the `data:`\n * payloads that are complete, and hand back what is still arriving.\n *\n * A frame ends at a blank line; its `data:` lines join with `\\n` (the SSE spec),\n * which for the server's one-line frames is the line itself. Every transport\n * (fetch in og118-web, URLSession on the iPhone) used to carry its own copy of\n * this cut; the shared fixture `contracts/fixtures/turno-real.sse` is what each\n * copy must read identically.\n *\n * @param buffer everything received so far that has not been consumed\n * @returns the complete payloads in order, and the unconsumed tail\n */\nexport function takeSseFrames(buffer: string): { payloads: string[]; rest: string } {\n const frames = buffer.split('\\n\\n');\n const rest = frames.pop() ?? '';\n const payloads: string[] = [];\n for (const frame of frames) {\n const data = frame\n .split('\\n')\n .filter((line) => line.startsWith('data:'))\n .map((line) => line.slice(5).trim());\n if (data.length > 0) payloads.push(data.join('\\n'));\n }\n return { payloads, rest };\n}\n","// DO NOT EDIT — generado desde contracts/copy.json (pnpm gen:copy).\n//\n// Las frases que el substrato posee. Swift deriva del mismo contrato\n// (Copy.generated.swift); ninguna superficie manda sobre la otra.\n\nexport const COPY = {\n /** Título de un hilo sin mensaje de usuario usable (deriveConversationTitle). */\n conversationDefaultTitle: 'New chat',\n /** Aviso (no error) de un turno diferido: el motor sigue trabajando tras cerrar el stream. */\n turnDeferredNotice: (author: string): string => '{author} sigue escribiendo. Su respuesta aparecerá aquí en cuanto termine.'.split('{author}').join(author),\n /** El aviso cuando la relectura acotada del hilo se agotó sin que llegara la respuesta diferida. */\n turnDeferredTimeout: 'La respuesta tardó más de lo normal. Vuelve a abrir este chat para verla.',\n /** Falla genérica del transporte o del motor, cuando no trae mensaje propio. */\n turnFailed: 'La respuesta falló. Intenta de nuevo.',\n /** El watchdog de inactividad cerró el turno. */\n turnTimeout: 'La respuesta tardó demasiado. Intenta de nuevo.',\n /** El turno cerró sin texto, sin reacción y sin deferred: el silencio es una falla. */\n turnEmpty: 'La respuesta llegó vacía. Intenta de nuevo.',\n} as const;\n","/**\n * Transcript bridge — fold the live agentic turn into flat chat messages.\n *\n * Pure, framework-agnostic (no React, no transport). The agent contract models\n * ONE live turn (AgentTurnState); a conversation surface needs the thread as a\n * flat list. These two helpers bridge `AgentTurnState` → `ChatMessage` so any\n * shell (fi-glass and beyond) can keep a visible transcript without re-deriving\n * the mapping. Moved here from the og118 consumer (DD-002-LESSON): a reusable\n * primitive belongs in the framework, not the app wrapper.\n *\n * NO TEXT WITHOUT AN AUTHOR: both helpers take the speaker as a REQUIRED\n * argument. A shell whose user can swap the answering persona must never fold a\n * bubble the transcript cannot attribute — the alternative (an optional author\n * the consumer may forget) is exactly how og118 spent every turn claiming\n * \"og118\" answered while an element actually did.\n */\n\nimport type { ChatMessage, MessageImage, MessageTrace } from '../chat/message';\nimport type { MessageAuthor } from './events';\nimport type { AgentTurnState } from './state';\n\n/** A user message, ready to render optimistically the instant the user sends.\n * `images` attaches vision input (OG118-IMAGE-UPLOAD-1); empty/absent folds to\n * the exact text-only shape every existing consumer produces. */\nexport function makeUserMessage(\n text: string,\n author: MessageAuthor,\n images?: MessageImage[],\n): ChatMessage {\n return {\n role: 'user',\n author,\n content: text,\n timestamp: new Date().toISOString(),\n ...(images && images.length > 0 ? { images } : {}),\n };\n}\n\n/**\n * Snapshot the turn's glass-box provenance for persistence (B3-FIGLASS-TRACE-\n * PERSISTENCE-1). Returns undefined for a plain conversational turn with no\n * provenance at all, so those messages fold exactly as before — the trace is\n * opt-in, never bloating the simple case. The declared plan is kept even with\n * zero settled steps (the act of planning is itself the glass-box signal), and\n * the model is kept on its own: a plain answer still knows what produced it.\n */\nfunction snapshotTrace(turn: AgentTurnState): MessageTrace | undefined {\n const hasPlan = turn.plan != null && turn.plan.steps.length > 0;\n const hasTools = turn.steps.length > 0;\n const hasSources = turn.sources.length > 0;\n const model = turn.meta?.model?.trim() || undefined;\n if (!hasPlan && !hasTools && !hasSources && !model) return undefined;\n return {\n ...(hasPlan ? { plan: turn.plan! } : {}),\n ...(hasTools ? { tools: turn.steps } : {}),\n ...(hasSources ? { sources: turn.sources } : {}),\n ...(model ? { model } : {}),\n };\n}\n\n/**\n * Fold a finished turn's answer into an assistant message. The answer text is\n * the message content; the agentic provenance (declared plan + per-step\n * outcomes, tool calls, evidence) is snapshotted into `trace` so the durable\n * transcript re-renders the same glass-box the live turn showed — the \"see the\n * execution, not just the result\" differentiator survives the fold. A turn with\n * no provenance at all folds with no `trace`, unchanged.\n *\n * Model provenance rides the TRACE, not `metadata`: persistence drops metadata\n * by design (apps stash secrets there), so a model chip read from it showed on\n * the live turn and vanished on reload — a badge that was never once seen after\n * a refresh. It is provenance, and provenance persists.\n *\n * Authorship comes from the turn itself when the backend named a speaker (the\n * `author` event — the resolved persona/element); `defaultAuthor` is the agent's\n * own identity, used when it did not. Required, so the folded message always\n * knows who spoke.\n */\nexport function foldAssistantTurn(\n turn: AgentTurnState,\n defaultAuthor: MessageAuthor,\n): ChatMessage {\n const trace = snapshotTrace(turn);\n return {\n role: 'assistant',\n author: turn.author ?? defaultAuthor,\n content: turn.text,\n timestamp: new Date().toISOString(),\n ...(trace ? { trace } : {}),\n // The speaker's reactions are a gesture on the message, kept as a field so\n // the shell renders chips and a reload keeps them; absent when there were none.\n ...(turn.reactions.length > 0 ? { reactions: turn.reactions } : {}),\n };\n}\n\n/** Persisted messages carry no id (sanitize drops it); this is what a reload shows. */\nfunction messageKey(message: ChatMessage): string {\n return `${message.role}\\u0000${message.timestamp ?? ''}\\u0000${message.content}`;\n}\n\n/**\n * Union of two copies of one thread by (role, timestamp, content): every message\n * of `target` plus the ones only `source` has, ordered by timestamp (stable for ties).\n *\n * @returns `target` itself (same reference) when `source` adds nothing.\n */\nexport function mergeConversationMessages(target: ChatMessage[], source: ChatMessage[]): ChatMessage[] {\n const known = new Set(target.map(messageKey));\n const missing = source.filter((m) => !known.has(messageKey(m)));\n if (missing.length === 0) return target;\n return [...target, ...missing]\n .map((message, order) => ({ message, order }))\n .sort((a, b) => (a.message.timestamp ?? '').localeCompare(b.message.timestamp ?? '') || a.order - b.order)\n .map(({ message }) => message);\n}\n","/**\n * ConversationState — the reduced state of a whole agentic CONVERSATION (the\n * thread across turns), plus the pure `applyConversationEvent` reducer that\n * derives it.\n *\n * Sibling of {@link ./state} one level up: `AgentTurnState` reduces the wire\n * events of ONE streaming turn; this reduces the lifecycle of the conversation\n * those turns live in — the optimistic push, the fold, the revert that hands the\n * user's words back, the recoverable-failure banners, persistence bookkeeping.\n *\n * WHY IT MOVED HERE (framework-first-canary, the demotion's mirror): fi-glass's\n * `useAgentConversation` held this logic across 7 `useState` + 10 `useRef` in a\n * 575-line hook, so the rules of the machine — \"a failed turn must never cost\n * the user their words\", \"an optimistic push is not a confirmed turn\" — could\n * only be exercised by mounting React and driving a fake transport. They are not\n * React rules; they are conversation rules, identical for every shell. Here they\n * are one value and one function, testable with plain assertions.\n *\n * Pure: no React, no transport, no timers, no I/O. Immutable: every event\n * returns a new state object. Time enters as an EVENT (`turn_timeout`), never as\n * a clock read — same discipline as the turn reducer's heartbeat counter.\n */\n\nimport type { ChatMessage, MessageImage } from '../chat/message';\nimport type { MessageAuthor } from './events';\nimport type { AgentTurnState } from './state';\nimport { makeUserMessage, foldAssistantTurn, mergeConversationMessages } from './transcript';\nimport { COPY } from '../copy.generated';\n\n/**\n * A turn that settled WITHOUT its answer because the engine is still working\n * (`AgentTurnState.deferred`). Not a failure: nothing to retry, the answer lands\n * in the thread out of band and the shell shows this until the thread refreshes.\n */\nexport interface TurnNotice {\n kind: 'deferred';\n message: string;\n}\n\nexport function deferredNotice(author: MessageAuthor): TurnNotice {\n return {\n kind: 'deferred',\n message: COPY.turnDeferredNotice(author.name),\n };\n}\n\n/** Why a turn failed, in terms a shell can render a recovery banner from. */\nexport interface TurnFailure {\n /** `empty` = the turn settled with no text, no reaction and no deferral: silence is a failure. */\n kind: 'stream' | 'timeout' | 'empty';\n message: string;\n}\n\n/**\n * What a failed turn hands back so the shell can restore it into the composer.\n * Carries the WHOLE message: returning only the text let a shell re-send a\n * prompt whose images had silently ceased to exist.\n */\nexport interface UnsentDraft {\n text: string | null;\n images: MessageImage[] | null;\n}\n\n/** The reduced state of the conversation. */\nexport interface ConversationState {\n /** The visible thread. */\n messages: ChatMessage[];\n /** Set while an optimistically-pushed turn is still in flight; gates the fold. */\n pending: boolean;\n /** A recoverable turn failure the shell renders instead of a zombie panel. */\n failure: TurnFailure | null;\n /** The last turn was released without its answer; shown until the thread refreshes. */\n notice: TurnNotice | null;\n /** True once a turn timed out; keeps the watchdog from re-arming on it. */\n timedOut: boolean;\n /** What a failed turn handed back, for the shell to restore. */\n unsent: UnsentDraft;\n /** The last send, replayed verbatim by a retry (text AND images). */\n lastSent: { text: string; images?: MessageImage[] } | null;\n /**\n * True when the current `messages` change is NOT a confirmed, settled turn\n * (the mount seed, a conversation switch, the optimistic push). A shell\n * persists only when this is false, so a failed turn never leaves a durable\n * lone user message.\n */\n skipPersist: boolean;\n}\n\nexport type ConversationEvent =\n /** The user sent. `controlled` shells do not get an optimistic push. */\n | {\n type: 'send';\n text: string;\n images?: MessageImage[];\n author: MessageAuthor;\n controlled: boolean;\n }\n /** The transport finished cleanly. Folds the assistant turn in. */\n /** `stopped`: the USER ended the turn; an empty settle is then a choice, not a failure. */\n | { type: 'turn_settled'; turn: AgentTurnState; author: MessageAuthor; controlled: boolean; stopped?: boolean }\n /**\n * The transport reported failure. `appHandled` means the app renders its own\n * banner for this error class (e.g. a 401 token gate), so the generic\n * recoverable failure is suppressed — the revert still happens either way.\n */\n | { type: 'turn_failed'; message?: string; controlled: boolean; appHandled?: boolean }\n /** The idle watchdog fired. Time as an event keeps the reducer pure. */\n | { type: 'turn_timeout'; controlled: boolean }\n | { type: 'dismiss_failure' }\n | { type: 'dismiss_notice' }\n /** The shell restored `unsent` into its composer. */\n | { type: 'clear_unsent' }\n /** Load a different conversation (or start a fresh one). */\n | { type: 'hydrate'; messages: ChatMessage[] }\n /**\n * The server's copy of THIS thread arrived (a worker appended mid-turn). It is\n * unioned into the live thread; the pending turn is untouched and the merge is not a confirmed turn.\n */\n | { type: 'merge_seed'; messages: ChatMessage[] }\n /**\n * The shell CONSUMED the skip: it saw `skipPersist` and declined to persist\n * this change. One-shot — the flag clears so the NEXT confirmed change\n * persists normally. (Getting this backwards makes the shell skip forever and\n * nothing is ever saved.)\n */\n | { type: 'persist_skip_consumed' };\n\nexport function initialConversationState(seed: ChatMessage[] = []): ConversationState {\n return {\n messages: seed,\n pending: false,\n failure: null,\n notice: null,\n timedOut: false,\n unsent: { text: null, images: null },\n lastSent: null,\n // The mount seed is not a confirmed turn.\n skipPersist: true,\n };\n}\n\nconst NO_DRAFT: UnsentDraft = { text: null, images: null };\n\n/**\n * Revert the optimistic user message that is still the thread's tail, handing\n * its content back as `unsent`.\n *\n * Reverting used to DESTROY what the user wrote: the message left the thread and\n * existed nowhere else, so a turn the watchdog killed took the prompt with it.\n * Both failure paths (transport error, timeout) route through here so neither can\n * forget — and it hands back the images too, because the composer already cleared\n * its drafts on send.\n */\nfunction revertOptimistic(state: ConversationState, controlled: boolean): ConversationState {\n // A controlled shell never pushed an optimistic message — nothing to revert.\n if (controlled) return state;\n const last = state.messages[state.messages.length - 1];\n if (last?.role !== 'user') return state;\n return {\n ...state,\n messages: state.messages.slice(0, -1),\n unsent: {\n text: last.content,\n images: last.images && last.images.length > 0 ? last.images : null,\n },\n };\n}\n\n/** Pure reducer: apply one conversation event, returning a new state. */\nexport function applyConversationEvent(\n state: ConversationState,\n event: ConversationEvent,\n): ConversationState {\n switch (event.type) {\n case 'send': {\n const text = event.text.trim();\n const images = event.images && event.images.length > 0 ? event.images : undefined;\n // An image-only send is valid (the picture IS the message); a truly empty\n // one is a no-op.\n if (!text && !images) return state;\n const next: ConversationState = {\n ...state,\n pending: true,\n failure: null,\n notice: null,\n timedOut: false,\n // A new send supersedes any draft still waiting to be recovered.\n unsent: NO_DRAFT,\n lastSent: { text, ...(images ? { images } : {}) },\n // The optimistic push is not a confirmed turn.\n skipPersist: true,\n };\n if (event.controlled) return next;\n return {\n ...next,\n messages: [...state.messages, makeUserMessage(text, event.author, images)],\n };\n }\n\n case 'turn_settled': {\n if (!state.pending) return state;\n const base = { ...state, pending: false };\n // Controlled shells never fold: the consumer's own thread already holds the\n // turn it mapped from its transport. A turn that said nothing AND made no\n // gesture folds nothing; a reaction-only turn (empty text, `reactions`\n // set — server-bot F5) IS an answer and gets its bubble.\n if (event.controlled || (!event.turn.text && event.turn.reactions.length === 0)) {\n if (event.turn.deferred) {\n return { ...base, notice: deferredNotice(event.turn.author ?? event.author) };\n }\n if (event.controlled) return base;\n // A stop leaves the question on screen, so it is saved: a fresh array lets a thread-keyed shell see it.\n if (event.stopped) return { ...base, messages: [...state.messages], skipPersist: false };\n // Silence is not an answer: a turn that said nothing and made no gesture\n // left the user's message hanging with no sign of what happened.\n return {\n ...revertOptimistic(base, false),\n failure: { kind: 'empty', message: COPY.turnEmpty },\n };\n }\n return {\n ...base,\n messages: [...state.messages, foldAssistantTurn(event.turn, event.author)],\n // A settled turn IS confirmed — this one gets persisted.\n skipPersist: false,\n };\n }\n\n case 'turn_failed': {\n if (!state.pending) return state;\n const reverted = revertOptimistic({ ...state, pending: false }, event.controlled);\n // The revert always happens; only the generic banner is suppressed when the\n // app owns this error class.\n if (event.appHandled) return reverted;\n return {\n ...reverted,\n failure: {\n kind: 'stream',\n message: event.message || COPY.turnFailed,\n },\n };\n }\n\n case 'turn_timeout': {\n if (!state.pending || state.timedOut) return state;\n return {\n ...revertOptimistic({ ...state, pending: false }, event.controlled),\n timedOut: true,\n failure: { kind: 'timeout', message: COPY.turnTimeout },\n };\n }\n\n case 'dismiss_failure':\n return state.failure === null ? state : { ...state, failure: null, timedOut: false };\n\n case 'dismiss_notice':\n return state.notice === null ? state : { ...state, notice: null };\n\n case 'clear_unsent':\n return state.unsent.text === null && state.unsent.images === null\n ? state\n : { ...state, unsent: NO_DRAFT };\n\n case 'hydrate':\n return { ...initialConversationState(event.messages), lastSent: state.lastSent };\n\n case 'merge_seed': {\n const messages = mergeConversationMessages(state.messages, event.messages);\n return messages === state.messages ? state : { ...state, messages, skipPersist: true };\n }\n\n case 'persist_skip_consumed':\n return state.skipPersist ? { ...state, skipPersist: false } : state;\n\n default:\n return state;\n }\n}\n","/**\n * conversationToMarkdown — la conversación como un archivo que alguien se lleva.\n *\n * Función pura sobre el record: sin React, sin navegador, sin descarga. Quien\n * quiera entregarlo (un Blob en el browser, un archivo en disco, un adjunto de\n * correo) pone ESA parte; aquí sólo vive la forma del documento, que es lo que\n * se repite en cada shell.\n *\n * Markdown y no PDF ni HTML porque el destino real es seguir trabajando: se\n * pega en un cuaderno digital, se abre en cualquier editor, se lee tal cual en\n * texto plano si no hay nada más a la mano.\n */\n\nimport type { ChatMessage } from '../chat/message';\nimport type { ConversationRecord } from './record';\n\nexport interface ConversationMarkdownOptions {\n /** Cómo se nombra a cada lado. Default: `Tú` / `Asistente`. */\n labels?: { user?: string; assistant?: string };\n /** Línea de procedencia bajo el título (de dónde salió esta conversación). */\n source?: string;\n}\n\nfunction etiqueta(m: ChatMessage, o: ConversationMarkdownOptions): string {\n if (m.role === 'user') return o.labels?.user ?? 'Tú';\n if (m.role === 'assistant') return o.labels?.assistant ?? 'Asistente';\n return m.role;\n}\n\n/** El documento completo, listo para escribir a un archivo `.md`. */\nexport function conversationToMarkdown(\n record: ConversationRecord,\n options: ConversationMarkdownOptions = {},\n): string {\n const partes: string[] = [`# ${record.title || 'Conversación'}`, ''];\n\n const fecha = record.createdAt || record.updatedAt;\n if (fecha) partes.push(`*${new Date(fecha).toLocaleString()}*`, '');\n if (options.source) partes.push(`*${options.source}*`, '');\n\n for (const m of record.messages) {\n const contenido = (m.content ?? '').trim();\n if (!contenido) continue;\n partes.push(`## ${etiqueta(m, options)}`, '', contenido, '');\n }\n\n return `${partes.join('\\n').trimEnd()}\\n`;\n}\n\n/**\n * Un nombre de archivo seguro derivado del título.\n *\n * Los títulos vienen del primer mensaje del usuario, así que traen de todo:\n * `/`, `:`, saltos de línea, emoji. Un nombre sin sanear rompe la descarga en\n * silencio o crea directorios que nadie pidió.\n */\nexport function conversationFileName(record: ConversationRecord): string {\n const base = (record.title || 'conversacion')\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .replace(/[^\\w\\s-]/g, '')\n .trim()\n .replace(/\\s+/g, '-')\n .slice(0, 60)\n .replace(/-+$/, '');\n return `${base || 'conversacion'}.md`;\n}\n","/**\n * Conversation helpers — pure, deterministic primitives for building and\n * summarizing ConversationRecords. No React, no browser, no transport.\n *\n * Privacy by structure: `sanitizeConversationMessage` builds a NEW message with\n * exactly the allowed subset (role / content / timestamp). Any other field a\n * ChatMessage may carry now or later — `id`, `thinking`, `metadata`, a future\n * tool payload or token — is dropped by construction, not by an allow/deny list\n * someone must remember to update. The initial privacy guarantee is the\n * restriction, not PII heuristics.\n *\n * Determinism: helpers that stamp a time accept an optional `now` so tests are\n * reproducible; they fall back to the wall clock only when it is omitted.\n */\n\nimport { COPY } from '../copy.generated';\nimport type { ChatMessage } from '../chat/message';\nimport type { ConversationRecord, ConversationSummary } from './record';\n\n/** Schema version stamped on every record created here. */\nexport const CONVERSATION_SCHEMA_VERSION = 1;\n\n/** Fallback title when there is no usable user message yet. */\nconst DEFAULT_TITLE = COPY.conversationDefaultTitle;\nconst TITLE_MAX = 60;\nconst PREVIEW_MAX = 120;\n\n/** Collapse whitespace and truncate to `max` chars with an ellipsis. Pure. */\nfunction truncate(text: string, max: number): string {\n const t = text.trim().replace(/\\s+/g, ' ');\n if (t.length <= max) return t;\n return `${t.slice(0, Math.max(0, max - 1)).trimEnd()}…`;\n}\n\n/**\n * Reduce a ChatMessage to the fields safe to persist: role, author, content,\n * timestamp, plus the glass-box `trace` when present (B3-FIGLASS-TRACE-\n * PERSISTENCE-1).\n *\n * Privacy by structure: `metadata` is DROPPED on purpose — apps stuff secrets\n * there (a `Bearer` token, tool payloads), so it must never reach durable\n * storage. `trace` and `author` are the deliberate exceptions, not holes in that\n * boundary: both carry only non-sensitive, already-user-visible provenance —\n * plan-step labels/summaries (model-authored, rendered live), tool NAMES (core's\n * ToolCall is {id,name,server,isError} — no arguments/payloads), source URLs,\n * and the public name of the persona that spoke. Persisting what the live turn\n * already showed leaks nothing new — and dropping the author would re-anonymize\n * every bubble on reload, which is the bug the contract exists to prevent.\n * Included only when present, so a plain message stays minimal; id, thinking and\n * metadata are still dropped by construction.\n */\nexport function sanitizeConversationMessage(message: ChatMessage): ChatMessage {\n return {\n role: message.role,\n content: message.content,\n timestamp: message.timestamp,\n ...(message.author ? { author: message.author } : {}),\n ...(message.trace ? { trace: message.trace } : {}),\n // Attached images are user-visible message CONTENT (OG118-IMAGE-UPLOAD-1),\n // not metadata — dropping them would blank the picture on reload the way\n // dropping `author` used to anonymize bubbles. Producers downscale before\n // encoding, so the persisted base64 stays within the record size caps.\n ...(message.images && message.images.length > 0\n ? { images: message.images.map((i) => ({ mediaType: i.mediaType, data: i.data })) }\n : {}),\n // The speaker's reactions are user-visible too (chips under the bubble);\n // dropping them would strip the gesture on reload. Plain strings, no payload.\n ...(message.reactions && message.reactions.length > 0\n ? { reactions: message.reactions.map(String) }\n : {}),\n };\n}\n\n/** Title from the first non-empty user message; `DEFAULT_TITLE` otherwise. */\nexport function deriveConversationTitle(\n messages: ChatMessage[],\n max: number = TITLE_MAX,\n): string {\n const firstUser = messages.find(\n (m) => m.role === 'user' && m.content.trim() !== '',\n );\n if (!firstUser) return DEFAULT_TITLE;\n return truncate(firstUser.content, max) || DEFAULT_TITLE;\n}\n\n/** Preview from the last non-empty message of any role; `''` otherwise. */\nexport function deriveConversationPreview(\n messages: ChatMessage[],\n max: number = PREVIEW_MAX,\n): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].content.trim() !== '') {\n return truncate(messages[i].content, max);\n }\n }\n return '';\n}\n\n/** Arguments for {@link createConversationRecord}. */\nexport interface CreateConversationRecordArgs {\n /** Stable id (doubles as the backend session_id). */\n id: string;\n /** Initial thread; sanitized before storing. Default: empty. */\n messages?: ChatMessage[];\n /** ISO timestamp to stamp createdAt/updatedAt. Default: now. */\n now?: string;\n}\n\n/** Build a fresh, sanitized record with derived title + preview. */\nexport function createConversationRecord(\n args: CreateConversationRecordArgs,\n): ConversationRecord {\n const now = args.now ?? new Date().toISOString();\n const messages = (args.messages ?? []).map(sanitizeConversationMessage);\n return {\n id: args.id,\n title: deriveConversationTitle(messages),\n createdAt: now,\n updatedAt: now,\n messages,\n preview: deriveConversationPreview(messages),\n schemaVersion: CONVERSATION_SCHEMA_VERSION,\n };\n}\n\n/**\n * Resolve the title to stamp when persisting messages: a user-set (custom)\n * title is preserved; otherwise it is derived from the messages. This is the\n * SSOT that keeps `persist` from clobbering a rename on the next message.\n */\nexport function resolveConversationTitle(\n messages: ChatMessage[],\n prev?: { title: string; titleCustom?: boolean },\n): string {\n if (prev?.titleCustom && prev.title.trim() !== '') return prev.title;\n return deriveConversationTitle(messages);\n}\n\n/**\n * The metadata delta of an organization mutation (rename / pin / archive).\n *\n * These three mutations used to exist only as whole-record transforms, which\n * forced every transport to ship the whole record — and a whole-record write\n * from a device holding a stale copy silently drops the flags it never meant to\n * touch (CONV-CONCURRENCY-1). The delta expresses the same semantics as the\n * SMALLEST thing that changed, so a transport can send just that.\n *\n * `null` means CLEAR the field; an omitted key means LEAVE IT ALONE. That is\n * precisely the distinction a full-record put cannot express — an absent field\n * and a deliberately-cleared one look identical on the wire.\n */\nexport interface ConversationMetadataPatch {\n title?: string;\n titleCustom?: boolean;\n /** ISO timestamp to pin at, or `null` to unpin. */\n pinnedAt?: string | null;\n /** ISO timestamp to archive at, or `null` to unarchive. */\n archivedAt?: string | null;\n /** Only a rename stamps this: pinning/archiving must not fake recency. */\n updatedAt?: string;\n}\n\n/**\n * Apply a metadata delta to a record. `null` clears the field, an omitted key\n * leaves it untouched. Pure — the single place the merge rule is written, so the\n * local (apply-then-put) and remote (send-the-delta) paths cannot drift.\n */\nexport function applyConversationMetadataPatch(\n record: ConversationRecord,\n patch: ConversationMetadataPatch,\n): ConversationRecord {\n const next: ConversationRecord = { ...record };\n if (patch.title !== undefined) next.title = patch.title;\n if (patch.titleCustom !== undefined) next.titleCustom = patch.titleCustom;\n if (patch.updatedAt !== undefined) next.updatedAt = patch.updatedAt;\n if (patch.pinnedAt !== undefined) {\n if (patch.pinnedAt === null) delete next.pinnedAt;\n else next.pinnedAt = patch.pinnedAt;\n }\n if (patch.archivedAt !== undefined) {\n if (patch.archivedAt === null) delete next.archivedAt;\n else next.archivedAt = patch.archivedAt;\n }\n return next;\n}\n\n/**\n * The delta of a user rename. A non-empty title is stored verbatim (trimmed,\n * whitespace-collapsed, capped at TITLE_MAX) and marks the record `titleCustom`\n * so future persists never re-derive it. An empty/whitespace title reverts to\n * the derived title and clears the custom flag (emptyTitlePolicy:\n * revert-to-derived). Needs the record because reverting has to re-derive from\n * its messages.\n */\nexport function conversationRenamePatch(\n record: ConversationRecord,\n rawTitle: string,\n now?: string,\n): ConversationMetadataPatch {\n const trimmed = rawTitle.trim().replace(/\\s+/g, ' ');\n const ts = now ?? new Date().toISOString();\n if (trimmed === '') {\n return {\n title: deriveConversationTitle(record.messages),\n titleCustom: false,\n updatedAt: ts,\n };\n }\n return { title: trimmed.slice(0, TITLE_MAX), titleCustom: true, updatedAt: ts };\n}\n\n/**\n * The delta of a pin/unpin. Pinning lifts the record out of the archive — a pin\n * is an explicit \"keep this in front of me\", incompatible with archived.\n * `updatedAt` is deliberately absent: pinning is organization, not content, and\n * must not fake recency in the active list.\n */\nexport function conversationPinPatch(\n pinned: boolean,\n now?: string,\n): ConversationMetadataPatch {\n if (pinned) {\n return { pinnedAt: now ?? new Date().toISOString(), archivedAt: null };\n }\n return { pinnedAt: null };\n}\n\n/**\n * The delta of an archive/unarchive. Archiving clears any pin (an archived\n * conversation cannot stay in the pinned section). Unarchiving rejoins the\n * active list at the record's own `updatedAt`, which — like pinning — is not\n * touched.\n */\nexport function conversationArchivePatch(\n archived: boolean,\n now?: string,\n): ConversationMetadataPatch {\n if (archived) {\n return { archivedAt: now ?? new Date().toISOString(), pinnedAt: null };\n }\n return { archivedAt: null };\n}\n\n/**\n * Apply a user rename to a record. Thin composition of the delta and the merge\n * rule above — kept so callers holding a whole record (the local, single-writer\n * path) do not each re-implement it.\n */\nexport function renameConversationRecord(\n record: ConversationRecord,\n rawTitle: string,\n now?: string,\n): ConversationRecord {\n return applyConversationMetadataPatch(\n record,\n conversationRenamePatch(record, rawTitle, now),\n );\n}\n\n/** Pin or unpin a record (whole-record form of `conversationPinPatch`). */\nexport function setConversationPinned(\n record: ConversationRecord,\n pinned: boolean,\n now?: string,\n): ConversationRecord {\n return applyConversationMetadataPatch(record, conversationPinPatch(pinned, now));\n}\n\n/** Archive or unarchive a record (whole-record form of `conversationArchivePatch`). */\nexport function setConversationArchived(\n record: ConversationRecord,\n archived: boolean,\n now?: string,\n): ConversationRecord {\n return applyConversationMetadataPatch(\n record,\n conversationArchivePatch(archived, now),\n );\n}\n\n/** Project a record to its light summary — excludes `messages`. */\nexport function summarizeConversation(\n record: ConversationRecord,\n): ConversationSummary {\n return {\n id: record.id,\n title: record.title,\n createdAt: record.createdAt,\n updatedAt: record.updatedAt,\n preview: record.preview,\n ...(record.pinnedAt ? { pinnedAt: record.pinnedAt } : {}),\n ...(record.archivedAt ? { archivedAt: record.archivedAt } : {}),\n ...(record.projectId ? { projectId: record.projectId } : {}),\n };\n}\n\n/** Lowercase + strip diacritics, so \"métodos\" matches \"metodos\" (es-MX). */\nfunction normalizeForSearch(text: string): string {\n return text\n .toLowerCase()\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '');\n}\n\n/**\n * Filter summaries by a free-text query over title + preview (CONV-SEARCH-1).\n * Case- and diacritic-insensitive; every whitespace-separated term must match\n * somewhere (AND semantics). An empty/whitespace query returns the input\n * untouched. Pure — feed the result to {@link organizeConversationSummaries}.\n */\nexport function filterConversationSummaries(\n summaries: ConversationSummary[],\n query: string,\n): ConversationSummary[] {\n const terms = normalizeForSearch(query).split(/\\s+/).filter(Boolean);\n if (terms.length === 0) return summaries;\n return summaries.filter((s) => {\n const haystack = normalizeForSearch(`${s.title} ${s.preview}`);\n return terms.every((t) => haystack.includes(t));\n });\n}\n\n/** The sidebar's three sections, each already in display order. */\nexport interface OrganizedConversations {\n /** Pinned, last-pinned first. */\n pinned: ConversationSummary[];\n /** Neither pinned nor archived, most recently updated first. */\n active: ConversationSummary[];\n /** Archived, most recently archived first. */\n archived: ConversationSummary[];\n}\n\n/**\n * Split summaries into the pinned / active / archived sections every sidebar\n * renders. Pure and total: a summary lands in exactly one section (`archivedAt`\n * wins over a stray `pinnedAt`, though the pin/archive transformers never\n * produce that state). ISO 8601 timestamps sort lexicographically.\n */\nexport function organizeConversationSummaries(\n summaries: ConversationSummary[],\n): OrganizedConversations {\n const pinned: ConversationSummary[] = [];\n const active: ConversationSummary[] = [];\n const archived: ConversationSummary[] = [];\n for (const s of summaries) {\n if (s.archivedAt) archived.push(s);\n else if (s.pinnedAt) pinned.push(s);\n else active.push(s);\n }\n pinned.sort((a, b) => (b.pinnedAt ?? '').localeCompare(a.pinnedAt ?? ''));\n active.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n archived.sort((a, b) => (b.archivedAt ?? '').localeCompare(a.archivedAt ?? ''));\n return { pinned, active, archived };\n}\n"],"mappings":";AAuFO,SAAS,wBAAwC;AACtD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,OAAO,CAAC;AAAA,IACR,MAAM;AAAA,IACN,SAAS,CAAC;AAAA,IACV,WAAW,CAAC;AAAA,IACZ,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,YAAY;AAAA,IACZ,UAAU;AAAA,IACV,QAAQ;AAAA,EACV;AACF;AASO,SAAS,gBACd,OACA,OACgB;AAIhB,QAAM,kBACJ,MAAM,WAAW,aAAa,cAA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EAAE,cAAc,EAAE,CAAC;AAC9E,SAAO,EAAE,QAAQ,QAAQ,SAAS;AACpC;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@free-intelligence/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.0",
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "https://github.com/BernardUriza/free-intelligence",
|
|
7
|
+
"directory": "apps/packages/free-intelligence-core"
|
|
8
|
+
},
|
|
9
|
+
"sideEffects": false,
|
|
4
10
|
"license": "PolyForm-Noncommercial-1.0.0",
|
|
5
11
|
"type": "module",
|
|
6
12
|
"description": "Material-agnostic substrate-facing layer: theme-token contract, agent event contract, fi-runner client. Consumed directly by apps and by every fi-<material> skin.",
|
|
@@ -10,6 +16,10 @@
|
|
|
10
16
|
".": {
|
|
11
17
|
"types": "./dist/index.d.ts",
|
|
12
18
|
"import": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./availability": {
|
|
21
|
+
"types": "./dist/availability/index.d.ts",
|
|
22
|
+
"import": "./dist/availability/index.js"
|
|
13
23
|
}
|
|
14
24
|
},
|
|
15
25
|
"files": [
|
|
@@ -21,11 +31,30 @@
|
|
|
21
31
|
"react-dom": ">=18"
|
|
22
32
|
},
|
|
23
33
|
"devDependencies": {
|
|
34
|
+
"json-schema-to-typescript": "^15.0.4",
|
|
24
35
|
"tsup": "^8.5.1"
|
|
25
36
|
},
|
|
26
37
|
"scripts": {
|
|
27
38
|
"build": "tsup",
|
|
28
39
|
"type-check": "tsc --noEmit",
|
|
29
|
-
"test": "vitest run"
|
|
40
|
+
"test": "vitest run",
|
|
41
|
+
"gen:events": "node scripts/gen-wire-events.mjs",
|
|
42
|
+
"check:events": "node scripts/gen-wire-events.mjs --check",
|
|
43
|
+
"gen:swift-events": "node scripts/gen-swift-events.mjs",
|
|
44
|
+
"check:swift-events": "node scripts/gen-swift-events.mjs --check",
|
|
45
|
+
"gen:swift-record": "node scripts/gen-swift-record.mjs",
|
|
46
|
+
"check:swift-record": "node scripts/gen-swift-record.mjs --check",
|
|
47
|
+
"gen:record-types": "node scripts/gen-record-types.mjs",
|
|
48
|
+
"check:record-types": "node scripts/gen-record-types.mjs --check",
|
|
49
|
+
"gen:swift-theme": "node scripts/gen-swift-theme.mjs",
|
|
50
|
+
"check:swift-theme": "node scripts/gen-swift-theme.mjs --check",
|
|
51
|
+
"gen:copy": "node scripts/gen-copy.mjs",
|
|
52
|
+
"check:copy": "node scripts/gen-copy.mjs --check",
|
|
53
|
+
"gen:swift-copy": "node scripts/gen-swift-copy.mjs",
|
|
54
|
+
"check:swift-copy": "node scripts/gen-swift-copy.mjs --check",
|
|
55
|
+
"gen:theme-tokens": "node scripts/gen-theme-tokens.mjs",
|
|
56
|
+
"check:theme-tokens": "node scripts/gen-theme-tokens.mjs --check",
|
|
57
|
+
"check:glass-css": "node scripts/check-glass-css.mjs",
|
|
58
|
+
"check:og118-css": "node scripts/check-og118-css.mjs"
|
|
30
59
|
}
|
|
31
60
|
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* contracts/conversation-state.vectors.json — the thread around a turn, as a
|
|
3
|
+
* contract: optimistic send, fold, failure with the draft handed back, retry,
|
|
4
|
+
* hydration. The ops are abstract so the iPhone's harness can drive ChatModel
|
|
5
|
+
* with the same file; here they become ConversationEvents.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { readFileSync } from 'node:fs';
|
|
9
|
+
import { dirname, resolve } from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { describe, expect, it } from 'vitest';
|
|
12
|
+
import type { ChatMessage } from '../chat/message';
|
|
13
|
+
import type { MessageAuthor } from './events';
|
|
14
|
+
import { initialAgentTurnState } from './state';
|
|
15
|
+
import {
|
|
16
|
+
applyConversationEvent,
|
|
17
|
+
initialConversationState,
|
|
18
|
+
type ConversationState,
|
|
19
|
+
} from './conversation-state';
|
|
20
|
+
|
|
21
|
+
interface Op {
|
|
22
|
+
op: 'send' | 'settled' | 'failed' | 'retry' | 'hydrate' | 'merge_seed' | 'dismiss_failure' | 'clear_unsent';
|
|
23
|
+
text?: string;
|
|
24
|
+
reactions?: string[];
|
|
25
|
+
deferred?: boolean;
|
|
26
|
+
/** The user stopped the turn; an empty settle is then not a failure. */
|
|
27
|
+
stopped?: boolean;
|
|
28
|
+
message?: string;
|
|
29
|
+
/** Text the transport streamed before failing; core reverts regardless. */
|
|
30
|
+
partialText?: string;
|
|
31
|
+
messages?: ChatMessage[];
|
|
32
|
+
}
|
|
33
|
+
interface Vector {
|
|
34
|
+
name: string;
|
|
35
|
+
ops: Op[];
|
|
36
|
+
expect: unknown;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
40
|
+
const contrato = JSON.parse(
|
|
41
|
+
readFileSync(resolve(here, '../../contracts/conversation-state.vectors.json'), 'utf8'),
|
|
42
|
+
) as { version: number; vectors: Vector[] };
|
|
43
|
+
|
|
44
|
+
const USUARIO: MessageAuthor = { id: 'user', name: 'Tú' };
|
|
45
|
+
const AGENTE: MessageAuthor = { id: 'og118', name: 'og118' };
|
|
46
|
+
|
|
47
|
+
function aplicar(state: ConversationState, op: Op): ConversationState {
|
|
48
|
+
switch (op.op) {
|
|
49
|
+
case 'send':
|
|
50
|
+
return applyConversationEvent(state, { type: 'send', text: op.text ?? '', author: USUARIO, controlled: false });
|
|
51
|
+
case 'retry': {
|
|
52
|
+
const last = state.lastSent;
|
|
53
|
+
if (!last) return state;
|
|
54
|
+
return applyConversationEvent(state, { type: 'send', text: last.text, images: last.images, author: USUARIO, controlled: false });
|
|
55
|
+
}
|
|
56
|
+
case 'settled':
|
|
57
|
+
return applyConversationEvent(state, {
|
|
58
|
+
type: 'turn_settled',
|
|
59
|
+
turn: {
|
|
60
|
+
...initialAgentTurnState(),
|
|
61
|
+
text: op.text ?? '',
|
|
62
|
+
reactions: op.reactions ?? [],
|
|
63
|
+
deferred: op.deferred ?? false,
|
|
64
|
+
status: 'done',
|
|
65
|
+
},
|
|
66
|
+
author: AGENTE,
|
|
67
|
+
controlled: false,
|
|
68
|
+
stopped: op.stopped ?? false,
|
|
69
|
+
});
|
|
70
|
+
case 'failed':
|
|
71
|
+
return applyConversationEvent(state, { type: 'turn_failed', message: op.message, controlled: false });
|
|
72
|
+
case 'hydrate':
|
|
73
|
+
return applyConversationEvent(state, { type: 'hydrate', messages: op.messages ?? [] });
|
|
74
|
+
case 'merge_seed':
|
|
75
|
+
return applyConversationEvent(state, { type: 'merge_seed', messages: op.messages ?? [] });
|
|
76
|
+
case 'dismiss_failure':
|
|
77
|
+
return applyConversationEvent(state, { type: 'dismiss_failure' });
|
|
78
|
+
case 'clear_unsent':
|
|
79
|
+
return applyConversationEvent(state, { type: 'clear_unsent' });
|
|
80
|
+
default:
|
|
81
|
+
throw new Error(`op desconocido en el vector: ${(op as { op: string }).op}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface Corrida {
|
|
86
|
+
state: ConversationState;
|
|
87
|
+
saved: ChatMessage[] | null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The shell's persist effect: a changed thread is saved unless the state says skip (consumed once). */
|
|
91
|
+
function aplicarComoShell(corrida: Corrida, op: Op): Corrida {
|
|
92
|
+
const next = aplicar(corrida.state, op);
|
|
93
|
+
if (next.messages === corrida.state.messages) return { ...corrida, state: next };
|
|
94
|
+
if (next.skipPersist) {
|
|
95
|
+
return { ...corrida, state: applyConversationEvent(next, { type: 'persist_skip_consumed' }) };
|
|
96
|
+
}
|
|
97
|
+
return { state: next, saved: next.messages };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const rolYTexto = (m: ChatMessage) => ({ role: m.role, content: m.content });
|
|
101
|
+
|
|
102
|
+
function proyectar({ state: s, saved }: Corrida, expected: unknown) {
|
|
103
|
+
return {
|
|
104
|
+
messages: s.messages.map(rolYTexto),
|
|
105
|
+
failure: s.failure?.kind ?? null,
|
|
106
|
+
unsentText: s.unsent.text,
|
|
107
|
+
lastSentText: s.lastSent?.text ?? null,
|
|
108
|
+
...(expected && typeof expected === 'object' && 'saved' in expected
|
|
109
|
+
? { saved: saved ? saved.map(rolYTexto) : null }
|
|
110
|
+
: {}),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
describe('conversation-state.vectors.json', () => {
|
|
115
|
+
it('declara su versión y trae vectores', () => {
|
|
116
|
+
expect(contrato.version).toBe(1);
|
|
117
|
+
expect(contrato.vectors.length).toBeGreaterThan(0);
|
|
118
|
+
});
|
|
119
|
+
for (const v of contrato.vectors) {
|
|
120
|
+
it(v.name, () => {
|
|
121
|
+
const corrida = v.ops.reduce(aplicarComoShell, { state: initialConversationState(), saved: null });
|
|
122
|
+
expect(proyectar(corrida, v.expect)).toEqual(v.expect);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
});
|