SLOPSHOPPER

decision-compaction

Hands back the conversation itself in place of a compaction summary, less the tool calls and results a System One decision model judges no longer needed. The…

toastnetworktimer
★ 1v0.1.0Apache-2.0updated 2026-10-21zchee/claude-code-mods/mods/decision-compaction
A shopper browsing a rack in a slop shop
README

decision-compaction

Compaction without a summary. A Claude Code mod for session.compact that hands the conversation back as it was, with only those tool calls and tool outputs removed that a System One decision model says the assistant can do without. What you and the assistant wrote stays word for word.

License: Apache-2.0 Plugin API: Claude Code 2.1.292 Providers: 8

[!WARNING] The conversation text and the tool inputs are sent to the selected third-party API (TypeSafe, Cloudflare, OpenRouter, Codiv, Perplexity, decisions-api.dev, decisionapi.net or OpenAI) on every compaction. They are sent as they are: a secret you pasted into a prompt, or one that appears in a tool input such as a shell command, goes with them. Tool outputs are not sent: each is replaced by a note of its status and length.

With providerDecision on, a second provider can receive data in the same compaction. Every provider in decisionProviders (all eight by default) whose credentials resolve is a candidate to decide it, so a key you exported for another tool, OPENAI_API_KEY for example, makes that vendor eligible to receive the conversation. decisionProviders is the setting that narrows the set. The routing question, when there is a choice to make, goes to Cloudflare only when cloudflare is one of the providers considered (the configured provider, and those in decisionProviders) and its credentials are set; otherwise it goes to the configured provider. It carries a profile of the job that includes up to 2,000 characters of your prompts (the text typed after /compact, or your last three prompts).

Do not enable this mod for a session whose content must not leave your machine.

Table of contents

Install

From the marketplace, on Claude Code 2.1.275 or later:

claude plugin install decision-compaction --marketplace zchee/claude-code-mods

From a checkout, without installing:

claude --plugin-dir mods/decision-compaction

Then set a credential for the provider you want (see Providers), for example TYPESAFE_API_KEY in the environment, or the typesafeApiKey option in /config.

Options are read from settings under pluginConfigs and appear in /config. A mod loaded with --plugin-dir is keyed decision-compaction@inline (the bare decision-compaction is read too); an installed one is keyed by its plugin id, decision-compaction@<marketplace>.

How it works

On session.compact

On session.compact (a /compact, the engine's own threshold, or this mod's trigger) the hook:

  1. Matches each tool call to its output by tool_use_id. The first message is never changed, and neither is any of the last preserveRecentMessages; a call that sits in one of those, or whose output does, is not judged. A tool_use_id that occurs on more than one call or output is not judged either, since a decision is applied by that id.
  2. Describes the whole conversation in one state and shrinks it only as far as its budget requires. The reductions are tried in a fixed order and the first that is enough ends the search: shorter tool inputs, the middle cut out of long texts (old messages before the protected ones), old texts replaced by their length, old calls written on one line, old messages without a call omitted, and neighbouring old messages that hold nothing but calls merged into one entry. For a provider that caps the request body in bytes, the same reductions go on until the state also fits that cap with room left for one request's questions. Sizes are estimates; no tokenizer is used.
  3. Puts two yes/no questions to the provider for every call left to judge: is the call itself still needed, and is its complete output still needed word for word. A request holds as many of these questions as the token budget, the provider's own limit on questions and, for a provider that caps the body in bytes, that cap allow, and each request carries the full state. See Limits for the bounds.
  4. Compares each answer with keepThreshold. Either the call and its output both stay; or the call stays and the output is shortened to its opening truncateHeadChars characters, followed by a note saying how much was removed; or the call goes and its output goes with it. Output so short that shortening would save nothing is not touched.
  5. Hands back the new list of messages. A message nothing touched goes back exactly as the engine gave it, and an output never outlives its call.

A message that had one of its blocks dropped or cut is rebuilt from its role, its text and its remaining tool blocks, and nothing else survives the rebuild. Two consequences: a result that is kept, but shares its message with a result that was dropped or cut, loses any image content it had; and an assistant message that made several calls, one of which was dropped, loses its thinking block.

It fails open. On any error (a missing key, a provider option that names no provider, an HTTP error, a request that is rejected, a compaction whose requests are not answered in time, a malformed answer, a conversation that cannot be fitted or would take too many requests) and when the decisions would remove less than minReductionRatio, it says why in one line and lets the built-in summary run. A precompute compaction is always left to the engine.

Every request that asks about a tool call goes to one provider: the configured one, or the one the provider decision picked. Nothing falls over to another provider. With providerDecision on there can be one more request before them, the routing question, and it may go to a different provider (see providerDecision).

On turn.complete

On turn.complete, when the main conversation's context reaches compactAtPercent, the mod requests a compaction. What happens next depends on the usage that compaction leaves:

  • Under the threshold: the next time usage reaches the threshold, another compaction is requested at once.
  • At or above the threshold: that level becomes a floor, and no further compaction is requested until usage has risen ten points above it. A floor above 90% cannot be risen from, so after a compaction that leaves usage there, no automatic compaction is requested again until usage has first dropped under the threshold (for example after a /compact of your own or a /clear).
  • Unknown: usage is not known right after a compaction (it arrives with the next response). The first later reading at or above the threshold then becomes the floor, and the next request waits for a rise of ten points above that reading.

A turn you interrupted, and a subagent's turn, request nothing.

When Claude Code passes the mod over

Claude Code can seat its built-in cc-plugin-sec-default plugin before the plugins you install, and that plugin sends every session.compact past them. The transcript then says decision-compaction: its session.compact hook was skipped. "cc-plugin-sec-default" runs first and sent the event on past it., and every compaction of the session is the built-in summary. No setting of yours changes that: the mod has no other way to compact, and Claude Code ignores appendPlugins in your user settings in such a session. Only your organization can place the mod beneath that plugin, by listing it in appendPlugins in its managed settings.

Claude Code seats the plugin, in Claude Code 2.1.306:

  • on a Team or Enterprise plan,
  • on a machine with managed settings, or a managed MCP server file,
  • by default, on any plan, while Claude Code cannot yet tell that neither of those applies (its server-managed settings request has not answered that there are none). A managed prependPlugins that leaves the plugin out does not stop this default seat.

Once seated, the plugin stays seated until the Claude Code process ends; /clear and compaction keep it.

In such a session the turn.complete trigger would only run the built-in summary at compactAtPercent, earlier than Claude Code's own threshold and again at every later crossing. So the first compaction it requests that does not reach the mod's own hook stops it until the process ends, with a line and a toast saying why; Claude Code's own auto-compaction then decides when to compact. A compaction a hook above the mod vetoes, and one that fails, stop nothing.

Providers

providerEndpointModel by defaultCredentialsDocumented limits
typesafe (default)https://api.typesafe.ai/v1/systemonejev-latest (Jev 1.13; jev-1.14.0 is Jev 1.14)TYPESAFE_API_KEY64,000 tokens a request; 32,000 for the state plus the longest question; the same for Jev 1.13 and 1.14
cloudflarehttps://api.cloudflare.com/client/v4/accounts/<account id>/ai/run/@cf/cloudflare/<model>clef (clef-flash and clef-omni are the others)CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID64,000 tokens on clef and clef-omni, 24,000 on clef-flash (see below); 64 questions a request
openrouterhttps://openrouter.ai/api/v1/systemone~typesafe/jev-latest (Jev 1.14)OPENROUTER_API_KEY262,144 tokens for the state plus the questions, with a request of more than about 32,000 bytes of text run in TypeSafe's slower, less accurate long-context mode; 64 questions a request for any model other than Jev
codivhttps://api.codiv.ai/v1/systemoneopenjev-latest (OpenJev)CODIV_API_KEY65,536 tokens for the state and the questions together (the vendor advises a state of about 60,000); no question limit documented, 256 a request measured
perplexityhttps://api.perplexity.ai/v1/decisionspplx-decider-v1.1-27bPERPLEXITY_API_KEYunder 262,144 tokens a request; 128 questions a request
decisions-api-devhttps://decisions-api.dev/v1/systemonejev-latest (Jev 1.13, through this gateway; typesafe/jev-1.14 is Jev 1.14)DECISIONS_API_KEY32 KiB a request body, counted in bytes, so text that is not ASCII uses more of it; 8 questions a request
decisionapi-nethttps://decisionapi.net/v1/systemonejev-latest (Jev 1.14 as documented, through this gateway)DECISIONAPI_API_KEY32 KiB a request body, state and questions together, counted in bytes; 8 questions a request
openaihttps://api.openai.com/v1/decisionsgpt-6-lunaOPENAI_API_KEY1 to 200 questions a request; no token limit documented for the Decisions API, so the mod holds a request to 272,000 tokens, where the price doubles

The provider option takes exactly these eight names. Any other value is not replaced by the default: nothing is sent anywhere, and every compaction uses the built-in summary with a line naming the value. Only an option left unset or empty means typesafe. For that reason /config shows the option as a text field rather than a list (a list would let the engine turn an unknown value into the default without saying so).

What differs between the providers beyond the table:

  • openrouter, decisions-api-dev and decisionapi-net are gateways to TypeSafe's Jev. codiv's OpenJev is a model of its own, not TypeSafe's Jev: at Codiv jev-latest is an alias of OpenJev.
  • Jev 1.13 and Jev 1.14 are two models, and an alias names a different one at each provider. On 2026-10-16 TypeSafe's jev-latest, "the most recent stable, official release", was Jev 1.13 and its jev-preview Jev 1.14 (available from 2026-10-14); OpenRouter's ~typesafe/jev-latest, which "tracks the newest release", and decisionapi.net's default were Jev 1.14; decisions-api.dev's jev-latest answered as Jev 1.13. TypeSafe takes jev-1.14.0, the gateways typesafe/jev-1.14. To keep answers from one release, name it rather than an alias: an alias moves when a release ships.
  • cloudflare holds each Clef model to the count a cut state reports, measured on 2026-10-11: a text state too long for the window is cut without a word, and the reply then counts exactly 64,000 input tokens on clef and clef-omni and 24,000 on clef-flash. The catalogue states 65,536 for clef and 24,576 for clef-flash; a limit at those figures would never see the cut. clef-omni is a 30B mixture-of-experts model (3B active) that also reads audio, at $0.15 per million input tokens against $0.24 for clef and $0.038 for clef-flash.
  • perplexity accepts only its own decider models. Any other name in model, jev-latest included, is refused with an HTTP 400 and the compaction uses the built-in summary. Its usage.input_tokens, and so its bill at $0.02 per million, counts the state once for every question: a compaction of a 200,000-token state with 300 questions is billed about 60 million input tokens.
  • decisions-api-dev and decisionapi-net wrap the answer in a {code, message, data} envelope. A code other than 0, or an envelope without data.result, ends the compaction with the vendor's message quoted, as for any other failed request.
  • decisions-api-dev accepts a question id only if it starts with a letter, uses letters, digits, _ and -, and is at most 64 characters. The mod's ids can hold . and run longer, so it names each question in a request by its place (q0, q1, …) and maps the answers back to the ids. An answer under a name the mod did not send is refused.
  • openai takes a different request: the state goes as one JSON string in input and the questions as a list, each a predicate (yes/no) or a choice. The mod translates the request into that form and the answers back. OpenAI counts about 148 input tokens for each question (Codiv about 26 for the same one-line question), and the mod's size estimate adds that figure per question. If OpenAI refuses to answer a question (the line reads openai: refused to answer <question id>), or answers in a shape the mod does not read, the compaction ends with the built-in summary and the line names the question or the field.

~typesafe/jev-latest is OpenRouter's alias for the newest Jev; typesafe/jev-1.14 and typesafe/jev-1.13 pin a release. OpenRouter also takes TypeSafe's bare ids and maps them itself (jev-latest to ~typesafe/jev-latest, jev-1.13 to typesafe/jev-1.13). An id that already has an author prefix is used as written.

OpenRouter documents a window of 262,144 tokens for Jev, and sends a request "with more than about 32,000 bytes of text" to TypeSafe's long-context mode, which TypeSafe calls slower and less accurate than its default limits. The mod therefore asks OpenRouter's Jev for a body within that (see Budgets by route), and holds a request to the window only when the conversation does not fit it or you set a request budget.

OpenRouter also serves Cloudflare's Clef (cloudflare/clef, cloudflare/clef-flash, cloudflare/clef-omni), and passes such a request on to Cloudflare, which refuses one with more than 64 questions. A model other than Jev on openrouter is therefore asked at most 64 questions (32 tool calls) a request, as on cloudflare, and held to where OpenRouter cuts its state: cloudflare/clef and cloudflare/clef-flash were cut at 16,384 tokens on 2026-10-11, the window of the cheapest host OpenRouter sends them to, and cloudflare/clef-omni, which only Cloudflare hosts, at 64,000. Any other model it forwards is held to 32,000 tokens, since no limit of its is documented here.

Credentials

Each credential is read from its plugin option first, then from the environment, at the time of the compaction. The env block of the settings is read only when a credential a provider in play needs is still missing; if the settings cannot be read, that is logged and the compaction goes on with what it has. With providerDecision on and decisionProviders at its default of all eight providers, some key is usually unset, so the settings are read on most compactions.

Redaction

Text that comes from a provider or from the host (an HTTP error body, a Cloudflare failure envelope, the reason the host gives for refusing a request or a read) is quoted in the toast and the log on one line of at most 160 characters. Before it is shown, every credential this mod resolved is replaced with [redacted], and so is the token after the word Bearer, whether it follows a space, a colon or an equals sign. A resolved value shorter than eight characters is not replaced where it stands on its own, since no provider issues a key that short and replacing it would garble ordinary words.

Options

OptionDefaultMeaning
providertypesafeWhich provider decides; any other name sends nothing.
modelprovider defaultModel name for the configured provider.
providerDecisionfalseDecide the provider per compaction; see providerDecision.
decisionProvidersall eight providersWith providerDecision on, the providers that may be compared and so may receive the conversation: a list of provider names, or one text of names separated by commas. The configured provider is always considered. See providerDecision.
typesafeApiKeyunsetTypeSafe API key (stored as a secret).
openrouterApiKeyunsetOpenRouter API key (stored as a secret).
cloudflareApiTokenunsetCloudflare API token allowed to run Workers AI (stored as a secret).
cloudflareAccountIdunsetCloudflare account ID.
codivApiKeyunsetCodiv API key (stored as a secret).
perplexityApiKeyunsetPerplexity API key (stored as a secret).
decisionsApiKeyunsetdecisions-api.dev API key (stored as a secret).
decisionapiApiKeyunsetdecisionapi.net API key (stored as a secret).
openaiApiKeyunsetOpenAI API key (stored as a secret).
keepThreshold0.5Probability from which a call, or its full result, is kept.
preserveRecentMessages6Newest messages that are never changed.
compactAtPercent60Context usage at which a compaction is requested; 0 turns the trigger off.
minReductionRatio0.25Smallest share of characters the decisions must remove.
maxStateTokensthe route's ownMost estimated tokens the state may take, a whole number; unset, each route asks for its own (see Budgets by route).
maxRequestTokensthe route's ownMost estimated tokens one request may take, state and questions together, a whole number; unset, each route asks for its own (see Budgets by route).
truncateHeadChars300Characters kept of a shortened output; at 0 only the note remains.

Limits

