import { invalid } from './errors.ts' import { breakPlaceholders, clip, safetyLine, sanitizeText, serializeWakeBody, wrapUntrusted } from './text.ts' export type WatchMode = 'once' | 'batch' | 'each' export type WakeTarget = | { type: 'webhook'; url: string; key: string | null; keyHeaders: Array; body: 'envelope' | 'prompt'; timeoutMs: number } | { type: 'job'; jobId: string } export type WatchConfig = { mode: WatchMode minIntervalSeconds: number rewakeAfterSeconds: number includeSystem: boolean skipFromNames: Array note: string | null targets: Array } export type WatchState = { armed: boolean firedOnce: boolean pendingCount: number lastFiredAt: number | null } const idPattern = /^[A-Za-z0-9_.:-]{1,200}$/ const keyHeaderPattern = /^[A-Za-z][A-Za-z0-9-]{0,63}$/ const forbiddenHeaders = new Set(['host', 'content-length', 'content-type', 'cookie', 'transfer-encoding', 'connection']) function requireString(value: unknown, label: string, pattern = idPattern) { if (typeof value !== 'string' || !pattern.test(value.trim())) invalid(`${label} is required (letters, digits, _ . : -).`) return value.trim() } function onlyKeys(value: Record, keys: Array, label: string) { for (const key of Object.keys(value)) { if (!keys.includes(key)) invalid(`Unknown field "${key}" on ${label}. Allowed: ${keys.join(', ')}.`) } } /** Kody secret placeholders start with `{{`; agent-supplied text must never form one. */ function assertNoPlaceholder(value: string, label: string) { if (value.includes('{{') || value.includes('}}')) invalid(`${label} must not contain "{{" or "}}".`) } /** * Validate one wake target. `ownerTargets: false` (public HTTP) allows only * webhook targets: a job target runs a Kody job as the package owner. * A webhook may carry the agent's own `key`, sent only to that exact URL. */ export function parseTarget(value: unknown, options: { ownerTargets: boolean }): WakeTarget { if (!value || typeof value !== 'object' || Array.isArray(value)) invalid('Each target must be an object with a type.') const input = value as Record const type = input.type if (!options.ownerTargets && type !== 'webhook') { invalid('Public HTTP callers may only register webhook targets. Ask the room creator to add other kinds from Kody.') } switch (type) { case 'webhook': { onlyKeys(input, ['type', 'url', 'key', 'keyHeaders', 'body', 'timeoutMs'], 'webhook target') const url = typeof input.url === 'string' ? input.url.trim() : '' if (!/^https:\/\/[A-Za-z0-9.-]+(:\d+)?([/?#].*)?$/.test(url) || url.length > 2000) invalid('webhook url must be https:// with a literal host.') assertNoPlaceholder(url, 'webhook url') let key: string | null = null if (input.key != null) { if (typeof input.key !== 'string' || input.key.length < 8 || input.key.length > 4096 || /[\u0000-\u001F\u007F]/.test(input.key)) { invalid('webhook key must be a printable string of 8 to 4096 characters.') } assertNoPlaceholder(input.key, 'webhook key') key = input.key } const keyHeaders = input.keyHeaders ?? ['Authorization'] if (!Array.isArray(keyHeaders) || keyHeaders.length < 1 || keyHeaders.length > 3) invalid('keyHeaders must list 1 to 3 header names.') for (const name of keyHeaders) { if (typeof name !== 'string' || !keyHeaderPattern.test(name) || forbiddenHeaders.has(name.toLowerCase())) invalid(`Header "${clip(String(name), 40)}" is not allowed.`) } if (input.keyHeaders != null && key == null) invalid('keyHeaders needs key.') const body = input.body ?? 'envelope' if (body !== 'envelope' && body !== 'prompt') invalid('webhook body must be "envelope" or "prompt".') const timeoutMs = input.timeoutMs ?? 8000 if (typeof timeoutMs !== 'number' || timeoutMs < 1000 || timeoutMs > 20000) invalid('timeoutMs must be 1000 to 20000.') return { type: 'webhook', url, key, keyHeaders: keyHeaders as Array, body, timeoutMs } } case 'job': onlyKeys(input, ['type', 'jobId'], 'job target') return { type, jobId: requireString(input.jobId, 'jobId') } default: return invalid('target.type must be webhook or job. Rooms is vendor-neutral: spawners wake Devin, Cursor, or T3 children with their own webhook.') } } /** Validate watch options (exchange-threads style). */ export function parseWatchConfig(input: Record, options: { ownerTargets: boolean }): WatchConfig { const mode = input.mode ?? 'batch' if (mode !== 'once' && mode !== 'batch' && mode !== 'each') invalid('mode must be once, batch, or each.') const seconds = (value: unknown, label: string, fallback: number) => { const out = value === false ? 0 : (value ?? fallback) if (typeof out !== 'number' || !Number.isInteger(out) || out < 0 || out > 86400) invalid(`${label} must be an integer from 0 to 86400.`) return out } const skip = input.skipFromNames ?? [] if (!Array.isArray(skip) || skip.length > 20 || skip.some((name) => typeof name !== 'string')) invalid('skipFromNames must be up to 20 strings.') const note = input.note == null ? null : String(input.note) if (note && note.length > 1000) invalid('note must be 1000 characters or fewer.') if (!Array.isArray(input.targets) || input.targets.length < 1 || input.targets.length > 5) invalid('targets must list 1 to 5 wake targets.') return { mode, minIntervalSeconds: seconds(input.minIntervalSeconds, 'minIntervalSeconds', 0), rewakeAfterSeconds: seconds(input.rewakeAfterSeconds, 'rewakeAfterSeconds', 300), includeSystem: input.includeSystem === true, skipFromNames: (skip as Array).map((name) => name.trim().toLowerCase()).filter(Boolean), note: note ? sanitizeText(note) : null, targets: input.targets.map((target) => parseTarget(target, options)), } } export type WakeMessage = { seq: number; id: string; at: string; kind: string; fromId: string; fromName: string; text: string } export type WakeDecision = { fire: boolean reason: 'fire' | 'own_message' | 'system' | 'already_fired' | 'waiting_for_reply' | 'throttled' batchCount: number next: WatchState } /** * Decide whether one new room message wakes a watcher. * - once: first matching message, then never again until re-armed by `watch`. * - each: every matching message. * - batch: first matching message after the watcher's own last post, then * quiet until they post again (or `rewakeAfterSeconds` passes). * `minIntervalSeconds` throttles; suppressed messages are counted into the * next wake's `batchCount`. There are no timers: a suppressed message alone * does not wake later. */ export function decideWake(input: { config: WatchConfig state: WatchState watcherId: string message: WakeMessage now: number }): WakeDecision { const { config, state, message, now } = input const own = message.fromId === input.watcherId || config.skipFromNames.includes(message.fromName.trim().toLowerCase()) if (own) { return { fire: false, reason: 'own_message', batchCount: 0, next: config.mode === 'batch' ? { ...state, armed: true, pendingCount: 0 } : state } } if (message.kind === 'system' && !config.includeSystem) return { fire: false, reason: 'system', batchCount: 0, next: state } if (config.mode === 'once' && state.firedOnce) return { fire: false, reason: 'already_fired', batchCount: 0, next: state } const sinceFire = state.lastFiredAt == null ? Infinity : (now - state.lastFiredAt) / 1000 const pending = { ...state, pendingCount: state.pendingCount + 1 } if (config.mode === 'batch' && !state.armed) { const rewake = config.rewakeAfterSeconds > 0 && sinceFire >= config.rewakeAfterSeconds if (!rewake) return { fire: false, reason: 'waiting_for_reply', batchCount: 0, next: pending } } if (sinceFire < config.minIntervalSeconds) return { fire: false, reason: 'throttled', batchCount: 0, next: pending } return { fire: true, reason: 'fire', batchCount: pending.pendingCount, next: { armed: false, firedOnce: true, pendingCount: 0, lastFiredAt: now }, } } export type WakePayload = { source: '@kody/rooms' event: 'room.message' roomId: string memberId: string mode: WatchMode batchCount: number cursor: number viewUrl: string | null note: string | null prompt: string message: { id: string; seq: number; at: string; kind: string; from: { agent_id: string; name: string }; text: string; untrusted: true } } /** Build the wake payload. Peer text is wrapped, sanitized, and placeholder-safe. */ export function buildWakePayload(input: { roomId: string memberId: string config: WatchConfig batchCount: number message: WakeMessage viewUrl: string | null appUrl: string | null }): WakePayload { const { message } = input const text = breakPlaceholders(sanitizeText(clip(message.text, 4000))) const block = wrapUntrusted({ text: message.text, fromId: message.fromId, fromName: message.fromName, messageId: message.id, seq: message.seq }) const more = input.batchCount > 1 ? ` (${input.batchCount} new messages; this is the latest)` : '' const how = input.appUrl ? `Read everything after your cursor with GET ${input.appUrl}/api/read?after= and header X-Room-Token: $KODY_ROOM_TOKEN, or import read from kody:@kody/rooms/read.` : 'Read everything after your cursor with kody:@kody/rooms/read.' const prompt = [ `New message in Kody room ${input.roomId}${more}.`, safetyLine, block, how, 'Reply to the batch as one message with post. Do not quote secrets or tokens.', input.config.note ? `Note from whoever set up this wake: ${breakPlaceholders(input.config.note)}` : '', input.viewUrl ? `Room view: ${input.viewUrl}` : '', ] .filter(Boolean) .join('\n\n') return { source: '@kody/rooms', event: 'room.message', roomId: input.roomId, memberId: input.memberId, mode: input.config.mode, batchCount: input.batchCount, cursor: message.seq, viewUrl: input.viewUrl, note: input.config.note ? breakPlaceholders(input.config.note) : null, prompt, message: { id: message.id, seq: message.seq, at: message.at, kind: message.kind, from: { agent_id: message.fromId, name: breakPlaceholders(sanitizeText(message.fromName)) }, text, untrusted: true, }, } } export type HttpWake = { kind: 'http'; url: string; method: 'POST'; headers: Record; body: string; timeoutMs: number; busyIsOk: boolean; noRedirect: boolean } export type WakeAction = HttpWake | { kind: 'job'; jobId: string } const json = { 'Content-Type': 'application/json' } /** Turn a target plus payload into one concrete delivery action. */ export function planDelivery(target: WakeTarget, payload: WakePayload, watchId: string): WakeAction { switch (target.type) { case 'webhook': return { kind: 'http', url: target.url, method: 'POST', headers: { ...json, ...(target.key ? Object.fromEntries(target.keyHeaders.map((name) => [name, name.toLowerCase() === 'authorization' ? `Bearer ${target.key}` : target.key!])) : {}) }, body: serializeWakeBody(target.body === 'prompt' ? { prompt: payload.prompt } : payload), timeoutMs: target.timeoutMs, busyIsOk: false, noRedirect: true, } case 'job': return { kind: 'job', jobId: target.jobId } } } /** Short, secret-free description of a target for status output. */ export function describeTarget(target: WakeTarget) { switch (target.type) { case 'webhook': { const host = /^https:\/\/([^/?#]+)/.exec(target.url)?.[1] ?? '?' return { type: target.type, host, body: target.body, hasKey: target.key != null } } case 'job': return { type: target.type, jobId: target.jobId } } }