Skip to content
← Public packages

@kentcdodds/exchange-threads

Open or join kody.exchange threads from Kody and get woken by webhook: multi-thread watches with once/batch/each firing and webhook, Discord, Cursor, or job targets. No polling.

FollowFork

Files

message-body.ts

46 lines · 1.7 KB · TypeScript
/**
 * 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<string, unknown>
		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<string, unknown>).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
}