AgentKit primitives for building AI agents on Upstash Redis, as a pnpm monorepo. Read this before starting work; it captures the non-obvious decisions and gotchas that aren't visible from the code.
Everything runs on Upstash Redis. No vector database, ever. All "semantic"/similarity features use
Upstash Redis Search with the $smart fuzzy operator — via @upstash/redis's redis.search
API, not RediSearch FT.* and not @upstash/vector. Matching is lexical/fuzzy (BM25), not
embeddings — keep that in mind when naming/among scoring. The one exception is upstash-hermes-memory, whose memory
text is a Redis Search HYBRID field with managed embeddings (still no separate vector database).
| Package | What it is |
|---|---|
@upstash/agentkit-sdk (packages/sdk) |
Core, framework-agnostic primitives. No ai dependency (redis-only). |
@upstash/agentkit-ai-sdk (packages/ai-sdk) |
Vercel AI SDK adapter. |
@upstash/agentkit-eve (packages/eve) |
Eve framework adapter. Depends on the ai-sdk package. |
@upstash/agentkit-tanstack-ai (packages/tanstack-ai) |
TanStack AI backends: persistence stores, StreamDurability, LockStore, MemoryAdapter, middlewares, search tools. |
@upstash/agentkit-resumable-stream (packages/resumable-stream) |
Upstash provider for resumable-stream/generic: HTTP publisher/subscriber (JSON envelope, splits large messages, ordered per-channel publish queue, never rejects), requestStop/createStopSignal. No context wrapper: apps call createResumableStreamContext from resumable-stream/generic with our publisher and subscriber. Depends only on @upstash/redis; resumable-stream >=2.2.10 is a peer. Tested against real Redis only. |
@upstash/agentkit-eve-extension (packages/eve-extension) |
AgentKit as a mountable eve extension (eve ≥0.24): one agent/extensions/<ns>.ts file composes memory tools, search tools, a chat-history hook, and an instructions fragment under <ns>__*. |
@upstash/mcp-toolkit (packages/mcp-toolkit) |
Durable building blocks for the official @modelcontextprotocol/server v2: /tasks (long-running MCP tools — native MCP Tasks for clients that declare the extension, else start + task_status + task_cancel) and /events (MCP Events, webhook delivery). /tasks and /events are generic (the McpTasks / McpEvents classes, interfaces, memory backends); every Upstash backend for both is in /upstash (no /tasks/upstash, no /events/upstash). @upstash/redis, @upstash/qstash and @upstash/workflow are regular dependencies (the package "just works"); only @modelcontextprotocol/server is a peer. Renamed from @upstash/mcp-tasks before its first release. Not an agentkit-* package — separate name, versioned independently (the changesets linked glob only covers @upstash/agentkit-*), and it depends on none of the others. |
upstash-hermes-memory (python/hermes-memory, PyPI) |
Hermes Agent memory provider (UpstashMemoryProvider, entry point hermes_agent.memory_providers: upstash) plus Python ports of AgentMemory / ChatHistory that write the TS keys and indexes byte for byte. See Python packages below. |
Examples (examples/): ai-sdk-demo (hand-written Next.js), eve-demo (a real eve CLI scaffold),
eve-extension-demo (a minimal eve scaffold that mounts the extension), mcp-toolkit-demo
(Next.js; the MCP server plus a browser client that shows the JSON-RPC wire log), and
resumable-stream-demo (Next.js; the AI SDK resume-streams guide on @upstash/agentkit-resumable-stream,
with a stop route; scripted ai/test model without OPENAI_API_KEY).
langchain was removed — don't reintroduce it. A first tanstack-ai adapter was removed in June 2026
(it only wrapped memory + a model cache); the current packages/tanstack-ai is a different package that
implements TanStack AI's own backend contracts (see its section below) — keep it.
AgentMemory,ToolCache,ChatHistory,createSearchToolDefs(the framework-agnostic search-tool defs — use these for RAG, there is noRagprimitive),createRateLimit(+RateLimitConfig; thin@upstash/ratelimitfactory —limiterrequired),ReactiveSearchIndex(+ReactiveSearchIndexConfig/AnySearchSchema, inreactive-index.ts),s(schema builder, re-exported from@upstash/redis), typesChatRecord/ChatSummary/ChatSearchHit, utilskey/now/stableHash/stableStringify. (Model cache removed;Ragremoved — RAG is done via the search tools;search-index.ts/RedisSearchIndexand thewithIndexhelper removed —ReactiveSearchIndexreplaces them, owning create-on-read.)@upstash/ratelimitis a dependency of core (not a peer); rate limiting lives here now.ChatHistoryis durable chat history on Redis Search (the source of truth for transcripts, resurrecting the old removed ChatHistory). One JSON doc per chat atagentkit:chat:<userId>:<sessionId>indexed overuserId+sessionId(filters) anduserMessages+modelMessages($smarttext); the rawmessagesarray rides along unindexed. Every method takes a single object with a required, non-emptyuserId/sessionId(validated; the per-user key is the tenant boundary — no cross-user collision possible, so no ownership check).listChats({userId})filters by user;searchChats({userId, query, target})fuzzy-searches user/model text;saveChatreplaces the whole array (overwrite, not append — pass the full transcript; typically called server-side in the route'sonFinish). Generic overTMessage.- Reactive index provisioning (
withIndex): a missing Upstash index surfaces differently per op —query→null,count→{count:-1},aggregate→throws a null-.lengthTypeError(verified against live Redis).withIndex(provision, op, isMissingResult?)runs the op, and on a missing index (sentinel return or thrown error) creates the index +waitIndexing()and retries once. Used byChatHistoryreads andai-sdkcreateSearchTools(replaced its old proactive ensure). - Design rule: every feature takes only
redisand creates/owns its search index internally, exposing the raw handle via.searchIndex. Callers never pass a search index in.
createRateLimit(re-exported from core — call.limit(id)beforegenerateText, no model wrapper),cachedTools,createMemoryTools,createSearchTools,createChatHistory(→ChatHistory<UIMessage>; also re-exportsChatHistory/ChatRecord/etc.). (No model cache — removed.)createAgentMemory(src/agent-memory.ts) — the AI SDK memory-provider shape. Not a model wrapper (other providers usewrapLanguageModel, which this repo forbids): automatic recall runs inprepareStepon step 0 and the override carries forward.- Only
cachedTools(no singularcachedTool— removed):cachedTools(map, { userId, redis?, ttlSeconds? })takes a map oftool()-built tools (so each keeps inference) and caches each under its map key as the toolName, scoped touserId— so the user never passes a tool name. - Self-contained: users import only from this package.
redisdefaults toRedis.fromEnv(); tools build their ownToolCache/AgentMemoryinternally. No@upstash/agentkit-sdkimport required by users.
.→defineCachedTool,defineMemoryRecallTool,defineMemorySaveTool,defineSearchTools(eve counterpart to ai-sdkcreateSearchTools— returns a{search,aggregate,count}record ofdefineTool-branded tools; call it in eachagent/tools/*.tsand export one member, repeatingschema+name— agent files must be self-contained, see eve-demo specifics), plus rate limiting:createRateLimitAuth(a ready eve route-authAuthFn,packages/eve/src/auth.ts) and the corecreateRateLimitfactory re-exported. No model wrapper / no./modelsubpath.- No chat history in the eve adapter —
ChatHistoryis core/ai-sdk only here. eve sessions are durable server-side (Vercel Workflow) anduseEveAgenthas noinitialMessagesprop, so a stored transcript doesn't round-trip cleanly; resume is via eve'ssessioncursor, not us. (The eve-extension package does capture transcripts to Redis via itschat_historyhook, and reads them back as tools —search_chat_history/read_chat_history— so the model can look up past conversations. That's lookup-on-demand, not session resume: the same no-round-trip caveat holds.) ./sandbox→UpstashSandbox, an Upstash Box sandbox provider (eve ≥0.64defineSandboxProvider). See Known issues for the design notes../memory→ eve's native memory feature (agent/memory/<slot>.ts), on Redis. Two exports, both shipped because they sit at different eve seams:redisDocuments()is aMemoryDocumentBackendfor eve's ownfileMemory()(storage only — replaces Vercel Blob, which is the documented gap:fileMemory()with nobackenderrors outsideeve dev/Vercel-with-Blob), andredisMemory()is a fullMemoryProviderover coreAgentMemory(ranked BM25 recall atturn.started/compaction.completed, automatic capture atturn.completed, plussave_memory/search_memory/read_session/forget_memorytools). See the eve memory slots section below. This is additive:defineMemoryRecallTool/defineMemorySaveTool, ai-sdkcreateMemoryToolsand the extension'srecall_memory/save_memoryare untouched and still the answer for purely model-driven memory with no slot and no eve-version floor.- Eve is file-centric, but the tool factories now call
defineToolinternally and return the brandedToolDefinition— users export them directly (no outerdefineTool(...)wrap). Because of this,eveis a required (non-optional) peer dep ofpackages/eve. defineCachedTooldoes not cache streams: eve ≥0.31 lets executors be async generators (preliminary output snapshots), but a cache hit could never replay them — soDefineCachedToolConfignarrows the inputexecutetoPromise<TOutput> | NonStreaming<TOutput>and rejects generator executors at the type level. TheNonStreaming([Symbol.asyncIterator]?: never) intersection is load-bearing: with a plainPromise<TOutput> | TOutputunion, TS just infersTOutputas the generator object and the rejection silently fails (guarded by a@ts-expect-errortest intools.test.ts). A runtime backstop covers JS callers: a directly returnedAsyncIterablethrows aTypeErrorbeforeToolCachewould serialize the generator object into Redis (a promised value is just a value — only direct returns are streams, matching eve). Factory returns stay plainToolDefinition— directexecutecallers (tests) narrow the awaited union themselves.- Rate limiting in eve = a route-auth gate:
createRateLimitAuth(config)goes first ineveChannel({ auth: [...] }); it.limit()s, throwsForbiddenError(403) over the limit, else returnsnullto fall through to the real authenticators (localDev()/vercelOidc()/…).
- Built with
eve extension build(not tsup), on eve ≥0.25's dist packaging format:package.jsonhas"eve": { "extension": { "source": "./extension", "dist": "./dist/extension" } },filesshipsdist/only (compiled.mjs+.d.tsper contribution, plus_manifest.jsonwithbuiltWithEve; eve validates compatibility from the manifest), andeveis a floored peer (">=0.48.0"— was the scaffold's"*"until issue #22; see Consumer eve version below). The old 0.24 format ("eve": { "extension": "./extension" }, ships source the consumer recompiles) is rejected by eve ≥0.25 with "must declareeve.extension.dist" — don't regress to it. Nopreparescript (an install-time build broke CI: sdk isn't built yet at install;pnpm buildhandles topological order). - Consumer requirements (verified against real
eve initconsumers): none for a bare mount. Apps that configuresearchdeclare@upstash/redisthemselves — their own mount file importssfrom it, and pnpm's strict layout rejects the phantom dep (npm hoists and hides it). The old "also install@upstash/agentkit-sdk" workaround is not needed on the 0.25 format — the compiled dist resolves sdk from the extension's own package. (The old eve bug whereeve devfailed to load an extension installed as a real directory — npm/yarn hoisted layouts — was fixed upstream in eve 0.25.3; no workaround needed on ≥0.25.3.) Consumer eve version:eve extension buildstamps the manifest'srequireswith the building eve's current contribution-format versions, and a consumer rejects any version not in its own supported list — the current dist, built with eve 0.83.0, stamps formatVersion 2; extension 1 / tool 102 / dynamicTool 92 / hook 51 / instructions 2 / config 1, which needs consumers on eve ≥0.83.0 — 0.83.0 is the first release accepting all three (0.82.0 refuses them, and 0.83.0 in turn refuses the 0.82.0 stamps 96/88/48 — verified by packing a 0.82.0-built dist into aneve@0.83.0consumer: "requires tool contract v96 … supports …"; 0.75.0–0.81.1 refuse them too; the 0.74.0 build stamped 78/73/39 with floor 0.74.0, published0.16.0; 0.72.0–0.73.0 refuse those: a pack of this dist built against 0.72.0/0.72.1/0.73.0 failseve buildwith the obtuse "has no compile or runtime usage" error; the intermediate 0.72.1 build stamped 76/72/38 with floor 0.72.0 and was never released; 0.72.0 dropped tool 71–75; the published dist, built with 0.69.0, stamped 71/68/35 with floor 0.69.0 and fails on eve ≥0.72.0). Earlier: 0.69.0 was the first release accepting any of 71/68/35 (0.65.0–0.68.0 accept none of them), and 0.69.0 in turn dropped tool 59 / dynamicTool 56 / hook 29, the stamps of the 0.68.0 build (published0.14.0). The 0.68.0 build stamped tool 59 / dynamicTool 56 / hook 29 (floor 0.68.0: 0.67.0–0.67.2 accept dynamicTool 56 but neither of the others). The dist before that, built with 0.65.0, stamped tool 55 / dynamicTool 52 / hook 25 (floor 0.65.0; the 0.64.1 build stamped tool 54), because eve now drops mid-range contracts rather than only adding new ones (0.64.0's supportedtoollist is [1–13, 29–32, 34, 35, 54], itsdynamicToollist [1–20, 22, 31–33, 52] and itshooklist [10–15, 17–23, 25] — 0.64.0 dropped tool 53, dynamicTool 51 AND hook 24 in one release, which is exactly the stamp published0.12.0carries, so 0.12.0 cannot build on any eve newer than it). 0.63.0 stamps tool 53 / dynamicTool 51 / hook 24 and rejects tool 54 / dynamicTool 52 / hook 25 (0.63.0's supportedtoollist is [1–13, 29–32, 34, 35, 53] and itsdynamicToollist [1–20, 22, 31–33, 51]: 36–52 are dropped with "experimental_workflow … removed" / "Background defineTool and TaskExec were removed", and dynamicTool 29 — the stamp published0.10.0carries — with "Background dynamic tools were removed"). 0.61.0 stamps tool 51 / dynamicTool 50 / hook 24 and 0.61.1–0.62.0 still reject tool 53 / dynamicTool 51; 0.55.0 topped out at tool 38 / dynamicTool 37 / hook 22 (itstoollist was [1–13, 28–32, 34–38]); 0.54.3–0.54.5 top out at tool 36 (dynamicTool 34 on 0.54.3, 35 on 0.54.4/0.54.5), 0.54.0/0.54.2 at tool 35 / dynamicTool 33, 0.53.0/0.53.1 at tool 34 / dynamicTool 32, 0.52.3 at tool 32 / dynamicTool 31, 0.52.2 at tool 30 / dynamicTool 29 / hook 20, 0.52.1/0.52.0 at tool 29, 0.51.1 at tool 27 / dynamicTool 27 / hook 20, 0.51.0 at tool 25 / hook 18, 0.50.0 at dynamicTool 22 / hook 17, and 0.48.0–0.49.1 at tool 24 / dynamicTool 21 / hook 16. (hookhas sat at 22 since 0.53.0 — it istool/dynamicToolthat keep moving.) Verified end-to-end, not just from the contract tables: the rebuilt extension,pnpm packed into a real eve app, builds on eve 0.55.0 and fails on 0.54.5 (Selected module binding "extensions/agentkit.ts" has no compile or runtime usage.— an incompatible manifest makes the mount contribute nothing, so the error is that obtuse; don't expect the old explicit "requires tool contract vN" wording). eve moved the tool contract inside the 0.45 patch line, twice across 0.47.7 → 0.48.0, and then fourteen more times across 0.49.1 → 0.55.0, so a patch bump of the eve devDep can re-stamp the manifest and raise the floor — re-derive it, don't assume the minor is enough, and don't assume one release's worth of headroom. Since ~0.50 eve also drops contracts out of the middle of its supported range, so a newer eve is not automatically compatible either: the floor has repeatedly landed on the pinned version itself, with no back-compat window at all. Theevepeer is">=0.83.0", not"*"— issue #22 proved the wildcard is a trap: eve 0.33 dropped hook contracts ≤9 nine hours after 0.32 shipped, so a wildcard install succeeds and then fails ateve buildwith a manifest error. The manifest is still the real compatibility tie; the peer floor is the install-time guard. On every eve devDep bump: rebuild, read the newdist/extension/_manifest.jsonstamps, find the oldest eve whose capability table (in eve'sdist/src/compiler/extension-compatibility.js) supports them all, and move the peer floor to match. Reading that table (verified on eve 0.63.0, re-verified on 0.64.1):EXTENSION_CAPABILITY_CONTRACTSis still the internal const —{ <capability>: { current, supported[], dropped{<version>: "why"} } }, and thedroppedstrings are the best available changelog for why a contract went away — but it is not exported. The exported names areEXTENSION_CAPABILITY_SUPPORT(capability →supported[]),EXTENSION_CAPABILITY_VERSIONS(capability →current, i.e. exactly what a build stamps), and the one-call checkfindUnsupportedExtensionCapabilities(manifest)— pass the whole parsed manifest (it readsmanifest.requiresitself; passing justrequiresthrowsCannot convert undefined or null to object). It returns[]for compatible, else[{capability, requiredVersion, supportedVersions}]. So the whole floor check is:Comparingconst m = await import("<consumer>/node_modules/eve/dist/src/compiler/extension-compatibility.js"); const manifest = JSON.parse(fs.readFileSync(".../dist/extension/_manifest.json", "utf8")); m.findUnsupportedExtensionCapabilities(manifest); // [] === compatible m.EXTENSION_CAPABILITY_VERSIONS; // what THIS eve would stamp
EXTENSION_CAPABILITY_VERSIONSagainst the committed manifest is the fast way to tell whether a rebuild would re-stamp anything before running it. To find the floor empirically without installing each eve, fetch the tarballs and regex the minified table:tar -xzf eve-<v>.tgz package/dist/src/compiler/extension-compatibility.jsthen match<capability>:\{current:(\d+),supported:\[([0-9,]*)\]. extension/extension.ts=defineExtension({ config: zod }); the default export is the mount factory. Config knobs:userId(string or(ctx: SessionContext) => string— eve's public base of tool+hook ctx, imported fromeve/tools),redis(defaultsRedis.fromEnv()),memory{topK,minScore},search{schema,indexName,prefix,defaultLimit},chatHistory: boolean | {prefix,indexName,ttlSeconds}(off by default — enable withtrueor a tuning object). Non-JSON config values (Redis, functions, thesschema) pass throughz.custom— fine, the mount file is evaluated in the runtime.- Contributions: static tools
recall_memory/save_memory; dynamic toolssearch/search_aggregate/search_count(onedefineDynamicper file, resolved atsession.started— static modules evaluate at discovery where mount config is not yet bound, so schema-derived descriptions/input schemas must be built in a resolver; unconfiguredsearch→ resolver returnsnulland the tools don't exist; and the input schema is passed as plain JSON Schema (z.toJSONSchema(…)into a resolver-local variable), never the live zod object — eve ≥0.59 replays dynamic tools from a JSON snapshot and rejects a live schema captured from the resolver, see the 0.63.0 bump note under Eve framework facts); dynamic toolssearch_chat_history/read_chat_history(samedefineDynamicreason — they exist only whenchatHistoryis enabled, which config binding decides at runtime); hookchat_history(appends everymessage.received/message.completedvia coreChatHistory.getChatsaveChat, errors swallowed — a thrown hook fails the turn);instructions.mdfragment (merges after the agent's own instructions). Shared code lives inextension/lib/runtime.ts— extensions CAN have internal shared modules (unlike agent files).
- Chat-history tools (
search_chat_history= coresearchChats,read_chat_history=getChat):userIdis pinned from the session viaresolveUserId(ctx), never model input — that's the reason they're dedicated tools instead of pointingsearchatagentkit:chat:(the generic search tool takes its filter from the model, so nothing would force auserIdclause and it would read every tenant's transcripts; also$termsaggregation fails on that index — text fields aren't FAST). Search returns summaries only (sessionId/title/updatedAt/messageCount/score) and excludes the live session (its text is already in context); read caps at 50 messages with atruncatedflag. Verified end to end against real Redis, incl. cross-tenant isolation (binding config in a probe = setglobalThis[Symbol.for("eve.ext-config-scope")]before importing the builtextension.mjs, then call the mount factory). resolveUserIddefaultsauth.current?.principalId ?? auth.initiator?.principalId ?? session.idand sanitizes:→_(eve principal ids likeeve:appand session ids would break core key-part validation).sessionIdis sanitized the same way.- Consumers drop/override slots via a directory mount +
disableTool()(that's the supported answer for "I don't want tool X" — no config flags for it, incl. "capture history but don't let the model read it": enablechatHistoryanddisableTool()the two history slots). Static memory tools are importable from@upstash/agentkit-eve-extension/toolsfortoolResultFrom/overrides; the dynamic search and chat-history tools are not. - What an extension can contribute (eve ≥0.41, per eve's
docs/extensions.md): tools, channels, connections, skills, schedules, subagents, instruction fragments, hooks — channels, schedules and subagents are allowed, and a contributed subagent may own its own agent config and sandbox. What the extension root cannot declare: agent configuration, a sandbox, or nested extensions. What stays in@upstash/agentkit-eveis therefore a packaging choice, not a framework limit: the Box sandbox backend (an extension root can't declare a sandbox), the rate-limitAuthFn(you drop it into your own channel'sauthwalk), anddefineCachedTool(wraps user tools).
-
Layout (
packages/eve/src/memory/):index.tsis the barrel + the "two seams, which to pick" overview and the tsup entry for the./memorysubpath;documents.tsisredisDocuments();provider.tsisredisMemory();memory.test.tscovers both. The two halves share no code, so each file carries only the design notes that belong to it. Note the siblingmemory-tools.ts(renamed frommemory.tswhen this directory landed, so./memory.jsand./memory/can't be confused) — that'sdefineMemoryRecallTool/defineMemorySaveTool, the package-root exports, which are a different feature from the memory slots. -
Both designs shipped, on purpose. They are different eve seams, not competing implementations:
redisDocuments()= storage under eve'sfileMemory()(whole-document recall, model-curated, bounded to 4,000 recalled chars / 64 KiB stored);redisMemory()= a whole provider (top-K BM25 recall of relevant memories, automatic capture,forget_memoryby id, unbounded store). The demo declares both slots. -
EVALworks on Upstash Redis over REST — verified live, not assumed (2026-09, anupstash start-redisDB).redis.eval(script, keys, args)from@upstash/redisis accepted with auto-pipelining on (the default), a Lua table return round-trips as a JSON array, andHGET/HSET/EXPIREinside the script behave normally (SCRIPT LOAD/EVALSHAwork too, but the backend just sends the ~300-byte script each time — writes are rare andEVALSHAwould need aNOSCRIPTfallback). This is the only way to satisfyMemoryDocumentBackend.write's optimistic-concurrency contract.MULTIdoes exist over REST —redis.multi()posts to a dedicated/multi-execendpoint and executes atomically (measured live; don't repeat the old claim that REST has no MULTI). It just cannot do a CAS: a transaction hands back every result atEXEC, so nothing inside it can branch on a value it just read —multi().get(k).set(k,v).exec()returns["a","OK"]with thesetalready done. Conditioning the write isWATCH's job, andWATCH/UNWATCHare what REST actually lacks: the server answersERR Command "WATCH" is not allowed in REST, since watching spans requests and REST keeps no session. A staleexpectedVersionmust throw eve'sMemoryDocumentConflictError—fileMemory()catches exactly that, re-reads and retries up to 8 times, using the structuralMemoryDocumentConflictError.is(), so the class is imported fromeve/memory/fileat runtime (the only new runtime eve import besidesdefineTool). -
@upstash/redisauto-deserializes replies, so a stored document whose text is valid JSON (123,{"a":1}) comes back as a number/object — measured. Documents are therefore stored with aneve-memory-document-v1:marker prefix (stripped on read) that makes every value unparseable as JSON, guaranteeing a byte-exact round trip. Layout: one hash per scope key atagentkit:memoryFile:<scopeKey>withcontent+versionfields. -
Upstash Search indexing lag is minutes, not seconds, without
waitIndexing(). Measured end-to-end: a fact captured atturn.completedwas still invisible to recall 8 turns / 10s later and only appeared minutes afterwards. SoredisMemory()'s capture ends withsearchIndex.waitIndexing()(waitForIndexing, defaulttrue) — free, because eve runs capture after the response is delivered — and that is what makes the e2e eval pass on the very next turn. Recall stays wait-free. -
read()is a plainHMGETagain — the read-your-writes workaround is gone. It used to keep a bounded FIFO set of scope keys it had written and re-read (up to twice) before returningnull, because@upstash/redis@1.38.0sent its sync token one request late and anHMGETstraight after theEVALwrite could hit a replica that hadn't caught up. Fixed upstream in 1.38.4, which is now the@upstash/redispeer floor ofpackages/eve(>=1.38.4, raised from>=1.38.0precisely because this code now relies on the fix — do not lower it). Verified before removing the workaround, by stubbingfetchand reading the token off each outgoing request: 1.38.0 sends[null, "", "tok-1"]for three calls (each one behind), 1.38.4 sends["", "tok-1", "tok-2"]. -
Recall must be replay-stable, and the cache stays — this was checked with Vercel, don't delete it. eve records a digest per
operationIdand throws "Memory recall operation … replayed with a different result" if a durable replay returns something else. eve's docs say a provider does not need to persist recall results byoperationId"unless its store can change before a replay" (docs/memory/custom-provider.md, clarified in vercel/eve#2951 after we asked — supermemory andfileMemory()don't cache because their stores can't). We are the exception: recall is a live ranked query plus two live counts, andsave_memorywritessource: "agent"records — exactly what recall ranks — mid-turn, whileforget_memoryflipsdeleted, capture appends the turn's messages, and a concurrent session on the same scope key can do any of it. So the rendered block is cached atagentkit:memoryRecall:<userId>:<operationId>(replayCacheTtlSeconds, default 3600,0disables), keyed per operation so each new turn still runs a fresh query. -
What can be in the recalled block, and how each line is labelled. A line is
<id>: <text>plus a parenthesised note. Three sources land in one ranked list and each is named:metadata.source"agent"→ you saved this (save_memory),"userMessage"→ the user said this,"agentMessage"→ you said this (rememberMessages"fromModel"/"all"). They are not equally trustworthy — a deliberate save vs. a passing remark — which is the whole reason the label exists.metadatais unindexed (it rides along likecreatedAton coreAgentMemory, whose generic is now the schema:AgentMemory<TSchema, TMetadata extends MetadataOf<TSchema>>, sometadataand everyfilterare derived frommetadataSchemaand checked against it): free to add, but not filterable — a query still matchestextonly, so "recall only saved facts" would need an indexed schema field and a re-index. Both write paths still share thestableHash(text)id, so identical text collapses onto one record whichever way it arrived, keeping the last write's metadata; and records written beforemetadataexisted, or by the standalone memory tools that share this store, carry no source and get no note rather than a guessed one. -
Lifecycle: eve offers four hooks, we register three (documented in
packages/eve/README.mdand thememory/index.tsbarrel): recall atturn.started(before the model runs) and again atcompaction.completed(against the new checkpoint, so memory isn't folded into the summary — eve excludes recalled records from the summarizer); capture atturn.completedonly (after the response is delivered, which is what makes thewaitIndexing()free). There is nocompaction.requestedcapture — messages are stored as they happen so the summarizer takes nothing with it, and it was the one context whereturn(and so the orderingsequence) can be null. Don't re-add it from an older description of this file.redisDocuments()underfileMemory()only ever sees the two recall points — eve reads the document and injects it whole. -
Recall is returned as ONE keyed message (
id: "agentkit-redis-memory"), like eve's ownfile-memory-document: eve supersedes a record when the same id comes back with different content, and omitting an item does not delete it — so per-memory ids would accumulate and a forgotten memory would linger in context. -
eve requires provider tools be
defineTool()-branded (isBrandedToolEntryincontext/memory-tools.jsthrows otherwise), and it re-invokesprovider.tools()from a durable closure on every execute — so the factory must be pure. Tool names are<slot>__<key>. -
memory.scope.keyis the partition key (eve locks it before calling the provider). It is sanitized:→_forAgentMemory'suserId, which rejects the key separator.forget_memoryvalidates the model-supplied id against/^[A-Za-z0-9_-]{1,64}$/— it becomes a Redis key part. -
Default prefix stays
agentkit:memoryso slots share the memory tools' Redis Search index (the DB caps at 10 indexes; a slot must not mint its own).agentkit:memoryFileis deliberately outsideagentkit:memory:— that prefix is the AgentMemory index's, and a document written under it would be indexed as a malformed memory doc. -
rememberMessagesdefaults totrue, and the hazard below is real — keep it documented. Captured utterances and curated facts share one BM25 ranking, and the utterances win: recall builds its query from the user's current message, so a stored "What do you remember?" scores near-perfectly against the next "What do you remember?". Measured on a live index — captured question 50.9, whileUser likes cucumber.(saved deliberately viasave_memory) was cut from the top 5 entirely. Asking the agent what it remembers is what degrades what it remembers;rememberMessages: falseis the model-curated escape hatch. (This default was flipped off and then back on: off was the measured-safest, on is the product call. Don't silently re-flip it either way.)rememberMessagesis a union:true(default, and it means"fromUser"— the caller's text only) |"all"|"fromModel"|false. No function form — an extractor can't be passed, socapture: false+ a liveextractis not expressible anddefaultExtractMemoriesis internal."fromModel"/"all"are worse than"fromUser"(the assistant's text is derived from the recalled block, so the agent re-memorizes its own restatements)."fromUser"readsturn.input— the turn's own delivery, kept separate from projected history, so recalled records can't be re-captured; and every memory's id isstableHash(text).slice(0,12), so identical text collapses onto one key and capture is idempotent across turns and replays. -
One store, in its own keyspace — this is the load-bearing decision. Facts and captured turns both live at
agentkit:memorySlot:<userId>:<id>, withsessionId/source/deletedas indexed fields (plus unindexedsequence/subIndexfor ordering). There is noChatHistoryin this path any more and no option;read_sessionis always contributed and reads the same records back, sorted(sequence, sourceRank, subIndex)wheresourcedoubles as the intra-turn ordinal (userMessage→agent→agentMessage). -
Why its own prefix, and never
agentkit:memory. A schema describes an index and an index covers a keyspace. Upstash Search does not match a missing field against{$eq: …}and has no$ne— verified live: a doc written withoutdeletedis returned by{userId}alone and by nothing that also filtersdeleted:{$eq:false}. So pointing the slot's stricter schema at the shared keyspace would make every record written by published@upstash/agentkit-sdk@0.6.0silently unreachable. Its own prefix means nothing older is in scope. Costs one of the DB's 10 indexes; do not "optimise" it back into the shared store. -
Recall injects
source: "agent"only. Captured turns share the store but not the ranking — that is the structural fix for the measured poisoning (captured question 50.9 vs a deliberately savedUser likes cucumber.cut from the top 5). The block ends with a livecountof non-fact records pointing atsearch_memory, because black-box testing showed the model does not use a tool it is merely offered: across 32 conversations it calledread_sessionzero times. -
forget_memoryredacts, it does not delete. Text →"",deleted→true; every read butread_sessionfilters tombstones out, andread_sessionrenders[redacted]so a reader cannot mistake removal for "never said". CoreAgentMemory.forgetis still a realDELfor its other callers — the provider redacts by callingadd()with the same id, sinceaddwrites the whole document. -
"all"/"fromModel"dropforget_memory, and this is load-bearing. Those modes store the assistant's replies, and the assistant's reply confirming a deletion quotes the deleted text — so erasure writes a fresh copy of what it erased. Measured over 18 black-box conversations on the rebuilt provider: the curated fact was correctly redacted, and the phrase survived in three other records, allagentMessage, all replies about the deletion (a fourth was the tester's own search query). Agent replies were 18 of 41 records — half the store and the whole leak. A tool that reports "permanently deleted" while that happens is worse than no tool, so those modes contributesave_memory/search_memory/read_sessiononly. Don't "restore the missing tool for consistency" — it was removed because it cannot tell the truth there. -
Config names carry the phase (the object is flat, so they have to):
maxRecallCharacters(recalled block) vsmaxMemoryCharacters(one stored memory),rememberMessages. Renamed pre-release frommaxCharacters/maxEntryCharacters/capture+extract;query/buildRecallQuerywas removed outright (the recall query is always the turn's user text). Every optional field carries a JSDoc@defaulttag — keep that up when adding one. There is nomemoryToolsknob —save_memory/search_memory/forget_memoryare always contributed (plusread_sessionwhen transcripts are on), since a slot with no way to save, search or forget is a strange thing to declare.search_memoryis the manual counterpart to automatic recall: recall only surfaces what matches the current message, so the model needs a way to look up an older fact after a topic change../memoryhad never shipped (published@upstash/agentkit-eve@0.8.0exports only.and./sandbox), so this cost nothing — check that before assuming a rename here is breaking. -
eve floor for this subpath is
>=0.45.2, verified against the builtdistthe same way the sandbox floor is:pnpm packthe package into a throwaway consumer that callsdefineMemorywith both providers, thentscper eve version. 0.45.0 fails (Cannot find module 'eve/memory'and'eve/memory/file'), 0.45.1 fails oneve/memory/filealone, and 0.45.2 / 0.46.1 / 0.47.6 / 0.49.0 / 0.52.2 are all clean; the runtime import throwsERR_PACKAGE_PATH_NOT_EXPORTEDbelow the floor.MemoryProvider's declared shape is byte-identical across 0.45.2→0.52.2, so nothing here is version-fragile. -
What the tests pin down (a PR review flagged that only the
profiletools were covered):memory/memory.test.tshas an offline suite that spiesAgentMemory.prototype.recall/addand scripts the search index, so it asserts recall/capture actually fire at the lifecycle hooks it registers and with what — the exact{userId, topK, query, minScore}, theagentkit_memorySlotindex name, the{userId:{$eq}, text:{$smart}}filter, and that a replayedoperationIdre-queries zero times. The live suite then asserts the JSON documents in Redis (key =recordIdFor(sessionId|sequence|source|subIndex|text), value ={text,userId,createdAt}plus the indexed metadata) and round-trips them back through recall. All of it is mutation-checked: removing a hook or thememory.addcall turns 10 tests red. -
E2E proof:
examples/eve-demodeclares both slots (agent/memory/profile.ts,agent/memory/recall.ts) andevals/memory.eval.tsdrives them with eve'smockModel(AGENTKIT_MOCK_MODEL=1, no OpenAI key). The mock echoes the memory blocks eve injected into its prompt, which is what proves automatic recall. CI runs it next to the extension eval.
- ai-sdk caching:
cacheTools→cachedTool+cachedTools→ nowcachedToolsonly (singularcachedToolremoved; toolName = map key,userIdscopes). - eve
cachedExecute→defineCachedTool(cache key field:cachePrefix→namespace→toolName);recall/saveMemoryTool→defineMemoryRecallTool/defineMemorySaveTool. - Memory + memory-tool scoping:
scope→namespace→userId(string or per-call function). - ChatHistory is back (was removed pending a frontend+backend solution) — now
ChatHistoryon Redis Search; Redis is the durable source of truth (eve's Workflow store is pruned 1–30 days after a run completes, per Vercel plan, so don't rely on it for long-term history). - Removed entirely: the model cache (
ModelCache/SemanticCache,cachedModel,modelCacheMiddleware), Telemetry, the generic Sandbox (sandbox is eve-only), and dead core exportsChatMessage/Logger/noopLogger.
- No script source carries a shebang; the scripts helper adds it. Scripts are defined with
lua(name, body)and run through a script runner (createScriptRunnerinpackages/sdk/src/scripts.ts, used by tanstack-ai viasrc/scripts.tsand by eve; mcp-toolkit has its own copy insrc/shared/scripts.tsbecause it depends on no agentkit package; Python inupstash_hermes_memory/_scripts.py). The runner sends#!lua script_name=<package>-<lang>-<name> flags=allow-key-lockingon the first line, e.g.agentkit-tanstack-ai-js-lock_acquire, so Upstash's script stats can tell which SDK script ran (same scheme as@upstash/ratelimit'sratelimit-js-<script>). Names are unique per package and checked by each package'sscripts.test.ts; the server truncates names at 100 bytes. enableUpstashScriptFlagson every store that runs scripts (same option as@upstash/ratelimit): unset = send the flags, and if the server rejects them (Redis 7+/Valkey "shebang" errors, Redis 6 "near '#'", old Upstash "Unknown metadata value") rerun without them, warn once, and remember that per client;false= never send them;true= always send and throw.truesends the flags even to a client that fell back for another store. To check the fallback against a real Redis or Valkey, run*.non-upstash.test.tsandtest_scripts_non_upstash.pylocally withNON_UPSTASH_REDIS_REST_URL/_TOKENpointing at a REST proxy (e.g. serverless-redis-http) in front of it; they skip otherwise and are not part of CI. In Python thescript_namepart is only sent with telemetry on (the Hermes catalog requires usage reporting to be opt-in);allow-key-lockingis sent either way.- Every
EVALscript runs withflags=allow-key-locking(same as@upstash/ratelimitsince #154). Upstash then locks only the keys the script declares instead of the whole database. The price: every key a script touches must be inKEYS— a key built or read inside Lua fails withERR Dynamic keys are not allowed in Lua scripts when 'allow-key-locking' flag is set(verified live 2026-09-27). Don't pass placeholder keys for optional indexes either; makeKEYSvariable-length and testif KEYS[n]in the script. - Scripts that need a key they can only learn by reading (the artifact store's old run/thread index) read it first, declare it, and compare-and-swap inside the script, retrying on a mismatch.
- Current scripts:
RedisLockacquire/release/extend (tanstack-ai), everedisDocuments()CAS, the tanstack-ai persistence/generation stores, and mcp-toolkit's task update/settle and subscription put. Upstash tolerates a leading newline before the shebang, standard Redis does not — keep it on line 1.
- Naming of the knobs (consistent across all features):
prefix— the baseagentkit:Xkey prefix (config level).ToolCache/AgentMemory/ChatHistoryconfigs andcreateRateLimit/createChatHistoryall useprefix.indexName— the explicit Redis Search index name, separate fromprefix(defaults to the identifier-safeprefix):createSearchToolDefs/createSearchTools/defineSearchTools,AgentMemory, andChatHistoryconfigs.userId— the per-call value that splits data under a prefix (one user's data from another's):AgentMemory.add/recall/forget, the memory tools, and theToolCachekey.toolName— the per-call tool segment of theToolCachekey (the ai-sdkcachedToolsmap key; evedefineCachedTool'stoolNamefield).
redisis optional everywhere → falls back toRedis.fromEnv(). It's the only client knob.- Memory tools:
userIdis required — a string (shared if static; avoid in multi-tenant prod) or(input, ctx/options) => stringto derive per-call. - Cached tools: key is
userId+toolName. ai-sdkcachedTools(map, { userId })only (toolName = map key; no singularcachedTool). evedefineCachedTool({ toolName, userId }). - Rate limiting:
limiteris required (e.g.Ratelimit.slidingWindow(10, "60 s")) —limit/windowwere removed.prefixis the key prefix; the per-user value isidentifier(required on eve'screateRateLimitAuth). - Reactive index (
ReactiveSearchIndex, exported): wraps aSearchIndexand provisions it on the first read (query/aggregate/count) viaexistsOk+ retry. Writes (json.set) never need the index, so features call noensure()on the write path. Used byAgentMemory/ChatHistory/createSearchToolDefs; it's the type each feature's.searchIndexgetter returns. (The oldwithIndexhelper is gone.) - Key naming:
agentkit:rateLimit:<identifier>,agentkit:toolCache:<userId>:<toolName>:<hash>,agentkit:memory:<userId>:<id>(+ optional unindexedsessionId→ aChatHistorysessionId),agentkit:chat:<userId>:<sessionId>,agentkit:memoryFile:<scopeKey>(eve memory-document backend — a hash, not JSON),agentkit:memoryRecall:<userId>:<operationId>(eve recall replay cache),agentkit:sandbox:template:<name>:<templateKey>(default prefixes shown). - Telemetry (mirrors
@upstash/ratelimit): every feature that takes aredisclient tags it via the client's hiddenaddTelemetry(protected in@upstash/redis, so typed structurally), appending to theUpstash-Telemetry-Sdkheader — e.g.@upstash/redis@1.38.0,@upstash/agentkit-sdk@0.2.0,@upstash/agentkit-ai-sdk@0.2.0. Corepackages/sdk/src/telemetry.tsexportsaddTelemetry(redis, { sdk?, enabled? })+SDK_TELEMETRY(both re-exported from the package root); each adapter has its own thinsrc/telemetry.tspassing its package tag, so a client carries both the core and adapter tags. Dedup is aWeakMap<client, Set<sdk>>— one tag per (client, sdk) pair, since the client appends on every call. Opt out:enableTelemetry: falseon any config (threaded down into the core primitive and itsReactiveSearchIndex), the redis client's ownenableTelemetry, orUPSTASH_DISABLE_TELEMETRY. Testing the header is wire-level, not mock-level:@upstash/rediscalls the globalfetch, so thetelemetry.test.tssuites stubglobalThis.fetch, point a client at a fake URL (responseEncoding: false,retry: false,enableAutoPipelining: false— auto-pipelining sends a batch and expects an array body, which breaks a naive stub) and assert on the capturedUpstash-Telemetry-Sdkheader; the sdk suite also runs one live-Redis case proving a tagged request is still accepted. The eve-extension suite (packages/eve-extension/test/) binds mount config the way eve does —globalThis[Symbol.for("eve.ext-config-scope")] = "agentkit"while importingextension/extension.ts, then call the mount factory — and tests the source, notdist/. Failures are swallowed — telemetry must never break the client. Version constants: each package has a committedversion.ts(packages/*/src, extension:extension/lib/) written byscripts/sync-version.mjs, which runs only at release time from rootci:version(changeset version && node scripts/sync-version.mjs) so the constant lands in the release PR next to the package.json bump.build/devmust never regenerate it — no build step may rewrite tracked source (dirty worktrees, watch-mode churn). CI runs the read-only--checkmode to catch drift. Note the installed@upstash/ratelimit@2.0.8has noenableTelemetryoption yet — don't pass one tonew Ratelimit().
- AI SDK v7 stable everywhere. Every package + demo pins
aito exactly7.0.173.eve(0.63.0 through 0.69.0 alike) declaresaias a peer (^7.0.105— it sat at^7.0.82from 0.47.6 through 0.52.3, moved to^7.0.93somewhere in 0.53.0 → 0.55.0 and to^7.0.105by 0.61.0, so the 0.52.3 → 0.55.0 bump forced the repo-wide pin7.0.87→7.0.101and the 0.55.0 → 0.63.0 bump7.0.101→7.0.107), so the apps/packages provide the single copy. Providers:@ai-sdk/openai^4.0.71,@ai-sdk/provider^4.0.17,@ai-sdk/react^4.0.110(all stable ranges; bump them withpnpm -r update "@ai-sdk/*"when eve moves — a stale@ai-sdk/reactrange can pin a second, olderaicopy via its peer resolution, which is exactly the two-copy breakage to avoid). (History: the repo was on7.0.0-beta.178foreve@0.13.1,7.0.30foreve@0.25.2, then7.0.58foreve@0.32.0–0.47.3— the exact pin moves in lockstep with eve'saipeer range.) - A stale
aipin is a hard install failure, not a warning. eve 0.47.6 raised itsaipeer^7.0.58→^7.0.82. pnpm only printsunmet peer aiin this workspace, but a real npm consumer on the old exact pin getsnpm error code ERESOLVE … peer ai@"^7.0.82" from eve@0.47.6and cannot install without--force/--legacy-peer-deps. Treat eve'saipeer as a release-blocking input on every eve bump; check it withnpm view eve@<v> peerDependencies.ai. This fired again on 0.52.3 → 0.55.0 (peer^7.0.82→^7.0.93):npm install eve@latestbeside the oldai@7.0.87pin dies withnpm error ERESOLVE … peer ai@"^7.0.93" from eve@0.55.0. pnpm in-workspace was silent about it. - The
@ai-sdk/*bump riding along withai7.0.87 collapsed a long-standing secondaicopy:@ai-sdk/react@4.0.62was resolving its ownai@7.0.59beside the pinned one (visible onmainas twoai@…keys inpnpm-lock.yaml). Afterpnpm -r update "@ai-sdk/*"the lockfile has exactly oneai@7.0.87. Verify withgrep -oE "^ ai@[0-9][^:(]*" pnpm-lock.yaml | sort -uafter any bump. It recurs every time theaipin moves and you forget the provider update. On the 0.52.3 → 0.55.0 bump, pinningai@7.0.101alone left the lockfile with two copies —@ai-sdk/react@4.0.90still dragged in its ownai@7.0.87.pnpm -r update "@ai-sdk/*"(which moved the ranges to^4.0.66/^4.0.14/^4.0.104) collapsed it back to one. Run it as step two of everyaipin bump, then re-run thegrep. - Why exact-pin and not a pnpm
override: because everyone lands on the same exactai, pnpm installs a single copy. Two copies ofaicause type/identity breakage. An override was tried and removed as unnecessary — keep it that way unless a dep forces a differentai@7. - No
pnpm.overridesin rootpackage.json. Version alignment is the mechanism. (@types/reactwas also deduped by aligningai-sdk-demoto19.2.15, not by an override.) pnpm-workspace.yamlsetsminimumReleaseAge: 0so fresh eve/ai releases aren't gated.- Two
zod4.x copies exist in the lockfile (@vercel/cli-config, eve-transitive, wants its own) — preexisting and harmless; our packages all resolve one shared zod in this workspace. ⚠️ "one shared zod" is a property of OUR LOCKFILE, not of a consumer install — never infer consumer dedup from a green repo.packages/eve-extensionused to pin"zod": "4.4.3"exactly whilepackages/sdkdeclares"^3.23.8 || ^4". In the workspace both resolved to 4.4.3, so everything was green; in every real consumer install (npm and pnpm) the sdk resolved zod4.6.5and the extension got its own nested4.4.3— two instances. zod changed its internal schema representation in 4.6.0, so a schema built by zod ≥4.6.0 cannot be converted by zod <4.6.0 (measured: 4.4.3 ✗, 4.5.0 ✗, 4.6.0 ✓, 4.6.5 ✓). The extension's search resolvers callz.toJSONSchema(defs.<tool>.inputSchema)on defs built by the sdk's zod, so cross-instance it threwCannot read properties of undefined (reading 'push'); eve logged[eve:dynamic-tools] … failed — skipping its complete resultand all three search tools silently never mounted, witheve buildgreen. Fixed by widening the extension to"^4.4.3"so normal resolution dedupes to one instance. Rules that follow: (1) never exact-pinzodin a published package — a range that overlaps the sdk's is what makes dedup possible (exact-pinning is the right move forai, the opposite of the right move forzod, becauseaiis pinned identically in every workspace package whilezod's ranges differ); (2) a dual-instance bug of this class is invisible to every in-repo check — only a packed-tarball consumer install can see it, so verify dependency changes topackages/eve-extensionwithpnpm packinto a scratch consumer (see "Verifying a consumer install").- v7 type renames to know:
ToolCallOptions→ToolExecutionOptions<never>. v7'sLanguageModelMiddleware = Omit<LanguageModelV4Middleware,'specificationVersion'> & { specificationVersion?: string }so middlewares need nospecificationVersion(v6 required'v3', v5 required none — don't add it on v7).
-
Tests run against a REAL (production) Upstash Redis. Do NOT mock Redis. Only LLM calls are mocked, except the
e2e.test.tsfiles which hit real OpenAI. -
Models: unit/e2e tests use
gpt-4o(TEST_MODEL); READMEs + demos usegpt-5.4-mini. -
Each package has
src/test-support.ts:hasRedisCreds,testRedis()(Redis.fromEnv),uniquePrefix(label)(colon-separated — key prefixes only),uniqueUserId(label)(dash-separated — use for userIds, which reject:),cleanupKeys(redis, prefix)— loads repo-root.envvia dotenv. ai-sdk also hashasOpenAIKey,TEST_MODEL. Suitesdescribe.skipIf(!hasRedisCreds)so they skip without creds. -
vitest:
fileParallelism: false,testTimeout: 30_000. -
Upstash DB caps at 10 search indexes (
ERR Exceeded max index count of 10). Tests mustdrop()/ reuse indexes and run sequentially. There is noSEARCH.LISTcommand to enumerate them. -
Indexing is async, and visibility needs BOTH halves of a rule. To assert on a search result you must satisfy both, or the docs may never become visible — not "late", never:
- The index must already exist when the doc is written. A doc written while the index is still
missing can be dropped by the create-time backfill permanently. Anything relying on the reactive
create (
ReactiveSearchIndexprovisioning on the first read) to pick up docs seeded just beforehand is a coin flip. searchIndex.waitIndexing()must be called after the write, on that already-existing index.
Measured against live Redis with a 3-way probe —
provision-then-write-then-waitreturned the full result set on the first read (0ms);provision-only(no post-write wait) andwait-only(index created after the writes) both sat at 0 hits for the full 10s probe and never recovered. Waiting longer does not help: a 25s poll on the old ordering still failed. So order is provision → write →waitIndexing()→ read, andwaitIndexing()on an index that doesn't exist yet is a silent no-op, which is the trap. - The index must already exist when the doc is written. A doc written while the index is still
missing can be dropped by the create-time backfill permanently. Anything relying on the reactive
create (
-
This was the cause of the long-running
Testflake, and it is fixed.packages/sdk/src/ chat-history.test.ts("lists a user's chats" →expected [ 'c1' ] to include 'c2') andpackages/eve/src/search-tools.test.ts("search runs a $smart query…" →expected 0 to be greater than 0/expected 1 to be greater than or equal to 2) red-lit CI repeatedly, including the 2026-08-26 nightly onmain(eve 0.44.3) and three runs of PR #27. Both now provision the index before seeding and keep a smallpollUntilhelper as insurance for residual lag; assertions are unchanged. 10/10 consecutive green each after the fix (was 4/10 and 4/10). If either goes red again, treat it as a real regression, not noise. -
The provision-before-seed fix was only applied to those two files.
packages/ai-sdk/src/ search-tools.test.ts,packages/ai-sdk/src/memory.test.ts,packages/eve/src/memory.test.tsandpackages/sdk/src/memory.test.tsstill seed before the index reliably exists, so they flake the same way (expected 0 to be greater than 0,recalled[0]undefined) — measured 2026-09 at roughly 4-in-6 red on a one-index throwaway DB, and confirmed identical on pristinemain, so it is not a regression from any dependency bump. On the real 10-index DB the pressure is far lower. Until they get the same treatment, verify a suspicious red byFLUSHDB-> one warm-up run (which provisions the index) -> a second measured run, and always A/B againstgit stashbefore blaming a bump. -
upstash start-redisneeds no account or API key (confirmed 2026-09):npm i -g @upstash/clithenupstash start-redisprints a free REST URL + token, valid 72h. That is how to get creds in a box that has none — write them to the repo-root.env(gitignored) and the suites stop skipping. -
Throwaway DBs from
upstash start-redis(the@upstash/clicommand;npm i -g @upstash/cli) cap at one search index, not 10 —ERR Exceeded max index count of 1. A singlepnpm testcascades into bogus create-index failures on one. Run one test file at a time with aFLUSHDBbetween (curl "$URL" -H "Authorization: Bearer $TOKEN" -d '["FLUSHDB"]'; FLUSHDB does drop indexes, andSEARCH.DROP <name>is the only other lever — there is no list command). -
Throwaway DBs also die mid-run, and the failure mode looks exactly like a code regression. Measured 2026-09-15: every
start-redisdatabase (they all live behind the sharedp2-global-eph.upstash.ioendpoint) went unreachable after roughly 3–6 test files — the REST endpoint stops completing the TLS handshake, socurlhangs to its timeout and vitest reportsTest timed out in 30000ms/Hook timed out in 10000msacross every live suite at once, including ones that never touch search (tool-cache,chat-history). Metrics for the dead DB showcommands_totalstuck at a tiny number. Re-fetching the same credentials with theIdempotency-Keyheader does not revive it; only a brand-newupstash start-redisdoes. So:PINGbefore each test file, and reprovision + rerun the file when the ping fails — a self-healing loop turns a cascade of red into a clean green run. A whole-suite red where the failures are timeouts rather than assertions is an infrastructure death, not a regression; confirm withcurl … '["PING"]'before believing it. (curl -X POST https://upstash.com/start-redisreturns the same kind of database as the CLI.) Butstart-redisis rate-limited: measured 2026-10-01, ~20 provisions inside a few minutes (one per test file) gotHTTP 429with an empty body and noRetry-After, and it stayed 429 for 10+ minutes. A 429 makes the Endpoint/Token greps come back empty, so a script that doesn't check the status code silently runs the suite with no Redis. Reuse one database and reprovision only when its PING fails; check for200before parsing. On a box wherenpm i -gis not writable, install the CLI to a prefix:npm i -g @upstash/cli --prefix /tmp/upstash-cli→/tmp/upstash-cli/bin/upstash. -
A brand-new throwaway DB is often DEAD ON ARRIVAL — always
PINGit before writing it to.env. The note above says "only a brand-newstart-redisdoes [revive things]"; that is too optimistic. Measured 2026-09-22: a just-provisioned database answeredcurlwith exit 35 /SSL_ERROR_SYSCALLon the very first request and never recovered, and three consecutive fresh databases each failed the 6th of 6 warm-up pings. They all share thep2-global-eph.upstash.ioendpoint, so "fresh" buys nothing on its own. Provision in a loop and only accept a candidate that answers several consecutivePINGs, e.g.:for i in $(seq 1 6); do out=$(curl -s -X POST https://upstash.com/start-redis) U=$(echo "$out" | grep -oP '(?<=\*\*Endpoint:\*\* )\S+'); T=$(echo "$out" | grep -oP '(?<=\*\*Token:\*\* )\S+') ok=0; for n in $(seq 1 6); do [ "$(curl -s --max-time 12 "$U" -H "Authorization: Bearer $T" -d '["PING"]')" = '{"result":"PONG"}' ] && ok=$((ok+1)); sleep 2 done [ $ok -ge 6 ] && { printf 'UPSTASH_REDIS_REST_URL=%s\nUPSTASH_REDIS_REST_TOKEN=%s\n' "$U" "$T" > .env; break; } done
A healthy DB runs a whole eval in ~350ms; when you see a mocked eval take 3–4 minutes, that is
@upstash/redisburning its retry/backoff budget against a dead endpoint, not slow code. The distinguishing detail in a failing eval gate:observed <tool> calls: {}means the tool mounted and ran (and Redis failed underneath), whereasobserved tools: [<other>]means the tool never mounted — only the latter is a real code problem. Idle control settles it: provision one more DB, run nothing against it, PING it every 15s. On 2026-09-30 an untouched DB passed 6/6 warm-up PINGs and was dead 25s later; when that happens, no live result from that box means anything. -
The read-your-writes sync-token bug is FIXED as of
@upstash/redis@1.38.4(the repo is pinned^1.38.4;packages/eve's peer floor is>=1.38.4). Historically, in 1.38.0 and earlier back to 1.34.5,HttpClient.request()builtrequestHeadersfromthis.headersand only then copiedthis.upstashSyncTokeninto it, so every request was sent with the token from one response ago; a read issued right after a write could reach a replica that hadn't caught up. It was a race — the replica is normally current within a round trip — so it only ever surfaced as a rare CI red, and it cost PR #33 one (memory/memory.test.ts, "creates with expectedVersion null, then round-trips through read" —expected null to deeply equal {…}). This was never the search-index lag documented above; it hit plainGET/HMGET/TTLon ordinary keys. Do not reintroduce workarounds for it, and do not lower the floor below 1.38.4. To re-verify after a dependency change, stubfetchand readupstash-sync-tokenoff each outgoing request: three calls should send["", "tok-1", "tok-2"], not[null, "", "tok-1"]. Note the search-indexpollUntils in the suites are for a different problem and stay. -
Scores are BM25 (unbounded), not
[0,1]—minScorethresholds are BM25 values. -
.envis gitignored — never commit creds. NeedsUPSTASH_REDIS_REST_URL/_TOKEN; optionallyOPENAI_API_KEYandUPSTASH_BOX_API_KEY.
- Create:
redis.search.createIndex({ name, dataType: "json", prefix, schema })(idempotent — catch "already exists"). Handle:redis.search.index({ name, schema })→.query({filter, limit}),.aggregate(...),.count(...),.waitIndexing(),.describe(),.drop(). - Write docs as JSON under the prefix:
redis.json.set(prefix + id, "$", {...}). queryreturns[{ key, score, data }].- Schema via
s:s.object({...}),s.string(),s.number(),s.boolean(),s.date(),s.keyword(),s.facet(),.noTokenize()(use for filter/tag fields). - Filter ops:
$smart,$phrase,$fuzzy,$regex,$eq,$lt/$lte/$gt/$gte,$in,$range,$and/$or/$must/$should/$mustNot. Aggregations:$terms,$stats,$sum,$avg,$min,$max,$count,$histogram,$percentiles,$cardinality.
- Layout: three entry points, built to
dist/tasks/index.js,dist/events/index.jsanddist/upstash.js.src/tasks/index.tsandsrc/events/index.tsmust never import an@upstash/*package (check the builtdist/{tasks,events}/index.jsimports); the backends live insrc/{tasks,events}/backends/and are exported only fromsrc/upstash.ts. There is no root export. Shared:src/shared/{auth,clients,crypto,env}.ts(principal resolution, lazy Upstash clients +nonRetryable+readQStashJson+boundToUrl, WebCrypto helpers, and the dependency-freeenv/INTERNAL_ERROR),src/telemetry.ts,src/version.ts. The cores may importshared/env.tsbut nevershared/clients.ts— it imports@upstash/redisand@upstash/qstash, and the bundler would pull them into/tasksand/events(this happened once, caught only by grepping the built chunks:grep -l "@upstash/" dist/chunk-*.js). WebCrypto only (nonode:crypto/node:net), so it runs on edge runtimes;signWebhook,SecretBox.seal/openandsubscriptionIdare async for that reason. - Native MCP Tasks by default, tools as the fallback (DX-3209, 0.2.0).
new McpTasks({ mode }):"native"(default) or"tools"(exactly 0.x). In native mode atools/callwhose per-request envelope declares the extension (ctx.mcpReq.envelope["io.modelcontextprotocol/clientCapabilities"] .extensions["io.modelcontextprotocol/tasks"], an object) is answered with{ resultType: "task", taskId, status, statusMessage, createdAt, lastUpdatedAt, ttlMs, pollIntervalMs }; every other call gets the 0.x tool result (structuredContent= the task object + a text line telling the model to polltask_status). Claude Code CLI ≥ 2.1.304 declares the extension on main-conversation calls only (not subagents, not VS Code/desktop), so the fallback is needed even for Claude Code:task_status/task_cancelare always listed. No HTTP wrapper — all via SDK 2.3.x extension points insideattach(server):server.server.registerCapabilities({ extensions: { [TASKS]: {} } })(shows onserver/discover; must run before connect, whichcreateMcpHandlerandmcp-handlerboth guarantee),server.server.setRequestHandler("tasks/get" | "tasks/cancel", { params }, …)(the 3-arg custom-method form), and returningresultType: "task"from the tool handler (the SDK's encode seam passes a handler-providedresultTypethrough ontools/call; it also addscontent: [], harmless).tasks/get=resultType: "complete"+ task fields +resultwhen completed /error {code, message}when failed (handlerisError→ message = the result's text; transport failure → stored code/message;error.datanever leaves Redis).tasks/cancelreuses thetask_cancelpath (cancelOwned) and answers{ resultType: "complete" }. Unknown, malformed (non-UUID, never reaches the store), foreign or unauthenticated →ProtocolError-32602with the same message (Claude Code reads -32602 as unknown task).tasks/updateis served (see the next bullet);tasks/list,tasks/resultare not registered → SDK's-32601. In native mode the task tool's description is the config's own (no "call task_status" line: with it, Claude Code's model polledtask_statuson top oftasks/get, 9 calls in one live run) andtask_status's description adds "only for a tool result that told you to call task_status" — dropping the line alone still left 1-6 calls per task in headless 2.1.309 runs, the extra sentence took it to 0 of 3 runs.mode: "tools"keeps the old descriptions. SDK gotchas: on 2026-07-28 the HTTP entry requiresMcp-Name: <taskId>ontasks/*(SEP-2663; the SDK client sends it, hand-written curl must too), and envelope validation rejects a non-object extension value ([TASKS]: true→ -32602 before dispatch). Tests:src/tasks/native.test.ts. - Asking the user:
task.elicit(DX-3209 follow-up). In-memory and Workflow only; not QStash (the user rejected the "re-run the handler up to the question" replay design as too odd). Type-level: asking is its own boolean,TaskDispatcher<CanAsk extends boolean = false, TContext = unknown>(CanAsk first; a type alias, not an interface:truemakeswaitForInput+resumerequired,falsetypes them?: never).InProcessDispatcher implements TaskDispatcher<true>,WorkflowDispatcher→<true, WorkflowContext>,QStashDispatcher/ testManualDispatcher→false.implementsnever changes a class's type, so CanAsk must be visible in the shape; that's why it's tied to the two methods.McpTasks<Dispatcher = InProcessDispatcher>is generic over the dispatcher itself and derivesCanAskOf<D>(D extends TaskDispatcher<true, never>) andContextOf<D>(inferred fromcreateExecuteHandler'sTaskEndpoints<infer C>); a class over<CanAsk, TContext>can't infer CanAsk from a structural type without a brand. No dispatcher / store-only → InProcessDispatcher → elicit. Handler:TaskHandler<Args, CanAsk = false, TContext = unknown>,task: TaskContext & (CanAsk extends true ? TaskElicit : unknown) & TContext;TaskElicitlives intypes.tsbut is not exported from/tasks.TaskInputContext/TransportContextare gone;run(taskId, context: TContext, journal?)andwaitForInput(wait, context: TContext).task.elicitis a type error under QStash and non-opted dispatchers (@ts-expect-errortests ininput.test.ts). Runtime:elicitis on every context; withoutdispatcher.waitForInputit settles the taskfailed("task.elicit needs a dispatcher that can wait…, and QStashDispatcher can't…") and throws the internalTaskStopped, whichrunswallows (QStash acks 200). Flow: keys by call orderelicit-<n>, one open question at a time, max 16 per task (Claude Code ignores >16 keys); a journaledmcp-task:ask:<n>step reads the store (answer already there → return it) or writesstatus: "input_required",statusMessage= the question,inputRequests: { key: inputRequired.elicit(params) }; then loopdispatcher.waitForInput({ taskId, key, round, expiresAt, pollIntervalMs }, ctx)+ a journaledmcp-task:look:<n>:<round>store read until answered / terminal-or-missing (→TaskStopped). The store is the source of truth; a wait only says when to look. In memory: sleep untilresume/cancelwakes it or onepollIntervalMs(so Redis + in-process and expiry work too). Workflow:context.waitForEvent("mcp-task:wait:<key>:<round>", eventId, { timeout ≤ 600s })andresume=client.notify({ eventId, workflowRunId })(lookback); a lost notify is picked up at the next look. Event ids may only hold letters, digits,-,_,.— the QStash dev server answeredmcp-task:<id>:<key>with 400 and the run stopped (caught only by the real E2E; nowmcp-task.<taskId>.<key>, and the fake engine ininput.test.tsenforces it).elicitinsidetask.runthrows.run()now returns early only for missing/terminal tasks (a Workflow replay comes back throughrunwhileinput_required), andisCancelled()is "missing or terminal" — both used to be!== "working", which would read a paused task as cancelled. Answers:TaskStore.respond(taskId, responses, statusMessage)— atomic, only whileinput_required, only open unanswered keys; when none is left open →working,inputRequestscleared, returns the keys (exactly one call resumes). Redis:RESPOND_SCRIPT(allow-key-locking, one KEY) stores each answer in its ownresponse:<key>hash field (pre-encoded JSON, never re-encoded in Lua;inputRequestsiscjson.decoded only for its keys);getfolds those intoinputResponses.tasks/update: the SDK liftsinputResponsesout of params intoctx.mcpReq.inputResponses(+droppedInputResponseKeysfor wrapped{method,result}entries → refused); shape/size validated before any store read (≤16 entries, keys[\w.:-]{1,64}, ≤64 KiB JSON, each{action, content?}with flat content) →-32602 "Invalid inputResponses…"; then the same ownership path astasks/get→-32602unknown. Accepted content is validated with the SDK'sacceptedContent(…, schema); a mismatch fails the task.inputResponsesnever leave the store (toWirestrips them;inputRequestsonly shown whileinput_required). Fallback: no model-callable answer tool on purpose (the model or a prompt injection could approve on the user's behalf).task_statuson aninput_requiredtask returnsinputRequired({ inputRequests })(MRTR) when the request is 2026-07-28 and its envelope declareselicitation({}or withform); the client's retry carriesinputResponses, which go through the same validation +answer(). Otherwise its text says only the user can answer and suggeststask_cancel. Same inmode: "tools". Claude Code (2.1.309) answers only in interactive sessions; headless stream-json sendstasks/cancel~3 ms after seeinginput_required(verified clean on both backends: memory handler released, Workflow runRUN_CANCELED). Tests:src/tasks/input.test.ts(a replaying fake Workflow engine driving the realworkflowRoute+WorkflowDispatcher, real Redis for the Redis+in-process variant), Redisrespondcases inbackends/qstash.test.ts. - Class API: register at module scope,
attachper request (DX-3022 review item 1; classes since DX-3209).const tasks = new McpTasks({...})andtasks.registerTask(name, config, handler)run at module scope and fill the handler map with no server;tasks.attach(server)adds every registered tool + the shared tools inside the per-request factory. Events are the same:new McpEvents({...}),events.registerEvent(name, config)(returns{ name, emit }),events.attach(server). Registering on the module-scope instance is the point; what stays banned is registering on the per-request server (the 0.x-eraregisterTask(server, …)shape): it only filled the map when a server was built, so a cold instance serving only/api/executethrew "No task handler" and every delivery 500'd. Don't bring it back, and don't reintroduce the top-levelcreateServer();workaround.attach(server)is the only wiring: the experimental SDKextensions: [tasks]shape (id/setup(ctx), typescript-sdk #2820) was prototyped and deliberately not shipped.createTaskLayer/createEventLayer/define/registerwere removed as a clean break (no aliases). Tests: the "never built a server" cases insrc/tasks/core.test.tsandsrc/events/core.test.ts. - Ownership (
principalis required, both classes).new McpTasks/new McpEventsthrow without it. It receives{ auth, request }(SDK v2'sctx.http.authInfoandctx.http.req), may be async, and stampstask.owner/subscription.subscriber.authis only what the app's route passed tohandler.fetch(request, { authInfo })after verifying the token: the SDK never derives it from headers.requestis unverified, for cookie/session apps; docs warn against trusting caller-set headers.PrincipalResolverreturns a plain string (string | Promise<string>; the old{ id, context }form is gone): it throws to refuse, andresolvePrincipalalso fails closed on a rejection or anything but a non-empty string. Refused = not authenticated: the call is refused (isError"Not authenticated" for tools, reasonnot_authenticatedfor events/*) — no anonymous mode, fail closed; a stored task without an owner answers nobody. Single-tenant servers passprincipal: () => "local".task_status/task_canceltakez.uuid()task ids (so nothing else reaches a Redis key) and report a non-owned task as unknown (no existence oracle). Owners are JSON-encoded on write, so auto-deserialization hands them back as strings and a plain===compares them. The publicMcpTasksis only{ registerTask, attach, createExecuteHandler }; a dispatcher getsrun/failas the argument of itscreateExecuteHandler(endpoints), and also through the optionalTaskDispatcher.connect?(endpoints), which theMcpTasksconstructor calls once (that is how a dispatcher with no endpoint gets connected). - Generic errors and per-user limits (DX-3209 security review, kept simple). Every client-facing
handler is wrapped:
guardTool(task tool,task_status,task_cancel) turns any throw fromauthorizeor the store intoisErrorINTERNAL_ERROR_MESSAGE("Internal error. Try again later.",shared/env.ts), andguardMethod(tasks/get|cancel|update,events/subscribe| unsubscribe) intoProtocolError(-32603, same text); aProtocolError(the intended -32602s, -32015) passes through, and the real error goes tologInternalError→console.error. Before, a store error likeWRONGPASS at https://…upstash.ioreached the model. A missing/weakMCP_EVENTS_SECRET_KEYis now also only in the log (subscribe gets -32603).authorizereturningfalseand not authenticated keep their own messages. Limits instartTask, both beforestore.create:maxArgsBytes(default 64 KiB,JSON.stringify(args)UTF-8 bytes, checked beforeauthorize) andmaxActiveTasks(default 100,Infinity= off and skips the count; checked afterauthorize) viaTaskStore.countActive(owner)(working + input_required). Memory: a scan of the map. Redis:<prefix>active:<owner>zset of task ids scored by expiry,ZADDin the createMULTIwithPEXPIRE NX+PEXPIRE GT(a short-TTL task once expired the whole set with a plain PEXPIRE, caught by the live test);countActive=ZREMRANGEBYSCOREthe expired, pipelineHGET statusper id,ZREMmissing/terminal, count the rest. No Lua: two concurrent creates can overshoot by a little, accepted and documented. - In-memory task backends ship, and are the defaults (DX-3209, 0.2.0).
src/tasks/memory.ts, exported from/tasks:MemoryTaskStore(lazy expiryttlMsafter create, swept at most once a minute oncreate, no timers; first terminal write wins; hands out copies) andInProcessDispatcher(implementsconnect; runsrun(taskId)on asetTimeout(0)after the tool call answers; a throw →console.error+fail({ -32603, "The task handler threw an error", data: { error } }), no retries;cancelis a no-op,isCancelled()does the work;createExecuteHandleranswers 404 but still connects;drain()for shutdown and tests; oneMcpTasksper instance, a secondconnectthrows).store/dispatcherare optional onMcpTasks(internalTaskBackendsunion inMcpTasksOptions: both, store only, or neither); a dispatcher without a store throws (QStash + memory store would run on an instance that never saw the record). Omitting the dispatcher inNODE_ENV=productionlogs oneconsole.warnper process; passing the in-memory backends explicitly silences it. The warning avoids the literal@upstash/sogrep "@upstash/" dist/tasks/index.jsstays empty. The handle's firststatusMessageis"Queued"(was "Queued for durable execution", untrue in memory). Tests:src/tasks/memory.test.tsruns the defaults end to end in native and tools modes. Test doubles stay insrc/test-support.ts:ManualDispatcher(connected byMcpTasks, drive withrun/fail) andInlineDispatcher(the shippedInProcessDispatcher+ adispatchedlog). The events in-memory backends (MemorySubscriptionStore,InlineDelivery) are still test-only, not shipped. - No
idempotencyKey(removed 2026-10-08, keep it simple; add back only if someone asks). Task ids are alwayscrypto.randomUUID(), soTaskStore.createis a plainMULTI(HSET+PEXPIRE) returningvoid— no create-if-absent script, since a collision cannot happen.ttlMsis always a positive number (null= unlimited was removed: it let tasks live forever). - Workflow route steps first (fixed 2026-10-08, caught by the e2e failure check). Workflow
authorizes every request, the failure callback included, by running the route function on a
DisabledWorkflowContextuntil its first step; a route that throws or returns before any step is refused (Not authorized to run the failure function). A handler that threw before its firsttask.runtherefore never reachedfailureFunctionand stayedworkinguntil its TTL.workflowRoutenow runs amcp-task:startstep before anything else. - Default task TTL is 1 day (changed 2026-10-08 from 5 minutes). The TTL counts from creation and is never extended, so 5 minutes let a slow task plus its QStash retries expire mid-run and read as "unknown task". The demo servers use the default.
- Signing keys required, no fail-open.
QStashDispatcher,WorkflowDispatcherandQStashDeliveryverify withreceiveror aReceiverfrom theQSTASH_*_SIGNING_KEYenv vars, and throw on the first request when neither exists (resolved outside the verifytry, so it is not misreported as a 401).WorkflowDispatcherpassesreceivertoserve()explicitly because Workflow's own default silently skips verification when the env vars are missing; theservehandler is built on the first request so route modules still evaluate at build time. Workflow does not bind the signature to the URL (verified in@upstash/workflow1.3.3 and 1.4.0:verifyRequestcallsverifier.verify({ body, signature })with nourl), so a QStash signature issued for any other endpoint of the same account was accepted and the task ran — measured by reverting the fix. The receiver handed toserve()isboundToUrl(receiver, url);workflow.test.ts"refuses a signature QStash issued for another endpoint" guards it. Signature tests use a realReceiverwith test keys and real HS256 JWTs (signQStash/qstashRequestintest-support.ts): wrong key, wrongsub, wrong body hash, expired — never a stubbedverify. - Telemetry:
addTelemetry(Redis) andaddQStashTelemetry(QStashClient, or a WorkflowClientvia its.client) append@upstash/mcp-toolkit@<v>toUpstash-Telemetry-Sdk, once per client;enableTelemetry: falseon each backend opts out. - Round trips:
RedisTaskStore.createis oneMULTI;updateandsettleshare one guarded-write script (terminal statuses hardcoded as JSON literals) that returnsHGETALLafter the call.updatereturnsvoid(no-op on a missing or terminal task;UnknownTaskErroris gone),settlereturns the task after the call (null only when missing).task_cancelcallsdispatcher.cancel(taskId)when the returned status iscancelled—cancelmust be idempotent. There is nodispatchId:QStashDispatcher.cancelis a no-op (a redelivery of a cancelled task finds it settled and does nothing), Workflow's run id is the task id. - No QStash
deduplicationId(tasks or events): the layer dispatches each task once, and an event's id reaches the host aswebhook-id, which is where Standard Webhooks dedupes. Workflow'sworkflowRunIdis the task id; that is only safe because ids are random (Workflow refuses a reused run id). A faileddispatchsettles the fresh recordfailed("Could not be queued") and rethrows. - Workflow context is inferred from the dispatcher (
McpTasks<Dispatcher>→ContextOf), sonew McpTasks({ dispatcher: new WorkflowDispatcher(...) })typestask.run/task.sleepwith no type argument; a test inworkflow.test.tskeeps it that way. RedisSubscriptionStore= one index per event (<prefix>idx:<event>, a zset scored by expiry, no TTL — bounded by the number of event names) plus<prefix>sub:<id>withPX.putanddeleteare plainMULTIs (the old Lua PUT and the 256-subsetargsKeyindex are gone);putprunes expired members.find(event)= oneZRANGEby score +MGETs of at most 1,000 keys, and the layer filters in JS (matches(sub.args, values)). O(subscribers of the event) per emit — fine at MCP-host scale; revisit only if an event gets tens of thousands.- No secret defaults:
MCP_EVENTS_SECRET_KEYhas no fallback, demo included; the event layer resolves it on first use (not at construction, so builds without env still work) and a missing key throws rather than dropping deliveries. - Running a missing/expired task is a no-op (QStash acks 200) instead of throwing — a retry cannot fix it. Handler throws are logged with the task id before the 500.
- Design choices that differ from the naive version (all covered by tests):
TaskStore.settleis a guarded, atomic terminal transition (a Lua script on Redis) so atask_canceland the executor completing cannot clobber each other — first terminal write wins; the store keeps one hash field per task property (not one JSON blob) so a progressupdateand a cancel never overwrite each other's fields; and the core never settlesfaileditself — only the dispatcher does, once it has stopped retrying. - Redis encoding: every hash field is written
JSON.stringifyd and read back with no decode of our own —@upstash/redisauto-JSON.parses responses, so the single parse is the exact inverse. Decoding again turns astatusMessageof"123"into the number123(this actually happened). - QStash retry budget must outlast a restart.
Upstash-Retried(count so far, from 0) is the only retry header; there is no max-retries header, which is why the final failure comes from QStash'sfailureCallback(posted to the same route,sourceBody= the original body) rather than from counting attempts (isFinalQStashAttemptis gone). With a flat"1000"delay a kill-9'd server exhausts all retries in ~10s and the task is dead-lettered while still readingworking— observed, then fixed, then re-verified end to end (kill -9 mid-task → restart → QStash redelivery →completed).retriesis plan-capped: the local dev server and the free tier reject anything above 5 withquota maxRetries exceeded(this bit aDEFAULT_RETRIES = 12attempt — the tool call comes back as anisErrorresult carrying that message, not as a thrown error). So the budget is bought with backoff instead:DEFAULT_RETRIES = 5andDEFAULT_RETRY_DELAY = "min(pow(3, retried) * 1000, 300000)"≈ 2 minutes over five attempts. - The dispatcher owns its delivery endpoint (
TaskDispatcher.createExecuteHandler(endpoints), surfaced astasks.createExecuteHandler();EventDelivery.createDeliveryHandler(send)likewise, sharingreadQStashJsonfor verify + parse): signature verification, task-id parsing and the retry status codes live in the transport, so an app route is one line and cannot forgetReceiver.verify. Modelled on Vercel Workflow'sQueue.createQueueHandler(see below). Status contract: 200 ack, 500 only when the task threw, and 489 +Upstash-NonRetryable-Error: truefor a bad signature or body. QStash retries every other non-2xx, 401 and 400 included (checked against the QStash retry docs 2026-10-08), so 489 is the only way to stop it. The same contract holds forQStashDelivery. The receiver is resolved lazily but outside the verifytry, on purpose: resolving atcreateExecuteHandler()would fail Next.js builds that import route modules without env. Verification uses the publishedurl, notrequest.url, because behind a proxy the incoming URL is the internal one while QStash signed the public destination. - Ecosystem context (verified 2026-09). Keep two axes apart when reading this — is there an
interface you can implement is not does Redis work today, and the answers invert.
Among official MCP SDKs, only C# ships a store interface you can implement (
IMcpTaskStore, 7 methods) — but the only in-box implementation isInMemoryMcpTaskStore, so Redis is homework. Rust'sTaskManageris a concrete in-memory struct with no trait; Python/Java have store interfaces only in unmerged PRs; Go/Kotlin/Swift/Ruby have none. Unofficial FastMCP is the mirror image: no implementable seam (Docket is both queue and store, and you pick a backend by URL scheme —memory://orredis://, nothing else), but Redis works out of the box with one URL, and it is the only tasks implementation anywhere that makes the work durable (Docket queue plusworker_cliworkers out of process; the memory backend is single-process). No official SDK in any language abstracts execution — all of themTask.Run/tokio::spawn/.subscribe()in-process, i.e. durable record, non-durable work. So this package'sTaskStore+TaskDispatchersplit is not a port of prior MCP art — the closest analogue is Vercel Workflow'sWorld = Storage + Queue + Streamer. - Tests:
src/{tasks,events}/core.test.tsdrive a realMcpServerthroughcreateMcpHandlerover genuine JSON-RPC;src/*/backends/qstash.test.tshit real Redis. All run under the root vitest config. The demo'spnpm e2e(scripts/e2e.mjs) is the end-to-end check and runs in CI after the example build: it starts the QStash dev server (:8181) andnext start(:3100) withMCP_TOOLKIT_E2E=1, then runsscripts/smoke.mjsagainst/api/mcpand/api/mcp-workflow. No model. Users areBearer demo-<name>(app/lib/auth.ts; no header =demo-user). It covers completion, cancel, cross-user isolation, 401, the failure path (always_fail, defined only underMCP_TOOLKIT_E2Ewith retries cut), refused unsigned/forged deliveries, filtered and signed webhooks,authorizeat delivery (demo-internnever gets production), and 410 deleting the subscription (checked in Redis).pnpm smokealone runs the same checks against a running app. The demo keeps tasks (Report Desk,/api/mcp) and events (Deploy Watch,/api/deploy-watch) in separate servers on purpose. The events tests stub the globalfetch(vi.stubGlobal) — the layer has nofetchoption. - Events facts. Wire format follows ChatGPT's MCP Events (webhook only):
events/list|subscribe| unsubscriberegistered viaserver.server.setRequestHandler(method, { params }, handler)andregisterCapabilities({ events: {} } as never)(the SDK has no events types). Subscription id =sub_+ sha256(canonical[subscriber, url, event, args]), so unsubscribe/refresh can only ever touch the caller's own record (tested). An event's values come from ONE place, the payload (the user's call, 2026-10-08: "it doesn't make sense for emit to get the docId as two parameters"):emit(payload, { eventId? })is the whole API,registerEventthrows unless everyinputfield is also apayloadfield, andvaluesOf(input, payload)gives the values used both to match (a subscription matches when every arg it gave equals the payload's value) and to authorize. Access model: the filter says what, a requiredauthorizesays who may — at subscribe/refresh with the subscription's args (phase: "subscribe", withauth/request), and insend()before every delivery with the event's values, not the subscription's args (phase: "deliver", principal only; the token is never stored). That is the fix for the review's medium finding: checkingsub.argslet a subscriber with no filter ({}) passauthorize({})and receive every document's events, and the old explicitemit(payload, { args })could route doc A's payload to doc B's readers.core.test.ts"checks a subscriber without a filter against each event's own values" guards it (mutation-checked). A refusal at delivery is final (done), a throwingauthorizeretries.sendreturns a boolean (true= done,false= retry). Removed on purpose — don't bring back:personal,to,match, explicitargs, principalcontext,taskFinishedEvent/onSettle,timestamp,EmitResult.matched,list(),timeoutMs/fetch/defaultson the event layer.subscriberesolves the principal before validating anything (no info to anonymous callers). Secrets are AES-256-GCM sealed undersecretKey(MCP_EVENTS_SECRET_KEY), which must decode to ≥ 32 base64 bytes (openssl rand -base64 32);SecretBox.openreturnsnullon a tampered/rotated secret. A refresh with the same secret skips the challenge. A failed challenge is always the sameProtocolError(-32015, "Callback URL failed verification")with no reason or status (no network probing); the detail isconsole.warned. The challenge answer is read capped at 4 KB, delivery bodies are cancelled, and 3xx is dropped.callbackUrlProblemstrips trailing dots and refuses every IP literal (v4 after the URL parser's normalization, and any[…]v6) plus localhost/single-label/.local/.internal; the old private-range/NAT64/6to4 parser is gone. It does not resolve DNS. Bad params are-32602with areason. Subscription limit:maxSubscriptions(default 8,Infinity= off) live subscriptions per subscriber across all events. The layer checksstore.countbefore the challenge (no outbound POST for a caller at the limit), andput(sub, { limit })re-checks atomically (Redis: one Lua script overidx:<event>andby:<subscriber>). Refreshes never count. Routing and delivery-timeauthorizeuse the payload's input fields parsed withinput(projection), so transforms match on both sides; a payload that doesn't fitinputmakesemitthrow. QStashdeduplicationIdcannot contain:(dev server answers 400), one more reason not to derive it from caller-chosen event ids. - Local dev needs the QStash dev server (
npx @upstash/qstash-cli dev) — it prints deterministic creds.APP_URLmust be reachable from QStash.
- The repo is split (since 2026-09-30):
packages/eve-extension+examples/eve-extension-demoare oneve@0.83.0(extension peer>=0.83.0, since 2026-10-23;>=0.82.0since 2026-10-22, never released;>=0.74.0since 2026-10-08; 0.70.0 />=0.70.0and 0.72.1 />=0.72.0were never released);packages/eve+examples/eve-demostay oneve@0.65.0(peer>=0.65.0) — see the 0.68.0 → 0.69.0 and 0.65.0 → 0.68.0 bump notes below. Before that (2026-09-23) it was oneeve@0.65.0everywhere, with both packages declaringeve: ">=0.65.0". (For one day the repo was also split earlier: the extension on 0.64.1,packages/eveon 0.63.0, because eve 0.64.0 removed theSandboxBackend*authoring types thatpackages/eve/src/sandbox.tsimplemented.) eve 0.64 replaced sandbox backends with providers (eve/sandbox/provider:defineSandboxProvider,SandboxProvider*,SandboxDeleteOptions) and object-formdefineSandbox({ backend, bootstrap, onSession })with exported environments +defineSandbox(() => environment.open()); the sandbox was ported to that API (see Known issues). Nothing else inpackages/eveneeded a change for 0.63 → 0.65: memory, tools, auth and search typecheck and test unchanged. Why the peer is>=0.65.0and not lower: a single peer range covers the whole public surface../sandboxneeds ≥0.64 (provider API), and the decision on 2026-09-23 was to require the latest eve across all packages rather than carry a split floor. The older floors recorded below (>=0.45.2for./memory,>=0.32for the root) describe what those entry points need, not what is declared. Subpath exports:eve/tools,eve/hooks,eve/extension,eve/context,eve/instructions,eve/sandbox,eve/sandbox/provider,eve/sandbox/vercel,eve/channels/*,eve/next,eve/react,eve/memory,eve/memory/scope,eve/memory/file,eve/memory/file/vercel,eve/evals,eve/evals/expect, … Memory landed late:eve/memoryfirst exists in 0.45.1 andeve/memory/filein 0.45.2 (0.45.0 and everything below has neither) — measured withnpm view eve@<v> exports. That is the real floor for@upstash/agentkit-eve/memoryon its own. - Breaking changes absorbed on the 0.25 → 0.32 jump: (a) 0.31 replaced continuation-token session
APIs with fixed ID-addressed handles — frontend/client
sendis now positional (agent.send(message, options?), notsend({ message }); eve-demo'sagent-chat.tsxwas updated); (b)SandboxBackendHandlegained a requiredstop()(authored-runtime stop, errors must reject) alongsideshutdown(); (c) tool executors may returnAsyncIterable<TOutput>(streaming output snapshots, 0.31) —ToolDefinition.execute's return type is now a union;defineCachedToolrejects streaming executors at the type level (see the eve exports section); (d) 0.30 changedlocalDev()to grant a deployment-based synthetic principal (runtimeprincipalIdvalues differ in local dev; our sanitizingresolveUserIdis unaffected); (e) eve 0.32'saipeer is^7.0.58(drove the repo-wide exact-pin bump). Durable sessions now complete after 30 days by default (0.28) — strengthens RedisChatHistoryas the long-term transcript store. - The 0.32 → 0.44.3 jump (issue #22) needed no source changes — everything compiled and passed
as-is. Why each headline break missed us: hook contract v10 (0.33, "model identity moved from
session.startedruntime metadata tostep.startedcall attribution") — ourchat_historyhook only readsmessage.received/message.completed, whose shapes (incl.data.finishReason) are unchanged; 0.33'sdefineDynamicnarrowing ("accepts onlyevents") — our dynamic tools already used the events-only form; 0.38 renamed frontend bindingstop()→cancel()— eve-demo never called it (agent.send(message)positional survives); 0.44.1 reruns session-scoped dynamic resolvers on resume ("keep them idempotent") — ours are pure factories. The real fix was rebuild + re-stamp the manifest + tighten the peers.aistayed exact-pinned at7.0.58(eve 0.44's peer is still^7.0.58). One live-dev gotcha: a demo's.eve/dir holding local workflow state written by ≤0.37 fails to replay on ≥0.38 ("Event id is not slot-numbered" retry loops that wedge new turns — 0.38.2 moved the dev world to slot-numbered event ids)..eve/is gitignored dev scratch: after an eve bump,rm -rf examples/*/.evebeforeeve dev/next dev. Both demos were verified with live turns on 0.44.3 (memory save + fresh-session recall, search count matching seed data, cached weather tool, and the extension's dynamic search + chat-history hook/tools writing and reading realagentkit:chat:demo-user:*docs);gpt-5.4-minidoes exist and responds — the "may 404" caveat in Known issues didn't materialize. - The 0.44.3 → 0.45.0 bump also needed no source changes — build, typecheck, both demo builds and
the mocked-model eval all passed unmodified. It was, again, purely a manifest/peer-floor move:
rebuilding on 0.45.0 re-stamps tool 17→18 and dynamicTool 18→19, and 0.45.0 is the first eve
supporting either, so the extension peer floor went
>=0.43.0→>=0.45.0(a 0.45-built dist hard-errors at discovery on 0.44.3: "requires tool contract v18, but this eve supports … v17"). Note the floor is now equal to the pinned version — 0.45 raised both contracts it stamps, so there is no back-compat window at all this time. Why 0.45's headline breaks missed us: built-in tool definitions moved fromeve/tools/defaultsto per-tooleve/tools/<name>subpaths anddefineBashTool/defineReadFileTool/defineWriteFileTool/defineGlobTool/defineGrepToolwere removed — we import onlydefineTool/defineDynamic/SessionContext/ToolContext/ToolDefinitionfromeve/tools, nevereve/tools/defaultsnor any of those factories; andexperimental.subagentPersistentSessionswas removed (subagent contract 1 and 2 are now dropped, only 3 is supported) — we contribute no subagents.aistays exact-pinned at7.0.58(eve 0.45's peer is still^7.0.58). - The 0.45.0 → 0.45.2 bump also needed no source changes — only the manifest re-stamp
tool 18→19, which moves the extension's peer floor
>=0.45.0→>=0.45.1(0.45.1 is the first eve accepting tool 19). Contribution contracts can move in a patch release, so re-derive the floor from the freshly built manifest rather than the minor version. - The 0.45.2 → 0.47.3 bump was the first one in a while that needed a real source change.
eve 0.47.0 made
delete(options?: SandboxDeleteOptions)a required member ofSandboxBackendHandle, sopackages/eve/src/sandbox.tsfailed withTS2741: Property 'delete' is missing …until the handle implemented it (box.delete(), see the sandbox section). Everything else was mechanical: no other package changed source, both demos build, and the extension only needed a rebuild. The extension manifest went tool 19→21 / dynamicTool 19→21 / hook 14→16 (instructions 2, config 1, extension 1 unchanged), moving its peer floor>=0.45.1→>=0.47.0— again floor == pinned minor, no back-compat window. 0.46.1 sits in between (tool 20 / hook 15) and is genuinely rejected by the new dist.packages/eve's own peer stayed>=0.32.0on purpose (its shippeddistnamed no post-0.32 type — true of the dist at that time;0.9.0's./memorysubpath later broke that, and the floor is now>=0.45.2. See the version bullet at the top of this section — the log entries below record what was true per bump, not the current floor). - The 0.47.3 → 0.47.6 bump needed no source change, but it moved two pins. The extension rebuild
re-stamped tool 21→22 only (dynamicTool 21, hook 16, instructions 2, config 1, extension 1 all
unchanged), moving its peer floor
>=0.47.0→>=0.47.5— 0.47.5 is the first eve accepting tool 22, and 0.47.4 was never published, so the floor names a version that exists while the one below it in the range does not. Proven bypnpm packing the rebuilt dist into a real eve consumer: 0.47.0–0.47.3 install cleanly and then faileve buildwith the same obtuse "has no compile or runtime usage" message; 0.47.5/0.47.6 build and mount every contribution. Separately, eve 0.47.6 raised itsaipeer to^7.0.82, so the repo-wideaipin went7.0.58→7.0.87and@ai-sdk/*moved with it (see the AI SDK section — that bump also de-duplicatedai).packages/eve's peer stayed>=0.32.0, re-verified this round by typechecking its builtdistagainst 20 eve versions, 0.30.8–0.47.6 (all clean): the dist names onlydefineToolandForbiddenErrorat runtime plus fiveeve/sandboxtypes in its.d.ts—SandboxDeleteOptionsis source-only and fully erased from the artifact. Unlike the extension,packages/evehas no generated manifest (plain tsup) and itsdistis byte-identical whether built against 0.47.3 or 0.47.6, so an eve bump can never silently move its floor. - The 0.47.6 → 0.49.0 bump needed no source change, and moved only the extension's floor. The
extension rebuild re-stamped tool 22→24 only (dynamicTool 21, hook 16, instructions 2, config 1,
extension 1 all unchanged), moving its peer floor
>=0.47.5→>=0.48.0. The important lesson: the tool contract moved twice inside three releases — 22→23 in 0.47.7 and 23→24 in 0.48.0 — so "the next patch is probably fine" is wrong; 0.47.7 is rejected by the 0.49.0-built dist just like 0.47.5/0.47.6 are. Proven bypnpm packing the rebuilt dist into a real eve consumer: 0.47.5 / 0.47.6 / 0.47.7 install cleanly (the old>=0.47.5peer admits all three) and then faileve buildwith the same obtuse "has no compile or runtime usage" message; 0.48.0 and 0.49.0 build and mount every contribution. Note this supersedes the unreleased 0.47.6 rebuild (PR #31/#32,.changeset/eve-extension-0476-rebuild.md, tool 22 / floor>=0.47.5): that changeset was folded into.changeset/eve-extension-0490-rebuild.mdrather than sitting beside it, and the merged entry is written against the last published state —0.8.0, built with eve 0.47.3, tool 21, peer>=0.47.0. eve'saipeer stayed^7.0.82and itsnitrodep stayed3.0.260610-beta, so the repo-wideai7.0.87 pin did not move.packages/eve's peer stayed>=0.32.0, re-verified by typechecking its builtdistagainst 0.32.0/0.44.3/0.45.2/0.47.0/0.47.3/0.47.6/0.47.7/0.48.0/0.49.0 (all clean); eve'sdist/src/shared/sandbox-backend.d.tsis byte-identical between 0.47.6 and 0.49.0, soSandboxBackendHandlegained no new required member. - The 0.49.0 → 0.52.2 bump needed no source change, and again moved only the extension's floor —
but it is the first bump where eve dropped contracts out of the middle of its supported range.
The extension rebuild re-stamped tool 24→30, dynamicTool 21→29, hook 16→20 (instructions 2,
config 1, extension 1 unchanged), moving its peer floor
>=0.48.0→>=0.52.2. Only 0.52.2 accepts the new dist: 0.52.1/0.52.0 top out at tool 29, 0.51.1 at tool 27, 0.51.0 at tool 25 / hook 18, 0.50.0 at dynamicTool 22 / hook 17. Proven bypnpm packing the rebuilt dist into a real eve consumer — 0.52.1 installs cleanly and then failseve buildwith the usual obtuse "has no compile or runtime usage", 0.52.2 builds and mounts all 7 tools + the hook. The new hazard: a newer eve is no longer automatically compatible. 0.52.2's supportedtoollist is [1–13, 28, 29, 30] — 14–27 are all indropped("TaskExec.delegated was removed; migrate to workflow-backed background tools"), and dynamicTool/hook dropped entries cite "Message and reasoning append events now expose deltas instead of cumulative snapshots". That is why the published0.9.0dist (tool 24, built with 0.49.0) breaks on every eve from 0.50.0 up while its>=0.48.0peer happily admits them — a floored peer with no ceiling is still a trap when the framework drops contracts. Despite those scary drop reasons, no source change was needed: thechat_historyhook only subscribes tomessage.received/message.completed(not the append events), and nothing in the repo touchesTaskExec.delegated— both packages' sources typecheck clean against 0.52.2. eve'saipeer stayed^7.0.82, so the repo-wideai7.0.87 pin did not move.packages/eve's peer stayed>=0.32.0, re-verified by typechecking its builtdistagainst 0.32.0/0.44.3/0.45.2/0.47.6/0.48.0/0.49.0/0.50.0/0.51.1/0.52.2 (all clean); itsdistis byte-identical to the published 0.9.0, so@upstash/agentkit-evegets no changeset this round — only@upstash/agentkit-eve-extensionships different bytes. Expect a largepnpm-lock.yamldiff on this bump (~550 lines, mostly deletions) — that is normal, not corruption. eve'snitrodep moved3.0.260610-beta→3.0.260903-beta, and the new nitro dropped a pile of optional peer deps (vite,rollup,jiti,chokidar,dotenv,@upstash/redis), which collapses eve's long peer-suffixed resolution keyeve@0.49.0(@opentelemetry/api)(@upstash/redis)(ai)(chokidar)(dotenv)(jiti)(rollup)(vite)down toeve@0.52.2(@opentelemetry/api)(ai)and garbage-collects the now-unreferenced entries. Confirm withpnpm install --frozen-lockfile(must print "Already up to date"), not by eyeballing the line count. - The 0.52.2 → 0.52.3 bump needed no source change, and again moved only the extension's floor —
but unlike every bump before it, this one fixes no break. The extension rebuild re-stamped
tool 30→32, dynamicTool 29→31, hook 20→22 (instructions 2, config 1, extension 1 unchanged),
moving its peer floor
>=0.52.2→>=0.52.3. Only 0.52.3 accepts the new dist — 0.52.2 tops out at tool 30 / dynamicTool 29 / hook 20 — proven by packing the rebuilt dist into a real eve consumer: on 0.52.2 it failseve buildwith the usual obtuse "has no compile or runtime usage", on 0.52.3 it builds and mounts all 7 tools + the hook. The difference that matters: eve 0.52.3 did NOT drop the contracts the published0.10.0needs. 0.52.3 still supports tool 30 / dynamicTool 29 / hook 20 (itstoollist is [1–13, 28–32], i.e. it added 31/32 without dropping 30), so published0.10.0installs and builds fine on eve 0.52.3 — verified in a scratch consumer witheve@latest+@upstash/agentkit-eve-extension@latest, which mounts all 7 tools and the hook. So this rebuild is "keep the stamps current", not a fix: its only consumer-visible effect is that the raised floor makes the new version unusable on 0.52.2. Weigh that before shipping it — holding the rebuild is a legitimate option while 0.10.0 still works on latest, and>=0.52.3should not be raised as a reflex.packages/eve's peer stayed>=0.32.0and it ships no changeset: itsdistis byte-identical before and after the bump (diff -rover the whole built output,.js+.d.ts), so only its devDependency moved. eve'saipeer stayed^7.0.82, so the repo-wideai7.0.87 pin did not move. The lockfile diff is small this time (~30 lines) — no nitro churn, unlike the previous bump. - The 0.52.3 → 0.55.0 bump (2026-09-15) needed no source change, moved the extension's floor by
three minors, and — for the first time since 0.47.6 — moved the repo-wide
aipin. eve went 0.52.3 → 0.55.0 in a week (0.52.4, 0.52.5, 0.53.0, 0.53.1, 0.54.0, 0.54.2–0.54.5, 0.55.0). The extension rebuild re-stamped tool 32→38, dynamicTool 31→37 (hook stayed 22; instructions 2, config 1, extension 1 unchanged), moving its peer floor>=0.52.3→>=0.55.0. Only 0.55.0 accepts the new dist — 0.54.4/0.54.5 top out at tool 36 / dynamicTool 35 — proven by packing the rebuilt dist into a real eve consumer: 0.54.5 installs fine (the old>=0.52.3floor lets it) and then failseve buildwith the usual obtuse "has no compile or runtime usage"; 0.55.0 builds and mounts all 7 tools + the hook. Published0.10.0was NOT broken by 0.55.0 — 0.55.0'stoollist is [1–13, 28–32, 34–38] and itshooklist still has 20, so the published stamps (tool 30 / dynamicTool 29 / hook 20) remain supported; a scratchnpm install eve@latest @upstash/agentkit-eve-extension@latest @upstash/agentkit-eve@latestconsumer resolved eve 0.55.0 andeve buildsucceeded, mounting all 7 tools + the hook, with adefineMemoryRecallTooltool from@upstash/agentkit-evealongside. So this is again a "keep the stamps current" rebuild, not a fix. The new thing on this bump: eve'saipeer moved^7.0.82→^7.0.93, which makes the old exactai@7.0.87pin a hard npm ERESOLVE failure againsteve@latest. Repo-wide pin went to7.0.101, pluspnpm -r update "@ai-sdk/*"to collapse the secondaicopy@ai-sdk/reactdrags in (see the AI SDK section).packages/eve's peer stayed>=0.32.0and it ships no changeset: itsdistis byte-identical before and after the bump (diff -rqover the whole built output,.js,.d.tsand.map), anddefineSandbox({ backend: upstash() })against that dist typechecks clean on 0.32.0/0.45.2/0.47.6/0.52.3/0.54.5/0.55.0.packages/eve/src/sandbox.ts'sSandboxBackendHandleimplementation needed no new member for 0.55.0 —pnpm typecheckis clean across all four packages. Even the extension's compiled output is unchanged:_manifest.jsonis the only file inpackages/eve-extension/distthat differs from published0.10.0. - (Superseded 2026-11-05: TanStack AI 1.x IS applied, see the entry below.) Historical note on the 1.0.0 migration, written while it was not yet applied: Against 1.0.0
srcbuilds and the persistence conformance suite passes, butpnpm typecheckfails in tests only:chat()now requiresthreadId(middleware.test.ts,search-tools.test.ts; 4 runtime failures "chat() needs a threadId"), andArtifactRecordrequiresblobKey(persistence.test.tsfixtures). Also:@tanstack/ai@1.0.0's own.d.tshas a broken import (spawn.d.ts:import('../../..')), soskipLibCheck: falseconsumers get TS2307 from upstream. New 1.0 contracts not implemented yet:SessionIndexStore,CredentialStore(BYOK). ai 7.0.149+ added theinterruptedfinish reason;@ai-sdk/reactpinsaiexactly, so keep it in step (^4.0.156for ai 7.0.152). - eve 0.83.0 (2026-10-23) is applied to the extension only;
packages/evestays on 0.82.0. 0.83.0 dropped the 0.82.0 contract stamps (extension rebuild: tool 96→102, dynamicTool 88→92, hook 48→51; extension peer>=0.83.0) and also brokepackages/eve/src/sandbox.ts's typing (not migrated yet — needs a source change):eve/sandbox/providerno longer exportsSandboxProviderHandle/SandboxProviderResources;NetworkPolicylists are mutablestring[](ours arereadonly);SandboxSessionrequireswriteFiles;SandboxPrepareContextlostresources/sourceRevision; the connection no longer hashandle/sandbox/onSandboxDelete. Until that migration lands,packages/eve+examples/eve-demopineve ^0.82.0(two eve versions in the workspace on purpose). - eve 0.83.2 + ai 7.0.153 (2026-10-25): extension +
examples/eve-extension-demomove to eve^0.83.2;packages/eve+examples/eve-demostay on^0.82.0. The extension rebuilt on 0.83.2 stamps the same contracts as 0.83.0 (tool 102 / dynamicTool 92 / hook 51), so its>=0.83.0peer floor is still truthful. Published@upstash/agentkit-eve@0.16.1./sandboxfails at sandbox-template init on eve 0.83.x (plaineve buildwithUpstashSandbox.environment()-> "Cannot read properties of undefined (reading 'workspace')";--skip-sandbox-prewarmhides it), so its>=0.75.0peer admits eve versions where./sandboxis broken until the source migration lands. TanStack AI 1.0.0 still not applied (see above). - eve 0.83.3 + ai 7.0.154 (2026-10-27): extension +
examples/eve-extension-demomove to eve^0.83.3, ai is7.0.154everywhere (@ai-sdk/react ^4.0.158). Same contracts as 0.83.0, peer floor unchanged. eve 0.84.0 (2026-10-26) is NOT applied: it breakspackages/eve-extensionandpackages/evesources (needs a source migration). Published@upstash/agentkit-eve-extension@0.16.1failseve buildon eve 0.84.0 with "uses an old epoch-based distribution manifest … Rebuild the extension with this eve release". Extension typecheck on 0.84.0:SessionContextno longer exported fromeve/tools; hook keymessage.receivedgone; tool defs no longer acceptevents.packages/eveon 0.84.0:signalremoved fromMemoryDocumentReadInput/WriteInput,MemoryCompactionCompletedContextand thecompaction.completedrecall hook gone,MemoryToolsContext.turngone, plus the sandbox typings above. TanStack AI 1.0.0 still not applied (see above); ai 7.0.154 is clean (published@upstash/agentkit-ai-sdk@0.15.1typechecks and imports on it). - eve 0.85.0: the extension IS migrated (extension-only;
packages/eve+examples/eve-demostay on eve 0.82.0). eve 0.84.0 replaced per-capability contract epochs with a{formatVersion: 3, builtWithEve, contractMajor: 0}manifest and a v27 session-event/dynamic API. Source changes inpackages/eve-extension:SessionContextis gone fromeve/tools(ownSessionRef = Pick<SessionFrame, "session">inextension/lib/session.ts, used for theuserIdfunction andresolveUserId); dynamic tools usedefineDynamic(ctx => tool | null)instead ofdefineDynamic({events: {"session.started"}}); the chat-history hook mapsmessage.received->delivery.consumed(text parts ofevent.data.parts) andmessage.completed->content.completedfiltered tokind: "text"+phase: "reply"(one stored assistant message per reply text part; narration is not stored). The peer floor is>=0.85.0: verified by packing the dist (built with 0.85.0) into consumers on 0.83.3 ("no valid compatibility manifest"), 0.84.0 and 0.84.1 ("was built with eve 0.85.0. Upgrade eve to 0.85.0 or later") and 0.85.0 (eve buildclean). Any rebuild on a newer eve will raise the floor again to that eve. - ai 7.0.155 (2026-10-28) applied everywhere except
packages/eve+examples/eve-demo(stay on 7.0.154;@ai-sdk/react ^4.0.159); with 7.0.155packages/evetsc fails atsrc/sandbox.ts:340(spawn return type vs eve 0.82.0 overloads) and eve-demonext buildfails; eve 0.84.1 / 0.85.0 NOT applied. Same state as 0.84.0: extension typecheck on 0.85.0 still fails (SessionContextmissing fromeve/tools, hook keymessage.receivedgone,eventsrejected on tool defs) and published@upstash/agentkit-eve-extension@0.16.1still failseve buildon eve 0.85.0 ("uses an old epoch-based distribution manifest"); needs a source migration. Published@upstash/agentkit-ai-sdk@0.15.1typechecks (skipLibCheck: false, with@types/json-schemainstalled, which@ai-sdk/provideromits) and imports on ai 7.0.155. TanStack AI 1.0.0 still not applied. - eve 0.87.0 + ai 7.0.156 (2026-10-29):
packages/eve+examples/eve-demoare migrated and back in step with the rest of the repo on eve^0.87.0/ ai 7.0.156 (the eve 0.82.0 hold above is over); the extension stays on eve^0.85.0. Source changes inpackages/eve:redisMemory()registers onlyturn.startedrecall (eve 0.84 removedcompaction.completed; registering it madeeve buildfail with "provider.recall Unknown key compaction.completed"), and because eve 0.84+ gives a memory tool noturn,turn.startedstores the turn sequence at<replayCachePrefix>:sequence:<scope>:<session>forsave_memoryto order its record by (read_sessionsorts on it; without a prior recall it falls back to 0).UpstashSandboxfollows the connection-based provider contract:preparereturns{snapshotId: null}whenctx.isEmpty, otherwise creates a temp box,ctx.populate(connection)(eve stripspreparefrom the options and runs it there), snapshots (named fromctx.templateKey) and deletes the box;startis an idempotent upsert on the box nameeve-<sha256(session.id)[:16]>(suffix fallback if a deleted record holds the name);resumethrowsSandboxSessionGoneError;onSessionEnddeletes by recordedboxId, or by the derived name when state is null, and is a no-op when nothing exists;connection.stop()is Boxpause;setNetworkPolicyis a connection extension; a writablestdinspawn throws. The peer floor is>=0.87.0: the source typechecks with 0 errors only on 0.87.0 (0.83.x fails onsignal/stdin, 0.84.0–0.86.0 onsignalin sandbox andMemoryDocumentReadInput/WriteInput, 0.82.0 and older on the old provider handle API).examples/eve-demoalso needed:turn.replyinstead ofturn.messageinevals/memory.eval.ts;useEveAgentnow returnsmessages/status: idle|busy|resumingwithtoolparts (wasdata.messages,dynamic-tool);@vercel/connect2.5.6 (eve 0.87 peer) andnext16.2.9 sopackages/eveand the demo resolve the same eve instance (two peer variants of eve makeMemoryProvidertypes nominally incompatible). Not verified live: theUpstashSandboxlive-Box suite (needsUPSTASH_BOX_API_KEY) was not run; the offline suite and the eve-demo mocked eval (which reachesBox.createfromprepare) were. The extension was not moved to eve 0.87: a dist built on 0.87.0 is refused by eve 0.85/0.86, so adopting it forces its peer floor to>=0.87.0for no contract change. TanStack AI 1.0.0 still not applied (test-only typecheck/runtime breaks; the published@upstash/agentkit-tanstack-ai@0.2.0typechecks and imports on 1.0.0, the memory contract passes, and the demo e2e passes). - The 0.74.0 → 0.82.0 bump (2026-10-22) moves everything, with a source migration in
packages/eve. eve 0.75.0 renamed the sandbox provider handle hooksonSessionStop/onSessionDelete→onSandboxStop/onSandboxDelete, and eve 0.66.0 had removedMutableNetworkSandboxSession(network policy became provider-specific).packages/eve/src/sandbox.tsnow declares its ownUpstashSandboxSession = SandboxSession & { setNetworkPolicy }(exported; whatctx.getSandbox(environment)returns) and uses the new hook names, so theevepeer floor moved>=0.65.0→>=0.75.0(floor read off the 0.74.0 vs 0.75.0 tarballs:onSessionStoppresent vs absent inshared/sandbox-provider.d.ts; not verified by a fulltscagainst 0.75.0).packages/eve+examples/eve-demoare on eve ^0.82.0. The extension rebuild re-stamps tool 78→96, dynamicTool 73→88, hook 39→48; only 0.82.0 accepts them (0.75.0–0.81.1 do not), floor>=0.74.0→>=0.82.0.upstashPersistencegained anactivitiesstore (ActivityStore, one JSON doc per thread at<prefix>:activities:<threadId>, same TTL as messages) because@tanstack/ai-persistence≥0.8.0's conformance suite requires it, so ai-persistence moves 0.7.2 → 0.10.1 and the peer floors become@tanstack/ai>=0.65.0(ActivityRecordtype),@tanstack/ai-persistence>=0.8.0(ActivityStoretype). ai 7.0.148, @tanstack/ai 0.71.0, -memory 0.2.16 and the demo packages are bumped. - The 0.72.1 → 0.74.0 bump (2026-10-08) is EXTENSION-ONLY again (same reason:
packages/evestill imports the removedMutableNetworkSandboxSession,TS2305insrc/sandbox.ts/sandbox.test.tson 0.74.0;packages/eve+examples/eve-demostay on 0.65.0). The rebuild re-stamps tool 76→78, dynamicTool 72→73, hook 38→39; only 0.74.0 accepts them (verified by building the packed dist against a consumer on each of 0.72.0/0.72.1/0.73.0 — all faileve build— and 0.74.0, which mounts clean), so the floor moved>=0.72.0→>=0.74.0. Published 0.15.0 fails on 0.74.0 as on 0.72.x. Also bumped:ai7.0.133,@tanstack/ai0.65.1,-client0.38.0,-react0.30.0;@tanstack/ai-persistencestill held at 0.7.2 (above). - The 0.69.0 → 0.72.1 bump (2026-10-07) is EXTENSION-ONLY (
packages/evestill imports the removedMutableNetworkSandboxSession; verified on 0.71.2 and 0.72.1:TS2305insrc/sandbox.ts/sandbox.test.ts; needs a source change, sopackages/eve+examples/eve-demostay on 0.65.0). The rebuild re-stamps tool 71→76, dynamicTool 68→72, hook 35→38; read off every 0.69.0–0.72.1 tarball'sextension-compatibility.js: 0.70.0–0.71.3 accept tool 73/dynamicTool 70/hook 37 (not 76/72/38), and 0.72.0+ accepts only tool 76 (+ the old 35), so the floor moved>=0.69.0→>=0.72.0. Published 0.15.0 (71/68/35) builds clean on eve 0.69–0.71.3 but failseve buildon 0.72.x (Selected module binding "extensions/agentkit.ts" has no compile or runtime usage.), verified in a fresh npm consumer witheve@0.72.1. Also:@tanstack/ai-persistencestays at 0.7.2 (devDep) because 0.8.0's conformance suite now requires anactivitiesstore (ActivityStore) orskip: ['activities']— a test/source change, not a bump. - The 0.68.0 → 0.69.0 bump (2026-10-01) is EXTENSION-ONLY, for the same reason as 0.68.0. eve 0.69.0
dropped tool 59, dynamicTool 56 and hook 29 — exactly the stamps of published
@upstash/agentkit-eve-extension@0.14.0(built with 0.68.0) — one day after it shipped, while its peer>=0.68.0still admitted 0.69.0: a freshnpm i eve@latest @upstash/agentkit-eve-extension@latestinstalled clean and then failedeve buildwith the obtuse "Selected module binding "extensions/agentkit.ts" has no compile or runtime usage.". eve'sdroppedreasons: tool 59 — "Workflow tools no longer accept execution or return background task receipts…"; dynamicTool 56 / hook 29 — "Background task execution was removed…". No source change: the rebuild re-stamps tool 59→71, dynamicTool 56→68, hook 29→35, and the floor moved>=0.68.0→>=0.69.0— read off every 0.65.0–0.69.0 tarball'sextension-compatibility.js(only 0.69.0 accepts any of 71/68/35) and proven with the packed tarball in fresh npm consumers: 0.69.0 builds and mounts every tool + the hook; 0.68.0 is refused at install (ERESOLVE … peer eve@">=0.69.0") and, forced with--legacy-peer-deps, failseve buildwith the same obtuse error. eve 0.69.0'saipeer is still^7.0.105.packages/evestill cannot move:MutableNetworkSandboxSession(below) is still imported. - The 0.65.0 → 0.68.0 bump (2026-09-30) is EXTENSION-ONLY again.
packages/evecannot take it without a source migration: eve 0.66.0 (ee286fe) removedMutableNetworkSandboxSessionfromeve/sandbox(network policy became provider-specific;SandboxSessionlostsetNetworkPolicy), andpackages/eve/src/sandbox.ts+sandbox.test.tsimport it — tsup's DTS step andtscfail withTS2305 … has no exported member 'MutableNetworkSandboxSession'plus a cascade of implicit-anyerrors. (Knock-on:examples/eve-demo'snext buildthen fails on implicit-anyinagent/channels/eve.ts, because@upstash/agentkit-evehas no.d.ts.) The extension needed no source change: its rebuild re-stamps tool 55→59, dynamicTool 52→56, hook 25→29, and the floor moved>=0.65.0→>=0.68.0, read off each 0.65.0–0.68.0 tarball'sdist/src/compiler/extension-compatibility.js. eve 0.68.0 still accepts the old 55/52/25 stamps, so published0.13.0keeps working on it. eve ≥0.64's scaffold also needsjust-bashfor a plaineve build; the extension demo side-steps that with--skip-sandbox-prewarm(see its section). - The 0.64.1 → 0.65.0 bump (2026-09-23, same PR #46) finished what 0.64.1 couldn't: the whole repo
is on 0.65.0 and every package requires it.
packages/eve's sandbox was ported from the removed backend API to an eve provider (UpstashSandbox, see Known issues) — the only source change; memory/tools/auth/search needed none.@upstash/boxmoved^0.5.1→^0.7.5(peer>=0.5.0→>=0.7.1, the first release withexec.session, measured by grepping each 0.5.0–0.7.5 tarball'sclient.d.ts). The extension rebuild on 0.65.0 re-stamps tool 54→55 (dynamicTool 52, hook 25 unchanged) — 0.65.0 is the first eve accepting tool 55, so its floor is>=0.65.0whichever way you derive it (the decision to require latest eve everywhere and the manifest agree). eve 0.65.0's own breaking changes (thetodotool removed,ask_questionno longer a default tool,ctx.ask()result shape) touch nothing here. Verified: lint, typecheck, build, 155/155 tests (with live Redis and live Box), both example builds (eve-demo also without any Box/Redis env:next builddoes not prepare sandboxes), both mocked-model evals, plus the out-of-repo sandbox e2e described under Known issues. - The 0.63.0 → 0.64.1 bump (2026-09-23) is EXTENSION-ONLY, and the first bump the whole repo could not take.
eve 0.64.0 dropped tool 53, dynamicTool 51 and hook 24 in a single release — precisely the stamps the
just-published
@upstash/agentkit-eve-extension@0.12.0carries — while 0.12.0's peer>=0.63.0still admitted 0.64.x, sonpm i eve@latest @upstash/agentkit-eve-extension@latestinstalled clean and then died on the firsteve buildwith the usual obtuse "Selected module binding "extensions/agentkit.ts" has no compile or runtime usage.". This is the third time the same trap fired (0.10.0 on eve 0.63.0, 0.11.0's zod dedupe, now 0.12.0 on eve 0.64.0) — the lesson each time is the same: after ANY release, re-install the published tarball againsteve@latestin a scratch consumer and run a real turn. The rebuild re-stamps tool 53→54, dynamicTool 51→52, hook 24→25 (builtWithEve0.64.1) and moves the floor>=0.63.0→>=0.64.0— measured, not read off the tables: the rebuilt dist packed into real npm consumers fails on 0.63.0 (same obtuse error) and builds on 0.64.0/0.64.1, and with the new floor npm refuses the 0.63.0 install up front withERESOLVE … peer eve@">=0.64.0" from @upstash/agentkit-eve-extension@0.12.0.packages/evedeliberately stayed on 0.63.0 — see the sandbox-provider note under Eve framework facts; bumping it is a source migration, not a pin bump. There is a stale branchchore/eve-0.64.1-extension-only(96bb264) on origin that attempted this fix from beforeae3db83(the zod widen): do not merge or build on it — it would regresszodback to the exact pin4.4.3and re-break the search tools. - The 0.55.0 → 0.63.0 bump (2026-09-20) is the first eve bump that fixes a real break, and the first
that needed source changes. eve went 0.55.0 → 0.63.0 in five days (0.56–0.58, 0.59.0/0.59.1, 0.60.0/
0.60.1, 0.61.0/0.61.1, 0.62.0, 0.63.0). Three things happened at once:
(1) eve 0.63.0 (2026-09-19) dropped
dynamicTool29 — the stamp published0.10.0(built with 0.52.2) carries — so a freshnpm install eve@latest @upstash/agentkit-eve-extension@latestconsumer installs (the>=0.55.0floor lets it) and then failseve buildwith the usual obtuse "has no compile or runtime usage". 0.55.0 through 0.62.0 all still accepted tool 30 / dynamicTool 29 / hook 20; 0.63.0 is the first release that does not, eleven days after0.10.0shipped. The rebuild re-stamps tool 38→53, dynamicTool 37→51, hook 22→24 and moves the floor>=0.55.0→>=0.63.0(0.62.0 rejects the new stamps — proven by packing the rebuilt dist into real eve consumers on 0.62.0 and 0.63.0). (2) eve 0.59.0 made dynamic-tool schemas durable (7973fa2: resolvers are replayed from a JSON snapshot, so a live schema captured from the resolver is rejected atsession.startedwith "callback "inputSchema" has a non-serializable capture", logged as[eve:dynamic-tools] … skipping its complete result— and the tool silently never mounts). Oursearch/search_aggregate/search_counthanded eve the live zod schema core builds from the consumer'ssearch.schema, so on eve 0.59–0.62 the extension mounted but its three search tools vanished at runtime, witheve buildgreen. The fix is inextension/tools/search*.ts: computez.toJSONSchema(defs.<tool>.inputSchema)into a resolver-local variable and pass THAT — plain JSON Schema data needs no durable factory and eve rehydrates it into its own validator.⚠️ WritinginputSchema: z.toJSONSchema(defs.search.inputSchema)inline does NOT work: the compiler transforms inline schema expressions into factories and snapshots their captures, anddefsis not JSON.eve buildnever resolves dynamic tools, so only a turn that calls one proves it mounted —examples/eve-extension-demo's mock model now callsagentkit__search_countaftersave_memory, and the smoke eval gates on it (verified: reverting the fix fails exactly that gate, 3/4). (3) eve 0.59.0 replaced the eval API (6ddfa9b):EveEvalContextlost the session driver —t.reply/t.newSession()are gone,t.send()opens a FRESH session per call and returns anEveEvalTurn(turn.message,turn.calledTool(…),turn.session), andawait t.session()makes an explicit one for multi-turn conversations. Both evals were migrated;memory.eval.tsthreads all five turns through ONEt.session()because eve-demo's mock model countsuserMessagesagainsttoolResultsin the accumulated prompt — repeatedt.send()would compile, run, and test something else. eve'saipeer moved to^7.0.105, so the repo-wide pin went7.0.101→7.0.107(+pnpm -r update "@ai-sdk/*", oneai@7.0.107in the lockfile).packages/eve's peer stayed>=0.32.0and it ships no changeset: itsdistis byte-identical to published0.9.0. Test-baseline note: on a pay-as-you-go databasevitest runis 142 passed / 6 skipped / 0 failed — the "11 failures" earlier automated runs reported were the freestart-redisdatabase's 1-search-index cap, not eve. - Extension packaging changed 0.24 → 0.25: 0.24 shipped source the consumer recompiles; 0.25 ships
prebuilt
dist/extension+_manifest.json(see the eve-extension section). 0.25 rejects 0.24-format packages at discovery. - Import eve's real types — do NOT hand-roll them. From
eve/tools:defineTool,defineDynamic,disableTool,toolResultFrom,ToolDefinition,ToolContext,SessionContext(base of tool- hook ctx — use it for per-call
userIdfns). Fromeve/hooks:defineHook,HookContext. Fromeve/extension:defineExtension. Fromeve/sandbox:defineSandbox,SandboxBackend,SandboxSession,SandboxNetworkPolicy, etc. (eveis a devDep ofpackages/evefor these types.)
- hook ctx — use it for per-call
ToolDefinition<TInput,TOutput>={ description, inputSchema, execute(input, ctx: ToolContext), … }.- Extensions (eve ≥0.24): agent-shaped packages mounted under
agent/extensions/<ns>.ts; contributions compose as<ns>__<name>. They may contribute tools, channels, connections, skills, schedules, subagents, hooks and instruction fragments (eve ≥0.41; channels keep their declared route paths and schedules their cron expressions). The extension root cannot declare agent configuration, a sandbox, or nested extensions — but a contributed subagent may own its own config and sandbox. Config binds at runtime (mount evaluation), not at discovery. Hooks are observe-only (can't inject context or short-circuit); a thrown hook fails the turn. - Stream events for transcripts:
message.received(data.message: flattened user text) andmessage.completed(data.message: string | null, fires multiple times per turn — interim text before tool calls;data.finishReasontells terminal from narration). - Eve uses AI SDK v7 models, which is why the repo standardized on v7 (so eve can keep depending on the ai-sdk package instead of duplicating middleware).
- The real
SandboxBackendis two-phase:{ name, create(input) → SandboxBackendHandle, prewarm(input) → { reused } }.SandboxSession= the AI SDKExperimental_SandboxSession(run,spawn,readFile→stream,readBinaryFile,readTextFile,writeFile/writeBinaryFile/writeTextFile) plusid,resolvePath,setNetworkPolicy,removePath. The handle's lifecycle methods arestop()(eve ≥0.32: authored code ends sandbox work early viactx.getSandbox().stop(); must keep the session reattachable and reject on provider errors),shutdown()(server shutdown; best-effort, failures collected/logged by eve) and — since eve 0.47.0 — a requireddelete(options?: SandboxDeleteOptions)(authoredctx.getSandbox().delete(); permanently destroy the sandbox + its disposable state, preserve reusable/template state; errors reject and eve then keeps the reconnect state so the caller can retry). The old per-opendispose()is gone.SandboxDeleteOptions({ readonly abortSignal?: AbortSignal }) is exported fromeve/sandbox; neither it nordeleteexists in eve ≤0.46.1, sopackages/evesource now needs eve ≥0.47 to compile. After a successfuldelete, eve drops its own handle reference but leaves the handle in the process-wide active-handles map, soshutdown()can still be called on a deleted sandbox.
- Optional peer dep of the eve package.
Box.create({ apiKey | UPSTASH_BOX_API_KEY, runtime, size, … });box.exec.command(cmd) → { result, exitCode },box.files.read/write,box.getPublicURL(port),box.updateNetworkPolicy(...),box.pause()/delete().pause()= release compute, keep the box reattachable viaBox.get(id);delete()= permanent teardown of the box — that pair is exactly eve'sstop/shutdownvsdeletesplit. Snapshots outlive the box they were taken from (prewarmsnapshots a template box then deletes it), so deleting a box never touches template snapshots. - Snapshots (for eve templates):
box.snapshot(),Box.fromSnapshot(id),box.listSnapshots(),box.deleteSnapshot(id). Runtimes: node|python|golang|ruby|rust.
- It's a real
eveCLI scaffold, a workspace member — not a hand-written demo. Treat its generatedagent/,app/,components/as scaffold code. - It has a mocked-model e2e eval now (
evals/memory.eval.ts+evals/evals.config.ts), run withAGENTKIT_MOCK_MODEL=1 npx eve evalfrom the demo dir — noOPENAI_API_KEYneeded, real Redis.agent/agent.tsswaps in eve'smockModelunder that env var (same pattern as eve-extension-demo). The mock is prompt-aware:MockModelRequest.messagesexposes what eve injected, so echoing it is how the eval asserts on automatic memory recall. Watch out:toolResultslists every tool result in the prompt, not just this turn's — script against a count, notlength > 0. Eval API (eve ≥0.59):t.send()opens a FRESH session per call and returns anEveEvalTurn(turn.messageis the reply,turn.succeeded()/turn.calledTool()its assertions);t.replyandt.newSession()no longer exist. A multi-turn conversation needs one explicitawait t.session()andsession.send()for every turn —memory.eval.tsdoes exactly that, because the prompt-aware mock only works when all five turns share one accumulated conversation.eve evalworks fine in this demo despite its sandbox: nothing opens a Box during an eval, so noUPSTASH_BOX_API_KEYis needed. CI runs it. An eval file can talk to Redis itself —Redis.fromEnv()resolves inside the eval runner (it loads the project.env), so an eval can assert on persisted state and not just on the reply;memory.eval.tstags its fact with a per-run nonce and scansagentkit:memory:*for it, so a document left by an earlier run can't make the gate pass. - Two eve memory slots live in
agent/memory/(profile.ts=fileMemory({ backend: redisDocuments() }),recall.ts=redisMemory()), bothscope: byPrincipal. Slots are agent-owned — an extension cannot contribute them.byPrincipalfails closed (null for anonymous/runtime → slot disabled) where the old?? ctx.session.idfallback failed open into a per-session partition. It still keeps alice/bob separate becausedemoUserAuthruns beforelocalDev()inagent/channels/eve.ts, so the UI'sx-user-idheader supplies the principal; the eve TUI sends no header and lands on the sharedlocal-devprincipal. That header is demo-only — anyone can set it, so it is not a real tenant boundary. - Its
AGENTS.mdsays: readnode_modules/eve/docs/before writing eve agent code. - Every
agent/file must be self-contained. eve's dev-runtime snapshot resolves only package imports from each tool/channel/hook file — it does not include sharedagent/-source modules (a sharedagent/redis.tsoragent/lib/*both fail withCannot find module …at the turn step). So: no relative imports of other agent files; rely onredisdefaulting toRedis.fromEnv()(every helper, incl.createRateLimitAuth, defaults it — omit it). Search tools repeat theirschema+nameper file. App-only shared code (e.g. the books seeder a page calls) lives in the projectlib/, notagent/. (This is why the README's old "build once inagent/lib/" search-tools pattern was changed.) engines.node: 24.x→ CI (Node 24) is clean; local Node 20 only warns. It still builds on 20.- Keep
ai-sdk-demo's@types/reactpinned to19.2.15(andreact19.2.6) to match eve-demo and avoid a duplicate@types/react(causes a JSXkey"unique symbol" type clash in eve-demo's build).
- A minimal
eveCLI scaffold (agent + eve channel, no frontend) whose whole point is the one mount fileagent/extensions/agentkit.ts. Model:openai("gpt-5.4-mini"). - Its mount reuses eve-demo's books index (
eve-demo-books, same schema) — the DB caps at 10 search indexes, so the demos share; seed data comes from eve-demo'slib/books.tsseeder. - Needs a local
.env(gitignored) with the Upstash + OpenAI creds —eve devreads the project dir, not the repo root. - Its build script is
eve build --skip-sandbox-prewarmsince eve 0.64. eve 0.64 prewarms a sandbox template by default even for a scaffold with nosandbox/directory, and its default provider is just-bash, which eve does not bundle — a plaineve builddies with "The just-bash sandbox provider requires thejust-bashpackage, which is not bundled with eve" /Cannot find package 'just-bash'. On eve 0.63.0 the same project builds with no flag. The alternative is addingjust-bashas a devDependency; the flag is used here because this demo has no sandbox to prewarm.eve evalis unaffected — it never prewarms. - The extension demo's
userIdis the static"demo-user"so memory persists across sessions in an unauthenticated local agent (the default derivation would fall back to the per-session id).
Python lives beside the pnpm workspace, not instead of any of it:
- uv workspace at the root (
pyproject.toml, memberspython/*, oneuv.lock).pnpm py:lint(ruff) andpnpm py:test(pytest) run across every member;uv sync --all-packagessets it up. - Python packages are NOT versioned by Changesets (dropped 2026-11 for the Hermes plugin
catalog). The version lives in
pyproject.tomlonly. A Python package must not contain apackage.json: Hermes's installer (hermes_cli/plugins_cmd_install.py) treats anypackage.jsonin the plugin directory as Node dependencies, asks tonpm cithem and prints "Skipped Node deps" when declined — that was the catalog reviewer's complaint about the old private version-carrierpackage.json.python/*is therefore not inpnpm-workspace.yamleither, andCHANGELOG.mdis written by hand (## <version>sections; the release reads them).tests/test_version.pyguards the no-package.jsonrule. - Releasing a Python package: bump
versioninpyproject.toml, runnode scripts/sync-version.mjs(copies it intosrc/<module>/_version.py(VERSION, for telemetry) andplugin.yamlwhen the package has one), thenuv lock, and add the CHANGELOG section, all in one PR. Never edit_version.py/plugin.yamlversions by hand —sync-version.mjs --checkfails CI on drift. Both scripts read[project]name/version viascripts/pyproject.mjs. scripts/publish-python.mjs(pnpm ci:publish:python) runs on every push to main (no longer gated on "no pending changesets"): for everypython/*whose version is not on PyPI yet,uv build+uv publish(trusted publishing, no token), then tag<name>@<version>+ GitHub release from the CHANGELOG section. Idempotent and keyed on the registry.0.0.0= unreleased and is always skipped.--dry-runprints the plan. So merging a version bump publishes it.release.ymlrunsgit checkout --detach ${{ github.sha }}before it: in version modechangesets/action(defaultcommitMode: git-cli) leaves HEAD on itschangeset-release/main"Version Packages" commit, and an untaggedgit tagwould land there instead of on main.- Adding a package:
python/<name>/withpyproject.toml(version = "0.0.0"until the first release),src/<name with _>/_version.py, tests. Then register a PyPI trusted publisher for it (repoupstash/agentkit, workflowrelease.yml) before its first non-zero version merges. - Telemetry in
upstash-hermes-memoryis opt-in (catalog rule 13: "Telemetry and usage reporting are opt-in").AgentMemory/ChatHistorydefaultenable_telemetry=False; the provider enables it only forUPSTASH_HERMES_TELEMETRY=1(read viaget_secret, per profile) and creates itsupstash_redis.Rediswithallow_telemetry=the same flag, because upstash-redis sends its ownpy-upstash-redis/runtime/platform headers by default.UPSTASH_DISABLE_TELEMETRYwins over the opt-in. This deliberately differs from the TS packages, where telemetry is on by default. - Python tests share the test Redis (10-index cap) with vitest: run them after the Node tests,
never in parallel, and reuse the TS key prefixes/index names when the data is meant to be shared.
Live tests take a unique
prefixfixture and drop their indexes; callindex.wait_indexing()after a write or delete before asserting on search results (SEARCH.COUNTlags otherwise). upstash-hermes-memorye2e:uv run python python/hermes-memory/e2e/hermes_e2e.pydrives a real Hermes (temporaryHERMES_HOME, package onPYTHONPATH,gpt-5-miniviaOPENAI_API_KEY; Hermes sendsreasoning.effort, so non-reasoning models likegpt-4o-minifail) and checks Redis.
- Setup gotcha — use pnpm 11.5.3, matching the
packageManagerpin. Rootpackage.jsonpins"packageManager": "pnpm@11.5.3". On a box whose global pnpm is a different version (and no corepack), every pnpm command dies withERROR Failed to switch pnpm to v11.5.3. Looks like pnpm CLI is missing at ".../pnpm/11.5.3/bin" … spawnSync … ENOENT. Install the pinned version rather than working around it:A second flavour of the same error: pnpm 11 did download 11.5.3 intonpm i -g pnpm@11.5.3 # or, to a local prefix: npm i -g pnpm@11.5.3 --prefix /tmp/pnpm11~/.local/share/pnpm/.tools/pnpm/11.5.3/but itsbin/*symlinks point at a…_tmp_<pid>path under a different home prefix (e.g./workspace/home/...when$HOMEis/home/boxuser), so they dangle and every pnpm invocation still ENOENTs. Repoint them at the real files that are already there:The escape hatchD=~/.local/share/pnpm/.tools/pnpm/11.5.3 ln -sf $D/node_modules/pnpm/bin/pnpm.mjs $D/bin/pnpm; ln -sf $D/node_modules/pnpm/bin/pnpm.mjs $D/bin/pn ln -sf $D/node_modules/pnpm/bin/pnpx.mjs $D/bin/pnpx; ln -sf $D/node_modules/pnpm/bin/pnpx.mjs $D/bin/pnx
pnpm config set manage-package-manager-versions false --globaldoes let an older pnpm run, but don't ship a lockfile written by it: pnpm 10.x rewritespnpm-lock.yamldropping ~51libc: [glibc|musl]fields (huge spurious diff, and CI's--frozen-lockfileon pnpm 11 will disagree) and it ignorespnpm-workspace.yaml'sallowBuilds, printingIgnored build scripts: esbuild, sharp. - Non-interactive shells:
pnpm installcan abort withERR_PNPM_ABORTED_REMOVE_MODULES_DIR_NO_TTYwhen it wants to purgenode_modules. Prefix withCI=true— but noteCI=truealso implies--frozen-lockfile, so a deliberate dependency bump needsCI=true pnpm install --no-frozen-lockfile. - Node also warns
Unsupported engine: wanted {"node":"24.x"}on newer Node — harmless, everything builds and tests fine.
pnpm build # tsup (ESM + dts) all packages
pnpm typecheck # builds the sdk first, then tsc --noEmit across packages
pnpm lint # eslint + prettier (*.md is prettier-ignored)
pnpm test # vitest run (against real Redis)
pnpm -r --filter "./examples/*" build # build both demo apps- CI: Node 24 + pnpm 11; runs lint → typecheck → build → test → example builds.
Every in-repo check runs against pnpm-lock.yaml, so it cannot see how a consumer's resolver will
lay out our dependencies — that blind spot is what hid the dual-zod bug. When you change any
dependencies/peerDependencies of a published package, verify in a real scratch consumer:
cd packages/eve-extension && pnpm pack --pack-destination /tmp # rewrites workspace:* -> the real version
mkdir /tmp/c && cd /tmp/c # scaffold: package.json (type:module,
# imports {"#*":"./agent/*","#evals/*":"./evals/*"}),
# agent/agent.ts, agent/channels/eve.ts,
# agent/extensions/agentkit.ts, evals/
npm install eve@latest /tmp/upstash-agentkit-eve-extension-*.tgz \
@upstash/redis @ai-sdk/openai ai zod @vercel/connectCopy examples/eve-extension-demo's agent/agent.ts (the AGENTKIT_MOCK_MODEL scripted mockModel)
and its evals/agentkit-smoke.eval.ts, then AGENTKIT_MOCK_MODEL=1 npx eve eval. eve build passing
proves almost nothing about dynamic tools — only a turn that calls one does.
Two cheap, Redis-free checks worth running first:
# 1. how many copies of a dep does the consumer actually have, and who gets which?
find node_modules -path "*/zod/package.json" | while read f; do echo "$f $(node -p "require('./$f').version")"; done
# 2. does the extension's zod convert the sdk's schema? (reproduces the dual-instance break in ~1s)
# import createSearchToolDefs from the consumer's sdk, then call the EXTENSION's zod
# toJSONSchema(defs.search.inputSchema) -> "Cannot read properties of undefined (reading 'push')" == two instances- Releases use Changesets:
pnpm changeset,pnpm ci:version,pnpm ci:publish. Do not usepnpm version/pnpm release(they collide with built-in pnpm commands). Keep one pending changeset per package, describing the final state..changeset/accumulates across PRs, so a bump that supersedes an unreleased changeset already onmain(e.g. an eve version bump re-stamping the extension manifest and floor a second time) must fold it in, not sit beside it — two entries with contradictory peer floors would both land in the same CHANGELOG. Write the merged entry against the last published version (npm view <pkg> version peerDependencies- the package CHANGELOG), not against the intermediate that never shipped.
npx changeset statusshows what the pending set resolves to.
- the package CHANGELOG), not against the intermediate that never shipped.
- Conventional commits; use
!for breaking changes. Commit at meaningful checkpoints.
Historical log — superseded naming. The items below record a completed task and use the intermediate
namespacename, which was later renamed touserId(the per-call tenant value) plustoolName(the cache's tool segment). For the live key naming and conventions, see the "API conventions" section above — not this checklist.
- Remove model cache (code + examples done; READMEs pending below).
- ai-sdk: add
cachedTools(map oftool()-built tools, namespace defaults to map key) alongsidecachedTool;cachePrefix→namespace; droppedtoolCachefrom the config. -
cachedTool/cachedToolsare fully type-safe (config extends the AI SDKtool()type — input/output inference, noany). - Search tools: ensure the index (create +
waitIndexing, memoized) before running each tool — a missing Upstash index returnsnull/-1rather than throwing, so we ensure up front. -
createMemoryTools(ai-sdk) + eve memory tools:scope→namespace(string or per-call function). CoreAgentMemoryadd/recall/forget usenamespace. - Rate limiting:
namespaceis a plain string; prefixagentkit:rateLimit. - Key naming (now
userId/toolName, notnamespace):agentkit:rateLimit:<identifier>,agentkit:toolCache:<userId>:<toolName>:<hash>,agentkit:memory:<userId>:<id>. - Unit/e2e tests use
gpt-4o(TEST_MODEL). - eve: dropped the
./modelsubpath — model wrappers are exported from the package root. - ai-sdk example app fleshed out (memory + search + cached tool + rate limit).
- READMEs (root + 3 packages): feature order = agent memory, search tools, sandbox (eve only), tool cache, rate limiting; never show
wrapLanguageModel; all method options with inlineoptional:comments; cached-tool snippet importsgenerateText+ a prompt; model cache removed;gpt-5.4-mini; reflectnamespace/cachedTools/no-./model. - Flesh out the eve + ai-sdk example apps with all features.
- eve
./sandboxrewritten as a class implementing eve's real two-phaseSandboxBackend(types imported fromeve/sandbox); typechecks against eve and the live-Box test passes.
- eve
./sandbox—UpstashSandboxprovider (packages/eve/src/sandbox.ts, eve ≥0.64 contract,@upstash/box≥0.7.1).UpstashSandbox = defineSandboxProvider({ name: "upstash", environment }); users writeexport const environment = UpstashSandbox.environment({...})andexport default defineSandbox(() => environment.open()). Options =Omit<BoxConfig, "networkPolicy" | "name">+prepare(sandbox)+baseSnapshot. Mapping:prepare(ctx)(runs ateve build, lazily on first access undereve dev, in the build process) → temp box, writectx.resources(workspace tree →/workspace, skills tree → literal$HOME/.agents/skills, expanded by runningprintf %s "$HOME"in the box), run the user hook,box.snapshot(), delete the temp box, return{ snapshotId }(or{ snapshotId: null }and no box when there's nothing to bake). eve persists that artifact in the build output — so the old Redis template registry is gone (and with it theredis/templatePrefix/enableTelemetryoptions).start(ctx, open, artifact)→Box.fromSnapshot(orbaseSnapshot, orBox.create), deny-all at creation, thenopen.networkPolicyif given; returns state{ boxId, version: 1 }. A missing prepared snapshot throws ("rebuild or redeploy") — Box reports it as "Snapshot is not ready" — instead of falling back to an empty box. Box names are account-unique, so each start names its boxeve-<sha256(session.id)[:12]>-<random6>;nameis therefore excluded from the options (the old backend passed a usernamestraight toBox.create, which would have collided on the 2nd box).resume(ctx, artifact, state)→Box.get(boxId)plusgetStatus():Box.getresolves for a deleted box (its record lingers withstatus: "deleted"), so without the status check resume handed eve a dead box — caught by the live test. A gone box throws (eve's contract: resume must not recreate);sandbox.delete()is how a session gets a fresh one. Handle:onSessionStop→pause()(rejects on failure),onRuntimeShutdown→pause()(swallowed),onSessionDelete→box.delete()(honours an already-aborted signal; adeletedflag makes repeat teardown a no-op). The snapshot is shared by every session of the environment and is never deleted by a session. Session:run/spawnuse Box'sexec.session(WebSocket; ≥0.7.1): streamed, separate stdout/stderr, env asKEY=VALUE(reaches every command in a&&chain — the oldK=v cmdprefix did not), cwd, and kill on eve's abort signal (eve binds the turn's signal to every session call; the old bufferedexec.commandcould not cancel). eve's built-inbash/glob/grepcallrun,read_file/write_filecallreadTextFile/writeTextFile. Paused boxes auto-resume on exec. Network policy lives on the box (survives pause/resume), so the old "re-apply the persisted policy on every open" workaround is gone. Path bridge unchanged:toBoxPath/rewriteWorkspacePathsmap/workspace→/workspace/home. Known limitation: eacheve buildwith something to prepare mints a new snapshot (Box has no snapshot lookup by name), so old snapshots accumulate. Verified 2026-09-23: 17 offline + 3 live-Box tests insandbox.test.ts(full prepare → start → stop → resume → delete cycle; spawn streaming/kill; abort; attachHeaders), plus an out-of-repo e2e: packed tarballs + eve 0.65.0,eve buildprepared a snapshot, and a two-turn mocked-modeleve evalhad the built-inbashtool read the workspace seed, a skill and theprepareoutput, confirm deny-all egress, and read turn 1's file back in turn 2 (resume) — one Box per session, no leaked prepare boxes. That e2e is not in CI (it needs a Box key). — verified live (2026-08): it exists and responds in both demos. No swap needed.gpt-5.4-mini(demo model) may not exist- The
19.2.17@types/reactmay linger as an unpruned orphan in.pnpm; harmless (nothing links it).
- Entry points (tsup +
exports):.= everything that needs only@tanstack/ai(stream, locks, middleware, search,RedisLock/EventLog);./persistence(src/persistence/index.ts, needs@tanstack/ai-persistence),./memory(src/memory/index.ts, needs@tanstack/ai-memory),./byok(src/byok/),./sandbox(src/sandbox/index.ts, needs@tanstack/ai-sandbox) and./mcp(src/mcp/index.ts, needs@tanstack/ai-mcp). Rule: the root entry must never import types from an optional peer — checkdist/index.d.tshas no@tanstack/ai-persistence/@tanstack/ai-memory/@upstash/blobimport after a build. (Copilot review on #48; verified 2026-09-28 with a consumer that has only@tanstack/aiandskipLibCheck: false— the only errors are two pre-existing ones inside@tanstack/ai's ownspawn.d.ts.) - Demo + E2E (
examples/tanstack-ai-demo): Next.js port of TanStack'sts-react-chatpersistent-chat route onto our backends (detached run,resumeServerSentEventsResponse,reconstructChat, memory), withRedisLockreplacing its process-local "one producer per run" set:withLock(runId, fn, { acquireTimeoutMs: 0 })(timeout = someone else produces it, just tail), lease renewed for the run, and on lease loss the run is aborted and the producer neither appends nor closes the log (the new owner may be writing). The producer promise goes to Next.jsafter()(+maxDuration) so it survives the response on serverless; truly durable background runs (QStash) are a follow-up.AGENTKIT_MOCK_MODEL=1swaps in a scripted model (lib/model.ts: word-by-word stream,remember:→save_memory, echoes recalled memories).pnpm e2e(e2e/, files*.e2e.tsso rootpnpm testskips them) starts twonext startservers on free ports, one Redis, a per-runDEMO_PREFIX, and checks cross-instance resume, mid-run reconstruct, memory across threads, single production of a doubly-POSTed run, single production of a run that outlives its lease (PRODUCER_LEASE_MS=1000+ along:~6s mock answer), and a 400 on a bad body. CountTEXT_MESSAGE_STARTto detect a second producer: two producers interleave their words in one log, so text regexes miss it (a no-renewal build passed a regex check and failed this). Gotchas hit building it: AG-UI bodies need a messageid; Next.js route handlers don't return a thrownResponse(catchchatParamsFromRequest's 400 yourself); spawnnode_modules/.bin/nextdetached and kill the process group (killingnpxorphansnext); backends are created lazily sonext buildneeds no credentials. CI runs it after "Build example apps"; skipped without Redis secrets. src/package-exports.test.tspinspackage.json#exportsto the tsup entries — added after a pushed commit shippeddist/persistence.jswithout exporting it (only the demo's build caught it).- Layout (
src/): one folder per feature —persistence/(stores,records.tsplumbing,blob-store.ts),stream/(upstashStream+EventLog),locks/(upstashLocks+RedisLock),memory/,middleware/,search/, andtesting/(scripted adapter, test bucket, env helpers — never imported byindex.ts). Root:index.ts,telemetry.ts,version.ts,integration.test.ts. - Redis primitives (
src/locks/redis-lock.ts,src/stream/event-log.ts; moved here from core 2026-09-28, exported from this package):RedisLock(+LockLease,LockAcquireTimeoutError,LockLostError) —SET NX PXlease + a never-expiringINCRfencing counter, release/extend are ownership-checked Lua;withLockrenews everyleaseMs/3and aborts the section's signal on loss.EventLog(+LogEntry,EventLogClosedError) — Redis Streams:appendis oneEVALscript ofXADDs (atomic, ordered ids) that refuses a closed log and refreshes the stream TTL,readresumes with an exclusiveXRANGE (idand tails by polling (REST keeps no blocking reads),closesets a separate:closedkey and readers do a final drain after seeing it, so nothing appended before close is lost. Values carry anagentkit-event-v1:marker because@upstash/redisauto-deserializes stream fields ("123"would come back as123). Both verified live over REST (2026-09-27):MULTI+XADD,XRANGE (,EVAL,SET NX PXall work. - Why it exists: TanStack AI (≥0.61) defines backend contracts for production state and ships
only in-memory implementations (
memoryPersistence,memoryStream,InMemoryLockStore,InMemoryRunStore, the ai-memoryinMemory()/ioredis-shapedredis()adapters). As of 2026-09 there were no Redis/Postgres persistence backends on npm. This package fills the seams; it does not wrap models or reinvent TanStack features. - Already upstream, don't duplicate:
@tanstack/ai-sandbox-upstash-box(Box sandbox provider) is TanStack's own package. - Exports:
upstashPersistence(messages/runs/interrupts/metadata),upstashStream(StreamDurability, offsetsupstash:v1:<encodeURIComponent(runId)>:<streamId>),upstashLocks(LockStoreoverRedisLock,src/locks/),upstashMemory+memoryScopeKey(MemoryAdapterover coreAgentMemory),toolCache/rateLimitmiddlewares +RateLimitExceededError,createSearchTools(returns aTool[]built withtoolDefinition().server()), re-exportedcreateRateLimit/Ratelimit. - Peers:
@tanstack/airequired;@tanstack/ai-persistenceand@tanstack/ai-memoryoptional (only their types are imported, so the runtime never needs them).@tanstack/aiis pinned exactly as a devDep (0.61.0) — TanStack AI is pre-1.0 and moves fast; re-run the conformance suite on bumps. - Persistence layout (
agentkit:tanstack:*): every record (run, interrupt, generation run, artifact, blob record, metadata value, transcript) is a RedisJSON document, so values keep their JSON types and need no codec. Shared plumbing is insrc/records.ts:CREATE:JSON.SET … NX+ZADDinto each index, returns the stored doc (idempotentcreateOrResume).PATCH:EXISTSguard (a bareJSON.MERGEon a missing key creates it, verified live 2026-09-28) thenJSON.MERGE.toMergePatchesturns{...existing, ...patch}semantics into two merge patches: a key present withundefinedbecomesnull(merge-patch delete); object-valued fields are nulled in the first patch and set in the second, because merge patches merge nested objects instead of replacing them. A literalnullin a patch therefore deletes the field.checkRunvalidates run status at read time (TanStack's readers act destructively on it).
- Indexes:
threadRuns:<id>/parentRuns:<id>(zset bystartedAt),detachedRuns(bydetachedSince, a candidate list —listReclaimablere-checks each record),threadInterrupts/runInterrupts(byrequestedAt),threadGenerationRuns,runArtifacts/threadArtifacts(bycreatedAt, ties byte-ordered like the reference store).commitBatchchecks every interrupt is present and pending (JSON.GET $.status) and applies all patches in one script. - Artifacts: which indexes a doc is in lives in a side hash
artifactIndexes:<id>(raw index-key strings) so the doc stays exactly the record. Re-saving under another run/thread: the caller reads the side hash, declares the old index keys (required byallow-key-locking), and the script compare-and-swaps, retrying on a race. - Metadata: one doc per pair, key
meta:<encodeURIComponent(ns)>:<encodeURIComponent(key)>, value wrapped as{ v }so a bare string round-trips. - Blobs (
blob-store.ts, only whenupstashPersistence({ bucket })): bytes in Upstash Blob at an immutable versioned path<pathPrefix><encodeURIComponent(key)>/<uuid>;blobVersion:<key>points at the current one and is swapped in the same script as the record (PUT_RECORDreturns the replaced path, deleted after commit;DELETE_RECORDlikewise), andgetreads record + pointer in oneMULTI, so concurrent puts can never leave a record describing another writer's bytes; the record is a JSON doc plus a lexical zset of keys.PUT_RECORDreplaces the doc but restores the oldcreatedAt(read viaJSON.GET $.createdAt). Blob listings omit content type + metadata, hence records in Redis. Ranges usesignedReadUrl+Range; a 200 is sliced locally.@upstash/blobis an optional peer (structuralBlobBucketLike). Live-Blob conformance runs withUPSTASH_BLOB_TOKEN(get it via the MCP'sblob_bucket get+include_credentials): 26/26 on 2026-09-28. - Config types reuse the primitives and core:
UpstashLocksConfig = Omit<RedisLockConfig, "redis"> & {redis?},UpstashStreamConfigfromEventLogConfig,ToolCacheMiddlewareConfigfromToolCacheConfig,UpstashMemoryConfigpicks fromAgentMemoryConfig,CreateSearchToolsConfigfromSearchToolDefsConfig— spread straight through, no per-field copying. - Memory: own keyspace
agentkit:tanstackMemory(its schema adds an indexedsourcefield, so it must not shareagentkit:memory— see the eve memory-slot notes on why). Scope →userIdviamemoryScopeKey: per user across threads by default, parts escaped so./_/:can't forge a collision. Recalled lines are labelled by source like eve'sredisMemory(). - Testing:
persistence.test.tsruns TanStack'srunPersistenceConformance(from@tanstack/ai-persistence/testkit; it declares a vitest ^4 peer but runs fine on the repo's vitest 2) with a fresh prefix per case — all seven stores, nothing skipped, 26/26 on 2026-09-27.memory.test.tsalso runsrunMemoryAdapterContract(@tanstack/ai-memory/testkit), each scope pinned under a unique tenant — it needswaitForIndexing(save provisions the index once, writes, then waits), exactly like eve'sredisMemory()capture. Middleware/memory/search tests drive a realchat()agent loop throughsrc/test-adapter.ts(a scriptedTextAdapteremitting AG-UITOOL_CALL_*/TEXT_MESSAGE_*/RUN_FINISHEDchunks) — no model provider needed. - Not built yet (proposed): Code Mode isolate driver on Box (port of
@tanstack/ai-isolate-daytona's need_tools/replay loop), QStash-backed background runs writing toupstashStream, a QStash schedule forreapDetachedRuns,@tanstack/ai-code-mode'sAgentStoreand@tanstack/ai-code-mode-snippets'SnippetStorage(both small keyed stores;ai-code-modepeers the pre-1.0@tanstack/ai-harness). - Hybrid recall + one shared index (2026-11-13, minor for sdk/ai-sdk/eve/eve-extension/tanstack-ai):
@upstash/redis >=1.41.0(s.hybrid()).AgentMemory/ChatHistorywith default config share one index,agentkit, overagentkit:memory:+agentkit:chat:(src/shared-index.ts, same schema as the Python package). Chats still getkind: "chat"(Python reads it), but TS tells chats apart bysessionId(IS_CHAT=sessionId $regex ".+"; Search has no "exists"): chats saved before the shared index have nokind. A store with its ownprefix/indexName/metadataSchema(eve memory slot, TanStackupstashMemory) keeps its own index. MemorytextisHYBRID; recall with a query is$rrfof$smart+$ann.minScore > 0makes recall keyword-only above that BM25 floor (rank-fusion scores have no cutoff). Only anUpstashErrorfrom the hybrid query falls back to keyword, with aconsole.warn.ReactiveSearchIndex({ createFirst: true })(memory, chat history) sends itsexistsOkcreate before the first read: an older definition fails with aSEARCH.DROPhint, a full one-index database with one namingagentkit_memory/agentkit_chat, and a failed create is forgotten so the next read retries. Search tools leavecreateFirstoff (a caller's own index may cover more fields than the tool's schema). Reviewed 2026-11-17 against an upgrade frommainon a one-index database. The repo test database is NOT capped at one index (it held four). - eve 1.0.1 (2026-11-17): all eve pins are
1.0.1(stable; was1.0.0-rc.9) (this supersedes the "eve still on 0.91.0" notes below). The extension is built with it, and eve refuses a dist built with a newer eve, so its peer is>=1.0.1(0.x users stay on extension 0.19).packages/evekeeps>=0.87.0 || >=1.0.0-0.redisMemory()gives its tools fixed evelabels ("Saving to memory", ...), never the tool input. - @upstash/box 0.8.0 (2026-11-15):
packages/evedevDependency andexamples/eve-demomoved^0.7.5→^0.8.0(a caret on 0.x never picks up the next minor); peer stays>=0.7.1, no code change, no changeset. 0.8.0 deprecatesBoxApiKey.UpstashKey(Upstash no longer provides model keys for box agents), which./sandboxdoes not use; typecheck, build, the 25 offlinesandbox.test.tscases and the eve-demo build pass (the 3 live-Box cases needUPSTASH_BOX_API_KEY). No newai/@tanstack/ai*release since 7.0.173 / 1.4.0. evelatestis1.0.0-rc.18(still no stable after 0.91.0): published@upstash/agentkit-eve-extension@0.19.0+@upstash/agentkit-eve@0.19.0install on it with one eve/ai/zod,eve buildclean, mockedeve eval4/4; this repo with every eve pin on rc.18 also passes lint, typecheck, build, the eve example builds and both mocked evals. A dist built on rc.18 stampsbuiltWithEve: 1.0.0-rc.18and is refused by rc.17 and rc.9 alike (was built with eve 1.0.0-rc.18. Upgrade eve to 1.0.0-rc.18 or later), so the extension's peer floor must equal the exact RC it is built on (PR #104). - ai 7.0.173 (2026-11-14): pins moved 7.0.172 → 7.0.173 with
@ai-sdk/*refreshed (openai ^4.0.118,react ^4.0.177; oneai@7.0.173in the lockfile); no code change, devDependency/example pins only (no changeset). eve1.0.0-rc.17raised itsaipeer to^7.0.172, so the eve 1.0 adoption (PR #104) needs at least this pin. eve still on 0.91.0 here (no stable since); published@upstash/agentkit-eve-extension@0.19.0+@upstash/agentkit-eve@0.19.0install on rc.17 with one eve/ai/zod,eve buildclean, mockedeve eval4/4. TanStack: no new@tanstack/ai*contract release since 1.4.0; thespawn.d.tsTS2307 (skipLibCheck: false) is still in 1.4.0. - ai 7.0.172 (2026-11-13): pins moved 7.0.170 → 7.0.172 with
@ai-sdk/*refreshed (openai ^4.0.117,provider ^4.0.38,react ^4.0.176; oneai@7.0.172in the lockfile); no code change. Behaviour note from 7.0.171:toUIMessageStreamnow sends a failed tool call's real error text to the client (was "An error occurred."; opt back in withredactToolErrors: true), so any message an agentkit tool throws is user-visible. eve still on 0.91.0 (npmlatestis1.0.0-rc.13, not adopted); published@upstash/agentkit-eve-extension@0.19.0+@upstash/agentkit-eve@0.19.0install on rc.13 with one eve/ai/zod,eve buildclean, mockedeve eval4/4. - ai 7.0.170 + @tanstack/ai 1.4.0 + @tanstack/ai-openai 1.1.1 (2026-11-12): devDependency/example pins only (no published-content change, no changeset);
@ai-sdk/*ranges moved withpnpm -r update "@ai-sdk/*"(oneai@7.0.170in the lockfile) andpnpm dedupedropped a stale second@tanstack/ai@1.1.0that@tanstack/ai-client@1.1.0(^1.1.0) kept in the lockfile. eve stays on 0.91.0: no stable release since, npmlatestis1.0.0-rc.10(not adopted; eve 1.0 adoption is PR #104); published@upstash/agentkit-eve-extension@0.19.0+@upstash/agentkit-eve@0.19.0install on it,eve buildclean and the mockedeve evalpasses 4/4. AskipLibCheck: falseconsumer ofaierrors inside@ai-sdk/provider(TS7016 … module 'json-schema', no@types/json-schemadependency) on 7.0.163 through 7.0.170 alike: upstream, fixed bynpm i -D @types/json-schema. The free throwaway Redis caps search indexes at 1: run index-using test files one at a time withFLUSHDBin between (FLUSHDBdrops the indexes too;SEARCH.DROPINDEXis not available). - ai 7.0.163 (2026-11-05): pins bumped from 7.0.159 (no code change);
examples/ai-sdk-demo's@ai-sdk/reactraised to^4.0.167because 4.0.160 depends on an exactai@7.0.156, which split theUIMessagetype from the demo'sai@7.0.163and failednext build(SteeringMessageUIPart). Re-checked 2026-11-05: published@upstash/agentkit-eve-extension@0.19.0/@upstash/agentkit-eve@0.19.0build clean oneve@1.0.0-rc.5(the 0.91.0 build stays); TanStack AI 1.x (ai 1.1.0, ai-persistence 1.0.1, ai-memory 1.1.0) still not adopted (samethreadId/blobKeytest-file errors). - TanStack AI 1.x applied (2026-11-05):
@tanstack/ai1.1.0,ai-persistence1.0.1,ai-memory1.1.0 (devDeps, exact) and the tanstack-ai-demo'sai-client1.1.0 /ai-react1.0.2 /ai-openai1.1.0.srcneeded no change; only tests did:chat()calls passthreadId(middleware.test.ts,search-tools.test.ts) andArtifactRecordfixtures carryblobKey(persistence.test.ts). The peer floors (>=0.65.0/>=0.8.0/>=0.2.8) are untouched: the source is unchanged and still works on 0.x, and published@upstash/agentkit-tanstack-ai@0.2.0imports on 1.x, so no changeset. Upstream@tanstack/ai@1.1.0'sspawn.d.tsstill has the brokenimport('../../..')(TS2307 withskipLibCheck: false). The 1.0 contractsSessionIndexStoreandCredentialStoreare implemented in the follow-up below. - Sandbox + MCP stores (2026-11-11,
@upstash/agentkit-tanstack-aiminor):./sandbox=upstashSandboxCheckpointStore(SandboxCheckpointStore+forkFromCheckpoint) andupstashSandboxInstanceStore;./mcp=upstashMcpTaskStore(TaskStoreforcreateMCPServer) andupstashMcpEventStore(MCPEventStore, MCP Events direct mode) andupstashMcpSessionStore(below). Optional peers@tanstack/ai-sandbox/@tanstack/ai-mcp>=1.0.0(checkpoint/instance.d.tsandMCPEventSubscriptionare identical from 1.0.0 to 1.2.x). Gotchas: (1) writer leases are"<token>|<fence>|<expiresAt>"strings compared against the CALLER's clock in Lua (ARGV), not a Redis TTL — the conformance suite injects a fakenow; the PX is lease + 1 day, GC only. (2) The fork must refuse a destination with ANY persistence state (transcript,threadRuns,threadInterrupts,threadGenerationRuns,threadArtifacts) and write the transcript into${prefix}:thread:<id>in the same script — so the checkpoint store must shareupstashPersistence()'sprefix(thread ids are NOT URI-encoded in those persistence keys; our ownsandbox:*keys are). (3)runSandboxCheckpointForkConformancecreates the fork promise before reading destination state over the network, so a live-Redis rejection shows up as a vitest "unhandled error"; the test wrapsforkFromCheckpointwith a no-op.catch(assertions unchanged). (4) Heads, index members, id-index values and set members are"~" + id, because@upstash/redisJSON-parses"007"to7. (5)src/sandbox/validate.tschecks only ids,createdAtand blob keys (they become hash fields); TanStack re-checks paths, sizes and hashes on restore. FORK writes the transcript first: a Lua script is not rolled back on error. (6)upstashPersistencegained an overload: withbucketthe return type has a requiredblobs, whichcreateSandboxSnapshotsneeds (src/sandbox/wiring.test.tspins it). Also runsrunDurableRunFieldsConformanceon the run store.upstashMcpSessionStore(McpSessionStore, MCP Apps):- What can't be stored: its
McpServerDescriptorcarries functions (toolFilter,needsApproval,toolName) and transport objects (fetch,authProvider). set: stores only JSON-safe fields, checked by prototype and recursion inisJsonSafe, and records the dropped paths inm. With a key, the whole{d, m}is sealed with AES-GCM (src/secret-box.ts, shared with BYOK; the AAD is prefix + thread + server), so a Redis writer cannot change the url or stripm.get: calls the user'sresolve({ threadId, serverId, descriptor, missing }), then FAILS CLOSED, returningnullif any recorded path is still missing. Upstream'screateMcpAppCallHandlerthen falls back to its registry (descriptor.x ?? fromRegistry?.x, per field) or refuses.- Why fail closed: a per-thread server that lost
needsApprovalwould let a widget run a gated tool. - Test:
src/mcp/session-store.test.tsdrives the real handler against a realcreateMCPServerover node:http that requires the stored Authorization header.
- What can't be stored: its
- TanStack AI 1.0 contracts implemented (2026-11-05,
@upstash/agentkit-tanstack-aiminor):stores.log(persistence/log-store.ts, see below),stores.sessions(SessionIndexStore,persistence/sessions.ts) and./byok(upstashCredentials,byok/credentials.ts,CredentialStore). Peer floors raised to@tanstack/ai >=1.0.0and@tanstack/ai-persistence >=1.0.0(verified by packing 0.71.0/0.10.1: neither hasSessionIndexStore/@tanstack/ai/byok;ai-memoryfloor untouched). Sessions: doc{r,e}per(tenant, thread)+ one ZSET per tenant (scoreupdatedAt, member~<threadId>so the client never JSON-parses a numeric-looking id);listwalks the ZSET in batches of whole score groups and re-reads a tie group in full so thethreadIdUTF-8 order is exact, filtering after loading;ZRANGE BYSCORE REVtakes(max, min)(cast throughnumber, the SDK types forbid(-exclusive strings). Revisions come from anINCRcounter, never reused (the credential contract requires that; sessions may reuse). Passes the 19sessionscases ofrunPersistenceConformance(they run only when the store is present). Credentials: one hash per owner (%nonesegment = undefined tenant/user, distinct from""), value{r,t,x?,c | iv,ct}with type/expiry in the clear solistnever decrypts; optional AES-256-GCMencryptionKey, AAD = owner key + id (a copied ciphertext does not decrypt).storedProviderKeyslives in@tanstack/ai/byok/server, not/byok.stores.log(LogStore): per log a meta hash (head, first, epoch, owner, harness, exp, rel, wake, aff, del, laneH, oseq), a records ZSET (score seq, member<seq>:<json>), snapshot string (seqmust stay the first JSON key:truncatereads it with a Lua pattern), offers hash + info hash + pending ZSET, and a tick counter; sharedlogDueZSET (when each log needs an owner) andlogHostshash. Every op is one Lua script over the same nine declared keys; the store clock is RedisTIMEinside the script; numbers written from Lua go through%.0f(plaintostringprints epoch ms in scientific notation); ids returned from Lua are~-prefixed because the client JSON-parses numeric-looking strings ("007"-> 7).subscribe= immediate local callback + areportedand anobservedtick per log so each counter value is reported once (a baseline read that already contains a local write must not mark it reported: that swallowed the notification), plus a 250 ms tick poll for other machines (non-overlapping; a watch starts from this store's own last write to the log, thewrittenmap, not from its first read, so another machine's write that lands before the first poll is still reported; a failed read is retried on the next tick).changed()skips a counter the poll already reported (deterministic repro in tests: delay the append reply with a Proxy), which fixed a double notification (a poll can see the tick before the write reply arrives; it failed thecalls a listener after each appendconformance case in CI).appendrejects more than 10,000 records (a 50,000-record batch outran the Lua time limit and left part of the writes). Known follow-ups:listLogsWithoutOwnerre-checks entries skipped byharnesses/ a live pin on every call; consumed offers, old hosts anddeleteLogtombstones are never cleaned up;read/listOfferedInputswithout a limit return everything. Conformance needs thetwinoption (a second store set on the same keyspace) for the 4log across instancescases; all 56 log cases and 19 sessions cases pass. Not implemented:ownershipTTL-based cleanup of finished logs (logs and their keys live untildeleteLog). - eve 0.91.0 + ai 7.0.159 (2026-10-31):
eve ^0.91.0/ai 7.0.159everywhere; the eve-extension dist is rebuilt on 0.91.0 (manifestbuiltWithEve: 0.91.0) and itsevepeer floor is>=0.91.0 || >=1.0.0-0— verified by packing the 0.91.0-built dist into consumers: eve 0.90.0 refuses it (was built with eve 0.91.0. Upgrade eve to 0.91.0 or later), 0.91.0 and1.0.0-rc.1build clean. Both eve peers carry|| >=1.0.0-0because semver never matches a prerelease against>=0.x:npm install eve@latest(1.0.0-rc.1) failed ERESOLVE against the published@upstash/agentkit-eve@0.18.0(peer eve@">=0.87.0"). Not adopted:eve@1.0.0-rc.1(a dist built on it stampsbuiltWithEve: 1.0.0-rc.1and would refuse every 0.x eve, so build on stable) and TanStack AI 1.0 (@tanstack/ai1.0.1,-persistence1.0.1,-memory1.0.0):chat()now requiresthreadIdandArtifactRecordrequiresblobKey, sopackages/tanstack-aitest files failtscand the middleware tests throwchat() needs a threadId(source + build are fine); pins stay on 0.71.0 / 0.10.1 / 0.2.16.