Repository navigation
Description
Shortest path to an edge resilience library developers choose
Audit date: 2026-10-11. Source: v1.21.0, commit 8a9eda6. This is the coordinating report for ten implementation opportunities, #108–#117. Scope: source/adapters/utilities, test surfaces and fixtures, scripts, package/TS configuration, public docs, release/CI workflows, tracked internal artifacts, and all nine initially open issues. Vendor/competitor statements use primary docs. Adoption predictions are marked [INFERRED].
Verification: TypeScript --noEmit passes; compilation into a temporary directory passes; nine standalone synthetic probes against compiled source pass and confirm the defects below. No live/billable provider calls. Full Vitest and bundle smoke were attempted but blocked by the existing Linux-oriented node_modules on this Windows host (missing Windows Rollup and esbuild binaries). No suite-pass/coverage/bundle-size claim is made. The pre-existing factory.test.ts working-tree modification was preserved; source evidence links refer to the audited commit.
1. Verdict
The project has substantial functionality but lacks a trustworthy, narrow promise outsiders can validate.
Keep graduated recovery, portable fetch adapters and spend provenance; those support the right product.
The biggest liability is that tenant safety, stream lifecycle and budget admission do not match the resilience/governance pitch.
Fix the trust failures, ship a deterministic failure demo, then integrate with the SDK developers already use.
Positioning: “Fetch-native failover and tenant spend policies for edge apps—embedded in your Worker, with no gateway service to operate.”
Evidence: src/providers/base.ts:192, src/utils/circuit-breaker.ts:105, src/types.ts:249, src/factory.ts:253, src/factory.ts:738, src/factory.ts:1580.
Architecture map before judgment
LLMProviders.generateResponse is a facade → factory cache lookup → catalog/provider plan → exhaustion/breaker/rate-counter prechecks → quota hook → provider-specific request → BaseProvider breaker around retry sequence → fetch/binding → per-adapter envelope validation/normalization → hooks → cost/ledger/quota recording → async cache write.
Boundaries matter:
- The factory owns fallback/model substitution; the adapter owns validation/wire formats and its entire retry sequence. Breaker counts the logical adapter operation, not every failed physical retry. src/index.ts:381, src/factory.ts:411, src/providers/base.ts:196.
- Canonical is currently conversion/introspection, not the execution contract; providers and factory still execute LLMRequest. src/canonical.ts:196, src/factory.ts:407.
- Streaming branches into separate transports, opens a first read, then returns a wrapper. It bypasses adapter breaker/retry execution and records usage only on happy-path drain. src/factory.ts:785, src/factory.ts:1544, src/providers/openai.ts:481.
- State is mixed: metrics are adapter-local; breaker/exhaustion/histogram are module-global; cost tracking is global unless a ledger is attached; ledger is caller-owned memory. src/providers/base.ts:116, src/providers/base.ts:306, src/factory.ts:354.
- Budget pressure affects ranking; it is not an enforced money reservation. src/model-catalog.ts:936, src/factory.ts:1838.
2. Scorecard
Scores are engineering judgments of this revision, not market measurements.
| Area | /10 | Justification / evidence |
|---|---|---|
| Correctness and resilience | 4 | Good primitives, but tenant/cache isolation and streaming lifecycle failures undermine the core promise (src/factory.ts:253, src/factory.ts:738, src/factory.ts:1623). |
| API design and DX | 5 | Useful fromEnv facade; dual request conversion and optional-field detection lose identity (src/index.ts:305, src/canonical.ts:264). |
| Provider freshness | 3 | Runtime allowlists reject modern OpenAI IDs, Claude IDs are undocumented dated constructions, and legacy prices are wrong (src/providers/openai.ts:139, src/providers/anthropic.ts:152, src/providers/cloudflare.ts:324). |
| Performance and bundle | 6 | Zero runtime dependencies and no eager WASM; one export barrel/all-provider registry, eager ranking, and no size baseline (package.json:74, src/factory.ts:366, src/model-catalog.ts:1262, scripts/worker-import-smoke.mjs:6). |
| Testing and reliability engineering | 6 | Real schema/failure and deterministic breaker tests; no Workers execution gate or concurrent/cancel lifecycle matrix (src/tests/circuit-breaker.test.ts:16, src/tests/schema-drift.test.ts:1046, vitest.config.ts:7). |
| Docs and positioning | 4 | 902-line reference-heavy README; quickstart mixes Node and Workers, with no runnable examples in the tracked tree (README.md:40, README.md:800). |
| OSS hygiene and releases | 6 | Pinned actions, OIDC provenance and semver policy are strengths; tracked archives, unresolved sourcemaps and backlog staleness reduce polish (.github/workflows/publish.yml:14, .github/workflows/publish.yml:29, .agent-memory/status.json:2, #94). |
| Ecosystem fit | 3 | Hooks/tool executor/gateway metadata are seams; no AI SDK adapter and plain-text streams cannot carry full tool events (src/types.ts:294, src/types.ts:535, src/index.ts:102). |
3. Hypotheses
| Hypothesis | Result | Evidence / interpretation |
|---|---|---|
| H1: stale OpenAI coverage | CONFIRMED | Five GPT-4/3.5-era IDs only, with strict rejection of others (src/providers/openai.ts:139, src/providers/base.ts:353). Official current model catalog covers newer families. The problem is executable coverage, not only README copy. |
| H2: two shapes should converge | CONFIRMED | Canonical is converted back to legacy; optional-field discrimination loses metadata-only identity (src/canonical.ts:196, src/canonical.ts:264). Use additive explicit entry points now, one execution contract in the major. |
| H3: Workers state adapter differentiates | PARTIAL | Per-isolate limitation is already documented and snapshots exist (README.md:283, src/utils/credit-ledger.ts:523). The missing feature is atomic coordination, not serialization. KV snapshots are unsuitable for enforceable budgets; KV docs explain overwritten concurrent writes. [INFERRED] A first-party durable adapter earns adoption only if real users need app-owned policy. |
| H4: reference manual as landing page | CONFIRMED | Canonical contract appears immediately after quickstart, reference begins at line 800; runtime-specific launch path is absent (README.md:67, README.md:800). The conversion impact is [INFERRED]; verify with novice-user tests. |
| H5: internal artifacts hurt credibility | PARTIAL | Tracked archive/retry and corpus files are objective facts; perceived harm is [INFERRED], confirm through contributor onboarding. Preserve useful charter policy rather than deleting by directory name (.agent-memory/status.json:2, .charter/config.json:2, CONTRIBUTING.md:24). |
| H6: resilience + governance is the moat | PARTIAL | It is the strongest product direction, supported by graduated breaker + ledger (src/utils/circuit-breaker.ts:105, src/utils/credit-ledger.ts:226). It is not unique today: AI Gateway dynamic routing already has fallbacks/budgets. [INFERRED] Win on embedded portable policy, proven behavior and ecosystem fit; validate with users. |
4. Top ten opportunities
Ordered by urgency and attainable impact/effort; larger efforts are split into a small first PR.
| # | Opportunity | Category | Impact | Effort | Risk | Evidence / filed issue |
|---|---|---|---|---|---|---|
| 1 | Tenant-safe complete response-cache identity | Correctness | H | S | Cache misses after key-version bump | src/factory.ts:253 · #108 |
| 2 | Separate tenant denial; add atomic reservations | Governance | H | S first / M–L durable | Accounting semantics | src/factory.ts:738 · #109 |
| 3 | Repair byte streaming, cancellation and terminal accounting | Resilience | H | M | Stream terminal semantics | src/providers/cloudflare.ts:1403 · #110 |
| 4 | Scope state and honor resilience switches | Resilience/DX | H | M | Major default-state migration | src/providers/base.ts:306 · #111 |
| 5 | Verify catalog IDs, prices and custom-model escape hatch | Coverage | H | M | Alias/lifecycle compatibility | src/providers/anthropic.ts:152 · #112 |
| 6 | Canonical identity + one planner for inspection/dispatch | API | H | M | Major convergence | src/canonical.ts:264 · #113 |
| 7 | Failure lab, focused README and public repo cleanup | Product/OSS | H [INFERRED] | M | Low | README.md:40 · #114 |
| 8 | Explicit artifacts/subpaths and measured bundle budgets | Bundle/DX | H | S–M | Module resolution/support floor | package.json:29 · #115 |
| 9 | Fault contracts, deadlines and non-interfering telemetry | Reliability | H | M | Retry/accounting policy | src/factory.ts:605 · #116 |
| 10 | Optional AI SDK adapter + focused provider registration | Ecosystem | H [INFERRED] | M | Peer API/version maintenance | src/types.ts:294 · #117 |
5. Bugs and risks: defects, not preferences
| Severity | Trigger / observed behavior | Fix sketch / evidence |
|---|---|---|
| High, potentially critical in shared caches | Tenant/system changes hit another request's cache entry; verified one-fetch synthetic repro | Versioned complete tenant-scoped key, policy bypass; src/factory.ts:253, #108. |
| High | Tenant quota denial marks provider exhausted for unrelated callers; verified | Local terminal QuotaDeniedError, separate account exhaustion; src/factory.ts:1654, src/factory.ts:738, #109. |
| High | Zero monetary budget still spends; rpm=1 admits two concurrent calls; verified | Atomic reserve/settle, enforce configured scope; src/factory.ts:1838, src/utils/credit-ledger.ts:226, #109. |
| High | Workers AI byte SSE produces empty output; verified synthetic byte fixture | Incremental byte decoder plus workerd/live-shaped contract fixture; src/providers/cloudflare.ts:1413, #110. |
| High | Streaming error/cancel bypasses accounting; wrapper cannot propagate cancel and eagerly drains | Pull-based lifecycle, abort propagation, settle every terminal path; src/factory.ts:1580, src/factory.ts:1623, #110. |
| High | Stream success/failure does not update execution breaker; verified stats | Same streaming admission and terminal reporting; src/providers/openai.ts:495, #110. |
| High | Client breaker “disabled” still runs; other clients share named health; verified | Inject context into adapter + planner; src/providers/base.ts:196, src/providers/base.ts:306, #111. |
| High | Throwing success hook causes another provider call; verified | Isolate telemetry outside provider failure classification, record charge first; src/factory.ts:605, #116. |
| High | Unsupported Claude/Cerebras wire IDs and material underpricing | Source-verified provider-aware catalog; src/providers/anthropic.ts:152, src/providers/cerebras.ts:141, src/providers/cloudflare.ts:324, #112. |
| Medium | Minimal canonical input loses tenant identity; verified | Explicit shape entry points; src/canonical.ts:264, #113. |
| Medium | Schema-error stream branches never resolve usage | Terminal finally resolves usage/completion; src/providers/openai.ts:550, #110. |
| Medium | Body can stall after headers; retries ignore cancellation/deadline | Request-wide abort/deadline; src/providers/base.ts:176, src/utils/retry.ts:89, #116. |
| Medium | Quota/cache persistence can be dropped after Worker response | Await required settlement or expose completion for waitUntil; src/factory.ts:1688, src/factory.ts:676, #109/#116. |
| Medium | KV recipe overwrites concurrent snapshots and can hit per-key write limits | Durable atomic operations; README.md:299, KV constraints, #109. |
Deliberate limits are not defects: no transparent mid-answer fallback; probabilistic recovery is not a single-probe lock; in-memory counters themselves do not lose synchronous increments. Authentication fail-fast is an existing policy with tests, though README's 401 fallback claim is wrong (src/factory.ts:1294, src/tests/factory.test.ts:1031, README.md:554).
6. PR-ready specs for the top three
The implementation issues contain actual TypeScript proposals, acceptance tests, semver/migration impact and README snippets:
- #108: deterministic Web Crypto cache identity, tenant/application namespace and request strategy.
- #109: concrete QuotaDeniedError and QuotaCoordinator reserve/settle contracts; immediate patch separated from durable enforcement.
- #110: concrete ManagedTextStream/StreamCompletion API and pull/cancel/settle wrapper; byte decoder and transport contract tests.
All proposed exports are labeled proposed. They are not descriptions of currently published APIs. Core constraints remain zero runtime deps, fetch-only, Workers-first and Apache-2.0.
7. Roadmap
Now, ≤2 weeks (solo-maintainer realistic):
- Ship fix(cache): isolate tenants and key every response-affecting input #108 and fix(quota): separate tenant denial from provider exhaustion and reserve in-flight spend #109's local-denial fix first.
- Patch fix(streaming): decode Workers AI byte SSE and unify cancellation, breakers, and accounting #110's byte decoding/terminal cleanup in a narrowly tested slice.
- Fix the worst verified IDs/pricing in fix(catalog): verify vendor model IDs and prices and remove fabricated defaults #112; stop advertising uncertain costs/retirement dates.
- Ship a credential-free demo + separate Workers/Node quickstarts from docs(product): ship a failure-injection Worker demo and a focused public README #114.
- Patch hook isolation in test(resilience): add transport fault contracts and make telemetry unable to replay requests #116. Deliver fewer things well if the streaming work takes longer; do not attempt every large item inside two weeks.
Next, v-next minor:
- Add opt-in client-scoped context (fix(resilience): scope state per client and honor breaker and retry policy #111), managed stream completion (fix(streaming): decode Workers AI byte SSE and unify cancellation, breakers, and accounting #110), explicit canonical entry point/shared planner (fix(api): preserve canonical identity and make route planning match dispatch #113).
- Atomic admission interface + durable example (fix(quota): separate tenant denial from provider exhaustion and reserve in-flight spend #109); contract/fault-runtime suite (test(resilience): add transport fault contracts and make telemetry unable to replay requests #116).
- Subpath exports/package matrix and measured bundle baseline (build: ship explicit ESM/CJS artifacts, provider subpaths, and bundle budgets #115).
- First optional AI SDK adapter and Gemini/API-compatible registration slice (feat(interop): add an optional Vercel AI SDK resilience adapter and prioritize provider access #117).
- Resolve chore: sourcemaps in dist/ point to missing src/ — include src/ in npm publish or use inlineSources #94; reconcile feat: add LLMResponse.reasoning field — separate reasoning tokens from message for thinking-model support #95/Add Cloudflare-managed Anthropic Claude Opus 4.8 catalog lane #90 implementations and Clarify AI Gateway response-cache contract and metadata #85's remaining cache metadata. Verify ci: supply-chain workflow fails before creating jobs #77 independently.
Later, next major (batch breaking changes):
- Single canonical execution request/client; remove legacy request aliases and duplicate convenience surface.
- Client-local state default; explicit shared account context.
- Explicit admission/enforced-budget behavior and known/unknown pricing semantics.
- Typed stream events for tools/reasoning/finish/usage; retain a text projection helper.
- Remove already deprecated ImageProvider; retain vision analysis.
- Explicit model provider/endpoint identity and capability requirements; support-floor changes only here.
A enterprise gateway control plane, every provider/auth system, resumable tool streams and full MCP hosting is team-scale. Defer until adoption funds maintenance.
8. Growth and competitive strategy
Feature breadth is not the opening. The shortest path is proving one useful promise in public.
| Alternative | Why it wins today | Plausible opening for this library |
|---|---|---|
| Vercel AI SDK | Integrated generation/tools/UI and established provider contracts | Optional model adapter that adds policy/failover without replacing the application framework |
| LiteLLM | Broad endpoints, routing/cooldowns and distributed usage support | Embedded portable TS Worker path with no Python/server deployment |
| Portkey | Managed configuration and mature gateway fallback behavior | Local programmable policy under application ownership, without another required service |
| OpenRouter | Aggregated provider access/routing and a single access surface | Coordinate direct keys, a Workers AI binding and local/custom endpoints under one application policy |
| Cloudflare AI Gateway | Already provides routing, quotas/fallbacks and platform observability | Complement it with app-owned portable policy and deterministic testing; do not sell its existing features as uniquely yours |
These openings are [INFERRED] adoption hypotheses. Confirm with three external integrations and onboarding tests. The comparison is architectural, not an unsupported latency/cost benchmark.
Killer demo: one Worker, two tenants, three routes, live timeline. Turn primary 503/429 on; watch degradation/fallback/recovery. Run simultaneous requests into a small reservation budget; only the affected tenant stops. Cancel a slow stream and prove upstream stops/partial usage settles. Default fake mode costs nothing; live mode uses verified IDs and optional user keys. Demo/recording acceptance is #114.
README above the fold: outcome sentence → 3 concrete benefits → runtime-specific 15-line quickstart → demo/GIF → “when to use” comparison → honest guarantees → links to reference guides. Markdown docs first; avoid a docs-site maintenance project before traction.
Three launch channels: Cloudflare Developers Discord/forum with deployable Worker; Show HN with deterministic outage demo; AI SDK community/provider directory after adapter works. Publish measured reproducible results, not invented superiority claims.
Five good first issues to split from scoped work: standalone Node quickstart; move API reference into linked guide; fixture provenance manifest; missing public config-type export audit; inline sourcemaps under #94. Keep each bounded to one deliverable and clear acceptance tests.
Provider/API adoption ranking [INFERRED]: modern OpenAI + Responses first; Gemini API-key text second; generic OpenAI-compatible registration/OpenRouter third; then DeepSeek direct/xAI/Mistral/Ollama based on actual requests. Vertex enterprise auth and Cohere follow sponsored demand. Existing #79/#78/#80 remain the provider parents. Rankings are product bets, not measured market share.
Backlog hygiene: #95 reasoning is present (src/types.ts:235, CHANGELOG.md:48); #90 Cloudflare Claude lane exists (src/model-catalog.ts:591). They need maintainer reconciliation/validation, not duplicate implementation. #85 partly shipped; #87 remains the canonical parent; #94 is still applicable. No existing issue was closed or overwritten by this review.
9. Open maintainer decisions
- Are budgets soft routing signals or enforceable tenant spend policies? What happens with unknown prices/partial usage?
- Is state scoped to client, tenant, provider account or an explicitly shared policy domain?
- Is AI SDK interoperability the first external-user path, or are downstream gateway maintainers the primary audience?
- Which current providers/models are exercised by real users, and who can supply sanitized live contract fixtures?
- Should authentication/content-filter/provider-specific invalid requests ever fall back? Which constraints are mandatory across providers?
- What Node minimum/ESM-CJS support is a maintained promise?
- Can archive/corpus artifacts leave the public tree while charter policy remains documented?
- Are already implemented feat: add LLMResponse.reasoning field — separate reasoning tokens from message for thinking-model support #95/Add Cloudflare-managed Anthropic Claude Opus 4.8 catalog lane #90 ready to close after validation? What remains in Clarify AI Gateway response-cache contract and metadata #85/Harden provider contracts for Worker-backed agent routing #87?
- Can you recruit five novice users and three external adopters before expanding breadth?
The central decision: ship verifiable tenant-safe, cancel-safe failover and accounting, then let people adopt it inside their existing SDK. More adapter count alone will not create the obvious choice.
Activity
stackbilt-admin commentedon Oct 13, 2026
Local implementation checkpoint — 2026-10-12
This work is uncommitted/unpushed on
main, based on8a9eda6c058d63f0ec08332f6a408aaf409232cf, and is not merged or released. Keep this issue open pending review/integration. The local handoff isdocs/maintenance/issue-sweep.md; it will travel with the code.Current local checkpoint:
Next order: #112 vendor model IDs/pricing audit; #109 atomic reservations. The remaining non-streaming hook-replay defect in #116 is a valuable smaller intervening task. #117, #77 and new-provider proposals are untouched; #90/#95 were not re-audited for closure.
All code is still local, with package version 1.21.0 unchanged. New public APIs require a minor release when integrated. Preserve the pre-existing line-ending-only factory-test change. The local checkpoint documents exact files and verification commands; no GitHub checkbox/closure should imply the code is shipped.
Validation for the combined local sweep: 605 tests pass across 27 files, TypeScript typecheck passes, Worker-targeted bundle/import smoke passes. Packed entrypoint exports/client methods and all 33 JavaScript sourcemaps were checked on Windows with Node 24.19.0/npm 11.17.0. No live/billable providers or workerd execution; this does not prove minimum Node-version compatibility.
feat: streaming lifecycle, tenant-safe caching, client-scoped resilie…
stackbilt-admin commentedon Oct 15, 2026
Docs sweep update — 2026-10-15
The 2026-10-12 checkpoint comment above described local, unmerged work. That work has now shipped. Release status for this roadmap:
QuotaDeniedError), #110 streaming lifecycle, #111 client-scoped resilience state, #113 canonical normalization and preflight routing, #116 hook isolationModelCatalogEntry.explicitOnly. Fixes JSON mode on Claude 4.6+ and $0 costs for dated OpenAI snapshots.All three were published to npm with provenance from the release workflow.
Opened since: #124. The Anthropic adapter sends
tool_resultblocks withouttool_use_idand drops tool error text, and Claude 5.x thinking blocks are not passed back in tool loops. This is the prerequisite for routing the Claude 5.x models.Next targets per the checkpoint (
docs/maintenance/issue-sweep.md): #124, then #109 atomic spend reservations (needs a design pass). #114, #115 and #117 are not started. The issues stay open for their remaining scope as listed in the checkpoint table.Auto-updated by /docs skill.
stackbilt-admin commentedon Nov 6, 2026
Status update — 2026-11-06
Since the 2026-10-15 update, two more releases shipped. Both were published to npm with provenance from the release workflow.
reasoning.effortmapped per model from Cloudflare docs,reasoningEffortreport,reasoning.strict,ReasoningEffortUnsupportedError(closes #135; first part of #136). Pinned-model integrity:allowFallback: falseandfallbackreports on responses and streams (closes #128); stream completions report the served provider and model (closes #133). AlsolengthCauseandusage.reasoningTokens.nullreasoning fields no longer fail schema validation (closes #130).How this maps to the roadmap
allowFallback: falseorreasoning.strictis set) and actual attempt metadata (fallback.failedAttempts,requestedModel). Canonical execution and capability enforcement across fallbacks remain.allowFallback: falseand the fallback report give Worker-backed routers a way to keep a request on one provider and to detect substitution.LLMResponse.reasoningandusage.reasoningTokensexist. This needs a check against its acceptance criteria before closing.Opened since the last update
tool_use_id, tool error text, Claude 5.x thinking blocks)json_schemamainmainnullreasoning fields in Groq, OpenAI and CerebrasNext targets: #124, then #109's atomic spend reservations, which need a decision first (§9, question 1: soft routing signals or enforced tenant spend caps). #114, #115 and #117 are still not started. The checkpoint in
docs/maintenance/issue-sweep.mdis current as of 1.24.1.stackbilt-admin commentedon Nov 7, 2026
Status update: 1.25.0 (2026-11-06)
1.25.0 (#142, release #143) is published to npm with provenance:
tool_use_id, tool error text, and verbatim replay of tool-use turns (signed thinking,redacted_thinking) via the new optionalproviderContentfield. Closes Anthropic adapter sends tool_result blocks without tool_use_id, so multi-turn tool use fails #124.llmp:v2:tollmp:v3:, so the factory response cache starts cold after upgrading.Next: the remaining #136 needs; then the Claude 5.x routing steps now tracked on #112; then #109 atomic spend reservations (needs a design pass first).
stackbilt-admin commentedon Nov 8, 2026
Status update: 2026-11-08
No release since 1.25.0.
Contributor PRs, re-reviewed against 1.25.0. Both typecheck and pass the suite, the build and the worker import check.
json_schema{ name, schema, strict? }for glm-5.3 and glm-5.3-flash), and the flagged models match Cloudflare's JSON mode list. Waiting on factory tests that use the real Cloudflare adapter. Planned as a minor.Ready to close. These were re-checked against their acceptance criteria:
inlineSources, since 1.22.0).reasoningis onLLMResponseand on the canonical response, and is mapped in the Cloudflare, Groq, OpenAI, Cerebras and Anthropic adapters.anthropic/claude-opus-4.8is inCloudflareProvider.getModels()and in the catalog with a 1M-token context.Unchanged: next targets are the remaining #136 needs, then the Claude 5.x routing steps on #112, then #109 (needs a decision on §9 question 1 first). #114, #115 and #117 have not started. #137 (supply-chain workflow) is still open; #77 is closed.