diff --git a/AGENTS.md b/AGENTS.md index ab788638f..7de303af6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -971,6 +971,17 @@ so merge ranges from all mounted editors before replacing a registry entry. process answers nothing after it releases the lease, and refuses nothing it was routed. Before SIGTERM's cut it keeps serving and starts no new Planner turn. Do not move a step across the release or the listener stop, and do not make readiness depend on a query. + A running remote turn whose client offered `turn-handover` is handed over at the turn-wait's + end instead of cut (`Chat.handTurnOver`, `RemoteSession.handOver`): its frames are dropped + unanswered from then on, every write it called finishes first (never stopped half way), and the + checkpoint goes into its `planner_link_holds` session (`turn`), written before the release; a + failed write makes the process end the turn itself and abort the client. The next process takes + it out of the row before showing the hold, holds it open in Chat (`busy`, from `Chat.restore`), + answers the client's `resume` only then, and applies frames after its cursor once + (`docs/agent-connection.md`). Any other turn is cut; a person's message it cut waits in line + again (`requeueCut`) for one automatic pick-up: a retry if it called only reads (`READ_TOOLS`), + a continuation from the saved Atomic session if it called a write, else nothing but Retry. + `Chat.restore` says a restart interrupted any reply it ends mid-way. `Chat.close` waits for every send already admitted before it marks the Chat closed, so a message being saved at the cut is saved and answered; a `chat:send` that reaches a closed Chat of a stopping process (`holdStarts`) is answered with nothing, never "chat is closed", because diff --git a/apps/server/src/agent/job-scope.ts b/apps/server/src/agent/job-scope.ts index 551fbbbb5..3b4d5b36e 100644 --- a/apps/server/src/agent/job-scope.ts +++ b/apps/server/src/agent/job-scope.ts @@ -40,6 +40,29 @@ export const CHILD_TOOLS: ReadonlySet = new Set([ "anchor_child", ]); +/** + * The host tools that change nothing: running one again, or having run one, has no effect anyone + * can see. Every other tool, one this list does not name included, counts as a write. + */ +export const READ_TOOLS: ReadonlySet = new Set([ + "read_plan", + "read_reference", + "list_background_jobs", + "read_background_job", + "read_implementation_graph", + "list_children", + "read_child", + "list_investigations", + "read_investigation", + "read_decision_scope", + "read_repository_file", + "list_repository_tree", + "search_repository", + "repository_history", + "list_pull_requests", + "pull_request_read", +]); + export const INVESTIGATION_READS: ReadonlySet = new Set([ "list_investigations", "read_investigation", diff --git a/apps/server/src/chat/handover.ts b/apps/server/src/chat/handover.ts new file mode 100644 index 000000000..7748e439e --- /dev/null +++ b/apps/server/src/chat/handover.ts @@ -0,0 +1,58 @@ +/** + * What Chat keeps of a Planner turn its process handed to the next one (`turn-handover`), for the + * next process to go on with it in the same entries, or to end it saying what its writes came to. + * Ids and small values only: the words of its reply are read back from the transcript, which the + * guard says is the one this was written beside. + */ + +import { createHash } from "node:crypto"; + +import type { Chat as Wire } from "@chopin/protocol"; +import type { Focus } from "./address"; + +export type HandedChat = { + turn: Wire.Turn; + writing?: string; + tooling?: string; + /** The harness's text part ids and the entries they write into. */ + messageIds: [string, string][]; + /** The calls and the entries their rows are filed in. */ + toolEntries: [string, string][]; + /** The person's message the turn answers, when one began it. */ + request?: { entryId: string; userId: string; claimantSessionId?: string; focus?: Focus }; + answering?: string; + captured: string[]; + /** The entries the turn wrote, by id. */ + entries: string[]; + /** What those entries held when the process that handed the turn over committed them (`guard`). */ + guard: string; +}; + +/** + * What a turn's entries hold, as a digest: their words, and each call's state and report count. + * A transcript that did not commit what the process handing over had shows a different one, so the + * next process never goes on from a reply with a hole in it. + */ +export function guard(entries: readonly Wire.Entry[], ids: readonly string[]): string { + let wanted = new Set(ids); + let shown = entries.filter(entry => wanted.has(entry.id)).map(entry => [ + entry.id, + entry.text, + (entry.tools ?? []).map( + tool => [tool.id, tool.name, tool.status, tool.rev ?? 0, tool.result ?? ""], + ), + ]); + return createHash("sha256").update(JSON.stringify([ids.length, shown])).digest("hex"); +} + +/** Whether a value read back from a hold is Chat's part of a handed-over turn. */ +export function handedChat(value: unknown): HandedChat | undefined { + if (typeof value !== "object" || value === null) return undefined; + let chat = value as Partial; + if ( + typeof chat.guard !== "string" || !Array.isArray(chat.entries) || !chat.turn + || typeof chat.turn.id !== "string" || !Array.isArray(chat.messageIds) + || !Array.isArray(chat.toolEntries) || !Array.isArray(chat.captured) + ) return undefined; + return chat as HandedChat; +} diff --git a/apps/server/src/chat/restart-recovery.test.ts b/apps/server/src/chat/restart-recovery.test.ts new file mode 100644 index 000000000..dae67a803 --- /dev/null +++ b/apps/server/src/chat/restart-recovery.test.ts @@ -0,0 +1,164 @@ +/** + * A turn a restart cuts off that cannot be handed to the next process (one run in this process, or + * on a client that takes no hand-over): Chat says so, and a person's message whose reply it cut off + * waits in line again, at the place it was sent, for the next process to pick up once. That process + * runs it again as at first when the cut attempt called nothing but reads, goes on from the agent's + * saved session when it called a write and its harness keeps one, and otherwise leaves the notice + * and its Retry. + */ +import { afterEach, expect, test } from "bun:test"; + +import * as Chat from "./service"; +import { + harness, + installJobCleanup, + JOB, + member, + reopened, + savedLine, + socket, + until, +} from "./job.test-fixtures"; + +import type { Socket } from "../wire"; + +installJobCleanup(); +afterEach(() => Chat.holdStarts(false)); + +const WAITS = "A restart interrupted this reply, so @ana's message waits to be answered again."; + +function speaking(handle: string): Socket { + return { data: { handle, principalId: `U_${handle}` }, send() {} } as unknown as Socket; +} + +/** + * A turn on @ana's message that has made the calls `made` (read_plan reads, refine_decision + * writes), each reported unless `reported` is false: a call made whose result has not come back. + */ +async function running(made: Array<"read_plan" | "refine_decision">, reported = true) { + let h = harness(); + await Chat.send(h.context, socket(), member("@chopin write the plan")); + await until(() => h.prompts.length === 1); + h.emit("assistant.message_delta", { messageId: "m1", deltaContent: "Writing" }); + made.forEach((toolName, at) => { + h.emit("tool.execution_start", { toolCallId: `call-${at}`, toolName }); + if (!reported) return; + h.emit("tool.execution_complete", { + toolCallId: `call-${at}`, + success: true, + result: { content: "{}" }, + }); + }); + await until(() => h.chat.entries.flatMap(entry => entry.tools ?? []).length === made.length); + return h; +} + +/** What a restart does once its turn-wait runs out: starts held, the turn cut off. */ +async function restart(h: ReturnType): Promise { + Chat.holdStarts(); + Chat.interrupt(h.chat, Chat.RESTART_INTERRUPTED); + await Chat.settled(h.chat); + await until(() => !h.chat.busy); +} + +/** The next process: it opens what was saved and starts the line, as `resumeLine` does. */ +async function nextProcess(h: ReturnType) { + Chat.holdStarts(false); + let next = await reopened(h); + Chat.resume(next.context); + return next; +} + +test("a reply that only read is run again by the next process, once, as at first, its cut attempt taken out", async () => { + let h = await running(["read_plan"]); + await restart(h); + expect(h.chat.entries.at(-1)?.text).toBe(WAITS); + // Nobody is offered a Retry of a message that waits to be answered. + expect(h.chat.entries.at(-1)?.turnFailure?.request).toBeUndefined(); + expect(await savedLine(h)).toEqual(["write the plan"]); + + let next = await nextProcess(h); + await until(() => next.prompts.length === 1); + expect(next.prompts[0]).toContain("write the plan"); + expect(next.chat.entries.map(entry => entry.text)).toEqual(["write the plan"]); + expect(next.frames).toContainEqual(expect.objectContaining({ kind: "chat:removed" })); + next.emit("assistant.message_delta", { messageId: "m2", deltaContent: "Done." }); + next.emit("session.idle"); + await until(() => !next.chat.busy); + expect(next.chat.entries.map(entry => entry.text)).toEqual(["write the plan", "Done."]); +}); + +for (let reported of [true, false]) { + test(`a reply that called a write ${reported ? "that reported" : "that had not reported"} is not run again: it is gone on with from the saved session, told what each call truly came to`, async () => { + let h = await running(["read_plan", "refine_decision"], reported); + h.context.config.harness = "atomic"; + h.context.sessionForks = { prepareTurn: () => ({}), finishTurn: () => {} }; + await restart(h); + expect(h.chat.entries.at(-1)?.text).toBe(WAITS); + + let next = await nextProcess(h); + next.context.config.harness = "atomic"; + next.context.sessionForks = { prepareTurn: () => ({}), finishTurn: () => {} }; + Chat.resume(next.context); + await until(() => next.prompts.length === 1); + let prompt = next.prompts[0]!; + expect(prompt).toContain("Chopin restarted while you were answering @ana's message"); + expect(prompt).toContain(reported ? "- read_plan: it completed" : "- read_plan: No result"); + expect(prompt).toContain( + reported + ? "- refine_decision: it completed" + : "- refine_decision: No result: a restart interrupted the turn before this call reported one. It may have been applied.", + ); + expect(prompt).toContain("Do not repeat a call that took effect"); + expect(prompt).not.toContain("write the plan"); + // What the cut attempt wrote stays: the reply goes on after it. + expect(next.chat.entries.map(entry => entry.text)).toContain("Writing"); + }); +} + +test("a reply that called a write on a harness that keeps no session is left with the notice and its Retry", async () => { + let h = await running(["refine_decision"]); + await restart(h); + expect(h.chat.entries.at(-1)?.text).toBe(Chat.RESTART_INTERRUPTED); + expect(h.chat.entries.at(-1)?.turnFailure).toMatchObject({ kind: "error" }); + expect(h.chat.entries.at(-1)?.turnFailure?.request).toBeDefined(); + expect(await savedLine(h)).toEqual([]); +}); + +test("a message is picked up once: cut again after it was, it is left with the notice and its Retry", async () => { + let h = await running(["read_plan"]); + await restart(h); + let next = await nextProcess(h); + await until(() => next.prompts.length === 1); + await restart(next); + expect(next.chat.entries.at(-1)?.text).toBe(Chat.RESTART_INTERRUPTED); + expect(await savedLine(next)).toEqual([]); +}); + +test("a message sent back to the line waits where it was sent, ahead of one sent after it", async () => { + let h = await running(["read_plan"]); + h.context.steers = undefined; + h.context.config.harness = "copilot-sdk"; + await Chat.send(h.context, speaking("bo"), member("@chopin and then this")); + await until(() => h.chat.queue.length === 1); + await restart(h); + expect(await savedLine(h)).toEqual(["write the plan", "and then this"]); +}); + +test("a reply whose write was called but has not reported is not run again, though nothing says it was applied", async () => { + let h = await running(["refine_decision"], false); + await restart(h); + expect(h.chat.entries.flatMap(entry => entry.tools ?? []).map(tool => tool.status)).toEqual([ + "failed", + ]); + expect(h.chat.entries.at(-1)?.text).toBe(Chat.RESTART_INTERRUPTED); + expect(await savedLine(h)).toEqual([]); +}); + +test("a background job a restart cuts off goes back to wait, its attempts unspent", async () => { + let h = harness(); + let job = Chat.job(h.context, JOB, "job prompt", "session"); + await until(() => h.prompts.length === 1); + await restart(h); + expect(await job).toMatchObject({ status: "preempted" }); +}); diff --git a/apps/server/src/chat/service.ts b/apps/server/src/chat/service.ts index c2f64b309..5cad39cc6 100644 --- a/apps/server/src/chat/service.ts +++ b/apps/server/src/chat/service.ts @@ -79,7 +79,14 @@ import { translateJob } from "./job-translate"; import { argsText, outputText, textOutput } from "./activity"; import { toolErrorSchema } from "@chopin/agent-link"; import { watchJobAbort } from "./job-fence"; -import { JOB_TOOLS, WRITE_TOOLS } from "../agent/job-scope"; +import { JOB_TOOLS, READ_TOOLS, WRITE_TOOLS } from "../agent/job-scope"; +import { guard, type HandedChat, handedChat } from "./handover"; +import { + forgetHandedTurn, + type HandedTurn, + type HandedTurnEnd, +} from "../harness/remote/handed-turns"; +import type { JsonValue, PlannerDecidedCall } from "../storage/model"; import type { Job, JobOutcome } from "../conversation-plan/jobs"; export type { LetGo } from "./message-queue"; export type { Announcer, NoticeInput } from "./notices"; @@ -137,6 +144,22 @@ type MemberEntry = Wire.Entry & { delivery?: Delivery; viaReaction?: true; answeredIntents?: string[]; + recovery?: Recovery; +}; + +/** + * What a restart's cut did with a person's message whose reply it cut off: sent it back to wait in + * line (`pending`) for the next process to pick up once, by running it again as at first (`retry`, + * when the cut attempt called nothing but reads) or by going on from the agent's saved session + * (`continue`, when it called a write and its harness keeps one). Kept with the transcript, so a + * message is picked up once however many restarts follow. + */ +type Recovery = { + attempts: number; + kind: "retry" | "continue"; + /** The cut's notice, which a retry takes out with the attempt. */ + notice: string; + pending?: true; }; /** How long the agent's cursor stays where it finished, after a turn ends. */ @@ -228,6 +251,11 @@ type MemberRequest = Pick & orchestrated?: string; /** Told once that the turn started (`true`), or why it was let go of before it could. */ delivered?: (started: true | LetGo) => void; + /** + * Picks up a reply a restart cut off after it called a write: what the agent is told in place of + * the message, which its saved session already holds. + */ + continued?: string; }; /** How a turn started by an instruction finished, for whoever started it. */ @@ -374,15 +402,358 @@ function occupied(chat: Chat): boolean { /** * Cuts off the turn running now because the process is restarting: says so in the Chat, then - * stops it. It is not run again, because it may already have changed the document. + * stops it. It is not run again here, because it may already have changed the document. A person's + * message whose reply it cuts off waits in line again for the next process to pick up once + * (`requeueCut`), where that is safe. */ export function interrupt(chat: Chat, notice: string): void { if (!chat.busy || !chat.turnController || chat.turnController.signal.aborted) return; chat.interruption = notice; + chat.restartCut = true; chat.stopCause = "a restart interrupted the turn"; chat.turnController.abort(); } +/** + * The process is restarting: hands the turn running now to the next process instead of cutting it + * off, where its harness can keep it running (a remote client that offered `turn-handover`) and + * nothing in this process waits on its end (`handable`). Its writes already asked for finish here, + * applied or refused, and its client is told to keep it running; Chat leaves its reply and its rows + * as they are, commits them, and returns what the next process needs to go on with it in the same + * entries. A turn held open for a client the process before handed it to is passed on as it is. + * Undefined when the turn cannot be handed over, for the caller to cut it off. + */ +export async function handOver(chat: Chat, withinMs: number): Promise { + if (chat.closed || !chat.busy) return undefined; + let waiting = chat.adopting; + if (waiting && waiting.handed.state === "waiting") { + chat.busy = false; + return waiting.chat; + } + let session = chat.agent; + let controller = chat.turnController; + let turn = chat.turn; + if (!chat.handable || !turn || !controller || !session?.handOver) return undefined; + chat.handingOver = { held: false }; + // A write a hand-over kept from the document says so, and not that the turn ended. + chat.stopCause = "Chopin restarted"; + let captured: Omit | undefined; + let held = await session.handOver(withinMs, () => { + let request = chat.activeRequest; + captured = { + turn: { ...turn }, + ...(chat.writing ? { writing: chat.writing } : {}), + ...(chat.tooling ? { tooling: chat.tooling } : {}), + messageIds: [...chat.messageIds ?? []], + toolEntries: [...chat.toolEntries ?? []], + ...(request + ? { + request: { + entryId: request.entryId, + userId: request.userId, + ...(request.claimantSessionId ? { claimantSessionId: request.claimantSessionId } : {}), + ...(request.focus ? { focus: request.focus } : {}), + }, + } + : {}), + ...(chat.answering ? { answering: chat.answering } : {}), + captured: [...chat.captured ?? []], + }; + chat.handingOver = { held: true }; + controller.abort(); + }); + if (!held || !captured) { + chat.handingOver = undefined; + chat.stopCause = undefined; + return undefined; + } + await settled(chat); + chat.handingOver = undefined; + // A transcript that could not be saved cannot be gone on with: its client is told to stop, and + // the next process says the restart ended the reply. + if (chat.closed) { + session.abandonHandOver?.(); + return undefined; + } + let entries = [ + ...new Set([ + ...captured.messageIds.map(([, id]) => id), + ...captured.toolEntries.map(([, id]) => id), + ...captured.writing ? [captured.writing] : [], + ...captured.tooling ? [captured.tooling] : [], + ]), + ]; + let half: HandedChat = { ...captured, entries, guard: guard(chat.entries, entries) }; + session.handedChat?.(half as unknown as JsonValue); + return half; +} + +/** + * Hands a document's running turn to the next process (`handOver`) and has it kept for that process + * (`keep`, which writes it into the document's link hold) while this one still serves and holds the + * writer lease. One that cannot be kept is left to nobody: this process ends it itself, saying so + * (`notice`), and tells its client to abort it. Says whether the turn was handed over or ended so; + * one that was not is for the caller to cut off. + */ +export async function handTurnOver( + context: Pick, + keep: () => Promise, + withinMs: number, + notice: string, +): Promise { + let { chat } = context; + let waiting = chat.adopting; + let session = chat.agent; + let handed = await handOver(chat, withinMs); + if (!handed) return false; + if (await keep()) return true; + if (waiting) { + waiting.handed.end("ended"); + return true; + } + await endHandedTurn(context, session ?? {}, handed, notice).catch(err => + console.error("[chat] could not end a turn that could not be handed over:", err) + ); + return true; +} + +/** + * The turn handed over could not be kept for the next process: this one ends it itself while it + * still holds the writer lease, as a cut would. Its client is told to abort it, every call left + * running says the restart cut it off, Chat says the reply was interrupted, and that is committed. + */ +async function endHandedTurn( + context: Pick, + session: Pick, + handed: HandedChat, + notice: string, +): Promise { + let { chat, server, room } = context; + session.abandonHandOver?.(); + if (chat.closed) return; + settle(chat, server, room, "a restart interrupted the turn"); + let request = handed.request; + say(chat, server, room, { + id: ulid(), + author: { kind: "system" }, + text: notice, + turnFailure: turnFailureOf({ + error: new Error(notice), + interruption: notice, + suspended: false, + ...(request ? { request: request.entryId } : {}), + ...(request?.focus ? { focus: request.focus.channelId } : {}), + }), + ts: now(), + }); + await context.persist(); +} + +/** + * Holds open the turn the process before handed over, which `restore` found as it committed it, for + * its client to take back: once it does, the turn goes on in this Chat's same entries, through this + * process's harness, and ends as any turn does. If nobody takes it back by its deadline, or its + * client comes back without it, it ends here saying so, with what each of its writes came to. + * Resolves once the turn has ended either way; nothing waiting in line starts before then. + * `repository` gives the turn the document's repository as its owner reads it, once taken back. + */ +export function adopt( + context: Room, + repository?: () => Promise, +): Promise { + let { chat, server, room } = context; + let adopting = chat.adopting; + if (!adopting) return Promise.resolve(); + if (adopting.bound) return adopting.done.promise; + adopting.bound = true; + let { handed, chat: half } = adopting; + handed.bind( + () => { + if (chat.adopting !== adopting) return; + chat.adopting = undefined; + // Each write of the turn says what it came to: its client hears it again now too. + for (let call of handed.held.decided) { + let activity = tool(chat, call.call); + if (activity?.status === "running") publish(context, decidedRow(activity, call)); + } + let request = half.request; + let member: MemberRequest | undefined = request + ? { + entryId: request.entryId, + userId: request.userId, + ...(request.focus ? { focus: request.focus } : {}), + } + : undefined; + let running = (async () => { + let found = await repository?.().catch(() => undefined); + if (found) context.repository = found; + await run( + context, + half.turn.handle, + "", + undefined, + request?.claimantSessionId, + true, + member, + [], + undefined, + adopting, + ); + })(); + chat.running = running; + void running.catch(err => console.error("[chat] a turn taken back failed:", err)); + }, + why => void endAdopting(context, adopting, why), + ); + state(chat, server, room); + return adopting.done.promise; +} + +/** + * Nobody took back the turn held open for its client: it ends here, saying why, each of its writes + * with what it came to and every other call cut off, and the line moves on. + */ +async function endAdopting(context: Room, adopting: Adopting, why: HandedTurnEnd): Promise { + let { chat, server, room } = context; + if (chat.adopting !== adopting) return; + chat.adopting = undefined; + let { handed, chat: half } = adopting; + forgetHandedTurn(handed); + if (chat.closed) return adopting.done.resolve(); + for (let call of handed.held.decided) { + let activity = tool(chat, call.call); + if (activity?.status === "running") publish(context, decidedRow(activity, call)); + } + chat.messageIds = new Map(half.messageIds); + chat.toolEntries = new Map(half.toolEntries); + settle(chat, server, room, "a restart interrupted the turn"); + chat.messageIds = undefined; + chat.toolEntries = undefined; + chat.writing = undefined; + chat.tooling = undefined; + let notice = handedEnd(why, handed.login); + let request = half.request; + say(chat, server, room, { + id: ulid(), + author: { kind: "system" }, + text: notice, + turnFailure: turnFailureOf({ + error: new Error(notice), + interruption: notice, + suspended: false, + ...(request ? { request: request.entryId } : {}), + ...(request?.focus ? { focus: request.focus.channelId } : {}), + }), + ts: now(), + }); + try { + await context.persist(); + } catch (err) { + console.error("[chat] could not save a handed-over turn nobody took back:", err); + } + adopting.done.resolve(); + // As any turn's end does: the line starts, or the Chat says nothing runs. + await drain(context, { job: false, outcome: undefined }); +} + +/** + * How a reply a restart cuts off can be picked up again by the next process: run again as at first + * when every call it made only read (`READ_TOOLS`; a tool it does not name counts as a write, and so + * does a decision it opened), whether or not a write it called was applied yet; gone on with from + * the agent's saved session when it called a write and its harness keeps one (a full Atomic + * session); otherwise not at all, and Retry is offered. + */ +function recoveryOf(context: Room): Recovery["kind"] | undefined { + let { chat } = context; + let calls = [...chat.toolEntries?.keys() ?? []].map(id => tool(chat, id)?.name); + let wrote = (chat.captured?.size ?? 0) > 0 + || calls.some(name => name === undefined || !READ_TOOLS.has(name)); + if (!wrote) return "retry"; + return context.config.harness === "atomic" && context.sessionForks ? "continue" : undefined; +} + +/** + * Sends the person's message whose reply a restart cut off back to wait in line, at the place it + * was sent, with a record that the next process picks it up once (`Recovery`): its row first, then + * its entry, which the turn's own save commits with the cut's notice (`notice`). Not when a restart + * already sent it back once, when its line is closed, or when it cannot be picked up safely. Says + * whether it did. + */ +async function requeueCut(context: Room, notice: string): Promise { + let { chat, room, server } = context; + let request = chat.activeRequest; + if (!request || chat.lineClosed) return false; + let entry = chat.entries.find(value => value.id === request.entryId) as MemberEntry | undefined; + if (!entry || entry.author.kind !== "member" || (entry.recovery?.attempts ?? 0) >= 1) { + return false; + } + let kind = recoveryOf(context); + if (!kind) return false; + let item: Queued = { + entry: entry.id, + handle: request.handle, + text: request.text, + ...(entry.references?.length ? { references: entry.references } : {}), + userId: request.userId, + ...(request.claimantSessionId ? { sessionId: request.claimantSessionId } : {}), + ...(request.focus ? { focus: request.focus } : {}), + repository: context.repository, + }; + try { + await saveRow(context, item); + } catch (err) { + console.error("[chat] could not send a message a restart cut off back to wait in line:", err); + return false; + } + entry.recovery = { attempts: (entry.recovery?.attempts ?? 0) + 1, kind, notice, pending: true }; + lineUp(context, entry, item); + chat.queue.splice(placeOf(chat.queue, item, seqOf(chat)), 0, item); + for (let changed of renumber(chat.queue, chat.entries)) announce(server, room, changed); + return true; +} + +/** + * What the next process does with a message a restart sent back to wait in line, once, as its turn + * starts: a retry takes the cut attempt and its notice out, and runs the message as at first; a + * continuation tells the agent, in place of the message, what each call of the cut attempt came to, + * as its rows say, and to finish the reply without repeating a call that took effect. + */ +function pickUp( + chat: Chat, + entry: MemberEntry, + handle: string, +): { removed: string[]; retry?: true; continued?: string } { + let recovery = entry.recovery; + if (!recovery?.pending) return { removed: [] }; + delete recovery.pending; + let at = chat.entries.indexOf(entry); + let notice = chat.entries.findIndex(value => value.id === recovery.notice); + let attempt = notice > at + ? chat.entries.slice(at + 1, notice).filter(value => value.author.kind === "agent") + : []; + if (recovery.kind === "retry") { + return notice > at + ? { removed: [...attempt.map(value => value.id), recovery.notice], retry: true } + : { removed: [] }; + } + let calls = attempt.flatMap(value => value.tools ?? []).map(call => + `- ${call.name}: ${ + call.status === "done" ? "it completed" : (call.result ?? call.status).slice(0, 300) + }` + ); + return { + removed: [], + continued: [ + `Chopin restarted while you were answering @${handle}'s message, and your reply stopped there.`, + ...(calls.length + ? ["What each call you made in that reply came to:", ...calls] + : ["You had made no calls in that reply."]), + "Finish the reply from where it stopped. Do not repeat a call that took effect; where one " + + "may have, read the document before you repeat it.", + ].join("\n"), + }; +} + /** Resolves when the turn running now, and the ones it starts after it, have ended. */ export async function settled(chat: Chat): Promise { await chat.running?.catch(() => {}); @@ -628,6 +999,30 @@ export type Chat = { lastSeq?: number; /** For a thread Chat: the top-level Chat an entry appended here is copied into, if it is. */ sharedWith?: (entry: Wire.Entry) => Chat | undefined; + /** + * Whether the running turn may be handed to the next process when this one restarts (`handOver`): + * one a person asked for, or that runs on its own, with nothing in this process waiting on its end. + */ + handable?: boolean; + /** The running turn is being handed to the next process; `held` once its client was told. */ + handingOver?: { held: boolean }; + /** The running turn was cut off because the process is restarting (`interrupt`). */ + restartCut?: true; + /** + * A turn the process before this one handed over, held open (`busy`) for its client to take back + * (`adopt`): nothing waiting in line starts beside it, and it ends honestly if nobody does. + */ + adopting?: Adopting; +}; + +/** A turn this Chat holds open for the client the process before handed it to. */ +type Adopting = { + handed: HandedTurn; + chat: HandedChat; + /** Whether `adopt` has bound it to the document's room. */ + bound?: true; + /** Settles once the turn has ended here, taken back or not. */ + done: PromiseWithResolvers; }; export function create(): Chat { @@ -647,43 +1042,115 @@ export function create(): Chat { }; } +/** What a person reads when a restart ends a reply that was running, and what Chat records. */ +export const RESTART_INTERRUPTED = + "A restart interrupted this reply, and it was not run again. Ask again if you still want it."; + +/** What Chat says of a handed-over turn nobody took back, by why, naming the machine's owner. */ +function handedEnd(why: HandedTurnEnd | undefined, login: string): string { + if (why === "deadline") { + return `Chopin restarted during this reply and @${login}'s machine didn't reconnect, so it ` + + "stopped here. Ask again if you still want it."; + } + if (why === "unnamed") { + return `Chopin restarted during this reply and @${login}'s machine came back without it, so ` + + "it stopped here. Ask again if you still want it."; + } + return RESTART_INTERRUPTED; +} + +/** + * A write's row, from what came of it as the turn that made it was handed over: what it applied, + * or that it was refused, never that it may have been applied. + */ +function decidedRow(activity: Wire.Activity, call: PlannerDecidedCall): Wire.Activity { + let answer = answerOf(call.output); + let cancelled = answer?.reason === "cancelled"; + let result = cancelled + ? "Not applied: Chopin restarted." + : outputText(toolRowOutput(call.output)); + return { + ...activity, + status: call.isError || cancelled ? "failed" : "done", + ...(result ? { result } : {}), + rev: (activity.rev ?? 0) + 1, + }; +} + +export type RestoreOptions = { + /** The last sequence the transcript gave out, so what restoring adds comes after it. */ + lastSeq?: number; + /** The document's turn the process before this one handed over, while this one holds it. */ + handed?: HandedTurn; +}; + /** * Come back with what was said before. * - * An entry that was still streaming when the process went away never finished, - * so the flag is cleared: it is as complete as it is ever going to be, and - * leaving it set would show a spinner nothing will ever stop. + * An entry that was still streaming when the process went away never finished, so the flag is + * cleared, every call left running says the restart cut it off, and Chat says the reply was + * interrupted: it is as complete as it is ever going to be. The one exception is a turn the process + * before handed over (`handed`) whose entries are just as it committed them: it is held open for its + * client to take back (`adopt`). A handed-over turn that is not says what each of its writes came to. */ export function restore( entries: Wire.Entry[], initiativePaused = false, rows: readonly ChatQueueRow[] = [], thread = "", + options: RestoreOptions = {}, ): Chat { + let { handed } = options; + let half = handed ? handedChat(handed.held.chat) : undefined; + let adopting = handed?.state === "waiting" && half !== undefined + && guard(entries, half.entries) === half.guard; + if (handed && !adopting) handed.refuse(); + let kept = new Set(adopting ? half!.entries : []); + let decided = new Map((handed?.held.decided ?? []).map(call => [call.call, call])); + let cut = false; let restored = entries.map(entry => { // A message an earlier release kept for a machine reads as an ordinary one: nothing is kept. let { - streaming: _streaming, + streaming, deliveryState: _state, deliveryFailure: _failure, ...rest } = entry as Wire.Entry & { deliveryState?: unknown; deliveryFailure?: unknown }; - return rest.tools?.some(tool => tool.status === "running") - ? { - ...rest, - tools: rest.tools.map(tool => - tool.status === "running" - ? { - ...tool, - status: "failed" as const, - result: cutOff(tool, "a restart interrupted the turn"), - rev: (tool.rev ?? 0) + 1, - } - : tool - ), - } - : rest; + if (kept.has(entry.id)) return streaming ? { ...rest, streaming } : rest; + if (streaming) cut = true; + if (!rest.tools?.some(tool => tool.status === "running")) return rest; + cut = true; + return { + ...rest, + tools: rest.tools.map(tool => { + if (tool.status !== "running") return tool; + let call = decided.get(tool.id); + return call ? decidedRow(tool, call) : { + ...tool, + status: "failed" as const, + result: cutOff(tool, "a restart interrupted the turn"), + rev: (tool.rev ?? 0) + 1, + }; + }), + } as Wire.Entry; }); + if (!adopting && handed) { + // A write the committed transcript lost still says what it came to. + let shown = new Set(restored.flatMap(entry => entry.tools?.map(tool => tool.id) ?? [])); + let lost = [...decided.values()].filter(call => !shown.has(call.call)); + if (lost.length) { + cut = true; + restored.push({ + id: ulid(), + author: { kind: "agent" }, + text: "", + ts: now(), + tools: lost.map(call => + decidedRow({ id: call.call, name: call.toolName, status: "running" }, call) + ), + }); + } + } // What waited in line waits still: its turn starts once the Chat is resumed (`resume`). An entry // that says it waits with no row does not; a row whose entry no longer waits is let go then. let line = fromEntries(restored, rows, thread); @@ -694,7 +1161,7 @@ export function restore( let { held: _held, ...rest } = entry.queued; entry.queued = { ...rest, rev: rest.rev + 1 }; } - return { + let chat: Chat = { initiativePaused, entries: restored, queue: line.queue, @@ -709,7 +1176,34 @@ export function restore( timings: new Map(), referenceCache: new Map(), backscroll: [], + ...(options.lastSeq !== undefined ? { lastSeq: options.lastSeq } : {}), }; + if (adopting) { + // Busy, so nothing in line starts beside it, until its client takes it back or it ends. + chat.adopting = { handed: handed!, chat: half!, done: Promise.withResolvers() }; + chat.busy = true; + chat.turn = { ...half!.turn }; + if (half!.writing) chat.writing = half!.writing; + if (half!.tooling) chat.tooling = half!.tooling; + } else if (cut) { + let text = handed ? handedEnd(handed.why, handed.login) : RESTART_INTERRUPTED; + let request = half?.request; + appendEntries(chat, { + id: ulid(), + author: { kind: "system" }, + text, + turnFailure: turnFailureOf({ + error: new Error(text), + interruption: text, + suspended: false, + ...(request ? { request: request.entryId } : {}), + ...(request?.focus ? { focus: request.focus.channelId } : {}), + }), + ts: now(), + }); + } + if (handed && !adopting) forgetHandedTurn(handed); + return chat; } function now(): number { @@ -824,7 +1318,13 @@ function delivery( } export function publicEntry(value: Wire.Entry): Wire.Entry { - let { delivery, viaReaction: _via, answeredIntents: _answered, ...entry } = value as MemberEntry; + let { + delivery, + viaReaction: _via, + answeredIntents: _answered, + recovery: _recovery, + ...entry + } = value as MemberEntry; return delivery?.destination === "planner" ? { ...entry, to: "planner" } : entry; } @@ -3575,12 +4075,14 @@ async function repositorySession( currentReferences: Wire.Reference[] = [], retry = false, bootstrapInPrompt = false, + /** The session of a turn the process before handed over, which this one takes back. */ + adopt?: string, ): Promise<{ session: PlannerSession; binding: ActiveOwnerBinding; bootstrap?: string }> { let retained = context.chat.retained; let reader = !!context.chat.reader; let isolated = reader || !!context.chat.job; // A background job keeps its isolated session: it never borrows or ends the retained Planner. - if (retained && !isolated) { + if (retained && !isolated && !adopt) { if (!retained.binding.signal.aborted && !retained.binding.currentToken()) { await retained.binding.waitForRebind?.(); } @@ -3663,7 +4165,7 @@ async function repositorySession( chat.referenceCache.clear(); // A reader's session has no tools and no history of its own, so it neither forks nor moves the // Planner's session tree: its reply stays untracked, for the next Planner turn to be told. - let forkSetup = !isolated + let forkSetup = !isolated && !adopt ? context.sessionForks?.prepareTurn(currentEntryId, retry) : undefined; let fullBootstrap = sessionBootstrap( @@ -3717,6 +4219,7 @@ async function repositorySession( ...(choice?.model || choice?.thinkingLevel ? { choice } : {}), harness: context.config.harness, ...(reader ? { reader: true as const } : {}), + ...(adopt ? { adopt: { sessionId: adopt } } : {}), }); if (!result.ok) { if (binding.signal.aborted) { @@ -3893,16 +4396,26 @@ async function run( member?: MemberRequest, references: Wire.Reference[] = [], jobTurn?: JobTurn, + adopted?: Adopting, ): Promise { let { chat, plan, room, server } = context; if (chat.closed) { if (jobTurn) finishJob(jobTurn, { status: "failed", reason: "The document closed." }); member?.delivered?.("closed"); + adopted?.handed.abandon(); + adopted?.done.resolve(); return; } let thread = about?.thread; - // Where this turn's own messages begin, so its last word can be found again. - let firstEntry = chat.entries.length; + // Where this turn's own messages begin, so its last word can be found again. A turn taken back + // from the process before began where its first entry is. + let firstEntry = adopted + ? Math.min( + chat.entries.length, + ...adopted.chat.entries.map(id => chat.entries.findIndex(entry => entry.id === id)) + .filter(at => at >= 0), + ) + : chat.entries.length; let failed = false; // The turn a failure notice names, kept past `finally`, which clears the live fields. let began: { request?: string; focus?: string } = {}; @@ -3928,11 +4441,16 @@ async function run( chat.steering = steered; let draft = context.draft && chat.draft?.id === context.draft ? chat.draft : undefined; // Whose own request the turn carries, before the messages given to it make it theirs too. - chat.answering = (member && !member.orchestrated) || about?.asked || draft + chat.answering = adopted + ? adopted.chat.answering + : (member && !member.orchestrated) || about?.asked || draft ? handle : about?.answered === undefined ? undefined : about.requester?.handle ?? about.answered; + // Nothing in this process waits on how it ends, so a restart may hand it to the next process. + chat.handable = !jobTurn && !reader && !draft && !about?.ended && !about?.signal + && !about?.readiness; chat.instructedFrom = member?.orchestrated; // One of Chopin's own, which orchestrated instructions stop only so many times in a row. let chopins = !jobTurn && !member && chat.answering === undefined; @@ -3969,9 +4487,9 @@ async function run( chat.savedRequest = !member && !jobTurn && !reader && about?.requester && chat.turn ? { ...about.requester, turnId: chat.turn.id, lifecycle: chat.lifecycle } : undefined; - chat.messageIds = new Map(); - chat.toolEntries = new Map(); - if (!jobTurn) chat.captured = new Set(); + chat.messageIds = new Map(adopted?.chat.messageIds); + chat.toolEntries = new Map(adopted?.chat.toolEntries); + if (!jobTurn) chat.captured = new Set(adopted?.chat.captured); if (jobTurn) { chat.job = jobTurn.job; chat.jobOutput = undefined; @@ -4004,6 +4522,7 @@ async function run( let heldBinding = held?.binding; let heldOwner = chat.owner; let heldReferences = held ? new Map(chat.referenceCache) : undefined; + let handedOver = false; try { if (about?.authorize && !await about.authorize()) { skipped = true; @@ -4021,6 +4540,7 @@ async function run( references, !!member?.retry, !jobTurn && command === undefined, + adopted?.handed.sessionId, ); opened = repositoryOpened; // Given once, with the session's first prompt. @@ -4043,6 +4563,12 @@ async function run( let turnContext: string | undefined; if (jobTurn) { prompt = jobTurn.prompt; + } else if (member?.continued) { + // Its saved session holds the message and the reply the restart cut off. + prompt = member.continued; + } else if (adopted) { + // Its client already has its prompt: the harness takes the turn it runs. + prompt = "Go on with the turn Chopin handed over."; } else if (reader) { // The backscroll and references are the writers' to take. prompt = text; @@ -4165,7 +4691,10 @@ async function run( failed = !turnController.signal.aborted || !!chat.interruption; turnController.abort(); if (jobTurn) { - outcome = chat.closed + // A restart's cut takes nothing from the job: it runs again later, its attempts unspent. + outcome = chat.restartCut && startsHeld && !chat.closed + ? PREEMPTED + : chat.closed ? { status: "failed", reason: "The document closed." } : { status: sendStarted || chat.interruption @@ -4191,10 +4720,21 @@ async function run( request: chat.activeRequest?.entryId, focus: chat.focus?.channelId, }); + let notice = ulid(); + // A person's message a restart cut off waits in line again, in the same commit as the notice, + // for the next process to pick up; one that cannot says so, and offers Retry. + let requeued = chat.restartCut && startsHeld && member && !member.orchestrated + && await requeueCut(context, notice); + if (requeued) { + let { request: _request, ...waits } = failure; + failure = waits; + } say(chat, server, room, { - id: ulid(), + id: notice, author: { kind: "system" }, - text: dropped + text: requeued + ? `A restart interrupted this reply, so @${handle}'s message waits to be answered again.` + : dropped ? "The machine's connection dropped during this reply. Its open questions are kept; " + "ask again once it has reconnected." : failure.kind === "tool" @@ -4207,6 +4747,7 @@ async function run( }); } chat.interruption = undefined; + chat.restartCut = undefined; } finally { ownerWatch?.release(); steered?.end(); @@ -4223,11 +4764,20 @@ async function run( chat.captured = undefined; chat.toolFinished = undefined; chat.toolProgress = undefined; + chat.handable = undefined; + // Handed to the next process: the turn goes on there, so its session is neither kept nor + // ended here, and nothing of its end is said or done here. + handedOver = chat.handingOver?.held === true; let kept = false; try { // A turn that failed, or whose link dropped under it, still leaves its open questions to the // session: a member can answer them, and the client may come back for them. - if (opened && !chat.closed && !isolated) kept = retain(context, opened); + if (handedOver) { + opened?.binding.release(); + if (chat.agent === opened?.session) chat.agent = undefined; + chat.owner = undefined; + kept = true; + } else if (opened && !chat.closed && !isolated) kept = retain(context, opened); if (!kept) { if (!isolated && chat.retained?.session === opened?.session) await chat.retained?.release(); else await opened?.session.destroy(); @@ -4278,16 +4828,18 @@ async function run( chat.toolEntries = undefined; chat.writing = undefined; chat.tooling = undefined; - settle( - chat, - server, - room, - chat.stopCause ?? ending ?? (failed - ? "the turn failed" - : turnController.signal.aborted - ? "the turn was stopped" - : "the turn ended"), - ); + if (!handedOver) { + settle( + chat, + server, + room, + chat.stopCause ?? ending ?? (failed + ? "the turn failed" + : turnController.signal.aborted + ? "the turn was stopped" + : "the turn ended"), + ); + } chat.stopCause = undefined; if (jobTurn) { chat.job = undefined; @@ -4298,7 +4850,7 @@ async function run( } chat.jobToolNames = undefined; chat.reader = undefined; - if (!isolated && context.sessionForks) { + if (!isolated && context.sessionForks && !handedOver) { try { await context.sessionForks.finishTurn(began.request, chat.entries.slice(firstEntry)); } catch (err) { @@ -4338,7 +4890,7 @@ async function run( * cursor the next turn had just placed. */ clearTimeout(chat.lingering); - if (!chat.closed) { + if (!chat.closed && !handedOver) { chat.lingering = setTimeout(() => { chat.lingering = undefined; Service.release(plan, server, room); @@ -4362,6 +4914,17 @@ async function run( if (persistenceError) { stopAfterPersistenceFailure(chat, server, room); } + if (adopted) { + // A run that failed before the harness took the turn leaves its client told to abort it. + adopted.handed.abandon(); + forgetHandedTurn(adopted.handed); + adopted.done.resolve(); + } + if (handedOver) { + // It runs on in the next process: nothing here waits on it, and nothing starts after it. + chat.busy = false; + return; + } // One of Chopin's own turns that ran to its end lets orchestrated instructions stop the next. if (chopins && !turnController.signal.aborted) chat.interruptions = undefined; if (jobTurn) { @@ -4506,6 +5069,9 @@ async function startQueued( continue; } leave(entry, now()); + // A message a restart sent back is picked up as its record says, once. + let picked = pickUp(chat, entry as MemberEntry, item.handle); + if (picked.removed.length) takeOut(chat, picked.removed); reline(context); try { await context.persist(); @@ -4518,6 +5084,9 @@ async function startQueued( return "closed"; } if (chat.closed) return "closed"; + if (picked.removed.length) { + broadcast(server, room, { kind: "chat:removed", ts: 0, ids: picked.removed }); + } announce(server, room, entry); // Its start is saved, so a restart does not start it again: its row can go. await forgetRow(context, item.entry); @@ -4541,6 +5110,8 @@ async function startQueued( ...(item.focus ? { focus: item.focus } : {}), ...(item.orchestrated ? { orchestrated: item.orchestrated.source } : {}), ...(item.delivered ? { delivered: item.delivered } : {}), + ...(picked.retry ? { retry: true as const } : {}), + ...(picked.continued ? { continued: picked.continued } : {}), }, item.references ?? [], ] as const; @@ -5158,6 +5729,8 @@ export function finished( let { chat } = context; let activity = tool(chat, id); if (activity?.status !== "running") return; + // A read a hand-over cut short is run again by the process that takes the turn back. + if (chat.handingOver && READ_TOOLS.has(activity.name)) return; let writes = WRITE_TOOLS.has(activity.name); if (stopped && !writes) return; if (!success || !writes) { @@ -5467,6 +6040,8 @@ export async function close(chat: Chat): Promise { chat.handoffJob = undefined; } chat.waiting = []; + // A turn held open for its client stays with its hold: the Chat that opens next holds it again. + chat.adopting?.done.resolve(); chat.turnController?.abort(); chat.referenceCache.clear(); chat.bootstrapEntries = undefined; diff --git a/apps/server/src/chat/turn-handover.test.ts b/apps/server/src/chat/turn-handover.test.ts new file mode 100644 index 000000000..906b9e149 --- /dev/null +++ b/apps/server/src/chat/turn-handover.test.ts @@ -0,0 +1,819 @@ +import { afterEach, describe, expect, it } from "bun:test"; + +import { ActiveOwnerBindings } from "../agent/active-owner"; +import { Sessions } from "../auth/session"; +import { decideReplying } from "../conversation-plan/decisions.test-fixtures"; +import { createPlannerAgent } from "../harness/agents"; +import { createRemoteAdapter } from "../harness/remote/adapter"; +import { notAttachedMessage, PlannerAttachments } from "../harness/remote/attachments"; +import { handedTurn } from "../harness/remote/handed-turns"; +import { openPlannerSession } from "../harness/session"; +import * as Plan from "../plan/service"; +import { configured } from "../testing/config"; +import { + LINK_PERSISTENCE, + linkAuth, + linkServer, + MEMBER_TOKEN, + rawLink, +} from "../testing/agent-link"; +import * as Chat from "./service"; + +import type { Server } from "bun"; +import type { HostedAuth } from "../auth/routes"; +import type { Lease, PlannerLinkHold } from "../storage/model"; +import type { Socket, SocketData } from "../wire"; + +let cleanups: Array<() => unknown> = []; +afterEach(async () => { + for (let cleanup of cleanups.splice(0).toReversed()) await cleanup(); +}); + +const REMOTE = { HARNESS: "remote", BACKGROUND_JOBS: "off" }; +const OFFER = "decision-option-previews, resumable-sessions, restart-notice, turn-handover"; +const WINDOW_MS = 10_000; + +async function until(check: () => boolean | Promise, ms = 4_000) { + for (let deadline = Date.now() + ms; Date.now() < deadline; await Bun.sleep(5)) { + if (await check()) return; + } + throw new Error("the condition did not hold in time"); +} + +type Linked = Awaited>; +type Raw = Awaited>; + +/** + * One Chopin process over the shared database: its writer lease, its agent connection server and + * holds, and the document's Chat served under `HARNESS=remote` as `main.ts` serves it. + */ +async function startProcess( + linked: Linked, + name: string, + options: { sessions?: Sessions; failHoldWrites?: () => boolean } = {}, +) { + let { storage, channel, logins } = linked; + let lease = (await storage.leases.acquire("chopin:writer", name, 60_000))! as Lease; + let auth = (options.sessions + ? { ...linked.auth, sessions: options.sessions } + : linked.auth) as typeof linked.auth; + let attachments = new PlannerAttachments(auth, 60_000, { + store: { + put: hold => + options.failHoldWrites?.() + ? Promise.reject(new Error("the database is not there")) + : storage.plannerHolds.put(lease, hold), + delete: async id => void await storage.plannerHolds.delete(lease, id), + }, + }); + await attachments.restore(await storage.plannerHolds.list()); + let server = linkServer(auth, 2_000, undefined, 60_000, undefined, undefined, { attachments }); + cleanups.push(server.stop); + let events: Array<{ kind: string; [key: string]: unknown }> = []; + let publisher = { + publish(_topic: string, message: string) { + events.push(JSON.parse(message)); + }, + } as unknown as Server; + let plan = await Plan.open(channel.id, { + storage, + lease: () => lease, + fatal: error => { + throw error; + }, + }, publisher); + let owners = new ActiveOwnerBindings(auth as unknown as HostedAuth); + let agent = createPlannerAgent(createRemoteAdapter()); + let context: Chat.Room = { + decide: decideReplying({ input: { type: "noul", noul: 0 } }), + chat: plan.chat, + plan, + room: channel.id, + server: publisher, + auth: auth as unknown as HostedAuth, + repository: { id: "R_score", owner: "octo-org", name: "score", defaultBranch: "main" }, + config: configured(REMOTE), + claimantSessionId: logins.get("rival"), + plannerNotAttached: async () => + await attachments.confirmed(channel.id) + ? undefined + : attachments.unavailable(channel.id) ?? notAttachedMessage("", "octo-org/score"), + activeOwner: () => owners.resolve(channel.id), + persist: () => Plan.persist(plan), + openPlannerSession: (binding, opening) => + openPlannerSession(binding, opening, { + githubTools: async () => ({ ok: true, value: {} }), + createSandbox: async () => + ({ + defaultWorkingDirectory: "/tmp", + run: async () => ({ exitCode: 0, stdout: "", stderr: "" }), + destroy: async () => {}, + }) as never, + registerCredential: () => () => {}, + agent, + }), + }; + let closed = false; + let close = async () => { + if (closed) return; + closed = true; + owners.revokeAll(); + await Chat.close(plan.chat); + await Plan.close(plan); + }; + cleanups.push(close); + let replies: Array<{ kind: string; rid?: string; [key: string]: unknown }> = []; + let ws = { + data: { handle: "rival", principalId: "U_rival", sessionId: logins.get("rival") }, + send(text: string) { + replies.push(JSON.parse(text)); + }, + } as unknown as Socket; + let send = async (text: string) => { + let rid = crypto.randomUUID(); + await Chat.send(context, ws, { + kind: "chat:send", + rid, + requestId: crypto.randomUUID(), + to: "planner", + text, + ts: 0, + } as never); + return replies.find(reply => reply.rid === rid); + }; + return { lease, server, attachments, plan, context, events, send, close }; +} + +type Process = Awaited>; + +/** A client that numbers its frames, as one that offered `turn-handover` does. */ +function frames(raw: Raw, session: string, turn: string, from = 1, numbered = true) { + let seq = from - 1; + let send = raw.send; + raw = { + ...raw, + send: (message: unknown) => { + let { seq: _, ...unnumbered } = message as Record; + send(numbered ? message : unnumbered); + }, + }; + return { + get seq() { + return seq; + }, + tools: () => raw.send({ type: "tools", session, turn, names: [], seq: ++seq }), + text: (id: string, delta: string) => + raw.send({ + type: "part", + session, + turn, + part: { type: "text-delta", id, delta }, + seq: ++seq, + }), + call: (toolCallId: string, toolName: string, input: unknown) => + raw.send({ + type: "host-tool-call", + session, + turn, + toolCallId, + toolName, + input: JSON.stringify(input), + seq: ++seq, + }), + /** The model's step and turn finish, as a client's harness reports them. */ + finish: () => { + let usage = { inputTokens: {}, outputTokens: {} }; + let reason = { unified: "stop" }; + raw.send({ + type: "part", + session, + turn, + part: { type: "finish-step", finishReason: reason, usage }, + seq: ++seq, + }); + raw.send({ + type: "part", + session, + turn, + part: { type: "finish", finishReason: reason, totalUsage: usage }, + seq: ++seq, + }); + }, + end: (status: "finished" | "aborted" = "finished") => + raw.send({ type: "turn-end", session, turn, status, seq: ++seq }), + /** Sends again, under `at`, what a client that kept its frames would. */ + again: (at: number, message: Record) => raw.send({ ...message, seq: at }), + }; +} + +async function result(raw: Raw, toolCallId: string): Promise { + await until(() => + raw.messages.some(message => + message.type === "host-tool-result" && message.toolCallId === toolCallId + ) + ); + let found = raw.messages.find(message => + message.type === "host-tool-result" && message.toolCallId === toolCallId + ); + raw.messages.splice(raw.messages.indexOf(found), 1); + return found; +} + +/** + * A deploy with a turn running on a client that offered `turn-handover`: the first process has + * applied a text frame, a write (applied) and a read, and the turn goes on writing on the client. + */ +async function deploy( + offer = OFFER, + firstOptions: Parameters[2] = {}, + /** Sets the first process's hooks up before the turn starts. */ + prepare?: (context: Chat.Room) => void, +) { + let linked = await linkAuth(undefined, { persistent: true }); + let first = await startProcess(linked, "first", firstOptions); + prepare?.(first.context); + let raw = await rawLink(first.server.url, MEMBER_TOKEN, offer); + raw.send({ type: "attach", version: 1, document: linked.channel.id }); + let attached = await raw.next("attached"); + raw.send({ type: "resume", sessions: [] }); + await raw.next("resumed"); + expect(await first.send("@chopin write it")).toMatchObject({ kind: "chat:send" }); + let start = await raw.next("start"); + raw.send({ type: "started", session: start.session }); + let turn = await raw.next("turn"); + let client = frames(raw, start.session, turn.turn, 1, offer.includes("turn-handover")); + client.tools(); + client.text("t1", "Writing"); + client.call("call-edit", "edit_plan", { + revision: first.plan.revision, + operations: [{ op: "replace_root", source: "# Plan\n\nApplied once.\n" }], + }); + let edited = await result(raw, "call-edit").catch(error => { + throw new Error(`${error} ${JSON.stringify(raw.messages)}`); + }); + expect(edited.isError).toBeUndefined(); + client.call("call-read", "read_plan", {}); + await result(raw, "call-read"); + await until(() => + first.context.chat.entries.some(entry => + entry.tools?.some(tool => tool.name === "read_plan" && tool.status === "done") + ) + ); + return { + linked, + first, + raw, + session: start.session, + turn: turn.turn as string, + client, + attached, + }; +} + +type Deployed = Awaited>; + +/** + * What `main.ts` does at its drain and cut, in its order: the running turn handed over and its hold + * written while still serving, then the commit, the hold written again, the release and the close. + */ +async function cut( + d: Deployed, + options: { + withinMs?: number; + windowMs?: number; + /** Changes what the cut writes, as a store that kept something else would. */ + tamper?: (rows: PlannerLinkHold[]) => void; + } = {}, +) { + return await cutProcess(d.linked, d.first, options); +} + +async function cutProcess( + linked: Linked, + first: Process, + options: Parameters[1] = {}, +) { + first.attachments.shutdown(); + let handed = await Chat.handTurnOver( + first.context, + () => first.attachments.keepHandedTurn(linked.channel.id), + options.withinMs ?? 30_000, + Chat.RESTART_INTERRUPTED, + ); + if (!handed) { + Chat.interrupt(first.context.chat, Chat.RESTART_INTERRUPTED); + await Chat.settled(first.context.chat); + } + await first.close(); + let rows = first.attachments.freeze(options.windowMs ?? WINDOW_MS); + options.tamper?.(rows); + await first.attachments.persist(rows); + for (let link of first.server.links) link.restart(options.windowMs ?? WINDOW_MS); + await linked.storage.leases.release(first.lease); + return { handed, rows }; +} + +/** The next process: it takes the lease, rebuilds the holds and opens the document. */ +async function takeOver( + d: Deployed, + options: { failHoldWrites?: () => boolean; name?: string } = {}, +) { + let { linked } = d; + let sessions = new Sessions(linked.storage, false, () => new Date(), { + persistence: LINK_PERSISTENCE, + }); + let second = await startProcess(linked, options.name ?? "second", { sessions, ...options }); + let adopted = Chat.adopt(second.context); + return { + ...second, + adopted, + /** The owner's browser sends its cookie to the new process. */ + async browserReturns() { + let cookie = linked.cookies.get("member")!; + await sessions.authenticate( + new Request(`${linked.auth.config.origin}/api/session`, { headers: { cookie } }), + ); + }, + }; +} + +async function resume( + d: Deployed, + next: Process, + turns: Array<{ session: string; turn: string }> | undefined = [{ + session: d.session, + turn: d.turn, + }], + token = MEMBER_TOKEN, +) { + let raw = await rawLink(next.server.url, token, OFFER); + raw.send({ type: "attach", version: 1, document: d.linked.channel.id }); + await raw.next("attached"); + raw.send({ + type: "resume", + sessions: [{ session: d.session, requests: [] }], + ...(turns ? { turns } : {}), + }); + return raw; +} + +function tools(context: Chat.Room) { + return context.chat.entries.flatMap(entry => entry.tools ?? []).map(tool => [ + tool.name, + tool.status, + ]); +} + +function said(context: Chat.Room) { + return context.chat.entries.map(entry => entry.text); +} + +describe("a remote turn a deploy hands over", () => { + it("is taken back by the next process, which applies each frame after the cursor once and ends it in the same reply", async () => { + let d = await deploy(); + let { handed } = await cut(d); + expect(handed).toBe(true); + let handover = await d.raw.next("turn-handover"); + expect(handover).toMatchObject({ session: d.session, turn: d.turn, after: 4 }); + // The client was never told the turn ended or was aborted. + expect(d.raw.messages.some(message => message.type === "abort")).toBe(false); + expect(await d.raw.closed).toEqual({ code: 1012, reason: "server restarting" }); + + let next = await takeOver(d); + // The turn is held open: busy, so nothing waiting in line starts beside it. + expect(next.context.chat.busy).toBe(true); + // The row no longer holds the turn: it is taken back by this process or none. + let [row] = await d.linked.storage.plannerHolds.list(); + expect(row!.sessions.some(session => session.turn)).toBe(false); + + await next.browserReturns(); + let back = await resume(d, next); + let resumed = await back.next("resumed"); + expect(resumed.turns).toEqual([{ session: d.session, turn: d.turn, after: 4 }]); + // What the write came to, again, and the read run again, whose result had no frame after it. + expect((await result(back, "call-edit")).output).toContain('"ok": true'); + expect(await result(back, "call-read")).toMatchObject({ turn: d.turn }); + + let client = frames(back, d.session, d.turn, 5); + // A frame the first process applied is dropped. + client.again(2, { + type: "part", + session: d.session, + turn: d.turn, + part: { type: "text-delta", id: "t1", delta: "Writing" }, + }); + client.text("t1", " more."); + client.finish(); + client.end(); + await next.adopted; + await next.context.chat.running; + + expect(Plan.source(next.plan).match(/Applied once\./g)).toHaveLength(1); + expect(said(next.context).filter(text => text.includes("Writing"))).toEqual(["Writing more."]); + expect(said(next.context).some(text => /restart/i.test(text))).toBe(false); + expect(tools(next.context)).toEqual([["edit_plan", "done"], ["read_plan", "done"]]); + expect(next.context.chat.busy).toBe(false); + expect(handedTurn(d.linked.channel.id)).toBeUndefined(); + }); + + it("drops what the client sends after the hand-over unanswered, never saying the turn ended", async () => { + let d = await deploy(); + d.first.attachments.shutdown(); + let handed = await Chat.handOver(d.first.context.chat, 30_000); + expect(handed).toBeDefined(); + await d.raw.next("turn-handover"); + d.client.call("call-late", "edit_plan", { revision: 0, operations: [] }); + d.client.end(); + await Bun.sleep(100); + expect(d.raw.messages.filter(message => message.type === "host-tool-result")).toEqual([]); + expect(d.raw.messages.some(message => message.type === "abort")).toBe(false); + }); + + it("waits for a write already asked for to apply before telling the client, and carries its outcome", async () => { + let d = await deploy(); + // The document's write is held, so the edit is still under way as the hand-over begins. + let gate = Promise.withResolvers(); + void Plan.exclusive(d.first.plan, () => gate.promise); + d.client.call("call-edit-2", "edit_plan", { + revision: d.first.plan.revision, + operations: [{ op: "replace_root", source: "# Plan\n\nApplied twice.\n" }], + }); + await until(() => + d.first.context.chat.entries.some(entry => + entry.tools?.some(tool => tool.id === "call-edit-2" && tool.status === "running") + ) + ); + d.first.attachments.shutdown(); + let handing = Chat.handOver(d.first.context.chat, 30_000); + await Bun.sleep(100); + expect(d.raw.messages.some(message => message.type === "turn-handover")).toBe(false); + gate.resolve(); + expect(await handing).toBeDefined(); + let handover = await d.raw.next("turn-handover"); + expect(handover.after).toBe(5); + expect(Plan.source(d.first.plan)).toContain("Applied twice."); + let [row] = await cutRows(d); + let turn = row!.sessions[0]!.turn!; + // Every write of the turn, the one applied before the hand-over began too. + expect(turn.decided.map(call => [call.toolCallId, call.isError ?? false])).toEqual([ + ["call-edit", false], + ["call-edit-2", false], + ]); + // The read had a frame after its result; nothing is owed. + expect(turn.rerun).toEqual([]); + // What it came to goes with the turn: this process sends the client nothing of it. + expect(d.raw.messages.some(message => message.toolCallId === "call-edit-2")).toBe(false); + expect(tools(d.first.context)).toContainEqual(["edit_plan", "done"]); + }); +}); + +describe("a remote turn nobody takes back", () => { + it("ends at its deadline saying the machine did not reconnect, each write with what it came to, and the line moves on", async () => { + let d = await deploy(); + await cut(d, { withinMs: 300, windowMs: 100 }); + let next = await takeOver(d); + expect(next.context.chat.busy).toBe(true); + await next.adopted; + await until(() => !next.context.chat.busy); + let text = said(next.context); + expect(text.at(-1)).toContain("@member's machine didn't reconnect, so it stopped here"); + expect(next.context.chat.entries.at(-1)?.turnFailure).toMatchObject({ kind: "error" }); + expect(tools(next.context)).toEqual([["edit_plan", "done"], ["read_plan", "done"]]); + expect(next.context.chat.entries.some(entry => entry.streaming)).toBe(false); + // Its session held nothing else, so it went with it: a client back later is given nothing. + await next.browserReturns(); + let late = await resume(d, next); + expect(await late.next("resumed")).toMatchObject({ sessions: [], turns: [] }); + }); + + it("ends at once when its client comes back without it", async () => { + let d = await deploy(); + await cut(d); + let next = await takeOver(d); + await next.browserReturns(); + let back = await resume(d, next, []); + expect(await back.next("resumed")).toMatchObject({ turns: [] }); + await next.adopted; + expect(said(next.context).at(-1)).toContain("came back without it"); + expect(next.context.chat.busy).toBe(false); + }); + + it("is not given to a resume that names another turn of the session", async () => { + let d = await deploy(); + await cut(d); + let next = await takeOver(d); + await next.browserReturns(); + let back = await resume(d, next, [{ session: d.session, turn: "another-turn" }]); + expect(await back.next("resumed")).toMatchObject({ turns: [] }); + await next.adopted; + expect(said(next.context).at(-1)).toContain("came back without it"); + }); + + it("is not taken back when the transcript is not the one the hand-over was written beside, and still says what its writes came to", async () => { + let d = await deploy(); + await cut(d, { + tamper: rows => { + let turn = rows[0]!.sessions[0]!.turn!; + turn.chat = { ...turn.chat as object, guard: "another transcript" }; + }, + }); + let next = await takeOver(d); + expect(next.context.chat.busy).toBe(false); + expect(said(next.context).at(-1)).toBe(Chat.RESTART_INTERRUPTED); + expect(tools(next.context)).toEqual([["edit_plan", "done"], ["read_plan", "done"]]); + await next.browserReturns(); + let back = await resume(d, next); + expect(await back.next("resumed")).toMatchObject({ turns: [] }); + }); + + it("is not taken back by a process that could not take it out of the hold, so no later one takes it back twice", async () => { + let d = await deploy(); + await cut(d); + let next = await takeOver(d, { failHoldWrites: () => true }); + expect(next.context.chat.busy).toBe(false); + expect(said(next.context).at(-1)).toBe(Chat.RESTART_INTERRUPTED); + expect(tools(next.context)).toEqual([["edit_plan", "done"], ["read_plan", "done"]]); + await next.browserReturns(); + let back = await resume(d, next); + expect(await back.next("resumed")).toMatchObject({ turns: [] }); + }); +}); + +describe("a remote turn whose hold cannot be written", () => { + it("is ended by the process that handed it over, saying so, and its client is told to abort it", async () => { + let failing = false; + let d = await deploy(OFFER, { failHoldWrites: () => failing }); + failing = true; + d.first.attachments.shutdown(); + let handed = await Chat.handTurnOver( + d.first.context, + () => d.first.attachments.keepHandedTurn(d.linked.channel.id), + 30_000, + Chat.RESTART_INTERRUPTED, + ); + expect(handed).toBe(true); + await d.raw.next("turn-handover"); + expect(await d.raw.next("abort")).toMatchObject({ session: d.session, turn: d.turn }); + expect(said(d.first.context).at(-1)).toBe(Chat.RESTART_INTERRUPTED); + expect(d.first.context.chat.entries.at(-1)?.turnFailure).toMatchObject({ kind: "error" }); + expect(tools(d.first.context)).toEqual([["edit_plan", "done"], ["read_plan", "done"]]); + expect(await d.linked.storage.plannerHolds.list()).toEqual([]); + }); +}); + +describe("a remote turn taken back", () => { + it("fails rather than run a host call again when a frame names one the turn already made", async () => { + let d = await deploy(); + await cut(d); + let next = await takeOver(d); + await next.browserReturns(); + let back = await resume(d, next); + await back.next("resumed"); + let client = frames(back, d.session, d.turn, 5); + client.call("call-edit", "edit_plan", { + revision: 0, + operations: [{ op: "replace_root", source: "# Plan\n\nApplied again.\n" }], + }); + await next.adopted; + await next.context.chat.running; + expect(Plan.source(next.plan)).not.toContain("Applied again."); + expect(await back.next("abort")).toMatchObject({ turn: d.turn }); + }); + + it("fails rather than leave a hole when the client skips a frame", async () => { + let d = await deploy(); + await cut(d); + let next = await takeOver(d); + await next.browserReturns(); + let back = await resume(d, next); + await back.next("resumed"); + let client = frames(back, d.session, d.turn, 6); + client.text("t1", " skipped one."); + await next.adopted; + expect(await back.next("abort")).toMatchObject({ turn: d.turn }); + expect(said(next.context).some(text => text.includes("skipped one"))).toBe(false); + }); + + it("keeps what waited in line waiting until it ends, then starts it", async () => { + let d = await deploy(); + // A message sent while the turn runs on a client that takes none mid-turn waits in line. + expect(await d.first.send("@chopin then this")).toMatchObject({ kind: "chat:send" }); + expect(d.first.context.chat.queue).toHaveLength(1); + await cut(d); + let next = await takeOver(d); + expect(next.context.chat.queue).toHaveLength(1); + await next.browserReturns(); + let back = await resume(d, next); + await back.next("resumed"); + // The machine is attached again, which starts the line (`resumeLine`): it still waits. + Chat.resume(next.context); + await Bun.sleep(100); + expect(back.messages.some(message => message.type === "start" || message.type === "turn")) + .toBe(false); + let client = frames(back, d.session, d.turn, 5); + client.text("t1", " done."); + client.finish(); + client.end(); + await next.adopted; + // The waiting message starts once the turn handed over has ended. + await back.next("start"); + }); + + it("is written back by a process that stops before its client returns, and taken back by the next", async () => { + let d = await deploy(); + await cut(d); + let second = await takeOver(d); + await cutProcess(d.linked, second); + let [row] = await d.linked.storage.plannerHolds.list(); + let turn = row!.sessions[0]!.turn!; + expect(turn).toMatchObject({ id: d.turn, after: 4 }); + expect(turn.decided.map(call => call.toolCallId)).toEqual(["call-edit"]); + let third = await takeOver(d, { name: "third" }); + await third.browserReturns(); + let back = await resume(d, third); + expect((await back.next("resumed")).turns).toEqual([ + { session: d.session, turn: d.turn, after: 4 }, + ]); + }); + + it("is handed over again with every write it made, those of the process before included", async () => { + let d = await deploy(); + await cut(d); + let second = await takeOver(d); + await second.browserReturns(); + let back = await resume(d, second); + await back.next("resumed"); + let client = frames(back, d.session, d.turn, 5); + client.call("call-edit-3", "edit_plan", { + revision: second.plan.revision, + operations: [{ op: "replace_root", source: "# Plan\n\nApplied in the second.\n" }], + }); + await result(back, "call-edit-3"); + await cutProcess(d.linked, second); + let handover = await back.next("turn-handover"); + expect(handover.after).toBe(5); + let [row] = await d.linked.storage.plannerHolds.list(); + expect(row!.sessions[0]!.turn!.decided.map(call => call.toolCallId)).toEqual([ + "call-edit", + "call-edit-3", + ]); + let third = await takeOver(d, { name: "third" }); + await third.browserReturns(); + let again = await resume(d, third); + expect((await again.next("resumed")).turns).toEqual([ + { session: d.session, turn: d.turn, after: 5 }, + ]); + expect((await result(again, "call-edit")).output).toContain('"ok": true'); + expect((await result(again, "call-edit-3")).output).toContain('"ok": true'); + expect(Plan.source(third.plan).match(/Applied in the second\./g)).toHaveLength(1); + }); +}); + +describe("a process that is stopping", () => { + it("answers no resume that names a turn it holds, so the client keeps it for the next process", async () => { + let d = await deploy(); + await cut(d); + let next = await takeOver(d); + await next.browserReturns(); + next.attachments.shutdown(); + let back = await resume(d, next); + await Bun.sleep(200); + expect(back.messages.some(message => message.type === "resumed")).toBe(false); + }); +}); + +describe("a client without turn-handover", () => { + it("has its turn cut off at a restart with a notice, as before, and is never sent a hand-over", async () => { + let d = await deploy("decision-option-previews, resumable-sessions, restart-notice"); + expect(d.attached.features).not.toContain("turn-handover"); + let { handed } = await cut(d); + expect(handed).toBe(false); + expect(d.raw.messages.some(message => message.type === "turn-handover")).toBe(false); + expect(said(d.first.context).at(-1)).toBe(Chat.RESTART_INTERRUPTED); + let [row] = await d.linked.storage.plannerHolds.list(); + expect(row?.sessions.some(session => session.turn) ?? false).toBe(false); + }); + + it("is not offered turn-handover without resumable-sessions", async () => { + let linked = await linkAuth(); + let server = linkServer(linked.auth); + cleanups.push(server.stop); + let raw = await rawLink(server.url, MEMBER_TOKEN, "turn-handover, restart-notice"); + raw.send({ type: "attach", version: 1, document: linked.channel.id }); + expect((await raw.next("attached")).features).toEqual(["restart-notice"]); + }); +}); + +describe("a turn's frames", () => { + it("must be numbered on a link that offered turn-handover, and must not be on one that did not", async () => { + for ( + let [offer, frame] of [ + [OFFER, { names: [] }], + ["resumable-sessions", { names: [], seq: 1 }], + ] as const + ) { + let linked = await linkAuth(undefined, { persistent: true }); + let first = await startProcess(linked, "first"); + let raw = await rawLink(first.server.url, MEMBER_TOKEN, offer); + raw.send({ type: "attach", version: 1, document: linked.channel.id }); + await raw.next("attached"); + raw.send({ type: "resume", sessions: [] }); + await raw.next("resumed"); + await first.send("@chopin write it"); + let start = await raw.next("start"); + raw.send({ type: "started", session: start.session }); + let turn = await raw.next("turn"); + raw.send({ type: "tools", session: start.session, turn: turn.turn, ...frame }); + expect(await raw.next("error")).toMatchObject({ code: "protocol" }); + } + }); +}); + +describe("a transcript a restart left mid-reply", () => { + it("says the restart interrupted the reply, with every call it cut off, when nothing takes the turn back", () => { + let chat = Chat.restore([ + { id: "m1", author: { kind: "member", handle: "ana" }, text: "@chopin write it", ts: 1 }, + { + id: "a1", + author: { kind: "agent" }, + text: "Writing", + ts: 2, + streaming: true, + tools: [{ id: "c1", name: "edit_plan", status: "running", args: "{}" }], + }, + ] as never); + expect(chat.entries.map(entry => entry.text)).toEqual([ + "@chopin write it", + "Writing", + Chat.RESTART_INTERRUPTED, + ]); + expect(chat.entries[1]!.streaming).toBeUndefined(); + expect(chat.entries[1]!.tools![0]).toMatchObject({ + status: "failed", + result: + "No result: a restart interrupted the turn before this call reported one. It may have " + + "been applied.", + }); + expect(chat.entries[2]!.turnFailure).toMatchObject({ kind: "error" }); + }); + + it("says nothing when no reply was left mid-way", () => { + let chat = Chat.restore([ + { id: "a1", author: { kind: "agent" }, text: "Done.", ts: 2 }, + ] as never); + expect(chat.entries.map(entry => entry.text)).toEqual(["Done."]); + }); +}); + +describe("a write a hand-over finds under way", () => { + it("is let finish, never stopped half way, and what it truly came to goes with the turn", async () => { + let gate = Promise.withResolvers(); + let signals: AbortSignal[] = []; + let d = await deploy(OFFER, {}, context => { + context.orchestrate = async request => { + if (request.signal) signals.push(request.signal); + await gate.promise; + return { ok: true, documents: [] } as never; + }; + }); + d.client.call("call-orchestrate", "orchestrate", { operation: "list" }); + await until(() => signals.length === 1); + d.first.attachments.shutdown(); + let handing = Chat.handOver(d.first.context.chat, 30_000); + await Bun.sleep(100); + expect(signals[0]!.aborted).toBe(false); + expect(d.raw.messages.some(message => message.type === "turn-handover")).toBe(false); + gate.resolve(); + expect(await handing).toBeDefined(); + await d.raw.next("turn-handover"); + let [row] = await cutRows(d); + let decided = row!.sessions[0]!.turn!.decided.find(call => call.toolName === "orchestrate"); + expect(decided?.toolCallId).toBe("call-orchestrate"); + expect(decided?.isError).toBeUndefined(); + expect(JSON.parse(decided!.output as string)).toEqual({ ok: true, documents: [] }); + }); +}); + +describe("a remote turn Chat cannot go on with", () => { + it("is aborted on its client when its run fails before this process's harness takes it", async () => { + let d = await deploy(); + await cut(d); + let next = await takeOver(d); + next.context.activeOwner = async () => { + throw new Error("the owner's login is gone"); + }; + await next.browserReturns(); + let back = await resume(d, next); + await back.next("resumed"); + expect(await back.next("abort")).toMatchObject({ session: d.session, turn: d.turn }); + await next.adopted; + await until(() => !next.context.chat.busy); + expect(next.context.chat.entries.at(-1)?.turnFailure).toBeDefined(); + }); +}); + +/** 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); + return await d.linked.storage.plannerHolds.list(); +} diff --git a/apps/server/src/handover/turns.ts b/apps/server/src/handover/turns.ts index 7ff3bd3e1..92ac306a2 100644 --- a/apps/server/src/handover/turns.ts +++ b/apps/server/src/handover/turns.ts @@ -1,7 +1,8 @@ /** * What a stopping process does about the turns running now: it keeps serving, gives them until a - * bound to finish, and cuts off those still running with a notice. A turn cut off is never run - * again, because it may already have changed the document. + * bound to finish, and then hands each one it can to the next process, which takes it back (a remote + * client that offered `turn-handover`), and cuts off the rest with a notice. A turn cut off is never + * run again here, because it may already have changed the document. */ export type Turns = { /** The chats with a turn running now. */ @@ -10,8 +11,13 @@ export type Turns = { interrupt(chat: Chat): void; /** Resolves when the turn has ended. */ settled(chat: Chat): Promise; - /** Called once, before the first turn is cut off. */ + /** Called once, before the first turn is handed over or cut off. */ beforeInterrupt(): void; + /** + * Hands the running turn to the next process instead of cutting it off, and says whether it did; + * one it did not is cut off. + */ + handOver?(chat: Chat): Promise; }; export type TurnWait = { @@ -30,14 +36,19 @@ export async function finishTurns(turns: Turns, wait: TurnWait): Pro let running = turns.busy(); if (running.length === 0) return 0; turns.beforeInterrupt(); - for (let chat of running) turns.interrupt(chat); + let handed = await Promise.all( + running.map(chat => turns.handOver?.(chat).catch(() => false) ?? false), + ); + let cut = running.filter((_, at) => !handed[at]); + if (cut.length === 0) return 0; + for (let chat of cut) turns.interrupt(chat); let timer: ReturnType | undefined; await Promise.race([ - Promise.allSettled(running.map(chat => turns.settled(chat))), + Promise.allSettled(cut.map(chat => turns.settled(chat))), new Promise(resolve => { timer = setTimeout(resolve, wait.settleMs ?? 2_000); }), ]); clearTimeout(timer); - return running.length; + return cut.length; } diff --git a/apps/server/src/harness/remote/attachments.ts b/apps/server/src/harness/remote/attachments.ts index 527c247f7..b7a95dc83 100644 --- a/apps/server/src/harness/remote/attachments.ts +++ b/apps/server/src/harness/remote/attachments.ts @@ -22,6 +22,7 @@ import { LINK_CLOSE } from "@chopin/agent-link"; import { GitHubError } from "../../github/client"; +import { forgetHandedTurn, HandedTurn, handedTurn, registerHandedTurn } from "./handed-turns"; import { AgentLink, type RejoinHost } from "./link"; import { attachLink } from "./registry"; @@ -30,7 +31,7 @@ import type { Admission } from "../../auth/admission"; import type { AuthConfig } from "../../auth/config"; import type { AuthenticatedSession, Sessions } from "../../auth/session"; import type { GitHub } from "../../github/client"; -import type { PlannerLinkHold, StoredPlannerLinkHold } from "../../storage/model"; +import type { PlannerHeldTurn, PlannerLinkHold, StoredPlannerLinkHold } from "../../storage/model"; import type { StorageAdapter } from "../../storage/port"; export type AttachmentAuth = { @@ -231,6 +232,10 @@ export class PlannerAttachments { #rows = new Map>(); /** The cut has taken the holds' state: nothing more is written, and nothing is announced. */ #frozen = false; + /** The server is going down: a link that attaches from now on withdraws nothing either. */ + #stopping = false; + /** The turns handed over with the holds this process rebuilt, while it holds them. */ + #handedTurns = new Set(); constructor(auth: AttachmentAuth, graceMs: number, options: PlannerAttachmentOptions = {}) { this.#auth = auth; @@ -588,39 +593,71 @@ export class PlannerAttachments { for (let { aiLaunchId } of row.sessions) { if (aiLaunchId) this.#options.endAi?.(aiLaunchId); } + // A turn handed over with it is not taken back; Chat still says what its writes came to. + for (let session of row.sessions) { + if (session.turn) this.#handed(row, session.id, session.turn, false, now); + } this.#forgetRow(hold); continue; } - // A session is kept only for a question its client waits on or an answer it has not - // acknowledged. An earlier release also kept one for a workflow run, which nothing keeps now. + // A session is kept only for a question its client waits on, an answer it has not + // acknowledged, or a turn its client was told to keep running (`turn-handover`). An earlier + // release also kept one for a workflow run, which nothing keeps now. let sessions = row.sessions.filter(session => - session.waiting.length > 0 || session.owed.length > 0 + session.waiting.length > 0 || session.owed.length > 0 || session.turn !== undefined ); for (let { aiLaunchId } of row.sessions.filter(session => !sessions.includes(session))) { if (aiLaunchId) this.#options.endAi?.(aiLaunchId); } - if (sessions.length > 0) { - let open = this.#options.openDocument; - hold.parked = AgentLink.rebuilt(row.channelId, sessions, { - lapse: () => this.#lapsed(hold, hold.parked!), - ...(open ? { open: () => open(row.channelId) } : {}), - ...(this.#options.endAi ? { endAi: this.#options.endAi } : {}), - ...(this.#options.aiHeld ? { aiHeld: this.#options.aiHeld } : {}), - }); - } let length = row.handoverUntil && this.#auth.clock().getTime() - row.suspendedAt.getTime() <= HOLD_STALE_MS ? row.handoverUntil.getTime() - row.suspendedAt.getTime() : undefined; - // Before the hold is shown, so a crash from here on leaves a row with no window. A write - // that fails leaves the row as it was, and the window the client was told is still given. - if (length !== undefined && this.#options.store) { + let turns = sessions.filter(session => session.turn !== undefined); + // Before the hold is shown, so a crash from here on leaves a row with no window, and with no + // turn to take back: a turn handed over is taken back once, by this process, or by none. A + // write that fails leaves the row as it was: the window the client was told is still given, + // but a turn whose row still holds it is only ended, never taken back. + let consumed = false; + if ((length !== undefined || turns.length > 0) && this.#options.store) { try { - await this.#options.store.put({ ...row, sessions, handoverUntil: undefined }); + await this.#options.store.put({ + ...row, + sessions: sessions.map(({ turn: _turn, ...session }) => session), + handoverUntil: undefined, + }); + consumed = true; } catch (error) { console.error("[agent] keeping a remote Planner's link state failed:", error); } } + // The turn waits for its client at least as long as the window and as long as the client was + // told to keep it, counted from here. + let handed = new Map(turns.map(session => [ + session.id, + this.#handed( + row, + session.id, + session.turn!, + consumed, + new Date( + this.#auth.clock().getTime() + Math.max(length ?? 0, session.turn!.withinMs), + ), + ), + ])); + if (sessions.length > 0) { + let open = this.#options.openDocument; + hold.parked = AgentLink.rebuilt(row.channelId, sessions, { + lapse: () => this.#lapsed(hold, hold.parked!), + ...(open ? { open: () => open(row.channelId) } : {}), + ...(this.#options.endAi ? { endAi: this.#options.endAi } : {}), + ...(this.#options.aiHeld ? { aiHeld: this.#options.aiHeld } : {}), + handed: id => { + let turn = handed.get(id); + return turn?.state === "waiting" ? turn : undefined; + }, + }); + } this.#holds.set(row.channelId, hold); // The window is the length the cut gave, counted from here: the cut could not know when // its lease would be released, and this is after it was, however long the steps between @@ -638,6 +675,37 @@ export class PlannerAttachments { } } + /** + * A turn the process before handed over with a hold this process rebuilt: registered for Chat to + * hold open and its client to take back, if it may be (`adoptable`), until `until`. + */ + #handed( + row: StoredPlannerLinkHold, + sessionId: string, + held: PlannerHeldTurn, + adoptable: boolean, + until: Date, + ): HandedTurn { + let turn = new HandedTurn({ + channelId: row.channelId, + sessionId, + held, + userId: row.userId, + ...(row.machineId !== undefined ? { machineId: row.machineId } : {}), + login: row.login, + adoptable, + until, + }); + // One turn per document is taken back; another, which no Planner of this release hands over, + // only ends. + if (handedTurn(row.channelId)?.state === "waiting") turn.end("ended"); + else { + registerHandedTurn(turn); + this.#handedTurns.add(turn); + } + return turn; + } + /** * The room of `channelId` is open: the questions a rebuilt hold's client left open are waited * on again, for it, through `host`. @@ -717,8 +785,49 @@ export class PlannerAttachments { })); } + /** + * Writes the document's hold now, while this process still serves and holds the writer lease, + * with the turn its Planner has just handed over (`turn-handover`): the next process can take the + * turn back only from this row, so the lease is never released before it is written. The row has + * no hand-over window, which only the cut gives (a process that crashes before its cut leaves the + * link's hold disconnected); the cut writes it again. Says whether it was written. + */ + async keepHandedTurn(channelId: string): Promise { + let store = this.#options.store; + let hold = this.#holds.get(channelId); + let source = hold?.link ?? hold?.parked; + if (!store || !hold || !source) return false; + let sessions = source.snapshot(); + if (!sessions.some(session => session.turn)) return false; + let { ownerSessionId, machineId, machine } = hold; + let row: PlannerLinkHold = { + channelId, + userId: hold.userId, + login: hold.login, + ...(machineId === undefined ? { ownerSessionId } : { machineId, machine: machine! }), + generation: hold.generation, + sessions, + suspendedAt: this.#auth.clock(), + }; + let written = (this.#rows.get(channelId) ?? Promise.resolve()).then(() => store.put(row)); + let settled = written.then(() => {}, () => {}); + this.#rows.set(channelId, settled); + void settled.then(() => { + if (this.#rows.get(channelId) === settled) this.#rows.delete(channelId); + }); + try { + await written; + hold.persisted = true; + return true; + } catch (error) { + console.error("[agent] keeping a handed-over Planner turn failed:", error); + return false; + } + } + /** The server is going down: no link withdraws a question it asked on its way out. */ shutdown(): void { + this.#stopping = true; for (let hold of this.#holds.values()) { hold.link?.shutdown(); hold.parked?.shutdown(); @@ -728,6 +837,9 @@ export class PlannerAttachments { /** Stops every grace timer. Ownership stays in storage, which startup clears. */ close(): void { this.#frozen = true; + // What waits to be taken back went with the holds the cut wrote: this process holds none. + for (let turn of this.#handedTurns) forgetHandedTurn(turn); + this.#handedTurns.clear(); for (let hold of this.#holds.values()) { clearTimeout(hold.timer); clearTimeout(hold.handoverTimer); @@ -974,6 +1086,9 @@ export class PlannerAttachments { hold.restored = false; this.#forgetRow(hold); hold.link = link; + // A link that attaches as the server goes down leaves its questions open, as the others do, + // and answers no resume. + if (this.#stopping) link.shutdown(); hold.forget = attachLink(hold.channelId, link); this.#changed(hold.channelId); return { diff --git a/apps/server/src/harness/remote/endpoint.ts b/apps/server/src/harness/remote/endpoint.ts index 079253155..bf5b5b404 100644 --- a/apps/server/src/harness/remote/endpoint.ts +++ b/apps/server/src/harness/remote/endpoint.ts @@ -166,11 +166,16 @@ function offersSubprotocol(request: Request): boolean { const SUPPORTED_FEATURES = new Set(Object.values(AGENT_FEATURES)); -/** The supported features the request's `Chopin-Agent-Features` header names, if it has one. */ +/** + * The supported features the request's `Chopin-Agent-Features` header names, if it has one. A turn + * is handed over only to a client whose sessions outlive its link, so `turn-handover` is named only + * beside `resumable-sessions`. + */ function requestedFeatures(request: Request): { features?: string[] } { let header = request.headers.get(AGENT_FEATURES_HEADER); if (header === null) return {}; let named = new Set(header.split(",").map(feature => feature.trim())); + if (!named.has(AGENT_FEATURES.resumableSessions)) named.delete(AGENT_FEATURES.turnHandover); return { features: [...SUPPORTED_FEATURES].filter(feature => named.has(feature)) }; } @@ -392,6 +397,7 @@ export function agentLink( revalidateEveryMs: hooks.revalidateEveryMs, ...(hooks.aiRetryMs === undefined ? {} : { aiRetryMs: hooks.aiRetryMs }), features, + identity: { userId, ...(machineId ? { machineId } : {}) }, catalogChanged: () => { if (channelId) hooks.catalogChanged?.(channelId, { userId, catalog: link.catalog }); }, diff --git a/apps/server/src/harness/remote/handed-turns.ts b/apps/server/src/harness/remote/handed-turns.ts new file mode 100644 index 000000000..98fcd1651 --- /dev/null +++ b/apps/server/src/harness/remote/handed-turns.ts @@ -0,0 +1,159 @@ +/** + * Turns the process before this one handed over (`turn-handover`), as this process rebuilt them + * from their link holds. Each is taken back at most once, when its client resumes naming it, or + * ended honestly: when its client comes back without it, when its session ends, or when nobody + * took it back by its deadline. + */ + +import type { PlannerHeldTurn } from "../../storage/model"; + +/** Why a handed-over turn ended without being taken back. */ +export type HandedTurnEnd = + /** No client took it back by its deadline. */ + | "deadline" + /** Its client came back without it. */ + | "unnamed" + /** Its session ended, or the turn could not be taken back. */ + | "ended"; + +export type HandedTurnInit = { + channelId: string; + sessionId: string; + held: PlannerHeldTurn; + /** The hold it came from: only that account, on that machine, may take it back. */ + userId: string; + machineId?: string; + login: string; + /** + * Whether it may be taken back: the hold's row was rewritten without it, so no later process can + * take it back a second time. One that may not is only ended, saying what its writes came to. + */ + adoptable: boolean; + /** When it ends if nobody took it back. */ + until: Date; +}; + +export class HandedTurn { + readonly channelId: string; + readonly sessionId: string; + readonly held: PlannerHeldTurn; + readonly userId: string; + readonly machineId: string | undefined; + readonly login: string; + readonly adoptable: boolean; + readonly until: Date; + state: "waiting" | "adopted" | "ended" = "waiting"; + /** Why it ended, once it has without being taken back. */ + why: HandedTurnEnd | undefined; + /** + * Settles once the document's Chat has opened with it: `true` when Chat holds the turn open for + * its client, so a `resume` naming it may be answered, `false` when Chat ended it. + */ + readonly opened = Promise.withResolvers(); + #adopted: (() => void) | undefined; + #ended: ((why: HandedTurnEnd) => void) | undefined; + /** What else hears that it ended: its session's link, which lets a session kept only for it go. */ + #done: (() => void)[] = []; + /** How its session lets go of it once taken back, if Chat cannot go on with it. */ + #abandon: (() => void) | undefined; + #timer: ReturnType | undefined; + + constructor(init: HandedTurnInit) { + this.channelId = init.channelId; + this.sessionId = init.sessionId; + this.held = init.held; + this.userId = init.userId; + this.machineId = init.machineId; + this.login = init.login; + this.adoptable = init.adoptable; + this.until = init.until; + if (!init.adoptable) { + this.state = "ended"; + this.why = "ended"; + this.opened.resolve(false); + return; + } + this.#timer = setTimeout( + () => this.end("deadline"), + Math.max(0, init.until.getTime() - Date.now()), + ); + this.#timer.unref?.(); + } + + /** Chat holds the turn open: it hears when the client takes it back, or that it ended. */ + bind(adopted: () => void, ended: (why: HandedTurnEnd) => void): void { + this.#adopted = adopted; + this.#ended = ended; + if (this.state === "waiting") this.opened.resolve(true); + } + + /** Chat could not hold the turn open: it ended it itself. */ + refuse(): void { + this.end("ended"); + } + + /** Runs `then` once the turn has ended without being taken back. */ + whenEnded(then: () => void): void { + if (this.state === "ended") then(); + else if (this.state === "waiting") this.#done.push(then); + } + + /** Runs `then` if Chat cannot go on with the turn its client took back (`abandon`). */ + whenAbandoned(then: () => void): void { + this.#abandon = then; + } + + /** + * Chat is done with the turn it went on with: its session lets go of it if this process's harness + * never took it, telling its client to abort it. + */ + abandon(): void { + let abandon = this.#abandon; + this.#abandon = undefined; + abandon?.(); + } + + /** The client took the turn back. Says whether it could: it was still waiting. */ + adopt(): boolean { + if (this.state !== "waiting") return false; + this.state = "adopted"; + this.#done = []; + clearTimeout(this.#timer); + this.#adopted?.(); + return true; + } + + /** The turn ends without its client taking it back; Chat says so. */ + end(why: HandedTurnEnd): void { + if (this.state !== "waiting") return; + this.state = "ended"; + this.why = why; + clearTimeout(this.#timer); + this.opened.resolve(false); + this.#ended?.(why); + for (let then of this.#done.splice(0)) then(); + } +} + +let turns = new Map(); + +/** Records a turn this process rebuilt, replacing any earlier one of its document. */ +export function registerHandedTurn(turn: HandedTurn): void { + turns.get(turn.channelId)?.end("ended"); + turns.set(turn.channelId, turn); +} + +/** The handed-over turn of a document, while this process still holds it. */ +export function handedTurn(channelId: string): HandedTurn | undefined { + return turns.get(channelId); +} + +/** Forgets a document's handed-over turn once Chat is done with it. */ +export function forgetHandedTurn(turn: HandedTurn): void { + if (turns.get(turn.channelId) === turn) turns.delete(turn.channelId); +} + +/** Every document with a handed-over turn this process still holds. */ +export function handedTurnChannels(): string[] { + return [...turns.keys()]; +} diff --git a/apps/server/src/harness/remote/link.ts b/apps/server/src/harness/remote/link.ts index 8a3de42ac..cbbf36e82 100644 --- a/apps/server/src/harness/remote/link.ts +++ b/apps/server/src/harness/remote/link.ts @@ -16,6 +16,8 @@ import { } from "@chopin/agent-link"; import { AI_RENEW_BEFORE_MS, AiLaunchRefused, copilotUnanswered } from "../../ai/launches"; import { AI_ACCOUNT_UNCHECKED_SESSION, NO_AI_ACCOUNT_SESSION } from "../../ai/account-check"; +import { READ_TOOLS } from "../../agent/job-scope"; +import { EDIT_SETTLE_MS } from "../../agent/document-ops"; import type { HarnessV1PromptControl, @@ -35,11 +37,18 @@ import type { ServerMessageOf, TurnAttachment, } from "@chopin/agent-link"; -import type { JsonValue, PlannerHeldSession } from "../../storage/model"; +import type { + JsonValue, + PlannerDecidedCall, + PlannerHeldSession, + PlannerHeldTurn, + PlannerOwedRead, +} from "../../storage/model"; import { withdrawnValue } from "../atomic/human-input"; import { DETACH_WAITER } from "../../questions/service-ask"; import type { AskedInput, HumanInput, HumanInputStatus, InputMethod } from "../atomic/human-input"; import type { PlannerTurn } from "../turn-level"; +import type { HandedTurn } from "./handed-turns"; import type { RemotePlanner } from "./registry"; const OPERATION_TIMEOUT_MS = 10_000; @@ -157,6 +166,11 @@ export type LinkOptions = { * withheld from it because Copilot couldn't be asked: `AI_RETRY_MS` unless a test says. */ aiRetryMs?: number; + /** + * Who the link acts for: only that account's client, through the same machine, takes back a turn + * the process before handed over. + */ + identity?: { userId: string; machineId?: string }; }; const REFUSAL_CLOSE: Record = { @@ -338,6 +352,25 @@ type Turn = { hostTools?: AbortController; grace?: ReturnType; listeners: (() => void)[]; + /** With `turn-handover`: the `seq` of the last frame applied. */ + cursor: number; + /** How many frames have been applied, so a read can tell whether any came after its result. */ + applied: number; + /** + * Being handed to the next process, or handed: its frames are neither applied nor answered, and + * nothing of it reaches its client from here. + */ + suspended?: true; + /** Its hand-over failed and it is being cut: its client's `turn-end` still ends it. */ + cutting?: true; + /** Every write host call it made and what came of it, those an earlier process decided included. */ + decided: PlannerDecidedCall[]; + /** Its read host calls, by the id the harness knows them by, with how many frames came before each was answered. */ + reads: Map; + /** Taken back from the process before, until a turn of this process's harness takes it: what arrived meanwhile. */ + waiting?: TurnMessage[]; + /** Taken back from the process before: the reads to run again once the harness takes it. */ + rerun?: PlannerOwedRead[]; }; type TurnMessage = ClientMessageOf<"tools" | "part" | "host-tool-call" | "turn-end">; @@ -442,7 +475,7 @@ function rebuiltInput( /** One Planner session whose turns run in the attached client. */ class RemoteSession { readonly id: string; - readonly planner: RemotePlanner; + planner: RemotePlanner; #port: Port; #started = Promise.withResolvers(); /** Whether the client has acknowledged `start`: only a started session can be resumed. */ @@ -469,15 +502,31 @@ class RemoteSession { #aiFrozen = false; /** Launches a renewal replaced, still held until their grace ends, with the timer that ends them. */ #replaced = new Map>(); + /** + * The turn this process handed to the next one, and what the next needs to take it back: its + * frames are dropped here unanswered, whatever arrives. + */ + #handedOver: { turn: Turn; held: PlannerHeldTurn } | undefined; + /** A turn the process before handed over, rebuilt with the session, until it is taken back or ends. */ + #pending: HandedTurn | undefined; constructor(id: string, planner: RemotePlanner, port: Port) { this.id = id; this.planner = planner; this.#port = port; - this.planner.withdrawInputs = () => this.#port.withdrawSession(this.id); + this.#wire(planner); void this.#started.promise.catch(() => {}); } + #wire(planner: RemotePlanner): void { + planner.withdrawInputs = () => this.#port.withdrawSession(this.id); + planner.handOver = (withinMs, before) => this.handOver(withinMs, before); + planner.handedChat = chat => { + if (this.#handedOver) this.#handedOver.held.chat = chat; + }; + planner.abandonHandOver = () => this.#abandonHandOver(); + } + /** Whether a turn is under way: the Planner is replying. */ get replying(): boolean { return this.#current !== undefined; @@ -544,6 +593,172 @@ class RemoteSession { return this.#acknowledged && !this.#closed && !this.planner.isolated; } + /** + * The turn the next process is to take back: one this process handed over, or one the process + * before handed over that nobody has taken back or ended yet. Its hold keeps it. + */ + get heldTurn(): PlannerHeldTurn | undefined { + if (this.#handedOver) return this.#handedOver.held; + return this.#pending?.state === "waiting" ? this.#pending.held : undefined; + } + + /** The turn the process before handed over with the session, while it waits to be taken back. */ + get pendingTurn(): HandedTurn | undefined { + return this.#pending?.state === "waiting" ? this.#pending : undefined; + } + + /** A turn the process before handed over came back with the session, to be taken back or ended. */ + await(turn: HandedTurn): void { + this.#pending = turn; + } + + /** + * The process is restarting: hands the running turn to the next process instead of ending it + * (`turn-handover`). From here its frames are neither applied nor answered. Nothing of what its host + * tools are doing is stopped, because a write stopped half way can report an outcome that is not + * what it did: the hand-over waits, a bound at most, for every call that may write to finish, and + * its real outcome goes with the turn; a read's result reaches nobody from here, so the process that + * takes the turn back runs it again. Then its client is told to keep the turn running, `before` + * runs, and the turn ends here without an abort. Undefined, with the turn left to be cut, when it + * cannot be handed over: its client did not offer the feature, it is no person's own turn, a write + * did not finish in time, or the link closed. + */ + async handOver(withinMs: number, before: () => void): Promise { + let turn = this.#current; + if ( + !turn || turn.ended || turn.stopped || turn.suspended || turn.waiting || this.planner.isolated + || !this.#port.features?.includes(AGENT_FEATURES.turnHandover) + ) return undefined; + turn.suspended = true; + let deciding = () => [...turn.hostCalls.values()].some(call => !READ_TOOLS.has(call.name)); + let until = Date.now() + EDIT_SETTLE_MS + 1_000; + while (!turn.ended && deciding() && Date.now() < until) { + await new Promise(resolve => setTimeout(resolve, 10)); + } + if ( + turn.ended || deciding() + || !this.#port.send({ + type: "turn-handover", + session: this.id, + turn: turn.id, + after: turn.cursor, + withinMs, + }) + ) { + turn.cutting = true; + return undefined; + } + // A read is run again unless a frame came after its result: one sent with nothing after it may + // not have reached the client, and one cut short was never sent. + let rerun = [...turn.reads.values()] + .filter(read => read.answered === undefined || read.answered === turn.applied) + .map(({ answered: _, ...read }) => read); + let held: PlannerHeldTurn = { + id: turn.id, + after: turn.cursor, + withinMs, + decided: [...turn.decided], + rerun, + hostIds: [...turn.hostIds], + own: [...turn.own], + ownCalls: [...turn.ownCalls], + ...(turn.inputs.size ? { inputs: [...turn.inputs] } : {}), + }; + this.#handedOver = { turn, held }; + before(); + this.#finish(turn); + return held; + } + + /** + * The turn handed over cannot be kept for the next process (its hold could not be written): its + * client is told to abort it on the link that is still open, and nothing of it is kept. + */ + #abandonHandOver(): void { + let handed = this.#handedOver; + if (!handed) return; + this.#handedOver = undefined; + this.#port.send({ type: "abort", session: this.id, turn: handed.turn.id }); + } + + /** + * The client resumed naming the turn the process before handed over: it is this session's turn + * again, from the cursor that process left it at. What arrives for it waits for this process's + * harness to take it (`#take`), which runs its owed reads again. + */ + adopt(handed: HandedTurn): void { + let { held } = handed; + this.#pending = undefined; + let turn: Turn = { + id: held.id, + emit: () => {}, + hostNames: new Set(), + own: new Set(held.own), + ownCalls: new Set(held.ownCalls), + hostIds: new Set(held.hostIds), + hostCalls: new Map(), + inputs: new Map(held.inputs ?? []), + stopped: false, + withdrawn: false, + ended: false, + settle: Promise.withResolvers(), + listeners: [], + cursor: held.after, + applied: 0, + decided: [...held.decided], + reads: new Map(), + waiting: [], + rerun: [...held.rerun], + }; + void turn.settle.promise.catch(() => {}); + this.#current = turn; + } + + /** + * Chat could not go on with the turn the client resumed (its run failed before this process's + * harness took it): the client is told to abort it, and it ends here, so nothing it sends waits + * for a harness that will not come, and the session's next turn is a turn of its own. + */ + abandonAdopted(): void { + let turn = this.#current; + if (!turn?.waiting || turn.ended) return; + turn.waiting = undefined; + this.#fail(turn, new Error("Chopin could not go on with the turn it took back.")); + } + + /** What the writes of the turn it took back came to, sent again after `resumed`. */ + resendDecided(): void { + let turn = this.#current; + if (!turn) return; + for (let call of turn.decided) { + this.#port.send({ + type: "host-tool-result", + session: this.id, + turn: turn.id, + toolCallId: call.toolCallId, + output: call.output as never, + ...(call.isError ? { isError: true } : {}), + }); + } + } + + /** Whether a harness turn of this process may take the session's turn from the process before. */ + get adopting(): boolean { + return this.#current?.waiting !== undefined; + } + + /** + * A Planner of this process takes the session back for the turn it adopted: its own tools and + * hooks replace those of the session the restart rebuilt. + */ + rebindPlanner(planner: RemotePlanner): HarnessV1Session { + let previous = this.planner; + this.planner = planner; + planner.suspended = previous.suspended; + this.#wire(planner); + return this.#session(); + } + /** * The link dropped unexpectedly and the session waits for its client to come back. The turn * under way fails, as it always did, and its host tools stop; the session and its open @@ -754,11 +969,16 @@ class RemoteSession { turn.stopped ? undefined : new Error("The machine disconnected during the turn."), ); } + // A turn the process before handed over cannot come back without its session. + if (!held) this.#pending?.end("ended"); this.#closed = true; this.#releaseAi(!held); } receive(message: TurnMessage): void { + // A turn handed to the next process takes nothing more here, and is answered nothing: what + // its client sends now is for the process that takes it back. + if (this.#handedOver?.turn.id === message.turn) return; let turn = this.#current; if (!turn || turn.id !== message.turn || turn.ended) { if (message.type === "host-tool-call") { @@ -773,6 +993,24 @@ class RemoteSession { } return; } + if (turn.waiting) { + turn.waiting.push(message); + return; + } + if (turn.suspended && !(turn.cutting && message.type === "turn-end")) return; + if (message.seq !== undefined && !turn.cutting) { + // Applied once, in order: a frame sent again is dropped, and one that skips a frame fails + // the turn rather than leave a hole in it. + if (message.seq <= turn.cursor) return; + if (message.seq !== turn.cursor + 1) { + return this.#fail( + turn, + new Error(`The machine skipped frame ${turn.cursor + 1} of its turn.`), + ); + } + turn.cursor = message.seq; + } + turn.applied++; if (message.type === "turn-end") { let failure = message.status === "finished" || turn.stopped ? undefined @@ -821,6 +1059,14 @@ class RemoteSession { } let id = this.#streamed(turn, message); turn.hostCalls.set(id, { name: message.toolName, id: message.toolCallId }); + if (READ_TOOLS.has(message.toolName)) { + turn.reads.set(id, { + toolCallId: message.toolCallId, + call: id, + toolName: message.toolName, + input: message.input, + }); + } turn.emit({ type: "tool-call", toolCallId: id, @@ -851,16 +1097,27 @@ class RemoteSession { message: ClientMessageOf<"host-tool-call">, reason: "aborted" | "unavailable", ): void { + let output = hostError( + reason === "aborted" + ? "The turn was aborted." + : `${message.toolName} is not available in this turn.`, + ); + // What it came to goes with the turn if it is handed over, as a write's does. + if (reason === "unavailable") { + turn.decided.push({ + toolCallId: message.toolCallId, + call: message.toolCallId, + toolName: message.toolName, + output, + isError: true, + }); + } this.#port.send({ type: "host-tool-result", session: this.id, turn: turn.id, toolCallId: message.toolCallId, - output: hostError( - reason === "aborted" - ? "The turn was aborted." - : `${message.toolName} is not available in this turn.`, - ), + output, isError: true, }); } @@ -963,6 +1220,9 @@ class RemoteSession { * that is restarting withdraws nothing. */ #stopped(turn: Turn): void { + // A turn being handed over goes on in its client: nothing here stops it, unless its hand-over + // failed and it is being cut. + if (turn.suspended && !turn.cutting) return; if (!turn.stopped && !turn.ended && !this.planner.stopping) { turn.withdrawn = true; this.#port.withdraw(this.id, turn.id); @@ -1001,6 +1261,20 @@ class RemoteSession { }; } let result = carried.output as NonNullable; + let read = turn.reads.get(toolCallId); + // A read a hand-over cut short is neither shown nor sent: the process that takes the turn + // back runs it again. + if (read && turn.suspended) return; + if (read) read.answered = turn.applied; + else { + turn.decided.push({ + toolCallId: call.id, + call: toolCallId, + toolName, + output: carried.output, + ...(carried.isError ? { isError: true } : {}), + }); + } turn.emit({ type: "tool-result", toolCallId, @@ -1008,7 +1282,9 @@ class RemoteSession { result, isError: carried.isError ?? isError, }); - if (!turn.stopped) this.#port.send(carried); + // What a write came to while its turn is handed over goes with the turn, and reaches the + // client from the process that takes it back. + if (!turn.stopped && !turn.suspended) this.#port.send(carried); }, async submitToolApproval() { // The remote Planner asks no approvals; host tools are already allowed. @@ -1029,6 +1305,10 @@ class RemoteSession { } async #prompt(options: PlannerTurn): Promise { + // The turn the process before handed over, which its client resumed: this harness turn takes it + // rather than start one. + let adopted = this.#current; + if (adopted?.waiting && !adopted.ended) return this.#take(adopted, options); this.#ready(); if (options.skills.length > 0) throw unsupported("skills"); let takesAttachments = this.#port.features?.includes(AGENT_FEATURES.attachments) === true; @@ -1064,6 +1344,10 @@ class RemoteSession { settle: Promise.withResolvers(), ...(hostTools ? { hostTools } : {}), listeners: [], + cursor: 0, + applied: 0, + decided: [], + reads: new Map(), }; let sent = this.#port.send({ type: "turn", @@ -1101,6 +1385,41 @@ class RemoteSession { if (this.#current) throw new Error("The remote Planner session already has an active turn."); } + /** + * This process's harness takes the turn the client resumed: what it is offered, its hooks and its + * stop, then the reads the process before owed it run again as host calls, and what the client + * sent meanwhile is applied in order. + */ + #take(turn: Turn, options: PlannerTurn): HarnessV1PromptControl { + let previews = this.#port.features?.includes(AGENT_FEATURES.decisionOptionPreviews); + let hostNames = options.tools + .filter(tool => tool.name !== "upload_plan_image" || previews) + .map(tool => tool.name); + turn.emit = options.emit; + turn.hostNames = new Set(hostNames); + let hostTools = this.planner.hostTools; + this.planner.hostTools = undefined; + this.planner.turnMessage = undefined; + if (hostTools) turn.hostTools = hostTools; + this.planner.activeTools = [...hostNames, ...turn.own]; + this.#listen(turn, options.abortSignal); + let waiting = turn.waiting ?? []; + turn.waiting = undefined; + for (let read of turn.rerun ?? []) { + turn.hostCalls.set(read.call, { name: read.toolName, id: read.toolCallId }); + turn.reads.set(read.call, { ...read }); + turn.emit({ + type: "tool-call", + toolCallId: read.call, + toolName: read.toolName, + input: read.input, + }); + } + turn.rerun = undefined; + for (let message of waiting) this.receive(message); + return this.#control(turn); + } + async close(withdraw = false): Promise { if (this.#closed) return; if (this.planner.stopping && this.#port.kept(this.id)) { @@ -1232,6 +1551,8 @@ export class AgentLink { #confirming = false; /** What the client sent while its takeover was being decided, in order. */ #queued: ClientMessage[] = []; + /** What the client sent while its `resume` waited to be answered, in order. */ + #resuming: ClientMessage[] | undefined; /** The link that took this suspended link's sessions; what is still sent here goes there. */ #successor: AgentLink | undefined; /** Takes the sessions an earlier link kept; present until the client's first message. */ @@ -1333,6 +1654,8 @@ export class AgentLink { endAi?: (launchId: string) => void; /** Hears that a held session holds an AI launch, or no longer does. */ aiHeld?: (launchId: string, holding: boolean) => void; + /** The turn the process before handed over with a held session, if it did. */ + handed?: (sessionId: string) => HandedTurn | undefined; }, ): AgentLink { let link = new AgentLink({ send() {}, close() {} }, { @@ -1357,6 +1680,12 @@ export class AgentLink { planner.unsentDecisions = decisions => document.host?.unsent(decisions); let session = new RemoteSession(item.id, planner, link.#port); session.restore(item.aiLaunchId); + let handed = hooks.handed?.(item.id); + if (handed) { + session.await(handed); + // A session kept only for that turn goes with it if nobody takes it back. + handed.whenEnded(() => link.#letGoIdle(item.id)); + } link.#sessions.set(item.id, session); for (let owed of item.owed) { link.#outbox.push({ @@ -1419,6 +1748,9 @@ export class AgentLink { stops: [], ...(asked.length > 0 ? { asked } : {}), ...(session.aiLaunchId ? { aiLaunchId: session.aiLaunchId } : {}), + // A turn handed over, or one the process before handed over that is still waiting to be + // taken back, goes to the next process. + ...(session.heldTurn ? { turn: session.heldTurn } : {}), }; }); } @@ -1497,7 +1829,8 @@ export class AgentLink { /** Whether the client's work in `session` is kept when this link drops without being ended. */ #keeps(session: RemoteSession): boolean { return this.resumable && session.resumable - && (this.#waitingOn(session.id) > 0 || this.#owedOn(session.id) > 0); + && (this.#waitingOn(session.id) > 0 || this.#owedOn(session.id) > 0 + || session.heldTurn !== undefined); } get attached(): boolean { @@ -1574,6 +1907,11 @@ export class AgentLink { return this.#options.features?.includes(AGENT_FEATURES.resumableSessions) === true; } + /** Whether this link offered `turn-handover`: its turns' frames are numbered. */ + get #numbered(): boolean { + return this.#options.features?.includes(AGENT_FEATURES.turnHandover) === true; + } + /** Whether this link holds a session a `resume` names: its client is returning to it. */ holds(sessions: ClientMessageOf<"resume">["sessions"]): boolean { return sessions.some(item => this.#sessions.has(item.session)); @@ -1608,7 +1946,11 @@ export class AgentLink { /** Opens a Planner session on the client; throws when it cannot. */ async startSession(sessionId: string, planner: RemotePlanner): Promise { if (this.#state !== "attached") throw new Error("The agent connection is not attached."); - if (this.#sessions.has(sessionId)) { + let taken = this.#sessions.get(sessionId); + // The session whose turn the client resumed from a hand-over: Chat's Planner takes it as it is, + // without starting it again. + if (taken?.adopting) return taken.rebindPlanner(planner); + if (taken) { throw new Error("The remote Planner session is already open."); } await this.#recheck(); @@ -1673,6 +2015,10 @@ export class AgentLink { return this.#violate("protocol", "Send attach first, and nothing else until it is answered."); } if (this.#takeover) return this.#confirm(message); + if (this.#resuming) { + this.#resuming.push(message); + return; + } this.#dispatch(message); } @@ -1784,6 +2130,21 @@ export class AgentLink { this.#teardown({ withdraw }); } + /** + * Lets a session this suspended link keeps go once it keeps nothing: no question, no answer owed + * and no turn to take back. A link that has ended its suspension leaves the session to whoever + * took it. + */ + #letGoIdle(id: string): void { + if (this.#state !== "suspended") return; + let session = this.#sessions.get(id); + if (!session || session.heldTurn || this.#waitingOn(id) > 0) return; + if (this.#outbox.some(owed => owed.session === id)) return; + session.linkClosed(); + this.#sessions.delete(id); + this.#lapsed(); + } + #waitingOn(session: string): number { let count = 0; for (let input of this.#inputs.values()) if (input.session === session) count++; @@ -1873,21 +2234,73 @@ export class AgentLink { /** * The client resumes: it names the sessions it still holds and the questions each still waits * on. Those sessions, with the questions that are still open or were answered meanwhile, move - * to this link; whatever it does not name ends. + * to this link; whatever it does not name ends. With `turn-handover` it names the turns it still + * runs from a `turn-handover`: each that the process before handed over in a session it resumes, + * for this account and machine, is taken back once the document's Chat holds it open, and listed + * with the cursor it was left at. A handed-over turn it does not name ends here. Until the answer + * is sent, what else the client sends waits; a process that is stopping sends none, so a turn is + * never answered as not taken back by a process that could not have taken it. */ - #resume(message: ClientMessageOf<"resume">): void { + async #resume(message: ClientMessageOf<"resume">): Promise { let earlier = this.#claim?.(); this.#claim = undefined; let held = new Map(message.sessions.map(item => [item.session, new Set(item.requests)])); let resumed: ServerMessageOf<"resumed">["sessions"] = []; let results: Owed[] = []; if (earlier) results = earlier.#hand(this, held, resumed); - this.#send({ type: "resumed", sessions: resumed }); + let named = new Set((message.turns ?? []).map(item => `${item.session}/${item.turn}`)); + let handed: { session: RemoteSession; turn: HandedTurn }[] = []; + for (let { session: id } of resumed) { + let session = this.#sessions.get(id); + let turn = session?.pendingTurn; + if (!session || !turn) continue; + if (this.#numbered && named.has(`${id}/${turn.held.id}`) && this.#identifies(turn)) { + handed.push({ session, turn }); + } else turn.end("unnamed"); + } + let turns: NonNullable["turns"]> = []; + if (handed.length > 0) { + this.#resuming = []; + // Chat holds the turn open before it is taken back, so nothing that waits in its line starts + // beside it; a turn Chat ended, or that ended meanwhile, is not taken back. + let opened = await Promise.all(handed.map(({ turn }) => turn.opened.promise)); + if (this.#stopping || this.#state !== "attached") { + this.#resuming = undefined; + return; + } + handed.forEach(({ session, turn }, at) => { + if (!opened[at] || !this.#sessions.has(session.id) || turn.state !== "waiting") return; + session.adopt(turn); + turns.push({ session: session.id, turn: turn.held.id, after: turn.held.after }); + }); + } + this.#send({ + type: "resumed", + sessions: resumed, + ...(this.#numbered ? { turns } : {}), + }); + for (let { session, turn } of handed) { + if (!turns.some(item => item.session === session.id)) continue; + turn.whenAbandoned(() => session.abandonAdopted()); + session.resendDecided(); + // Chat goes on with the turn now: it opens this process's harness turn, which takes it. + turn.adopt(); + } // The launch a resumed session held may have ended with its link, or with the process. for (let { session } of resumed) this.#sessions.get(session)?.renewAi(); for (let { result, session, delivered, unsent } of results) { this.#answer(result, session, delivered, unsent); } + let waiting = this.#resuming; + this.#resuming = undefined; + for (let later of waiting ?? []) this.#dispatch(later); + } + + /** Whether a turn the process before handed over is this link's to take back: same account and machine. */ + #identifies(turn: HandedTurn): boolean { + let identity = this.#options.identity; + return identity !== undefined && turn.channelId === this.#channelId + && identity.userId === turn.userId && identity.machineId === turn.machineId; } /** @@ -2269,8 +2682,18 @@ export class AgentLink { return this.#violate("protocol", "resume needs the resumable-sessions feature."); } if (this.#resumed) return this.#violate("protocol", "resume must come first, once."); + if (message.turns !== undefined && !this.#numbered) { + return this.#violate( + "protocol", + "resume names turns only with the turn-handover feature.", + ); + } this.#resumed = true; - return this.#resume(message); + return void this.#resume(message).catch(error => { + console.error("[agent] resuming a link failed:", error); + this.#resuming = undefined; + this.#refuse("unavailable", "The connection could not be resumed."); + }); case "capabilities": { if (!this.#options.features?.includes(AGENT_FEATURES.capabilityCatalog)) { return this.#violate("protocol", "capabilities needs the capability-catalog feature."); @@ -2315,6 +2738,15 @@ export class AgentLink { case "part": case "host-tool-call": case "turn-end": { + // With `turn-handover` every frame of a turn is numbered, and without it none is. + if (this.#numbered !== (message.seq !== undefined)) { + return this.#violate( + "protocol", + this.#numbered + ? `${message.type} needs seq with the turn-handover feature.` + : "seq needs the turn-handover feature.", + ); + } let session = this.#sessions.get(message.session); if (session) return session.receive(message); if (message.type !== "host-tool-call") return; diff --git a/apps/server/src/harness/remote/registry.ts b/apps/server/src/harness/remote/registry.ts index 18717e4b0..9d1b648c7 100644 --- a/apps/server/src/harness/remote/registry.ts +++ b/apps/server/src/harness/remote/registry.ts @@ -1,5 +1,6 @@ import type { FullPlanner } from "../atomic/full"; import type { HumanInput, HumanInputStatus } from "../atomic/human-input"; +import type { JsonValue, PlannerHeldTurn } from "../../storage/model"; import type { AgentLink, RebuiltDocument } from "./link"; /** What Chopin keeps for one Planner session whose model runs in an attached client. */ @@ -56,6 +57,19 @@ export type RemotePlanner = * reports and asks reaches the document. */ rebuilt?: RebuiltDocument; + /** + * Set by the session for a client that offered `turn-handover`: hands its running turn to the + * next process instead of ending it, calling `before` just before the turn ends here. Undefined + * when it could not, and the turn is then cut as before. + */ + handOver?: (withinMs: number, before: () => void) => Promise; + /** Set by the session: what Chat needs to go on with the turn it handed over. */ + handedChat?: (chat: JsonValue) => void; + /** + * Set by the session: the turn it handed over cannot be kept for the next process, so its + * client is told to abort it. + */ + abandonHandOver?: () => void; }; let planners = new Map(); diff --git a/apps/server/src/harness/session.ts b/apps/server/src/harness/session.ts index de8071444..20be641f9 100644 --- a/apps/server/src/harness/session.ts +++ b/apps/server/src/harness/session.ts @@ -30,6 +30,7 @@ import type { ActiveOwnerBinding } from "../agent/active-owner"; import type { HostedRepository } from "../agent/repository"; import type { DocumentRoom } from "../agent/tools"; import type { RemoteWorkspace } from "../agent/planner"; +import type { JsonValue, PlannerHeldTurn } from "../storage/model"; export type OpenError = | GitHubToolsError @@ -84,6 +85,11 @@ export type PlannerChannel = { tellChat?: TellChat; /** An answer to a reader's reaction: no tools, isolated on every harness. */ reader?: true; + /** + * A remote session the process before handed over a running turn of (`turn-handover`), whose + * client resumed it: the session is taken as it is, under its own id, never started again. + */ + adopt?: { sessionId: string }; }; export type PlannerChoice = { model?: string; thinkingLevel?: string }; @@ -149,6 +155,16 @@ export type PlannerSession = { rebinding?: (wait: Promise) => void; /** Explicitly withdraws open questions held by this session (as when a person clicks Stop). */ withdrawInputs?: () => void; + /** + * Hands the running turn to the next process instead of ending it, for a remote client that + * offered `turn-handover`; `before` runs just before the turn ends here. Undefined when it could + * not, and the turn is then cut as before. + */ + handOver?: (withinMs: number, before: () => void) => Promise; + /** Records what Chat needs to go on with the turn handed over, for the next process. */ + handedChat?: (chat: JsonValue) => void; + /** The turn handed over cannot be kept for the next process: its client is told to abort it. */ + abandonHandOver?: () => void; }; export type PlannerSessionDependencies = { @@ -310,7 +326,7 @@ export async function openPlannerSession( let timeout: ReturnType | undefined; try { if (owner.signal.aborted) throw new Error("Planner owner unavailable"); - let sessionId = crypto.randomUUID(); + let sessionId = channel.adopt?.sessionId ?? crypto.randomUUID(); unregister = (deps.registerCredential ?? registerCredential)( sessionId, () => current.currentToken(), @@ -398,7 +414,7 @@ export async function openPlannerSession( void opening.then(late => late.destroy()).catch(() => {}); throw cause; } - let { choice: _opened, ...callOptions } = channel; + let { choice: _opened, adopt: _adopt, ...callOptions } = channel; let instructions = typeof channel.instructions === "function" ? channel.instructions( workspace @@ -450,6 +466,17 @@ export async function openPlannerSession( suspended: () => remote.suspended === true, shuttingDown: () => remote.stopping === true, withdrawInputs: () => remote.withdrawInputs?.(), + handOver: async (withinMs: number, before: () => void) => { + let held = await remote.handOver?.(withinMs, before); + // The session goes on in the next process, which takes it under the same id. + if (held) { + unregisterRemote?.(); + unregisterRemote = undefined; + } + return held; + }, + handedChat: (chat: JsonValue) => remote.handedChat?.(chat), + abandonHandOver: () => remote.abandonHandOver?.(), } : {}), stream: (prompt, abortSignal, choice, files, message, context) => { diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 271dfbc35..6dc5de60e 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -107,6 +107,7 @@ import { cut } from "./handover/cut"; import { acquireWhenFree } from "./handover/lease-wait"; import { abandonable, Requests } from "./handover/requests"; import { finishTurns } from "./handover/turns"; +import { handedTurn, handedTurnChannels } from "./harness/remote/handed-turns"; import { Readiness, registerHealthRoutes } from "./http/health"; import { registerMachinesPath } from "./http/machines-path"; import { Router } from "./http/router"; @@ -1290,6 +1291,54 @@ async function resumeLine(channelId: string, threads = false): Promise { if (threads) await Threads.loadLines(context); } +/** + * Opens every document whose running turn the process before handed over (`turn-handover`), so its + * Chat holds the turn open for its client before anything waiting in its line can start, and keeps + * the document open until the turn has ended, taken back or not. Resolves once each is held open. + */ +async function adoptHandedTurns(): Promise { + if (!config.agent || !writerLease.held) return; + for (let id of handedTurnChannels()) { + if (deletingChannels.has(id) || archivingChannels.has(id)) { + handedTurn(id)?.end("ended"); + continue; + } + await withDocumentTransition(id, async () => { + await Rooms.get(id)?.closing; + let held = Rooms.hold(id); + let ending: Promise; + try { + await plan(held.room, server); + let channel = await storage.channels.get(id); + if (!channel) throw new Error("the document is gone"); + // Its default branch is read with the owner's login, once the client is back. + let context = conversation(held.room, undefined, { + id: channel.repositoryId, + owner: channel.repositoryOwner, + name: channel.repositoryName, + defaultBranch: "", + }); + ending = Chat.adopt(context, async () => { + let binding = await ownerBindings?.resolve(id); + binding?.release(); + return binding?.repository; + }); + } catch (err) { + held.release(); + evict(held.room); + throw err; + } + void ending.finally(() => { + held.release(); + evict(held.room); + }); + }).catch(err => { + console.error(`chopin: could not hold open the turn handed over in ${id} -`, err); + handedTurn(id)?.end("ended"); + }); + } +} + /** * Opens every document whose Chat, or one of its threads, kept messages waiting in line, and starts * them, so no one has to open it first. @@ -2639,8 +2688,32 @@ let leaseWait: AbortController | undefined; * What a person reads when a restart ends a reply that was running, and what Chat records. * It does not say who the reply was from, and it says what to do. */ -const INTERRUPTED_REPLY = - "A restart interrupted this reply, and it was not run again. Ask again if you still want it."; +const INTERRUPTED_REPLY = Chat.RESTART_INTERRUPTED; + +/** + * How long a client keeps a turn handed over (`turn-handover`) for the next process to take back, + * after its link closes. The next process waits at least as long, and at least its hand-over window. + */ +const TURN_HANDOVER_WITHIN_MS = 30_000; + +/** + * Hands a document's running turn to the next process instead of cutting it off, where its client + * offered `turn-handover`, and writes it into the document's link hold while this process still + * holds the writer lease (`Chat.handTurnOver`). Says whether it did; one it did not is cut off. + */ +async function handOverTurn(chat: Chat.Chat): Promise { + let room = Rooms.all().find(each => each.plan?.chat === chat); + let opened = room?.plan; + let attachments = plannerAttachments; + if (!room || !opened || !attachments || config.auth.local) return false; + let id = room.id; + return await Chat.handTurnOver( + { chat, server, room: id, persist: () => Service.persist(opened) }, + () => attachments.keepHandedTurn(id), + TURN_HANDOVER_WITHIN_MS, + INTERRUPTED_REPLY, + ); +} /** The agent link a socket carries, if it carries one. */ function agentLinkOf(ws: ServerWebSocket) { @@ -2692,6 +2765,7 @@ function drain(graceful: boolean): Promise { settled: Chat.settled, // So the link a turn runs through withdraws no question when the turn is cut off. beforeInterrupt: () => plannerAttachments?.shutdown(), + handOver: handOverTurn, }, { waitMs: handover.turnWaitMs }) ); let settling = await Promise.allSettled( @@ -4526,8 +4600,12 @@ try { void fillOpenCardSummaries().catch(err => console.error("chopin: could not fill open decision summaries -", err) ); - // Messages an earlier process kept waiting in line, through a restart or a hand-over. - void resumeWaitingChats().catch(err => + // Turns an earlier process handed over are held open first, so nothing waiting in their + // Chats' lines starts beside them; then the messages an earlier process kept waiting in line, + // through a restart or a hand-over. + void adoptHandedTurns().catch(err => + console.error("chopin: could not hold open the turns an earlier process handed over -", err) + ).then(() => resumeWaitingChats()).catch(err => console.error("chopin: could not start the messages an earlier process kept waiting -", err) ); // Holds are rebuilt and runs recovered: an AI launch an earlier process left with no run or diff --git a/apps/server/src/plan/service.ts b/apps/server/src/plan/service.ts index 527085426..13f170f36 100644 --- a/apps/server/src/plan/service.ts +++ b/apps/server/src/plan/service.ts @@ -48,6 +48,7 @@ import * as presence from "./presence"; import * as edit from "./edit"; import * as room from "./room"; import * as Chat from "../chat/service"; +import { handedTurn } from "../harness/remote/handed-turns"; import { validateReactions } from "../chat/reactions"; import { restoreReferences } from "../chat/references"; import { savedImages, savedRefusals } from "../chat/images"; @@ -1651,10 +1652,11 @@ export async function open( presence: presence.create(), questions: Questions.restore(sidecar.openQuestions), comments: Comments.create(), - chat: { - ...Chat.restore(sidecar.transcript, sidecar.initiativePaused, line), + // A turn the process before handed over is the root's alone: a child has no Chat. + chat: Chat.restore(sidecar.transcript, sidecar.initiativePaused, line, "", { ...(sidecar.transcriptSeq !== undefined ? { lastSeq: sidecar.transcriptSeq } : {}), - }, + ...(loaded.channel.parentChannelId ? {} : { handed: handedTurn(id) }), + }), conversationPlan: sidecar.conversationPlan ?? restoreConversationPlan(undefined), conversationPlanRetries: sidecar.conversationPlanRetries ?? [], conversationPlanJobs: sidecar.conversationPlanJobs ?? [], diff --git a/apps/server/src/storage/model.ts b/apps/server/src/storage/model.ts index bc8018f5e..0e88319cb 100644 --- a/apps/server/src/storage/model.ts +++ b/apps/server/src/storage/model.ts @@ -1090,11 +1090,60 @@ export type PlannerHeldSession = { * or replaces it when the client resumes. An id, not a credential. */ aiLaunchId?: string; + /** + * A turn the client was running when the process restarted and was told to keep running + * (`turn-handover`): what the next process needs to adopt it once, or to end it honestly. Consumed + * by the process that rebuilds the hold, which rewrites the row without it before anything else. + */ + turn?: PlannerHeldTurn; +}; + +/** A write host call of a handed-over turn and what came of it, as its client is to be told. */ +export type PlannerDecidedCall = { + /** The client's id for the call. */ + toolCallId: string; + /** The id Chat files the call's row under. */ + call: string; + toolName: string; + output: JsonValue; + isError?: boolean; +}; + +/** A read host call of a handed-over turn whose result may not have reached its client. */ +export type PlannerOwedRead = { + toolCallId: string; + call: string; + toolName: string; + input: string; +}; + +export type PlannerHeldTurn = { + /** The link turn's id, as the client knows it. */ + id: string; + /** The last frame of the turn the process applied. */ + after: number; + /** How long the client was told to keep the turn for after the close. */ + withinMs: number; + /** Every write the turn called, with its outcome, those an earlier process decided included. */ + decided: PlannerDecidedCall[]; + /** Reads to run again on adoption: their results may not have reached the client. */ + rerun: PlannerOwedRead[]; + /** Every host call id the turn used, so a frame sent again cannot run one twice. */ + hostIds: string[]; + /** The client's own tools the turn offered, and the calls of them it made. */ + own: string[]; + ownCalls: string[]; + /** Host tools whose input the client streamed and had not called yet: the input's id and tool. */ + inputs?: [string, string][]; + /** What Chat needs to go on with the turn (`chat/handover.ts`): ids and small values only. */ + chat?: JsonValue; }; /** * A document's remote Planner as its link left it, for the process that takes over to rebuild. - * Holds nothing a person typed and no secret: the owner's login is a session id. + * Holds no secret: the owner's login is a session id. Nothing a person typed either, but for a + * handed-over turn's write results (`PlannerHeldTurn.decided`), which may quote the document and + * go as the next process takes the turn. */ export type PlannerLinkHold = { channelId: string; diff --git a/docs/agent-connection.md b/docs/agent-connection.md index dc3f7b522..cd5d0e07f 100644 --- a/docs/agent-connection.md +++ b/docs/agent-connection.md @@ -121,6 +121,7 @@ client must then use none of them. | `ai-catalog` | With `ai-credentials`, a [catalog launch](#listing-models-before-a-session) for the link, asked for with `ai-catalog`, that lists the account's models and runs none | | `catalog-launches` | With `ai-catalog`, each `ai-catalog`'s `catalogLaunch`, and a `capabilities` report naming the one it was [listed through](#when-the-persons-accounts-change) | | `account-ids` | With `ai-credentials`, each granted provider's [`account`](#models-through-chopin): which of the person's connections of it the grant stands for | +| `turn-handover` | With `resumable-sessions`, numbered turn frames (`seq`), and a running turn [handed to the next process](#a-turn-across-a-restart) when the server restarts | ### Pings @@ -386,6 +387,7 @@ how `invoke_planner` returns it. Once a client is attached, both arrive as { "type": "ai-catalog", "ai": { "launch?": "", "expiresAt?": 0, "providers": [], "withheld": [] }, "catalogLaunch?": "" } { "type": "turn", "session": "", "turn": "", "prompt": "", "instructions?": "", "model?": "", "thinkingLevel?": "", "attachments?": [{ "id": "", "name": "", "kind": "image", "mediaType": "", "size": 0, "data": "" }], "message?": "", "retry?": true, "tools": [], "responseFormat?": {} } { "type": "abort", "session": "", "turn": "" } +{ "type": "turn-handover", "session": "", "turn": "", "after": 0, "withinMs": 0 } { "type": "steer", "request": "", "session": "", "turn": "", "prompt": "" } { "type": "host-tool-result", "session": "", "turn": "", "toolCallId": "", "output": json, "isError?": true } { "type": "input-result", "request": "", "status": "answered", "value?": json, "message?": "" } @@ -456,6 +458,8 @@ how `invoke_planner` returns it. Once a client is attached, both arrive as after `abort`, before its `turn-end`, is answered `cancelled` at once, with its method's `cancelled` value (see [Questions](#questions)), and opens no Decision. +- `turn-handover`, with `turn-handover`, says the server is restarting and hands the running turn + to the next process instead of aborting it; see [A turn across a restart](#a-turn-across-a-restart). - `steer`, with `steer-turn`, gives the turn that is running a message a person sent to Chopin while it works, when no message waits in line before it: `prompt` is the message as the model should read it (the sender's handle first, `@bo: ...`), to be read at the turn's next step, after @@ -495,15 +499,15 @@ how `invoke_planner` returns it. Once a client is attached, both arrive as ```text { "type": "started", "session": "" } { "type": "start-failed", "session": "", "message": "" } -{ "type": "tools", "session": "", "turn": "", "names": [] } -{ "type": "part", "session": "", "turn": "", "part": {} } -{ "type": "host-tool-call", "session": "", "turn": "", "toolCallId": "", "toolName": "", "input": "{}" } -{ "type": "turn-end", "session": "", "turn": "", "status": "finished", "message?": "" } +{ "type": "tools", "session": "", "turn": "", "names": [], "seq?": 1 } +{ "type": "part", "session": "", "turn": "", "part": {}, "seq?": 2 } +{ "type": "host-tool-call", "session": "", "turn": "", "toolCallId": "", "toolName": "", "input": "{}", "seq?": 3 } +{ "type": "turn-end", "session": "", "turn": "", "status": "finished", "message?": "", "seq?": 4 } { "type": "input-request", "request": "", "session": "", "block?": { "index": 0, "digest": "sha256:<64 hex>" }, "input": {} } { "type": "input-cancel", "request": "" } { "type": "control-result", "request": "", "ok": true, "message?": "" } { "type": "detach" } -{ "type": "resume", "sessions": [{ "session": "", "requests": [""] }] } +{ "type": "resume", "sessions": [{ "session": "", "requests": [""] }], "turns?": [{ "session": "", "turn": "" }] } { "type": "input-received", "request": "" } { "type": "capabilities", "catalog": {}, "catalogLaunch?": "" } { "type": "ai-catalog" } @@ -560,7 +564,13 @@ how `invoke_planner` returns it. Once a client is attached, both arrive as anything. - `resume`, with `resumable-sessions`, is the first message after `attached`: the sessions the client still holds from a dropped link (see - [Resuming](#resuming-after-a-dropped-link)). + [Resuming](#resuming-after-a-dropped-link)). With `turn-handover`, `turns` names the turns it + still runs from a `turn-handover`. +- `seq`, with `turn-handover`, numbers each `tools`, `part`, `host-tool-call` and `turn-end` of a + turn: 1 for its first and one more for each after it, in the order the client sends them. On a + link that offered the feature every one of those frames carries it, and on one that did not none + does; either mistake is a `protocol` violation. A frame whose `seq` the server already applied is + dropped, and one that skips a number fails the turn. Messages for a session or turn that has ended are ignored, except a `host-tool-call`, which gets an error result (`The turn has ended.` or @@ -1538,6 +1548,69 @@ A client that receives a frame it cannot parse should close with 4400 and reason 3000 to 4999, so a client cannot answer with 1008. The package client does this and settles everything still waiting on the connection at once. +### A turn across a restart + +A client that offers `turn-handover` (only beside `resumable-sessions`; the server names it in +`attached.features` only with that feature) keeps a turn running while Chopin restarts, and the +next process takes it back where the old one left it. Every `tools`, `part`, `host-tool-call` and +`turn-end` frame of a turn carries `seq` (see [Client to server](#client-to-server)). + +- **The old process.** When its turn-wait runs out (`HANDOVER_TURN_WAIT_MS`), a process that is + restarting sends `turn-handover` for a running turn instead of `abort`: + `{ "type": "turn-handover", "session": "", "turn": "", "after": 0, "withinMs": 0 }`. From the + moment it decides to, it applies and answers nothing more of the turn: what the client sends for + it is dropped unanswered, never answered `The turn has ended.`. Before it sends the message, every + host call of the turn that may write finishes in the server, nothing stopped half way, and what + it came to goes with the turn; `after` is the `seq` of the last frame it applied. A turn whose + write does not finish within a few seconds, or one nobody in Chat is waiting on, is cut off with + `abort` as before. The process writes the turn into the document's link hold before it releases + the writer lease; a turn it could not write is ended by that process itself, with a notice in + Chat, and the client is sent `abort` on the link that is still open. +- **What the client does.** Keep the turn running across the close, with its pending host calls + open (never settled as failed because the link closed) and every frame after `after` kept, and + queue the frames it makes while the link is down, host calls included. A turn the client already + ended keeps its frames, `turn-end` included, until the close. Name each such turn in the next + `resume`, in `turns`, each in a session it also names in `sessions`. `turn-handover` covers the + close that follows it alone: once a `resumed` lists or leaves out the turn, a later close without + a new `turn-handover` ends the turn as before. If no `resumed` lists it within `withinMs` of the + close, abort it locally and send nothing. +- **The next process.** It takes the turn out of the hold before it shows the hold, so no later + process can take it back a second time, and holds it open in the document's Chat (busy, so + nothing waiting in its line starts beside it). It answers a `resume` naming the turn once Chat + holds it, and only for the same account, through the same machine, document, session and turn: + `resumed` carries `turns`, `[{ "session": "", "turn": "", "after": 0 }]`, each turn it took back + with its own cursor. Resend every kept frame with `seq` greater than `after`, in order, then go + on live with the next `seq`. After `resumed` the server sends `host-tool-result` again for each + write the turn made and runs again each read whose result may not have reached the client; a + client ignores a result for a call it no longer waits on. A turn named but not listed was not + taken back: abort it locally and send nothing for it. If `resumed` lists a turn the client + already gave up (its `withinMs` passed), send only `turn-end` with `status: "aborted"` and + `seq` one after `after`, never the frames it kept, whose calls it already treated as failed. +- **A turn nobody takes back.** The next process waits for the client at least `withinMs` and at + least its hand-over window, counted from when it took the lease. A turn its client does not name + in `resume`, one still not taken back by then, and one whose transcript is not the one it was + handed over beside, ends in Chat with a notice that says why, each write it made with what it came + to and every other call with how it was cut off. A process that is itself stopping answers no + `resume` that names a turn, and writes the turn back into the hold for the process after it. + +Without the feature nothing changes: no frame carries `seq`, and a restart cuts the running turn +off with a notice in Chat. + +The reference client (`packages/agent-link/src/client.ts`) asks for `turn-handover` with +`resumable-sessions`. On a link that accepted it, it numbers each turn frame as it sends it and +keeps it. After `turn-handover` it sends nothing more of that turn on that link; when the link +closes it keeps the turn running, its pending host calls open and new frames (host calls included) +queued, and carries the turn in `resumption`. The next `connectAgent` given that resumption names +the turn in `resume.turns`. When `resumed` lists it, the client resends every kept frame after +`after`, in order, then sends live on the new link; a later close without a new `turn-handover` +ends the turn. When `resumed` leaves it out, the client aborts it and sends nothing. `withinMs` +runs from the close; when it passes first the client aborts the turn, and if a `resume` had already +named it and `resumed` lists it, sends only `turn-end` with `status: "aborted"` and `seq` +`after + 1`. A turn that has ended keeps its frames, `turn-end` included, until its session's next +`turn`, an `abort` or `destroy` of it, or the close. An `abort` or `destroy` after a handover, a +detach, a resume refused without `retry`, or a server that no longer lists the feature ends a +handed-over turn. + ## Planner backend commands A paired machine can run a document's Planner without a browser sign-in. The diff --git a/docs/hosted-agent.md b/docs/hosted-agent.md index a7b1a47f5..571c0eaef 100644 --- a/docs/hosted-agent.md +++ b/docs/hosted-agent.md @@ -549,8 +549,12 @@ and option counts or header, question, label, description, and answer lengths. Only Chopin's aggregate bounds apply. A request whose cards would take the document past its 256 KiB source limit fails with that message before any card appears. A written answer is limited by one shared-draft edit (64 KiB) and the -whole draft (256 KiB). Text is never silently truncated. Chopin does not replay -interrupted turns after a restart. +whole draft (256 KiB). Text is never silently truncated. A turn a restart cuts off is not +replayed as it was: a remote client that offered `turn-handover` keeps it running and the next +process takes it back ([A turn across a restart](agent-connection.md#a-turn-across-a-restart)); +otherwise the person's message whose reply was cut waits in line to be picked up once, run again +only when the cut reply called nothing but reads (see +[Deploys nobody can see](zero-downtime-deploys.md#a-planner-turn-across-a-deploy)). A coding agent can hand an instruction to the Planner with [`invoke_planner`](local-agent-mcp.md#hand-an-instruction-to-the-planner) under @@ -662,7 +666,8 @@ be closed. Attachments live in the server process, so a restart does not keep a but it does keep what its client holds: at the cut, and when a link drops with work kept, the server writes each hold to `planner_link_holds` (see [Storage](storage.md#postgresql-schema)): the sessions the client holds, the questions -it waits on and the answers it has not acknowledged. The next +it waits on, the answers it has not acknowledged, and a turn it was told to keep running across +the restart (`turn-handover`). The next process rebuilds each as a suspended hold, so a client that returns and sends `resume` takes its sessions back. No turn of the new process opened those sessions, so they reach the document through its room: a question asked on one after the restart is a diff --git a/docs/zero-downtime-deploys.md b/docs/zero-downtime-deploys.md index 2bc394864..a7674d7fe 100644 --- a/docs/zero-downtime-deploys.md +++ b/docs/zero-downtime-deploys.md @@ -17,7 +17,7 @@ When you start the new container with `HANDOVER=wait` while the old container st Once the new container is warm, your deploy script sends `SIGTERM` to the **old** container. The old process then drains in four phases: 1. **Stop taking new work:** Stays ready and serves active users, sends `Connection: close` on every HTTP response so the proxy closes idle keep-alive sockets, stops refreshing GitHub tokens, and stops starting new Planner turns (browser requests wait to be resent to the new server; `invoke_planner` calls return `planner-unavailable` so callers can retry). -2. **Wait for active Planner turns:** Lets running turns, in Chat and in its threads, finish for up to `HANDOVER_TURN_WAIT_MS` without dropping WebSockets. Any turn still running at the deadline, whether in Chopin or on a person's machine, is stopped with a notice where it was replying and is never re-run. +2. **Wait for active Planner turns:** Lets running turns, in Chat and in its threads, finish for up to `HANDOVER_TURN_WAIT_MS` without dropping WebSockets. A turn still running at the deadline on a person's machine whose client offered `turn-handover` is handed to the new server instead (see [A Planner turn across a deploy](#a-planner-turn-across-a-deploy)). Any other is stopped with a notice where it was replying; a person's message whose reply was stopped waits in line again for the new server to pick up once. 3. **Checkpoint documents:** Saves and checkpoints all open documents while still serving. 4. **The cut (in strict order):** 1. `GET /api/health/ready` switches to `503 draining` for the entire `HANDOVER_UNREADY_MS` window while the server still finishes incoming requests. It logs how many readiness checks arrived (zero means the proxy is not checking readiness actively). @@ -136,6 +136,15 @@ Under `HARNESS=remote`, external Planner clients and paired machines also surviv - **Clients without `restart-notice`:** See a `1012` close and reconnect on their normal backoff; if that exceeds the handover window, the document shows the machine as away until it reconnects. - **Paired machine backends:** Because issued Planner credentials are stored by hash in PostgreSQL, the new server accepts valid credentials immediately with no `401`. Restored holds count as active documents on the new server so the connector's first poll keeps running those Planners rather than stopping them. +## A Planner turn across a deploy + +A reply still running when the turn-wait ends is not simply lost: + +- **On a person's machine whose client offered `turn-handover`** (see [Agent connection](agent-connection.md#a-turn-across-a-restart)), the turn is handed over. The old server lets every write already asked for finish, tells the client to keep the turn running, writes where the turn stands (the last frame it applied, what each write came to, and a digest of the reply as Chat committed it) into the document's `planner_link_holds` row while it still holds the writer lease, and releases the lease only after that write. The new server takes the turn out of that row before anything else, holds it open in the document's Chat so nothing waiting in its line starts beside it, and goes on with it in the same reply once the client resumes: what the old server applied is never applied again, and each write keeps its one outcome. A client that is not back within 30 seconds, and the hand-over window, ends the reply with a notice saying the machine did not reconnect; a hold that cannot be written makes the old server end the reply itself, saying so. +- **Any other turn** (one run in Chopin, on a client without the feature, or a background job) is stopped with a notice. A person's message whose reply was stopped waits in line again, at the place it was sent, and the new server picks it up once: it runs it again as at first when the stopped reply only read, goes on with it from the agent's saved session when it called a write and its harness keeps one (a full Atomic session), told what each call came to, and otherwise leaves the notice and its Retry. A background job goes back to wait, its attempts unspent. A crash records nothing: the next server ends the reply with a notice, and Retry stands. + +Nothing new goes into the document's sidecar for this, so a rollback can still open every document; a release without the feature ignores a handed-over turn in a link hold and ends it as it always did. A release that keeps a durable line but does not know why a message waits in it again starts it as a new turn, as if its sender had sent it again, even after a stopped reply that called a write. + ## Rollback - **Expand-only migrations:** Whenever an old and new server share a database during a deploy, migrations must only add tables or columns and never drop or rename fields the running release reads. Breaking schema cleanups require a stop-then-start deploy. diff --git a/packages/agent-link/src/protocol.test.ts b/packages/agent-link/src/protocol.test.ts index 69892bbec..741284d5e 100644 --- a/packages/agent-link/src/protocol.test.ts +++ b/packages/agent-link/src/protocol.test.ts @@ -561,6 +561,64 @@ describe("Agent connection messages", () => { } }); + it("numbers a turn's frames, hands a turn over and lists what a resume took back, with turn-handover", () => { + expect(AGENT_FEATURES.turnHandover).toBe("turn-handover"); + let frames: ClientMessage[] = [ + { type: "tools", session: "s", turn: "t", names: ["read"], seq: 1 }, + { type: "part", session: "s", turn: "t", part: { type: "text-start", id: "a" }, seq: 2 }, + { + type: "host-tool-call", + session: "s", + turn: "t", + toolCallId: "c", + toolName: "read_plan", + input: "{}", + seq: 3, + }, + { type: "turn-end", session: "s", turn: "t", status: "aborted", seq: 4 }, + ]; + for (let frame of frames) { + expect(parseClientMessage(encodeMessage(frame))).toEqual({ ok: true, message: frame }); + } + for (let seq of [0, -1, 1.5, "1", Number.MAX_SAFE_INTEGER + 2]) { + expect(parseClientMessage(JSON.stringify({ ...frames[3], seq }))).toMatchObject({ + ok: false, + }); + } + let handover: ServerMessage = { + type: "turn-handover", + session: "s", + turn: "t", + after: 0, + withinMs: 30_000, + }; + expect(parseServerMessage(encodeMessage(handover))).toEqual({ ok: true, message: handover }); + for (let bad of [{ after: -1 }, { withinMs: 0 }, { withinMs: 1.5 }, { extra: true }]) { + expect(parseServerMessage(JSON.stringify({ ...handover, ...bad }))).toMatchObject({ + ok: false, + }); + } + let resume: ClientMessage = { + type: "resume", + sessions: [{ session: "s", requests: [] }], + turns: [{ session: "s", turn: "t" }], + }; + expect(parseClientMessage(encodeMessage(resume))).toEqual({ ok: true, message: resume }); + expect(parseClientMessage(JSON.stringify({ ...resume, turns: [{ session: "s" }] }))) + .toMatchObject({ ok: false }); + let resumed: ServerMessage = { + type: "resumed", + sessions: [{ session: "s", requests: [] }], + turns: [{ session: "s", turn: "t", after: 7 }], + }; + expect(parseServerMessage(encodeMessage(resumed))).toEqual({ ok: true, message: resumed }); + expect( + parseServerMessage( + JSON.stringify({ ...resumed, turns: [{ session: "s", turn: "t", after: -1 }] }), + ), + ).toMatchObject({ ok: false }); + }); + it("derives the link URL from a Chopin origin", () => { expect(agentUrl("https://chopin.test/some/doc?x=1").href) .toBe("wss://chopin.test/api/v1/agent"); diff --git a/packages/agent-link/src/protocol.ts b/packages/agent-link/src/protocol.ts index 791204f05..ebbe383ed 100644 --- a/packages/agent-link/src/protocol.ts +++ b/packages/agent-link/src/protocol.ts @@ -142,6 +142,23 @@ export const AGENT_FEATURES = { * what it reads. Without the feature no grant carries `account`. */ accountIds: "account-ids", + /** + * With `resumable-sessions` (the server names it only beside that feature): a turn can outlive + * the process that started it. Every `tools`, `part`, `host-tool-call` and `turn-end` of a turn + * carries `seq`, 1 for its first and one more for each after it. A server that is restarting may + * send `turn-handover` for a running turn instead of aborting it: it has applied the turn's frames + * up to `after` and decided every host call among them, and it applies and answers nothing more of + * that turn. The client keeps the turn running across the close, with its pending host calls open + * and every frame after `after` kept, and names it in its next `resume`. The process that takes + * over lists the turns it adopted in `resumed` with its own cursor, `after`; the client resends + * every frame after it, in order, and goes on. A turn the client named that `resumed` does not list + * was not adopted: the client ends it and sends nothing more for it. One not taken back within + * `withinMs` of the close the client aborts; if a later `resumed` lists it anyway, the client sends + * only `turn-end` with `status: "aborted"` and `seq` one after `after`. A frame whose `seq` the + * server has already applied is dropped, and one that skips a number fails the turn. Without the + * feature no frame carries `seq`, and a restart ends a running turn as before. + */ + turnHandover: "turn-handover", } as const; /** @@ -191,6 +208,8 @@ const MAX_NOTE = MAX_LINK_NOTE_LENGTH; const MAX_TOOLS = 256; /** The most sessions one link keeps across a drop. */ const MAX_HELD_SESSIONS = 64; +/** The largest `seq` a turn's frame may carry. */ +const MAX_SEQ = Number.MAX_SAFE_INTEGER; const MAX_QUESTIONS = 16; const MAX_OPTIONS = 32; const MAX_TURN_ATTACHMENTS = 20; @@ -202,6 +221,8 @@ const name = z.string().min(1).max(MAX_NAME); const note = z.string().max(MAX_NOTE); const text = z.string().max(MAX_LINK_MESSAGE_BYTES); const count = z.number().int().nonnegative(); +/** With `turn-handover`: a turn frame's number, 1 for its first and one more for each after it. */ +const seq = z.number().int().min(1).max(MAX_SEQ); const json = z.json(); const finishReason = z.strictObject({ @@ -476,6 +497,18 @@ const heldSessions = z.array(z.strictObject({ requests: z.array(id).max(MAX_OPEN_REQUESTS), })).max(MAX_HELD_SESSIONS); +/** + * With `turn-handover`: in `resume`, the turns a client still runs from a `turn-handover`, each in a + * session it also names; in `resumed`, with `after`, the turns the server adopted and the last + * frame of each it has applied. + */ +const heldTurns = z.array(z.strictObject({ session: id, turn: id })).max(MAX_HELD_SESSIONS); +const adoptedTurns = z.array(z.strictObject({ + session: id, + turn: id, + after: z.number().int().min(0).max(MAX_SEQ), +})).max(MAX_HELD_SESSIONS); + /** An environment variable's name, as a runner sets a provider's key variable. */ const variable = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,127}$/); @@ -519,8 +552,17 @@ export const clientMessageSchema = z.discriminatedUnion("type", [ session: id, turn: id, names: z.array(name).max(MAX_TOOLS), + /** With `turn-handover`. */ + seq: seq.optional(), + }), + z.strictObject({ + type: z.literal("part"), + session: id, + turn: id, + part: streamPartSchema, + /** With `turn-handover`. */ + seq: seq.optional(), }), - z.strictObject({ type: z.literal("part"), session: id, turn: id, part: streamPartSchema }), z.strictObject({ type: z.literal("host-tool-call"), session: id, @@ -528,6 +570,8 @@ export const clientMessageSchema = z.discriminatedUnion("type", [ toolCallId: id, toolName: name, input: text, + /** With `turn-handover`. */ + seq: seq.optional(), }), z.strictObject({ type: z.literal("turn-end"), @@ -535,6 +579,8 @@ export const clientMessageSchema = z.discriminatedUnion("type", [ turn: id, status: z.enum(["finished", "failed", "aborted"]), message: note.optional(), + /** With `turn-handover`. */ + seq: seq.optional(), }), z.strictObject({ type: z.literal("input-request"), @@ -574,9 +620,15 @@ export const clientMessageSchema = z.discriminatedUnion("type", [ }), /** * With `resumable-sessions`, the first message after `attached`: the sessions this client - * still holds from a link that dropped, and the questions each still waits on. + * still holds from a link that dropped, and the questions each still waits on. With + * `turn-handover`, `turns` names the turns it still runs from a `turn-handover`. */ - z.strictObject({ type: z.literal("resume"), sessions: heldSessions }), + z.strictObject({ + type: z.literal("resume"), + sessions: heldSessions, + /** With `turn-handover`. */ + turns: heldTurns.optional(), + }), /** * With `ai-catalog`: asks, once per link, for the link's catalog grants (after `resumed` on a * link that resumes). Asking again changes nothing. @@ -718,6 +770,20 @@ export const serverMessageSchema = z.discriminatedUnion("type", [ responseFormat: responseFormat.optional(), }), z.strictObject({ type: z.literal("abort"), session: id, turn: id }), + /** + * With `turn-handover`: this process is restarting and hands the running turn on. It applied the + * turn's frames up to `after` and decided every host call among them, and applies and answers + * nothing more of it. Keep the turn running, its pending host calls open and its frames after + * `after` kept, and name it in the next `resume`; abort it if no `resumed` lists it within + * `withinMs` of the link closing. + */ + z.strictObject({ + type: z.literal("turn-handover"), + session: id, + turn: id, + after: z.number().int().min(0).max(MAX_SEQ), + withinMs: z.number().int().min(1), + }), /** * With `ai-credentials`: the session's grants changed, and `ai` replaces what `start`, `fork` or * an earlier `ai` gave. The earlier launch's credential and placeholders stop working; an empty @@ -759,9 +825,16 @@ export const serverMessageSchema = z.discriminatedUnion("type", [ /** * The answer to `resume`: the sessions the server kept and gave back, each with the questions * it still holds, open or answered meanwhile. Anything the client held that is not listed has - * ended. + * ended. With `turn-handover`, `turns` lists the turns the server adopted, each with the last + * frame it has applied (`after`): resend every frame after it, in order. A turn the client named + * that is not listed was not adopted. */ - z.strictObject({ type: z.literal("resumed"), sessions: heldSessions }), + z.strictObject({ + type: z.literal("resumed"), + sessions: heldSessions, + /** With `turn-handover`. */ + turns: adoptedTurns.optional(), + }), ]); export type CapabilityCatalog = z.infer;