Skip to content
Source
Sign inSign up
TanStack/ai

feat(ai-orchestration): generator-based workflows + orchestrators #542

ClosedAlemTuzlakwants to merge 82 commits intomain fromworktree-cryptic-singing-wadleropened View on GitHub

AlemTuzlakcommented

Summary

  • New @tanstack/ai-orchestration package: define agents, workflows, and orchestrators using async generators. yield* agents.x(...) for typed agent calls, yield* approve(...) for pause/resume on user decision, plain JS for everything else (if, for, await, Promise.all).
  • defineOrchestrator is sugar over defineWorkflow (same runtime, different vocabulary). defineRouter(config, fn) lets users extract the orchestrator router as a named function with full type inference.
  • All workflow lifecycle is emitted as native AG-UI events (RunStarted, StepStarted/Finished, StateSnapshot, StateDelta via JSON Patch RFC 6902, RunFinished carrying typed output, RunError). Approvals reuse the existing approval-requested custom event.
  • WorkflowClient added to @tanstack/ai-client (mirrors ChatClient's connection-adapter pattern), useWorkflow / useOrchestration hooks added to @tanstack/ai-react.
  • Server-side parseWorkflowRequest(request) extractor; consumers use runWorkflow({ workflow, runStore, ...params }) + toServerSentEventsResponse(stream) — symmetric with how chat() is called.
  • Pluggable RunStore interface with default inMemoryRunStore (1h TTL).
  • Two demo pages on ts-react-chat: /workflow (article writing pipeline with writer → legal → skeptic → editor → approve/revise loop, dramatic fullscreen ArticleModal on publish) and /orchestration (Claude Code-style spec → approve → implement [nested workflow] → review).
  • Editorial-brutalist UI: Fraunces variable serif + JetBrains Mono, warm ink/cream palette with citron accent, paper-grain textures, hazard-tape approval bands, live DraftPreview rendering the article-in-progress as the editor mutates state.

Architecture decisions captured during design

  • Workflow body is an async generator (function*), not a node-array DSL — preserves "feels like JavaScript".
  • State lives in a declared schema, mutated as a plain object inside the generator; engine snapshots between yields and emits JSON Patches.
  • succeed({...}) / fail(reason) helpers replace as const discriminator casts at return sites.
  • v1 runStore is in-memory only; engine uses live generator handles (no replay) for resume. Pluggable interface in place for future durable stores.

Out of scope (post-prototype)

  • Comprehensive test suite (3 engine smoke tests included; full coverage deferred per the prototype-first direction)
  • Full API docs
  • Streaming structured output integration (waits on a separate in-flight chat() PR)
  • Abort signal plumbing through API routes (engine supports it; route handlers no-op for now)
  • parallel / loop / step / ask primitives
  • Dedicated devtools workflow panel (events render in the existing iteration timeline)

Test plan

  • `pnpm --filter @tanstack/ai-orchestration test:lib` — 3 smoke tests pass
  • `pnpm --filter @tanstack/ai-orchestration build` — builds clean
  • `pnpm --filter @tanstack/ai-orchestration test:types` — clean
  • `pnpm --filter @tanstack/ai-orchestration test:eslint` — clean
  • `pnpm --filter @tanstack/ai-client test:types` and `@tanstack/ai-react test:types` — clean
  • In the example app (`pnpm --filter ts-react-chat dev`):
    • Open `/workflow`, click Run with default topic — writer → legal → skeptic → editor steps stream live in the timeline rail; `DraftPreview` populates and refreshes
    • Approve the published-article approval card → modal opens with the full typeset article (esc / backdrop closes it)
    • Click Revise with feedback in the textarea → editor re-runs (visible in timeline + DraftPreview), approval prompts again
    • Open `/orchestration`, click Run — triage routes through spec → await-approval → implementation sub-workflow (nested steps appear under their parent) → review
    • Verify `State Snapshot` paper card on the right reflects `STATE_DELTA` updates as the workflow progresses

Summary by CodeRabbit

Release Notes

  • New Features

    • Added @tanstack/ai-orchestration for multi-step LLM workflows with typed agents and router-based orchestration
    • Added useWorkflow and useOrchestration React hooks for client-side workflow management
    • Added human approval/feedback loops, run persistence, and refinement capabilities
    • Added article workflow and feature orchestration examples in demo app with terminal UI
  • Documentation

    • Comprehensive guides for workflows, orchestrators, approvals, and run persistence
    • Added API reference and integration examples
  • Tests

    • Full test coverage for orchestration engine, run store, and client behavior
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      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
      ℹ️ Recent review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: 5f05beda-d3c3-4eba-845c-1eda8e3eedf6

      📥 Commits

      Reviewing files that changed from the base of the PR and between d5645cfd4d1b9cfc877f7d4d714517e166a99ce3 and 9de8cfa591236d225f425226d819e8fda99ea53e.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (91)
      • .agent/self-learning/coupling.json
      • docs/api/ai-orchestration.md
      • docs/chat/agentic-cycle.md
      • docs/config.json
      • docs/getting-started/overview.md
      • docs/getting-started/workflows.md
      • docs/orchestration/approvals.md
      • docs/orchestration/orchestrators.md
      • docs/orchestration/overview.md
      • docs/orchestration/refining-across-runs.md
      • docs/orchestration/retries-and-errors.md
      • docs/orchestration/run-persistence.md
      • docs/orchestration/workflows.md
      • docs/structured-outputs/multi-turn.md
      • docs/tools/tools.md
      • examples/ts-react-chat/package.json
      • examples/ts-react-chat/src/components/ArticleModal.tsx
      • examples/ts-react-chat/src/components/CodeBlock.tsx
      • examples/ts-react-chat/src/components/DraftPreview.tsx
      • examples/ts-react-chat/src/components/FileTreePanel.tsx
      • examples/ts-react-chat/src/components/Header.tsx
      • examples/ts-react-chat/src/components/StateInspector.tsx
      • examples/ts-react-chat/src/components/WorkflowTimeline.tsx
      • examples/ts-react-chat/src/lib/diff-extract.ts
      • examples/ts-react-chat/src/lib/shiki/highlighter.ts
      • examples/ts-react-chat/src/lib/shiki/theme.ts
      • examples/ts-react-chat/src/lib/workflows/article-workflow.test.ts
      • examples/ts-react-chat/src/lib/workflows/article-workflow.ts
      • examples/ts-react-chat/src/lib/workflows/orchestrator.ts
      • examples/ts-react-chat/src/routeTree.gen.ts
      • examples/ts-react-chat/src/routes/api.orchestration.ts
      • examples/ts-react-chat/src/routes/api.workflow.ts
      • examples/ts-react-chat/src/routes/orchestration.tsx
      • examples/ts-react-chat/src/routes/workflow.tsx
      • examples/ts-react-chat/src/styles.css
      • knip.json
      • packages/ai-client/src/connection-adapters.ts
      • packages/ai-client/src/index.ts
      • packages/ai-client/src/workflow-client.ts
      • packages/ai-client/tests/workflow-client.test.ts
      • packages/ai-orchestration/README.md
      • packages/ai-orchestration/eslint.config.js
      • packages/ai-orchestration/package.json
      • packages/ai-orchestration/skills/ai-orchestration/SKILL.md
      • packages/ai-orchestration/src/define/define-agent.ts
      • packages/ai-orchestration/src/define/define-orchestrator.ts
      • packages/ai-orchestration/src/define/define-router.ts
      • packages/ai-orchestration/src/define/define-workflow.ts
      • packages/ai-orchestration/src/engine/emit-events.ts
      • packages/ai-orchestration/src/engine/invoke-agent.ts
      • packages/ai-orchestration/src/engine/run-workflow.ts
      • packages/ai-orchestration/src/index.ts
      • packages/ai-orchestration/src/primitives/approve.ts
      • packages/ai-orchestration/src/primitives/bind-agents.ts
      • packages/ai-orchestration/src/primitives/now.ts
      • packages/ai-orchestration/src/primitives/patched.ts
      • packages/ai-orchestration/src/primitives/retry.ts
      • packages/ai-orchestration/src/primitives/sleep.ts
      • packages/ai-orchestration/src/primitives/step.ts
      • packages/ai-orchestration/src/primitives/uuid.ts
      • packages/ai-orchestration/src/primitives/wait-for-signal.ts
      • packages/ai-orchestration/src/registry/select-version.ts
      • packages/ai-orchestration/src/result.ts
      • packages/ai-orchestration/src/run-store/compat-events.ts
      • packages/ai-orchestration/src/run-store/in-memory.ts
      • packages/ai-orchestration/src/server/index.ts
      • packages/ai-orchestration/src/server/parse-request.ts
      • packages/ai-orchestration/src/types.ts
      • packages/ai-orchestration/tests/engine.attach.test.ts
      • packages/ai-orchestration/tests/engine.cas.test.ts
      • packages/ai-orchestration/tests/engine.durability.test.ts
      • packages/ai-orchestration/tests/engine.idempotency.test.ts
      • packages/ai-orchestration/tests/engine.patched.test.ts
      • packages/ai-orchestration/tests/engine.primitives.test.ts
      • packages/ai-orchestration/tests/engine.publisher.test.ts
      • packages/ai-orchestration/tests/engine.retry.test.ts
      • packages/ai-orchestration/tests/engine.signals.test.ts
      • packages/ai-orchestration/tests/engine.smoke.test.ts
      • packages/ai-orchestration/tests/engine.timeout.test.ts
      • packages/ai-orchestration/tests/in-memory-store.test.ts
      • packages/ai-orchestration/tests/parse-request.test.ts
      • packages/ai-orchestration/tests/registry.test.ts
      • packages/ai-orchestration/tests/test-utils.ts
      • packages/ai-orchestration/tests/workflow-core-delegation.test.ts
      • packages/ai-orchestration/tsconfig.json
      • packages/ai-orchestration/vite.config.ts
      • packages/ai-react/package.json
      • packages/ai-react/src/index.ts
      • packages/ai-react/src/use-workflow.ts
      • packages/ai-react/tests/use-workflow-schema-inference.test.ts
      • packages/ai/skills/ai-core/SKILL.md

      📝 Walkthrough

      Walkthrough

      Adds a full orchestration stack for generator-based workflows and orchestrators, with new engine primitives, streaming client support, example workflow pages, docs, and tests.

      Changes

      AI Orchestration Stack

      Layer / File(s)Summary
      Types, factories, and primitives
      packages/ai-orchestration/src/types.ts, packages/ai-orchestration/src/define/*, packages/ai-orchestration/src/primitives/*, packages/ai-orchestration/src/registry/select-version.ts, packages/ai-orchestration/src/result.ts
      Public workflow/orchestration types, definition helpers, primitives, registry selection, and result helpers are added.
      Engine execution and persistence
      packages/ai-orchestration/src/engine/*, packages/ai-orchestration/src/run-store/*, packages/ai-orchestration/src/server/*
      Event emission, agent invocation, workflow execution, step-record conversion, in-memory storage, and request parsing exports are added.
      Client adapters and workflow state
      packages/ai-client/src/*, packages/ai-react/src/*
      Workflow event transport, workflow client state management, and React hook wrappers are added and re-exported.
      Example app workflows, routes, and UI
      examples/ts-react-chat/src/*
      Article and feature-orchestrator workflows, route pages, shared UI components, syntax highlighting, styling, and route registration are added.
      Docs, skills, and navigation
      docs/*, packages/ai-orchestration/skills/*, packages/ai/skills/*, .agent/self-learning/coupling.json, knip.json
      API and getting-started docs, orchestration guides, skill docs, navigation, and related config are expanded.
      Tests and verification
      packages/ai-orchestration/tests/*, packages/ai-client/tests/*, packages/ai-react/tests/*, examples/ts-react-chat/src/lib/workflows/article-workflow.test.ts
      Engine, client, registry, and example workflow tests are added for execution, persistence, and hook behavior.

      AI Orchestration Stack

      Layer / File(s)Summary
      Types, factories, and primitives
      packages/ai-orchestration/src/types.ts, packages/ai-orchestration/src/define/*, packages/ai-orchestration/src/primitives/*, packages/ai-orchestration/src/registry/select-version.ts, packages/ai-orchestration/src/result.ts
      Public workflow/orchestration types, definition helpers, primitives, registry selection, and result helpers are added.
      Engine execution and persistence
      packages/ai-orchestration/src/engine/*, packages/ai-orchestration/src/run-store/*, packages/ai-orchestration/src/server/*
      Event emission, agent invocation, workflow execution, step-record conversion, in-memory storage, and request parsing exports are added.
      Client adapters and workflow state
      packages/ai-client/src/*, packages/ai-react/src/*
      Workflow event transport, workflow client state management, and React hook wrappers are added and re-exported.
      Example app workflows, routes, and UI
      examples/ts-react-chat/src/*
      Article and feature-orchestrator workflows, route pages, shared UI components, syntax highlighting, styling, and route registration are added.
      Docs, skills, and navigation
      docs/*, packages/ai-orchestration/skills/*, packages/ai/skills/*, .agent/self-learning/coupling.json, knip.json
      API and getting-started docs, orchestration guides, skill docs, navigation, and related config are expanded.
      Tests and verification
      packages/ai-orchestration/tests/*, packages/ai-client/tests/*, packages/ai-react/tests/*, examples/ts-react-chat/src/lib/workflows/article-workflow.test.ts
      Engine, client, registry, and example workflow tests are added for execution, persistence, and hook behavior.

      Sequence Diagram(s)

      sequenceDiagram
        participant Browser
        participant useWorkflow
        participant fetchWorkflowEvents
        participant Route as /api/workflow
        participant runWorkflow
        participant inMemoryRunStore
        participant ArticleWorkflow
        Browser->>useWorkflow: start(input)
        useWorkflow->>fetchWorkflowEvents: connect POST /api/workflow
        fetchWorkflowEvents->>Route as /api/workflow: send request body
        Route as /api/workflow->>runWorkflow: run articleWorkflow
        runWorkflow->>inMemoryRunStore: read/write run state and steps
        runWorkflow->>ArticleWorkflow: execute generator steps
        runWorkflow-->>fetchWorkflowEvents: SSE stream events
        fetchWorkflowEvents-->>useWorkflow: parsed events
        useWorkflow-->>Browser: updated workflow state

      Estimated code review effort

      🎯 5 (Critical) | ⏱️ ~120 minutes

      • TanStack/workflow#12 — The PR adds durable workflow primitives, run persistence, attach/resume behavior, signal and approval handling, and workflow client/runtime pieces that match the stated workflow durability and adapter goals.

      Suggested reviewers

      • tombeckenham

      Poem

      🐇 I hop through runs and steps so bright, Streams and patches dance in flight. Approvals ping, then routes unwind, Orchestrations bloom with easter-egg mind. Hop hop — the workflow moon is right!

      ✨ Finishing Touches
      📝 Generate docstrings
      • Create stacked PR
      • Commit on current branch
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `worktree-cryptic-singing-wadler`
    2. github-actions[bot](GitHub profile, opens in a new tab)commented

      🚀 Changeset Version Preview

      7 package(s) bumped directly, 24 bumped as dependents.

      🟥 Major bumps

      PackageVersionReason
      @tanstack/ai-preact0.6.35 → 1.0.0Changeset
      @tanstack/ai-react0.12.1 → 1.0.0Changeset
      @tanstack/ai-solid0.10.10 → 1.0.0Changeset
      @tanstack/ai-svelte0.10.10 → 1.0.0Changeset
      @tanstack/ai-vue0.10.11 → 1.0.0Changeset
      @tanstack/ai-anthropic0.11.0 → 1.0.0Dependent
      @tanstack/ai-code-mode0.1.22 → 1.0.0Dependent
      @tanstack/ai-code-mode-skills0.1.22 → 1.0.0Dependent
      @tanstack/ai-elevenlabs0.2.13 → 1.0.0Dependent
      @tanstack/ai-event-client0.4.0 → 1.0.0Dependent
      @tanstack/ai-fal0.7.15 → 1.0.0Dependent
      @tanstack/ai-gemini0.12.0 → 1.0.0Dependent
      @tanstack/ai-grok0.9.0 → 1.0.0Dependent
      @tanstack/ai-groq0.2.7 → 1.0.0Dependent
      @tanstack/ai-isolate-node0.1.22 → 1.0.0Dependent
      @tanstack/ai-isolate-quickjs0.1.22 → 1.0.0Dependent
      @tanstack/ai-ollama0.6.22 → 1.0.0Dependent
      @tanstack/ai-openai0.10.3 → 1.0.0Dependent
      @tanstack/ai-openrouter0.9.8 → 1.0.0Dependent
      @tanstack/ai-orchestration0.0.1 → 1.0.0Dependent
      @tanstack/ai-react-ui0.8.3 → 1.0.0Dependent
      @tanstack/ai-solid-ui0.7.3 → 1.0.0Dependent
      @tanstack/openai-base0.4.0 → 1.0.0Dependent

      🟨 Minor bumps

      PackageVersionReason
      @tanstack/ai0.22.1 → 0.23.0Changeset
      @tanstack/ai-client0.13.0 → 0.14.0Changeset

      🟩 Patch bumps

      PackageVersionReason
      @tanstack/ai-devtools-core0.4.0 → 0.4.1Dependent
      @tanstack/ai-isolate-cloudflare0.2.13 → 0.2.14Dependent
      @tanstack/ai-vue-ui0.2.6 → 0.2.7Dependent
      @tanstack/preact-ai-devtools0.1.43 → 0.1.44Dependent
      @tanstack/react-ai-devtools0.2.43 → 0.2.44Dependent
      @tanstack/solid-ai-devtools0.2.43 → 0.2.44Dependent
    3. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 9de8cfa591236d225f425226d819e8fda99ea53e

      CommandStatusDurationResult
      nx run-many --targets=build --exclude=examples/...✅ Succeeded1m 12sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-05-28 19:01:45 UTC

    4. pkg-pr-new[bot](GitHub profile, opens in a new tab)commented

      Open in StackBlitz

      @tanstack/ai

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai@542

      @tanstack/ai-anthropic

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-anthropic@542

      @tanstack/ai-client

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-client@542

      @tanstack/ai-code-mode

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode@542

      @tanstack/ai-code-mode-skills

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-code-mode-skills@542

      @tanstack/ai-devtools-core

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-devtools-core@542

      @tanstack/ai-elevenlabs

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-elevenlabs@542

      @tanstack/ai-event-client

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-event-client@542

      @tanstack/ai-fal

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-fal@542

      @tanstack/ai-gemini

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-gemini@542

      @tanstack/ai-grok

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-grok@542

      @tanstack/ai-groq

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-groq@542

      @tanstack/ai-isolate-cloudflare

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-cloudflare@542

      @tanstack/ai-isolate-node

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-node@542

      @tanstack/ai-isolate-quickjs

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-isolate-quickjs@542

      @tanstack/ai-ollama

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-ollama@542

      @tanstack/ai-openai

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openai@542

      @tanstack/ai-openrouter

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-openrouter@542

      @tanstack/ai-orchestration

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-orchestration@542

      @tanstack/ai-preact

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-preact@542

      @tanstack/ai-react

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react@542

      @tanstack/ai-react-ui

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-react-ui@542

      @tanstack/ai-solid

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid@542

      @tanstack/ai-solid-ui

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-solid-ui@542

      @tanstack/ai-svelte

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-svelte@542

      @tanstack/ai-utils

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-utils@542

      @tanstack/ai-vue

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue@542

      @tanstack/ai-vue-ui

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/ai-vue-ui@542

      @tanstack/openai-base

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/openai-base@542

      @tanstack/preact-ai-devtools

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/preact-ai-devtools@542

      @tanstack/react-ai-devtools

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/react-ai-devtools@542

      @tanstack/solid-ai-devtools

      npm i https://pkg.pr.new/TanStack/ai/@tanstack/solid-ai-devtools@542

      commit: 9de8cfa

    5. Actionable comments posted: 15

      🧹 Nitpick comments (14)
      examples/ts-react-chat/src/components/DraftPreview.tsx (1)

      55-58: ⚡ Quick win

      Avoid remounting the preview container on every update.

      Using key={bumpKey} remounts the scrollable panel each time content changes, which can reset scroll position/focus during streaming updates.

      Suggested direction
      -        <div
      -          key={bumpKey}
      -          className="relative px-6 py-7 max-h-[34rem] overflow-auto anim-log-in"
      -        >
      +        <div
      +          className="relative px-6 py-7 max-h-[34rem] overflow-auto anim-log-in"
      +          data-bump={bumpKey}
      +        >

      Then trigger pulse via CSS/animation based on data-bump (or a short-lived isPulsing class), without remounting the node.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@examples/ts-react-chat/src/components/DraftPreview.tsx` around lines 55 - 58,
      The preview container in DraftPreview currently uses key={bumpKey} which forces
      a remount and resets scroll/focus; remove the dynamic key and instead add a
      stable root element (the existing div with className "relative px-6 py-7...")
      and toggle a data attribute or short-lived CSS class (e.g. data-bump={bumpKey}
      or isPulsing) on that same div to trigger the pulse animation via CSS/animation,
      ensuring you update where bumpKey is produced so it sets the attribute/class
      rather than the key.
      examples/ts-react-chat/src/components/ArticleModal.tsx (1)

      10-21: ⚡ Quick win

      Refine useEffect dependencies to prevent unnecessary re-runs.

      The effect depends on the entire props object, which will cause the keyboard listener and scroll lock to be re-registered whenever the props object identity changes—even if only unrelated props like article change. Since the effect only uses props.onClose, specify that in the dependency array instead.

      ♻️ Proposed fix
           document.body.style.overflow = prev
         }
      - }, [props])
      + }, [props.onClose])
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@examples/ts-react-chat/src/components/ArticleModal.tsx` around lines 10 - 21,
      The useEffect in ArticleModal registers a keydown listener and toggles body
      overflow but incorrectly depends on the entire props object, causing unnecessary
      re-runs; change the dependency array to only include the specific callback used
      (props.onClose) by referencing the onKey handler and the effect that sets
      document.body.style.overflow so the listener and scroll lock are only
      re-registered when props.onClose changes.
      packages/typescript/ai-orchestration/src/primitives/bind-agents.ts (1)

      13-41: 💤 Low value

      Optional: collapse the two branches by building the descriptor inline.

      The two function* definitions differ only in the kind discriminator and the agent/workflow payload field. A single closure that switches on def.__kind reads about as clearly and removes duplicated descriptor wiring if this evolves (e.g., adds tracing fields).

      ♻️ Possible consolidation
         for (const [name, def] of Object.entries(agents)) {
      -    if (def.__kind === 'agent') {
      -      bound[name] = function* (
      -        input: unknown,
      -      ): Generator<StepDescriptor, unknown, unknown> {
      -        const descriptor: StepDescriptor = {
      -          kind: 'agent',
      -          name,
      -          input,
      -          agent: def,
      -        }
      -        const result = yield descriptor
      -        return result
      -      }
      -    } else {
      -      bound[name] = function* (
      -        input: unknown,
      -      ): Generator<StepDescriptor, unknown, unknown> {
      -        const descriptor: StepDescriptor = {
      -          kind: 'nested-workflow',
      -          name,
      -          input,
      -          workflow: def,
      -        }
      -        const result = yield descriptor
      -        return result
      -      }
      -    }
      +    bound[name] = function* (
      +      input: unknown,
      +    ): Generator<StepDescriptor, unknown, unknown> {
      +      const descriptor: StepDescriptor =
      +        def.__kind === 'agent'
      +          ? { kind: 'agent', name, input, agent: def }
      +          : { kind: 'nested-workflow', name, input, workflow: def }
      +      return yield descriptor
      +    }
         }
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/src/primitives/bind-agents.ts` around
      lines 13 - 41, The two generator functions for entries of agents and nested
      workflows duplicate descriptor construction; refactor the loop that builds
      bound[name] so a single generator closure creates a StepDescriptor with common
      fields (kind, name, input) and then sets the specific payload field based on
      def.__kind (e.g., set descriptor.agent = def for 'agent' or descriptor.workflow
      = def for 'nested-workflow'), yield the descriptor and return the result; update
      references to StepDescriptor, agents, bound, and def.__kind in that single
      generator to remove the duplicated function bodies.
      packages/typescript/ai-orchestration/src/server/parse-request.ts (1)

      9-14: 💤 Low value

      Dead abort field on RawBody.

      abort is declared on the parsed body shape but never returned from parseWorkflowRequest, and WorkflowRequestParams has no place to forward it. Since abort plumbing is explicitly out of scope for this PR, consider dropping the field from RawBody until it's wired up, so the parser shape doesn't advertise a capability it doesn't deliver.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/src/server/parse-request.ts` around
      lines 9 - 14, RawBody currently includes an unused abort?: boolean field which
      isn't propagated by parseWorkflowRequest and isn't represented on
      WorkflowRequestParams; remove abort from the RawBody interface to avoid
      advertising an unsupported capability, update any related types/usages that
      reference RawBody (e.g., the RawBody declaration in parse-request.ts) and run
      type checks to ensure no consumers relied on that field.
      packages/typescript/ai-orchestration/src/run-store/in-memory.ts (1)

      26-26: 💤 Low value

      Prefer a runtime-agnostic timer type.

      NodeJS.Timeout adds a dependency on @types/node for this utility. Use ReturnType<typeof setTimeout> instead, which works uniformly across Node, browsers, and Workers without environment-specific type imports.

      ♻️ Proposed change
      -  const expirations = new Map<string, NodeJS.Timeout>()
      +  const expirations = new Map<string, ReturnType<typeof setTimeout>>()
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts` at line 26,
      The Map declaration uses NodeJS.Timeout which ties the code to `@types/node`;
      change the type to a runtime-agnostic one by replacing NodeJS.Timeout with
      ReturnType<typeof setTimeout> in the declaration of expirations (the const
      expirations = new Map<string, ...>()), and ensure any places that read/clear
      timers (e.g., where clearTimeout is called) continue to accept that type without
      importing Node types.
      packages/typescript/ai-orchestration/src/engine/invoke-agent.ts (2)

      42-47: 💤 Low value

      Shape detection is positional — a small in check on shape (c) is OK but worth a comment.

      'stream' in result && 'output' in result accepts any object with those keys. The case is narrow (Promises don't have them, async iterables don't either), but a one-line comment noting that ordering matters (shape (c) before (a) before (b)) would help future maintainers who add a new shape.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/src/engine/invoke-agent.ts` around lines
      42 - 47, The shape detection in the result handling block (the `'stream' in
      result && 'output' in result` check inside invoke-agent.ts that returns {
      stream: filterInnerRunBoundaries(result.stream), output: result.output.then((o)
      => parseOutput<T>(agent, o)) }) relies on positional checks and intentionally
      accepts any object with those keys; add a concise one-line comment immediately
      above this if explaining that this is a narrow, positional shape check (shape
      (c)) and must remain ordered before the other shape branches (shape (a) then
      (b)) so future maintainers understand the rationale and don’t reorder or replace
      the check.

      148-155: 💤 Low value

      Minor: hoist SchemaValidationError above its usage.

      The class is declared at the bottom but referenced at lines 30 and 122. Works at runtime (calls happen after module init), but conventional ordering improves readability and avoids any future no-use-before-define lint trips.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/src/engine/invoke-agent.ts` around lines
      148 - 155, Move the exported SchemaValidationError class declaration above any
      code that constructs or references it so its definition precedes its usages;
      locate the places in this module where new SchemaValidationError(...) is
      thrown/checked (the earlier references in the same file) and cut-paste the class
      block to the top of the file (keeping export class SchemaValidationError ...
      unchanged) so lint rules like no-use-before-define no longer flag the symbol.
      packages/typescript/ai-orchestration/src/primitives/retry.ts (1)

      14-29: 💤 Low value

      Optional: jitter for exponential backoff.

      For the documented use (retrying agent calls that often hit shared upstream rate limits), unjittered exponential delays cause synchronized retry storms across concurrent runs. Adding ±20% jitter is trivial and standard.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/src/primitives/retry.ts` around lines 14
      - 29, The exponential backoff should include jitter to avoid synchronized retry
      storms: update computeDelay (the exponential branch) to compute the base
      exponential delay as currently done (using base and attempt), then apply ±20%
      random jitter (e.g., multiply by a random factor in [0.8, 1.2]), clamp the final
      value to <= maxDelayMs and >= 0 and return it (rounded to an integer if
      desired); keep the existing behavior for the 'none' and 'linear' branches and
      keep delay(ms: number): Promise<void> as-is.
      packages/typescript/ai-orchestration/src/engine/state-diff.ts (1)

      18-20: 💤 Low value

      structuredClone requires Node ≥ 17 / modern browsers. Consider adding a one-line note about the Node version requirement to the package's engines field or README, since it's not currently documented.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/src/engine/state-diff.ts` around lines
      18 - 20, The function snapshotState uses structuredClone which requires Node
      >=17 / modern browsers; update the package metadata to document this requirement
      by adding an engines entry (e.g., Node >=17) in this package's package.json
      and/or add a one-line note to the README mentioning that snapshotState
      (structuredClone) needs Node ≥17 or a modern browser runtime; reference the
      snapshotState function and structuredClone in your change so reviewers can see
      the compatibility note tied to the implementation.
      packages/typescript/ai-orchestration/src/engine/emit-events.ts (1)

      9-122: 💤 Low value

      Type-safety opportunity: helpers can return specific event types instead of generic StreamChunk casts.

      All event helper functions currently use as StreamChunk casts that bypass TypeScript's structural validation. Since all event types (RunStartedEvent, RunFinishedEvent, StepStartedEvent, etc.) are already exported from @tanstack/ai and are members of the AGUIEvent union (which StreamChunk aliases), you can improve type safety by having each helper return its specific event type instead. This lets TypeScript validate the payload shape at construction without the cast:

      export function runStartedEvent(args: {
        runId: string
        threadId?: string
      }): RunStartedEvent {  // instead of StreamChunk
        return {
          type: 'RUN_STARTED',
          timestamp: Date.now(),
          runId: args.runId,
          threadId: args.threadId ?? args.runId,
        }
      }

      The return type is still compatible with StreamChunk via the union, so callers see no difference. This catches any future misalignment between the payload and AG-UI's event schemas at the source.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/src/engine/emit-events.ts` around lines
      9 - 122, Change each helper to return its specific AG-UI event type (e.g.
      runStartedEvent -> RunStartedEvent, runFinishedEvent -> RunFinishedEvent,
      runErrorEvent -> RunErrorEvent, stepStartedEvent -> StepStartedEvent,
      stepFinishedEvent -> StepFinishedEvent, stateSnapshotEvent ->
      StateSnapshotEvent, stateDeltaEvent -> StateDeltaEvent, customEvent ->
      CustomEvent) instead of the generic StreamChunk and remove the trailing "as
      StreamChunk" casts; import those concrete types from `@tanstack/ai` so TypeScript
      validates the payload shape at construction (leave approvalRequestedEvent
      returning customEvent as-is since it delegates to customEvent). Ensure
      signatures and returned object shapes match the imported types.
      packages/typescript/ai-orchestration/tests/engine.smoke.test.ts (1)

      98-145: ⚡ Quick win

      Consider adding a resume smoke test alongside the pause assertion.

      The pause behavior is well-covered, but the symmetric path — calling runWorkflow({ workflow, runId, approval, runStore }) after the pause and asserting STEP_FINISHED(approval) plus RUN_FINISHED with the expected output — is the more failure-prone half of approval handling (state restore, pendingApprovalStepId finalization, generator.next seed value). A second assertion block on the same store would lock that contract.

      🧪 Sketch
      // after the pause assertions:
      const events2: Array<unknown> = []
      for await (const c of runWorkflow({
        workflow: wf as any,
        runId: runStarted.runId,
        approval: { approved: true },
        runStore: store,
      })) {
        events2.push(c)
      }
      const types2 = events2.map((e) => (e as { type: string }).type)
      expect(types2).toContain('STEP_FINISHED')
      expect(types2).toContain('RUN_FINISHED')
      const finished = events2.find(
        (e) => (e as { type: string }).type === 'RUN_FINISHED',
      ) as { output: { ok: boolean } }
      expect(finished.output).toEqual({ ok: true })
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/tests/engine.smoke.test.ts` around lines
      98 - 145, Add a symmetric resume smoke test after the existing pause assertions
      in the 'pauses on approval — stream ends after approval-requested, RUN_FINISHED
      not emitted' test: call runWorkflow again with the same workflow (wf), runId
      (from runStarted.runId), approval payload (e.g., { approved: true }) and the
      same runStore (store), collect emitted events into a new array (events2), then
      assert that events2 includes STEP_FINISHED and RUN_FINISHED and that the
      RUN_FINISHED event's output equals the expected { ok: true }; this verifies
      state restore, pendingApproval finalization, and the generator.next seed value
      are handled correctly.
      examples/ts-react-chat/src/routes/api.orchestration.ts (1)

      10-10: 💤 Low value

      Consider extracting the TTL constant for clarity.

      The TTL is specified inline as 60 * 60 * 1000. Consider extracting this to a named constant for improved readability and maintainability.

      ♻️ Suggested refactor
      +const RUN_STORE_TTL_MS = 60 * 60 * 1000 // 1 hour
      +
      -const runStore = inMemoryRunStore({ ttl: 60 * 60 * 1000 })
      +const runStore = inMemoryRunStore({ ttl: RUN_STORE_TTL_MS })
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@examples/ts-react-chat/src/routes/api.orchestration.ts` at line 10, The
      inline TTL literal passed to inMemoryRunStore (60 * 60 * 1000) reduces
      readability; extract it to a named constant (e.g., RUN_STORE_TTL_MS) near the
      top of the module and use that constant when constructing runStore so the
      purpose and units are clear; update any related comments or usages of runStore
      if needed to reference the constant.
      packages/typescript/ai-react/src/use-workflow.ts (1)

      37-40: 💤 Low value

      Consider clarifying the comment about fresh values.

      The comment states "Track latest options so callbacks read fresh values" but the body option is captured at client construction time (line 51) and won't reflect prop changes. Consider clarifying that only the event callbacks (onCustomEvent, onStateChange) read fresh values, while structural options like body and connection are fixed at client creation.

      📝 Suggested clarification
      -  // Track latest options so callbacks read fresh values without recreating
      -  // the client. Mirrors useChat's pattern.
      +  // Track latest options so event callbacks (onCustomEvent, onStateChange)
      +  // read fresh values without recreating the client. Structural options like
      +  // `body` and `connection` are captured at construction. Mirrors useChat's pattern.
         const optsRef = useRef(opts)
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-react/src/use-workflow.ts` around lines 37 - 40, The
      comment near optsRef (where const optsRef = useRef(opts); optsRef.current =
      opts) is misleading because some options (like body and connection) are captured
      at client construction and not updated, while event callbacks do read fresh
      values; update the comment to state that optsRef is used so callback handlers
      (onCustomEvent, onStateChange) will see the latest opts via optsRef.current, but
      structural options such as body and connection are fixed when the client is
      created (refer to the client construction site where body is passed) and will
      not change if props update.
      examples/ts-react-chat/src/components/WorkflowTimeline.tsx (1)

      105-109: 💤 Low value

      Consider using replaceAll for consistent formatting.

      The current code uses replace('-', ' · '), which only replaces the first occurrence. If stepType contains multiple dashes (e.g., "agent-call-retry"), only the first will be replaced.

      ♻️ Suggested fix
      -            {step.stepType.replace('-', ' · ')}
      +            {step.stepType.replaceAll('-', ' · ')}
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@examples/ts-react-chat/src/components/WorkflowTimeline.tsx` around lines 105
      - 109, The JSX rendering in WorkflowTimeline.tsx uses step.stepType.replace('-',
      ' · ') which only replaces the first dash; update the expression in the span
      rendering (the usage of step.stepType) to replace all dashes (e.g., use
      step.stepType.replaceAll('-', ' · ') or step.stepType.split('-').join(' · ')) so
      multi-dash types like "agent-call-retry" become "agent · call · retry".
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@examples/ts-react-chat/src/components/DraftPreview.tsx`:
      - Around line 9-11: The current cast of props.draft to Draft lets malformed
      payloads reach code that calls draft.paragraphs.map and crash; update the
      DraftPreview component to perform runtime shape checks instead of blind casting:
      ensure props.draft is an object and that draft.paragraphs is an Array (and
      optionally validate each item has the expected fields) before using .map or
      rendering; modify the draft initialization and any other places that access
      draft.paragraphs (the draft variable and the rendering logic that iterates
      paragraphs) to guard with Array.isArray(draft.paragraphs) (or fallback to an
      empty array) so .map is only called on a real array and malformed inputs are
      safely handled.
      
      In `@examples/ts-react-chat/src/components/WorkflowTimeline.tsx`:
      - Around line 175-177: FailureBlock currently asserts props.result to a specific
      shape without runtime checks; replace the unchecked assertion with a defensive
      runtime guard: implement a small type guard (e.g., isErrorLike) or inline checks
      that verify props.result is an object and that result.error is an object with a
      string message before reading result.error.message, otherwise fall back to
      JSON.stringify(props.result) or a generic message; update the FailureBlock logic
      to use that guard when deriving msg so accessing result.error?.message cannot
      throw or return misleading values.
      
      In `@examples/ts-react-chat/src/routes/api.orchestration.ts`:
      - Around line 15-23: The POST handler should guard against exceptions from
      parseWorkflowRequest and runWorkflow by wrapping their calls in a try/catch:
      call parseWorkflowRequest(...) and runWorkflow(...) inside the try, and on
      success return toServerSentEventsResponse(stream); in the catch block construct
      and return a structured error response (JSON body with an error message and
      appropriate status like 400 for bad input or 500 for server error) so clients
      get a clear failure instead of an unhandled exception; reference the POST
      handler, parseWorkflowRequest, runWorkflow, featureOrchestrator, runStore and
      toServerSentEventsResponse when making the changes.
      
      In `@packages/typescript/ai-client/src/connection-adapters.ts`:
      - Around line 553-558: The loop in readStreamLines/connection-adapters is
      yielding raw JSON.parse output (in the for-await over readStreamLines(reader,
      abortSignal)) without runtime validation; add Zod validation after JSON.parse:
      import z from 'zod', define a WorkflowSseChunkSchema (or WorkflowEventSchema)
      that matches the expected SSE chunk shape, then replace the raw yield with
      validation via WorkflowSseChunkSchema.safeParse(parsed) and only yield the
      validated .data (or continue on failure), logging or ignoring invalid chunks as
      appropriate so malformed chunks don't propagate.
      
      In `@packages/typescript/ai-client/src/workflow-client.ts`:
      - Around line 109-124: Wrap the async stream-handling in approve() (and the
      similar blocks in start() and the other approval path) with a try/catch so that
      any exceptions from openStream/consumeStream (or connect/iteration) update
      client state to reflect the failure: call this.setState({ status: 'error',
      error: err, pendingApproval: null }) inside the catch, then rethrow the error.
      Locate the stream flow in approve(), start(), and the other approval-handling
      code paths and apply the same pattern to ensure state is not left as 'running'
      when stream errors occur.
      - Around line 301-306: The traversal over path segments currently assumes every
      intermediate node exists and is an object/array, which can throw on malformed
      deltas; update the loop that walks segments (the code using variables segments,
      cursor and last) to validate at each iteration that cursor is non-null and
      typeof cursor === 'object' and that segments[i] exists (and is indexable) before
      assigning cursor = cursor[segments[i]]; if any check fails, abort/skip applying
      this delta (return/continue) rather than letting it throw. Apply the same
      defensive checks to the other similar block (the splice/delete handling around
      lines 317-321) so both deletion and insertion/splice paths safely ignore invalid
      paths instead of crashing the stream.
      - Around line 135-142: The stop() method currently constructs an async iterable
      by calling openStream(...) but never consumes it, so the abort payload is never
      sent; change stop to async and consume the returned async iterable from
      openStream({ abort: true, runId: this.clientState.runId }) (e.g., use a
      for-await-of loop to iterate the stream until completion or break immediately
      after first send) and propagate/handle any errors, then call this.setState({
      status: 'aborted' })—this ensures openStream actually executes the abort
      request. Reference: stop(), openStream(), this.clientState.runId,
      this.setState().
      - Around line 152-249: handleChunk currently casts incoming streaming chunks
      without runtime checks which can corrupt this.clientState or throw; add Zod
      schemas for the different chunk shapes (e.g., CUSTOM, RUN_ERROR, RUN_FINISHED,
      RUN_STARTED, STATE_DELTA, STATE_SNAPSHOT, STEP_FINISHED, STEP_STARTED,
      TEXT_MESSAGE_CONTENT) and validate each incoming chunk at the top of handleChunk
      before any casting or state updates (use a discriminated union on chunk.type),
      then reject/log invalid chunks and return early; update references in this
      function (handleChunk, setState, this.clientState, applyJsonPatch,
      WorkflowClientState) to use the validated/typed data instead of unchecked casts.
      
      In `@packages/typescript/ai-orchestration/package.json`:
      - Line 47: The package.json entry for the internal peer dependency
      "@tanstack/ai" uses "workspace:^" instead of the required internal protocol
      "workspace:*"; update the dependency value for "@tanstack/ai" in
      packages/typescript/ai-orchestration/package.json to "workspace:*" so the
      internal peer dependency follows the project's workspace protocol conventions.
      
      In `@packages/typescript/ai-orchestration/src/engine/invoke-agent.ts`:
      - Around line 52-82: The output Promise can hang if the async iterator exits
      early; update drain() to always settle output in a finally block: introduce a
      local boolean (e.g., settled = false) and move the parseOutputFromText(agent,
      lastTextContent) + resolveOutput(parsed) / rejectOutput(err) logic into a
      finally that runs after the for-await loop so output is resolved or rejected on
      every exit path, and guard resolveOutput/rejectOutput with the settled flag to
      avoid double-settling; keep the existing catch to rethrow errors but ensure it
      sets settled so the finally knows whether it must call resolve/reject; reference
      drain(), output, resolveOutput, rejectOutput, lastTextContent,
      parseOutputFromText and filterInnerRunBoundaries when making the change.
      
      In `@packages/typescript/ai-orchestration/src/engine/run-workflow.ts`:
      - Around line 332-364: The nested-workflow branch in runWorkflow currently
      yields nested chunks but then always emits STEP_FINISHED and continues even if
      the nested run errored or paused; update the nested-workflow handling (the
      runWorkflow call and the for-await loop over nestedIter) to mirror the agent
      error handler logic: when a nested chunk with type 'RUN_ERROR' is received, emit
      STEP_FINISHED for the step with the error content and propagate the failure into
      the parent (call the parent generator's throw equivalent as done in the agent
      handler) instead of continuing, and when an approval-related
      pause/approval-requested is observed, do not treat the nested step as
      finished—either block here or explicitly fail the nested approval at this
      boundary until parent-pause-on-nested-pause is supported; refer to the
      nested-workflow descriptor handling and the agent error handler (lines around
      the existing error catch that emits STEP_FINISHED and calls
      live.generator.throw(err)) to implement identical error/approval propagation
      behavior.
      - Around line 51-62: mergeStateDefaults currently calls
      workflow.stateSchema['~standard'].validate(initial) but ignores Promise results,
      causing async validations to be skipped and defaults/coercions lost; change
      mergeStateDefaults to be async, await the validate(...) call, then check the
      awaited result for issues (same logic as the synchronous branch) and return the
      coerced validated.value when present, otherwise return initial; update any
      callers (e.g., startRun) if needed to await mergeStateDefaults so both sync and
      async schema validators are handled consistently.
      
      In `@packages/typescript/ai-orchestration/src/engine/state-diff.ts`:
      - Around line 32-72: The diff function can emit operations with value: undefined
      which JSON.stringify drops; update the places that create ops (the top-level
      replace in diff when types disagree or arrays differ, and the per-key add in the
      object branch) to normalize undefined to null (or alternatively treat undefined
      as a remove); specifically, change the value payloads created in diff (both the
      replace op that uses value: next and the add op that uses value: nextObj[key])
      to use a helper normalization (e.g., normalizedValue = next === undefined ? null
      : next) before constructing the Operation so no op is emitted with value:
      undefined.
      
      In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts`:
      - Around line 28-55: The teardown in scheduleExpiry and delete currently removes
      live entries but leaves LiveRun.abortController un-aborted and
      LiveRun.approvalResolver unresolved, leaking paused generators and
      pendingEvents; update scheduleExpiry (where the timeout handle is created) and
      delete to first retrieve the live entry from live.get(runId) and if present call
      abortController.abort(), reject/resolve the approvalResolver (reject with a
      clear Abort/Error) and clear/publish pendingEvents before deleting; also ensure
      the created timeout handle uses setTimeout(...).unref?.() so the TTL won't keep
      the Node process alive. Ensure you reference and operate on the LiveRun object
      obtained via live.get(runId) when implementing these changes.
      
      In `@packages/typescript/ai-orchestration/src/server/parse-request.ts`:
      - Around line 30-39: Replace the unsafe cast in parseWorkflowRequest by defining
      a Zod schema for RawBody/WorkflowRequestParams (including approval with
      approvalId types, input, runId) and use it to parse/validate await
      request.json(); on parse failure throw a 400 HTTP error (or return a clear
      validation error) so malformed bodies are rejected at the HTTP boundary before
      calling runWorkflow; update parseWorkflowRequest to return the validated, typed
      result from zod.parse/zod.safeParse instead of the structural cast.
      
      ---
      
      Nitpick comments:
      In `@examples/ts-react-chat/src/components/ArticleModal.tsx`:
      - Around line 10-21: The useEffect in ArticleModal registers a keydown listener
      and toggles body overflow but incorrectly depends on the entire props object,
      causing unnecessary re-runs; change the dependency array to only include the
      specific callback used (props.onClose) by referencing the onKey handler and the
      effect that sets document.body.style.overflow so the listener and scroll lock
      are only re-registered when props.onClose changes.
      
      In `@examples/ts-react-chat/src/components/DraftPreview.tsx`:
      - Around line 55-58: The preview container in DraftPreview currently uses
      key={bumpKey} which forces a remount and resets scroll/focus; remove the dynamic
      key and instead add a stable root element (the existing div with className
      "relative px-6 py-7...") and toggle a data attribute or short-lived CSS class
      (e.g. data-bump={bumpKey} or isPulsing) on that same div to trigger the pulse
      animation via CSS/animation, ensuring you update where bumpKey is produced so it
      sets the attribute/class rather than the key.
      
      In `@examples/ts-react-chat/src/components/WorkflowTimeline.tsx`:
      - Around line 105-109: The JSX rendering in WorkflowTimeline.tsx uses
      step.stepType.replace('-', ' · ') which only replaces the first dash; update the
      expression in the span rendering (the usage of step.stepType) to replace all
      dashes (e.g., use step.stepType.replaceAll('-', ' · ') or
      step.stepType.split('-').join(' · ')) so multi-dash types like
      "agent-call-retry" become "agent · call · retry".
      
      In `@examples/ts-react-chat/src/routes/api.orchestration.ts`:
      - Line 10: The inline TTL literal passed to inMemoryRunStore (60 * 60 * 1000)
      reduces readability; extract it to a named constant (e.g., RUN_STORE_TTL_MS)
      near the top of the module and use that constant when constructing runStore so
      the purpose and units are clear; update any related comments or usages of
      runStore if needed to reference the constant.
      
      In `@packages/typescript/ai-orchestration/src/engine/emit-events.ts`:
      - Around line 9-122: Change each helper to return its specific AG-UI event type
      (e.g. runStartedEvent -> RunStartedEvent, runFinishedEvent -> RunFinishedEvent,
      runErrorEvent -> RunErrorEvent, stepStartedEvent -> StepStartedEvent,
      stepFinishedEvent -> StepFinishedEvent, stateSnapshotEvent ->
      StateSnapshotEvent, stateDeltaEvent -> StateDeltaEvent, customEvent ->
      CustomEvent) instead of the generic StreamChunk and remove the trailing "as
      StreamChunk" casts; import those concrete types from `@tanstack/ai` so TypeScript
      validates the payload shape at construction (leave approvalRequestedEvent
      returning customEvent as-is since it delegates to customEvent). Ensure
      signatures and returned object shapes match the imported types.
      
      In `@packages/typescript/ai-orchestration/src/engine/invoke-agent.ts`:
      - Around line 42-47: The shape detection in the result handling block (the
      `'stream' in result && 'output' in result` check inside invoke-agent.ts that
      returns { stream: filterInnerRunBoundaries(result.stream), output:
      result.output.then((o) => parseOutput<T>(agent, o)) }) relies on positional
      checks and intentionally accepts any object with those keys; add a concise
      one-line comment immediately above this if explaining that this is a narrow,
      positional shape check (shape (c)) and must remain ordered before the other
      shape branches (shape (a) then (b)) so future maintainers understand the
      rationale and don’t reorder or replace the check.
      - Around line 148-155: Move the exported SchemaValidationError class declaration
      above any code that constructs or references it so its definition precedes its
      usages; locate the places in this module where new SchemaValidationError(...) is
      thrown/checked (the earlier references in the same file) and cut-paste the class
      block to the top of the file (keeping export class SchemaValidationError ...
      unchanged) so lint rules like no-use-before-define no longer flag the symbol.
      
      In `@packages/typescript/ai-orchestration/src/engine/state-diff.ts`:
      - Around line 18-20: The function snapshotState uses structuredClone which
      requires Node >=17 / modern browsers; update the package metadata to document
      this requirement by adding an engines entry (e.g., Node >=17) in this package's
      package.json and/or add a one-line note to the README mentioning that
      snapshotState (structuredClone) needs Node ≥17 or a modern browser runtime;
      reference the snapshotState function and structuredClone in your change so
      reviewers can see the compatibility note tied to the implementation.
      
      In `@packages/typescript/ai-orchestration/src/primitives/bind-agents.ts`:
      - Around line 13-41: The two generator functions for entries of agents and
      nested workflows duplicate descriptor construction; refactor the loop that
      builds bound[name] so a single generator closure creates a StepDescriptor with
      common fields (kind, name, input) and then sets the specific payload field based
      on def.__kind (e.g., set descriptor.agent = def for 'agent' or
      descriptor.workflow = def for 'nested-workflow'), yield the descriptor and
      return the result; update references to StepDescriptor, agents, bound, and
      def.__kind in that single generator to remove the duplicated function bodies.
      
      In `@packages/typescript/ai-orchestration/src/primitives/retry.ts`:
      - Around line 14-29: The exponential backoff should include jitter to avoid
      synchronized retry storms: update computeDelay (the exponential branch) to
      compute the base exponential delay as currently done (using base and attempt),
      then apply ±20% random jitter (e.g., multiply by a random factor in [0.8, 1.2]),
      clamp the final value to <= maxDelayMs and >= 0 and return it (rounded to an
      integer if desired); keep the existing behavior for the 'none' and 'linear'
      branches and keep delay(ms: number): Promise<void> as-is.
      
      In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts`:
      - Line 26: The Map declaration uses NodeJS.Timeout which ties the code to
      `@types/node`; change the type to a runtime-agnostic one by replacing
      NodeJS.Timeout with ReturnType<typeof setTimeout> in the declaration of
      expirations (the const expirations = new Map<string, ...>()), and ensure any
      places that read/clear timers (e.g., where clearTimeout is called) continue to
      accept that type without importing Node types.
      
      In `@packages/typescript/ai-orchestration/src/server/parse-request.ts`:
      - Around line 9-14: RawBody currently includes an unused abort?: boolean field
      which isn't propagated by parseWorkflowRequest and isn't represented on
      WorkflowRequestParams; remove abort from the RawBody interface to avoid
      advertising an unsupported capability, update any related types/usages that
      reference RawBody (e.g., the RawBody declaration in parse-request.ts) and run
      type checks to ensure no consumers relied on that field.
      
      In `@packages/typescript/ai-orchestration/tests/engine.smoke.test.ts`:
      - Around line 98-145: Add a symmetric resume smoke test after the existing pause
      assertions in the 'pauses on approval — stream ends after approval-requested,
      RUN_FINISHED not emitted' test: call runWorkflow again with the same workflow
      (wf), runId (from runStarted.runId), approval payload (e.g., { approved: true })
      and the same runStore (store), collect emitted events into a new array
      (events2), then assert that events2 includes STEP_FINISHED and RUN_FINISHED and
      that the RUN_FINISHED event's output equals the expected { ok: true }; this
      verifies state restore, pendingApproval finalization, and the generator.next
      seed value are handled correctly.
      
      In `@packages/typescript/ai-react/src/use-workflow.ts`:
      - Around line 37-40: The comment near optsRef (where const optsRef =
      useRef(opts); optsRef.current = opts) is misleading because some options (like
      body and connection) are captured at client construction and not updated, while
      event callbacks do read fresh values; update the comment to state that optsRef
      is used so callback handlers (onCustomEvent, onStateChange) will see the latest
      opts via optsRef.current, but structural options such as body and connection are
      fixed when the client is created (refer to the client construction site where
      body is passed) and will not change if props update.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: eeed6f10-2679-46f2-97cf-1966e42df69f

      📥 Commits

      Reviewing files that changed from the base of the PR and between 4a943d686160fc4f34d79a0e6a3847240003be8b and 16354b71b0312b52c6208518074a18d489b05db6.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (44)
      • examples/ts-react-chat/package.json
      • examples/ts-react-chat/src/components/ArticleModal.tsx
      • examples/ts-react-chat/src/components/DraftPreview.tsx
      • examples/ts-react-chat/src/components/Header.tsx
      • examples/ts-react-chat/src/components/StateInspector.tsx
      • examples/ts-react-chat/src/components/WorkflowTimeline.tsx
      • examples/ts-react-chat/src/lib/workflows/article-workflow.ts
      • examples/ts-react-chat/src/lib/workflows/orchestrator.ts
      • examples/ts-react-chat/src/routeTree.gen.ts
      • examples/ts-react-chat/src/routes/api.orchestration.ts
      • examples/ts-react-chat/src/routes/api.workflow.ts
      • examples/ts-react-chat/src/routes/orchestration.tsx
      • examples/ts-react-chat/src/routes/workflow.tsx
      • examples/ts-react-chat/src/styles.css
      • packages/typescript/ai-client/src/connection-adapters.ts
      • packages/typescript/ai-client/src/index.ts
      • packages/typescript/ai-client/src/workflow-client.ts
      • packages/typescript/ai-orchestration/README.md
      • packages/typescript/ai-orchestration/eslint.config.js
      • packages/typescript/ai-orchestration/package.json
      • packages/typescript/ai-orchestration/src/define/define-agent.ts
      • packages/typescript/ai-orchestration/src/define/define-orchestrator.ts
      • packages/typescript/ai-orchestration/src/define/define-router.ts
      • packages/typescript/ai-orchestration/src/define/define-workflow.ts
      • packages/typescript/ai-orchestration/src/engine/emit-events.ts
      • packages/typescript/ai-orchestration/src/engine/invoke-agent.ts
      • packages/typescript/ai-orchestration/src/engine/run-workflow.ts
      • packages/typescript/ai-orchestration/src/engine/state-diff.ts
      • packages/typescript/ai-orchestration/src/index.ts
      • packages/typescript/ai-orchestration/src/primitives/approve.ts
      • packages/typescript/ai-orchestration/src/primitives/bind-agents.ts
      • packages/typescript/ai-orchestration/src/primitives/index.ts
      • packages/typescript/ai-orchestration/src/primitives/retry.ts
      • packages/typescript/ai-orchestration/src/result.ts
      • packages/typescript/ai-orchestration/src/run-store/in-memory.ts
      • packages/typescript/ai-orchestration/src/run-store/index.ts
      • packages/typescript/ai-orchestration/src/server/index.ts
      • packages/typescript/ai-orchestration/src/server/parse-request.ts
      • packages/typescript/ai-orchestration/src/types.ts
      • packages/typescript/ai-orchestration/tests/engine.smoke.test.ts
      • packages/typescript/ai-orchestration/tsconfig.json
      • packages/typescript/ai-orchestration/vite.config.ts
      • packages/typescript/ai-react/src/index.ts
      • packages/typescript/ai-react/src/use-workflow.ts
      @@ -485,0 +538,21 @@
      538+ credentials: resolvedOptions.credentials ?? 'same-origin',
      539+ headers: requestHeaders,
      540+ method: 'POST',
      541+ signal: abortSignal ?? resolvedOptions.signal,
      542+ })
      543+
      544+ if (!response.ok) {
      545+ throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      546+ }
      547+
      548+ const reader = response.body?.getReader()
      549+ if (!reader) {
      550+ throw new Error('Response body is not readable')
      551+ }
      552+
      553+ for await (const line of readStreamLines(reader, abortSignal)) {
      554+ const data = line.startsWith('data: ') ? line.slice(6) : line
      555+ if (!data) continue
      556+ try {
      557+ yield JSON.parse(data)
      558+ } catch {
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

      🧩 Analysis chain

      🏁 Script executed:

      cd packages/typescript/ai-client/src && wc -l connection-adapters.ts

      Repository: TanStack/ai

      Length of output: 82


      🏁 Script executed:

      cd packages/typescript/ai-client/src && sed -n '540,570p' connection-adapters.ts | cat -n

      Repository: TanStack/ai

      Length of output: 863


      🏁 Script executed:

      cd packages/typescript/ai-client/src && head -20 connection-adapters.ts | cat -n

      Repository: TanStack/ai

      Length of output: 744


      🏁 Script executed:

      cd packages/typescript && rg "import.*zod" --type ts

      Repository: TanStack/ai

      Length of output: 2168


      🏁 Script executed:

      cd packages/typescript && rg "WorkflowChunkSchema\|z\.object\|safeParse" src/ -A 2 -B 2

      Repository: TanStack/ai

      Length of output: 100


      🏁 Script executed:

      cd packages/typescript/ai-client && grep -n "JSON.parse\|safeParse\|parse\|\.z\." src/connection-adapters.ts

      Repository: TanStack/ai

      Length of output: 468


      🏁 Script executed:

      cd packages/typescript/ai-client && grep -n "readStreamLines\|for await" src/connection-adapters.ts | head -20

      Repository: TanStack/ai

      Length of output: 364


      🏁 Script executed:

      cd packages/typescript/ai-client/src && cat -n workflow-client.ts | head -100

      Repository: TanStack/ai

      Length of output: 3301


      🏁 Script executed:

      cd packages/typescript/ai-client/src && grep -n "WorkflowChunk\|StreamChunk" connection-adapters.ts

      Repository: TanStack/ai

      Length of output: 1286


      🏁 Script executed:

      cd packages/typescript/ai-client && find . -name "*.ts" -exec grep -l "JSON.parse" {} \; | head -10

      Repository: TanStack/ai

      Length of output: 162


      🏁 Script executed:

      cd packages/typescript/ai-client/src && sed -n '480,495p' connection-adapters.ts | cat -n

      Repository: TanStack/ai

      Length of output: 653


      🏁 Script executed:

      cd packages/typescript/ai-client/src && sed -n '310,330p' connection-adapters.ts | cat -n

      Repository: TanStack/ai

      Length of output: 914


      Add Zod schema validation for workflow SSE chunks.

      Line 557 yields raw JSON.parse output without runtime schema validation. Per coding guidelines for packages/typescript/**/src/**/*.ts, Zod must be used for schema validation. This makes the workflow event handling fragile when chunks are malformed or unexpectedly shaped.

      Proposed fix
      +import { z } from 'zod'
      +
      +const WorkflowChunkSchema = z.object({
      +  type: z.string(),
      +}).passthrough()
      ...
             for await (const line of readStreamLines(reader, abortSignal)) {
               const data = line.startsWith('data: ') ? line.slice(6) : line
               if (!data) continue
               try {
      -          yield JSON.parse(data)
      +          const parsed = WorkflowChunkSchema.safeParse(JSON.parse(data))
      +          if (parsed.success) {
      +            yield parsed.data
      +          }
               } catch {
                 // skip malformed lines
               }
             }
      📝 Committable suggestion

      ‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      Suggested change
      1104+ for await (const line of readStreamLines(reader, abortSignal)) {
      1105+ const data = line.startsWith('data: ') ? line.slice(6) : line
      1106+ if (!data) continue
      1107+ try {
      1108+ const parsed = WorkflowChunkSchema.safeParse(JSON.parse(data))
      1109+ if (parsed.success) {
      1110+ yield parsed.data
      1111+ }
      1112+ } catch {
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-client/src/connection-adapters.ts` around lines 553 -
      558, The loop in readStreamLines/connection-adapters is yielding raw JSON.parse
      output (in the for-await over readStreamLines(reader, abortSignal)) without
      runtime validation; add Zod validation after JSON.parse: import z from 'zod',
      define a WorkflowSseChunkSchema (or WorkflowEventSchema) that matches the
      expected SSE chunk shape, then replace the raw yield with validation via
      WorkflowSseChunkSchema.safeParse(parsed) and only yield the validated .data (or
      continue on failure), logging or ignoring invalid chunks as appropriate so
      malformed chunks don't propagate.
      @@ -0,0 +229,21 @@
      229+ case 'STEP_STARTED': {
      230+ const step: WorkflowStep = {
      231+ startedAt: chunk.timestamp as number,
      232+ status: 'running',
      233+ stepId: chunk.stepId as string,
      234+ stepName: chunk.stepName as string,
      235+ stepType: chunk.stepType as WorkflowStep['stepType'],
      236+ }
      237+ this.setState({
      238+ currentStep: step,
      239+ currentText: '',
      240+ steps: [...this.clientState.steps, step],
      241+ })
      242+ break
      243+ }
      244+ case 'TEXT_MESSAGE_CONTENT':
      245+ this.setState({
      246+ currentText: this.clientState.currentText + (chunk.delta as string),
      247+ })
      248+ break
      249+ }
      coderabbitai[bot](GitHub profile, opens in a new tab)commented

      🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

      🧩 Analysis chain

      🏁 Script executed:

      # Check if the file exists and examine its structure
      ls -la packages/typescript/ai-client/src/ 2>/dev/null | head -20

      Repository: TanStack/ai

      Length of output: 1038


      🏁 Script executed:

      # Verify Zod is in project dependencies
      fd package.json packages/typescript | head -3

      Repository: TanStack/ai

      Length of output: 194


      🏁 Script executed:

      # Search for Zod usage in the typescript packages
      rg -l "zod|Zod" packages/typescript --type ts --type json

      Repository: TanStack/ai

      Length of output: 3265


      🏁 Script executed:

      # Check ai-client package.json for dependencies
      cat packages/typescript/ai-client/package.json

      Repository: TanStack/ai

      Length of output: 1362


      🏁 Script executed:

      # Read the workflow-client.ts file to understand the full context
      cat -n packages/typescript/ai-client/src/workflow-client.ts | head -100

      Repository: TanStack/ai

      Length of output: 3301


      🏁 Script executed:

      # Check how validation/schema handling is done in similar client files
      cat -n packages/typescript/ai-client/src/chat-client.ts | head -150

      Repository: TanStack/ai

      Length of output: 6752


      🏁 Script executed:

      # Read the handleChunk method and surrounding context in workflow-client.ts
      cat -n packages/typescript/ai-client/src/workflow-client.ts | sed -n '140,260p'

      Repository: TanStack/ai

      Length of output: 4613


      🏁 Script executed:

      # Check the full workflow-client.ts for imports and helper functions
      cat -n packages/typescript/ai-client/src/workflow-client.ts

      Repository: TanStack/ai

      Length of output: 11593


      🏁 Script executed:

      # Check if there are other similar chunk/event validation patterns in the ai-client package
      rg -A 10 "handleChunk|processChunk|validateChunk" packages/typescript/ai-client/src --type ts

      Repository: TanStack/ai

      Length of output: 2388


      🏁 Script executed:

      # Check how Zod is used elsewhere in the typescript packages for event/stream validation
      rg -B 3 -A 5 "z\.(object|discriminatedUnion|union)" packages/typescript/ai/src --type ts | head -80

      Repository: TanStack/ai

      Length of output: 4901


      Use Zod to validate inbound workflow chunks.

      handleChunk relies on unchecked casts for externally streamed events without runtime validation. Per coding guidelines, schema validation with Zod is mandatory across packages/typescript/**/src/**/*.ts files. A malformed chunk can corrupt state transitions or throw mid-reducer.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-client/src/workflow-client.ts` around lines 152 - 249,
      handleChunk currently casts incoming streaming chunks without runtime checks
      which can corrupt this.clientState or throw; add Zod schemas for the different
      chunk shapes (e.g., CUSTOM, RUN_ERROR, RUN_FINISHED, RUN_STARTED, STATE_DELTA,
      STATE_SNAPSHOT, STEP_FINISHED, STEP_STARTED, TEXT_MESSAGE_CONTENT) and validate
      each incoming chunk at the top of handleChunk before any casting or state
      updates (use a discriminated union on chunk.type), then reject/log invalid
      chunks and return early; update references in this function (handleChunk,
      setState, this.clientState, applyJsonPatch, WorkflowClientState) to use the
      validated/typed data instead of unchecked casts.
    6. Actionable comments posted: 2

      Caution

      Some comments are outside the diff and can’t be posted inline due to platform limitations.

      ⚠️ Outside diff range comments (1)
      examples/ts-react-chat/src/routes/api.workflow.ts (1)

      16-28: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

      Add structured error handling around request parsing and run startup.

      parseWorkflowRequest and runWorkflow can throw; without a guard this route returns unstructured failures and drops client context.

      Suggested minimal fix
             POST: async ({ request }) => {
      -        const params = await parseWorkflowRequest(request)
      -        if (params.abort && params.runId) {
      -          runStore.getLive(params.runId)?.abortController.abort()
      -          return new Response(null, { status: 204 })
      -        }
      -        const stream = runWorkflow({
      -          runStore,
      -          workflow: articleWorkflow,
      -          ...params,
      -        })
      -        return toServerSentEventsResponse(stream)
      +        try {
      +          const params = await parseWorkflowRequest(request)
      +          if (params.abort && params.runId) {
      +            runStore.getLive(params.runId)?.abortController.abort()
      +            return new Response(null, { status: 204 })
      +          }
      +          const stream = runWorkflow({
      +            runStore,
      +            workflow: articleWorkflow,
      +            ...params,
      +          })
      +          return toServerSentEventsResponse(stream)
      +        } catch (error) {
      +          return new Response(
      +            JSON.stringify({
      +              error: error instanceof Error ? error.message : 'Unknown error',
      +            }),
      +            { status: 400, headers: { 'Content-Type': 'application/json' } },
      +          )
      +        }
             },
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@examples/ts-react-chat/src/routes/api.workflow.ts` around lines 16 - 28, Wrap
      the request handling in a try/catch that separately guards parseWorkflowRequest
      and runWorkflow so thrown errors return structured HTTP responses instead of
      unhandled failures: catch parse errors from parseWorkflowRequest and return a
      400 JSON error, preserve the existing abort logic when params indicate abort,
      then wrap the runWorkflow call and stream conversion in its own try/catch that
      logs the error and returns a 500 JSON error if runWorkflow or
      toServerSentEventsResponse throws; reference parseWorkflowRequest, runWorkflow,
      runStore, and toServerSentEventsResponse to locate the code and keep the
      existing abortController abort path intact.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@docs/orchestration/orchestrators.md`:
      - Around line 24-29: The fenced code block containing "for turn = 0..maxTurns:"
      is unlabeled and triggers MD040; update the opening fence (the triple backticks
      before the block) to include a language tag such as text or pseudo (e.g., change
      ``` to ```text) so the block is labeled, preserving the existing lines with
      router, run, decision, and lastResult.
      
      In `@examples/ts-react-chat/src/components/CodeBlock.tsx`:
      - Around line 40-67: The effect in CodeBlock leaves previous errored/html state
      across runs, so at the start of the async work inside the useEffect you should
      reset the highlight state: call setErrored(false) and clear stale HTML via
      setHtml('') (or equivalent initial value) before awaiting getHighlighter(), so
      subsequent successful highlights render after a prior failure; keep the existing
      cancellation object (ctl) and error handling around
      getHighlighter()/highlighter.codeToHtml unchanged.
      
      ---
      
      Outside diff comments:
      In `@examples/ts-react-chat/src/routes/api.workflow.ts`:
      - Around line 16-28: Wrap the request handling in a try/catch that separately
      guards parseWorkflowRequest and runWorkflow so thrown errors return structured
      HTTP responses instead of unhandled failures: catch parse errors from
      parseWorkflowRequest and return a 400 JSON error, preserve the existing abort
      logic when params indicate abort, then wrap the runWorkflow call and stream
      conversion in its own try/catch that logs the error and returns a 500 JSON error
      if runWorkflow or toServerSentEventsResponse throws; reference
      parseWorkflowRequest, runWorkflow, runStore, and toServerSentEventsResponse to
      locate the code and keep the existing abortController abort path intact.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: 4ab30fa8-c053-478b-aa83-fbf0a01a7518

      📥 Commits

      Reviewing files that changed from the base of the PR and between 16354b71b0312b52c6208518074a18d489b05db6 and 0f662123642802e1c0f3ee7bf6ceccf936765650.

      📒 Files selected for processing (31)
      • .agent/self-learning/coupling.json
      • docs/api/ai-orchestration.md
      • docs/chat/agentic-cycle.md
      • docs/config.json
      • docs/getting-started/overview.md
      • docs/orchestration/approvals.md
      • docs/orchestration/orchestrators.md
      • docs/orchestration/overview.md
      • docs/orchestration/refining-across-runs.md
      • docs/orchestration/retries-and-errors.md
      • docs/orchestration/run-persistence.md
      • docs/orchestration/workflows.md
      • docs/structured-outputs/multi-turn.md
      • docs/tools/tools.md
      • examples/ts-react-chat/package.json
      • examples/ts-react-chat/src/components/CodeBlock.tsx
      • examples/ts-react-chat/src/components/DraftPreview.tsx
      • examples/ts-react-chat/src/components/FileTreePanel.tsx
      • examples/ts-react-chat/src/components/Header.tsx
      • examples/ts-react-chat/src/lib/diff-extract.ts
      • examples/ts-react-chat/src/lib/shiki/highlighter.ts
      • examples/ts-react-chat/src/lib/shiki/theme.ts
      • examples/ts-react-chat/src/lib/workflows/article-workflow.ts
      • examples/ts-react-chat/src/lib/workflows/orchestrator.ts
      • examples/ts-react-chat/src/routeTree.gen.ts
      • examples/ts-react-chat/src/routes/api.orchestration.ts
      • examples/ts-react-chat/src/routes/api.workflow.ts
      • examples/ts-react-chat/src/routes/orchestration.tsx
      • examples/ts-react-chat/src/routes/workflow.tsx
      • examples/ts-react-chat/src/styles.css
      • knip.json
      ✅ Files skipped from review due to trivial changes (7)
      • docs/tools/tools.md
      • docs/chat/agentic-cycle.md
      • docs/api/ai-orchestration.md
      • docs/structured-outputs/multi-turn.md
      • docs/orchestration/overview.md
      • docs/orchestration/refining-across-runs.md
      • docs/orchestration/approvals.md
    7. Actionable comments posted: 4

      ♻️ Duplicate comments (1)
      packages/typescript/ai-orchestration/src/run-store/in-memory.ts (1)

      32-61: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

      Run teardown still drops live state without unblocking paused workflows.

      TTL expiry and deleteRun remove live entries, but they don’t abort the live controller or resolve/reject a pending approval wait, so paused generators can hang/leak.

      🔧 Suggested patch
         const expirations = new Map<string, NodeJS.Timeout>()
       
      +  function teardownLive(runId: string) {
      +    const l = live.get(runId)
      +    if (!l) return
      +    try {
      +      l.abortController.abort()
      +    } catch {}
      +    if (l.approvalResolver) {
      +      l.approvalResolver({
      +        approved: false,
      +        approvalId: '',
      +        feedback: 'run terminated',
      +      })
      +    }
      +    live.delete(runId)
      +  }
      +
         function scheduleExpiry(runId: string) {
           const existing = expirations.get(runId)
           if (existing) clearTimeout(existing)
           const handle = setTimeout(() => {
             runs.delete(runId)
      -      live.delete(runId)
      +      teardownLive(runId)
             stepLogs.delete(runId)
             expirations.delete(runId)
           }, ttl)
           expirations.set(runId, handle)
         }
      @@
           deleteRun(runId, _reason) {
             runs.delete(runId)
      -      live.delete(runId)
      +      teardownLive(runId)
             stepLogs.delete(runId)
             const handle = expirations.get(runId)
             if (handle) clearTimeout(handle)
             expirations.delete(runId)
             return Promise.resolve()
           },
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts` around lines
      32 - 61, The TTL expiry handler in scheduleExpiry and the deleteRun
      implementation remove entries from runs/live/stepLogs but never notify the live
      controller or settle any pending approval waiters, causing paused generators to
      hang; update both the timeout callback in scheduleExpiry and the deleteRun
      function to first retrieve the live entry (live.get(runId)), and if present call
      the live controller's cancellation/unblock API (e.g., controller.abort() or
      controller.cancel()) and settle any stored approval promise (resolve/reject it
      with a consistent Error like "run deleted" or "run expired"), then proceed to
      clear timeouts and delete the maps; ensure setRunState still calls
      scheduleExpiry so expiry path is covered.
      🧹 Nitpick comments (2)
      packages/typescript/ai-orchestration/tests/engine.primitives.test.ts (1)

      304-306: ⚡ Quick win

      UUID assertion is not v4-specific.

      The current pattern allows non-v4 UUIDs while the test intent says v4.

      Suggested regex
      -    expect(recordedId).toMatch(
      -      /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,
      -    )
      +    expect(recordedId).toMatch(
      +      /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
      +    )
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/tests/engine.primitives.test.ts` around
      lines 304 - 306, The test currently asserts recordedId against a generic UUID
      regex; change it to validate a v4 UUID specifically by using a v4-specific
      pattern or the project's UUID validator (e.g., assert / validate via the uuid
      library) for the recordedId variable in engine.primitives.test.ts; update the
      expect(recordedId).toMatch(...) to a regex that enforces the v4 variant (correct
      hex and the '4' in the version nibble and the appropriate variant bits) or
      replace the regex check with a call like isV4(recordedId) if a helper exists.
      packages/typescript/ai-orchestration/tests/engine.timeout.test.ts (1)

      206-250: ⚡ Quick win

      This test doesn’t reliably prove retry short-circuiting.

      callCount is never incremented, and Line 249 (< 200) can still pass with all retries. The assertion is currently too permissive for the stated behavior.

      Suggested tightening
               try {
                 yield* step(
                   'timing-out',
      -            () => new Promise(() => {}), // never resolves
      +            () =>
      +              new Promise<void>(() => {
      +                callCount++
      +              }), // never resolves
                   {
                     timeout: 20,
                     retry: {
      @@
      -      // allow generous slack here for CI noise.
      -      expect(elapsed).toBeLessThan(200)
      +      expect(elapsed).toBeLessThan(120)
      +      expect(callCount).toBe(1)
      @@
      -      expect(finished).toBeDefined()
      +      expect(finished?.output.caughtImmediately).toBe(true)
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/typescript/ai-orchestration/tests/engine.timeout.test.ts` around
      lines 206 - 250, The test never increments callCount so it can't prove retry
      short-circuiting; modify the workflow step function passed to step(...) (the
      anon function that returns new Promise(() => {})) to increment callCount each
      invocation (so callCount reflects attempts), then replace or augment the
      elapsed-based assertion with a deterministic check such as
      expect(callCount).toBe(1) (or assert caughtImmediately is true) after
      collect(...) completes; this uses the existing wf/step, callCount, collect,
      runWorkflow and StepTimeoutError symbols to observe that retries were
      short-circuited rather than relying on the flaky elapsed < 200 timing check.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In `@packages/typescript/ai-orchestration/src/engine/fingerprint.ts`:
      - Around line 38-40: The current fingerprint uses join(',') which can collide
      when patch names contain commas; instead serialize the sorted patches
      unambiguously before feeding fnv1a64—e.g., replace the join(',') usage with a
      robust serializer like JSON.stringify(sorted) (or another deterministic
      escaping) so the input to fnv1a64 (referenced here as workflow.patches, sorted,
      and fnv1a64) cannot collide.
      
      In `@packages/typescript/ai-orchestration/src/server/parse-request.ts`:
      - Around line 49-51: The returned params currently include both approval and
      signalDelivery which allows ambiguous downstream behavior; modify the
      normalization in parse-request.ts so that when body.signal is present you do not
      forward body.approval (e.g., compute a normalizedApproval = body.signal ?
      undefined : body.approval or set approval: body.signal ? undefined :
      body.approval) and continue to set signalDelivery: body.signal and input:
      body.input; update the object construction that currently references approval,
      signalDelivery, input to use this normalized approval value so signal takes
      precedence over approval.
      
      In `@packages/typescript/ai-orchestration/tests/engine.cas.test.ts`:
      - Around line 33-71: Test never performs the duplicate delivery step; after the
      first runWorkflow call that delivers signalDelivery with signalId 'same-id' you
      must call runWorkflow again with the same runId and signalDelivery: { signalId:
      'same-id', payload: { ok: true } } (using the same inMemoryRunStore) and collect
      its events, then assert the duplicate attempt returns the existing
      record/idempotent result (e.g., verify the returned events still include
      RUN_FINISHED and/or that the duplicate response indicates the existing delivery
      rather than creating a new one). Use the same helpers shown (runWorkflow,
      collect, inMemoryRunStore, signalDelivery) and add an expect on the second
      collect to confirm idempotent behavior.
      
      In `@packages/typescript/ai-orchestration/tests/engine.idempotency.test.ts`:
      - Around line 162-206: The test "persists signalDelivery.signalId on the
      resulting step record" is incomplete (ends with a `void 0` no-op) and either
      needs to be finished or skipped; replace the `void 0` placeholder by
      implementing the verification using the same pattern as the later working test:
      use the defined workflow `wf`, the `inMemoryRunStore()` `store`, call
      `collect(runWorkflow(...))` to start and pause, then resume with `runWorkflow`
      passing `signalDelivery: { signalId: 'sig-abc-123', payload: {...} }`, and
      assert that the persisted step record in `store` contains the `signalId` (or
      alternatively mark the test with `.skip`/`.todo` to reflect it's intentionally
      incomplete) — look for usages of `runWorkflow`, `collect`, `inMemoryRunStore`,
      and the test name to place the assertion or skip.
      
      ---
      
      Duplicate comments:
      In `@packages/typescript/ai-orchestration/src/run-store/in-memory.ts`:
      - Around line 32-61: The TTL expiry handler in scheduleExpiry and the deleteRun
      implementation remove entries from runs/live/stepLogs but never notify the live
      controller or settle any pending approval waiters, causing paused generators to
      hang; update both the timeout callback in scheduleExpiry and the deleteRun
      function to first retrieve the live entry (live.get(runId)), and if present call
      the live controller's cancellation/unblock API (e.g., controller.abort() or
      controller.cancel()) and settle any stored approval promise (resolve/reject it
      with a consistent Error like "run deleted" or "run expired"), then proceed to
      clear timeouts and delete the maps; ensure setRunState still calls
      scheduleExpiry so expiry path is covered.
      
      ---
      
      Nitpick comments:
      In `@packages/typescript/ai-orchestration/tests/engine.primitives.test.ts`:
      - Around line 304-306: The test currently asserts recordedId against a generic
      UUID regex; change it to validate a v4 UUID specifically by using a v4-specific
      pattern or the project's UUID validator (e.g., assert / validate via the uuid
      library) for the recordedId variable in engine.primitives.test.ts; update the
      expect(recordedId).toMatch(...) to a regex that enforces the v4 variant (correct
      hex and the '4' in the version nibble and the appropriate variant bits) or
      replace the regex check with a call like isV4(recordedId) if a helper exists.
      
      In `@packages/typescript/ai-orchestration/tests/engine.timeout.test.ts`:
      - Around line 206-250: The test never increments callCount so it can't prove
      retry short-circuiting; modify the workflow step function passed to step(...)
      (the anon function that returns new Promise(() => {})) to increment callCount
      each invocation (so callCount reflects attempts), then replace or augment the
      elapsed-based assertion with a deterministic check such as
      expect(callCount).toBe(1) (or assert caughtImmediately is true) after
      collect(...) completes; this uses the existing wf/step, callCount, collect,
      runWorkflow and StepTimeoutError symbols to observe that retries were
      short-circuited rather than relying on the flaky elapsed < 200 timing check.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: defaults

      Review profile: CHILL

      Plan: Pro

      Run ID: 31b1c1cb-f2c1-479a-8cf6-cf2edba5fd8e

      📥 Commits

      Reviewing files that changed from the base of the PR and between 0f662123642802e1c0f3ee7bf6ceccf936765650 and 5486c02be2701abc0cdc1883e3a1635d35327393.

      📒 Files selected for processing (34)
      • docs/config.json
      • docs/getting-started/workflows.md
      • packages/typescript/ai-client/src/index.ts
      • packages/typescript/ai-client/src/workflow-client.ts
      • packages/typescript/ai-orchestration/README.md
      • packages/typescript/ai-orchestration/src/define/define-workflow.ts
      • packages/typescript/ai-orchestration/src/engine/emit-events.ts
      • packages/typescript/ai-orchestration/src/engine/fingerprint.ts
      • packages/typescript/ai-orchestration/src/engine/run-workflow.ts
      • packages/typescript/ai-orchestration/src/index.ts
      • packages/typescript/ai-orchestration/src/primitives/now.ts
      • packages/typescript/ai-orchestration/src/primitives/patched.ts
      • packages/typescript/ai-orchestration/src/primitives/sleep.ts
      • packages/typescript/ai-orchestration/src/primitives/step.ts
      • packages/typescript/ai-orchestration/src/primitives/uuid.ts
      • packages/typescript/ai-orchestration/src/primitives/wait-for-signal.ts
      • packages/typescript/ai-orchestration/src/registry/select-version.ts
      • packages/typescript/ai-orchestration/src/run-store/in-memory.ts
      • packages/typescript/ai-orchestration/src/server/parse-request.ts
      • packages/typescript/ai-orchestration/src/types.ts
      • packages/typescript/ai-orchestration/tests/engine.attach.test.ts
      • packages/typescript/ai-orchestration/tests/engine.cas.test.ts
      • packages/typescript/ai-orchestration/tests/engine.durability.test.ts
      • packages/typescript/ai-orchestration/tests/engine.idempotency.test.ts
      • packages/typescript/ai-orchestration/tests/engine.patched.test.ts
      • packages/typescript/ai-orchestration/tests/engine.primitives.test.ts
      • packages/typescript/ai-orchestration/tests/engine.publisher.test.ts
      • packages/typescript/ai-orchestration/tests/engine.retry.test.ts
      • packages/typescript/ai-orchestration/tests/engine.signals.test.ts
      • packages/typescript/ai-orchestration/tests/engine.smoke.test.ts
      • packages/typescript/ai-orchestration/tests/engine.timeout.test.ts
      • packages/typescript/ai-orchestration/tests/in-memory-store.test.ts
      • packages/typescript/ai-orchestration/tests/registry.test.ts
      • packages/typescript/ai-react/src/use-workflow.ts
      ✅ Files skipped from review due to trivial changes (2)
      • packages/typescript/ai-orchestration/src/primitives/uuid.ts
      • packages/typescript/ai-orchestration/README.md
    8. socket-security[bot](GitHub profile, opens in a new tab)commented

      Review the following changes in direct dependencies. Learn more about Socket for GitHub.

      Diff Package Supply Chain
      Security
      Vulnerability Quality Maintenance License
      Addedshiki@​4.1.01001007794100
      Added@​tanstack/​workflow-core@​0.0.2781009892100

      View full report

    9. Closing as superseded by #979. We are standardizing on TanStack Workflow as the durable runtime and on one async handler/context authoring model. The generator/yield* API and duplicate orchestration runtime/store will not move forward.

      The AG-UI, client, persistence, and interrupt questions are carried into the new RFC. Thank you for the extensive prototype work; it directly informed the ownership boundaries and decisions in #979.

    10. tannerlinsley closed this

Sign in to join this conversation.