The bounds below are fixed; they are not options.

  • Margin under the documented limits. The token estimate is made without a tokenizer and its weights were fitted to Jev, and Cloudflare cuts a state that is too long without saying so. A budget is therefore held to 85% of the provider's documented limit: 27,200 tokens for the state plus the longest question and 54,400 a request on typesafe, 54,400 on cloudflare clef and clef-omni and 20,400 on clef-flash, 222,822 on openrouter's Jev (13,926 on its clef and clef-flash, 54,400 on its clef-omni and 27,200 on any other model it forwards), 231,200 on openai, 51,000 for the state plus the longest question (85% of the 60,000 the vendor advises) and 55,705 a request on codiv, 222,821 on perplexity, and 27,200 for the state plus the longest question and 54,400 a request on decisions-api-dev and decisionapi-net. Both serve TypeSafe's Jev and state their own limit in bytes, so they are held to the token window TypeSafe documents for Jev, and the byte cap below is the bound that decides. openai documents 1 to 200 questions and no token limit for its Decisions API. On 2026-10-11 it answered a state of 300,000 tokens in under two seconds; a request over "272K" input tokens is billed at twice the rate, so it is held to 272,000 tokens and 200 questions before the margin. codiv documents no question limit but refused 300 questions (at most 256 a request), so it is held to 256. A budget you set is held to these figures, and so is the one a route asks for when you set none (see Budgets by route).
  • A byte cap. decisions-api-dev and decisionapi-net also hold a request to the 85% share of their 32 KiB cap, 27,852 of 32,768 bytes, measured as UTF-8 of the encoded request body, since a body over the cap is refused whole. When one of them is the configured provider the state is fitted to that cap as well as to its tokens: the reductions above go on until the body, with the questions of one request set aside (4 tool calls, all that 8 questions hold), fits in 27,852 bytes. English prose takes more bytes for each estimated token than the token budget allows for, and text that is not ASCII more still, so on these two providers it is usually the bytes that decide how much of the conversation the model sees. Questions are counted at or above the bytes they are sent in (decisions-api-dev counts each under the longest name it may send, q7). A conversation still over the cap after every reduction is left to the built-in summary, and the line says how many bytes were left. With providerDecision on, the state is fitted for the configured provider, so one of these two offered as another route may have no room for a question within the cap; it is then ruled out, and the line says how many of the 27,852 bytes the request takes before any question.
  • A byte cap that is asked for, not required. openrouter's Jev answers a body of any size within its window, but runs one of more than about 32,000 bytes in TypeSafe's long-context mode. With maxRequestTokens unset, a request to it is therefore held to 27,200 bytes (85% of 32,000) the way the two resellers are held to theirs, with two differences: when the conversation cannot be fitted under it, or its calls would then take more than 16 requests, the cap is dropped, the state is fitted again without it and the requests run in the long-context mode, rather than the built-in summary running; and with providerDecision on, it never rules openrouter out. A small session is thus decided in the default mode from a tighter state, and a larger one in the long-context mode from a fuller state. The line of each compaction says which (requests within the 27200 bytes openrouter asks for, or past them). A request budget you set drops the cap.
  • A reply that shows a cut. If a provider reports as many input tokens as the request limit the mod holds for it (before the margin), the state was probably cut short. The answers are discarded and the built-in summary runs. On decisions-api-dev and `decisionapi-n
Source 12 files
hooks/register.ts 335 lines
1import type { EngineInterface, PluginOptions, Register } from 'claude-code'
2
3import { reductionOf } from './compact'
4import { configOf, eligibleOf } from './config'
5import {
6  briefOf,
7  credentialsFor,
8  credentialsOf,
9  cutOf,
10  environmentOf,
11  messageOf,
12  PROVIDERS,
13  redacted,
14  unresolvedOf,
15} from './providers'
16import type { Credentials, Environment, ProviderName } from './providers'
17import { decisionLinesOf, percentOf, summaryOf } from './report'
18import { run } from './run'
19import { armOf, isCompactionDue, settle } from './trigger'
20
21/**
22 * How long an outcome toast stays: long enough to read one full line.
23 */
24const TOAST_MS = 15_000
25
26/**
27 * The hook time that must remain after a retry's wait for the work that
28 * follows it: reading the answers and rebuilding the messages.
29 */
30const PAUSE_RESERVE_MS = 1500
31
32/**
33 * Says which names of the `decisionProviders` option are no provider. Each
34 * is quoted, and quoted only in part when long, as the `provider` option
35 * is: the field may hold anything that was pasted into it.
36 */
37function unknownLineOf(names: readonly string[]): string {
38  const quoted = names.map(name => cutOf(JSON.stringify(name)))
39
40  return (
41    `the decisionProviders option names ${quoted.join(', ')}, ` +
42    `${names.length === 1 ? 'which is' : 'which are'} none of ` +
43    `${PROVIDERS.join(', ')}; ignored`
44  )
45}
46
47/**
48 * Reads the credential variables from the process environment, and from the
49 * `env` block of the settings only while a credential one of the providers
50 * needs is still without a value: the settings are a second source, not a
51 * part of every compaction. Each name is spelled out because `$.env.get`
52 * takes a string literal only.
53 *
54 * Settings that cannot be read are no settings. The compaction goes on with
55 * what the options and the environment gave, and `problem` says what went
56 * wrong so that it can be logged.
57 */
58async function readEnvironment(
59  $: EngineInterface,
60  options: PluginOptions,
61  providers: readonly ProviderName[],
62): Promise<{ environment: Environment; problem?: string }> {
63  const read: Environment = {
64    TYPESAFE_API_KEY: await $.env.get('TYPESAFE_API_KEY'),
65    OPENROUTER_API_KEY: await $.env.get('OPENROUTER_API_KEY'),
66    CLOUDFLARE_API_TOKEN: await $.env.get('CLOUDFLARE_API_TOKEN'),
67    CLOUDFLARE_ACCOUNT_ID: await $.env.get('CLOUDFLARE_ACCOUNT_ID'),
68    CODIV_API_KEY: await $.env.get('CODIV_API_KEY'),
69    PERPLEXITY_API_KEY: await $.env.get('PERPLEXITY_API_KEY'),
70    DECISIONS_API_KEY: await $.env.get('DECISIONS_API_KEY'),
71    DECISIONAPI_API_KEY: await $.env.get('DECISIONAPI_API_KEY'),
72    OPENAI_API_KEY: await $.env.get('OPENAI_API_KEY'),
73  }
74
75  if (unresolvedOf(providers, options, read).length === 0) {
76    return { environment: environmentOf(read, undefined) }
77  }
78
79  try {
80    const settings = await $.settings.read()
81
82    return { environment: environmentOf(read, settings.env) }
83  } catch (error) {
84    return {
85      environment: environmentOf(read, undefined),
86      problem: messageOf(error),
87    }
88  }
89}
90
91/**
92 * Writes one line to the transcript. Every line this module shows goes
93 * through here or through `tell`, and so through `redacted`: whatever a
94 * line was built from, no credential leaves in it.
95 */
96function log($: EngineInterface, text: string, credentials: Credentials): void {
97  $.ui.log(redacted(text, credentials))
98}
99
100/**
101 * Says one line both where it stays (the transcript) and where it is seen
102 * at once (a toast), redacted like every other line.
103 */
104function tell(
105  $: EngineInterface,
106  text: string,
107  credentials: Credentials,
108): void {
109  const shown = redacted(text, credentials)
110
111  $.ui.log(shown)
112  $.ui.toast(shown, { timeoutMs: TOAST_MS })
113}
114
115/**
116 * Registers the two hooks.
117 *
118 * `session.compact` hands back the conversation itself in place of a
119 * summary, less the tool calls and results a decision model judged no
120 * longer needed. It
121 * fails open: on any error, and when too little would be removed, it says
122 * why in one line and hands the compaction on to the built-in summary.
123 *
124 * `turn.complete` requests a compaction once the main conversation's
125 * context reaches `compactAtPercent`, one request at a time, and not again
126 * while usage stays near what a compaction that could not get under the
127 * threshold left.
128 *
129 * @param on the engine's registrar
130 * @param options the plugin's options
131 */
132export const register: Register = (on, options) => {
133  const config = configOf(options)
134  const providers: readonly ProviderName[] = eligibleOf(config)
135
136  // Whether the hook below ran while `turn.complete` waited on the
137  // compaction it requested; undefined while it waits on none. Any
138  // compaction that reaches the hook will do: a plugin that sends
139  // `session.compact` past this one sends every trigger past it.
140  let isReached: boolean | undefined
141
142  on('session.compact', async ($, e, next) => {
143    if (isReached === false) {
144      isReached = true
145    }
146
147    // A precompute installs nothing and its result is used only if the
148    // conversation is still the same when a real compaction comes. Deciding
149    // then would send the conversation to a third party, and pay for it,
150    // for a result that may be thrown away; the engine's own precompute is
151    // left to stand as the fallback this hook fails open to.
152    if (e.trigger === 'precompute') {
153      return next(e)
154    }
155
156    // Held outside the `try` so that the line written when it fails is
157    // redacted with whatever had been resolved by then.
158    let credentials: Credentials = {}
159    let result
160
161    try {
162      // Options that name no provider the person chose are acted on in no
163      // way: not even a credential is read for them.
164      if (config.refusal !== undefined) {
165        throw new Error(config.refusal)
166      }
167
168      // Credentials are read here, for this compaction, so a key set or
169      // rotated after the module loaded is the one that is used. What the
170      // host says when it refuses a read is its own text, so it is quoted
171      // short like a provider's.
172      const { environment, problem } = await readEnvironment(
173        $,
174        options,
175        providers,
176      ).catch(error => {
177        throw new Error(
178          `the environment could not be read: ${briefOf(messageOf(error), {})}`,
179        )
180      })
181
182      credentials = credentialsOf(options, environment)
183
184      if (config.unknownProviders !== undefined) {
185        log($, unknownLineOf(config.unknownProviders), credentials)
186      }
187
188      if (problem !== undefined) {
189        log(
190          $,
191          `the settings could not be read (${briefOf(problem, credentials)}); ` +
192            'credentials are taken from the options and the environment alone',
193          credentials,
194        )
195      }
196
197      result = await run({
198        messages: e.messages,
199        instructions: e.instructions,
200        config,
201        // Only the providers the person allows may be sent anything, so
202        // only their credentials go on. Every line shown is still redacted
203        // with all that was resolved: a key of another provider is no less
204        // a secret.
205        credentials: credentialsFor(providers, credentials),
206        ports: {
207          fetch: (url, init) => $.http.fetch(url, init),
208          pause: async (ms, signal) => {
209            if (next.budget.remainingMs < ms + PAUSE_RESERVE_MS) {
210              return false
211            }
212
213            await $.clock.sleep(ms, {
214              signal: AbortSignal.any([next.signal, signal]),
215            })
216
217            return true
218          },
219          after: (ms, fn) => $.clock.after(ms, fn),
220          signal: next.signal,
221        },
222      })
223    } catch (error) {
224      tell($, `built-in summary used instead: ${messageOf(error)}`, credentials)
225
226      return next(e)
227    }
228
229    if (result.routing !== undefined) {
230      log($, `provider decision: ${result.routing}`, credentials)
231    }
232
233    for (const line of decisionLinesOf(result.outcome.decisions)) {
234      log($, line, credentials)
235    }
236
237    const reduction = reductionOf(result.outcome)
238
239    if (reduction <= 0 || reduction < config.minReductionRatio) {
240      tell(
241        $,
242        'built-in summary used instead: the reduction is below the ' +
243          `${percentOf(config.minReductionRatio)} minimum (${summaryOf(result)})`,
244        credentials,
245      )
246
247      return next(e)
248    }
249
250    tell(
251      $,
252      `compacted without a summary: ${result.outcome.messages.length} of ` +
253        `${e.messages.length} messages remain (${summaryOf(result)})`,
254      credentials,
255    )
256
257    return { messages: result.outcome.messages }
258  })
259
260  const arm = armOf()
261  let isCompacting = false
262  // A plugin seated before this one (Claude Code's cc-plugin-sec-default,
263  // outermost for Team and Enterprise plans, on a machine with managed
264  // settings, and by default while Claude Code cannot tell that neither
265  // applies) can send `session.compact` past this module. A requested
266  // compaction is then only the built-in summary, earlier than Claude Code's
267  // own threshold, and a seat holds until the process ends.
268  let isPassedOver = false
269
270  on('turn.complete', async ($, e, next) => {
271    // A turn the person interrupted is not a moment to compact: they stopped
272    // the session to say something, and a compaction would hold it paused.
273    const isDue =
274      config.compactAtPercent > 0 &&
275      e.agentId === undefined &&
276      !e.isAborted &&
277      !isCompacting &&
278      !isPassedOver
279
280    if (isDue) {
281      isCompacting = true
282
283      try {
284        const { context } = await $.session.usage()
285
286        if (isCompactionDue(arm, context.percent, config.compactAtPercent)) {
287          let wasReached = false
288
289          isReached = false
290
291          const out = await $.session.compact().finally(() => {
292            wasReached = isReached === true
293            isReached = undefined
294          })
295
296          // A skip is a veto from above: nothing compacted, and nothing says
297          // the hook below would not have run.
298          if (out.skip === undefined && !wasReached) {
299            isPassedOver = true
300            tell(
301              $,
302              'Claude Code compacted with its built-in summary without asking ' +
303                'this mod: a plugin that runs first (such as ' +
304                'cc-plugin-sec-default) sends session.compact past it. No ' +
305                `compaction is requested at ${config.compactAtPercent}% until this ` +
306                "process ends; Claude Code's own threshold applies",
307              {},
308            )
309          }
310
311          settle(
312            arm,
313            (await $.session.usage()).context.percent,
314            config.compactAtPercent,
315          )
316        }
317      } catch (error) {
318        // No credential is resolved on this path; the reason is the host's
319        // own text, so it is still quoted short and held to the rule that
320        // nothing after the word `Bearer` is shown.
321        log(
322          $,
323          `compaction at ${config.compactAtPercent}% of the context was ` +
324            `not run: ${briefOf(messageOf(error), {})}`,
325          {},
326        )
327      } finally {
328        isCompacting = false
329      }
330    }
331
332    return next(e)
333  })
334}
335
hooks/compact.ts 847 lines
1import type {
2  SessionMessage,
3  ToolResultSummary,
4  ToolUseSummary,
5} from 'claude-code'
6
7import type { Limits } from './providers'
8import { estimatedTokensOf, headOf } from './state'
9import type { Call, Fitted, Stage } from './state'
10import { bytesOf, noulOf } from './systemone'
11import type { Questions, Reply, Wire } from './systemone'
12
13/**
14 * Sends one batch of questions about a state and resolves with the reply.
15 */
16export type Ask = (state: unknown, questions: Questions) => Promise<Reply>
17
18/**
19 * What one request may hold, in estimated tokens: the person's budgets,
20 * held under what the provider documents, and the state's share of the
21 * request held to what a batch of questions leaves.
22 */
23export type Budget = {
24  stateTokens: number
25  requestTokens: number
26  questions?: number
27  /**
28   * For a provider that caps the request body in bytes: the bytes a body
29   * may take, already held to `LIMIT_SHARE` of the cap, and the bytes it
30   * takes besides its questions.
31   */
32  bytes?: { limit: number; state: number }
33}
34
35/**
36 * The two probabilities answered for one call.
37 */
38export type Scores = {
39  keepCall: number
40  keepResult: number
41}
42
43/**
44 * What happens to a call: `pinned` and `keep` leave it whole, `truncate`
45 * keeps the call and the head of its result, `drop` removes both.
46 */
47export type Action = 'pinned' | 'keep' | 'truncate' | 'drop'
48
49export type Decision = Scores & {
50  call: Call
51  action: Action
52}
53
54/**
55 * What the batches reported between them.
56 */
57type Reported = {
58  /**
59   * The largest `input_tokens` any batch reported. Every batch sends the
60   * same state, so the largest is the one to hold against the estimate.
61   * A provider that counts the state once a question reports it multiplied
62   * by the questions of that batch.
63   */
64  inputTokens?: number
65  /**
66   * The costs the batches reported, summed.
67   */
68  cost?: number
69}
70
71/**
72 * A finished compaction: the conversation as it should read afterwards and
73 * the figures the report is written from.
74 */
75export type Outcome = {
76  messages: SessionMessage[]
77  decisions: Decision[]
78  charsBefore: number
79  charsAfter: number
80  stateTokens: number
81  /**
82   * The reduction the state needed; absent from an outcome that asked a
83   * provider nothing.
84   */
85  stage?: Stage
86  requests: number
87  reported: Reported
88  /**
89   * How many results were in fact cut to their head. It can be fewer than
90   * the `truncate` decisions: a result too short to gain from a cut is left
91   * whole, and its call then counts with the ones kept.
92   */
93  shortened: number
94}
95
96/**
97 * What the questions about a set of calls need of a request, whichever
98 * provider it goes to.
99 */
100export type Demand = {
101  /**
102   * The estimated size of the longest single question: what a limit stated
103   * for "the state plus the longest question" has to leave free.
104   */
105  longestQuestion: number
106  /**
107   * How many calls a request must at least be able to ask about.
108   */
109  batchCalls: number
110  /**
111   * The estimated size of the questions of that many calls, taking the
112   * calls whose questions are longest.
113   */
114  batchTokens: number
115  /**
116   * The UTF-8 bytes the questions of one request may take: those of the
117   * calls whose questions take the most bytes, `batchCalls` of them or as
118   * many as the provider's question cap lets one request hold, whichever
119   * is fewer. What a cap on the body in bytes has to leave free.
120   */
121  batchBytes: number
122}
123
124/**
125 * The questions asked about each call.
126 */
127const QUESTIONS_PER_CALL = 2
128
129/**
130 * What a request costs around its state and questions: the `model` field
131 * and the three key names, which are about the same in every wire format.
132 */
133const ENVELOPE_TOKENS = 32
134
135/**
136 * How many calls every request must have room to ask about, beside the
137 * state. Each request carries the whole state, so a state allowed to fill
138 * the request leaves room for one call's questions at a time, and the state
139 * is then paid for once per call instead of once per batch.
140 */
141const MIN_CALLS_PER_REQUEST = 16
142
143/**
144 * The most requests one compaction sends. The state rides in every one of
145 * them, so this bounds what a compaction can cost at this many times the
146 * state; a conversation that would need more is left to the built-in
147 * summary.
148 */
149const MAX_REQUESTS = 16
150
151/**
152 * How many requests are in flight at once. Waiting on a request is not
153 * charged to the hook, so there is no need to send every batch at the same
154 * moment, which is what a provider's rate limit is most likely to refuse.
155 */
156const CONCURRENT_REQUESTS = 3
157
158/**
159 * The share of a provider's documented limits a budget may reach. The token
160 * estimate is made without a tokenizer and its weights were fitted to one
161 * model, so a budget right at a limit could be over it by the provider's
162 * own count, and a provider may cut what is over without saying so.
163 */
164export const LIMIT_SHARE = 0.85
165
166/**
167 * A result is left whole unless cutting it saves more than the note that
168 * replaces its tail costs.
169 */
170const NOTE_ROOM = 120
171
172/**
173 * The scores a pinned call is reported with: it was not asked about, and it
174 * stays whole.
175 */
176const UNASKED: Scores = { keepCall: 1, keepResult: 1 }
177
178/**
179 * The id of the question whether a call should stay.
180 */
181function callQuestionId(call: Call): string {
182  return `call_${call.id}`
183}
184
185/**
186 * The id of the question whether a call's whole output should stay.
187 */
188function resultQuestionId(call: Call): string {
189  return `result_${call.id}`
190}
191
192/**
193 * What is asked about a single call, as two questions. They are separate
194 * because the answers differ in practice: that a file was read can matter
195 * long after its contents stopped mattering.
196 *
197 * The rubric they are read under is in the state's `context`, sent once.
198 *
199 * @returns its two `noul` questions, by id
200 */
201export function questionsOf(call: Call): Questions {
202  const named = `tool call ${call.id} (${call.tool})`
203  const outcome = call.isError ? 'an error, ' : ''
204
205  return {
206    [callQuestionId(call)]: {
207      type: 'noul',
208      instructions:
209        `Does the assistant still need to know that it made ${named}, and ` +
210        'with which input, to carry on with the goal?',
211    },
212    [resultQuestionId(call)]: {
213      type: 'noul',
214      instructions:
215        `Does the complete output of ${named}, ${outcome}` +
216        `${call.resultChars} characters long, have to stay word for word ` +
217        'because the assistant still relies on its content and running the ' +
218        'tool again would not bring it back?',
219    },
220  }
221}
222
223/**
224 * The estimated size of each of a call's questions and of the two together,
225 * as they ride in a request body written in the route's wire format, with
226 * what the provider counts for each question beyond its text; and the UTF-8
227 * bytes of the two, each with the comma after it.
228 */
229function questionTokensOf(
230  call: Call,
231  wire: Wire,
232): { both: number; longest: number; bytes: number } {
233  let both = 0
234  let longest = 0
235  let bytes = 0
236
237  for (const [id, question] of Object.entries(questionsOf(call))) {
238    const json = wire.questionJsonOf(id, question)
239    const tokens = estimatedTokensOf(json) + 1 + wire.tokensPerQuestion
240
241    both += tokens
242    longest = Math.max(longest, tokens)
243    bytes += bytesOf(json) + 1
244  }
245
246  return { both, longest, bytes }
247}
248
249/**
250 * The sum of the `count` largest of some sizes.
251 */
252function largestOf(sizes: readonly number[], count: number): number {
253  return [...sizes]
254    .sort((a, b) => b - a)
255    .slice(0, count)
256    .reduce((sum, size) => sum + size, 0)
257}
258
259/**
260 * Measures what the questions about the calls need of a request: the
261 * longest single question, and the questions of `MIN_CALLS_PER_REQUEST`
262 * calls, or of all of them when there are fewer. The calls with the longest
263 * questions are the ones counted, so the room set aside holds whichever
264 * calls end up in a batch together.
265 *
266 * @param calls the calls that will be asked about
267 * @param wire the wire format the questions are written in
268 * @param maxQuestions the provider's cap on the questions of one request,
269 * when it has one; it bounds only the bytes set aside
270 * @returns the demand, all zero when there are no calls
271 */
272export function demandOf(
273  calls: readonly Call[],
274  wire: Wire,
275  maxQuestions?: number,
276): Demand {
277  const sizes = calls.map(call => questionTokensOf(call, wire))
278  const batchCalls = Math.min(MIN_CALLS_PER_REQUEST, sizes.length)
279  const byteCalls =
280    maxQuestions === undefined
281      ? batchCalls
282      : Math.min(batchCalls, Math.floor(maxQuestions / QUESTIONS_PER_CALL))
283
284  return {
285    longestQuestion: sizes.reduce(
286      (longest, size) => Math.max(longest, size.longest),
287      0,
288    ),
289    batchCalls,
290    batchTokens: largestOf(
291      sizes.map(size => size.both),
292      batchCalls,
293    ),
294    batchBytes: largestOf(
295      sizes.map(size => size.bytes),
296      byteCalls,
297    ),
298  }
299}
300
301/**
302 * Holds the person's budgets against a provider's limits and against each
303 * other.
304 *
305 * A budget above `LIMIT_SHARE` of a documented limit is lowered to it rather
306 * than trusted. The state is further held to what the request leaves once
307 * the questions of a batch are set aside: a state that filled the request
308 * would be sent again for every single call.
309 *
310 * @param want the configured budgets
311 * @param limits the provider's documented limits
312 * @param demand what the questions need of a request
313 * @returns the budget one request is held to; throws when the request has
314 * no room for a state beside one batch of questions
315 */
316export function budgetOf(
317  want: { maxStateTokens: number; maxRequestTokens: number },
318  limits: Limits,
319  demand: Demand,
320): Budget {
321  const requestTokens = Math.min(
322    want.maxRequestTokens,
323    Math.floor(limits.maxRequestTokens * LIMIT_SHARE),
324  )
325  const beside = requestTokens - ENVELOPE_TOKENS - demand.batchTokens
326
327  if (beside < 1) {
328    throw new Error(
329      `a request of ${requestTokens} tokens has no room for a state beside ` +
330        `the questions of ${demand.batchCalls} ` +
331        `${demand.batchCalls === 1 ? 'call' : 'calls'}, which take about ` +
332        `${demand.batchTokens}`,
333    )
334  }
335
336  const budget: Budget = {
337    stateTokens: Math.min(
338      want.maxStateTokens,
339      Math.floor(limits.maxStateTokens * LIMIT_SHARE) - demand.longestQuestion,
340      beside,
341    ),
342    requestTokens,
343  }
344
345  if (limits.maxQuestions !== undefined) {
346    budget.questions = limits.maxQuestions
347  }
348
349  return budget
350}
351
352/**
353 * Splits the calls into batches, each of which fits one request beside the
354 * state under both the token budget and the provider's question count.
355 *
356 * The state is never split: every batch is asked against all of it, so the
357 * only thing that varies between requests is which calls they ask about.
358 *
359 * @param calls the calls to ask about, in order
360 * @param stateTokens the estimated size of the fitted state
361 * @param budget what one request may hold
362 * @param wire the wire format the questions are written in
363 * @returns the batches, in order; throws when the state leaves room for not
364 * even one call's questions, and when there would be more batches than
365 * `MAX_REQUESTS`
366 */
367export function batchesOf(
368  calls: readonly Call[],
369  stateTokens: number,
370  budget: Budget,
371  wire: Wire,
372): Call[][] {
373  const room = budget.requestTokens - stateTokens - ENVELOPE_TOKENS
374  const byteRoom =
375    budget.bytes === undefined
376      ? Infinity
377      : budget.bytes.limit - budget.bytes.state
378  const mostCalls =
379    budget.questions === undefined
380      ? Infinity
381      : Math.floor(budget.questions / QUESTIONS_PER_CALL)
382
383  if (mostCalls < 1) {
384    throw new Error(
385      `a request may hold ${budget.questions} questions, fewer than the ` +
386        `${QUESTIONS_PER_CALL} one call needs`,
387    )
388  }
389
390  const batches: Call[][] = []
391  let batch: Call[] = []
392  let used = 0
393  let usedBytes = 0
394
395  for (const call of calls) {
396    const { both, bytes } = questionTokensOf(call, wire)
397
398    if (both > room) {
399      throw new Error(
400        `no question fits beside the state: the state takes about ` +
401          `${stateTokens} of the ${budget.requestTokens} tokens a request ` +
402          'may hold',
403      )
404    }
405
406    if (bytes > byteRoom) {
407      throw new Error(
408        `no question fits beside the state: the request takes ` +
409          `${budget.bytes?.state} of the ${budget.bytes?.limit} bytes it ` +
410          'may hold before any question',
411      )
412    }
413
414    if (
415      batch.length >= mostCalls ||
416      used + both > room ||
417      usedBytes + bytes > byteRoom
418    ) {
419      batches.push(batch)
420      batch = []
421      used = 0
422      usedBytes = 0
423    }
424
425    batch.push(call)
426    used += both
427    usedBytes += bytes
428  }
429
430  if (batch.length > 0) {
431    batches.push(batch)
432  }
433
434  if (batches.length > MAX_REQUESTS) {
435    throw new Error(
436      `asking about ${calls.length} tool calls would take ` +
437        `${batches.length} requests, and one compaction sends at most ` +
438        `${MAX_REQUESTS}`,
439    )
440  }
441
442  return batches
443}
444
445/**
446 * Turns the two probabilities into what happens to the call. The result
447 * question is the stronger claim, so it is read first: a result worth
448 * keeping keeps its call with it.
449 *
450 * @param threshold the probability from which an item is kept
451 */
452export function decide(
453  call: Call,
454  scores: Scores,
455  threshold: number,
456): Decision {
457  if (call.isPinned) {
458    return { call, ...scores, action: 'pinned' }
459  }
460
461  if (scores.keepResult >= threshold) {
462    return { call, ...scores, action: 'keep' }
463  }
464
465  if (scores.keepCall >= threshold) {
466    return { call, ...scores, action: 'truncate' }
467  }
468
469  return { call, ...scores, action: 'drop' }
470}
471
472/**
473 * Says whether cutting a text of this length to its head removes more than
474 * the note that then stands for the rest adds.
475 */
476function isWorthCutting(chars: number, headChars: number): boolean {
477  return chars > headChars + NOTE_ROOM
478}
479
480/**
481 * A result text cut to its head, with one line saying what was done and by
482 * what, so the assistant reading it later knows the rest existed and how to
483 * get it back. A text too short for the cut to save anything is left as is.
484 */
485function cut(text: string, headChars: number, isError: boolean): string {
486  if (!isWorthCutting(text.length, headChars)) {
487    return text
488  }
489
490  const head = headOf(text, headChars)
491  const kind = isError ? 'error output' : 'output'
492
493  return (
494    `${head}${head === '' ? '' : '\n'}[decision-compaction removed ` +
495    `${text.length - head.length} more characters of this tool ${kind}; ` +
496    'run the tool again if they are needed]'
497  )
498}
499
500/**
501 * A result with its text cut, or the same object when nothing was cut. The
502 * stored record is left off a cut result: it holds the full output.
503 */
504function cutResult(
505  result: ToolResultSummary,
506  headChars: number,
507): ToolResultSummary {
508  const { tool_use_id, isError } = result
509  const text = cut(result.text, headChars, isError)
510
511  if (text === result.text) {
512    return result
513  }
514
515  return { tool_use_id, text, isError }
516}
517
518/**
519 * A tool use whose mirrored outcome is cut like its result, or the same
520 * object when nothing was cut. Only used inside a message that is rebuilt
521 * anyway, so the copy and the result it mirrors agree.
522 */
523function cutUse(use: ToolUseSummary, headChars: number): ToolUseSummary {
524  if (use.text === undefined) {
525    return use
526  }
527
528  const text = cut(use.text, headChars, use.isError === true)
529
530  if (text === use.text) {
531    return use
532  }
533
534  const { result: _record, ...kept } = use
535
536  return { ...kept, text }
537}
538
539/**
540 * Carries the decisions out on the conversation.
541 *
542 * A message nothing touched is returned as the very object it came in as, so
543 * it still carries the engine's `handle` and stands whole. A changed message
544 * is a new object with no `handle`, which the engine builds from its role,
545 * text and tool blocks; because that loses whatever else the original held,
546 * a message is rebuilt only when one of its own blocks changed. A dropped
547 * call takes its result with it, so no result is left without its call, and
548 * a message left with no text and no block is removed.
549 *
550 * @param messages the conversation
551 * @param decisions what was decided for each paired call
552 * @param headChars how much of a truncated result stays
553 * @returns the conversation afterwards, oldest first
554 */
555export function rebuild(
556  messages: readonly SessionMessage[],
557  decisions: readonly Decision[],
558  headChars: number,
559): SessionMessage[] {
560  const fate = new Map<string, 'truncate' | 'drop'>()
561
562  for (const { call, action } of decisions) {
563    if (action === 'truncate' || action === 'drop') {
564      fate.set(call.toolUseId, action)
565    }
566  }
567
568  const rebuilt: SessionMessage[] = []
569
570  for (const message of messages) {
571    const given = message.toolResults ?? []
572    const uses = message.toolUses.filter(
573      use => fate.get(use.tool_use_id) !== 'drop',
574    )
575    const results = given
576      .filter(result => fate.get(result.tool_use_id) !== 'drop')
577      .map(result =>
578        fate.get(result.tool_use_id) === 'truncate'
579          ? cutResult(result, headChars)
580          : result,
581      )
582    const isUntouched =
583      uses.length === message.toolUses.length &&
584      results.length === given.length &&
585      results.every((result, index) => result === given[index])
586
587    if (isUntouched) {
588      rebuilt.push(message)
589      continue
590    }
591
592    const isEmptied =
593      uses.length + results.length === 0 && message.text.trim() === ''
594
595    if (!isEmptied) {
596      rebuilt.push({
597        role: message.role,
598        text: message.text,
599        toolUses: uses.map(use =>
600          fate.get(use.tool_use_id) === 'truncate'
601            ? cutUse(use, headChars)
602            : use,
603        ),
604        ...(results.length > 0 ? { toolResults: results } : {}),
605      })
606    }
607  }
608
609  return rebuilt
610}
611
612/**
613 * The size of a tool input as the model reads it. An input that cannot be
614 * serialised has no size to compare, and counts as nothing.
615 */
616function inputCharsOf(use: ToolUseSummary): number {
617  try {
618    return (JSON.stringify(use.input) ?? '').length
619  } catch {
620    return 0
621  }
622}
623
624/**
625 * The characters a message holds for the model: its text, its tool inputs
626 * and its tool results. The outcome mirrored on a tool use is not counted,
627 * since the result block already is.
628 */
629function charsOf(message: SessionMessage): number {
630  const inputs = message.toolUses.reduce(
631    (sum, use) => sum + inputCharsOf(use),
632    0,
633  )
634  const results = (message.toolResults ?? []).reduce(
635    (sum, result) => sum + result.text.length,
636    0,
637  )
638
639  return message.text.length + inputs + results
640}
641
642function totalChars(messages: readonly SessionMessage[]): number {
643  return messages.reduce((chars, message) => chars + charsOf(message), 0)
644}
645
646/**
647 * The share of the conversation's characters a compaction removed.
648 *
649 * @returns a ratio from 0 to 1; 0 for an empty conversation
650 */
651export function reductionOf(
652  outcome: Pick<Outcome, 'charsBefore' | 'charsAfter'>,
653): number {
654  return outcome.charsBefore === 0
655    ? 0
656    : (outcome.charsBefore - outcome.charsAfter) / outcome.charsBefore
657}
658
659/**
660 * One batch as it came back: the reply and, for every call of the batch,
661 * the two probabilities read from it.
662 */
663type Judged = {
664  reply: Reply
665  scores: [Call, Scores][]
666}
667
668/**
669 * Puts one batch to the provider and reads both answers of every call in
670 * it. A reply that lacks one of them fails the batch: a call nobody answered
671 * for must not be decided by a default.
672 */
673async function judge(
674  batch: readonly Call[],
675  state: unknown,
676  ask: Ask,
677): Promise<Judged> {
678  const reply = await ask(
679    state,
680    Object.fromEntries(
681      batch.flatMap(call => Object.entries(questionsOf(call))),
682    ),
683  )
684
685  return {
686    reply,
687    scores: batch.map(call => [
688      call,
689      {
690        keepCall: noulOf(reply, callQuestionId(call)),
691        keepResult: noulOf(reply, resultQuestionId(call)),
692      },
693    ]),
694  }
695}
696
697/**
698 * The outcome when there is nothing to ask about: the conversation as it is.
699 *
700 * @param messages the conversation
701 * @param calls its paired calls, all of them pinned
702 * @returns an outcome with no request made
703 */
704export function untouched(
705  messages: readonly SessionMessage[],
706  calls: readonly Call[],
707): Outcome {
708  const chars = totalChars(messages)
709
710  return {
711    messages: [...messages],
712    decisions: calls.map(call => decide(call, UNASKED, 0)),
713    charsBefore: chars,
714    charsAfter: chars,
715    stateTokens: 0,
716    requests: 0,
717    reported: {},
718    shortened: 0,
719  }
720}
721
722/**
723 * Runs `work` over the items with at most `width` of them under way at a
724 * time, and resolves with the results in the items' order, whichever order
725 * they came back in. The first failure rejects the whole and starts nothing
726 * further; `onFailure` hears of it at once, so that the caller can stop what
727 * is still under way.
728 */
729async function inTurns<Item, Result>(
730  items: readonly Item[],
731  width: number,
732  work: (item: Item) => Promise<Result>,
733  onFailure: (reason: unknown) => void,
734): Promise<Result[]> {
735  const results: Result[] = []
736  let next = 0
737  let hasFailed = false
738
739  const worker = async () => {
740    while (!hasFailed && next < items.length) {
741      const index = next++
742
743      try {
744        results[index] = await work(items[index] as Item)
745      } catch (error) {
746        hasFailed = true
747        onFailure(error)
748
749        throw error
750      }
751    }
752  }
753
754  await Promise.all(
755    Array.from({ length: Math.min(width, items.length) }, worker),
756  )
757
758  return results
759}
760
761/**
762 * Asks about every candidate call and applies the answers to the
763 * conversation. The batches go out `CONCURRENT_REQUESTS` at a time, each
764 * with the whole state, and each call is decided by the answers of its own
765 * batch, in whatever order the batches come back. One batch failing fails
766 * the compaction, since half the answers decide nothing; no batch is sent
767 * after it, and `halt` is told at once so the others can be abandoned.
768 *
769 * @param messages the conversation
770 * @param calls its paired calls, pinned ones included
771 * @param fitted the state, already fitted to the budget, with its size as
772 * the route's wire format carries it
773 * @param ask how a batch is sent
774 * @param settings the budget, the route's wire format, the keep threshold,
775 * the truncation length, and `halt`, which hears the reason the moment a
776 * batch fails
777 */
778export async function compact(
779  messages: readonly SessionMessage[],
780  calls: readonly Call[],
781  fitted: Fitted,
782  ask: Ask,
783  settings: {
784    budget: Budget
785    wire: Wire
786    keepThreshold: number
787    truncateHeadChars: number
788    halt?: (reason: Error) => void
789  },
790): Promise<Outcome> {
791  const batches = batchesOf(
792    calls.filter(call => !call.isPinned),
793    fitted.tokens,
794    settings.budget,
795    settings.wire,
796  )
797  const answered = await inTurns(
798    batches,
799    CONCURRENT_REQUESTS,
800    batch => judge(batch, fitted.state, ask),
801    reason =>
802      settings.halt?.(
803        reason instanceof Error ? reason : new Error(String(reason)),
804      ),
805  )
806  const scores = new Map<Call, Scores>()
807  const reported: Reported = {}
808
809  for (const { scores: judged, reply } of answered) {
810    for (const [call, value] of judged) {
811      scores.set(call, value)
812    }
813
814    if (reply.usage.input_tokens !== undefined) {
815      reported.inputTokens = Math.max(
816        reported.inputTokens ?? 0,
817        reply.usage.input_tokens,
818      )
819    }
820
821    if (reply.usage.cost !== undefined) {
822      reported.cost = (reported.cost ?? 0) + reply.usage.cost
823    }
824  }
825
826  const decisions = calls.map(call =>
827    decide(call, scores.get(call) ?? UNASKED, settings.keepThreshold),
828  )
829  const kept = rebuild(messages, decisions, settings.truncateHeadChars)
830
831  return {
832    messages: kept,
833    decisions,
834    charsBefore: totalChars(messages),
835    charsAfter: totalChars(kept),
836    stateTokens: fitted.tokens,
837    stage: fitted.stage,
838    requests: batches.length,
839    reported,
840    shortened: decisions.filter(
841      ({ call, action }) =>
842        action === 'truncate' &&
843        isWorthCutting(call.resultChars, settings.truncateHeadChars),
844    ).length,
845  }
846}
847
hooks/config.ts 235 lines
1import type { PluginOptions } from 'claude-code'
2
3import { cutOf, providerOf, PROVIDERS } from './providers'
4import type { ProviderName } from './providers'
5
6/**
7 * The plugin's options as the hooks use them: every value present, typed
8 * and inside the range it is meaningful in.
9 */
10export type Config = {
11  provider: ProviderName
12  /**
13   * Why no compaction may be decided with these options, when there is such
14   * a reason. It is set for an option that says where the conversation is
15   * sent and cannot be read: a destination is never guessed.
16   */
17  refusal?: string
18  /**
19   * The model name for the configured provider; absent for its default.
20   */
21  model?: string
22  providerDecision: boolean
23  /**
24   * The providers the provider decision may pick besides the configured
25   * one, in `PROVIDERS` order.
26   */
27  decisionProviders: readonly ProviderName[]
28  /**
29   * The names in `decisionProviders` that are no provider, as given; absent
30   * when there are none. They are dropped, not refused: leaving a name out
31   * can only narrow where the conversation is sent.
32   */
33  unknownProviders?: string[]
34  keepThreshold: number
35  preserveRecentMessages: number
36  compactAtPercent: number
37  minReductionRatio: number
38  /**
39   * The state budget the person set; absent for the one each route asks
40   * for (`wantedOf`).
41   */
42  maxStateTokens?: number
43  /**
44   * The request budget the person set; absent for the one each route asks
45   * for (`wantedOf`).
46   */
47  maxRequestTokens?: number
48  truncateHeadChars: number
49}
50
51/**
52 * What an option reads as when it is unset or unusable; the manifest's
53 * `userConfig` states the same values to the person. The two budgets have
54 * none here: each route has its own (`wantedOf`), and the manifest states
55 * no default for them, so that one never set stays absent.
56 */
57const DEFAULTS = {
58  provider: 'typesafe',
59  providerDecision: false,
60  decisionProviders: PROVIDERS,
61  keepThreshold: 0.5,
62  preserveRecentMessages: 6,
63  compactAtPercent: 60,
64  minReductionRatio: 0.25,
65  truncateHeadChars: 300,
66} as const satisfies Config
67
68/**
69 * A numeric option held to a range. A value that is not a finite number
70 * reads as the default; one outside the range is moved to its nearest end.
71 */
72function within(
73  value: unknown,
74  fallback: number,
75  low: number,
76  high: number,
77): number {
78  const number =
79    typeof value === 'number' && Number.isFinite(value) ? value : fallback
80
81  return Math.min(high, Math.max(low, number))
82}
83
84/**
85 * Reads the `decisionProviders` option: a list, or the names in one text
86 * separated by commas. Unset, it is every provider. The host fills in the
87 * manifest's default for a field that was never set, so an empty text is a
88 * field the person cleared, and like an empty list it names no provider:
89 * only the configured one is then eligible. Names are matched as `provider`
90 * is, exactly; a value of any other type names no provider.
91 */
92function decisionProvidersOf(value: unknown): {
93  named: readonly ProviderName[]
94  unknown: string[]
95} {
96  if (value === undefined || value === null) {
97    return { named: DEFAULTS.decisionProviders, unknown: [] }
98  }
99
100  const given = Array.isArray(value)
101    ? value
102    : typeof value === 'string'
103      ? value.split(',')
104      : [value]
105  const names = given
106    .map(name =>
107      typeof name === 'string' ? name.trim() : String(JSON.stringify(name)),
108    )
109    .filter(name => name !== '')
110
111  return {
112    named: PROVIDERS.filter(provider => names.includes(provider)),
113    unknown: [...new Set(names.filter(name => providerOf(name) === undefined))],
114  }
115}
116
117/**
118 * The providers a compaction may send anything to: the configured one, and
119 * with the provider decision on also those `decisionProviders` names, in
120 * `PROVIDERS` order. Everything that reads a credential or offers a route
121 * goes by this one list.
122 *
123 * @param config the configuration
124 * @returns the providers
125 */
126export function eligibleOf(config: Config): ProviderName[] {
127  return PROVIDERS.filter(
128    provider =>
129      provider === config.provider ||
130      (config.providerDecision && config.decisionProviders.includes(provider)),
131  )
132}
133
134/**
135 * A budget option: a whole number of tokens from 1 up, or absent when it is
136 * unset or not a number, so that the route's own budget stands.
137 */
138function budgetOptionOf(value: unknown): number | undefined {
139  return typeof value === 'number' && Number.isFinite(value)
140    ? Math.max(1, Math.floor(value))
141    : undefined
142}
143
144/**
145 * Says whether an option was left unset: absent, or text with nothing in
146 * it, which is what a cleared field holds.
147 */
148function isUnset(value: unknown): boolean {
149  return (
150    value === undefined ||
151    value === null ||
152    (typeof value === 'string' && value.trim() === '')
153  )
154}
155
156/**
157 * Reads the plugin's options. Nothing here throws, because this runs while
158 * the module loads and a throw would take both hooks with it: an option the
159 * person mistyped reads as its default.
160 *
161 * The one exception is `provider`, which decides who is sent the
162 * conversation. Only an unset `provider` reads as the default. A value that
163 * names none of the providers is not replaced by one the person did not
164 * choose: it is reported in `refusal`, and every compaction is then left to
165 * the built-in summary.
166 *
167 * @param options what `register` received
168 * @returns the configuration
169 */
170export function configOf(options: PluginOptions): Config {
171  const named = providerOf(options.provider)
172  const deciding = decisionProvidersOf(options.decisionProviders)
173  const config: Config = {
174    provider: named ?? DEFAULTS.provider,
175    providerDecision: options.providerDecision === true,
176    decisionProviders: deciding.named,
177    keepThreshold: within(options.keepThreshold, DEFAULTS.keepThreshold, 0, 1),
178    preserveRecentMessages: Math.floor(
179      within(
180        options.preserveRecentMessages,
181        DEFAULTS.preserveRecentMessages,
182        0,
183        Infinity,
184      ),
185    ),
186    compactAtPercent: within(
187      options.compactAtPercent,
188      DEFAULTS.compactAtPercent,
189      0,
190      100,
191    ),
192    minReductionRatio: within(
193      options.minReductionRatio,
194      DEFAULTS.minReductionRatio,
195      0,
196      1,
197    ),
198    truncateHeadChars: Math.floor(
199      within(
200        options.truncateHeadChars,
201        DEFAULTS.truncateHeadChars,
202        0,
203        Infinity,
204      ),
205    ),
206  }
207
208  if (named === undefined && !isUnset(options.provider)) {
209    config.refusal =
210      `the provider option is ${cutOf(JSON.stringify(options.provider))}, ` +
211      `which is none of ${PROVIDERS.join(', ')}`
212  }
213
214  if (deciding.unknown.length > 0) {
215    config.unknownProviders = deciding.unknown
216  }
217
218  if (typeof options.model === 'string' && options.model.trim() !== '') {
219    config.model = options.model.trim()
220  }
221
222  const maxStateTokens = budgetOptionOf(options.maxStateTokens)
223  const maxRequestTokens = budgetOptionOf(options.maxRequestTokens)
224
225  if (maxStateTokens !== undefined) {
226    config.maxStateTokens = maxStateTokens
227  }
228
229  if (maxRequestTokens !== undefined) {
230    config.maxRequestTokens = maxRequestTokens
231  }
232
233  return config
234}
235
hooks/providers.ts 1425 lines
1import type { HttpResponse, PluginOptions } from 'claude-code'
2
3import { decodeOpenAI, OPENAI } from './openai'
4import { headOf } from './state'
5import { BARE, bodyOf, bytesOf, idsOf, isRecord, replyOf } from './systemone'
6import type { Question, Questions, Reply, Wire } from './systemone'
7
8/**
9 * The providers that serve the System One protocol, in the order the
10 * manifest lists them. Of two gateways to the same model the one listed
11 * first is the one the provider decision offers.
12 */
13export const PROVIDERS = [
14  'typesafe',
15  'cloudflare',
16  'openrouter',
17  'codiv',
18  'perplexity',
19  'decisions-api-dev',
20  'decisionapi-net',
21  'openai',
22] as const
23
24export type ProviderName = (typeof PROVIDERS)[number]
25
26/**
27 * One way to reach one model: the provider that is called and the model name
28 * as that provider's request body spells it.
29 */
30export type Route = {
31  provider: ProviderName
32  model: string
33}
34
35/**
36 * What a provider's documentation says a request may hold, in tokens as the
37 * provider counts them, or the count a state cut short reports where that
38 * is lower.
39 *
40 * `maxStateTokens` bounds the state together with the longest single
41 * question, which is how TypeSafe states its limit; `maxQuestions` is absent
42 * where no cap is documented. `maxRequestBytes` is a cap on the UTF-8 bytes
43 * of the whole request body, for a provider that states its limit in bytes.
44 */
45export type Limits = {
46  maxStateTokens: number
47  maxRequestTokens: number
48  maxQuestions?: number
49  maxRequestBytes?: number
50}
51
52/**
53 * The budgets a compaction asks for when the person set none: what a route
54 * reads quickly enough, as measured on 2026-10-11, for every request of a
55 * compaction to be answered before its deadline. Sixteen requests go out
56 * three at a time under thirty seconds, so each one is held to about four
57 * and a half seconds with 32 questions in it. Where the state is read once
58 * a request, the request takes the provider's whole window, so that a
59 * compaction needs fewer of them; where it is read once a question or once
60 * a chunk of questions, the request is held to the state and the questions
61 * of sixteen calls beside it, since a fuller one is only slower. The
62 * budget then holds both to the limits as it does any value the person
63 * sets.
64 *
65 * `maxRequestBytes` is a cap on the UTF-8 bytes of the request body that a
66 * route asks for but does not require: past it the provider still answers,
67 * only in a mode it documents as slower and less accurate. It is held to
68 * the same share as a cap in `Limits`, and lifted when the person sets a
69 * request budget of their own, and when the conversation cannot be fitted
70 * under it or its calls would then not go in the requests a compaction may
71 * send: that mode is for the requests that need it, and the built-in
72 * summary is a worse outcome than a slower decision.
73 */
74export type Wanted = {
75  maxStateTokens: number
76  maxRequestTokens: number
77  maxRequestBytes?: number
78}
79
80/**
81 * The secrets and the account id the providers need, each present only when
82 * one was configured.
83 */
84export type Credentials = {
85  typesafeApiKey?: string
86  openrouterApiKey?: string
87  cloudflareApiToken?: string
88  cloudflareAccountId?: string
89  codivApiKey?: string
90  perplexityApiKey?: string
91  decisionsApiKey?: string
92  decisionapiApiKey?: string
93  openaiApiKey?: string
94}
95
96/**
97 * The environment variable each credential falls back to when its plugin
98 * option is unset.
99 */
100const ENV_NAMES = {
101  typesafeApiKey: 'TYPESAFE_API_KEY',
102  openrouterApiKey: 'OPENROUTER_API_KEY',
103  cloudflareApiToken: 'CLOUDFLARE_API_TOKEN',
104  cloudflareAccountId: 'CLOUDFLARE_ACCOUNT_ID',
105  codivApiKey: 'CODIV_API_KEY',
106  perplexityApiKey: 'PERPLEXITY_API_KEY',
107  decisionsApiKey: 'DECISIONS_API_KEY',
108  decisionapiApiKey: 'DECISIONAPI_API_KEY',
109  openaiApiKey: 'OPENAI_API_KEY',
110} as const satisfies Record<keyof Credentials, string>
111
112type EnvName = (typeof ENV_NAMES)[keyof Credentials]
113
114/**
115 * The values of the credential variables as one source holds them.
116 */
117export type Environment = Partial<Record<EnvName, string | undefined>>
118
119/**
120 * One request as `$.http.fetch` takes it.
121 */
122type Exchange = {
123  url: string
124  init: { method: 'POST'; headers: Record<string, string>; body: string }
125}
126
127/**
128 * Everything that differs between providers. The call path and the answer
129 * validation are shared, so a provider is this record and nothing else.
130 */
131type Descriptor = {
132  /**
133   * The provider's name as a sentence about it spells it.
134   */
135  title: string
136  defaultModel: string
137  /**
138   * The models the provider is offered with in the routing decision.
139   */
140  models: readonly string[]
141  /**
142   * The model family a model of this provider is, which is what two routes
143   * are compared by: the same Jev is served directly and through gateways.
144   */
145  family: (model: string) => string
146  /**
147   * True for a provider that forwards to a model another provider hosts.
148   */
149  isGateway: boolean
150  limits: Limits
151  /**
152   * The limits of a model that holds less or more than `limits`, for a
153   * provider whose models differ; `limits` stands for any other model.
154   */
155  modelLimitsOf?: (model: string) => Limits | undefined
156  /**
157   * The budgets asked for when the person set none.
158   */
159  wanted: Wanted
160  /**
161   * The budgets of a model that reads faster or slower than `wanted`
162   * assumes; `wanted` stands for any other model.
163   */
164  modelWantedOf?: (model: string) => Wanted | undefined
165  /**
166   * True for a provider whose `usage.input_tokens` counts the state once
167   * for every question of the request, so that what one reading of the
168   * state took is the count divided by the questions asked.
169   */
170  countsStatePerQuestion?: true
171  /**
172   * True for a provider that refuses a request too long for its window
173   * rather than cutting the state, so that its count of input tokens is
174   * never read as a cut.
175   */
176  refusesOverlong?: true
177  needs: readonly (keyof Credentials)[]
178  bodyModelOf: (model: string) => string
179  urlOf: (model: string, credentials: Credentials) => string
180  tokenOf: (credentials: Credentials) => string | undefined
181  wire: Wire
182  /**
183   * Takes the response out of whatever the provider wraps it in and into
184   * the System One shape the readers of a reply take, given the questions
185   * the request asked.
186   */
187  unwrap: (
188    payload: unknown,
189    credentials: Credentials,
190    asked: Questions,
191  ) => unknown
192}
193
194/**
195 * What each Clef model holds, as measured on 2026-10-11. A text state too
196 * long for the window is cut without a word, and the reply then counts
197 * exactly the figures below: 64,000 on `clef` and `clef-omni`, 24,000 on
198 * `clef-flash`. Those are the limits, not the 65,536 and 24,576 the
199 * catalogue states for `clef` and `clef-flash`, since a cut is only seen
200 * at the count it reports. Every model takes 1 to 64 questions (HTTP 422
201 * above that).
202 */
203const CLOUDFLARE_LIMITS = {
204  clef: { maxStateTokens: 64_000, maxRequestTokens: 64_000, maxQuestions: 64 },
205  'clef-flash': {
206    maxStateTokens: 24_000,
207    maxRequestTokens: 24_000,
208    maxQuestions: 64,
209  },
210  'clef-omni': {
211    maxStateTokens: 64_000,
212    maxRequestTokens: 64_000,
213    maxQuestions: 64,
214  },
215} as const satisfies Record<string, Limits>
216
217/**
218 * What each Clef model is asked for. With 32 questions, `clef` answered a
219 * 30,000-token state in 4.1 seconds and a 49,000-token one in 7.4,
220 * `clef-flash` a 10,000-token one in 3.1 and a 19,000-token one in 5.3,
221 * and `clef-omni` a 49,000-token one in 3.4.
222 */
223const CLOUDFLARE_WANTED = {
224  clef: { maxStateTokens: 30_000, maxRequestTokens: 54_400 },
225  'clef-flash': { maxStateTokens: 14_000, maxRequestTokens: 20_400 },
226  'clef-omni': { maxStateTokens: 45_000, maxRequestTokens: 54_400 },
227} as const satisfies Record<keyof typeof CLOUDFLARE_LIMITS, Wanted>
228
229const CLOUDFLARE_MODELS = Object.keys(CLOUDFLARE_LIMITS) as readonly (
230  keyof typeof CLOUDFLARE_LIMITS
231)[]
232
233/**
234 * How many questions one request to either Decisions reseller may hold.
235 */
236const RESELLER_QUESTIONS = 8
237
238/**
239 * The two Decisions resellers state their cap in bytes: the state and the
240 * questions of a request within 32 KiB, and at most eight questions. Both
241 * serve TypeSafe's Jev 1.13 and 1.14, which TypeSafe documents with the
242 * same window, so the token figures are that window. They do not bind:
243 * 32 KiB of English is far fewer tokens, and the state is fitted to the
244 * byte cap as well. They stand against what the provider counts, so a
245 * reply that counts the whole window is still read as a state that was cut
246 * short.
247 */
248const RESELLER: Limits = {
249  maxStateTokens: 32_000,
250  maxRequestTokens: 64_000,
251  maxQuestions: RESELLER_QUESTIONS,
252  maxRequestBytes: 32_768,
253}
254
255/**
256 * The question ids decisions-api.dev accepts: a letter first, then letters,
257 * digits, `_` or `-`, 64 characters at most. The mod's ids may hold `.` and
258 * run to 100 characters, so the request names each question by its place
259 * instead.
260 */
261const ALIAS_OF = (index: number) => `q${index}`
262
263/**
264 * The longest alias a request can carry: the one of the last place the
265 * question cap allows. A question is measured under it, whatever its own
266 * id, since the alias is what is sent.
267 */
268const LONGEST_ALIAS = ALIAS_OF(RESELLER_QUESTIONS - 1)
269
270/**
271 * The System One body with every question id replaced by its place in the
272 * request, `q0`, `q1`, …. The ids are checked against the mod's own rule
273 * first, as for every provider; option names inside a `choice` are left as
274 * they are, since only question ids are restricted.
275 */
276const ALIASED: Wire = {
277  encode: (model, state, questions) =>
278    bodyOf(
279      model,
280      state,
281      Object.fromEntries(
282        idsOf(questions).map((id, index) => [
283          ALIAS_OF(index),
284          questions[id] as Question,
285        ]),
286      ),
287    ),
288  questionJsonOf: (_id, question) =>
289    BARE.questionJsonOf(LONGEST_ALIAS, question),
290  stateJsonOf: BARE.stateJsonOf,
291  tokensPerQuestion: 0,
292}
293
294/**
295 * A Jev id as TypeSafe or a gateway to it names it: bare (`jev-latest`,
296 * `jev-1.14.0`), which OpenRouter maps onto TypeSafe's namespace before
297 * routing, or under that namespace (`typesafe/jev-1.14`) or its alias
298 * (`~typesafe/jev-latest`). The namespace alone does not make a model Jev:
299 * any other model TypeSafe publishes there is a model of its own.
300 */
301const JEV = /^(?:~?typesafe\/)?jev(?:-|$)/
302
303/**
304 * A Jev id that pins a release, captured as major and minor version: the
305 * `jev-1.14.0` TypeSafe takes, the `typesafe/jev-1.14` of the gateways, and
306 * the `typesafe/jev-1.14-20261014` a gateway's reply names.
307 */
308const JEV_RELEASE = /^(?:~?typesafe\/)?jev-(\d+\.\d+)(?:[.-]|$)/
309
310/**
311 * The release each provider's Jev aliases named on 2026-10-16. An alias
312 * moves when a release ships, and not at every provider at once: TypeSafe's
313 * own `jev-latest` was still Jev 1.13, its `jev-preview` Jev 1.14, while
314 * OpenRouter's `~typesafe/jev-latest`, which "tracks the newest release",
315 * already answered as Jev 1.14. decisions-api.dev's `jev-latest` answered
316 * as Jev 1.13.
317 * decisionapi.net documents Jev 1.14 as its default and its
318 * `~typesafe/jev-latest` as 1.14; its reply names no model, so that is
319 * documented, not measured.
320 */
321const JEV_ALIASES: Partial<
322  Record<ProviderName, Readonly<Record<string, string>>>
323> = {
324  typesafe: { 'jev-latest': '1.13', 'jev-preview': '1.14' },
325  openrouter: { 'jev-latest': '1.14', '~typesafe/jev-latest': '1.14' },
326  'decisions-api-dev': { 'jev-latest': '1.13' },
327  'decisionapi-net': { 'jev-latest': '1.14', '~typesafe/jev-latest': '1.14' },
328}
329
330/**
331 * The family of a model at a provider that serves TypeSafe's Jev: one
332 * family for each Jev release, since two releases are two models, and the
333 * model itself for anything that is not Jev. A Jev alias whose release is
334 * not known is the family `jev`, which no pinned release joins.
335 */
336function jevFamilyOf(provider: ProviderName): (model: string) => string {
337  return model => {
338    const named = model.trim()
339
340    if (!JEV.test(named)) {
341      return named
342    }
343
344    const aliases = JEV_ALIASES[provider] ?? {}
345    const release =
346      JEV_RELEASE.exec(named)?.[1] ??
347      (Object.hasOwn(aliases, named) ? aliases[named] : undefined)
348
349    return release === undefined ? 'jev' : `jev-${release}`
350  }
351}
352
353/**
354 * The window a model OpenRouter forwards is held to when it is not Jev, as
355 * measured on 2026-10-11 where it cuts a state, below the window its
356 * listing states. OpenRouter's Clef and Clef-flash cut a state at 16,384
357 * tokens, the window of the cheapest host it routes them to, not at the
358 * figures Cloudflare's own endpoint cuts it at; its Clef-omni, which only
359 * Cloudflare hosts, cut at 64,000.
360 */
361const OPENROUTER_CLEF_WINDOWS: Readonly<Record<string, number>> = {
362  'cloudflare/clef': 16_384,
363  'cloudflare/clef-flash': 16_384,
364  'cloudflare/clef-omni': 64_000,
365}
366
367/**
368 * The window of any other model OpenRouter forwards that is not Jev: what
369 * the mod holds a model to whose limit no one documented.
370 */
371const OPENROUTER_OTHER_WINDOW = 32_000
372
373/**
374 * The text OpenRouter sends to Jev in TypeSafe's default mode: "Requests
375 * with more than about 32,000 bytes of text, and every request with an
376 * image, run in TypeSafe's long-context mode, which TypeSafe says is slower
377 * and less accurate than staying within its default limits."
378 */
379const OPENROUTER_DEFAULT_MODE_BYTES = 32_000
380
381/**
382 * The Workers AI catalogue prefix; a Cloudflare model is `clef` in the body
383 * and this prefix plus `clef` in the URL.
384 */
385const CLOUDFLARE_PREFIX = '@cf/cloudflare/'
386
387/**
388 * How much is quoted of a text this mod did not write (an error body, a
389 * failure envelope, the host's reason for refusing a call): enough to read
390 * the reason, short enough for one toast line.
391 */
392export const REASON_CHARS = 160
393
394/**
395 * The shortest value treated as a secret when a text is redacted. A shorter
396 * one is not a key any of the providers issues, and replacing it wherever
397 * its few characters occur would garble the ordinary words around it.
398 */
399const MIN_SECRET_CHARS = 8
400
401/**
402 * What stands where a credential was. It holds no part of what it replaces,
403 * not even the word that announced it.
404 */
405const REDACTED = '[redacted]'
406
407/**
408 * An `Authorization` value as a response may echo it: the scheme and the
409 * token after it, whoever's token that is. The two are separated by white
410 * space in a header, and by a colon or an equals sign where the header was
411 * written out as a field (`Bearer: ...`, `bearer=...`).
412 */
413const BEARER = /bearer(?:\s*[:=]\s*|\s+)[^\s"'<>]+/gi
414
415function textOf(value: unknown): string | undefined {
416  return typeof value === 'string' && value.trim() !== ''
417    ? value.trim()
418    : undefined
419}
420
421/**
422 * A Cloudflare model's short name, whether it was given so or by its
423 * catalogue id.
424 */
425function cloudflareShortOf(model: string): string {
426  const named = model.trim()
427
428  return named.startsWith(CLOUDFLARE_PREFIX)
429    ? named.slice(CLOUDFLARE_PREFIX.length)
430    : named
431}
432
433/**
434 * Accepts a Cloudflare model by its short name or its catalogue id, and
435 * answers the short name. The body's `model` must name one of the Clef
436 * models, so any other name is refused here rather than by a 4xx after the
437 * state was sent.
438 */
439function cloudflareModelOf(model: string): string {
440  const short = cloudflareShortOf(model)
441
442  if (!CLOUDFLARE_MODELS.some(known => known === short)) {
443    throw new Error(
444      `cloudflare serves ${CLOUDFLARE_MODELS.slice(0, -1).join(', ')} and ` +
445        `${CLOUDFLARE_MODELS.at(-1)}, not ${JSON.stringify(model.trim())}`,
446    )
447  }
448
449  return short
450}
451
452/**
453 * The limits of a Clef model, by its short name or its catalogue id.
454 */
455function cloudflareLimitsOf(model: string): Limits | undefined {
456  const short = cloudflareShortOf(model)
457
458  return Object.hasOwn(CLOUDFLARE_LIMITS, short)
459    ? CLOUDFLARE_LIMITS[short as keyof typeof CLOUDFLARE_LIMITS]
460    : undefined
461}
462
463/**
464 * The budgets a Clef model is asked for, by its short name or its
465 * catalogue id.
466 */
467function cloudflareWantedOf(model: string): Wanted | undefined {
468  const short = cloudflareShortOf(model)
469
470  return Object.hasOwn(CLOUDFLARE_WANTED, short)
471    ? CLOUDFLARE_WANTED[short as keyof typeof CLOUDFLARE_WANTED]
472    : undefined
473}
474
475/**
476 * The first message of a Workers AI envelope's `errors` list.
477 */
478function envelopeErrorOf(payload: Record<string, unknown>): string | undefined {
479  const first = Array.isArray(payload.errors) ? payload.errors[0] : undefined
480
481  return isRecord(first) ? textOf(first.message) : undefined
482}
483
484/**
485 * The error for a response envelope that reports failure, quoting the
486 * reason it gives.
487 */
488function envelopeFailure(
489  reason: string | undefined,
490  credentials: Credentials,
491): Error {
492  return new Error(
493    'the response envelope reports failure: ' +
494      briefOf(reason ?? '', credentials),
495  )
496}
497
498/**
499 * Takes a Workers AI response out of its `{ result, success, errors }`
500 * envelope. A body that is already a bare reply is passed through, because
501 * the envelope is documented for the REST API in general and not for Clef.
502 * The reason a failed envelope gives is quoted like any other text of a
503 * provider's: redacted and held to one short line.
504 */
505function unwrapCloudflare(payload: unknown, credentials: Credentials): unknown {
506  if (!isRecord(payload)) {
507    return payload
508  }
509
510  if (payload.success === false) {
511    throw envelopeFailure(envelopeErrorOf(payload), credentials)
512  }
513
514  return isRecord(payload.result) ? payload.result : payload
515}
516
517/**
518 * Takes a response out of the `{ code, message, data: { result } }` envelope
519 * the two Decisions resellers answer with. A `code` other than 0, or no
520 * `result`, is a failure, and the envelope's `message` is quoted as its
521 * reason like any other text of a provider's: redacted and held to one
522 * short line.
523 */
524function unwrapDataEnvelope(
525  payload: unknown,
526  credentials: Credentials,
527): Record<string, unknown> {
528  const data = isRecord(payload) ? payload.data : undefined
529  const result = isRecord(data) ? data.result : undefined
530
531  if (!isRecord(payload) || payload.code !== 0 || !isRecord(result)) {
532    throw envelopeFailure(
533      isRecord(payload) ? textOf(payload.message) : undefined,
534      credentials,
535    )
536  }
537
538  return result
539}
540
541/**
542 * Reads a decisions-api.dev response: out of its envelope, and with every
543 * answer back under the id of the question asked in that place. An answer
544 * under a name that was not sent is refused: it answers nothing that was
545 * asked. Both maps have no prototype, so an id or a name such as
546 * `__proto__` is an ordinary key.
547 */
548function unwrapAliased(
549  payload: unknown,
550  credentials: Credentials,
551  asked: Questions,
552): unknown {
553  const result = unwrapDataEnvelope(payload, credentials)
554
555  if (!isRecord(result.answers)) {
556    return result
557  }
558
559  const idOf: Record<string, string> = Object.create(null)
560  const answers: Record<string, unknown> = Object.create(null)
561
562  Object.keys(asked).forEach((id, index) => {
563    idOf[ALIAS_OF(index)] = id
564  })
565
566  for (const [alias, answer] of Object.entries(result.answers)) {
567    const id = Object.hasOwn(idOf, alias) ? idOf[alias] : undefined
568
569    if (id === undefined) {
570      throw new Error(
571        `answered ${briefOf(alias, credentials)}, which was not asked`,
572      )
573    }
574
575    answers[id] = answer
576  }
577
578  return { ...result, answers }
579}
580
581/**
582 * A model name as configured, without the white space around it: how most
583 * providers' bodies spell it.
584 */
585const TRIMMED = (model: string) => model.trim()
586
587/**
588 * A response that already is a bare System One reply.
589 */
590const AS_SENT = (payload: unknown) => payload
591
592/**
593 * What Jev is asked for in TypeSafe's default mode, which holds a request
594 * to 64,000 tokens and the state with any one question to 32,000: both
595 * windows, since Jev reads either in well under a second. The two resellers
596 * are asked for the same; their byte cap binds long before it does.
597 */
598const JEV_WANTED: Wanted = { maxStateTokens: 27_000, maxRequestTokens: 54_400 }
599
600/**
601 * What OpenRouter's Jev is asked for: a body small enough that OpenRouter
602 * keeps it in TypeSafe's default mode, whose windows the token budgets are
603 * then those of. Where the cap is lifted (`Wanted`), a request runs in the
604 * long-context mode, held to the same token budgets unless the person set
605 * larger ones, up to OpenRouter's window.
606 */
607const OPENROUTER_JEV_WANTED: Wanted = {
608  ...JEV_WANTED,
609  maxRequestBytes: OPENROUTER_DEFAULT_MODE_BYTES,
610}
611
612/**
613 * What a model OpenRouter forwards that is not Jev is asked for, before the
614 * window it is held to.
615 */
616const OPENROUTER_OTHER_WANTED: Wanted = {
617  maxStateTokens: 27_000,
618  maxRequestTokens: 27_200,
619}
620
621const TABLE: Record<ProviderName, Descriptor> = {
622  // TypeSafe documents Jev 1.13 and Jev 1.14 alike: a request within 64,000
623  // tokens, the state with any one question within 32,000, and no cap on
624  // the questions. A request over either is refused with HTTP 400
625  // (`max_tokens_exceeded`), never cut; on 2026-10-16 both releases did
626  // so. Its `TypeSafe-Danger-Zone-Long-Context` header raises both windows
627  // to "262k" tokens in a mode TypeSafe calls slower and less accurate, so
628  // it is never sent.
629  typesafe: {
630    title: 'TypeSafe',
631    defaultModel: 'jev-latest',
632    models: ['jev-latest', 'jev-1.14.0'],
633    family: jevFamilyOf('typesafe'),
634    isGateway: false,
635    limits: { maxStateTokens: 32_000, maxRequestTokens: 64_000 },
636    // With 32 questions, Jev 1.13 answered a 27,000-token state in 0.36
637    // seconds at most and Jev 1.14 in 0.36; 1,500 questions on 24,000
638    // tokens took Jev 1.14 0.85 seconds (2026-10-16). Time never binds.
639    wanted: JEV_WANTED,
640    needs: ['typesafeApiKey'],
641    bodyModelOf: TRIMMED,
642    urlOf: () => 'https://api.typesafe.ai/v1/systemone',
643    tokenOf: credentials => credentials.typesafeApiKey,
644    wire: BARE,
645    unwrap: AS_SENT,
646  },
647  cloudflare: {
648    title: 'Cloudflare',
649    defaultModel: 'clef',
650    models: CLOUDFLARE_MODELS,
651    family: model => model,
652    isGateway: false,
653    limits: CLOUDFLARE_LIMITS.clef,
654    modelLimitsOf: cloudflareLimitsOf,
655    wanted: CLOUDFLARE_WANTED.clef,
656    modelWantedOf: cloudflareWantedOf,
657    needs: ['cloudflareApiToken', 'cloudflareAccountId'],
658    bodyModelOf: cloudflareModelOf,
659    urlOf: (model, credentials) =>
660      'https://api.cloudflare.com/client/v4/accounts/' +
661      `${encodeURIComponent(credentials.cloudflareAccountId ?? '')}/ai/run/` +
662      `${CLOUDFLARE_PREFIX}${model}`,
663    tokenOf: credentials => credentials.cloudflareApiToken,
664    wire: BARE,
665    unwrap: unwrapCloudflare,
666  },
667  // OpenRouter documents Jev's window as 262,144 tokens for the state and
668  // the questions together, on Jev 1.13 and 1.14 alike, with no question
669  // cap. A request of more than about 32,000 bytes of text runs in
670  // TypeSafe's long-context mode, so Jev is asked for a body within that
671  // (`OPENROUTER_JEV_WANTED`). Its alias for the newest Jev is
672  // `~typesafe/jev-latest`. An id that has an author prefix is sent on as
673  // written, so the same name without the `~` is an id its documentation
674  // does not list. Any other model it forwards has limits of its own
675  // (`limitsOf`).
676  openrouter: {
677    title: 'OpenRouter',
678    defaultModel: '~typesafe/jev-latest',
679    models: ['~typesafe/jev-latest'],
680    family: jevFamilyOf('openrouter'),
681    isGateway: true,
682    limits: { maxStateTokens: 262_144, maxRequestTokens: 262_144 },
683    wanted: OPENROUTER_JEV_WANTED,
684    modelWantedOf: model =>
685      JEV.test(model.trim()) ? undefined : OPENROUTER_OTHER_WANTED,
686    needs: ['openrouterApiKey'],
687    bodyModelOf: TRIMMED,
688    urlOf: () => 'https://openrouter.ai/api/v1/systemone',
689    tokenOf: credentials => credentials.openrouterApiKey,
690    wire: BARE,
691    unwrap: AS_SENT,
692  },
693  // Codiv serves its own open Jev, which answers as `openjev-0.1` and is a
694  // model of its own, not TypeSafe's Jev; at Codiv `jev-latest` is an alias
695  // of it. Its window is 65,536 tokens for the state and the questions
696  // together, and it advises about 60,000 for the state. It documents no
697  // fixed question cap, but on 2026-10-11 it refused 300 questions with
698  // HTTP 400 ("at most 256 questions per request"). It answers questions in
699  // chunks of about thirteen and its `usage.input_tokens` counts the state
700  // once a chunk: 32 questions on a 30,000-token state counted 90,946. A
701  // state too long for the window is refused with HTTP 400, never cut.
702  codiv: {
703    title: 'Codiv',
704    defaultModel: 'openjev-latest',
705    models: ['openjev-latest'],
706    family: model => (/^(?:open)?jev(?:-|$)/.test(model) ? 'openjev' : model),
707    isGateway: false,
708    limits: {
709      maxStateTokens: 60_000,
710      maxRequestTokens: 65_536,
711      maxQuestions: 256,
712    },
713    refusesOverlong: true,
714    // 32 questions on a 30,000-token state took 4.8 seconds, and 128 on a
715    // 49,000-token one took 24.
716    wanted: { maxStateTokens: 25_000, maxRequestTokens: 30_000 },
717    needs: ['codivApiKey'],
718    bodyModelOf: TRIMMED,
719    urlOf: () => 'https://api.codiv.ai/v1/systemone',
720    tokenOf: credentials => credentials.codivApiKey,
721    wire: BARE,
722    unwrap: AS_SENT,
723  },
724  // Perplexity refuses any model but its own deciders (HTTP 400, "Invalid
725  // model"), Jev included. A request must stay under 262,144 input tokens,
726  // the state and every question counted, and holds 1 to 128 questions.
727  // Its `usage.input_tokens` counts the state again for every question: on
728  // 2026-10-11 the same state cost 108, 216 and 864 tokens with 1, 2 and 8
729  // questions, and 8 questions reported as 312,744 tokens were answered.
730  perplexity: {
731    title: 'Perplexity',
732    defaultModel: 'pplx-decider-v1.1-27b',
733    models: ['pplx-decider-v1.1-27b'],
734    family: model =>
735      /^pplx-decider(?:-|$)/.test(model) ? 'pplx-decider' : model,
736    isGateway: false,
737    limits: {
738      maxStateTokens: 262_143,
739      maxRequestTokens: 262_143,
740      maxQuestions: 128,
741    },
742    countsStatePerQuestion: true,
743    // 32 questions on a 15,000-token state took 6.3 seconds, and 8 on a
744    // 30,000-token one 3.1: the time goes with the state times the questions.
745    // A call's two questions name it and nothing of its input, about 120
746    // tokens, so the 4,000 beside the state hold 16 to 32 calls.
747    wanted: { maxStateTokens: 10_000, maxRequestTokens: 14_000 },
748    needs: ['perplexityApiKey'],
749    bodyModelOf: TRIMMED,
750    urlOf: () => 'https://api.perplexity.ai/v1/decisions',
751    tokenOf: credentials => credentials.perplexityApiKey,
752    wire: BARE,
753    unwrap: AS_SENT,
754  },
755  // The two Decisions resellers forward to TypeSafe's Jev and wrap the
756  // reply in an envelope of their own. decisions-api.dev alone restricts
757  // question ids, so its requests name questions by their place. It names
758  // Jev 1.14 `typesafe/jev-1.14` and refuses TypeSafe's own ids for it
759  // (`jev-1.14.0`, `jev-preview`); its `jev-latest` answered as Jev 1.13 on
760  // 2026-10-16.
761  'decisions-api-dev': {
762    title: 'decisions-api.dev',
763    defaultModel: 'jev-latest',
764    models: ['jev-latest', 'typesafe/jev-1.14'],
765    family: jevFamilyOf('decisions-api-dev'),
766    isGateway: true,
767    limits: RESELLER,
768    wanted: JEV_WANTED,
769    needs: ['decisionsApiKey'],
770    bodyModelOf: TRIMMED,
771    urlOf: () => 'https://decisions-api.dev/v1/systemone',
772    tokenOf: credentials => credentials.decisionsApiKey,
773    wire: ALIASED,
774    unwrap: unwrapAliased,
775  },
776  // decisionapi.net states "1–8 questions per request and a JSON request
777  // body of at most 32 KiB, including state and questions". It documents
778  // Jev 1.14 as its default.
779  'decisionapi-net': {
780    title: 'decisionapi.net',
781    defaultModel: 'jev-latest',
782    models: ['jev-latest'],
783    family: jevFamilyOf('decisionapi-net'),
784    isGateway: true,
785    limits: RESELLER,
786    wanted: JEV_WANTED,
787    needs: ['decisionapiApiKey'],
788    bodyModelOf: TRIMMED,
789    urlOf: () => 'https://decisionapi.net/v1/systemone',
790    tokenOf: credentials => credentials.decisionapiApiKey,
791    wire: BARE,
792    unwrap: unwrapDataEnvelope,
793  },
794  // OpenAI takes the same questions in a body of its own shape and answers
795  // in a list. Its Decisions API documents 1 to 200 questions a request and
796  // no token limit of its own. On 2026-10-11 it refused more than 200
797  // questions (HTTP 400, "maximum length 200") and answered a state of
798  // 300,162 input tokens in under two seconds. A request over "272K" input
799  // tokens is billed at twice the rate, so that is the window it is held
800  // to. It refuses a request too long rather than
801  // cutting it, so a reply counting the whole window is one whose estimate
802  // drifted past the price step, and is discarded all the same.
803  openai: {
804    title: 'OpenAI',
805    defaultModel: 'gpt-6-luna',
806    models: ['gpt-6-luna'],
807    family: model => model,
808    isGateway: false,
809    limits: {
810      maxStateTokens: 272_000,
811      maxRequestTokens: 272_000,
812      maxQuestions: 200,
813    },
814    // A 225,000-token state with 32 questions took 1.6 seconds.
815    wanted: { maxStateTokens: 200_000, maxRequestTokens: 231_200 },
816    needs: ['openaiApiKey'],
817    bodyModelOf: TRIMMED,
818    urlOf: () => 'https://api.openai.com/v1/decisions',
819    tokenOf: credentials => credentials.openaiApiKey,
820    wire: OPENAI,
821    unwrap: (payload, _credentials, asked) => decodeOpenAI(payload, asked),
822  },
823}
824
825/**
826 * Narrows a configured value to a provider name.
827 *
828 * @param value the value of the `provider` option
829 * @returns the provider, or undefined when the value names none
830 */
831export function providerOf(value: unknown): ProviderName | undefined {
832  return PROVIDERS.find(name => name === value)
833}
834
835/**
836 * The limits a request over a route must keep to. A provider whose models
837 * hold different amounts answers for the model named. OpenRouter is a
838 * gateway: a request it forwards is also held to what the model's own host
839 * accepts. Its Jev window is documented, and no question cap with it. Any
840 * other model it serves is held to Cloudflare's 64 questions as well,
841 * because Clef, the one other System One model, is served there and refuses
842 * a request with more (HTTP 422, "Dictionary should have at most 64
843 * items"). A Clef model is held to where OpenRouter cuts it, and any other
844 * model to the window of a model whose limit no one documented.
845 *
846 * @param route the provider and the model
847 * @returns its limits
848 */
849export function limitsOf(route: Route): Limits {
850  const { limits, modelLimitsOf } = TABLE[route.provider]
851
852  if (route.provider === 'openrouter' && !JEV.test(route.model.trim())) {
853    const model = route.model.trim()
854    const window =
855      (Object.hasOwn(OPENROUTER_CLEF_WINDOWS, model)
856        ? OPENROUTER_CLEF_WINDOWS[model]
857        : undefined) ?? OPENROUTER_OTHER_WINDOW
858
859    return {
860      maxStateTokens: window,
861      maxRequestTokens: window,
862      maxQuestions: TABLE.cloudflare.limits.maxQuestions,
863    }
864  }
865
866  return modelLimitsOf?.(route.model) ?? limits
867}
868
869/**
870 * The budgets a compaction over a route asks for when the person set none.
871 *
872 * @param route the provider and the model
873 * @returns the state and request budgets, before the limits hold them
874 */
875export function wantedOf(route: Route): Wanted {
876  const { wanted, modelWantedOf } = TABLE[route.provider]
877
878  return modelWantedOf?.(route.model) ?? wanted
879}
880
881/**
882 * The models a provider is offered with in the routing decision.
883 *
884 * @param provider the provider
885 * @returns the model names as its body spells them
886 */
887export function modelsOf(provider: ProviderName): readonly string[] {
888  return TABLE[provider].models
889}
890
891/**
892 * The model family a route reaches: a gateway's route to Jev is the same
893 * Jev that TypeSafe serves directly.
894 *
895 * @param route the route
896 * @returns the family, the model name itself for a model of its own
897 */
898export function familyOf(route: Route): string {
899  return TABLE[route.provider].family(route.model)
900}
901
902/**
903 * Names a gateway as a sentence about it spells the name.
904 *
905 * @param provider the provider
906 * @returns the name, or undefined for a provider that hosts its models
907 */
908export function gatewayOf(provider: ProviderName): string | undefined {
909  const described = TABLE[provider]
910
911  return described.isGateway ? described.title : undefined
912}
913
914/**
915 * The UTF-8 bytes a request over a route takes besides its questions: the
916 * body as encoded around one question, less that question as the route's
917 * wire format measures it. The model name and the state are counted
918 * exactly as they are sent. What is left holds no bracket of the question
919 * map or list; each question is measured with brackets of its own and a
920 * comma after it, so a body counted this way is over by a few bytes a
921 * question, never under.
922 *
923 * @param route the route
924 * @param state what the questions are asked about
925 * @returns the byte count
926 */
927export function bytesBesideOf(route: Route, state: unknown): number {
928  const described = TABLE[route.provider]
929  const question: Question = { type: 'noul', instructions: '' }
930  const body = described.wire.encode(
931    described.bodyModelOf(route.model),
932    state,
933    { q: question },
934  )
935
936  return bytesOf(body) - bytesOf(described.wire.questionJsonOf('q', question))
937}
938
939/**
940 * How a request over a route is written, which is also how its size is
941 * estimated.
942 *
943 * @param route the route
944 * @returns the provider's wire format
945 */
946export function wireOf(route: Route): Wire {
947  return TABLE[route.provider].wire
948}
949
950/**
951 * Builds the route for a provider: the configured model when one is set, the
952 * provider's default otherwise, spelled as the provider's body expects it.
953 *
954 * @param provider the provider
955 * @param model the configured model name, when one is set
956 * @returns the route; throws when the provider does not serve the model
957 */
958export function routeOf(provider: ProviderName, model?: string): Route {
959  const described = TABLE[provider]
960
961  return {
962    provider,
963    model: described.bodyModelOf(textOf(model) ?? described.defaultModel),
964  }
965}
966
967/**
968 * Names the environment variables of the credentials a provider needs and
969 * does not have. The names are safe to show; the values never are.
970 *
971 * @param provider the provider
972 * @param credentials what was resolved
973 * @returns the variable names, empty when the provider can be called
974 */
975export function missingOf(
976  provider: ProviderName,
977  credentials: Credentials,
978): EnvName[] {
979  return TABLE[provider].needs
980    .filter(need => credentials[need] === undefined)
981    .map(need => ENV_NAMES[need])
982}
983
984/**
985 * Throws when a provider lacks a credential it needs, naming the variable
986 * to set. Checked before any work is done for a request that could not be
987 * sent.
988 *
989 * @param provider the provider
990 * @param credentials what was resolved
991 */
992export function assertConfigured(
993  provider: ProviderName,
994  credentials: Credentials,
995): void {
996  const missing = missingOf(provider, credentials)
997
998  if (missing.length > 0) {
999    throw new Error(
1000      `${provider} is not configured: ${missing.join(' and ')} is unset`,
1001    )
1002  }
1003}
1004
1005/**
1006 * Names the credential variables that still have no value after the plugin
1007 * options and one source of the environment were read, among those the given
1008 * providers need. An empty answer means a further source would add nothing,
1009 * so it need not be read.
1010 *
1011 * @param providers the providers a compaction may call
1012 * @param options the plugin's options
1013 * @param read the variables as that source holds them
1014 * @returns the variable names, each once
1015 */
1016export function unresolvedOf(
1017  providers: readonly ProviderName[],
1018  options: PluginOptions,
1019  read: Environment,
1020): EnvName[] {
1021  const credentials = credentialsOf(options, read)
1022
1023  return [
1024    ...new Set(providers.flatMap(provider => missingOf(provider, credentials))),
1025  ]
1026}
1027
1028/**
1029 * Keeps only the credentials the given providers need. A credential of a
1030 * provider that may not be called is dropped here, so no later step can
1031 * send anything with it.
1032 *
1033 * @param providers the providers a compaction may call
1034 * @param credentials what was resolved
1035 * @returns the credentials of those providers
1036 */
1037export function credentialsFor(
1038  providers: readonly ProviderName[],
1039  credentials: Credentials,
1040): Credentials {
1041  const needed = new Set(providers.flatMap(provider => TABLE[provider].needs))
1042  const kept: Credentials = {}
1043
1044  for (const key of needed) {
1045    const value = credentials[key]
1046
1047    if (value !== undefined) {
1048      kept[key] = value
1049    }
1050  }
1051
1052  return kept
1053}
1054
1055/**
1056 * Lays one source of the credential variables under another: a value the
1057 * first source holds wins, and the `env` block of the settings fills the
1058 * rest. The block is read as untyped data, since settings are a plain object.
1059 *
1060 * @param read the variables as the process environment holds them
1061 * @param settingsEnv the `env` key of the merged settings
1062 * @returns the variables with every gap the settings can fill filled
1063 */
1064export function environmentOf(
1065  read: Environment,
1066  settingsEnv: unknown,
1067): Environment {
1068  const fallback = isRecord(settingsEnv) ? settingsEnv : {}
1069  const merged: Environment = {}
1070
1071  for (const name of Object.values(ENV_NAMES)) {
1072    merged[name] = textOf(read[name]) ?? textOf(fallback[name])
1073  }
1074
1075  return merged
1076}
1077
1078/**
1079 * Resolves each credential: the plugin option when it is set, the
1080 * environment otherwise.
1081 *
1082 * @param options the plugin's options
1083 * @param environment the credential variables, already merged over settings
1084 * @returns the credentials that have a value
1085 */
1086export function credentialsOf(
1087  options: PluginOptions,
1088  environment: Environment,
1089): Credentials {
1090  const credentials: Credentials = {}
1091
1092  for (const [key, name] of Object.entries(ENV_NAMES)) {
1093    const value = textOf(options[key]) ?? textOf(environment[name])
1094
1095    if (value !== undefined) {
1096      credentials[key as keyof Credentials] = value
1097    }
1098  }
1099
1100  return credentials
1101}
1102
1103/**
1104 * Takes every credential out of a text that is about to be shown.
1105 *
1106 * A provider's error body is quoted to the person, and a body may repeat
1107 * what the request carried: the key itself, or the whole `Authorization`
1108 * header. Each secret that was resolved is replaced wherever it stands, the
1109 * longest first so that one secret containing another leaves no remainder,
1110 * and then anything that follows the word `Bearer`, which covers a token
1111 * this mod never held. A resolved value under `MIN_SECRET_CHARS` is not
1112 * replaced by value; the `Bearer` rule still covers it where it follows
1113 * that word. The account id is not a secret and is left alone.
1114 *
1115 * @param text the text
1116 * @param credentials the resolved credentials
1117 * @returns the text with `REDACTED` where a credential stood
1118 */
1119export function redacted(text: string, credentials: Credentials): string {
1120  const secrets = PROVIDERS.map(provider =>
1121    TABLE[provider].tokenOf(credentials),
1122  )
1123    .filter(
1124      (secret): secret is string =>
1125        secret !== undefined && secret.length >= MIN_SECRET_CHARS,
1126    )
1127    .sort((a, b) => b.length - a.length)
1128  let shown = text
1129
1130  for (const secret of secrets) {
1131    shown = shown.split(secret).join(REDACTED)
1132  }
1133
1134  return shown.replace(BEARER, REDACTED)
1135}
1136
1137/**
1138 * The C0 and C1 control characters: a terminal acts on them rather than
1139 * showing them, so a quoted text could move the cursor or recolour what
1140 * follows it.
1141 */
1142const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g
1143
1144/**
1145 * A text this mod did not write, made fit to quote in a message: redacted,
1146 * on one line, with no control character, and no longer than
1147 * `REASON_CHARS`.
1148 *
1149 * The text is redacted before it is shortened: a cut that fell inside a
1150 * credential would leave a part of it that no longer matches the whole. The
1151 * cut never falls between the two halves of a surrogate pair.
1152 *
1153 * @param text what a provider or the host said
1154 * @param credentials the resolved credentials
1155 * @returns the line to quote; `no reason given` for a text that says nothing
1156 */
1157export function briefOf(text: string, credentials: Credentials): string {
1158  const line = redacted(text, credentials)
1159    .replace(CONTROL, ' ')
1160    .replace(/\s+/g, ' ')
1161    .trim()
1162
1163  return line === '' ? 'no reason given' : cutOf(line)
1164}
1165
1166/**
1167 * A text held to `REASON_CHARS`: cut there, never between the two halves of
1168 * a surrogate pair, with `…` where it was cut.
1169 *
1170 * @param text the text
1171 * @returns the text, or its first `REASON_CHARS` characters and `…`
1172 */
1173export function cutOf(text: string): string {
1174  return text.length > REASON_CHARS ? `${headOf(text, REASON_CHARS)}…` : text
1175}
1176
1177/**
1178 * The message of a thrown value, which need not be an `Error`.
1179 *
1180 * @param error what was thrown
1181 * @returns its message, or the value as text
1182 */
1183export function messageOf(error: unknown): string {
1184  return error instanceof Error ? error.message : String(error)
1185}
1186
1187/**
1188 * Builds the request for one batch of questions. The credential goes into
1189 * the `authorization` header and nowhere else, so nothing built from the
1190 * returned URL or body can leak it.
1191 *
1192 * @param route which provider and model
1193 * @param credentials the resolved credentials
1194 * @param state what the questions are asked about
1195 * @param questions the questions, by id
1196 * @returns the URL and the init for `$.http.fetch`; throws when a credential
1197 * the provider needs is missing, naming its environment variable
1198 */
1199export function exchangeOf(
1200  route: Route,
hooks/report.ts 162 lines
1import { reductionOf } from './compact'
2import type { Action, Decision } from './compact'
3import { labelOf } from './route'
4import type { Result } from './run'
5
6/**
7 * The longest line `$.ui.log` is given; a longer decisions list is split.
8 */
9const LOG_LINE_CHARS = 4096
10
11/**
12 * What every line of the per-call verdicts starts with.
13 */
14const VERDICTS = 'per-call verdicts'
15
16/**
17 * Room kept in every line for the lead, the longest of which is
18 * `per-call verdicts, part 12 of 34: `.
19 */
20const LEAD_ROOM = 40
21
22/**
23 * What stands between two entries on a line.
24 */
25const BETWEEN = '; '
26
27/**
28 * A ratio as a whole percentage.
29 *
30 * @param ratio the ratio, 0 to 1
31 * @returns for example `42%`
32 */
33export function percentOf(ratio: number): string {
34  return `${Math.round(ratio * 100)}%`
35}
36
37function countOf(decisions: readonly Decision[], action: Action): number {
38  return decisions.filter(decision => decision.action === action).length
39}
40
41/**
42 * One line saying what a compaction did and what it cost to decide.
43 *
44 * It names the provider and model that answered, and puts the state's
45 * estimated size beside the input tokens the provider itself counted. The
46 * two disagreeing shows how far the estimate drifts; the provider's count
47 * falling well below the estimate shows a state the provider cut short.
48 *
49 * The calls are counted by what happened to them, not by what was decided:
50 * a call whose result was to be cut, but was too short to gain from it,
51 * stands whole and is counted so.
52 *
53 * @param result the compaction
54 * @returns the line, without a lead
55 */
56export function summaryOf(result: Result): string {
57  const { outcome, route } = result
58  const uncut = countOf(outcome.decisions, 'truncate') - outcome.shortened
59  const counts = (
60    [
61      ['left whole', countOf(outcome.decisions, 'keep') + uncut],
62      ['with the result cut short', outcome.shortened],
63      ['removed', countOf(outcome.decisions, 'drop')],
64      ['not judged', countOf(outcome.decisions, 'pinned')],
65    ] as const
66  )
67    .filter(([, count]) => count > 0)
68    .map(([said, count]) => `${count} ${said}`)
69  const parts = [
70    `${percentOf(reductionOf(outcome))} smaller`,
71    counts.length > 0
72      ? `tool calls: ${counts.join(', ')}`
73      : 'no answered tool call',
74  ]
75
76  if (outcome.requests > 0) {
77    const counted =
78      outcome.reported.inputTokens === undefined
79        ? ''
80        : `, ${outcome.reported.inputTokens} input tokens counted by the provider`
81    const cost =
82      outcome.reported.cost === undefined
83        ? ''
84        : `, cost $${outcome.reported.cost.toFixed(6)}`
85
86    parts.push(
87      `${labelOf(route)} in ${outcome.requests} ` +
88        `${outcome.requests === 1 ? 'request' : 'requests'}`,
89      `state about ${outcome.stateTokens} tokens estimated ` +
90        `(${outcome.stage ?? 'whole'})${counted}${cost}`,
91    )
92
93    if (result.askedBytes !== undefined) {
94      const { limit, isHeld } = result.askedBytes
95
96      parts.push(
97        isHeld
98          ? `requests within the ${limit} bytes ${route.provider} asks for`
99          : `requests past the ${limit} bytes ${route.provider} asks for, ` +
100              'which the conversation does not fit',
101      )
102    }
103  }
104
105  return parts.join('; ')
106}
107
108/**
109 * The decisions as log lines: one entry per call that was asked about, with
110 * both probabilities, split so that no line exceeds what one log line holds.
111 *
112 * @param decisions every decision of the compaction
113 * @param maxChars the longest a line may be
114 * @returns the lines, in call order
115 */
116export function decisionLinesOf(
117  decisions: readonly Decision[],
118  maxChars: number = LOG_LINE_CHARS,
119): string[] {
120  const entries = decisions
121    .filter(decision => decision.action !== 'pinned')
122    .map(
123      ({ call, action, keepCall, keepResult }) =>
124        `${call.id} ${call.tool} -> ${action} ` +
125        `(call ${keepCall.toFixed(2)}, result ${keepResult.toFixed(2)})`,
126    )
127
128  // Each line is a group of entries, filled by length: an entry joins the
129  // newest group while the group, with it and the separator before it,
130  // stays within the room, and opens a group of its own otherwise. An entry
131  // longer than the room therefore still gets a line.
132  const room = Math.max(1, maxChars - LEAD_ROOM)
133  const groups: string[][] = []
134  let used = 0
135
136  for (const entry of entries) {
137    const newest = groups.at(-1)
138    const added = BETWEEN.length + entry.length
139
140    if (newest === undefined || used + added > room) {
141      groups.push([entry])
142      used = entry.length
143    } else {
144      newest.push(entry)
145      used += added
146    }
147  }
148
149  if (groups.length === 0) {
150    return [`${VERDICTS}: no tool call was asked about`]
151  }
152
153  return groups.map((group, index) => {
154    const lead =
155      groups.length === 1
156        ? VERDICTS
157        : `${VERDICTS}, part ${index + 1} of ${groups.length}`
158
159    return `${lead}: ${group.join(BETWEEN)}`
160  })
161}
162
hooks/run.ts 310 lines
1import type { SessionMessage } from 'claude-code'
2
3import { askerOf, attemptOf } from './ask'
4import type { Ports } from './ask'
5import {
6  batchesOf,
7  budgetOf,
8  compact,
9  demandOf,
10  LIMIT_SHARE,
11  untouched,
12} from './compact'
13import type { Budget, Outcome } from './compact'
14import { eligibleOf } from './config'
15import type { Config } from './config'
16import {
17  assertConfigured,
18  bytesBesideOf,
19  limitsOf,
20  messageOf,
21  routeOf,
22  wantedOf,
23  wireOf,
24} from './providers'
25import type { Credentials, Route } from './providers'
26import { chooseRoute, profileOf } from './route'
27import { estimatedTokensOf, goalOf, pairCalls, stateWithin } from './state'
28import type { Fitted } from './state'
29
30/**
31 * One compaction to carry out.
32 */
33export type Job = {
34  messages: readonly SessionMessage[]
35  /**
36   * The instructions given with the compaction, when there were any.
37   */
38  instructions?: string
39  config: Config
40  credentials: Credentials
41  ports: Ports
42}
43
44/**
45 * A compaction carried out: the outcome, the route it went over, and how
46 * the route was picked when the decision was on.
47 */
48export type Result = {
49  outcome: Outcome
50  route: Route
51  routing?: string
52  /**
53   * The bytes the route asks a request body to stay within, at the share
54   * it is held to, and whether every request did; absent for a route that
55   * asks for no such cap.
56   */
57  askedBytes?: { limit: number; isHeld: boolean }
58}
59
60/**
61 * Carries out one compaction from the transcript to the rebuilt messages.
62 *
63 * The state is fitted once, against the configured provider's limits and
64 * wire format, a cap on the body in bytes included, and every request that
65 * asks about a call then goes over one route: the configured one, or the
66 * one the provider decision picked. A route whose wire format carries the
67 * state differently is held to the state's size in that format. A failure
68 * anywhere throws; the caller falls back to the built-in summary.
69 *
70 * Everything sent to a provider, the routing question included, is sent
71 * inside one attempt: one deadline, armed here once the state is fitted and
72 * released when the outcome is known. Past it, on the engine's signal, and
73 * at the first request about tool calls that fails for good, whatever is
74 * still out is abandoned, nothing further is sent or waited for, and this
75 * throws the one reason. The routing question failing is not such an end:
76 * the configured route decides instead. Once the outcome is known, whatever
77 * is still out starts nothing more.
78 *
79 * Options that carry a refusal are not acted on at all: they name no
80 * provider the person chose, so nothing may be sent anywhere.
81 *
82 * @param job the transcript, the configuration, the credentials, the ports
83 * @returns the result
84 */
85export async function run(job: Job): Promise<Result> {
86  const { messages, config, credentials, ports } = job
87
88  if (config.refusal !== undefined) {
89    throw new Error(config.refusal)
90  }
91
92  const configured = routeOf(config.provider, config.model)
93
94  if (!config.providerDecision) {
95    assertConfigured(configured.provider, credentials)
96  }
97
98  const calls = pairCalls(messages, config.preserveRecentMessages)
99  const unpinned = calls.filter(call => !call.isPinned)
100
101  if (unpinned.length === 0) {
102    return { outcome: untouched(messages, calls), route: configured }
103  }
104
105  const demandFor = (route: Route) =>
106    demandOf(unpinned, wireOf(route), limitsOf(route).maxQuestions)
107  // A budget the person left unset is the one the route asks for, so a
108  // provider decision weighs each route by its own.
109  const budgetFor = (route: Route) =>
110    budgetOf(
111      {
112        maxStateTokens: config.maxStateTokens ?? wantedOf(route).maxStateTokens,
113        maxRequestTokens:
114          config.maxRequestTokens ?? wantedOf(route).maxRequestTokens,
115      },
116      limitsOf(route),
117      demandFor(route),
118    )
119  // The cap on the body in bytes a route asks for but does not require,
120  // while the person has set no request budget of their own.
121  const askedBytesOf = (route: Route) =>
122    limitsOf(route).maxRequestBytes === undefined &&
123    config.maxRequestTokens === undefined
124      ? wantedOf(route).maxRequestBytes
125      : undefined
126  // What each route is held to over one fitted state: the state as its wire
127  // format carries it, the cap on its body in bytes when it has one, and
128  // its budget.
129  const planOf = (fitted: Fitted) => {
130    const stateJson = JSON.stringify(fitted.state)
131    const fittedFor = (route: Route): Fitted =>
132      wireOf(route) === wireOf(configured)
133        ? fitted
134        : {
135            ...fitted,
136            tokens: estimatedTokensOf(wireOf(route).stateJsonOf(stateJson)),
137          }
138    // A route that caps the body in bytes is held to the bytes the state
139    // takes in its request as written, counted exactly, and to the same
140    // share of its cap as of its token limits: what a question will take is
141    // still an estimate, and a body over the cap is refused whole.
142    const heldTo = (route: Route, maxRequestBytes?: number): Budget => {
143      const budget = budgetFor(route)
144
145      return maxRequestBytes === undefined
146        ? budget
147        : {
148            ...budget,
149            bytes: {
150              limit: Math.floor(maxRequestBytes * LIMIT_SHARE),
151              state: bytesBesideOf(route, fitted.state),
152            },
153          }
154    }
155    // The cap the provider requires; or the one the route asks for, where
156    // the questions about every call go in the requests a compaction may
157    // send under it; or none.
158    const bytesOn = (route: Route): number | undefined => {
159      const routeAsked = askedBytesOf(route)
160
161      if (routeAsked === undefined) {
162        return limitsOf(route).maxRequestBytes
163      }
164
165      try {
166        batchesOf(
167          unpinned,
168          fittedFor(route).tokens,
169          heldTo(route, routeAsked),
170          wireOf(route),
171        )
172      } catch {
173        return undefined
174      }
175
176      return routeAsked
177    }
178
179    return {
180      fittedFor,
181      bytesOn,
182      budgetOn: (route: Route) => heldTo(route, bytesOn(route)),
183    }
184  }
185  const goal = goalOf(messages, job.instructions)
186  const fitTo = (maxRequestBytes: number | undefined) =>
187    stateWithin(messages, calls, {
188      maxStateTokens: budgetFor(configured).stateTokens,
189      preserveRecentMessages: config.preserveRecentMessages,
190      goal,
191      wire: wireOf(configured),
192      // Held to the same share of a byte cap as the request is below, with
193      // the bytes of one request's questions left free.
194      ...(maxRequestBytes === undefined
195        ? {}
196        : {
197            bytes: {
198              limit:
199                Math.floor(maxRequestBytes * LIMIT_SHARE) -
200                demandFor(configured).batchBytes,
201              besideOf: (state: unknown) => bytesBesideOf(configured, state),
202            },
203          }),
204    })
205  const asked = askedBytesOf(configured)
206  let fitted: Fitted
207  let isFittedToAsked = asked !== undefined
208
209  // A cap the route only asks for gives way when the conversation cannot be
210  // fitted under it, rather than fail the compaction the way a cap the
211  // provider requires does.
212  try {
213    fitted = fitTo(limitsOf(configured).maxRequestBytes ?? asked)
214  } catch (error) {
215    if (asked === undefined) {
216      throw error
217    }
218
219    fitted = fitTo(undefined)
220    isFittedToAsked = false
221  }
222
223  let plan = planOf(fitted)
224
225  // A state fitted under an asked-for cap whose calls would still not go
226  // in the requests a compaction may send is fitted again without it: the
227  // cap is not kept, so the detail given up for it need not be.
228  if (isFittedToAsked && plan.bytesOn(configured) === undefined) {
229    fitted = fitTo(undefined)
230    plan = planOf(fitted)
231  }
232
233  const { fittedFor, budgetOn, bytesOn } = plan
234  const attempt = attemptOf(ports)
235
236  try {
237    const result: Pick<Result, 'route' | 'routing'> = { route: configured }
238
239    if (config.providerDecision) {
240      const routed = await chooseRoute(
241        configured,
242        eligibleOf(config),
243        credentials,
244        route => {
245          try {
246            const budget = budgetOn(route)
247            const { tokens } = fittedFor(route)
248
249            if (tokens > budget.stateTokens) {
250              return (
251                `the state is about ${tokens} tokens and it takes ` +
252                `${budget.stateTokens}`
253              )
254            }
255
256            batchesOf(unpinned, tokens, budget, wireOf(route))
257          } catch (error) {
258            return messageOf(error)
259          }
260
261          return undefined
262        },
263        profileOf(messages, unpinned, fitted.tokens, goal),
264        // The routing question is one the compaction can do without: when
265        // it fails, the configured route decides.
266        route => askerOf(route, credentials, attempt, false),
267      )
268      const failure = attempt.failure()
269
270      // A routing question cut off by the deadline or the engine's signal
271      // is not a reason to go on with the configured route: the attempt is
272      // over, and what ended it is the reason to give.
273      if (failure !== undefined) {
274        throw failure
275      }
276
277      result.route = routed.route
278      result.routing = routed.why
279    }
280
281    const outcome = await compact(
282      messages,
283      calls,
284      fittedFor(result.route),
285      askerOf(result.route, credentials, attempt, true),
286      {
287        budget: budgetOn(result.route),
288        wire: wireOf(result.route),
289        keepThreshold: config.keepThreshold,
290        truncateHeadChars: config.truncateHeadChars,
291        halt: attempt.fail,
292      },
293    )
294    const routeAsked = askedBytesOf(result.route)
295
296    return routeAsked === undefined
297      ? { ...result, outcome }
298      : {
299          ...result,
300          outcome,
301          askedBytes: {
302            limit: Math.floor(routeAsked * LIMIT_SHARE),
303            isHeld: bytesOn(result.route) !== undefined,
304          },
305        }
306  } finally {
307    attempt.close()
308  }
309}
310
hooks/trigger.ts 108 lines
1/**
2 * What the `turn.complete` trigger remembers between turns.
3 */
4type Arm = {
5  /**
6   * The usage the last requested compaction left, while that is still at or
7   * above the threshold: the level the next request has to rise from.
8   */
9  floor?: number
10  /**
11   * True from a requested compaction until usage is next known. Usage is
12   * absent right after a compaction (it comes with the next response), so
13   * the floor is then taken from the first reading that follows.
14   */
15  isFloorPending: boolean
16}
17
18/**
19 * How far usage has to rise above the floor before another compaction is
20 * requested, in points of the context window.
21 */
22const REARM_POINTS = 10
23
24/**
25 * A trigger that has requested nothing yet.
26 *
27 * @returns the initial state
28 */
29export function armOf(): Arm {
30  return { isFloorPending: false }
31}
32
33/**
34 * Says whether a compaction should be requested at this reading of usage,
35 * and updates what is remembered.
36 *
37 * A reading at or above the threshold asks for one, unless an earlier
38 * request left usage near where it is now: a compaction that could not get
39 * usage under the threshold would otherwise be requested again at the end
40 * of every turn. The next request then waits until usage has risen
41 * `REARM_POINTS` above that floor. A reading under the threshold forgets
42 * the floor. When the answer is yes the floor is set to the reading at
43 * once, so a request that then fails is not repeated on the next turn.
44 *
45 * @param arm what is remembered, changed in place
46 * @param percent the context usage in percent, absent when it is not known
47 * @param threshold the `compactAtPercent` option
48 * @returns true when a compaction should be requested now
49 */
50export function isCompactionDue(
51  arm: Arm,
52  percent: number | undefined,
53  threshold: number,
54): boolean {
55  if (percent === undefined) {
56    return false
57  }
58
59  if (percent < threshold) {
60    delete arm.floor
61    arm.isFloorPending = false
62
63    return false
64  }
65
66  if (arm.isFloorPending) {
67    arm.floor = percent
68    arm.isFloorPending = false
69  }
70
71  if (arm.floor !== undefined && percent < arm.floor + REARM_POINTS) {
72    return false
73  }
74
75  arm.floor = percent
76
77  return true
78}
79
80/**
81 * Records what a requested compaction left behind.
82 *
83 * A reading at or above the threshold becomes the floor: the compaction
84 * could not get usage under it, so the next request has to wait for a rise.
85 * A reading under the threshold leaves no floor, because the compaction
86 * worked and the next crossing of the threshold is a new one; a floor kept
87 * there would hold the next request back until usage was `REARM_POINTS`
88 * above a level that was never a problem, which a high threshold can put
89 * past the top of the window. Usage that is not known yet marks the floor as
90 * pending.
91 *
92 * @param arm what is remembered, changed in place
93 * @param percent the context usage read after the compaction
94 * @param threshold the `compactAtPercent` option
95 */
96export function settle(
97  arm: Arm,
98  percent: number | undefined,
99  threshold: number,
100): void {
101  delete arm.floor
102  arm.isFloorPending = percent === undefined
103
104  if (percent !== undefined && percent >= threshold) {
105    arm.floor = percent
106  }
107}
108
hooks/state.ts 779 lines
1import type { SessionMessage, ToolUseSummary } from 'claude-code'
2
3import { bytesOf } from './systemone'
4import type { Wire } from './systemone'
5
6/**
7 * One tool call with the result that answers it, found by `tool_use_id`.
8 */
9export type Call = {
10  /**
11   * A name of a few characters (`t1`, `t2`, ...) that stands for the call in
12   * the state and in the question ids, where the engine's own `tool_use_id`
13   * would be paid for, character by character, in every request.
14   */
15  id: string
16  toolUseId: string
17  tool: string
18  input: Record<string, unknown>
19  /**
20   * Where in the conversation the assistant made the call.
21   */
22  callIndex: number
23  /**
24   * Where in the conversation the answer to the call arrived.
25   */
26  resultIndex: number
27  resultChars: number
28  isError: boolean
29  /**
30   * True when the call is shown to the model but never asked about, so it
31   * stays exactly as it is. That holds when either of its two messages is
32   * one that is never changed, and when its `tool_use_id` is not unique in
33   * the conversation: a decision is applied by that id, so one taken for
34   * such a call would also reach the other blocks that carry it.
35   */
36  isPinned: boolean
37}
38
39/**
40 * A call as the state shows it: its input, and a note in place of its output.
41 */
42export type CallNote = {
43  id: string
44  tool: string
45  input: string
46  result: string
47}
48
49/**
50 * One message of the conversation as the state shows it. `calls` holds
51 * notes, or one line per call once the state had to shrink that far.
52 */
53type Entry = {
54  at: number
55  role: SessionMessage['role']
56  text: string
57  calls?: CallNote[] | string[]
58}
59
60/**
61 * What every request sends as `state`.
62 */
63export type State = {
64  context: string
65  goal: string
66  conversation: Entry[]
67}
68
69/**
70 * How far the state had to be reduced before it fitted, for the report.
71 */
72export type Stage =
73  | 'whole'
74  | 'inputs shortened'
75  | 'long texts cut in the middle'
76  | 'old texts replaced by their length'
77  | 'old calls on one line'
78  | 'old call-free messages omitted'
79  | 'rows of old calls joined'
80
81/**
82 * A state that fits its budget.
83 */
84export type Fitted = {
85  state: State
86  /**
87   * The estimated size of the serialised state, as the wire format it was
88   * fitted for carries it.
89   */
90  tokens: number
91  stage: Stage
92}
93
94/**
95 * What the fitting needs to know.
96 */
97type FitNeed = {
98  maxStateTokens: number
99  preserveRecentMessages: number
100  goal: string
101  /**
102   * The wire format the state is sent in. It is measured as that format
103   * carries it: a format that escapes the state inside a string makes it
104   * larger than its own JSON.
105   */
106  wire: Wire
107  /**
108   * For a route that caps the request body in bytes: the UTF-8 bytes the
109   * body may take besides the questions it must leave room for, and the
110   * bytes it takes around a state, questions left out. The state is then
111   * held to both budgets; absent, it is fitted in tokens alone.
112   */
113  bytes?: { limit: number; besideOf: (state: State) => number }
114}
115
116/**
117 * The frame every question is read in. It carries the rubric once, so the
118 * per-call questions can stay short: they are repeated for every call.
119 */
120const CONTEXT =
121  'This is the transcript of a coding assistant session whose context ' +
122  'window is nearly full. To free space, old tool calls and their outputs ' +
123  'are being removed; nothing is summarised or reworded. `conversation` ' +
124  'lists the messages in order, oldest first. A tool call appears under ' +
125  '`calls` with its `id` and its input. Its output is not shown: `result` ' +
126  'only says whether it succeeded and how long it was. Long texts may be ' +
127  'shortened and old messages may be missing. `goal` says what the ' +
128  'assistant is working on. Each question is about one tool call, named by ' +
129  'its `id`. What is removed is gone for good, but the assistant can run ' +
130  'any tool again and read any file again.'
131
132/**
133 * The successive caps on a call's serialised input, in characters.
134 */
135const INPUT_CAPS = [1000, 240, 64] as const
136
137/**
138 * What stays of a long text when it is abridged: its start and its end.
139 */
140const KEPT_START_CHARS = 400
141const KEPT_END_CHARS = 160
142
143/**
144 * A text is abridged only past this length, so the note that replaces its
145 * middle is always shorter than what it replaces.
146 */
147const LONG_TEXT = KEPT_START_CHARS + KEPT_END_CHARS + 48
148
149/**
150 * The longest the note standing for a collapsed text gets; a text no longer
151 * than this is left alone, since the note would not be shorter.
152 */
153const COLLAPSED_NOTE_CHARS = 48
154
155const GOAL_CHARS = 2000
156const PROMPT_CHARS = 500
157const GOAL_PROMPTS = 3
158
159/**
160 * Letters one token is assumed to cover inside a word.
161 */
162const LETTERS_PER_TOKEN = 6
163
164function isLetter(code: number): boolean {
165  return (code >= 65 && code <= 90) || (code >= 97 && code <= 122)
166}
167
168function isDigit(code: number): boolean {
169  return code >= 48 && code <= 57
170}
171
172function isHighSurrogate(code: number): boolean {
173  return code >= 0xd800 && code <= 0xdbff
174}
175
176/**
177 * Estimates how many tokens a provider will count for a text, with no
178 * tokenizer: a hooks module cannot load one.
179 *
180 * Each character is weighed by its class:
181 *
182 * - ASCII letters: 1 token for each started group of `LETTERS_PER_TOKEN`
183 *   in an unbroken run of them;
184 * - ASCII digits: 0.5 each;
185 * - other visible ASCII characters: 0.9 each;
186 * - characters beyond ASCII: 1 each, which is about what CJK text comes to;
187 * - white space: nothing.
188 *
189 * The weights follow the design this mod is modelled on, which reports them
190 * landing a little above Jev's own count; they are an estimate, so the
191 * budgets they are compared with must leave headroom.
192 */
193export function estimatedTokensOf(text: string): number {
194  // Counted in tenths of a token so the sum stays in whole numbers: adding
195  // 0.9 repeatedly drifts, and the drift would move the rounded result.
196  let tenths = 0
197  let letters = 0
198
199  for (let index = 0; index < text.length; index++) {
200    const code = text.charCodeAt(index)
201
202    if (isLetter(code)) {
203      letters++
204      continue
205    }
206
207    tenths += Math.ceil(letters / LETTERS_PER_TOKEN) * 10
208    letters = 0
209
210    if (isDigit(code)) {
211      tenths += 5
212    } else if (code > 127) {
213      tenths += 10
214    } else if (code > 32) {
215      tenths += 9
216    }
217  }
218
219  tenths += Math.ceil(letters / LETTERS_PER_TOKEN) * 10
220
221  return Math.ceil(tenths / 10)
222}
223
224/**
225 * The first `count` characters of a text, never ending between the two
226 * halves of a surrogate pair: a lone half does not survive JSON transport.
227 *
228 * @param count how many characters at most
229 * @returns the start of the text
230 */
231export function headOf(text: string, count: number): string {
232  const end = Math.max(0, Math.min(count, text.length))
233
234  return end > 0 &&
235    end < text.length &&
236    isHighSurrogate(text.charCodeAt(end - 1))
237    ? text.slice(0, end - 1)
238    : text.slice(0, end)
239}
240
241/**
242 * The last `count` characters of a text, never starting between the two
243 * halves of a surrogate pair.
244 */
245function tailOf(text: string, count: number): string {
246  const start = Math.max(0, text.length - count)
247
248  return start > 0 && isHighSurrogate(text.charCodeAt(start - 1))
249    ? text.slice(start + 1)
250    : text.slice(start)
251}
252
253/**
254 * A text cut to a length, with a mark where it was cut.
255 */
256function clipped(text: string, limit: number): string {
257  if (text.length > limit) {
258    return `${headOf(text, limit - 1)}…`
259  }
260
261  return text
262}
263
264/**
265 * A long text with its middle replaced by a note of how much is missing.
266 */
267function abridged(text: string): string {
268  const head = headOf(text, KEPT_START_CHARS)
269  const tail = tailOf(text, KEPT_END_CHARS)
270  const missing = text.length - head.length - tail.length
271
272  return `${head}\n[${missing} characters left out]\n${tail}`
273}
274
275/**
276 * Says whether a message is one that is never changed: the first, which
277 * usually states the task, and the newest `recent`, which the assistant is
278 * still working from.
279 *
280 * @param index the message's index
281 * @param total how many messages the conversation has
282 * @param recent how many of the newest are kept as they are
283 * @returns true when the message is pinned
284 */
285function isPinnedIndex(
286  index: number,
287  total: number,
288  recent: number,
289): boolean {
290  // 1 for the newest message, 2 for the one before it, and so on.
291  const fromNewest = total - index
292
293  return index === 0 || fromNewest <= recent
294}
295
296/**
297 * One tool use and where it stands: the message that holds it, and its
298 * place among all the tool uses of the conversation.
299 */
300type Site = {
301  use: ToolUseSummary
302  at: number
303  order: number
304}
305
306/**
307 * Lists the calls that have been answered, in the order they were made,
308 * each joined to its answer through the `tool_use_id` the two share. A call
309 * still waiting for its answer is not listed: removing it would leave the
310 * answer, when it arrives, with nothing to belong to.
311 *
312 * An id is expected on one tool use and on one result. Where it stands on
313 * more than one of either, every call that carries it is marked as not to
314 * be judged: what is decided for a call is applied by its id, so it would
315 * reach each block with that id, one in a pinned message included. Such a
316 * call is joined to the first result with its id.
317 *
318 * @param messages the conversation
319 * @param recent how many of the newest messages are pinned
320 * @returns the paired calls, the ones not to be judged included
321 */
322export function pairCalls(
323  messages: readonly SessionMessage[],
324  recent: number,
325): Call[] {
326  const sites = new Map<string, Site[]>()
327  let order = 0
328
329  for (const [at, message] of messages.entries()) {
330    for (const use of message.toolUses) {
331      const site: Site = { use, at, order: order++ }
332      const sharing = sites.get(use.tool_use_id)
333
334      if (sharing === undefined) {
335        sites.set(use.tool_use_id, [site])
336      } else {
337        sharing.push(site)
338      }
339    }
340  }
341
342  const answered = new Set<string>()
343  const repeated = new Set<string>()
344  const pairs: {
345    site: Site
346    resultIndex: number
347    resultChars: number
348    isError: boolean
349  }[] = []
350
351  for (const [resultIndex, message] of messages.entries()) {
352    for (const { tool_use_id: id, text, isError } of message.toolResults ??
353      []) {
354      if (answered.has(id)) {
355        repeated.add(id)
356        continue
357      }
358
359      answered.add(id)
360
361      for (const site of sites.get(id) ?? []) {
362        pairs.push({ site, resultIndex, resultChars: text.length, isError })
363      }
364    }
365  }
366
367  const isKept = (at: number) => isPinnedIndex(at, messages.length, recent)
368  const isShared = (id: string) =>
369    repeated.has(id) || (sites.get(id)?.length ?? 0) > 1
370
371  return pairs
372    .sort((a, b) => a.site.order - b.site.order)
373    .map(({ site, resultIndex, resultChars, isError }, index) => ({
374      id: `t${index + 1}`,
375      toolUseId: site.use.tool_use_id,
376      tool: site.use.tool,
377      input: site.use.input,
378      callIndex: site.at,
379      resultIndex,
380      resultChars,
381      isError,
382      isPinned:
383        isShared(site.use.tool_use_id) ||
384        isKept(site.at) ||
385        isKept(resultIndex),
386    }))
387}
388
389/**
390 * Says whether a message is something the person typed: a user message
391 * with text that brings no tool result.
392 */
393function isPrompt(message: SessionMessage): boolean {
394  return (
395    message.role === 'user' &&
396    (message.toolResults?.length ?? 0) === 0 &&
397    message.text.trim() !== ''
398  )
399}
400
401/**
402 * Says what the assistant is working on: the instructions given with the
403 * compaction when there are any (the text typed after `/compact`, or a
404 * plugin's), since they were written for exactly this; otherwise the last
405 * prompts the person typed.
406 *
407 * @param messages the conversation
408 * @param instructions the compaction's instructions, when given
409 * @returns the goal text, possibly empty
410 */
411export function goalOf(
412  messages: readonly SessionMessage[],
413  instructions?: string,
414): string {
415  const stated = instructions?.trim() ?? ''
416
417  if (stated !== '') {
418    return clipped(stated, GOAL_CHARS)
419  }
420
421  // Read from the newest message back, and stop at the first few prompts:
422  // the conversation before them has no part in the goal.
423  const prompts: string[] = []
424
425  for (
426    let at = messages.length - 1;
427    at >= 0 && prompts.length < GOAL_PROMPTS;
428    at--
429  ) {
430    const message = messages[at]
431
432    if (message !== undefined && isPrompt(message)) {
433      prompts.unshift(clipped(message.text.trim(), PROMPT_CHARS))
434    }
435  }
436
437  return prompts.join('\n')
438}
439
440function statusOf(call: Call): string {
441  return call.isError ? 'error' : 'ok'
442}
443
444/**
445 * A call's input as JSON text. An input that cannot be serialised (a cycle)
446 * is named rather than allowed to fail the whole compaction.
447 */
448function inputJsonOf(call: Call): string {
449  try {
450    return JSON.stringify(call.input) ?? '{}'
451  } catch {
452    return '[input that cannot be shown]'
453  }
454}
455
456/**
457 * One argument of a call as `name=value` on a single line: a string as it
458 * is, any other value as its JSON, every stretch of white space as one
459 * space.
460 */
461function argumentOf(name: string, value: unknown): string {
462  const shown =
463    typeof value === 'string' ? value : String(JSON.stringify(value))
464
465  return `${name}=${shown.replace(/\s+/g, ' ')}`
466}
467
468/**
469 * A call on one line, for when a structured note costs too much. Its parts,
470 * a space apart: the id, the tool with its arguments in brackets (held to
471 * the tightest input cap), the outcome, and the length of the result.
472 */
473function lineOf(call: Call): string {
474  const said = Object.keys(call.input)
475    .map(name => argumentOf(name, call.input[name]))
476    .join(' ')
477
478  return [
479    call.id,
480    `${call.tool}(${clipped(said, INPUT_CAPS[2])})`,
481    statusOf(call),
482    `${call.resultChars}ch`,
483  ].join(' ')
484}
485
486/**
487 * One entry of the working list: the entry, what it costs, and whether it
488 * may be reduced.
489 */
490type Slot = {
491  entry: Entry
492  tokens: number
493  /**
494   * What the entry takes in UTF-8 bytes, comma included; 0 when the state
495   * has no byte budget.
496   */
497  bytes: number
498  isOld: boolean
499  isOut: boolean
500}
501
502/**
503 * One reduction: the stage it reports, the slots it visits in order, which
504 * of them it applies to, and what it does to one.
505 */
506type Pass = {
507  stage: Stage
508  over: readonly Slot[]
509  applies: (slot: Slot) => boolean
510  reduce: (slot: Slot) => void
511}
512
513/**
514 * Where several entries in a row hold nothing but one-line calls, gives the
515 * lines of all of them to the first and drops the rest. The keys of an
516 * entry are then paid for once for the whole row, and every line still
517 * starts with the id its questions name. `reweigh` measures a slot again
518 * once its entry has grown.
519 */
520function folded(
521  slots: readonly Slot[],
522  reweigh: (slot: Slot) => void,
523): Slot[] {
524  const isFoldable = (slot: Slot) =>
525    slot.isOld &&
526    slot.entry.text === '' &&
527    typeof slot.entry.calls?.[0] === 'string'
528  const kept: Slot[] = []
529  const grown = new Set<Slot>()
530
531  for (const slot of slots) {
532    const last = kept.at(-1)
533
534    if (
535      last !== undefined &&
536      isFoldable(last) &&
537      isFoldable(slot) &&
538      last.entry.role === slot.entry.role
539    ) {
540      // The first merge of a run gives the entry a list of its own; every
541      // later one appends to it. Copying the list or weighing the entry per
542      // merge would cost the square of the run's length, and a session of
543      // nothing but tool calls is one long run.
544      if (!grown.has(last)) {
545        last.entry.calls = [...(last.entry.calls as string[])]
546        grown.add(last)
547      }
548
549      ;(last.entry.calls as string[]).push(...(slot.entry.calls as string[]))
550      continue
551    }
552
553    kept.push(slot)
554  }
555
556  for (const slot of grown) {
557    reweigh(slot)
558  }
559
560  return kept
561}
562
563/**
564 * Describes the conversation to the decision model within `maxStateTokens`.
565 *
566 * The model judges better the more of the session it can see, so the state
567 * starts as everything and gives up detail only while its estimate is over
568 * the budget, cheapest loss first, and stops the moment it is under. Each
569 * rung below is tried only when the one above was not enough:
570 *
571 * 1. a cap on the JSON of each call's input, tightened twice;
572 * 2. the middle of every long text, in old messages before pinned ones;
573 * 3. the text of an old message, of which only its length is then stated;
574 * 4. the structure of an old call, written as a single line instead;
575 * 5. old messages in which no call was made;
576 * 6. the separate entries of neighbouring old messages that hold only calls.
577 *
578 * The estimate is checked here, whichever provider is asked, because a
579 * provider may cut a state that is too long without saying so. Where the
580 * route caps the body in bytes, the state is held to that budget too, on
581 * the same rungs: text with many letters to a token takes more bytes than
582 * the token budget assumes. A conversation still over either budget on the
583 * last rung is refused by throwing.
584 *
585 * @param messages the conversation
586 * @param calls its paired calls, as `pairCalls` answered them
587 * @param need the budget, the pinning, the goal and the wire format
588 * @returns the fitted state, its estimated size and the stage reached
589 */
590export function stateWithin(
591  messages: readonly SessionMessage[],
592  calls: readonly Call[],
593  need: FitNeed,
594): Fitted {
595  const frame = (conversation: Entry[]): State => ({
596    context: CONTEXT,
597    goal: need.goal,
598    conversation,
599  })
600  const tokensOf = (state: State) =>
601    estimatedTokensOf(need.wire.stateJsonOf(JSON.stringify(state)))
602  const frameTokens = tokensOf(frame([]))
603  const { bytes } = need
604  const frameBytes = bytes === undefined ? 0 : bytes.besideOf(frame([]))
605  // What an entry costs inside the list: its own JSON as the wire format
606  // carries it and the comma after it, in tokens and in UTF-8 bytes. The
607  // last entry has no comma, so a sum of these is over by one byte at most.
608  const weigh = (entry: Entry): Pick<Slot, 'tokens' | 'bytes'> => {
609    const json = need.wire.stateJsonOf(JSON.stringify(entry))
610
611    return {
612      tokens: estimatedTokensOf(json) + 1,
613      bytes: bytes === undefined ? 0 : bytesOf(json) + 1,
614    }
615  }
616  const inputs = new Map(calls.map(call => [call, inputJsonOf(call)]))
617  const made = new Map<number, Call[]>()
618
619  for (const call of calls) {
620    made.set(call.callIndex, [...(made.get(call.callIndex) ?? []), call])
621  }
622
623  let slots: Slot[] = []
624  let total = 0
625  let totalBytes = 0
626
627  const tally = () => {
628    total = frameTokens
629    totalBytes = frameBytes
630
631    for (const slot of slots) {
632      total += slot.tokens
633      totalBytes += slot.bytes
634    }
635  }
636
637  const lay = (inputCap: number) => {
638    slots = []
639
640    messages.forEach((message, at) => {
641      const own = made.get(at) ?? []
642
643      if (message.text.trim() === '' && own.length === 0) {
644        return
645      }
646
647      const entry: Entry = {
648        at,
649        role: message.role,
650        text: message.text.trim() === '' ? '' : message.text,
651      }
652
653      if (own.length > 0) {
654        entry.calls = own.map(call => ({
655          id: call.id,
656          tool: call.tool,
657          input: clipped(inputs.get(call) ?? '', inputCap),
658          result: `${statusOf(call)}, ${call.resultChars} characters, not shown`,
659        }))
660      }
661
662      slots.push({
663        entry,
664        ...weigh(entry),
665        isOld: !isPinnedIndex(at, messages.length, need.preserveRecentMessages),
666        isOut: false,
667      })
668    })
669
670    tally()
671  }
672
673  const fits = () =>
674    total <= need.maxStateTokens &&
675    (bytes === undefined || totalBytes <= bytes.limit)
676
677  const fitted = (stage: Stage): Fitted => {
678    const state = frame(
679      slots.filter(slot => !slot.isOut).map(slot => slot.entry),
680    )
681
682    return { state, tokens: tokensOf(state), stage }
683  }
684
685  for (const cap of INPUT_CAPS) {
686    lay(cap)
687
688    if (fits()) {
689      return fitted(cap === INPUT_CAPS[0] ? 'whole' : 'inputs shortened')
690    }
691  }
692
693  const old = slots.filter(slot => slot.isOld)
694  const oldFirst = [...old, ...slots.filter(slot => !slot.isOld)]
695
696  const passes: readonly Pass[] = [
697    {
698      stage: 'long texts cut in the middle',
699      over: oldFirst,
700      applies: slot => slot.entry.text.length > LONG_TEXT,
701      reduce: slot => {
702        slot.entry.text = abridged(slot.entry.text)
703      },
704    },
705    {
706      stage: 'old texts replaced by their length',
707      over: old,
708      applies: slot => slot.entry.text.length > COLLAPSED_NOTE_CHARS,
709      reduce: slot => {
710        const length = messages[slot.entry.at]?.text.length ?? 0
711
712        slot.entry.text = `[${length} characters of text left out]`
713      },
714    },
715    {
716      stage: 'old calls on one line',
717      over: old,
718      applies: slot => slot.entry.calls !== undefined,
719      reduce: slot => {
720        slot.entry.calls = (made.get(slot.entry.at) ?? []).map(lineOf)
721      },
722    },
723    {
724      stage: 'old call-free messages omitted',
725      over: old,
726      applies: slot => slot.entry.calls === undefined,
727      reduce: slot => {
728        slot.isOut = true
729      },
730    },
731  ]
732
733  for (const pass of passes) {
734    for (const slot of pass.over) {
735      if (!pass.applies(slot)) {
736        continue
737      }
738
739      pass.reduce(slot)
740
741      const now = slot.isOut ? { tokens: 0, bytes: 0 } : weigh(slot.entry)
742
743      total += now.tokens - slot.tokens
744      totalBytes += now.bytes - slot.bytes
745      slot.tokens = now.tokens
746      slot.bytes = now.bytes
747
748      if (fits()) {
749        return fitted(pass.stage)
750      }
751    }
752  }
753
754  slots = folded(
755    slots.filter(slot => !slot.isOut),
756    slot => {
757      Object.assign(slot, weigh(slot.entry))
758    },
759  )
760  tally()
761
762  if (fits()) {
763    return fitted('rows of old calls joined')
764  }
765
766  if (total <= need.maxStateTokens && bytes !== undefined) {
767    throw new Error(
768      'the conversation does not fit the request body: about ' +
769        `${totalBytes} bytes are left after every reduction and ` +
770        `${bytes.limit} are allowed`,
771    )
772  }
773
774  throw new Error(
775    `the conversation does not fit the state budget: about ${total} tokens ` +
776      `are left after every reduction and ${need.maxStateTokens} are allowed`,
777  )
778}
779
hooks/systemone.ts 244 lines
1/**
2 * A yes/no question; the answer is the probability of yes.
3 */
4type NoulQuestion = {
5  type: 'noul'
6  instructions: string
7  criteria?: { true?: string; false?: string }
8}
9
10/**
11 * A pick of one option; `criteria` maps each option to what it stands for.
12 */
13export type ChoiceQuestion = {
14  type: 'choice'
15  instructions: string
16  criteria: Record<string, string | null>
17}
18
19export type Question = NoulQuestion | ChoiceQuestion
20
21/**
22 * The questions of one request, by the id their answers come back under.
23 */
24export type Questions = Record<string, Question>
25
26/**
27 * What a provider reported a request cost. Every field is optional because
28 * the eight providers do not report the same fields.
29 */
30type Usage = {
31  input_tokens?: number
32  cost?: number
33}
34
35/**
36 * One response, unwrapped from whatever envelope its provider put around it.
37 */
38export type Reply = {
39  model?: string
40  answers: Record<string, unknown>
41  usage: Usage
42}
43
44/**
45 * The picked option of a `choice` answer and how sure the model was.
46 */
47type Picked = {
48  choice: string
49  confidence?: number
50}
51
52/**
53 * The rule every question id must pass before any provider-specific alias
54 * is applied: letters, digits, `_`, `.` and `-`, 100 characters at most. A
55 * provider with a stricter rule is sent aliases in place of the ids.
56 */
57const QUESTION_ID = /^[A-Za-z0-9_.-]{1,100}$/
58
59/**
60 * Whether a decoded JSON value is an object, as opposed to an array, `null`
61 * or a scalar.
62 */
63export function isRecord(value: unknown): value is Record<string, unknown> {
64  return typeof value === 'object' && value !== null && !Array.isArray(value)
65}
66
67function numberOf(value: unknown): number | undefined {
68  return typeof value === 'number' && Number.isFinite(value) ? value : undefined
69}
70
71/**
72 * How one provider's request body is written, and how big what it carries
73 * comes out once written: the token estimate is taken of the text that is
74 * sent, not of the objects it was written from.
75 */
76export type Wire = {
77  /**
78   * Serialises one request.
79   */
80  encode: (model: string, state: unknown, questions: Questions) => string
81  /**
82   * The JSON one question takes in the body, its id included.
83   */
84  questionJsonOf: (id: string, question: Question) => string
85  /**
86   * The JSON of the state, or of a part of it, as it stands in the body:
87   * as it is, or escaped inside a string.
88   */
89  stateJsonOf: (json: string) => string
90  /**
91   * The tokens a provider counts for each question beyond its own text.
92   */
93  tokensPerQuestion: number
94}
95
96const UTF8 = new TextEncoder()
97
98/**
99 * The size of a text once sent, in UTF-8 bytes: what a cap stated in bytes
100 * is held against. A character beyond ASCII takes two to four of them.
101 */
102export function bytesOf(text: string): number {
103  return UTF8.encode(text).length
104}
105
106/**
107 * Checks the ids of one request. An id a provider would reject is refused
108 * before anything is sent: a 422 on one id would otherwise cost the whole
109 * batch it rides in.
110 *
111 * @param questions the questions, by id
112 * @returns the ids; throws when there is none or one is not a valid id
113 */
114export function idsOf(questions: Questions): string[] {
115  const ids = Object.keys(questions)
116
117  if (ids.length === 0) {
118    throw new Error('a System One request needs at least one question')
119  }
120
121  for (const id of ids) {
122    if (!QUESTION_ID.test(id)) {
123      throw new Error(`question id ${JSON.stringify(id)} is not a valid id`)
124    }
125  }
126
127  return ids
128}
129
130/**
131 * Serialises one request in the System One form: the three fields every
132 * provider that speaks the protocol as published takes.
133 *
134 * @param model the model name as the provider's body spells it
135 * @param state what every question is asked about
136 * @param questions the questions, by id
137 * @returns the JSON text of the request body
138 */
139export function bodyOf(
140  model: string,
141  state: unknown,
142  questions: Questions,
143): string {
144  idsOf(questions)
145
146  return JSON.stringify({ model, state, questions })
147}
148
149/**
150 * The System One body: the state as it is and the questions as a map by id.
151 */
152export const BARE: Wire = {
153  encode: bodyOf,
154  questionJsonOf: (id, question) => JSON.stringify({ [id]: question }),
155  stateJsonOf: json => json,
156  tokensPerQuestion: 0,
157}
158
159/**
160 * Reads a decoded response body as a reply. Only the `answers` map is
161 * required; each answer is checked when it is read, by the reader that knows
162 * which type the question had.
163 *
164 * @param payload the decoded body, already out of any provider envelope
165 */
166export function replyOf(payload: unknown): Reply {
167  if (!isRecord(payload) || !isRecord(payload.answers)) {
168    throw new Error('the response holds no answers object')
169  }
170
171  const reported = isRecord(payload.usage) ? payload.usage : {}
172  const usage: Usage = {}
173
174  for (const field of ['input_tokens', 'cost'] as const) {
175    const value = numberOf(reported[field])
176
177    if (value !== undefined) {
178      usage[field] = value
179    }
180  }
181
182  const reply: Reply = { answers: payload.answers, usage }
183
184  if (typeof payload.model === 'string') {
185    reply.model = payload.model
186  }
187
188  return reply
189}
190
191/**
192 * Reads the answer to a `noul` question: a probability, so a finite number
193 * from 0 to 1. Anything else throws, because a decision taken on a missing or
194 * out-of-range value would delete or keep a tool result for no reason.
195 *
196 * @param reply the reply the answer is in
197 * @param id the question's id
198 * @returns the probability of yes
199 */
200export function noulOf(reply: Reply, id: string): number {
201  const answer = reply.answers[id]
202  const value = isRecord(answer) ? numberOf(answer.noul) : undefined
203
204  if (value === undefined || value < 0 || value > 1) {
205    throw new Error(`no probability from 0 to 1 was answered for ${id}`)
206  }
207
208  return value
209}
210
211/**
212 * Reads the answer to a `choice` question. The pick must be one of the
213 * options that were offered: a name outside them cannot be acted on.
214 *
215 * @param reply the reply the answer is in
216 * @param id the question's id
217 * @param options the option names the question offered
218 * @returns the picked option and the confidence, when one was reported
219 */
220export function choiceOf(
221  reply: Reply,
222  id: string,
223  options: readonly string[],
224): Picked {
225  const answer = reply.answers[id]
226
227  if (
228    !isRecord(answer) ||
229    typeof answer.choice !== 'string' ||
230    !options.includes(answer.choice)
231  ) {
232    throw new Error(`no offered option was answered for ${id}`)
233  }
234
235  const picked: Picked = { choice: answer.choice }
236  const confidence = numberOf(answer.confidence)
237
238  if (confidence !== undefined) {
239    picked.confidence = confidence
240  }
241
242  return picked
243}
244
hooks/openai.ts 201 lines
1import { idsOf, isRecord } from './systemone'
2import type { Question, Questions, Wire } from './systemone'
3
4/**
5 * One question as OpenAI's Decisions API takes it: a list entry that names
6 * itself, where System One keys a map by the id.
7 */
8type OpenAIQuestion =
9  | { name: string; type: 'predicate'; instructions: string }
10  | {
11      name: string
12      type: 'choice'
13      instructions: string
14      choices: { value: string; description?: string }[]
15    }
16
17/**
18 * The longest JSON of a value OpenAI sent that an error quotes.
19 */
20const QUOTED_CHARS = 64
21
22/**
23 * A value OpenAI sent, made fit to quote in an error: its JSON, which
24 * escapes every control character, when that is short, and only its length
25 * otherwise. It is never cut: the message is redacted where it is shown,
26 * and a credential cut short would no longer be found there.
27 */
28function quoted(value: unknown): string {
29  const json = JSON.stringify(value)
30
31  if (json === undefined) {
32    return 'missing'
33  }
34
35  return json.length <= QUOTED_CHARS
36    ? json
37    : `a value of ${json.length} characters`
38}
39
40/**
41 * A text made to end a sentence, so that two of them read as two sentences
42 * once appended to the instructions.
43 */
44function sentenceOf(text: string): string {
45  const trimmed = text.trim()
46
47  return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`
48}
49
50/**
51 * A question in OpenAI's form. A `predicate` has no field for what yes and
52 * no stand for, so a `noul` question's criteria are appended to its
53 * instructions, one sentence each; a `choice` option's description is
54 * omitted where System One gives `null`.
55 */
56function questionOf(name: string, question: Question): OpenAIQuestion {
57  if (question.type === 'choice') {
58    return {
59      name,
60      type: 'choice',
61      instructions: question.instructions,
62      choices: Object.entries(question.criteria).map(([value, description]) =>
63        description === null ? { value } : { value, description },
64      ),
65    }
66  }
67
68  const said = [question.instructions]
69  const criteria = question.criteria ?? {}
70
71  if (criteria.true !== undefined) {
72    said.push(`True means: ${sentenceOf(criteria.true)}`)
73  }
74
75  if (criteria.false !== undefined) {
76    said.push(`False means: ${sentenceOf(criteria.false)}`)
77  }
78
79  return { name, type: 'predicate', instructions: said.join(' ') }
80}
81
82/**
83 * Serialises one request for OpenAI: the state as a JSON string in `input`,
84 * which takes text and no object, and the questions as a list.
85 *
86 * @param model the model name
87 * @param state what every question is asked about
88 * @param questions the questions, by id
89 * @returns the JSON text of the request body
90 */
91function encodeOpenAI(
92  model: string,
93  state: unknown,
94  questions: Questions,
95): string {
96  return JSON.stringify({
97    model,
98    input: JSON.stringify(state),
99    questions: idsOf(questions).map(id =>
100      questionOf(id, questions[id] as Question),
101    ),
102  })
103}
104
105/**
106 * Reads OpenAI's list of answers as the System One map by id, which is what
107 * the readers of a reply take: a `predicate`'s probability as `noul`, a
108 * `choice`'s pick and confidence as they are. Only the fields read here are
109 * relied on, so a field OpenAI adds changes nothing; one it renames throws,
110 * naming the field. A refusal to answer throws, naming the question: every
111 * question was sent with a name, so every answer has one.
112 *
113 * An answer is taken only under the name of a question that was asked, and
114 * only once: any other name answers nothing the request asked, and a second
115 * answer to the same question would leave which one counts to chance. The
116 * map has no prototype, so a name such as `__proto__` is an ordinary key.
117 *
118 * @param payload the decoded response body
119 * @param asked the questions the request asked, by id
120 * @returns the body in the System One shape
121 */
122export function decodeOpenAI(payload: unknown, asked: Questions): unknown {
123  if (!isRecord(payload) || !Array.isArray(payload.answers)) {
124    throw new Error('the response holds no answers list')
125  }
126
127  const answers: Record<string, unknown> = Object.create(null)
128
129  payload.answers.forEach((answer: unknown, index) => {
130    const at = `answers[${index}]`
131
132    if (!isRecord(answer)) {
133      throw new Error(`${at} is not an object`)
134    }
135
136    if (typeof answer.name !== 'string' || answer.name === '') {
137      throw new Error(`${at}.name is missing`)
138    }
139
140    if (!Object.hasOwn(asked, answer.name)) {
141      throw new Error(
142        `${at}.name is ${quoted(answer.name)}, which was not asked`,
143      )
144    }
145
146    if (Object.hasOwn(answers, answer.name)) {
147      throw new Error(`${at} answers ${answer.name} a second time`)
148    }
149
150    if (answer.type === 'refusal') {
151      throw new Error(`refused to answer ${answer.name}`)
152    }
153
154    if (answer.type === 'predicate') {
155      answers[answer.name] = { noul: answer.probability }
156    } else if (answer.type === 'choice') {
157      // An option's value may be a boolean in OpenAI's schema. Read as text
158      // it can only match an option that was offered as that same text;
159      // any other pick is refused by the reader of the answer.
160      answers[answer.name] = {
161        choice:
162          typeof answer.choice === 'boolean'
163            ? String(answer.choice)
164            : answer.choice,
165        confidence: answer.confidence,
166      }
167    } else {
168      throw new Error(
169        `${at}.type is ${quoted(answer.type)}, neither predicate nor choice`,
170      )
171    }
172  })
173
174  const reported = isRecord(payload.usage) ? payload.usage : {}
175  const decoded: Record<string, unknown> = {
176    answers,
177    usage: { input_tokens: reported.input_tokens },
178  }
179
180  if (typeof payload.model === 'string') {
181    decoded.model = payload.model
182  }
183
184  return decoded
185}
186
187/**
188 * The body OpenAI's Decisions API takes. The state rides as a string, so its
189 * JSON is escaped once more and is measured in that form.
190 *
191 * OpenAI counts far more input tokens per question than its text: 129
192 * one-line predicates were counted as 19,139 input tokens, about 148 each,
193 * where Codiv counted about 26 each for the same questions.
194 */
195export const OPENAI: Wire = {
196  encode: encodeOpenAI,
197  questionJsonOf: (id, question) => JSON.stringify(questionOf(id, question)),
198  stateJsonOf: json => JSON.stringify(json).slice(1, -1),
199  tokensPerQuestion: 148,
200}
201
hooks/route.ts 442 lines
1import type { SessionMessage } from 'claude-code'
2
3import type { Ask } from './compact'
4import {
5  briefOf,
6  familyOf,
7  gatewayOf,
8  messageOf,
9  missingOf,
10  modelsOf,
11} from './providers'
12import type { Credentials, ProviderName, Route } from './providers'
13import type { Call } from './state'
14import { choiceOf } from './systemone'
15import type { ChoiceQuestion } from './systemone'
16
17/**
18 * A route the decision may pick: the name it is offered under and what is
19 * documented about the model behind it.
20 */
21type Candidate = {
22  key: string
23  route: Route
24  about: string
25}
26
27/**
28 * The job in a few numbers: what the routing question is asked about. It
29 * stands in for the full state, which would cost a second full-size request
30 * just to choose where to send the first.
31 */
32export type Profile = {
33  context: string
34  goal: string
35  messages: number
36  candidate_calls: number
37  state_tokens: number
38  tools: Record<string, number>
39  error_share: number
40  non_ascii_share: number
41}
42
43/**
44 * Says why the fitted state and its questions do not fit a route's limits,
45 * or nothing when they do.
46 */
47type SizeCheck = (route: Route) => string | undefined
48
49/**
50 * The route to use and one line saying how it was arrived at.
51 */
52type Routed = {
53  route: Route
54  why: string
55}
56
57/**
58 * The id of the one routing question.
59 */
60const ROUTE_QUESTION = 'route'
61
62/**
63 * How many tools the profile names; the rest are counted together.
64 */
65const TOOLS_SHOWN = 8
66
67/**
68 * What the providers' own documentation says each model is for. The
69 * decision is only as good as these lines, so each states published facts
70 * and nothing inferred.
71 */
72const ABOUT: Record<string, string> = {
73  clef:
74    'Clef, a 27B model. Cloudflare recommends it for highest-precision ' +
75    'decisions. It is slower and costs more per token than Clef-flash.',
76  'clef-flash':
77    'Clef-flash, a 9B model. Cloudflare recommends it for latency-critical ' +
78    'decisions on a hot path. It is the fastest of the models offered here.',
79  'clef-omni':
80    'Clef-omni, a 30B mixture-of-experts model with 3B active parameters. ' +
81    'It costs less per token than Clef and more than Clef-flash.',
82  jev:
83    "Jev, TypeSafe's flagship System One model. It reads text only, and " +
84    'English is its primary training language: TypeSafe reports lower ' +
85    'accuracy on other languages, CJK scripts included.',
86  'jev-1.13':
87    "Jev 1.13, TypeSafe's flagship System One model, which TypeSafe " +
88    'serves as `jev-latest`, its most recent stable official release. ' +
89    'English is its primary training language: TypeSafe reports lower ' +
90    'accuracy on other languages, CJK scripts included.',
91  'jev-1.14':
92    "Jev 1.14, the newest release of TypeSafe's flagship System One " +
93    'model, available from 2026-10-14; TypeSafe serves it as ' +
94    '`jev-preview`, "a preview version of `jev-latest`: should be better ' +
95    'in most ways". English is its primary training language: TypeSafe ' +
96    'reports lower accuracy on other languages, CJK scripts included.',
97  openjev:
98    'OpenJev, DiffusionGemma 26B-A4B made into a System One model; it ' +
99    'reads a distribution for every answer in one denoising step.',
100  'pplx-decider':
101    "Perplexity's 27B decision model. It reads text and images and " +
102    'returns typed answers with probabilities.',
103  'gpt-6-luna':
104    'GPT-6 Luna, which OpenAI describes as its most efficient model for ' +
105    'focused, high-volume tasks, served through its Decisions API.',
106}
107
108const PROFILE_CONTEXT =
109  'A coding assistant session is about to be compacted: a decision model ' +
110  'will be asked, for each old tool call, whether the call and its output ' +
111  'still have to stay in the transcript. This object describes that job: ' +
112  'how many messages and candidate tool calls there are, the estimated ' +
113  'size in tokens of the state every request will carry, which tools were ' +
114  'called how often, the share of calls that ended in an error, and the ' +
115  'share of the conversation text that is not ASCII. `goal` is what the ' +
116  'assistant is working on.'
117
118/**
119 * A route as a line of text shows it.
120 *
121 * @param route the route
122 * @returns `provider/model`
123 */
124export function labelOf(route: Route): string {
125  return `${route.provider}/${route.model}`
126}
127
128function keyOf(route: Route): string {
129  return `${route.provider}.${route.model.replace(/[^A-Za-z0-9_.-]/g, '-')}`
130}
131
132function aboutOf(route: Route): string {
133  const known = ABOUT[familyOf(route)]
134  const gateway = gatewayOf(route.provider)
135  const via = gateway === undefined ? '' : ` Reached through ${gateway}.`
136
137  return known === undefined
138    ? `The model ${route.model} at ${route.provider}; nothing is documented ` +
139        'here about what it is best at.'
140    : `${known}${via}`
141}
142
143/**
144 * Says why a route cannot take the job, or nothing when it can. Both checks
145 * are ones code can make with certainty, which is why they are made here
146 * and not put to a model.
147 */
148function refusalOf(
149  route: Route,
150  credentials: Credentials,
151  sizeRefusalOf: SizeCheck,
152): string | undefined {
153  const missing = missingOf(route.provider, credentials)
154
155  return missing.length > 0
156    ? `${missing.join(' and ')} unset`
157    : sizeRefusalOf(route)
158}
159
160/**
161 * Lists the routes that can take the job.
162 *
163 * Every eligible provider is considered with each model it offers; the
164 * configured provider with the configured model in place of its default. A
165 * route is left out when a credential it needs is unset or the fitted state
166 * exceeds its documented limit. A model family is offered once: over the
167 * route that reaches it directly whenever there is one, else over the
168 * first gateway to it in `PROVIDERS` order, and every other route to it is
169 * left out of the choice.
170 *
171 * @param configured the route the options name
172 * @param eligible the providers that may be sent anything, in `PROVIDERS`
173 * order
174 * @param credentials the resolved credentials
175 * @param sizeRefusalOf the check of the fitted state against a route's limits
176 * @returns the candidates, for every route not offered the reason, and
177 * whether the configured provider is among the routes that can take the job
178 */
179export function candidatesOf(
180  configured: Route,
181  eligible: readonly ProviderName[],
182  credentials: Credentials,
183  sizeRefusalOf: SizeCheck,
184): { candidates: Candidate[]; refused: string[]; isConfiguredUsable: boolean } {
185  const usable: Route[] = []
186  const refused: string[] = []
187
188  for (const provider of eligible) {
189    const offered = modelsOf(provider)
190    const models =
191      provider === configured.provider && !offered.includes(configured.model)
192        ? [configured.model]
193        : offered
194
195    for (const model of models) {
196      const route = { provider, model }
197      const refusal = refusalOf(route, credentials, sizeRefusalOf)
198
199      if (refusal === undefined) {
200        usable.push(route)
201      } else {
202        refused.push(`${labelOf(route)}: ${refusal}`)
203      }
204    }
205  }
206
207  const offered = new Map<string, Route>()
208
209  for (const route of [
210    ...usable.filter(route => gatewayOf(route.provider) === undefined),
211    ...usable.filter(route => gatewayOf(route.provider) !== undefined),
212  ]) {
213    if (!offered.has(familyOf(route))) {
214      offered.set(familyOf(route), route)
215    }
216  }
217
218  const candidates: Candidate[] = []
219
220  for (const route of usable) {
221    const same = offered.get(familyOf(route))
222
223    if (same !== undefined && same !== route) {
224      refused.push(`${labelOf(route)}: the same model as ${labelOf(same)}`)
225      continue
226    }
227
228    candidates.push({ key: keyOf(route), route, about: aboutOf(route) })
229  }
230
231  return {
232    candidates,
233    refused,
234    isConfiguredUsable: usable.some(
235      route => route.provider === configured.provider,
236    ),
237  }
238}
239
240function shareOf(part: number, whole: number): number {
241  return whole === 0 ? 0 : Math.round((part / whole) * 100) / 100
242}
243
244/**
245 * Describes the job for the routing question.
246 *
247 * @param messages the conversation
248 * @param calls the calls that will be asked about
249 * @param stateTokens the estimated size of the fitted state
250 * @param goal what the assistant is working on
251 * @returns the profile
252 */
253export function profileOf(
254  messages: readonly SessionMessage[],
255  calls: readonly Call[],
256  stateTokens: number,
257  goal: string,
258): Profile {
259  const counts = new Map<string, number>()
260
261  for (const call of calls) {
262    counts.set(call.tool, (counts.get(call.tool) ?? 0) + 1)
263  }
264
265  const ranked = [...counts].sort(([, a], [, b]) => b - a)
266  const tools = Object.fromEntries(ranked.slice(0, TOOLS_SHOWN))
267  const rest = ranked
268    .slice(TOOLS_SHOWN)
269    .reduce((sum, [, count]) => sum + count, 0)
270
271  if (rest > 0) {
272    tools.other = rest
273  }
274
275  let chars = 0
276  let nonAscii = 0
277
278  for (const { text } of messages) {
279    chars += text.length
280
281    for (let index = 0; index < text.length; index++) {
282      if (text.charCodeAt(index) > 127) {
283        nonAscii++
284      }
285    }
286  }
287
288  return {
289    context: PROFILE_CONTEXT,
290    goal,
291    messages: messages.length,
292    candidate_calls: calls.length,
293    state_tokens: stateTokens,
294    tools,
295    error_share: shareOf(
296      calls.filter(call => call.isError).length,
297      calls.length,
298    ),
299    non_ascii_share: shareOf(nonAscii, chars),
300  }
301}
302
303/**
304 * The one question the decision asks: which of the candidates should judge
305 * this job, each described by what is documented about it.
306 *
307 * @param candidates the routes on offer, two or more
308 * @returns the `choice` question
309 */
310function routeQuestionOf(
311  candidates: readonly Candidate[],
312): ChoiceQuestion {
313  return {
314    type: 'choice',
315    instructions:
316      'Which decision model should judge this compaction job? A wrong ' +
317      '"remove" loses output the assistant may still need, a wrong "keep" ' +
318      'only wastes context, and the answers are waited for while the ' +
319      'session is paused. Pick the model whose documented strengths fit ' +
320      'the job the state describes.',
321    criteria: Object.fromEntries(
322      candidates.map(candidate => [candidate.key, candidate.about]),
323    ),
324  }
325}
326
327/**
328 * Decides which route a compaction goes over.
329 *
330 * First by what code can check: `candidatesOf` leaves out every route that
331 * cannot take the job. Only when two or more remain is a model asked, with
332 * one `choice` question over the job's profile, on the fastest route there
333 * is: Cloudflare's Clef-flash when Cloudflare is eligible and configured,
334 * the configured route otherwise. The question carries a profile with the
335 * person's prompts in it, so it goes to no provider outside the eligible
336 * ones. With one candidate or a failed routing request the
337 * configured route is used, so the decision can never make a compaction
338 * fail that would have worked without it; the exception is a configured
339 * route that cannot take the job at all, where the one that can is used.
340 * The one candidate may be the direct route to the model a configured
341 * gateway also reaches: there is then one model and nothing to choose, and
342 * the configured gateway stays in use.
343 *
344 * With no candidate at all there is nothing to send the job to, the
345 * configured route included, so this throws, and the reason lists why each
346 * route was ruled out: the person has to see which credential or limit to
347 * change.
348 *
349 * @param configured the route the options name
350 * @param eligible the providers that may be sent anything, in `PROVIDERS`
351 * order
352 * @param credentials the resolved credentials
353 * @param sizeRefusalOf the check of the fitted state against a route's limits
354 * @param profile the job's profile
355 * @param askOn how a question is sent over a given route
356 * @returns the route and why it was picked; throws when no route can take
357 * the job
358 */
359export async function chooseRoute(
360  configured: Route,
361  eligible: readonly ProviderName[],
362  credentials: Credentials,
363  sizeRefusalOf: SizeCheck,
364  profile: Profile,
365  askOn: (route: Route) => Ask,
366): Promise<Routed> {
367  const { candidates, refused, isConfiguredUsable } = candidatesOf(
368    configured,
369    eligible,
370    credentials,
371    sizeRefusalOf,
372  )
373  const [first, second] = candidates
374  const left = refused.length === 0 ? '' : ` (${refused.join('; ')})`
375
376  if (first === undefined) {
377    throw new Error(`no route can take this job: ${refused.join('; ')}`)
378  }
379
380  if (second === undefined) {
381    if (!isConfiguredUsable) {
382      return {
383        route: first.route,
384        why: `only ${labelOf(first.route)} can take this job${left}`,
385      }
386    }
387
388    const found =
389      first.route.provider === configured.provider
390        ? 'one route is available'
391        : 'one model is available'
392
393    return {
394      route: configured,
395      why: `${found}${left}; using the configured ${labelOf(configured)}`,
396    }
397  }
398
399  const asked: Route =
400    eligible.includes('cloudflare') &&
401    missingOf('cloudflare', credentials).length === 0
402      ? { provider: 'cloudflare', model: 'clef-flash' }
403      : configured
404
405  try {
406    const reply = await askOn(asked)(profile, {
407      [ROUTE_QUESTION]: routeQuestionOf(candidates),
408    })
409    const picked = choiceOf(
410      reply,
411      ROUTE_QUESTION,
412      candidates.map(candidate => candidate.key),
413    )
414    const chosen = candidates.find(candidate => candidate.key === picked.choice)
415
416    if (chosen === undefined) {
417      throw new Error('the picked option is not a candidate')
418    }
419
420    const sure =
421      picked.confidence === undefined
422        ? ''
423        : `, confidence ${picked.confidence.toFixed(2)}`
424
425    return {
426      route: chosen.route,
427      why: `${labelOf(asked)} picked ${labelOf(chosen.route)}${sure}`,
428    }
429  } catch (error) {
430    // The reason may quote a provider's text, and it reaches the report
431    // line, so it is quoted like any other: redacted and on one short line.
432    const reason = briefOf(messageOf(error), credentials)
433
434    return {
435      route: configured,
436      why:
437        `the routing request failed (${reason}); using the configured ` +
438        labelOf(configured),
439    }
440  }
441}
442
hooks/ask.ts 280 lines
1import type { HttpInit, HttpResponse } from 'claude-code'
2
3import type { Ask } from './compact'
4import {
5  briefOf,
6  exchangeOf,
7  isRetryable,
8  messageOf,
9  replyFrom,
10} from './providers'
11import type { Credentials, Route } from './providers'
12
13/**
14 * What a request needs from the engine, handed in as functions because the
15 * engine interface itself cannot leave the hooks module's own file.
16 */
17export type Ports = {
18  /**
19   * `$.http.fetch`.
20   */
21  fetch: (url: string, init: HttpInit) => Promise<HttpResponse>
22  /**
23   * Waits before a retry. Resolves false, without waiting, when the hook has
24   * no time left to spend on it. `signal` aborts when the attempt the wait
25   * belongs to is over, and the wait must end with it then: a wait that
26   * outlived its attempt would hold the hook for nothing.
27   */
28  pause: (ms: number, signal: AbortSignal) => Promise<boolean>
29  /**
30   * `$.clock.after`: runs `fn` once after `ms` milliseconds unless the
31   * answer's `cancel` is called first.
32   */
33  after: (ms: number, fn: () => void) => { cancel: () => void }
34  /**
35   * `next.signal`: aborts when the compaction this hook serves is given up.
36   */
37  signal: AbortSignal
38}
39
40/**
41 * How long to wait before the second and the third attempt of one request.
42 * The hook's own code and its waits are charged to its ten seconds; the time
43 * a request is out is not. The two waits of one request stay under two
44 * seconds together, but that bound is per request, not per compaction: with
45 * `MAX_REQUESTS` batches going out `CONCURRENT_REQUESTS` at a time, as many
46 * rounds of batches as that makes (six, at sixteen and three) can each wait
47 * in turn. What bounds the waits of a compaction together is the `pause`
48 * port, which declines a wait when the hook has too little of its time left.
49 */
50const BACKOFF_MS = [400, 1200] as const
51
52/**
53 * How long one compaction may wait on its providers, from the moment its
54 * first request can go out: the routing question, every batch, every retry
55 * and every wait between retries together. A request has no timeout of its
56 * own, and the time it takes is not charged to the hook, so without a bound
57 * a provider that accepts a request and never answers would hold the
58 * compaction open for good, and the built-in summary would never get its
59 * turn. The bound is the longest the person waits on the providers, with the
60 * session paused, before that summary starts.
61 */
62const COMPACTION_DEADLINE_MS = 30_000
63
64/**
65 * The requests and waits of one compaction, under the one bound they share.
66 *
67 * The compaction is over, as far as its providers go, at the first of: its
68 * deadline passing, the engine giving the compaction up, `fail` being
69 * called, or `close` being called. From then on `fetch` and `pause` start
70 * nothing and reject with the reason. When it is over for any reason but
71 * `close`, whatever they had under way rejects with it at once; however it
72 * ends, a wait under way is aborted. A request that is out cannot be
73 * withdrawn, so its late answer is ignored.
74 */
75type Attempt = {
76  /**
77   * `Ports.fetch`, started only while the compaction is not over. A request
78   * the host refuses by throwing, instead of by rejecting, rejects all the
79   * same.
80   */
81  fetch: Ports['fetch']
82  /**
83   * `Ports.pause`, started only while the compaction is not over, with a
84   * signal that aborts when it is.
85   */
86  pause: (ms: number) => Promise<boolean>
87  /**
88   * Why the compaction is over, or undefined while it is not.
89   */
90  failure: () => Error | undefined
91  /**
92   * Ends the compaction with a reason. Only the first reason counts.
93   */
94  fail: (reason: Error) => void
95  /**
96   * Ends the compaction, when nothing ended it before, and releases the
97   * deadline's timer and the listener on the engine's signal. Called once
98   * the compaction has its outcome, whichever that is: a request still out
99   * then has nobody to answer, and must not retry or wait.
100   */
101  close: () => void
102}
103
104/**
105 * Puts one compaction's requests under one deadline, armed here and nowhere
106 * else, and under the engine's signal.
107 *
108 * @param ports the engine calls
109 * @returns the attempt; the caller closes it when the compaction is decided
110 */
111export function attemptOf(ports: Ports): Attempt {
112  let failure: Error | undefined
113  let disarm = () => {}
114  let reject: (reason: Error) => void = () => {}
115  // Aborted when the attempt is over, however it ends: the waits listen to
116  // it, so that none of them outlives the attempt.
117  const ended = new AbortController()
118
119  const cut = new Promise<never>((_resolve, rejectCut) => {
120    reject = rejectCut
121  })
122
123  // An end that comes while nothing is under way has nobody to reach, and
124  // must not surface as a rejection nobody handled.
125  cut.catch(() => {})
126
127  const fail = (reason: Error) => {
128    if (failure !== undefined) {
129      return
130    }
131
132    failure = reason
133    disarm()
134    reject(reason)
135    ended.abort(reason)
136  }
137
138  const interrupted = () =>
139    new Error(
140      'the compaction was interrupted before its requests were answered',
141    )
142
143  if (ports.signal.aborted) {
144    fail(interrupted())
145  } else {
146    const onAbort = () => fail(interrupted())
147
148    // Neither is left set up without the other: the listener goes on first
149    // and comes off again when the timer cannot be armed, so an attempt that
150    // could not be made leaves nothing on the engine's signal or its clock.
151    ports.signal.addEventListener('abort', onAbort, { once: true })
152
153    let timer: { cancel: () => void }
154
155    try {
156      timer = ports.after(COMPACTION_DEADLINE_MS, () =>
157        fail(
158          new Error(
159            'the requests of this compaction were not all answered within ' +
160              `${COMPACTION_DEADLINE_MS / 1000} seconds`,
161          ),
162        ),
163      )
164    } catch (error) {
165      ports.signal.removeEventListener('abort', onAbort)
166
167      throw error
168    }
169
170    disarm = () => {
171      disarm = () => {}
172      timer.cancel()
173      ports.signal.removeEventListener('abort', onAbort)
174    }
175  }
176
177  // The executor turns a `start` that throws into a rejection, so a call
178  // refused on the spot takes the same path as one refused later.
179  const within = <Value>(start: () => Promise<Value>): Promise<Value> =>
180    failure === undefined
181      ? Promise.race([new Promise<Value>(resolve => resolve(start())), cut])
182      : Promise.reject(failure)
183
184  return {
185    fetch: (url, init) => within(() => ports.fetch(url, init)),
186    pause: ms => within(() => ports.pause(ms, ended.signal)),
187    failure: () => failure,
188    fail,
189    // The shared cut is not rejected here: whatever is still out when the
190    // outcome is known is waited on by nobody and is left to settle on its
191    // own. Only what it would start from here on is refused.
192    close: () => {
193      failure ??= new Error('the compaction already has its outcome')
194      disarm()
195      ended.abort(failure)
196    },
197  }
198}
199
200/**
201 * Builds the function that sends one set of questions over a route.
202 *
203 * A response that may succeed on another attempt (rate limiting, an
204 * overloaded or failing server) is retried after a short wait, at most
205 * twice; any other failure is final at once. Only this one route is ever
206 * tried: there is no falling over to another provider.
207 *
208 * A failure of a decisive request ends the attempt on the spot, in the same
209 * step that found it, so that no other request of the compaction retries or
210 * waits after it. Once the attempt is over, every request fails with the
211 * attempt's reason, whatever its own would have been.
212 *
213 * What the host says when it refuses a call is quoted redacted and short:
214 * it may repeat the request's headers.
215 *
216 * @param route the provider and model
217 * @param credentials the resolved credentials
218 * @param attempt the compaction's requests and their shared bound
219 * @param isDecisive true for a request the compaction cannot do without (a
220 * batch of questions about calls), false for one it can (the routing
221 * question)
222 * @returns the function `compact` and the routing decision ask through
223 */
224export function askerOf(
225  route: Route,
226  credentials: Credentials,
227  attempt: Attempt,
228  isDecisive: boolean,
229): Ask {
230  const hosted = <Value>(what: string, call: Promise<Value>): Promise<Value> =>
231    call.catch(error => {
232      throw (
233        attempt.failure() ??
234        new Error(`${what} failed: ${briefOf(messageOf(error), credentials)}`)
235      )
236    })
237
238  return async (state, questions) => {
239    try {
240      const exchange = exchangeOf(route, credentials, state, questions)
241      const send = () =>
242        hosted(
243          `the request to ${route.provider}`,
244          attempt.fetch(exchange.url, exchange.init),
245        )
246
247      let response = await send()
248
249      for (const wait of BACKOFF_MS) {
250        if (response.ok || !isRetryable(response.status)) {
251          break
252        }
253
254        const waited = hosted(
255          `the wait before asking ${route.provider} again`,
256          attempt.pause(wait),
257        )
258
259        if (!(await waited)) {
260          break
261        }
262
263        response = await send()
264      }
265
266      return replyFrom(route, response, credentials, questions)
267    } catch (error) {
268      const reason =
269        attempt.failure() ??
270        (error instanceof Error ? error : new Error(String(error)))
271
272      if (isDecisive) {
273        attempt.fail(reason)
274      }
275
276      throw reason
277    }
278  }
279}
280