diff --git a/apps/server/src/chat/turn-handover.test.ts b/apps/server/src/chat/turn-handover.test.ts index 906b9e149..a633ebb49 100644 --- a/apps/server/src/chat/turn-handover.test.ts +++ b/apps/server/src/chat/turn-handover.test.ts @@ -11,15 +11,18 @@ import { openPlannerSession } from "../harness/session"; import * as Plan from "../plan/service"; import { configured } from "../testing/config"; import { + finishTurn, LINK_PERSISTENCE, linkAuth, linkServer, MEMBER_TOKEN, rawLink, } from "../testing/agent-link"; +import { connectAgent } from "@chopin/agent-link/client"; import * as Chat from "./service"; import type { Server } from "bun"; +import type { AgentHandlers, TurnContext } from "@chopin/agent-link/client"; import type { HostedAuth } from "../auth/routes"; import type { Lease, PlannerLinkHold } from "../storage/model"; import type { Socket, SocketData } from "../wire"; @@ -315,7 +318,7 @@ async function cutProcess( /** The next process: it takes the lease, rebuilds the holds and opens the document. */ async function takeOver( - d: Deployed, + d: { linked: Linked }, options: { failHoldWrites?: () => boolean; name?: string } = {}, ) { let { linked } = d; @@ -812,6 +815,63 @@ describe("a remote turn Chat cannot go on with", () => { }); }); +describe("the reference client across a deploy", () => { + it("keeps its turn running, takes it back from the next process, and the reply ends once, whole", async () => { + let linked = await linkAuth(undefined, { persistent: true }); + let first = await startProcess(linked, "first"); + let gate = Promise.withResolvers(); + let edited: unknown; + let handlers: AgentHandlers = { + async turn(turn: TurnContext) { + turn.emit({ type: "text-start", id: "t1" }); + turn.emit({ type: "text-delta", id: "t1", delta: "Writing" }); + edited = await turn.callHostTool("edit_plan", { + revision: first.plan.revision, + operations: [{ op: "replace_root", source: "# Plan\n\nApplied once.\n" }], + }); + // Still running when the deploy begins, and after the next process takes it back. + await gate.promise; + turn.emit({ type: "text-delta", id: "t1", delta: " more." }); + turn.emit({ type: "text-end", id: "t1" }); + finishTurn(turn); + }, + }; + let client = await connectAgent({ + url: first.server.url, + token: MEMBER_TOKEN, + document: linked.channel.id, + handlers, + resumable: true, + }); + expect(client.features).toContain("turn-handover"); + await first.send("@chopin write it"); + await until(() => edited !== undefined); + expect(edited).toEqual({ output: expect.anything(), isError: false }); + expect((await cutProcess(linked, first)).handed).toBe(true); + let held = await client.resumption; + expect(held?.turns.size).toBe(1); + + let next = await takeOver({ linked }); + await next.browserReturns(); + let back = await connectAgent({ + url: next.server.url, + token: MEMBER_TOKEN, + document: linked.channel.id, + handlers, + resume: held!, + }); + cleanups.push(() => back.detach()); + gate.resolve(); + await next.adopted; + await until(() => !next.context.chat.busy); + + expect(Plan.source(next.plan).match(/Applied once\./g)).toHaveLength(1); + let said = next.context.chat.entries.map(entry => entry.text); + expect(said.filter(text => text.includes("Writing"))).toEqual(["Writing more."]); + expect(said.some(text => /restart/i.test(text))).toBe(false); + }); +}); + /** What the hold of the first process says once its drain has written it. */ async function cutRows(d: Deployed): Promise { await d.first.attachments.keepHandedTurn(d.linked.channel.id); diff --git a/packages/agent-link/src/client.test.ts b/packages/agent-link/src/client.test.ts index ac5a35037..c8ef73d5d 100644 --- a/packages/agent-link/src/client.test.ts +++ b/packages/agent-link/src/client.test.ts @@ -4,7 +4,7 @@ import { connectAgent } from "./client"; import { MAX_LINK_MESSAGE_BYTES, MAX_LINK_NOTE_LENGTH, parseClientMessage } from "./protocol"; import type { ServerWebSocket } from "bun"; -import type { AgentHandlers, HostToolResult, TurnContext } from "./client"; +import type { AgentHandlers, HostToolResult, Resumption, TurnContext } from "./client"; import type { ClientMessage, ClientMessageOf, ServerMessage, ServerMessageOf } from "./protocol"; let stops: Array<() => unknown> = []; @@ -125,7 +125,9 @@ describe("Agent connection client", () => { it("asks for the features it knows and reports no runs", async () => { let server = fakeServer({ features: ["decision-option-previews"] }); let client = await connect(server, { turn() {} }); - expect(server.asked).toEqual(["decision-option-previews, resumable-sessions, restart-notice"]); + expect(server.asked).toEqual([ + "decision-option-previews, resumable-sessions, restart-notice, turn-handover", + ]); expect(client.features).toEqual(["decision-option-previews"]); expect("reportRuns" in client).toBe(false); }); @@ -903,6 +905,549 @@ describe("Agent connection client", () => { }); }); +const HANDING = ["resumable-sessions", "turn-handover"]; +const FRAMES = new Set(["tools", "part", "host-tool-call", "turn-end"]); +type Frame = ClientMessageOf<"tools" | "part" | "host-tool-call" | "turn-end">; + +/** The next `count` turn frames the server received, in the order they came. */ +async function frames(server: ReturnType, count: number): Promise { + let taken: Frame[] = []; + for (let deadline = Date.now() + 2_000; taken.length < count;) { + let index = server.received.findIndex(message => FRAMES.has(message.type)); + if (index >= 0) taken.push(server.received.splice(index, 1)[0] as Frame); + else if (Date.now() > deadline) throw new Error(`${taken.length} of ${count} frames came`); + else await Bun.sleep(5); + } + return taken; +} + +/** Waits for `check` to hold, for two seconds at most. */ +async function until(check: () => boolean) { + for (let deadline = Date.now() + 2_000; !check(); await Bun.sleep(5)) { + if (Date.now() > deadline) throw new Error("It never came to hold."); + } +} + +/** Each frame as its type, its number, and the tool it calls or how the turn ended. */ +const summary = (sent: Frame[]) => + sent.map(frame => [ + frame.type, + frame.seq, + ...(frame.type === "host-tool-call" ? [frame.toolName] : []), + ...(frame.type === "turn-end" ? [frame.status] : []), + ]); + +/** Resolves once the client has read every message the server sent before it. */ +async function read(server: ReturnType) { + let request = crypto.randomUUID(); + server.send({ type: "input-result", request, status: "cancelled" }); + for (let acknowledged = false; !acknowledged;) { + acknowledged = (await server.next("input-received")).request === request; + } +} + +async function attachTo( + server: ReturnType, + handlers: AgentHandlers, + resume?: Resumption, +) { + let attaching = connectAgent({ + url: server.url, + token: "t", + document: "d", + handlers, + ...(resume ? { resume } : {}), + }); + let asked = await server.next("resume"); + return { asked, attaching }; +} + +/** A client running turn `t` of session `s` on a link that accepted `turn-handover`. */ +async function running(handlers: AgentHandlers) { + let server = fakeServer({ features: HANDING }); + let { attaching } = await attachTo(server, handlers); + server.send({ type: "resumed", sessions: [] }); + let client = await attaching; + stops.push(() => client.detach()); + server.send({ type: "start", session: "s", mode: "planner" }); + await server.next("started"); + server.send(turn("t")); + return { server, client }; +} + +/** + * A turn that says one thing and asks for a read, then, as the test lets it, says another and + * asks for a write, and finishes once both are answered. + */ +function script() { + let gates = [Promise.withResolvers(), Promise.withResolvers()] as const; + let results: HostToolResult[] = []; + let context = Promise.withResolvers(); + let handlers: AgentHandlers = { + async turn(turn) { + context.resolve(turn); + turn.emit({ type: "text-delta", id: "x", delta: "a" }); + let read = turn.callHostTool("read_plan", {}); + await gates[0].promise; + turn.emit({ type: "text-delta", id: "x", delta: "b" }); + await gates[1].promise; + let write = turn.callHostTool("edit_plan", {}); + results.push(await read, await write); + }, + }; + return { gates, results, context: context.promise, handlers }; +} + +const handover = (after: number, withinMs = 5_000) => ({ + type: "turn-handover" as const, + session: "s", + turn: "t", + after, + withinMs, +}); +const kept = [{ session: "s", requests: [] }]; + +function answer(server: ReturnType, calls: Frame[]) { + for (let call of calls) { + if (call.type !== "host-tool-call") continue; + let { session, turn, toolCallId, toolName } = call; + server.send({ type: "host-tool-result", session, turn, toolCallId, output: toolName }); + } +} + +describe("Agent connection client handing a turn over", () => { + it("numbers every frame of a turn from 1 on a link that accepted the feature, and none on one that did not", async () => { + let handlers: AgentHandlers = { + async turn(context) { + context.offerTools(["bash"]); + let huge = "x".repeat(MAX_LINK_MESSAGE_BYTES); + expect(() => context.emit({ type: "text-delta", id: "x", delta: huge })).toThrow(); + context.emit({ type: "text-delta", id: "x", delta: "a" }); + await context.callHostTool("read_plan", {}); + }, + }; + let { server } = await running(handlers); + let sent = await frames(server, 3); + answer(server, sent); + sent.push(...await frames(server, 1)); + expect(summary(sent)).toEqual([ + ["tools", 1], + ["part", 2], + ["host-tool-call", 3, "read_plan"], + ["turn-end", 4, "finished"], + ]); + + let older = fakeServer({ features: ["resumable-sessions"] }); + let { attaching } = await attachTo(older, handlers); + older.send({ type: "resumed", sessions: [] }); + stops.push(async () => (await attaching).detach()); + await attaching; + older.send(turn("t")); + let plain = await frames(older, 3); + answer(older, plain); + plain.push(...await frames(older, 1)); + expect(summary(plain)).toEqual([ + ["tools", undefined], + ["part", undefined], + ["host-tool-call", undefined, "read_plan"], + ["turn-end", undefined, "finished"], + ]); + expect(plain.some(frame => "seq" in frame)).toBe(false); + }); + + it("keeps a handed-over turn running across the close, its calls open and its frames held, and sends every frame after the cursor of the server that takes it back", async () => { + let { gates, results, context, handlers } = script(); + let { server, client } = await running(handlers); + expect(summary(await frames(server, 2))).toEqual([ + ["part", 1], + ["host-tool-call", 2, "read_plan"], + ]); + // The old process applied the first frame only: the read it never took is the next one's. + server.send(handover(1, 400)); + await read(server); + gates[0].resolve(); + await Bun.sleep(20); + server.close(); + let resumption = await client.resumption; + gates[1].resolve(); + await Bun.sleep(20); + expect((await context).signal.aborted).toBe(false); + expect(results).toEqual([]); + expect(server.received.filter(message => FRAMES.has(message.type))).toEqual([]); + + let { asked, attaching } = await attachTo(server, handlers, resumption); + expect(asked).toEqual({ type: "resume", sessions: kept, turns: [{ session: "s", turn: "t" }] }); + server.send({ + type: "resumed", + sessions: kept, + turns: [{ session: "s", turn: "t", after: 1 }], + }); + stops.push(async () => (await attaching).detach()); + await attaching; + let resent = await frames(server, 3); + expect(summary(resent)).toEqual([ + ["host-tool-call", 2, "read_plan"], + ["part", 3], + ["host-tool-call", 4, "edit_plan"], + ]); + // Taken back, it no longer runs against the handover's time. + await Bun.sleep(450); + expect((await context).signal.aborted).toBe(false); + answer(server, resent); + expect(summary(await frames(server, 1))).toEqual([["turn-end", 5, "finished"]]); + expect(results).toEqual([ + { output: "read_plan", isError: false }, + { output: "edit_plan", isError: false }, + ]); + }); + + it("takes a turn back once: a later close without a new handover ends it, and a new handover sends only what follows its cursor", async () => { + let { gates, results, context, handlers } = script(); + let { server, client } = await running(handlers); + await frames(server, 2); + server.send(handover(0, 150)); + await read(server); + server.close(); + let { attaching } = await attachTo(server, handlers, (await client.resumption)!); + // What is sent again follows the resuming server's cursor, not the handover's. + server.send({ + type: "resumed", + sessions: kept, + turns: [{ session: "s", turn: "t", after: 1 }], + }); + let second = await attaching; + stops.push(() => second.detach()); + gates[0].resolve(); + expect(summary(await frames(server, 2))).toEqual([ + ["host-tool-call", 2, "read_plan"], + ["part", 3], + ]); + // This process applied through the read, and hands the turn over in its turn. + server.send(handover(2)); + await read(server); + server.close(); + let held = (await second.resumption)!; + // Only this handover's time runs now, not the first one's. + await Bun.sleep(200); + expect((await context).signal.aborted).toBe(false); + let { asked, attaching: third } = await attachTo(server, handlers, held); + expect(asked.turns).toEqual([{ session: "s", turn: "t" }]); + server.send({ + type: "resumed", + sessions: kept, + turns: [{ session: "s", turn: "t", after: 2 }], + }); + let last = await third; + expect(summary(await frames(server, 1))).toEqual([["part", 3]]); + server.close(); + expect((await last.resumption)?.turns.size).toBe(0); + expect((await context).signal.aborted).toBe(true); + gates[1].resolve(); + await Bun.sleep(20); + expect(results).toEqual([ + { output: { error: "The agent connection closed." }, isError: true }, + { output: { error: "The turn has ended." }, isError: true }, + ]); + }); + + it("keeps an ended turn's frames, its end included, for a server that hands it over before reading them", async () => { + let { server, client } = await running({ + turn(context) { + context.emit({ type: "text-delta", id: "x", delta: "done" }); + }, + }); + expect(summary(await frames(server, 2))).toEqual([["part", 1], ["turn-end", 2, "finished"]]); + server.send(handover(1)); + await read(server); + server.close(); + let { asked, attaching } = await attachTo( + server, + { turn() {} }, + (await client.resumption)!, + ); + expect(asked.turns).toEqual([{ session: "s", turn: "t" }]); + server.send({ + type: "resumed", + sessions: kept, + turns: [{ session: "s", turn: "t", after: 1 }], + }); + stops.push(async () => (await attaching).detach()); + await attaching; + expect(summary(await frames(server, 1))).toEqual([["turn-end", 2, "finished"]]); + }); + + it("forgets an ended turn once its session's next turn starts, so the server cannot hand it over", async () => { + let { server, client } = await running({ turn() {} }); + await frames(server, 1); + server.send({ ...turn("next"), session: "s" }); + await frames(server, 1); + server.send(handover(0)); + await read(server); + server.close(); + expect((await client.resumption)?.turns.size).toBe(0); + }); + + it("gives a handed-over turn up when no link takes it back within withinMs of the close", async () => { + let { gates, results, context, handlers } = script(); + let { server, client } = await running(handlers); + await frames(server, 2); + server.send(handover(2, 200)); + await read(server); + gates[0].resolve(); + gates[1].resolve(); + let turn = await context; + await Bun.sleep(250); + // The time runs from the close, not from the handover. + expect(turn.signal.aborted).toBe(false); + server.close(); + let resumption = (await client.resumption)!; + await Bun.sleep(20); + expect(turn.signal.aborted).toBe(false); + await until(() => results.length > 0); + expect(turn.signal.aborted).toBe(true); + expect(results).toEqual([ + { output: { error: "The turn was aborted." }, isError: true }, + { output: { error: "The turn was aborted." }, isError: true }, + ]); + let { asked, attaching } = await attachTo(server, handlers, resumption); + expect(asked).toEqual({ type: "resume", sessions: kept }); + server.send({ type: "resumed", sessions: kept }); + stops.push(async () => (await attaching).detach()); + await attaching; + await Bun.sleep(20); + expect(server.received.filter(message => FRAMES.has(message.type))).toEqual([]); + }); + + it("answers a server that takes back a turn it gave up after naming it with one aborted end at the cursor", async () => { + let { gates, context, handlers } = script(); + let { server, client } = await running(handlers); + await frames(server, 2); + server.send(handover(1, 50)); + await read(server); + gates[0].resolve(); + server.close(); + let { asked, attaching } = await attachTo(server, handlers, (await client.resumption)!); + expect(asked.turns).toEqual([{ session: "s", turn: "t" }]); + let turn = await context; + await until(() => turn.signal.aborted); + server.send({ + type: "resumed", + sessions: kept, + turns: [{ session: "s", turn: "t", after: 1 }], + }); + stops.push(async () => (await attaching).detach()); + await attaching; + expect(await frames(server, 1)).toEqual([ + { type: "turn-end", session: "s", turn: "t", status: "aborted", seq: 2 }, + ]); + await Bun.sleep(20); + expect(server.received.filter(message => FRAMES.has(message.type))).toEqual([]); + }); + + it("ends a turn it named that the server does not take back, and sends nothing of it", async () => { + let { gates, results, context, handlers } = script(); + let { server, client } = await running(handlers); + await frames(server, 2); + server.send(handover(1)); + await read(server); + server.close(); + let { attaching } = await attachTo(server, handlers, (await client.resumption)!); + server.send({ type: "resumed", sessions: kept }); + stops.push(async () => (await attaching).detach()); + await attaching; + expect((await context).signal.aborted).toBe(true); + gates[0].resolve(); + gates[1].resolve(); + await Bun.sleep(20); + expect(results).toEqual([ + { output: { error: "The turn was aborted." }, isError: true }, + { output: { error: "The turn has ended." }, isError: true }, + ]); + expect(server.received.filter(message => FRAMES.has(message.type))).toEqual([]); + }); + + it("gives a handed-over turn up for a server that can no longer take it back, or that refuses the resume for good", async () => { + for (let next of [["resumable-sessions"], [], "refused"] as const) { + let { context, handlers } = script(); + let { server, client } = await running(handlers); + await frames(server, 2); + server.send(handover(1)); + await read(server); + server.close(); + let resumption = (await client.resumption)!; + if (next === "refused") { + let { attaching } = await attachTo(server, handlers, resumption); + server.send({ type: "refused", code: "access-revoked", message: "x" }); + await expect(attaching).rejects.toMatchObject({ code: "access-revoked" }); + } else if (next.length > 0) { + let older = fakeServer({ features: [...next] }); + let { asked, attaching } = await attachTo(older, handlers, resumption); + expect(asked).toEqual({ type: "resume", sessions: kept }); + older.send({ type: "resumed", sessions: kept }); + stops.push(async () => (await attaching).detach()); + await attaching; + } else { + let plain = fakeServer({ features: [] }); + let attached = await connectAgent({ + url: plain.url, + token: "t", + document: "d", + handlers, + resume: resumption, + }); + stops.push(() => attached.detach()); + } + expect((await context).signal.aborted, JSON.stringify(next)).toBe(true); + } + }); + + it("ends a handed-over turn the server then aborts or destroys, or the client detaches from, and keeps nothing of it", async () => { + for (let ending of ["abort", "destroy", "detach"] as const) { + let { context, handlers } = script(); + let { server, client } = await running(handlers); + await frames(server, 2); + server.send(handover(1)); + if (ending === "abort") server.send({ type: "abort", session: "s", turn: "t" }); + if (ending === "destroy") server.send({ type: "destroy", session: "s" }); + await read(server); + if (ending === "detach") void client.detach(); + else expect((await context).signal.aborted, ending).toBe(true); + server.close(); + expect((await client.resumption)?.turns.size ?? 0, ending).toBe(0); + expect((await context).signal.aborted, ending).toBe(true); + } + }); + + it("ends a turn the server never handed over when its link closes, as before", async () => { + let { gates, results, context, handlers } = script(); + let { server, client } = await running(handlers); + await frames(server, 2); + server.close(); + expect((await client.resumption)?.turns.size).toBe(0); + expect((await context).signal.aborted).toBe(true); + gates[0].resolve(); + gates[1].resolve(); + await Bun.sleep(20); + expect(results).toEqual([ + { output: { error: "The agent connection closed." }, isError: true }, + { output: { error: "The turn has ended." }, isError: true }, + ]); + }); + + /** A part of about 2 MB of UTF-8 but 1 MB of characters: bytes, not characters, pass the cap. */ + const large = { type: "text-delta" as const, id: "x", delta: "\u00e9".repeat(1_000_000) }; + const LINK_CLOSED = { output: { error: "The agent connection closed." }, isError: true }; + + it("never hands over a turn whose kept frames passed 32 MiB, and its link's close ends it as before", async () => { + let results: HostToolResult[] = []; + let { server, client } = await running({ + async turn(context) { + for (let part = 0; part < 17; part++) context.emit(large); + results.push(await context.callHostTool("read_plan", {})); + }, + }); + // Still numbered past the cap, as the server requires. + expect(summary(await frames(server, 18)).at(-1)).toEqual(["host-tool-call", 18, "read_plan"]); + server.send(handover(18)); + await read(server); + server.close(); + expect((await client.resumption)?.turns.size).toBe(0); + await until(() => results.length > 0); + expect(results).toEqual([LINK_CLOSED]); + }); + + it("counts against the cap only the frames after the server's cursor", async () => { + let gate = Promise.withResolvers(); + let handlers: AgentHandlers = { + async turn(context) { + for (let part = 0; part < 16; part++) context.emit(large); + await gate.promise; + for (let part = 0; part < 2; part++) context.emit(large); + await context.callHostTool("read_plan", {}); + }, + }; + let { server, client } = await running(handlers); + await frames(server, 16); + server.send(handover(16)); + await read(server); + gate.resolve(); + await Bun.sleep(50); + server.close(); + let { asked, attaching } = await attachTo(server, handlers, (await client.resumption)!); + expect(asked.turns).toEqual([{ session: "s", turn: "t" }]); + server.send({ + type: "resumed", + sessions: kept, + turns: [{ session: "s", turn: "t", after: 16 }], + }); + stops.push(async () => (await attaching).detach()); + await attaching; + expect(summary(await frames(server, 3))).toEqual([ + ["part", 17], + ["part", 18], + ["host-tool-call", 19, "read_plan"], + ]); + }); + + it("ends a handed-over turn whose kept frames pass the cap as before the feature: at its link's close, or at once once that closed", async () => { + for (let when of ["held", "away", "named"] as const) { + let gate = Promise.withResolvers(); + let results: HostToolResult[] = []; + let handlers: AgentHandlers = { + async turn(context) { + let read = context.callHostTool("read_plan", {}); + await gate.promise; + for (let part = 0; part < 17; part++) context.emit(large); + let write = context.callHostTool("edit_plan", {}); + results.push(await read, await write); + }, + }; + let { server, client } = await running(handlers); + await frames(server, 1); + server.send(handover(1)); + await read(server); + if (when === "held") { + gate.resolve(); + // Held back until the cap, then sent as before the feature. + expect(summary(await frames(server, 2)), when).toEqual([ + ["part", 18], + ["host-tool-call", 19, "edit_plan"], + ]); + } + server.close(); + let resumption = (await client.resumption)!; + if (when === "held") expect(resumption.turns.size, when).toBe(0); + if (when === "away") { + gate.resolve(); + await until(() => results.length > 0); + } + let { asked, attaching } = await attachTo(server, handlers, resumption); + if (when === "named") { + expect(asked.turns, when).toEqual([{ session: "s", turn: "t" }]); + gate.resolve(); + } else expect(asked, when).toEqual({ type: "resume", sessions: kept }); + await until(() => results.length > 0); + expect(results, when).toEqual([ + LINK_CLOSED, + when === "held" ? LINK_CLOSED : { output: { error: "The turn has ended." }, isError: true }, + ]); + server.send({ + type: "resumed", + sessions: kept, + ...(when === "named" ? { turns: [{ session: "s", turn: "t", after: 1 }] } : {}), + }); + stops.push(async () => (await attaching).detach()); + await attaching; + await Bun.sleep(20); + expect(server.received.filter(message => FRAMES.has(message.type)), when).toEqual( + when === "named" + ? [{ type: "turn-end", session: "s", turn: "t", status: "aborted", seq: 2 }] + : [], + ); + } + }); +}); + describe("Agent connection client facing a faulty server", () => { /** Answers attach, then a frame no client can parse in place of the question's answer. */ function garblingServer() { diff --git a/packages/agent-link/src/client.ts b/packages/agent-link/src/client.ts index d5a5dbb43..21c08d70f 100644 --- a/packages/agent-link/src/client.ts +++ b/packages/agent-link/src/client.ts @@ -38,6 +38,7 @@ export const WIRE = { aiCatalog: "ai-catalog", catalogLaunches: "catalog-launches", accountIds: "account-ids", + turnHandover: "turn-handover", /** The header a runner sends the launch's own credential in, to Chopin's credential proxy. */ aiLaunchHeader: "x-chopin-launch", /** How often a client retries a `resume` refused with `retry`, after a `restarting` notice. */ @@ -62,14 +63,19 @@ export type TurnEnd = ClientMessageOf<"turn-end">["status"]; /** One turn the server asked the attached Planner to run. */ export type TurnContext = { readonly message: ServerMessageOf<"turn">; - /** Aborted when the server aborts the turn, destroys its session, or the link closes. */ + /** + * Aborted when the server aborts the turn, destroys its session, or the link closes. A turn the + * server handed over (`turn-handover`) runs on across the close, and is aborted only when no + * later link takes it back within the time the server gave. + */ readonly signal: AbortSignal; emit(part: StreamPart): void; /** The client's own tools this turn may call, declared before calling any. */ offerTools(names: string[]): void; /** * Runs one of Chopin's tools in the server, against the document. Settles with an - * error result once the turn is aborted, destroyed, or ended, or the link closes. + * error result once the turn is aborted, destroyed, or ended, or the link closes, except that + * a handed-over turn's calls stay open for the process that takes it back to answer. */ callHostTool(toolName: string, input: unknown): Promise; end(status: TurnEnd, message?: string): void; @@ -123,6 +129,11 @@ export type AgentOptions = { * and open Decisions however long the client is away, and `resumption` says what to hand the * next `connectAgent` as `resume`. A client that sets `false` ends everything when its link * drops, as the earlier protocol always did. + * + * It asks for `turn-handover` too: a turn the server hands over before a restart keeps running + * across the close, with its host calls open and its frames kept, until a link given the + * `resumption` takes it back or the time the server gave runs out. A turn whose kept frames pass + * 32 MiB is no longer handed over and ends with its link, as before. */ resumable?: boolean; /** What a dropped link of this client held, from its `resumption`; implies `resumable`. */ @@ -192,12 +203,13 @@ type PendingAsk = { }; /** - * The sessions a link that dropped unexpectedly held, and the questions each still waited on. It - * is only a token: give it to `connectAgent` as `resume`. + * The sessions a link that dropped unexpectedly held, the questions each still waited on, and the + * turns the server handed over. It is only a token: give it to `connectAgent` as `resume`. */ export type Resumption = { readonly sessions: ReadonlySet; readonly asks: ReadonlyMap; + readonly turns: ReadonlyMap; }; export type LinkClosed = { @@ -227,7 +239,7 @@ export type AgentClient = { readonly features: readonly string[]; /** * Settles when the link closes: with what a resumable link held when it dropped unexpectedly, - * or undefined when the link ended any other way, which ends every question it held. + * or undefined when the link ended any other way, which ends every question and turn it held. */ readonly resumption: Promise; /** Asks the document's members through Decisions. */ @@ -306,7 +318,7 @@ export function linkSocket( authorization: `Bearer ${token}`, [WIRE.featuresHeader]: [ WIRE.decisionOptionPreviews, - ...(resumable ? [WIRE.resumableSessions, WIRE.restartNotice] : []), + ...(resumable ? [WIRE.resumableSessions, WIRE.restartNotice, WIRE.turnHandover] : []), ...(catalog ? [WIRE.capabilityCatalog] : []), ...(attachments ? [WIRE.attachments] : []), ...(sessionForks ? [WIRE.sessionForks] : []), @@ -439,14 +451,119 @@ export async function fitImages( const LINK_CLOSED = "The agent connection closed."; +/** The message as one frame and its bytes, or an error when it is larger than one may be. */ +function encode(message: ClientMessage): { text: string; size: number } { + let text = JSON.stringify(message); + let size = new TextEncoder().encode(text).byteLength; + if (size > WIRE.maxMessageBytes) { + throw new Error("The message exceeds the agent connection's size limit."); + } + return { text, size }; +} + +/** + * The most a turn keeps of its frames for a process that may take it over, in bytes of their JSON. + * A turn past it can no longer be handed over: it ends with its link, as before the feature. + */ +const MAX_KEPT_BYTES = 32 * 1024 * 1024; + +/** A message of a turn: each carries `seq` on a link that accepted `turn-handover`. */ +type TurnFrame = ClientMessageOf<"tools" | "part" | "host-tool-call" | "turn-end">; + +/** One link: how it sends, and the turns it runs. */ +type Link = { + send(message: ClientMessage): boolean; + /** Sends a frame `encode` made; false when the link is no longer open. */ + sendText(text: string): boolean; + turns: Map; +}; + +/** + * With `turn-handover`: the number of a turn's last frame, and every frame after the latest + * cursor a server gave, which the process that takes the turn over may need again, with their + * bytes. `kept` is gone once those passed `MAX_KEPT_BYTES`. + */ +type Frames = { + seq: number; + kept?: Array<{ seq: number; text: string; size: number }>; + size: number; +}; + type TurnState = { + key: string; + session: string; + turn: string; controller: AbortController; ended: boolean; calls: Map void>; /** A part being made to fit a frame, which what the turn sends next waits for. */ outbox?: Promise; + /** The link its frames go to: the next one's once that link takes a handed-over turn back. */ + link: Link; + frames?: Frames; + /** From a `turn-handover` until the `resumed` that lists or leaves out the turn. */ + handover?: { + withinMs: number; + /** Started as the link closes: gives the turn up unless a later link took it back. */ + timer?: ReturnType; + /** No process took the turn back in time, or the one asked did not list it. */ + abandoned?: true; + }; }; +/** + * Sends one of a turn's frames. With `turn-handover` each is numbered and kept for a process that + * may take the turn over, and held back from the server once it handed the turn over. False when + * nothing was sent. + */ +function sendFrame(state: TurnState, message: TurnFrame): boolean { + let frames = state.frames; + if (!frames) return state.link.send(message); + let seq = frames.seq + 1; + let { text, size } = encode({ ...message, seq }); + frames.seq = seq; + if (frames.kept) { + frames.kept.push({ seq, text, size }); + frames.size += size; + if (frames.size > MAX_KEPT_BYTES) { + // Past the cap it ends with its link as before the feature: at once if that has closed. + frames.kept = undefined; + if (state.handover?.timer) { + settleCalls(state, LINK_CLOSED); + abandon(state); + } else state.handover = undefined; + } + } + return !state.handover && state.link.sendText(text); +} + +/** Keeps only the frames after `after`, which a server has not applied, and counts their bytes. */ +function keepAfter(frames: Frames, after: number): Array<{ text: string }> { + let kept = frames.kept!.filter(frame => frame.seq > after); + frames.kept = kept; + frames.size = kept.reduce((sum, frame) => sum + frame.size, 0); + return kept; +} + +function forget(state: TurnState): void { + if (state.link.turns.get(state.key) === state) state.link.turns.delete(state.key); +} + +/** Ends a turn at the server's word: it is no longer handed over, and an ended one is forgotten. */ +function stop(state: TurnState): void { + state.handover = undefined; + state.controller.abort(); + if (state.ended) forget(state); +} + +/** Gives up a handed-over turn no process took back: it is aborted, and sends nothing more. */ +function abandon(state: TurnState): void { + if (!state.handover || state.handover.abandoned) return; + clearTimeout(state.handover.timer); + state.handover.abandoned = true; + state.controller.abort(); +} + function hostFailure(message: string): HostToolResult { return { output: { error: message }, isError: true }; } @@ -491,7 +608,6 @@ export function connectAgent(options: AgentOptions): Promise { options.catalogLaunches === true, options.accountIds === true, ); - let turns = new Map(); let asks = new Map(); let sessions = new Set(); let closing = Promise.withResolvers(); @@ -504,21 +620,36 @@ export function connectAgent(options: AgentOptions): Promise { let ended = false; /** What the server said, just before closing, about when it expects to be back. */ let restartWithin: number | undefined; - let route = { send: (message: ClientMessage) => send(message) }; - - function send(message: ClientMessage): boolean { - let encoded = JSON.stringify(message); - if (new TextEncoder().encode(encoded).byteLength > WIRE.maxMessageBytes) { - throw new Error("The message exceeds the agent connection's size limit."); - } - if (socket.readyState !== WebSocket.OPEN) return false; - socket.send(encoded); - return true; - } + /** The handed-over turns this link's `resume` named, which its `resumed` takes back or not. */ + let naming: TurnState[] = []; + let link: Link = { + send: message => link.sendText(encode(message).text), + sendText(text) { + if (socket.readyState !== WebSocket.OPEN) return false; + socket.send(text); + return true; + }, + turns: new Map(), + }; + let { turns, send } = link; function runTurn(message: ServerMessageOf<"turn">): void { let key = `${message.session}/${message.turn}`; - let state: TurnState = { controller: new AbortController(), ended: false, calls: new Map() }; + // The server starts a session's next turn only once it has the last one's end, so the frames + // an ended turn kept for a handover are no longer needed. + for (let state of turns.values()) { + if (state.ended && state.session === message.session) forget(state); + } + let state: TurnState = { + key, + session: message.session, + turn: message.turn, + controller: new AbortController(), + ended: false, + calls: new Map(), + link, + ...(features.includes(WIRE.turnHandover) ? { frames: { seq: 0, kept: [], size: 0 } } : {}), + }; turns.set(key, state); state.controller.signal.addEventListener( "abort", @@ -539,17 +670,17 @@ export function connectAgent(options: AgentOptions): Promise { }; if (!state.outbox && !fitsWithoutImages(made)) { // Too large even without its images: it fails here, as it always has. - send(made); + sendFrame(state, made); return; } if (!state.outbox && bytes(made) <= WIRE.maxMessageBytes) { - send(made); + sendFrame(state, made); return; } // Made smaller off this call, so the parts after it wait their turn behind it. let outbox: Promise = (state.outbox ?? Promise.resolve()) .then(() => fitImages(made)) - .then(send) + .then(fitted => sendFrame(state, fitted)) .catch(() => {}) .finally(() => { if (state.outbox === outbox) state.outbox = undefined; @@ -557,7 +688,7 @@ export function connectAgent(options: AgentOptions): Promise { state.outbox = outbox; }, offerTools: names => - send({ + sendFrame(state, { type: "tools", session: message.session, turn: message.turn, @@ -575,7 +706,7 @@ export function connectAgent(options: AgentOptions): Promise { state.calls.set(toolCallId, result.resolve); let sent: boolean; try { - sent = send({ + sent = sendFrame(state, { type: "host-tool-call", session: message.session, turn: message.turn, @@ -587,7 +718,8 @@ export function connectAgent(options: AgentOptions): Promise { state.calls.delete(toolCallId); return Promise.reject(error); } - if (!sent) { + // A handed-over turn keeps the call for the process that takes the turn back. + if (!sent && !state.handover) { state.calls.delete(toolCallId); return Promise.resolve(hostFailure(LINK_CLOSED)); } @@ -596,10 +728,12 @@ export function connectAgent(options: AgentOptions): Promise { end: (status, text) => { if (state.ended) return; state.ended = true; - turns.delete(key); + // A turn with frames to give a process that takes it over keeps them until the server can + // no longer hand it over. + if (!state.frames) forget(state); settleCalls(state, "The turn has ended."); let finish = () => - send({ + sendFrame(state, { type: "turn-end", session: message.session, turn: message.turn, @@ -618,14 +752,23 @@ export function connectAgent(options: AgentOptions): Promise { ); } + /** + * What the resumption this link was given holds ends: its questions are cancelled and its + * handed-over turns given up. + */ + function endResumption(): void { + cancelAsks(options.resume?.asks ?? []); + for (let state of options.resume?.turns.values() ?? []) abandon(state); + } + /** * The server refused or failed the link before it was ready. What a resumption holds ends with * it, except when the refusal says Chopin could not decide (`retry`): the same resumption can - * succeed later, so its questions stay pending for the caller to try again. + * succeed later, so its questions stay pending and its turns run on for the caller to try again. */ function failAttach(retry: boolean, error: Error): void { ended = true; - if (!ready && !retry) cancelAsks(options.resume?.asks ?? []); + if (!ready && !retry) endResumption(); attaching.reject(error); } @@ -662,9 +805,20 @@ export function connectAgent(options: AgentOptions): Promise { return; case "turn": return runTurn(message); - case "abort": - turns.get(`${message.session}/${message.turn}`)?.controller.abort(); + case "abort": { + let state = turns.get(`${message.session}/${message.turn}`); + if (state) stop(state); + return; + } + case "turn-handover": { + // The server applied the turn through `after` and takes nothing more of it: the rest is + // kept for the process that takes it back, unless the turn already passed the cap. + let state = turns.get(`${message.session}/${message.turn}`); + if (!state?.frames?.kept) return; + keepAfter(state.frames, message.after); + state.handover = { withinMs: message.withinMs }; return; + } case "steer": { let running = turns.get(`${message.session}/${message.turn}`); try { @@ -723,8 +877,8 @@ export function connectAgent(options: AgentOptions): Promise { return; case "destroy": sessions.delete(message.session); - for (let [key, turn] of turns) { - if (key.startsWith(`${message.session}/`)) turn.controller.abort(); + for (let turn of turns.values()) { + if (turn.session === message.session) stop(turn); } options.handlers.destroy?.(message); return; @@ -744,13 +898,37 @@ export function connectAgent(options: AgentOptions): Promise { for (let request of requests) { let ask = held?.asks.get(request); if (!ask) continue; - ask.route = route; + ask.route = link; asks.set(request, ask); // Withdrawn while this link was being resumed, so its first cancel went nowhere. if (ask.withdrawn) send({ type: "input-cancel", request }); } } cancelAsks([...held?.asks ?? []].filter(([request]) => !asks.has(request))); + let cursors = new Map( + (message.turns ?? []).map(item => [`${item.session}/${item.turn}`, item.after]), + ); + for (let state of naming) { + let after = cursors.get(state.key); + if (after === undefined) abandon(state); + else if (state.handover?.abandoned) { + // Given up after this link named it: it ends where this process's cursor is. + send({ + type: "turn-end", + session: state.session, + turn: state.turn, + status: "aborted", + seq: after + 1, + }); + } else { + // Taken back: every frame after the server's cursor again, in order, then live. + clearTimeout(state.handover?.timer); + state.handover = undefined; + state.link = link; + turns.set(state.key, state); + for (let frame of keepAfter(state.frames!, after)) link.sendText(frame.text); + } + } for (let session of held?.sessions ?? []) { if (!returned.has(session)) options.handlers.destroy?.({ type: "destroy", session }); } @@ -781,7 +959,7 @@ export function connectAgent(options: AgentOptions): Promise { }); if (signal?.aborted) return withdrawn("The question was withdrawn before it was asked."); let answered = Promise.withResolvers>(); - let pending: PendingAsk = { session, settle: answered.resolve, route }; + let pending: PendingAsk = { session, settle: answered.resolve, route: link }; asks.set(request, pending); let sent: boolean; try { @@ -842,16 +1020,24 @@ export function connectAgent(options: AgentOptions): Promise { let closed = restartWithin === undefined ? reported : { ...reported, reconnectWithinMs: restartWithin }; + let resuming = resumable && attached && !ended && features.includes(WIRE.resumableSessions); + let handed = new Map(); for (let turn of turns.values()) { + if (resuming && turn.handover) { + // It runs on, its calls open, for the process that takes it back in time. + handed.set(turn.key, turn); + turn.handover.timer ??= setTimeout(() => abandon(turn), turn.handover.withinMs); + continue; + } settleCalls(turn, LINK_CLOSED); turn.controller.abort(); } turns.clear(); - if (resumable && attached && !ended && features.includes(WIRE.resumableSessions)) { + if (resuming) { // Unexpected: the questions stay pending for the next link to carry on. One withdrawn // meanwhile ended with its caller's wait; the next link just does not name it. cancelAsks([...asks].filter(([, ask]) => ask.withdrawn)); - resumption.resolve({ sessions: new Set(sessions), asks: new Map(asks) }); + resumption.resolve({ sessions: new Set(sessions), asks: new Map(asks), turns: handed }); } else { cancelAsks(asks); resumption.resolve(undefined); @@ -869,7 +1055,7 @@ export function connectAgent(options: AgentOptions): Promise { let closed = { code: WIRE.malformedClose, reason: "malformed-message" }; // A link that sends what cannot be read ends for good, whatever it kept. ended = true; - if (!ready) cancelAsks(options.resume?.asks ?? []); + if (!ready) endResumption(); socket.close(closed.code, closed.reason); release(closed); return; @@ -887,15 +1073,24 @@ export function connectAgent(options: AgentOptions): Promise { if (ask.withdrawn) continue; requests.set(ask.session, [...requests.get(ask.session) ?? [], request]); } + // A server that cannot take a turn back (one rolled back) has it given up here. + for (let state of held?.turns.values() ?? []) { + if (!state.handover || state.handover.abandoned) continue; + if (features.includes(WIRE.turnHandover)) naming.push(state); + else abandon(state); + } send({ type: "resume", sessions: [...held?.sessions ?? []].map(session => ({ session, requests: requests.get(session) ?? [], })), + ...(naming.length > 0 + ? { turns: naming.map(({ session, turn }) => ({ session, turn })) } + : {}), }); } else { - cancelAsks(options.resume?.asks ?? []); + endResumption(); ready = true; attaching.resolve(client); } diff --git a/packages/agent-link/src/protocol.test.ts b/packages/agent-link/src/protocol.test.ts index 741284d5e..6f3151249 100644 --- a/packages/agent-link/src/protocol.test.ts +++ b/packages/agent-link/src/protocol.test.ts @@ -292,6 +292,7 @@ describe("Agent connection messages", () => { aiCatalog: AGENT_FEATURES.aiCatalog, catalogLaunches: AGENT_FEATURES.catalogLaunches, accountIds: AGENT_FEATURES.accountIds, + turnHandover: AGENT_FEATURES.turnHandover, aiLaunchHeader: AI_LAUNCH_HEADER, restartResumeRetryMs: RESTART_RESUME_RETRY_MS, });