import { MEMORY_RULE } from "./constants"; export type Resolver = (v: any) => void; /** * Settle-once wait: register a resolver in `map` under `key`, resolve with the delivered * value or null on timeout. Whichever side fires FIRST performs cleanup inside its own * callback (single-threaded event loop ⇒ no window where a late answer finds a resolver * whose race already ended and gets silently dropped). */ export function createWait(map: Map, key: string, timeoutMs: number): Promise { return new Promise((resolve) => { const timer = setTimeout(() => { map.delete(key); // after this, a late answer takes the injection path resolve(null); }, timeoutMs); map.set(key, (v: any) => { clearTimeout(timer); map.delete(key); resolve(v); }); }); } /** Provenance envelope. All peer-supplied text must be sanitized by the caller. */ export function envelope(opts: { kind: string; from: string; to: string; thread: string; body: string; extra?: string; }): string { return ( `[[AGENT-COMM]]\n` + `kind: ${opts.kind}\n` + `from: ${opts.from}\n` + `to: ${opts.to}\n` + `thread: ${opts.thread}\n` + `at: ${new Date().toISOString()}\n` + `---\n${opts.body}\n` + (opts.extra ? `---\n${opts.extra}\n` : "") + `${MEMORY_RULE}\n` + `[[/AGENT-COMM]]` ); }