Skip to content

Migrate API to AI SDK v7 on current main - #1287

Draft
sidneyswift wants to merge 18 commits into
mainfrom
codex/ai-sdk-v7-current-main
Draft

sidneyswift wants to merge 18 commits into
mainfrom
codex/ai-sdk-v7-current-main

Conversation

@sidneyswift

@sidneyswift sidneyswift commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Moves the production API from AI SDK 6 to 7 on current main, preserving server-owned tool context, durable chat history, stream metadata and credit accounting. Historical usage retains flat cache/reasoning counts; OpenAI 4.0.8 fixes the image serialization regression reproduced against 4.0.0.

Review uncovered two pre-existing runtime defects: the abort wrapper hid async generators from the SDK, and fallback model pricing ran outside a durable step. The wrapper now preserves iteration and abort-bounded cleanup. Fallback pricing has its own step with the original calculation unchanged; debit remains a separate existing step.

Validation: full Node 24.18 suite before the scoped repairs passed 10,423 tests (79 skipped). Subsequent repairs passed focused generator/task and pricing tests, actual compiled workflow/pricing fixtures with zero network calls, production and SDK signature types, and lint. All 16 reported checks are green at a50f600 and preview is ready. Native Node 22.23.4 passed 10,437 tests (81 skipped), including the new generator/task tests, all nine compiled pricing cases, workflow checks and types. Independent generator reviews closed both findings; Catalog and Packs independently passed the exact pricing repair.

Draft: paired App reader/replay/cancellation acceptance and Root release approval remain required. Existing Composio/Trigger peer compatibility needs release qualification. No merge, production database apply, manual deployment or real provider/debit operation performed.

Release blocker: source review found Gateway can forward custom and reasoning-file chunks that existing v6 App tabs reject. UI-first does not resolve open old tabs. A reviewed compatibility contract and actual producer/old-new reader oracle are required before API merge or rollout.

Projection integration is wired in source at dfb906d: verified ingress before seeding/fenced updates; fresh-only canonical collection with separate native model history; separate journal receipt plus raw delivery verification; and required message ACK before billing. Compatibility failures preserve observed usage and skip new billing, auto-commit and successful fenced release. No deployment identities are admitted; production evidence verification remains gated.

Validation for this increment:242 focused tests, actual runAgentStep with synthetic Gateway wire, installed SDK6/7 canonical readers, compiled local-World proof and ingress-refusal fixture, actual compiled fenced workflow/pricing boundaries, production/signature types and lint. No real provider or production World operation. Independent exact-head review and full App transport/cursor/deployment/retention qualification remain required. Older all-green native CI evidence above is only for a50f600.

Corrective successor c408619 repairs the two dfb906d CI failures (formatting and strict JSON event typing), preserves genuine Stop accounting and prior known usage, and marks thrown producer outcomes as explicit generation failures without masking the original error if signalling fails. Generation, required projected-message persistence and failure signalling now refuse later WDK attempts before effects when the previous outcome is unknown. This conservative policy also refuses pre-effect retries; it does not establish hosted exactly-once execution or change model SDK internal retries.

Validation for this corrective delta: 168 focused tests pass; strict/non-strict fence types, SDK signatures, formatting and lint pass. Compiled local-runtime controls cover completion lost before storage, ACK lost after storage, and failure before effects, with zero network attempts; the compiled fenced workflow also passes. Native c408 Unit Tests later failed in one outdated streaming fixture (missing attempt metadata and eager rejected promises); 2909b8e repairs that fixture. No continuation/start-envelope change was included in c408. The empty producer admission list, paired App transport/replay contract, deployment identities and retention remain release holds.

Continuation source integration is now frozen at 5bc0b42 (foundation 2909b8e). Exact parser capability is required before admitting assistant reuse; explicit durable protocol, current ownership and bounded configured-World input readback gate every initial/resumed reader and terminal success. Initial readback failure reports an admitted run without cancelling/restarting it. The producer marks only reused canonical assistant bases; opaque observation/provider/tool payloads remain intact while reserved control metadata is rejected. Fenced execution digests bind the requirement; chat preflights allow the capability header. No producer admission or live World qualification is implied.

