@a-dray/aglib 0.6.7 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/run.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,UAAU,QAAQ,CAAC,OAAwB;IAC/C,6EAA6E;IAC7E,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI,EAAE,CAAC;IACxC,IAAI,IAAI,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,KAAK,CAAC,MAAM,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAClG,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;IACxE,CAAC;IACD,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;IAC5B,MAAM,SAAS,GAAG,KAAK,EAAE,SAAS,IAAI,OAAO,CAAC,SAAS,IAAI,MAAM,CAAC,UAAU,EAAE,CAAC;IAC/E,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACzC,6EAA6E;IAC7E,uEAAuE;IACvE,0EAA0E;IAC1E,sDAAsD;IACtD,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM;QAC3B,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,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AgentRun, Arrival, RunAgentOptions, RunResult } from \"./agent.js\";\nimport type { Failure } from \"./result.js\";\nimport type { HarnessContext, HarnessResult, Update } from \"./harness/harness.js\";\nimport type { Delivery, Store, StoreConflict, StoreError } from \"./store/store.js\";\nimport type { Content } from \"./content.js\";\nimport type { Entry, Stored, Usage } from \"./session/entry.js\";\nimport { err } from \"./result.js\";\nimport { createLog } from \"./session/log.js\";\nimport { toMessages } from \"./session/messages.js\";\nimport { createExecutor } from \"./tools/execute.js\";\n\n/**\n * Start an agent on a session.\n *\n * Without a store the log lives in memory and the session is ephemeral; with\n * one, every commit is durable before the next turn is built. The agent\n * definition is identical either way — durability is a composition choice, not\n * a different program.\n */\nexport function runAgent(options: RunAgentOptions): AgentRun {\n // A claim names its own session; a caller sending into a new one names none.\n const hooks = options.agent.hooks ?? [];\n if (new Set(hooks.map(hook => hook.name)).size !== hooks.length || hooks.some(hook => !hook.name)) {\n throw new Error(\"Lifecycle hook names must be non-empty and unique.\");\n }\n const claim = options.claim;\n const sessionId = claim?.sessionId ?? options.sessionId ?? crypto.randomUUID();\n const controller = new AbortController();\n // Composed rather than forwarded. `addEventListener(\"abort\", …)` never fires\n // on a signal that has already aborted, so a caller who gave up before\n // calling got a full run anyway; and a listener added per run to a signal\n // that outlives it is a leak the run cannot clean up.\n const signal = options.signal\n ? AbortSignal.any([options.signal, controller.signal])\n : controller.signal;\n\n const updates = createChannel<Update>();\n const result = execute();\n\n return {\n result,\n cancel: () => controller.abort(),\n [Symbol.asyncIterator]: () => updates.iterator(),\n };\n\n async function execute(): Promise<RunResult> {\n // What this activation consumed. Summed from the model usage entries it\n // commits rather than reported by the harness, so one answer serves a loop\n // we own and a loop we do not — and so a run that failed still says what it\n // burned on the way there.\n const usage: Usage = {};\n let hookContext: HarnessContext | undefined;\n let result: RunResult | undefined;\n let unwatch: (() => void) | undefined;\n let clearInputWait: (() => void) | undefined;\n\n try {\n const { agent, store } = options;\n const restored = store ? await open(store, sessionId, agent, options.key) : undefined;\n if (restored && !restored.ok) {\n return {\n status: \"failed\", error: restored.error,\n seq: positionOf(restored.error, 0), usage,\n };\n }\n // The store's own position, not the last entry's. They agree only while\n // nothing has ever been folded away, and the store is the one that knows.\n const log = createLog(restored?.value.entries ?? [], restored?.value.seq ?? 0);\n const stopping = (error: Failure): RunResult => (result = { status: \"failed\", error, seq: log.seq, usage });\n\n // A claim was read at a position. If the session has moved since, this\n // worker lost, and the deliveries it was carrying are still where it\n // found them.\n if (claim && claim.seq !== log.seq) {\n return stopping({ code: \"conflict\", message: `Session is at ${log.seq}, not ${claim.seq}`, retryable: true });\n }\n\n // A ceiling on money needs something that can count it. Refused here\n // rather than silently ignored, because a limit that is declared and not\n // enforced is the most expensive kind of nothing.\n\n // The activation still open on this log, if one is. It decides three\n // things below: whether there is anything to resume, which run a\n // resumption continues, and which run a fresh activation supersedes.\n const interrupted = openRunId(log.entries);\n\n // What this run is adding, then what was waiting. A claim's deliveries\n // are named so the log records who each came from; anything the worker\n // supplies itself leads, because the only thing that ever does is\n // orientation for a harness with nowhere else to put it.\n const arrivals: readonly Arrival[] = [\n ...arrivalsOf(options.input),\n ...(claim?.pending ?? []).map((delivery): Arrival => ({\n input: delivery.input,\n ...(delivery.from ? { from: delivery.from } : {}),\n })),\n ];\n\n // A resumption continues the run it was handed, under that run's id. A\n // fresh id would leave the log holding a `run.started` nothing closes and\n // a `run.finished` nothing opened — a pair that only the store's\n // type-based rule saves, and that anything grouping entries by run reads\n // as broken. A resumption without an interrupted run is refused below.\n const runId = arrivals.length || !interrupted ? crypto.randomUUID() : interrupted;\n\n // The ceiling has one owner, and it is here rather than in a harness.\n // Counting committed entries is the only way to bound a harness that owns\n // its own loop — which is most of them — so a limit declared on the agent\n // holds for every one instead of only for ours.\n const limits = agent.limits;\n let stopped: Failure | undefined;\n let turns = 0;\n let toolCalls = 0;\n const generations = new Set<string>();\n\n function exceeded(): Failure | undefined {\n if (!limits) return undefined;\n if (limits.maxTurns !== undefined && turns >= limits.maxTurns) {\n return { code: \"turn-limit\", message: `Stopped after ${turns} turns.`, retryable: false };\n }\n if (limits.maxToolCalls !== undefined && toolCalls >= limits.maxToolCalls) {\n return { code: \"tool-call-limit\", message: `Stopped after ${toolCalls} tool calls.`, retryable: false };\n }\n // Checked where work is recorded rather than on a timer: a deadline\n // stops the next piece of work, it does not interrupt one mid-flight.\n if (limits.deadline !== undefined && Date.now() >= Date.parse(limits.deadline)) {\n return { code: \"deadline\", message: `Stopped at the deadline of ${limits.deadline}.`, retryable: false };\n }\n return undefined;\n }\n\n // How many deliveries the next write takes off this session's own queue:\n // what the claim was carrying, and afterwards whatever `drain` folded in.\n // Cleared by the write that lands, because the input is gone once the\n // entries carrying it are durable, and not before.\n let take = claim?.pending.length ?? 0;\n\n async function commit(entries: readonly Entry[], deliveries: readonly Delivery[] = []): Promise<void> {\n if (!entries.length && !deliveries.length) return;\n // Counted before the write, not after: the tokens were consumed whether\n // or not this entry wins the compare-and-swap, and a run that reports\n // nothing after paying for a generation is the opposite of what\n // `RunResult.usage` promises.\n for (const entry of entries) {\n if ((entry.type === \"assistant\" || entry.type === \"model.finished\") && entry.usage) accumulate(usage, entry.usage);\n }\n\n if (store) {\n const written = await store.append({\n sessionId, expectedSeq: log.seq, entries,\n ...(deliveries.length ? { enqueue: deliveries } : {}),\n ...(take ? { takePending: take } : {}),\n });\n if (!written.ok) throw new CommitFailed(written.error, positionOf(written.error, log.seq));\n take = 0;\n }\n for (const stored of log.append(entries)) updates.push({ type: \"entry\", entry: stored });\n\n if (!stopped) {\n for (const entry of entries) {\n if (entry.type === \"assistant\") {\n const id = entry.generation?.id;\n // A provider may commit a completed asynchronous call before\n // the generation itself ends. It is recovery state, not another\n // turn and not yet the boundary at which a turn ceiling applies.\n if (!entry.generation || entry.generation.endedAt) {\n if (!id || !generations.has(id)) turns += 1;\n if (id) generations.add(id);\n }\n }\n // `tool.finished`, not `tool.started`: the start is committed before\n // the batch executes, so counting it there cancelled the very batch\n // that reached the ceiling — `maxToolCalls: 1` ran no tools at all,\n // and said it had stopped after one.\n if (entry.type === \"tool.finished\") toolCalls += 1;\n }\n stopped = exceeded();\n if (stopped) controller.abort();\n }\n }\n\n let inputWake = false;\n let wakePromise: Promise<void> | undefined;\n let resolveWake: (() => void) | undefined;\n const wake = () => {\n inputWake = true;\n resolveWake?.();\n resolveWake = undefined;\n wakePromise = undefined;\n };\n if (store?.watch) {\n unwatch = store.watch((change) => {\n if (change.sessionId !== sessionId || !change.runnable) return;\n wake();\n });\n }\n signal.addEventListener(\"abort\", wake);\n clearInputWait = () => signal.removeEventListener(\"abort\", wake);\n\n async function waitForInput(): Promise<void> {\n if (!store || signal.aborted) return;\n if (inputWake) { inputWake = false; return; }\n if (!store.watch) {\n await new Promise<void>((resolve) => setTimeout(resolve, 100));\n return;\n }\n wakePromise ??= new Promise<void>((resolve) => { resolveWake = resolve; });\n await wakePromise;\n inputWake = false;\n }\n\n // Input that arrived while this activation was running, taken from the\n // front of the queue and committed as part of it. `takePending` removes\n // exactly what was committed, in the same write, so losing the position\n // loses the turn and never the messages.\n async function drain(): Promise<number> {\n if (!store) return 0;\n // Nothing is folded into an activation that is over. Draining here\n // committed the waiting deliveries and took them off the queue, and the\n // loop then ended — leaving a peer's message answered by nobody and\n // invisible to `next` (nothing pending) and to `interrupted` (no open run),\n // which is the trap this whole path exists to close.\n if (signal.aborted) return 0;\n const current = await store.read({ sessionId, afterSeq: log.seq });\n if (!current.ok || !current.value.pending.length) return 0;\n // Only `turn` asks to join this activation. The queue is ordered and\n // consumption is a prefix, so a later delivery cannot jump over one\n // explicitly left for the next activation.\n const boundary = current.value.pending.findIndex((delivery) => delivery.priority !== \"turn\");\n const waiting = current.value.pending.slice(0, boundary < 0 ? current.value.pending.length : boundary);\n if (!waiting.length) return 0;\n take = waiting.length;\n await commit(waiting.map((delivery): Entry => ({\n type: \"run.started\", runId, input: delivery.input,\n ...(delivery.from ? { from: delivery.from } : {}),\n })));\n return waiting.length;\n }\n\n const executor = agent.tools?.length\n ? createExecutor({\n tools: agent.tools,\n ...(agent.decide ? { decide: agent.decide } : {}),\n sessionId, runId,\n report: (callId, data) => updates.push({ type: \"tool.progress\", callId, data }),\n })\n : undefined;\n\n if (!arrivals.length) {\n // An open run is what a resumption continues. Without one there is\n // nothing half-done here: a closed log would otherwise take a second\n // `run.finished` with no beginning to match it.\n if (!interrupted) {\n return stopping({\n code: \"nothing-to-resume\",\n message: \"An activation with no input continues an interrupted run, and this session has none open.\",\n retryable: false,\n });\n }\n if (agent.harness.recovery !== \"history\") {\n // Asked to continue a log this harness cannot read. The interrupted\n // run is ended rather than left open, because nothing else will\n // continue it either — the harness is a property of the session — and\n // a run that stays open is handed back by `interrupted` every window,\n // for ever. A worker that provisions anything before it runs pays for\n // that each time round.\n const failure: Failure = {\n code: \"no-recovery\",\n message: `The ${agent.harness.id} harness cannot restart from history, so this activation cannot be continued.`,\n retryable: false,\n };\n stopped = failure;\n }\n }\n\n // An interrupted predecessor is ended before a new activation begins over\n // it, so one session never holds two open runs. Only on a claim: the\n // store established there that nothing else is running, where a bare\n // `sessionId` establishes nothing and the run may still be live.\n if (arrivals.length && interrupted && claim) {\n await commit([{\n type: \"run.finished\", runId: interrupted, outcome: \"cancelled\",\n error: {\n code: \"superseded\",\n message: \"This activation was interrupted, and a later one began over it.\",\n retryable: false,\n },\n }]);\n }\n\n // Nothing opens a resumption. A `run.started` recording input nobody sent\n // would be a second beginning for one conversation; the loop reads the\n // history it was handed instead, sees the call that already ran, and\n // carries on rather than asking for it again.\n await commit(arrivals.map((arrival): Entry => ({\n type: \"run.started\", runId, input: arrival.input,\n ...(arrival.from ? { from: arrival.from } : {}),\n })));\n\n // Every ceiling is checked where work is recorded, and a resumption\n // records nothing before its first turn — so a deadline that had already\n // passed was never seen. Checked once here too, before the harness is\n // handed anything.\n stopped ??= exceeded();\n\n function makeContext(): HarnessContext {\n const supplied = options.context;\n const current = supplied ? {\n ...(supplied.run ? { run: supplied.run } : {}),\n get turn() {\n const value = supplied.turn;\n return typeof value === \"function\" ? value() : value;\n },\n } : undefined;\n return {\n sessionId, runId,\n instructions: agent.instructions,\n history: () => toMessages({\n instructions: agent.instructions,\n entries: log.entries,\n ...(agent.attribution ? { attribution: true } : {}),\n ...(current ? { context: current } : {}),\n }),\n entries: () => log.entries,\n ...(current ? { context: current } : {}),\n ...(executor ? { tools: executor } : {}),\n commit,\n ...(store ? { drain, waitForInput } : {}),\n emit: (update) => updates.push(update),\n signal, hooks,\n };\n }\n\n async function stoppingHooks(outcome: HarnessResult) {\n const inputs: Entry[] = [];\n const outgoing: Delivery[] = [];\n for (const hook of hooks) {\n const response = await hook.beforeStop?.(hookContext!, outcome);\n if (response && \"input\" in response && outcome.status === \"completed\" && !signal.aborted && !stopped &&\n !log.entries.some(entry => entry.type === \"hook.input\" && entry.runId === runId && entry.hook === hook.name)) {\n inputs.push({ type: \"hook.input\", runId, hook: hook.name, input: response.input });\n }\n if (response && \"deliveries\" in response) outgoing.push(...response.deliveries);\n }\n return { inputs, deliveries: outgoing };\n }\n\n hookContext = makeContext();\n let outcome: HarnessResult;\n let outgoing: readonly Delivery[] = [];\n try {\n for (const hook of hooks) await hook.beforeRun?.(hookContext);\n for (;;) {\n outcome = stopped ? { status: \"failed\", error: stopped }\n : signal.aborted ? { status: \"cancelled\" }\n : await agent.harness.run(hookContext);\n if (stopped) outcome = { status: \"failed\", error: stopped };\n else if (signal.aborted) outcome = { status: \"cancelled\" };\n const ending = await stoppingHooks(outcome);\n if (!ending.inputs.length) { outgoing = ending.deliveries; break; }\n await commit(ending.inputs);\n }\n } catch (error) {\n if (error instanceof CommitFailed) throw error;\n outcome = { status: \"failed\", error: {\n code: \"hook-or-harness\", message: error instanceof Error ? error.message : String(error), retryable: false,\n } };\n }\n\n // A harness stopped by the ceiling reports a cancellation, because that is\n // all it saw. The run knows why it was cancelled and says so instead.\n const settled = stopped && outcome.status === \"cancelled\"\n ? { status: \"failed\" as const, error: stopped }\n : outcome;\n\n await commit(\n [{\n type: \"run.finished\", runId,\n outcome: settled.status === \"completed\" ? \"completed\" : settled.status === \"cancelled\" ? \"cancelled\" : \"failed\",\n ...(settled.status === \"failed\" ? { error: settled.error } : {}),\n }],\n outgoing,\n );\n\n if (settled.status === \"completed\") {\n return result = { status: \"completed\", output: settled.output, seq: log.seq, usage };\n }\n if (settled.status === \"cancelled\") return result = { status: \"cancelled\", seq: log.seq, usage };\n return stopping(settled.error);\n } catch (error) {\n if (error instanceof CommitFailed) {\n return result = { status: \"failed\", error: error.failure, seq: error.seq, usage };\n }\n throw error;\n } finally {\n if (hookContext) {\n const final = result ?? { status: \"failed\" as const, error: {\n code: \"run-error\", message: \"The run could not finish.\", retryable: false,\n }, seq: hookContext.entries().at(-1)?.seq ?? 0, usage };\n for (const hook of hooks) {\n try { await hook.afterRun?.(hookContext, final); }\n catch (error) {\n updates.push({ type: \"hook.error\", hook: hook.name, message: error instanceof Error ? error.message : String(error) });\n }\n }\n }\n unwatch?.();\n clearInputWait?.();\n updates.close();\n }\n }\n}\n\nclass CommitFailed extends Error {\n constructor(readonly failure: Failure, readonly seq: number) {\n super(failure.message);\n }\n}\n\n/**\n * Where the session actually is after a refused write. A conflict knows; every\n * other failure leaves the caller with the position it already had. Reporting\n * zero told a caller at forty that it was at the beginning.\n *\n * The `typeof` is not defensive noise: a store may report a conflict, and only\n * a `StoreConflict` carries the position. Casting on the code alone produced a\n * `RunResult.seq` of `undefined` under a type that says `number`.\n */\nfunction positionOf(error: StoreError, fallback: number): number {\n const actual = (error as StoreConflict).actualSeq;\n return error.code === \"conflict\" && typeof actual === \"number\" ? actual : fallback;\n}\n\nconst isArrival = (value: unknown): value is Arrival =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && \"input\" in value;\n\n/**\n * One arrival, or several.\n *\n * The elements decide it, because the outer shape cannot: an arrival names its\n * `input`, a content part names its `type`, and nothing is both. Reading every\n * array as a batch is what turned one image-and-text message into one entry per\n * part, each holding a part where whole content belongs.\n */\nfunction arrivalsOf(input: RunAgentOptions[\"input\"]): readonly Arrival[] {\n if (input === undefined) return [];\n // Nothing sent is nothing sent. Falling through committed a `run.started`\n // whose input was an empty array of content parts.\n if (Array.isArray(input) && input.length === 0) return [];\n if (Array.isArray(input) && input.length > 0 && input.every(isArrival)) return input;\n if (isArrival(input)) return [input];\n return [{ input: input as Content }];\n}\n\n/**\n * The activation still open on this log, if one is.\n *\n * `run.started` opens and `run.finished` closes, which is the same rule the\n * store maintains its claim from — read here from the entries rather than asked\n * of the store, because the log is the only thing that knows.\n */\nfunction openRunId(entries: readonly Stored[]): string | undefined {\n let open: string | undefined;\n for (const entry of entries) {\n if (entry.type === \"run.started\") open = entry.runId;\n if (entry.type === \"run.finished\") open = undefined;\n }\n return open;\n}\n\n/** Token counts add; unknown stays unknown rather than becoming a zero. */\nfunction accumulate(total: Usage, turn: Usage): void {\n for (const key of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n if (turn[key] !== undefined) total[key] = (total[key] ?? 0) + turn[key]!;\n }\n}\n\nasync function open(store: Store, sessionId: string, agent: Agent, key?: string) {\n const existing = await store.read({ sessionId });\n if (existing.ok) {\n // `version` is documented as the boundary past which an agent is no longer\n // compatible with an existing session. Nothing was comparing it, so the\n // boundary held for exactly as long as nobody crossed it.\n const stored = existing.value.agent;\n if (stored.id !== agent.id || stored.version !== agent.version) {\n return err<StoreError>({\n code: \"conflict\",\n message: `Session ${sessionId} belongs to ${stored.id}@${stored.version}, not ${agent.id}@${agent.version}`,\n retryable: false,\n });\n }\n return existing;\n }\n if (existing.error.code !== \"not-found\") return existing;\n const created = await store.create({\n sessionId, agent: { id: agent.id, version: agent.version }, ...(key ? { key } : {}),\n });\n if (!created.ok) return created;\n return store.read({ sessionId });\n}\n\n/**\n * A bounded fan-out queue for ephemeral updates.\n *\n * One buffer of recent updates, which every listener starts from and which\n * never grows past its limit. That single rule gives three things:\n *\n * **A run nobody drains costs a fixed amount.** A headless worker used to\n * accumulate every delta of an entire activation, because the queue only ever\n * grew. Dropping the oldest is safe precisely because updates are not recovery\n * state and the committed log is.\n *\n * **Arriving late loses nothing that matters.** The first entry commits before\n * `runAgent` returns, so a caller that iterates immediately would otherwise\n * never see its own run start. A UI reconnecting mid-run gets recent history\n * for the same reason, without asking the store for it.\n *\n * **Everyone sees everything.** Each listener drains its own copy, so an\n * application can watch a run for telemetry and for a UI at once instead of the\n * two stealing events from each other.\n */\nfunction createChannel<T>(limit = 1_024) {\n interface Listener { buffer: T[]; wake?: () => void }\n const listeners = new Set<Listener>();\n const replay: T[] = [];\n let closed = false;\n\n const bounded = (buffer: T[], value: T) => {\n if (buffer.length >= limit) buffer.shift();\n buffer.push(value);\n };\n\n return {\n push(value: T) {\n bounded(replay, value);\n for (const listener of listeners) {\n bounded(listener.buffer, value);\n listener.wake?.();\n }\n },\n close() {\n closed = true;\n for (const listener of listeners) listener.wake?.();\n },\n iterator(): AsyncIterator<T> {\n const listener: Listener = { buffer: [...replay] };\n listeners.add(listener);\n const done = (): IteratorResult<T> => {\n listeners.delete(listener);\n return { value: undefined, done: true };\n };\n return {\n async next(): Promise<IteratorResult<T>> {\n for (;;) {\n const value = listener.buffer.shift();\n if (value !== undefined) return { value, done: false };\n if (closed) return done();\n await new Promise<void>((resolve) => { listener.wake = resolve; });\n }\n },\n async return(): Promise<IteratorResult<T>> { return done(); },\n };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"run.js","sourceRoot":"","sources":["../src/run.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,UAAU,QAAQ,CAAC,OAAwB;IAC/C,6EAA6E;IAC7E,MAAM,KAAK,GAAG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oBACR,SAAS,CAAC;wBACR,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;wBACtC,IAAI,KAAK,KAAK,SAAS;4BAAE,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;wBACvD,IAAI,MAAM;4BAAE,OAAO,IAAI,EAAE,CAAC;wBAC1B,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,GAAG,QAAQ,CAAC,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;oBACrE,CAAC;gBACH,CAAC;gBACD,KAAK,CAAC,MAAM,KAAiC,OAAO,IAAI,EAAE,CAAC,CAAC,CAAC;aAC9D,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Agent, AgentRun, Arrival, RunAgentOptions, RunResult } from \"./agent.js\";\nimport type { Failure } from \"./result.js\";\nimport type { HarnessContext, HarnessResult, Update } from \"./harness/harness.js\";\nimport type { Delivery, Store, StoreConflict, StoreError } from \"./store/store.js\";\nimport type { Content } from \"./content.js\";\nimport type { Entry, Stored, Usage } from \"./session/entry.js\";\nimport { err } from \"./result.js\";\nimport { createLog } from \"./session/log.js\";\nimport { toMessages } from \"./session/messages.js\";\nimport { createExecutor } from \"./tools/execute.js\";\n\n/**\n * Start an agent on a session.\n *\n * Without a store the log lives in memory and the session is ephemeral; with\n * one, every commit is durable before the next turn is built. The agent\n * definition is identical either way — durability is a composition choice, not\n * a different program.\n */\nexport function runAgent(options: RunAgentOptions): AgentRun {\n // A claim names its own session; a caller sending into a new one names none.\n const hooks = options.agent.hooks ?? [];\n if (new Set(hooks.map(hook => hook.name)).size !== hooks.length || hooks.some(hook => !hook.name)) {\n throw new Error(\"Lifecycle hook names must be non-empty and unique.\");\n }\n const claim = options.claim;\n const sessionId = claim?.sessionId ?? options.sessionId ?? crypto.randomUUID();\n const controller = new AbortController();\n // Composed rather than forwarded. `addEventListener(\"abort\", …)` never fires\n // on a signal that has already aborted, so a caller who gave up before\n // calling got a full run anyway; and a listener added per run to a signal\n // that outlives it is a leak the run cannot clean up.\n const signal = options.signal\n ? AbortSignal.any([options.signal, controller.signal])\n : controller.signal;\n\n const updates = createChannel<Update>();\n const result = execute();\n\n return {\n result,\n cancel: () => controller.abort(),\n [Symbol.asyncIterator]: () => updates.iterator(),\n };\n\n async function execute(): Promise<RunResult> {\n // What this activation consumed. Summed from the model usage entries it\n // commits rather than reported by the harness, so one answer serves a loop\n // we own and a loop we do not — and so a run that failed still says what it\n // burned on the way there.\n const usage: Usage = {};\n let hookContext: HarnessContext | undefined;\n let result: RunResult | undefined;\n let unwatch: (() => void) | undefined;\n let clearInputWait: (() => void) | undefined;\n let renewal: ReturnType<typeof setInterval> | undefined;\n let lost: Failure | undefined;\n\n try {\n const { agent, store } = options;\n // A claimed run keeps its claim while its model or a tool is quiet, and\n // stops the moment the claim is gone: whoever holds it now owns the\n // session, and nothing this run does next would be its to do.\n const renew = async (): Promise<Failure | undefined> => {\n if (!claim || !store || lost) return lost;\n const renewed = await store.renew({ sessionId, claimId: claim.claimId });\n if (!renewed.ok) { lost = renewed.error; controller.abort(); }\n return lost;\n };\n if (claim && store) {\n if (await renew()) return { status: \"failed\", error: lost!, seq: claim.seq, usage };\n let renewing = false;\n renewal = setInterval(() => {\n if (renewing) return;\n renewing = true;\n void renew()\n .catch((error: unknown) => { lost = { code: \"unavailable\", message: String(error), retryable: false }; controller.abort(); })\n .finally(() => { renewing = false; });\n }, claim.renewAfterMs);\n }\n const restored = store ? await open(store, sessionId, agent, options.key) : undefined;\n if (restored && !restored.ok) {\n return {\n status: \"failed\", error: restored.error,\n seq: positionOf(restored.error, 0), usage,\n };\n }\n // The store's own position, not the last entry's. They agree only while\n // nothing has ever been folded away, and the store is the one that knows.\n const log = createLog(restored?.value.entries ?? [], restored?.value.seq ?? 0);\n const stopping = (error: Failure): RunResult => (result = { status: \"failed\", error, seq: log.seq, usage });\n\n // A claim was read at a position. If the session has moved since, this\n // worker lost, and the deliveries it was carrying are still where it\n // found them.\n if (claim && claim.seq !== log.seq) {\n return stopping({ code: \"conflict\", message: `Session is at ${log.seq}, not ${claim.seq}`, retryable: true });\n }\n\n // A ceiling on money needs something that can count it. Refused here\n // rather than silently ignored, because a limit that is declared and not\n // enforced is the most expensive kind of nothing.\n\n // The activation still open on this log, if one is. It decides three\n // things below: whether there is anything to resume, which run a\n // resumption continues, and which run a fresh activation supersedes.\n const interrupted = openRunId(log.entries);\n\n // What this run is adding, then what was waiting. A claim's deliveries\n // are named so the log records who each came from; anything the worker\n // supplies itself leads, because the only thing that ever does is\n // orientation for a harness with nowhere else to put it.\n const arrivals: readonly Arrival[] = [\n ...arrivalsOf(options.input),\n ...(claim?.pending ?? []).map((delivery): Arrival => ({\n input: delivery.input,\n ...(delivery.from ? { from: delivery.from } : {}),\n })),\n ];\n\n // A resumption continues the run it was handed, under that run's id. A\n // fresh id would leave the log holding a `run.started` nothing closes and\n // a `run.finished` nothing opened — a pair that only the store's\n // type-based rule saves, and that anything grouping entries by run reads\n // as broken. A resumption without an interrupted run is refused below.\n const runId = arrivals.length || !interrupted ? crypto.randomUUID() : interrupted;\n\n // The ceiling has one owner, and it is here rather than in a harness.\n // Counting committed entries is the only way to bound a harness that owns\n // its own loop — which is most of them — so a limit declared on the agent\n // holds for every one instead of only for ours.\n const limits = agent.limits;\n let stopped: Failure | undefined;\n let turns = 0;\n let toolCalls = 0;\n const generations = new Set<string>();\n\n function exceeded(): Failure | undefined {\n if (!limits) return undefined;\n if (limits.maxTurns !== undefined && turns >= limits.maxTurns) {\n return { code: \"turn-limit\", message: `Stopped after ${turns} turns.`, retryable: false };\n }\n if (limits.maxToolCalls !== undefined && toolCalls >= limits.maxToolCalls) {\n return { code: \"tool-call-limit\", message: `Stopped after ${toolCalls} tool calls.`, retryable: false };\n }\n // Checked where work is recorded rather than on a timer: a deadline\n // stops the next piece of work, it does not interrupt one mid-flight.\n if (limits.deadline !== undefined && Date.now() >= Date.parse(limits.deadline)) {\n return { code: \"deadline\", message: `Stopped at the deadline of ${limits.deadline}.`, retryable: false };\n }\n return undefined;\n }\n\n // How many deliveries the next write takes off this session's own queue:\n // what the claim was carrying, and afterwards whatever `drain` folded in.\n // Cleared by the write that lands, because the input is gone once the\n // entries carrying it are durable, and not before.\n let take = claim?.pending.length ?? 0;\n\n async function commit(entries: readonly Entry[], deliveries: readonly Delivery[] = []): Promise<void> {\n if (!entries.length && !deliveries.length) return;\n // Counted before the write, not after: the tokens were consumed whether\n // or not this entry wins the compare-and-swap, and a run that reports\n // nothing after paying for a generation is the opposite of what\n // `RunResult.usage` promises.\n for (const entry of entries) {\n if ((entry.type === \"assistant\" || entry.type === \"model.finished\") && entry.usage) accumulate(usage, entry.usage);\n }\n\n if (store) {\n const written = await store.append({\n sessionId, expectedSeq: log.seq, entries,\n ...(claim ? { claimId: claim.claimId } : {}),\n ...(deliveries.length ? { enqueue: deliveries } : {}),\n ...(take ? { takePending: take } : {}),\n });\n if (!written.ok) throw new CommitFailed(written.error, positionOf(written.error, log.seq));\n take = 0;\n }\n for (const stored of log.append(entries)) updates.push({ type: \"entry\", entry: stored });\n\n if (!stopped) {\n for (const entry of entries) {\n if (entry.type === \"assistant\") {\n const id = entry.generation?.id;\n // A provider may commit a completed asynchronous call before\n // the generation itself ends. It is recovery state, not another\n // turn and not yet the boundary at which a turn ceiling applies.\n if (!entry.generation || entry.generation.endedAt) {\n if (!id || !generations.has(id)) turns += 1;\n if (id) generations.add(id);\n }\n }\n // `tool.finished`, not `tool.started`: the start is committed before\n // the batch executes, so counting it there cancelled the very batch\n // that reached the ceiling — `maxToolCalls: 1` ran no tools at all,\n // and said it had stopped after one.\n if (entry.type === \"tool.finished\") toolCalls += 1;\n }\n stopped = exceeded();\n if (stopped) controller.abort();\n }\n }\n\n let inputWake = false;\n let wakePromise: Promise<void> | undefined;\n let resolveWake: (() => void) | undefined;\n const wake = () => {\n inputWake = true;\n resolveWake?.();\n resolveWake = undefined;\n wakePromise = undefined;\n };\n if (store?.watch) {\n unwatch = store.watch((change) => {\n if (change.sessionId !== sessionId || !change.runnable) return;\n wake();\n });\n }\n signal.addEventListener(\"abort\", wake);\n clearInputWait = () => signal.removeEventListener(\"abort\", wake);\n\n async function waitForInput(): Promise<void> {\n if (!store || signal.aborted) return;\n if (inputWake) { inputWake = false; return; }\n if (!store.watch) {\n await new Promise<void>((resolve) => setTimeout(resolve, 100));\n return;\n }\n wakePromise ??= new Promise<void>((resolve) => { resolveWake = resolve; });\n await wakePromise;\n inputWake = false;\n }\n\n // Input that arrived while this activation was running, taken from the\n // front of the queue and committed as part of it. `takePending` removes\n // exactly what was committed, in the same write, so losing the position\n // loses the turn and never the messages.\n async function drain(): Promise<number> {\n if (!store) return 0;\n // Nothing is folded into an activation that is over. Draining here\n // committed the waiting deliveries and took them off the queue, and the\n // loop then ended — leaving a peer's message answered by nobody and\n // invisible to `next` (nothing pending) and to `interrupted` (no open run),\n // which is the trap this whole path exists to close.\n if (signal.aborted) return 0;\n const current = await store.read({ sessionId, afterSeq: log.seq });\n if (!current.ok || !current.value.pending.length) return 0;\n // Only `turn` asks to join this activation. The queue is ordered and\n // consumption is a prefix, so a later delivery cannot jump over one\n // explicitly left for the next activation.\n const boundary = current.value.pending.findIndex((delivery) => delivery.priority !== \"turn\");\n const waiting = current.value.pending.slice(0, boundary < 0 ? current.value.pending.length : boundary);\n if (!waiting.length) return 0;\n take = waiting.length;\n await commit(waiting.map((delivery): Entry => ({\n type: \"run.started\", runId, input: delivery.input,\n ...(delivery.from ? { from: delivery.from } : {}),\n })));\n return waiting.length;\n }\n\n const executor = agent.tools?.length\n ? createExecutor({\n tools: agent.tools,\n // A tool's effect is the thing a lost claim cannot take back, so a\n // claimed run checks it still owns the session before admitting one\n // — and again after the policy, which may itself have waited.\n ...(claim ? { decide: async (call: Parameters<NonNullable<typeof agent.decide>>[0]) => {\n const before = await renew();\n if (before) return { action: \"reject\" as const, message: before.message };\n const decision = agent.decide ? await agent.decide(call) : { action: \"execute\" as const };\n const after = await renew();\n return after ? { action: \"reject\" as const, message: after.message } : decision;\n } } : agent.decide ? { decide: agent.decide } : {}),\n sessionId, runId,\n report: (callId, data) => updates.push({ type: \"tool.progress\", callId, data }),\n })\n : undefined;\n\n if (!arrivals.length) {\n // An open run is what a resumption continues. Without one there is\n // nothing half-done here: a closed log would otherwise take a second\n // `run.finished` with no beginning to match it.\n if (!interrupted) {\n return stopping({\n code: \"nothing-to-resume\",\n message: \"An activation with no input continues an interrupted run, and this session has none open.\",\n retryable: false,\n });\n }\n if (agent.harness.recovery !== \"history\") {\n // Asked to continue a log this harness cannot read. The interrupted\n // run is ended rather than left open, because nothing else will\n // continue it either — the harness is a property of the session — and\n // a run that stays open is handed back by `interrupted` every window,\n // for ever. A worker that provisions anything before it runs pays for\n // that each time round.\n const failure: Failure = {\n code: \"no-recovery\",\n message: `The ${agent.harness.id} harness cannot restart from history, so this activation cannot be continued.`,\n retryable: false,\n };\n stopped = failure;\n }\n }\n\n // An interrupted predecessor is ended before a new activation begins over\n // it, so one session never holds two open runs. Only on a claim: the\n // store established there that nothing else is running, where a bare\n // `sessionId` establishes nothing and the run may still be live.\n //\n // Nothing opens a resumption. A `run.started` recording input nobody sent\n // would be a second beginning for one conversation; the loop reads the\n // history it was handed instead, sees the call that already ran, and\n // carries on rather than asking for it again.\n //\n // One commit for both: closing the predecessor in a write of its own\n // released the claim between the two, and another worker could take the\n // session in that gap.\n const opening: Entry[] = arrivals.map((arrival): Entry => ({\n type: \"run.started\", runId, input: arrival.input,\n ...(arrival.from ? { from: arrival.from } : {}),\n }));\n if (opening.length && interrupted && claim) {\n opening.unshift({\n type: \"run.finished\", runId: interrupted, outcome: \"cancelled\",\n error: {\n code: \"superseded\",\n message: \"This activation was interrupted, and a later one began over it.\",\n retryable: false,\n },\n });\n }\n await commit(opening);\n\n // Every ceiling is checked where work is recorded, and a resumption\n // records nothing before its first turn — so a deadline that had already\n // passed was never seen. Checked once here too, before the harness is\n // handed anything.\n stopped ??= exceeded();\n\n function makeContext(): HarnessContext {\n const supplied = options.context;\n const current = supplied ? {\n ...(supplied.run ? { run: supplied.run } : {}),\n get turn() {\n const value = supplied.turn;\n return typeof value === \"function\" ? value() : value;\n },\n } : undefined;\n return {\n sessionId, runId,\n instructions: agent.instructions,\n history: () => toMessages({\n instructions: agent.instructions,\n entries: log.entries,\n ...(agent.attribution ? { attribution: true } : {}),\n ...(current ? { context: current } : {}),\n }),\n entries: () => log.entries,\n ...(current ? { context: current } : {}),\n ...(executor ? { tools: executor } : {}),\n commit,\n ...(store ? { drain, waitForInput } : {}),\n emit: (update) => updates.push(update),\n signal, hooks,\n };\n }\n\n async function stoppingHooks(outcome: HarnessResult) {\n const inputs: Entry[] = [];\n const outgoing: Delivery[] = [];\n for (const hook of hooks) {\n const response = await hook.beforeStop?.(hookContext!, outcome);\n if (response && \"input\" in response && outcome.status === \"completed\" && !signal.aborted && !stopped &&\n !log.entries.some(entry => entry.type === \"hook.input\" && entry.runId === runId && entry.hook === hook.name)) {\n inputs.push({ type: \"hook.input\", runId, hook: hook.name, input: response.input });\n }\n if (response && \"deliveries\" in response) outgoing.push(...response.deliveries);\n }\n return { inputs, deliveries: outgoing };\n }\n\n hookContext = makeContext();\n let outcome: HarnessResult;\n let outgoing: readonly Delivery[] = [];\n try {\n for (const hook of hooks) await hook.beforeRun?.(hookContext);\n for (;;) {\n outcome = stopped ? { status: \"failed\", error: stopped }\n : signal.aborted ? { status: \"cancelled\" }\n : await agent.harness.run(hookContext);\n if (stopped) outcome = { status: \"failed\", error: stopped };\n else if (signal.aborted) outcome = { status: \"cancelled\" };\n const ending = await stoppingHooks(outcome);\n if (!ending.inputs.length) { outgoing = ending.deliveries; break; }\n await commit(ending.inputs);\n }\n } catch (error) {\n if (error instanceof CommitFailed) throw error;\n outcome = { status: \"failed\", error: {\n code: \"hook-or-harness\", message: error instanceof Error ? error.message : String(error), retryable: false,\n } };\n }\n\n // A harness stopped by the ceiling reports a cancellation, because that is\n // all it saw. The run knows why it was cancelled and says so instead.\n const settled = stopped && outcome.status === \"cancelled\"\n ? { status: \"failed\" as const, error: stopped }\n : outcome;\n if (renewal) clearInterval(renewal);\n\n await commit(\n [{\n type: \"run.finished\", runId,\n outcome: settled.status === \"completed\" ? \"completed\" : settled.status === \"cancelled\" ? \"cancelled\" : \"failed\",\n ...(settled.status === \"failed\" ? { error: settled.error } : {}),\n }],\n outgoing,\n );\n\n if (settled.status === \"completed\") {\n return result = { status: \"completed\", output: settled.output, seq: log.seq, usage };\n }\n if (settled.status === \"cancelled\") return result = { status: \"cancelled\", seq: log.seq, usage };\n return stopping(settled.error);\n } catch (error) {\n if (error instanceof CommitFailed) {\n return result = { status: \"failed\", error: error.failure, seq: error.seq, usage };\n }\n throw error;\n } finally {\n if (hookContext) {\n const final = result ?? { status: \"failed\" as const, error: {\n code: \"run-error\", message: \"The run could not finish.\", retryable: false,\n }, seq: hookContext.entries().at(-1)?.seq ?? 0, usage };\n for (const hook of hooks) {\n try { await hook.afterRun?.(hookContext, final); }\n catch (error) {\n updates.push({ type: \"hook.error\", hook: hook.name, message: error instanceof Error ? error.message : String(error) });\n }\n }\n }\n if (renewal) clearInterval(renewal);\n unwatch?.();\n clearInputWait?.();\n updates.close();\n }\n }\n}\n\nclass CommitFailed extends Error {\n constructor(readonly failure: Failure, readonly seq: number) {\n super(failure.message);\n }\n}\n\n/**\n * Where the session actually is after a refused write. A conflict knows; every\n * other failure leaves the caller with the position it already had. Reporting\n * zero told a caller at forty that it was at the beginning.\n *\n * The `typeof` is not defensive noise: a store may report a conflict, and only\n * a `StoreConflict` carries the position. Casting on the code alone produced a\n * `RunResult.seq` of `undefined` under a type that says `number`.\n */\nfunction positionOf(error: StoreError, fallback: number): number {\n const actual = (error as StoreConflict).actualSeq;\n return error.code === \"conflict\" && typeof actual === \"number\" ? actual : fallback;\n}\n\nconst isArrival = (value: unknown): value is Arrival =>\n typeof value === \"object\" && value !== null && !Array.isArray(value) && \"input\" in value;\n\n/**\n * One arrival, or several.\n *\n * The elements decide it, because the outer shape cannot: an arrival names its\n * `input`, a content part names its `type`, and nothing is both. Reading every\n * array as a batch is what turned one image-and-text message into one entry per\n * part, each holding a part where whole content belongs.\n */\nfunction arrivalsOf(input: RunAgentOptions[\"input\"]): readonly Arrival[] {\n if (input === undefined) return [];\n // Nothing sent is nothing sent. Falling through committed a `run.started`\n // whose input was an empty array of content parts.\n if (Array.isArray(input) && input.length === 0) return [];\n if (Array.isArray(input) && input.length > 0 && input.every(isArrival)) return input;\n if (isArrival(input)) return [input];\n return [{ input: input as Content }];\n}\n\n/**\n * The activation still open on this log, if one is.\n *\n * `run.started` opens and `run.finished` closes, which is the same rule the\n * store maintains its claim from — read here from the entries rather than asked\n * of the store, because the log is the only thing that knows.\n */\nfunction openRunId(entries: readonly Stored[]): string | undefined {\n let open: string | undefined;\n for (const entry of entries) {\n if (entry.type === \"run.started\") open = entry.runId;\n if (entry.type === \"run.finished\") open = undefined;\n }\n return open;\n}\n\n/** Token counts add; unknown stays unknown rather than becoming a zero. */\nfunction accumulate(total: Usage, turn: Usage): void {\n for (const key of [\"inputTokens\", \"outputTokens\", \"cacheReadTokens\", \"cacheWriteTokens\", \"costUsd\"] as const) {\n if (turn[key] !== undefined) total[key] = (total[key] ?? 0) + turn[key]!;\n }\n}\n\nasync function open(store: Store, sessionId: string, agent: Agent, key?: string) {\n const existing = await store.read({ sessionId });\n if (existing.ok) {\n // `version` is documented as the boundary past which an agent is no longer\n // compatible with an existing session. Nothing was comparing it, so the\n // boundary held for exactly as long as nobody crossed it.\n const stored = existing.value.agent;\n if (stored.id !== agent.id || stored.version !== agent.version) {\n return err<StoreError>({\n code: \"conflict\",\n message: `Session ${sessionId} belongs to ${stored.id}@${stored.version}, not ${agent.id}@${agent.version}`,\n retryable: false,\n });\n }\n return existing;\n }\n if (existing.error.code !== \"not-found\") return existing;\n const created = await store.create({\n sessionId, agent: { id: agent.id, version: agent.version }, ...(key ? { key } : {}),\n });\n if (!created.ok) return created;\n return store.read({ sessionId });\n}\n\n/**\n * A bounded fan-out queue for ephemeral updates.\n *\n * One buffer of recent updates, which every listener starts from and which\n * never grows past its limit. That single rule gives three things:\n *\n * **A run nobody drains costs a fixed amount.** A headless worker used to\n * accumulate every delta of an entire activation, because the queue only ever\n * grew. Dropping the oldest is safe precisely because updates are not recovery\n * state and the committed log is.\n *\n * **Arriving late loses nothing that matters.** The first entry commits before\n * `runAgent` returns, so a caller that iterates immediately would otherwise\n * never see its own run start. A UI reconnecting mid-run gets recent history\n * for the same reason, without asking the store for it.\n *\n * **Everyone sees everything.** Each listener drains its own copy, so an\n * application can watch a run for telemetry and for a UI at once instead of the\n * two stealing events from each other.\n */\nfunction createChannel<T>(limit = 1_024) {\n interface Listener { buffer: T[]; wake?: () => void }\n const listeners = new Set<Listener>();\n const replay: T[] = [];\n let closed = false;\n\n const bounded = (buffer: T[], value: T) => {\n if (buffer.length >= limit) buffer.shift();\n buffer.push(value);\n };\n\n return {\n push(value: T) {\n bounded(replay, value);\n for (const listener of listeners) {\n bounded(listener.buffer, value);\n listener.wake?.();\n }\n },\n close() {\n closed = true;\n for (const listener of listeners) listener.wake?.();\n },\n iterator(): AsyncIterator<T> {\n const listener: Listener = { buffer: [...replay] };\n listeners.add(listener);\n const done = (): IteratorResult<T> => {\n listeners.delete(listener);\n return { value: undefined, done: true };\n };\n return {\n async next(): Promise<IteratorResult<T>> {\n for (;;) {\n const value = listener.buffer.shift();\n if (value !== undefined) return { value, done: false };\n if (closed) return done();\n await new Promise<void>((resolve) => { listener.wake = resolve; });\n }\n },\n async return(): Promise<IteratorResult<T>> { return done(); },\n };\n },\n };\n}\n"]}
@@ -9,6 +9,7 @@ const tables = `
9
9
  pending TEXT NOT NULL DEFAULT '[]',
10
10
  last_seq INTEGER NOT NULL DEFAULT 0,
11
11
  running_since TEXT,
12
+ claim_id TEXT,
12
13
  updated_at TEXT NOT NULL
13
14
  );
14
15
  CREATE TABLE IF NOT EXISTS entries (
@@ -37,6 +38,7 @@ const tables = `
37
38
  */
