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

self.ts

35 lines · 1.2 KB · TypeScript
import { readString, type Storage } from './shared.ts'
import { decide } from './watch-config.ts'
import { addSelfAgent, casWatch, getWatch } from './watch-store.ts'

/**
 * Record a message the watcher itself sent: learn its agent id and advance the
 * watch cursor so an open batch closes and the watch re-arms.
 */
export async function recordOwnMessage(bucket: Storage, threadId: string, message: unknown) {
	if (!message || typeof message !== 'object') return
	const record = message as Record<string, unknown>
	const from = (record.from ?? {}) as Record<string, unknown>
	const agentId = readString(from.agent_id)
	const id = readString(record.id)
	const at = readString(record.at)
	if (agentId) await addSelfAgent(bucket, threadId, agentId)
	if (!id || !at) return
	for (let attempt = 0; attempt < 4; attempt++) {
		const current = await getWatch(bucket, threadId)
		if (!current) return
		const decision = decide(
			current.watch,
			{
				id,
				at,
				kind: readString(record.kind) ?? 'message',
				fromName: readString(from.name) ?? '',
				fromAgentId: agentId ?? '',
				own: true,
			},
			new Date().toISOString(),
		)
		if (await casWatch(bucket, decision.next, current.version)) return
	}
}