@juspay/neurolink 13.12.3 → 13.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -94,8 +94,7 @@ export function resolveHistoryBudget(result, compactionThreshold) {
94
94
  // so the default reproduces the previous number EXACTLY (0.8/0.8 = 1) and
95
95
  // anything lower shrinks the target. Clamped to at most 1 because this is
96
96
  // the "give the model less context" lever, never the "give it more" one —
97
- // over-filling a window is a hard provider error that ModelPool records as
98
- // a permanent cooldown.
97
+ // over-filling a window fails the current request.
99
98
  const scale = compactionThreshold === undefined
100
99
  ? 1
101
100
  : Math.max(0, Math.min(1, compactionThreshold / DEFAULT_COMPACTION_THRESHOLD));
package/dist/neurolink.js CHANGED
@@ -9960,7 +9960,9 @@ Current user's request: ${currentInput}`;
9960
9960
  streamPool.recordSuccess(capturedMember);
9961
9961
  }
9962
9962
  catch (streamConsumeErr) {
9963
- streamPool.recordFailure(capturedMember, classifyProviderError(streamConsumeErr));
9963
+ if (!isAbortError(streamConsumeErr)) {
9964
+ streamPool.recordFailure(capturedMember, classifyProviderError(streamConsumeErr));
9965
+ }
9964
9966
  throw streamConsumeErr;
9965
9967
  }
9966
9968
  })();