38
39
  const added = [
39
40
  { table: "sessions", column: "running_since", type: "TEXT" },
41
+ { table: "sessions", column: "claim_id", type: "TEXT" },
40
42
  ];
41
43
  const indexes = `
42
44
  CREATE INDEX IF NOT EXISTS sessions_by_key ON sessions (key, updated_at DESC, id DESC);
@@ -72,6 +74,9 @@ const DEFAULT_DELIVERY_MEMORY_MS = 7 * 24 * 60 * 60 * 1000;
72
74
  export function createSqliteStore(input) {
73
75
  const database = input.database;
74
76
  const claimMs = input.claimMs ?? DEFAULT_CLAIM_MS;
77
+ /** A third of the window: two renewals can be missed before a live owner looks dead. */
78
+ const renewAfterMs = Math.max(1, Math.floor(claimMs / 3));
79
+ const owns = (row, claimId) => row.claim_id === claimId && !!row.running_since && Date.parse(row.running_since) + claimMs > Date.now();
75
80
  const deliveryMemoryMs = input.deliveryMemoryMs ?? DEFAULT_DELIVERY_MEMORY_MS;
76
81
  // Tables, then the columns an older build's tables lack, then the indexes —
77
82
  // which is the only order that works, because an index may be over a column
@@ -163,7 +168,7 @@ export function createSqliteStore(input) {
163
168
  * the queue is consumed here rather than in `next`, a loser leaves the
164
169
  * messages it was carrying untouched.
165
170
  */
166
- async append({ sessionId, expectedSeq, entries, enqueue, metadata, takePending }) {
171
+ async append({ sessionId, expectedSeq, claimId, entries, enqueue, metadata, takePending }) {
167
172
  const at = new Date().toISOString();
168
173
  try {
169
174
  // Inside the try: on a busy database this is where the failure lands,
@@ -174,6 +179,12 @@ export function createSqliteStore(input) {
174
179
  database.exec("ROLLBACK");
175
180
  return err(notFound(sessionId));
176
181
  }
182
+ // Ownership before position: a writer whose claim lapsed and passed on
183
+ // can still be at the right sequence, if nothing committed in between.
184
+ if (claimId !== undefined && !owns(session, claimId)) {
185
+ database.exec("ROLLBACK");
186
+ return err({ code: "conflict", message: "Session ownership expired or changed", retryable: false });
187
+ }
177
188
  if (session.last_seq !== expectedSeq) {
178
189
  database.exec("ROLLBACK");
179
190
  return err({
@@ -188,8 +199,6 @@ export function createSqliteStore(input) {
188
199
  // ends it. `next` reads this to keep a second one from beginning, and
189
200
  // the log is the only thing that knows — so it is derived from the log
190
201
  // rather than asserted by a caller.
191
- const opens = entries.some((entry) => entry.type === "run.started");
192
- const closes = entries.some((entry) => entry.type === "run.finished");
193
202
  // Only a write that records work renews the claim. Renewing on any
194
203
  // append at all meant a message *to* a session renewed the claim of the
195
204
  // worker that was supposed to read it — so a dead worker's session
@@ -203,7 +212,11 @@ export function createSqliteStore(input) {
203
212
  // longer than the claim window was handed to a second worker while it
204
213
  // was still going — and a compare-and-swap cannot un-run a tool call.
205
214
  // A worker that dies still releases, because a dead worker stops writing.
206
- const runningSince = closes ? null : (opens || (worked && session.running_since)) ? at : session.running_since;
215
+ // The last lifecycle entry decides, so one write that closes an
216
+ // interrupted run and opens its successor leaves the session open.
217
+ const lifecycle = entries.findLast((entry) => entry.type === "run.started" || entry.type === "run.finished");
218
+ const runningSince = lifecycle?.type === "run.finished" ? null
219
+ : lifecycle?.type === "run.started" || (worked && session.running_since) ? at : session.running_since;
207
220
  const merged = metadata
208
221
  ? JSON.stringify({ ...JSON.parse(session.metadata), ...metadata })
209
222
  : session.metadata;
@@ -256,6 +269,8 @@ export function createSqliteStore(input) {
256
269
  run(`UPDATE sessions SET pending = ?, updated_at = ? WHERE id = ?`, [JSON.stringify([...queueOf(target), delivery]), at, delivery.sessionId]);
257
270
  delivered.add(delivery.sessionId);
258
271
  }
272
+ if (!runningSince)
273
+ run(`UPDATE sessions SET claim_id = NULL WHERE id = ?`, [sessionId]);
259
274
  database.exec("COMMIT");
260
275
  // After the commit, never before: a watcher that looked on an earlier
261
276
  // wake would find nothing and never be told again.
@@ -293,6 +308,23 @@ export function createSqliteStore(input) {
293
308
  return err(failed(error));
294
309
  }
295
310
  },
311
+ async renew({ sessionId, claimId }) {
312
+ try {
313
+ database.exec("BEGIN IMMEDIATE");
314
+ const row = one(`SELECT * FROM sessions WHERE id = ?`, [sessionId]);
315
+ if (!row || !owns(row, claimId)) {
316
+ database.exec("ROLLBACK");
317
+ return err({ code: "conflict", message: "Session ownership expired or changed", retryable: false });
318
+ }
319
+ run(`UPDATE sessions SET running_since = ? WHERE id = ?`, [new Date().toISOString(), sessionId]);
320
+ database.exec("COMMIT");
321
+ return ok(undefined);
322
+ }
323
+ catch (error) {
324
+ database.exec("ROLLBACK");
325
+ return err(failed(error));
326
+ }
327
+ },
296
328
  /**
297
329
  * Claim a session that has input and no activation already running.
298
330
  *
@@ -316,9 +348,11 @@ export function createSqliteStore(input) {
316
348
  database.exec("COMMIT");
317
349
  return ok(undefined);
318
350
  }
319
- run(`UPDATE sessions SET running_since = ? WHERE id = ?`, [new Date(now).toISOString(), row.id]);
351
+ const claimId = crypto.randomUUID();
352
+ run(`UPDATE sessions SET running_since = ?, claim_id = ? WHERE id = ?`, [new Date(now).toISOString(), claimId, row.id]);
320
353
  database.exec("COMMIT");
321
354
  return ok({
355
+ claimId, renewAfterMs,
322
356
  sessionId: row.id,
323
357
  seq: row.last_seq,
324
358
  pending: queueOf(row),
@@ -354,9 +388,11 @@ export function createSqliteStore(input) {
354
388
  database.exec("COMMIT");
355
389
  return ok(undefined);
356
390
  }
357
- run(`UPDATE sessions SET running_since = ? WHERE id = ?`, [new Date(now).toISOString(), row.id]);
391
+ const claimId = crypto.randomUUID();
392
+ run(`UPDATE sessions SET running_since = ?, claim_id = ? WHERE id = ?`, [new Date(now).toISOString(), claimId, row.id]);
358
393
  database.exec("COMMIT");
359
394
  return ok({
395
+ claimId, renewAfterMs,
360
396
  sessionId: row.id,
361
397
  seq: row.last_seq,
362
398
  pending: [],
@@ -1 +1 @@
1
- {"version":3,"file":"sqlite.js","sourceRoot":"","sources":["../../../src/store/adapters/sqlite.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,iBAAiB,CAAC;AAa1C,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;CA0Bd,C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ourcesContent":["import type {\n Store, StoreChange, StoreError, StoreConflict, SessionRead, SessionSummary, Runnable,\n} from \"../store.js\";\nimport type { Delivery, Entry, Stored } from \"../../session/entry.js\";\nimport type { JsonValue } from \"../../json.js\";\nimport { err, ok } from \"../../result.js\";\n\n/**\n * The minimum a driver must provide. Declared here rather than importing one so\n * the same file serves `node:sqlite` and `bun:sqlite`, and so an application can\n * hand in a database it already opened — which is what lets its own tables live\n * beside the log and join against it.\n */\nexport interface SqliteDatabase {\n exec(sql: string): void;\n query(sql: string): { all(...parameters: unknown[]): unknown[]; run(...parameters: unknown[]): unknown };\n}\n\nconst tables = `\n CREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n agent_ver TEXT NOT NULL,\n key TEXT,\n metadata TEXT NOT NULL DEFAULT '{}',\n pending TEXT NOT NULL DEFAULT '[]',\n last_seq INTEGER NOT NULL DEFAULT 0,\n running_since TEXT,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS entries (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n at TEXT NOT NULL,\n body TEXT NOT NULL,\n PRIMARY KEY (session_id, seq)\n );\n CREATE TABLE IF NOT EXISTS deliveries (\n session_id TEXT NOT NULL,\n sender TEXT NOT NULL,\n delivery_id TEXT NOT NULL,\n at TEXT NOT NULL,\n PRIMARY KEY (session_id, sender, delivery_id)\n );\n`;\n\n/**\n * Columns added after a table had already shipped.\n *\n * `CREATE TABLE IF NOT EXISTS` is a no-op against a table that exists, so a\n * column added later never appears in a database made by an older build — and\n * the first index over it fails with a raw `SQLiteError` from inside `bun:sqlite`,\n * which is no way to meet a store whose whole promise is that the log survives.\n * Additive only: a column is added, nothing is dropped, rewritten or lost.\n */\nconst added: readonly { table: string; column: string; type: string }[] = [\n { table: \"sessions\", column: \"running_since\", type: \"TEXT\" },\n];\n\nconst indexes = `\n CREATE INDEX IF NOT EXISTS sessions_by_key ON sessions (key, updated_at DESC, id DESC);\n CREATE INDEX IF NOT EXISTS sessions_runnable ON sessions (updated_at) WHERE pending <> '[]';\n DROP INDEX IF EXISTS sessions_stranded; -- sessions_interrupted under its former name\n CREATE INDEX IF NOT EXISTS sessions_interrupted ON sessions (updated_at) WHERE running_since IS NOT NULL;\n CREATE INDEX IF NOT EXISTS deliveries_by_age ON deliveries (at);\n`;\n\ninterface SessionRow {\n id: string; agent_id: string; agent_ver: string; key: string | null;\n metadata: string; pending: string; last_seq: number; running_since: string | null; updated_at: string;\n}\n\n/** `updatedAt` and the session id, so a page boundary is a point and not an instant. */\nconst splitCursor = (cursor: string): [string, string] => {\n const cut = cursor.lastIndexOf(\"|\");\n return cut < 0 ? [cursor, \"\"] : [cursor.slice(0, cut), cursor.slice(cut + 1)];\n};\n\n/**\n * How long a claim holds before another worker may take the session.\n *\n * Long enough that an ordinary turn finishes inside it, short enough that a\n * worker killed mid-turn does not strand its session for an afternoon. If the\n * original worker is somehow still alive when it expires, its writes fail the\n * compare-and-swap, so the window governs wasted work and never correctness.\n */\nconst DEFAULT_CLAIM_MS = 10 * 60 * 1000;\n\n/**\n * How long a delivery id is remembered.\n *\n * `id` means \"this delivery, once\" — a webhook redelivered ten seconds later,\n * a retried send, a cron that fired twice all collapse to one. That has to\n * outlive the queue, because the common case is a duplicate arriving after the\n * first copy was already read. It cannot be remembered forever, so it is\n * remembered for a window an application can set and reason about.\n */\nconst DEFAULT_DELIVERY_MEMORY_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport function createSqliteStore(input: {\n database: SqliteDatabase;\n claimMs?: number;\n /** How long a delivery id is remembered. Defaults to seven days. */\n deliveryMemoryMs?: number;\n}): Store {\n const database = input.database;\n const claimMs = input.claimMs ?? DEFAULT_CLAIM_MS;\n const deliveryMemoryMs = input.deliveryMemoryMs ?? DEFAULT_DELIVERY_MEMORY_MS;\n\n // Tables, then the columns an older build's tables lack, then the indexes —\n // which is the only order that works, because an index may be over a column\n // the migration is about to add.\n database.exec(tables);\n for (const { table, column, type } of added) {\n const present = database.query(`SELECT 1 FROM pragma_table_info(?) WHERE name = ?`).all(table, column);\n if (!present.length) database.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);\n }\n database.exec(indexes);\n\n const one = <T>(sql: string, parameters: readonly unknown[]): T | undefined =>\n database.query(sql).all(...parameters)[0] as T | undefined;\n const run = (sql: string, parameters: readonly unknown[]) => { database.query(sql).run(...parameters); };\n const notFound = (sessionId: string): StoreError =>\n ({ code: \"not-found\", message: `No session ${sessionId}`, retryable: false });\n const failed = (error: unknown): StoreError =>\n ({ code: \"failed\", message: error instanceof Error ? error.message : String(error), retryable: false });\n const queueOf = (row: { pending: string }): Delivery[] => JSON.parse(row.pending) as Delivery[];\n\n /**\n * Watchers, woken after a write is committed.\n *\n * Every call site is already past its `COMMIT`, which is what makes the change\n * readable. The microtask is for the other half: a watcher that throws must\n * not fail the write that woke it — it surfaces as the caller's own unhandled\n * error rather than as a refused append — and one that writes back through\n * this store must not do so from inside the stack of the write it is\n * answering.\n */\n const watchers = new Set<(change: StoreChange) => void>();\n const woke = (changes: readonly StoreChange[]): void => {\n if (!watchers.size || !changes.length) return;\n for (const watcher of [...watchers]) {\n // One microtask each. A watcher that throws must not fail the write that\n // woke it, and must not suppress the watchers after it in the loop — in\n // its own task the throw surfaces as the caller's unhandled error and\n // costs nobody else their wake. Membership is re-checked at delivery, so\n // a watcher that let go between the write and this task is not called:\n // `off()` says stop, and a queued wake is still a wake.\n queueMicrotask(() => {\n if (!watchers.has(watcher)) return;\n for (const change of changes) watcher(change);\n });\n }\n };\n\n return {\n /** Idempotent: a session that is already here keeps what it was created with. */\n async create({ sessionId, agent, key, metadata }) {\n try {\n const existing = one<{ id: string }>(`SELECT id FROM sessions WHERE id = ?`, [sessionId]);\n if (existing) return ok(undefined);\n run(\n `INSERT OR IGNORE INTO sessions (id, agent_id, agent_ver, key, metadata, updated_at)\n VALUES (?, ?, ?, ?, ?, ?)`,\n [sessionId, agent.id, agent.version, key ?? null, JSON.stringify(metadata ?? {}), new Date().toISOString()],\n );\n // Only a session that really appeared is a change, and a new one has\n // nothing waiting on it — announcing `runnable: false` for a session\n // that already had input would have been wrong rather than spurious.\n woke([{ sessionId, runnable: false }]);\n return ok(undefined);\n } catch (error) { return err(failed(error)); }\n },\n\n async read({ sessionId, afterSeq = 0 }) {\n try {\n const session = one<SessionRow>(`SELECT * FROM sessions WHERE id = ?`, [sessionId]);\n if (!session) return err(notFound(sessionId));\n const rows = database.query(\n `SELECT seq, at, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq`,\n ).all(sessionId, afterSeq) as { seq: number; at: string; body: string }[];\n return ok<SessionRead>({\n sessionId,\n agent: { id: session.agent_id, version: session.agent_ver },\n seq: session.last_seq,\n metadata: JSON.parse(session.metadata) as JsonValue,\n entries: rows.map((row): Stored => ({ ...(JSON.parse(row.body) as Entry), seq: row.seq, at: row.at })),\n pending: queueOf(session),\n });\n } catch (error) { return err(failed(error)); }\n },\n\n /**\n * Entries, deliveries, metadata and the queue in one transaction.\n *\n * The compare-and-swap on `last_seq` decides everything else: a caller\n * working from a stale position loses and is told the real one, and because\n * the queue is consumed here rather than in `next`, a loser leaves the\n * messages it was carrying untouched.\n */\n async append({ sessionId, expectedSeq, entries, enqueue, metadata, takePending }) {\n const at = new Date().toISOString();\n try {\n // Inside the try: on a busy database this is where the failure lands,\n // and a throw here escaped the `Result` the port promises.\n database.exec(\"BEGIN IMMEDIATE\");\n const session = one<SessionRow>(`SELECT * FROM sessions WHERE id = ?`, [sessionId]);\n if (!session) { database.exec(\"ROLLBACK\"); return err(notFound(sessionId)); }\n if (session.last_seq !== expectedSeq) {\n database.exec(\"ROLLBACK\");\n return err<StoreConflict>({\n code: \"conflict\", message: `Session moved to ${session.last_seq}`,\n retryable: true, actualSeq: session.last_seq,\n });\n }\n entries.forEach((entry, offset) => {\n run(`INSERT INTO entries (session_id, seq, at, body) VALUES (?, ?, ?, ?)`,\n [sessionId, expectedSeq + offset + 1, at, JSON.stringify(entry)]);\n });\n\n // An activation is open from the entry that starts it to the entry that\n // ends it. `next` reads this to keep a second one from beginning, and\n // the log is the only thing that knows — so it is derived from the log\n // rather than asserted by a caller.\n const opens = entries.some((entry) => entry.type === \"run.started\");\n const closes = entries.some((entry) => entry.type === \"run.finished\");\n // Only a write that records work renews the claim. Renewing on any\n // append at all meant a message *to* a session renewed the claim of the\n // worker that was supposed to read it — so a dead worker's session\n // stayed claimed for as long as anyone kept talking to it, invisible to\n // `next` (the claim never lapsed) and to `interrupted` (the queue was not\n // empty). An activation renews by doing its work, and being spoken to\n // is not its work.\n const worked = entries.length > 0;\n // Every write by an open activation renews its claim. Without this the\n // timestamp stayed at whenever the run began, so any turn outstanding\n // longer than the claim window was handed to a second worker while it\n // was still going — and a compare-and-swap cannot un-run a tool call.\n // A worker that dies still releases, because a dead worker stops writing.\n const runningSince = closes ? null : (opens || (worked && session.running_since)) ? at : session.running_since;\n\n const merged = metadata\n ? JSON.stringify({ ...(JSON.parse(session.metadata) as object), ...(metadata as object) })\n : session.metadata;\n const waiting = queueOf(session);\n if (takePending !== undefined && takePending > waiting.length) {\n // The one loss this design exists to prevent, reachable from a\n // caller's off-by-one: silently dropping messages nothing recorded.\n // `takePending` is only ever `claim.pending.length`, so a larger\n // number means the caller is working from a queue that is not there.\n database.exec(\"ROLLBACK\");\n return err<StoreError>({\n code: \"conflict\",\n message: `Asked to take ${takePending} deliveries from a queue of ${waiting.length}`,\n retryable: false,\n });\n }\n const queue = takePending ? waiting.slice(takePending) : waiting;\n /** Which sessions this write put input on, this one included. */\n const delivered = new Set<string>();\n run(\n `UPDATE sessions SET last_seq = ?, metadata = ?, pending = ?, running_since = ?, updated_at = ?\n WHERE id = ?`,\n [expectedSeq + entries.length, merged, JSON.stringify(queue), runningSince, at, sessionId],\n );\n\n // Swept before the ids are checked, not after: an id past its window is\n // forgotten, and one still inside it is not. Sweeping afterwards left\n // every expired id alive for exactly one more send.\n run(`DELETE FROM deliveries WHERE at < ?`,\n [new Date(Date.parse(at) - deliveryMemoryMs).toISOString()]);\n\n for (const delivery of enqueue ?? []) {\n const target = one<{ pending: string }>(`SELECT pending FROM sessions WHERE id = ?`, [delivery.sessionId]);\n if (!target) { database.exec(\"ROLLBACK\"); return err(notFound(delivery.sessionId)); }\n\n // Two deliveries with the same id from the same sender are the same\n // delivery, and stay so after the first has been read — the whole\n // point of an idempotency key is that it survives the queue. The\n // sender is part of it because the id is the sender's own: without\n // that, two agents numbering their messages from one silently\n // suppress each other.\n // The column is one string, so the two fields are joined into one\n // here. The encoding is this adapter's own and never leaves it: no\n // caller reads the column, and a store that keys the same fact some\n // other way is answering the same question, which is the one the\n // conformance suite asks.\n if (delivery.id) {\n const sender = delivery.from ? `${delivery.from.kind}:${delivery.from.id}` : \"\";\n const seen = one<{ delivery_id: string }>(\n `SELECT delivery_id FROM deliveries WHERE session_id = ? AND sender = ? AND delivery_id = ?`,\n [delivery.sessionId, sender, delivery.id]);\n if (seen) continue;\n run(`INSERT INTO deliveries (session_id, sender, delivery_id, at) VALUES (?, ?, ?, ?)`,\n [delivery.sessionId, sender, delivery.id, at]);\n }\n\n run(`UPDATE sessions SET pending = ?, updated_at = ? WHERE id = ?`,\n [JSON.stringify([...queueOf(target), delivery]), at, delivery.sessionId]);\n delivered.add(delivery.sessionId);\n }\n database.exec(\"COMMIT\");\n // After the commit, never before: a watcher that looked on an earlier\n // wake would find nothing and never be told again.\n woke([\n { sessionId, runnable: delivered.has(sessionId) || queue.length > 0 },\n ...[...delivered].filter((id) => id !== sessionId).map((id) => ({ sessionId: id, runnable: true })),\n ]);\n return ok({ seq: expectedSeq + entries.length });\n } catch (error) {\n database.exec(\"ROLLBACK\");\n return err(failed(error));\n }\n },\n\n async list({ key, limit = 50, before }) {\n try {\n // The cursor carries the id as well as the timestamp, because sessions\n // written in the same tick have no order without it — and a plain\n // `< before` then steps over every row that shares the boundary instant.\n const [beforeAt, beforeId] = before ? splitCursor(before) : [null, null];\n const rows = database.query(\n `SELECT * FROM sessions\n WHERE (? IS NULL OR key = ?)\n AND (? IS NULL OR updated_at < ? OR (updated_at = ? AND id < ?))\n ORDER BY updated_at DESC, id DESC LIMIT ?`,\n ).all(key ?? null, key ?? null, beforeAt, beforeAt, beforeAt, beforeId, limit) as SessionRow[];\n return ok(rows.map((row): SessionSummary => ({\n sessionId: row.id,\n agent: { id: row.agent_id, version: row.agent_ver },\n key: row.key,\n seq: row.last_seq,\n metadata: JSON.parse(row.metadata) as JsonValue,\n updatedAt: row.updated_at,\n })));\n } catch (error) { return err(failed(error)); }\n },\n\n /**\n * Claim a session that has input and no activation already running.\n *\n * The queue is reported and left in place; the append that commits it as\n * entries is what removes it. Nothing here is destructive, so a worker that\n * takes this and then dies costs one expired claim and no messages.\n */\n async next({ signal }) {\n // Nothing is owed to a caller that has given up. Answered rather than\n // refused: \"nothing to claim\" is true, and it needs no code of its own.\n if (signal?.aborted) return ok(undefined);\n const now = Date.now();\n const stale = new Date(now - claimMs).toISOString();\n try {\n database.exec(\"BEGIN IMMEDIATE\");\n const row = one<SessionRow>(\n `SELECT * FROM sessions\n WHERE pending <> '[]' AND (running_since IS NULL OR running_since < ?)\n ORDER BY updated_at LIMIT 1`, [stale]);\n if (!row) { database.exec(\"COMMIT\"); return ok(undefined); }\n run(`UPDATE sessions SET running_since = ? WHERE id = ?`, [new Date(now).toISOString(), row.id]);\n database.exec(\"COMMIT\");\n return ok<Runnable>({\n sessionId: row.id,\n seq: row.last_seq,\n pending: queueOf(row),\n metadata: JSON.parse(row.metadata) as JsonValue,\n });\n } catch (error) {\n database.exec(\"ROLLBACK\");\n return err(failed(error));\n }\n },\n\n /**\n * Claim a session whose activation was interrupted.\n *\n * The mirror of `next`, over the two columns that already exist: an open\n * run — `running_since` set, because the entry that would clear it never\n * committed — whose claim has lapsed, and an empty queue, because the\n * commit that opened the run took what made it runnable. Nothing else in\n * the store can see this session, which is why the port asks for it here\n * rather than leaving every application to write this query itself.\n */\n async interrupted({ signal }) {\n if (signal?.aborted) return ok(undefined);\n const now = Date.now();\n const stale = new Date(now - claimMs).toISOString();\n try {\n database.exec(\"BEGIN IMMEDIATE\");\n const row = one<SessionRow>(\n `SELECT * FROM sessions\n WHERE pending = '[]' AND running_since IS NOT NULL AND running_since < ?\n ORDER BY updated_at LIMIT 1`, [stale]);\n if (!row) { database.exec(\"COMMIT\"); return ok(undefined); }\n run(`UPDATE sessions SET running_since = ? WHERE id = ?`, [new Date(now).toISOString(), row.id]);\n database.exec(\"COMMIT\");\n return ok<Runnable>({\n sessionId: row.id,\n seq: row.last_seq,\n pending: [],\n metadata: JSON.parse(row.metadata) as JsonValue,\n });\n } catch (error) {\n database.exec(\"ROLLBACK\");\n return err(failed(error));\n }\n },\n\n /**\n * The feed is this store's own writes, and reaches exactly as far as they\n * do: a watcher here is woken by what this instance commits, and by nothing\n * else. Another process on the same file, a second store over the same\n * handle, and the application's own SQL beside the log are all invisible,\n * because sqlite has no channel to tell us — that is the miss the port\n * requires a heartbeat for. The case that matters is covered: the surface\n * that writes a delivery and the worker that reads it are the same process,\n * and usually the same store.\n */\n watch(watcher) {\n watchers.add(watcher);\n return () => { watchers.delete(watcher); };\n },\n\n async close() { watchers.clear(); /* the caller owns the handle it passed in */ },\n };\n}\n"]}
1
+ {"version":3,"file":"sqlite.js","sourceRoot":"","sources":["../../../src/store/adapters/sqlite.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,iBAAiB,CAAC;AAa1C,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2Bd,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,KAAK,GAA+D;IACxE,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,EAAE;IAC5D,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE;CACxD,CAAC;AAEF,MAAM,OAA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AAU,CAAC,CAAC;gBAC1B,OAAO,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;YAC5B,CAAC;QACH,CAAC;QAED;;;;;;;;;WASG;QACH,KAAK,CAAC,OAAO;YACX,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;YACtB,OAAO,GAAG,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;QAC7C,CAAC;QAED,KAAK,CAAC,KAAK,KAAK,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,6CAA6C,CAAC,CAAC;KAClF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Store, StoreChange, StoreError, StoreConflict, SessionRead, SessionSummary, Runnable,\n} from \"../store.js\";\nimport type { Delivery, Entry, Stored } from \"../../session/entry.js\";\nimport type { JsonValue } from \"../../json.js\";\nimport { err, ok } from \"../../result.js\";\n\n/**\n * The minimum a driver must provide. Declared here rather than importing one so\n * the same file serves `node:sqlite` and `bun:sqlite`, and so an application can\n * hand in a database it already opened — which is what lets its own tables live\n * beside the log and join against it.\n */\nexport interface SqliteDatabase {\n exec(sql: string): void;\n query(sql: string): { all(...parameters: unknown[]): unknown[]; run(...parameters: unknown[]): unknown };\n}\n\nconst tables = `\n CREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n agent_ver TEXT NOT NULL,\n key TEXT,\n metadata TEXT NOT NULL DEFAULT '{}',\n pending TEXT NOT NULL DEFAULT '[]',\n last_seq INTEGER NOT NULL DEFAULT 0,\n running_since TEXT,\n claim_id TEXT,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS entries (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n at TEXT NOT NULL,\n body TEXT NOT NULL,\n PRIMARY KEY (session_id, seq)\n );\n CREATE TABLE IF NOT EXISTS deliveries (\n session_id TEXT NOT NULL,\n sender TEXT NOT NULL,\n delivery_id TEXT NOT NULL,\n at TEXT NOT NULL,\n PRIMARY KEY (session_id, sender, delivery_id)\n );\n`;\n\n/**\n * Columns added after a table had already shipped.\n *\n * `CREATE TABLE IF NOT EXISTS` is a no-op against a table that exists, so a\n * column added later never appears in a database made by an older build — and\n * the first index over it fails with a raw `SQLiteError` from inside `bun:sqlite`,\n * which is no way to meet a store whose whole promise is that the log survives.\n * Additive only: a column is added, nothing is dropped, rewritten or lost.\n */\nconst added: readonly { table: string; column: string; type: string }[] = [\n { table: \"sessions\", column: \"running_since\", type: \"TEXT\" },\n { table: \"sessions\", column: \"claim_id\", type: \"TEXT\" },\n];\n\nconst indexes = `\n CREATE INDEX IF NOT EXISTS sessions_by_key ON sessions (key, updated_at DESC, id DESC);\n CREATE INDEX IF NOT EXISTS sessions_runnable ON sessions (updated_at) WHERE pending <> '[]';\n DROP INDEX IF EXISTS sessions_stranded; -- sessions_interrupted under its former name\n CREATE INDEX IF NOT EXISTS sessions_interrupted ON sessions (updated_at) WHERE running_since IS NOT NULL;\n CREATE INDEX IF NOT EXISTS deliveries_by_age ON deliveries (at);\n`;\n\ninterface SessionRow {\n id: string; agent_id: string; agent_ver: string; key: string | null;\n metadata: string; pending: string; last_seq: number; running_since: string | null; claim_id: string | null; updated_at: string;\n}\n\n/** `updatedAt` and the session id, so a page boundary is a point and not an instant. */\nconst splitCursor = (cursor: string): [string, string] => {\n const cut = cursor.lastIndexOf(\"|\");\n return cut < 0 ? [cursor, \"\"] : [cursor.slice(0, cut), cursor.slice(cut + 1)];\n};\n\n/**\n * How long a claim holds before another worker may take the session.\n *\n * Long enough that an ordinary turn finishes inside it, short enough that a\n * worker killed mid-turn does not strand its session for an afternoon. If the\n * original worker is somehow still alive when it expires, its writes fail the\n * compare-and-swap, so the window governs wasted work and never correctness.\n */\nconst DEFAULT_CLAIM_MS = 10 * 60 * 1000;\n\n/**\n * How long a delivery id is remembered.\n *\n * `id` means \"this delivery, once\" — a webhook redelivered ten seconds later,\n * a retried send, a cron that fired twice all collapse to one. That has to\n * outlive the queue, because the common case is a duplicate arriving after the\n * first copy was already read. It cannot be remembered forever, so it is\n * remembered for a window an application can set and reason about.\n */\nconst DEFAULT_DELIVERY_MEMORY_MS = 7 * 24 * 60 * 60 * 1000;\n\nexport function createSqliteStore(input: {\n database: SqliteDatabase;\n claimMs?: number;\n /** How long a delivery id is remembered. Defaults to seven days. */\n deliveryMemoryMs?: number;\n}): Store {\n const database = input.database;\n const claimMs = input.claimMs ?? DEFAULT_CLAIM_MS;\n /** A third of the window: two renewals can be missed before a live owner looks dead. */\n const renewAfterMs = Math.max(1, Math.floor(claimMs / 3));\n const owns = (row: SessionRow, claimId: string) =>\n row.claim_id === claimId && !!row.running_since && Date.parse(row.running_since) + claimMs > Date.now();\n const deliveryMemoryMs = input.deliveryMemoryMs ?? DEFAULT_DELIVERY_MEMORY_MS;\n\n // Tables, then the columns an older build's tables lack, then the indexes —\n // which is the only order that works, because an index may be over a column\n // the migration is about to add.\n database.exec(tables);\n for (const { table, column, type } of added) {\n const present = database.query(`SELECT 1 FROM pragma_table_info(?) WHERE name = ?`).all(table, column);\n if (!present.length) database.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);\n }\n database.exec(indexes);\n\n const one = <T>(sql: string, parameters: readonly unknown[]): T | undefined =>\n database.query(sql).all(...parameters)[0] as T | undefined;\n const run = (sql: string, parameters: readonly unknown[]) => { database.query(sql).run(...parameters); };\n const notFound = (sessionId: string): StoreError =>\n ({ code: \"not-found\", message: `No session ${sessionId}`, retryable: false });\n const failed = (error: unknown): StoreError =>\n ({ code: \"failed\", message: error instanceof Error ? error.message : String(error), retryable: false });\n const queueOf = (row: { pending: string }): Delivery[] => JSON.parse(row.pending) as Delivery[];\n\n /**\n * Watchers, woken after a write is committed.\n *\n * Every call site is already past its `COMMIT`, which is what makes the change\n * readable. The microtask is for the other half: a watcher that throws must\n * not fail the write that woke it — it surfaces as the caller's own unhandled\n * error rather than as a refused append — and one that writes back through\n * this store must not do so from inside the stack of the write it is\n * answering.\n */\n const watchers = new Set<(change: StoreChange) => void>();\n const woke = (changes: readonly StoreChange[]): void => {\n if (!watchers.size || !changes.length) return;\n for (const watcher of [...watchers]) {\n // One microtask each. A watcher that throws must not fail the write that\n // woke it, and must not suppress the watchers after it in the loop — in\n // its own task the throw surfaces as the caller's unhandled error and\n // costs nobody else their wake. Membership is re-checked at delivery, so\n // a watcher that let go between the write and this task is not called:\n // `off()` says stop, and a queued wake is still a wake.\n queueMicrotask(() => {\n if (!watchers.has(watcher)) return;\n for (const change of changes) watcher(change);\n });\n }\n };\n\n return {\n /** Idempotent: a session that is already here keeps what it was created with. */\n async create({ sessionId, agent, key, metadata }) {\n try {\n const existing = one<{ id: string }>(`SELECT id FROM sessions WHERE id = ?`, [sessionId]);\n if (existing) return ok(undefined);\n run(\n `INSERT OR IGNORE INTO sessions (id, agent_id, agent_ver, key, metadata, updated_at)\n VALUES (?, ?, ?, ?, ?, ?)`,\n [sessionId, agent.id, agent.version, key ?? null, JSON.stringify(metadata ?? {}), new Date().toISOString()],\n );\n // Only a session that really appeared is a change, and a new one has\n // nothing waiting on it — announcing `runnable: false` for a session\n // that already had input would have been wrong rather than spurious.\n woke([{ sessionId, runnable: false }]);\n return ok(undefined);\n } catch (error) { return err(failed(error)); }\n },\n\n async read({ sessionId, afterSeq = 0 }) {\n try {\n const session = one<SessionRow>(`SELECT * FROM sessions WHERE id = ?`, [sessionId]);\n if (!session) return err(notFound(sessionId));\n const rows = database.query(\n `SELECT seq, at, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq`,\n ).all(sessionId, afterSeq) as { seq: number; at: string; body: string }[];\n return ok<SessionRead>({\n sessionId,\n agent: { id: session.agent_id, version: session.agent_ver },\n seq: session.last_seq,\n metadata: JSON.parse(session.metadata) as JsonValue,\n entries: rows.map((row): Stored => ({ ...(JSON.parse(row.body) as Entry), seq: row.seq, at: row.at })),\n pending: queueOf(session),\n });\n } catch (error) { return err(failed(error)); }\n },\n\n /**\n * Entries, deliveries, metadata and the queue in one transaction.\n *\n * The compare-and-swap on `last_seq` decides everything else: a caller\n * working from a stale position loses and is told the real one, and because\n * the queue is consumed here rather than in `next`, a loser leaves the\n * messages it was carrying untouched.\n */\n async append({ sessionId, expectedSeq, claimId, entries, enqueue, metadata, takePending }) {\n const at = new Date().toISOString();\n try {\n // Inside the try: on a busy database this is where the failure lands,\n // and a throw here escaped the `Result` the port promises.\n database.exec(\"BEGIN IMMEDIATE\");\n const session = one<SessionRow>(`SELECT * FROM sessions WHERE id = ?`, [sessionId]);\n if (!session) { database.exec(\"ROLLBACK\"); return err(notFound(sessionId)); }\n // Ownership before position: a writer whose claim lapsed and passed on\n // can still be at the right sequence, if nothing committed in between.\n if (claimId !== undefined && !owns(session, claimId)) {\n database.exec(\"ROLLBACK\");\n return err({ code: \"conflict\", message: \"Session ownership expired or changed\", retryable: false });\n }\n if (session.last_seq !== expectedSeq) {\n database.exec(\"ROLLBACK\");\n return err<StoreConflict>({\n code: \"conflict\", message: `Session moved to ${session.last_seq}`,\n retryable: true, actualSeq: session.last_seq,\n });\n }\n entries.forEach((entry, offset) => {\n run(`INSERT INTO entries (session_id, seq, at, body) VALUES (?, ?, ?, ?)`,\n [sessionId, expectedSeq + offset + 1, at, JSON.stringify(entry)]);\n });\n\n // An activation is open from the entry that starts it to the entry that\n // ends it. `next` reads this to keep a second one from beginning, and\n // the log is the only thing that knows — so it is derived from the log\n // rather than asserted by a caller.\n // Only a write that records work renews the claim. Renewing on any\n // append at all meant a message *to* a session renewed the claim of the\n // worker that was supposed to read it — so a dead worker's session\n // stayed claimed for as long as anyone kept talking to it, invisible to\n // `next` (the claim never lapsed) and to `interrupted` (the queue was not\n // empty). An activation renews by doing its work, and being spoken to\n // is not its work.\n const worked = entries.length > 0;\n // Every write by an open activation renews its claim. Without this the\n // timestamp stayed at whenever the run began, so any turn outstanding\n // longer than the claim window was handed to a second worker while it\n // was still going — and a compare-and-swap cannot un-run a tool call.\n // A worker that dies still releases, because a dead worker stops writing.\n // The last lifecycle entry decides, so one write that closes an\n // interrupted run and opens its successor leaves the session open.\n const lifecycle = entries.findLast((entry) => entry.type === \"run.started\" || entry.type === \"run.finished\");\n const runningSince = lifecycle?.type === \"run.finished\" ? null\n : lifecycle?.type === \"run.started\" || (worked && session.running_since) ? at : session.running_since;\n\n const merged = metadata\n ? JSON.stringify({ ...(JSON.parse(session.metadata) as object), ...(metadata as object) })\n : session.metadata;\n const waiting = queueOf(session);\n if (takePending !== undefined && takePending > waiting.length) {\n // The one loss this design exists to prevent, reachable from a\n // caller's off-by-one: silently dropping messages nothing recorded.\n // `takePending` is only ever `claim.pending.length`, so a larger\n // number means the caller is working from a queue that is not there.\n database.exec(\"ROLLBACK\");\n return err<StoreError>({\n code: \"conflict\",\n message: `Asked to take ${takePending} deliveries from a queue of ${waiting.length}`,\n retryable: false,\n });\n }\n const queue = takePending ? waiting.slice(takePending) : waiting;\n /** Which sessions this write put input on, this one included. */\n const delivered = new Set<string>();\n run(\n `UPDATE sessions SET last_seq = ?, metadata = ?, pending = ?, running_since = ?, updated_at = ?\n WHERE id = ?`,\n [expectedSeq + entries.length, merged, JSON.stringify(queue), runningSince, at, sessionId],\n );\n\n // Swept before the ids are checked, not after: an id past its window is\n // forgotten, and one still inside it is not. Sweeping afterwards left\n // every expired id alive for exactly one more send.\n run(`DELETE FROM deliveries WHERE at < ?`,\n [new Date(Date.parse(at) - deliveryMemoryMs).toISOString()]);\n\n for (const delivery of enqueue ?? []) {\n const target = one<{ pending: string }>(`SELECT pending FROM sessions WHERE id = ?`, [delivery.sessionId]);\n if (!target) { database.exec(\"ROLLBACK\"); return err(notFound(delivery.sessionId)); }\n\n // Two deliveries with the same id from the same sender are the same\n // delivery, and stay so after the first has been read — the whole\n // point of an idempotency key is that it survives the queue. The\n // sender is part of it because the id is the sender's own: without\n // that, two agents numbering their messages from one silently\n // suppress each other.\n // The column is one string, so the two fields are joined into one\n // here. The encoding is this adapter's own and never leaves it: no\n // caller reads the column, and a store that keys the same fact some\n // other way is answering the same question, which is the one the\n // conformance suite asks.\n if (delivery.id) {\n const sender = delivery.from ? `${delivery.from.kind}:${delivery.from.id}` : \"\";\n const seen = one<{ delivery_id: string }>(\n `SELECT delivery_id FROM deliveries WHERE session_id = ? AND sender = ? AND delivery_id = ?`,\n [delivery.sessionId, sender, delivery.id]);\n if (seen) continue;\n run(`INSERT INTO deliveries (session_id, sender, delivery_id, at) VALUES (?, ?, ?, ?)`,\n [delivery.sessionId, sender, delivery.id, at]);\n }\n\n run(`UPDATE sessions SET pending = ?, updated_at = ? WHERE id = ?`,\n [JSON.stringify([...queueOf(target), delivery]), at, delivery.sessionId]);\n delivered.add(delivery.sessionId);\n }\n if (!runningSince) run(`UPDATE sessions SET claim_id = NULL WHERE id = ?`, [sessionId]);\n database.exec(\"COMMIT\");\n // After the commit, never before: a watcher that looked on an earlier\n // wake would find nothing and never be told again.\n woke([\n { sessionId, runnable: delivered.has(sessionId) || queue.length > 0 },\n ...[...delivered].filter((id) => id !== sessionId).map((id) => ({ sessionId: id, runnable: true })),\n ]);\n return ok({ seq: expectedSeq + entries.length });\n } catch (error) {\n database.exec(\"ROLLBACK\");\n return err(failed(error));\n }\n },\n\n async list({ key, limit = 50, before }) {\n try {\n // The cursor carries the id as well as the timestamp, because sessions\n // written in the same tick have no order without it — and a plain\n // `< before` then steps over every row that shares the boundary instant.\n const [beforeAt, beforeId] = before ? splitCursor(before) : [null, null];\n const rows = database.query(\n `SELECT * FROM sessions\n WHERE (? IS NULL OR key = ?)\n AND (? IS NULL OR updated_at < ? OR (updated_at = ? AND id < ?))\n ORDER BY updated_at DESC, id DESC LIMIT ?`,\n ).all(key ?? null, key ?? null, beforeAt, beforeAt, beforeAt, beforeId, limit) as SessionRow[];\n return ok(rows.map((row): SessionSummary => ({\n sessionId: row.id,\n agent: { id: row.agent_id, version: row.agent_ver },\n key: row.key,\n seq: row.last_seq,\n metadata: JSON.parse(row.metadata) as JsonValue,\n updatedAt: row.updated_at,\n })));\n } catch (error) { return err(failed(error)); }\n },\n\n async renew({ sessionId, claimId }) {\n try {\n database.exec(\"BEGIN IMMEDIATE\");\n const row = one<SessionRow>(`SELECT * FROM sessions WHERE id = ?`, [sessionId]);\n if (!row || !owns(row, claimId)) {\n database.exec(\"ROLLBACK\");\n return err({ code: \"conflict\", message: \"Session ownership expired or changed\", retryable: false });\n }\n run(`UPDATE sessions SET running_since = ? WHERE id = ?`, [new Date().toISOString(), sessionId]);\n database.exec(\"COMMIT\");\n return ok(undefined);\n } catch (error) {\n database.exec(\"ROLLBACK\");\n return err(failed(error));\n }\n },\n\n /**\n * Claim a session that has input and no activation already running.\n *\n * The queue is reported and left in place; the append that commits it as\n * entries is what removes it. Nothing here is destructive, so a worker that\n * takes this and then dies costs one expired claim and no messages.\n */\n async next({ signal }) {\n // Nothing is owed to a caller that has given up. Answered rather than\n // refused: \"nothing to claim\" is true, and it needs no code of its own.\n if (signal?.aborted) return ok(undefined);\n const now = Date.now();\n const stale = new Date(now - claimMs).toISOString();\n try {\n database.exec(\"BEGIN IMMEDIATE\");\n const row = one<SessionRow>(\n `SELECT * FROM sessions\n WHERE pending <> '[]' AND (running_since IS NULL OR running_since < ?)\n ORDER BY updated_at LIMIT 1`, [stale]);\n if (!row) { database.exec(\"COMMIT\"); return ok(undefined); }\n const claimId = crypto.randomUUID();\n run(`UPDATE sessions SET running_since = ?, claim_id = ? WHERE id = ?`, [new Date(now).toISOString(), claimId, row.id]);\n database.exec(\"COMMIT\");\n return ok<Runnable>({\n claimId, renewAfterMs,\n sessionId: row.id,\n seq: row.last_seq,\n pending: queueOf(row),\n metadata: JSON.parse(row.metadata) as JsonValue,\n });\n } catch (error) {\n database.exec(\"ROLLBACK\");\n return err(failed(error));\n }\n },\n\n /**\n * Claim a session whose activation was interrupted.\n *\n * The mirror of `next`, over the two columns that already exist: an open\n * run — `running_since` set, because the entry that would clear it never\n * committed — whose claim has lapsed, and an empty queue, because the\n * commit that opened the run took what made it runnable. Nothing else in\n * the store can see this session, which is why the port asks for it here\n * rather than leaving every application to write this query itself.\n */\n async interrupted({ signal }) {\n if (signal?.aborted) return ok(undefined);\n const now = Date.now();\n const stale = new Date(now - claimMs).toISOString();\n try {\n database.exec(\"BEGIN IMMEDIATE\");\n const row = one<SessionRow>(\n `SELECT * FROM sessions\n WHERE pending = '[]' AND running_since IS NOT NULL AND running_since < ?\n ORDER BY updated_at LIMIT 1`, [stale]);\n if (!row) { database.exec(\"COMMIT\"); return ok(undefined); }\n const claimId = crypto.randomUUID();\n run(`UPDATE sessions SET running_since = ?, claim_id = ? WHERE id = ?`, [new Date(now).toISOString(), claimId, row.id]);\n database.exec(\"COMMIT\");\n return ok<Runnable>({\n claimId, renewAfterMs,\n sessionId: row.id,\n seq: row.last_seq,\n pending: [],\n metadata: JSON.parse(row.metadata) as JsonValue,\n });\n } catch (error) {\n database.exec(\"ROLLBACK\");\n return err(failed(error));\n }\n },\n\n /**\n * The feed is this store's own writes, and reaches exactly as far as they\n * do: a watcher here is woken by what this instance commits, and by nothing\n * else. Another process on the same file, a second store over the same\n * handle, and the application's own SQL beside the log are all invisible,\n * because sqlite has no channel to tell us — that is the miss the port\n * requires a heartbeat for. The case that matters is covered: the surface\n * that writes a delivery and the worker that reads it are the same process,\n * and usually the same store.\n */\n watch(watcher) {\n watchers.add(watcher);\n return () => { watchers.delete(watcher); };\n },\n\n async close() { watchers.clear(); /* the caller owns the handle it passed in */ },\n };\n}\n"]}
@@ -11,7 +11,7 @@
11
11
  *
12
12
  * So the contract is executable. These cases say what the interface means —
13
13
  * that a claim does not consume, that a queue survives a lost race, that an
14
- * open activation renews by writing rather than by having started, that a
14
+ * open activation can renew without writing its cursor, that a
15
15
  * delivery id outlives the queue — and an adapter runs them rather than reading
16
16
  * them.
17
17
  *
@@ -279,6 +279,25 @@ export function defineStoreConformance(subject) {
279
279
  }), "commit the two that were taken");
280
280
  equals(got(await store.read({ sessionId: id("s") }), "read").pending.map((one) => one.input), ["third"], "what arrived since is behind them and survives");
281
281
  });
282
+ define("ownership renews without moving the cursor and fences a reclaimed position", async (store) => {
283
+ await created(store, id("s"));
284
+ got(await store.append({ sessionId: id("s"), expectedSeq: 0, entries: [], enqueue: [{ sessionId: id("s"), input: "work", id: "once" }] }), "deliver");
285
+ const first = await claim(store);
286
+ holds(first !== undefined, "first worker claims");
287
+ holds(typeof first.claimId === "string" && first.claimId.length > 0, "ownership is identified");
288
+ got(await store.renew({ sessionId: id("s"), claimId: first.claimId }), "renew without a log write");
289
+ equals(got(await store.read({ sessionId: id("s") }), "read").seq, first.seq, "renewal leaves the cursor alone");
290
+ await wait(LAPSE_MS);
291
+ const second = await claim(store);
292
+ holds(second !== undefined && second.claimId !== first.claimId, "a replacement owns a distinct claim");
293
+ equals(second.seq, first.seq, "a reclaim need not change the position");
294
+ const staleRenew = await store.renew({ sessionId: id("s"), claimId: first.claimId });
295
+ holds(!staleRenew.ok && staleRenew.error.code === "conflict", "a stale renewal is refused");
296
+ const staleWrite = await store.append({ sessionId: id("s"), expectedSeq: first.seq, claimId: first.claimId, entries: [said("stale")], takePending: 1 });
297
+ holds(!staleWrite.ok && staleWrite.error.code === "conflict", "a stale write is refused at the same sequence");
298
+ equals(got(await store.read({ sessionId: id("s") }), "read").pending.length, 1, "a refused writer cannot consume the queue");
299
+ got(await store.append({ sessionId: id("s"), expectedSeq: second.seq, claimId: second.claimId, entries: [said("current")], takePending: 1 }), "the current writer commits");
300
+ });
282
301
  define("a session is claimed while it runs and released when the run finishes", async (store) => {
283
302
  await created(store, id("s"));
284
303
  got(await store.append({