Skip to content

feat(sdk): add reasoning effort option to prompt/skill/task - #69

Merged
FredKSchott merged 2 commits into
withastro:mainfrom
0xnavarro:feat/reasoning-effort
May 8, 2026
Merged

FredKSchott merged 2 commits into
withastro:mainfrom
0xnavarro:feat/reasoning-effort

Conversation

@0xnavarro

Copy link
Copy Markdown
Contributor

Add reasoning option to prompt(), skill(), task(), init(), and role frontmatter

Why this PR

Closes a small gap between pi-ai and Flue:

  • pi-ai already supports SimpleStreamOptions.reasoning across every
    reasoning-capable provider (Anthropic, OpenAI Completions/Responses,
    Google, Google Vertex, Azure, Bedrock, Mistral, OpenRouter, …). Each
    provider clamps the requested level against Model.thinkingLevelMap.
  • pi-agent-core already exposes state.thinkingLevel and forwards it as
    SimpleStreamOptions.reasoning on every stream call
    (agent.js:createLoopConfig).
  • Flue surfaces neither. Today, reasoning effort is fixed per model in the
    registry, so serving N tiers (e.g. a cheap classifier at low, a careful
    auditor at xhigh) from one deployment requires N model entries or N
    deployments.

This PR wires the existing underlying capability onto Flue's public surface
so a single agent can pick effort per call.

Motivation

The use case that drove this: orchestration systems that call the same
model with different depth-of-thought depending on the task, without
multiplying deployments. With this change, an agent can route cheap work
to low and critical audits to xhigh on the same model, in the same
session, with no additional infra.

API

const agent = await init({
  model: 'anthropic/claude-opus-4-7',
  reasoning: 'medium', // default for every call
});
const session = await agent.session();

await session.prompt('Summarize this thread.');                    // medium
await session.prompt('Audit this diff.', { reasoning: 'xhigh' });  // xhigh
await session.task('Research this library.', { reasoning: 'high' });

Role files pick up reasoning: from frontmatter:

---
model: anthropic/claude-opus-4-7
reasoning: high
---

Precedence

call > role > session > agent — identical to model.

Validation

  • Passing reasoning against a model whose pi-ai metadata reports
    reasoning: false throws a [flue]-prefixed runtime Error naming the
    field and the model (no dedicated error class — aligns with how the rest
    of the SDK surfaces config errors).
  • 'off' is valid only at init / role / session tiers. Passing it per-call
    throws; per-call code should pick a concrete effort or omit the option
    entirely.
  • Unknown levels in role frontmatter throw at build time.
  • pi-ai's clampThinkingLevel silently maps unsupported levels (e.g.
    xhigh on a model without that mapping) to the closest supported one.
    Flue does not intercept that.

Forwarding

The resolved level is written to harness.state.thinkingLevel before each
prompt / skill / task call and restored on exit, including on validation
failure (the harness's previous state is never mutated until every resolve
succeeds). pi-agent-core then maps the level to SimpleStreamOptions.reasoning
on every stream call.

Minor refactor inside withScopedRuntime

Adding strict validation meant resolveThinkingLevelForCall can now throw
from the middle of the scoped-runtime setup. In the pre-existing code, the
harness state (model, systemPrompt, tools) was mutated as each value
was resolved, so a throw between mutations left the harness half-updated
and the try/finally never ran (the throw happened before the try).
That would have been a regression introduced by this PR.

The fix is local and mechanical: resolve every value into local variables
first, then capture previous* snapshots, then mutate all four
state.* fields together, then enter the try { ... } finally { restore }
block. Same variables (previousTools, previousModel,
previousSystemPrompt), same restore logic, same number of
this.harness.state.* accesses — just reordered so the mutation is
atomic. A test ('leaves harness state intact when reasoning validation fails') pins the rollback contract.

If you'd prefer the refactor to land as a separate commit or a follow-up
PR, happy to split it out.

Compaction

