diff --git a/CHANGELOG.md b/CHANGELOG.md index 78a03e4..b1f48fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,11 @@ Harness spec 3.10.0: a turn the harness starts by itself is a turn like any othe back over, the message is kept with the session — also across a restart of the service — and the agent reads it at the start of its next turn. It used to wait in memory, and with `busy_input: queue` came back attached to an unrelated later prompt. +- **A message is never given to the agent twice.** After a dropped connection the web UI may not + know whether a message you sent while the agent worked was read; sending it again is now safe — + the agent recognises it and says whether it was read already or is waiting for the next turn. + A message the agent had no time for when the connection was down is kept for its next turn + after any kind of turn, not only one it started by itself. - **Stop in the web UI stops the reply you stopped.** If your message was still waiting behind a turn the agent had started by itself (answering a finished job or a subagent), Stop used to end that turn instead and your message ran afterwards anyway. A server that names the turn diff --git a/harness/README.md b/harness/README.md index 9089e25..0d3a489 100644 --- a/harness/README.md +++ b/harness/README.md @@ -134,6 +134,12 @@ follows 3.10.0 as first written follows this. comes before the `inbox` event that says the queue is empty. - **A wake that may not start a turn** (a schedule's session on an interactive-only model): the session is idle again and the note is kept for the person's next message. +- **A steered message is given to the model once** (`_lembas/steer`; part of `harness_turns`). A + prompt's turn that ends with no link up carries its too-late steers to the next turn, as a + harness turn does — an `unsent` in an answer nobody reads was a message lost. And a + `session/prompt` whose `turnId` is the `messageId` of a steered message the device still knows + (taken in, carried, or waiting in the running turn) does not run: it is answered with + `_meta.lembas.steered` saying which. A client that lost the link can send again safely. - **`session/cancel` may name its turn** (`_meta.lembas.turnId`; part of `harness_turns`, which no release has carried yet; `conformance/cancel.json`, 7 cases). A prompt can now wait behind a turn its client did not start, and a cancel that names no turn stops whatever runs: a client diff --git a/harness/acp.md b/harness/acp.md index 71fa49c..610eebf 100644 --- a/harness/acp.md +++ b/harness/acp.md @@ -205,7 +205,8 @@ where `_meta.lembas` may also carry: | Field | When | |---|---| -| `unsent: string[]` | messages sent with `_lembas/steer` that the turn ended before taking in — send them next | +| `unsent: string[]` | messages sent with `_lembas/steer` that the turn ended before taking in — send them next. Only in an answer a client is there to read: when no link is up as the turn ends, they are carried to the next turn instead (`_lembas/steer`, *A steered message is given to the model once*) and this answer, kept for a resend, has none | +| `steered: "taken" \| "carried" \| "waiting"` | spec 3.10.0 (capability `harness_turns`): the `turnId` is the `messageId` of a message this session was steered — **nothing ran**; what became of that message (`_lembas/steer`, below) | | `command: string` | the prompt was that command | | `summary: string` | `/compact` | | `undone: { prompt, files } \| null` | `/undo` (null: nothing to undo) | @@ -872,6 +873,28 @@ next step. Result `{ queued: number }`. `-32602` when nothing runs: send it as a "Runs" is any turn — the client's prompt, a terminal's, or one the harness started (capability `harness_turns`; a device without it refuses a steer during a harness turn). +**A steered message is given to the model once** (spec 3.10.0, capability `harness_turns`). What +becomes of a message the device accepted, whichever kind of turn it was steered into: + +- **taken in** at a step of that turn — said with `steered` and its `messageId`; +- **handed back** when the turn ended first and a client is there to hear it: `unsent` in the + prompt's answer, or on the `task` end of a turn the harness started. The device has let go of + it; the client sends it next, as a prompt; +- **carried** when the turn ended first and **no link is up** — after a prompt's turn exactly as + after a harness turn: kept with the session, across a restart, taken in at the next turn's + first step (said with `steered` and its id there), and never handed back as well. In a session + a terminal runs it stays in the terminal's own queue instead. + +A client that lost the link cannot always tell which of these happened. So **a `session/prompt` +whose `turnId` is the `messageId` of a steered message the device still knows does not run**: it +is answered at once, `stopReason: "end_turn"`, with `_meta.lembas.steered` — `"taken"` (the model +has been given it, in some turn), `"carried"` (it waits for the next turn's first step) or +`"waiting"` (it is in the queue of the turn running now, and will be taken in or handed back). +Only a message that was handed back, or that the device never accepted, runs as a prompt. The +device keeps the ids of the last 200 messages taken in with the session, across a restart; a +client therefore uses one id for a message whether it steers it or prompts it (LLeMbas: the +message's id), and sending again is always safe. + ### `_lembas/session/history` — client → agent → result Params `{ sessionId }`. Result `{ sessionId, title, root, turns }`, each turn diff --git a/src/acp/agent.ts b/src/acp/agent.ts index 9f1cbbd..ae06631 100644 --- a/src/acp/agent.ts +++ b/src/acp/agent.ts @@ -1124,6 +1124,10 @@ export class AcpAgent { // A turn id this session has taken already: not run again — the original's answer, // now or when it is done. if (s.turns.has(turnId)) return s.turns.run(turnId, () => Promise.reject(new Error("unreachable"))) + // An id this session knows as a steered message's: the same message, sent again as a prompt by + // a client that could not tell what became of it. The model is not given it twice. + const steered = s.app.engine.steerState(turnId) + if (steered) return { stopReason: "end_turn", _meta: { lembas: { turnId, steered } } } // Spec 3.5.0: a scheduled turn is judged again (the setting may have been turned off since the // session was opened); a prompt without `scheduled` is the person's, in the run's agent chat. const scheduled = this.judgeScheduled(p?._meta?.lembas?.scheduled) @@ -1223,7 +1227,7 @@ export class AcpAgent { const reason = await app.turns.prompt(prepared.prompt, prepared.extra, prepared.shown, { turnId, attachments: prepared.attachments }) // Messages sent mid-task (`_lembas/steer`) that the task ended before taking in: handed back, // so the web UI sends them as the next turn rather than losing them. - const unsent = app.engine.takeInbox() + const unsent = this.leftover(s) return { stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: { turnId, ...(unsent.length ? { unsent } : {}), ...(prepared.command ? { command: prepared.command } : {}) } } } } finally { // A command's model and mode hold for its prompt only — unless the turn itself changed the @@ -1234,6 +1238,17 @@ export class AcpAgent { } } + /** What a prompt's turn ended before taking in (`_lembas/steer`). With a client there to read + * the answer it is handed back (`unsent`); with none — the link is down as the turn ends — it + * is kept with the session for the next turn's first step, as after a turn the harness + * started (engine.carry): an answer nobody reads would lose it. One or the other. */ + private leftover(s: Session): string[] { + const agent = s.agent ?? this + if (!agent.peer.isClosed) return s.app.engine.takeInbox() + s.app.engine.carry() + return [] + } + /** A scheduled request's settings as this device runs them (spec 3.5.0), or undefined when the * request is not scheduled; a refusal is thrown as -32602 with `data.reason`. */ private judgeScheduled(meta: any): ScheduledTurn | undefined { @@ -1271,7 +1286,7 @@ export class AcpAgent { try { if (prepared.model) app.switchModel(prepared.model, "borrowed") const reason = await app.turns.prompt(prepared.prompt, prepared.extra, prepared.shown, { turnId, attachments: prepared.attachments }) - const unsent = app.engine.takeInbox() + const unsent = this.leftover(s) return { stopReason: STOP[reason] ?? "end_turn", _meta: { lembas: meta(unsent.length ? { unsent } : {}, reason, finalReply(app.engine.messages), error) } } } finally { off() diff --git a/src/acp/share.ts b/src/acp/share.ts index 4bbce89..b605f2b 100644 --- a/src/acp/share.ts +++ b/src/acp/share.ts @@ -473,6 +473,9 @@ export class Share { const turnId = typeof p?.turnId === "string" && p.turnId ? p.turnId : crypto.randomUUID() // A turn id taken already: the original's answer. if (this.turns.has(turnId)) return this.turns.run(turnId, () => Promise.reject(new Error("unreachable"))) + // A steered message's id, sent again as a prompt: not given to the model twice. + const steered = this.app.engine.steerState(turnId) + if (steered) return { stopReason: "end_turn", _meta: { lembas: { turnId, steered } } } // What the client holds for the session (its instructions, personalization, library scope), // passed on by the hub: read into the prompt here as the service would. if (p?.context && typeof p.context === "object") this.app.setContext(p.context as SessionContext, typeof p?.instance === "string" ? p.instance : undefined) diff --git a/src/session/engine.ts b/src/session/engine.ts index 54fb7af..54017fd 100644 --- a/src/session/engine.ts +++ b/src/session/engine.ts @@ -163,7 +163,9 @@ export const END_META = "ended" * the harness started that ended before taking them in, with nobody listening to hand them back * to, which go in at the next turn's first step. */ export const CARRIED_META = "carried" -type Carried = { notes: string[]; steers: { text: string; id?: string }[] } +type Carried = { notes: string[]; steers: { text: string; id?: string }[]; taken?: string[] } +/** How many ids of steered messages the model has been given are remembered, newest last. */ +export const STEERS_KEPT = 200 export class Engine { messages: Message[] = [] @@ -269,12 +271,13 @@ export class Engine { /** What the store holds for this session that the model has not been given yet. */ private storedCarried(): Carried { - const none: Carried = { notes: [], steers: [] } + const none: Carried = { notes: [], steers: [], taken: [] } if (!this.o.store || !this.sessionId) return none try { const c = this.o.store.meta | null>(this.sessionId, CARRIED_META) if (!c || typeof c !== "object") return none return { + taken: Array.isArray(c.taken) ? c.taken.filter((n): n is string => typeof n === "string").slice(-STEERS_KEPT) : [], notes: Array.isArray(c.notes) ? c.notes.filter((n): n is string => typeof n === "string") : [], steers: Array.isArray(c.steers) ? c.steers.filter((x) => x && typeof x.text === "string").map((x) => ({ text: x.text, ...(typeof x.id === "string" ? { id: x.id } : {}) })) : [], } @@ -286,7 +289,7 @@ export class Engine { private saveCarried() { if (!this.o.store || !this.sessionId) return try { - this.o.store.setMeta(this.sessionId, CARRIED_META, this.carried.notes.length || this.carried.steers.length ? this.carried : null) + this.o.store.setMeta(this.sessionId, CARRIED_META, this.carried.notes.length || this.carried.steers.length || this.carried.taken?.length ? this.carried : null) } catch {} } @@ -297,6 +300,19 @@ export class Engine { this.saveCarried() } + /** What became of a steered message, by the id its sender gave it: `taken` — the model has been + * given it, in some turn of this session (the last STEERS_KEPT ids are remembered, with the + * session); `carried` — kept for the next turn's first step; `waiting` — in the running turn's + * queue, to be taken in or handed back. Undefined: not known here, or handed back as unsent. + * A prompt carrying such an id is that same message and must not give it to the model twice. */ + steerState(id: string): "taken" | "carried" | "waiting" | undefined { + if (!id) return undefined + if (this.carried.taken?.includes(id)) return "taken" + if (this.carried.steers.some((x) => x.id === id)) return "carried" + if (this.inboxIds.includes(id)) return "waiting" + return undefined + } + /** Messages steered into this turn that it ended before taking in, with nobody to hand them * back to: kept with the session, and given to the model at the next turn's first step — in * every `busy_input` mode, since nobody will send them again. Emptied from the inbox, so they @@ -886,12 +902,14 @@ export class Engine { } // What an earlier turn left (carry) goes in whatever the mode; the inbox only when steering. const late = this.carried.steers.splice(0) - if (late.length) this.saveCarried() const now = this.busyInput === "steer" ? this.inbox.splice(0) : [] const nowIds = this.busyInput === "steer" ? this.inboxIds.splice(0) : [] if (!late.length && !now.length) return notes.length > 0 const texts = [...late.map((x) => x.text), ...now] const ids = [...late.map((x) => x.id), ...nowIds].filter((i): i is string => typeof i === "string") + // The model has these now: their ids are remembered with the session (steerState). + if (ids.length) this.carried.taken = [...(this.carried.taken ?? []), ...ids].slice(-STEERS_KEPT) + if (late.length || ids.length) this.saveCarried() this.turnSteers.push(...texts) this.push({ role: "user", parts: [{ type: "text", text: `${this.o.steerMark ?? STEER_MARK}\n${texts.join("\n\n")}` }], turn: false }) this.o.bus.emit({ type: "steered", texts, ...(ids.length ? { ids } : {}) }) diff --git a/tests/acp-steer-once.test.ts b/tests/acp-steer-once.test.ts new file mode 100644 index 0000000..2547ef6 --- /dev/null +++ b/tests/acp-steer-once.test.ts @@ -0,0 +1,143 @@ +// A steered message is given to the model once (harness/acp.md `_lembas/steer`; spec 3.10.0): a +// prompt carrying the id of a message the session was steered does not run — it says what became +// of the message — and a prompt's turn that ends with no link up carries its too-late steers to +// the next turn, as a turn the harness started does. +import { afterEach, expect, test } from "bun:test" +import { mkdirSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { AcpAgent, type Limits } from "../src/acp/agent.ts" +import { Hub } from "../src/acp/hub.ts" +import { Peer, type Transport } from "../src/acp/rpc.ts" +import { paths } from "../src/config/paths.ts" +import { setTrust } from "../src/project/root.ts" +import { delta, fakeProvider, type Fake, type Scripted } from "./fake-provider.ts" + +let fake: Fake | undefined +const stops: (() => unknown)[] = [] +afterEach(async () => { + for (const s of stops.splice(0).reverse()) await s() + fake?.stop() +}) + +function pair(): [Transport, Transport] { + const make = () => ({ msg: (_: string) => {}, end: () => {} }) + const a = make() + const b = make() + const side = (me: typeof a, o: typeof a): Transport => ({ + send: (t) => queueMicrotask(() => o.msg(t)), + onMessage: (fn) => (me.msg = fn), + onClose: (fn) => (me.end = fn), + close: () => (me.end(), o.end()), + }) + return [side(a, b), side(b, a)] +} + +const SLOW = 30_000 +const say = (text: string): Scripted => ({ chunks: [delta({ content: text }, "stop")] }) +const slow = (text: string, ms: number): Scripted => ({ chunks: [delta({ content: "… " }), delta({ content: text })], gapMs: ms }) +const users = (body: any): string => body.messages.filter((m: any) => m.role === "user").map((m: any) => (typeof m.content === "string" ? m.content : m.content.map((p: any) => p.text ?? "").join("\n"))).join("\n") + +function setup(script: Scripted[], config = "") { + fake = fakeProvider(script) + mkdirSync(paths.config, { recursive: true }) + writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${fake.url}\n models: { f/m: {} }\n`, { mode: 0o600 }) + writeFileSync(join(paths.config, "config.yaml"), `model: f/m\nmode: auto\n${config}`) + const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-once-"))) + setTrust(dir, "trusted") + return dir +} +const limitsFor = (root: string): Limits => ({ roots: [root], maxMode: "auto", approvalTimeoutMs: 3000, requireTrust: true, enabled: true }) + +async function link(root: string, hub?: Hub) { + const [ta, tb] = pair() + new AcpAgent(new Peer(ta), limitsFor(root), undefined, hub) + const c = new Peer(tb) + const events: any[] = [] + c.on("_lembas/event", (p) => void events.push(p.event)) + await c.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } }) + return { c, events, drop: () => tb.close() } +} +async function service(root: string) { + const hub = new Hub({ service: true, limits: { ...limitsFor(root), enabled: true } }) + expect(await hub.listen()).toBe(true) + stops.push(async () => { + for (const s of hub.held.values()) await s.app.close().catch(() => {}) + hub.close() + }) + return hub +} +const until = async (ok: () => boolean, ms = 10_000) => { + const end = Date.now() + ms + while (Date.now() < end && !ok()) await Bun.sleep(20) + return ok() +} +const go = (c: Peer, sid: string, text: string, turnId: string) => c.request("session/prompt", { sessionId: sid, prompt: [{ type: "text", text }], _meta: { lembas: { turnId } } }) +const begun = (events: any[]) => events.some((e) => e.type === "text" && e.text === "… ") + +test("a message the turn took in, sent again as a prompt with its id, does not run: taken — also after a restart", async () => { + const root = setup([slow("First.", 1000), say("With it.")]) + const hub = await service(root) + const { c, events } = await link(root, hub) + const s: any = await c.request("session/new", { cwd: root, mcpServers: [] }) + const sid = s.sessionId as string + const first = go(c, sid, "go", "web-1") + expect(await until(() => begun(events))).toBe(true) + await c.request("_lembas/steer", { sessionId: sid, text: "and say hello", messageId: "web-2" }) + // While it waits in the running turn's queue, the same id as a prompt runs nothing either. + expect(await go(c, sid, "and say hello", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "waiting" } } }) + expect((await first)._meta.lembas.unsent).toBeUndefined() + expect(events.find((e) => e.type === "steered")).toMatchObject({ ids: ["web-2"] }) + expect(fake!.requests).toHaveLength(2) + expect(await go(c, sid, "and say hello", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "taken" } } }) + // The device starts again: the session comes from the store, and still knows the id. + const held = hub.held.get(sid)! + await held.app.close() + hub.held.delete(sid) + const again = await link(root) + expect(await go(again.c, sid, "and say hello", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "taken" } } }) + expect(fake!.requests).toHaveLength(2) + expect(again.events.some((e) => e.type === "prompt")).toBe(false) +}, SLOW) + +test("a prompt's turn that ends with no link up carries its too-late steer; its id as a prompt says carried, then taken — the model reads it once", async () => { + // busy_input: queue — nothing goes in at a step by itself, so the turn ends with it waiting. + const root = setup([slow("First.", 1000), say("Second."), say("Third.")], "busy_input: queue\n") + const hub = await service(root) + const first = await link(root, hub) + const s: any = await first.c.request("session/new", { cwd: root, mcpServers: [] }) + const sid = s.sessionId as string + void go(first.c, sid, "go", "web-1").catch(() => {}) + expect(await until(() => begun(first.events))).toBe(true) + await first.c.request("_lembas/steer", { sessionId: sid, text: "one more thing", messageId: "web-2" }) + first.drop() + const held = hub.held.get(sid)! + expect(await until(() => !held.prompting && !held.app.engine.busy)).toBe(true) + // The link is back. The answer kept for the first prompt hands nothing back: it was carried. + const { c, events } = await link(root, hub) + expect((await go(c, sid, "go", "web-1"))._meta.lembas.unsent).toBeUndefined() + // "Send now" for the message the client is unsure of: not run, and said to be carried. + expect(await go(c, sid, "one more thing", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "carried" } } }) + expect(fake!.requests).toHaveLength(1) + // The next turn takes it in at its first step. + expect((await go(c, sid, "next", "web-3")).stopReason).toBe("end_turn") + expect(events.find((e) => e.type === "steered")).toMatchObject({ texts: ["one more thing"], ids: ["web-2"] }) + expect(await go(c, sid, "one more thing", "web-2")).toEqual({ stopReason: "end_turn", _meta: { lembas: { turnId: "web-2", steered: "taken" } } }) + expect(fake!.requests).toHaveLength(2) + expect(users(fake!.requests[1]).split("one more thing")).toHaveLength(2) +}, SLOW) + +test("a steer handed back as unsent is the client's again: its id as a prompt runs", async () => { + const root = setup([slow("First.", 1000), say("Now that.")], "busy_input: queue\n") + const { c, events } = await link(root) + const s: any = await c.request("session/new", { cwd: root, mcpServers: [] }) + const sid = s.sessionId as string + const first = go(c, sid, "go", "web-1") + expect(await until(() => begun(events))).toBe(true) + await c.request("_lembas/steer", { sessionId: sid, text: "then that", messageId: "web-2" }) + expect((await first)._meta.lembas.unsent).toEqual(["then that"]) + const r = await go(c, sid, "then that", "web-2") + expect(r._meta.lembas.steered).toBeUndefined() + expect(fake!.requests).toHaveLength(2) + expect(events.filter((e) => e.type === "prompt").map((e) => e.turnId)).toEqual(["web-1", "web-2"]) +}, SLOW)