Validation: 10,580 tests passed/80 skipped with the sandbox-blocked OAuth HTTP listener file excluded; the original full-run failure is retained. Final scoped changes passed 122 focused tests, strict continuation/fence and SDK signature checks, lint/format, and compiled synthetic workflow controls with zero network attempts. An immutable two-case actual SDK/Gateway synthetic producer and SSE fixture is available for paired App testing. Independent exact-head review, successor native CI, complete App send/reconnect pairing, live identities/retention and Root release acceptance remain pending. Draft; no merge or deployment.

Independent-review repairs: ea32054 validates reused-assistant identity, protocol and bounded canonical base after trusted bind/history authority but before any fenced message write/update. Three red cases now reach only bind; 69 workflow tests and 17 compiled synthetic cases pass with zero network attempts. 2ed9207 reports post-start promotion loss as HTTP 409 chat_stream_ownership_lost with admission: admitted and the actual run ID, regardless of the existing single cancellation attempt's result; pre-start conflicts explicitly report not_admitted without a run ID. Its 75 focused tests and type/lint/format checks pass. Paired producer bytes are unchanged. Independent closure, App admission-response pairing, native CI and release acceptance remain pending.

sweetmantech and others added 5 commits November 18, 2026 13:44
Bump to v7: ai 6.0.190 → 7.0.2; @ai-sdk/{anthropic,google,openai} 3 → 4;
@ai-sdk/gateway 3 → 4; @ai-sdk/mcp 1 → 2. (Zod already v4.)

The agent harness survived v7 intact — ToolLoopAgent, the agent loop, and
context passthrough all still exist. This was a rename + typed-context
migration, not a redesign.

Codemod handled the mechanical renames (isToolOrDynamicToolUIPart →
isToolUIPart, experimental_generateImage → generateImage, stepCountIs →
isStepCount, system → instructions, experimental_context → context, etc.).

Manual work, by category:
- Typed tool context (the real v7 change): v7 infers a tool's context as
  `never` unless declared, which broke both `tool()` overloads (TS2769) and
  `toolsContext`. Annotated every context-using tool's execute 2nd arg as
  `ToolExecutionOptions<AgentContext>` (bash/glob/grep/task/webFetch/read/
  write/edit/skill). v7 also split the old single `experimental_context` into
  a per-tool-name `toolsContext` map — added `buildToolsContext()` to fan the
  one AgentContext out to every tool key; wired it into runAgentStep + taskTool.
- Usage token shape: v7 nests details under inputTokenDetails/outputTokenDetails
  and drops top-level reasoningTokens/cachedInputTokens. Fixed
  addLanguageModelUsage (codemod had doubled a path), ZERO_USAGE,
  recordCreditDeduction.
- Provider options: GoogleProviderOptions → GoogleGenerativeAIProviderOptions.
- ToolLoopAgent gained a 4th (runtime-context) generic — updated RoutingDecision
  / ChatConfig agent types to v7 arity.
- Reverted codemod over-applications: local generateText/generateArray `{system}`
  wrappers (pass `instructions: system` inward), toolChain `system`→`instructions`
  on the custom ToolChainItem/PrepareStepResult types, webFetch discriminant
  `as const` + param-default move (v7 tool() inference).
- Test fixtures aligned to v7 (mock exports + usage/UIMessage shapes); no
  weakened assertions.