Compaction has its own default of 'high' when the model supports reasoning
(keeps summary quality, which feeds every future turn). Setting
reasoning: 'off' at the agent level also disables reasoning inside
compaction. Any other agent-level value leaves compaction at its default —
per-call / role / session reasoning intentionally does not propagate to
compaction, because that's internal work driven by agent config, not the
current user call.

Tests

37 tests across three files (pnpm run test from packages/sdk/):

  • test/reasoning.test.ts — unit tests for resolveCallReasoning and
    parseReasoningFrontmatter (precedence, "off" semantics, validation,
    frontmatter parsing).
  • test/reasoning-forwarding.test.ts — integration tests with a fake
    streamFn capturing SimpleStreamOptions for prompt(), skill(), and
    task(); covers role × session × agent precedence on the wire, harness
    state rollback on validation failure, and session-reasoning inheritance
    across nested task sessions.
  • test/compaction-reasoning.test.ts — semantic mirror + source-text anchor
    for the compaction reasoning branch.

Out of scope

  • thinkingBudgets (Anthropic/Gemini token-based budgets) — follow-up.
  • Vercel AI Gateway / OpenRouter-specific routing knobs — follow-up.
  • Provider auto-fallback beyond pi-ai's clampThinkingLevel — keeping
    strict for now.
  • HTTP body snapshot of the outgoing Responses API request — would require
    exposing a mockable base-URL harness; the streamFn-level tests cover
    the SDK boundary.

Notes for the maintainer

  • Positional parameters on createBuiltinTools (6) and runTaskForTool
    (7) grew with this PR. A context-object refactor makes sense the next
    time those signatures are touched; deferred here to keep the diff
    focused.
  • The test runner uses a small in-process harness (test/run.ts) because
    Node 22's --test flag combined with --experimental-transform-types
    silently drops describe blocks when the file transitively imports code
    using TS parameter properties (observed with src/result.ts). Running
    the suite in-process sidesteps the subprocess isolation bug. Happy to
    switch to a different runner (tsx, vitest) if you prefer.
  • No Changeset file because the repo doesn't use @changesets/cli — all
    the release notes content lives here in the PR body.

@0xnavarro

Copy link
Copy Markdown
Contributor Author

Two design questions I flagged in the PR body that are worth explicit maintainer input:

  1. Strict validation vs. silent pass-through. Flue currently throws a [flue]-prefixed error when reasoning is passed against a model with Model.reasoning === false. pi-ai would silently accept it and the provider-level branch would just skip the field. I went strict because it matches how Flue already treats invalid roles/models, but if you prefer the silent semantics it's a one-line change in resolveCallReasoning.

  2. The withScopedRuntime reorder. I inlined it in this PR because the new strict validation can now throw mid-setup and the pre-existing mutation order left the harness half-updated on failure. If you'd rather land it as a separate commit or a follow-up PR I'm happy to split.

Happy to iterate on either. Also open to splitting this into an issue + PR if that's the preferred workflow for feature work.

0xnavarro and others added 2 commits May 8, 2026 00:36
Exposes per-call `reasoning` on PromptOptions, SkillOptions, TaskOptions,
plus defaults on AgentInit, SessionOptions, and role frontmatter.
Precedence: call > role > session > agent, mirroring `model`.

pi-ai already supports SimpleStreamOptions.reasoning across every
reasoning-capable provider, and pi-agent-core already forwards
state.thinkingLevel there. Flue now surfaces that capability so a single
agent can pick effort per call instead of requiring N deployments or
N model IDs for N tiers.

Validation matches existing SDK conventions: a [flue]-prefixed runtime
Error when the resolved model reports reasoning: false; 'off' is
init/role/session-only (per-call 'off' throws); unknown levels in role
frontmatter throw at build time.

Compaction honours an agent-level 'off' opt-out but otherwise keeps its
high default (summary quality feeds every future turn and is orthogonal
to per-call effort).

withScopedRuntime is reordered so all resolutions happen before any
harness.state mutation. Adding strict validation made
resolveThinkingLevelForCall throwable from mid-setup; without the
reorder, a throw between mutations would leave the harness half-updated
and the try/finally never run. Same previousTools/previousModel/
previousSystemPrompt variables, same restore logic — just atomic.

