import { existsSync } from 'node:fs'; import { pathToFileURL } from 'node:url'; import { AuthStore } from '../src/lib/auth.js'; import { getProfileEventLedgerPath, getRuntimeAccountId, } from '../src/lib/init-command.js'; import { SqliteEventRepository, type CanonicalEvent, } from '../src/runtime/framework/events/index.js'; export interface PerceptionWatchOptions { fromStart: boolean; intervalMs: number; json: boolean; maxEvents: number | null; } export function parsePerceptionWatchOptions(argv: readonly string[]): PerceptionWatchOptions { let fromStart = false; let json = false; let intervalMs = 100; let maxEvents: number | null = null; for (let index = 0; index < argv.length; index += 1) { const value = argv[index]; if (value === '--from-start') { fromStart = true; continue; } if (value === '--json') { json = true; continue; } if (value === '--interval-ms') { const parsed = Number(argv[index + 1]); if (!Number.isInteger(parsed) || parsed < 25 || parsed > 10_000) { throw new Error('--interval-ms must be an integer from 25 to 10000.'); } intervalMs = parsed; index += 1; continue; } if (value === '--max-events') { const parsed = Number(argv[index + 1]); if (!Number.isInteger(parsed) || parsed < 1) { throw new Error('--max-events must be a positive integer.'); } maxEvents = parsed; index += 1; continue; } if (value === '--help' || value === '-h') { process.stdout.write(`Usage: npm run watch:perception -- [options] Options: --from-start Print existing perception Events in the current game first. --interval-ms SQLite poll interval. Default: 100. --max-events Exit after printing n perception Events. --json Print full Canonical Events as JSONL. `); process.exit(0); } throw new Error(`Unknown option: ${value}`); } return { fromStart, intervalMs, json, maxEvents }; } function eventTickLabel(event: CanonicalEvent): string { const from = Number.isInteger(event.payload.from_tick) ? Number(event.payload.from_tick) : null; const to = Number.isInteger(event.payload.to_tick) ? Number(event.payload.to_tick) : from; const tick = Number.isInteger(event.payload.tick) ? Number(event.payload.tick) : null; if (from !== null) return from === to ? `tick ${from}` : `ticks ${from}-${to}`; if (tick !== null) return `tick ${tick}`; return 'tick ?'; } export function formatPerceptionEvent(event: CanonicalEvent): string { const time = event.occurredAt.slice(11, 23) || event.occurredAt; const text = typeof event.payload.text === 'string' && event.payload.text.trim() ? event.payload.text.trim() : JSON.stringify(event.payload); return `[${time}] #${event.commitSeq} epoch ${event.epochSeq ?? '?'} ${eventTickLabel(event)} ${event.type} | ${text}`; } function sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } async function main(): Promise { const options = parsePerceptionWatchOptions(process.argv.slice(2)); const profile = new AuthStore().getActive(); if (!profile) throw new Error('No active CCL profile.'); const ledgerPath = getProfileEventLedgerPath(profile); if (!existsSync(ledgerPath)) throw new Error('Canonical Event Ledger is unavailable.'); const opened = SqliteEventRepository.open(ledgerPath); if (!opened.ok) throw new Error(opened.unavailable.message); let activeSegmentId: string | null = null; let cursor = 0; let initialized = false; let stopping = false; let printedEvents = 0; const stop = () => { stopping = true; }; process.once('SIGINT', stop); process.once('SIGTERM', stop); try { while (!stopping) { const scope = opened.repository.latestScope({ adapterId: 'clawclaw', accountId: getRuntimeAccountId(profile), }, { segmentKinds: ['game'] }); if (!scope) { await sleep(options.intervalMs); continue; } if (scope.segment.segmentId !== activeSegmentId) { const existingSegmentAtStartup = !initialized; activeSegmentId = scope.segment.segmentId; cursor = options.fromStart || !existingSegmentAtStartup ? 0 : opened.repository.highWaterCommitSeq(scope.session.sessionId, activeSegmentId); initialized = true; process.stderr.write( `[perception-live] session=${scope.session.sessionId} segment=${activeSegmentId} cursor=${cursor}\n`, ); } const events = opened.repository.listCommittedEvents({ sessionId: scope.session.sessionId, segmentId: activeSegmentId, afterCommitSeq: cursor, order: 'asc', limit: 1_000, }); for (const event of events) { cursor = Math.max(cursor, event.commitSeq); if (event.producerPluginId !== 'clawclaw.perception') continue; process.stdout.write(options.json ? `${JSON.stringify(event)}\n` : `${formatPerceptionEvent(event)}\n`); printedEvents += 1; if (options.maxEvents !== null && printedEvents >= options.maxEvents) { stopping = true; break; } } if (stopping) break; await sleep(events.length === 1_000 ? 0 : options.intervalMs); } } finally { opened.repository.close(); } } const entryUrl = process.argv[1] ? pathToFileURL(process.argv[1]).href : null; if (entryUrl === import.meta.url) { main().catch((error) => { process.stderr.write(`[perception-live] ${error instanceof Error ? error.message : String(error)}\n`); process.exitCode = 1; }); }