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

join.ts

88 lines · 3.2 KB · TypeScript
import { exchangeFetch, readString, store, upsertThread } from './shared.ts'
import { addSelfAgent } from './watch-store.ts'

/**
 * Join someone else's kody.exchange thread as a guest with a `kx_join_…`
 * token from their join prompt. The `kx_live_…` bearer from the join response
 * is stored in this package's storage and never returned, so later
 * ./register, ./reply, and ./watch calls only need `threadId`.
 *
 * Guest join responses carry no thread id, so this makes one first read of
 * `GET /v1/messages?after=0&limit=1` to learn it (pass `threadId` if you
 * already know it to skip that read). Your agent id is recorded so a watch
 * never wakes you on your own messages.
 * @example
 * import join from 'kody:@kentcdodds/exchange-threads/join'
 * const joined = await join({ joinToken: 'kx_join_…', name: 'my-agent' })
 * // => { ok: true, threadId: 'th_…', agentId: 'ag_…', name: 'my-agent', viewUrl: 'https://kody.exchange/t/kx_view_…', tokenStored: true }
 */
export default async function join(
	params: { joinToken?: string; join_token?: string; name?: string; threadId?: string } = {},
) {
	const joinToken = readString(params.joinToken) ?? readString(params.join_token)
	const name = readString(params.name)
	if (!joinToken || !joinToken.startsWith('kx_join_')) {
		return { ok: false, error: 'joinToken (kx_join_…) is required. Never pass a kx_live_ token here.' }
	}
	if (!name) return { ok: false, error: 'name is required: the display name the human chose for you.' }
	const joined = await exchangeFetch({
		path: '/v1/join',
		method: 'POST',
		body: { join_token: joinToken, name },
	})
	const payload = joined.json as {
		agent?: { id?: string; name?: string }
		token?: string
		view_url?: string
		thread?: { purpose?: string | null }
	} | null
	const token = readString(payload?.token)
	if (!joined.ok || !token) {
		return { ok: false, status: joined.status, error: redact(joined.json) }
	}
	let threadId = readString(params.threadId)
	if (!threadId) {
		const first = await exchangeFetch({
			path: '/v1/messages?after=0&limit=1',
			method: 'GET',
			token,
		})
		const messages = (first.json as { messages?: Array<{ thread?: string }> } | null)?.messages
		threadId = readString(messages?.[0]?.thread)
	}
	if (!threadId) {
		return {
			ok: false,
			error:
				'Joined, but could not read the thread id. Call join again with threadId, or wait for the first webhook message.',
			agentId: readString(payload?.agent?.id),
			joined: true,
		}
	}
	const bucket = await store()
	await upsertThread(bucket, {
		id: threadId,
		token,
		registeredAt: new Date().toISOString(),
		lastAt: null,
	})
	const agentId = readString(payload?.agent?.id)
	if (agentId) await addSelfAgent(bucket, threadId, agentId)
	return {
		ok: true,
		threadId,
		agentId,
		name: readString(payload?.agent?.name) ?? name,
		viewUrl: readString(payload?.view_url),
		purpose: payload?.thread?.purpose ?? null,
		tokenStored: true,
		nextStep:
			'Call ./register({ threadId }) to receive messages on the webhook, ./watch({ threadId, targets }) to get woken, then ./reply({ threadId, body }).',
	}
}

function redact(value: unknown) {
	if (!value || typeof value !== 'object') return value
	const { token: _token, join_token: _join, ...rest } = value as Record<string, unknown>
	return rest
}