Tests: 37 across unit (resolver + frontmatter parser), integration
(streamFn fake capturing SimpleStreamOptions on all three call types,
harness-state rollback on validation failure, nested task inheritance),
and compaction (semantic mirror + source-text anchor).
pi-ai already supports SimpleStreamOptions.reasoning across every
reasoning-capable provider, and pi-agent-core already exposes
state.thinkingLevel and forwards it on every stream call. Flue surfaced
neither, so reasoning effort was effectively fixed per model in the
registry — serving N tiers from one deployment required N model entries
or N deployments.

Adds a thinkingLevel knob with the same precedence chain as model:
per-call > role > agent > 'off'. One deployment can now serve a cheap
classifier at 'low' and a careful auditor at 'high' from the same
model entry.

Surfaces:
- AgentInit.thinkingLevel — agent-wide default
- Role frontmatter `thinkingLevel:` — role-level override
- PromptOptions / SkillOptions / TaskOptions — per-call override
- Re-exported ThinkingLevel from @flue/sdk and @flue/sdk/client

Implementation:
- Session seeds harness initial state from config.thinkingLevel ?? 'off'
- withScopedRuntime snapshots/restores state.thinkingLevel alongside
  model, systemPrompt, and tools — same pattern, no surprises
- Tasks inherit the parent's resolved level, mirroring inheritedModel
- Frontmatter parser validates against an exhaustive set tied to the
  pi-agent-core type via `satisfies Record<ThinkingLevel, true>`, so
  upstream changes fail to type-check instead of silently rejecting
  valid values
- pi-ai handles per-provider clamping; Flue passes through

Compaction consistency: the turn-prefix summary call now also sets
reasoning: 'high' on reasoning-capable models, matching the main
summary call. Compaction stays decoupled from the user's thinkingLevel
so a 'low' classifier still gets quality summaries.

Drive-by fix: build-plugin-node.ts had `'\n\n'` inside a template
literal, producing a literal newline mid-string in the emitted entry
point and breaking every `flue build`. Escaped to `'\\n\\n'`.

Example: examples/hello-world/.flue/agents/with-thinking.ts +
roles/auditor.md exercise all three layers.
@FredKSchott
FredKSchott force-pushed the feat/reasoning-effort branch from c918cfa to ec5c809 Compare May 8, 2026 07:38
@FredKSchott

Copy link
Copy Markdown
Member

Thanks for the contribution! I went with a simpler implementation, committed to the PR.

@FredKSchott
FredKSchott merged commit 8c5a24d into withastro:main May 8, 2026
cursor Bot pushed a commit to getsentry/toolkit that referenced this pull request May 8, 2026
The Flue issue-triage workflow fails on every multi-turn call:

  [flue] Error: skill("issue-triage") failed: 404 Item with id
  'rs_...' not found. Items are not persisted when `store` is set
  to false.

Root cause is upstream and not patchable from here:

- Flue 0.3.11 (latest) drives every chat through @mariozechner/pi-ai
  with `thinkingLevel: "off"` hardcoded, no public option to override.
- pi-ai 0.73.1 is the last version under that npm scope (the project
  migrated to @earendil-works/pi-ai 0.74.0 on 2026-05-07, which Flue
  does not yet depend on).
- pi-ai's OpenAI Responses provider hardcodes `store: false` and,
  for reasoning models, only requests `include:
  ["reasoning.encrypted_content"]` when a reasoning effort is passed.
  With Flue passing none, gpt-5 emits `rs_*` items that have neither
  server-side persistence nor inline encrypted payloads, and the next
  turn 404s.