Verified: source `tsc --noEmit` clean (0 errors), full `pnpm test` green
(3676 passed / 659 files). Pre-existing test-file type-debt in unrelated
domains left untouched. Full build validated on Vercel preview.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
CI on the v7 bump surfaced three failures (code was correct; tooling wasn't):

- lint: `@typescript-eslint/no-explicit-any` on the `ToolLoopAgent` 4th
  (runtime-context) generic in RoutingDecision/ChatConfig → use
  `Record<string, unknown>` (which is v7's `Context` constraint, and the
  source agent's inferred `any` slot is assignable to it).
- format: prettier on two v7-updated test fixtures.
- Vercel build: `Error: dynamic usage of require is not supported` while
  collecting page data for the Workflow step route — `@vercel/oidc` (pulled
  in by `@ai-sdk/gateway@4`) does a dynamic require Turbopack can't bundle.
  Switch the build to `next build --webpack` (which tolerates it), matching
  what chat and marketing already use. Verified locally: webpack compiles the
  Workflow routes; the require error is gone (remaining local failures are
  env-only, present on Vercel).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Webpack got past Turbopack's "dynamic require" refusal, but then the Workflow
step route failed at runtime: bundling `@vercel/oidc/index.js` made its
internal `require('./get-vercel-oidc-token.js')` resolve to a relative path
that doesn't exist on Vercel ("Cannot find module …/get-vercel-oidc-token.js").

Fix: add `@vercel/oidc` to `serverExternalPackages` (+ as a direct dependency
so it's resolvable). Node then loads the package — and its internal require —
natively instead of bundling it. Pairs with the `next build --webpack` switch;
Turbopack refuses to externalize it ("can't be external").

Verified locally (webpack): the Workflow routes compile and collect page data
with no @vercel/oidc error; only env-dependent routes fail locally (env present
on Vercel).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@vercel

vercel Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
api Ready Ready Preview Nov 18, 2026 9:03pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Pre-merge checks: Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Solid & Clean Code Warning The standing FAIL still holds at the current checkout (HEAD 2ed9207, later than the 5bc0b42 it cited). I checked all three cited issues against the code. 1. **Function length (SRP), `lib/agent/conte… 1. Split wrapToolAsyncIterable so each function is 20 lines or fewer. Move close and requestAbortCleanup into files named after the functions they implement. Move advance into its own file. Keep nesting at three levels or less. 2. I…
Full details: Solid & Clean Code

Explanation

The standing FAIL still holds at the current checkout (HEAD 2ed9207, later than the 5bc0b42 it cited). I checked all three cited issues against the code. 1. Function length (SRP), lib/agent/contextManagement/wrapToolAsyncIterable.ts. This file is new in the PR (status A, 71 lines). The returned [Symbol.asyncIterator]() method spans lines 10–69, about 60 lines. It holds the nested helpers close (15–28), requestAbortCleanup (29–33) and advance (34–59). It combines iterator cleanup, abort handling and step forwarding. The check sets a 20-line limit for functions. The file exports one function whose name matches the file name, so that naming rule passes. 2. Function length (SRP), lib/agent/contextManagement/wrapToolsWithAbort.ts. The file is modified by the PR (git diff against merge base 60af564 shows the new import of wrapToolAsyncIterable, the new async-iterable detection branch at lines 34–45, and the raceToolExecution call at line 46). The execute arrow spans lines 29–50, about 22 lines. It is over the 20-line limit and mixes detection, wrapping and racing. 3. DRY, scripts/chat-pricing-durable-compile.mjs (118 lines, A) and scripts/chat-pricing-step-fixture.mjs (143 lines, A). Both files repeat the same setup. This includes createRequire(package.json), createRequire(require.resolve("workflow/next")), the dynamic StandaloneBuilder import, realpath(mkdtemp(...)) temp creation, the node_modules symlink, the tsconfig.json write and the rm cleanup. The checked files show each step at matching lines. No shared harness module exists under scripts/. Passing areas: raceToolExecution.ts (21 lines) is small and single-purpose. The file names match their exported functions. The PR description's test, CI and review claims do not address function length or duplication, so they do not resolve these findings. Not checked: the PR's Gerrit or CodeRabbit comment state, which is not part of this check.

Resolution

  1. Split wrapToolAsyncIterable so each function is 20 lines or fewer. Move close and requestAbortCleanup into files named after the functions they implement. Move advance into its own file. Keep nesting at three levels or less. 2. In wrapToolsWithAbort.ts, move the async-iterable detection into a named helper such as isAsyncIterableResult. Move the wrapping call into a delegating function. Keep the execute arrow under 20 lines. 3. Extract the shared pricing-script setup into one module, such as scripts/pricing-workflow-harness/. The module covers the createRequire wiring, the StandaloneBuilder import, temp directory creation with realpath, the node_modules symlink, the tsconfig.json write and the rm cleanup. Give each assertion or output step its own named function. Make chat-pricing-durable-compile.mjs and chat-pricing-step-fixture.mjs call that harness.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

This branch was successfully deployed

1 active deployment
Preview — 2ed92074 Deployed Nov 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants