Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
fix(sam): bound turn size, meter spend per step, upgrade Think to 0.17.0 (#571)
Ben Senescu2028172555c1
diff --git a/package.json b/package.jsonindex 604dba32..78fdfbbc 100644--- a/package.json+++ b/package.json@@ -76,7 +76,7 @@"dependencies": {"@ai-sdk/react": "^3.0.211","@better-auth/api-key": "1.6.22",- "@cloudflare/think": "0.15.1",+ "@cloudflare/think": "0.17.0","@cloudflare/workers-oauth-provider": "^0.10.2","@every-app/sdk": "^0.1.14","@modelcontextprotocol/client": "2.0.0",@@ -90,7 +90,7 @@"@tanstack/react-router-devtools": "^1.167.0","@tanstack/react-start": "^1.168.26","@tanstack/react-table": "^8.21.3",- "agents": "0.20.1",+ "agents": "0.22.0","ai": "^6.0.199","autumn-js": "^1.2.33","better-auth": "^1.6.22",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex dfa8d0b6..ed312346 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -31,8 +31,8 @@ importers:specifier: 1.6.22version: 1.6.22(8d706e213363f271470d19db6adbe48a)'@cloudflare/think':- specifier: 0.15.1- version: 0.15.1(@ai-sdk/[email protected])(@ai-sdk/[email protected]([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected](@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@cloudflare/[email protected])(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ specifier: 0.17.0+ version: 0.17.0(@ai-sdk/[email protected])(@ai-sdk/[email protected]([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected](@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])'@cloudflare/workers-oauth-provider':specifier: ^0.10.2version: 0.10.2@@ -73,8 +73,8 @@ importers:specifier: ^8.21.3agents:- specifier: 0.20.1- version: 0.20.1(@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@cloudflare/[email protected])(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ specifier: 0.22.0+ version: 0.22.0(@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])ai:specifier: ^6.0.199version: 6.0.199([email protected])@@ -690,16 +690,14 @@ packages:'@cloudflare/[email protected]':resolution: {integrity: sha512-6ZMKQZqdZeommh8LGFK5C2rep4byJfCuyjR4NBdMqn2wW9tbeDJORfDhP/No75MLx8nJeWdgeXvq3D2Ijpa0XA==}- '@cloudflare/[email protected]':- resolution: {integrity: sha512-BAMVRoBArhszewE0ONcq6sNxfB0QsXIZkhdZYl+6hXdUC/tHShRK1ZDaGhHuWhDBBGYsPY07ploFy4WOmCLkwQ==}- hasBin: true+ '@cloudflare/[email protected]':+ resolution: {integrity: sha512-tnfMZSqSz1dhfBx0io/mXMJE2huwJc2kTPAkx55y1bTUQwt9A2uONBmN1FixNsI9DFp1zXJDzcO0juGFKfTyLQ==}peerDependencies:'@ai-sdk/react': ^3.0.0 || ^4.0.0'@chat-adapter/telegram': ^4.29.0- agents: '>=0.18.0 <1.0.0'+ agents: '>=0.20.2 <1.0.0'ai: ^6.0.0 || ^7.0.0react: ^19.0.0- vite: '>=6 <9'zod: ^4.0.0peerDependenciesMeta:'@ai-sdk/react':@@ -708,8 +706,6 @@ packages:optional: truereact:optional: true- vite:- optional: true'@cloudflare/[email protected]':resolution: {integrity: sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==}@@ -3047,9 +3043,8 @@ packages:resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==}engines: {node: '>= 8.0.0'}- resolution: {integrity: sha512-HQRYMeZpD3k8djYBH7atRPojZMee3NvmXkzsmMWXfdHZ94vMljmWqSsD1XZd70LovHyQrw6/R81AZZIsRiFM6Q==}- hasBin: true+ resolution: {integrity: sha512-dIy/BRdO5GSqdOIp0pmkcLmHCCxIKb4RBByXFXmXG6Nc6WBSNYRXoLLDvWj2fJAfi4l5/OndJjZuBAP0vW0DZQ==}peerDependencies:'@ai-sdk/react': ^3.0.0 || ^4.0.0'@cloudflare/codemode': '>=0.5.0'@@ -3082,6 +3077,8 @@ packages:optional: truejust-bash:optional: true+ react:+ optional: truevite:optional: true@@ -3206,10 +3203,6 @@ packages:resolution: {integrity: sha512-/djoAN709iY65ETD6LKCtyyEI04XIBP5xVvfmNxsEP0uJB5tyaGBztSryRr4HqMStr9R06PisQE7m9zDTXKu6g==}- resolution: {integrity: sha512-xLFICM6OgSMcysNHCgrhri7hpcn0TfuyU5KxtjpIAJAUuD0Bjph2pSkLgxjn45iQBjBxs4S5Fq+RmXhIYuQtNw==}- hasBin: true-resolution: {integrity: sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig==}@@ -3437,10 +3430,6 @@ packages:resolution: {integrity: sha512-xRwvIOMGrfOAnM1JYtqQImuaNtDEv9v6oIYAs4LIHwTiKee8uwvIi363igssOC0O5U04i4AlENs79LQLu9tEMw==}engines: {node: '>=20'}- resolution: {integrity: sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==}- engines: {node: '>=20'}-resolution: {integrity: sha512-dVzqDpPFYR9ApEC9e+JJshFJZXcw4HzM8W+3DHzO5oy9+8rLC53G7x6fEf9A7/gSuSCxuvndzui5qJKftfIM9A==}@@ -3519,10 +3508,6 @@ packages:engines: {node: '>=0.8'}hasBin: true- resolution: {integrity: sha512-C8+k9fPArd1B0nnDUV83Fjw7hzJyaY+LN4v3Va+k4enMlSw0ZvyJERjJwntcp+1Snos+sy07SQYpV+1k10zARQ==}- hasBin: true-resolution: {integrity: sha512-BoZaseYGXOo5j5HUwTaegIog3JJbuH4BbrY9A1ArLjXpy+RWb3mV28F/9Gv1dDA7E2L8kngWva4NWisnLTyfgQ==}engines: {node: '>=20'}@@ -4056,10 +4041,6 @@ packages:resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}engines: {node: '>=6.9.0'}- resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}- engines: {node: 6.* || 8.* || >= 10.*}-resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==}engines: {node: '>=18'}@@ -4952,11 +4933,6 @@ packages:resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==}engines: {node: '>= 0.8'}- resolution: {integrity: sha512-htgSwiBcBu9zIYLrsxBAOvdkjukHvncbTk0nDrJgfruvZ08rxtEN1Ab4T7j9osykP80Bq3zA2oWFd3ngc4Z9uw==}- peerDependencies:- '@cloudflare/workers-types': ^4.20260424.1-resolution: {integrity: sha512-1zToNyolZFK/7nuAw/K2bZrNzFqaZyRoCEkS+9vG6WSC5ikrN6qWRe96q6ImU51uptz2r+dAwSkwhJVdQi4LiA==}peerDependencies:@@ -6042,10 +6018,6 @@ packages:resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}engines: {node: '>=0.4'}- resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}- engines: {node: '>=10'}-resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}@@ -6054,14 +6026,6 @@ packages:engines: {node: '>= 14.6'}hasBin: true- resolution: {integrity: sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==}- engines: {node: ^20.19.0 || ^22.12.0 || >=23}-- resolution: {integrity: sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg==}- engines: {node: ^20.19.0 || ^22.12.0 || >=23}-resolution: {integrity: sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==}@@ -6669,26 +6633,21 @@ snapshots:- ai- zod- '@cloudflare/[email protected](@ai-sdk/[email protected])(@ai-sdk/[email protected]([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected](@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@cloudflare/[email protected])(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':+ '@cloudflare/[email protected](@ai-sdk/[email protected])(@ai-sdk/[email protected]([email protected])([email protected]))(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected](@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])':dependencies:'@ai-sdk/anthropic': 4.0.24([email protected])'@ai-sdk/openai': 4.0.24([email protected])'@cloudflare/codemode': 0.5.1(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected])'@cloudflare/shell': 0.4.3(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected])- agents: 0.20.1(@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@cloudflare/[email protected])(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ agents: 0.22.0(@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])ai: 6.0.199([email protected])- aywson: 0.0.16- create-think: 0.1.1just-bash: 3.0.2- smol-toml: 1.7.0workers-ai-provider: 4.0.0(@ai-sdk/[email protected]([email protected]))(@ai-sdk/[email protected]([email protected]))(@ai-sdk/[email protected])([email protected]([email protected]))- yargs: 18.0.0zod: 4.3.6optionalDependencies:'@ai-sdk/react': 3.0.211([email protected])([email protected])react: 19.2.4- vite: 7.3.6(@types/[email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- '@ai-sdk/google'- '@ai-sdk/provider'@@ -8648,7 +8607,7 @@ snapshots:dependencies:humanize-ms: 1.2.1- [email protected](@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@cloudflare/[email protected])(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]):+ [email protected](@ai-sdk/[email protected]([email protected])([email protected]))(@babel/[email protected])(@babel/[email protected])(@cloudflare/[email protected](@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))([email protected]([email protected]))([email protected]))(@modelcontextprotocol/[email protected])(@modelcontextprotocol/[email protected](@cfworker/[email protected])([email protected]))(@modelcontextprotocol/[email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]):dependencies:'@babel/plugin-proposal-decorators': 8.0.2(@babel/[email protected])'@cfworker/json-schema': 4.1.1@@ -8660,11 +8619,8 @@ snapshots:esbuild: 0.28.1mimetext: 3.0.28nanoid: 5.1.16- partyserver: 0.5.8(@cloudflare/[email protected])partysocket: 1.3.0([email protected])- react: 19.2.4yaml: 2.9.0- yargs: 18.0.0zod: 4.3.6optionalDependencies:'@ai-sdk/react': 3.0.211([email protected])([email protected])@@ -8672,12 +8628,12 @@ snapshots:ai: 6.0.199([email protected])just-bash: 3.0.2+ react: 19.2.4vite: 7.3.6(@types/[email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- '@babel/core'- '@babel/plugin-transform-runtime'- '@babel/runtime'- - '@cloudflare/workers-types'- rolldown@@ -8804,11 +8760,6 @@ snapshots:- dependencies:- chalk: 5.6.2- jsonc-parser: 3.3.1-dependencies:'@babel/core': 7.29.7@@ -9035,12 +8986,6 @@ snapshots:slice-ansi: 8.0.0string-width: 8.2.1- dependencies:- string-width: 7.2.0- strip-ansi: 7.2.0- wrap-ansi: 9.0.2-dependencies:'@types/node': 18.19.130@@ -9100,8 +9045,6 @@ snapshots:- [email protected]: {}-@@ -9612,8 +9555,6 @@ snapshots:- [email protected]: {}-@@ -10730,11 +10671,6 @@ snapshots:- [email protected](@cloudflare/[email protected]):- dependencies:- '@cloudflare/workers-types': 4.20260702.1- nanoid: 5.1.16-dependencies:event-target-polyfill: 0.0.4@@ -11885,23 +11821,10 @@ snapshots:- [email protected]: {}-- [email protected]: {}-- dependencies:- cliui: 9.0.1- escalade: 3.2.0- get-caller-file: 2.0.5- string-width: 7.2.0- y18n: 5.0.8- yargs-parser: 22.0.0-diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex b7b8c5a8..1fbe79e9 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,6 +1,13 @@minimumReleaseAge: 11520minimumReleaseAgeExclude:- "@every-app/*"+ # TEMPORARY (remove after 2026-09-05): the chat-agent framework upgrade+ # (@cloudflare/think 0.17.0, agents 0.22.0) was published 2026-08-27 —+ # hours shy of the 8-day window. Needed for the unconditional+ # durable-chat-recovery release that SAM's OOM guard (`onChatRecovery`+ # returning `{ continue: false }`) is written against.+ - "@cloudflare/think"+ - "agents"# TEMPORARY (remove after 2026-08-15): workers-oauth-provider 0.10.2 was# published 2026-08-07; needed for the MCP SDK v2 migration plus the# ChatGPT DCR client-auth-negotiation fix.diff --git a/src/client/features/sam/ChatComposer.tsx b/src/client/features/sam/ChatComposer.tsxindex fe635880..f5609480 100644--- a/src/client/features/sam/ChatComposer.tsx+++ b/src/client/features/sam/ChatComposer.tsx@@ -5,15 +5,18 @@ import {type FormEvent,type KeyboardEvent,} from "react";-import { ArrowUp, Loader2 } from "lucide-react";+import { ArrowUp, Loader2, Square } from "lucide-react";export function ChatComposer({busy,onSend,+ onStop,placeholder = "Ask Sam about your strategy or OpenSEO…",}: {busy: boolean;onSend: (text: string) => void;+ /** Cancels the running turn; while busy the send button becomes Stop. */+ onStop?: () => void;placeholder?: string;}) {const [value, setValue] = useState("");@@ -61,18 +64,29 @@ export function ChatComposer({placeholder={placeholder}className="max-h-40 flex-1 resize-none border-0 bg-transparent px-1 py-1 text-sm leading-relaxed outline-none placeholder:text-base-content/50 focus:outline-none"/>- <button- type="submit"- aria-label="Send message"- disabled={busy || !value.trim()}- className="btn btn-primary btn-circle btn-sm"- >- {busy ? (- <Loader2 className="size-4 animate-spin" />- ) : (- <ArrowUp className="size-4" />- )}- </button>+ {busy && onStop ? (+ <button+ type="button"+ aria-label="Stop"+ onClick={onStop}+ className="btn btn-neutral btn-circle btn-sm"+ >+ <Square className="size-3.5 fill-current" />+ </button>+ ) : (+ <button+ type="submit"+ aria-label="Send message"+ disabled={busy || !value.trim()}+ className="btn btn-primary btn-circle btn-sm"+ >+ {busy ? (+ <Loader2 className="size-4 animate-spin" />+ ) : (+ <ArrowUp className="size-4" />+ )}+ </button>+ )}</form>);}diff --git a/src/client/features/sam/SamConversation.tsx b/src/client/features/sam/SamConversation.tsxindex 62adfcec..c22df741 100644--- a/src/client/features/sam/SamConversation.tsx+++ b/src/client/features/sam/SamConversation.tsx@@ -3,6 +3,8 @@ import { useAgent } from "agents/react";// variant skips the client->server transcript sync Think doesn't support.import { useAgentChat } from "@cloudflare/think/react";import { useEffect, useRef } from "react";+import { RotateCcw } from "lucide-react";+import { findLast } from "remeda";import { ChatComposer } from "@/client/features/sam/ChatComposer";import { invalidateSamSessions } from "@/client/features/sam/samQueries";import {@@ -32,10 +34,20 @@ export function SamConversation({const agent = useAgent({ agent: "sam-chat", name: sessionId });// SAM streams dense tool-input deltas; unthrottled per-chunk store fanout// re-renders the transcript per delta and trips React #185 (cloudflare/agents#1361).- const { messages, sendMessage, setMessages, clearHistory, status } =- useAgentChat({ agent, experimental_throttle: 50 });+ const {+ messages,+ sendMessage,+ setMessages,+ clearHistory,+ status,+ stop,+ isRecovering,+ } = useAgentChat({ agent, experimental_throttle: 50 });- const isBusy = status === "submitted" || status === "streaming";+ // isRecovering: the DO is settling a turn a reset interrupted (persisting+ // the partial reply). Nothing can be sent into it until that lands.+ const isBusy =+ status === "submitted" || status === "streaming" || isRecovering;const { scrollRef, onScroll, pinToBottom } = useStickToBottom(messages,status,@@ -68,6 +80,19 @@ export function SamConversation({const editAndResend = async (messageId: string, newText: string) => {if (await rewindTo(messageId)) sendText(newText);};+ // Retry after a failed turn goes through the same rewind-then-resend path+ // as edit, so the failed partial reply is deleted server-side before the+ // new one streams in. Each click is one human-gated turn, metered per step;+ // the DO never re-runs a turn on its own (see onChatRecovery).+ const lastUserMessage = findLast(messages, (m) => m.role === "user");+ const retryLast = () => {+ if (!lastUserMessage) return;+ const text = lastUserMessage.parts+ .filter((part) => part.type === "text")+ .map((part) => part.text)+ .join("\n");+ void editAndResend(lastUserMessage.id, text);+ };// The DO names the session from its first message during the turn, so refresh// the side-panel once the turn settles (busy -> idle) to pick up the title.@@ -158,12 +183,29 @@ export function SamConversation({</div>) : null}- {status === "error" ? (- <p className="text-sm text-error">- Something went wrong. Please try again.+ {isRecovering ? (+ <p className="text-xs text-base-content/50">+ Saving the reply that got cut off…</p>) : null}+ {status === "error" ? (+ <div className="flex flex-wrap items-center gap-3 text-sm text-error">+ <span>SAM stopped before finishing this reply.</span>+ {lastUserMessage ? (+ <button+ type="button"+ className="btn btn-outline btn-error btn-xs gap-1"+ disabled={isBusy}+ onClick={retryLast}+ >+ <RotateCcw className="size-3" />+ Retry+ </button>+ ) : null}+ </div>+ ) : null}+{showSuggestions ? (<div className="flex flex-wrap gap-2">{SUGGESTIONS.map((question) => (@@ -186,6 +228,7 @@ export function SamConversation({<ChatComposerbusy={isBusy}onSend={sendText}+ onStop={() => void stop()}placeholder="Ask SAM to research, analyze, or track anything…"/></div>diff --git a/src/server/billing/subscription.ts b/src/server/billing/subscription.tsindex 15eb92b1..4f89e09b 100644--- a/src/server/billing/subscription.ts+++ b/src/server/billing/subscription.ts@@ -234,12 +234,12 @@ export async function trackUsageCreditSpend(args: {costUsd: number;monthlyRemaining: number;properties?: Record<string, unknown>;-}): Promise<void> {+}): Promise<{ monthlyCredits: number; topupCredits: number }> {const totalCostUsd = roundUsdForBilling(args.costUsd * SEO_DATA_COST_MARKUP);const totalCostCredits = Math.ceil(totalCostUsd * AUTUMN_SEO_DATA_CREDITS_PER_USD,);- if (totalCostCredits <= 0) return;+ if (totalCostCredits <= 0) return { monthlyCredits: 0, topupCredits: 0 };// Clamp at 0: Autumn balances can read negative after an overdraft, and a// negative monthly reading here would inflate the topup deduction.@@ -300,4 +300,5 @@ export async function trackUsageCreditSpend(args: {cost_usd: totalCostUsd,},});+ return { monthlyCredits: monthlyDeduct, topupCredits: topupDeduct };}diff --git a/src/server/features/sam/SamChatAgent.ts b/src/server/features/sam/SamChatAgent.tsindex 6f5fe1d8..ba82d649 100644--- a/src/server/features/sam/SamChatAgent.ts+++ b/src/server/features/sam/SamChatAgent.ts@@ -1,6 +1,7 @@import { Think } from "@cloudflare/think";import type {ChatErrorContext,+ ChatRecoveryContext,ChatRecoveryOptions,ChatResponseResult,SaveMessagesResult,@@ -11,6 +12,8 @@ import type {TurnContext,} from "@cloudflare/think";import { clearChatTerminal } from "agents/chat";+import { createCompactFunction } from "agents/experimental/memory/utils";+import { generateText } from "ai";import type { UIMessage } from "ai";import { z } from "zod";import { eq } from "drizzle-orm";@@ -48,6 +51,26 @@ const PROJECT_CONTEXT_BLOCK = "project_context";const PUBLIC_ORIGIN_KEY = "sam-public-origin";+// Batching threshold for metering, not a charge: the user pays the turn's+// actual OpenRouter cost (times the usual markup) whatever this is set to.+// Spend accumulates step by step and is sent to Autumn once the unbilled+// total reaches this much, with the remainder flushed when the turn ends —+// so a $0.50 turn is ~10 Autumn calls rather than one per step, and a turn+// the isolate kills mid-way has at most this much unbilled. Each call rounds+// up to a whole credit (a tenth of a cent).+const SAM_BILLING_CHUNK_USD = 0.05;++// Long tool-heavy turns are what outgrow the Durable Object memory limit; the+// model's 1M-token window never gets a say. Compact between turns past this+// estimated token count, and mid-turn once a step's input passes 90% of the+// proactive ceiling — both far below the window, because the constraint is DO+// memory, not the provider.+const SAM_COMPACT_AFTER_TOKENS = 120_000;+const SAM_MAX_INPUT_TOKENS = 160_000;++const INTERRUPTED_TURN_NOTICE =+ "That reply was cut off before it finished — the work got too big to complete in one go. Everything above is saved. Ask again for a narrower slice (fewer keywords, competitors, or pages), or tell me where to pick up.";+// Derive a short session title from the first user message.function deriveTitle(text: string): string {const trimmed = text.replace(/\s+/g, " ").trim();@@ -101,10 +124,27 @@ export class SamChatAgent extends Think {private samContext: SamContext | null = null;// Per-turn billing state: beforeTurn arms it (non-null = hosted mode, meter- // this turn), onStepFinish accumulates the OpenRouter cost, onChatResponse- // meters the spend.- private turnCostUsd = 0;+ // this turn), onStepFinish accumulates OpenRouter cost and meters it in+ // chunks as the turn runs, onChatResponse/onChatError flush the remainder.+ // Chunked per step rather than once per turn so a turn the Durable Object+ // memory limit kills mid-way still bills what it spent — the Sep 2026+ // recovery loop burned ~$160/day of OpenRouter spend that never reached+ // onChatResponse. Deductions run off the inference loop, serialized so they+ // land in order; the end-of-turn flush awaits the chain.+ private turnUnbilledUsd = 0;private turnMonthlyRemaining: number | null = null;+ private billing: Promise<void> = Promise.resolve();++ // Mid-turn context guard, using the compaction configured in+ // configureSession (see SAM_MAX_INPUT_TOKENS). The reactive backstop is+ // deliberately off: it re-runs the whole turn from compacted history, which+ // would re-issue every tool call — a second site audit, a second DataForSEO+ // charge for the same research — on a classifier that is a regex over the+ // provider's error text. A turn that still overflows ends as an error the+ // user can retry.+ override contextOverflow = {+ proactive: { maxInputTokens: SAM_MAX_INPUT_TOKENS },+ };/** Permanently remove this session's transcript for an account erasure. */async destroyForErasure(): Promise<void> {@@ -129,6 +169,10 @@ export class SamChatAgent extends Think {}getModel() {+ return this.buildModel("max");+ }++ private buildModel(reasoningEffort: "max" | "low") {const apiKey = getEnvValueSync(this.env, "OPENROUTER_API_KEY");if (!apiKey) {throw new Error("OPENROUTER_API_KEY is required for the SAM agent");@@ -136,6 +180,7 @@ export class SamChatAgent extends Think {return buildChatAgentModel(apiKey,getEnvValueSync(this.env, "OPENROUTER_MODEL"),+ reasoningEffort,);}@@ -184,7 +229,24 @@ export class SamChatAgent extends Think {description:"This project's shared memory — sections, competitors, key pages and research log, the same records the user sees in the app. Change it with update_project_context.",provider: { get: () => this.renderProjectContext() },- });+ })+ .onCompaction(+ createCompactFunction({+ summarize: (prompt) => this.summarizeForCompaction(prompt),+ }),+ )+ .compactAfter(SAM_COMPACT_AFTER_TOKENS);+ }++ // Compaction summaries run outside the step loop (so outside onStepFinish),+ // on the same model at low reasoning; their cost joins the turn's total.+ private async summarizeForCompaction(prompt: string): Promise<string> {+ const result = await generateText({+ model: this.buildModel("low"),+ prompt,+ });+ this.recordSpend(openRouterCostUsd(result.providerMetadata));+ return result.text;}private async loadSamContext(): Promise<SamContext | null> {@@ -253,7 +315,9 @@ export class SamChatAgent extends Think {}async beforeTurn(_ctx: TurnContext): Promise<TurnConfig> {- this.turnCostUsd = 0;+ // turnUnbilledUsd deliberately carries over: a between-turn compaction+ // summary can land after the previous flush, and it is the same org's+ // spend either way.this.turnMonthlyRemaining = null;return withPgClient(async (): Promise<TurnConfig> => {const ctx = await this.loadSamContext();@@ -321,45 +385,75 @@ export class SamChatAgent extends Think {id: ctx.project.id,domain: ctx.project.domain,}),- // SAM is meant to run complex multi-step work in one turn (site-read- // intake plus a full research chain, multi-competitor sweeps), so give- // it generous headroom — cost is bounded by per-step metering and the- // model stopping on its own, not by this cap. The per-step budget is- // shared by max-effort reasoning + visible output; a tight cap risks- // reasoning eating the reply (the issue #161 failure mode), so it's- // deliberately roomy — ~10x measured reasoning use — while keeping the- // worst-case turn (48 steps at the full cap) under ~$2.- maxSteps: 48,- maxOutputTokens: 32_000,+ // SAM runs complex multi-step work in one turn (site-read intake plus+ // a full research chain, multi-competitor sweeps), so the step budget+ // is generous; cost is bounded by per-step metering and the model+ // stopping on its own. The per-step token budget is shared by+ // max-effort reasoning and the visible reply, so it stays well above+ // measured reasoning use (~3k tokens — a tight cap lets reasoning eat+ // the reply, issue #161) but below the 32k that, with 48 steps, let a+ // single turn outgrow the Durable Object memory limit.+ maxSteps: 40,+ maxOutputTokens: 16_000,};});}onStepFinish(ctx: StepContext): void {- this.turnCostUsd += openRouterCostUsd(ctx.providerMetadata);+ this.recordSpend(openRouterCostUsd(ctx.providerMetadata));+ }++ // Add spend to the turn's unbilled total and meter it once a chunk has+ // accumulated, or on `flush` at the end of the turn. Self-hosted turns (no+ // armed balance) are never metered.+ private recordSpend(costUsd: number, { flush = false } = {}): void {+ this.turnUnbilledUsd += costUsd;+ const armed = this.turnMonthlyRemaining;+ if (armed === null) return;+ if (!flush && this.turnUnbilledUsd < SAM_BILLING_CHUNK_USD) return;+ const chunkUsd = this.turnUnbilledUsd;+ this.turnUnbilledUsd = 0;+ this.billing = this.billing+ .then(() => this.meterSpend(chunkUsd, armed))+ .catch((error: unknown) => {+ console.error("[sam] credit metering failed", error);+ });+ }++ private async meterSpend(+ costUsd: number,+ armedMonthlyRemaining: number,+ ): Promise<void> {+ const ctx = await withPgClient(() => this.loadSamContext());+ if (!ctx) return;+ // Earlier chunks in the chain have already drawn the monthly balance+ // down; the value captured at enqueue time only covers a flush that+ // outlives its turn (onChatError), where the field has been re-armed.+ const { monthlyCredits } = await trackUsageCreditSpend({+ customer: {+ userId: ctx.row.userId,+ userEmail: ctx.userEmail,+ organizationId: ctx.project.organizationId,+ projectId: ctx.project.id,+ },+ customerId: ctx.project.organizationId,+ creditFeature: "agent",+ costUsd,+ monthlyRemaining: this.turnMonthlyRemaining ?? armedMonthlyRemaining,+ properties: { provider: "openrouter" },+ });+ if (this.turnMonthlyRemaining !== null) {+ this.turnMonthlyRemaining -= monthlyCredits;+ }}async onChatResponse(result: ChatResponseResult): Promise<void> {+ this.flushSpend();+await withPgClient(async () => {const ctx = await this.loadSamContext();if (!ctx) return;- if (this.turnMonthlyRemaining !== null) {- await trackUsageCreditSpend({- customer: {- userId: ctx.row.userId,- userEmail: ctx.userEmail,- organizationId: ctx.project.organizationId,- projectId: ctx.project.id,- },- customerId: ctx.project.organizationId,- creditFeature: "agent",- costUsd: this.turnCostUsd,- monthlyRemaining: this.turnMonthlyRemaining,- properties: { provider: "openrouter" },- });- }-// Name the session from its first message so the side-panel is readable.if (ctx.row.title === "New chat") {const title = deriveTitle(firstUserText(this.messages));@@ -389,9 +483,20 @@ export class SamChatAgent extends Think {// clients replay — returning nothing would make it the string "undefined".onChatError(error: unknown, ctx?: ChatErrorContext): unknown {console.error("[sam] chat turn error", ctx?.stage, error);+ // A stopped or failed turn still consumed what it consumed.+ this.flushSpend();return error;}+ // Meter the turn's remainder without holding the turn (and the queue+ // behind it) on Autumn: the DO stays alive for the chain via waitUntil,+ // which also covers the error stages Think never follows with a response+ // hook.+ private flushSpend(): void {+ this.recordSpend(0, { flush: true });+ this.ctx.waitUntil(this.billing);+ }+// Think's chat recovery re-runs an interrupted turn: after a Durable Object// reset it wakes, reads the incident, and calls the model again to continue// the partial reply. When the reset was a memory-limit kill (a long,@@ -400,12 +505,32 @@ export class SamChatAgent extends Think {// it — one incident was observed at attempt 44 of a max of 10. Each attempt// is a full OpenRouter call that never reaches onChatResponse, so none of it// is metered: in early Sep 2026 these loops were ~95% of the key's spend.- // Keep the durable bookkeeping (partial reply persisted, terminal banner- // sent) but never re-run inference automatically; the user resends instead.- override async onChatRecovery(): Promise<ChatRecoveryOptions> {+ // Keep the durable bookkeeping (partial reply persisted) but never re-run+ // inference automatically; the user resends instead. Skipped recoveries+ // get no framework banner (that only fires when a retry budget is+ // exhausted), so schedule our own notice — delivered from inside this hook+ // it would land before the partial reply in the transcript.+ override async onChatRecovery(+ ctx: ChatRecoveryContext,+ ): Promise<ChatRecoveryOptions> {+ console.warn("[sam] interrupted turn not re-run", {+ name: this.name,+ incidentId: ctx.incidentId,+ recoveryKind: ctx.recoveryKind,+ });+ // Recovery runs from the DO's startup path, and a hook that fails or+ // times out is re-run on the next wake; idempotent so the notice is+ // scheduled once per incident, not once per restart.+ await this.schedule(1, "notifyInterruptedTurn", ctx.incidentId, {+ idempotent: true,+ });return { persist: true, continue: false };}+ async notifyInterruptedTurn(): Promise<void> {+ await this.deliverNotice(INTERRUPTED_TURN_NOTICE);+ }+// Recovery continuations already queued as alarms before this deploy still// fire, and would each make one more model call (re-arming through the// alarm circuit breaker when that call OOMs too). Skip them without touchingdiff --git a/src/server/features/sam/samChatTools.test.ts b/src/server/features/sam/samChatTools.test.tsindex 1457f7e4..576af0d9 100644--- a/src/server/features/sam/samChatTools.test.ts+++ b/src/server/features/sam/samChatTools.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from "vitest";import type { Tool } from "ai";-import { waitingAuditStatusTool } from "./samChatTools";+import { toModelOutput, waitingAuditStatusTool } from "./samChatTools";vi.mock("cloudflare:workers", () => ({env: {},@@ -58,3 +58,30 @@ describe("waitingAuditStatusTool", () => {expect(execute).toHaveBeenCalledTimes(3);});});++describe("toModelOutput", () => {+ const rows = Array.from({ length: 40 }, (_, i) => ({ keyword: `kw ${i}` }));+ const text = rows.map((row) => `| ${row.keyword} | 100 |`).join("\n");++ it("keeps only the head of the text when the structured data carries the rows", () => {+ const out = toModelOutput({+ content: [{ type: "text", text }],+ structuredContent: { rows },+ });+ expect(out.data).toEqual({ rows });+ expect(out.summary.length).toBeLessThan(text.length);+ expect(out.summary).toContain("(full rows in data)");+ });++ it("keeps the full text when structuredContent is only a meta deep link", () => {+ expect(+ toModelOutput({+ content: [{ type: "text", text }],+ structuredContent: { meta: { url: "https://example.com" } },+ }),+ ).toEqual({+ summary: text,+ data: { meta: { url: "https://example.com" } },+ });+ });+});diff --git a/src/server/features/sam/samChatTools.ts b/src/server/features/sam/samChatTools.tsindex 8739dafe..4046bc77 100644--- a/src/server/features/sam/samChatTools.ts+++ b/src/server/features/sam/samChatTools.ts@@ -58,6 +58,7 @@ import {} from "@/server/mcp/tools/search-console-tools";import { whoamiTool } from "@/server/mcp/tools/whoami";import { discoverSiteUrls, readPages, readSite } from "@/server/lib/scrape";+import { capToolOutput } from "@/server/features/sam/samToolOutput";import openSeoFactSheet from "@/server/features/sam/openseo-fact-sheet.md?raw";// Enough pages for SAM to work out what a business does, sells, and positions@@ -77,18 +78,35 @@ type McpToolDefinition<Shape extends ZodRawShape> = {) => Promise<CallToolResult>;};-// Flatten an MCP CallToolResult into a plain value for the model: the handler's-// human-readable text summary plus the structured data it returned.-function toModelOutput(result: CallToolResult): unknown {- const summary = (result.content ?? [])+// Flatten an MCP CallToolResult into a plain value for the model. The text+// block renders the same rows the structured data carries (see+// tool-text-output.test.ts), so when both exist only the head of the text+// survives — the title line and any caveat, not a second copy of every row.+// A tool result is re-sent on every step of its turn and persisted in the+// transcript, so the duplicate would cost twice everywhere.+const SUMMARY_HEAD_CHARS = 300;++export function toModelOutput(result: CallToolResult): {+ summary: string;+ data?: CallToolResult["structuredContent"];+} {+ const text = (result.content ?? []).filter((part): part is { type: "text"; text: string } => part.type === "text",).map((part) => part.text).join("\n");- return result.structuredContent- ? { summary, data: result.structuredContent }- : { summary };+ const data = result.structuredContent;+ // A text-only response still gets a `{ meta }` structuredContent when it+ // carries a deep link; that is not a second copy of the text.+ const dataHasRows =+ data != null && Object.keys(data).some((key) => key !== "meta");+ if (!dataHasRows) return data ? { summary: text, data } : { summary: text };+ const summary =+ text.length > SUMMARY_HEAD_CHARS+ ? `${text.slice(0, SUMMARY_HEAD_CHARS)}… (full rows in data)`+ : text;+ return { summary, data };}// Adapt one OpenSEO tool into an AI SDK tool. The shared handler receives the@@ -124,8 +142,8 @@ function adaptMcpTool<Shape extends ZodRawShape>(// Tool calls run inside Think's inference loop, outside any ambient// request scope, so each execution scopes its own Postgres client// (no-op in D1 mode) — same rule as the DO's other DB-touching seams.- return toModelOutput(- await withPgClient(() => handler(fullArgs, context)),+ return capToolOutput(+ toModelOutput(await withPgClient(() => handler(fullArgs, context))),);} catch (error) {// Surface the failure to the model so it can recover or report it,@@ -272,7 +290,7 @@ function scrapeTools(projectDomain: string | null): ToolSet {note: "Could not read the requested page(s). Ask the user to describe the site instead, and say you couldn't read it.",};}- return { blocked: false, pages: site.pages };+ return capToolOutput({ blocked: false, pages: site.pages });},}),};diff --git a/src/server/features/sam/samToolOutput.test.ts b/src/server/features/sam/samToolOutput.test.tsnew file mode 100644index 00000000..2700685b--- /dev/null+++ b/src/server/features/sam/samToolOutput.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from "vitest";+import { z } from "zod";+import { capToolOutput } from "./samToolOutput";++const row = (i: number) => ({ keyword: `keyword ${i}`, volume: i * 10 });++const capped = z.object({ truncated: z.string() }).loose();++describe("capToolOutput", () => {+ it("returns small results untouched", () => {+ const value = { summary: "ok", data: { rows: [row(1)] } };+ expect(capToolOutput(value)).toBe(value);+ });++ it("halves the largest array until the result fits and says so", () => {+ const rows = Array.from({ length: 800 }, (_, i) => row(i));+ const value = { summary: "800 keywords", data: { rows } };++ const out = capped+ .extend({ data: z.object({ rows: z.array(z.unknown()) }) })+ .parse(capToolOutput(value, 8_000));++ expect(JSON.stringify(out).length).toBeLessThanOrEqual(8_000);+ expect(out.data.rows[0]).toEqual(row(0));+ expect(out.truncated).toBe(+ `Output trimmed to fit the chat context: \`data.rows\` shows ${out.data.rows.length} of 800 rows. Narrow the request (filters, a smaller limit, fewer pages) to see the rest.`,+ );+ expect(value.data.rows).toHaveLength(800);+ });++ it("shortens long strings when there is no array to trim", () => {+ const value = {+ pages: [{ url: "https://a.test", text: "x".repeat(20_000) }],+ };++ const out = capped.parse(capToolOutput(value, 3_000));++ expect(JSON.stringify(out).length).toBeLessThanOrEqual(3_000);+ expect(out.truncated).toContain("`pages[*].text` shortened to");+ });++ it("keeps the note inside the cap and names each shape once", () => {+ const rows = Array.from({ length: 500 }, (_, i) => ({+ id: i,+ body: "z".repeat(9_000),+ }));++ const out = capped.parse(capToolOutput({ data: { rows } }, 32_000));++ expect(JSON.stringify(out).length).toBeLessThanOrEqual(32_000);+ expect(out.truncated.match(/`data\.rows\[\*\]\.body`/g)).toHaveLength(1);+ expect(out.truncated).toContain("`data.rows` shows");+ });+});diff --git a/src/server/features/sam/samToolOutput.ts b/src/server/features/sam/samToolOutput.tsnew file mode 100644index 00000000..db52ed66--- /dev/null+++ b/src/server/features/sam/samToolOutput.ts@@ -0,0 +1,175 @@+// Every tool result SAM sees is persisted into the transcript and re-sent to+// the model on each later step of the turn, so one oversized payload (a keyword+// list with hundreds of rows, ten scraped pages) is paid for dozens of times —+// and it is how long SAM turns outgrew the Durable Object memory limit in+// Sep 2026. Trim any result over the budget before it reaches the model and+// say what was dropped, so the model narrows the request instead of guessing.+// The MCP server hands external clients the full payload; only SAM is capped.++const SAM_MAX_TOOL_OUTPUT_CHARS = 32_000;+// A single long string (a scraped page) never gets more than this share.+const MAX_STRING_CHARS = 8_000;+const MIN_STRING_CHARS = 500;+// Reserved for the `truncated` note, so the note can't push a trimmed result+// back over the cap.+const NOTE_BUDGET_CHARS = 600;++type Trim = {+ path: string;+ kept: number;+ total: number;+ unit: "rows" | "chars";+};++type Slot = { parent: object; key: string | number; path: string };++const size = (value: unknown): number => JSON.stringify(value)?.length ?? 0;++// Every array/string slot in the value, depth-first, with its dotted path.+function slots(value: unknown, path = ""): Slot[] {+ if (Array.isArray(value)) {+ return value.flatMap((item, index) => {+ const itemPath = `${path}[${index}]`;+ const here: Slot[] =+ Array.isArray(item) || typeof item === "string"+ ? [{ parent: value, key: index, path: itemPath }]+ : [];+ return [...here, ...slots(item, itemPath)];+ });+ }+ if (typeof value === "object" && value !== null) {+ return Object.entries(value).flatMap(([key, item]) => {+ const itemPath = path ? `${path}.${key}` : key;+ const here: Slot[] =+ Array.isArray(item) || typeof item === "string"+ ? [{ parent: value, key, path: itemPath }]+ : [];+ return [...here, ...slots(item, itemPath)];+ });+ }+ return [];+}++const read = (slot: Slot): unknown => Reflect.get(slot.parent, slot.key);+const write = (slot: Slot, value: unknown): void => {+ Reflect.set(slot.parent, slot.key, value);+};++// Trims are keyed per shape, not per element: 500 shortened `rows[i].body`+// strings are one note line, `rows[*].body`.+const shape = (path: string): string => path.replace(/\[\d+\]/g, "[*]");++// Whether a shape path still points at something in the trimmed value — the+// note must not describe rows the halving loop has since dropped.+function present(value: unknown, path: string): boolean {+ let node = value;+ for (const segment of path.split(/\.|(?=\[)/)) {+ if (segment === "") continue;+ if (segment === "[*]") {+ if (!Array.isArray(node) || node.length === 0) return false;+ node = node[0];+ continue;+ }+ if (typeof node !== "object" || node === null) return false;+ node = Reflect.get(node, segment);+ if (node === undefined) return false;+ }+ return true;+}++function note(trims: Trim[]): string {+ const parts = trims.map((trim) =>+ trim.unit === "rows"+ ? `\`${trim.path}\` shows ${trim.kept} of ${trim.total} rows`+ : `\`${trim.path}\` shortened to ${trim.kept} chars`,+ );+ const text = `Output trimmed to fit the chat context: ${parts.join("; ")}. Narrow the request (filters, a smaller limit, fewer pages) to see the rest.`;+ return text.length > NOTE_BUDGET_CHARS+ ? `${text.slice(0, NOTE_BUDGET_CHARS - 1)}…`+ : text;+}++/**+ * Returns `value` unchanged when it serializes under `maxChars`. Otherwise+ * returns a trimmed deep copy: long strings are capped first, then the+ * largest array is halved (keeping the head — results are ordered by+ * relevance) until it fits, then the longest string, with a `truncated` note+ * listing what was cut. The note is included in the cap.+ */+export function capToolOutput(+ value: unknown,+ maxChars = SAM_MAX_TOOL_OUTPUT_CHARS,+): unknown {+ if (size(value) <= maxChars) return value;++ const budget = maxChars - NOTE_BUDGET_CHARS;+ const copy: unknown = structuredClone(value);+ const trims = new Map<string, Trim>();+ const record = (+ slot: Slot,+ kept: number,+ total: number,+ unit: Trim["unit"],+ ) => {+ const path = shape(slot.path);+ const existing = trims.get(path);+ trims.set(path, {+ path,+ kept: existing ? Math.min(existing.kept, kept) : kept,+ total: existing ? Math.max(existing.total, total) : total,+ unit,+ });+ };++ for (const slot of slots(copy)) {+ const item = read(slot);+ if (typeof item === "string" && item.length > MAX_STRING_CHARS) {+ write(slot, item.slice(0, MAX_STRING_CHARS));+ record(slot, MAX_STRING_CHARS, item.length, "chars");+ }+ }++ while (size(copy) > budget) {+ const largest = slots(copy)+ .map((slot) => ({ slot, item: read(slot) }))+ .filter(+ (entry): entry is { slot: Slot; item: unknown[] } =>+ Array.isArray(entry.item) && entry.item.length > 1,+ )+ .reduce<{ slot: Slot; item: unknown[] } | undefined>(+ (best, entry) =>+ best && size(best.item) >= size(entry.item) ? best : entry,+ undefined,+ );+ if (!largest) break;+ const kept = Math.ceil(largest.item.length / 2);+ write(largest.slot, largest.item.slice(0, kept));+ record(largest.slot, kept, largest.item.length, "rows");+ }++ while (size(copy) > budget) {+ const longest = slots(copy)+ .map((slot) => ({ slot, item: read(slot) }))+ .filter(+ (entry): entry is { slot: Slot; item: string } =>+ typeof entry.item === "string" &&+ entry.item.length > MIN_STRING_CHARS,+ )+ .reduce<{ slot: Slot; item: string } | undefined>(+ (best, entry) =>+ best && best.item.length >= entry.item.length ? best : entry,+ undefined,+ );+ if (!longest) break;+ const kept = Math.max(MIN_STRING_CHARS, Math.ceil(longest.item.length / 2));+ write(longest.slot, longest.item.slice(0, kept));+ record(longest.slot, kept, longest.item.length, "chars");+ }++ const truncated = note(+ [...trims.values()].filter((trim) => present(copy, trim.path)),+ );+ return typeof copy === "object" && copy !== null && !Array.isArray(copy)+ ? { ...copy, truncated }+ : { data: copy, truncated };+}diff --git a/src/server/lib/openrouter.ts b/src/server/lib/openrouter.tsindex 464c1a77..9e5d04d4 100644--- a/src/server/lib/openrouter.ts+++ b/src/server/lib/openrouter.ts@@ -29,6 +29,7 @@ const MINIMAX_M3 = "minimax/minimax-m3";export function buildChatAgentModel(apiKey: string,modelId?: string,+ reasoningEffort: "max" | "low" = "max",): LanguageModelV3 {const model = modelId ?? DEFAULT_CHAT_AGENT_MODEL;const openrouter = createOpenRouter({ apiKey });@@ -44,7 +45,7 @@ export function buildChatAgentModel(if (model === MINIMAX_M3) {return openrouter(model, {usage: { include: true },- reasoning: { effort: "medium" },+ reasoning: { effort: reasoningEffort === "low" ? "low" : "medium" },provider: {order: ["together", "atlas-cloud/fp8"],zdr: true,@@ -55,6 +56,6 @@ export function buildChatAgentModel(return openrouter(model, {usage: { include: true },- extraBody: { reasoning: { effort: "max" } },+ extraBody: { reasoning: { effort: reasoningEffort } },});}