The Code Mode extension imported it from /portable, which loads the WASM QuickJS runtime the extension never uses. closes #11254
59 KiB
Changelog
[Unreleased]
Breaking Changes
-
SqliteExecutor(re-exported from Chord) gainsrunCounted(sql, ...params), resolving with the rows the statement changed; customSqliteDatabaseimplementations add it. -
Storage.commit(writes, adopt, context)takes anadopt(seq)callback, the Session's in-memory adoption and publication of the batch: a storage calls it exactly once, synchronously, once the batch is durable and before its next commit starts, then resolves withseq, and never for a commit that fails before the batch is durable. Memory, SQLite, JSONL, and IndexedDB storages do; custom storages and wrappers must call or forward it, and the storage conformance suite checks it. A commit that rejects after its adoption is published and fails the Session without rolling the adopted changes back. -
Storage.mintId()'s contract is narrowed to IDs greater than every ID minted since the storage was opened and every ID stored, also across reopen. The bundled storages already behave so. -
Watches use Chord's
WatchHandleandWatchEnd(Durable re-exports both, withWatchChangeandNativeWatchChange). End reasons arestopped,cancelled,ended(wassession_closed),listener_error, andfailed(wassession_failed);retiredis gone (see below). An ended watch drops its listener and every reference into its Session, so a stopped watch that is still referenced keeps only its last value. -
Watch listeners take one change object before the context:
watch.start(async ({ value, ops, retired }, context) => …)for document, conversation view (Conversation.watch()), and task graph watches. Migration:start(async (value, ops, ctx) => …)becomesstart(async ({ value, ops }, ctx) => …). -
Document watches follow their address (kind, scope, and key) instead of one incarnation:
DocumentWatch<T>isWatchHandle<Readonly<T>>(nonull). A retirement no longer ends the watch with a last frame[["r", null]]andretired: the next call hasretired: true, the last value the watch was given, and no ops (folded with what is pending; a change made in the retiring commit itself is not shown), and a document created at the address later arrives on the same watch as[["r", value]], possibly in the same call. A task document's watch endsendedonce the retirement call of the commit that makes its task terminal has returned; Session close or failure still ends it first if that call was not delivered yet (a watch never started). Acquiring an absent document still givesundefined. A watch pins the incarnation at its address, nothing while it is absent. Migration: testchange.retiredinstead of anullvalue or aretiredend, and stop a watch whose document may be retired for good, as it otherwise stays until the Session ends. -
Document, conversation view, and task graph watches deliver the commits made while their listener runs (or before
start()) in one callback: the newest value, the commits' operations folded (appends to one string join, sets of one field keep the last) and the newest commit's Context. Past 10,000 pending operations the callback gets one root replacement[["r", newest]]. Before, each commit was its own callback and more than 100 pending commits became a root replacement. -
Removed the Chord state getters
Session.documentState(),Conversation.viewState(), andHarness.taskGraph(), and theDocumentStatetype; usewatchDoc(),Conversation.watch(), andHarness.watchTaskGraph(). Durable no longer uses Chord'sreplicatedState(). -
Partial answers and running tool output are stored later than they are shown: their throttled commits are deferred (
CommitPersistence, spec §4.1), so watches and views see each at once, while Storage gets them together with the next commit that readspi.live(the end of the answer, a tool settling, a run ending) and at the latest aftersettings.progress.persistWithinMs(default 1,000 ms). With 32 streams over SQLite this cuts storage transactions about 5.7x and disk writes about 2.9x for turns with parallel tools, 27x and 9x for long answers, and CPU by about a quarter. A crash now loses up to about a second of streamed content instead of 100 ms; a stream that crashes before its first store leaves no aborted entry, and that attempt's usage is not recorded.subscribeCommits()gets these commits only once they are stored, with exactly what was stored (held operations first; a document the commit retires shows as its retirement only, without the operations stored before it), and gets a publication for a deadline's store too; it no longer sees every partial. Migration: asubscribeCommits()listener that showed live progress should usewatchDoc()orConversation.watch(); one that mirrors Storage keeps working; setsettings.progress.persistWithinMs: 0to store progress right after each commit, about as before (one storage transaction per partial). -
The change type of
FileSystem.watch()in@earendil-works/pi-durable/envis renamed fromWatchChangetoFileChange(same shape:{ paths },{ overflow: true }, or{ error }), soWatchChangenames only a watch listener's change. Migration: importtype FileChangefrom@earendil-works/pi-durable/envwhereWatchChangewas imported from it. -
HostCallbackgains"telemetry": ahost_errorreport about a telemetry adapter that threw while a commit was published. Exhaustive switches overHostCallbackneed a case for it. -
ConversationView.entriesis a window over the transcript instead of the active transcript: the fork-aware historyConversation.entries()scans, in entry ID order, with head markers (compaction summaries, resets, handoffs) appended in place instead of cutting the entries before them. A watch starts with the newest 50 entries; new entries are appends, and past 100 the oldest leave in one splice down to 50, which also sets the newConversationView.before, the ID of the entry just before the window (absent when the window starts the transcript). First values and overflow replacements ([["r", view]]) hold at mostmaxentries, never the whole transcript. Migration: read the active transcript the model sees fromConversation.context(); render a transcript longer than the window withConversationTranscript, or page older entries withConversation.entries(); a client that rebuilt the head cut from the view's operations no longer gets one (#11327). -
Conversation.watch(context, window?)andHarness.observeConversation(id, observer, context, window?)take aConversationWindow(from,mindefault 50,maxdefault2 * min):min/maxbound the window, andfromstarts the first value at that entry ID when at mostmaxentries are at or after it, otherwise at the newestmin; it picks only that first value, so every entry committed after the attachment is appended, and afrompast the newest entry starts empty. Bounds that are not integers, ormaxbelowmin, reject with aRangeError. Each watch and observer has its own window, so the observers of one conversation no longer share one change object or one value; they share the document values (#11327). -
pi.liveis no longer empty after a run that ended without an answer: it keepsrunFailure(below) until a later run starts. Code that compares an idlepi.livewith{}, or tests for idleness that way, checksrun === undefinedinstead (#11327). -
Removed
watchEvents()and its typesAgentEvent,AgentEventStream,SnapshotEvent,MessageChange, andToolEventCall, and spec §9.4. A renderer renders state instead of assembling it from events: everything the events carried that a renderer draws is in the conversation view, typed for producer and consumer, and new information becomes a field there rather than an event type every client must learn (#11327). Migration, for a client ofwatchEvents():Before:
const stream = await watchEvents(harness, conversation.id, context); initialize(stream.snapshot); // entries, run, generation, tools, compactions, inbox, agent, usage stream.start(async ({ value: events }) => { for (const event of events) { if (event.type === "message_update") applyChanges(event.changes); // streamed text else if (event.type === "message_end") appendEntry(event.entry); else if (event.type === "tool_execution_update") applyOutput(event.toolCallId, event.output); else if (event.type === "run_end") showIdle(); // ... and every other event type } }); // After a drop: attach again; the new snapshot replaces everything held.After:
const transcript = new ConversationTranscript((query, limit, ctx) => conversation.entries(query, limit, undefined, ctx)); const watch = await conversation.watch(context); render(transcript.merge(watch.value)); watch.start(async ({ value }) => render(transcript.merge(value))); function render(view: TranscriptView): void { const live = view.docs["pi.live"] as LiveState; drawItems(view.items); // entries, a "load more" row per gap, "load earlier" at the top if (live.generation?.message !== undefined) drawStreaming(live.generation.message); for (const slot of live.tools ?? []) drawTool(slot); // status, running output, details, result entry if (live.runFailure !== undefined) drawFailure(live.runFailure); // why the last run ended without an answer setBusy(live.run !== undefined); } // A "load earlier" or "load more" row scrolled into view: render(await transcript.loadEarlier(context)); render(await transcript.fillGap(gap, context)); // After a drop: only what was missed when it fits the window, otherwise the newest entries and a gap. const resumed = await conversation.watch(context, transcript.resume);The watch's operations carry the same deltas the events did (text and thinking appends, tool-call argument appends, output trims and appends), for a client that forwards them, for example to a remote replica. Where each event went:
event state snapshotthe watch's first value, watch.value, its window bounded bymaxrun_start,run_endpi.live.runappears, disappearsturn_start,turn_endpi.live.run.taskIdmoves to the next generation; the task graph'spi.generationnodes,completingat their holdmessage_start,message_updatepi.live.generation.message, the streamed answer, with itsusagemessage_end,entry_appendedthe entry appended to entriestool_execution_start,tool_execution_update,tool_execution_endthe slot in pi.live.toolsornestedTools:statuspending, running, done;output,details,diagnostics;entryonce done (absent after a fault); a nested call'sarguments, itssummary, and its result in the caller'sNestedCallDocauto_retry_start,auto_retry_endpi.live.generation.retryset, removeddeferred_pollpi.live.generation.deferred.pollAtcompaction_start,compaction_enda status in pi.live.compactionsappears, disappears;pi.live.compactionFailurewhen it failed; the summary entry when it is placedinbox_updatepi.inboxagent_changed,usage_changedpi.agent,pi.usagesubmissionSubmission.status()andwait(),Harness.submission(id); queued items inpi.inbox, the run's inputs inpi.live.run.inputstask_failedthe task graph ( completingwith the outcome's status),Harness.getTask(), andonReport'stask_faulted; for a run,pi.live.runFailure; for a compaction,compactionFailure; for a tool, a done slot withoutentrya run that ended without an answer ( run_endwith anunansweredsubmission)pi.live.runFailure:reason(model_error,no_model,aborted,reset,faulted,orphaned),detail,taskId,inputsSome event data has no state in the view. A tool's arguments after repair and
beforeToolat its start: in the nested slot'sargumentsfor a nested call, only in the tool task's checkpoint for a model-issued one. A submission's settlement:Submission.status()/wait()andHarness.submission(id); an input settled without a run (withdrawn,stale, aborted while queued,run_failed) just leavespi.inbox. A failed task's error:Harness.getTask()andonReport; the task graph keeps only live tasks, not terminal outcomes. A nested call's full result: its caller'sNestedCallDoc(watchDoc()), which retires when the caller settles. Exact turn boundaries: the run'staskIdand the task graph, with no explicit event. Whether a compaction did anything: itsCompactionResult(waitForTask()), and the summary entry when it is placed. -
Restart-limited tasks no longer park: a task cut off
settings.restartLimittimes in a row ends instead, visibly. A tool call ends with an error result (diagnostic coderestart_limit) and its task fails with detail{ reason: "restart_limit" }, a compaction fails intopi.live.compactionFailure, a generation ends its run withpi.live.runFailurereasonrestart_limit(its inputs settleunansweredwith that reason), and a task of an extension's kind endsfaultedwith detail{ reason: "restart_limit" }, reported astask_faultedwith reasonrestart_limit. The built-in tasks are reported astask_interrupted(below). An abort handler cut off at the limit still faults its task, but a run someone aborted now ends withrunFailurereasonaborted, the cut-off asdetail, and an aborted compaction leaves nocompactionFailure.Harness.retryTask(), therestart_limitblocked reason ofTaskInspectionandTaskGraphNode, and thetask_parkedreport (and its telemetry value) are removed. Migration: a parked task kept its conversation busy untilretryTask(); it now ends, so showrunFailure,compactionFailure, the tool's error result, or thetask_interruptedandtask_faultedreports instead, and to run the work again, submit it again (a new input,compact(), or a new task); raiserestartLimitbefore the task is next reserved to let it run longer (#11139). -
A generation whose model request was in flight when the host died no longer resends it on open: the attempt counts as failed under
settings.retry. Its partial becomes an aborted entry, as before; the next attempt waits for the backoff, shown inpi.live.generation.retry, and with no retry left the run ends withpi.live.runFailurereasoninterruptedand the inputs settleunansweredwith that reason. A deferred poll whose fetch was in flight is charged the same way, even when the replacement host's clock is behind, and its next attempt polls the same deferred response again instead of submitting a new request; a run that ends instead cancels it. A close still resends.restartLimitstill bounds these phases: a charge that itself keeps being cut off ends the runrestart_limit, past the limit without converting the partial (#11139). -
Watch listeners and synchronous observers take Chord's tagged watch shapes. Durable re-exports
WatchCallandNativeWatchCallinstead ofWatchChangeandNativeWatchChange; a listener gets{ kind: "value", value, ops, retired }. Chord's{ kind: "failed", error }call, for a source that recovers, never comes from Durable, whose failures end the watch.WatchEndis tagged bykind, and a watch whose acquisition context is aborted endsaborted(wascancelled). Before:watch.start(async ({ value, ops }) => render(value, ops)),if (end.reason === "cancelled"). After:watch.start(async (call) => { if (call.kind === "value") render(call.value, call.ops); }),if (end.kind === "aborted"). -
Observer<T>(observeDoc(),observeConversation(),observeTaskGraph()) has the watch's shapes:advance(call: WatchCall<T>, context)(always avaluecall) andend(end: WatchEnd):endedat close or after a task document's retirement with its task (wasundefined),failedwith the error that failed the Session (was{ error }), andlistener_errorwith the error for an observer that threw (was{ error }), now also for one whoseadvancereturns a promise that rejects. Before:{ advance: ({ value }) => push(value), end: (failure) => failure && fail(failure.error) }. After:{ advance: (call) => call.kind === "value" && push(call.value), end: (end) => end.kind === "failed" && fail(end.error) }. -
subscribeCommits(listener)isobserveCommits(observer)with the observer shape:{ advance(publication, context), end(end) }, returning{ detach() }. Its observation has novalue: commits are events, and the Session does not know Storage's newestseqbefore its own first commit.endcomes once,endedafter the last publication at close orfailedwhen the Session fails; an observer that throws (or whoseadvancerejects) is reported, detached, and endedlistener_error(a throwing listener stayed subscribed). Before:const unsubscribe = harness.subscribeCommits((publication) => apply(publication)); unsubscribe();. After:const observation = harness.observeCommits({ advance: (publication) => apply(publication), end: () => {} }); observation.detach();. -
HarnessOptions.onReport(report)takes oneReport: the fields ofReportInfo, tagged bykind(wastype), and theerror(was the first argument).session_failedisstorage_failed, andtask_outdated's reasonincompatible_taskis the scheduler's own word for why the replacement cannot take the task:task_too_old(older than the task) ormigration_failed(newer without amigrate), as a blocked task shows. Thepi.durable.reportevent andpi.durable.reportsmetric keep theirtypeattribute, with the new values. Before:onReport: (error, info) => { if (info.type === "session_failed") restart(error); }. After:onReport: (report) => { if (report.kind === "storage_failed") restart(report.error); }. -
DocumentCommitChangeis tagged: a document change is{ type: "document", kind: "change", record, conversationId, version, value, ops }and a retirement{ type: "document", kind: "retire", record, conversationId }(wasvalue: nullandversion: undefined). Before:if (change.type === "document" && change.value !== null) use(change.value). After:if (change.type === "document" && change.kind === "change") use(change.value). -
CompactionStatus.reasonandCompactionFailure.reasoninpi.livearetrigger(what started the compaction; a run failure'sreasonis why it failed).pi.liveis version 2: itsmigraterenames the field in a stored version 1 value when it is read, and the next commit that writespi.livestores it at version 2, so code built against version 1 cannot read a conversation this version wrote to. Before:live.compactionFailure?.reason. After:live.compactionFailure?.trigger. -
TaskInspection.stateusesTaskState's word:{ kind: "pending", migrates }(wasready). Before:state.kind === "ready". After:state.kind === "pending". -
FileChange(FileSystem.watch()in@earendil-works/pi-durable/env) is tagged bykind:{ kind: "paths", paths },{ kind: "overflow" }, or{ kind: "failed", error }(was{ paths },{ overflow: true },{ error }), andFileWatcher.close(context)isstop(context). Before:if ("overflow" in change) rescan(); else if ("paths" in change) reload(change.paths); await watcher.close(ctx);. After:if (change.kind === "overflow") rescan(); else if (change.kind === "paths") reload(change.paths); await watcher.stop(ctx);. -
SessionEnd(Session.closed,Harness.closed) is tagged bykind:{ kind: "closed" }or{ kind: "failed", error }(wasreason). Before:harness.closed.then((end) => { if (end.reason === "failed") reopen(end.error); }). After:harness.closed.then((end) => { if (end.kind === "failed") reopen(end.error); }). -
ReportFrom, the second argument of a task'sruntime.report(error, from), is tagged bykind:{ kind: "extension", extension? }or{ kind: "host", callback }(wastype). Before:runtime.report(error, { type: "host", callback: "env" }). After:runtime.report(error, { kind: "host", callback: "env" }).
Added
- Deferred commits:
Session.commit(),Conversation.commit(),TaskRuntime.commit(), and a tool'sapi.commit()take{ persistence: { kind: "deferred", withinMs? } }. A commit that changes only existing conversation documents withhistory: "latest"andfork: "initial"is then adopted in memory and shown to watches at once, and stored with the next commit that reads or writes the document, before the document leaves memory, at close, or withinwithinMs(defaultsettings.progress.persistWithinMs, orcreateSession(storage, { persistWithinMs })); any other write makes it immediate. A crash loses what is held. See spec §4.1. - Synchronous observers for adapters, such as a Chord source over a Durable view:
Session.observeDoc(token, ...scope, observer, context),Harness.observeConversation(id, observer, context), andHarness.observeTaskGraph(observer, context)attach anObserver<T>(advance(change, context),end(failure)) atomically on the Session line, like a watch, and return anObservation<T>(value,detach();observeDocgivesundefinedfor an absent document).advancegets every change unfolded as memory adopts it, for a stored commit inside Storage'sadoptand for a deferred one before it is stored, so it must only record it: no awaits, no Session calls, no throws. A document observer gets one call per change at its address (two for a commit that retires and recreates it), the task graph also a call outside any commit when a registry change or a failed migration changes ablockedreason, and a change can arrive before the attaching promise resolves. The attaching context governs only the attachment; a closed Session or an invalid argument rejects the promise. One that throws is reported aslistener_error, detached, and ended with the error.endcomes once, at Session close or failure, or after a task document's retirement with its task. Document, view, and task graph watches are built on them (spec §9.1). ConversationTranscriptkeeps what a client has of one conversation over anyConversationView:merge(view)returns the view withitems, the client's whole transcript (entries, agapwhere a later window did not continue it, and anearliermarker until the start is loaded), instead of the window;loadEarlier(context)andfillGap(gap, context)page entries through a loader such asConversation.entries(), andresumeis the window that continues it after a drop:conversation.watch(context, transcript.resume). A merge costs O(items) and returns the sameitemsarray when it adds nothing; concurrent loads of the same page are shared (#11327).pi.live.runFailure(RunFailure,RunFailureReason) records why the newest run ended without an answer,model_error,no_model,aborted,reset,faulted, ororphaned, with the run's task and inputs and adetailwhere one exists (the error text, the missing model, the fault, the orphan reason). The commit that ends the run sets it; a later commit that starts a run removes it (#11327).RunFailureReasongainsinterrupted(the host stopped while the model was answering, with no retry left) andrestart_limit(the run's task was cut offsettings.restartLimittimes in a row) (#11139).onReportgetstask_interrupted(reasonrestart_limitorinterrupted,restarts, and the task) when crashes end a built-in task: a tool call, a compaction, or a generation at the restart limit, or a run that endsinterrupted. The telemetry report attributes gain the typetask_interruptedand the reasoninterrupted(#11139).HarnessOptions.readOnlyopens a Harness as a viewer of a session another process drives: open leaves running tasks as committed instead of recovering them, every commit with writes rejects withReadOnlySessionbefore it reaches Storage, andresume()and every call that would run tasks reject with it.
Changed
- Document, conversation view, and task graph watches use Chord's watch handles (
Watch). - A stored commit is published when Storage adopts it, inside
Storage.commit(): the commit's telemetry events and Durable's own observers (document watches, conversation views, the task graph, the scheduler, and waits) run insideadopt, so two views never show one commit apart.subscribeCommits()listeners run one microtask later, outside the storage's synchronous step, before every wait the commit resolves and every abort signal it fires; they have no order relative to watch listeners andonWake. With a storage that works after adopting (JSONL's sidecar reclaim), all of these run beforeStorage.commit()resolves. subscribeCommits()listeners are read when a commit's dispatch runs: a listener added between adoption and the dispatch gets the commit only when one was registered at adoption; one added after the dispatch ran misses it.- The abort signal of a newly marked running task fires after
subscribeCommits()listeners instead of before them. - A throwing Durable commit observer fails the Session after
Storage.commit()returned, after the other observers and the host listeners got the commit; the commit still stands. When Storage also rejects that commit after adopting it, the storage error fails the Session and the observer's error is reported aslistener_error.
Fixed
- Fixed a tool round with
control.handoffending the run on the tool-calling answer: the handoff'spi.resetentry is written and the same run continues with a new generation in the new context, so the submission settles with the eventual answer. Queued writes and selected steers are placed after the handoff text, follow-ups wait for the run's final boundary, and a queued reset still ends the rununansweredwith reasonreset.terminateremains the way to end a round without another model request. - Fixed a conversation watcher (conversation views) holding a copy of a streamed text or tool call per partial commit, through Chord append ops that kept the whole string alive; a 140 KB answer followed by a 140 KB tool call held well over 100 MB (#9265)
- Fixed a nested call's error summary keeping the call's whole output alive through a slice of it (#9265)
- Fixed task span error messages and codemode call previews keeping the whole text they were cut from alive (#9265)
- Fixed partial commits of a streamed answer copying every growing text, thinking and tool-call argument string in full on each commit (about 20 s of CPU and a 100 MB heap peak for a 500 KB tool call): they now append new text with Chord's
appendText(), and apply the argument changes of their own parse of the streamed argument text (#9265) - Fixed stored assistant messages lacking
thinkingLevel: a generation records the Pi thinking level its request asked for on the response, also after polling a deferred one, as pi-agent-core's agent loop does - Fixed partial commits polluting
Object.prototypewhen a streamed tool call's arguments gained a__proto__member after an earlier commit: the merge read the missing member through toObject.prototypeand wrote into it - Fixed a commit that Storage rejects after adopting it (a failed JSONL reclaim) publishing nothing: it is published and its waits resolve before the Session fails, so a replica built from
subscribeCommits()stays equal to Storage andpi.durable.tasks.activestays balanced. - Fixed a throwing telemetry adapter (a commit's
pi.durable.entryorpi.durable.submissionevent,pi.durable.tasks.active) rejecting a durable commit and leaving the views and the scheduler without it: it is reported ashost_errorwith callback"telemetry", and the commit resolves. A throwing report metric or report event is dropped. - Fixed a host that crashes during a model request resending it forever, adding an aborted entry each time: the interrupted request is a failed attempt under the retry policy, and the run ends with
runFailurereasoninterruptedonce no retry is left; other work cut offrestartLimittimes ends instead of keeping its conversation busy (#11139) - Fixed the Code Mode extension loading pi-codemode's WASM QuickJS runtime (
quickjs-wasi) although it only runs scripts in the sandbox the host passes: it importstoCodemodeIdentifierfrom@earendil-works/pi-codemode/declarationsinstead of/portable(#11254)
[1.4.0] - 2026-10-21
Breaking Changes
TaskRuntime.sleep()is removed: it waited inside a phase, which holds an invocation and, after a restart, reruns the phase and restarts the wait. A task now ends its phase asleep withruntime.sleepUntil(until, checkpoint, context)or by returning{ status: "sleeping", until, checkpoint }fromruntime.commit(); move the work after the wait into the next phase and carry what it needs in the checkpoint.TaskRuntime.setTimer()paces work inside a phase without waiting for it.- Tasks have a
sleepingstatus, so code that handles everyTaskState,TaskGraphState, orTaskInspectionstate needs a case for it. - Opening a SQLite storage migrates it to schema version 2 automatically, rebuilding its task table. A migrated database cannot be opened by 1.3.0 or earlier, so a deployment cannot roll back past this release. JSONL storage needs no migration, but 1.3.0 or earlier never resumes a sleeping task it finds (a run's conversation stays busy).
TaskRuntimehassleepUntil()andsetTimer(), andToolExecutionApihasnow(): code that builds either object by hand, such as a test fake or a tool wrapper that does not spread the original, must add them.- A task cut off by a crash 5 times in a row without committing a new state is parked instead of run again (see the crash-loop guard under Added); set
settings.restartLimittoInfinityto keep the old behavior.TaskInspection's blocked reasons includerestart_limit. defineDoc()anddefineDocFamily()require an explicitcheckpointWhenpredicate on every definition; there is no default. Use() => falseto keep ordinary changes as deltas, or supply a policy that periodically writes a base.
Added
- Added
IndexedDbStorage(@earendil-works/pi-durable/storage/indexeddb), a browser storage backed by IndexedDB. HarnessOptions.telemetryemits the content-freeDURABLE_TELEMETRY_SCHEMA: public submission admission spans, task phase spans (including extension tasks), committed entry and submission events, running phase-change checkpoints, and nested-tool replay events. Optional propagation stores opaque carriers on submissions and tasks so queued inputs and reopened tasks retain their trace;TaskOptions.traceaccepts a carrier override or"root"(absence inherits the creator's carrier); creation-timelinksconnect inputs sharing a run, while steer admissions link to the running trace. Internal admissions emit events without a submit span. Optional metrics record phase duration and live task counts. Failed phases record fixed error-status categories (task_faulted,task_failed,task_orphaned) and diagnostics capped at 500 characters; aborted phases keep statusok. EveryonReportreport also emits a fixed-fieldpi.durable.reportevent on its current span (dropped by the NOOP span when there is none), plus api.durable.reportscounter by type; report telemetry contains no error payload and leaves the callback unchanged. Clock failures report without a phase context. Generation and compaction forward their phase context to pi-ai requests.settings.compaction.modelOverridessets compaction thresholds per model, keyed by exact"provider/modelId", so one harness can serve small- and large-window models; the threshold check, overflow recovery, and the compaction task use the entry of the model they act for (#10942).- Durable sleeps: a sleeping task holds no invocation, survives restarts, and resumes at its checkpoint once the Harness clock reaches
until. HarnessOptions.setTimerarms the timers of the Session, the scheduler, and its tasks (progress throttles, idle-memory eviction, sleeps), also forcreateSession(); withnow, they run on a host or fake clock. A foreground timer the host throws on or declines falls back tosetTimeout.ToolExecutionApi.now()reads the Harness clock.Harness.wake()andHarnessOptions.onWaketell a host when the Session next needs a process:activewhile work can run,atfor the earliest sleep. WithonWake, the Harness keeps no timer for sleeps, so a Cloudflare Durable Object can hibernate and wake on its alarm, callingresume().- Crash-loop guard: open counts the restarts of each task that a crash, eviction, or reset cut off (
TaskRecord.restarts); a close writes the tasks it stopped back aspendinguncounted, and a new state the task commits starts the count over. Atsettings.restartLimitthe task is parked: blocked with reasonrestart_limitininspect()and the task graph, not active inwake(), and reported once.Harness.retryTask(id)runs it again. An abort handler cut off that many times ends its taskfaulted. onReport(error, info):info(ReportInfo) says what happened intype:session_failed;task_faulted,task_parked,migration_failed,task_outdated, ortask_errorwith the task and the extension that installed it;extension_errorwith the extension's name;host_errorwith the failingHostCallback; orlistener_error.settings.afterFailedRun: a run that fails withmodel_errororno_modelkeeps the inputs queued behind it (keep, the default), starts the next run with them (continue), or settles themunansweredwith reasonrun_failed(withdraw).- The task graph shows why a task cannot run (
TaskGraphNode.blocked:missing_task,task_too_old,migration_failed, orrestart_limit) and follows registry changes and failed migrations. - Added
HarnessOptions.identity(a pi-aiClientIdentity) to set theUser-Agentand provider attribution of every model request through the Harness, including hooks and tools.api.modelsin tools and hooks is now a wrapper of the host'sModelsthat adds the identity, not the same object. HarnessOptions.modelsandHarnessOptions.settingsalso accept a function returning the current value, likeenv. Generation, compaction, hooks and tools call it at each use (api.modelsreads the current value at each access), so a host can replace its model configuration or settings without reopening the Harness. A plain object still works.
Changed
- A task phase that faults is reported through
onReport(astask_faulted), not only recorded in its outcome. onReportgets a second argument,info, andTaskRuntime.report()takes an optionalfrom(see Added); anonReportwritten for one argument still works.- Generation retry backoffs, deferred-response polls, and compaction retry backoffs sleep instead of waiting in a running phase, so a process can stop or hibernate during them. A record an earlier version stored mid-backoff sleeps again when it resumes before its time. A deferred poll whose model is gone after a reopen now fails
no_modelonce the poll is due, not at once. - Code mode measures script deadlines and wall time on the Harness clock (
HarnessOptions.now) instead ofDate.now(). - SQLite drivers, portable interfaces, and the generic migration runner now come from
@earendil-works/chord/sqlite. Existing Durable SQLite entry points keep re-exporting their public names; storage helpers and Durable schema migrations stay here. ToolControl.terminateis now typedbooleaninstead oftrue, matchingpi-agent-coreandpi-coding-agent;falsedoes not end the run (#10858).
Fixed
- In Cloudflare Workers with
nodejs_compat, the timers that evict idle documents and contexts were armed, since timers there have anunref(); a pending one kept a Durable Object from hibernating and blocked its eviction. They are now declined in Workers, and memory is freed at later commits. - The README's Errors section now limits the
StorageRequestErrorexemption to reads: aStorageRequestErrorthrown bycommit()ormintId()fails the Harness like any other storage error (#11014). - The Node environment now detects the legacy WSL
bash.exelauncher from%SystemRoot%instead of assumingC:\Windows(#9501 by @petrroll).
[1.3.0] - 2026-10-15
Added
SqliteStorage.open(database, { prefix })can namespace every table and index;openNodeSqliteStorage()andopenDurableObjectSqliteStorage()forward it, for databases shared with host tables.
Changed
- Cloudflare Durable Object SQLite adapters created for the same storage object now coordinate their operations, allowing multiple Pi storages to safely share one Durable Object database.
Fixed
- The system baseline written after a compaction now leads the model context when the kept history includes an assistant message, as does a first baseline written after earlier answers, instead of following the new input; Anthropic and OpenAI Codex requests sent it as a mid-conversation system message without an initial prompt or tool set. Other system messages after an assistant message stay in place (#10904).
toBase64, used byreadand the Photon image processor, no longer takes about 140 MB of heap to encode a 3 MiB image, which exceeded the 128 MB memory limit of a Cloudflare Durable Object; it now builds a binary string 8 KiB at a time and encodes it withbtoa(#10923).
[1.2.0] - 2026-10-12
Breaking Changes
ToolTaskInputandToolTaskResultare tagged unions: a model-issued call is{ kind: "model", ... }with its previous fields, a nested call{ kind: "nested", ... }.pi.toolis version 2 and migrates live version 1 tasks.ToolExecutionResult.contentis nowoutput, next to the newstructuredOutput.bashandpowershellanswer a nonzero exit with an error result carrying anexit_codediagnostic, instead of throwing (tool_error).- Any error a
Storagemethod throws, a read included, now fails the Session, which closes itself: every later call and every pending wait rejects withSessionFailed, whosecauseis that error, and nothing is retried.StorageRejectedis removed; a storage retries its own transient failures and throws the newStorageRequestErrorfor an invalid request, which fails only that call. A throw in the scheduler's own commits, or in the commit listeners of the Harness's components, fails the Session too. subscribeCommits()andsubscribeClose()listeners that throw, or return a rejected promise, are reported throughonReportinstead of failing the operation that ran them.- A display-only write submission, one of only
kindanddata(nomodel,head, oredits), is appended and settleddoneat once, even while the conversation is busy or has queued items, instead of waiting inpi.inboxfor the next boundary; only a queued reset still holds it back, so the reset does not hide it. It changes nothing the model sees, so a chat message shows as soon as it is sent, ahead of earlier submissions still queued, and it no longer places items left queued after a failed run (#10407).
Added
- Optional
ExecutionEnv.listFiles(path, options, context)for bounded, gitignore-aware tree listings (ListFilesOptions,FileListing,FileListEntry);registerEnvConformancetakes alistFilesoption to cover it. - Input submissions take
entry: { kind, data }(InputEntry): the input is placed as an entry of that kind carrying that data, with its content as the user message, instead ofpi.user, and behaves as any other input; the kind must not start withpi.. Queued inputs carry it in theirpi.inboxitem (#10407). Session.closedsettles once the Session has closed, Storage included:{ reason: "closed" }afterclose(), or{ reason: "failed", error }after a storage error.WatchEndgains{ reason: "session_failed", error }, and the README has an Errors section.ToolExecutionApi.executeTool(name, args, context, { key?, progress? }): a tool calls another tool as a nested call. The nested call is its ownpi.tooltask owned by the caller, runs validation, theToolTaskhooks (whoseToolHookCallcarriesparent), output limits, and its replay policy, and returns aNestedToolExecutionResult(itstaskId,structuredOutput,details,diagnostics,usage,isError,durationMs, but not the model'soutput) to the caller instead of the transcript. Each nested call is a member ofNestedCallDoc, a task-scoped document family of the caller keyed by the call's key, holding itstaskIdand, once it ends, itsresultas returned, so it is gone from storage once the caller settles; its task's receipt stays small. Keys, by default the call's position, let a replay-safe caller's rerun reattach to its nested calls; a caller that is not replay-safe has its unfinished nested calls abandoned after a restart. Nested calls show inpi.live.nestedTools, with the arguments they run with and asummary(error, duration, usage) once done (progress: falsekeeps their running output out), and as tool events withparentToolCallIdandparentTaskId; every tool event also carries its call'staskId. A caller aborts the nested calls it left running before it settles.- Structured tool output: a tool declares
structuredOutputSchemaand returnsstructuredOutput, which the Harness validates and gives to programs that call the tool; a tool without a schema gives them its bounded output, one text item as a string, one image as itself, and otherwise the content list, for errors too.structuredOutputis always the tool's own value: a schema tool's error result keeps the value it returned, and the text of one without becomes atool_errordiagnostic of the nested result, as a thrown error's message does. A nested call with invalid structured output gets an error result; a model-issued one only loses it, and the host gets a report.api.retainedOutput()reads the bounded output the model will see.bashandpowershellreturn{ output, truncated, fullOutputPath?, exitCode }. ToolRegistration.callers(model,tools, or both, the default) andpi.agentmodelTools: who may call a tool, and which of its tools a conversation offers the model;Agent.callablelists the tools nested calls resolve among.addToolsalso extendsmodelTools.- Deferred tools:
ToolRegistration.deferredkeeps a tool from the model untilmodelToolsnames it, in its array or its newadd({ remove?, add? });control.addToolswrites names toadd, and loaded tools follow the others in load order, so a load only appends declarations.Agent.deferredlists the deferred tools not loaded yet.@earendil-works/pi-durable/tool-searchprovides the coding agent'stool_searchtool, which searches them with BM25 and loads the matches. Thecodemodesection leaves deferred tools out. TaskOptions.abandonOnRestart: a task its creator awaits only in memory is aborted, with its owned work, when a later Harness starts scheduling, before any of it runs again. Its mark carriesabortReason: "restart", which cascades; such a task waits for a missing definition instead of becomingorphaned. Nested calls andapi.createTask()children of tools that are not replay-safe get it by default. No task below an owner with cancellation intent starts a run phase any more, even before the cascade marks it.TaskRuntime.abortOwned(id, context): abort a task this task owns and wait until it is terminal.TaskRuntime.ownedTasks(context): the live tasks a task owns directly, whichever invocation created them, as copies. A tool call settling finds the nested calls it left running with it.@earendil-works/pi-durable/codemode: acodemodetool (createCodemodeExtension({ sandbox })) whose scripts call the conversation's tools as nested calls and survive a restart: the script is replayed deterministically from a journal of the results it got, written before each delivery, reattaching to its nested calls, and then continues. Divergence, a changed sandbox fingerprint or module version, and a passed deadline end the call with an error. As in the coding agent, acodemodeprompt section lists the tools scripts can call (namespaces, an inline token budget), scripts find tools withsearchTools(),describeTool(), anddescribeNamespace(), and the result is laid out with a header, text item markers, a console block, truncation tomax_output_tokenswith a spill file, and saved images. Scripts getmodels.*(the catalog,models.classify(),models.generateImages(); the last two as nested calls of internal tools, at most four at once), and the tool declares the Lark grammar of its source for models that support grammar-constrained sampling. A failed call rejects in the script with its text, except an error result of a schema tool with its own value, which resolves:tools.bashgives{ output, exitCode, ... }for a nonzero exit. Scripts keepstore()/load()values per conversation, forked as of the fork's entry. The result'sdetails.callslist the script's tool calls with their status; live progress is inpi.live.nestedTools(npm run bench:codemode).readreturns images as one image block instead of anunsupported_imageerror: PNG, JPEG, GIF, and WebP within the model's image limits (by default 2000x2000 pixels and 4.5 MB of base64) as they are, or, withcreateCodingTools({ images }), oriented, converted, and shrunk to fit.@earendil-works/pi-durable/imagesprovides a Photon (WebAssembly) image processor, with/images/nodeand/images/cloudflareloaders;/images/nodeprepares images in a worker thread, so a large photo never blocks the event loop, and the thread exits after 30 s without images; nothing loads it unless imported. A model without image input gets a diagnostic saying it sees a placeholder.pi.live.compactionFailurekeeps the newest compaction failure (task, reason, error) until a compaction produces a summary; the agent events' snapshot carries it ascompactionFailure, andcompaction_endcarrieserrorfor a compaction that failed. A failed background or manual compaction was invisible once its status was removed.
Fixed
-
A wait that closes a cycle through waits and held owners is rejected by
runtime.commit(), naming the cycle, instead of leaving every task on it waiting forever; waiting on itself or on an owner chain were the only cycles caught. A background task may now wait on the owner of its conversation, which is no cycle (#10411; tests and approach from #10533 by @odysseus0) -
Appending to an array in a document no longer costs a walk over the whole array per commit: Chord's delta tracker plans inserts and removals that keep the remaining elements in order from the changed ranges alone, and builds an appended array in one copy instead of two. 32,000 one-item appends, one commit each, take 1.4 s instead of 11.3 s; what remains is the copy each immutable value needs (
npm run bench:document-append). -
A generation whose blocking threshold compaction failed, faulted, was orphaned, or was aborted directly now fails with
model_error(Compaction failed: <error>) instead of sending its request anyway. The context was still above the blocking threshold, so the request at best left no room for the answer: a session at 996K of a 1M window got an emptylengthanswer on every turn, with no visible error. -
Compaction no longer includes thinking in the summarization request. Replayed thinking is often not in the live context, so a request that included it could be larger than the context it summarized and fail with "prompt is too long" on every attempt.
-
A throwing
onReportno longer replaces the error being reported or becomes an unhandled rejection, a throwingnow()is reported once andDate.nowused, and a watch listener's error is reported as well as ending the watch withlistener_error. -
A task whose fault write failed no longer runs again in the same process.
-
The scheduler no longer visits every live task on each pass: abort cascades start only from tasks with cancellation intent, owned live work and idle scopes are walks down an in-memory ownership index, and reservation, finalization, and failFast checks keep their own candidate sets. A chain of 500 owned tasks that took 12 s to settle takes 50 ms, 20,000 take 1.5 s; a tool making 8000 parallel nested calls finishes in 2.7 s instead of 18.8 s, with one document per nested call instead of one growing index (
npm run bench:scheduler-fanout). -
The scheduler's ownership indexes are bounded by live work: it keeps a conversation's owner and an ended task's ownership only while live work is below them, instead of every conversation and subagent chain it ever saw. Work that later appears in an old conversation loads its chain from storage again. After 10,000 ended subagent calls under a live parent it kept 10,000 ended tasks and 10,001 conversation edges; now none of either beyond the parent's conversation (
npm run bench:scheduler-memory). A queued input no longer makes the scheduler scan every queued submission when nothing is being cancelled. -
The Session's document cache is bounded by use: a loaded document that no watch or document state observes leaves memory once it was not read or written for
documentRetentionMs(new inHarnessSettingsandcreateSession()options; default ten minutes,0drops it right after use) and loads from Storage again on its next access. It held every conversation and session document ever touched, built-in and third-party, for the life of the process: 5,000 conversations kept 26,000 documents and about 3.8 KB each; with retention 0 they keep none (npm run bench:document-cache).
[1.1.0] - 2026-10-07
Breaking Changes
Storageimplementations must honor the neworderfield ofConversationQuery,EntryQuery,TaskQuery, andSubmissionQuery, and continue a cursor in the order it was returned with. A storage that ignores it returns pages in the wrong direction; the conformance suite covers both orders (#10546).TaskRuntime.context()takes the cutoff as an options object, matchingConversation.context():runtime.context(conversationId, context, { at })replacesruntime.context(conversationId, context, at).
Added
ToolExecutionApi.modelsandHookApi.models: the Harness'smodels, so tools and hooks can resolve models and make requests with the same catalog, credentials, and request transforms as generation (#10395).Conversation.context(context, { at })returns the model context as of a visible earlier entry, the same viewfork(at)would start with, without creating a conversation (#10512).ScanOrder(ascendingordescending) asorderon conversation, entry, task, and submission scans, includingTx.scanTasks()andConversation.entries(), so hosts can page the newest tasks first. Defaults are unchanged: entries newest first, everything else oldest first. A cursor continues in its scan's order, so the query may omitorder; asking for the other order with it throws (#10546).- Task records carry
startedAtandendedAt, wall-clock times the Session stamps at the first change torunningand at the change toterminal, withHarnessOptions.nowor the newcreateSession(storage, { now })option.startedAtsurvives waits and reopen.inspect()shows them on each live task's record. Records written by earlier versions have neither (#10549). pi.tool-resultmessages carrydurationMs: how longexecute()took in that attempt, measured with a monotonic clock. Calls that did not execute, and interrupted or aborted calls, have none (#10549).- Assistant messages carry the
durationMspi-ai measures for each response (#10549). openDurableObjectSqliteStorage(ctx.storage)in@earendil-works/pi-durable/storage/sqlite/cloudflare: SQLite storage on a SQLite-backed Cloudflare Durable Object.settings.contextRetentionMs(default ten minutes): how long an idle conversation keeps its last context read in memory;0drops it once idle.
Changed
runtime.context()keeps each conversation's last read range and derived view in memory: a later read by any of its tasks with the same head marker scans and derives only the entries committed since. A generation no longer rereads and re-derives the whole transcript for each model request. Busy conversations keep it; idle ones forsettings.contextRetentionMs.
Fixed
- A conversation's first system message, and the baseline after a compaction or reset, now leads the model context instead of following the input that started the run. Providers with native mid-conversation tool changes, such as Anthropic, keep the prompt cache across later tool changes instead of rewriting it in full (#10542).
[1.0.4] - 2026-10-05
Breaking Changes
NodeExecutionEnv.watch()fails withpermission_deniedwhen a target, or a watched directory itself, cannot be read for lack of permission; before, it was watched as if missing. Later rescans that hit this report{ error }withpermission_deniedinstead ofinvalid.- The env conformance suite checks three more
watch()behaviors: changes to the file a watched symbolic link points to, recursive coverage below a target that a non-recursive target overlaps, and a directory replaced at the same path. Custom environments that passed the 1.0.3 suite may need changes.
Added
createPowerShellTool()in@earendil-works/pi-durable/tools: apowershelltool that runspwsh, else Windows PowerShell, directly through argvexec(no other shell parses the command), with UTF-8 output and thebashtool's output window, spill and errors.
Fixed
- The
readtool reads a file that grows while it is read (an active log) instead of failing with "changed while it was read"; it reads again only when the file shrank or was rewritten in place. NodeExecutionEnv.watch(): a directory replaced at the same path gets a new native watcher; a target that is a symbolic link to a file reports changes to that file; a non-recursive target no longer stops an overlapping recursive target from covering subdirectories; closing during a rescan no longer leaks watchers.- Bounded tool output keeps a U+FEFF at the start of the retained tail, and drops a byte-order mark only at the very start of byte output.
settings.progressfields given asundefinedkeep their defaults.
[1.0.3] - 2026-10-05
Breaking Changes
FileSystemrequiresopenBinaryReader()andopenDirReader(); custom environments must implement them.BinaryReaderrequiresscanLines().FileSystemrequireswatch().Shell.exec()accepts an argv array besides a shell string, andShellExecOptions.onOutputreceives a thirdinfoargument naming the stream (stdoutorstderr); custom environments must accept both forms and pass the stream.
Added
openBinaryReader()for bounded positional reads of one opened regular file, withnoFollowto refuse a final-component symlink.openDirReader()for paged directory listings that read metadata only for returned entries.- Argv form of
exec(), which runs a program without a shell. createEnvConformance()andregisterEnvConformance()in@earendil-works/pi-durable/testingfor checking customExecutionEnvimplementations.settings.progresswithpartialIntervalMsandoutputIntervalMsconfigures how often generation partials and running tool output are committed; defaults stay 100 ms (#10357)ShellExecOptions.windowandShellOutputInfo.skipped: an environment may omit shell output outside the caller's retained tail and report the omission, so remote environments need not transfer output the caller drops.ToolExecutionApi.outputWindowprovides the window andoutput(chunk, skipped)counts omissions; thebashtool passes them through.BinaryReader.scanLines()locates and measures a span of lines in one pass inside the environment;LineScanner,StreamDecoder,rangeDecoder()andstartsWithBom()in@earendil-works/pi-durable/envlet other environments decode and scan exactly likeNodeExecutionEnv.FileSystem.watch()reports changes to files and directories, recursive with excludes, including missing targets, with explicitoverflowanderrorand anativeorpollingmode.NodeExecutionEnvpolls on Windows (native watchers there keep directories open, which blocks renaming their parents) and on network and FUSE file systems, and on macOS rescans shortly after installing native watchers because FSEvents misses changes made right afterfs.watchreturns; itswatchoption sets the mode, poll interval, and directory limit.
Changed
- The
readtool reads only the file's header, one scan, and the lines it shows, instead of loading the whole file; its results are unchanged.
Fixed
NodeExecutionEnv.flushFile()on a directory fails withis_directoryon Windows, as on POSIX.- Tail-retained tool output no longer depends on when progress commits happened: a progress snapshot compacted the stored output to the kept window, which could move where a later window's first line started.
NodeExecutionEnvshell output and text line readers no longer drop a U+FEFF that follows a chunk boundary; Node's streamingTextDecoderwith BOM handling dropped it, unlike decoding all of the bytes at once.
[1.0.2] - 2026-10-04
Fixed
- Persisted a distinct provider session UUID per conversation and forwarded it for prompt-cache and session affinity (#10424)
[1.0.1] - 2026-10-03
[1.0.0] - 2026-10-01
Added
- Initial release of
@earendil-works/pi-durable, a durable agent harness. See the README and the design document.