- The fix that would let us keep gpt-5 (Flue exposing `reasoning` /
  `thinkingLevel` per call, withastro/flue#69) was merged into Flue
  main on 2026-05-08 but is not yet released. The pi-ai-side fix
  (earendil-works/pi#1504, defaulting `store: true`) was auto-closed
  and never merged.

Until one of those lands, drop the default to `openai/gpt-4.1` — a
non-reasoning model on the same OpenAI Responses path that never
emits `rs_*` items, so multi-turn replay works without any patch.
Operators can still override via the `FLUE_TRIAGE_MODEL` repo
variable; once Flue picks up `reasoning` plumbing we can flip the
default back to `openai/gpt-5` and pass `reasoning: "minimal"`.

Refs:
- earendil-works/pi#3369
- earendil-works/pi#1504
- withastro/flue#69

Co-Authored-By: Cursor Agent <[email protected]>
cursor Bot pushed a commit to getsentry/toolkit that referenced this pull request May 8, 2026
pi-ai (the LLM client Flue uses) hardcodes store: false on the OpenAI
Responses API. With reasoning models (gpt-5, o-series, ...), every
multi-turn call 404s because pi-ai replays the rs_* reasoning IDs from
the previous turn and OpenAI cannot look them up when nothing was
persisted.

The supported escape hatch is to ask OpenAI to inline the encrypted
reasoning blob via include: ["reasoning.encrypted_content"]. pi-ai's
convertResponsesMessages then ships that blob back on replay, so no
server-side persistence is needed.

@flue/sdk 0.3.11 doesn't expose a reasoning/thinkingLevel knob, so we
reach into the Session's pi-agent-core harness and install pi-ai's
existing onPayload hook to add the include flag for any
openai-responses / azure-openai-responses reasoning model. The hook is
a no-op for non-reasoning models and other providers.

This unblocks gpt-5 as the default triage model. FLUE_TRIAGE_MODEL
still overrides if we want to pin a different model.

Verified by reconstructing the harness wiring (Agent + getModel) and
asserting:
  1. The hook adds reasoning.encrypted_content to gpt-5 payloads.
  2. Non-reasoning models (gpt-4.1) are left untouched.
  3. pi-agent-core forwards onPayload into streamFn, which is the same
     code path pi-ai's openai-responses provider invokes after building
     the request.

Refs: earendil-works/pi#3369, earendil-works/pi#1504, withastro/flue#69.

Co-Authored-By: Cursor Agent <[email protected]>
dcramer added a commit to getsentry/toolkit that referenced this pull request May 8, 2026
#942)

<!-- CURSOR_AGENT_PR_BODY_BEGIN -->
## Problem

The Flue issue-triage workflow ([failing
run](https://github.com/getsentry/sentry-mcp/actions/runs/25576059392/job/75083371051))
404s on the first multi-turn round-trip after a tool call:

```
[flue] Error: [flue] skill("issue-triage") failed: 404 Item with id 'rs_...' not found.
Items are not persisted when `store` is set to false.
```

Same root cause every framework keeps tripping on (vercel/ai#7543,
openai/openai-agents-python#2265, openclaw/openclaw#16803,
earendil-works/pi#3369): `@mariozechner/pi-ai` — the LLM client Flue uses
internally — hardcodes `store: false` on the OpenAI Responses API and
then replays `rs_*` reasoning IDs from the previous turn. Without
server-side persistence the IDs don't resolve and OpenAI 404s.

## Why we don't downgrade to a non-reasoning model

The previous revision worked around this by switching the default to
`openai/gpt-4.1`. That bypasses the bug (gpt-4.1 is `reasoning: false`
in pi-ai's registry, so the entire reasoning code path is skipped), but
it also throws away gpt-5's reasoning quality on a hook whose whole job
is judgment calls (duplicate detection, severity, validity). We want to
stay on gpt-5.

## Why we don't patch pi-ai or fork it

- The earlier `pnpm patch` against `@mariozechner/[email protected]` flipped
the hardcoded `store: false` to `true`. That works narrowly but vendors
an upstream library mid-version, so any future bump silently invalidates
the patch.
- The same upstream PR (earendil-works/pi#1504) was
[auto-closed](earendil-works/pi#1504) by the
maintainer; we shouldn't carry it locally.
- pi-ai migrated to `@earendil-works/[email protected]` (May 7) but Flue
0.3.11 still depends on `@mariozechner/pi-ai`, so an override doesn't
help.
- The Flue PR that exposes a `reasoning`/`thinkingLevel` knob
([withastro/flue#69](withastro/flue#69)) is
merged into `main` but unreleased.

## Fix

OpenAI's documented escape hatch for `store: false` + reasoning is
`include: ["reasoning.encrypted_content"]`. With it, OpenAI returns the
full encrypted reasoning blob inline; pi-ai already serializes that blob
into `thinkingSignature` and ships it back on replay
(`convertResponsesMessages` in `openai-responses-shared.js`). No
`store=true`, no provider-side retention, no patch.

`@flue/sdk` 0.3.11 has no public knob to set this, but the underlying
pi-agent-core `Agent` does: it forwards an `onPayload` hook into
`streamFn`, and pi-ai's `openai-responses` provider invokes
`options?.onPayload?.(params, model)` after building the request. So we
reach into the Session's harness once, install a tiny `onPayload`, and
let pi-ai do the rest.

The hook is a no-op for non-reasoning models and for any provider that
isn't OpenAI Responses / Azure OpenAI Responses, so flipping
`FLUE_TRIAGE_MODEL` to a Claude or non-reasoning model still works
unchanged. We can drop the hook the moment Flue ships #69 or pi-ai stops
hardcoding `store: false`.

### Files

- `.flue/agents/issue-triage.ts` — install
`enableEncryptedReasoning(session)` and switch the default back to
`openai/gpt-5`.
- `docs/flue-hooks.md` — document the hook, the new default, and the
upstream tracking issues.

## Verification

- `pnpm install` —
`node_modules/.pnpm/@mariozechner[email protected]_…/dist/providers/openai-responses.js`
is back to unmodified upstream `store: false`; no `patches/` directory.
- `pnpm run tsc && pnpm run lint && pnpm run test` — all green.
- `pnpm exec flue build --target node` — agent compiles;
`dist/server.mjs` contains the bundled hook (`enableEncryptedReasoning`,
`harness.onPayload`, the literal `"reasoning.encrypted_content"`).
- Reconstructed the harness wiring with `pi-agent-core`'s `Agent` +
`pi-ai`'s `getModel`. Confirmed:
1. The hook adds `reasoning.encrypted_content` to a real
`getModel("openai", "gpt-5")` payload.
2. The same hook leaves `getModel("openai", "gpt-4.1")` payloads
untouched (no `include` field).
3. `pi-agent-core.createLoopConfig` forwards `harness.onPayload` into
the `streamFn` options object — i.e. exactly the path pi-ai's
openai-responses provider invokes after `buildParams`.

End-to-end execution of the triage workflow itself still requires
`OPENAI_API_KEY` / `GH_TOKEN`, which aren't available in this
environment. Once merged, re-running on issue #941 (or any new issue)
will exercise the gpt-5 path with the encrypted reasoning replay.
<!-- CURSOR_AGENT_PR_BODY_END -->

[Slack
Thread](https://sentry.slack.com/archives/C08J1NSPU6S/p1778269683926819?thread_ts=1778269683.926819&cid=C08J1NSPU6S)

<div><a
href="https://cursor.com/agents/bc-b3537aa0-e7d2-5ed6-accf-3446aae3ed2f"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-web-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-web-light.png"><img
alt="Open in Web" width="114" height="28"
src="https://cursor.com/assets/images/open-in-web-dark.png"></picture></a>&nbsp;<a
href="https://cursor.com/background-agent?bcId=bc-b3537aa0-e7d2-5ed6-accf-3446aae3ed2f"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cursor.com/assets/images/open-in-cursor-dark.png"><source
media="(prefers-color-scheme: light)"
srcset="https://cursor.com/assets/images/open-in-cursor-light.png"><img
alt="Open in Cursor" width="131" height="28"
src="https://cursor.com/assets/images/open-in-cursor-dark.png"></picture></a>&nbsp;</div>

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Junior (bot) <junior[bot]@sentry.io>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants