// Anthropic's Messages wire (architecture, "The kernel owns shared mechanics"): the Messages shapes a vendor serves as // Anthropic defines them (https://platform.claude.com/docs/en/api/messages and /build-with-claude/streaming), for // generative packs that run no model, beside the OpenAI wire (./openai-wire.ts) whose turn vocabulary it answers. A // pack decides its turn (the World's scenario's, else the stub) and its own facts (its ids, its usage fields); this // module reads a request as the scenario reads it and shapes the answer and its Server-Sent Events. Importing it does // nothing. import { estimateTokens, forbidsTools, type WireRequest, type WireTurn } from './openai-wire.ts'; import { sampleFromSchema } from './schema-sample.ts'; type Row = Record; const obj = (v: unknown): Row => (v && typeof v === 'object' && !Array.isArray(v) ? v as Row : {}); const arr = (v: unknown): Row[] => (Array.isArray(v) ? v as Row[] : []); /** A message's content as text: a string, or its text blocks (and the text of its tool results) joined. */ export const messagesText = (content: unknown): string => typeof content === 'string' ? content : arr(content).map((c) => (c.type === 'text' ? String(c.text ?? '') : c.type === 'tool_result' ? messagesText(c.content) : '')).filter(Boolean).join('\n'); /** The last user message's text. */ export function messagesLastUserText(messages: Row[]): string { for (let i = messages.length - 1; i >= 0; i--) if (messages[i]!.role === 'user') { const t = messagesText(messages[i]!.content); if (t) return t; } return ''; } /** The tool results the last message carries, by the names of the tool_use blocks they answer. */ export function messagesToolResults(messages: Row[]): string[] { const ids = arr(messages.at(-1)?.content).filter((c) => c.type === 'tool_result').map((c) => c.tool_use_id); if (!ids.length) return []; return messages.flatMap((m) => arr(m.content)).filter((c) => c.type === 'tool_use' && ids.includes(c.id)).map((c) => String(c.name)); } /** A Messages request as a scenario reads it (the OpenAI wire's `WireRequest`): its model, its system and messages' * text, its last user text, the tools it offers and the tool results it ends with. */ export function messagesWireRequest(body: Row): WireRequest { const messages = arr(body.messages); const system = typeof body.system === 'string' ? body.system : messagesText(body.system); return { model: String(body.model ?? ''), text: [system, ...messages.map((m) => messagesText(m.content))].join('\n'), lastUser: messagesLastUserText(messages), tools: arr(body.tools).map((t) => String(t.name ?? '')).filter(Boolean), results: messagesToolResults(messages), ...(forbidsTools(body.tool_choice) ? { toolsForbidden: true } : {}), }; } /** The labeled stub for a Messages request: with tools offered (`tool_choice` not `none`) and the last message not a * tool's result, it calls the tool the choice names, else the first, with input its schema admits; with a JSON schema * for the output, it answers a value the schema admits; otherwise it echoes the last user message. `label` names the * twin. */ export function messagesStubTurn(body: Row, label: string): WireTurn { const model = String(body.model); const messages = arr(body.messages); const tools = arr(body.tools).filter((t) => t.input_schema !== undefined); const choice = obj(body.tool_choice ?? { type: 'auto' }); if (tools.length && choice.type !== 'none' && (messagesToolResults(messages).length === 0 || choice.type === 'any' || choice.type === 'tool')) { const tool = (choice.type === 'tool' ? tools.find((t) => t.name === choice.name) : undefined) ?? tools[0]!; return { toolCalls: [{ name: String(tool.name), arguments: sampleFromSchema(tool.input_schema, String(tool.name)) as Row }] }; } const format = obj(obj(body.output_config).format ?? body.output_format); if (format.type === 'json_schema') return { text: JSON.stringify(sampleFromSchema(format.schema)) }; const said = messagesLastUserText(messages).trim(); return { text: `[twin-stub:${model}] This is a deterministic stub from the ${label} (no model runs). Your last message: ${said.length > 200 ? `${said.slice(0, 200)}…` : said || '(empty)'}` }; } /** The OpenAI wire's finish reasons as the Messages stop reasons they mean. */ const STOP: Record = { stop: 'end_turn', length: 'max_tokens', tool_calls: 'tool_use', content_filter: 'refusal' }; export type MessageShape = { id: string; model: string; turn: WireTurn; body: Row; /** each tool_use block's id, and the thinking block's signature */ toolId: (i: number) => string; signature?: (thinking: string) => string; /** usage fields the vendor adds (service_tier, the prompt cache's counts) */ usage?: Row; }; /** A message (`type: message`): a thinking block when the request turns thinking on, then the * text, then the tool_use blocks; its stop reason, and its usage estimated from the request and the answer. A text * longer than `max_tokens` is cut there and stops `max_tokens`. */ export function message(s: MessageShape): Row { const b = s.body; // thinking blocks come only when the request turns thinking on; a turn's reasoning is then their text const thinkingOn = ['enabled', 'adaptive'].includes(String(obj(b.thinking).type)); const max = typeof b.max_tokens === 'number' ? b.max_tokens : undefined; let text = s.turn.text ?? undefined; let cut = false; if (text !== undefined && max !== undefined && estimateTokens(text) > max) { text = text.slice(0, Math.max(1, max) * 4); cut = true; } const content: Row[] = []; if (thinkingOn) { const thinking = s.turn.reasoning ?? '[twin-stub] No model runs here, so there is no reasoning to show.'; content.push({ type: 'thinking', thinking, signature: s.signature ? s.signature(thinking) : '' }); } if (text !== undefined) content.push({ type: 'text', text }); (s.turn.toolCalls ?? []).forEach((c, i) => content.push({ type: 'tool_use', id: s.toolId(i), name: c.name, input: c.arguments ?? {} })); const stop = cut ? 'max_tokens' : s.turn.finishReason ? (STOP[s.turn.finishReason] ?? s.turn.finishReason) : s.turn.toolCalls?.length ? 'tool_use' : 'end_turn'; const request = messagesWireRequest(b); const output = estimateTokens(content.map((c) => (c.type === 'tool_use' ? JSON.stringify(c.input) : String(c.text ?? c.thinking ?? ''))).join('')); return { id: s.id, type: 'message', role: 'assistant', model: s.model, content, stop_reason: stop, stop_sequence: null, usage: { input_tokens: estimateTokens(request.text), cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: output, ...(s.usage ?? {}) }, }; } /** Text in the pieces a stream sends it in: a few words at a time. */ function pieces(text: string): string[] { const words = text.match(/\S+\s*|\s+/g) ?? [text]; const out: string[] = []; for (let i = 0; i < words.length; i += 4) out.push(words.slice(i, i + 4).join('')); return out.length ? out : ['']; } /** A message as the stream's events: message_start (its content empty), per block its start, deltas and stop (a ping * after the first start), message_delta with the stop reason and the output usage, message_stop. `extra` adds fields * a vendor puts on the two closing events (Merge's `routing`). */ export function messageSSE(m: Row, extra: Row = {}, options: { ping?: boolean; completeToolInput?: boolean } = {}): string { const events: string[] = []; const send = (type: string, data: Row): void => { events.push(`event: ${type}\ndata: ${JSON.stringify({ type, ...data })}\n\n`); }; const usage = obj(m.usage); send('message_start', { message: { ...m, content: [], stop_reason: null, stop_sequence: null, usage: { ...usage, output_tokens: 1 } } }); arr(m.content).forEach((block, index) => { if (block.type === 'text') { send('content_block_start', { index, content_block: { type: 'text', text: '' } }); if (index === 0 && options.ping !== false) send('ping', {}); for (const piece of pieces(String(block.text))) send('content_block_delta', { index, delta: { type: 'text_delta', text: piece } }); } else if (block.type === 'thinking') { send('content_block_start', { index, content_block: { type: 'thinking', thinking: '', signature: '' } }); if (index === 0 && options.ping !== false) send('ping', {}); for (const piece of pieces(String(block.thinking))) send('content_block_delta', { index, delta: { type: 'thinking_delta', thinking: piece } }); send('content_block_delta', { index, delta: { type: 'signature_delta', signature: block.signature } }); } else { send('content_block_start', { index, content_block: { ...block, input: {} } }); if (index === 0 && options.ping !== false) send('ping', {}); for (const piece of options.completeToolInput ? [JSON.stringify(block.input)] : pieces(JSON.stringify(block.input))) send('content_block_delta', { index, delta: { type: 'input_json_delta', partial_json: piece } }); } send('content_block_stop', { index }); }); send('message_delta', { delta: { stop_reason: m.stop_reason, stop_sequence: null }, usage: { output_tokens: usage.output_tokens }, ...extra }); send('message_stop', { ...extra }); return events.join(''); } /** An admitted Messages generation failure is an error SSE event, or the native JSON envelope. */ export function messageFailure(error: Row, stream: boolean, requestId?: string): Row | string { const data = { type: 'error', error, ...(stream ? {} : { request_id: requestId ?? null }) }; return stream ? `event: error\ndata: ${JSON.stringify(data)}\n\n` : data; }