// Example mod: filter the model's answer as it streams, and stream a process's output. // // hooks.transformTextDelta sees every chunk of the answer before it is shown. Return the chunk // to show (rewritten or not), or '' to hold it back. When the answer is complete it is called // once more with {delta: '', done: true}: return whatever you held back. The transcript keeps // exactly what was shown. It must be synchronous and fast: it runs inside the stream. // // A key can arrive split across chunks ("sk-ab" then "cdef..."), so this filter holds back a // tail that might be the start of one and decides when the next chunk (or the end) arrives. // // cmd.process.spawn runs a command and hands each stdout/stderr chunk to onOutput as it is // produced; cmd.exec only answers once the process exits. import type {ModApi} from '@commandcode/harness'; const KEY_PATTERN = /\bsk-[A-Za-z0-9_-]{16,}/g; // A tail that could still grow into a key: "s", "sk", "sk-", "sk-abc...". const MAYBE_KEY_TAIL = /(?:\bs|\bsk|\bsk-[A-Za-z0-9_-]*)$/; function redact(text: string): string { return text.replace(KEY_PATTERN, '[REDACTED]'); } export default function (cmd: ModApi): void { // Held-back text, for the stream it belongs to. A retry or a new turn starts a new stream. let held = ''; let stream = ''; cmd.hooks({ transformTextDelta: ({delta, done, turnNumber, attempt}) => { const id = `${turnNumber}:${attempt}`; if (id !== stream) { stream = id; held = ''; } const text = held + delta; if (done) { held = ''; return redact(text); } const tail = MAYBE_KEY_TAIL.exec(text)?.[0] ?? ''; held = tail; return redact(text.slice(0, text.length - tail.length)); }, }); cmd.addCommand({ name: 'stream', description: 'Run a command and show its latest output line as it runs', argumentHint: '', handler: async ({args}) => { if (!args.trim()) return {message: 'usage: /stream '}; let lines = 0; cmd.ui.setStatus(`running ${args}`); try { const {code} = await cmd.process.spawn({ command: args, onOutput: (chunk, from) => { const last = chunk.trimEnd().split('\n').at(-1) ?? ''; lines += chunk.split('\n').length - 1; if (last) cmd.ui.setStatus(`${from}: ${last}`); }, }); return {message: `${args} exited ${code} after ${lines} lines`}; } finally { cmd.ui.setStatus(null); } }, }); }