Skip to content

feat(chat): hand run() a streamText with the managed options already applied - #4884

Open
ericallam wants to merge 9 commits into
fix/chat-agent-accumulatorfrom
feat/chat-bound-streamtext
Open

feat(chat): hand run() a streamText with the managed options already applied#4884
ericallam wants to merge 9 commits into
fix/chat-agent-accumulatorfrom
feat/chat-bound-streamtext

Conversation

@ericallam

@ericallam ericallam commented Sep 3, 2026

Copy link
Copy Markdown
Member

Summary

Every run() had to spread chat.toStreamTextOptions(), and leaving it out dropped six things with no error: the managed prompt and its cache control, the registry-resolved model, the prompt's sampling config, telemetry, the skill tools, and the prepareStep that delivers steering, compaction and injected context.

Before:

import { chat } from "@trigger.dev/sdk/ai";
import { streamText, stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

export const myChat = chat.agent({
  id: "my-chat",
  tools: { myTool },
  run: async ({ messages, tools, signal }) =>
    streamText({
      ...chat.toStreamTextOptions({ registry, tools }),
      model: anthropic("claude-sonnet-4-5"),
      system: "You are a helpful assistant.",
      messages,
      abortSignal: signal,
      stopWhen: stepCountIs(15),
    }),
});

After:

import { chat } from "@trigger.dev/sdk/ai";
import { stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";

export const myChat = chat.agent({
  id: "my-chat",
  system: "You are a helpful assistant.",
  registry,
  tools: { myTool },
  run: async ({ messages, tools, signal, streamText }) =>
    streamText({
      model: anthropic("claude-sonnet-4-5"),
      messages,
      tools,
      abortSignal: signal,
      stopWhen: stepCountIs(15),
    }),
});

streamText comes from run's argument and shadows the one imported from ai, so the correct call is now the shorter one and the managed options cannot be lost by omission. chat.toStreamTextOptions() is unchanged and still supported, and is still the only option in a custom agent.

What changes when your options collide with the managed ones

Spread order decides the outcome today, and losing is silent:

streamText({ ...chat.toStreamTextOptions(), tools: myTools })       // skill tools dropped
streamText({ ...chat.toStreamTextOptions(), prepareStep: mine })    // steering, compaction and injection off

The managed streamText merges instead. tools are passed into the helper so skill tools survive, and a prepareStep you pass runs after the managed one rather than replacing it. Everything else you name is left alone and wins, telemetry included.

system is the exception: it can be set on chat.agent({ system }), through chat.prompt.set(), or at the call site, but only in one of them. Two at once throws and names the one that already owns it. No shape merges two system values across every supported AI SDK version, since v5 rejects an array of blocks and a structured block carries the provider options that make prompt caching work.

chat.headStart and chat.startHeadStart

buildStreamTextOptions supplies messages, stopWhen: stepCountIs(1) and abortSignal. Step 1 belongs to the route handler and step 2 onward to the agent, so re-setting stopWhen after a spread hands over a stream that has already run past step 1.

Before:

import { streamText, stepCountIs } from "ai";

export const POST = chat.headStart({
  agentId: "my-chat",
  run: async ({ chat: helper }) =>
    streamText({
      ...helper.toStreamTextOptions({ tools: headStartTools }),
      model: anthropic("claude-sonnet-4-6"),
      system: "You are a helpful assistant.",
    }),
});

After:

export const POST = chat.headStart({
  agentId: "my-chat",
  run: async ({ streamText }) =>
    streamText({
      model: anthropic("claude-sonnet-4-6"),
      system: "You are a helpful assistant.",
      tools: headStartTools,
    }),
});

Passing messages, prompt, stopWhen or abortSignal to that streamText is a type error, with a runtime throw behind it for JavaScript callers. tools is yours to pass. The old shape only warned in prose.

Also in here

  • chat.agent() takes system, registry, cacheControl and systemProviderOptions, so a managed prompt's model and its cache breakpoint no longer have to be passed at the call site.
  • ChatStreamText is exported for typing a loop factored out of run.

The signature is taken from the AI SDK's own declaration:

import type { streamText as aiStreamTextSignature } from "ai";
type AiStreamTextFn = typeof aiStreamTextSignature;

The peer range spans ai v5, v6 and v7, whose options differ. typeof resolves to whichever version is installed, so generics and tool inference are the caller's own and a v8 option needs no change here.

Actions. onAction no longer receives streamText or tools: an action is a state edit, and one that returns chat.turn() (added in #4816) is followed by run(), which already has both. The action docs on this branch describe that model. chat.toStreamTextOptions() now also applies chat.agent's system, registry, cacheControl and systemProviderOptions, so the spread form is equivalent to the streamText handed to run(), as the docs say; previously an agent's system prompt was silently dropped on that path. Those options are published on every boot, including for a hydrateMessages agent, which skips the snapshot boot block where they were first set.

Verification

Typecheck and the full suite pass on both ai@6.0.116 and ai@7.0.66. The option merge is a pure function so the merged object can be asserted directly, which is how experimental_telemetry being dropped was caught: most streamText options never reach the provider, so a test that observes the model cannot see them.

Run end to end against a deployed agent with every run rewritten to the new form and no spread anywhere: steering, undo across a cold boot, and regenerate all still pass, a caller's own prepareStep runs while managed steering still fires inside the turn, and consecutive injections arrive one per turn. The handover-owned options are pinned by @ts-expect-error assertions in a typechecked test rather than only by the runtime throw.

@changeset-bot

changeset-bot Bot commented Sep 3, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: bf66457

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 27 packages
Name Type
@trigger.dev/sdk Minor
@trigger.dev/python Minor
@internal/dashboard-agent Patch
@trigger.dev/build Minor
trigger.dev Minor
@trigger.dev/core Minor
@trigger.dev/react-hooks Minor
@trigger.dev/redis-worker Minor
@trigger.dev/rsc Minor
@trigger.dev/schema-to-json Minor
@trigger.dev/database Minor
@trigger.dev/otlp-importer Minor
@trigger.dev/rbac Minor
@trigger.dev/sso Minor
@internal/clickhouse Patch
@internal/llm-model-catalog Patch
@internal/metrics-pipeline Patch
@internal/redis Patch
@internal/replication Patch
@internal/run-engine Patch
@internal/run-store Patch
@internal/schedule-engine Patch
@internal/tracing Patch
@internal/webhook-engine Patch
@internal/webhook-sources Patch
@internal/testcontainers Patch
@internal/cache Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 21cafab4-8308-4db2-99e4-a01b82b24a31

📥 Commits

Reviewing files that changed from the base of the PR and between c9336c5 and bf66457.

📒 Files selected for processing (1)
  • .changeset/managed-streamtext-in-run.md

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

📜 Recent review details
⏰ Context from checks skipped due to timeout. (48)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (20, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (24, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (19, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (22, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (18, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (17, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (16, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (13, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (14, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (21, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (15, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (23, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 24)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 24)
  • GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Bun Runtime
  • GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Node.js 22.23 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Node.js 20.20 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
  • GitHub Check: sdk-compat / Deno Runtime
  • GitHub Check: sdk-compat / Cloudflare Workers
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - pnpm)
  • GitHub Check: internal / 🧪 Unit Tests: Internal
  • GitHub Check: fk-cascade-guard / fk-cascade-guard
  • GitHub Check: runops-guard / runops-guard
  • GitHub Check: typecheck / typecheck
  • GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp (1, 2)
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp (2, 2)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
  • GitHub Check: code-quality / code-quality
  • GitHub Check: audit
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Build and publish previews
🧰 Additional context used
🪛 LanguageTool
.changeset/managed-streamtext-in-run.md

[style] ~5-~5: To strengthen your wording, consider replacing the phrasal verb “leave out”.
Context: ...eady applied, so they cannot be lost by leaving out the spread: ```ts run: async ({ messag...

(OMIT_EXCLUDE)


[style] ~12-~12: ‘by accident’ might be wordy. Consider a shorter alternative.
Context: ...instead, so neither can be turned off by accident. system` can be set at the call site,...

(EN_WORDINESS_PREMIUM_BY_ACCIDENT)


[style] ~14-~14: To form a complete sentence, be sure to include a subject.
Context: ...an be turned off by accident. system can be set at the call site, on `chat.agent...

(MISSING_IT_THERE)


[grammar] ~18-~18: Ensure spelling is correct
Context: ...at.headStartandchat.startHeadStarthand theirrun` the same thing, carrying the options th...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)

🔇 Additional comments (1)
.changeset/managed-streamtext-in-run.md (1)

1-18: LGTM!


Walkthrough

The SDK now supplies managed streamText functions to agent runs and action handlers. These functions preserve prompts, tools, telemetry, registry settings, caching options, and prepareStep behavior. Head Start handlers receive bound functions that own handover options. Runtime exports, public types, tests, release notes, and chat-agent documentation were updated.

Merge Risk: 🟡 Moderate · up to bf664

The managed streamText behavior is documented more broadly, but several published examples remain inaccurate. Most can cause incorrect integration behavior; the backend example may encourage exposing another user’s data to a model provider without server-side authorization.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 6 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: providing run() with streamText that already includes managed options.
Description check ✅ Passed The description gives a detailed summary, migration examples, behavior changes, and verification results. It does not include the template's explicit issue reference, checklist, or screenshots section…
Full details: Docstring Coverage

Explanation

Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 6 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/chat-bound-streamtext

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

Comment @coderabbitai help to get the list of available commands.

@ericallam
ericallam force-pushed the feat/chat-bound-streamtext branch from 4984f70 to f36bb10 Compare September 3, 2026 16:58
@pkg-pr-new

pkg-pr-new Bot commented Sep 3, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

npm i https://pkg.pr.new/@trigger.dev/build@bf66457

trigger.dev

npm i https://pkg.pr.new/trigger.dev@bf66457

@trigger.dev/core

npm i https://pkg.pr.new/@trigger.dev/core@bf66457

@trigger.dev/python

npm i https://pkg.pr.new/@trigger.dev/python@bf66457

@trigger.dev/react-hooks

npm i https://pkg.pr.new/@trigger.dev/react-hooks@bf66457

@trigger.dev/redis-worker

npm i https://pkg.pr.new/@trigger.dev/redis-worker@bf66457

@trigger.dev/rsc

npm i https://pkg.pr.new/@trigger.dev/rsc@bf66457

@trigger.dev/schema-to-json

npm i https://pkg.pr.new/@trigger.dev/schema-to-json@bf66457

@trigger.dev/sdk

npm i https://pkg.pr.new/@trigger.dev/sdk@bf66457

commit: bf66457

@ericallam

Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot]

This comment was marked as resolved.

@ericallam
ericallam marked this pull request as ready for review September 3, 2026 21:47
devin-ai-integration[bot]

This comment was marked as resolved.

@ericallam
ericallam force-pushed the feat/chat-bound-streamtext branch from f36bb10 to 57bb078 Compare September 4, 2026 08:46
devin-ai-integration[bot]

This comment was marked as resolved.

@ericallam
ericallam force-pushed the feat/chat-bound-streamtext branch from 1a1da14 to 45bafb0 Compare September 4, 2026 09:08
devin-ai-integration[bot]

This comment was marked as resolved.

@ericallam
ericallam force-pushed the feat/chat-bound-streamtext branch 3 times, most recently from fa5e2a8 to e6709a8 Compare September 4, 2026 13:18
ericallam added a commit that referenced this pull request Sep 4, 2026
The bound streamText on the run and onAction arguments is #4884's, so
on this branch alone the test neither typechecked nor ran.
@ericallam
ericallam force-pushed the feat/chat-bound-streamtext branch 6 times, most recently from 06919ac to 0e34286 Compare September 4, 2026 18:39
devin-ai-integration[bot]

This comment was marked as resolved.

@ericallam
ericallam force-pushed the feat/chat-bound-streamtext branch from 0e34286 to 3203120 Compare September 4, 2026 22:48
ericallam added a commit that referenced this pull request Sep 5, 2026
The edit an action makes is snapshotted before the turn chat.turn()
requests begins, so a turn that is cancelled or runs out of memory
continues from the edited history rather than from the snapshot the edit
replaced. The turn's run() payload carries trigger "action-turn", not
"action", so a handler that returns early on the action trigger still
answers. An action sent through useChat keeps the request's metadata.

Also moves the action-turn test onto this branch's own surface; it had
used the bound streamText and chat.agent({ system }) from #4884.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AxuSksX18bj1yhnLpkcQ6a
@ericallam
ericallam force-pushed the feat/chat-bound-streamtext branch from 3203120 to b1fdca8 Compare September 5, 2026 05:06
devin-ai-integration[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

@ericallam
ericallam force-pushed the feat/chat-bound-streamtext branch from b1fdca8 to 871f86c Compare September 5, 2026 05:17
coderabbitai[bot]

This comment was marked as resolved.

ericallam and others added 9 commits September 5, 2026 07:23
Spreading chat.toStreamTextOptions() is the integration point for six things:
the managed prompt and its cache control, the resolved model, the prompt's
sampling config, telemetry, the skill tools, and the prepareStep that delivers
steering, compaction and injected context. Forgetting the spread drops all six
in silence, and spread order decides whether passing your own tools or
prepareStep clobbers the managed ones.

run() now receives a streamText with those options applied, so the managed
state cannot be lost by omission and the merge happens inside rather than at
the call site: tools go into the helper so skills survive, a caller system
becomes the base the prompt and injections append to, and a caller prepareStep
composes after the managed one instead of replacing it.

The signature is borrowed with typeof import("ai").streamText rather than
restated, so it resolves to whichever of ai v5/v6/v7 the user installed. The
runtime value rides the existing ESM/CJS shim that already isolates value
imports from ai.

PROTOTYPE. Typechecks and passes the suite on ai@6.0.116 and ai@7.0.66, but
adds a public registry option, does not settle what happens when caller and
managed system are both structured, and has no test for the composed
prepareStep.
An onAction handler has no tools in scope the way run() does, so a
regenerated answer built with the bound streamText could call nothing.
Omitting tools now falls back to chat.agent({ tools }); naming tools
still replaces the set for that call. onAction also receives tools.
chat.agent({ system, registry, cacheControl, systemProviderOptions })
reached only the bound streamText; the documented spread form ran without
them. The options are published for the run and toStreamTextOptions
defaults from them, caller options winning.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AxuSksX18bj1yhnLpkcQ6a
An action no longer calls the model itself; one that returns chat.turn()
is followed by run(), which already receives the bound streamText and the
agent's tools.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AxuSksX18bj1yhnLpkcQ6a
onAction returns nothing or chat.turn(); the section on returning a
response from an action is replaced, the frontend sends actions through
useChat, and the reference drops the onAction streamText argument.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AxuSksX18bj1yhnLpkcQ6a
…align the Head Start docs

chat.toStreamTextOptions() read the agent-level system, registry, cacheControl
and systemProviderOptions from a key set only inside the snapshot boot block,
which a hydrateMessages agent skips, so the spread form dropped them there.
The key is set on every boot now, with a test for the hydrateMessages case.

Docs: the actions gating example returns chat.turn() instead of a streamText
call onAction no longer receives; the extracted-loop examples import
ChatStreamText, stepCountIs and ModelMessage; the Head Start pages and the
chat-server docstrings list prompt among the owned options and describe
tools as caller-supplied.
…ool statements

The actions lifecycle flow only covered the edit-only path; it now says what
happens when onAction returns chat.turn(). The Head Start step said the bound
streamText already carried the caller's tools, and the migration example kept
a spread comment for a call with no spread.
@ericallam
ericallam force-pushed the feat/chat-bound-streamtext branch from c9336c5 to bf66457 Compare September 5, 2026 06:23
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