Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/pi-agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ starts its HTTP server on `0.0.0.0:PORT`.
chat request at a time, with a two-minute deadline and an eight-tool-call
budget. HTTP history is reconstructed from each request in memory, separate
from native TUI history. Automatic model retries and compaction are disabled.
Streaming responses send bounded SSE keepalives every 15 seconds during silent
model prefill or tool work. The two-minute task deadline, cancellation and output
limits still apply; keepalives do not extend a task or replay a request.
See the [Custom Agent contract](../../docs/agent-harness-contract.md) for the
platform requirements beyond this example.

Expand Down
35 changes: 25 additions & 10 deletions examples/pi-agent/agent-api.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createHTTPServer, readJSON, writeJSON } from "./http.mjs";
const CHAT_TIMEOUT_MS = 120_000;
const OUTPUT_LIMIT = 4 * 1024 * 1024;
const STREAM_BUFFER_LIMIT = 256 * 1024;
const STREAM_KEEPALIVE_MS = 15_000;

/**
* The CetiRun HTTP contract. The supplied runtime implements models(signal)
Expand Down Expand Up @@ -94,8 +95,9 @@ async function handleChat(request, response, runtime, activity, runs) {
created: Math.floor(Date.now() / 1000),
model: input.model,
};
let stream;
try {
const stream = input.stream ? startStream(response, completion, controller) : undefined;
stream = input.stream ? startStream(response, completion, controller, signal) : undefined;
const result = await runtime.run({
...input,
memory: { noMemory: request.headers["x-cetirun-memory-mode"] === "off", noCapture: ["off", "no-capture"].includes(request.headers["x-cetirun-memory-mode"]) },
Expand Down Expand Up @@ -123,33 +125,46 @@ async function handleChat(request, response, runtime, activity, runs) {
if (response.headersSent) response.destroy();
else writeJSON(response, 502, { error: { message: "Pi run failed or model access is unavailable" } });
} finally {
stream?.close();
activity.chat = false;
runs.delete(controller);
response.off("close", disconnected);
}
}

function startStream(response, completion, controller) {
function startStream(response, completion, controller, signal) {
let outputBytes = 0;
const write = (event) => {
if (response.destroyed || response.writableEnded || signal.aborted) return;
outputBytes += Buffer.byteLength(event);
if (outputBytes > OUTPUT_LIMIT || response.writableLength > STREAM_BUFFER_LIMIT) {
controller.abort();
return;
}
response.write(event);
};
const chunk = (delta, finishReason = null) => {
if (response.destroyed) return;
const data = JSON.stringify({
...completion,
object: "chat.completion.chunk",
choices: [{ index: 0, delta, finish_reason: finishReason }],
});
outputBytes += Buffer.byteLength(data);
if (outputBytes > OUTPUT_LIMIT || response.writableLength > STREAM_BUFFER_LIMIT) {
controller.abort();
return;
}
response.write(`data: ${data}\n\n`);
write(`data: ${data}\n\n`);
};
response.writeHead(200, {
"Content-Type": "text/event-stream",
"Cache-Control": "no-store",
Connection: "close",
});
chunk({ role: "assistant" });
return { chunk };
let timer = setInterval(() => write(": keepalive\n\n"), STREAM_KEEPALIVE_MS);
timer.unref();
const close = () => {
if (timer !== undefined) clearInterval(timer);
timer = undefined;
signal.removeEventListener("abort", close);
};
signal.addEventListener("abort", close, { once: true });
if (signal.aborted) close();
return { chunk, close };
}
55 changes: 55 additions & 0 deletions examples/pi-agent/test/server.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,61 @@ test("chat invokes the adapter once and streams valid final events", async (t) =
assert.equal(f.calls(), 2);
});

test("silent streaming work emits bounded keepalives and stops its timer on completion", async (t) => {
t.mock.timers.enable({ apis: ["setInterval"] });
const cleared = t.mock.method(globalThis, "clearInterval");
let finish;
const f = await fixture(t, { run: ({ signal }) => new Promise((resolve, reject) => {
finish = () => resolve({ text: "done" });
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
}) });
const response = await fetch(f.base + "/v1/chat/completions", post({ ...chat, stream: true }));
const reader = response.body.getReader();
const next = async () => {
let timer;
try {
return await Promise.race([
reader.read(),
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("stream produced no keepalive")), 1000); }),
]);
} finally { clearTimeout(timer); }
};
assert.match(new TextDecoder().decode((await next()).value), /"role":"assistant"/);
t.mock.timers.tick(15_000);
assert.equal(new TextDecoder().decode((await next()).value), ": keepalive\n\n");
finish();
let output = "";
for (;;) {
const chunk = await next();
if (chunk.done) break;
output += new TextDecoder().decode(chunk.value);
}
assert.match(output, /"finish_reason":"stop"/);
assert.equal(output.split("data: [DONE]").length, 2);
assert.equal(cleared.mock.callCount(), 1);
});

test("stream keepalives stop on cancellation without changing the task deadline", async (t) => {
t.mock.timers.enable({ apis: ["setInterval"] });
const cleared = t.mock.method(globalThis, "clearInterval");
const deadlines = t.mock.method(AbortSignal, "timeout");
let aborted;
const seenAbort = new Promise((resolve) => { aborted = resolve; });
const f = await fixture(t, { run: ({ signal }) => new Promise((_, reject) => {
signal.addEventListener("abort", () => { aborted(); reject(signal.reason); }, { once: true });
}) });
const response = await fetch(f.base + "/v1/chat/completions", post({ ...chat, stream: true }));
const reader = response.body.getReader();
await reader.read();
t.mock.timers.tick(15_000);
assert.equal(new TextDecoder().decode((await reader.read()).value), ": keepalive\n\n");
await reader.cancel();
await seenAbort;
await new Promise((resolve) => setImmediate(resolve));
assert.equal(cleared.mock.callCount(), 1);
assert.ok(deadlines.mock.calls.some((call) => call.arguments[0] === 120_000));
});

test("invalid extensions and history are rejected before execution", async (t) => {
const f = await fixture(t);
for (const value of [{ ...chat, tools: [] }, { ...chat, messages: [] }, { ...chat, stream: "yes" }]) {
Expand Down
Loading