diff --git a/adapter/strings/omp-spt.mjs b/adapter/strings/omp-spt.mjs index e6ef979..2d7c042 100644 --- a/adapter/strings/omp-spt.mjs +++ b/adapter/strings/omp-spt.mjs @@ -30,31 +30,84 @@ export function drainEvents(raw) { if (openEnd < 0) return { events, rest: raw.slice(start) }; const close = raw.indexOf("", openEnd + 1); if (close < 0) return { events, rest: raw.slice(start) }; + const end = close + "".length; const tag = raw.slice(start, openEnd); if (attribute(tag, "type") === "msg") { events.push({ from: attribute(tag, "from"), body: decodeBody(raw.slice(openEnd + 1, close)), + envelope: raw.slice(start, end), }); } - cursor = close + "".length; + cursor = end; } } -export function extractReply(messages) { - const assistant = [...(messages ?? [])].reverse().find((message) => message?.role === "assistant"); - if (!assistant) return ""; - if (typeof assistant.content === "string") return assistant.content; - return (assistant.content ?? []) +function messageText(message) { + if (typeof message?.content === "string") return message.content; + return (message?.content ?? []) .filter((part) => part?.type === "text" && typeof part.text === "string") .map((part) => part.text) .join(""); } +export function extractReply(messages, afterUserMessage) { + const allMessages = messages ?? []; + let start = 0; + if (afterUserMessage !== undefined) { + const userIndex = allMessages.findLastIndex((message) => { + if (message?.role !== "user") return false; + const text = messageText(message); + return text === afterUserMessage || text.startsWith(`${afterUserMessage}\n\n message?.role === "assistant"); + return assistant ? messageText(assistant) : ""; +} + function firstLine(text) { return text.split(/\r?\n/).find((line) => line.trim()) ?? ""; } +function errorSummary(error) { + const detail = error instanceof Error ? error.message : String(error); + return firstLine(detail).trim() || "unknown error"; +} + +function failureMessage(reason, error) { + const detail = error === undefined ? "" : `: ${errorSummary(error)}`; + return `[omp-spt] ${reason}${detail}`; +} + +function senderStub(sender) { + const escaped = sender + .replaceAll("&", "&") + .replaceAll('"', """) + .replaceAll("<", "<") + .replaceAll(">", ">"); + return ``; +} + +function injectEnvelope(messages, item) { + const index = messages.findLastIndex( + (message) => message?.role === "user" && messageText(message) === item.stub, + ); + if (index < 0) return messages; + const original = messages[index]; + const content = + typeof original.content === "string" + ? `${original.content}\n\n${item.envelope}` + : [...(original.content ?? []), { type: "text", text: `\n\n${item.envelope}` }]; + const injected = [...messages]; + injected[index] = { ...original, content }; + return injected; +} + function runSpt(args, input) { return new Promise((resolve, reject) => { const child = spawn(process.env.OMP_SPT_SPT_BIN || "spt", args, { @@ -75,126 +128,479 @@ function runSpt(args, input) { }); } -// [impl->REQ-OMP-NATIVE-TUI] -export default function ompSpt(pi) { - const id = process.env.SPT_ENDPOINT_ID?.trim(); - if (!id) return; - - let sid; - let token; - let listener; - let listenerBuffer = ""; - let agentActive = false; - let current; - let stopping = false; - let ui; - const queue = []; - - const logError = (message, error) => { - pi.logger.error(message, { error: String(error) }); - ui?.notify(`${message}: ${error}`, "error"); - }; +export function createOmpSpt(overrides = {}) { + const spawnProcess = overrides.spawnProcess ?? spawn; + const runSptCommand = overrides.runSptCommand ?? runSpt; + const setTimer = overrides.setTimeout ?? globalThis.setTimeout; + const clearTimer = overrides.clearTimeout ?? globalThis.clearTimeout; + const restartDelaysMs = [...(overrides.restartDelaysMs ?? [250, 1000, 4000])]; + const outcomeRetryDelaysMs = [ + ...(overrides.outcomeRetryDelaysMs ?? [250, 1000, 4000]), + ]; + const listenerStableMs = + overrides.listenerStableMs === false ? undefined : (overrides.listenerStableMs ?? 30_000); + const env = overrides.env ?? process.env; - async function setState(state) { - if (!sid) return; - const auth = token ? ["--token", token] : ["--session-id", sid]; - await runSpt(["api", "--adapter", ADAPTER, "state", state, id, ...auth]); - } + return function ompSpt(pi) { + const id = env.SPT_ENDPOINT_ID?.trim(); + if (!id) return; + + let sid; + let token; + let listener; + let listenerBuffer = ""; + let listenerRestartCount = 0; + let listenerStableTimer; + let restartTimer; + let dispatchTimer; + let bindPromise; + let agentActive = false; + let desiredState = "idle"; + let dispatching = false; + let current; + let stopping = false; + let ui; + let runtimeCtx; + let endpointState; + let stateOperation = Promise.resolve(); + let endPromise; + let fatalPromise; + let teardownPromise; + const queue = []; + + const logError = (message, error) => { + pi.logger.error(message, { error: errorSummary(error) }); + ui?.notify(`${message}: ${errorSummary(error)}`, "error"); + }; + + function authArgs() { + if (!token) throw new Error("bind did not return an authentication token"); + return ["--token", token]; + } + + function setState(state) { + if (!sid || !token || stopping) return Promise.resolve(); + const operation = stateOperation.catch(() => {}).then(async () => { + if (endpointState === state || stopping) return; + await runSptCommand(["api", "--adapter", ADAPTER, "state", state, id, ...authArgs()]); + endpointState = state; + }); + stateOperation = operation; + return operation; + } + + async function syncDesiredState() { + if (!bindPromise) return; + await bindPromise; + while (!stopping && endpointState !== desiredState) { + await setState(desiredState); + } + } - function dispatchNext() { - if (stopping || agentActive || current || queue.length === 0) return; - current = queue.shift(); - try { - pi.sendUserMessage(current.body); - } catch (error) { - logError("omp-spt could not submit an inbound message", error); + function endSession() { + if (!sid || !token) return Promise.resolve(); + if (!endPromise) { + const operation = (async () => { + await stateOperation.catch(() => {}); + await runSptCommand(["api", "--adapter", ADAPTER, "session-end", id, ...authArgs()]); + endpointState = undefined; + })(); + endPromise = operation; + void operation.catch(() => { + if (endPromise === operation) endPromise = undefined; + }); + } + return endPromise; + } + + // [impl->REQ-OMP-EXTENSION-CUSTODY] + function settleItem(item, payload) { + if (!item) return Promise.resolve(); + if (item.outcomePromise) return item.outcomePromise; + item.settling = true; + item.outcomePromise = (async () => { + if (!item.from) throw new Error("missing EVENT from attribute"); + for (let attempt = 0; ; attempt += 1) { + try { + await runSptCommand(["send", item.from, "--from", id], payload); + item.settled = true; + return; + } catch (error) { + if (attempt >= outcomeRetryDelaysMs.length) throw error; + const delay = outcomeRetryDelaysMs[attempt]; + pi.logger.error( + `omp-spt could not send the outcome to ${item.from}; retrying ${ + attempt + 1 + }/${outcomeRetryDelaysMs.length} in ${delay}ms`, + { error: errorSummary(error) }, + ); + await new Promise((resolve) => { + const timer = setTimer(resolve, delay); + timer?.unref?.(); + }); + } + } + })(); + return item.outcomePromise; + } + + function stopResources() { + if (dispatchTimer !== undefined) { + clearTimer(dispatchTimer); + dispatchTimer = undefined; + } + if (restartTimer !== undefined) { + clearTimer(restartTimer); + restartTimer = undefined; + } + if (listenerStableTimer !== undefined) { + clearTimer(listenerStableTimer); + listenerStableTimer = undefined; + } + const child = listener; + listener = undefined; + if (child) { + try { + child.kill(); + } catch (error) { + pi.logger.error("omp-spt could not reap the listener", { error: errorSummary(error) }); + } + } + listenerBuffer = ""; + } + + async function failPending(reason) { + const pending = current ? [current, ...queue] : [...queue]; current = undefined; - setTimeout(dispatchNext, 0); + queue.length = 0; + for (const item of pending) { + try { + await settleItem(item, failureMessage(reason)); + } catch (error) { + logError(`omp-spt could not return custody to ${item.from ?? "unknown"}`, error); + } + } } - } - function startListener() { - const args = ["ready", id]; - if (process.env.OMP_SPT_SUBNET) args.push("--subnet", process.env.OMP_SPT_SUBNET); - listener = spawn(process.env.OMP_SPT_SPT_BIN || "spt", args, { - stdio: ["ignore", "pipe", "pipe"], - windowsHide: true, - }); - listener.stdout.setEncoding("utf8"); - listener.stderr.setEncoding("utf8"); - listener.stdout.on("data", (chunk) => { - listenerBuffer += chunk; - const drained = drainEvents(listenerBuffer); - listenerBuffer = drained.rest; - for (const event of drained.events) queue.push(event); - dispatchNext(); - }); - listener.stderr.on("data", (chunk) => pi.logger.debug("omp-spt listener", { output: chunk.trim() })); - listener.on("error", (error) => logError("omp-spt listener failed", error)); - listener.on("close", (code) => { - if (!stopping) { - ui?.setStatus("omp-spt", "spt offline"); - ui?.notify(`omp-spt listener exited (${code})`, "error"); + function teardownSession(pendingReason) { + if (!teardownPromise) { + stopping = true; + stopResources(); + const operation = (async () => { + await failPending(pendingReason); + await bindPromise?.catch(() => {}); + await endSession(); + })(); + teardownPromise = operation; + void operation.catch(() => { + if (teardownPromise === operation) teardownPromise = undefined; + }); } - }); - } + return teardownPromise; + } - pi.on("session_start", async (_event, ctx) => { - ui = ctx.ui; - sid = ctx.sessionManager.getSessionId(); - try { - const bindArgs = ["api", "--adapter", ADAPTER, "bind", id, "--set-session-id", sid]; - if (process.env.OMP_SPT_SUBNET) bindArgs.push("--subnet", process.env.OMP_SPT_SUBNET); - const bound = await runSpt(bindArgs); - token = bound.match(/\btoken=([^\s]+)/)?.[1]; - await setState("idle"); - startListener(); - ctx.ui.setStatus("omp-spt", `spt:${id}`); - } catch (error) { - ctx.ui.setStatus("omp-spt", "spt bind failed"); - logError(`omp-spt could not bind ${id}`, error); + // [impl->REQ-OMP-LISTENER-FAIL-CLOSED] + async function failClosed(message, error) { + if (fatalPromise) return fatalPromise; + fatalPromise = (async () => { + ui?.setStatus("omp-spt", "spt failed"); + logError(message, error); + try { + await teardownSession("endpoint stopped before your message could complete"); + } catch (teardownError) { + logError("omp-spt session teardown failed", teardownError); + } + runtimeCtx?.shutdown(); + })(); + return fatalPromise; } - }); - pi.on("agent_start", async () => { - agentActive = true; - try { - await setState("busy"); - } catch (error) { - logError("omp-spt could not mark the endpoint busy", error); + function scheduleDispatch() { + if ( + stopping || + agentActive || + dispatching || + current || + queue.length === 0 || + dispatchTimer !== undefined + ) { + return; + } + dispatchTimer = setTimer(() => { + dispatchTimer = undefined; + void dispatchNext().catch((error) => failClosed("omp-spt dispatch failed", error)); + }, 0); + dispatchTimer?.unref?.(); } - }); - pi.on("agent_end", async (event) => { - agentActive = false; - const completed = current; - current = undefined; - if (completed?.from) { - const reply = extractReply(event.messages) || "[omp-spt] turn ended without an assistant response."; + async function rejectItem(item, reason, error) { + logError(`omp-spt ${reason}`, error); try { - await runSpt(["send", completed.from, "--from", id], reply); - } catch (error) { - logError(`omp-spt could not reply to ${completed.from}`, error); + await settleItem(item, failureMessage(reason, error)); + } catch (outcomeError) { + await failClosed(`omp-spt could not send the outcome to ${item.from ?? "unknown"}`, outcomeError); + return; + } + if (current === item) current = undefined; + if (!stopping) { + desiredState = "idle"; + try { + await setState("idle"); + } catch (stateError) { + await failClosed( + "omp-spt could not restore idle state after a failed submission", + stateError, + ); + } } } - try { - await setState("idle"); - } catch (error) { - logError("omp-spt could not mark the endpoint idle", error); + + // [impl->REQ-OMP-EXTENSION-CUSTODY] + async function dispatchNext() { + if (stopping || agentActive || dispatching || current || queue.length === 0) return; + dispatching = true; + const item = queue.shift(); + current = item; + try { + try { + desiredState = "busy"; + await setState("busy"); + } catch (error) { + await rejectItem(item, "could not accept your message", error); + return; + } + if (stopping) return; + if (agentActive) { + if (current === item) current = undefined; + queue.unshift(item); + return; + } + item.stub = senderStub(item.from ?? "unknown"); + item.submitted = true; + try { + pi.sendUserMessage(item.stub); + } catch (error) { + item.submitted = false; + await rejectItem(item, "could not submit your message to OMP", error); + } + } finally { + dispatching = false; + scheduleDispatch(); + } } - setTimeout(dispatchNext, 0); - }); - pi.on("session_shutdown", async () => { - stopping = true; - listener?.kill(); - ui?.setStatus("omp-spt", undefined); - if (!sid) return; - const auth = token ? ["--token", token] : ["--session-id", sid]; - try { - await runSpt(["api", "--adapter", ADAPTER, "session-end", id, ...auth]); - } catch (error) { - pi.logger.error("omp-spt session teardown failed", { error: String(error) }); + // [impl->REQ-OMP-LISTENER-FAIL-CLOSED] + function handleListenerDeath(reason) { + listenerBuffer = ""; + if (listenerStableTimer !== undefined) { + clearTimer(listenerStableTimer); + listenerStableTimer = undefined; + } + if (stopping || restartTimer !== undefined) return; + if (listenerRestartCount >= restartDelaysMs.length) { + void failClosed("omp-spt listener restart budget exhausted", reason); + return; + } + const attempt = listenerRestartCount + 1; + const delay = restartDelaysMs[listenerRestartCount]; + listenerRestartCount = attempt; + const message = `omp-spt listener stopped; restarting ${attempt}/${restartDelaysMs.length} in ${delay}ms`; + pi.logger.error(message, { error: errorSummary(reason) }); + ui?.setStatus("omp-spt", `spt reconnecting (${attempt}/${restartDelaysMs.length})`); + ui?.notify(message, "warning"); + restartTimer = setTimer(() => { + restartTimer = undefined; + startListener(); + }, delay); + restartTimer?.unref?.(); } - }); + + function startListener() { + if (stopping) return; + const args = ["ready", id]; + if (env.OMP_SPT_SUBNET) args.push("--subnet", env.OMP_SPT_SUBNET); + let child; + try { + child = spawnProcess(env.OMP_SPT_SPT_BIN || "spt", args, { + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + }); + } catch (error) { + handleListenerDeath(error); + return; + } + listener = child; + listenerBuffer = ""; + let dead = false; + const died = (reason) => { + if (dead) return; + dead = true; + if (listener === child) listener = undefined; + try { + child.kill(); + } catch (error) { + pi.logger.error("omp-spt could not reap the dead listener", { + error: errorSummary(error), + }); + } + handleListenerDeath(reason); + }; + if (listenerStableMs !== undefined) { + listenerStableTimer = setTimer(() => { + listenerStableTimer = undefined; + if (listener === child && !stopping) listenerRestartCount = 0; + }, listenerStableMs); + listenerStableTimer?.unref?.(); + } + child.stdout.setEncoding("utf8"); + child.stderr.setEncoding("utf8"); + child.stdout.on("data", (chunk) => { + if (listener !== child || stopping) return; + listenerBuffer += chunk; + const drained = drainEvents(listenerBuffer); + listenerBuffer = drained.rest; + for (const event of drained.events) { + if (!event.from) { + logError( + "omp-spt received a message without a sender", + new Error("missing EVENT from attribute"), + ); + continue; + } + queue.push(event); + } + if (!agentActive && !current && !dispatching) void dispatchNext(); + }); + child.stderr.on("data", (chunk) => + pi.logger.debug("omp-spt listener", { output: String(chunk).trim() }), + ); + child.on("error", (error) => died(error)); + child.on("close", (code) => died(new Error(`spt ready exited ${code}`))); + ui?.setStatus("omp-spt", `spt:${id}`); + } + + // [impl->REQ-OMP-NATIVE-TUI] + pi.on("session_start", async (_event, ctx) => { + runtimeCtx = ctx; + ui = ctx.ui; + sid = ctx.sessionManager.getSessionId(); + const bindArgs = ["api", "--adapter", ADAPTER, "bind", id, "--set-session-id", sid]; + if (env.OMP_SPT_SUBNET) bindArgs.push("--subnet", env.OMP_SPT_SUBNET); + bindPromise = (async () => { + const bound = await runSptCommand(bindArgs); + token = bound.match(/\btoken=([^\s]+)/)?.[1]; + if (!token) throw new Error("spt bind response did not include token="); + })(); + try { + await bindPromise; + } catch (error) { + if (stopping) return; + ui.setStatus("omp-spt", "spt bind failed"); + await failClosed(`omp-spt could not bind ${id}`, error); + return; + } + if (stopping) { + try { + await teardownSession("OMP session shut down before initialization completed"); + } catch (error) { + logError("omp-spt session teardown failed", error); + } + return; + } + try { + await syncDesiredState(); + if (stopping) { + await teardownSession("OMP session shut down before initialization completed"); + return; + } + ui.setStatus("omp-spt", `spt:${id}`); + startListener(); + } catch (error) { + if (stopping) { + logError("omp-spt session teardown failed", error); + return; + } + ui.setStatus("omp-spt", "spt bind failed"); + await failClosed(`omp-spt could not bind ${id}`, error); + } + }); + + // [impl->REQ-OMP-SESSION-IMMUTABLE] + const blockSessionChange = (description, ctx) => { + if (stopping) return; + ctx.ui.notify( + `omp-spt blocked the in-TUI ${description}; end this SPT session first`, + "warning", + ); + return { cancel: true }; + }; + + pi.on("session_before_switch", (event, ctx) => + blockSessionChange(`${event.reason} session switch`, ctx), + ); + pi.on("session_before_branch", (_event, ctx) => + blockSessionChange("session branch", ctx), + ); + + // [impl->REQ-OMP-MESSAGE-CONTEXT] + pi.on("context", (event) => { + if (!current?.submitted || current.settling) return; + const messages = injectEnvelope(event.messages, current); + if (messages !== event.messages) return { messages }; + }); + + pi.on("agent_start", async () => { + if (stopping) return; + agentActive = true; + desiredState = "busy"; + try { + await syncDesiredState(); + } catch (error) { + if (!stopping) await failClosed("omp-spt could not mark the endpoint busy", error); + } + }); + + // [impl->REQ-OMP-EXTENSION-CUSTODY] + pi.on("agent_end", async (event) => { + agentActive = false; + desiredState = "idle"; + if (stopping) return; + const completed = current; + if (completed?.submitted && !completed.settled) { + const reply = extractReply(event.messages, completed.stub); + try { + await settleItem( + completed, + reply || failureMessage("turn ended without an assistant response"), + ); + } catch (error) { + await failClosed( + `omp-spt could not send the outcome to ${completed.from ?? "unknown"}`, + error, + ); + return; + } + } + if (current === completed) current = undefined; + try { + await setState("idle"); + } catch (error) { + await failClosed("omp-spt could not mark the endpoint idle", error); + return; + } + scheduleDispatch(); + }); + + pi.on("session_shutdown", async (_event, ctx) => { + runtimeCtx ??= ctx; + ui?.setStatus("omp-spt", undefined); + try { + await teardownSession("OMP session shut down before your message could complete"); + } catch (error) { + logError("omp-spt session teardown failed", error); + } + }); + }; } + +export default createOmpSpt(); diff --git a/tests/omp-extension.mjs b/tests/omp-extension.mjs index 2ccf034..00228cc 100644 --- a/tests/omp-extension.mjs +++ b/tests/omp-extension.mjs @@ -1,25 +1,810 @@ import assert from "node:assert/strict"; -import { decodeBody, drainEvents, extractReply } from "../adapter/strings/omp-spt.mjs"; +import { EventEmitter } from "node:events"; +import { + createOmpSpt, + decodeBody, + drainEvents, + extractReply, +} from "../adapter/strings/omp-spt.mjs"; +const flush = () => new Promise((resolve) => setImmediate(resolve)); +function deferred() { + let resolve; + let reject; + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise; + reject = rejectPromise; + }); + return { promise, reject, resolve }; +} + +class FakeStream extends EventEmitter { + setEncoding(encoding) { + this.encoding = encoding; + } +} + +class FakeChild extends EventEmitter { + constructor() { + super(); + this.stdout = new FakeStream(); + this.stderr = new FakeStream(); + this.kills = 0; + } + + kill() { + this.kills += 1; + } +} + +class FakeClock { + constructor() { + this.nextId = 1; + this.timers = new Map(); + } + + setTimeout(fn, delay) { + const handle = { id: this.nextId++, unref() {} }; + this.timers.set(handle, { fn, delay }); + return handle; + } + + clearTimeout(handle) { + this.timers.delete(handle); + } + + delays() { + return [...this.timers.values()].map(({ delay }) => delay); + } + + async runNext(expectedDelay) { + const entry = [...this.timers.entries()].sort((left, right) => left[1].delay - right[1].delay)[0]; + assert.ok(entry, `expected a ${expectedDelay}ms timer`); + const [handle, timer] = entry; + assert.equal(timer.delay, expectedDelay); + this.timers.delete(handle); + timer.fn(); + await flush(); + } +} + +function createHarness(options = {}) { + const handlers = new Map(); + const calls = []; + const children = []; + const submitted = []; + const statuses = []; + const notifications = []; + const errors = []; + const debug = []; + const clock = new FakeClock(); + let shutdowns = 0; + + const ui = { + notify(message, type) { + notifications.push({ message, type }); + }, + setStatus(key, text) { + statuses.push({ key, text }); + }, + }; + const ctx = { + ui, + sessionManager: { getSessionId: () => options.sessionId ?? "session-1" }, + shutdown() { + shutdowns += 1; + }, + }; + const pi = { + logger: { + error(message, details) { + errors.push({ message, details }); + }, + debug(message, details) { + debug.push({ message, details }); + }, + }, + on(name, handler) { + const registered = handlers.get(name) ?? []; + registered.push(handler); + handlers.set(name, registered); + }, + sendUserMessage(content) { + submitted.push(content); + options.onSubmit?.(content); + }, + }; + const runSptCommand = async (args, input) => { + const call = { args: [...args], input }; + calls.push(call); + const overridden = await options.onRun?.(call); + if (overridden !== undefined) return overridden; + if (args[0] === "api" && args[3] === "bind") { + return options.bindOutput ?? "BOUND endpoint token=token-123"; + } + return ""; + }; + const spawnProcess = (binary, args, spawnOptions) => { + const child = new FakeChild(); + child.binary = binary; + child.args = [...args]; + child.spawnOptions = spawnOptions; + children.push(child); + return child; + }; + const extension = createOmpSpt({ + env: { + SPT_ENDPOINT_ID: options.id ?? "omp-agent", + OMP_SPT_SUBNET: options.subnet, + OMP_SPT_SPT_BIN: "spt-test", + }, + restartDelaysMs: options.restartDelaysMs ?? [5, 10], + outcomeRetryDelaysMs: options.outcomeRetryDelaysMs ?? [], + listenerStableMs: options.listenerStableMs ?? false, + runSptCommand, + spawnProcess, + setTimeout: clock.setTimeout.bind(clock), + clearTimeout: clock.clearTimeout.bind(clock), + }); + extension(pi); + + async function emit(name, event = {}) { + let result; + for (const handler of handlers.get(name) ?? []) { + const returned = await handler({ type: name, ...event }, ctx); + if (returned !== undefined) result = returned; + } + return result; + } + + return { + calls, + children, + clock, + ctx, + debug, + emit, + errors, + handlers, + notifications, + statuses, + submitted, + get shutdowns() { + return shutdowns; + }, + }; +} + +function commandCalls(harness, command) { + return harness.calls.filter((call) => call.args[0] === command); +} + +function stateCalls(harness) { + return harness.calls.filter((call) => call.args[0] === "api" && call.args[3] === "state"); +} + +async function testParsingAndReplies() { + assert.equal(decodeBody('a<b>
"c" & &lt;'), 'a\n"c" & <'); + + const partialEnvelope = 'hello
wo'; + const partial = drainEvents(`noise${partialEnvelope}`); + assert.deepEqual(partial.events, []); + assert.equal(partial.rest, partialEnvelope); + + const envelope = `${partial.rest}rld
`; + const complete = drainEvents(`${envelope}skip`); + assert.deepEqual(complete.events, [ + { from: "doyle", body: "hello\nworld", envelope }, + ]); + assert.equal(complete.rest, ""); + + assert.equal( + extractReply([ + { role: "assistant", content: [{ type: "text", text: "first" }] }, + { role: "toolResult", content: [] }, + { + role: "assistant", + content: [ + { type: "text", text: "final " }, + { type: "text", text: "answer" }, + ], + }, + ]), + "final answer", + ); + assert.equal( + extractReply( + [ + { role: "assistant", content: "stale answer" }, + { role: "user", content: '' }, + ], + '', + ), + "", + ); +} + +// [unit->REQ-OMP-EXTENSION-CUSTODY] +// [unit->REQ-OMP-SESSION-IMMUTABLE] +// [unit->REQ-OMP-MESSAGE-CONTEXT] // [unit->REQ-OMP-NATIVE-TUI] -assert.equal(decodeBody('a<b>
"c" & &lt;'), 'a\n"c" & <'); - -const partial = drainEvents('noisehello
wo'); -assert.deepEqual(partial.events, []); -assert.equal(partial.rest, 'hello
wo'); - -const complete = drainEvents(`${partial.rest}rld
skip`); -assert.deepEqual(complete.events, [{ from: "doyle", body: "hello\nworld" }]); -assert.equal(complete.rest, ""); - -assert.equal( - extractReply([ - { role: "assistant", content: [{ type: "text", text: "first" }] }, - { role: "toolResult", content: [] }, - { role: "assistant", content: [{ type: "text", text: "final " }, { type: "text", text: "answer" }] }, - ]), - "final answer", -); -assert.equal(extractReply([{ role: "user", content: "hello" }]), ""); +async function testLifecycleCustodyAndContext() { + const harness = createHarness({ subnet: "mesh-a" }); + assert.deepEqual([...harness.handlers.keys()], [ + "session_start", + "session_before_switch", + "session_before_branch", + "context", + "agent_start", + "agent_end", + "session_shutdown", + ]); + + await harness.emit("session_start"); + assert.deepEqual(harness.calls[0], { + args: [ + "api", + "--adapter", + "omp-spt", + "bind", + "omp-agent", + "--set-session-id", + "session-1", + "--subnet", + "mesh-a", + ], + input: undefined, + }); + assert.deepEqual(harness.calls[1].args, [ + "api", + "--adapter", + "omp-spt", + "state", + "idle", + "omp-agent", + "--token", + "token-123", + ]); + assert.equal(harness.children.length, 1); + assert.equal(harness.children[0].binary, "spt-test"); + assert.deepEqual(harness.children[0].args, ["ready", "omp-agent", "--subnet", "mesh-a"]); + + for (const reason of ["new", "resume", "fork", "handoff"]) { + assert.deepEqual(await harness.emit("session_before_switch", { reason }), { cancel: true }); + assert.ok( + harness.notifications.some(({ message }) => + message.includes(`${reason} session switch`), + ), + ); + } + assert.deepEqual(await harness.emit("session_before_branch"), { cancel: true }); + assert.ok( + harness.notifications.some(({ message }) => message.includes("session branch")), + ); + + const aliceEnvelope = + 'hello<world
line
'; + const bobEnvelope = 'second'; + harness.children[0].stdout.emit("data", `${aliceEnvelope}${bobEnvelope}`); + await flush(); + assert.deepEqual(harness.submitted, ['']); + assert.deepEqual( + stateCalls(harness).map((call) => call.args[4]), + ["idle", "busy"], + ); + + const originalMessages = [{ role: "user", content: '' }]; + const context = await harness.emit("context", { messages: originalMessages }); + assert.equal(originalMessages[0].content, ''); + assert.equal(context.messages[0].content, `\n\n${aliceEnvelope}`); + + const arrayContext = await harness.emit("context", { + messages: [{ role: "user", content: [{ type: "text", text: '' }] }], + }); + assert.deepEqual(arrayContext.messages[0].content, [ + { type: "text", text: '' }, + { type: "text", text: `\n\n${aliceEnvelope}` }, + ]); + + await harness.emit("agent_start"); + assert.deepEqual( + stateCalls(harness).map((call) => call.args[4]), + ["idle", "busy"], + "agent_start must not duplicate the already-honest busy transition", + ); + await harness.emit("agent_end", { + messages: [ + { role: "user", content: '' }, + { role: "assistant", content: [{ type: "text", text: "alice reply" }] }, + ], + }); + assert.deepEqual(harness.submitted, ['']); + assert.deepEqual(harness.clock.delays(), [0]); + + await harness.clock.runNext(0); + assert.deepEqual(harness.submitted, ['', '']); + await harness.emit("agent_start"); + await harness.emit("agent_end", { + messages: [ + { role: "assistant", content: "previous reply" }, + { role: "user", content: '' }, + ], + }); + + const outcomes = commandCalls(harness, "send"); + assert.equal(outcomes.length, 2); + assert.deepEqual( + outcomes.map((call) => call.args), + [ + ["send", "alice", "--from", "omp-agent"], + ["send", "bob", "--from", "omp-agent"], + ], + ); + assert.equal(outcomes[0].input, "alice reply"); + assert.match(outcomes[1].input, /turn ended without an assistant response/); + assert.deepEqual( + stateCalls(harness).map((call) => call.args[4]), + ["idle", "busy", "idle", "busy", "idle"], + ); + for (const call of [...stateCalls(harness), ...harness.calls.filter((candidate) => candidate.args[3] === "session-end")]) { + assert.deepEqual(call.args.slice(-2), ["--token", "token-123"]); + } + + await harness.emit("session_shutdown"); + const ended = harness.calls.filter((call) => call.args[3] === "session-end"); + assert.equal(ended.length, 1); + assert.deepEqual(ended[0].args.slice(-2), ["--token", "token-123"]); + assert.equal(harness.children[0].kills, 1); + assert.deepEqual(harness.clock.delays(), []); +} + +async function testDeferredBindLifecycleSerialization() { + const busyBind = deferred(); + const busyHarness = createHarness({ + onRun(call) { + if (call.args[0] === "api" && call.args[3] === "bind") return busyBind.promise; + }, + }); + const startingBusy = busyHarness.emit("session_start"); + await flush(); + const becomingBusy = busyHarness.emit("agent_start"); + await flush(); + assert.deepEqual(stateCalls(busyHarness), []); + assert.equal(busyHarness.children.length, 0); + + busyBind.resolve("BOUND endpoint token=token-busy"); + await Promise.all([startingBusy, becomingBusy]); + assert.deepEqual( + stateCalls(busyHarness).map((call) => call.args[4]), + ["busy"], + "agent_start before bind completion must suppress the stale idle publication", + ); + assert.equal(busyHarness.children.length, 1); + await busyHarness.emit("session_shutdown"); + assert.deepEqual(busyHarness.clock.delays(), []); + + const shutdownBind = deferred(); + const shutdownHarness = createHarness({ + onRun(call) { + if (call.args[0] === "api" && call.args[3] === "bind") return shutdownBind.promise; + }, + }); + const startingShutdown = shutdownHarness.emit("session_start"); + await flush(); + const shuttingDown = shutdownHarness.emit("session_shutdown"); + await flush(); + assert.equal(shutdownHarness.children.length, 0); + assert.equal( + shutdownHarness.calls.filter((call) => call.args[3] === "session-end").length, + 0, + ); + + shutdownBind.resolve("BOUND endpoint token=token-shutdown"); + await Promise.all([startingShutdown, shuttingDown]); + assert.deepEqual(stateCalls(shutdownHarness), []); + assert.equal(shutdownHarness.children.length, 0); + assert.equal( + shutdownHarness.calls.filter((call) => call.args[3] === "session-end").length, + 1, + ); + assert.ok( + !shutdownHarness.statuses.some(({ text }) => text === "spt:omp-agent"), + "bind completion after shutdown must not restore live status", + ); + assert.deepEqual(shutdownHarness.clock.delays(), []); +} + +// [unit->REQ-OMP-EXTENSION-CUSTODY] +// [unit->REQ-OMP-LISTENER-FAIL-CLOSED] +async function testOutcomeSendRetriesAndExhaustion() { + let retryAttempts = 0; + const retryHarness = createHarness({ + outcomeRetryDelaysMs: [5, 10], + onRun(call) { + if (call.args[0] === "send" && call.args[1] === "retry") { + retryAttempts += 1; + if (retryAttempts < 3) throw new Error(`outcome failure ${retryAttempts}`); + } + }, + }); + await retryHarness.emit("session_start"); + retryHarness.children[0].stdout.emit( + "data", + 'work', + ); + await flush(); + await retryHarness.emit("agent_start"); + const retryEnding = retryHarness.emit("agent_end", { + messages: [ + { role: "user", content: '' }, + { role: "assistant", content: "eventual outcome" }, + ], + }); + await flush(); + assert.equal(commandCalls(retryHarness, "send").length, 1); + assert.deepEqual(retryHarness.clock.delays(), [5]); + await retryHarness.clock.runNext(5); + assert.equal(commandCalls(retryHarness, "send").length, 2); + assert.deepEqual(retryHarness.clock.delays(), [10]); + await retryHarness.clock.runNext(10); + await retryEnding; + assert.equal(commandCalls(retryHarness, "send").length, 3); + assert.equal(commandCalls(retryHarness, "send").at(-1).input, "eventual outcome"); + assert.equal(retryHarness.shutdowns, 0); + await retryHarness.emit("session_shutdown"); + assert.deepEqual(retryHarness.clock.delays(), []); + + const exhaustedHarness = createHarness({ + outcomeRetryDelaysMs: [7], + onRun(call) { + if (call.args[0] === "send") throw new Error("outcome channel unavailable"); + }, + }); + await exhaustedHarness.emit("session_start"); + const exhaustedListener = exhaustedHarness.children[0]; + exhaustedListener.stdout.emit( + "data", + 'work', + ); + await flush(); + await exhaustedHarness.emit("agent_start"); + const exhaustedEnding = exhaustedHarness.emit("agent_end", { + messages: [ + { role: "user", content: '' }, + { role: "assistant", content: "undeliverable outcome" }, + ], + }); + await flush(); + assert.equal(commandCalls(exhaustedHarness, "send").length, 1); + assert.deepEqual(exhaustedHarness.clock.delays(), [7]); + await exhaustedHarness.clock.runNext(7); + await exhaustedEnding; + + assert.equal(commandCalls(exhaustedHarness, "send").length, 2); + assert.deepEqual( + stateCalls(exhaustedHarness).map((call) => call.args[4]), + ["idle", "busy"], + "exhausted custody must never be advertised idle", + ); + assert.equal(exhaustedHarness.shutdowns, 1); + assert.equal(exhaustedListener.kills, 1); + assert.equal( + exhaustedHarness.calls.filter((call) => call.args[3] === "session-end").length, + 1, + ); + assert.ok( + exhaustedHarness.errors.some(({ message }) => + message.includes("could not send the outcome to exhausted"), + ), + ); + await exhaustedHarness.emit("session_shutdown"); + assert.deepEqual(exhaustedHarness.clock.delays(), []); +} + +// [unit->REQ-OMP-EXTENSION-CUSTODY] +async function testSubmissionFailureAdvancesQueue() { + const harness = createHarness({ + onSubmit(content) { + if (content === '') throw new Error("OMP prompt flow rejected input"); + }, + }); + await harness.emit("session_start"); + harness.children[0].stdout.emit( + "data", + 'onetwo', + ); + await flush(); + + const firstOutcome = commandCalls(harness, "send"); + assert.equal(firstOutcome.length, 1); + assert.deepEqual(firstOutcome[0].args, ["send", "broken", "--from", "omp-agent"]); + assert.match(firstOutcome[0].input, /could not submit your message to OMP/); + assert.deepEqual(harness.clock.delays(), [0]); + + await harness.clock.runNext(0); + assert.deepEqual(harness.submitted, ['', '']); + await harness.emit("agent_start"); + await harness.emit("agent_end", { + messages: [ + { role: "user", content: '' }, + { role: "assistant", content: "next reply" }, + ], + }); + const outcomes = commandCalls(harness, "send"); + assert.equal(outcomes.length, 2); + assert.deepEqual( + outcomes.map((call) => call.args[1]), + ["broken", "next"], + ); + assert.equal(outcomes[1].input, "next reply"); + await harness.emit("session_shutdown"); + assert.deepEqual(harness.clock.delays(), []); +} + +async function testFailedIdleRecoveryFailsClosed() { + let idleCalls = 0; + const harness = createHarness({ + onSubmit() { + throw new Error("OMP prompt flow rejected input"); + }, + onRun(call) { + if (call.args[0] === "api" && call.args[3] === "state" && call.args[4] === "idle") { + idleCalls += 1; + if (idleCalls === 2) throw new Error("state channel unavailable"); + } + }, + }); + await harness.emit("session_start"); + harness.children[0].stdout.emit("data", 'one'); + await flush(); + + assert.equal(commandCalls(harness, "send").length, 1); + assert.match(commandCalls(harness, "send")[0].input, /could not submit your message to OMP/); + assert.equal(harness.shutdowns, 1); + assert.equal(harness.calls.filter((call) => call.args[3] === "session-end").length, 1); + assert.ok( + harness.errors.some(({ message }) => + message.includes("could not restore idle state after a failed submission"), + ), + ); + assert.deepEqual(harness.clock.delays(), []); +} + +// [unit->REQ-OMP-LISTENER-FAIL-CLOSED] +async function testListenerRestartExhaustion() { + const harness = createHarness({ restartDelaysMs: [5, 10] }); + await harness.emit("session_start"); + const first = harness.children[0]; + first.emit("close", 7); + assert.deepEqual(harness.clock.delays(), [5]); + + await harness.clock.runNext(5); + const second = harness.children[1]; + second.stdout.emit("data", 'half'); + second.emit("error", new Error("listener crashed")); + second.emit("close", 8); + assert.deepEqual(harness.clock.delays(), [10], "error plus close schedules one restart"); + + await harness.clock.runNext(10); + const third = harness.children[2]; + third.emit("close", 9); + await flush(); + + assert.equal(harness.children.length, 3); + assert.equal(harness.shutdowns, 1); + assert.ok( + harness.errors.some(({ message }) => message.includes("listener restart budget exhausted")), + ); + assert.ok( + harness.notifications.some(({ message, type }) => + type === "error" && message.includes("listener restart budget exhausted"), + ), + ); + assert.equal(harness.calls.filter((call) => call.args[3] === "session-end").length, 1); + assert.deepEqual(harness.clock.delays(), []); + + await harness.emit("session_shutdown"); + assert.equal( + harness.calls.filter((call) => call.args[3] === "session-end").length, + 1, + "fatal shutdown and lifecycle shutdown share one teardown", + ); +} + +async function testListenerStableIntervalResetsRetries() { + const harness = createHarness({ + listenerStableMs: 20, + restartDelaysMs: [5, 10], + }); + await harness.emit("session_start"); + await harness.emit("agent_start"); + assert.deepEqual(harness.clock.delays(), [20]); + + harness.children[0].emit("close", 1); + assert.deepEqual(harness.clock.delays(), [5]); + await harness.clock.runNext(5); + + const shortLived = harness.children[1]; + shortLived.stdout.emit( + "data", + 'a parsed event is not stability', + ); + shortLived.emit("close", 2); + assert.deepEqual( + harness.clock.delays(), + [10], + "a parsed event followed by an immediate crash remains in the consecutive crash loop", + ); + await harness.clock.runNext(10); + + const stable = harness.children[2]; + assert.deepEqual(harness.clock.delays(), [20]); + await harness.clock.runNext(20); + stable.emit("close", 3); + assert.deepEqual( + harness.clock.delays(), + [5], + "a listener surviving the stable interval resets the next retry to attempt one", + ); + assert.match( + harness.notifications.filter(({ type }) => type === "warning").at(-1).message, + /restarting 1\/2 in 5ms/, + ); + + await harness.clock.runNext(5); + assert.equal(harness.children.length, 4); + await harness.emit("session_shutdown"); + assert.deepEqual(harness.clock.delays(), []); +} + +// [unit->REQ-OMP-EXTENSION-CUSTODY] +// [unit->REQ-OMP-LISTENER-FAIL-CLOSED] +async function testFatalTeardownAwaitsInFlightOutcome() { + let releaseOutcome; + const outcomeGate = new Promise((resolve) => { + releaseOutcome = resolve; + }); + const harness = createHarness({ + restartDelaysMs: [], + onRun(call) { + if (call.args[0] === "send" && call.args[1] === "slow") return outcomeGate; + }, + }); + await harness.emit("session_start"); + harness.children[0].stdout.emit("data", 'work'); + await flush(); + await harness.emit("agent_start"); + const ending = harness.emit("agent_end", { + messages: [ + { role: "user", content: '' }, + { role: "assistant", content: "finished" }, + ], + }); + await flush(); + assert.equal(commandCalls(harness, "send").length, 1); + + harness.children[0].emit("close", 11); + await flush(); + assert.equal(harness.shutdowns, 0, "fatal teardown must join the sender outcome"); + assert.equal(harness.calls.filter((call) => call.args[3] === "session-end").length, 0); + + const shutdown = harness.emit("session_shutdown"); + await flush(); + assert.equal( + harness.calls.filter((call) => call.args[3] === "session-end").length, + 0, + "concurrent lifecycle shutdown must join fatal custody teardown", + ); + + releaseOutcome(); + await Promise.all([ending, shutdown]); + await flush(); + assert.equal(harness.shutdowns, 1); + assert.equal(harness.calls.filter((call) => call.args[3] === "session-end").length, 1); + assert.deepEqual(harness.clock.delays(), []); +} + +async function testSessionEndRetriesAfterTransientFailure() { + let endAttempts = 0; + const harness = createHarness({ + restartDelaysMs: [], + onRun(call) { + if (call.args[0] === "api" && call.args[3] === "session-end") { + endAttempts += 1; + if (endAttempts === 1) throw new Error("transient teardown failure"); + } + }, + }); + await harness.emit("session_start"); + harness.children[0].emit("close", 12); + await flush(); + + assert.equal(harness.shutdowns, 1); + assert.equal( + harness.calls.filter((call) => call.args[3] === "session-end").length, + 1, + ); + assert.ok( + harness.errors.some( + ({ message, details }) => + message.includes("session teardown failed") && + details.error.includes("transient teardown failure"), + ), + ); + + await harness.emit("session_shutdown"); + assert.equal( + harness.calls.filter((call) => call.args[3] === "session-end").length, + 2, + "a rejected teardown must not poison the later lifecycle retry", + ); + assert.deepEqual(harness.clock.delays(), []); +} + +async function testHumanBusyFailureFailsClosed() { + const harness = createHarness({ + onRun(call) { + if (call.args[0] === "api" && call.args[3] === "state" && call.args[4] === "busy") { + throw new Error("state channel unavailable"); + } + }, + }); + await harness.emit("session_start"); + await harness.emit("agent_start"); + + assert.equal(harness.shutdowns, 1); + assert.equal(harness.calls.filter((call) => call.args[3] === "session-end").length, 1); + assert.ok( + harness.errors.some(({ message }) => message.includes("could not mark the endpoint busy")), + ); + assert.equal(harness.children[0].kills, 1); + assert.deepEqual(harness.clock.delays(), []); +} + +// [unit->REQ-OMP-EXTENSION-CUSTODY] +// [unit->REQ-OMP-LISTENER-FAIL-CLOSED] +async function testShutdownReapsAndFailsQueuedCustody() { + const harness = createHarness(); + await harness.emit("session_start"); + const listener = harness.children[0]; + listener.stdout.emit( + "data", + 'onetwo', + ); + await flush(); + await harness.emit("agent_start"); + await harness.emit("agent_end", { + messages: [ + { role: "user", content: '' }, + { role: "assistant", content: "done" }, + ], + }); + assert.deepEqual(harness.clock.delays(), [0]); + + await harness.emit("session_shutdown"); + assert.equal(listener.kills, 1); + assert.deepEqual(harness.clock.delays(), []); + assert.deepEqual( + commandCalls(harness, "send").map((call) => call.args[1]), + ["first", "queued"], + ); + assert.match(commandCalls(harness, "send")[1].input, /OMP session shut down/); + assert.equal(harness.calls.filter((call) => call.args[3] === "session-end").length, 1); + assert.deepEqual(harness.statuses.at(-1), { key: "omp-spt", text: undefined }); + assert.equal(harness.shutdowns, 0, "normal lifecycle shutdown must not recursively shut down OMP"); +} + +await testParsingAndReplies(); +await testLifecycleCustodyAndContext(); +await testDeferredBindLifecycleSerialization(); +await testOutcomeSendRetriesAndExhaustion(); +await testSubmissionFailureAdvancesQueue(); +await testFailedIdleRecoveryFailsClosed(); +await testListenerRestartExhaustion(); +await testListenerStableIntervalResetsRetries(); +await testFatalTeardownAwaitsInFlightOutcome(); +await testSessionEndRetriesAfterTransientFailure(); +await testHumanBusyFailureFailsClosed(); +await testShutdownReapsAndFailsQueuedCustody(); console.log("OMP-EXTENSION OK");