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

notify.ts

93 lines · 3.1 KB · TypeScript
import { kody } from 'kody:runtime'
import { createRun } from 'kody:@kentcdodds/cursor/runs'
import sendMeAMessage from 'kody:@kentcdodds/discord/send-me-a-message'
import { isCursorAgentBusyError } from './cursor-busy.ts'
import { clip, defusePlaceholders } from './message-body.ts'
import {
	buildPrompt,
	buildWebhookRequest,
	type NotifyTarget,
	type TargetResult,
	type WakeContext,
	type WebhookTarget,
} from './watch-config.ts'

function errorDetail(error: unknown) {
	const message = error instanceof Error ? error.message : String(error)
	// Gateway errors name the secret and host, never the value. Keep it short.
	return clip(message.replace(/\s+/g, ' '), 300)
}

async function sendWebhook(target: WebhookTarget, ctx: WakeContext): Promise<TargetResult> {
	const request = buildWebhookRequest(target, ctx)
	const controller = new AbortController()
	const timer = setTimeout(() => controller.abort(), target.timeoutMs)
	try {
		// One try only: a retry could double-wake the receiver.
		const response = await fetch(request.url, {
			method: request.method,
			headers: request.headers,
			body: request.body,
			signal: controller.signal,
		})
		await response.body?.cancel().catch(() => {})
		return {
			type: 'webhook',
			ok: response.ok,
			status: response.status,
			detail: response.ok
				? undefined
				: response.headers.get('x-kody-path-segment-warning')
					? 'path segment warning: store only the last URL segment in the secret'
					: undefined,
		}
	} catch (error) {
		if (error instanceof Error && error.name === 'AbortError') {
			return { type: 'webhook', ok: false, status: 0, detail: `timed out after ${target.timeoutMs}ms` }
		}
		return { type: 'webhook', ok: false, status: 0, detail: errorDetail(error) }
	} finally {
		clearTimeout(timer)
	}
}

async function sendOne(target: NotifyTarget, ctx: WakeContext): Promise<TargetResult> {
	try {
		switch (target.type) {
			case 'webhook':
				return await sendWebhook(target, ctx)
			case 'discord': {
				await sendMeAMessage({
					content: [
						'New peer message on a watched kody.exchange thread.',
						`${defusePlaceholders(clip(ctx.fromName, 80))} just wrote (${ctx.batchCount} in this wake).`,
						ctx.viewUrl ? `Watch the thread: ${ctx.viewUrl}` : `Thread: ${ctx.threadId}`,
						'',
						defusePlaceholders(clip(ctx.text || '(empty)', 240)),
					].join('\n'),
				})
				return { type: 'discord', ok: true }
			}
			case 'cursor': {
				try {
					await createRun({ agentId: target.agentId, prompt: buildPrompt(ctx) })
					return { type: 'cursor', ok: true, detail: 'sent' }
				} catch (error) {
					if (!isCursorAgentBusyError(error)) throw error
					return { type: 'cursor', ok: true, detail: 'busy (already awake)' }
				}
			}
			case 'job': {
				await kody.jobRunNow({ id: target.jobId })
				return { type: 'job', ok: true }
			}
		}
	} catch (error) {
		return { type: target.type, ok: false, detail: errorDetail(error) }
	}
}

/** Notify every target. One failing target never blocks the others. */
export async function notifyTargets(targets: NotifyTarget[], ctx: WakeContext) {
	return await Promise.all(targets.map((target) => sendOne(target, ctx)))
}