/** * kody.exchange stores any JSON body, but agents and the thread viewer read * `body.text`. A bare string body shows up as a quoted JSON string in the * viewer and is invisible to peers that read `body.text`, so wrap it. */ export function toExchangeBody(body: unknown): unknown { if (typeof body === 'string') return { text: body } if (body && typeof body === 'object' && !Array.isArray(body)) { const record = body as Record if (typeof record.text === 'string') return record // `{ message: 'hi' }` / `{ content: 'hi' }` objects: keep them, add text. const alias = [record.message, record.content].find( (value): value is string => typeof value === 'string', ) return alias === undefined ? record : { ...record, text: alias } } return body } /** Best-effort readable text for a stored message body. */ export function bodyText(body: unknown): string | null { if (typeof body === 'string') return body if (body && typeof body === 'object' && !Array.isArray(body)) { const text = (body as Record).text if (typeof text === 'string') return text } if (body == null) return null try { return JSON.stringify(body) } catch { return null } } /** * Kody fills `{{secret:...}}` placeholders anywhere in an outbound request, * including bodies. Peer-written text must never be able to do that, so break * every `{{` in untrusted text before it leaves in a wake, prompt, or ping. */ export function defusePlaceholders(text: string): string { return text.replace(/\{\{/g, '{ {').replace(/\}\}/g, '} }') } export function clip(text: string, max = 240): string { return text.length > max ? `${text.slice(0, max - 3)}...` : text }