@@ -108,9 +108,8 @@ export declare class ClassifierRouter {
108
108
  * Returns undefined — meaning "leave the 0.8 default alone" — whenever the
109
109
  * feature is off, no scope was read, or the scope is the widest one. The
110
110
  * mapping can only ever LOWER the threshold, which is enforced in
111
- * `contextScopeToThreshold` rather than here, because the consequence of
112
- * getting it wrong in the other direction is not recoverable: a
113
- * `context_window` error puts the model into ModelPool's 10-year cooldown.
111
+ * `contextScopeToThreshold` rather than here, to avoid sending requests
112
+ * that exceed the selected model's context window.
114
113
  */
115
114
  private selectContextBudget;
116
115
  /** Tool narrowing: per-difficulty directive, then classifier hints. */
@@ -219,9 +219,9 @@ export class ClassifierRouter {
219
219
  ? byId.get(decision.selectedModelId)
220
220
  : undefined;
221
221
  if (picked) {
222
- // A pick that cannot hold the request is vetoed outright, whatever the
223
- // confidence. That failure is not a degraded answer but a hard provider
224
- // error, which ModelPool records as a permanent cooldown.
222
+ // A pick that cannot hold this request is vetoed outright, whatever the
223
+ // confidence. It would fail this request even though the member remains
224
+ // healthy for shorter requests.
225
225
  if (!this.fitsRequest(picked, input)) {
226
226
  this.deps.logger?.debug?.("[ClassifierRouter] classifier pick dropped — window too small", {
227
227
  id: decision.selectedModelId,
@@ -385,9 +385,8 @@ export class ClassifierRouter {
385
385
  * Returns undefined — meaning "leave the 0.8 default alone" — whenever the
386
386
  * feature is off, no scope was read, or the scope is the widest one. The
387
387
  * mapping can only ever LOWER the threshold, which is enforced in
388
- * `contextScopeToThreshold` rather than here, because the consequence of
389
- * getting it wrong in the other direction is not recoverable: a
390
- * `context_window` error puts the model into ModelPool's 10-year cooldown.
388
+ * `contextScopeToThreshold` rather than here, to avoid sending requests
389
+ * that exceed the selected model's context window.
391
390
  */
392
391
  selectContextBudget(decision) {
393
392
  if (this.config.contextBudget === false || !decision.contextScope) {
@@ -205,12 +205,9 @@ const JEV_CONTEXT_CRITERIA = [
205
205
  * Compaction thresholds per context scope, indexed to match
206
206
  * {@link CLASSIFIER_CONTEXT_SCOPES}.
207
207
  *
208
- * Every one is at or below the 0.8 default, and that is a hard invariant
209
- * rather than a tuning choice. Raising a budget lets a request through that
210
- * the model then rejects for exceeding its window — and `ModelPool` treats a
211
- * `context_window` error as a PERMANENT cooldown (10 years), so one
212
- * optimistic guess retires that model for the life of the process. Shrinking
213
- * a budget merely compacts a little earlier than it had to.
208
+ * Every one is at or below the 0.8 default. Raising a budget could let a
209
+ * request through that the model rejects for exceeding its window; shrinking
210
+ * a budget compacts a little earlier instead.
214
211
  */
215
212
  const CONTEXT_SCOPE_THRESHOLD = [0.45, 0.6, 0.75, 0.8];
216
213
  /** Below this calibrated confidence the scope reading is ignored entirely. */
@@ -184,10 +184,9 @@ export function rankCatalogue(candidates, difficulty, input, requiredCapabilitie
184
184
  return needed.every((cap) => c.capabilities?.includes(cap));
185
185
  });
186
186
  const pool = capable.length > 0 ? capable : [...candidates];
187
- // A model that cannot hold the request is not a cheaper option, it is a
188
- // failed one — and a context_window error puts the model in ModelPool's
189
- // permanent (10-year) cooldown, so this filter is load-bearing rather than
190
- // an optimisation. Applied only when it leaves something behind.
187
+ // A model that cannot hold this request would fail it. Keep it out of this
188
+ // request's candidates when another model fits. Applied only when it leaves
189
+ // something behind.
191
190
  const needTokens = input?.estimatedInputTokens ?? 0;
192
191
  const fits = needTokens > 0
193
192
  ? pool.filter((c) => c.contextWindow === undefined || c.contextWindow >= needTokens)
@@ -67,12 +67,8 @@ export declare class ModelPool {
67
67
  /**
68
68
  * Records a provider failure, setting a cooldown appropriate for the error class.
69
69
  *
70
- * - Retryable classes (rate_limit, server, network, unknown): timed cooldown
71
- * for `cooldownMs` so the member can recover and be retried later.
72
- * - Non-retryable classes (auth, context_window): permanent cooldown for the
73
- * lifetime of this ModelPool instance, because these errors are structural
74
- * and will not resolve between calls (wrong credentials, model not available
75
- * in team whitelist, payload exceeds the model's context window).
70
+ * A context-window error belongs to the request, so it does not change member
71
+ * health. Other classes, including auth, use the configured timed cooldown.
76
72
  */
77
73
  recordFailure(member: ModelPoolMember, errorClass: ProviderErrorClass): void;
78
74
  /**
@@ -91,30 +91,7 @@ export function classifyProviderError(error) {
91
91
  // ─────────────────────────────────────────────────────────────────────────────
92
92
  // Cooldown constants
93
93
  // ─────────────────────────────────────────────────────────────────────────────
94
- const DEFAULT_COOLDOWN_MS = 60_000; // 1 minute for retryable errors
95
- // Non-retryable errors use a permanent-for-the-instance cooldown: 10 years.
96
- // NOTE: Because ModelPool is stored as a long-lived field on the NeuroLink
97
- // instance (neurolink.ts constructor), a "permanent" cooldown blocks the
98
- // member for the entire lifetime of the NeuroLink instance, not just the
99
- // current call. Only use PERMANENT_COOLDOWN_MS for error classes where the
100
- // root cause is structural and will not resolve between calls (e.g. wrong API
101
- // key, model not whitelisted for the team). Transient or unclassified errors
102
- // must use the timed cooldown so a momentary failure doesn't permanently
103
- // retire a healthy member.
104
- const PERMANENT_COOLDOWN_MS = 10 * 365 * 24 * 60 * 60 * 1000;
105
- /**
106
- * Error classes that should receive a timed cooldown rather than a permanent
107
- * ban. "unknown" is deliberately included: because the classification is
108
- * uncertain, treating an unrecognised error as permanent could retire a
109
- * healthy member due to a one-off network blip or a non-standard error
110
- * message. A timed cooldown lets the member recover automatically.
111
- */
112
- const RETRYABLE_ERROR_CLASSES = new Set([
113
- "rate_limit",
114
- "server",
115
- "network",
116
- "unknown",
117
- ]);
94
+ const DEFAULT_COOLDOWN_MS = 60_000; // 1 minute for member health failures
118
95
  // ─────────────────────────────────────────────────────────────────────────────
119
96
  // ModelPool
120
97
  // ─────────────────────────────────────────────────────────────────────────────
@@ -218,19 +195,16 @@ export class ModelPool {
218
195
  /**
219
196
  * Records a provider failure, setting a cooldown appropriate for the error class.
220
197
  *
221
- * - Retryable classes (rate_limit, server, network, unknown): timed cooldown
222
- * for `cooldownMs` so the member can recover and be retried later.
223
- * - Non-retryable classes (auth, context_window): permanent cooldown for the
224
- * lifetime of this ModelPool instance, because these errors are structural
225
- * and will not resolve between calls (wrong credentials, model not available
226
- * in team whitelist, payload exceeds the model's context window).
198
+ * A context-window error belongs to the request, so it does not change member
199
+ * health. Other classes, including auth, use the configured timed cooldown.
227
200
  */
228
201
  recordFailure(member, errorClass) {
229
- const key = this.memberKey(member);
230
- const cooldown = RETRYABLE_ERROR_CLASSES.has(errorClass)
231
- ? this.now() + this.cooldownMs
232
- : this.now() + PERMANENT_COOLDOWN_MS;
233
- this.state.set(key, { cooldownUntil: cooldown });
202
+ if (errorClass === "context_window") {
203
+ return;
204
+ }
205
+ this.state.set(this.memberKey(member), {
206
+ cooldownUntil: this.now() + this.cooldownMs,
207
+ });
234
208
  }
235
209
  /**
236
210
  * Records a successful response, clearing any existing cooldown for this member
@@ -294,12 +294,9 @@ export type ClassifierRouterDecision = {
294
294
  * Fraction of the model's window at which compaction should trigger for
295
295
  * THIS request, replacing the fixed 0.8 default.
296
296
  *
297
- * **Only ever lower than the default, never higher.** Raising it would let
297
+ * **Only ever lower than the default, never higher.** Raising it could let
298
298
  * a request through that the model then rejects with a context-window
299
- * error — and `ModelPool` treats that as a permanent cooldown (10 years),
300
- * so a single optimistic guess retires the model for the life of the
301
- * process. Shrinking a budget wastes a little context; growing one is
302
- * unrecoverable.
299
+ * error. Shrinking the budget compacts a little earlier instead.
303
300
  */
304
301
  compactionThreshold?: number;
305
302
  /** The scope reading `compactionThreshold` was derived from. */
@@ -1248,8 +1248,7 @@ export type TextGenerationOptions = {
1248
1248
  * depends on the entire conversation should compact as late as possible.
1249
1249
  * When the classifier router runs with a decision model it fills this in
1250
1250
  * per request — always at or below the default, never above, because a
1251
- * request that overflows the window fails hard and `ModelPool` records that
1252
- * failure as a permanent cooldown.
1251
+ * request that overflows the window fails.
1253
1252
  */
1254
1253
  compactionThreshold?: number;
1255
1254
  /**
@@ -4,8 +4,7 @@
4
4
  * A ModelPool holds an ordered list of (provider, model, region) members and
5
5
  * selects among them per-turn using a configurable strategy. On provider
6
6
  * failure, the pool cools down the failed member and retries with the next
7
- * available one, using error-class-aware logic to distinguish retryable from
8
- * permanent failures.
7
+ * available one. Request-scoped context-window errors do not cool members.
9
8
  */
10
9
  /** One candidate provider/model/region tuple in a pool. */
11
10
  export type ModelPoolMember = {
@@ -35,7 +34,7 @@ export type ModelPoolConfig = {
35
34
  strategy?: ModelPoolStrategy;
36
35
  /**
37
36
  * How long (ms) a failed member stays in cooldown before it is eligible
38
- * again. Applies to retryable error classes (rate_limit, server, network).
37
+ * again. Applies to all error classes except context_window.
39
38
  * Default: 60_000 (1 minute).
40
39
  */
41
40
  cooldownMs?: number;
@@ -4,7 +4,6 @@
4
4
  * A ModelPool holds an ordered list of (provider, model, region) members and
5
5
  * selects among them per-turn using a configurable strategy. On provider
6
6
  * failure, the pool cools down the failed member and retries with the next
7
- * available one, using error-class-aware logic to distinguish retryable from
8
- * permanent failures.
7
+ * available one. Request-scoped context-window errors do not cool members.
9
8
  */
10
9
  export {};
@@ -304,8 +304,7 @@ export type StreamOptions = {
304
304
  * depends on the entire conversation should compact as late as possible.
305
305
  * When the classifier router runs with a decision model it fills this in
306
306
  * per request — always at or below the default, never above, because a
307
- * request that overflows the window fails hard and `ModelPool` records that
308
- * failure as a permanent cooldown.
307
+ * request that overflows the window fails.
309
308
  */
310
309
  compactionThreshold?: number;
311
310
  /**
@@ -2255,7 +2255,7 @@
2255
2255
  {"objectID":"2cad48473fb9c200377fe1a4b2f1e1feea861afe5ae7ee9a53caf6cbe313cc4a","title":"One line per model","url":"/docs/features/classifier-router-catalog#one-line-per-model","content":"Each surviving model becomes a ClassifierCandidate and renderCandidate()\nturns it into one terse line for jev's criteria map. The order and the\nprecedence are both deliberate:\ndescription always renders first, when present.\ntiers, when declared, renders next as intended for\ntrivial/simple tasks — the host's most direct statement of where a\n model belongs.\nContext window and capability flags always render. These are facts\n about the model (\"accepts images\", \"128K context\"), not opinions about\n how good it is, so nothing suppresses them.\nDeclared cost/quality replace the registry's own opinion, rather\n than sitting beside it. When either is set, the line adds capability N\n(higher is more capable) / relative cost N (lower is cheaper) and\n suppresses the registry's price, speed bucket, quality bucket, and\n \"strong at …\" use-case scores entirely. When neither is set, the registry\n fills all of that in exactly as it always did.\n\nTwo real renders, from the same model, show the difference:\n\nThis precedence exists because the registry's opinion used to win, and a\nlive measurement showed it silently overriding the host's own routing\nintent. A pool member declared exactly the second line above — an explicit\nstatement that this model is for rote work — but the registry rates the\nsame underlying model highly on general benchmarks, so the old rendering\nappended its own \"high quality\" and \"strong at coding, analysis, reasoning\"\non top. Five registry clauses against one line of host prose, and the host\nlost: a hard concurrency-bug task routed to the cheap model in 5 of 8 runs,\nbecause the model-pick question asks for \"the cheapest one that can still\ncomplete this request correctly\" and had just been told the cheap one was\nhigh quality and strong at reasoning. The declared quality: 2 never\nreached the model at all — only description did.","hierarchy":{"lvl0":"Features","lvl1":"The model catalogue","lvl2":"One line per model","lvl3":""}},
2256
2256
  {"objectID":"cac106bc67990b1f4b93d0096370fca3aa0e30de9da3db2bb3636813f4dd6b7d","title":"A choice over N models is a ranking of N","url":"/docs/features/classifier-router-catalog#a-choice-over-n-models-is-a-ranking-of-n","content":"Because readDecisionChoice returns every option's probability, one choice\nquestion over the whole catalogue doesn't just name a winner — it ranks all N\ncandidates by how likely each is to be the right pick. This is what makes\npicking from up to maxModels (120 by default; the whole registry today is 64) a single request rather than N binary questions.","hierarchy":{"lvl0":"Features","lvl1":"The model catalogue","lvl2":"A choice over N models is a ranking of N","lvl3":""}},
2257
2257
  {"objectID":"a0961baceadf689ad6859272fa26f697f86c61f66d83070a78eae6af11db354e","title":"Deterministic fallback ranking","url":"/docs/features/classifier-router-catalog#deterministic-fallback-ranking","content":"Every other decide consumer in this codebase falls back to _what the code\nalready did_. There was no prior \"pick from the whole registry\" behaviour to\nfall back to, so the catalogue needed its own: rankCatalogue() runs whenever\nno decision provider is configured, the call fails, or the difficulty tier's own\ntop-of-pool choice is what's needed (selectModels() always computes it, even\nwhen jev's pick clears its bar, as the fallback list that ships alongside the\nwinner).\n\nThe ranking is tierScore() — a deterministic formula per difficulty:\n\nsuitability reads the registry's own 1–10 score for the dimension that tier\ncares about (conversation for trivial/simple, coding for moderate,\nreasoning for hard/expert). tierCostWeight is what makes this a real\nranker rather than a sort by price: at trivial it is 1 (the cheapest\nadequate model wins outright), at expert it is 0.05 (price is nearly\nirrelevant). This never consults the network and is the ordering the decision\nmodel's own pick is compared against when deciding whether it clears its bar.","hierarchy":{"lvl0":"Features","lvl1":"The model catalogue","lvl2":"Deterministic fallback ranking","lvl3":""}},
2258
- {"objectID":"b0a5b78dc4cfcabcd52b58ea94936ee81e97b59b5907f058ccba74881a7aeacd","title":"Context-window filtering","url":"/docs/features/classifier-router-catalog#context-window-filtering","content":"Nothing in routing read maxContextTokens before this. Two independent checks\nnow do:\nrankCatalogue() filters candidates whose contextWindow is below the\n request's estimated input tokens, applied only when it would leave something\n behind (an empty result falls back to the unfiltered pool rather than\n routing nowhere).\nThe classifier's own pick is separately vetoed. Even when jev picks a\n model directly, fitsRequest() checks whether that specific model's window\n can hold the request. If it can't, the pick is dropped regardless of\n confidence — this is a hard provider error, not a degraded answer, because\n an oversized request against a real model puts that model into ModelPool's\n permanent (10-year) cooldown. A wrong guess here is not \"less accurate,\" it\n is unrecoverable for the life of the process.","hierarchy":{"lvl0":"Features","lvl1":"The model catalogue","lvl2":"Context-window filtering","lvl3":""}},
2258
+ {"objectID":"b0a5b78dc4cfcabcd52b58ea94936ee81e97b59b5907f058ccba74881a7aeacd","title":"Context-window filtering","url":"/docs/features/classifier-router-catalog#context-window-filtering","content":"Nothing in routing read maxContextTokens before this. Two independent checks\nnow do:\nrankCatalogue() filters candidates whose contextWindow is below the\n request's estimated input tokens, applied only when it would leave something\n behind (an empty result falls back to the unfiltered pool rather than\n routing nowhere).\nThe classifier's own pick is separately vetoed. Even when jev picks a\n model directly, fitsRequest() checks whether that specific model's window\n can hold the request. If it can't, the pick is dropped regardless of\n confidence — an oversized request would fail on that model. The model\n remains available for later requests that fit its window.","hierarchy":{"lvl0":"Features","lvl1":"The model catalogue","lvl2":"Context-window filtering","lvl3":""}},
2259
2259
  {"objectID":"e34966644db91aef39b46ef5c2f2fa259e9c828895197c9b2260a07c6e640bce","title":"What this is bad at","url":"/docs/features/classifier-router-catalog#what-this-is-bad-at","content":"Registry quality is coarse, and the catalogue path never shows its own\n work. Auto-enriched quality is a 3-bucket scale (high/medium/low)\n before buildModelCatalog() turns it into 1/2/3; two \"high\" models\n cannot be separated on capability alone. Worse for this page's topic: because\n the catalogue always populates cost/quality, its rendered line never\n shows the registry's own price, speed bucket, or \"strong at …\" scores — only\n the terse capability N / relative cost N form. Declare tiers/quality\n on a hand-declared pool member for finer control over the number itself; there\n is no way to get the richer rendering for a catalogue-sourced model.\nA catalogue candidate's \"relative cost\" is real pricing wearing a relative\n label. buildModelCatalog() seeds it from inputCostPer1K + outputCostPer1K\n — a small decimal like 0.00074 — not a small integer a host would typically\n pick for a hand-declared cost. The number is still correct and still never\n rendered as currency, but it does not compare cleanly against a hand-declared\n member's cost: 1 in the same pool, since one is a real price and the other\n is an arbitrary scale.\nUnknown-to-the-registry models rank on relative numbers, not real prices.\n A model the registry doesn't know (self-hosted, brand-new) keeps whatever\n cost/quality the host declared, compared only against other declared\n values on the same relative scale — never rendered as a dollar figure it\n isn't.\nA wide catalogue is still one choice question, and the cap is hard, not\n smart, when it does bind. Every model adds tokens to that single question;\n maxModels is the safeguard, and a model past it would simply never be\n offered rather than offered with lower priority. Today this is theoretical —\n the registry is 64 models against a default cap of 120, so nothing is\n dropped — but the mechanism has no ranking behavior for the day a registry\n does exceed it.\nPermissive reachability means occasional dead candidates.","hierarchy":{"lvl0":"Features","lvl1":"The model catalogue","lvl2":"What this is bad at","lvl3":""}},
2260
2260
  {"objectID":"2d7354001109ce1051977450cf365d1f2a8e13b345ad206ee23b1f5466228454","title":"See also","url":"/docs/features/classifier-router-catalog#see-also","content":"Classifier Router\nModel routing with a decision model\nThe decide inference type","hierarchy":{"lvl0":"Features","lvl1":"The model catalogue","lvl2":"See also","lvl3":""}},
2261
2261
  {"objectID":"57703ab4e28ce3ad7f4c83d5d3e43f1b1d5541cbb2ac1d6f10f7a057046f0e1b","title":"Model routing with a decision model","url":"/docs/features/classifier-router-jev-strategy","content":"Model routing with a decision model\n\nThe classifier router has a jev strategy: one\ndecision-model round trip answers difficulty,\nrequired capabilities, risk and the model pick simultaneously, with a\ncalibrated confidence on each. This page is the strategy's own mechanics —\nclassifier-router.md covers the router as a whole.\n\nThe degradation contract. With no decision provider configured,\nresolveStrategy() resolves auto to heuristic, exactly as it always did.\nclassifyJev() itself never throws: any failure, timeout, or malformed answer\nfalls back to classifyHeuristic(). Configuring a decision provider (for example TYPESAFE_API_KEY or\nAI_GATEWAY_API_KEY) upgrades routing; it cannot make routing worse than before\nthe key existed. The same holds for PERPLEXITY_API_KEY, which is also the\nPerplexity text provider's key, and for CLOUDFLARE_API_KEY with\nCLOUDFLARE_ACCOUNT_ID, which are also the Cloudflare Workers AI text provider's\ntoken and account id, and for SUBQ_API_KEY, and for OPENAI_API_KEY, which is also the OpenAI chat\nprovider's key (for a host with only that key auto now resolves to jev,\nanswered by OpenAI Decisions, the default decision provider when none ahead of it is configured, unless OPENAI_BASE_URL,\nOPENAI_API_BASE or credentials.openai.baseURL names a host other than https://api.openai.com, which makes it a gateway's key), and for SCALEDOWN_API_KEY, which is ScaleDown's own and counts by itself (with only that key auto resolves to jev, answered by ScaleDown). \"Configured\" counts the environment, the instance\ncredentials, and the request's own per-call credentials — a host that holds\nno decision key but passes a tenant's credentials: { laya } on a generate()\ncall routes that call with jev, and the decision goes to the tenant's account.\n\nWhat goes into the state\n\nclassifyJev() sends the request truncated to 8000 characters, plus four\nsignals the caller already has on hand:\n\nAlongside it, one batch asks: difficulty (a choice over the five tiers),\nneeds_vision / needs_tools / needs_reasoning (boolean), risky\n(boolean), context (a score — see\nper-request context budget), and, only when the\npool has more than one member, model (a choice over the pool, rendered by\nthe catalogue). All of this rides in\none request. On TypeSafe that takes ~400ms, because latency is flat in question\ncount; on Perplexity each further question adds about 65 ms, up to 128 (see\nits guide); on\nCloudflare Clef a small request took 0.3 to 1.0 s on 2026-10-03 (see\nits guide). See\nthe batching rule.\n\nNeuroLink refuses a state it estimates at more than 16,000 tokens (about 60,000\ncharacters of prose) with max_tokens_exceeded, to keep Clef inside what it was\nseen to read in full and inside a timeout a fail-open consumer can afford. A\nlonger request is refused there, and the heuristic classifier's tier stands, as it\ndoes on any failure.\n\nThe difficulty rubric\n\nFive tiers, ordered easiest to hardest, worded about the shape of the work —\nthe model is never told a provider or model name:\n\n| Tier | Criterion |\n| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |\n| trivial | Mechanical and local: rename a symbol, fix a typo, add an import, run one named command, or answer something already stated. |\n| simple | A small localised change or a direct factual answer. One file, one obvious approach. |\n| moderate | Ordinary engineering: implement a well-specified change across a few files, write tests, fix a clearly described bug, review a small diff. |\n| hard | Deep reasoning: architecture and design, debugging a failure whose cause is unknown, security analysis, concurrency, cross-system refactors. |\n| expert | Frontier-level work: ambiguous requirements, novel design with no established pattern, or analysis where a wrong answer is costly and hard to detect. |\n\nAsymmetric confidence bars, and why they differ\n\nA verdict harder than the neutral tier (moderate) spends more if wrong; a\nverdict easier than neutral spends less if wrong. Those are not the same\nmistake:\nRouting a simple task to an expensive model wastes money. Cheap to be wrong\n about, so the bar to route up is low: minUpgradeConfidence defaults to\n 0.3.\nRouting a hard task to a weak model produces a wrong answer. Expensive to be\n wrong about, so the bar to route down is high: minDowngradeConfidence\n defaults to 0.6.\n\nBelow the applicable bar, the difficulty verdict is discarded and the heuristic\nclassifier's tier stands instead — not a downgraded jev answer, the ordinary\nzero-cost fallback.\n\nOne case skips both bars: a risky reading above 0.7 forces the tier to at\nleast hard, unconditionally. Risk can only ever ","hierarchy":{"lvl0":"Features","lvl1":"Model routing with a decision model","lvl2":"","lvl3":""}},
@@ -2699,11 +2699,11 @@
2699
2699
  {"objectID":"efd21276881aaff463922d63ebd364e1b177ac659b6927d25c7858f7bb0a6190","title":"9.6 Metrics","url":"/docs/features/codex-proxy-support#96-metrics","content":"Two Codex-outbound-specific OTel counters, both emitted from\nsrc/lib/proxy/proxyTracer.ts:\n\n| Metric | Labels | Meaning |\n| ---------------------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| proxy_codex_outbound_schema_degraded_total | {reason, toolName} | A tool declaration's JSON Schema needed flattening or lost a feature on the way to a Claude tool. reason is one of circular_ref_flattened (a genuine cycle degraded to {type:\"object\"}) or strict_mode_flag_dropped (the Codex tool's strict flag has no Claude equivalent and was dropped). |\n| proxy_codex_outbound_unsupported_field_total | {field} | A Codex-outbound request field this repo cannot faithfully represent in the Claude request was dropped rather than failing the translation. |\n\nEvery other proxy metric in the existing dashboard (proxy_request_duration_ms,\nproxy_tokens_*, proxy_errors_total, proxy_fallback_attempts_total,\nproxy_fallback_success_total, proxy_fallback_failure_total, …) also fires\nfor a Codex-outbound-fallback request, on the serving engine, same as any other\nproxied call.\n\nproxy_cost_usd_total is a cumulative counter, not a gauge.","hierarchy":{"lvl0":"Features","lvl1":"Codex (ChatGPT) Support for NeuroLink Proxy","lvl2":"9.6 Metrics","lvl3":""}},
2700
2700
  {"objectID":"43b245bbe599ce8328e90e4528f7d83e953cf3ddea0448aac3ac7834587419f7","title":"9.7 Sign-off status","url":"/docs/features/codex-proxy-support#97-sign-off-status","content":"The following were flagged in the original design as behavior-changing choices\nneeding product sign-off. All three were signed off 2026-09-28 and ship as\ndesigned, not as placeholders awaiting approval:\nThe lossy grammar/custom-tool → single {input: string} parameter mapping\n (§9.4 above), with custom_tool_call on the way back.\nThe {input: raw} non-JSON-argument history fallback and its downstream\n effect on tool execution.\nThe reasoning-effort → thinking-budget table in §9.4 above.\n\nSee docs/superpowers/specs/2026-09-27-codex-outbound-fallback-design.md for\nthe full design record and rulings.","hierarchy":{"lvl0":"Features","lvl1":"Codex (ChatGPT) Support for NeuroLink Proxy","lvl2":"9.7 Sign-off status","lvl3":""}},
2701
2701
  {"objectID":"7d4e6e1166cdf67bb24a8c10d864e2a5e88df37bb004a60467cdf247ebd829ca","title":"9.8 Live validation (after the Codex quota resets 2026-10-03)","url":"/docs/features/codex-proxy-support#98-live-validation-after-the-codex-quota-resets-2026-10-03","content":"Everything above has been verified at the request/response shape level —\ntranslation correctness, config validation, metrics, loop-prevention logic —\nusing synthetic and characterization fixtures (including a redacted real Codex\nCLI wire capture). None of it has been exercised against live Codex, Vertex\nor Anthropic traffic end to end, because the Codex account available to this\nwork is quota-rejected until 2026-10-03. The validation plan's Part B live\nmatrix (stage-d-validation.md §4) is the run to do once quota is back; its\nscenarios, unchanged from the plan:\n[ ] B1 — Cold start, single turn (gpt-5.6-sol → Anthropic): if the\n Section-0 tool policy permits dispatch, proxy_tokens_input rises by\n roughly the translated prefix token count and proxy_tokens_cache_creation\n rises above 0; if the policy is fail-closed, a Codex-shaped diagnostic\n with no dispatch attempted is the correct, expected outcome — not a bug.\n[ ] B2 — Warm second turn, same session/account (gpt-5.6-sol →\n Anthropic): confirm both turns were served by the same account (query\n proxy_cost_usd_total's account label) before drawing any cache\n conclusion, then confirm proxy_tokens_cache_read rises by ≥80% of the\n prior turn's cache_creation delta with the second turn's own\n cache_creation delta near zero — the live proof that A.6's byte-\n stability requirement (already fixture-verified offline) holds against\n a real cache hop.\n[ ] B3 — Functions-namespace tool call (gpt-6-astra → Anthropic):\n read_file alongside the ever-present exec/request_review\n collaboration tools; the client-visible stream carries a well-formed\n function_call the Codex CLI can execute, proxy_fallback_success_total{provider='anthropic'}\n increments by exactly 1, and there is no Anthropic 400 on the\n accompanying custom-tool schema.","hierarchy":{"lvl0":"Features","lvl1":"Codex (ChatGPT) Support for NeuroLink Proxy","lvl2":"9.8 Live validation (after the Codex quota resets 2026-10-03)","lvl3":""}},
2702
- {"objectID":"89c0f088b6b4f91a1fc99b1db7acb741e912010bac6416ffe5d94730ff7e11a2","title":"Per-request context budget","url":"/docs/features/context-budget","content":"Per-request context budget\n\nContext compaction has always triggered at a fixed 80% of the model's window.\nThat number is now a default, not a constant: a per-request compactionThreshold\noption lowers it for requests that need less room, and the\nclassifier router's jev strategy can fill\nit in automatically by asking how much of the conversation the request actually\nneeds.\n\nThe degradation contract. Every input here is optional. With no\ncompactionThreshold passed and no classifier router configured, the effective\nthreshold is exactly 0.8, exactly as before — resolveHistoryBudget()'s\nscale factor is compactionThreshold / 0.8, so the default value reproduces\nthe previous budget calculation to the token.\n\nSetting it directly\n\nCLI: neurolink generate \"...\" --compaction-threshold 0.45 (existing flag,\ndescription: \"Fraction of the context window (0-1) at which history is\ncompacted. Default 0.8.\").\n\nLetting the classifier fill it in\n\nWhen classifierRouter.contextBudget is enabled (default: true whenever\nthe strategy resolves to a decision model; ignored by heuristic/llm), the\nsame jev request that classifies difficulty also asks a score question:\n\nHow much of the earlier conversation does answering this request actually\nrequire?\n\nagainst a four-level rubric:\n\n| Scope | Criterion | Threshold |\n| ------------------- | -------------------------------------------------------------------------------------------------- | --------- |\n| current-message | Self-contained. Earlier conversation would not change the answer. | 0.45 |\n| recent-turns | Needs the last few exchanges — a follow-up, a correction, a reference to something just discussed. | 0.60 |\n| full-conversation | Needs the whole conversation, including decisions and constraints established much earlier. | 0.75 |\n| everything | Needs the conversation and every document, file and tool result that has been gathered. | 0.80 |\n\nThis is a rubric, not a token count, and deliberately so: a decision model\nplaces a request on an ordered scale reliably and reads digit strings as text,\nnot quantities — asking \"how many tokens does this need\" would get an answer\nshaped like a guess at a number, not a calibrated judgement.\n\nThe reading is used only above MIN_CONTEXT_SCOPE_CONFIDENCE (0.5); below\nthat, contextScope is left undefined and the request falls back to the\n0.8 default exactly as if the question had not been asked. The scope judgement\nis independent of the difficulty tier — a trivial request can still need the\nwhole conversation, and an expert one can be entirely self-contained — so\nit is read and applied on its own, and survives every path on which the\ndifficulty verdict itself is discarded by its confidence bar.\n\napplyClassifierRouting() then applies the derived threshold only when the\ncaller left compactionThreshold unset:\n\nAn explicit per-call value always wins. The classifier is filling in a default\nyou didn't set, never overriding one you did.\n\nThe one-directional invariant\n\nThe mapping from scope to threshold can only ever lower the 0.8 default,\nnever raise it, and this is enforced independently at two layers:\ncontextScopeToThreshold() clamps its result with Math.min(0.8, ...)\n before returning.\nClassifierRouter.selectContextBudget() re-checks the result and discards\n it unless threshold < 0.8.\n\nThe reason this is a hard invariant rather than a tuning choice: shrinking a\nbudget merely compacts a little earlier than strictly necessary — the model\nstill answers correctly with slightly less history than it could have used.\nGrowing one lets a request through that the provider then rejects with a\ncontext-window error, and ModelPool treats that as a permanent (10-year)\ncooldown — one optimistic guess retires the model for the life of the\nprocess. Getting this wrong in one direction is recoverable; getting it wrong\nin the other is not, so the code refuses to let a bug make that mistake even\nonce.\n\nHow the threshold changes the actual budget\n\nresolveHistoryBudget() is what the compactor targets — the model's available\ninput space minus system prompt, current prompt, tool definitions and file\nattachments, all of which ride alongside history rather than being part of\nit. The per-request threshold scales that budget directly:\n\nWith the default 0.8, scale is exactly 1 and the budget is unchanged\nfrom before this option existed. A 0.4 threshold halves the history budget.\nThe 0.95 safety factor is unrelated to this feature — it exists because\ntoken estimation is character-based and approximate, so the compactor always\naims slightly under the true ceiling.\n\nWhat this is bad at\nIt is a suggestion, not a measurement. The rubric asks \"how much would\n a human say this needs,\" not \"how many tokens will this actually consume.\"\n A request correctly judged recent-turns can still occasionally need","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"","lvl3":""}},
2702
+ {"objectID":"89c0f088b6b4f91a1fc99b1db7acb741e912010bac6416ffe5d94730ff7e11a2","title":"Per-request context budget","url":"/docs/features/context-budget","content":"Per-request context budget\n\nContext compaction has always triggered at a fixed 80% of the model's window.\nThat number is now a default, not a constant: a per-request compactionThreshold\noption lowers it for requests that need less room, and the\nclassifier router's jev strategy can fill\nit in automatically by asking how much of the conversation the request actually\nneeds.\n\nThe degradation contract. Every input here is optional. With no\ncompactionThreshold passed and no classifier router configured, the effective\nthreshold is exactly 0.8, exactly as before — resolveHistoryBudget()'s\nscale factor is compactionThreshold / 0.8, so the default value reproduces\nthe previous budget calculation to the token.\n\nSetting it directly\n\nCLI: neurolink generate \"...\" --compaction-threshold 0.45 (existing flag,\ndescription: \"Fraction of the context window (0-1) at which history is\ncompacted. Default 0.8.\").\n\nLetting the classifier fill it in\n\nWhen classifierRouter.contextBudget is enabled (default: true whenever\nthe strategy resolves to a decision model; ignored by heuristic/llm), the\nsame jev request that classifies difficulty also asks a score question:\n\nHow much of the earlier conversation does answering this request actually\nrequire?\n\nagainst a four-level rubric:\n\n| Scope | Criterion | Threshold |\n| ------------------- | -------------------------------------------------------------------------------------------------- | --------- |\n| current-message | Self-contained. Earlier conversation would not change the answer. | 0.45 |\n| recent-turns | Needs the last few exchanges — a follow-up, a correction, a reference to something just discussed. | 0.60 |\n| full-conversation | Needs the whole conversation, including decisions and constraints established much earlier. | 0.75 |\n| everything | Needs the conversation and every document, file and tool result that has been gathered. | 0.80 |\n\nThis is a rubric, not a token count, and deliberately so: a decision model\nplaces a request on an ordered scale reliably and reads digit strings as text,\nnot quantities — asking \"how many tokens does this need\" would get an answer\nshaped like a guess at a number, not a calibrated judgement.\n\nThe reading is used only above MIN_CONTEXT_SCOPE_CONFIDENCE (0.5); below\nthat, contextScope is left undefined and the request falls back to the\n0.8 default exactly as if the question had not been asked. The scope judgement\nis independent of the difficulty tier — a trivial request can still need the\nwhole conversation, and an expert one can be entirely self-contained — so\nit is read and applied on its own, and survives every path on which the\ndifficulty verdict itself is discarded by its confidence bar.\n\napplyClassifierRouting() then applies the derived threshold only when the\ncaller left compactionThreshold unset:\n\nAn explicit per-call value always wins. The classifier is filling in a default\nyou didn't set, never overriding one you did.\n\nThe one-directional invariant\n\nThe mapping from scope to threshold can only ever lower the 0.8 default,\nnever raise it, and this is enforced independently at two layers:\ncontextScopeToThreshold() clamps its result with Math.min(0.8, ...)\n before returning.\nClassifierRouter.selectContextBudget() re-checks the result and discards\n it unless threshold < 0.8.\n\nShrinking a budget compacts a little earlier than strictly necessary. Growing\none could let a request through that the provider rejects with a\ncontext-window error. That failure affects the current request, so the code\nkeeps the threshold at or below the default while leaving the model available\nfor later requests that fit.\n\nHow the threshold changes the actual budget\n\nresolveHistoryBudget() is what the compactor targets — the model's available\ninput space minus system prompt, current prompt, tool definitions and file\nattachments, all of which ride alongside history rather than being part of\nit. The per-request threshold scales that budget directly:\n\nWith the default 0.8, scale is exactly 1 and the budget is unchanged\nfrom before this option existed. A 0.4 threshold halves the history budget.\nThe 0.95 safety factor is unrelated to this feature — it exists because\ntoken estimation is character-based and approximate, so the compactor always\naims slightly under the true ceiling.\n\nWhat this is bad at\nIt is a suggestion, not a measurement. The rubric asks \"how much would\n a human say this needs,\" not \"how many tokens will this actually consume.\"\n A request correctly judged recent-turns can still occasionally need one\n detail from much earlier — the invariant above is what keeps that failure\n mode cheap (a slightly early compaction) rather than catastrophic.\nOne judgement per request, not per turn of the conversation that follows.\n If the classifier runs once per turn (which it does), ","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"","lvl3":""}},
2703
2703
  {"objectID":"6e42051940f716e8463919220990087875ede2015f3d6d14951b113f55d268ad","title":"Per-request context budget","url":"/docs/features/context-budget#per-request-context-budget","content":"Context compaction has always triggered at a fixed 80% of the model's window.\nThat number is now a default, not a constant: a per-request compactionThreshold\noption lowers it for requests that need less room, and the\nclassifier router's jev strategy can fill\nit in automatically by asking how much of the conversation the request actually\nneeds.\n\nThe degradation contract. Every input here is optional. With no\ncompactionThreshold passed and no classifier router configured, the effective\nthreshold is exactly 0.8, exactly as before — resolveHistoryBudget()'s\nscale factor is compactionThreshold / 0.8, so the default value reproduces\nthe previous budget calculation to the token.","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"Per-request context budget","lvl3":""}},
2704
2704
  {"objectID":"f0d23f694f874e0f664f348ae61fb3dcfa09869d8fa23d3708bef58bb1d8a3a5","title":"Setting it directly","url":"/docs/features/context-budget#setting-it-directly","content":"CLI: neurolink generate \"...\" --compaction-threshold 0.45 (existing flag,\ndescription: \"Fraction of the context window (0-1) at which history is\ncompacted. Default 0.8.\").","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"Setting it directly","lvl3":""}},
2705
2705
  {"objectID":"568e5df23dcc19c14f20bcd8cb4bf66718bff8e85951c9091179443a86b9ed15","title":"Letting the classifier fill it in","url":"/docs/features/context-budget#letting-the-classifier-fill-it-in","content":"When classifierRouter.contextBudget is enabled (default: true whenever\nthe strategy resolves to a decision model; ignored by heuristic/llm), the\nsame jev request that classifies difficulty also asks a score question:\n\nHow much of the earlier conversation does answering this request actually\nrequire?\n\nagainst a four-level rubric:\n\n| Scope | Criterion | Threshold |\n| ------------------- | -------------------------------------------------------------------------------------------------- | --------- |\n| current-message | Self-contained. Earlier conversation would not change the answer. | 0.45 |\n| recent-turns | Needs the last few exchanges — a follow-up, a correction, a reference to something just discussed. | 0.60 |\n| full-conversation | Needs the whole conversation, including decisions and constraints established much earlier. | 0.75 |\n| everything | Needs the conversation and every document, file and tool result that has been gathered. | 0.80 |\n\nThis is a rubric, not a token count, and deliberately so: a decision model\nplaces a request on an ordered scale reliably and reads digit strings as text,\nnot quantities — asking \"how many tokens does this need\" would get an answer\nshaped like a guess at a number, not a calibrated judgement.\n\nThe reading is used only above MIN_CONTEXT_SCOPE_CONFIDENCE (0.5); below\nthat, contextScope is left undefined and the request falls back to the\n0.8 default exactly as if the question had not been asked. The scope judgement\nis independent of the difficulty tier — a trivial request can still need the\nwhole conversation, and an expert one can be entirely self-contained — so\nit is read and applied on its own, and survives every path on which the\ndifficulty verdict itself is discarded by its confidence bar.","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"Letting the classifier fill it in","lvl3":""}},
2706
- {"objectID":"f7d479c7b3b2b6db55717893f01303b5b45844b00a20671f44bab1f911b45719","title":"The one-directional invariant","url":"/docs/features/context-budget#the-one-directional-invariant","content":"The mapping from scope to threshold can only ever lower the 0.8 default,\nnever raise it, and this is enforced independently at two layers:\ncontextScopeToThreshold() clamps its result with Math.min(0.8, ...)\n before returning.\nClassifierRouter.selectContextBudget() re-checks the result and discards\n it unless threshold < 0.8.\n\nThe reason this is a hard invariant rather than a tuning choice: shrinking a\nbudget merely compacts a little earlier than strictly necessary — the model\nstill answers correctly with slightly less history than it could have used.\nGrowing one lets a request through that the provider then rejects with a\ncontext-window error, and ModelPool treats that as a permanent (10-year)\ncooldown — one optimistic guess retires the model for the life of the\nprocess. Getting this wrong in one direction is recoverable; getting it wrong\nin the other is not, so the code refuses to let a bug make that mistake even\nonce.","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"The one-directional invariant","lvl3":""}},
2706
+ {"objectID":"f7d479c7b3b2b6db55717893f01303b5b45844b00a20671f44bab1f911b45719","title":"The one-directional invariant","url":"/docs/features/context-budget#the-one-directional-invariant","content":"The mapping from scope to threshold can only ever lower the 0.8 default,\nnever raise it, and this is enforced independently at two layers:\ncontextScopeToThreshold() clamps its result with Math.min(0.8, ...)\n before returning.\nClassifierRouter.selectContextBudget() re-checks the result and discards\n it unless threshold < 0.8.\n\nShrinking a budget compacts a little earlier than strictly necessary. Growing\none could let a request through that the provider rejects with a\ncontext-window error. That failure affects the current request, so the code\nkeeps the threshold at or below the default while leaving the model available\nfor later requests that fit.","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"The one-directional invariant","lvl3":""}},
2707
2707
  {"objectID":"e0867ad2f11fe401499dda82ede924767539b8377443f7e7ef3463829da48f72","title":"How the threshold changes the actual budget","url":"/docs/features/context-budget#how-the-threshold-changes-the-actual-budget","content":"resolveHistoryBudget() is what the compactor targets — the model's available\ninput space minus system prompt, current prompt, tool definitions and file\nattachments, all of which ride alongside history rather than being part of\nit. The per-request threshold scales that budget directly:\n\nWith the default 0.8, scale is exactly 1 and the budget is unchanged\nfrom before this option existed. A 0.4 threshold halves the history budget.\nThe 0.95 safety factor is unrelated to this feature — it exists because\ntoken estimation is character-based and approximate, so the compactor always\naims slightly under the true ceiling.","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"How the threshold changes the actual budget","lvl3":""}},
2708
2708
  {"objectID":"196b4b8863a944ba130eda4eb2f4fd645841348f85a0647738e81dd3a92df3f0","title":"What this is bad at","url":"/docs/features/context-budget#what-this-is-bad-at","content":"It is a suggestion, not a measurement. The rubric asks \"how much would\n a human say this needs,\" not \"how many tokens will this actually consume.\"\n A request correctly judged recent-turns can still occasionally need one\n detail from much earlier — the invariant above is what keeps that failure\n mode cheap (a slightly early compaction) rather than catastrophic.\nOne judgement per request, not per turn of the conversation that follows.\n If the classifier runs once per turn (which it does), the scope can change\n turn to turn, but there's no persistence of \"this whole session is a\n current-message session\" — a caller who wants that stability should pass\n compactionThreshold explicitly rather than rely on auto.\nIt shares the base model's limits. Everything in\n what decide is bad at\n applies — including that irrelevant state costs accuracy, so a very long\n prompt slice can degrade the scope reading itself.\nNo feedback loop. If the classifier's current-message guess turns out\n wrong and the model asks a follow-up that needed history you already\n dropped, nothing here recovers that turn; the invariant only bounds the\n cost of the guess, it doesn't undo it.","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"What this is bad at","lvl3":""}},
2709
2709
  {"objectID":"7764ebf2c6fa54846f789e257b1adea74fb778597e9e2e3767d4410462d2818f","title":"See also","url":"/docs/features/context-budget#see-also","content":"Model routing with a decision model\nRelevance-driven compaction\nThe decide inference type","hierarchy":{"lvl0":"Features","lvl1":"Per-request context budget","lvl2":"See also","lvl3":""}},
@@ -3735,7 +3735,7 @@
3735
3735
  {"objectID":"d256fe39eb21be95c6b75bdd3179d95e245c3a116465afec9bee7fe38b55e989","title":"Tier-up on denial","url":"/docs/features/provider-fallback#tier-up-on-denial","content":"Tier-up on denial","hierarchy":{"lvl0":"Features","lvl1":"Provider Fallback & Model Chains","lvl2":"Tier-up on denial","lvl3":""}},
3736
3736
  {"objectID":"8bf09b3f1207ac25c29b5833f5f6de11dff159a64e441fcabfa717d8dae88a4e","title":"Cross-provider failover","url":"/docs/features/provider-fallback#cross-provider-failover","content":"Cross-provider failover","hierarchy":{"lvl0":"Features","lvl1":"Provider Fallback & Model Chains","lvl2":"Cross-provider failover","lvl3":""}},
3737
3737
  {"objectID":"9c51b871367ba3a45cb97dd7259ba5717cc5cc072f50c091b63c661c7a470b7d","title":"Related","url":"/docs/features/provider-fallback#related","content":"Credential Validation — sdk.checkCredentials() and the typed ModelAccessDeniedError\nReal-time Voice Services — fallback also applies to realtime sessions on access denial\nProvider Setup — configuring supported providers\nObservability — wiring model.fallback events into your monitoring stack","hierarchy":{"lvl0":"Features","lvl1":"Provider Fallback & Model Chains","lvl2":"Related","lvl3":""}},
3738
- {"objectID":"3b5d0122d0762f5202d83a9db0e7430a5ae248ba21c1277692dc84d45ff346bf","title":"Provider Orchestration Brain","url":"/docs/features/provider-orchestration","content":"Provider Orchestration Brain\n\nThe orchestration engine introduced in 7.42.0 pairs a task classifier with a provider/model router. When enabled, NeuroLink inspects each prompt, chooses the most suitable provider/model based on capabilities and availability, and carries that preference through the fallback chain.\n\nHighlights\nBinary task classifier – categorises prompts (analysis vs. creative, etc.) before routing.\nModel router – selects provider/model pairs, honouring local providers like Ollama when available.\nProvider validation – confirms credentials/availability before committing to the route.\nNon-invasive – orchestration augments requests via context so standard fallback logic still applies.\n\nEnabling Orchestration (SDK)\nEnable orchestration for automatic provider/model selection\nTask classifier analyzes prompt to determine best provider\nLog routing decisions to analytics\nValidate routed provider meets quality expectations\nSee which provider/model was selected by the router\n\nThe router adds __orchestratedPreferredProvider to the request context so analytics and downstream logging capture routing decisions.\n\nTuning the Router\nEnvironment awareness – orchestration only routes to providers that pass hasProviderEnvVars, so missing API keys fall back gracefully.\nOllama detection – checks http://localhost:11434/api/tags to verify local models before selection.\nConfidence scores – ModelRouter.route returns confidence and reasoning. Enable debug logs (export NEUROLINK_DEBUG=true) to inspect decisions.\nManual overrides – specifying provider or model bypasses orchestration for that call.\n\nWorking with the CLI\n\nCLI sessions instantiate NeuroLink without orchestration by default. To experiment with the router from the CLI:\nRun Node.js one-liner from CLI\nEnable orchestration in SDK mode\nLet router select best provider for comparison task\nOutput selected provider and model\n\nFuture CLI releases will surface a --enable-orchestration flag; until then keep orchestration for SDK/server workloads.\n\nBest Practices\n\nEnable orchestration in development to understand routing patterns, then pin provider or model in production for predictable behavior. Orchestration is ideal for exploratory workflows; explicit selection ensures consistency in critical paths.\n\nThe default fallback order prioritizes self-hosted providers — LiteLLM and Ollama — before cloud providers. This avoids external API costs and rate limits during development. Ensure your local providers are running to take advantage of this local-first routing.\n\nPair orchestration with evaluation to verify the routed provider meets quality expectations.\nMaintain provider credentials for all potential routes; orchestration skips providers missing keys.\nMonitor debug logs in staging to understand how tasks map to providers before rolling out widely.\nCombine with regional controls (region option) when routing to cloud-specific providers such as Vertex or Bedrock.\n\nTroubleshooting\n\n| Symptom | Action |\n| ----------------------------------- | -------------------------------------------------------------------------------------------------- |\n| Router always returns empty context | Ensure enableOrchestration: true and prompts contain text. |\n| Routed provider never used | Check credentials via neurolink status; orchestration only hints the preferred provider. |\n| Ollama route ignored | Confirm Ollama server running at http://localhost:11434 and model tag matches router suggestion. |\n| Fallback cycles between providers | Pin provider/model explicitly or reduce orchestrated confidence thresholds (see ModelRouter). |\n\nModelPool — failover with per-member cooldown\n\nOrchestration above hints a provider. ModelPool is the separate, explicit\nmechanism that owns selection: you hand it an ordered list of\nprovider/model/region members and it tries them in turn, taking a failed member\nout of rotation for a while rather than retrying it on every call.\n\nFile: src/lib/routing/modelPool.ts · Types: src/lib/types/modelPool.ts\n\nstrategy picks among the members that are currently available: priority\nalways takes the first, round-robin rotates, weighted prefers higher\nweight.\n\nCooldown is classified, not uniform\n\nA failure is classified into a ProviderErrorClass — rate_limit, auth,\ncontext_window, server, network, unknown — and the class decides how\nlong the member sits out:\n\n| Class | Cooldown |\n| -------------------------------------------- | ----------------------------------------- |\n| rate_limit, server, network, unknown | cooldownMs (default 60s) |\n| auth, context_window | permanent for the life of the process |\n\n\"Permanent\" is literal: PERMANENT_COOLDOWN_MS is ten years. The reasoning is\nthat neither ","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"","lvl3":""}},
3738
+ {"objectID":"3b5d0122d0762f5202d83a9db0e7430a5ae248ba21c1277692dc84d45ff346bf","title":"Provider Orchestration Brain","url":"/docs/features/provider-orchestration","content":"Provider Orchestration Brain\n\nThe orchestration engine introduced in 7.42.0 pairs a task classifier with a provider/model router. When enabled, NeuroLink inspects each prompt, chooses the most suitable provider/model based on capabilities and availability, and carries that preference through the fallback chain.\n\nHighlights\nBinary task classifier – categorises prompts (analysis vs. creative, etc.) before routing.\nModel router – selects provider/model pairs, honouring local providers like Ollama when available.\nProvider validation – confirms credentials/availability before committing to the route.\nNon-invasive – orchestration augments requests via context so standard fallback logic still applies.\n\nEnabling Orchestration (SDK)\nEnable orchestration for automatic provider/model selection\nTask classifier analyzes prompt to determine best provider\nLog routing decisions to analytics\nValidate routed provider meets quality expectations\nSee which provider/model was selected by the router\n\nThe router adds __orchestratedPreferredProvider to the request context so analytics and downstream logging capture routing decisions.\n\nTuning the Router\nEnvironment awareness – orchestration only routes to providers that pass hasProviderEnvVars, so missing API keys fall back gracefully.\nOllama detection – checks http://localhost:11434/api/tags to verify local models before selection.\nConfidence scores – ModelRouter.route returns confidence and reasoning. Enable debug logs (export NEUROLINK_DEBUG=true) to inspect decisions.\nManual overrides – specifying provider or model bypasses orchestration for that call.\n\nWorking with the CLI\n\nCLI sessions instantiate NeuroLink without orchestration by default. To experiment with the router from the CLI:\nRun Node.js one-liner from CLI\nEnable orchestration in SDK mode\nLet router select best provider for comparison task\nOutput selected provider and model\n\nFuture CLI releases will surface a --enable-orchestration flag; until then keep orchestration for SDK/server workloads.\n\nBest Practices\n\nEnable orchestration in development to understand routing patterns, then pin provider or model in production for predictable behavior. Orchestration is ideal for exploratory workflows; explicit selection ensures consistency in critical paths.\n\nThe default fallback order prioritizes self-hosted providers — LiteLLM and Ollama — before cloud providers. This avoids external API costs and rate limits during development. Ensure your local providers are running to take advantage of this local-first routing.\n\nPair orchestration with evaluation to verify the routed provider meets quality expectations.\nMaintain provider credentials for all potential routes; orchestration skips providers missing keys.\nMonitor debug logs in staging to understand how tasks map to providers before rolling out widely.\nCombine with regional controls (region option) when routing to cloud-specific providers such as Vertex or Bedrock.\n\nTroubleshooting\n\n| Symptom | Action |\n| ----------------------------------- | -------------------------------------------------------------------------------------------------- |\n| Router always returns empty context | Ensure enableOrchestration: true and prompts contain text. |\n| Routed provider never used | Check credentials via neurolink status; orchestration only hints the preferred provider. |\n| Ollama route ignored | Confirm Ollama server running at http://localhost:11434 and model tag matches router suggestion. |\n| Fallback cycles between providers | Pin provider/model explicitly or reduce orchestrated confidence thresholds (see ModelRouter). |\n\nModelPool — failover with per-member cooldown\n\nOrchestration above hints a provider. ModelPool is the separate, explicit\nmechanism that owns selection: you hand it an ordered list of\nprovider/model/region members and it tries them in turn, taking a failed member\nout of rotation for a while rather than retrying it on every call.\n\nFile: src/lib/routing/modelPool.ts · Types: src/lib/types/modelPool.ts\n\nstrategy picks among the members that are currently available: priority\nalways takes the first, round-robin rotates, weighted prefers higher\nweight.\n\nCooldown is classified, not uniform\n\nA failure is classified into a ProviderErrorClass — rate_limit, auth,\ncontext_window, server, network, unknown — and the class decides how\nlong the member sits out:\n\n| Class | Cooldown |\n| ---------------------------------------------------- | ------------------------------ |\n| rate_limit, auth, server, network, unknown | cooldownMs (default 60s) |\n| context_window | None; request-scoped error |\n\nAn auth failure may come from credentials supplied for one call, so the member\nbecomes eligible ag","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"","lvl3":""}},
3739
3739
  {"objectID":"4f317fa66a6678bfaf848dc5b575809a95b82ded04ae00dab6cb107a05d97723","title":"Provider Orchestration Brain","url":"/docs/features/provider-orchestration#provider-orchestration-brain","content":"The orchestration engine introduced in 7.42.0 pairs a task classifier with a provider/model router. When enabled, NeuroLink inspects each prompt, chooses the most suitable provider/model based on capabilities and availability, and carries that preference through the fallback chain.","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"Provider Orchestration Brain","lvl3":""}},
3740
3740
  {"objectID":"bad00a4fdf2c1282d34f035fbae43b10d1cb83f5a5ebc20a6496dfeadf76f6c3","title":"Highlights","url":"/docs/features/provider-orchestration#highlights","content":"Binary task classifier – categorises prompts (analysis vs. creative, etc.) before routing.\nModel router – selects provider/model pairs, honouring local providers like Ollama when available.\nProvider validation – confirms credentials/availability before committing to the route.\nNon-invasive – orchestration augments requests via context so standard fallback logic still applies.","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"Highlights","lvl3":""}},
3741
3741
  {"objectID":"7cc7c82f69d5facc285eec0da2371475dd19e2b49cadd29bf39ddec3b00e07a1","title":"Enabling Orchestration (SDK)","url":"/docs/features/provider-orchestration#enabling-orchestration-sdk","content":"Enable orchestration for automatic provider/model selection\nTask classifier analyzes prompt to determine best provider\nLog routing decisions to analytics\nValidate routed provider meets quality expectations\nSee which provider/model was selected by the router\n\nThe router adds __orchestratedPreferredProvider to the request context so analytics and downstream logging capture routing decisions.","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"Enabling Orchestration (SDK)","lvl3":""}},
@@ -3744,7 +3744,7 @@
3744
3744
  {"objectID":"1545454fa4a70dc964cc0627bc182227bf8b8db112855909bab614de3bb1885f","title":"Best Practices","url":"/docs/features/provider-orchestration#best-practices","content":"Enable orchestration in development to understand routing patterns, then pin provider or model in production for predictable behavior. Orchestration is ideal for exploratory workflows; explicit selection ensures consistency in critical paths.\n\nThe default fallback order prioritizes self-hosted providers — LiteLLM and Ollama — before cloud providers. This avoids external API costs and rate limits during development. Ensure your local providers are running to take advantage of this local-first routing.\n\nPair orchestration with evaluation to verify the routed provider meets quality expectations.\nMaintain provider credentials for all potential routes; orchestration skips providers missing keys.\nMonitor debug logs in staging to understand how tasks map to providers before rolling out widely.\nCombine with regional controls (region option) when routing to cloud-specific providers such as Vertex or Bedrock.","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"Best Practices","lvl3":""}},
3745
3745
  {"objectID":"2b5d0e24f33d5a81843688f39e754fdc8bb877de4e1a182d2c5626e3f76abe8a","title":"Troubleshooting","url":"/docs/features/provider-orchestration#troubleshooting","content":"| Symptom | Action |\n| ----------------------------------- | -------------------------------------------------------------------------------------------------- |\n| Router always returns empty context | Ensure enableOrchestration: true and prompts contain text. |\n| Routed provider never used | Check credentials via neurolink status; orchestration only hints the preferred provider. |\n| Ollama route ignored | Confirm Ollama server running at http://localhost:11434 and model tag matches router suggestion. |\n| Fallback cycles between providers | Pin provider/model explicitly or reduce orchestrated confidence thresholds (see ModelRouter). |","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"Troubleshooting","lvl3":""}},
3746
3746
  {"objectID":"b513b3c39e1600f86ecfca6b0b756edeaa173c0050da6e3d2c3dc54fca5e724a","title":"ModelPool — failover with per-member cooldown","url":"/docs/features/provider-orchestration#modelpool-failover-with-per-member-cooldown","content":"Orchestration above hints a provider. ModelPool is the separate, explicit\nmechanism that owns selection: you hand it an ordered list of\nprovider/model/region members and it tries them in turn, taking a failed member\nout of rotation for a while rather than retrying it on every call.\n\nFile: src/lib/routing/modelPool.ts · Types: src/lib/types/modelPool.ts\n\nstrategy picks among the members that are currently available: priority\nalways takes the first, round-robin rotates, weighted prefers higher\nweight.","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"ModelPool — failover with per-member cooldown","lvl3":""}},
3747
- {"objectID":"3b11b24a4c9a09b6b95686ff5369869b947d9bfdbf532e7034b3e3f863f24e11","title":"Cooldown is classified, not uniform","url":"/docs/features/provider-orchestration#cooldown-is-classified-not-uniform","content":"A failure is classified into a ProviderErrorClass — rate_limit, auth,\ncontext_window, server, network, unknown — and the class decides how\nlong the member sits out:\n\n| Class | Cooldown |\n| -------------------------------------------- | ----------------------------------------- |\n| rate_limit, server, network, unknown | cooldownMs (default 60s) |\n| auth, context_window | permanent for the life of the process |\n\n\"Permanent\" is literal: PERMANENT_COOLDOWN_MS is ten years. The reasoning is\nthat neither class can fix itself mid-process — a rejected key stays rejected,\nand a request that overflowed a model's window will overflow it again — so\nretrying only burns latency on every subsequent call.\n\n⚠️ This is why a context budget may only ever shrink. One optimistic guess\nthat overflows a model's window does not cost a retry; it retires that model\nfor the life of the process. Everything in\ncontext budget and the\nmodel catalogue that looks\nover-cautious about raising a threshold is cautious for this reason, and the\ncatalogue vetoes a model whose window cannot hold the request _regardless of\nhow confident the pick was_ — an oversized request is a hard provider error,\nnot a slightly worse answer.","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"Cooldown is classified, not uniform","lvl3":""}},
3747
+ {"objectID":"3b11b24a4c9a09b6b95686ff5369869b947d9bfdbf532e7034b3e3f863f24e11","title":"Cooldown is classified, not uniform","url":"/docs/features/provider-orchestration#cooldown-is-classified-not-uniform","content":"A failure is classified into a ProviderErrorClass — rate_limit, auth,\ncontext_window, server, network, unknown — and the class decides how\nlong the member sits out:\n\n| Class | Cooldown |\n| ---------------------------------------------------- | ------------------------------ |\n| rate_limit, auth, server, network, unknown | cooldownMs (default 60s) |\n| context_window | None; request-scoped error |\n\nAn auth failure may come from credentials supplied for one call, so the member\nbecomes eligible again after the configured cooldown. A context-window error\ndepends on the request size: the current call can fail or try another member,\nbut later calls can still use the model. The pool's per-call exclusion set\nprevents an immediate retry of the same member for that request.\n\nThe context budget and\nmodel catalogue still avoid sending\nrequests that exceed a model's window. A larger threshold could fail the\ncurrent request; it does not retire the member for later requests.","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"Cooldown is classified, not uniform","lvl3":""}},
3748
3748
  {"objectID":"d5c7e3ad322e8452031c096403fe688555d2106f1a84816b09e5276850a28d91","title":"A configured pool disables the classifier router","url":"/docs/features/provider-orchestration#a-configured-pool-disables-the-classifier-router","content":"The classifier router is skipped entirely\nwhen a modelPool is configured, because the two would otherwise both claim\nthe right to choose a model. The pool wins: it is the explicit, host-declared\nstatement, and it is the one carrying failover state. A host that wants\nper-request routing should use the classifier router's own pool rather than a\nModelPool.","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"A configured pool disables the classifier router","lvl3":""}},
3749
3749
  {"objectID":"de5c406fe2aa8ec1da41c7f179857880b2e74ef1fe05691fbb63efebdacac3cd","title":"Dive Deeper","url":"/docs/features/provider-orchestration#dive-deeper","content":"Code reference: src/lib/utils/modelRouter.ts\nCode reference: src/lib/utils/taskClassifier.ts\nCode reference: src/lib/routing/modelPool.ts\nClassifier Router — per-request model selection\nProvider Fallback\ndocs/advanced/analytics.md for logging orchestration metadata.","hierarchy":{"lvl0":"Features","lvl1":"Provider Orchestration Brain","lvl2":"Dive Deeper","lvl3":""}},
3750
3750
  {"objectID":"280f65232d644ee2663a8864b5d8e95eba74208c53a429db5fcac1f0c48e6d4a","title":"`GET /accounts` — one row per account","url":"/docs/features/proxy-accounts-endpoint","content":"GET /accounts — one row per account\n\nWhat it is for\n\nAnswering \"which of my accounts can still take work?\" used to need two calls\nwhose schemas do not line up:\n/status returns six rows here — three real logins plus proxy/internal\n and two translation pseudo-accounts — with request and error counters, and\n no quota.\n/limits returns three rows, only the real logins, with quota and no\n counters.\n\nEvery consumer therefore reimplemented the same merge, discarded the plumbing\nrows by hand, and drifted whenever the proxy's internals moved. /accounts\ndoes the join once, server-side, and adds the thing neither endpoint had:\nper-account token totals and cost.\n\nResponse\n\ncostBasis: \"api-equivalent\" is not a bill\n\nPooled OAuth accounts bill by subscription. costUsd is what the recorded\ntokens would have cost at published per-token rates — useful for judging\nwhether a subscription is earning its keep, and for spotting a runaway account.\nIt is not an invoice, and a consumer that renders it as one is wrong. On this\nmachine it reads roughly $900/day, which is alarming without that framing.\n\nunpricedModels names any model with no pricing row, so a $0 contribution is\nvisible rather than silent.\n\nQuery parameters\n\n| Param | Default | Meaning |\n| --------- | ------- | ------------------------------------------------------------ |\n| refresh | false | true forces a live quota fetch from Anthropic's usage API. |\n\nThe default is deliberate. A live refresh spends the user's own OAuth\ncredentials upstream. This endpoint is built to be polled, so it reads the\nstored snapshot unless asked otherwise; a dashboard on a short interval must\nnot hammer Anthropic.\n\nNotes on individual fields\nallowed and expired are always null. Deriving them needs the token\n store, which /status reaches behind its own timeouts. cooling is the field\n an operator acts on and one small file read answers it, so that one is real.\n Use /status when you need the other two.\nstatus is derived, not passed through. /limits returns\n status: \"snapshot\", which describes how the quota was obtained rather than\n the account's health, and must not leak into a field consumers read as health.\nTimestamps. Upstream mixes units in one object: sessionResetAt,\n weeklyResetAt and windows[].resetsAt are unix seconds; lastUpdated,\n windows[].updatedAt and coolingUntil are milliseconds. Only the\n seconds fields get a *Ms companion; the rest pass through untouched.\n Blanket-multiplying the object would throw the millisecond fields tens of\n thousands of years forward.\nisPrimary marks the account the pool prefers, from the proxy's\n hot-reloaded routing config where one is set and the value it was constructed\n with otherwise. Keys compare normalised, so a bare label (me@example.com)\n and a full pool key (anthropic:me@example.com) match. It is false on\n internal and translation rows, which are not credentials and cannot be\n primary.\nseverity and isActive are absent on header-sourced overage windows —\n a structural property of how those rows are parsed, not a transient gap. This\n endpoint fills them (severity: \"critical\" when the window is rejected,\n isActive: false) so no consumer needs the branch.\n\nHow usage totals are computed\n\nsrc/lib/proxy/accountLedger.ts reads ~/.neurolink/logs/proxy-<date>.jsonl\nincrementally: one cursor per file, advanced only to the last complete newline.\nThe directory runs to hundreds of megabytes, so a re-read per request is not an\noption. Measured on a 930 MB directory: 40 ms cold, 1 ms warm.\n\nFour correctness rules the module exists to enforce:\nOnly proxy-<date>.jsonl. proxy-attempts-* carries one row per retry;\n folding it in multiplies a retried request's tokens by its retry count.\nFold by requestId, conditionally. A request is logged twice when a\n streamed body finishes and its token counts arrive late — the Codex engine\n does exactly this. Totals derive from a requestId-keyed map, never a sum of\n lines. The fold is NOT unconditional deduplication: two lines merge only\n when the earlier one carries no usage. requestId can come from a\n client-supplied X-Request-ID and nothing enforces uniqueness, so two\n genuinely distinct usage-bearing requests that share an id are counted\n separately. A consumer that dedupes on id alone will undercount — see the\n fuller explanation below.\nFilter by engine. The log is shared with the Codex pool, and an operator\n can use the same email for both. Without the filter, ChatGPT tokens land on\n the Anthropic row and get priced at the wrong vendor's rates.\nNever build the row set from the log. An account that served no traffic\n today would vanish — precisely when you most want to see it, because it is\n probably cooling or exhausted.\n\nA deleted file (retention) freezes its totals rather than dropping them; a file\nthat shrank was deleted and recreated, so the cursor resets.\n\nRow kinds and what they mean\n\nkind says what a row actually","hierarchy":{"lvl0":"Features","lvl1":"`GET /accounts` — one row per account","lvl2":"","lvl3":""}},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "13.12.3",
3
+ "version": "13.12.4",
4
4
  "packageManager": "pnpm@10.34.9+sha512.f49b5a8ea0fdedb44bb3c0c1d6575092a53c2950d95b7ad15df11f17974877a2de3a01c07e934e9b28ce716e51c09a94962c7306d09be2e1e4b18a8c8762fd32",
5
5
  "description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
6
6
  "author": {
@@ -665,7 +665,7 @@
665
665
  "@semantic-release/release-notes-generator": "14.1.0",
666
666
  "@smithy/types": "4.13.1",
667
667
  "@sveltejs/adapter-auto": "8.0.0",
668
- "@sveltejs/kit": "3.0.0",
668
+ "@sveltejs/kit": "3.1.1",
669
669
  "@sveltejs/package": "3.0.2",
670
670
  "@sveltejs/vite-plugin-svelte": "7.0.0",
671
671
  "@types/cors": "2.8.19",