[Unreleased]
- The npm packages ship unscoped:
lousho(SDK),lousho-studio(Studio) andcreate-lousho(scaffold). The@linuxdevil/*scoped names from alpha.118/119 are dropped — they were never published to npm, sonpm install loushocontinues the existing package line.
[1.0.0-alpha.119] - 2026-11-14
[1.0.0-alpha.118] - 2026-11-14
- Breaking: the npm package is published unscoped as
lousho(the@linuxdevil/loushoscoped name from this cycle was never published and is dropped). Studio ships separately aslousho-studio. Update dependencies from"@linuxdevil/lousho"to"lousho"and"@linuxdevil/studio"to"lousho-studio". Theloushobinary name is unchanged, sonpx lousho …andlousho …commands keep working. - Docs:
docs/agent-forge.mdis retitled Lousho Studio and now documents installing the separatelousho-studiopackage, workspaces, which SDK runs a workspace’s agents (with each banner), the collector, and reporting deployed agents viaLOUSHO_OBSERVE_PROJECT. - Breaking: Studio is now the separate package
lousho-studio; the SDK tarball no longer containsapps/agent-forge.lousho studiofinds an installedlousho-studio(local, next to the SDK, or global) and opens the current folder as a workspace, or printsStudio is a separate install: npx lousho-studiowhen it is missing. Inside the SDK checkout it keeps its dev/prod modes (--prod/--dev). Install Studio withnpm i -g lousho-studio(ornpx lousho-studio). - Studio: the Code tab gains “Eject to project” (
POST /agents/:id/eject), which writes the agent-directory form (specToAgentDir) toagents/<id>/in the workspace after a confirm dialog, with an explicit overwrite step when the folder already exists. - New
lousho/observesubpath:startObserveDaemon,probeHealth,isObserveDaemon,defaultDbPath,OBSERVE_DEFAULT_PORTand the daemon option/retention defaults, so a host process (Studio) can run and probe the collector through public exports. - Install docs use the public npm packages again (
npm install lousho,npm create lousho). lousho/improve(experimental):improveAgent()proposes tested edits to an agent’s instructions and skills, offline, gated against the current harness and held-out cases. It applies nothing. See Improving an agent.lousho bridge: a new command that speaks Studio’s bridge protocol (NDJSON on stdin/stdout, protocol 1) so Lousho Studio can build and run a project’s agents with that project’s own SDK and dependencies. It answershello,catalog,compileandshutdown, and runs agents:run/chatstart a run or chat turn,steer/abortcontrol it,resolveApproval/answerQuestionresume a paused run, and everyAgentEvent, trace span, steer join and run settle arrives as a pushed event (flows are refused withLOUSHO_HOST_UNSUPPORTED).- Model strings resolve any official AI SDK provider:
mistral/...,groq/...,xai/...,bedrock/...,vertex/...,azure/...and 13 more load@ai-sdk/<vendor>on the first call, andai-sdk/<vendor>/<model>loads any other@ai-sdk/*package. The package reads its own credentials. See Providers.
[1.0.0-alpha.117] - 2026-11-09
[1.0.0-alpha.116] - 2026-11-09
[1.0.0-alpha.115] - 2026-11-09
[1.0.0-alpha.114] - 2026-11-09
[1.0.0-alpha.113] - 2026-11-09
[1.0.0-alpha.112] - 2026-11-09
[1.0.0-alpha.111] - 2026-11-09
[1.0.0-alpha.110] - 2026-11-09
[1.0.0-alpha.109] - 2026-11-09
[1.0.0-alpha.108] - 2026-11-09
[1.0.0-alpha.107] - 2026-11-09
[1.0.0-alpha.106] - 2026-11-09
[1.0.0-alpha.105] - 2026-11-09
[1.0.0-alpha.104] - 2026-11-09
[1.0.0-alpha.103] - 2026-11-08
[1.0.0-alpha.102] - 2026-11-08
[1.0.0-alpha.101] - 2026-11-08
[1.0.0-alpha.100] - 2026-11-08
[1.0.0-alpha.99] - 2026-11-08
[1.0.0-alpha.98] - 2026-11-08
[1.0.0-alpha.97] - 2026-11-08
[1.0.0-alpha.96] - 2026-11-08
[1.0.0-alpha.95] - 2026-11-08
[1.0.0-alpha.94] - 2026-11-08
[1.0.0-alpha.93] - 2026-11-08
[1.0.0-alpha.92] - 2026-11-08
[1.0.0-alpha.91] - 2026-11-08
[1.0.0-alpha.90] - 2026-11-08
[1.0.0-alpha.89] - 2026-11-08
[1.0.0-alpha.88] - 2026-11-08
[1.0.0-alpha.87] - 2026-11-08
[1.0.0-alpha.86] - 2026-11-08
[1.0.0-alpha.85] - 2026-11-08
[1.0.0-alpha.84] - 2026-11-08
[1.0.0-alpha.83] - 2026-11-08
[1.0.0-alpha.82] - 2026-11-08
[1.0.0-alpha.81] - 2026-11-08
[1.0.0-alpha.80] - 2026-11-08
[1.0.0-alpha.79] - 2026-11-08
[1.0.0-alpha.78] - 2026-11-08
[1.0.0-alpha.77] - 2026-11-08
[1.0.0-alpha.76] - 2026-11-08
[1.0.0-alpha.75] - 2026-11-08
[1.0.0-alpha.74] - 2026-11-08
[1.0.0-alpha.73] - 2026-11-08
[1.0.0-alpha.72] - 2026-11-08
[1.0.0-alpha.71] - 2026-11-08
[1.0.0-alpha.70] - 2026-11-08
[1.0.0-alpha.69] - 2026-11-08
[1.0.0-alpha.68] - 2026-11-08
[1.0.0-alpha.67] - 2026-11-08
[1.0.0-alpha.66] - 2026-11-08
[1.0.0-alpha.65] - 2026-11-08
[1.0.0-alpha.64] - 2026-11-08
[1.0.0-alpha.63] - 2026-11-08
[1.0.0-alpha.62] - 2026-11-08
[1.0.0-alpha.61] - 2026-11-08
[1.0.0-alpha.60] - 2026-11-08
[1.0.0-alpha.59] - 2026-11-08
[1.0.0-alpha.58] - 2026-11-08
[1.0.0-alpha.57] - 2026-11-08
[1.0.0-alpha.56] - 2026-11-08
[1.0.0-alpha.55] - 2026-11-08
[1.0.0-alpha.54] - 2026-11-08
[1.0.0-alpha.53] - 2026-11-07
[1.0.0-alpha.52] - 2026-11-07
[1.0.0-alpha.51] - 2026-11-07
[1.0.0-alpha.50] - 2026-11-07
[1.0.0-alpha.49] - 2026-11-07
[1.0.0-alpha.48] - 2026-11-07
[1.0.0-alpha.47] - 2026-11-07
[1.0.0-alpha.46] - 2026-11-07
[1.0.0-alpha.45] - 2026-11-07
[1.0.0-alpha.44] - 2026-11-07
[1.0.0-alpha.43] - 2026-11-07
[1.0.0-alpha.42] - 2026-11-07
[1.0.0-alpha.41] - 2026-11-07
[1.0.0-alpha.40] - 2026-11-07
[1.0.0-alpha.39] - 2026-11-07
[1.0.0-alpha.38] - 2026-11-07
[1.0.0-alpha.37] - 2026-11-07
[1.0.0-alpha.36] - 2026-11-07
[1.0.0-alpha.35] - 2026-11-07
[1.0.0-alpha.34] - 2026-11-07
[1.0.0-alpha.33] - 2026-11-07
[1.0.0-alpha.32] - 2026-11-07
- Install docs use the public npm packages again (
npm install lousho,npm create lousho). lousho/improve(experimental):improveAgent()proposes tested edits to an agent’s instructions and skills, offline, gated against the current harness and held-out cases. It applies nothing. See Improving an agent.agent.recover({ retryWithDiagnosis: true })gives a run that reachedmaxAttemptsone fork told why it failed, before quarantining it.createOutputCheck()is a new hook that runs your check after a tool succeeds and tells the model what it found. A fork no longer inheritslastErrorandattemptsfrom its source.- Behavior change:
agent.recover()no longer resumes a failing run forever. It backs off exponentially from the last failure (up to 15 minutes) and stops aftermaxAttemptsfailures in a row (default 10), calling the newonQuarantined(run)once.agent.resume()still runs a quarantined run. Pass a largermaxAttemptsto keep retrying longer. lousho observe failuresalso lists runs whose process died and scores below--min-score(default 0.5).agent.recover()pauses during a provider outage instead of using up each run’s attempts: after 3 provider failures in a row it stops resuming, probes with one run at growing intervals, and reports through the newonOutage(paused).createProgressGuard()gainsmaxSameResults(default 5), which denies a tool that keeps returning the same result even when its arguments differ. Run spans recordlousho.run.finish_reason, andlousho observe failureslists runs that ended without an answer and names rate limits.lousho observe failureslists recurring tool and model failures by agent, from the observe database or from trace files (--traces), each with a class and trace ids. See Observability.createProgressGuard(): an opt-in hook that adds advice to repeated tool failures, denies calls that keep returning the same result and tools that keep failing the same way, and stops the run withLOUSHO_RUN_NO_PROGRESSif denials continue. Actions stream as the newheal.actionevent; tool hooks getctx.emit, and tool spans recordlousho.tool.replaced_by_hook. See Hooks.
[1.0.0-alpha.31] - 2026-11-01
- Behavior change: the package is renamed from
@lousho/build-ai-agenttolousho, and the scaffolder fromcreate-lousho-agenttocreate-lousho(npm create lousho). Update imports from@lousho/build-ai-agenttolousho(subpaths such aslousho/testingkeep their names). Install withnpm install loushoornpm create lousho(no token needed). The packages are also mirrored to GitHub Packages asloushoandcreate-loushofor the repository’s Packages tab.
[1.0.0-alpha.30] - 2026-10-31
What is onmain and not yet on npm. Entries marked Behavior change can
break working code; Upgrading lists each one with its
opt-out.
Added
- The
lousho observedaemon: a local collector (loopback,http://127.0.0.1:7777, SQLite at~/.lousho/observe.db) that gathers every agent’s traces, heartbeats and eval scores whenLOUSHO_OBSERVEis set — no per-agent code changes.lousho observe start|status|stop|rebuild-rollups|token create; a secondstarton a busy port attaches when it is already the observe daemon. See Observability. - Agent Forge is rebuilt around a left navigation grouped Build (Agents, Playground), Observe (Traces, Threads, Monitoring), Evaluate (Evaluations: Scores, Datasets, Evaluators, Annotation queues) and Assets (Prompts, Context Hub), plus Settings. It replaces the Build/Observe toggle and the old Observe tabs, and the Build toolbar shows only on Agents. See Agent Forge.
- Every Studio screen has a hash route with its filters in the query string (
#/traces?agent=…&status=error,#/traces/<id>?obs=<step>), so a reload, a bookmark, a pasted link or back/forward lands on the same view. See Routes and deep links. - Studio keyboard:
Ctrl+K/Cmd+Kopens a command palette (go to a screen, open an agent, open a pasted trace id, toggle the light/dark theme),?lists the shortcuts, andj/k/Entermove through and open table rows. See Keyboard. - The last Studio nav item shows whether the collector answers. While the daemon is down, each daemon screen shows the command to start it and fills in once it is back. Daemon screens read it through the token-gated
/observe/**proxy on the studio server, which forwards reads plus only the writes the screens make. See The collector. - Studio Traces and Trace screens: the list filters by search (name, input, output), agent, status, model, project, prompt and time range (15m to 30d or custom, default 24 h), sorts by duration, tokens or cost, and shows input/output previews, the error message and the model. A trace opens in one viewer (tree or waterfall, the failed step selected by default) whose inspector shows the error, input and output as chat bubbles with tool-call chips (Rendered, Raw or JSON), thumbs up/down feedback, usage and attributes; the header links the agent and thread and has Copy link, Add to dataset and Add to queue. Model-call steps carry Open in Playground. See Traces.
- Studio Threads (
#/threads, one row per session, a session’s turns oldest first), Monitoring (#/monitoring: the fleet table with status, last heartbeat, runs today, error rate, p95 latency and dropped events, plus Runs, Latency p95, Error rate, Cost and Tokens charts over 1h to 30d whose buckets open the matching traces) and Scores (#/evals/scores: one row per eval with pass rate, trend, per-check pass rates and latest failures, filtered by eval, agent, source and range). See Monitoring. - Studio Playground (
#/playground): system, user and assistant messages with{name}variables, a provider and model (mockwith no key), tools borrowed from a saved agent, a streamed run with Stop, Open trace when it finishes, and Save as new prompt version. See Playground. - Playground deep links:
#/playground?trace=<id>&fromObs=<obs>loads a model call from a trace, and#/playground?prompt=<name>[@<ref>]loads a registry prompt. POST /playground/runon the studio server runs a playground request and streams SSEdelta,tool_call,doneanderrorevents; runs report to the daemon as agentplayground. See Playground run endpoint.- Studio Prompts (
#/prompts: versions, labels, runs that used each version, a side-by-side diff, Move<label>here, Open in Playground) and Context Hub (#/hub: namespaces viewed as one agent,privateorfleetscope, and editing a fleet entry). See Prompts. - The Agents builder: node cards show the model, tool count and status; an empty canvas offers templates; Inspector sections collapse and the bottom drawer resizes (both remembered); and a run’s status pill links Open trace. Builder runs report to the observe daemon under their agent id, with captured content kept out of the project’s trace files. See Agents.
- Datasets: the daemon stores named datasets of
{ input, expected? }examples (GET/POST /api/v1/datasets,GET /api/v1/datasets/:name,POST /api/v1/datasets/:name/exampleswith an example or{ from_trace_id }, which copies a trace’s root input and output, andDELETE …/examples/:id).defineEval({ dataset: 'name' })in place ofcasesruns one test per example (cis{ input, expected, label, example_id, source_trace_id }) and fails withLOUSHO_DATASET_UNAVAILABLEwhen the daemon cannot serve it. Studio’s#/evals/datasetslists, creates and browses datasets and deletes examples, and a trace’s Add to dataset copies it into one. See Datasets and Evals. - Online evaluator rules:
/api/v1/evaluatorsholds rules with afilteron agent, status and name, asample_rateand anenabledswitch. Each enabled rule scores new traces as their root ends, assource: onlinescores named after the rule. See Online evaluator rules. - Code evaluators: a
coderule is a function(trace) => number | { value, comment }the daemon runs in the isolate sandbox. It needsisolated-vm, plusNODE_OPTIONS=--no-node-snapshoton Node 20+; without them code rules are skipped with one warning.POST /api/v1/evaluators/:id/testdry-runs a rule on one trace without writing a score. See Online evaluators. - Judge evaluators: a
judgerule is a model and a rubric. The daemon queues a job per matching trace, and Agent Forge runs the judge with its provider keys (a key saved in Settings, or the provider’s env var; the saved key wins), so judges run only while Studio is running.LOUSHO_STUDIO_JUDGE=0turns Studio’s judge loop off. Studio’s/observe/api/v1/evaluators/:id/testdry-runs judge rules too. See Judge rules. - Studio Evaluators screen (
#/evals/evaluators): lists the rules with their last run and runs in the last 24 hours, and creates, edits, enables, disables and deletes them. Test on trace dry-runs a rule on one trace id. The judge kind stays disabled until Studio has a provider key, saved in Settings or set in the provider’s env var. See Evaluators. - Annotation queues:
/api/v1/queuesholds named lists of traces with an optional rubric (name,description,min,maxper score);GET /api/v1/queues/:id/nextreturns the oldest pending item andPOST …/items/:item/completewrites its scores as human scores (or skips it). Studio’s#/evals/queuescreates queues and reviews them one trace at a time beside the rubric (Enter submits,Sskips), and a trace’s Add to queue adds it. See Annotation queues. - Human feedback scores:
POST /api/v1/scores{ trace_id, obs_id?, name, value, comment? }adds asource: humanscore (201 { score_id }; unknown trace or step404). Each eval case also records one<evalName>score: 1 when no gate check failed and the case did not throw, else 0 with the failed gates in the comment. See The observe daemon. - Prompt labels: a label (
prod,staging) points at one version;lousho prompt label <name> <label> <version>(orPUT /api/v1/prompts/:name/labels/:label) moves it,push --labelssets it on the pushed version, andcreateAgent({ prompt: 'name@prod' }),lousho prompt get name@prodandGET /api/v1/prompts/:name/:refresolve it. A push whose text and variables equal the latest version’s mints nothing (unchanged: true). Seelousho prompt. - Trace list API:
GET /api/v1/tracestakesfrom/to(half-open ms),q(substring of name, input or output),min_duration_ms,model,prompt(<name>[@<version>]),sort(start,duration,tokens,cost) andorder, and rows addagent_name,model,error_messageand input/output previews. See Trace list API. - Sessions API:
GET /api/v1/sessions(filter by agent, status and start window, paged) andGET /api/v1/sessions/:id(the session and its traces, oldest first) with per-session trace counts, tokens, cost and last input. See Sessions API. - Retention: once a day the daemon deletes finished traces whose last observation ended more than
lousho observe start --retention-days Nago (default 30,0keeps everything), with their scores and prompt-use links, plus older scores whose trace is gone and sessions that are notactiveand no run references. A trace with a run still open and anactivesession are kept. Rollups, prompts, hub entries, the agent registry, tokens, datasets, evaluator rules and annotation queues are never pruned.lousho observe prune --older-than <N>dprunes now and runsVACUUM. See Retention. lousho observe export [--since 7d] [--agent X] [--out file]writes traces as JSONL ({ trace, observations, scores }per line) straight from the db, without a running daemon. See Export.- Insights series carry
p95_latency_msanderror_rateper agent and bucket. A db written by an older daemon lacks them for past buckets: runlousho observe rebuild-rollupsonce to backfill. See The observe daemon. - Heartbeats carry the reporter’s dropped-event count, and each
/api/v1/agentsrow shows it asdropped(nullfor older SDKs); Studio’s Monitoring fleet table shows it. See The observe daemon and Monitoring. - Prompt registry:
createAgent({ prompt: 'name@version' })orLOUSHO_PROMPTresolves versioned instructions from the daemon at build; every run records the version used.lousho prompt push|list|getmanages it. When the daemon is unreachable, embeddedinstructionsare used; with noinstructionsthe agent fails closed: every run rejects withLOUSHO_PROMPT_UNRESOLVEDinstead of running without a system prompt. A failed fetch is not cached for good: runs in the next 30 seconds resolve at once, then the next run fetches again (waiting up to 2.5 seconds). - Context hub:
hub()/hubTools()publish and query namespaced shared memory scopedprivate(the writing agent) orfleet(every agent on the daemon). - Fleet monitoring: heartbeat-derived agent status,
agent.deregisteron graceful exit, a crashed agent’s open sessions and unfinished observations flip tointerrupted, and webhook alerts (--webhook,alerts.json) on down transitions and error-rate thresholds. - Eval scores report to the daemon: every
AssertionResultlands as a score row on the exercised run’s trace (source: evalorjudge);lousho eval --observeforces emission. Each case’sevalspan and score rows are flushed when the case finishes, each wait capped at 1 second; the scores share the reporter’s queue, so they go out after the span and are retried while the daemon is down. A wait that runs out skips the waits of the next 30 seconds of cases. - Reporting to the daemon: spans that finished without an error report status
ok. A down daemon’s batches are requeued and retried with exponential backoff (1 s up to 30 s); batches are capped at 1000 events and 4 MB, and a batch the daemon refuses (400/413) is dropped and counted indropped. The queue holds at most 5000 events or 32 MB, oldest evicted first. A process dying of an uncaught exception or unhandled rejection sends the newest 16 MB it holds, blocking for at most 1 second; a graceful exit makes one final attempt capped at about 2 seconds. A run’s root span is reported when the run starts, so a run whose process is killed is still listed and turnsinterrupted. LOUSHO_OBSERVEaccepts1/true/on/yes, anhttp(s)://URL, or0/false/off/no/none/disabled/empty (any case). Any other value warns once namingLOUSHO_OBSERVEand disables reporting, instead of being posted to as a URL.- With
LOUSHO_OBSERVEpointing at a loopback daemon,createAgentcaptures message and tool content for the daemon by default (captureContent: falseturns it off). Only the daemon gets it: the agent’s ownexporter(trace files, OTLP or vendor exporters, the built server’s OTel export) still records no content unless the agent setscaptureContent: true. Captured content goes throughredactContentfirst (see the scrubber entry under Changed). See Observability. - Each observe daemon writes its own pidfile beside its db (
foo.dbgivesfoo.pid), so two dbs in one folder never share one.lousho observe startexits 1 when the port already serves another db, andstoprefuses to signal when the daemon on the pidfile’s port reports another db or answers as a different service./healthnames the db it serves only to callers on the same machine. A daemon started with--db foo.dbby an earlier build of this feature wrote the shared pidfile and is not found by the newstop: stop it before updating. lousho observe startand Studio print theLOUSHO_OBSERVEvalue for the port and host the daemon really uses (LOUSHO_OBSERVE=http://127.0.0.1:7788on a non-default port), and the Studio proxy answers/observe/__targetwith the daemon URL reporters should use.sandbox({ driver: 'isolate' })runs tool code in anisolated-vmV8 isolate (optional peerisolated-vm);defineTool({ sandbox })opts a tool in, timeouts and OOM map tosandbox.erroron the tool span.'docker'and'e2b'driver names are reserved for later drivers.
Changed
- Behavior change: content captured for traces is scrubbed for secrets by default.
redactContentisboolean | ((text) => string): unset ortrueruns a built-in scrubber over message text, system instructions, tool-call arguments and tool results that replaces API-key shapes (sk-…,lsv2_…, GitHub tokens, AWS access key ids, the token afterBearer) with[redacted]; a function replaces the scrubber (text it throws on is recorded as[redacted]);falserecords content as is. It catches common key formats, not every secret, so setcaptureContent: falseif content must never reach the db. See Secrets in captured content. - Behavior change: sessions end. The daemon marks a session
endedonce none of its runs is open and nothing in it has started or finished forlousho observe start --session-idle-minutes N(default 30,0turns it off);ended_atis the last activity, and a new run makes itactiveagain. Sessions in an existing db close on the first sweep that finds them idle, and ended sessions then age out with retention. See Idle sessions. - Behavior change: the daemon keeps 30 days of runs by default. On its first sweep after start, and daily after that, it deletes traces whose observations all finished more than
--retention-daysago, with their scores; a trace with a run still open, and a session stillactive, is kept. Start it with--retention-days 0to keep an existing db’s history. See Retention. - Studio redesign: a new look in light and dark (Settings > Appearance picks Light, Dark or System, plus Compact or Comfortable table density), a left nav that collapses to an icon rail, and a Settings screen in sections (among them Appearance, Provider keys with Set / From environment / Not set, Collector, Keyboard shortcuts). Traces gains Refresh and a Live toggle that refreshes every 5 seconds, the trace viewer switches between Tree and Waterfall, Evaluations moves between Scores, Datasets, Evaluators and Annotation queues with tabs, Ctrl/Cmd+Enter runs the Playground, and the Agents canvas opens with the whole graph fitted and the Inspector folded until you select a node. See Agent Forge.
Fixed
- Studio filter bar: the search box keeps what you type — a trailing space (
tool) no longer gets reset when the URL echoes the trimmed query; clearing filters or navigating still updates it. - Insights runs/day averages over the days an agent was active in the window, so an agent first seen today with 12 runs reports 12/day instead of 12/7.
- Studio threads: each turn now shows its full input and output (chat messages render as bubbles) instead of the 200-char previews; a turn fetches its trace as it scrolls near the viewport, shows the preview labelled “Preview (truncated)” while loading or if the trace can’t be read, and says so when the recorder truncated the turn’s I/O.
- An open run’s root start is kept when the reporter’s buffer trims or a crash flush cuts to its newest 16 MB, so a run whose child spans overflow the buffer is still listed.
- Studio Scores and
GET /api/v1/scores?aggregate=eval:humanandonlinescores now pass only on a value of exactly 1, so a thumbs-down or an online rule returning 0 (or 0.9) without a comment counts as a failure instead of a pass;evalandjudgescores keep their rule (no failure comment, or a perfect 1), and the table and the eval detail agree. - Studio: the command palette and
?shortcuts sheet now keep every keydown to themselves, soSno longer skips the annotation-queue item behind them; Traces, Threads, a Thread, Prompts and the Context Hub recover in place after the daemon restarts instead of staying on “daemon down”; and the queue review’s trace tree no longer wraps a row name one letter per line at 1280px. - The run inspector shows
error, notrunning, for a failed step that has no end time. - Studio trace viewer: an observation the crash sweep marked
interrupted(or an openerrorone) now shows as terminal instead of “running” forever; its duration and the waterfall stop at the latest known end and the header clock stops ticking. - The observe daemon refuses cross-site browser writes and DNS rebinding on
/api/*: a loopback-bound daemon answers only loopbackHostnames (403), writes carrying a non-loopbackOrigin(includingnull) orSec-Fetch-Site: cross-siteget 403, and a write with a body must beContent-Type: application/json(415) —curl -dneeds-H "Content-Type: application/json". The SDK reporter, CLI and Studio already comply. See Observability. - Observe retention (
lousho observe start --retention-days,lousho observe prune) also deletes old traces the sweep markedinterrupted(a crashed run whose end never arrived); their age counts from when they were interrupted. - The observe daemon’s online evaluator worker no longer blocks the daemon: it yields between traces, checks each rule’s filter against the root row before loading anything else, hands code rules at most 200 observations (attrs over 8192 characters become
{ truncated: true }) and no scores, and judge jobs claimed by Agent Forge carry the root fields only (observations: []). - Error text recorded on spans (
errorattributes and the span status message, on runs, LLM calls, tools, resumed runs and flows) goes through the sameredactContentchoice as captured content, so tokens in an error no longer reach traces, exports, evaluators or judge prompts; the built-in scrubber also catches case-insensitiveBearer, Stripesk_/rk_live and test keys, Slackxox[abprs]-tokens, GoogleAIzakeys and JWTs.recordSpanErrorandwithSpantake an optional redactor (default: the built-in scrubber).
Documentation
- Agent Forge documents the left navigation, every screen, the deep-link routes and the keyboard shortcuts, with screenshots in
docs/images; Observability, CLI and Evals link to the screens. The screenshots come from an opt-in Playwright spec:LOUSHO_DOC_SHOTS=1 npx playwright test -c apps/agent-forge/playwright.config.ts docShots. See Keyboard and Routes and deep links.
Security
- Agent Forge’s studio server requires its per-launch token on every API route regardless of path case or encoding:
/PLAYGROUND/run,/Observe/api/v1/scores,//settings/...or/%70layground/runno longer skip the check. Routing is case-sensitive, and every request except aGET/HEADof/healthor the built client needs the token. - Agent Forge’s
/observe/**proxy only ever forwards to theLOUSHO_OBSERVE_URLdaemon: the upstream URL is built from the request’s path and query alone, so an absolute-form request line (GET http://a@evil.example/observe/...) can no longer point it at another host, and a path that URL parsing would rewrite (..,%2e, a literal\) is refused with 400 instead of reaching a write route the allowlist does not name. The proxy sendsLOUSHO_OBSERVE_TOKENas the bearer to a daemon that requires one, and the Playground’s “Save as new prompt version” (POST /api/v1/prompts) is forwarded instead of answering 405.
[1.0.0-alpha.29] - 2026-10-21
Changed
-
Behavior change: the built node-server and Docker image refuse to start on a non-loopback host when no auth is configured (no
LOUSHO_API_TOKEN, build token orauth.ts), withLOUSHO_SERVER_UNPROTECTED. Set a token, addauth.ts, bind to127.0.0.1, or setLOUSHO_ALLOW_PUBLIC=1to serve an open agent on purpose.lousho build --target=dockerprints the run command with-e LOUSHO_API_TOKEN=<token>. -
The
limits.maxCostUsdwarning for a model with no known price names the model, says the limit is not enforced for it, and shows theregisterModel()call that fixes it. It is printed once per model instead of on every step. -
Scaffolded READMEs link to the docs site (
https://lousho.com/quickstart) instead of the GitHub file onmain. - Sessions has one statement on sharing a SQLite store, used across the docs: several processes on one host and a local disk are fine; network filesystems and multiple hosts are not.
-
Behavior change: the built node-server and Docker image resume runs a crash left in progress when they start (
agent.recover()), and check again every 30 seconds until shutdown. Runs paused on an approval or a question are left alone, and a run another replica holds is skipped.LOUSHO_RECOVER_ON_START=0turns it off. See Crash recovery. -
Behavior change:
createAgent()anddefineTool()reject an option key they don’t know withLOUSHO_CONFIG_INVALIDand a suggestion (requireApproval→needsApproval,maxOutputTokens→modelSettings.maxTokens) instead of ignoring it. A mistypedneedsApprovalused to run the tool unapproved. Keys set toundefinedare ignored. -
Behavior change: the workspace file tools deny
.envand.env.*by default as well as.git..env.example,.env.sampleand.env.templatestay readable. Adenylist you pass still replaces the defaults. -
POST /chatanswers409withRetry-After: 2andcode: LOUSHO_SESSION_BUSYwhen another process or replica is running the session, instead of a200stream holding only the error. AnIdempotency-Keyresend that hits a running turn gets the same409. -
Scaffolded agents (
lousho init,create-lousho-agent) setmodelSettings: { maxTokens: 4096 }, so a first run on a low-credit OpenRouter key no longer fails with “requires more credits, or fewer max_tokens”. The generated README explains the error. -
Error
docslinks point tohttps://lousho.com/errors#<code>instead of the GitHub file onmain. -
The Docker image creates
/app/dataowned bynodeand declares it aVOLUME, so a fresh named volume works withLOUSHO_STORE=sqlite:/app/data/lousho.db. - The Authentication examples read secrets from the environment and fail at startup when they are missing, instead of falling back to a literal secret.
-
Behavior change: the built node-server (and the Docker image) now guards
POST /channels/<name>and its approvals route for a channel withoutverifywithLOUSHO_API_TOKEN/auth.ts, the same as/chat. Before, such a channel answered anyone even with a token set. Channels that verify their own requests (Slack, Discord, Telegram, GitHub, Teams,webhookChannelwith a secret, any channel withverify) are unchanged, and the start-up log lists each channel route’s guard (self-verified,server-authoropen). -
Behavior change:
webhookChannelreplies with{ sessionId, text, finishReason, approval? }(plusapprovalPrompton a pause), ashttpChanneldoes, instead of the fullExecutionResult. The full result echoed the system prompt and the whole transcript to the caller.fullResult: truerestores the old body. -
Channels answer a turn on a session that another process or replica is running (
LOUSHO_SESSION_BUSY) with409andRetry-After: 2instead of a500, and report a turn that fails before the request is acknowledged toonErrorwith stage'turn'(it said'parse'). - README and Comparison no longer list ACP and MCP as differentiators, and describe Agent Forge as a local visual console.
-
CI is one workflow with two jobs:
ci(type checks, lint, build, tests with coverage, docs, API and fallow gates, pack-smoke, size check, and a zod 4 type check) andcompat(the newest peers,ai7 with zod 4, plus the real-Docker sandbox tests). The separate Docker Engine, Agent Forge E2E and weekly registry-smoke workflows and theai6 / zod 3 matrix entries are gone;npm run registry-smokeandnpm run test:e2e:studiostill run locally. When the fallow gate fails, CI now prints its full health and duplication reports.
Added
GET /readyon the built node-server and Docker image:200 {"status":"ready"}while serving,503 {"status":"draining"}once shutdown starts./healthis unchanged. See Deployment.- The built server exports OpenTelemetry traces over OTLP/HTTP when
OTEL_EXPORTER_OTLP_ENDPOINT(orOTEL_EXPORTER_OTLP_TRACES_ENDPOINT) is set, next to any exporter the agent already has. It loads@opentelemetry/sdk-trace-node,@opentelemetry/resourcesand@opentelemetry/exporter-trace-otlp-httponly then, says how to install them when missing, and honoursOTEL_SERVICE_NAME. See Observability. createAgent({ toolErrorMessage })replaces the text of a thrown tool error (kind: 'execution') before it reaches the model,tool.errorevents and hooks; a sanitizer that throws gives “The tool failed.”. See Tools.lousho initandcreate-lousho-agentgenerate anAGENTS.mdfor coding agents (the project’s real scripts, conventions and docs links) and aCLAUDE.mdthat imports it.lousho addfalls back to the registry bundled in the npm package (registry/dist) whenregistry.lousho.comand its GitHub fallbacks are unreachable, with a notice that the bundled copy may be older.- Pause, restart and resume: one tutorial for an approval that waits across a restart, crash recovery, and resending over HTTP.
SECURITY.md: supported versions, private reporting through GitHub, and the disclosure policy.httpChannel()created withoutverifylogs one warning that the channel is unauthenticated and itssessionKeyvalues are guessable. Channels showsverifyin the quick start, and Deployment says which routesLOUSHO_API_TOKENguards.POST /chataccepts anIdempotency-Keyheader: a resend with the same key replays the finished turn’s reply (Idempotent-Replayed: true, nothing runs), resumes a turn a crash interrupted instead of appending the message again, and is a409(LOUSHO_SESSION_BUSY) while that turn still runs. The key is stored on the turn’s user message (metadata.idempotencyKey), so it survives restarts;session.pending()reports it asidempotencyKey. See Resending a turn.fromAiSdkTools(record)converts Vercel AI SDK tools (tool({ ... })or plain{ description, inputSchema | parameters, execute, needsApproval? }objects) into Lousho tools, keyed by name: zod and Standard Schemas are kept,jsonSchema()wrappers and plain JSON Schemas are converted (their ownvalidatestill runs),needsApproval(boolean or function) pauses the run for approval, andexecutegets the call id and the run’s abort signal. It imports nothing fromai, so tools built onai4 to 7 work with any installed version. New guide: Migrating from the AI SDK.lousho evalwithout vitest installed now says it runs*.eval.tsfiles through vitest, the directory it searched from, and the install command; Evals states the requirement up front.result.usage.delegated.toolErrors: the tool calls that failed inside a run’s sub-agents (and theirs), which the lead’s ownresult.toolErrorsdoes not count.ToolCallContext.onDelegatedUsagetakes the child’stoolErrorsas an optional second argument.- The session HTTP API (
createRouteHandler(), the deployed node server, the Worker,lousho dev) writes an SSE comment (: ping) after 15 seconds without an event, so proxies and client idle timeouts no longer drop a turn whose model or tool is slow;heartbeatMschanges the interval (0turns it off). See HTTP API. google/<model>model strings (e.g.createAgent({ model: 'google/gemini-2.5-flash' })) and aGoogleProvider, backed by the optional peer@ai-sdk/google(^1.2.0withai4,^3.0.0withai6,^4.0.0withai7) and readingGOOGLE_GENERATIVE_AI_API_KEY.lousho init --provider google,lousho doctor(package pairing, key,--ping) and the missing-peer install hint cover it. See Providers.- An unknown model prefix (
mistral/...,xai/...) now says how to reach the vendor anyway:openrouter/<vendor>/<model>,pi/<vendor>/<model>when pi serves it, orfromAiSdk()with the vendor’s AI SDK package. See Vendors without a prefix. lousho doctorfails an installedai5 (AI SDK v5 is not supported) with an upgrade hint toai6 or 7 and the matching@ai-sdk/*majors.
Fixed
lousho buildworks again in a project without the optional@opentelemetry/*packages (every fresh scaffold): the OTel exporter added for the built server is loaded only whenOTEL_EXPORTER_OTLP_ENDPOINTis set, and the build leaves those packages unresolved instead of failing withCould not resolve "@opentelemetry/api". The scaffold end-to-end test now builds the server and checks/health.- The
httpChannel()“no verify” warning no longer says the channel is unauthenticated when the built server guards it withLOUSHO_API_TOKENorauth.ts, and Channels showswebhookChannel’s trimmed reply. lousho addworks again whenregistry.lousho.comis unreachable: the fallback now tries the release tag as the repository names it (1.0.0-alpha.24), then thev-prefixed tag, thenmain. It asked only forv<version>, which 404’d.- The file tools’
denylist (.gitby default) is now also checked where a path really leads: a symlink or Windows junction inside the workspace pointing at.gitor into it (gitj -> .git) letedit_file gitj/configrewrite.git/config(for examplecore.hooksPath, which runs code on the next git command) andwrite_file gitj/PWNEDcreate files in.git. Reads, writes, edits,list_dir, andglob/grepgiven such a link aspathare now refused. Providers with links can implement the new optionalFsProvider.realPath(path);NodeWorkspacedoes. See Workspace tools. NodeWorkspace.writeFile(and sowrite_file/edit_file) writes a temp file in the same directory and renames it into place, so a process killed mid-write no longer leaves a truncated file. A replaced file keeps its permission bits; a read-only file is still refused.WorkspaceCheckpointsstores a file’s backup beforewrite_file/edit_filewrites it, not after. A process killed between the write and the backup lost the original: on resume the re-run call backed up the agent’s own content, sorewind()reportedrestoredbut put back the agent’s version (or, foredit_file, recorded nothing). A re-run now keeps the turn’s first backup, and rewind treats a file still holding its backed-up content as nothing to undo.track()also accepts aPreparedWorkspaceWrite({ prepare, write }), which the built-in tools use.edit_filere-run after a crash (the edit already in the file:old_stringgone, a non-emptynew_stringpresent, also withreplace_all) now succeeds with “the edit was already applied” and writes nothing, instead of failing withold_string was not foundand sending the model into a loop. Awrite_file/edit_filethat leaves the file unchanged no longer records a checkpoint backup.- Sessions no longer says to call
resume()before resolving an approval after a restart:agent.approvals.resolve()/streamResolve()from a fresh process finds the session itself. It and Build a coding agent now say how to show a resumed turn’s progress (session.on(),onEvent), and the guide points long coding turns at compaction. - MCP tool schemas with OpenAPI’s
nullable: true(any type) now acceptnull; the model’s validnullwas rejected withToolArgumentsValidationError. - A failed MCP tool call (server exited, timeout, protocol error) now rejects with
LOUSHO_MCP_CALL_FAILED, naming<server>__<tool>with the MCP error ascause, instead of a bareMCP error -32000: Connection closed. MCP now says stdioenvis merged onto the MCP SDK’s default allow-list, notprocess.env. - Flows (consumer harness): a
{{variable}}holding an object (atoolCallresult, an MCP result) no longer reaches a prompt as[object Object]: an object whose only field istext(an MCP tool result) is that text, a raw MCP{ content }result its text parts, and any other object or array its JSON. Placeholders take dotted paths ({{res.user.name}},{{list.0}}, own properties only), also as whole tool-argument values. Anevaluatorstep stores its result inoutputVariable. See Template values. - Flows: a durable run is saved before its first step, so a run whose first step failed can be
resume()d instead of failing withLOUSHO_CHECKPOINT_NOT_FOUND, whose hint for a flow run now points atFlowExecutor.execute()rather than forking session history. A step’s checkpoint is saved before itsstep-completeevent, so a crash in between no longer re-runs a step reported complete. - Flows: an
llmCallwhose model request fails rejects with the same compactedCompactedLLMProviderErroras an agent run (LOUSHO_PROVIDER_*code,compacted.category), not the provider SDK’s rawAPICallError, and itsretryno longer retries a failure markedretryable: false(a 401, an exhausted quota, a too-long prompt). - A provider answering a streaming request with HTTP 200 and a body that is neither an event stream nor valid JSON (for example a truncated
{"choices": [ {"oops) no longer ends as a silent empty reply. It now fails as a retryable 502, sowithRetryretries it and an exhausted retry surfaces as a provider error. - A sub-agent with an
outputschema that ran out of steps and gave a valid object in its forced final call is now ataskresult (the object, with a line saying the steps ran out), not a failure telling the lead it gave no final answer - which made leads re-run the task. - Sub-agents are held to their lead’s token, cost and duration
limitswhile they run, counted with what the lead and its other running sub-agents have spent, so parallel sub-agents no longer each spend the lead’s whole budget (a lead withmaxCostUsdcould end at several times it). A sub-agent stopped this way reports the limit to the lead. A spend limit stays a hard stop with no forcedoutputanswer; the finished tool results stay inresult.messages(Budgets). - Behavior change:
POST /chatto a session paused on an approval is a409JSON body (LOUSHO_SESSION_AWAITING_APPROVAL, withapprovalIdandapprovalIds) instead of a200stream ending in a generic error. - A decision on an approval whose winning decision is still streaming is a
409(LOUSHO_APPROVAL_CONFLICT), as docs/auth.md says, instead of a404. - The session routes’
400bodies carry acode:LOUSHO_REQUEST_INVALID(invalid JSON, missing or empty fields),LOUSHO_APPROVAL_DECISION_INVALID(an approval body with neitherapprovednoranswer),LOUSHO_SESSION_ID_INVALID. lousho chatprints a failed turn with its error code, the provider’s failure category and HTTP status, and the fix (error: User not found. (auth-failure, HTTP 401)then[LOUSHO_PROVIDER_REQUEST_FAILED] ...), as docs/cli.md says, instead of the bare provider message. The terminal chat of a project scaffolded bylousho init/create-lousho-agentdoes the same.- A
.envsaved with a UTF-8 byte order mark (PowerShell 5.1’sSet-Content -Encoding utf8) no longer loses its first variable: theloushocommands and the scaffoldedsrc/index.tsdrop the mark before parsing. Variables already set in the environment still win. lousho doctor src/agent.tsloads a.ts/.jsagent module the waylousho devdoes instead of failing withLOUSHO_SPEC_UNSUPPORTED_FORMAT, and a missing key for the module’s provider is a failure. A scaffolded project’snpm run doctornow runslousho doctor src/agent.ts, so it fails when the agent’s key is missing.lousho doctor --pingchecks OpenRouter at/api/v1/key, which needs the key (its/modelsanswers without one, so a wrong key passed); a key the provider rejects is now a failure, and a ping of a customOPENAI_BASE_URLsays it shows reachability only.lousho doctorfix lines use PowerShell syntax ($env:NAME="<your key>") on Windows.- The
lousho evaltable shows the scores of passing scored gates (such ast.check('words', n, atLeast(3))), not only in--json. - Behavior change. An agent with
outputand tools no longer sends the strictresponseFormatschema on calls that offer tools:openai/gpt-4o-minivia OpenRouter then called tools on every step untilmaxStepsand never answered.responseFormatnow goes only on calls without tools (an agent without tools, the “answer now” call atmaxSteps, the repair step); tool-offering calls answer from the schema in the prompt, with the existing parse and repair.output: { schema, responseFormat: 'always' }restores the old behavior, and is the default withpromptSchema: false.object.deltaevents still stream on every step of anoutputrun. See Structured output. - An agent directory built with
lousho build --target=node-server(ordocker) can now change who may decide an approval and who may use a session:auth.tsmay export functions namedauthorizeApprovalandauthorizeSessionnext to its default auth list,resolveAgentDir()returns them, and the built server applies them. Before, the built server always used the defaults, so a manager could not approve another user’s paused call while that user could approve their own. See Who may decide an approval.
Documentation
- Tool idempotency:
toolCallIdandctx.approval.ididentify one call; after a crash the model may retry with a new call, so side effects that must happen once need a key from your own data. New guidance for ending a run after a rejected approval, and for extract-then-approve-then-act with structured output. - Durable execution:
agent.resume()resolves with a result, not a stream (stream a resumed run withagent.stream([], { sessionId })), andagent.pending()also lists runs still active in another process. Installation: TypeScript 6+ projects need"types": ["node"]for the SDK’s declarations.
[1.0.0-alpha.24] - 2026-10-17
Two fixes on top of 1.0.0-alpha.23, published from the release branch.Added
model-unloadedprovider error category: “model is not loaded/unloaded” replies from a local server (LM Studio, Ollama) classify as retryable, sowithRetry()rides out the server evicting or still loading a model.- A run ended by
maxStepsor a budget without a final answer now returns explanatory text instead of an empty string.
Changed
- MCP: a warning is logged when a server’s tool schemas exceed about 16K tokens (deferred tools excluded). A server marked
optional: trueconnects in the background, so a slow or failing optional server no longer blocks the firstsend().
Fixed
- Compaction: when the provider rejects a request for context size and the configured
contextWindowis larger than the model’s real one, the error is marked on the transcript and folded into it for a retry when a compaction hook exists; the hook compacts under the server’s observed window (or the rejected request size when unnamed) for the rest of the run. toolCallsof a run continued from a transcript (approval resolve, resume) are collected from its messages, so they no longer disappear from the result.recall_<slot>with a query that matches nothing now says the slot is not empty, instead of returning a bare[]that contradicted the injected<memory>block.- The guardrail starter set’s
ignore-instructionssignal also catches “ignore these/those/her/his/their/our instructions” and “ignore your instructions”, without a qualifier such as “previous”.
[1.0.0-alpha.23] - 2026-10-16
The same tree as 1.0.0-alpha.21; no code changes. create-lousho-agent 0.1.2-alpha.7.[1.0.0-alpha.22]
Never published to npm (the registry goes from 1.0.0-alpha.21 to 1.0.0-alpha.23); no changes.[1.0.0-alpha.21] - 2026-10-16
Everything merged tomain after 1.0.0-alpha.20. create-lousho-agent
0.1.2-alpha.6.
Breaking
- Removed the deprecated trigger adapters and their types from
@lousho/build-ai-agent/triggers.TriggerAdapter,TriggerRegistry, theWebhookAuthhelpers,verifySlackSignature()andparseCronExpression()stay. Migration (see Migrating from triggers):WebhookTriggerAdapter,WebhookTriggerAdapterOptions,WebhookTriggerHandle->webhookChannel()withmountChannels()(sameauthoption)SlackTriggerAdapter,SlackTriggerAdapterOptions->slackChannel()withmountChannels()CronTriggerAdapter,CronTriggerAdapterOptions,CronIntervalOptions,CronExpressionOptions->defineSchedule()withstartSchedules()(nointervalMs: use a cron expression such as*/5 * * * *)
Added
agent.recover({ intervalMs?, signal?, onError?, onRecovered? })finishes interrupted durable runs in the background: it pollsagent.pending()and resumes each'in-progress'run once its crashed holder’s run lease is free, leaving approval and question pauses (and non-retryable failures) alone; returns{ done, stop() }(Durable execution).- An agent directory’s config accepts
retry(agent.json:maxRetries,timeoutMs,backoff, …) and, in anagent.tscode config,output(a Standard Schema), solousho dev/chat/build ./agentkeep structured output and per-attempt timeouts.loadAgentDir(dir, { output })now returnsSimpleAgent<Infer<output>>, soresult.objectis typed. result.toolErrorscounts a run’s tool calls that ended in an error result, so an answer the model gave after its tools failed (finishReason: 'stop') is no longer indistinguishable from a good one;limits.maxToolErrorsstops the run ('budget-exceeded',budget.limit: 'maxToolErrors') once that many failed. See Failed calls in the result.- An error a run rejects with carries what the run spent as
error.usage(also onPropagatingToolErrorand your own errors). A sub-agent’s spend is saved on its lead’s checkpoint as it runs, so a lead resumed after a crash mid-sub-agent counts the interrupted sub-agent’s model calls. - A
send(msg, { sessionId })oragent.resume()run that rejects recordslastErrorandattemptson its checkpoint, andagent.pending()lists them (attemptsis new for session turns too), so a restart loop can tell a failing run from a crashed one. - Docs: a webhook-redelivery recipe (run a job once by checking the checkpoint before
send()), a note on structured-output schemas that mirror a side-effect tool, and thefetchoption for proxies and fault injection on every provider class.
Changed
- Behavior change: the fallback default model for the OpenAI, OpenRouter and Pi providers (what
lousho initscaffolds and what runs when no model is configured) is nowgpt-4.1-miniinstead ofgpt-4o-mini; setmodelorLOUSHO_MODELto keep the old one. README and Quick Start use it. Addeddocs/comparison.md; CI also runs on pushes tomain; README no longer claims unverifiable live validation. createAgent({ prompt })is deprecated:instructionsis the one documented name (promptstill works as an alias, marked@deprecated). Docs, README and examples now useinstructions, andnpm run docs:verify-snippetsfails a docs snippet that passesprompttocreateAgent.- The published package no longer ships source maps (
dist/**/*.map, ~3.7 MB; tsup no longer emits them). The tarball goes from 965 files / 18.9 MB unpacked / 5.0 MB packed to 774 files / 15.1 MB / 4.3 MB.src/still ships becauselousho buildbundles the SDK from it.npm run size-checknow guards the tarball size and a hello-world bundle againstscripts/size-budget.json. docs/comparison.mdis now a dated (October 2026) per-competitor table covering the AI SDK 7, Mastra, LangGraph.js, OpenAI Agents SDK, Claude Agent SDK, eve, VoltAgent and open-harness, and the README’s differentiator list keeps only claims still true against them.
Fixed
- Behavior change: a session without a
checkpointStorethat pauses on an approval now keeps an in-process pause marker, so a secondsend()/stream()/compact()on it throwsSessionAwaitingApprovalError(LOUSHO_SESSION_AWAITING_APPROVAL) — before, the new turn ran over the truncated transcript and the laterapprovals.resolve()silently overwrote the committed turn. The marker coverssend,stream,compact,clear,pendinganddiscardPending, and is dropped when the turn resolves, aborts, fails or is discarded. Across processes there is still no durable marker: a session that may pause needs acheckpointStore. - Session turn checkpoints no longer reuse a
<id>.turn-<n>id aftercompact()shortened the transcript: thennow comes from a persisted high-water mark (<id>.turn-counter), sofork()can no longer resolve a stale checkpoint of a different turn, andprune()keeps the counter while its session’s paused run needs it. - Memory: two parallel
remember_<slot>calls with anitemKeyno longer store duplicate items — the check-and-replace is serialized per memory key. A remembered item is capped at 20,000 characters and the injected<memory>block at 20,000 (each line 4,000), so one item can no longer outgrow the context window of every later run. lousho add <kit> --dir <new-dir>no longer creates the target directory before the install is decided: a non-interactive refusal, a manifest refusal or a ‘no’ at the prompt now truly leaves “nothing was written” — before, an empty directory stayed behind.- A malformed or truncated provider response before any output (the AI SDK
JSONParseError/TypeValidationErroron a garbage first SSE chunk, or a stream cut byUND_ERR_SOCKET/ “terminated” / “other side closed”, also inside acause) is now retried bywithRetry()like other network errors, with aprovider.retryevent, instead of ending the turn withLOUSHO_PROVIDER_REQUEST_FAILED. Nothing is retried once text or a tool call was emitted. lousho build --target=node-servernow lists the provider package in the build’spackage.jsonwhen the agent module (or a codeagent.ts) uses an SDK provider class such asnew OpenRouterProvider(...), not only a literalmodel: '<provider>/...', and warns when it detects no provider.docs/deployment.mdno longer tells readers to call the internalcreateDeployedServer(); it shows a graceful shutdown for a self-served agent.- Errors and cost (consumer harness): a session turn that fails outside its run (e.g.
LOUSHO_SESSION_BUSY) now sends the error’s stablecodeon theerrorevent, with the message still sanitized;provider.fallbackevents carryfromModel/toModel, so two providers of the same name (both OpenRouter) can be told apart; and one step with no known price no longer discards the run’s cost:usage.costUsdkeeps the priced steps’ sum andusage.costPartial: trueflags it (also onbyModelentries,delegatedandstep.done/run.doneusage), andlimits.maxCostUsdis enforced on that partial total. grepno longer times out on a cheap pattern over a slow disk: the 10 s budget now counts only the time spent matching, not reading files. The timeout error says whether the pattern is slow or the many files used the budget, and how many files were scanned. NewcreateFsTools({ grepTimeoutMs }).- Permissions: a
permissionsrule naming a tool the agent does not have (a typo such aswrite_flie, so adenysilently guarded nothing) now logs a[lousho]warning atcreateAgent()with a “did you mean”, andlousho doctor <agent-dir>reports it as a warning. Wildcards, globs, patterns and agents whose tools may arrive later (MCP, tool search, sub-agents) are only checked for near-miss typos. lousho init/create-lousho-agenttemplate:npm run devwith piped input (printf 'hi\n' | npm run dev) no longer exits before the reply; it streams the reply and exits when the turn is done.lousho eval: the “with soft failures” total (softFailedin the JSON summary) also counts cases that failed a gate or threw; the JUnit report keeps their soft failures as<system-out>notes.- Sessions: a checkpointed turn whose first model call fails (a 5xx after retries, an exhausted 429, a malformed response) no longer loses the user’s message. The turn is kept as an
in-progresspending turn (newCheckpoint.unstarted), sopending()and the route’sGETshow it, and the nextsend()/resume()runs it again with the message in the transcript once. Over the session routes, that stored turn claims the session for its caller. lousho eval --replay/--recordskip amockModel()provider: a scripted mock needs no network, so a mock eval no longer fails withno cassette ... [LOUSHO_CASSETTE_INVALID].limits.maxCostUsdno longer logs “cost limit is not enforced” on runs that usemockModel(), which has no price.lousho doctorlists optional packages the agent does not use as one info line instead of a warning each.- Docs:
fileMemory({ dir })in an agent directory’smemory/*.tsresolves against the working directory (anchor it to the module);lousho mcptakes an agent directory; runningcreate-lousho-agentfrom a local tarball;lousho dev/chatcannot pass run metadata. - Flows: a durable run (
checkpointStoreandrunId) holds a run lease, like an agent run: a concurrentFlowExecutor.execute()orresume()of the samerunId(in this process, another process or through another store object) is refused withLOUSHO_SESSION_BUSYand runs nothing, instead of running the remaining steps twice. A lease left by a crashed process expires, so the run can still be resumed. See Durable runs. - Flows: a
toolCallargument that is exactly'{{name}}'or'$name'passes the variable’s value (a number, an object) instead of its text, so{ n: '{{n}}' }works with az.number()tool. Mixed strings are still interpolated as text. See Argument values. - Flows: a
stepnode (StepNode) fails with a message naming the supported way to run acreateAgent()agent in a flow (a tool that callsagent.send()). See Running an agent in a flow. - Sub-agents: a sub-agent’s own
memoryworks when the lead’stasktool runs it (recall in its system prompt, itsremember_<name>/recall_<name>tools), scoped by the lead run’ssessionId,metadataandprincipal; before, its slots were silently ignored there. NewsubagentOptions: { continuation: false }leavestaskIdandmodeout of thetasktool, and the error for another sub-agent’staskIdtells the model to omit it for a new task. See Sub-agents.
Security
- Behavior change: the file tools from
createFsTools()(read_file,list_dir,glob,grep,write_file,edit_file) refuse any path with a.gitsegment (.git/config,./.git,a/../.git,.GIT, a worktree’s.gitfile; on Windows also 8.3 names such asGIT~1) with aWorkspaceError, andglob,grepandlist_dirleave.gitout of their results..git/configcan hold a CI checkout token (http.<url>.extraheader) and a worktree’s.gitnames a host path. The newdenyoption sets the names (default['.git'];[]turns it off). Theshelltool is not path-filtered. See Security model. lousho build <dir> --target=node-server|dockerno longer copies an agent directory’s.envfiles or its.lousho/session store (real user transcripts) intodist/and the Docker image. Only the files the server reads are copied:instructions.md,instructions/,skills/and a JSON/YAML config, in the directory and each sub-agent;.env*,.lousho, a JSON/YAML config’sstore.dir,.gitandnode_modulesare skipped at any depth.dist/is emptied before each build so sessions a previous build’s server wrote there are not resurrected, and the generated.dockerignorealso lists**/.env,**/.env.*and**/.lousho. Rebuild and redeploy images built from an agent directory with an earlier version. See Deployment.createRouteHandler()’s UI stream (POST <base>/ui) and framework hook route (POST <base>) now enforce the documented 1 MB body cap (413) likePOST /chatdoes; they previously buffered the full body viarequest.json().- A channel approval decision now binds to the session recorded in the approval’s own durable snapshot, not the
sessionKeythe caller sends, so a request carrying a foreign session key can no longer resolve another conversation’s pending approval. POST /chat/:sessionId/approvals/:idchecks the approval’s kind after authorization:answeronly decides question approvals andapproved/noteonly tool approvals; a mismatched body is400 LOUSHO_APPROVAL_KIND_MISMATCHinstead of silently approving a tool.POST /chatmessage arrays may carryrole: 'user'only; client-suppliedsystem,assistantandtoolmessages are dropped before the turn (content-part arrays without roles are unaffected).- Behavior change:
crossSiteRequestno longer trustsX-Forwarded-HostorForwarded: host=as same-site evidence — those headers are client-controllable. A request is same-site when itsOriginmatches the server’s actualHost(or anallowedOriginsentry); behind a trusted proxy, setallowedOriginsto the public origin. - Session-owner bookkeeping adds a per-principal cap (1024 claimed sessions per caller) under the global 100,000 LRU, so one caller flooding new session ids can no longer evict everyone else’s ownership claims.
webhookChannel()only definesverifywhen anauthoption is configured; an unauthenticated webhook is treated as an open channel and its cross-site requests are refused likehttpChannel()’s. The deprecatedWebhookTriggerAdaptertreats a missingverifyas success.- Malformed percent-encoding in route parameters (
%zz, truncated UTF-8) answers400instead of aURIError500 on/chat/:sessionId/...and channel approval routes.
[1.0.0-alpha.20] - 2026-10-16
create-lousho-agent 0.1.2-alpha.5.Security
- Behavior change: with route auth and no
authorizeSession, a session belongs to the first principal that sends it a turn (reading claims nothing); any other principal gets403 LOUSHO_SESSION_FORBIDDEN. Owners are kept in memory per agent for the 100,000 most recently used sessions, so a stored session whose owner is not on record (after a restart, on another replica, past the cap) is refused to everyone: passauthorizeSessionfor multi-instance deployments and durable stores, orauthorizeSession: () => truefor the old behavior. A route behind one bearer token has a single caller and checks no owner.POST /chatwith an emptyinput(andPOST <base>/uiwithout a user message) is a400that claims nothing, and a turn that stores nothing drops its claim, so an owner can no longer be evicted by flooding. See Who may use a session. - Behavior change:
POST /chat/:sessionId/approvals/:idanswers404unless the approval belongs to that session, and by default only the caller the paused run acts for may decide it; allow others (a supervisor) withauthorizeApproval. - Behavior change: the session routes (
createRouteHandler(),createDeployedServer(), the Worker,lousho dev) refuse cross-site requests: a POST whoseOriginis neither the server’s own (Host,X-Forwarded-HostorForwarded: host=) nor in the newallowedOrigins, or that the browser markedSec-Fetch-Site: cross-site, is403 LOUSHO_REQUEST_FORBIDDEN, and a POST body must beContent-Type: application/json(415 LOUSHO_UNSUPPORTED_MEDIA_TYPE). Requests withoutOriginare unaffected. Opt out withallowedOrigins: ['*']andrequireJsonBody: false;allowedHostsrefuses unlistedHostheaders. Built servers readLOUSHO_ALLOWED_ORIGINS,LOUSHO_ALLOWED_HOSTSandLOUSHO_REQUIRE_JSON_BODY=false. The React/Vue/Svelte bindings no longer sendContent-Typetwice and accept aHeadersinstance. See Cross-site requests. - Behavior change:
lousho devanswers403to a non-loopbackHost(off loopback: an IP address or the--hostname; new--allowed-hosts a,b), so a web page cannot reach it through DNS rebinding, and warns when bound off loopback. A channel withoutverifyrefuses a cross-site browser request (403), andhttpChannel()withoutverifyrequires a JSON body (415). - Behavior change: the Cloudflare Worker refuses every
/chatroute (403 LOUSHO_REQUEST_FORBIDDEN) when noLOUSHO_API_TOKENsecret is set; set the varLOUSHO_ALLOW_OPEN_SESSIONS(or the earlierLOUSHO_ALLOW_OPEN_TRANSCRIPTS) to"true"to allow it./health, the OAuth callback and channels stay open, andlousho build --target=cloudflare-workerwarns about the secret. - Behavior change:
WebhookTriggerAdapterbinds127.0.0.1by default (was0.0.0.0), refuses a non-loopbackhostwithoutauthunlessallowUnauthenticated: true(LOUSHO_TRIGGER_INVALID), refuses a foreignHostor anOriginon loopback withoutauth, caps bodies at 1 MB (413) before auth, and no longer echoes handler errors. See Webhook. - Behavior change: MCP tools ask for approval by default (
approval: 'always'); a server’sreadOnlyHint/destructiveHintcount only withapproval: 'annotations'. An MCP tool named like a local tool is refused withLOUSHO_CONFIG_INVALIDinstead of replacing it. See MCP. - Flows: a
toolCallstep passes the same gate as an agent’s tool call (permissions,permissionMode,onPermissionDecisionand a newapproveoption onFlowExecutionContext); a call that needs approval and is not approved fails withLOUSHO_FLOW_TOOL_DENIEDwithout running. Step arguments are validated against the tool’s schema (LOUSHO_TOOL_ARGS_INVALID) and a flow’s declaredinputsare enforced (LOUSHO_VALIDATION_FAILED). See Flows. - Registry: the approval an install receipt requires for an
exec,needsApprovalor unattested item can no longer be waived from inside the agent directory (anallowrule,acceptEditsor the directory’s ownapprovefile); only a person or anapprovepassed in code decides it. Receipts now also cover a kit’ssubagents/<name>/tools.coding-kit/coding-pirefuse writes to their own config, tools and.git/, dropgit difffrom the shell allowlist and acceptnode --testonly with test file paths (reinstall withlousho add coding-kit --overwrite). See Registry. - Shell tool: an
allowstring pattern refuses arguments that escape the workspace (..segments, also in--flag=../x,~, absolute paths, quoted or escaped forms such ascat "../x", globs that can expand to.., and$,{,}), and under cmd.exe%and^count as shell operators. Use aCommandRuleor an anchored RegExp to allow such arguments. - Agent Forge (
lousho studio) no longer answers any origin: it sends no CORS headers, refuses a foreignOriginor a non-loopbackHost, and every API and WebSocket call needs the per-launch token printed in its URL. See Agent Forge. - Tracing:
redactContentdefaults totrue, so prompts, instructions and tool output are no longer written to span attributes or.lousho/tracesunless you passredactContent: false(orcaptureContent: trueforgen_ai.*content). - The session routes no longer send raw error text to clients:
errorevents,500s andprovider.retry/provider.fallbackevents carry the error’snameandcodewith a generic message, and the full error is logged. PassexposeErrors: truefor the old behavior (lousho devdoes). Channel500s no longer echo internal errors either. fromUIMessages()(andPOST <base>/ui) keeps onlyuserandassistantmessages from the client; a client-sentsystemmessage is dropped.- OAuth: a principal without an issuer gets tokens namespaced by its authenticator, so the same id from Slack and GitHub no longer shares a token (docs/oauth.md has the one-time move);
telegramChannelandteamsChannelsend a sign-in link only in a 1:1 chat; the[REDACTED]net forctx.getToken()tokens also covers thrown errors, object keys, URLs, class instances and base64 forms of the token. serveMcpover HTTP validatesHostandOriginagainst DNS rebinding (newallowedHosts/allowedOrigins), and loopback checks there and inWebhookTriggerAdapteraccept exactlylocalhost,127.x.x.xand::1(127.attacker.examplepassed).- The
openrouterprovider withoutapiKeyreadsOPENROUTER_API_KEYand no longer sendsOPENAI_API_KEYto openrouter.ai. - Slack and Discord signatures accept a timestamp at most a minute ahead (was five minutes either way), read in seconds;
discordChannelrefuses timestamps more than five minutes old.githubChannel({ deliveries })takes a sharedDeliveryStoreforX-GitHub-Deliveryreplay protection. - The
@modelcontextprotocol/sdkpeer range is^1.31.0(was^1.30.1): 1.30.x is affected by GHSA-6qxp-vccf-f47h, which MCP OAuth relies on. SubprocessSandbox:writeFile()stays under the newrootoption (LOUSHO_SANDBOX_PATH_DENIED, also through symlinks), and containers run as1000:1000with all capabilities dropped,no-new-privilegesand default limits (512 MiB, 256 pids, 1 CPU); passuser: 'root'for the old user. See Guardrails.
Changed
-
Behavior change: session turns keep the checkpoint history of the latest 10 committed turns (
agent.session({ id, turnHistoryLimit });0keeps none); storage used to grow with the square of the conversation. Excess history already in a store is deleted over the next commits, also when each turn uses a new process or store object. NewfileStore(dir).prune({ olderThanMs })returnscheckpointHistorytoo;fileStore()returns the newFileStoretype. -
Behavior change: a checkpointed run holds a run lease while it executes (new optional
CheckpointStore.acquireLease(),releaseLease(),renewLease(),saveIfLeased(); file, SQLite, memory and best-effort KV stores). A second process, replica or store object that sends to the same session, resumes it or resolves its approval getsLOUSHO_SESSION_BUSYinstead of running its tool calls again, and a stalled holder can no longer overwrite the run that took over. A dead holder on the same host is taken over at once; on another machine 30-60 s after its last heartbeat. Schedule fires are claimed the same way, so replicas fire a tick once. See Run leases. -
Behavior change: approvals run at most once: deciding one re-saves the turn as
'in-progress'with the call inCheckpoint.startedToolCallIds, and resuming after a crash mid-call gives it akind: 'interrupted'tool error instead of running it again. Resolving an approval whose run was deleted or replaced fails withLOUSHO_APPROVAL_ORPHANEDand withdraws it. -
Behavior change: a session turn paused for approval locks the session id: a new turn on it throws
SessionAwaitingApprovalError(LOUSHO_SESSION_AWAITING_APPROVAL) until the approval is decided ordiscardPending()drops the turn. -
Behavior change: a deterministic provider error records
lastErroron the turn’s checkpoint, and later calls on that session fail fast withLOUSHO_SESSION_TURN_FAILEDinstead of replaying the failing turn;resume()retries it. -
Behavior change: run ids (
send({ sessionId }), a fork’snewSessionId) are 1-200 characters ofA-Za-z0-9_.-on every store and may not end in.turn-<n>,.pausedor.fire;''is refused. Session ids (agent.session({ id }), the routes) stay 1-128 characters ofA-Za-z0-9_-. The error messages now say which of the two rules applies. -
Behavior change: with a store, tools,
needsApproval, permission rules and hooks get the session id asctx.sessionId, not the checkpoint key<id>.turn-<n>(newExecuteOptions.contextSessionId). -
Behavior change: a model step with several calls that need approval pauses once, on all of them (
result.approvalIds,agent.approvals.resolveAll()); calls that need no approval run before the pause. See Several calls in one step. -
Behavior change:
once()no longer remembers a yes from acreateAgent({ approve })callback, and'defer'is reserved: an approval note that is exactly'defer'defers. -
Behavior change:
approvalTtlMsand anaskrule’sttlMsabove 100 years throwLOUSHO_CONFIG_INVALID(they meant “never expires”). -
Behavior change: memory items are keyed
<slot name>#<scope key>, so two slots on one scope no longer share items. RunmigrateMemoryKeys(slot)once to copy items stored under the old bare key. See Memory. -
Behavior change: a prompt schedule runs every fire in its own session
schedule-<name>-<fire time>(defineSchedule({ sharedSession: true })keeps one shared session), and a fire that does not finish'stop'reports the newLOUSHO_SCHEDULE_RUN_INCOMPLETE. -
Behavior change: channels without a
storekeep transcripts in the agent’screateAgent({ store })when it hassessions. -
Behavior change: the routes let a session turn run to its end and save it when the client disconnects (
onDisconnect: 'abort'for the old behavior;waitUntilkeeps a serverless function alive). An aborted turn keeps the user’s input, the tool calls that ran and the partial reply (metadata: { interrupted: true }), and its usage counts. -
Behavior change: tool results are capped at
maxToolResultChars(default50_000,Infinityfor none) for every tool; MCP image/audio/blob data reaches the model as a placeholder and MCP tool descriptions are cut at 2,000 characters. -
Behavior change: a user file part the provider cannot send rejects the call with
LOUSHO_UNSUPPORTED_CONTENT(under fallback the next provider gets it) instead of a text note;unsupportedFiles: 'text-note'keeps the note. See Multimodal input. -
Behavior change:
createAgent({ provider })with a built-in orfromAiSdk()provider and noretrywraps it inwithRetry()(provider’smaxRetries, default 2), andwithRetry()is the only retry layer: the built-in providers turn theaiSDK’s own retries off (retry: falseused to send 3 requests,maxRetries: 3sent 12). -
Behavior change: a rate-limited call has the code
LOUSHO_PROVIDER_RATE_LIMITED, and an out-of-credit account (insufficient_quota, 402) is the new non-retryable categoryquota-exceeded. -
Behavior change:
OpenAIProvidersendsstore: falseon the Responses API unlessstore: trueis set. -
Behavior change (types):
LLMProviderConfighas no index signature, so a misspelled option is a type error;LLMProviderRegistry.register()/create()take the provider’s own config type (newBuiltinProviderConfigs).ExecutionFinishReasonis a closed union, and an unknown provider finish reason is reported as'other'. -
Behavior change:
agent.stream()rethrows the run’s error after theerrorandrun.doneevents ({ throwOnError: false }for the old behavior). -
Behavior change (CLI): every usage error exits 2 and 1 means a command ran and failed.
lousho eval,build,dev,chat,acp,mcpanddoctorload./.env. The fallback registry URL points at the installed version’s release tag. -
Behavior change:
connectMcp()rethrows a server’s start failure asMcpStartError(LOUSHO_MCP_START_FAILED, with exit code and the last stderr lines) instead of wrapping it. -
Evals:
t.maxCostUsd(n)fails when a run reports no cost ({ unknownCost: 'skip' }for the old, now warning, behavior);judge.modelandllmJudge()/llmCritique()’smodelare optional. -
Pruned tool results leave a stub naming the call and its arguments (
[pruned: search({"query":"deploy"}) result, 18234 chars; already read]). -
Agent Forge: a run on a real provider without an API key fails with
LOUSHO_PROVIDER_MISSING_API_KEY(HTTP 422) instead of silently using the mock provider, and the provider pill shows what actually ran. -
The examples import
@lousho/build-ai-agentand its public subpaths instead of the repository’ssrc/, so they can be copied into an app as they are. -
The
package.jsonthatlousho build --target=node-server|dockerwrites lists only the optional peers the bundled server loads (the provider package,@modelcontextprotocol/sdkwithmcpServers), no longer@lousho/build-ai-agent:dist/server.jsbundles the SDK,aiandzod, so the image’s install is smaller. -
The npm package no longer ships the CommonJS build of the CLI (
dist/cli/*.jsand maps) or the CLI’s type declarations:bin/lousho.jsloads onlydist/cli/*.mjs.
Added
-
Providers: a
timeoutoption (default 10 minutes until the response starts and between chunks;0orInfinityturns it off) and afetchoption on every built-in provider.OpenAIProvider({ api: 'chat' })andLOUSHO_OPENAI_API=chatuse Chat Completions for OpenAI-compatible servers (LM Studio, Ollama, vLLM, llama.cpp; the built-in hosted tools are then refused withLOUSHO_HOSTED_TOOL_UNSUPPORTED); see Local and OpenAI-compatible servers.withRateLimit()/createRateLimiter()andcreateAgent({ rateLimit })queue model calls client-side.promptCaching: 'auto'(the default) marks Anthropic cache breakpoints for Claude onanthropicandopenrouter.withRetry({ idleTimeoutMs })fails a stream that stalls between chunks (timeoutMsnow bounds only the wait for the first chunk).withFallback()results carryservedBy. -
Model settings:
createAgent({ modelSettings })and per-callmodelSettings(maxTokens,temperature,topP, penalties,stop,seed,toolChoice), range-checked up front, also inagent.json. Per-callmaxStepsandinstructionsonsend()/stream(). See Configuration. -
Cost: built-in prices for more default models (Ollama
llama3window, OpenRouter variants), cache read/write prices (cachedInputCostPerMTok,cacheWriteCostPerMTok,cacheWriteTokens) and OpenRouter’s reportedusage.costforcostUsdandlimits.maxCostUsd. -
Approvals:
remember: 'session'and editedargson a decision,'defer'from anapprovecallback,approvalTtlMs/ttlMsdeadlines (expiresAton events and UI state),agent.approvals.list()across processes (new optionalApprovalStore.list()),agent.pending()for unfinished runs (new optionalCheckpointStore.list()), andresumedAfterApprovalon tool-call hook contexts. See Approvals and Recovering after a crash. -
Routes:
authorizeSessionandauthorizeApprovaloncreateRouteHandler()/createDeployedServer(); approvals report theirsessionIdand error events theircode. Built node and Docker servers drain on SIGTERM (shutdown({ timeoutMs }),LOUSHO_SHUTDOWN_TIMEOUT_MS). Channel routes decide each call of a multi-call pause and accept asessionKeyafter a restart. -
Flows: durable runs (
checkpointStore+runId,FlowExecutor.resume()), pausing for approval (status: 'awaiting-approval'), per-noderetryandtimeoutMs, cancellation throughsignal, andusageon the result. See Flows. -
Structured output: partial-object streaming (
object.delta,partialObjectin the UI bindings),result.outputRepaired,{ schema, promptSchema: false }, a forced no-tools answer whenmaxStepsorlimits.maxStepsruns out, andoutputError.kind: 'truncated'. Unions, records, tuples and optional fields now work on strict endpoints. See Structured output. -
Memory:
expose: { forget: true },itemSchema/itemKeyupserts (new optionalMemoryProvider.upsert()),memoryKey(), de-duplicatedadd(), andmigrateMemoryKeys(). See Memory. -
MCP:
optional: true,cwd,stderr,connectTimeoutMs,timeoutMs,tools: { include, exclude }, per-callapproval({ args }),onToolsChangedandMcpConnections.reconnect(). See MCP. -
Observability:
invoke_agentspans carry the request model and token totals (agentUsageTotals: falseleaves them off),legacyAttributes: false,parentSpanIdonsend()/stream(), retry attributes onchatspans, sub-agent names on their spans, and compaction calls as countedchatspans. See Observability. -
Tools and sub-agents:
defineTool({ timeoutMs }),subagentOptions: { background: false },read_skill_filefor skill folders,ToolDescriptor.transient,CommandRuleobjects for the shell tool’sallow/deny, and an optionalShellProvider.shellthat tells the model which shell runs its commands. -
Compaction:
reserveOutputTokensandonCompactionon the object form;GenerateHookContext.generate()for counted side calls. -
Evals: sub-agent tool calls in trajectory evals,
SendOptions.onEvent,repeat/passAt,{ agent }forsetProviderInterceptorcallbacks,lousho eval --timeoutanddefineEval({ timeoutMs }), andrecordReplay({ rerecordHint }). See Evals. -
Channels and schedules:
githubChannel({ pullRequestOpened: true }),webhookChannel({ principal }), exportedfireSchedule(),startSchedules({ keepAlive: true })and an awaitablestop(), andmountFetchChannels({ waitUntil }). -
CLI:
lousho doctor --pingand base URLs in its output, andlousho --version. -
lousho build --target=node-server|dockerbuilds a.ts/.jsagent module (the filelousho dev src/agent.tsserves: a default oragentexport holdingcreateAgent()options or a built agent). Thecloudflare-workertarget says it builds only a spec or an agent directory. The minimal and tools scaffolds export their options assrc/agent.ts’s default export, solousho dev|chat|mcp|acp|build src/agent.tswork on a new project, and every scaffold has abuildscript (andtsup); the minimal and tools ones also havedev:ui(lousho dev src/agent.ts). -
The Docker image
lousho build --target=dockerwrites has aHEALTHCHECKonGET /health, and its.dockerignorekeeps.env,.env.*and*.tgzout of the image. -
lousho add,studio,evalandtraces --helpdescribe every flag;lousho help <command>prints that command’s help.
Fixed
- Durability: concurrent commits on one session no longer lose a turn (new optional
SessionStore.saveIf()compare-and-swap;KVStorestays best effort), and session objects re-read the store instead of caching the transcript. Concurrentsend({ sessionId })calls in one process run in order. Parallel tool calls are checkpointed as each settles, so a crash no longer re-runs finished calls. A restarted process that resolves a session’s approval commits the turn instead of dropping it.session.clear()deletes every turn’s checkpoints and history, finished turns stay forkable,session.fork()works for 122-128 character ids, and sub-agent task ids are never reused. - Stores:
fileStorefile names are case-safe on Windows and macOS (Aliceandaliceno longer share a file), long ids and device names are hashed, older long names are still read, writes arefsynced and WindowsEPERM/EBUSYis retried. A corrupt checkpoint fails withLOUSHO_CHECKPOINT_CORRUPTand can be discarded.SqliteStorewaits 50 ms instead of freezing the event loop, retries locked writes without blocking (LOUSHO_STORAGE_BUSY) andprune()keeps paused turns.KVStoreapproval claims run a tool once in the common case (ctx.approval.idserves as an idempotency key). Image and file bytes survive every store. Taking over a stale file lock is serialized, andKVCheckpointStore.list()throws without alistbinding instead of returning[].agent.approvals.get()returnsundefinedfor an id that cannot name an approval.fileMemoryandsqliteMemorykeep every item with several writers. - OAuth: concurrent
ctx.getToken()calls share one refresh, and a refused refresh no longer deletes a newer token. - Approvals and memory: a run resumed after an approval or a crash keeps its memory tools and the scope it paused with; memory stays on after a handoff; recall errors skip the slot with a warning; invalid scopes fail with
LOUSHO_MEMORY_INVALID; keyword recall matches whole words;<memorytags in item text are escaped;recall_<name>returns scores and metadata. - Providers on
ai4, 6 and 7: tool errors are no longer wrapped twice onai7, malformed or truncated tool-call JSON reaches the model as a repairableLOUSHO_TOOL_ARGS_INVALIDerror (light repairs are tried first;tool.starthasrawArgs), prefixed tool names (functions.read_file) resolve, unknown tools suggest the closest name, duplicate tool-call ids both run, a completion sent to a streaming request is replayed, mid-stream andfinish_reason: "error"failures become retryable 502s, a stream that fails before any output is retried, and unsettemperature/maxTokensare left out.withFallback()keeps its state per call, so concurrent calls no longer misreport fallbacks or book cost under the wrong model, andwithRateLimit()overwithRetry()streams reports the final attempt and holds its slot until the retried stream ends. - Provider errors: local runtimes’ context overflows are
context-length-exceeded, refused connections name the URL, status and message are read together, nested OpenRouter reasons are shown, a longRetry-Afterfails at once instead of sleeping, negative hints are ignored, and compacted errors keep their category throughcreateAgent(). A missing provider package fails withLOUSHO_PEER_MISSING, and the routes send itsnpm installcommand to the client. - Provider features:
reasoningreaches more models and warns once when it is dropped; image MIME types are sniffed;OpenRouterProviderhonoursbaseURLandOllamaProvidersendsheadersandapiKey;supportsTools()knows current models; registered providers work in model strings; retired fallback models are replaced; price lookup handles OpenRouter spellings; the forced answer atmaxStepsworks on Claude. - Runs: abort no longer waits on a provider or tool that ignores the signal (
finishReason: 'aborted',result.abortReason;mockModelhonourssignal), aborted streams keep their text, a throwing event listener or trace exporter no longer fails the run, tool results with cycles, BigInts, Maps or Sets serialize,send(result.messages)does not repeat the system prompt,send([])throwsLOUSHO_CONFIG_INVALID, afinish_reason: tool_callsreply without calls ends'stop', aload_skilltool that clashes withskillsthrows,maxStepsmust be a whole number >= 1, and handoffs work on local models and Anthropic (no mid-conversation system message). - Structured output: the repair and forced-answer prompts stay out of transcripts, near-miss replies (prose,
<think>blocks, fenced JSON) are accepted without a repair call, a reply that repeats the schema gets a clearer repair message, and unsupported root unions or zod 4z.date()fields throw aConfigurationErrornaming the fix.defineTool()rejects inputs no model can satisfy and acceptsz.preprocessdates on zod 4.1+. - Compaction: summarizing splits oversized histories, counts tool definitions and the output schema, warns when it falls back to a 128,000-token window for an unknown model, caps
protectedTokensat half the threshold, retries the summarizer after a rejection, counts its call in usage and budgets, and reportsappliedStrategy. - Sub-agents and handoffs: dynamic sub-agent config functions get the lead’s
sessionId,metadataandprincipal; a failed sub-agent’s spend counts; truncated answers say so; agent-directory and Workersubagents/run as native sub-agents; a handoff target’stoolSearchapplies. - Schedules: a fixed-hour cron job in a spring-forward gap runs once after the gap instead of being skipped.
- Flows: a failed
parallelbranch aborts its siblings,forEachvariables are per iteration, unnamed steps get unique ids, andresume()refuses a changed flow (LOUSHO_FLOW_CHANGED). - MCP:
Not connectedcounts as a dropped connection and reconnects,tools/listfollows every page, dropped servers report'failed'with their stderr, calls honour abort, text-only results are sent once, tool names are made valid for every provider, object schemas with a siblingoneOfkeep their shape,agent.ready()reconnects afterclose(), andserveMcp()over HTTP cancels the run a client cancels or abandons (matched by its newMcp-Session-Id) and rejects its pending approvals.serveAcpkeeps serving after a malformed JSON line. - Channels: redelivered webhooks run once (Telegram, GitHub, Slack), concurrent decisions on one approval decide it once (
409 LOUSHO_APPROVAL_CONFLICT, also on the routes),webhookChannelauthenticates on Fetch hosts and its pause replies carry the prompt,githubChannelignores/approvefor unknown approvals, and channelmetadatareaches the run.POST <base>/uianswers 400 for an invalid id, andauth: ''isLOUSHO_AUTH_CONFIG_INVALIDoncreateRouteHandler()andserveFetch(). - UI bindings (React, Vue, Svelte): remote mode keeps one session across turns, a stream that ends early becomes an error, each step starts a new paragraph, abnormal endings set
status: 'error', React gainsreset(), server error messages are kept, Svelte no longer aborts on a transient subscribe,formatUsage()shows small costs, andparseEventStream()joins multi-linedata:fields. - Tracing and OpenTelemetry: open spans are bounded without losing parents, queued background sub-agents stay in the lead’s trace, background sub-agent cost rolls up, and
execute_toolspans carry the error message. - Evals: replay matches calls by request, sub-agent cassettes are named after the agent, cassette names include a hash of the case label, re-recording unchanged exchanges leaves no diff, tool order no longer breaks replay, reasoning and full usage are recorded, judge scores parse more formats (the last
SCORE:wins) and judges see the user’s input at temperature 0,lousho evalgives live cases 10 minutes and its reports are never empty when vitest fails. - CLI:
lousho devreloads CommonJS tool files and recreated folders, tool files no longer printMODULE_TYPELESS_PACKAGE_JSON, TypeScript syntax that type stripping cannot erase gets an error suggesting--experimental-transform-types, every agent command loadstools/*.tsof an installed project (one ESM build, shared brands,instanceofacross ESM and CJS copies),lousho buildreports bundling failures asLOUSHO_DEPLOY_FAILED, warns about missing provider packages, merges an existingwrangler.toml(new defaultcompatibility_date2026-09-01), no longer needs unused provider packages for a Worker and prints where it wrote, Docker images run asnode,lousho doctorandlousho mcpaccept agent directories,lousho addchecks flags and target directories up front and falls back to GitHub when the default registry is down,lousho inittemplates and Windows instructions are fixed,initsays when the provider’s API key is missing and git-ignores an--sdk-pathtarball, and help texts and messages are clearer. - Agent directories: every
createAgent()override passed toloadAgentDir()is forwarded,mock/<name>models work from every entry point, and import failures throwLOUSHO_AGENT_DIR_INVALIDwith an install hint.loadSkills()skips a looseREADME.md. - Workspace tools:
greprefuses catastrophic regexes and runs with a time budget,edit_filerefuses non-UTF-8 files instead of corrupting them, andtool_searchranks synonyms and word families. - Agent Forge: agents are read from and written to
.lousho/agents/, narrow screens and keyboard and screen-reader use work, invalid names and imports show errors instead of a blank page, finished runs reportdone, and several drawing and status glitches are fixed. - Packaging and types: ESM consumers get
.d.mtsdeclarations (plustypesVersionsfornode10), declarations type-check withskipLibCheck: falseon zod 3 and 4, the pi peers are caret ranges,llms-full.txtno longer ships and the Worker entry has no source maps. - Docs: corrections throughout (sessions vs runs under one id, schedules, nextjs approvals, memory,
engines.node), the snippet check now also runs every snippet that builds its own mock provider and checks fences indented in lists, and the ops-pipeline example works as described. - A checkpointed session turn that stalled past its run lease and then failed for good no longer stamps its
lastError(retryable: false) on the checkpoint of the process that took the turn over, which bricked that turn forever withLOUSHO_SESSION_TURN_FAILED: the session now holds the turn’s run lease itself (handed to the run asHELD_RUN_LEASE) andrecordFailure()writes throughRunLease.save, whose fenced save writes nothing once the lease is lost. agent.send(msg, { sessionId })and a freshagent.session({ id })no longer run beside a session turn that waits on an approval when its<id>.pausedmarker was never written (a crash or a send between the executor’s awaiting-approval checkpoint andmarkPaused()):pausedSessionTurnnow also scans the store’s<id>.turn-*checkpoints forstatus: 'awaiting-approval'when the marker is absent, on stores that implementlist().- A streamed tool call whose deltas repeat its
idwhile omittingindex(the OpenAI-compatible / Gemini-proxy servers the tool-call id rewrite exists for) stays one call: each repeat no longer mints acall_1_2,call_1_3, … id that split the arguments JSON across phantom calls none of which parses; the call’s slot in the delta’stool_callsstands in for the missingindex. - A non-streamed request whose body carries a nested
"stream": true(aproviderOptionspassthrough, tool arguments, gateway metadata) no longer has its JSON reply rewritten into an SSE stream the consumer cannot parse: whether a request asked for streaming is read from the parsed top-levelstreamfield instead of a regex over the raw body. - Session routes: two concurrent first-touch turns on one unowned session no longer both pass the owner check - the claim is atomic now, so the loser is refused (
403 LOUSHO_SESSION_FORBIDDEN) instead of streaming a turn inside the winner’s session; a claim lost while a turn ran clears what it stored and ends the stream on the same coded error. - Approve-with-edits on a sub-agent’s grouped approval validates the edited args against the tool’s schema like a top-level or single sub-agent decision does: before,
snapshot.subagentstoreddecision.argsraw, so an invalid edit (e.g. a string wherez.number()wants a number) ran the tool with garbage args; it now throwsLOUSHO_TOOL_ARGS_INVALIDand leaves the approval pending. - Aborting a run during a tool call no longer hangs
send()/stream()/approvals.resolve()forever on a tool that ignores itsabortSignal: the tool batch and the approved-tool wait ofresumeAfterApproval()are raced against the run’s signal the way the model call already was, the run endsfinishReason: 'aborted'with a ‘cancelled’ result for calls still running past a short grace window (a result that lands within it is still kept), and the tool keeps running in the background. - A run that re-pauses on several approvals after a resume persists every pending approval id in its checkpoint:
markAwaitingApproval()wrote onlyapprovalId, so durable discovery (pausedApprovalIds,agent.approvals.list()) named 1 of N approvals; it now carries the group’sapprovalIdslikemarkGroupPending()does. - The
inbox-triageregistry kit loads underlousho dev,chat,acp,mcpanddoctor: its relative imports carry the.tsextension Node’s type stripping needs (only bundlers resolved them). A test now installs every registry kit and loads it in a plainnodeprocess, as the CLI does. An extensionless relative import in an agent directory gets a hint naming the specifier to write ('./lib/store.ts'), and on a Node without built-in type stripping (before 22.18) the.tsload error says Node 22.19+ is required. OPENAI_BASE_URL(andANTHROPIC_BASE_URL) is used with@ai-sdk/openai1.x (@ai-sdk/anthropic1.x), the line that pairs withai4: the provider passes it when nobaseURLis configured. Before,model: 'openai/...'called api.openai.com whilelousho doctor --pingreported the custom endpoint.PropagatingToolError,McpToolErrorandWorkspaceErrorpassinstanceofacross the ESM and CJS copies of the SDK, so a.cjstool’s “do not retry” error stops the run under the ESMloushoCLI instead of being handed to the model (and retried).lousho devre-evaluates the local helper files an edited tool or agent module imports (the?t=cache-bust is passed on to relative imports), instead of logging “reloaded” while serving the stale helper; editor temp files no longer show in the “changed:” list.lousho eval: a case that vitest fails after the case finished (it ran past its time limit) is reported as that case failing, not as a pass plus an extravitestrow; a run that records no case at all (a mistyped--tag) exits 1 like a glob that matches nothing.- The yarn scaffold’s
yarn testworks: the templates listvite, vitest’s peer, which yarn 1 does not install. The README’s “Next 3 commands” lists three, and the tools template’s README counts its three tools. - CLI messages: a module that exports no agent names the command that loaded it (
lousho chat:, notlousho dev:);lousho mcpwithout a path says a spec, directory or module is accepted, and--port/--hostwithout--httpare a usage error instead of ignored;lousho version <arg>andinit --sdk-path <missing>exit 2; the unknown-provider error listsmock.
[1.0.0-alpha.19] - 2026-10-08
Everything published from 1.0.0-alpha.15 (2026-10-06) through 1.0.0-alpha.19 (alpha.17 on 2026-10-07, alpha.18 and alpha.19 on 2026-10-08). Most of it was prepared onmain under the version number 1.0.0-rc.0, which was never
published. Upgrading from an earlier 1.0.0-alpha.* release? Read the
upgrade guide: imports moved to subpaths, dead and
superseded APIs were removed, and the patch guardrails are now patch checks.
What 1.0 considers public is defined there (every exports entry and the
checked-in api/ reports).
Breaking
- Flows, the Jira / GitHub / Slack / email tools, encryption,
StorageServiceand the validators moved out of the package root. Import them from their subpath:FlowBuilder,FlowExecutor,validateFlowand every flow type (AgentFlow,EditorStep,FlowExecutionEvent,…) from@lousho/build-ai-agent/flows;createJiraTools,createGitHubTools,createSlackTool,slackTool,postSlackAlert,createEmailTooland their types from@lousho/build-ai-agent/integrations;EncryptionUtils,DTOEncryptionFilter,DecryptionError,sha256,generatePassword,StorageService,StorageServiceApprovalStore,LocalStorageCheckpointStoreand the validators (validateWithSchema,safeValidate,isValidEmail,…) from@lousho/build-ai-agent/utils. The integrations are no longer in@lousho/build-ai-agent/toolsand the flow types are no longer in@lousho/build-ai-agent/types. Nothing else changed: the classes and functions are the same. For file-backed stores withcreateAgent(), preferfileStore(dir). - Removed
AgentType,AgentTypeDescriptor,AgentConfig.agentType,AgentBuilder.setType()and the agent-type registry (agentTypesRegistry,getAgentTypeDescriptor,getAllAgentTypeDescriptors,isValidAgentType,validateAgentConfig,validateAgentTools). They had no runtime effect since 1.0.0-alpha: delete thesetType(...)call and theagentTypefield. Also removed, because nothing implemented or used them: the repository interfaces (IRepository,IAgentRepository,ISessionRepository,IResultRepository,SessionData,ResultData,SDKRepositories),DataLoadingStatus,PaginationParams,PaginatedResponse,DeepPartial,Timestamped,IdEntity,AgentExecutionOptions,AgentExecutionResult,AgentDefinitionandToolSetting. If your code used one of these types, copy its declaration into your project. A checkpoint saved withagentTypestill loads; the field is ignored. - Removed
ExecuteOptions.onEventand theExecutionEvent/ExecutionEventTypetypes, deprecated in an earlier alpha. PassonAgentEventtoAgentExecutor.execute()/stream()/resumeAfterApproval()instead (withcreateAgent(),onEventalready receivesAgentEvents and is unchanged). The mapping from the old event names toAgentEventtypes is in docs/streaming.md#listening-without-iterating (“Migrating fromonEvent/ExecutionEvent”). The one-time “onEvent is deprecated” warning is gone with it. - Removed
createDelegateTool(),DelegateAgentOptions,DelegateAgentResultandDelegationDepthExceededError. Use thesubagentsoption instead, oncreateAgent()orAgentExecutor.execute(): create the child withcreateAgent({ provider, instructions, description })and passsubagents: { billing }. The model gets onetasktool for every sub-agent, with the same inheritance (hooks, permissions, abort, usage roll-up) and a depth limit (maxSubagentDepth, default1). A run at the depth limit is not offered thetasktool, so a delegation cycle can no longer start;DelegationDepthExceededErroris gone. See docs/sub-agents.md. - The executor API moved out of the package root to
@lousho/build-ai-agent/executor:AgentExecutor,AgentBuilder,ExecuteOptions,resumeAfterApproval,streamResumeAfterApproval,resumeRequest,ResumeExecuteOptions,ResumeRequest,ToolRegistryandglobalToolRegistry. Changeimport { AgentExecutor, AgentBuilder } from '@lousho/build-ai-agent'toimport { AgentExecutor, AgentBuilder } from '@lousho/build-ai-agent/executor'.ToolRegistryis also still in@lousho/build-ai-agent/tools. The@lousho/build-ai-agent/coresubpath is removed: importAgentBuilderfrom@lousho/build-ai-agent/executor.createAgent(),ExecutionResultand every typecreateAgent()uses stay in the root. To move off the executor API entirely, see docs/migrating-to-create-agent.md. - The patch guardrails are now called patch checks, so “guardrail” only means the input/output/tool guardrails of
createAgent({ guardrails }). Rename:runGuardrailstorunPatchChecks,GuardrailtoPatchCheck,GuardrailResulttoPatchCheckResult,ProposedActiontoProposedPatch,RunGuardrailsResulttoRunPatchChecksResult,runGuardrailSafelytorunPatchCheckSafely,secretScanGuardrailtosecretScanCheck,createDiffSizeGuardrailtocreateDiffSizeCheck,createCommandGuardrailtocreateCommandCheck(options typeCommandCheckOptions),createTestRunGuardrailtocreateTestRunCheck,createLintGuardrailtocreateLintCheck. Arguments, results and behavior are unchanged.SECRET_PATTERNSkeeps its name.
Security
- Behavior change: MCP tools now ask for approval by default (
approval: 'always'). A server’s ownreadOnlyHint/destructiveHintno longer switch approval off or let a tool run in plan mode unless its entry opts in withapproval: 'annotations'(loaded descriptors then carrymetadata.mcp.annotationsTrusted: false). An MCP tool whose<server>__<tool>name equals a local tool’s is refused withLOUSHO_CONFIG_INVALIDinstead of silently replacing it and its approval gate. Setapproval: 'annotations'on servers you trust to keep the old behavior. See MCP. openApiTools()can refuse private destinations: with the new optionprivateAddresses: 'refuse'(default'allow', unchanged), every operation request and the document fetch, each redirect hop included, fails when its host is or resolves to a loopback, link-local, private or reserved address. Host names go through the pinned DNS lookuphttp_requestandweb_fetchuse (one resolution per connection, every address checked, the socket connects to the checked address), so DNS rebinding cannot reach a private address; IP literals in every formURLnormalizes (decimal, octal, hex, IPv4-mapped IPv6) andlocalhost/*.localhostare refused when the tools are made.allowPrivatelists hosts that may be private.'refuse'cannot be combined with a customfetch(it throws aConfigurationError: a custom fetch’s connections cannot be pinned) and needs Node.js (undici,node:dns); where undici cannot load, making the tools throws aConfigurationError. See docs/openapi-tools.md#security-rules.- The registry permission manifest is now enforced when an agent directory loads and runs.
loadAgentDirre-hashes every file thelousho-registry.jsonreceipt lists; an item with edited or missing files is reportedunattested(a warning naming the item and files, andmanifest.registryonresolveAgentDir(), which also gains the newAttestation,RegistryItemStatusandRegistryStatustypes) without refusing the load. Every tool a receipt item owns then runs inside the manifest accepted at install: anexec: trueorneedsApproval: trueitem’s tools - and any unattested item’s tools - always wait for approval (a tool’s owndenystill denies);fetchwhile the tool runs is limited to the declarednetworkhosts;process.envshows only the declaredenvnames; and arequiresSandboxtool gets a narrowed adapter (run()refused withoutexec,writeFile()withoutfilesystem: "write", a command env of the non-secret base plus the declared variables only). The envelope stays as narrow as the last accepted manifest untillousho add <name> --overwriteattests the current files. Limits, unchanged: the guards interceptfetchandprocess.env, nothttp/net/axios, the filesystem, module-scope captures or a container’s own network policy; the manifest is still not a sandbox. See docs/registry.md#permission-manifest.
Changed
- The published package is smaller: ~873 files / ~13.5 MiB unpacked / ~3.65 MiB packed, down from ~902 / ~20.8 MiB / ~5.6 MiB. Test-only files that still shipped (
*.test-d.tstype tests,*.testkit.tshelpers,__snapshots__/and the test-replay__cassettes__/directories) and the Agent Forge server source map no longer ship, and the SDK’s own source maps no longer embedsourcesContent— theirsourcesstill resolve to the shippedsrc/, so--enable-source-mapsstack traces keep working.pack-smokenow also runsbuild:studio, so it measures the tarball that is actually published, and it fails when a filelousho buildorlousho studioneeds is missing. - Test files are type-checked (
npm run typecheck:tests, in CI);pack-smokealso checks the published declarations withskipLibCheck: false.
Added
- Agent directories: new
agent.*config keyspermissionMode,permissions(a serializable rule form:toolis a name, a list or - in a code config - aRegExp;whennarrows the rule with a record of argument names to matchers - a regular expression string or an operator object (eq/ne,lt/lte/gt/gteonNumber(arg),matches), or a predicate in a code config;actionisallow/ask/deny),compaction,limits, plushooksandapprove, each a path (relative to the directory) to a file default-exporting the hook(s) / the approver function, or the value inline in a code config.instructions/<family>.mdappends toinstructions.mdwhen the resolved model id contains<family>(e.g.openai,anthropic).lousho build --target=node-server(and--target=docker) bundles a roothooks.*/approve.*file next to the config and resolves the compiled.jssibling; the Cloudflare Worker target carriespermissionMode,permissions,compactionandlimitsover and acceptshooks/approvefrom a code config (a file path is refused, a Worker cannot import it). See Agent directories. - Registry: a new item
typekitis a whole agent directory - itsfilesmay sit at any (still safe) relative path - solousho add <kit> --dir <target>installsagent.*,instructions.md, tools, skills and sub-agents in one item, under one permission manifest, and records it inlousho-registry.jsonlike any other item. The default registry’s first kit iscoding-kit, a port of theexamples/coding-harnessbaseline: workspace tools with checkpoint rewind, an allow-listed shell, permission rules, a loop guard and output cap as hooks, a compaction setting, afix-failing-testskill and a read-onlyexplorersub-agent (manifest:exec,fs-write; install withlousho add coding-kit --dir <dir> --yes --allow exec,fs-write). See Registry. - The
piprovider:createAgent({ model: 'pi/<pi-provider>/<model>' })routes calls through@earendil-works/pi-ai(1.0.3, a new optional peer -npm install @earendil-works/pi-ai@1.0.3), the enginepi-coding-agentruns on, so pi’s whole catalog (OpenRouter, Anthropic, OpenAI, Google,…) is usable natively; e.g.pi/openrouter/openai/gpt-4o-miniis OpenRouter’sopenai/gpt-4o-mini(nested slashes are kept: the segment afterpi/is the pi provider, the rest the model id). Messages (including reasoning blocks, tool calls/results and image parts), toolparameters(raw JSON Schema, zod 3/4 or Standard Schema), streamed chunks and usage/cost map to the same surface theai-SDK providers expose, and pi’s own retries are pinned off soretry/fallbackModelsstay the only retry layer. Credentials are per nested provider: pi reads each one’s own env var (pi/openrouter/...readsOPENROUTER_API_KEY), and a missing one fails the call withLOUSHO_PROVIDER_MISSING_API_KEYnaming it; a missing package fails withMissingPeerDependencyErrornamingnpm install @earendil-works/pi-ai@1.0.3. New exportPiProvider(+PiProviderConfig, whosemodelsinjects custom/faux catalog entries).piis Node-only: thecloudflare-workertarget refusespi/...specs. See docs/providers.md#the-pi-provider. piAgent()(“pi-coder”): a Pi coding-agent session (@earendil-works/pi-coding-agent, a new optional peer) usable in-process as acreateAgent({ subagents })entry -subagents: { coder: piAgent({ cwd, model, description, permissions }) }. Eachtaskcall is one Pi session under the task’ssessionId, sotaskIdresumes and approval resumes reopen the same JSONL transcript even across a restart.permissions(the samePermissionRules ascreateAgent()) gate every Pi tool call through atool_callextension handler:denyrefuses it,askpauses the lead run durably for approval when the caller can pause and refuses it otherwise; approving re-issues that exact call once (Pi has no run-blocked-call API, so a decision prompt asks the model to repeat it and the gate lets that one call through), rejecting sends the note as the next turn. Pi usage rolls into the lead’sresult.usage, and aborts propagate to the Pi session. Node-only: the package is loaded lazily, so a consumer without it still typechecks andrun()fails withLOUSHO_PEER_MISSING. Also new:defineRemoteSubagent(impl)wraps anyRemoteSubagentimplementation (same contract asremoteAgent()), andSubagentApprovalPauseis exported for such adapters.- Agent directories: three more
agent.*config keys wire the approval surface.approvalTtlMsiscreateAgent’s run-level default for how long a pause for approval stays decidable (milliseconds); apermissionsaskrule may setttlMs, bounding that rule’s pauses and winning overapprovalTtlMs(both positive finite numbers, rejected otherwise).storedeclares a durable store so paused approvals survive restarts (“draft today, approve tomorrow”):{ "dir": "./.lousho" }(resolved against the agent directory, staying inside it) becomes afileStore()- sessions, checkpoints and approvals as JSON files, withhistoryLimit/tokenKeyalso declarable; a code config may set anAgentStoreinstance instead.storeis Node-only: the Cloudflare Worker target rejects it.loadAgentDir(dir, { approve: null })/{ hooks: null }strip the directory’s wiring (the file the config names is not even imported), whereundefinedkeeps it. The generated node-server / docker server keeps a config-declaredstoreunlessLOUSHO_STOREis set. See Agent directories. - Agent directories:
"engine": "pi"in asubagents/<name>/config makes that directory apiAgent()coding sub-agent instead of a nestedcreateAgent()one - it lands in the parent’ssubagentsmap (thetasktool) and its sessions run in the parent’s directory, the workspace both share. Itsmodelis the usualpi/<provider>/<model>id and itspermissionsgate the Pi session’s own tool calls; the remaining config keys are ignored (Pi carries its own prompt and tools).loadAgentDir()’s newpiAgentoverride injectsPiAgentOptionsinto every such sub-agent (a fauxmodelRuntimein tests, asessionDirfor durable approvals); the directory always winscwd,nameanddescription. Cloudflare Worker targets rejectengine- Pi needs the Node runtime. The default registry’s second kit,coding-pi, iscoding-kiton the full Pi stack: pi-provider lead, dir-declared pi coder, same safety rails (install--allow exec,fs-write,network,env). See Agent directories. - The
approvecallback may return'defer'to abstain: the call stays pending (listed byagent.approvals.list(), resolvable byagent.approvals.resolve()/streamResolve()/answer()) and the run surfaces the pause -send()resolves withfinishReason: 'awaiting-approval', as if the callback had never been asked - so an approver can decide the calls it trusts and hand the rest to a human. Note:'defer'is now reserved; an approval note that is exactly'defer'defers instead of approving. See Deciding in code. - Tool-call hook contexts carry
resumedAfterApproval:trueonly whenpreToolCall/postToolCallfire for the post-approval re-run of a call the run paused on (agent.approvals.resolve(),resumeAfterApproval()). Stateful hooks (loop guards, audit counters) can skip the re-fire withif (ctx.resumedAfterApproval) return;. See Hooks. - New
ToolDescriptor.transientmarks a tool bound per run (a memory slot’sremember_*/recall_*tools, bound to the run’s scope keys): it is left out of the agent fingerprint, so an approval-resumed run - whose registry intentionally does not rebind them - no longer reportstools removedagent drift on every resolve. - Approvals can expire.
createAgent({ approvalTtlMs })(validated: positive finite) sets a default deadline for every pause,send()/stream()take a per-call override, apermissionsaskrule may setttlMs(wins over the run default), andExecuteOptions.approvalTtlMscoversAgentExecutor.execute(); sub-agents inherit the lead’s TTL unless they set their own. A pending approval pastexpiresAtresolves as denied with'approval expired'- enforced at decision time, so a durable-store resume (a restart, another process) can never approve a stale pause - andlist()keeps expired entries (marked byexpiresAt) soresolve()still continues the run.approval.requestedevents andUIPendingApprovalcarryexpiresAtfor UI countdowns; expiry writes an auditeddenydecision toonPermissionDecision. See Approvals. llmCritique(config): likellmJudgebut returns{ score, feedback }- one judge call, aSCORE:/FEEDBACK:prompt, graceful degradation on malformed output - so evaluator-optimizer loops get actionable revision guidance, not just a number. See Evals.- Testing helpers:
testToolContext(overrides?)(@lousho/build-ai-agent/testing) builds a validToolExecutionContextfor directtool.execute()calls -getToken/requireAuthfail loudly unless stubbed - andtoolResultText(message)(root export) unwraps atoolmessage’s JSON-encoded content to its result text. - Channels:
ChannelInbound.metadatanow reaches the run asSendOptions.metadata(memory scopes andwhencontexts can key on channel-supplied data; it is unauthenticated, unlikeprincipal), andwebhookChannel({ principal: (body, req) =>... })can derive the caller principal from a verified body/header - so a webhook intake (PagerDuty, Grafana) attributes the run to the alerting system. See Channels. - New registry kits and examples replicating the most-built agent archetypes:
inbox-triage(channel intake → classify → draft → approval-gated send, per-sender memory,@hourlysweep; installlousho add inbox-triage --allow env,fs-write) andincident-response(webhook alert → diagnose → risk-tiered approvals → remediate → verify → audit timeline; install--allow env,fs-write); examplesdeep-research(orchestrator-workers fan-out with cited synthesis),support-desk(triage →handoff()to specialist agents),evaluator-loop(writer ↔llmCritiquerevision loop) anddata-analyst(text-to-SQL with read-only enforcement). Each runs offline on mock models and acceptsOPENROUTER_API_KEYfor a live pass. claudeProject(dir): loads a repository’s Claude-Code-conventional context into options that spread intocreateAgent()—CLAUDE.md/AGENTS.md+.claude/rules/*.mdbecomeinstructions,.claude/skills/*/SKILL.mdload throughloadSkills()unchanged,.claude/agents/*.mdfrontmatter becomessubagents(frontmattermodelselects the sub-agent’s model;provider/modeloptions are the fallback), and.claude/scratchpad/gets ascratchpadnote tool (name-validated*.mdwrites). Nothing in the directory executes: markdown is read as data, and.claude/commands,settings*.jsonandmcp.jsonare listed onmanifest.ignoredrather than loaded. See Claude Code projects.decide(): typed answers from the OpenAI Decisions API (POST /v1/decisions, public beta —gpt-6-lunaonly) —predicatequestions return a probability,choicereturns a value plus per-optionprobabilitiesandconfidence,scorereturns a rubric’s probability-weighted level index, and any question may come back arefusal. Input is a string or messages withinput_text/input_image(inline base64) parts;apiKey(defaultOPENAI_API_KEY),baseURL,timeoutMs,signalandfetchare overridable. It is the fast path for typed decisions (route/gate/score) — no agent turn and no generated prose — and does not go through providers or OpenRouter. See Decisions.- Four new examples covering the agentic-patterns catalog:
waves(Workers · Aggregate · Verify · Extend — bounded parallel workers, deterministic merge, a typed{ verdict, gaps }verifier, extension waves seeded by its gaps),phase-pipeline(discuss → spec → plan → implement → proof gate → report onFlowBuilder/FlowExecutor, with the implement↔check retry ladder as aoneOfchain),coding-agent-workflows(a coding agent routed by a typed decision —outputschema{ route, confidence, reason }, a confidence floor escalating low-confidence calls to the careful path), andconnectors(MCP connectors à la Claude — runs fully offline against a mockserveMcpstdio server exposingdocs_*/slack_*tools; README maps Google Docs, Slack, GitHub and Notion). Plushostinger-deploy: build an agent withlousho build --target=docker, ship it to a Hostinger VPS over SSH and smoke-test/health+ bearer auth + approval pause/resume. See Prompting and context techniques, Connectors and Hostinger VPS. lousho addhas a default registry: without--registryorLOUSHO_REGISTRYit readshttps://registry.lousho.com/index.json- theregistry/dist/folder of this repository served as static JSON - instead of failing with “no registry configured; there is no hosted registry yet”, solousho add --listworks out of the box. It carries five starter items: the toolsopen-meteo-weather(current weather by city through Open-Meteo, no API key) andgithub-issues(list and create issues throughapi.github.com; creating asks for approval), the skillschangelogandcode-review, and thegeneric-webhookchannel (HMAC-SHA256 signature verification fromWEBHOOK_SECRET).--registryandLOUSHO_REGISTRYstill override it, and the new valuenone(in either place) disables the registry entirely with the oldLOUSHO_CONFIG_INVALID“no registry configured” error, for offline or locked-down use. The items live inregistry/as anitem.jsonplus their files per folder;npm run registry:buildvalidates each against the registry schemas, the path rules and the M7a code/manifest check, and writes the committedregistry/dist/(npm run registry:checkfails when it is stale and runs in CI). See docs/registry.md.
Fixed
- A channel button click (Slack, Discord), inline-keyboard tap (Telegram), Adaptive Card press (Teams) or
/approvecommand (GitHub) after a restart is now bound to the conversation’s session before the approval is resolved, so its continuation is appended to the session transcript again. The decision names the conversation it came from (inbound); with checkpointed sessions (mountChannelsstorewithcheckpoints, e.g. aSqliteStore) it is accepted only when that session’s pending turn waits on exactly that approval id and kind - a decision for another conversation, a replay of a decided one and a decision of the wrong kind are refused (LOUSHO_APPROVAL_NOT_FOUND) before the approval is touched, andonDecisionaudits only decisions that pass, so a replayed click cannot run the tool twice and the thread’s next message continues the same session. Without a checkpoint store nothing can be checked, so the approval store alone decides, as before. - A channel’s function
approversworks after a restart:ctx.approval(id)asked only this process’sagent.approvals.list(), so a pause the restarted process did not make looked the same as a denial and the function failed closed.ApprovalStoregains an optionalload(id)-resolve()without removing the record; every shipped store implements it, and a custom store without it keeps compiling and behaves as before - and the newagent.approvals.get(id)reads through it.ctx.approvalfalls back to that, so the function sees the same request (toolName,input,sessionId,principal) it saw before the restart and fails closed only when no store knows the id (a process-local approval store still forgets its pauses at a restart). - A hand-written Cloudflare Worker can now bundle
createAgent. The package root also exports file stores, the agent-directory loader, MCP over stdio and sandboxes, so bundling it forplatform: 'browser'failed withCould not resolve "async_hooks"(andcrypto,fs/promises,http,net,stream) - only the generated Worker ever bundled, becauselousho build --target=cloudflare-workerredirects those imports to shims itself.@lousho/build-ai-agent/workeris a new subpath exportingcreateAgent(and its config types),memoryStore, the KV stores (KVStore,KVCheckpointStore,CHECKPOINT_KV_BINDING), the schedule helpers (defineSchedule,handleScheduled),serveFetch(the/chatAPI as a fetch handler), the providers a Worker can run and the whole Worker-safe subset agent-directory code may import. The SDK’s own build produces it through the same Node-builtin/sandbox/QuickJS shims the adapter applies (plus newollama-ai-providerand@modelcontextprotocol/sdkones, which an external specifier would leave unresolvable andmcpServerstherefore fails on first connect - uselousho buildfor MCP on Workers), so the published entry carries nonode:import for a user’s own bundler to fail on;ai,zod,@opentelemetry/apiand the@ai-sdk/*provider packages stay external specifiers resolved from the user’s install. Guarded bysrc/deploy/worker.test.ts; see docs/cloudflare-workers.md#writing-your-own-worker. - The published
.d.tsfiles no longer import the types of optional peers:SubprocessSandboxOptions.dockerOptionsis now the structuralDockerConnectionOptions(same fields as dockerode’sDockerOptions, passed through unchanged) andMcpClientLikeis the structural subset of the MCP SDK’sClientit already was (listTools/callTool). Before,dist/index.d.tsimporteddockerodeand the shared schema chunk imported@modelcontextprotocol/sdk, so a consumer compiling withskipLibCheck: falsewithout those optional peers installed got TS2307 inside the SDK’s own declarations. A dockerodeDockerOptionsor MCPClientvalue still satisfies both types.
[1.0.0-alpha.18] - 2026-10-08
See the 1.0.0-alpha.19 section, which covers everything from 1.0.0-alpha.15 through 1.0.0-alpha.19.[1.0.0-alpha.17] - 2026-10-07
See the 1.0.0-alpha.19 section, which covers everything from 1.0.0-alpha.15 through 1.0.0-alpha.19.[1.0.0-alpha.15] - 2026-10-06
See the 1.0.0-alpha.19 section, which covers everything from 1.0.0-alpha.15 through 1.0.0-alpha.19.[1.0.0-alpha.9] - 2026-10-04
Security
http_requestis no longer open to DNS rebinding. It resolved a host name once to check it against the private-address list and then letfetchresolve it again to connect, so a name that answered a public address to the check and127.0.0.1(or a cloud metadata or intranet address) to the connection reached the private address; the docs and a comment in the Worker runtime described the check as rebinding-safe. Now the one resolution is the check: the in-process path connects through an undiciAgentwhoseconnect.lookupchecks every address and hands the socket the address it checked (each redirect hop included), and the sandboxed path (sandboxExecute, which agents use) resolves and checks the host in the agent’s process and has the sandboxed process connect to that address (node:http/https with a fixed lookup; the host name still goes inHostand TLS SNI). The private-address list is now the shared one (below), which adds0.0.0.0/8,100.64.0.0/10,192.0.0.0/24,198.18.0.0/15, multicast and reserved224.0.0.0/3,::,ff00::/8, NAT6464:ff9b::/96and 6to42002::/16to whathttp_requestrefused. Behavior changes: a host name that cannot be resolved now fails with the resolver’s error instead of being passed tofetch;undiciis loaded on the firsthttp_requestrequest (not only withvalidateSSL: false). New optioncreateHttpTool({ allowPrivate })for hosts that may resolve to private addresses. Cloudflare Workers have no DNS hook, so neither tool exists in the Worker build; docs/deployment.md now says what a Worker can and cannot check.- A run’s principal is fixed for the whole run: an approval resolved by another caller, a restart,
agent.resume()or a session’s pending turn continue as the caller that started the run, and the decider is recorded as the approver (ctx.approval.by), never swapped in as the run’s principal, so a later caller cannot use an earlier caller’s grant by approving their pending call. The principal comes only from route auth or a channel’s verified sender; the approvals route and channels never read it from a body field. It is frozen before a tool, a policy or a hook sees it. Remote sub-agents are not told who the caller is.
Changed
- Behaviour and types: a tool whose
executereturns an async iterator that is also async iterable (what anasync function*returns) is now iterated: its last yielded value is the result, instead of the iterator object itself (which used to reach the model as{}).AgentEventgainstool.partial(ToolPartialEvent),isToolEvent()narrows to it too,UIToolCallgainspartial?, thetool-output-availableUI chunk type gainspreliminary?: true, andDefinedToolgains a third, defaulted type parameter (whatexecuteresolves to). Migration: aswitchoverevent.typemeant to be exhaustive needs a'tool.partial'case; code using the result ofisToolEvent()as start/done/error only should checkevent.type; a tool that means to return an async generator as a value should wrap it ({ items: generator }) - a value that is only async iterable, such as aReadableStream, is still returned as it is. - Types only:
AgentEventgains thehandoffevent (HandoffEvent) andExecutionResultthe optionalagentName(set on every result the executor returns: the agent of the final reply). Migration: aswitchoverevent.typemeant to be exhaustive needs ahandoffcase; a test comparing a wholeExecutionResultwithtoEqual()now seesagentName. Nothing changes at runtime for an agent withouthandoffs. - BREAKING (types only):
McpServerStatusgains'needs-auth', andAgentOAuth(the type ofagent.oauth) gainsmcpSignInUrl(server). Migration: an exhaustiveswitchoverconnectMcp(...).status()values needs a'needs-auth'case (only servers withoauthever report it); an object written by hand to satisfyAgentOAuth(a test double, say) needs anmcpSignInUrlmethod. Runtime behaviour withoutoauthis unchanged. - BREAKING (types only):
ToolExecutionContextgains the methodsgetToken(provider)andrequireAuth(provider), andApprovalKindgains'sign-in'. Migration: code that builds a tool’s execute context by hand (for example to calltool.execute(args, { toolCallId, messages })in a unit test) must add the two methods or cast (as ToolExecutionContext); aswitchoverPendingApproval.kind/approval.requested’skindthat is meant to be exhaustive needs a'sign-in'case. Contexts the SDK builds have them already; nothing changes at runtime. - BREAKING:
send()andAgentExecutor.execute()with a listener (createAgent({ onEvent }),onAgentEvent, or the deprecatedonEventoption) now stream model calls: a step’s text arrives as severaltext.deltaevents, as instream(), instead of onetext.deltaper step after the step finished. What a listener receives otherwise does not change: the same event types in the same order, exactly onetext.doneper step with the step’s whole text, the samestep.doneusage andrun.done, the sameExecutionResult(text, tool calls, usage, steps). A provider withoutstream(), or whosesupportsStreaming(model)isfalse, still gives onetext.deltaper step. Output guardrails onsend()still check only the final reply (astream()you iterate checks every step’s text, as before).send()without a listener still callsprovider.generate(). Hooks’ctx.emitis set whenever the run has listeners (it was already; the docs said “only when streamed”). Migration: concatenatetext.delta, or listen totext.donefor whole steps;execute({ streamModelCalls: false })(new option, defaulttrue) restores whole steps. MockLLMProvider/createMockProvider():stream()now streams the same stepgenerate()returns: the same tool calls (it streamed none, so a streamed mock run never called a tool), finish reason and usage, and text chunks that add up to exactly the generated text (the old chunks ended with an extra space:'This is a mock response. '). Runs on the mock provider with a listener (Agent Forge’s, for one) therefore give the same results as before, andstream()runs on it now call tools assend()does.- Agent Forge: runs now stream their model calls, so the run WebSocket (
WS /agents/:id/stream) carries severaltext.deltaevents per step; the chat, logs and trace views are unchanged (they usetext.doneand the reconciled messages). Stop is checked between streamed chunks and after the last one, as it was after eachgenerate()call. - CI peer matrix: the
typecheck-ai7andtypecheck-zod4jobs are replaced by onepeersjob with five entries, each installed for real on top of the default install and run throughtsc,test:types, both builds andnpx vitest run:ai4-zod4,ai6-zod3,ai6-zod4,ai7-zod3,ai7-zod4. The two zod 4 entries onai6/7 also installollama-ai-provider-v2(3.x / 4.x), and the newsrc/providers/ollamaV2.contract.test.tsrunsOllamaProvideragainst the real package and a local fake Ollama server (generate(),stream(), a tool-call turn throughcreateAgent().send()and.stream()). Theai-v6dev alias replaces the hand-madeai6 stand-in inaiMajorPeers.test.ts. lousho init --provider ollamanow scaffoldsai@^7.0.0withollama-ai-provider-v2@^4.0.0andzod@^4.0.0(it wasai@^4.3.19withollama-ai-provider@^1.2.0and zod 3). Existing projects are not touched; to stay on the old pairing keepai@^4.3.19andollama-ai-provider@^1.2.0.- A run paused inside a sub-agent compares the sub-agent with its current definition on resume, under the lead’s
onAgentDrift. Behaviour change: withonAgentDrift: 'error',agent.approvals.resolve()(andresumeAfterApproval()) now also rejects withLOUSHO_AGENT_DRIFTwhen a paused sub-agent’s instructions, model or tools changed; before, only tool and provider default-model changes of a sub-agent were seen, and always as a warning. This holds at any depth (a sub-agent of a sub-agent uses the lead’s mode). With'warn'(still the default) theagent.driftevent carriessubagent. A rejected resume puts the lead’s approval record and its'awaiting-approval'checkpoint back, so fixing the sub-agent and resolving again finishes the run; before, a sub-agent’s missing-tool error became an error result of thetaskcall and the run continued. Migration: none for'warn'/'ignore'; with'error', resolve approvals paused before a sub-agent changed with the old definition, or use'warn'. See docs/durable-execution.md#resuming-with-a-changed-agent. lousho addenforces the permission manifest at install. Behaviour change: an item whose code does not match its manifest is now refused with the new codeLOUSHO_REGISTRY_MANIFEST_MISMATCH, and nothing is written. Before writing, every JavaScript / TypeScript file of the item is scanned (comments stripped) forchild_process/execa/shelljs/createShellTool/SubprocessSandbox(needsexec: true),fsimports andcreateFsTools(needsfilesystem: "read"), file-writing calls (needs"write"),fetch(and network modules (needs a non-emptynetwork),http(s)://hosts in strings (each must match anetworkentry) andprocess.env.NAMEreads (each must be inenv);eval(,new Function(, a computedprocess.env[...]and a non-literalimport()/require()are always refused. Each finding is listed as<file>:<line>: <what> (<fix>).networkentries must now be host patterns andenventries variable names (LOUSHO_REGISTRY_INVALIDotherwise). With--yes, an item asking forexec: true,filesystem: "write", anetworkor anenvis refused unless each is named in the new--allow exec,fs-write,network,envflag; the interactive prompt lists them, and the printed manifest marks them[elevated:...]. After writing,lousho addrecords the item (type, registry, time, permissions, each file’s sha256) in<agent-dir>/lousho-registry.json. Migration: registry authors declare what their code uses; scripts that runlousho add --yesadd--allowwith the permissions they accept. It is a static check, not a sandbox; see docs/registry.md#permission-manifest. The example item in docs/registry.md now usesinput(notinputSchema).- Behaviour change: continuing an unfinished checkpointed run (
send(message, { sessionId, principal }),AgentExecutor.execute({ sessionId, checkpointStore, principal })) with a principal other than the one it was saved with now throwsLOUSHO_CONFIG_INVALIDinstead of running the new input; without a principal (agent.resume(), a session’s pending turn) the run continues as the saved caller. Migration: resume such a run withoutprincipal, or start a new session.onPermissionDecisionis called with a second argument,{ principal }(callbacks that take one argument are unaffected). Checkpoints, approval snapshots and pending approvals now store the run’s principal (claims included): treat those stores as personal data. Checkpoints and snapshots written before this release resume with no principal; no migration.
Added
lousho devandlousho chattake--traces(or--traces=<dir>) to write local traces withfileTraceExporter():.lousho/tracesby default, the directorylousho tracesreads, for spec files, agent directories and modules (specToAgent()now also accepts anexporteroption). It is opt-in because trace files hold prompt and tool content even withcaptureContent: false(onlyredactContent: trueremoves it); the command prints where it writes.lousho initprojects already ignore.lousho/.- Code mode:
createAgent({ codeMode: true | CodeModeOptions })adds arun_codetool. The model writes the body of an async JavaScript function that calls the agent’s tools asawait tools.<name>(args), loops and combines their results, and returns one JSON value;run_codereturns{ result, logs, toolCalls }and only that enters the transcript. Scripts run in a QuickJS WebAssembly isolate from the new optional peerquickjs-emscripten(^0.32.0, listed bylousho doctor; without it the first run of acodeModeagent fails withMissingPeerDependencyError): a fresh runtime per script, norequire,import,process,fetch, timers or host objects, values passed as JSON copies, and the limitstimeoutMs(30,000, whole script including awaited tool calls),memoryLimitBytes(64 MiB),maxToolCalls(50) andmaxOutputChars(20,000, return value plus logs).toolspicks the callable tools (default: all butrun_code,ask_question, sub-agent tools,tool_search,load_skilland deferred tools);exclusive: truetakes them off the model’s tool list. Every inner call (id<run_code id>:<n>) goes through the same gate as a direct call: validation, hooks, permission rules and modes (plan mode refuses non-read-only inner calls;run_codeitself is read-only), tool guardrails (a block stops the run),needsApproval, sandbox routing and the principal. A call that would pause the run (approval, sign-in, a sub-agent’s approval) throws inside the script instead and the run does not pause;run_codeitself can be paused for approval by a rule and runs after the decision. A failed script’s error lists its first five tool calls with their (clipped) results. New export: typeCodeModeOptions. Types:parentToolCallId?on thetool.start,tool.partial,tool.doneandtool.errorevents (set on inner calls; theirtool.done/tool.errorcomes beforerun_code’s); inner calls getexecute_toolspans under therun_codespan with the attributelousho.tool.parent_call_id. No migration needed: nothing changes withoutcodeMode. See docs/code-mode.md. - Streaming partial tool results: a tool’s
executemay be anasync function*. Everyyieldis a complete snapshot of its output, streamed as the newtool.partialevent ({ toolCallId, toolName, output, index },indexfrom 0) between the call’stool.startandtool.done; the last yield is the result the model gets (andtool.done’sresult), areturnvalue is ignored and a generator that yields nothing has the resultundefined. Snapshots are not sent to the model, not added to the transcript, not checkpointed and not recorded in trace spans; hooks see only the result; tokens fromctx.getToken()are redacted in snapshots like in the result. The main loop, a streamed resume after an approval (agent.approvals.streamResolve()) and a flow’s tool-call node iterate the generator; aborting the run stops reading it and calls itsreturn();toolConcurrencycounts the whole generator run. A call that pauses for a sign-in mid-stream runs again from the start (index from 0); partial output is lost on a crash.defineTooltypes it:ToolOutput<typeof tool>is the yielded type (new helper typeToolResultOf<R>). The UI reducer (useLoushoAgent()and the Vue / Svelte bindings) keeps the latest snapshot astoolCalls[i].partial, andtoUIMessageStream()sends snapshots as the AI SDK’s preliminary tool output (tool-output-availablewithpreliminary: true). See docs/tools.md#streaming-partial-results. - Tool search: tools marked
deferLoading(defineTool({ deferLoading: true }), or every tool of an MCP server withmcpServers.<name>.deferLoading: true, also in spec files and agent directories) are withheld from the model, which finds them with a built-intool_searchtool ({ query }->{ loaded: [{ name, description }], more }); the tools it finds are sent from the next step on, andtool_searchstops being offered once everything is loaded. New optiontoolSearchoncreateAgent()andAgentExecutor.execute():{ thresholdPercent? (default 0.1 of the context window; 0 always defers), maxResults? (5), contextWindow?, search? }, orfalseto send every tool upfront. Below the threshold nothing is deferred and notool_searchexists. Which tools are loaded is read from the transcript at each model call, so loading survives crash resume, approvals, forks and session turns; compaction that prunes atool_searchresult unloads its tools; a handoff target or a sub-agent never inherits the lead’s loaded tools. Skills, memory,task,ask_questionand handoff tools are never deferred. New exports:ToolSearchOptions,ToolSearchResult,rankToolsByKeywords(). Types:ToolDescriptor.deferLoading,DefineToolOptions.deferLoading,McpStdioServerSpec/McpHttpServerSpec.deferLoading,LoadMcpToolsOptions.deferLoading,SubagentSpec.toolSearch,ToolMetadata.mcp.server. Behaviour change: tools loaded byloadMcpTools()/connectMcp()now carry their server name inmetadata.mcp.server; a test comparing an MCP tool’s wholemetadatawithtoEqual()needs that key. A user tool namedtool_searchis refused (LOUSHO_CONFIG_INVALID) only when deferral is active. See docs/tool-search.md. - Handoffs:
createAgent({ handoffs: [billing, handoff(refunds, options)] })lets an agent hand the whole conversation to anothercreateAgent()agent (with anameand adescription), offered to the model as onetransfer_to_<name>tool each. The handoff call is not run as a tool: once the other calls of its step are done, the run goes on in the samesend()/stream()as the target, with its instructions (replacing the system prompt), model, tools, skills, sub-agents, reasoning and own handoffs, the lead’s guardrails and permission rules before its own, on the transcript the handoff’sinputFilterreturns (handoffFilters.removeToolCalls,handoffFilters.lastUserMessage, or your own). Hooks,limitsand spend,maxSteps(counted across agents), the signal, the approval, checkpoint and token stores, listeners,output, the permission mode and the principal stay the run’s.handoff()options:toolName,description,input(validated; bad arguments get a tool error and no handoff),inputFilter,onHandoff,isEnabled(aPerRun<boolean>). Only the first handoff call of a turn is honored;maxHandoffs(default 5) caps one run. The transcript marks each handoff withmetadata.handoff = { from, to }; a session’s next turn,agent.resume(),session.resume()andagent.approvals.resolve()continue as the agent it last handed off to (agent.send()without a session starts at the lead), and the resume drift check compares with that agent. Approvals remembered withonce()are dropped at a handoff. Atransfer_to_*call passes the run’s gate like a tool call:permissionsrules apply to it (denygives the model akind: 'denied'tool error and no handoff happens;askpauses the run for approval and the decided call then hands off or reports the rejection), pre/post tool hooks may deny it or rewrite its arguments, and its decision is audited toonPermissionDecision/permission.decision. Each handoff appends a routing system note (metadata.handoff) carrying the validated call arguments to the transcript the target reads;handoffFilters.removeToolCallskeeps it and a custominputFiltermay drop or replace it.createAgent()warns once when a reachable handoff target was created with run-level options (approve,approvalStore,permissionMode,approvalTtlMs,store) - a run keeps the entry agent’s. Newhandoffevent (from,to,toolCallId) andExecutionResult.agentName;ExecuteOptions.handoffs/maxHandoffsfor the executor API. Remote agents cannot be handoff targets. See docs/handoffs.md. - OAuth for HTTP MCP servers, per the MCP authorization spec: an
mcpServersHTTP entry takesoauth: { redirectUri, clientId?, clientSecret?, scopes?, clientName? }(new typeMcpOAuthOptions; refused on stdio entries by the spec schema). The MCP SDK’s client does discovery (RFC 9728 protected resource metadata, RFC 8414 authorization server metadata), dynamic client registration (RFC 7591) when noclientIdis given, PKCE and resource indicators (RFC 8707), and refreshes an expired token; tokens are kept in the agent’s encrypted token store as providermcp-<server>, owned by the app. An operator signs the agent in once with the newagent.oauth.mcpSignInUrl(server); N9b’sagent.oauth.complete()andGET /oauth/callbackfinish it. Without a usable token the server’s status is the new'needs-auth'and connecting fails with the new error codeLOUSHO_MCP_AUTH_REQUIRED(a tool call refused mid-run is a tool error with that code; nothing pauses).connectMcp(servers, { tokens })takes the token store. Security:oauthneeds an httpsurl(http only for localhost, 127.0.0.1 and [::1]); anAuthorizationheader together withoauthis refused; withoauth,headersgo only to the MCP server’s origin, never to the authorization server; a stored grant is only used for theurlit was obtained for (a changedurlneeds a new sign-in); no token, code, verifier or client secret appears in errors, logs,status(), events or results. Out of scope for now: per-user MCP grants, alousho mcp logincommand, OAuth over stdio. See docs/oauth.md, “MCP servers with OAuth”. - Parallel input guardrails:
IoGuardrail.runInParallel(defaultfalse) makes aninputguardrail run while the first model call is already in flight, so a slow, model-backed check no longer delays the answer by its whole latency;promptInjectionGuardrail({ runInParallel })andmoderationGuardrail({ runInParallel })take it as an option. The blocking input guardrails run first as before (rewrites included), then the parallel ones start together on that input. Until all have passed, the call’stext.delta,reasoning.*and provider-run tool events are held in order (on the iterator andonAgentEventalike), its tool calls do not run, andonLLMResponse, post-generate hooks, output guardrails,text.doneand the checkpoint after the response wait. A trip aborts the call (its signal only, not the run’s), drops the held events and ends the run withfinishReason: 'guardrail',result.guardrailandguardrail.tripped(orGuardrailErrorunderonTripped: 'throw'), with nothing of the call in the transcript or a checkpoint; the call’s usage counts inresult.usageonly when the provider reported it. A parallel check cannot rewrite (action: 'rewrite'blocks, the reason prefixedrunInParallel guardrails cannot rewrite:), and a check that throws fails the run. Ignored onoutputandtoolsguardrails. No change for guardrails without the flag. See docs/guardrails.md#input-and-output-guardrails. - OAuth sign-in for tools:
defineOAuthProvider({ name, displayName?, credentialOwner?, authorizationUrl, tokenUrl, clientId, clientSecret?, clientAuth?, scopes?, redirectUri, authorizationParams?, fetch? }), and in a toolctx.getToken(provider)andctx.requireAuth(provider). Without a usable token the run pauses durably like an approval (finishReason: 'awaiting-approval',kind: 'sign-in',signIn: { provider, displayName?, url }on the pending approval and theapproval.requestedevent); the authorization URL uses PKCE S256 and a single-use 256-bitstatethat expires after 10 minutes, and the verifier is kept only in the encrypted pending record. The new routeGET /oauth/callback(lousho dev, the node server, the Worker) andGET <basePath>/oauth/callback(createRouteHandler) is not behind route auth (a browser redirect carries no API token): it calls the newagent.oauth.complete({ state, code?, error? }), which stores the token for the paused run’s principal and answers a small HTML page (400 for an unknown, used or expired state). Approving the pause (agent.approvals.resolve({ id, approved: true }), or the approvals route) runs the tool call again; before the callback it throwsLOUSHO_SIGNIN_PENDING(HTTP 409) and the run stays paused. Tokens within 60 s of expiry are refreshed;requireAuth()deletes a refused token and pauses. A user credential needs a principal (LOUSHO_OAUTH_PRINCIPAL_REQUIRED); an app credential (credentialOwner: 'app') is never asked of a chat user (LOUSHO_OAUTH_APP_SIGNIN_REQUIRED) and is connected by the operator withagent.oauth.signInUrl(provider). Theapprovecallback is never asked about a sign-in. Slack sends the link withchat.postEphemeraland Discord as an ephemeral follow-up, both without buttons; GitHub never posts it in a public thread; behindcreateDeployedServer()andlousho devthe callback continues the paused channel turn. The UI state (pendingApproval.signIn), thedata-lousho-approvalpart,lousho dev’s page,lousho chatandlousho acpshow the link. A tool result that contains a token handed out during that call is redacted to[REDACTED]with a warning. New error codesLOUSHO_OAUTH_PRINCIPAL_REQUIRED,LOUSHO_OAUTH_APP_SIGNIN_REQUIRED,LOUSHO_OAUTH_STORE_MISSING,LOUSHO_OAUTH_STATE_INVALID,LOUSHO_SIGNIN_PENDING,LOUSHO_OAUTH_TOKEN_EXCHANGE_FAILED. See OAuth. - Hosted tools on Anthropic and OpenRouter:
webSearch()andcodeInterpreter()now also run on the Anthropic provider (ai6 with@ai-sdk/anthropic3,ai7 with@ai-sdk/anthropic4):webSearch()is the newesttools.webSearch_*()the installed package exports (optionsmaxUses,allowedDomains,blockedDomains,userLocation),codeInterpreter()the newesttools.codeExecution_*(); events andusage.hostedToolCallskeep the neutral namecode_interpreter.fileSearch()on Anthropic, andcodeInterpreter()/fileSearch()on OpenRouter, areLOUSHO_HOSTED_TOOL_UNSUPPORTED.webSearch()works with everyopenrouter/...model on anyaimajor: the provider adds OpenRouter’sopenrouter:web_searchserver tool to the request body (after the function tools, composing with thereasoningfield;maxUses,allowedDomains,blockedDomainsandsearchContextSizemap to its parameters) and reports one hosted call per step that searched, read from the response: the cited urls fromurl_citationannotations assources, andresult: { requests }when OpenRouter reportsusage.server_tool_use.web_search_requests. OpenRouter bills each search on top of tokens (not incostUsd).supportsHostedTool()on both providers reflects this. The per-provider table in docs/hosted-tools.md is complete, and a replayable cassette from a live OpenRouter search is in the test suite (npm run test:livere-records it withOPENROUTER_API_KEY). - Hosted provider tools:
webSearch(),codeInterpreter(),fileSearch()andhostedTool(name, aiSdkTool)go increateAgent({ tools })next to local tools (array or record form; in the record form the key must be the tool’s name), and the provider runs them inside the model request. OpenAI maps them toopenai.tools.webSearch()/.codeInterpreter()/.fileSearch()onai6 with@ai-sdk/openai3 andai7 with@ai-sdk/openai4 (options it does not take, such asmaxUses, are dropped with one warning);hostedTool()passes any AI SDK provider tool through onai6 or 7, including onfromAiSdk()models. Provider-executed calls are never handed to the executor as local tool calls (onai6/7 they used to come back as calls of an unknown tool): they are reported astool.start/tool.done/tool.errorwith the new optional fieldexecutedBy: 'provider'(as they stream in, or after a non-streamed call in call order; results capped at 20,000 characters of JSON), kept on the step’s assistant message asmetadata.hostedToolCalls(with url sources; not sent back to the model), counted inusage.hostedToolCallsandrun.doneusage per tool name (fees not incostUsd), and named on thechatspan aslousho.hosted_tool_calls. A step whose only calls the provider ran ends the run even when the provider reportstool-calls. No permission rule, guardrail, approval or hook runs for them; instead, in permission mode'plan'only the read-onlywebSearch()andfileSearch()are sent to the provider (codeInterpreter()andhostedTool()are left out of the request, read before every model call), and every other mode sends them all. New:ExecuteOptions.hostedTools,GenerateOptions.hostedTools,GenerateResult.hostedToolCalls,HostedToolCall, stream chunkshosted-tool-call/hosted-tool-result, optionalLLMProvider.supportsHostedTool(type),mockModelturns withhostedToolCalls, cassettes that keep hosted calls, error codeLOUSHO_HOSTED_TOOL_UNSUPPORTED(ai 4, Ollama, a provider withoutsupportsHostedTool(), or an@ai-sdk/openaiwithout the tool). Sub-agents do not inherit the lead’s hosted tools; the agent fingerprint includes them. Anthropic and OpenRouter mappings follow in N1b (below). See docs/hosted-tools.md. session.history()andsession.fork({ fromStep, id?, patch? })onagent.session()sessions.history()lists the steps of the committed transcript (one per model response:stepnumbered from 1 across the session,turn,messageIndex,text, andtoolCallswithargsandresult).fork()saves the transcript up to and including a step (0keeps nothing), optionally with one tool result replaced (patch.toolResult), under a new id in the same store (default<id>-fork-<n>) and returns a session of the same agent and options (with the permission mode the session has at that moment); the original is not changed. The spend recorded forlimitsup to that point carries over. A turn waiting on an approval or a question, or an interrupted checkpointed turn, stays with the source session, so it is resolved once; workspace files are not rewound. Works on every shipped store (memory,fileStore(),SqliteStore,KVStore), with one contract suite run against each. New typesSessionHistoryStep,SessionForkOptionsandSessionSpawner; new error codesLOUSHO_SESSION_STEP_NOT_FOUND,LOUSHO_SESSION_EXISTSandLOUSHO_SESSION_FORK_UNSUPPORTED;AgentSession’s constructor takes an optional fourth argument, the function that creates its forks. See Forking a session.- Permission modes:
createAgent({ permissionMode }),send()/stream(){ permissionMode },agent.session({ permissionMode })andsession.setPermissionMode()put an agent in'plan'(only read-only tools run; everything else is refused withkind: 'denied', also when anallowrule matched, and a run that starts in plan mode gets one system-prompt paragraph saying so),'acceptEdits'(file edits that would ask run without asking) or'dontAsk'(a call that would ask is refused; nothing pauses). The modes are presets applied after hooks, permission rules, tool guardrails andneedsApproval, so no mode turns a deny into a run. A function mode, and a session’s mode, are read at every tool call, so a switch applies from the next call, also mid-turn and in a paused turn continued byagent.approvals.resolve(). Sub-agents run under the lead’s mode unless it is'default'; a remote sub-agent is refused in plan mode. Audit: under a mode other than'default'every call is audited,PermissionDecisionEntry.modesays when the mode changed the outcome, and the newonPermissionModeChangerecords each switch. New:PermissionModeandPermissionModeChangetypes,defineTool({ editsFiles })(metadata.editsFiles, set onwrite_fileandedit_file),readOnlyHint: trueonload_skill,recall_<name>,agent_statusandagent_await. The mode is not saved in checkpoints. Example:examples/plan-mode. See Permission modes. - Semantic recall: a memory slot can recall by meaning. New
EmbeddingProvider({ id, embed(texts) }) andaiSdkEmbedder(model, { id?, maxBatch? }), which wraps any AI SDK embedding model throughembedManyfrom the installedai(4, 6 or 7;aiis loaded on first use, no new dependency), and two providers that rank by cosine similarity:inMemoryVectorMemory({ embedder, maxItems?, minScore? })from the root andsqliteVectorMemory(store, options)from@lousho/build-ai-agent/sqlite(a newmemory_vectorstable, added to an existing database file on open;memory_itemsandsqliteMemory()are unchanged). With a query,list()returns the scope key’s items by score (floorminScore, default 0.2; score inmetadata.score); without one it lists the newest first. Items embedded by another embedder id are skipped when ranking untilprovider.reindex(scopeKey?)re-embeds them. AMemoryProvidermay setranking: 'relevance', which makes therecall_<name>tool say “by meaning, most relevant first”.hashEmbedder({ dimensions? })from@lousho/build-ai-agent/testingis a deterministic offline embedder for tests.describeMemoryProviderContracttakes{ query: 'filter' | 'rank' }. docs/memory.md has a new## Semantic recallsection at the end. teamsChannel({ appId, appPassword, tenantId?, name?, fetch?, approvers?, onError? }): an agent behind an Azure Bot in Microsoft Teams, mounted like the other channels (POST <basePath>/teams). The inbound Bot Framework token is verified with the auth module (oidc(): RS256, the key set of the fixed Bot Framework OpenID metadata, issuerhttps://api.botframework.com, audienceappId, 5-minute tolerance) before the body is parsed, and itsserviceurlclaim must equal the activity’sserviceUrl; replies go only to that service URL (https). Personal chats always reach the agent, group chats and channels only on an@mention(stripped from the text); one session per conversation; Markdown replies split at 25,000 characters; tool approvals are Adaptive Cards with Approve and Deny buttons (approversas on the other channels; the card updates to “Approved by…” and names its conversation, so a copied or replayed reference decides nothing);ask_questionis answered by the next message, also after a restart with durable stores. Nonode:*import. Telegram and GitHub now set the sender as the run’sprincipaltoo (authenticator: 'telegram'with the user id,'github'with the login), as Slack and Discord do. See docs/channels.md#microsoft-teams.- Cloudflare Worker target builds agent directories (config, instructions, TypeScript tools, skills):
npx lousho build./my-agent --target=cloudflare-worker. The build reads the directory on Node and generatesagent.module.ts(static imports oftools/*and of anagent.tsconfig;instructions.md, a JSON/YAML config and the skills embedded as JSON), and the Worker builds the agent with the rules ofresolveAgentDir()(the config check and the tool-export rules now live in Node-free modules both use). The config’smodelmust name a Worker provider, oragent.tssets aproviderinstance.subagents/,schedules/,channels/,memory/,projectInstructionsand an unsupported provider are rejected withLOUSHO_DEPLOY_FAILED, naming what to remove. In a Worker build, an agent file’s@lousho/build-ai-agentimport resolves to a Worker-safe subset (defineTool,defineSkill, the Worker providers,fromAiSdk, errors,…); another name fails the build with the list. The leak check now names the file that imported a Node builtin ("node:fs" imported by my-agent/tools/files.ts) instead of failing with esbuild’s “Could not resolve”. Tools run in the Worker’s isolate with its rights: see docs/cloudflare-workers.md#build-and-deploy. - Workspace rewind:
createFsTools(fs, { checkpoints })with a newWorkspaceCheckpointsbacks up every filewrite_fileandedit_filechange (content and, where the provider has the new optionalFsProvider.getMode/chmod, permission bits), grouped by session and turn.checkpoints.list({ sessionId })shows the changed paths per turn;checkpoints.rewind(toTurn, { sessionId, dryRun, force })restores every file changed in that turn or later, deletes files the agent created, and skips files changed since by something else ('changed-since'), files overmaxFileBytes('too-large') and paths that are no longer files. Every path is checked before anything is written, and restores go through the provider, soNodeWorkspacekeeps them inside its root. Retention: the newestmaxTurnsturns per session (default 20), the old content only for a turn’s first write of a path, rewound turns dropped,clear({ sessionId }). Stores:MemoryWorkspaceCheckpointStore(default) andFileWorkspaceCheckpointStore(dir)(one JSON file per session, atomic writes).NodeWorkspacegainsgetMode()andchmod(). Withoutcheckpointsthe tools behave as before. See Workspace tools. - Route auth and principals: a new subpath,
@lousho/build-ai-agent/auth, withjwt(),oidc(),basic(),apiToken(),anonymous()androuteAuth(). A route takes an ordered list of entries: the first one that returns aPrincipalaccepts the request,nullskips to the next,AuthError(401 | 403)stops; when every entry skips the answer is a generic401with oneWWW-Authenticateheader per challenge (Bearer,Basic realm="..."), and the body never says which check failed. JWTs are verified with Web Crypto only (no new dependency, nonode:import, so the helpers run on Workers and edge routes):alg: none, algorithms outside the configured list, acritheader and algorithm confusion (an HS token checked against a public key) are refused;expis required,nbf/iathonored,iss/audchecked, with a clock tolerance of 60 s (at most 300); JWKS key sets are cached for 10 minutes and refetched at most once per 30 s, and a key-set URL is never taken from a token.oidc()uses the configured issuer’s discovery document and requires it to name the same issuer.basic()andapiToken()compare in constant time.createRouteHandler({ auth })andcreateDeployedServer(agent, { auth })take the list (a token string and a boolean function work as before); the node server appendsapiToken(LOUSHO_API_TOKEN)when that variable is set; an agent directory’sauth.tsis bundled bylousho build --target=node-server/dockerand guards the built server (resolveAgentDir()returns it asauth, the manifest hasauth: true). The accepted principal reaches the run:send()/stream()/ session turns takeprincipal, andRunConfigContext(themodel/instructions/toolsfunctions) andMemoryScopeContext(memory scopes) carry it; Slack and Discord channels set the sender as the principal.Principalis also exported from the root. Bad helper options throw the new error codeLOUSHO_AUTH_CONFIG_INVALIDwhen the helper is created.createRouteHandler()withoutauthlogs one warning whenNODE_ENVisproduction. Route auth does not check session ownership, the principal does not reach tools or approval policies yet, and the Cloudflare Worker target keeps theLOUSHO_API_TOKENtoken only. See Route auth and principals. - OAuth token storage:
AgentStoregains a fourth optional part,tokens(OAuthTokenStore:get/set/delete/listper provider and credential owner, single-use pending sign-ins withputPending/takePending, andgetClient/setClientfor dynamically registered clients). Owners are{ owner: 'app' }or{ owner: 'user', principalId, issuer? };tokenStoreKey(provider, owner)is the stable, percent-encoded record key (<provider>|app,<provider>|user|<issuer>|<principalId>).memoryStore()keeps tokens in process memory;fileStore(dir),SqliteStoreandKVStoreencrypt every record with AES-256-GCM (Web Crypto, a fresh 12-byte IV per write, the record key as additional authenticated data) under a 32-byte key the application supplies astokenKeyorLOUSHO_TOKEN_KEY; there is no default key. Several keys (newest first, or comma-separated in the variable) rotate: writes use the first, reads try each. New error codesLOUSHO_TOKEN_KEY_MISSING(first write, or a read of an existing record, without a key) andLOUSHO_TOKEN_DECRYPT_FAILED(wrong key or a changed record; names the provider, never the token).list()returns metadata only.generateTokenKey()makes a key. SQLite: schema migration 4 adds theoauth_tokensandoauth_pendingtables, andprune()also deletes expired pending sign-ins (its result gainsoauthPending). KV: keys under<prefix>oauth/, pending sign-ins written with anexpirationTtl;KVBindinggains an optionallist()(used only bytokens.list()), andKVListOptions/KVListResultare exported from/kv. The generated Cloudflare Worker passes itsLOUSHO_TOKEN_KEYsecret toKVStore. Nothing signs in yet; the sign-in flow follows. New page OAuth; new## OAuthsection at the end of docs/errors.md. githubChannel({ webhookSecret, botName, token?, app?, botLogin?, name?, apiUrl?, fetch?, triggers?, approvers?, onError? }): an agent that answers GitHub issue, pull-request and review comments.@<botName>in a comment starts a turn and the reply is a new comment in the same thread (a review thread gets a reply under it; text over 60,000 characters is split); one session per issue or pull request and one per review thread, and later comments in a thread with a session are follow-ups.X-Hub-Signature-256is verified over the raw body in constant time before the body is parsed (401 otherwise); the webhook is acknowledged at once. Comments by bots, by the channel’s own account and every comment the channel posts (a hidden marker) are ignored, and so are edits, deletions and other events. Replies are posted withtoken(a personal access token, or a function) or as a GitHub App (app: { appId, privateKey }: a PKCS#1 or PKCS#8 key signs an RS256 JWT with Web Crypto, exchanged for an installation token that is cached per installation until 5 minutes before it expires;src/channels/githubAppAuth.ts, not exported). Approvals are comments: the prompt asks for/approve <id>or/deny <id>(first line only, notes below it), and by default only a commenter whoseauthor_associationisOWNER,MEMBERorCOLLABORATORmay decide, read from the command comment itself;approvers(logins, or a function that sees the association inuser.roles) overrides it, andtriggers(logins, or a function) restricts who may start a turn or answer a question (default: everyone who can comment, so restrict it on a public repository). A comment is untrusted input to the agent; see the security note in docs/channels.md. Anask_questionis answered by the next comment in the thread and survives a restart given durable stores. Errors name the call and the HTTP status, never the token. TheLOUSHO_CHANNEL_INVALIDhint, docs/agent-directories.md and docs/errors.md now listgithubChannel(). New section## GitHubat the end of docs/channels.md.- Agent Forge keeps the traces of its runs: every run is written with
fileTraceExporter()to.lousho/agents/<agent id>/traces(the fileslousho tracesreads), and the Trace tab gets a list of the agent’s past runs (time, duration, model calls, tokens, cost, status) with a “Live” entry while a run is active; choosing one opens its spans in the waterfall, with span kind and error status. New server routesGET /agents/:id/traces?limit=NandGET /agents/:id/traces/:traceId; the server reads only inside the agent’s trace folder. The livespanWebSocket messages now carrykindandstatus(optional fields ofSpanEvent). See Agent Forge. - A background sub-agent that needs approval pauses the lead when the lead awaits it (
agent_await), and resumes withapprovals.resolve()/resume(). The lead’s result isawaiting-approvalwith the child’s call (subagentPath: ['<agent>']) inagent.approvals.list(); the decision runs or rejects the child’s call, the child finishes, and the continued lead gets its answer as theagent_awaitresult. A child that pauses again, or several awaited tasks that are all paused, pause the lead one approval at a time. The child’s usage is added to the lead’s, and its conversation is saved under itstaskId. The paused tasks are kept on the lead’s approval record (SubagentSuspension.background, plain JSON), never in the tool arguments the model sees. Withoutagent_awaitnothing changes: the task reportsawaiting-approvaland is not resumable. Thetaskandagent_statustool descriptions tell the model that a task awaiting approval continues only when it callsagent_awaiton it. Docs: docs/sub-agents.md (“When the lead run ends” and “Continuing a task”). - Guardrail starter set:
piiGuardrail()(email, phone, credit card with a Luhn check, IBAN with its mod-97 check, US SSN, IPv4; blocks, or rewrites each match to[<type>]),secretsGuardrail()(private keys; Anthropic, OpenRouter, OpenAI, AWS, GitHub, Slack, Google and Stripe live keys; JWTs;Authorization: Bearertokens;extraPatterns; rewrites to[secret]by default),promptInjectionGuardrail()(phrase, role-marker and Unicode-tag heuristics, plus an optional model check that must answerSAFEorINJECTION: <reason>) andmoderationGuardrail({ model })(one model call that answersNONEor the categories that apply:hate,harassment,self-harm,sexual,sexual-minors,violence,illicit). The PII, secret and injection checks are heuristic pattern checks: they catch common cases and miss others, and are not a security boundary. Model-backed checks fail closed on a reply they cannot read. A guardrail result can now carryinfo?: GuardrailTripInfo(pii,secret,prompt-injection,moderationorcustom), copied toresult.guardrail,guardrail.trippedandguardrail.rewrote; it holds types, labels and offsets, never the matched text. Agent spec files can name them inpolicy.guardrailsaspii,secrets,prompt-injectionandmoderation. New exported typesGuardrailTripInfo,PiiType,ModerationCategory. Docs: Guardrails, Configuration, Stream events. telegramChannel({ botToken, secretToken, botUsername?, name?, fetch?, approvers?, onError? }): an agent behind a Telegram bot, mounted like the Slack and Discord channels (POST &channels&telegram). The webhook secret token header (X-Telegram-Bot-Api-Secret-Token) is compared in constant time (401 otherwise); updates are acknowledged with200and the turn runs after. A private chat is one session per chat; in a group only&ask,&ask@<botUsername>, an@<botUsername>mention or a reply to the bot wakes it, and a forum topic is its own session. Replies are plain text, split at 4096 characters. Tool approvals are an inline keyboard (Approve & Deny) that onlyapprovers(default: the user who started the turn) can tap; the tap names its chat, so it works after a restart. Anask_questionis sent withforce_reply; a pending one survives a restart given durable stores, like Slack and Discord. The bot token is never put in an error message or log line.src&channels&channelSupport.tsgains the internalsecretsEqual()(constant-time compare with Web Crypto). TheLOUSHO_CHANNEL_INVALIDhint, docs&agent-directories.md and docs&errors.md now listdiscordChannel()andtelegramChannel(). New section## Telegramat the end of docs&channels.md (attachments are not read yet).&rtodo.updatedstream event anduseTodos()(React, Vue) /loushoTodos()(Svelte): every successfultodo_writeemitstodo.updated { todos, counts, toolCallId }right after itstool.done(sub-agents too, withsubagent). The shared UI reducer keeps the list in a newAgentUIState.todos(carried across turns, cleared byreset()),useLoushoAgent()/loushoAgent()expose it,useTodos(agent)/loushoTodos(agent)add counts, the current item and progress (todoView()computes the same view framework-free), andtoUIMessageStream()sends adata-lousho-todospart for the AI SDK UI. See Todos.- Cloudflare Worker target: the
openrouterprovider and thehttptool (with a requiredLOUSHO_HTTP_ALLOWhost allowlist).openrouterreads its key from theOPENROUTER_API_KEYbinding and is@ai-sdk/openaipointed at OpenRouter, so its bundle passes thenode:leak check likeopenai. The Worker’shttpishttp_requestwith the Node tool’s input, over the platformfetch(): since a Worker cannot see or pin where a host name resolves, it reaches only the host names (api.github.com) and*.wildcards (subdomains only) listed in the comma-separatedLOUSHO_HTTP_ALLOWbinding, refuses IP-address hosts even when listed and any scheme buthttp:/https:, checks every redirect hop the same way, and refuses every request when the binding is unset or empty. An invalid entry fails every request with an error naming it.wrangler.tomlgets a commented[vars]LOUSHO_HTTP_ALLOWline when the spec listshttp.ollamaandweb-fetchstay unsupported on Workers. Internally, the request, redirect and response logic ofhttp_requestmoved to the Node-freesrc/tools/built-in/httpCore.ts, shared by both tools; the Node tool’s behaviour is unchanged. See docs/cloudflare-workers.md#providers-and-tools. fromAiSdk(model): any AI SDKLanguageModel(Google, Bedrock, Azure, Mistral, Gateway,…) ascreateAgent({ provider }). Optionsname(default: the model’sproviderfield),fileMediaTypes,replaysReasoningandmaxRetries(default 0); exported withFromAiSdkOptionsfrom the package root. ThrowsLOUSHO_CONFIG_INVALIDfor a model id string, for a model built for anotheraimajor than the installed one, and for a call with another model id than the wrapped one. See docs/providers.md#any-ai-sdk-model-fromaisdk.- Two ready-made durable stores.
@lousho/build-ai-agent/kvis a new subpath exportingKVStore,KVCheckpointStore,CHECKPOINT_KV_BINDINGand the typesKVStoreOptions,KVBinding,KVPutOptions, so a hand-written Cloudflare Worker can usecreateAgent({ provider, store: new KVStore(env.AGENT_KV) }); nothing in its import graph touchesnode:*, so it bundles without shims (assertSessionIdmoved to the Node-freesrc/session/sessionId.tsand is still exported where it was).fileStore(dir, { historyLimit? })(root export) is anAgentStoreof plain JSON files:sessions/<id>.json,checkpoints/<id>.json,checkpoint-history/<id>.jsonandapprovals/<id>.json, each written to a temp file and renamed into place, with no lock files and noStorageService; resolving an approval claims it with an exclusive create, so of two processes resolving one approval only one gets it. It replaces combiningFileSessionStore,LocalStorageCheckpointStoreandStorageServiceApprovalStoreby hand. See docs/sessions.md#choosing-a-store and docs/deployment.md. web_fetchbuilt-in tool:webFetchTool/createWebFetchTool(options), andweb-fetchin spec files. ItGETs one public web page and returns{ url, finalUrl, status, contentType, content, truncated }: HTML converted to text by a small built-in converter (scripts and styles dropped, link URLs kept, entities decoded), JSON andtext/*as sent, a note for other types; a 4xx/5xx is returned with its body. Loopback, private and link-local destinations are refused on every hop with the connection pinned to the checked address; redirects (10), bytes read (2 MiB), characters returned (50 000) and time (30 s) are capped;allowedHosts/blockedHostsare checked before DNS andallowPrivateexempts named hosts. Node only. See docs/tools.md#built-in-tools.src/security/privateAddress.ts(internal):isPrivateAddress()andpinnedLookup(), shared by the credential broker,http_requestandweb_fetch. The credential broker uses it instead of its own list, so it also refuses192.0.0.0/24,198.18.0.0/15, NAT64 and 6to4 addresses.- Slack and Discord: a pending
ask_questionsurvives a restart. Given durable stores for sessions, checkpoints and approvals, the next message in the Slack thread (or the next/askin the Discord channel) after a restart is still the answer: the turn continues, the reply is posted, and the question, the answer and the reply are appended to the session transcript (before, the answer became a new turn and the question was orphaned). A message in a conversation that waits on a tool approval still does not decide it. NewChannelContext.pendingQuestion(sessionKey)for custom channels: the id of theask_questionthat key’s session waits on, also one asked before a restart (it binds the approval to the session, so the continuation is recorded); handed out once until that answer has run. A channel’s answer and click continuations now run one at a time with the session’s turns. Supporting additions:Checkpoint.approvalKind,PendingTurn.approvalKind(session.pending()) andSessionAwaitingApprovalError.approvalKindare'question'for a turn paused on anask_question. Slack thread replies that answer a pending question no longer need a saved transcript first (a first turn paused on a question with checkpoints has none yet). See docs/channels.md. - Local traces and
lousho traces:createAgent({ exporter, captureContent })traces every run of the agent (send(),stream(), session turns,agent.resume()and runs continued byagent.approvals.resolve(); sub-agents join the lead’s trace). The new subpath@lousho/build-ai-agent/tracesexportsfileTraceExporter({ dir }), which writes each run as JSON Lines to<dir>/<YYYY-MM-DD>/<traceId>.jsonl(default.lousho/traces; one finished span per line; a write error warns once and never fails the run), andlistTraces()/readTrace()to read them.npx lousho traces [--dir D] [--limit N] [--json]lists recent runs with duration, model and tool calls, tokens and cost;npx lousho traces <id|prefix> [--json] [--content]prints one run as a span tree with duration bars. Projects made bylousho initnow ignore.lousho/. See docs/observability.md#local-traces. openApiTools(document, options): an OpenAPI 3.0 / 3.1 document (object, JSON or YAML string, or https URL) becomes one typed tool per operation, exported from the root and./tools. Names come fromoperationId(or<method>_<path>); the input has path, query, header and cookie parameters plus anapplication/jsonbody, with$refs resolved; every HTTP response is returned as{ status, statusText, body }. GET, HEAD and OPTIONS run and other methods ask for approval by default (approval), with read-only / destructive annotations. Options:baseUrl,include,exclude,prefix,headers,bearerToken,providedArguments(removed from the model’s schema),timeoutMs,maxResponseChars,fetch. The base URL must be https (http only for loopback), credentials never reach events or the transcript, and redirects are followed only on the base origin. Swagger 2.0, multipart bodies and remote$refs are refused.jsonSchemaToZod(schema, root?)takes an optional root for$refresolution. New page docs/openapi-tools.md.- Built-in OpenAI, Anthropic and OpenRouter providers send PDF file parts on
ai6 and 7 (Anthropic alsotext/plain);ai4 and Ollama keep the text note. A provider subclass opts more media types in withfileMediaTypes()(acceptsFileParts = truestill sends every type). The text-note warning is now once per provider and media type and names the type and theaimajor. Addednpm run test:live(vitest.live.config.ts) for*.live.test.tsfiles, which the default suite excludes. See docs/providers.md#multimodal-input. - Principals in tools, approval policies and permissions: the run’s principal reaches a tool’s
execute(args, ctx)asctx.principal,needsApprovalfunctions (ApprovalCheckContext.principal), permission rules’when(args, ctx)(PermissionContext.principal),preToolCall/postToolCallhooks (ToolCallHookContext.principal),onPermissionDecision’s new second argument (PermissionAuditContext), pending approvals (PendingApproval.principal, seen byapproveand by a channel’sapproversfunction asrequest.principal) and in-process sub-agents (task, background tasks,createDelegateTool();remoteAgent()does not forward it). NewExecuteOptions.principal, set bycreateAgent()forsend(),stream(), session turns and channel turns. It is saved in checkpoints (Checkpoint.principal) and approval snapshots (ExecutionSnapshot.principal), so a static or dynamic run resumed after an approval or a crash acts for the same caller.agent.approvals.resolve()/answer()/streamResolve()/streamAnswer()take{ principal }(newResolveApprovalOptions) for who decides, and the approved tool sees it asctx.approval.by;resumeAfterApproval()takes it asexecuteOptions.approver. The approvals route (POST /chat/:sessionId/approvals/:id) passes the caller route auth accepted, andmountChannels()the clicking user ({ id, type: 'user', authenticator: <channel name> }) or, for a question answered by a message, its sender.agent.fork()keeps the source run’s principal;session.fork()copies only the conversation. The principal is not added to events, spans or trace files. See Principals in tools and approvals.
Deprecated
SlackTriggerAdapter,CronTriggerAdapterandWebhookTriggerAdapter(@lousho/build-ai-agent/triggers) are deprecated and will be removed in a future major version. UseslackChannel()for Slack (sessions per thread, approval buttons),defineSchedule()withstartSchedules()for cron (orschedules/in an agent directory, or cron triggers in a spec file), andwebhookChannel()for webhooks, each mounted withmountChannels().verifySlackSignature(), theWebhookAuthhelpers,parseCronExpression(),TriggerAdapterandTriggerRegistryare not deprecated. Their options types (SlackTriggerAdapterOptions,CronTriggerAdapterOptionswithCronIntervalOptionsandCronExpressionOptions,WebhookTriggerAdapterOptions) andWebhookTriggerHandlecarry@deprecatedtoo. Nothing changes at run time. See docs/triggers.md.
Fixed
loushoCLI surface:lousho dev/lousho chat --tracesnow writes traces for a.ts/.jsmodule that exports an already-builtcreateAgent()agent - the module’s export could not take the flag’s exporter after the fact, so nothing was written.createAgent()remembers the config it was built with (readable via the internalcreateAgentConfigOf()), and the loader rebuilds the agent with the flag’s exporter (the module’s ownexporteris replaced while the flag is set; a module exporting an agent not made bycreateAgent()prints a warning and keeps its own). A spec path that does not exist (e.g.lousho chat missing.yaml) now fails with the codedLOUSHO_SPEC_NOT_FOUNDinstead of a raw ENOENT.lousho add --dry-runno longer fails when a target file already exists; it prints the file list with an “(exists - a real install needs —overwrite)” marker and exits 0 (the symlink checks still run). Top-levellousho --helplists the implemented flags again:--no-schedules/--tracesondevandchat,eval’s record/replay/drift/--configflags,init’s--sdk-path, andbuild’s positional form.- A cassette failure keeps its type through
agent.send(): a replay mismatch (or a missing cassette raised by the provider-interception seam thatlousho evalinstalls) was compacted into a genericCompactedLLMProviderError, losing the cassette path, the call number and the re-record hint.CassetteMismatchErroris now anSDKErrorwith codeLOUSHO_CASSETTE_INVALID(docs/errors.md already claimed cassette errors carry it), and the run loop rethrows cassette errors untouched instead of compacting them, sosend()rejects with theCassetteMismatchErroritself (.cassette,.callNumber).setProviderInterceptor()and theProviderInterceptortype are now exported from@lousho/build-ai-agent/testing, the public entry for the model-boundary seam docs/evals.md describes. - A tool call approved with
agent.approvals.resolve()(orresumeAfterApproval()) now has itsexecute_toolspan. It ran before the continued run started, outside any span, so OpenTelemetry andfileTraceExporter()showed the continued run’sinvoke_agentandchatspans but not the approved tool. The continued run’sinvoke_agentspan now opens first and the approved call runs inside it: itsexecute_toolspan is a child of it (arun_codecall’s inner calls and a sub-agent the tool starts are children of the tool span), with the samecaptureContent/redactContentrules as any tool span, and no span is made for a rejected call. A pause that happens again (sign-in) leaves theinvoke_agentspan with the tool span and nochat. - A tool that returns
undefined(or an async generator that yields nothing) no longer writes atoolmessage withcontent: undefinedinto the transcript. Its result is nownulleverywhere: the transcript and the next model request carry"null", andtool.done, approval resumes,run_codeand flows seenull. Providers, session stores and checkpoints get a valid string. recordReplaymatches a tool’s parameter schema the same way under zod 3 and zod 4. A zod 4 schema was fingerprinted from its JSON Schema (with$schema,required,additionalProperties) while a zod 3 one, and so every recorded cassette, used a fingerprint of the schema itself, so cassettes recorded with zod 3 failed to replay with zod 4 installed (the CIpeersjobsai4-zod4,ai6-zod4andai7-zod4failed on every replay test). Both now give the same fingerprint for the same schema; existing cassettes stay valid and need no re-recording, and a real change to a tool’s parameters still fails the match.- Parallel
taskcalls now get theirtaskIds, and background tasks start, in call order: allocating an id awaited a SHA-256 digest whose completion order is not fixed, so withmaxConcurrent: 1the second task could take the slot first (#296, the flaky “queues tasks beyond maxConcurrent” test). SubprocessSandbox.run()no longer fails with HTTP 404 “no such container” for a command that exits at once: the container isAutoRemoved, andwait()was only called afterstart(), so a fast command could be gone by then (10 of 40 paralleltrueruns failed on Docker Desktop). It now beginswait({ condition: 'next-exit' })beforestart(), and removes the container ifstart()itself fails.- The
cloudflare-workerbuild’s Node-builtin leak check now accepts the runtime-guardedloadNodeModule("node:module" | "node:dns")probes that@ai-sdk/provider-utils4 (installed withai6) uses, as it already did forai7’sloadBuiltinModule; without it a Worker bundle built onai6 failed with “Node builtins leaked” (found by the newai6matrix entries). isAgentEvent()is now exhaustive (the runtime type list is aRecord<AgentEventType, true>, so the compiler rejects a missing type). It had noagent.drift, so remote UI clients (parseEventStream(), the React, Vue and Svelte bindings) silently dropped that event.- A remote sub-agent’s token usage is added to the lead’s
result.usage. It was dropped, so budgets and cost reports undercounted delegation to aremoteAgent(). The lead adds what the remote agent reports on itsrun.doneevent to its totals, tousage.delegatedand tobyModel['remote:<name>'], which keeps the remote’s owncostUsd(the lead’scostUsdisundefinedwhen the remote sends none). A remote run that pauses for an approval adds what it spent up to the pause, and the continuation adds only what it spent after it; background remote tasks roll up the same way. A deployment that sends no usage adds nothing.RemoteRunOptionshas a new optionalonUsage(usage)callback;RemoteSubagent.run()still returnsPromise<string>, so hand-written ones compile unchanged. See docs/sub-agents.md#remote-sub-agents. lousho studiofinds the Agent Forge build that ships inside the installed package when it is run from a project that does not haveapps/agent-forge(it used to fail with “could not find apps/agent-forge” everywhere except the SDK repo). A project’s ownapps/agent-forgestill wins, and.lousho/is still created in the directory you ran it from.--devfrom an installed package still needs the TypeScript source and says so.- Documentation corrections: install commands, CLI command lists, optional peers, durable execution and compaction descriptions, the Status section, reasoning and file-part notes in the providers guide, and the
KVStorenote in the deployment guide now match the code. Ticket ids are gone from user-facing prose.
Tests
- Two more load-sensitive tests fixed.
SandboxShell.test.ts“passes only set values and allowed host names, never planted secrets” starts two realnode -eprocesses and timed out at the 5 s default in 1 of 20 parallel runs; it has a 30 s timeout now (pure slowness, no race: it passes in under a second alone).backgroundSubagents.test.ts“reports a sub-agent paused for approval as awaiting-approval” waited a fixed 10 ms for the child’s pause and failed in 9 of 20 parallel runs with the task stillrunning; the lead now asksagent_statusagain until the task has leftrunning. http.test.ts“rejects near the configured timeout” no longer compares real elapsed time to a real timeout (flaky under load, #324): it drives the request timer with a fake clock and checks the request is still pending at 499 ms, rejects with “timed out after 500ms” at 500 ms, and that the connection is closed.src/tools/workspace/checkpoints.node.test.ts“rewinds three turns” has a 30 s timeout: it takes well under a second alone, but timed out at the 5 s default when eight copies of the suite ran at once. The rewind itself is correct; every failure was the timeout.- Live-model cassettes recorded: real gpt-4o-mini runs through OpenRouter are now replayed in CI with no key, for the coding agent in the docs, the Telegram, GitHub and Teams channels, plan mode,
web_fetch, streamingsend(), the guardrail starter set,fromAiSdk()and PDF/PNG file parts, plus a recordedlousho tracesfixture. The live files that never ran (sendStreams,guardrailStarterSet,fileTraceExporter,remoteUsage) were missing theimport '../providers'that registers OpenRouter; fixed. New live tests (skipped without a key): ai 6 through OpenRouter andaiSdkEmbedder()over OpenRouter embeddings. pack-smokeallows a 16 MiB unpacked tarball (was 14 MiB):mainwas 45 KB under the old cap and permission modes went over it; see #316 for shrinking the package instead.- Sandbox egress and the credential broker are tested against a real Docker Engine: a new CI workflow, “Docker Engine” (
.github/workflows/docker.yml, on pull requests touching the sandbox, broker or docker deploy adapter, on demand and weekly), runsnpm run test:dockeron GitHub’subuntu-latestrunner (rootful Engine 28.0.4).src/security/sandboxEgress.docker.test.tschecks nine cases ofSubprocessSandbox({ network: { allow }, broker })withcurlimages/curl: an allowed HTTPS host answers through the broker, another host gets a 403, bypassing the proxy and raw IPs have no route, outside names do not resolve, the broker injects a credential the container never sees, a container outside the internal network cannot use the gateway listener, an aborted run andclose()leave no container or network, and a reused non-internal network is refused. The docker deploy image test (/healthand/chat) moved tosrc/deploy/adapters/docker.docker.test.tsand runs in the same job; it was skipped in CI before and passes there. No product defect was found.*.docker.test.tsfiles are excluded fromnpm testandnpm run test:coverage; they skip without a daemon unlessLOUSHO_DOCKER_TESTS=1is set (the workflow sets it), which makes a missing daemon fail. docs/workspace-tools.md says what the job checks; CONTRIBUTING.md mentionsnpm run test:docker. src/execution/principal.test.tsandprincipal.test-d.ts: the principal in tools (send, stream, session and channel turns), policies, rules, hooks and sub-agents (local, background, remote), pause and resume with another approver, a restart, a crash resume on an on-diskSqliteStore, old checkpoints and snapshots, forks, the approvals route and channel clicks; frozen in strict mode; absent from events and spans.- Test files can be type-checked:
npm run typecheck:testsrunstscoversrc/including every*.test.tsthrough the newtsconfig.tests.json, and the test files undersrc/execution,src/context,src/session,src/subagents,src/acpandsrc/testingnow pass it. The check is not in CI yet. One type change:textOf()also accepts a message or content whose parts arereadonly, such as amockModelrequest snapshot.
Docs
- The
vendor/model prefix note: every docs page whose snippets hardcode aprovider/modelstring now says the prefix chooses the provider and that with OpenRouter the id isopenrouter/<vendor>/<model>(e.g.openrouter/openai/gpt-4o-mini), socreateAgent()does not throwLOUSHO_PROVIDER_MISSING_API_KEYwhen onlyOPENROUTER_API_KEYis set. Stale model ids refreshed:anthropic/claude-3-5-haiku-latestexamples are nowanthropic/claude-haiku-4-5,'anthropic/claude-3-5-sonnet-latest'in errors.md is'anthropic/claude-sonnet-4-5',google('gemini-2.0-flash')isgoogle('gemini-2.5-flash')and the OpenRouter fallback example usesopenrouter/meta-llama/llama-3.3-70b-instruct. (anthropic/claude-3-5-sonnet-lateststays where it documents theANTHROPIC_API_KEYenv default, which is still that id insrc/providers/providerSpec.ts.) - Corrections in Errors, Troubleshooting and Testing: not every intentional error is an
SDKError(the namedErrorsubclasses —PropagatingToolError,CassetteMismatchError,CronExpressionError,DecryptionError— carry nocode); theFind a code by areatable now lists theAuthsection and every code that has one;LOUSHO_CASSETTE_INVALIDno longer claims to cover request mismatches (that isCassetteMismatchError), and its example useswebhookChannel()rather than awebhookTrigger()that does not exist;createAgent()’s default retry is documented as applying only to model strings and env-resolved models, not aproviderinstance; the file-parts entry now matches providers.md (PDFs andtext/plaindo reach providers onai6/7);connectMcp().status()lists'needs-auth'; themockModelusagedefault is “none reported” (the run estimates it) rather than zero; and the request-assertion snippet notes wheretemperaturecomes from, sincecreateAgent()has notemperatureoption. - Stream events gains the missing
agent.driftrow (emitted on a resume underonAgentDrift: 'warn', before the continuation’s first step) and the fields the table understated:executedBy: 'provider'ontool.start/tool.done/tool.error(hosted tools),replacedByHookontool.done,hookonpermission.decision,trigger: 'manual'oncompaction.start/compaction.done, and the fullusageshape (inputTokens/outputTokens,estimated,costUsd, andmodelCalls/hostedToolCallsonrun.done). The ordering guarantees now say that a streamed approval continuation reportsagent.driftand the decided call’stool.start/tool.donebefore its firststep.start, so those events fall outside a step. Runs uses the canonical event namestool.start/tool.done/run.doneinstead of the deprecatedtool-call/tool-result/finish, and Testing no longer claims amockModelturn withoutusagereports zeros (it reports none). - Long-tail corrections across the guides:
lousho eval --config,lousho init’sInitUsageErrorand-y,.ctsamong the dev-server module extensions and streamed approval continuations in docs/cli.md;lousho build --target=...(notlousho deploy) and the publiccreateRouteHandler().handler(not the internalserveFetch()) in docs/sub-agents.md;descriptionas acreateAgent()option andcreateDeployedServer()as build-internal in docs/agent-directories.md, docs/channels.md and docs/schedules.md; approval continuations on Workers emittool.start/tool.done,deploy-runtime-workeris bundler-internal andhandleScheduledneeds a store in docs/cloudflare-workers.md;schedule-<name>sessions,checkpoint-history/and the late-appearingapprovals/directory in docs/schedules.md and docs/sessions.md;saveAttachment/readAttachmentsignatures in docs/utilities.md; 256-bit OAuth state in docs/oauth.md; therecall_<name>description’s<name>in docs/memory.md;ctx.sessionIdin docs/tools.md; thethrowflow node in docs/flows.md; thetriggersspec field in docs/configuration.md;principalin a permission rule’swhenin docs/approvals.md; the'not-a-file'rewind skip andNodeWorkspace’s requiredrootin docs/workspace-tools.md; a built-in channel’snamesetting its route in docs/channels.md; thecompleted()‘max-steps’ message in docs/evals.md;formatUsage’s$0.0000in docs/models-and-cost.md; the completed registry static-check list and the leading letter/digit name rule in docs/registry.md;exporter,captureContentandredactContentascreateAgent()options in docs/migrating-to-create-agent.md;connectMcp().toolsas aRecordthat combines with array tools in docs/mcp.md;HookRegistry.size()as a method in docs/hooks.md;*.example.commatching subdomains only in docs/tools.md, docs/workspace-tools.md and docs/registry.md;resumeAfterApproval()named as an export, not an executor method, and the forkdivergedAtcomment corrected in docs/durable-execution.md. - New page, Permission modes: the modes and their table, which tools are read-only, the
editsFilesmarker, the order of evaluation, switching, the audit log, sub-agents and resume. Approvals “Permission policies” links to it; Tools, Stream events and Sub-agents (“What a sub-agent inherits”) gained a row each. - New page, Route auth and principals: the ordered list and its three outcomes, each helper, 401 / 403 /
WWW-Authenticate, which helpers run where (Node, Workers, edge),createRouteHandler, the node server andauth.ts, reading the principal in the run, and security notes (no session ownership check;basic()only over HTTPS). docs/errors.md gains a## Authsection at the end (LOUSHO_AUTH_CONFIG_INVALID). One-paragraph links from deployment.md (### Auth), nextjs.md (## Routes), memory.md (## Scopes), agent-directories.md (layout and deploy), api-overview.md and a “Route auth” row in the cloudflare-workers.md limits table; no heading of an existing page changed. - New page, Cloudflare Workers: a table of what the Worker target supports and what it does not comes first, then build and deploy, bindings, sessions, checkpoints and approvals in KV, scheduled runs, consistency, and bundle size and Node builtins. The Worker sections moved out of docs/deployment.md unchanged (
Bindings, sessions and the API on Workers,Cron triggers and handleScheduledandDurable execution (pause/resume) on Workersare gone from it); deployment.md keeps a shortcloudflare-workersummary that links to the page. Links todeployment.md#cron-triggers-and-handlescheduledmoved tocloudflare-workers.md#scheduled-runs. - Two dead heading links fixed: docs/executor-api.md now links to
tools.md#advanced-toolregistry, and docs/troubleshooting.md links tomcp.md#use-mcp-servers-in-an-agent(the configuration anchor moved with the MCP section). No other link indocs/or the README points to a missing heading. docs/approvals.md listsfileStore(dir)among the approval stores. - Long pages split; text moved unchanged. New pages: Runs, Models and cost, Stream events, Queued input and steering. Moved anchors (old to new):
api-overview.md#finish-reasons,#cancellationand#parallel-tool-callstoruns.md(same anchors);api-overview.md#models-tokens-and-costtomodels-and-cost.md#models-and-the-price-table;api-overview.md#usage-and-cost-of-a-runtomodels-and-cost.md#usage-and-cost-of-a-run;api-overview.md#flow-expressionstoflows.md#flow-expressions;api-overview.md#todo-toolstotools.md#todo-tools;api-overview.md#tool-errorstotools.md#errors;api-overview.md#context-compactiontocompaction.md;streaming.md#event-schema-version-1,#ordering-guarantees,#typescriptand#versioningtostream-events.md(same anchors);streaming.md#queued-inputand#steeringtoqueue-and-steer.md(same anchors); theAgentExecutor.execute()options table ofconfiguration.mdtoexecutor-api.md#options-of-agentexecutorexecute. The error codes page gained a “Find a code by area” table; its headings are unchanged. - The API overview, providers, structured output, tools, tracing, guardrails and testing guides teach
createAgent()first: usage and multimodal examples use it, the testing tool example usesdefineTool(), and every executor,AgentBuilderorToolRegistrysnippet sits under an “Advanced” heading that links to the executor API. They say thatcreateAgent()does not takeexporter,captureContentorsandboxyet. - New page, Triggers: the
@lousho/build-ai-agent/triggersadapters, a table that says when to use triggers, channels or schedules, theTriggerAdapterinterface (with a custom adapter andTriggerRegistry), and the webhook, Slack and cron sections that moved from the API overview, unchanged. The API overview now points to it; links toapi-overview.md#triggers,#webhook-authenticationand#slack-request-signaturesmoved totriggers.md. The missing-authwarning ofWebhookTriggerAdapterand the missing-signingSecretwarning ofSlackTriggerAdapternow link todocs/triggers.md. - New page docs/migrating-to-create-agent.md: from
AgentBuilder,AgentExecutor,ToolRegistryandresumeAfterApproval()tocreateAgent(), with a before-and-after example, a mapping table, theExecuteOptionsthatcreateAgent()does not take yet (with alternatives), the behavior differences and a step-by-step checklist. Linked from docs/executor-api.md and the README docs table. - New page, Hooks: the four hook points, the outcomes of a
preToolCall/postToolCallhook, four type-checked recipes (deny a tool, add a default argument, redact a result, inject context), ordering, andHookRegistry. TheHookRegistrybullet and the### Hook outcomessection moved there from the API overview, which now points to it; links toapi-overview.md#hook-outcomesmoved tohooks.md#hook-outcomes. - Approvals, sessions, streaming, sub-agents, compaction and skills guides show
createAgent()first. Executor snippets (AgentExecutor,resumeAfterApproval,streamResumeAfterApproval,InputQueue,HookRegistry) moved under headings named “Advanced: the executor API” (links to docs/executor-api.md);approvalsandstreamingrenamed a section to that name.createAgent({ hooks: [createCompactionHook(...)] })is the compaction example. Removed a statement from the sub-agents guide thatcreateAgent()takes noapprovalStore(it does, andagent.approvalsresolves sub-agent pauses). - Stale statements removed: ticket ids in the Agent Forge page, the “removed next minor” promise on
AgentTypein the API overview, and the installation note that read as if every user needs Node 22.19 for thehttptool (it comes from theundici@8dependency, which is loaded only forvalidateSSL: falserequests). TheProposedActiondoc comment no longer refers to an unlanded ticket. - New page docs/mcp.md, “MCP (Model Context Protocol)”: using MCP servers in an agent,
connectMcp(), approval for MCP tools,loadMcpTools(), serving an agent withserveMcp()andlousho mcp, and a Limits list. These sections moved out of docs/configuration.md, which keeps themcpServersspec field and links to the new page; links from approvals, CLI, tools, API overview and the README now point tomcp.md. docs/durable-execution.mdanddocs/workspace-tools.mdlead withcreateAgent()(send()with asessionId,agent.resume(),agent.approvals.resolve(),agent.fork()) instead ofAgentExecutor. The executor snippets (execute()with acheckpointStore,resumeAfterApproval(),AgentExecutor.fork(), theToolRegistrysetup) moved under “Advanced: the executor API”. In durable-execution the heading “What happens when you callexecute()again with the samesessionId” is now “What happens when you send again with the samesessionId”.- New page docs/troubleshooting.md: start from the symptom (setup, runs that end without an answer, tools, providers, sandbox and MCP), with cause, fix and a link for each. README docs table,
docs/installation.mdanddocs/errors.mdlink to it. - New guide, Build a coding agent: a terminal coding agent in six steps (workspace tools confined to the project, approval before writes and risky commands, a streamed UI that handles the approval pause, a session for follow-up questions, offline tests with
MemoryWorkspaceandmockModel), with an offline test of the same agent (docs/buildACodingAgent.test.ts; its replay of a recorded real-model run is skipped until the cassettedocs/__cassettes__/build-a-coding-agent.jsonis recorded). - The Quick Start is rewritten around
createAgent(): hello world, a tool, streaming, a session, an approval, an offline test withmockModel, a custom provider and spec files, each runnable with no API key (the first excepted). TheAgentBuilder+AgentExecutorsection moved to a new page, docs/executor-api.md (with theToolRegistrynote); the Quick Start no longer shows either API. create-lousho-agenthas a README (its npm page was empty) andlicense,homepageandrepositoryfields; they appear on npm with its next release.lousho init --helpno longer says--sdk-pathis needed until the package is on npm.- docs/auth.md gains a section at its end,
## Principals in tools and approvals(with### In a tool,### Approval policies and permission rules,### Who approved,### Pauses, crashes and forks,### Sub-agents,### What is stored and logged); its “Reading the principal in the run” and “Security notes” text is updated. One-sentence links, no new headings: docs/approvals.md (needsApprovalcontext,approve), docs/tools.md (ctx.principalandctx.approvalrows), docs/permission-modes.md (the audit log) and docs/channels.md (approvers). - UI and server examples corrected: docs/ai-sdk-ui.md’s client snippet used
useChat({ api: '/api/chat' }), theai4 signature, which is invalid for the documentedai6/7 combos — it now usesuseChat({ transport: new DefaultChatTransport({ api }) })and a note says whichaimajors are supported (ai4 keepsuseChat({ api })and returnsinput/handleInputChange/handleSubmit;ai5 is not in the peer range). docs/nextjs.md’suseChatsnippet has the same version note. The route handlers of ai-sdk-ui.md and nextjs.md openedagent.session({ id })per request with nostore, so a second turn forgot the first: both now passstore: memoryStore()and say to use a durable store on serverless; docs/react.md’s server section says the same for a per-request session. Thedata-lousho-approvalpart no longer reads as ifkind/questiononly mark anask_question: a tool waiting on an OAuth sign-in carrieskind: 'sign-in'andsignIn: { provider, displayName?, url }; docs/react.md’spendingApprovalrow says the same.
[1.0.0-alpha.8] - 2026-10-02
Changed
- No
anyleft in the SDK’s types:npm run lintnow fails on any ESLint warning, andno-explicit-any,no-unused-varsandban-ts-commentare errors. Runtime behavior is unchanged; some exported types are stricter, which can be a compile error where code read ananyvalue without checking it. What changed, and how to migrate:- Values the SDK cannot know are
unknown(narrow them, or cast to the shape you expect):FlowExecutionResult.outputand.variables,FlowExecutionContext.variables/session/memory,GenerateResult.rawResponse,StreamChunk.toolResult.result, extra keys ofLLMProviderConfig,AgentConfig.expectedResult/events/metadata,AgentExecutionResult.result,ResultData.result,SessionData.data,JiraTicket.customFields, the extra keys offormatZodError()’s result,ToolConfiguration.options,ToolSetting.options,FlowToolSetting.options,ToolNode.toolOptions,UIComponentNode.componentProps,FlowChunkEvent.issues/input/toolResults[].args/componentProps, andToolDefinition.function.parameters. FlowExecutionEventis a union discriminated ontype, withdatatyped per event type (newFlowExecutionEventOf<T>andFlowExecutionEventDataMap): checkevent.typebefore readingevent.data(if (event.type === 'tool-call') event.data?.tool).AgentConfig.settings(andAgentBuilder.setSettings()) is the newAgentSettings({ model?: string; [key: string]: unknown }).StorageService.readPlainJSONAttachment<T>()(andIStorageService’s) defaultsTtounknown: pass the type you stored,readPlainJSONAttachment<MyRecord>(key).OpenRouterProvider.getModelInfo()returns the newOpenRouterModel({ id: string; [key: string]: unknown }),nullorundefined.FlowBuilder.addAgent()/setAgents()takeFlowAgentDefinition;injectVariables()andapplyInputTransformation()take aFlowDefinitionNode(injectVariables()returns the type it was given);validateFlowInput()takesRecord<string, unknown>;validateAgentTools()takesRecord<string, { tool?: unknown }>;createDynamicZodSchemaForInputs()returnsz.ZodObject<Record<string, z.ZodTypeAny>>.- Still accepted as before:
needsApprovalpredicates typed for a tool’s own arguments, any argument toformatAxiosError()andhasRequiredKeys(), and anything aswritePlainJSONAttachment()data. The deprecatedExecutionEventkeepstoolResult.result: any.
- Values the SDK cannot know are
- Eval cassettes hook in at the model boundary:
lousho eval --record / --replay / --driftno longer reassignsAgentExecutor.executeat runtime. The run loop routes every model call through a small provider-interception seam (setProviderInterceptor()/interceptProvider()insrc/providers/interception.ts; a no-op unless an interceptor is installed), and the eval runner installs one that answers with the per-caserecordReplay()wrapper. Cassette files, keying,--driftoutput and JUnit reports are unchanged, so existing cassettes keep replaying. Streamed runs and sub-agents inside an eval case are covered by tests. - More errors carry SDK error codes: the plain
Errors thrown bysrc/execution(historyLimit,toolConcurrency, a second iteration of anAgentRun), the tool registry, the built-in tools,serveMcp(),NodeWorkspaceand thelousho init/studio/ chat helpers are nowSDKErrors with an existing code (LOUSHO_CONFIG_INVALIDviaConfigurationError,LOUSHO_RUN_ALREADY_ITERATED,LOUSHO_APPROVAL_NOT_FOUND,LOUSHO_PROVIDER_UNKNOWN,LOUSHO_TOOL_EXECUTION_FAILED). Messages are unchanged;error.code,error.hintand a[code] hint (docs)line (not on the built-in tools’ run-time failures, whose message is the model-visible tool result) are added. Code that matchederror.constructor === Errororerror.name === 'Error'needserror instanceof SDKError. - The remaining user-reachable plain
Errors carry SDK error codes: agent directories, flows, memory, skills, storage (SQLite), triggers, deploy, evals, record/replay cassettes,defineTool(), sub-agent options, channels, sandbox/credential-broker options and thellmregistry now throw anSDKError(message text unchanged, plus the[code] hint (docs)line, except for tool results and messages tests assert, which stay as written). New codes:LOUSHO_TOOL_ARGS_INVALID(whatToolArgumentsValidationErrorcarries now),LOUSHO_AGENT_DIR_INVALID,LOUSHO_SKILL_INVALID,LOUSHO_FLOW_INVALID,LOUSHO_STORAGE_FAILED,LOUSHO_TRIGGER_INVALID,LOUSHO_DEPLOY_FAILED,LOUSHO_EVALS_INVALID,LOUSHO_TEST_FAILED,LOUSHO_CASSETTE_INVALIDandLOUSHO_CHANNEL_REQUEST_FAILED, all indocs/errors.md. Code that matched these errors byerror.constructor === Errororerror.name === 'Error'must checkinstanceof SDKError/error.codeinstead.ToolExecutionErrortakes an optional fourthcodeargument. A new test (src/utils/plainErrors.test.ts) fails when new SDK code throws a plainError; the 5 that remain are listed there with the reason. - The last two allowlisted plain
Errors areSDKErrors: OpenRouter’s model-catalog fetch (LOUSHO_PROVIDER_REQUEST_FAILED;getModels()/getModelInfo()still catch it and fall back) and the UI runner’s failedPOSTto a remote agent (LOUSHO_REMOTE_REQUEST_FAILED, as used byuseLoushoAgent()and the Vue/Svelte bindings). Both keep their message text exactly (no help line appended), so the UI’s error event shows the same message, now withname: 'SDKError'instead of'Error'.SDKErroritself moved tosrc/utils/sdkError.ts(re-exported from the same places as before) so the browser entries can throw it without importingai. The allowlist insrc/utils/plainErrors.test.tsis down to the 3 intended sites. - zod 3 or zod 4: the
zodpeer is now^3.25.76 || ^4.0.0. Schemas of either major (includingzod/v4on zod 3.25 andzod/v3on zod 4) work indefineTool({ input }), structuredoutputand argument validation: zod 4 schemas are sent to the model asz.toJSONSchemaoutput (also toaiv4, whose own converter only reads zod 3), zod 3 schemas through theaiSDK’s converter as before, and both are parsed with their ownsafeParse.defineToolalso takes any Standard Schema that exposes~standard.jsonSchema; tool arguments validate with any Standard Schema’s~standard.validate. The SDK’s own schemas (AgentSpec, registry documents, built-in tools, MCP tool conversion) run on whichever major is installed, and issue messages read the same on both (zod 4’sInvalid input: expected string, received undefinedis reported asRequired).lousho initkeeps zod 3 for theai4 scaffold (Ollama), whose packages peer on zod 3. Ollama onai6/7 (ollama-ai-provider-v2, which peers on zod 4) is no longer blocked by the SDK’s zod peer. CI runs the type check, build and suite on zod 4 too. Migration:DefineToolOptions,DefinedToolandToolDescriptor.inputSchemaare typed with the new exportedStandardSchemaV1(parsed type:InferSchemaOutput) instead of zod 3’sZodTypeAny; code that called zod methods ondescriptor.inputSchemaneeds a cast. Thetasktool’s error for an unknown sub-agent now readsUnknown sub-agent "x". Expected one of: 'a', 'b'.createAgent({ output })is still typed with the installed major’sZodType. - Slack and Discord approvals are starter-only by default (behaviour change): without
approvers, only the user who started the turn (the Slack message author, the Discord command’s user) can approve or deny a tool call; before, anyone who could see the message could. Migration: passapprovers: () => truefor the old behaviour, or a list of user ids / a function for a team. Approval button values (Slack) and custom ids (Discord) now carry the starter (<starter>:<approval id>), so buttons posted before the upgrade carry no starter and only anapproverslist or function can approve them. - Package entries share one copy of each module: tsup code splitting is on, so
@lousho/build-ai-agent,/hooks,/tools,/mcpand the rest import shared chunks instead of each bundling their own copy.HookRegistry,SDKErrorand module-level registries are now the same object across entries (they were duplicated, soinstanceofand singletons could disagree), anddist/shrinks from about 25 MB to 8.8 MB.instanceof SDKErrorandinstanceof HookRegistryalso hold between the ESM and CJS copies a mixed-format process loads (aSymbol.forbrand). See Installation. - A crash resume of a dynamic agent restores the run’s config: checkpoints now carry
runConfig(thectxand model the run was resolved with, as approval snapshots already did), andagent.resume(id)/session.resume()/send(…, { sessionId })on an unfinished run use the saved model and re-resolvetoolsandinstructionswith the savedctx, instead ofinput: []and nometadata; a model chosen frommetadatano longer changes mid-run. Static agents are unchanged. - Resumed approved calls must run with the approved arguments (behaviour change): after the pre-tool hooks ran on the resumed call, the arguments are compared (deep, key order ignored) with the approved ones whether a hook returned
{ input }or changedctx.argsin place, and a difference is refused with the existingkind: 'validation'error (“approved with different input”); a hook that rebuilds the same arguments in another key order is no longer refused. Migration: a hook that rewrites arguments (a redactor, a normalizer) must also run on the original run, so the approval record already holds the rewritten input; a hook added only after the pause, that changes the arguments, now refuses the call. A call whose tool no longer exists after an approval (snapshots with an agent fingerprint) now rejects withLOUSHO_RESUME_TOOL_MISSINGinstead of giving the model anot-foundtool result; older snapshots keep the old behaviour. - Cancelled and settled tool calls use the shared tool-error shape: a tool call cancelled before it ran (the run was aborted or steered) and a sub-agent call dropped because the lead run was already pausing for another approval now reach the model as
{ error: 'ToolNotRunError', toolName, message, kind: 'not-run' }with the transcript message flaggedisError. Before, the result was{ error: '<text>' }(and the cancelled one was not flaggedisError); the text is now undermessage. - A
permissionsallow(orask) rule no longer overrides a tool’s ownneedsApprovaldeny (behaviour change): the tool’sneedsApprovalis now called for those calls too, and its'deny'/{ deny }denies the call; anallowstill skips the tool’s ask. Adenyrule still wins without callingneedsApproval. Migration: a tool that should run under anallowrule must not deny it fromneedsApproval. See docs/approvals.md. agent.session()passes the agent’screateAgent({ compaction })to the session, sosession.compact()uses the agent’s strategy and sizes unlessagent.session({ compaction })sets its own.- The
cloudflare-workertarget builds withaiv7 installed. Withaiv7 (@ai-sdk/openai/@ai-sdk/anthropicv4),lousho build --target=cloudflare-workerfailed with “Node builtins leaked” (node:module,node:dns,node:diagnostics_channel,node:async_hooks). Those are not imports:aiv7 and@ai-sdk/provider-utilsv5 probe them at run time throughprocess.getBuiltinModule(), only when running on Node, so the bundle never loads them on Workers. The build’s leak check now exempts exactly those four ids, and only as the argument of agetBuiltinModule/loadBuiltinModulecall; any othernode:reference still fails the build. Nonodejs_compatflag is needed. The 16 Worker bundle tests that were skipped onaiv7 now run on both majors. The bundle is about 3.4 MB raw on v7 (1.7 MB on v4), well under the 64 MiB limit. - BREAKING: sandboxed and workspace commands get an allowlisted environment. Commands run by
NodeWorkspace.exec()andSandboxShellno longer see the host’sprocess.env, soenv/printenvcannot reveal API keys or cloud credentials. They get a small base a shell needs (PATH,HOME/USERPROFILE,TMP/TEMP/TMPDIR,LANG,LC_*,TERM, plusSystemRoot,SystemDrive,ComSpec,PATHEXT,WINDIRon Windows) and what you add. A container (SubprocessSandbox) gets only what you add, never the host env.SandboxShellgainsenvandinheritEnvoptions;NodeWorkspaceOptions.inheritEnvandSandboxShellOptions.inheritEnvaccepttrue;SandboxRunOptionsgainsinheritEnv(NoopSandboxkeeps passing the host env unless it isfalse, whichSandboxShellsets).SubprocessSandboxgainsnetwork: 'none' | 'default' | { allow: string[] }(default'none', as before);{ allow }is validated and kept onsandbox.networkbut runs with no network until the egress proxy enforces it (fail closed). Migration: pass what commands need, either values (env: { NODE_ENV: 'test' }) or host names to copy (inheritEnv: ['CI', 'NODE_OPTIONS']); to restore the old behavior, passinheritEnv: true. See docs/workspace-tools.md. - Internal: the test suite runs with
aiv7 installed asai. A test helper (src/providers/aiMajor.testkit.ts:installedAiMajor,describeOnAiV4,itOnAiV4) reads the installed major; tests whose behavior is the same on both majors are made major-agnostic, the 66 that only make sense on v4 (v4 message and call shapes,MockLanguageModelV1) or on a Worker bundle that still leaksnode:built-ins on v7 are skipped there. Thetypecheck-ai7CI job now also builds and runsnpx vitest run. Test and CI change only; no product change. - Internal: the SDK source now type-checks against
aiv7 (with@ai-sdk/openai/@ai-sdk/anthropicv4) as well asaiv4.AiSdkProviderbuilds itsaiv4 request with SDK-owned structural types instead of the v4-onlyCoreMessage/CoreAssistantMessage/CoreToolMessage/Outputtypes and no longer callsai’stool()(an identity function on v4); the legacy.toolthatdefineTool()/toolDescriptorFromSchema()hand-build is cast once at that boundary. No runtime change on v4. A new CI job runstsc --noEmitwithai@7installed. Theai/@ai-sdk/*peer ranges are unchanged for now. - MCP tools without
readOnlyHintnow ask for approval by default (BREAKING for MCP users):loadMcpTools(),connectMcp()andcreateAgent({ mcpServers })setneedsApprovalfrom each tool’s MCP annotations:readOnlyHint: trueruns,destructiveHinttrue or absent (the MCP spec default) asks,destructiveHint: falseruns. Choose per server with the newapproval: 'annotations' | 'always' | 'never' | ({ name, annotations }) => boolean(loadMcpTools(client, name, { approval }),connectMcp()server entries,createAgent({ mcpServers })andAgentSpec.mcpServers, which validates it; a spec file takes the three strings). The descriptor keeps the raw annotations on the newToolDescriptor.metadata?.mcp.annotations(typesMcpToolAnnotations,ToolMetadata,McpApproval) and uses the annotationtitleasdisplayName. Migration: passapproval: 'never'to restore the old behaviour (every MCP tool runs without asking).createAgent()agents pause withfinishReason: 'awaiting-approval', while a bareAgentExecutorwithout anapprovalStorenow throws for such tools. See docs/configuration.md#mcp-tool-approval-approval. - Small built-in tools are defined with
defineTool(not breaking):currentDateTool,dayNameTool,createEmailTool(),createHttpTool(),createSlackTool(),createDelegateTool()and the descriptorsloadMcpTools()builds no longer callai’stool(). They now carry canonicalinputSchema/execute(the legacy.toolstays), and the built-ins have the tool namescurrent_date,day_name,send_email,http_request,slack_alertanddelegate_to_<agent>. Descriptions, schemas, approval and sandbox behaviour and the factory signatures are unchanged. MCP descriptors are built with the new internaltoolDescriptorFromSchema(), which (unlikedefineTool) accepts any server-provided name or empty description.routeFetchThroughSandbox()reads the canonicalexecutefirst. - GitHub and Jira tools are defined with
defineTool(not breaking): the 28createGitHubTools()tools and the 20createJiraTools()tools no longer callai’stool(), so nothing undersrc/toolsimportsaiany more. They now carry canonicalinputSchema/execute(the legacy.toolstays). Tool names, descriptions, schemas, the sandbox flags and the factory signatures are unchanged. The GitHub out-of-scope tools (branch/file writes, code search, issue CRUD, merge) are disabled through the canonicalexecuteas well astool.execute, so calling one still throws “out of scope” before any HTTP request.JiraTools.register()now also routes tools registered withdefineToolthrough the sandbox seam. - BREAKING (types only):
Message.contentis widened fromstringtostring | ContentPart[]. Messages you build keep working unchanged, but code that readsmessage.contentas a string (.length,.startsWith(), a template literal) no longer type-checks. Migration: readtextOf(message)instead, or narrow withtypeof message.content === 'string'. A customLLMProviderthat forwardscontentshould handle the parts or sendtextOf(message). - The execute context is our own type (not breaking): the new exported
ToolExecutionContext({ toolCallId, messages: readonly Message[], abortSignal?, sessionId?, onDelegatedUsage? },Messagefrom@lousho/build-ai-agent) replaces theaiSDK’sToolExecutionOptionsas the type of the second argument ofdefineTool()’sexecute,ToolDescriptor.execute,DefinedTool.executeand the third argument ofsandboxExecute, and is whatbuildToolRunContext()returns; the public types no longer importToolExecutionOptionsfromai. A function typed forai’s options that only readstoolCallIdorabortSignalstays assignable.ToolRunContextis now a deprecated alias of the optional fields ofToolExecutionContext(it already existed withonDelegatedUsageandtoolCallId).AgentExecutionOptions.messagesis typedMessage[]instead of theaiSDK’sCoreMessage[](the field is unused by the SDK). The legacyToolDescriptor.tool(aiv4Tool) is unchanged. See docs/tools.md#execute-context. - BREAKING (small):
SDKError.codevalues are now theLOUSHO_*codes:AGENT_EXECUTION_ERROR->LOUSHO_AGENT_EXECUTION_FAILED,TOOL_EXECUTION_ERROR->LOUSHO_TOOL_EXECUTION_FAILED,LLM_PROVIDER_ERROR->LOUSHO_PROVIDER_REQUEST_FAILED,SESSION_AWAITING_APPROVAL->LOUSHO_SESSION_AWAITING_APPROVAL,FLOW_EXECUTION_ERROR->LOUSHO_FLOW_EXECUTION_FAILED,CONFIGURATION_ERROR->LOUSHO_CONFIG_INVALID,VALIDATION_ERROR->LOUSHO_VALIDATION_FAILED,TIMEOUT_ERROR->LOUSHO_OPERATION_TIMEOUT,RATE_LIMIT_ERROR->LOUSHO_PROVIDER_RATE_LIMITED;codeis no longer optional (new SDKError(message)getsLOUSHO_GENERIC_ERROR). No class was renamed. The messages ofSDKErrors other thanToolExecutionError,LLMProviderError,TimeoutErrorandRateLimitErrorgain a second line with the code, hint and docs link, andloadSpec()now rejects a spec whose top-level field is a likely typo of a spec field (LOUSHO_SPEC_UNKNOWN_FIELD; other unknown fields are still ignored). Migration: comparecodeagainst the new values (or useinstanceof); match messages withtoContain/ a regex, or compareerror.detail, instead of exact equality. - BREAKING (small): tool failures that did not go through the thrown-error path now use the shared shape, so
erroris an error name instead of a message. Before: an unknown tool or a missing registry gave{ error: "Tool 'x' not found" }/{ error: 'No tool registry available' }; a rejected approval gave{ error: 'Tool execution was rejected by the reviewer', note }; a tool that threw after an approval gave{ error: '<message>' }; a call left without a result on resume gave{ error: 'Tool call was not run: ...' }. Now each is{ error: '<ToolNotFoundError | ToolRejectedError | <thrown error name> | ToolNotRunError>', toolName, message: '<the old text>', kind, ... }. A tool approved but missing from the registry on resume used to rejectresumeAfterApproval()withTool 'x' not found in registry; it now resolves with anot-founderror result. The sandbox guard throwsSandboxRequiredError(same message, still anError). Migration: readmessageinstead oferrorwhen you want the text, and branch onkind.ToolArgumentsValidationError.toToolResult()now also returnskind: 'validation'. - Background sub-agents still running when the lead run ends are now cancelled instead of running to completion on their own; a lead run that pauses for approval cancels them too (the resumed run starts with none). Migration: to keep them, have the lead collect them with
agent_awaitbefore its final answer, or setsubagentOptions: { awaitBackgroundOnFinish: true }. - Heavy dependencies are optional peers:
dockerode(Docker sandboxing,SubprocessSandbox),@modelcontextprotocol/sdk(serveMcp,lousho mcp, MCP clients) andprompts(the interactive questions oflousho init) moved fromdependenciestopeerDependencies, marked optional inpeerDependenciesMeta. They were already loaded lazily; now a project that uses none of them does not install them. Using one without its package fails that call withMissingPeerDependencyError, which now also carriesfeatureand names the exact command (for examplenpm install dockerode@^5.0.1).lousho doctorlists the three with what they enable (a missingdockerodefails the check when the agent spec uses a sandboxed tool), and its version lookup no longer returnsundefinedfor packages whoseexportsmap hidespackage.json. Migration: install the peer if you use Docker sandboxing (npm install dockerode), MCP (npm install @modelcontextprotocol/sdk), or interactivelousho init(npm install prompts;npm create lousho-agentalready does, andlousho init --yesneeds nothing). See docs/installation.md. - The
httptool no longer loadsundicifor default requests: with TLS verification on (the default) it uses the runtime’s globalfetch;undici(still a regular dependency) is loaded only forvalidateSSL: false, whose per-request TLS dispatcher the globalfetchcannot express.yamlstays a dependency (agent specs and skills need a YAML parser). - Retries no longer stack: the built-in providers (
OpenAIProvider,AnthropicProvider,OllamaProvider,OpenRouterProvider) now passmaxRetriesto theaiSDK calls:config.maxRetries, or 2 (theaiSDK’s default, so behaviour is unchanged) when unset.createAgent()builds the providers it resolves from strings withmaxRetries: 0and retries in itswithRetry()wrapper instead, so retries happen in one place (at most 3 calls by default, as before) and each one is observable. If you wrap a built-in provider inwithRetry()/resilientProvider()yourself, build it withmaxRetries: 0; note that amaxRetriesyou already set in a provider config is now honoured by theaiSDK. AgentTypeis optional and deprecated (not breaking):AgentBuilder.build()no longer requiressetType()andAgentConfig.agentTypeis now optional (createAgent()andspecToAgent()agents carry no type).AgentType,setType()and theagent-typesregistry/validators are marked@deprecated: they have no runtime effect and will be removed in the next minor; they stay exported for now. Drop yoursetType(...)calls.- BREAKING:
encrypt()now generates a random salt per call instead of a hardcoded one. Ciphertext produced before this change cannot be decrypted with the new code and must be re-encrypted. - BREAKING: The mock repositories (
MockAgentRepository,MockSessionRepository,MockResultRepository,MockMemoryRepository,MockAttachmentRepository— previously re-exported fromsrc/data/mocks.tsvia the package root/./datasubpath; this package has nocreateMockRepositoriesfactory) are no longer exported from the package root. Import them from@lousho/build-ai-agent/testinginstead. - One session-API client behind
remoteAgent()andremoteTarget(): both now share an internal client (src/server/sessionClient.ts) forPOST <url>/chat, the SSE read, bearer-token scrubbing and the error mapping, and use one pair of codes,LOUSHO_REMOTE_REQUEST_FAILEDandLOUSHO_REMOTE_UNAUTHORIZED. The unreleasedLOUSHO_REMOTE_AGENT_FAILEDis removed: aremoteAgent()failure now carriesLOUSHO_REMOTE_REQUEST_FAILED(network, non-2xx, truncated stream, or a remote run that ends in an error, with “the remote run ended in an error” in the message) orLOUSHO_REMOTE_UNAUTHORIZED(401). No option or behavior of either function changed.
Added
- Remote sub-agent approvals go through the lead run: a
remoteAgent()task whose remote run pauses for a tool approval now pauses the lead run the way a local sub-agent does (it used to fail withLOUSHO_SESSION_AWAITING_APPROVAL): the lead’s pending approval (agent.approvals.list(), channel buttons, the dev chat, ACP permission requests) has the remote tool’s name and input andsubagentPath: [<remote agent>], and a remoteask_questionarrives as a question. Deciding it on the lead (resolve,streamResolve,answer) posts the decision to the remotePOST <url>/chat/:sessionId/approvals/:idand the continuation’s final answer is thetaskresult; a further pause pauses the lead again. The lead’s approval snapshot stores the remote session id, the remote approval id, thetaskIdand the agent name (never the token), so a fresh lead process on the same store can decide it. Failures while deciding (401, other non-2xx including the remote’s 404 for an approval no longer pending, network) are thetaskcall’s structured tool error withLOUSHO_REMOTE_UNAUTHORIZED/LOUSHO_REMOTE_REQUEST_FAILED. A remote agent with anoutputschema now returns its object as JSON with the footer (the V4.2 shape), read fromrun.done’sobject.RemoteSubagent.run()takespausableanddecision(typeRemoteRunOptions); the internal session client gainsresolveRemoteApproval()andSessionTurnSummary.object. Only a lead run without an approval store keeps the oldLOUSHO_SESSION_AWAITING_APPROVALerror. See docs/sub-agents.md#remote-approvals. - Structured output for sessions and sub-agents, typed for either zod major:
createAgent({ output })andExecuteOptions.outputaccept a zod 3 schema, a zod 4 schema (zod/v4on zod 3.25, or zod 4) or a Standard Schema that can produce JSON Schema, andresult.objectis inferred from each without a cast (InferSchemaOutput, asdefineTool).AgentSessionis generic (AgentSession<TObject = unknown>):agent.session().send()and.stream()results carry the typedobject. A sub-agent with its ownoutputreturns its validated object as JSON (then thetaskIdfooter) as thetaskandagent_awaitresult; itsoutput-invalidfinish is a structured tool error. Sub-agents do not inherit the lead’soutput;remoteAgent()returns text only. The exported spec schemas (agentSpecSchema, …) are typed asSpecSchema<T>/SpecObjectSchema<T>, so the publishedschema-*.d.tsno longer depends on zod 3 generics (skipLibCheck: falseprojects on zod 4). The Ollama missing-peer note now saysollama-ai-provider-v2needs zod 4 (npm install zod@^4.0.0). See docs/structured-output.md. - Publish readiness:
npm run pack-smoke(scripts/pack-smoke.ts, a CI job) packs the SDK andcreate-lousho-agent, checks the tarball (no.env, tests or secret-looking strings; entry count and size caps), runsnpm publish --dry-runfor both (nothing is published), installs the tarballs plus peers from the registry into a fresh project and verifies ESM and CJS loads of everyexportsentry, a mock-model agent turn, theloushobin (--help,doctor) andtscwithmoduleResolutionbundler and node16. - One event system:
AgentEventlisteners for callers who do not iterate a run.createAgent({ onEvent: (event: AgentEvent) => void })and the newExecuteOptions.onAgentEvent(also taken byAgentExecutor.stream()andresumeAfterApproval()) are called synchronously with everyAgentEventof the run, onsend()/execute()as onstream(), sub-agents’ events included: the same events in the same order as the stream yields (a non-streamed run generates each model step whole, so its text is onetext.deltaper step). A run with a listener also reports hook events, permission decisions, budgets and guardrails to it when it is not streamed. A non-streamedresumeAfterApproval()with a listener now reports the decided call (run.start,tool.start,tool.done) like a streamed one. See docs/streaming.md#listening-without-iterating. - Reasoning: new
reasoningoption oncreateAgent(),send()/stream()(per call, overriding the agent’s),ExecuteOptionsandGenerateOptions:'none' | 'minimal' | 'low' | 'medium' | 'high'or{ effort?, budgetTokens?, summary?: 'auto' | 'none', force? }(typesReasoningOption,ReasoningEffort,ReasoningSettings). The built-in providers send it throughproviderOptionsonai4.3 and 6/7: OpenAIreasoningEffort(+reasoningSummary), Anthropicthinking: { type: 'enabled', budgetTokens }(effort table 1024 / 2048 / 8192 / 24576 tokens), Ollamathink(ollama-ai-provider-v2only; ignored with one warning onai4), and OpenRouter’s unifiedreasoningbody field (effortormax_tokens). It is only sent to model families known to accept it (force: trueoverrides);'none'sends nothing. New eventsreasoning.start,reasoning.delta(text) andreasoning.done(text,tokens?) in theAgentEventunion, emitted inside the step before its first text or tool call, fromaiv4reasoningparts and v6/v7reasoning-start/delta/end;ExecutionResult.reasoningholds the run’s reasoning text andGenerateResult.reasoninga call’s blocks (new typeReasoningBlock); new stream chunk typesreasoning-delta/reasoning-end(StreamChunk.reasoning). Reasoning is not written to the transcript as text; an assistant tool-call turn keeps Anthropic’s signed or redacted thinking blocks in the newMessage.reasoning, which the Anthropic provider sends back unmodified (it survives checkpoints and resumes). The UI reducer keepsUIMessage.reasoning,toUIMessageStream()emitsreasoning-start/reasoning-delta/reasoning-end,lousho acpsendsagent_thought_chunk,lousho chatprints reasoning dimmed, andchatspans carrylousho.usage.reasoning_tokens. Cassettes record the reasoning chunks. See docs/reasoning.md. - Tools know their session:
ToolExecutionContext.sessionIdis now set whenever the run has one:AgentExecutor.execute({ sessionId }),send({ sessionId }), everyagent.session()turn (the session id; a checkpointed turn’s own<id>.turn-<n>, as hooks see it), approval resumes (the paused run’s), and sub-agents (<parent session>/<task tool call id>). A session turn’s run now carries the session id even without a checkpoint store (no checkpoint is written), so hooks and theinvoke_agentspan’s conversation id see it too. - Hardened Slack and Discord channels:
approvers(a list of platform user ids, or(user: { id, name?, roles? }, { toolName, input, sessionId }) => boolean | Promise<boolean>) says who may click Approve / Deny (a refused click gets an ephemeral “not allowed” and the approval stays pending);onError(error, { channel, stage, sessionId? })on both channels, onmountChannels()and ondefineChannel()receives failures after the acknowledgment (reply delivery, a failed turn, an approval continuation; defaultconsole.errorwith channel, stage, session and SDK error code, never a token) and a failed turn tells the user so;mountChannels({ onDecision })reports who decided;parsegets a thirdctxargument (ChannelContext: pending approval, session id,hasSession) and a{ decision }may carryinboundandapprover. Pending approvals now resolve from the click itself and the Slack ‘active thread’ check asks the session store, so both survive a restart. Slack: the clicked message is replaced with the outcome (buttons removed) and direct messages (message.im, scopeim:history) are sessions keyed on the DM channel. See docs/channels.md. - Resumable sub-agent tasks: every
taskresult ends with ataskId(the footer is now[sub-agent '<name>': N step(s), finish reason '<reason>', taskId 'task_1']; a remote one gains, taskId '...'too), andtasktakes optionaltaskIdandmode: 'new' | 'resume' | 'fork'(defaultnewwithout ataskId,resumewith one).resumecontinues that sub-agent with its transcript and the new prompt as the next user turn;forkstarts a new task (newtaskId) from a copy of it and leaves the original alone. Conversations are kept per lead session in the agent’sstore.sessions(newSubagentOptions.sessions, set bycreateAgent({ store })) for lead runs with asessionId(checkpointedsend()and session turns), under a key hashed from the lead session and the taskId, so they survive a restart and cannot be reached from another session; other runs keep them in memory for the run. Background tasks share the ids (a background task’s id is nowtask_<n>counted with the synchronous ones): a finished one can be resumed, a running one is refused with the newLOUSHO_SUBAGENT_TASK_BUSY; an unknown, foreign or other sub-agent’s id gets the newLOUSHO_SUBAGENT_TASK_NOT_FOUND, both as the structured tool error. An approval inside a resumed child pauses and resumes the lead as before (streamed or not), and a resumed child’s usage counts toward the lead like a fresh call.remoteAgent()tasks resumed bytaskIdcontinue in the same remote session (RemoteSubagent.run()takessessionIdandtaskId); remote approvals are still not proxied, but a task whose remote run paused can be continued once the approval was decided on the remote agent. The model-facingtaskdescription and the sub-agents prompt block say how to continue a task. See docs/sub-agents.md#continuing-a-task. - Agent-directory and spec builds keep optional peers external, and the node server runs spec cron triggers:
lousho build --target=node-server|dockerleaves every optional peer of the SDK (read from itspeerDependenciesMeta) out of the bundle, replacing the hand-keptdockerode/ollama-ai-provider-v2list, so a build no longer needs peers the agent does not use; a spec’s{ type: 'cron' }triggers now start on the built server (and are validated at build time), as on the Cloudflare Worker target. See Deployment. - Agent fingerprint on resume: every checkpoint and approval snapshot now carries
agentFingerprint(new typeAgentFingerprint: the model id, each tool’s name with a hash of its JSON input schema, a hash of the instructions, and a SHA-256 prefix over them, via Web Crypto; functions are ignored), and a resume compares it with the resuming agent’s before any model call or tool runs. New optiononAgentDrift: 'warn' | 'error' | 'ignore'(typeAgentDriftMode) oncreateAgent(),AgentExecutor.execute()andresumeAfterApproval():'warn'(default) emits the newagent.driftevent (AgentDriftEvent:model?,toolsAdded,toolsRemoved,toolsChanged,instructions) and aconsole.warn,'error'rejects with the newLOUSHO_AGENT_DRIFTand leaves the checkpoint (or the pending approval) untouched. A pending tool call whose tool no longer exists always rejects with the newLOUSHO_RESUME_TOOL_MISSING. Works for crash resume,session.resume()and approval resume, streamed or not; old checkpoints and snapshots have no fingerprint and resume unchecked. A sub-agent’s nested approval snapshot carries its own fingerprint, but only the top-level agent is compared.resumeAfterApproval()’s options takecurrentAgent(set bycreateAgent()) so instructions can be compared. See docs/durable-execution.md#resuming-with-a-changed-agent. - Docker sandbox network allowlists are enforced through the credential broker:
new SubprocessSandbox({ network: { allow }, broker })creates (or reuses, bynetworkName) an internal Docker network (Internal: true, labelcom.lousho.sandbox=egress), has the broker listen on its gateway address for that subnet only, and starts each container on it withHTTP_PROXY/HTTPS_PROXYpointing there, so the broker (allowlist: its rule hosts plusallow) is the container’s only route out. Newsandbox.close()stops the listener and removes the network it created. Newbroker.listen({ host, clients, allow? })adds a listener on another address that drops peers outside theclientssubnet; the broker still listens on loopback only by default. Enforced on Docker Engine 25.0.5+ for Linux with the agent on the same host; Docker Desktop, rootless Docker, a remote daemon, a non-internal reused network and older Engines are refused with the new codeLOUSHO_SANDBOX_EGRESS_UNSUPPORTED(no container is started). Without abroker,{ allow }still means no network. See docs/workspace-tools.md. - The Docker sandbox honors cancellation:
SubprocessSandbox.run()takessignal(SandboxRunOptions). When it aborts, the container is killed and force-removed (errors from an already stopped or removed container are ignored) andrun()rejects with anAbortError, likeNoopSandbox; an already-aborted signal starts no container; a timeout uses the same cleanup.SandboxShellpasses the tool’s abort signal down, so a cancelledshellcall stops its container (it used to run until the timeout) and reportsaborted: true. See docs/workspace-tools.md. - Schedules on Cloudflare Workers: the
cloudflare-workertarget writes the spec’s{ type: 'cron', cron, input, name?, timezone? }triggers (deduplicated) towrangler.tomlas[triggers] crons = [...], and the generated Worker exportsscheduled(controller, env, ctx), which runs every trigger whose expression equalscontroller.cronas an agent turn insidectx.waitUntil(), in sessionschedule:<name>(visible in the KV store when bound). A failing trigger is logged withconsole.error(name and error code) and never stops the others. The build fails withLOUSHO_SCHEDULE_INVALIDnaming the trigger for what Cloudflare would not fire: atimezone(crons are UTC), a seconds field or@dailyshortcut, a numeric day-of-week (Cloudflare counts 1 as Sunday). NewhandleScheduled(agent, schedules, controller, ctx)(root anddeploy-runtime-worker) wiresdefineScheduleschedules to a hand-written Worker’sscheduled().startSchedulesshares its fire step with it. See docs/schedules.md#on-cloudflare-workers. aiv6 and v7 as peers:peerDependenciesnow acceptai^4.3.19 || ^6.0.0 || ^7.0.0and@ai-sdk/openai/@ai-sdk/anthropic^0.0.42 || ^1.0.0 || ^3.0.0 || ^4.0.0(still optional), plus the new optional peerollama-ai-provider-v2^2.0.0 || ^3.0.0 || ^4.0.0, so a project on the currentaimajor installs without peer conflicts. Pairings:ai4 with@ai-sdk/*0.0.x/1.x andollama-ai-provider1.x;ai6 with@ai-sdk/*3.x andollama-ai-provider-v22.x/3.x;ai7 with@ai-sdk/*4.x andollama-ai-provider-v24.x. A missing provider package’sMissingPeerDependencyError.installCommandnames the version for the installedaimajor (npm install @ai-sdk/openai@^4.0.0onai7; unchanged onai4).OllamaProviderloadsollama-ai-provider-v2onai6/7; that package needs zod 4, which the SDK does not support yet, so its install hint says so and Ollama stays onai4 for now.lousho doctorchecks provider packages against the installedaimajor and flags a mismatched pair (e.g.ai7 with@ai-sdk/openai1.x) with the version to install; a missing or unsupportedaigetsnpm install ai@^7.0.0.lousho init/npm create lousho-agentscaffoldai@^7.0.0with@ai-sdk/openai@^4.0.0/@ai-sdk/anthropic@^4.0.0for OpenAI and Anthropic, and keepai@^4.3.19for Ollama (zod 4) and OpenRouter (@ai-sdk/openai2+ defaults to the Responses API, not yet verified there). The hint ofresolveProvider()’s rare synchronous missing-peer error lists the command for eachaimajor. See Installation.lousho add:lousho add <name> [--registry <url-or-path>] [--dir <agent-dir>] [--yes] [--overwrite] [--dry-run]installs a tool, skill, channel, schedule or memory slot from a static JSON registry (an index plus one document per item that carries the file contents) into an agent directory as source you own;lousho add --listprints the index. The registry comes from--registryorLOUSHO_REGISTRY(there is no hosted registry yet). It prints the item’s permission manifest (hosts, env vars, filesystem, exec, whether its tools ask for approval) and the files first and asks for confirmation (--yesskips it; a non-interactive stdin without--yesrefuses;--dry-runwrites nothing). Paths must be relative, inside the folder of the item’s type and inside the agent directory (no.., absolute paths, drive letters, backslashes or symlink escapes), files and items have size caps, existing files need--overwrite, fetches time out and onlyhttp(s)and local paths are read; nothing from a registry is executed anddependenciesare only printed as annpm installline. New error codesLOUSHO_REGISTRY_UNREACHABLE,LOUSHO_REGISTRY_ITEM_NOT_FOUND,LOUSHO_REGISTRY_INVALID,LOUSHO_REGISTRY_UNSAFE_PATH,LOUSHO_REGISTRY_FILE_EXISTS. See docs/registry.md.- Checkpoint history for
KVCheckpointStoreand Agent Forge’s file store:KVCheckpointStore(andKVStore, with the newhistoryLimitoption) keeps the bounded per-session historymemoryStore()keeps, as one index key (<prefix><sessionId>#history) and one key per entry (<prefix><sessionId>#history/<id>) next to the unchanged latest-checkpoint key, soagent.fork(),compareTrajectories()and time travel work for Worker-deployed agents; a store written before this change still loads. A save now makes onegetand twoputs more (historyLimit: 0turns the history off), and two concurrent saves of one session can lose an index update (KV has no transactions). Agent Forge’sFileCheckpointStorereads a partially written history file as empty and writes its files atomically. The history contract suite now runs againstKVCheckpointStoretoo. See docs/durable-execution.md#checkpoint-history. - Hook outcomes: a
preToolCallhook may return{ deny: reason }(the call does not run; the model gets the samekind: 'denied'tool error as aneedsApprovaldeny, streams seetool.error, andonPermissionDecision/permission.decisionrecorddecision: 'deny'with the newhookfield andreason),{ result: value }(the call does not run;valueis its result) or{ input: args }(the call runs withargs, validated against the tool’s schema again; a mismatch is akind: 'validation'tool error naming the hook). ApostToolCallhook may return{ result: value }to replace the result the model sees. Pre-hooks run in registration order: the first deny or result skips the later ones, inputs chain. A replaced result is markedreplacedByHookon thetool.doneevent, theToolCallOutcome/tool-resultevent and the transcript’stoolmessagemetadata. Hooks still run first (after argument validation, before permission rules, tool guardrails andneedsApproval), so the approval sees the hook’s input; on a resumed approved call the pre-hooks run again and an{ input }that differs from the approved input is refused. Sub-agents inherit the outcomes. Hooks that return nothing type-check and behave as before;HookRegistry.runPreToolCall()now resolves to aPreToolCallDecisionandrunPostToolCall()to the name of the replacing hook (new typesPreToolCallOutcome,PostToolCallOutcome,PreToolCallDecision). A hook that throws still rejects the run. See docs/api-overview.md#hook-outcomes. lousho acp:lousho acp <spec.yaml|spec.json|agent-dir|agent.ts> [--model provider/model]serves an agent over the Agent Client Protocol (v1) on stdio, so Zed and other ACP editors can run it as an external agent; stdout carries only JSON-RPC lines (the agent’sconsole.loggoes to stderr). It implementsinitialize,session/new,session/prompt(text andresource_linkblocks) andsession/cancel, streamssession/updates (agent_message_chunk,tool_call,tool_call_update), askssession/request_permission(Allow / Reject) when a tool needs approval and streams the continuation, and maps finish reasons to stop reasons (max-stepstomax_turn_requests,budget-exceeded/lengthtomax_tokens,guardrailtorefusal, a cancel tocancelled). One ACP session is one SDK session. Anask_questionpause ends the turn with the question as the agent’s message; the next prompt answers it. A failed run answers a JSON-RPC error whosedata.codeis the SDK error code. The protocol core is exported asserveAcp(agent, { input, write, store? })(new typeServeAcpOptions), transport-independent. Not supported yet:session/load, the client’sfs/*andterminal/*methods, images, audio and embedded resources,planand thought chunks. See docs/acp.md.- Agent directories deploy and serve with their schedules and channels:
lousho build <agent-dir> --target=node-server(anddocker; the path may also be--agent) builds a directory into a server whose entry callsresolveAgentDir()andcreateDeployedServer(agent, { schedules, channels }), so the deployed process starts theschedules/and mounts thechannels/under/channelsand logs which it found. The code files are pre-bundled by the existing tsup step intodist/agent/**.js(one ESM build sharing one SDK copy;dist/is marked ESM) and the rest of the directory is copied, so nothing needs a TypeScript loader at run time; spec builds are unchanged.lousho dev <agent-dir>mounts the directory’s channels and starts its schedules, swapping both on hot reload (old schedules stopped first);--no-schedulesstarts none. The deploy runtime also exportscreateAgent,resolveAgentDirandstoreFromEnv. The Cloudflare Worker target is unchanged (P9). See docs/agent-directories.md#deploy-it-with-lousho-build. - Route handler:
createRouteHandler(agent, { basePath?, auth?, uiMessageStream? })returns{ GET, POST, handler }, Fetch handlers ((request: Request) => Promise<Response>) that serve the deployed session API underbasePath(default/api/agent; trailing slash accepted, other paths 404) from a Next.js App Routerapp/api/agent/[[...path]]/route.ts, SvelteKit+server.ts, Hono or Bun.serve, with no framework ornode:*import.authis a bearer token or a(request) => boolean | Promise<boolean>(default none: a public route needs one;GET /healthstays open).useLoushoAgent({ url, approvalsUrl })works against it (POST <basePath>with{ input, sessionId? },POST <basePath>/approvals/:id), anduiMessageStream: trueaddsPOST <basePath>/uiforuseChat.hasBearerTokeninsrc/server/fetchRoutes.tsis now exported for it. See docs/nextjs.md. - AI SDK UI stream:
toUIMessageStream(run)maps a run’s events to the Vercel AI SDK’s UI message stream chunks (start,start-step,text-start/text-delta/text-end,tool-input-start/tool-input-available/tool-output-available/tool-output-error,finish-step,error,finishwith the AI SDK finish reason), andtoUIMessageStreamResponse(run, init?)returns the SSEResponse(data: [DONE], headerx-vercel-ai-ui-message-stream: v1) for a route handler, souseChatcan render a Lousho run. An approval pause orask_questionis adata-lousho-approvalpart (approvalId,toolCallId,toolName,input,kind?,question?); usage and the run’s own finish reason are in thefinishchunk’smessageMetadata.fromUIMessages(messages, { lastUserOnly? })converts theUIMessage[]useChatposts (text, image and file parts; others ignored) to anAgentInput. Own structural chunk types (LoushoUIMessageChunk,UIMessageLike, …), noaiimport and nonode:*, so it also runs on Workers; exported from the package root (a dedicated subpath can follow). See docs/ai-sdk-ui.md. - Approval policies: a
needsApprovalfunction may return (or resolve to)'approve','deny','ask'or{ deny: reason }besides a boolean (trueis'ask',falseis'approve'; new typeApprovalOutcome), and gets a second argument{ toolName, toolCallId, sessionId?, messages }(new typeApprovalCheckContext). A deny does not pause: the call is not run, the model gets akind: 'denied'tool error with the reason, streams seetool.error, andonPermissionDecision/permission.decisionrecorddecision: 'deny'with the newreasonfield (norule); the audit entry is now reported once the call is decided (after tool guardrails) instead of before them. New helpersalways(),never()andonce({ per?: 'tool' | 'args' })(with typeApprovalPolicy):once()asks the first time a tool is called in a session and runs later calls once a human approved one (a rejection is not remembered;per: 'args'keys on the arguments’ hash). The memory is the approved call’stoolmessage (metadata.approval, set byresumeAfterApproval()and its streamed form), so it persists with sessions, checkpoints and approval snapshots and survives a resume in another process. Apermissionsdenyrule wins; analloworaskrule replaces the tool’s ask but not its deny (see Changed); the tool’s outcome applies when no rule matches. Existing boolean functions type-check and behave as before; a test assertingneedsApprovalwas called with exactly one argument now sees the context too. See docs/approvals.md#approve-deny-or-ask. - Approval continuations stream live:
POST /chat/:sessionId/approvals/:id(node server, Cloudflare Worker,lousho dev) now streams the continuation fromagent.approvals.streamResolve()/streamAnswer()instead of replaying it after the turn ends;createAgentRunner’sapprove()/reject()/answer()(React, Vue, Svelte) read that SSE stream event by event (anApprovalOutcomeJSON from an older server still works), andlousho chatprints the continuation as it streams. The UI reducer maps a streamedtool.errornamedToolRejectedErrorto arejectedtool call. A second pause arrives asapproval.requested. The approvals route has always answered with SSE, so no client opt-in was added. session.compact()andsession.clear():await session.compact({ strategy?, protectedTokens?, contextWindow?, signal? })compacts the session’s transcript now, whatever its size, with the given strategy, elseagent.session({ compaction })(new option, the value ofcreateAgent({ compaction })), else by pruning old tool results; it saves the result through the session’s store and resolves to{ messagesBefore, messagesAfter, tokensBefore, tokensAfter, strategy, error? }.clear()(which already existed and forgot the conversation) now emitscontext.cleared(newContextClearedEventin theAgentEventunion) and rejects withLOUSHO_SESSION_AWAITING_APPROVALwhen a durable turn waits on an approval; it keeps the session id. Newsession.on(listener)receivescompaction.start/compaction.done(which gain an optionaltrigger: 'manual') andcontext.cleared. Both reject with the newLOUSHO_SESSION_BUSYwhile a turn is in flight;compact()also withLOUSHO_SESSION_TURN_PENDINGfor an interrupted durable turn.lousho chatgains/compactand/clear. See docs/compaction.md#compacting-a-session.- Discord channel:
discordChannel({ publicKey, applicationId, botToken?, name?, fetch? })serves Discord’s HTTP Interactions endpoint throughmountChannels()(Web Crypto andfetchonly, Worker-safe, no gateway, no new dependency). It verifiesX-Signature-Ed25519/X-Signature-Timestamp(Ed25519 overtimestamp + body, 401 otherwise) and answersPINGwithPONG. A slash command (/ask prompt:<text>) is acknowledged at once with a deferred response; its session is keyed on guild + channel (+ thread), and the reply edits the original response, with text over 2000 characters continued in follow-up messages. A tool approval is posted with Approve / Deny buttons and resolved by the click; anask_questionis answered by the next/askin the channel. See docs/channels.md#discord. - Streaming resume after an approval:
streamResumeAfterApproval(decision, approvalStore, toolRegistry, provider, options?, checkpointStore?)takesresumeAfterApproval()’s arguments and returns anAgentRunwhoseresultis whatresumeAfterApproval()returns. Its events arerun.start, the decided call’stool.start/tool.done(tool.errorfor a rejection), then the continuation’s events as in a freshstream()run; a further pause ends it withapproval.requested. Abort,enqueue()andsteer()work as on any run, and the approval can be resolved in another process.createAgent()agents getagent.approvals.streamResolve(decision, { signal })andstreamAnswer({ id, answer }, { signal })(a pause made in a session continues in it,run.doneafter the transcript is saved; a dynamic agent keeps the model the paused run used). Also new: theResumeRequesttype andresumeRequest(request)(resumeAfterApproval()with one object argument). Additive:resolve(),answer()andresumeAfterApproval()are unchanged. See docs/streaming.md#streaming-after-an-approval. - Credential broker:
createCredentialBroker({ rules, allow?, allowPrivate?, port?, host?, pathFormScheme? })starts a host-side HTTP forward proxy (Node-only, on an ephemeral127.0.0.1port by default) and resolves to{ url, env, baseUrl(host), close() }.rulesmap a host (exact or*.suffix) to headers to inject, as strings or per-request functions, so a command the model runs can call an authenticated API without the token entering its environment: passbroker.env(HTTP_PROXY/HTTPS_PROXY/NO_PROXY, both cases) toNodeWorkspaceorSandboxShell’senv. Hosts outside the rules andallowget a 403 without a connection; hosts resolving to loopback, link-local or private addresses are refused unless inallowPrivate; a clientAuthorizationheader for a brokered host is replaced; hop-by-hop headers are dropped. Injection covers plain-HTTP requests and the/__broker/<host>/<path>form (forwarded tohttps://<host>/<path>, returned bybaseUrl(host)); HTTPSCONNECTtunnels are allowlist-checked and passed through untouched (no TLS interception).SubprocessSandbox’snetwork: { allow }still fails closed: routing containers through the broker is a separate follow-up. New typesCredentialBroker,CredentialBrokerOptions,BrokerHeaderValue. See docs/workspace-tools.md#credential-broker. - Memory in agent directories:
memory/*.ts|js|mjsfiles default-export a memory slot (defineMemory(), or the same options without aname; name = file name unless set). Unlike schedules and channels they are part of the agent:loadAgentDir()passes them tocreateAgent({ memory }),resolveAgentDir()lists them inmanifest.memory, and amemoryoverride is merged by name (the override wins a clash). A bad file fails with the newLOUSHO_MEMORY_INVALIDnaming the file. A directory withoutmemory/is unchanged. See docs/agent-directories.md#memory. - Channels in agent directories:
channels/*.ts|js|mjsfiles default-export a channel (defineChannel()or a built-in factory; name = file name unless set);resolveAgentDir()returns them aschannelsandmanifest.channels, and a file that exports no channel fails with the newLOUSHO_CHANNEL_INVALIDnaming the file.createDeployedServer(agent, { channels })mounts them under/channelsnext to the chat routes.loadSchedules()andloadChannels()share one loader (schedule files that do not export a schedule now throw anSDKErrorwithLOUSHO_SCHEDULE_INVALID, same message).lousho devand the Cloudflare Worker target do not mount them yet. See docs/agent-directories.md#channels. serveMcpannotations:defineTool({ annotations })(readOnlyHint,destructiveHint,idempotentHint,openWorldHint,title; stored asmetadata.mcp.annotations) is sent intools/listverbatim, and a tool withneedsApprovalis advertisedreadOnlyHint: false, destructiveHint: true(never read-only). An unannotated tool sends none. A Lousho agent consuming the server therefore runs read-only tools without an approval pause, pauses forneedsApprovalones and keeps asking for unannotated ones. The built-inread_file,list_dir,glob,grep,todo_read,current_dateandday_nametools are marked read-only. See docs/configuration.md#annotations.- Svelte store: new
@lousho/build-ai-agent/sveltesubpath withloushoAgent(source, options?). It returns a Svelte store (subscribe(run) => unsubscribe, so$agentworks in Svelte 4 and 5) whose value is the same state as the React hook and the Vue composable (messages,status,pendingApproval,error,usage,lastEvent), plussend(),stop(),approve(),reject(),answer()andreset(). The run in flight is aborted bystop()and when the last subscriber unsubscribes. The store contract is implemented by hand: the entry imports nothing fromsvelte, so there is no new peer dependency. See docs/svelte.md. - Per-run dynamic config:
createAgent()’smodel,instructions/promptandtoolseach also take a function of the run,(ctx) => value | Promise<value>(new typesPerRun<T>andRunConfigContext={ sessionId?, input, metadata? }), resolved once at the start of each run and of each session turn, before the first model call.fallbackModels,retry,projectInstructions, memory, MCP tools, sub-agents, permissions, approvals and guardrails apply to the resolved values; a dynamic agent used as a sub-agent resolves with the task prompt asinput.session.send()/session.stream()gain themetadataoption (send()/stream()already had it, and now pass it to these functions too). A function that throws fails the run with the newLOUSHO_CONFIG_RESOLVER_FAILED(fieldnames the option,causeis the error); a session keeps its transcript. A run paused for approval stores itsctxand resolved model in the approval snapshot (agent.metadata.loushoRunConfig): resuming it uses that model and re-resolves the tools with the samectx; a crash resume from a checkpoint resolves withinput: []. Static options behave and type as before.SessionRunner/SessionStreamRunnertake an optional fourthcallargument (new typeSessionTurnCall). See docs/api-overview.md#dynamic-config. - Vue composable: new
@lousho/build-ai-agent/vuesubpath withuseLoushoAgent(source, options?)for Vue 3. It takes the same sources and options as the React hook (either may be aref, read when a turn starts) and returnsmessages,status,pendingApproval,error,usageandlastEventas read-only refs, plussend(),stop(),approve(),reject(),answer()and a newreset()(aborts, forgets the in-process session, clears the chat). The run in flight is aborted bystop()and when the owning scope is disposed (onScopeDispose: component unmount,effectScope().stop()).vue(^3) is an optional peer dependency, loaded by no other entry. To share the logic, the reducer and the stream parser moved fromsrc/react/to a framework-neutralsrc/ui/, together with the run logic extracted from the React hook (createAgentRunner()); the./reactexports are unchanged, and the reducer gains an additiveui.resetaction. See docs/vue.md. - One flag parser for the
loushoCLI: every command (dev,chat,eval,build,mcp,doctor,studio;initalready did) parses its flags withnode:utilparseArgsin strict mode throughsrc/cli/args.ts.--flag valueand--flag=valuework everywhere,--ends the flags,-h/--helpprints the usage and exits 0, and an unknown flag, a flag without its value or an extra argument fails withLOUSHO_CONFIG_INVALIDand the command’s usage as the hint. Behaviour change (migration):dev,studio,mcp,buildanddoctorused to ignore unknown flags, and a flag missing its value could take the next flag or a prefix match (--portx 1read as--port); they now fail with exit 1 and the usage line, so remove typos from scripts. A value that starts with-must be written--flag=-x(a bare--flag -xis a missing value);--portmust be an integer from 0 to 65535 fordev,studioandmcp;dev,mcpanddoctorreject a second path;studio --prod --devis rejected instead of preferring--prod.lousho devandlousho studioparsing moved frombin/lousho.jsintosrc/cli/dev.ts/src/cli/studio.ts(parseDevArgs,runDev,parseStudioArgs,runStudio). See docs/cli.md. sqliteMemory(store, { maxItems? })(exported from@lousho/build-ai-agent/sqlite) keepsdefineMemoryslots in the agent’sSqliteStorefile: a newmemory_itemstable (migration 3, one JSON array per scope key, with the same serialization,maxItemsand query rules asfileMemory). An existing database gains the table on open and keeps its sessions and checkpoints. The memory provider contract tests now run against the in-memory, file and SQLite providers. See docs/memory.md#sqlite.- Slack channel:
slackChannel({ signingSecret, botToken, name?, fetch? })(new export, with typesSlackChannelOptions,SlackChannelEvent,SlackThread) serves a Slack app’s Events API and interactivity requests throughmountChannels(). It verifies thev0request signature with Web Crypto (nonode:*import; the timestamp and header checks are shared withverifySlackSignature()), answers theurl_verificationchallenge, and acknowledges every request before the turn runs. Each Slack thread is one session (team + channel + thread rootts): a mention starts or continues it, and later messages in a thread the bot was mentioned in continue it. Retries (X-Slack-Retry-Num) and bot messages are skipped. Replies go to the thread withchat.postMessageoverfetch; a tool approval is posted as Approve / Deny buttons whose click resumes the session, and anask_questionas text answered by the next thread message. The channel contract gains two additive hooks for this:parse(req, respond)may callrespondto answer the request before the turn runs, and may return{ decision }(new typeChannelDecision;ChannelApprovalDecisionnow lives indefineChannel.ts, same public export) to resolve a pause instead of starting a turn. See docs/channels.md#slack. - Remote sub-agents:
remoteAgent({ url, auth?, name?, description?, headers?, fetch? })(new export, with typesRemoteAgentOptionsandRemoteSubagent) makes a deployed agent usable wherever a local sub-agent is: increateAgent({ subagents })records andSubagentCatalog.resolve(), delegated to by thetasktool and bybackground: truetasks. Each task opens a fresh session on the remote agent overPOST <url>/chat(bearerauth: a string or a function, called per task), reads the SSE stream to the end and returns the remote agent’s final text; the lead run’s abort signal aborts the request. Failures (network, 401 or other non-2xx, malformed stream, remote run error) are structured tool errors with the new codeLOUSHO_REMOTE_AGENT_FAILED, and the token never appears in errors or events; a remote run that pauses for approval fails withLOUSHO_SESSION_AWAITING_APPROVALnaming the remote session (proxying approvals is a follow-up). Worker-safe (fetchonly). See docs/sub-agents.md#remote-sub-agents. - Eval against a deployed agent:
lousho eval --url <baseUrl> [--token <bearer>](token also fromLOUSHO_EVAL_TOKEN) runs every case of the trajectory eval files against a deployment (node server or Cloudflare Worker) instead of the in-process agent: one remote session per case overPOST /chat { sessionId, input }, the SSE stream read torun.doneand turned into the usual result (tool calls, reply, finish reason, steps, usage), so checks, scorers,t.judge(), the summary and--junitwork unchanged. A check that needs data the stream lacks (maxTokenswithout usage) fails and names what is missing. Programmatic equivalent:defineEval({ target: remoteTarget({ url, auth?, fetch? }) })(newremoteTarget(),EvalTarget;agentis now optional when atargetis given, andAgentSourcealso accepts any{ send() }).--urlwith--record/--replay/--driftis rejected withLOUSHO_CONFIG_CONFLICTING_OPTIONS; an unreachable deployment, a non-2xx answer or a truncated stream fails the case with the newLOUSHO_REMOTE_REQUEST_FAILED, and 401 withLOUSHO_REMOTE_UNAUTHORIZED. The token never reaches output or reports. See docs/evals.md#run-evals-against-a-deployment. - Schedules:
defineSchedule({ cron, timezone?, name?, prompt | run })declares a cron schedule (apromptsent to the agent as a new turn, orrun({ agent, firedAt, name })); an invalid cron expression, or not exactly one ofprompt/run, throws the newLOUSHO_SCHEDULE_INVALIDat definition time. An agent directory’sschedules/*.ts|js|mjsfiles default-export one each (name = file name unless set);resolveAgentDir()returns them asschedulesandmanifest.schedules.startSchedules(agent, schedules, { now?, setTimer?, onError? })runs them with injectable clock and timers, isolates errors, skips a fire while the previous one runs and returnsstop();createDeployedServer(agent, { schedules })starts them on listen and stops them on close. The Cloudflare Worker target is not covered yet. See docs/schedules.md. - Channels:
defineChannel({ name, verify?, parse, reply, onApproval?, sessionId?, stream? })describes one surface:verifyauthenticates a request (falseor{ ok: false }answers 401),parsemaps it to{ sessionKey, input, metadata?, replyTo }(ornullto acknowledge it without a turn),replydelivers the agent’s reply (withstream: true, also partial text as the model writes) andonApprovalrenders a pause (default: a text prompt throughreply).mountChannels(agent, channels, { store, basePath })returns a framework-free(req, res)handler, in the style of the/chatroutes, that servesPOST <basePath>/<name>(verify -> parse -> a turn in session`${name}:${sessionKey}`-> reply; turns of one session run one at a time) andPOST <basePath>/<name>/approvals/<id>({ approved, note? }or{ answer });handler.resolveApproval()decides a pause from code (e.g. a button callback) and replies through the same channel. Built in:httpChannel()(JSON{ sessionKey, input }in,{ sessionId, text, finishReason, approval? }out) andwebhookChannel({ secret })(WebhookTriggerAdapter’s behaviour; the adapter now delegates its auth and parsing to it, unchanged for callers). Slack and Discord channels are separate follow-ups. See docs/channels.md. - Cloudflare Worker parity: the
cloudflare-workertarget now serves the same API as the node server:POST /chat { sessionId, input }streamed as SSE, history per session,GET /chat/:sessionId,POST /chat/:sessionId/approvals/:idandGET /health; the deprecatedPOST /chat { message, sessionId? }still works and still checkpoints undersessionId.LOUSHO_API_TOKEN(a Worker secret:wrangler secret put LOUSHO_API_TOKEN) makes every route except/healthrequireAuthorization: Bearer <token>(constant-time compare). NewKVStore(kvBinding, { prefix?, ttl? })(src/deploy/kvStore.ts) is anAgentStoreon a Workers KV namespace:sessions/<id>(transcript JSON, bytes as{ "$bytes" }),checkpoints/<id>(KVCheckpointStore, which gains an optional TTL) andapprovals/<id>, with optional per-kind TTLs; the Worker builds it from the existingAGENT_CHECKPOINTSbinding, and keeps sessions in the isolate’s memory without one. An approval paused on one request can be decided by another request on a new isolate. The routes are now Fetch-native (src/server/fetchRoutes.ts:Requestin,Responseand aReadableStreamSSE body out, bearer auth with Web Crypto);src/server/chatRoutes.tsadapts them tonode:httpforlousho devand the node server, andsrc/server/bearerAuth.tsis gone. The built Worker runs acreateAgent()agent, so the build swaps its Node-only imports forsrc/deploy/shims/node.worker.ts, and thenode:leak check now also catches bare builtin specifiers; the bundle grows to about 1.7 MB. The generatedwrangler.tomldocuments the KV binding and both secrets. Thewrangler devtest now streams a session turn through workerd with a KV binding and a token. See docs/deployment.md#bindings-sessions-and-the-api-on-workers. - Steering:
run.steer(input)onAgentRun(fromagent.stream(),session.stream()andAgentExecutor.stream()), andInputQueue.steer(input)for non-streaming callers, redirect a running run to new user input. If a model call is in flight and has not emitted text or tool calls yet, it is aborted with a per-call signal (not the run’s), its partial output is discarded, the input is appended as a user message and the model is called again (applied: 'immediate'; that step ends withstep.done'steered'and counts towardmaxSteps; a provider that ignores the signal is not waited for). Once the model has emitted output, the input waits for the next safe point likeenqueue()('queued'); after the run has finished,appliedisfalse. Tool calls already running finish and keep their results; calls of that turn not started yet get the usual “cancelled before it ran” result. It returns{ id, applied, joined }(new typeSteerResult;joinedis a promise of whether the input reached the transcript). New eventinput.steered{ id, text, mode: 'immediate' | 'queued' }(InputSteeredEvent, additive, schema v1), followed by the existinginput.applied. With checkpointing, the input is checkpointed when it is taken, before the model is called again, and the discarded partial turn is never checkpointed.agent.session({ turnPolicy: 'steer' })makes asend()/stream()made while a turn runs steer that turn ('queue'and'wait'are unchanged).AgentRungains the requiredsteer()member, so a hand-writtenAgentRunobject must add it. See docs/streaming.md#steering and docs/sessions.md. aiv6/v7stream(): the built-in providers’stream()(and soagent.stream()) now works onaiv6 and v7 as well as v4, through a compatibility layer (streamCompat()): the request is mapped as forgenerate(), and either major’sfullStreamis read into the sameStreamChunks: text deltas, tool calls (the whole call, or one assembled fromtool-input-start/-delta/-endwhen the model sends none), and afinishchunk with the finish reason and usage, including cached and reasoning tokens. Anerrorpart now rejects the stream with its error on both majors (on v4 the step used to end with finish reasonerrorand the partial text), anabortpart with the signal’s reason; reasoning deltas are dropped until a reasoning chunk type exists.StreamChunk/StreamResultare unchanged. The protectedAiSdkProvider.convertMessages()now returns our structuralAiSdkMessage[]instead ofaiv4’sCoreMessage[](which v6/v7 do not export) and is marked deprecated; an override returningCoreMessage[]still compiles. Theai/@ai-sdk/*peer ranges still name v4. Tested on the realaiv7 (MockLanguageModelV4), withagent.stream()events asserted by one helper on v4 and v7. See docs/providers.md#vercel-ai-sdk-versions.spec.policyis enforced:specToAgent()compiles the policy block intocreateAgent()options through the newcompilePolicy().requiresApproval(trueor a list of tool names) becomespermissions: [ask(...)];guardrails(max-length,secret-scan,regex,deny-topics,llm-judge, by name or{ name, ...options, on }) become input and output guardrails;limits,askQuestionandcompactionpass through.loadSpec()validates the known fields (an unknown guardrail name fails with the names available and a did-you-mean; unknown policy keys are still kept for the generators), andlousho doctor <spec>prints one line per policy block and flags unknown guardrail names. Behaviour change:requiresApproval: truenow actually pauses tool calls (finishReason: 'awaiting-approval'); before, a spec that set it ran its tools without asking, and a spec with a guardrail name outside the built-ins (for examplediff-size-cap) now fails validation. See docs/configuration.md#policy-policy.aiv6/v7generate(): the built-in providers’generate()now works onaiv6 and v7 as well as v4, through a compatibility layer that detects the installed major (v5+ exportsstepCountIs). On v6/v7 it sends messages asModelMessages (tool calls withinput, tool results asoutput,mediaType),maxTokensasmaxOutputTokens, one step asstopWhen: stepCountIs(1), tools asinputSchemawithoutexecuteandresponseFormatas a JSON-modeoutput, and reads usage frominputTokens/outputTokens/totalTokens(cached and reasoning tokens from their details) into the sameGenerateResult.LLMProvider,GenerateOptionsandGenerateResultare unchanged, and v4 behaves as before.stream()on v6/v7 throws an error until that is supported; theaiand@ai-sdk/*peer ranges still name v4. Tested against the realaiv7 (MockLanguageModelV4) next to the v4 contract tests. See docs/providers.md#vercel-ai-sdk-versions.- Queued follow-up input:
run.enqueue(input)onAgentRun(fromagent.stream(),session.stream()andAgentExecutor.stream()) adds user input to a run that is still going; it joins the transcript at the next safe point (after the current step’s tool results, before the next model call) and the run continues as if the user had typed it, with one more step when it arrives during the final reply. It returns{ id, applied }:appliedisfalsewhen the run had already finished (send the input as a new turn, e.g.session.send()), otherwise a promise of whether it was applied. New eventsinput.queued{ id, text }andinput.applied{ id, step }(additive, schema v1). Non-streaming callers pass anInputQueue(new export) asExecuteOptions.inputQueueand call itspush(input). With checkpointing, a waiting input is saved right away at the end of the checkpoint (the queued-input slot), so a crash does not lose it.agent.session({ turnPolicy: 'queue' })makes asend()/stream()made while a turn runs (or waits to start) join that turn instead of waiting for its own ('wait', the default, keeps today’s behaviour).AgentRungains the requiredenqueue()member, so a hand-writtenAgentRunobject must add it. Steering (aborting the in-flight model call to redirect) is a separate follow-up. See docs/streaming.md#queued-input and docs/sessions.md. - Input and output guardrails:
guardrails?: { input?, output?, tools?, onTripped? }oncreateAgent()andExecuteOptions(new typeAgentGuardrails). A guardrail is{ name, check(ctx) }(new typeIoGuardrail;ctxis{ kind: 'input' | 'output' | 'tool', text, messages, toolName?, args?, signal? }) returning{ ok: true }or{ ok: false, reason, action?: 'block' | 'rewrite', replacement? }. Input guardrails run on each new user message before the first model call; output guardrails on the final reply (in a streamed run, on every step’s text, before itstext.done); tool guardrails on a call’s arguments after the permission rules (skipped ondeny) and beforeneedsApproval. A block ends the run with the newfinishReason: 'guardrail'andresult.guardrail({ name, kind, reason, toolName? }, new typeGuardrailTrip), with no model call for an input block;onTripped: 'throw'rejects with the newGuardrailError(LOUSHO_GUARDRAIL_TRIPPED) instead. A rewrite replaces the text.stream()emits the newguardrail.tripped(beforerun.done) andguardrail.rewroteevents. Sub-agents run their parent’s guardrails, then their own. Built-ins:maxLengthGuardrail({ maxChars }),regexGuardrail({ name, pattern?, action?, replacement? })(defaults to the secret-scan patterns, now exported asSECRET_PATTERNS),denyTopicsGuardrail({ topics })andllmJudgeGuardrail({ model, instruction }). The patch guardrails (runGuardrails(),secretScanGuardrail, …) are unchanged; the new types are namedIoGuardrail*becauseGuardrailandGuardrailResultare theirs.spec.policy.guardrailsin agent spec files is not wired yet. See docs/guardrails.md#input-and-output-guardrails. - Deployed
/chatupgrade: thenode-serveranddockertargets (dist/server.js) now serve thelousho devprotocol:POST /chat { sessionId, input }streams the turn as SSE (data: <AgentEvent JSON>, thenevent: done) with history kept per session,GET /chat/:sessionId,POST /chat/:sessionId/approvals/:id({ approved, note? }or{ answer }) andGET /health; the single-turnPOST /chat { message }still works (now with aDeprecation: trueheader). The routes are one shared module,src/server/chatRoutes.ts, used bylousho devand the deployed runtime.LOUSHO_STORE(memory, the default, orsqlite:<path>, Node >= 22) picks where sessions live. Bearer auth: setLOUSHO_API_TOKEN(or pass{ auth: { token } }as the new optional third argument ofadapter.scaffold(); the variable wins) and every route except/healthrequiresAuthorization: Bearer <token>(constant-time compare,401JSON otherwise); treat it as required for anything not on localhost. Thedockerimage is now based onnode:22-slim(wasnode:20-slim) fornode:sqlite.specToAgent(spec, { store })takes an optionalstore. The Cloudflare Worker target is unchanged (sessions over KV and SSE there are a separate follow-up). See docs/deployment.md#http-api. lousho chat: a terminal REPL for an agent.lousho chat <spec|dir|module> [--model provider/model] [--session id] [--store sqlite:<file>]loads the target likelousho devand reads one turn per line throughagent.session({ id, store }).stream(): text deltas as they arrive, each tool call as a dim[tool_name] {args}line followed by-> result,Approve <tool>(args)? [y/N]for a tool that needs approval, a numbered prompt with free text for anask_questioncall, and[usage]tokens and cost after each turn. Slash commands:/new,/model <provider/model>(rebuilds the agent, the session continues),/history,/quit. SDK errors print with their[LOUSHO_...]code and fix. The loop isrunChatRepl({ input, output, createAgent })insrc/cli/chatRepl.ts(testable with scripted lines and amockModelagent);loadTarget()is now exported fromsrc/cli/devReload.ts. See docs/cli.md#lousho-chat.- Memory slots:
defineMemory({ name, description?, scope, provider, recall?, expose? })(new export) defines a named long-term memory, andcreateAgent({ memory: [slot] })wires it in. On the first model call of every run (send(),stream(), each session turn), apreGeneratehook recalls the slot’s newestrecall.maxItems(default 10) items into the system prompt as a<memory name="...">block (recall.query: 'last-input'passes the last user message as the provider query;recall.onSessionStart: falseturns recall off). The model getsremember_<name>({ text })andrecall_<name>({ query?, limit? })tools (expose: { remember?, recall? }, both on by default).scopeis'global','session'(keyed byagent.session({ id })’s id orsend()’ssessionId) or a function of{ sessionId, metadata }; the newSendOptions.metadatafeeds it. Providers implementMemoryProvider(list/add/remove); built in areinMemoryMemory()andfileMemory({ dir })(one JSON file per scope key), both bounded bymaxItems(default 1000, oldest dropped). See docs/memory.md. - Budgets:
limits?: { maxTokens?, maxInputTokens?, maxOutputTokens?, maxCostUsd?, maxDurationMs?, maxSteps?, onExceeded? }oncreateAgent()andExecuteOptions(new typeRunLimits). Limits are checked before every model call (so after every tool batch) and after a model call that asks for tools, andmaxDurationMsaborts an in-flight model or tool call through the run’s signal. A tripped limit ends the run with the newfinishReason: 'budget-exceeded'andresult.budget: { limit, value, max, scope }(BudgetExceeded); tool calls of that step get a cancelled result and the run is checkpointed as finished, like'max-steps'.stream()emits the new typedbudget.exceededevent (BudgetExceededEvent) beforerun.done(additive, the event schema version stays 1).onExceeded: 'throw'rejects with the newBudgetExceededError(LOUSHO_BUDGET_EXCEEDED, no longer reserved) instead.limits.maxStepsis an alias ofmaxSteps(the stricter wins; alone it replaces the default of 10). Sub-agents’ usage counts toward their lead’s budget.agent.session({ id, limits })applies limits across a session’s turns: what the turns spent is saved asmetadata.sessionUsageon the transcript’s last message (new typesBudgetSpent,SessionBudget,SessionTurnOptions;ExecuteOptions.sessionBudgetcarries it to the run), somaxCostUsdper session holds across processes. See docs/configuration.md#budgets. - Stateful streaming dev chat:
lousho devserves one session per browser tab.POST /chatwith{ sessionId, input }streams the turn as SSE (data: <AgentEvent JSON>per event, thenevent: done) throughagent.session({ id, store }).stream(input)over an in-processmemoryStore()(or the agent’s ownstore, when a module’screateAgent()options oroverridesset one);GET /chat/:sessionIdreturns the transcript and the pending approval;POST /chat/:sessionId/approvals/:idwith{ approved, note? }or{ answer }decides an approval or answers a question and streams the continuation (rebuilt from the continued run’s result, sinceagent.approvals.resolve()is not streamed). The chat page renders text deltas, tool calls with arguments and results, Approve / Reject and question buttons, errors andrun.doneusage and cost, with a “New session” button and the id kept insessionStorage. Sessions survive a hot reload and continue on the new agent. The{ message }body ofPOST /chatstill works and is deprecated (no session, JSONExecutionResult,Deprecation: trueheader). See docs/cli.md#lousho-dev and docs/streaming.md. - Agent Forge History tab: the bottom drawer’s new History tab lists the loaded agent’s run steps (step, status, finish reason, tool calls, tokens, cost). “Edit and replay from here” appends a user message or edits one of the step’s tool results, forks the run at that step through
POST /runs/:id/fork, and shows the fork next to the original as a side-by-side trajectory with the diverging turn and the drift entries highlighted, refreshed when the fork finishes. See docs/agent-forge.md#the-history-tab. lousho devfor agent directories and TS agents, with hot reload:lousho dev <path>takes a spec file (as before), an agent directory (loadAgentDir()) or a.ts/.jsmodule whose default (oragent) export is aSimpleAgentor acreateAgent()options object, detected by path type and extension (a bad path, extension or export fails withLOUSHO_CONFIG_INVALID/LOUSHO_SPEC_UNSUPPORTED_FORMAT). It watches the directory tree, or the module and its relative imports, and rebuilds the agent about 100 ms after a change with a?t=<time>cache-busted import, so edited tools reload; the new agent is built andready()before it replaces the old one, which is thenclose()d. A failed rebuild keeps the last good agent and reports the error in the console, in a banner on the chat page and in the newGET /dev/status({ kind, path, reloads, error }).startDevServer(path, port?, host?, { overrides?, debounceMs? })gains the options argument. Spec-file behaviour is unchanged; the chat is not streamed or per-tab. See docs/cli.md#lousho-dev and docs/agent-directories.md#run-it-with-lousho-dev.- Multimodal input through the public API:
agent.send()/agent.stream(),session.send()/stream(),t.send()in evals anduseLoushoAgent().send()take the new exportedAgentInput(string | ContentPart[] | Message[]): a string or parts become one user message, aMessage[]is passed through (in a session it is appended to the transcript). Checkpoints,agent.resume()and queued input hold the parts like any message. The React user bubble shows the text with an[image]/[file]marker per non-text part.SqliteStoresessions and checkpoints saveUint8Arrayparts as{ "$bytes": "<base64>" }, asFileSessionStoredoes. Finishes the earlier change (its note thatagent.send()/session.send()take no parts is out of date). See docs/providers.md#multimodal-input. - Built-in
ask_questiontool:createAgent({ askQuestion: true })(off by default) oraskQuestionTool()gives the agentask_question({ question, options?, allowFreeText? }). A call pauses the run through the approval mechanism, so it waits durably like any approval (sessions,memoryStore()/SqliteStore, a restart between question and answer). The pending record gains optionalkind: 'question'andquestion: { text, options?, allowFreeText? }(new typesApprovalKind,ApprovalQuestion;describeApproval()andASK_QUESTION_TOOL_NAMEare exported), and so do theapproval.requestedevent and the React hook’spendingApproval. The newagent.approvals.answer({ id, answer })(the same asresolve({ id, approved: true, note: answer })) continues the run with{ answer, option? }as the tool result (option: index of the matching option);approved: falsegives the model akind: 'rejected'error saying the user declined to answer.useLoushoAgent()getsanswer(text). Theapprovecallback may now return a string (ApproveToolCallreturnsboolean | string), which approves with that note, so code can answer questions. A tool run after an approval sees the decision’s note asctx.approval.note(new optionalToolExecutionContext.approval). See docs/approvals.md “Asking the user a question”. - Agent Forge time travel API: Agent Forge’s
FileCheckpointStorekeeps the bounded per-session checkpoint history (history(),historyLimitoption,delete({ keepHistory })) with the same semantics asLocalStorageCheckpointStore, checked by the SDK’s history contract suite. The runtime control server gainsGET /runs/:id/history(each step’s status, save time, finish reason, tool calls, tokens and cost),POST /runs/:id/fork({ fromStep, patch?: { toolResult?, appendInput?, businessState? } }, forks withAgentExecutor.fork()and starts the fork as a run of its own) andGET /runs/compare?a=&b=(compareTrajectories()). Fixed on the way: Agent Forge’s chat transcript compiles against multimodalMessage.contentagain, keeping each message’s text. See docs/agent-forge.md#time-travel. - Fork and replay:
AgentExecutor.fork({ sessionId, fromStep, newSessionId?, checkpointStore, patch? })takes the newest entry offromStepin the session’s checkpoint history, appliespatch(messages(messages),businessState,toolResult: { toolCallId, result }replaced in place so the transcript stays provider-valid,appendInputqueued as a user message) and saves it as the'in-progress'checkpoint ofnewSessionId(default<sessionId>.fork-<n>), leaving the original session untouched; it returns{ sessionId, step, checkpoint }, andexecute({ sessionId, checkpointStore, input: [] })continues the fork. A missing step throws the newLOUSHO_CHECKPOINT_NOT_FOUNDcode.createAgent()agents gainagent.fork(sessionId, { fromStep, newSessionId?, patch? })overstore.checkpoints(resume withagent.resume()).compareTrajectories(a, b)compares two checkpoints or transcripts step by step: each run’s steps (text, tool calls and results), the first diverging step and thelousho eval --driftdiff. New typesForkOptions,ForkPatch,ForkResult,TrajectoryComparison,TrajectoryStepandDriftEntry. See docs/durable-execution.md#fork-and-replay. - Multimodal message parts:
Message.contentis nowstring | ContentPart[], where aContentPartis{ type: 'text', text },{ type: 'image', image, mimeType? }(anhttp(s)URL, adata:URL or aUint8Array) or{ type: 'file', data, mimeType, filename? }(new typesContentPart,TextContentPart,ImageContentPart,FileContentPart). The built-in providers map the parts ofusermessages to theaiv4 user-content parts: images go to the model with all four (theaiSDK downloads an image URL first for Anthropic and Ollama); file parts become a[file <name> (<mimeType>) not sent]text note with a one-timeconsole.warn, since the pinned peers (@ai-sdk/*0.0.x,ollama-ai-provider) cannot send files (a subclass setsacceptsFileParts = trueto send them).system,assistantandtoolmessages are sent as their text. The newtextOf(message)returns a message’s text (the string, or its text parts joined), and is whatestimateTokens()(each image or file part counts 1,000 tokens), compaction,recordReplay()fingerprints (cassette messages gain an optionalattachmentslist: each image or file as its URL or a digest of its bytes),mockModel(),MockLLMProvider, OpenTelemetry content attributes and the React reducer (ui.sendtakes parts too) now read.FileSessionStoresavesUint8Arrays as{ "$bytes": "<base64>" }and loads them back. Pass multimodal messages asAgentExecutor.execute({ input: Message[] });agent.send()/session.send()taking parts is a separate follow-up. See docs/providers.md#multimodal-input. - Declarative permission policies:
permissions?: PermissionRule[]oncreateAgent(),ExecuteOptionsandresumeAfterApproval()options. A rule is{ tool: string | string[] | RegExp | '*', when?: (args, { toolName, toolCallId, sessionId }) => boolean | Promise<boolean>, action: 'allow' | 'deny' | 'ask', reason? }; rules are checked in order for each tool call (after argument validation andpreToolCallhooks, beforeneedsApproval) and the first match decides:allowruns the call without approval even whenneedsApprovalwould ask,denygives the model a tool error with the newkind: 'denied'(ToolDeniedError, plusreason) and streamstool.error,askpauses for approval (or asksapprove). No match keeps today’s behaviour. New helpersallow(tools),deny(tools, reason?),ask(tools)and typesPermissionRule,PermissionAction,PermissionToolMatcher,PermissionContext,PermissionDecision,PermissionDecisionEntry,PermissionOptions. Audit log:onPermissionDecision(entry)gets{ toolName, toolCallId, decision: 'allow' | 'deny' | 'ask' | 'default', rule?: { index, reason? }, args?, at }per call (argsleft out underredactContent), and streams get the same entry as the new typedpermission.decisionevent (PermissionDecisionEvent; additive, the event schema version stays 1). Neither is produced unlesspermissionsoronPermissionDecisionis set. Sub-agents inherit the lead’s rules (checked before their own) and itsonPermissionDecision. See docs/approvals.md#permission-policies. - Compaction events and the
compactionoption:agent.stream(),session.stream()andAgentExecutor.stream()emit two new typed events whenever the compaction hook compacts a request:compaction.start(strategy,tokensBefore,contextWindow,thresholdTokens) before the work andcompaction.done(strategy,tokensBefore,tokensAfter,prunedToolCallIds,summary?,error?: { message }) after it, inside the step and before the model call;erroris set when the strategy failed and the hook fell back. Additive: the event schema version stays 1.GenerateHookContextgains the optionalemit(event)(set in streamed runs only) that the hook uses.createAgent({ compaction })takestrue(the prune hook with its defaults) or{ strategy?, thresholdPercent?, contextWindow?, protectedTokens?, summarizer? }, wheresummarizer(a'provider/model'string or anLLMProvider) selectstwoPhaseStrategy()with that model;summarizertogether withstrategyis aConfigurationError.createAgent({ hooks })(new) takes anyAgentHook[], run before the compaction hook. See docs/compaction.md. - Connect MCP servers from config:
connectMcp(servers, { lazy?, onError?, logger? })(@lousho/build-ai-agent/mcpand the root) connects stdio (command/args/env) and streamable HTTP (url/headers) servers, lists their tools as<server>__<tool>descriptors and returns{ tools, close(), status() }. Every server connects up front (listing tools needs a connection);lazy(defaulttrue) reconnects on the next tool call afterclose()or a dropped connection.onError: 'skip'leaves a failing server out with a warning instead of rejecting.createAgent({ mcpServers })connects them on the newagent.ready()or the firstsend()/stream()and adds their tools; the newagent.close()disconnects them (both are no-ops withoutmcpServers).specToAgent()now connectsspec.mcpServersthe same way (closes TODO);agent.mcpServersstill lists them.loadMcpTools()accepts any{ listTools, callTool }(McpClientLike). See docs/configuration.md#connect-mcp-servers-mcpservers-connectmcp. - Error codes with fixes: every
SDKErrornow has a stablecode(LOUSHO_<AREA>_<NAME>, e.g.LOUSHO_CONFIG_MISSING_PROVIDER,LOUSHO_PEER_MISSING,LOUSHO_SPEC_INVALID,LOUSHO_SESSION_AWAITING_APPROVAL), a one-sentencehintand adocslink to its section of the new docs/errors.md; its message ends with a[code] hint (docs)line (detailis the message without it), andtoString()always shows it.ERROR_CODES/ErrorCode(new exports) are the registry, and a test keeps it, the codes used insrc/and docs/errors.md in sync. The plainErrors thrown bycreateAgent()(no model,instructions+prompt,sessionIdwithout checkpoints),resolveProvider()(bad spec, unknown prefix, missing API key, missing peer),AgentExecutor.execute()/stream()(missingprovider/agent/input, approval with noapprovalStore),resumeAfterApproval()(unknown approval), sessions (invalid id, corrupt file, second iteration, no stream runner),loadSpec()andspecToAgent()are nowConfigurationError/ValidationError/SDKErrorwith codes;MissingPeerDependencyErrorextendsSDKError. Existing message text is unchanged (the help line is appended).loadSpec()suggests the field a top-level typo meant (unknown field 'promt' (did you mean 'prompt'?)). See docs/errors.md. - Checkpoint history:
memoryStore(),SqliteStoreandLocalStorageCheckpointStorekeep a bounded history per session: everysave()also appends the record to a ring (historyLimitoption, default 50,0keeps none; the oldest are dropped), and the new optionalCheckpointStore.history(sessionId, { limit? })returns{ step, savedAt, status, checkpoint }entries newest first.CheckpointStore.delete(sessionId, { keepHistory: true })keeps the history (by defaultdelete()clears it too),getCheckpointHistory(store, sessionId)reads it and returnsundefinedfor a store withouthistory(), andSqliteStoregains thecheckpoint_historytable (added when an existing database file is opened;prune()removes old entries). New typesCheckpointHistoryEntry,CheckpointHistoryOptions,CheckpointDeleteOptionsandMemoryStoreOptions.KVCheckpointStoreand Agent Forge’s file store keep no history yet. This is the first step of time-travel from a past step. See docs/durable-execution.md#checkpoint-history. lousho eval --record / --replay / --drift:--recordruns every eval case against its agent’s real provider throughrecordReplay()and writes one cassette per case next to the eval file (__cassettes__/<eval-name>/<case>.json, the normal cassette format);--replayruns every case from its cassette with no network, and a missing cassette fails the case with the--recordcommand to run. Plainlousho evalwithCIset replays the cases that have a cassette; withoutCIit is unchanged.--driftre-records into a temp directory and compares each case with its committed cassette (ordered tool names, JSON-normalized tool arguments, step count, finish reason; tokens with--drift-usage): the summary gets aDrift:table and each drifted case a softdriftassertion (a JUnit<system-out>note), or a gate failure with--strict. Existing eval files need no change: while a case runs,AgentExecutor.execute()wraps its provider for that case.EvalResultgainscassettes. Fixed on the way: trajectory and classic eval results now carry theirfile(it was read before the test ran and was always empty). See docs/evals.md#record-replay-and-drift.- OpenTelemetry GenAI metrics and cost:
createOtelTraceExporter()(@lousho/build-ai-agent/otel) now also records the GenAI client metricsgen_ai.client.token.usage(histogram,{token}, one record pergen_ai.token.typeinput/output) andgen_ai.client.operation.duration(histogram,s, for every model call and tool call) through@opentelemetry/api’s metrics API: the globalMeterProvider, or the newmeteroption;metrics: falseturns them off. Without a registeredMeterProviderthey are discarded by OpenTelemetry’s no-op meter. Spans gainlousho.cost_usd(estimated USD: per step onchatspans, cumulative oninvoke_agentspans, absent when the price table does not know a model) andlousho.usage.estimatedoninvoke_agentspans (it was already onchatspans). AnyTraceExportersees the cumulative attributes:withSpan()sums the cost of finished child spans onto their parent. See docs/observability.md. - One
storeoption:createAgent({ store })takes anAgentStore({ sessions?, checkpoints?, approvals? }, new export) and wires all three from it.SqliteStoreis one; the newmemoryStore()returns in-memory sessions, checkpoints and approvals, and docs/sessions.md shows the file-based combination (FileSessionStore,LocalStorageCheckpointStore,StorageServiceApprovalStore).agent.session({ id })then keeps its transcript instore.sessionsand checkpoints every turn instore.checkpoints;store.approvalsis the defaultapprovalStore.SendOptions.sessionIdmakessend()/stream()a durable run checkpointed instore.checkpoints(an error without one), so a one-shot durable job needs noAgentExecutor, andagent.approvals.resolve()keeps checkpointing it. The newagent.resume(sessionId)finishes an interruptedsend(..., { sessionId })run, or else the session’s pending turn (assession.resume()), and returnsnullwhen nothing is pending. A session’s ownstore/checkpointStoreand an explicitapprovalStorestill win, part by part. Withoutstore, nothing changes. - One tool-error shape: every failed tool call reaches the model as
{ error, toolName, message, kind }(message capped at 2,000 characters, transcript message flaggedisError), whichever path failed:kindis'execution','validation'(plusissues),'not-found','rejected'(plusnote),'not-run','mcp'or'sandbox'. New exportstoolErrorResult(),ToolErrorResult,ToolErrorKindandToolErrorInput;McpToolErrorand the sandbox guard’s error (namedSandboxRequiredError, not exported) carry atoolErrorKind.kindis additive on thrown-error and validation results. The paths that built their own shapes changed, see Changed. See docs/tools.md. - Background sub-agents end with the lead run: when a run ends (any
finishReason, or an error), its background sub-agents still queued or running are cancelled, and the run resolves once their runs have stopped, so none of their events reachesonEventafterwards.withSubagentOptions(subagents, { awaitBackgroundOnFinish: true })waits for them instead (an aborted or failed lead still cancels them). The newresult.backgroundTaskslists the run’s background tasks as{ taskId, agent, status, elapsedMs, ... }(absent when it started none).createAgent({ subagentOptions: { maxConcurrent, awaitBackgroundOnFinish } })sets the same options (over any attached withwithSubagentOptions(), without changing thesubagentsvalue). The executor hook behind it is public:ExecuteOptions.onRunEnd({ result } | { error })is called exactly once perexecute()/stream()run, however it ends; an error it throws rejects the run. See docs/sub-agents.md. - Durable sessions:
agent.session({ id, store, checkpointStore })(or astorethat carries both,{ sessions, checkpoints }, such as aSqliteStore) runs each turn withsessionId: '<id>.turn-<n>'and thatCheckpointStore, so it is checkpointed after every model response and tool result.session.resume()finishes a turn interrupted by a crash, a failed checkpoint write or aPropagatingToolError(also in a new process) without re-running recorded tool calls or model responses, adds it to the transcript assend()would and returns its result (nullwhen nothing is pending);session.pending()reports an unfinished turn andsession.discardPending()drops it.send()/stream()resume a pending turn before sending the new message. A turn paused for approval stays in its checkpoint until it finishes:resume()/send()throwSessionAwaitingApprovalError, andagent.approvals.resolve()continues it in the session. Sessions without a checkpoint store are unchanged. See docs/sessions.md. - Structured output:
createAgent({ output: zodSchema })(andExecuteOptions.output) makes the final reply a JSON object validated by the schema.send(),run.resultandagent.approvals.resolve()resolve with it asresult.object, typedz.output<typeof schema>fromsend()andstream()ofcreateAgent()agents (SimpleAgent,AgentRunandExecutionResultgain a type parameter that defaults tounknown);result.textkeeps the raw JSON. The system prompt gets an## Output formatsection with the schema as JSON Schema, and each model call carries the newGenerateOptions.responseFormat: { type: 'json', schema? }hint, which theai-SDK providers map toexperimental_outputJSON mode. The reply is parsed (a code fence is tolerated) and validated; when invalid, one repair step sends the model the issues (it counts againstmaxSteps), and a reply still invalid ends the run with the newfinishReason: 'output-invalid', noobjectandoutputError: { message, issues }.run.donegains an optionalobjectfield (additive: the event schema version stays 1). See docs/structured-output.md. - Background sub-agents: the
tasktool takesbackground: true, which starts the sub-agent and returns{ taskId, status: 'running', agent }at once. Agents withsubagentsalso getagent_status({ taskId? })(queued/running/done/failed/cancelled/awaiting-approval, pluselapsedMs),agent_await({ taskId | taskIds, timeoutMs? })(the synchronoustaskresult, orstatus: 'timeout') andagent_cancel({ taskId }).withSubagentOptions(subagents, { maxConcurrent })bounds how many run at once per lead run (default 3; the rest queue). Background sub-agents inherit the lead run’s runtime andmaxSubagentDepth, and aborting the lead cancels them. Not yet: resuming one that paused for approval (it reportsawaiting-approvalwith itsapprovalId). A user tool namedagent_status,agent_awaitoragent_cancelnow conflicts withsubagents, liketask. See docs/sub-agents.md. - React hook: new
@lousho/build-ai-agent/reactsubpath withuseLoushoAgent(source, options?).sourceis{ agent, sessionId? }(in process, viaagent.stream()oragent.session({ id }).stream()) or{ url, headers?, fetch? }(POSTs{ input }and reads the SSE or NDJSON event stream). It returnsmessages(text and tool calls with status, args and result),status(idle/streaming/awaiting-approval/error),pendingApproval,error,usage,lastEvent,send(),stop()(aborts; unmount aborts too),approve(note?)andreject(note?)(viaagent.approvals.resolve()in process, orPOST ${approvalsUrl}/${id}remotely). The framework-neutralreduceAgentEvents()reducer andparseEventStream()parser are exported from the same subpath.react(^18 || ^19) is an optional peer dependency. See docs/react.md. - Summarizing compaction:
summarizeStrategy({ model, protectedTokens?, prompt?, maxSummaryTokens? })replaces the turns before the protected tail with one[Conversation summary]user message written bymodel(anLLMProvideror a"provider/model"spec), keeping system and pinned messages and each assistant turn together with its tool results; if the summary call fails it falls back to pruning and reportserror.twoPhaseStrategy()(the recommended strategy) prunes first and summarizes only when still above the threshold.pinMessage()/isPinned()and the new optionalMessage.metadata(never sent to providers) mark messages no built-in strategy compacts.CompactionStrategy.compact()may now be async, socompactMessages()returns a Promise;CompactionResult/CompactionInfogainsummaryanderror, andCompactionInputgainsthresholdTokensandsignal. A strategy that throws no longer fails the run: the hook reports theerrortoonCompaction. See docs/compaction.md. createAgent({ retry, fallbackModels }):retry(withRetry()options, orfalse) retries failed model calls and defaults to{ maxRetries: 2 }for models given asprovider/modelstrings (or picked from the environment); aproviderinstance is wrapped only whenretryis set.fallbackModelsareprovider/modelstrings tried in order once the primary model’s retries are used up (withFallback([withRetry(primary), withRetry(fallback), ...])).agent.stream(),session.stream()andAgentExecutor.stream()report them as two new typed events,provider.retry(attempt,maxRetries,delayMs,error: { message, category? },provider) andprovider.fallback(from,to,error: { message }), for anywithRetry()/withFallback()provider. Additive: the event schema version stays 1.- Context compaction:
createCompactionHook()returns anAgentHookthat, before a model call estimated abovethresholdPercent(default 0.9) of the model’s context window, replaces tool results older than the newestprotectedTokens(default 40,000) with a[pruned: <tool> result, N chars]marker, in the run’s transcript itself.compactMessages()compacts a conversation by hand;CompactionStrategy/pruneToolResultsStrategy()make the strategy pluggable. See docs/compaction.md. AgentSpec.mcpServers: a validated map of MCP servers (stdiocommand/args/envor HTTPurl/headers) in agent spec files.loadSpec()reports a bad entry with its name,lousho doctorreads the validated field instead of the raw file, andspecToAgent()exposes the parsed servers asagent.mcpServers(connecting them is TODO). Existing specs are unaffected.createAgent()agents can pause for approval: aneedsApprovaltool no longer fails the run with “requires approval but no approvalStore”. The run pauses (finishReason: 'awaiting-approval') in a per-agentInMemoryApprovalStore(or the newapprovalStoreoption), andagent.approvals.list()/agent.approvals.resolve({ id, approved, note? })continue it, in its session if it paused in one. Theapproveoption decides calls in code without pausing.- Tools own their contract:
ToolDescriptorgains optionalinputSchema(zod) andexecute(args, ctx), which are now the canonical fields.defineTool()sets both and no longer callsai’stool(). Argument validation, the schema sent to the model, and tool execution read them first and fall back totool.parameters/tool.execute.ToolDescriptor.tool(theaiv4Tool) is now legacy: it is still built bydefineTool()and still accepted on hand-written descriptors this release, but new code should setinputSchemaandexecute. - ✅ Complete Phase 5 migration: Security, Storage, Templates, and Utils modules
- ✅ Security module with encryption, hashing, and quota validation
- ✅ Storage service with file locking mechanism
- ✅ Template rendering engine with Jinja2-like syntax
- ✅ Comprehensive utility functions (errors, formatters, validators)
- ✅ File extraction and processing utilities
- ✅ JSON path navigation utilities
- ✅ Framework-agnostic architecture (zero framework dependencies)
Fixed
lousho --help,-handhelpprint the usage and exit 0 (they were “unknown command” with exit 1).- Install truth: the README, installation, CLI, quick start and Agent Forge docs,
lousho init --helpand the message after a failedlousho initinstall now say the package is not on npm yet and point to one section, “Installing before the first release” (docs/installation.md);npm install github:LinuxDevil/agent-sdkis documented as not working. Stale “planned / not yet” statements about agent-directory channels,toolCallIdin sandboxed tools and the Agent Forge Settings tab are corrected. - On
ai5+ the providers send images asfileparts with an imagemediaType(image/*when unknown) instead of the deprecatedimagepart, which madeai7 log a deprecation warning for every image.ai4 still getsimageparts. - OpenRouter on
@ai-sdk/openai2+, and the Ollama base URL (behaviour fix):OpenRouterProvidernow builds its model withprovider.chat(modelId)(Chat Completions, the only API OpenRouter implements) instead of the bare call, which targets the Responses API from@ai-sdk/openai2 on; no change onai4.OllamaProviderappends/apito a base URL that has no path (http://host:11434orhttp://host:11434/), the formollama-ai-providerandollama-ai-provider-v2expect, so a configured bare host no longer hits/chatoutside/api(before,getModels()hit<baseURL>/api/tagsbut chat requests went to<baseURL>/chat); a URL ending in/apior with any other path is used as it is, andgetModels()no longer doubles/apifor a base URL that has it.lousho init(andcreate-lousho-agent) now scaffolds OpenRouter projects onai@^7.0.0with@ai-sdk/openai@^4.0.0.
Deprecated
ExecuteOptions.onEvent,ExecutionEventandExecutionEventType.onEventkeeps working: the executor now emits onlyAgentEvents, and an adapter derives the old events from them in the old order (start,text-complete,tool-call,tool-result,error,abort,finish, sub-agents’ tagged withsubagent), with a one-timeconsole.warn. Differences:finishnow comes after the run’s checkpoint is written (it was just before), and a run that fails outside a step (an input guardrail that throws,onRunEndthrowing) now gets anerrorevent too. Migration: replaceonEventwithonAgentEvent(orcreateAgent({ onEvent }));start->run.start,text-complete->text.done(step usage onstep.done),tool-call->tool.start,tool-result->tool.done/tool.error,abort/finish->run.done(finishReason),error->error({ name, message }). The full table is in docs/streaming.md#migrating-from-onevent—executionevent.
Removed
ExecuteOptions.streaming: it was never read. UseAgentExecutor.stream()/agent.stream()to stream a run. Passing it in an object literal is now a type error; remove the property.ToolDescriptor.injectStreamingControlleranddefineTool({ injectStreamingController })(deprecated earlier in this release): no SDK path ever called it, so removing the property changes nothing at runtime. Passing it is now a type error; remove the property.AgentExecutionOptions.streaming: it was never read (AgentExecutionOptionsis a legacy type no SDK API takes). Remove the property; stream a run withagent.stream()/AgentExecutor.stream().- BREAKING:
validateTokenQuotas()(src/security/quotas.ts) and the SaaS-era typesSaaSContext,QuotaConfig,UsageStatsandQuotaValidationResultno longer ship from the package root. Nothing in the SDK called them. No replacement; copy the file into your project if you relied on it. - BREAKING:
ConfigManagerandSDKConfig(src/core/ConfigManager.ts) no longer ship from the package root or./core(which still exportsAgentBuilder). Nothing in the SDK used them. No replacement; copy the file into your project if you relied on it. - BREAKING: The formatters
getCurrentTS(),getTS(),formatDate(),safeJsonParse(),removeCodeBlocks(),findCodeBlocks(),checkApiKey()and the typesCodeBlock,CodeBlockError,CodeBlockResult(src/utils/formatters.ts) no longer ship from the package root. No replacement; copy the file into your project if you relied on it. - BREAKING: The JSON path helpers
getObjectByPath()andsetRecursiveNames()(src/utils/json-path.ts) no longer ship from the package root. No replacement; copy the file into your project if you relied on it. - BREAKING: The file extraction helpers
getMimeType(),getFileExtensionFromMimeType(),replaceBase64Content(),isBinaryData(),extractBase64Data(),createDataUri()andProcessFilesParams(src/utils/file-extractor.ts) no longer ship from the package root. No replacement; copy the file into your project if you relied on it. - BREAKING: The flows-ai converters are gone:
convertToFlowDefinition()andconvertFromFlowDefinition()(src/flows/converters.ts) no longer ship from the package root or./flows. There is no replacement: the flows-ai engine they targeted was never a dependency of this package andFlowExecutornever used them. Run flows withFlowExecutordirectly. - BREAKING:
MemoryManagerand its typesMemoryManagerConfig,StoreMemoryOptions,RecallMemoryOptionsandMemorySearchResult(src/execution/MemoryManager.ts) no longer ship from the package root. Nothing in the SDK used them (AgentExecutor,createAgent,resumeand the flows never called them; only their own test and theexecution/index.tsre-export). Migrate todefineMemory()andcreateAgent({ memory })(memory slots, see docs/memory.md). - BREAKING:
ContextBuilder,ContextBuilderOptionsandExecutionContext(src/execution/ContextBuilder.ts) no longer ship from the package root. Nothing in the SDK used them; they truncated by message count only. Migrate tocreateAgent({ compaction })(token-aware compaction, see docs/compaction.md). - BREAKING: The
retry()family (retry,retryOnError,retryWithTimeout,retryBatch,RetryableOperation,RetryOptions,RetryResult;src/execution/retry.ts) no longer ships from the package root. Provider calls retry through the provider wrappers; nothing else in the SDK used it. Migrate tocreateAgent({ retry, fallbackModels }), or copy the file into your project for general-purpose retries. - BREAKING: The
data/module is gone: the classesAgent,Session,Result,Memory,Attachmentand the repository interfacesBaseRepository,AgentRepository,SessionRepository,ResultRepository,MemoryRepository,AttachmentRepository,RepositoryCollection,RepositoryFactory,PaginationOptions,PaginatedResultno longer ship from the package root. They were donor-product data tables that nothing in the SDK used onceMemoryManagerwas removed. No replacement: unused. UseAgentConfig, sessions (agent.session()) anddefineMemory()for the SDK’s own concepts. - BREAKING:
@lousho/build-ai-agent/testingexports test utilities only. The in-memory repository mocksMockAgentRepository,MockSessionRepository,MockResultRepository,MockMemoryRepositoryandMockAttachmentRepositoryare removed with thedata/module. No replacement: unused.mockModelandrecordReplayare unchanged. - BREAKING: The template engine (
TemplateManager,renderTemplate()and the typesTemplateFilter,TemplateContext,TemplateOptions,ITemplateManager;src/templates) no longer ships from the package root. Nothing in the SDK,lousho initor Agent Forge used it (the executor never rendered prompts through it; the scaffold templates are separate files undersrc/cli/init). No replacement: unused; use a template literal or your own renderer. nanoidis no longer a dependency. Generated ids (agent, run, trace, memory ids) now come fromglobalThis.crypto.randomUUID()via an internalnewId(), so they are UUIDs instead of 21-character nanoids. Nothing public depended on the old format.finishReason: 'max-steps': a run that exhaustsmaxStepswhile the model still wanted to continue (last turn ended in tool calls) now resolves withfinishReason: 'max-steps'instead of the stale last-turn reason (usually'tool_calls'), onExecutionResult, thefinishevent andrun.done. Resumed runs countinitialStepstoward the budget. A run that finishes naturally within the budget is unchanged. Code that treated'tool_calls'as “hit maxSteps” should check'max-steps'instead (the evalcompleted()message and the MCP server’s agent tool do).
Docs
- README revamped into a short front page; the details it dropped moved to
docs/(new pages: tools, approvals, providers, cli, flows, guardrails, utilities).
Renamed
- The project is now lousho (it was
loushy), before the first npm release, so nothing was ever published under the old name. Everything that carried the name changed with it, and this changelog uses the new names throughout, including in older entries: the package@lousho/build-ai-agent(was@loushy/build-ai-agent), theloushoCLI (wasloushy),create-lousho-agent(wascreate-loushy-agent), the exportsuseLoushoAgent,loushoAgent,LoushoAgentSource,LoushoUIMessageChunkand the otherLousho*types, everyLOUSHO_*error code and environment variable (LOUSHO_MODEL,LOUSHO_API_TOKEN,LOUSHO_STORE, …), the.lousho/directory, thelousho.*span attributes and thedata-lousho-approvalstream part. Migration for a checkout that used the old name: replaceloushywithlousho(keeping the case) in imports, scripts, environment variables and config, and rename an existing.loushy/directory to.lousho/.
Published
@lousho/build-ai-agentandcreate-lousho-agentare on npm. The README and the installation, quick start, CLI and Agent Forge docs no longer say the package is unpublished; “Installing before the first release” is now “Installing from a local build” (docs/installation.md#installing-from-a-local-build) and covers trying an unreleased commit. The hint printed after a failedlousho initinstall no longer mentions a 404; it points to--sdk-path. The docs site moved to https://lousho.com.