@juspay/neurolink 13.8.30 → 13.9.0

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.
@@ -23,3 +23,25 @@ export declare function sniffImageMimeType(buffer: Buffer): string | null;
23
23
  * Vertex image path).
24
24
  */
25
25
  export declare function detectImageMimeType(buffer: Buffer): string;
26
+ /**
27
+ * Detect the MIME type of any raster image NeuroLink accepts as input, or `null`
28
+ * when the bytes match none.
29
+ *
30
+ * {@link sniffImageMimeType} answers for the four formats every vision provider
31
+ * takes as they are, and its callers depend on that set staying four. This is
32
+ * the wider question for a caller deciding whether bytes are an image NeuroLink
33
+ * can send at all: those four, plus HEIC, HEIF (Google takes both natively),
34
+ * AVIF, BMP, TIFF, ICO and JPEG 2000, which the SDK tries to convert to PNG
35
+ * before dispatch (`SUPPORTED_INPUT_IMAGE_MIME_TYPES`) and sends as detected
36
+ * when no decoder can read them. Every type it returns is in that set, so a
37
+ * caller that relabels bytes with the answer is never handing the SDK a type it
38
+ * refuses.
39
+ *
40
+ * SVG is deliberately absent. It is markup with no byte signature, and no
41
+ * provider accepts it; a caller that wants it has to look for it separately.
42
+ *
43
+ * Only the leading bytes are read (a few hundred cover every signature), so a
44
+ * prefix of a large image is enough. A signature is a claim about the opening of
45
+ * the file, not proof the rest decodes.
46
+ */
47
+ export declare function sniffInputImageMimeType(buffer: Buffer): string | null;
@@ -7,6 +7,7 @@
7
7
  * otherwise a wrong default (historically `image/jpeg`) makes Anthropic reject
8
8
  * PNG/GIF/WebP with a media-type mismatch 400.
9
9
  */
10
+ import { detectIsoBmffImageMimeType } from "./isoBmff.js";
10
11
  /**
11
12
  * Detect an image's MIME type from its magic bytes, or `null` when the bytes
12
13
  * match no known signature.
@@ -76,3 +77,97 @@ export function sniffImageMimeType(buffer) {
76
77
  export function detectImageMimeType(buffer) {
77
78
  return sniffImageMimeType(buffer) ?? "image/png";
78
79
  }
80
+ /**
81
+ * `DIB` header sizes a BMP file may carry after its 14-byte file header: OS/2
82
+ * core (12, 16), `BITMAPINFOHEADER` (40) and its Adobe variants (52, 56), OS/2 2
83
+ * (64), `BITMAPV4HEADER` (108) and `BITMAPV5HEADER` (124).
84
+ */
85
+ const BMP_DIB_HEADER_SIZES = new Set([
86
+ 12, 16, 40, 52, 56, 64, 108, 124,
87
+ ]);
88
+ /**
89
+ * The formats NeuroLink accepts as input but no vision provider takes verbatim,
90
+ * plus HEIC, HEIF and AVIF (Google takes the first two natively).
91
+ *
92
+ * BMP and ICO open with two or four bytes that plain text could produce, so
93
+ * each is held to the next structural field as well: a BMP to a known `DIB`
94
+ * header size, an ICO to a non-empty directory whose first entry has its
95
+ * reserved byte clear. Without that a payload that merely begins `BM` would be
96
+ * an image.
97
+ */
98
+ function sniffConvertibleImageMimeType(buffer) {
99
+ // HEIC, HEIF and AVIF: the shared ISO-BMFF `ftyp` brand tables.
100
+ const isoBmff = detectIsoBmffImageMimeType(buffer);
101
+ if (isoBmff !== null) {
102
+ return isoBmff;
103
+ }
104
+ // TIFF: "II*\0" (little-endian) or "MM\0*" (big-endian).
105
+ if (buffer.length >= 4 &&
106
+ ((buffer[0] === 0x49 &&
107
+ buffer[1] === 0x49 &&
108
+ buffer[2] === 0x2a &&
109
+ buffer[3] === 0x00) ||
110
+ (buffer[0] === 0x4d &&
111
+ buffer[1] === 0x4d &&
112
+ buffer[2] === 0x00 &&
113
+ buffer[3] === 0x2a))) {
114
+ return "image/tiff";
115
+ }
116
+ // BMP: "BM", then a file header whose DIB header size is one that exists.
117
+ if (buffer.length >= 18 &&
118
+ buffer[0] === 0x42 &&
119
+ buffer[1] === 0x4d &&
120
+ BMP_DIB_HEADER_SIZES.has(buffer.readUInt32LE(14))) {
121
+ return "image/bmp";
122
+ }
123
+ // ICO: 00 00 01 00, an entry count above zero and a clear reserved byte in
124
+ // the first 16-byte directory entry.
125
+ if (buffer.length >= 22 &&
126
+ buffer[0] === 0x00 &&
127
+ buffer[1] === 0x00 &&
128
+ buffer[2] === 0x01 &&
129
+ buffer[3] === 0x00 &&
130
+ buffer.readUInt16LE(4) > 0 &&
131
+ buffer[9] === 0x00) {
132
+ return "image/x-icon";
133
+ }
134
+ // JPEG 2000: the full 12-byte signature box. The trailing 0D 0A 87 0A is a
135
+ // line-ending probe that a mangled transfer corrupts, so it is checked too.
136
+ if (buffer.length >= 12 &&
137
+ buffer[0] === 0x00 &&
138
+ buffer[1] === 0x00 &&
139
+ buffer[2] === 0x00 &&
140
+ buffer[3] === 0x0c &&
141
+ buffer.toString("latin1", 4, 8) === "jP " &&
142
+ buffer[8] === 0x0d &&
143
+ buffer[9] === 0x0a &&
144
+ buffer[10] === 0x87 &&
145
+ buffer[11] === 0x0a) {
146
+ return "image/jp2";
147
+ }
148
+ return null;
149
+ }
150
+ /**
151
+ * Detect the MIME type of any raster image NeuroLink accepts as input, or `null`
152
+ * when the bytes match none.
153
+ *
154
+ * {@link sniffImageMimeType} answers for the four formats every vision provider
155
+ * takes as they are, and its callers depend on that set staying four. This is
156
+ * the wider question for a caller deciding whether bytes are an image NeuroLink
157
+ * can send at all: those four, plus HEIC, HEIF (Google takes both natively),
158
+ * AVIF, BMP, TIFF, ICO and JPEG 2000, which the SDK tries to convert to PNG
159
+ * before dispatch (`SUPPORTED_INPUT_IMAGE_MIME_TYPES`) and sends as detected
160
+ * when no decoder can read them. Every type it returns is in that set, so a
161
+ * caller that relabels bytes with the answer is never handing the SDK a type it
162
+ * refuses.
163
+ *
164
+ * SVG is deliberately absent. It is markup with no byte signature, and no
165
+ * provider accepts it; a caller that wants it has to look for it separately.
166
+ *
167
+ * Only the leading bytes are read (a few hundred cover every signature), so a
168
+ * prefix of a large image is enough. A signature is a claim about the opening of
169
+ * the file, not proof the rest decodes.
170
+ */
171
+ export function sniffInputImageMimeType(buffer) {
172
+ return sniffImageMimeType(buffer) ?? sniffConvertibleImageMimeType(buffer);
173
+ }
@@ -17,6 +17,11 @@ function getHeader(headers, headerName) {
17
17
  }
18
18
  return null;
19
19
  }
20
+ /** A parsed hint must remain an exact, finite millisecond count. */
21
+ function representableDelayMs(value) {
22
+ const rounded = Math.round(value);
23
+ return Number.isSafeInteger(rounded) && rounded >= 0 ? rounded : undefined;
24
+ }
20
25
  /**
21
26
  * Parses a duration string (e.g., "6m0s", "30s", "1h30m", "500ms") into milliseconds.
22
27
  *
@@ -56,7 +61,9 @@ export function parseDurationMs(raw) {
56
61
  break;
57
62
  }
58
63
  }
59
- return matchedLength === trimmed.length ? Math.round(totalMs) : undefined;
64
+ return matchedLength === trimmed.length
65
+ ? representableDelayMs(totalMs)
66
+ : undefined;
60
67
  }
61
68
  /**
62
69
  * Parses a single Retry-After header value into milliseconds.
@@ -82,13 +89,13 @@ export function parseRetryAfterHeaderValue(value) {
82
89
  if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
83
90
  const seconds = Number(trimmed);
84
91
  if (Number.isFinite(seconds) && seconds >= 0) {
85
- return Math.round(seconds * 1000);
92
+ return representableDelayMs(seconds * 1000);
86
93
  }
87
94
  }
88
95
  // 2. HTTP-date or RFC 3339 / ISO 8601 date
89
96
  const parsedDate = Date.parse(trimmed);
90
97
  if (Number.isFinite(parsedDate)) {
91
- return Math.max(0, parsedDate - Date.now());
98
+ return representableDelayMs(Math.max(0, parsedDate - Date.now()));
92
99
  }
93
100
  // 3. Duration string (e.g. "6m0s", "30s", "500ms")
94
101
  const duration = parseDurationMs(trimmed);
@@ -122,16 +129,16 @@ export function parseRateLimitResetValue(value) {
122
129
  if (Number.isFinite(num) && num >= 0) {
123
130
  if (num < 1e9) {
124
131
  // Delta seconds (e.g. 30, 60, 300)
125
- return Math.round(num * 1000);
132
+ return representableDelayMs(num * 1000);
126
133
  }
127
134
  // Unix epoch timestamp
128
135
  const resetTime = num > 1e12 ? num : num * 1000;
129
- return Math.max(0, Math.round(resetTime - Date.now()));
136
+ return representableDelayMs(Math.max(0, resetTime - Date.now()));
130
137
  }
131
138
  }
132
139
  const parsedDate = Date.parse(trimmed);
133
140
  if (Number.isFinite(parsedDate)) {
134
- return Math.max(0, parsedDate - Date.now());
141
+ return representableDelayMs(Math.max(0, parsedDate - Date.now()));
135
142
  }
136
143
  const duration = parseDurationMs(trimmed);
137
144
  if (duration !== undefined && duration >= 0) {
@@ -0,0 +1,79 @@
1
+ # Speech-to-text and `transcribe` (src/lib/voice)
2
+
3
+ Loaded automatically when working under `src/lib/voice/`. Moved out of the root CLAUDE.md.
4
+
5
+ ## The `transcribe` inference type
6
+
7
+ `neurolink.transcribe()` (a whole recording: Buffer, path, `file://` or
8
+ `http(s)://` URL) and `neurolink.transcribeStream()` (PCM16LE frames →
9
+ `interim` / `final` / `corrected` / `silence` events), the CLI's
10
+ `neurolink transcribe <file>` (`src/cli/commands/transcribe.ts`), and the
11
+ server's `POST /api/agent/transcribe` and OpenAI-compatible
12
+ `POST /v1/audio/transcriptions` (`server/routes/transcribeRoutes.ts`). Audio
13
+ attached to `generate()` (`AudioProcessor` / `VideoProcessor`) picks its engine
14
+ by the same rule.
15
+
16
+ **STT providers; descriptor order is precedence.** `STT_PROVIDER_DESCRIPTORS`
17
+ in `src/lib/factories/sttDescriptors.ts` is the single source of truth for
18
+ every STT provider's name, aliases, credentials slice, env vars and
19
+ capabilities, exactly as `DECISION_PROVIDERS` is for `decide`. With no
20
+ provider named, `resolveDefaultSTTProvider()` returns `NEUROLINK_STT_PROVIDER`
21
+ (a shipped name, alias, or a `NEUROLINK_STT_ENDPOINTS` endpoint), else the
22
+ first configured descriptor — `whisper`, `deepgram`, `elevenlabs-stt`,
23
+ `google-stt`, `azure-stt` — else **Whistle**, the built-in local engine.
24
+ Reordering the list changes which engine every implicit transcription uses.
25
+ Note that `OPENAI_API_KEY` configures `whisper` and the Google AI Studio keys
26
+ configure `google-stt`, so an ambient text-provider key silently becomes the
27
+ STT default; a test asserting the Whistle default must blank them.
28
+
29
+ **Whistle is the zero-config default, and it ships with the package.**
30
+ `voice/providers/WhistleSTT.ts` runs a 17 MB model in WebAssembly on this
31
+ machine. Its three files are committed under `models/whistle/` (pinned
32
+ Hugging Face revisions, Apache-2.0, verified by SHA-256 in
33
+ `voice/whistle/assets.ts` before use) and listed in package.json `files`, so a
34
+ fresh install transcribes with no network. The directory order is an explicit
35
+ `credentials.stt.whistle.modelDir` / `NEUROLINK_WHISTLE_DIR`, then
36
+ `NEUROLINK_MODEL_DIR/whistle`, then the bundled copy (found by walking up from
37
+ the module to the package's own `package.json`), then
38
+ `~/.neurolink/models/whistle`, the only directory a download ever writes to and
39
+ now a fallback for installs that lost the bundled files. Whistle counts as
40
+ configured whenever its files are present **or** it may download them, so "no
41
+ STT backend configured" is only reachable with an **explicit, empty** model dir
42
+ (`NEUROLINK_WHISTLE_DIR` / `modelDir`, which skips the bundled copy) **and**
43
+ `NEUROLINK_WHISTLE_AUTO_DOWNLOAD=0` (or `credentials.stt.whistle.autoDownload:
44
+ false`). Tests that assert "no backend" must set both.
45
+
46
+ **The correction layer fails open through `tryDecide`.**
47
+ `voice/correction/` finds dictionary aliases in the transcript, asks the
48
+ decision provider per candidate whether the speaker meant the term or the
49
+ literal word (a `choice`, never a leading yes/no), then optionally rewrites the
50
+ text with a `generate`/`stream` call. With no decision provider, on the 4 s
51
+ guard timeout, or on any error, the dictionary is applied as is and every
52
+ `STTDecisionRecord` carries a `note` saying why — the same degradation contract
53
+ as the five `decide` call sites (see the `neurolink-decide` skill; the guard calls `tryDecide` directly, so
54
+ it is not one of the `await decide(` sites). A lone `OPENAI_API_KEY` now counts as
55
+ a decision provider, so a host that set it for `whisper` and passes a dictionary
56
+ sends the first 4,000 characters of the transcript to OpenAI's Decisions endpoint;
57
+ a test of the "no decision provider" note must blank it.
58
+
59
+ **Nothing may lose words.** Each layer keeps the text it was given when it
60
+ fails: a rewrite that drops more than `maxDropRatio` (0.25) of the words, times
61
+ out or errors is discarded; a correction that returns nothing keeps the engine
62
+ text; a failed fallback or second opinion keeps the primary; a streamed final
63
+ pass that comes back empty or with fewer than half the words already shown
64
+ keeps the live text; LocalAgreement's committed prefix only grows while passes
65
+ keep their words (it is capped at the newest pass's length); and an
66
+ utterance no engine could read is reported as a `silence` event with its length
67
+ rather than disappearing. `steps` on every result records which of these
68
+ happened. Covered by `pnpm run test:transcribe` (public surface, stub engines,
69
+ CLI, routes) and `pnpm run test:transcribe:stream` (the chunked adapter under
70
+ the determinism exception).
71
+
72
+ **The endpointer is a public, dependency-free subpath.**
73
+ `@juspay/neurolink/voice/endpointer` (package.json `exports`) points at
74
+ `dist/voice/streaming/endpointer.js`, so a browser app can find where a spoken
75
+ turn starts and ends without bundling the `voice` entry, which pulls in Node
76
+ built-ins. The file must stay free of runtime imports (type-only imports are
77
+ erased and fine): `test:transcribe` reads the shipped file and fails if an
78
+ `import` or `require` appears. Put a shared helper inside the file, not behind
79
+ an import.
@@ -2407,7 +2407,7 @@
2407
2407
  {"objectID":"6653ad7d7db43c9524583b9dadbf6368e9f153396ef5489c318c688f0fe95d24","title":"9. Streaming response shows as raw bytes","url":"/docs/features/claude-proxy-troubleshooting#9-streaming-response-shows-as-raw-bytes","content":"Cause: An earlier version of the Hono handler re-encoded the ReadableStream as a byte array instead of passing it through as a raw SSE stream.\n\nFix: This is fixed in the current version. The proxy returns a raw Response object for streaming requests, preserving the SSE format. If you encounter this, rebuild:","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy Troubleshooting","lvl2":"9. Streaming response shows as raw bytes","lvl3":""}},
2408
2408
  {"objectID":"c11829787189c82bd28cebb8f491b004b2778739e15705556ffaa098ed95dd7a","title":"10. Tools not working / \"0 chunks\"","url":"/docs/features/claude-proxy-troubleshooting#10-tools-not-working-0-chunks","content":"Cause: An earlier architecture had NeuroLink merging 68+ MCP tools with the client's tools, causing tool name conflicts and prefixing issues. Tool definitions were being modified or dropped in the merge.\n\nFix: This is fixed in the current version. The proxy uses passthrough mode for Claude-to-Claude requests: the raw request body is forwarded directly to Anthropic without any parsing, tool merging, or reconstruction. Tool definitions pass through exactly as Claude Code sent them.\n\nIf you are seeing tool issues:\nVerify the proxy is in passthrough mode (check logs for [proxy] POST /v1/messages -- passthrough requests do not show \"translation\" in the log).\nEnsure you are targeting a Claude model (passthrough is only for claude-* models).\nCheck that NEUROLINK_SKIP_MCP=true is set (prevents MCP tool injection).","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy Troubleshooting","lvl2":"10. Tools not working / \"0 chunks\"","lvl3":""}},
2409
2409
  {"objectID":"f5e4bc93c3248b16f666fc22de0855f134d5dde56d25280c5a7c2ae9abddc8ee","title":"11. Account not rotating on 429","url":"/docs/features/claude-proxy-troubleshooting#11-account-not-rotating-on-429","content":"Cause: The proxy uses fill-first routing by design. It keeps sending requests to one account until that account is rate-limited, then switches to the next.\n\nThis is expected behavior. Fill-first is optimal for Anthropic because:\nAnthropic's prompt caching is tied to the account/session. Spreading requests across accounts reduces cache hit rates.\nFill-first maximizes the benefit of each account's rate-limit window before moving on.\n\nOn a 429, the proxy applies exponential backoff to the current account (1s, 2s, 4s, 8s, ... up to 10 minutes) and immediately tries the next non-cooling account.\n\nTo verify rotation is working:","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy Troubleshooting","lvl2":"11. Account not rotating on 429","lvl3":""}},
2410
- {"objectID":"a344f10565b8cb427dd5b903be65d7445973de5f1fbfdc7eeb523cae2a8b673f","title":"12. \"400 invalid_image_reference\" when sending an image","url":"/docs/features/claude-proxy-troubleshooting#12-400-invalid_image_reference-when-sending-an-image","content":"Cause: A request to a translated route (/v1/chat/completions, Gemini generateContent, or /v1/messages routed to a non-Anthropic provider) named its image as a local file path, an http:// URL or another scheme, or (Gemini) sent raw base64 in inlineData.data without an image/<subtype> mimeType, or with a length or = padding that is not valid base64. The proxy resolves image references before the SDK sees them and accepts only data: URIs and public https:// URLs. The answer is identical whether or not the file exists, and it never echoes the path.\n\nFix: Send the image inline as a data: URI (a Claude base64 source is converted for you), or host it at a public https:// URL that answers without a redirect. A Gemini client may send inlineData.data as raw base64 (standard or URL-safe) next to a mimeType such as image/png: the proxy converts it to a data: URI. If that request gets this answer, check inlineData.mimeType: it must be an image/<subtype> type with no space, comma or semicolon, and audio, PDF and untyped parts are not translated. Then check data itself: a length one character over a multiple of four, or = padding that does not match the length, is refused rather than forwarded. image_url_unfetchable means an https:// URL was refused (a private or non-public address, a redirect, an error status, or larger than the size limit while downloading); image_input_too_large means more than 20 images, a data: image over 50 MB, or data: images together over 100 MB. See Image references on translated requests.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy Troubleshooting","lvl2":"12. \"400 invalid_image_reference\" when sending an image","lvl3":""}},
2410
+ {"objectID":"bf5a33e57595f9a2e92da78a456ee2cdb2da25664669413c618d314b1e3fa159","title":"12. \"400 invalid_image_reference\" or \"invalid_image_data\" when sending an image","url":"/docs/features/claude-proxy-troubleshooting#12-400-invalid_image_reference-or-invalid_image_data-when-sending-an-image","content":"Cause: A request to a translated route (/v1/chat/completions, Gemini generateContent, or /v1/messages routed to a non-Anthropic provider) was refused locally, before any provider was contacted, for one of two reasons.\ninvalid_image_reference: the image was named as a local file path, an http:// URL, an empty URL or another scheme, or (Gemini) raw base64 in inlineData.data was sent without an image/<subtype> mimeType, or with a length or = padding that is not valid base64. The proxy resolves image references before the SDK sees them. It accepts data: URIs and public https:// URLs, plus a Claude base64 source and Gemini raw base64 with an image/<subtype> mimeType, both of which it converts to a data: URI first. The answer is identical whether or not the file exists, and it never echoes the path.\ninvalid_image_data: the reference was acceptable, but the bytes behind it are not a recognised image. The proxy decodes every data: image (and every download) and reads its file signature; it does not trust the declared type. Text, a path, a page of HTML, a PDF, SVG, a truncated payload, an empty one (a data: URI with nothing after the comma, a Claude base64 source or a Gemini inlineData of an image type whose data is empty or absent), and a data: URI that is not ;base64 all land here. An empty slot is refused, never dropped: the request is not sent on without the picture. A Gemini inlineData.data that is a path made only of base64 characters (/var/tmp/photo) is the usual surprise: it is taken for base64, decodes to text, and is refused as data instead of being forwarded for the provider to fail on.\n\nFix: Send the image inline as a data: URI (a Claude base64 source is converted for you), or host it at a public https:// URL that answers without a redirect. A Gemini client may send inlineData.data as raw base64 (standard or URL-safe) next to a mimeType such as image/png: the proxy converts it to a data: URI.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy Troubleshooting","lvl2":"12. \"400 invalid_image_reference\" or \"invalid_image_data\" when sending an image","lvl3":""}},
2411
2411
  {"objectID":"f3a39e51eb140c1d4a2d4a3ca65428fa316193a4e5e8fa94ff94167e1c46fff2","title":"Enable debug logging","url":"/docs/features/claude-proxy-troubleshooting#enable-debug-logging","content":"This outputs detailed information for every request:","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy Troubleshooting","lvl2":"Enable debug logging","lvl3":""}},
2412
2412
  {"objectID":"787ea2a89999f69958b0dd99b8ae0410812df77cd2198c4e2b3d056c2147cdcd","title":"Check request logs","url":"/docs/features/claude-proxy-troubleshooting#check-request-logs","content":"The proxy writes structured JSONL logs to ~/.neurolink/logs/:\n\nEach log entry includes: timestamp, request ID, method, path, model, account label, response status, response time (ms), token usage, and OTel correlation fields (traceId, spanId).","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy Troubleshooting","lvl2":"Check request logs","lvl3":""}},
2413
2413
  {"objectID":"1df2cf3c6943377703033901df111cb673599219d7af3451c0e1b03cc7258d60","title":"Correlate logs with traces","url":"/docs/features/claude-proxy-troubleshooting#correlate-logs-with-traces","content":"When OTEL_EXPORTER_OTLP_ENDPOINT is set, every request log entry includes traceId and spanId fields. Use these to find the corresponding trace in your observability backend (Jaeger, Grafana Tempo, OpenObserve):","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy Troubleshooting","lvl2":"Correlate logs with traces","lvl3":""}},
@@ -2475,7 +2475,7 @@
2475
2475
  {"objectID":"7a743b6bb13366c925cd238d4853826a08f0b161659bcb0575d5b2e83709a2e5","title":"429 Rate Limit","url":"/docs/features/claude-proxy#429-rate-limit","content":"Treat top-level anthropic-ratelimit-unified-status: rejected as authoritative, even if sub-windows still say allowed.\nPrefer the rejected 5-hour or 7-day reset and otherwise use Retry-After.\nPersist the cooldown and rotate immediately for authoritative exhaustion.\nReturn the earliest recovery timestamp without another upstream request when all accounts are cooling.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"429 Rate Limit","lvl3":""}},
2476
2476
  {"objectID":"1522c22c8467bae6a5a51e9e4c4dca5792a7b45c457b0628ef5536d068d642b3","title":"401/402/403 Authentication Errors","url":"/docs/features/claude-proxy#401402403-authentication-errors","content":"OAuth accounts with refresh token: Serialize refresh, persist the new rotating token, and retry. A rejected refresh credential disables the account until re-authentication; transient refresh infrastructure errors cool and rotate.\nOAuth accounts without refresh token: Disable until re-authentication and rotate.\nAPI key accounts: Rotate after authentication failure.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"401/402/403 Authentication Errors","lvl3":""}},
2477
2477
  {"objectID":"b8f1c40c30e2fe7c3e03ca8b9857986dbce8dc17c382f69e1575e3c9b8e22c11","title":"400/422 Request Shape Error","url":"/docs/features/claude-proxy#400422-request-shape-error","content":"Detected via HTTP 422 status or invalid_request_error error type in the response body.\nNo retry or failover. These are client-side errors (malformed request, invalid parameters).\nReturn the error body directly to Claude Code.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"400/422 Request Shape Error","lvl3":""}},
2478
- {"objectID":"afa3c85f9ffa8a82a4379702baa0f7270668e8c8cd1792431947aadd4e3ed0d1","title":"400 Refused Image Reference","url":"/docs/features/claude-proxy#400-refused-image-reference","content":"A translated request (OpenAI, Gemini, or Claude routed to another provider) named an image the proxy will not resolve: a local path, an http:// URL, another scheme, an https:// URL that could not be fetched safely, or (Gemini) raw base64 whose mimeType is not an image/<subtype> type.\nAnswered locally before any provider is contacted, with code invalid_image_reference, image_url_unfetchable or image_input_too_large. No retry and no fallback.\nSee Image references on translated requests.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"400 Refused Image Reference","lvl3":""}},
2478
+ {"objectID":"afa3c85f9ffa8a82a4379702baa0f7270668e8c8cd1792431947aadd4e3ed0d1","title":"400 Refused Image Reference","url":"/docs/features/claude-proxy#400-refused-image-reference","content":"A translated request (OpenAI, Gemini, or Claude routed to another provider) named an image the proxy will not resolve: a local path, an http:// URL, another scheme, an https:// URL that could not be fetched safely, an empty URL, or (Gemini) raw base64 whose mimeType is not an image/<subtype> type; or it carried image bytes that are not a recognised image: text, a path, a page, SVG, an empty (or absent) or truncated payload.\nAnswered locally before any provider is contacted, with code invalid_image_reference, invalid_image_data, image_url_unfetchable or image_input_too_large. No retry and no fallback.\nSee Image references on translated requests.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"400 Refused Image Reference","lvl3":""}},
2479
2479
  {"objectID":"e1f4a02d90c3d80f462b4ab9d516b9be9e53d7f954539837078c9e19088d01fb","title":"404 Not Found","url":"/docs/features/claude-proxy#404-not-found","content":"Typically means the model is not available for this account.\nNo cooldown applied.\nReturn the error body immediately to the client (no failover to next account).","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"404 Not Found","lvl3":""}},
2480
2480
  {"objectID":"8ea0d60b8e33eeebfb825eb12ad9fcd0cdad610ee262ac5486db5d7fa3b8406b","title":"5xx / Transient Server Error","url":"/docs/features/claude-proxy#5xx-transient-server-error","content":"Transient errors (408, 500, 502, 503, 504, and Cloudflare 520-526/529).\nAlso matches 400 responses with api_error or overloaded_error types that wrap transient HTML content (e.g., Cloudflare error pages).\nApply bounded same-account retries, then rotate to the next account.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"5xx / Transient Server Error","lvl3":""}},
2481
2481
  {"objectID":"195dae3c0ea28fdcfeb0fbf39c456fd580652b07fa5f2ce81b341d4279621cf8","title":"All Accounts Exhausted","url":"/docs/features/claude-proxy#all-accounts-exhausted","content":"When every account is in a cooling state:\nWalk the fallback chain (if configured).\nEach fallback uses NeuroLink's stream() pipeline with the specified provider/model.\nIf all fallbacks also fail, return a 429 with Retry-After set to the earliest account recovery time.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"All Accounts Exhausted","lvl3":""}},
@@ -2487,7 +2487,9 @@
2487
2487
  {"objectID":"08067260c522d0f7b196b054e71ab3a4c733c6cedc590cfc5ff95f96e5d5d527","title":"Passthrough mode (Claude to Claude)","url":"/docs/features/claude-proxy#passthrough-mode-claude-to-claude","content":"When the target provider is anthropic (the default for any claude-* model), the proxy operates in passthrough mode:\nLoad allowed, enabled TokenStore accounts. Consider legacy or environment credentials only when no Anthropic TokenStore entries exist and the source is allowed.\nSelect the first non-cooling account according to the active routing strategy. With the default fill-first strategy, this is always the current primary account until it cools down.\nAuto-refresh the token if expiring within 5 minutes, sharing one in-flight refresh for concurrent requests.\nForward the raw request body via plain fetch() to https://api.anthropic.com/v1/messages?beta=true.\nSet authentication headers (Authorization: Bearer for OAuth, x-api-key for API keys).\nForward client headers as-is, preserving Claude Code's own request shape, then merge in required OAuth betas and trace headers when absent. The proxy extracts incoming traceparent and x-neurolink-* headers and injects outbound trace context plus x-claude-code-session-id when needed.\nFor streaming: verify the first chunk (bootstrap retry), then forward the stream. For non-streaming: return JSON.\n\nThis mode preserves the exact request format that Claude Code expects, including thinking blocks, cache control headers, and multi-turn tool use conversations. Rate-limit headers from Anthropic are passed through to the client — see Limit response headers below.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"Passthrough mode (Claude to Claude)","lvl3":""}},
2488
2488
  {"objectID":"fbc67516d545a8892da4fcf8e8d8f06fe29e480e22303b430eec8a70262aafa6","title":"Limit response headers","url":"/docs/features/claude-proxy#limit-response-headers","content":"Every proxy response — streaming, non-streaming, and errors including 429 — carries the account's limit state. There are two layers.\n\nVerbatim passthrough. Anthropic's own anthropic-ratelimit-* headers and retry-after are forwarded unchanged. This is deliberate: a proxied response looks identical to a direct one, so a client needs only a single parser for both. Which family is present depends on the serving account:\n\n| Account type | Headers | Semantics |\n| -------------------- | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |\n| OAuth / subscription | anthropic-ratelimit-unified-5h-*, -7d-*, -status, -overage-status | Utilization (0.0-1.0 of capacity used) plus a reset epoch. Anthropic publishes no absolute remaining count for subscription windows. |\n| API key | anthropic-ratelimit-requests-remaining/-limit, anthropic-ratelimit-tokens-remaining/-limit | Absolute remaining counts.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"Limit response headers","lvl3":""}},
2489
2489
  {"objectID":"dc6518f4c6b67f9a5231d413df258d79141e42dcc772f807732d7627f3502931","title":"Translation mode (Claude to other provider)","url":"/docs/features/claude-proxy#translation-mode-claude-to-other-provider","content":"When model routing directs to a non-Anthropic provider:\nParse the Claude request using parseClaudeRequest() -- extracts prompt, system prompt, images, tools, thinking config, and conversation history. The thinking type field is handled adaptively: both \"enabled\" (fixed budget) and \"adaptive\" (auto budget, mapped to thinkingLevel: \"medium\") are supported.\nCall neurolink.stream() with the target provider and model. Tools and conversation messages from the original request are passed through (not disabled).\nFor streaming: use ClaudeStreamSerializer to emit Claude-compatible SSE events (message_start, content_block_start, content_block_delta, content_block_stop, message_delta, message_stop).\nFor non-streaming: collect all text from the stream and call serializeClaudeResponse() to build a Claude Messages API response.\n\nIf the translated response model differs from the requested model, the proxy records that as a model-substitution metric (proxy_model_substitution_total) and adds the requested vs actual model attributes to the trace.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"Translation mode (Claude to other provider)","lvl3":""}},
2490
- {"objectID":"230e1aa96cd18fcbcdb4072e0aa5815cc298b7e55dcdf7e805181551efa5c413","title":"Image references on translated requests","url":"/docs/features/claude-proxy#image-references-on-translated-requests","content":"Translation mode serves three request formats, and each carries images in its own slot:\n\n| Format | Endpoint | Image slot |\n| ------ | ----------------------------------------------------------------------- | --------------------------------------------------------- |\n| OpenAI | POST /v1/chat/completions | image_url.url of the latest user turn |\n| Gemini | POST /v1beta/models/<model>:generateContent, :streamGenerateContent | inlineData of the latest user turn (data, mimeType) |\n| Claude | POST /v1/messages (routed or falling back to another provider) | source.url of an image block (source.type: \"url\") |\n\nThe SDK resolves an image string by itself (an http(s) URL is fetched, anything else naming an existing file is read from disk), which is right for a program naming its own files and wrong for a request that arrived over a socket. So the proxy resolves every reference first and hands the SDK nothing but bytes it vetted:\n\n| Reference | What the proxy does |\n| ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| data: URI | Accepted and passed through unchanged. Its length counts against the limits below.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"Image references on translated requests","lvl3":""}},
2490
+ {"objectID":"230e1aa96cd18fcbcdb4072e0aa5815cc298b7e55dcdf7e805181551efa5c413","title":"Image references on translated requests","url":"/docs/features/claude-proxy#image-references-on-translated-requests","content":"Translation mode serves three request formats, and each carries images in its own slot:\n\n| Format | Endpoint | Image slot |\n| ------ | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| OpenAI | POST /v1/chat/completions | image_url.url of the latest user turn |\n| Gemini | POST /v1beta/models/<model>:generateContent, :streamGenerateContent | inlineData of the final turn, only when that turn has the user role (data, mimeType); a request that ends with a model turn sends no images, and earlier turns contribute text only |\n| Claude | POST /v1/messages (routed or falling back to another provider) | source of an image block of the latest user turn (url, or base64 data and media_type) |\n\nThe SDK resolves an image string by itself (an http(s) URL is fetched, anything else naming an existing file is read from disk), which is right for a program naming its own files and wrong for a request that arrived over a socket.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"Image references on translated requests","lvl3":""}},
2491
+ {"objectID":"7851388e7ebf6105e257a055fc0e2f6cad27bb736d42dff4579f5b80ed235f2d","title":"What counts as an image, and the type it is sent with","url":"/docs/features/claude-proxy#what-counts-as-an-image-and-the-type-it-is-sent-with","content":"An inline image is judged by its bytes, never by what the client called it. The proxy decodes the payload strictly (an alphabet, length or = padding that no decoder takes is refused; the URL-safe alphabet and missing padding are rewritten to padded standard base64) and reads the file signature from its first bytes. A recognised image is forwarded as data:<detected type>;base64,<payload>, and the type comes from the bytes: a JPEG labelled image/png, image/jpg or even application/octet-stream reaches the provider as image/jpeg. A correction is logged at debug level, not warn. Header parameters (data:image/png;charset=utf-8;base64,...) are dropped.\n\n| Format | Types it is recognised as | What the provider receives |\n| ------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| PNG, JPEG, WebP, GIF | image/png, image/jpeg, image/webp, image/gif | The same bytes under the type they have. Every vision provider takes them as they are. |\n| HEIC, HEIF | image/heic, image/heif | A PNG when the SDK can convert the file, otherwise the original bytes under the detected type. Google takes HEIC and HEIF as they are, so for Google the second outcome works; every other provider refuses it.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"What counts as an image, and the type it is sent with","lvl3":""}},
2492
+ {"objectID":"e80f7928dacafcdcf655fe6d016bb531d3783beef2b7ddc418f837801d5c1368","title":"Empty image slots","url":"/docs/features/claude-proxy#empty-image-slots","content":"An image slot that carries nothing is still an image slot. The proxy refuses it instead of leaving it out, so a request that names a picture and supplies none is never sent upstream as though no picture had been attached. Each format spells \"no bytes\" its own way, and the answer depends on whether the slot is a payload or a URL:\n\n| Format | Empty image slot | Answer |\n| ------ | ------------------------------------------------------------------------------------ | ------------------------- |\n| OpenAI | image_url.url empty or absent | invalid_image_reference |\n| OpenAI | A data: URI with no payload (data:image/png;base64,) | invalid_image_data |\n| Claude | A base64 source whose data is empty or absent (with or without media_type) | invalid_image_data |\n| Claude | A url source whose url is empty or absent | invalid_image_reference |\n| Gemini | An inlineData with an image/<subtype> mimeType whose data is empty or absent | invalid_image_data |\n\nLeft out as before, because there is nothing to call an image by: a Gemini part with no inlineData, or one that declares no image/<subtype> type and carries no data; and a Claude image block whose source is neither base64 nor url. Only the images of the latest user turn are read, so an empty image in an earlier turn is not looked at.\n\nA refused reference answers 400 before anything is sent upstream or any stream starts, in the client's own error format, with one of these codes. The answer never echoes the reference, the data or any server path, and no fallback provider is tried because every one would refuse the same request.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"Empty image slots","lvl3":""}},
2491
2493
  {"objectID":"8a2ed66111704403b1e9a7c68b3214184ddc57877a63dc50ad6a25461d24c778","title":"OAuth cloaking","url":"/docs/features/claude-proxy#oauth-cloaking","content":"For OAuth-authenticated requests, the proxy applies transformations to make requests appear as standard Claude CLI traffic:\nUser-Agent: claude-cli/2.1.87 (external, sdk-cli)\nBeta headers: oauth-2025-04-20, claude-code-20250219, interleaved-thinking-2025-05-14, context-management-2025-06-27, prompt-caching-scope-2026-01-05, advanced-tool-use-2025-11-20, effort-2025-11-24\nIdentity headers: x-app: cli, anthropic-dangerous-direct-browser-access: true\nStainless SDK headers: x-stainless-runtime, x-stainless-lang, x-stainless-os, etc.\nBilling header: Injected into the system prompt as a deterministic Claude-Code-shaped billing block so prompt caching stays stable across requests\nUser ID: metadata.user_id is a JSON string with device_id, account_uuid, and session_id, cached per account/token seed and reused across requests\nTrace linkage: outbound requests include W3C trace headers and a stable x-claude-code-session-id when the proxy owns the request shape\n\nThe CloakingPipeline supports three modes:\n\n| Mode | Behavior |\n| -------- | ------------------------------------------------ |\n| auto | Apply cloaking only for OAuth accounts (default) |\n| always | Apply cloaking for all accounts |\n| never | Skip all cloaking |","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"OAuth cloaking","lvl3":""}},
2492
2494
  {"objectID":"95865db245f6ad8bafa53c81d03c73e6b1486683b1d545cae1670fc33b6c049f","title":"Cloaking plugins","url":"/docs/features/claude-proxy#cloaking-plugins","content":"The pipeline runs plugins in order field order:\nHeaderScrubber -- Removes or modifies headers that reveal proxy usage\nSessionIdentity -- Generates Claude-Code-shaped identity metadata with stable device_id and account_uuid\nSystemPromptInjector -- Adds billing and agent block to system prompts\nTlsFingerprint -- TLS fingerprint matching\nWordObfuscator -- Obfuscates identifiable patterns","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"Cloaking plugins","lvl3":""}},
2493
2495
  {"objectID":"8c04eba9378c5ec10f74e502b58467103bdefcde924c940884e1c6fe9d39d8c2","title":"Request logging","url":"/docs/features/claude-proxy#request-logging","content":"The proxy writes four complementary log families under ~/.neurolink/logs/:\nproxy-YYYY-MM-DD.jsonl -- final request summaries used for request counts, status trends, token totals, and dashboard panels\nproxy-attempts-YYYY-MM-DD.jsonl -- per-upstream-attempt diagnostics for retries, failover, and rate-limit debugging\nproxy-debug-YYYY-MM-DD.jsonl -- redacted body-capture index rows with phase, headers, file path, and response metadata\nbodies/YYYY-MM-DD/<request-id>/*.json.gz -- the corresponding redacted request and response body artifacts, stored compressed with 0o600 permissions\n\nFinal request summaries include request ID, method, path, model, account label, response status, response time, token usage, and traceId / spanId for trace correlation. Debug body captures are also emitted to OTLP logs as event.name=proxy.body_capture.\n\nRedaction: Sensitive headers and common JSON secret keys (authorization, access_token, refresh_token, api_key, etc.) are redacted before debug artifacts are written locally or emitted to OTLP.","hierarchy":{"lvl0":"Features","lvl1":"Claude Proxy","lvl2":"Request logging","lvl3":""}},
@@ -7958,9 +7960,9 @@
7958
7960
  {"objectID":"f3ed50a8afe14efb53c7029170f8bfe943eac05f70b247ba01d53b27d9e7ccd2","title":"Production Checklist","url":"/docs/guides/server-adapters/koa#production-checklist","content":"[ ] Configure environment variables securely\n[ ] Set appropriate CORS origins (not *)\n[ ] Enable rate limiting with reasonable limits\n[ ] Add authentication middleware\n[ ] Configure request timeouts\n[ ] Set body size limits\n[ ] Enable compression middleware\n[ ] Add security headers (koa-helmet)\n[ ] Configure logging with appropriate level\n[ ] Set up health check monitoring\n[ ] Configure error tracking (Sentry, etc.)\n[ ] Use process manager (PM2) for production","hierarchy":{"lvl0":"Guides","lvl1":"Koa Adapter","lvl2":"Production Checklist","lvl3":""}},
7959
7961
  {"objectID":"a8c9927bcf1e3a824cfa9b91cd734c74faeab471578e658bdc06aef74d298957","title":"Related Documentation","url":"/docs/guides/server-adapters/koa#related-documentation","content":"Server Adapters Overview - Getting started with server adapters\nHono Adapter - Recommended framework for most use cases\nExpress Adapter - Compare with Express adapter\nSecurity Best Practices - Authentication patterns\nDeployment Guide - Production deployment strategies","hierarchy":{"lvl0":"Guides","lvl1":"Koa Adapter","lvl2":"Related Documentation","lvl3":""}},
7960
7962
  {"objectID":"abda958c7148cc510ffd8fd63fc0e95f2261198d73957c24cd05bf43f24f54d4","title":"Additional Resources","url":"/docs/guides/server-adapters/koa#additional-resources","content":"Koa Documentation - Official Koa documentation\nKoa Wiki - Community resources and middleware list\n@koa/router - Router middleware documentation\n\nNeed Help? Join our GitHub Discussions or open an issue.","hierarchy":{"lvl0":"Guides","lvl1":"Koa Adapter","lvl2":"Additional Resources","lvl3":""}},
7961
- {"objectID":"55417289121a6d70296ad2b754304f12a3d3a469e5eba572acaadd6e76c8a010","title":"Middleware Reference","url":"/docs/guides/server-adapters/middleware","content":"Middleware Reference\n\nNeuroLink server adapters provide a comprehensive set of middleware components for common server operations. All middleware follows a consistent pattern and can be composed together for your specific use case.\n\nMiddleware Overview\n\n| Middleware | Purpose | Order |\n| ------------------------------------- | ----------------------------------------- | ----- |\n| createTimingMiddleware() | Measures request duration | 0 |\n| createRequestIdMiddleware() | Generates/propagates request IDs | 0 |\n| createErrorHandlingMiddleware() | Centralized error catching and formatting | 1 |\n| createSecurityHeadersMiddleware() | Adds security headers | 2 |\n| createLoggingMiddleware() | Request/response logging | 3 |\n| createRateLimitMiddleware() | Rate limiting | 5 |\n| createAbortSignalMiddleware() | Client disconnection detection | 5 |\n| createCompressionMiddleware() | Response compression signaling | 5 |\n| createAuthMiddleware() | Authentication | 10 |\n| createRequestValidationMiddleware() | Request body/query/params validation | 15 |\n| createCacheMiddleware() | Response caching | 20 |\n| createMCPBodyAttachmentMiddleware() | MCP SDK body compatibility | 10 |\n| createDeprecationMiddleware() | RFC 8594 deprecation headers | 100 |\n\nThe order value determines execution sequence - lower numbers run first.\n\nTiming Middleware\n\nMeasures request duration and adds timing headers to responses.\n\nUsage\n\nHeaders Set\n\n| Header | Description | Example |\n| ----------------- | -------------------------------------------------------- | ----------------- |\n| X-Response-Time | Total request processing time in milliseconds | 45.23ms |\n| Server-Timing | Standard Server-Timing header for performance monitoring | total;dur=45.23 |\n\nWhen to Use\nAlways recommended for production servers\nEssential for performance monitoring and debugging\nWorks with browser Developer Tools and APM systems\n\nRequest ID Middleware\n\nEnsures every request has a unique identifier for tracing and debugging.\n\nConfiguration\n\nUsage\n\nHeaders\n\n| Header | Direction | Description |\n| -------------- | --------- | ----------------------------------------------- |\n| X-Request-ID | Request | Propagates existing ID from client (if present) |\n| X-Request-ID | Response | Returns request ID for client-side correlation |\n\nWhen to Use\nAlways recommended for production servers\nEssential for distributed tracing\nEnables log correlation across services\nHelps with debugging and support tickets\n\nError Handling Middleware\n\nCatches errors and formats them consistently across all routes.\n\nConfiguration\n\nUsage\n\nError Response Format\n\nWhen to Use\nAlways recommended for production servers\nProvides consistent error responses\nPrevents leaking sensitive information in production\nEnable stack traces only in development\n\nSecurity Headers Middleware\n\nAdds common security headers to protect against various web vulnerabilities.\n\nConfiguration\n\nUsage\n\nHeaders Set\n\n| Header | Default Value | Description |\n| --------------------------- | ------------------------------------- | ----------------------------- |\n| X-Frame-Options | DENY | Prevents clickjacking |\n| X-Content-Type-Options | nosniff | Prevents MIME sniffing |\n| Strict-Transport-Security | max-age=31536000; includeSubDomains | Enforces HTTPS |\n| Referrer-Policy | strict-origin-when-cross-origin | Controls referrer information |\n| X-XSS-Protection | 1; mode=block | Legacy XSS protection |\n| Content-Security-Policy | Not set by default | Content security policy |\n\nWhen to Use\nAlways recommended for production servers\nRequired for security compliance (OWASP, PCI-DSS)\nConfigure CSP based on your application needs\nDisable HSTS initially if not ready for HTTPS-only\n\nLogging Middleware\n\nLogs request and response information with configurable detail levels.\n\nConfiguration\n\nUsage\n\nLog Output\n\nRequest Log:\n\nResponse Log:\n\nError Log:\n\nWhen to Use\nAlways recommended for production servers\nDisable body logging in production for performance and privacy\nUse structured logging (JSON) for log aggregation systems\nSkip health check endpoints to reduce noise\n\nCompression Middleware\n\nSignals compression preferences to adapters for response compression.\n\nConfiguration\n\nUsage\n\nHow It Works\n\nThis middleware ","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"","lvl3":""}},
7963
+ {"objectID":"55417289121a6d70296ad2b754304f12a3d3a469e5eba572acaadd6e76c8a010","title":"Middleware Reference","url":"/docs/guides/server-adapters/middleware","content":"Middleware Reference\n\nNeuroLink server adapters provide a comprehensive set of middleware components for common server operations. All middleware follows a consistent pattern and can be composed together for your specific use case.\n\nMiddleware Overview\n\n| Middleware | Purpose | Order |\n| ------------------------------------- | ----------------------------------------- | ----- |\n| createTimingMiddleware() | Measures request duration | 0 |\n| createRequestIdMiddleware() | Generates/propagates request IDs | 0 |\n| createErrorHandlingMiddleware() | Centralized error catching and formatting | 1 |\n| createSecurityHeadersMiddleware() | Adds security headers | 2 |\n| createLoggingMiddleware() | Request/response logging | 3 |\n| createRateLimitMiddleware() | Rate limiting | 5 |\n| createAbortSignalMiddleware() | Client disconnection detection | 5 |\n| createCompressionMiddleware() | Response compression signaling | 5 |\n| createAuthMiddleware() | Authentication | 10 |\n| createSessionMiddleware() | Sets ctx.session, scoped to the user | 12 |\n| createRequestValidationMiddleware() | Request body/query/params validation | 15 |\n| createCacheMiddleware() | Response caching | 20 |\n| createMCPBodyAttachmentMiddleware() | MCP SDK body compatibility | 10 |\n| createDeprecationMiddleware() | RFC 8594 deprecation headers | 100 |\n\nThe order value is informational: the server runs middleware in the order you register it, not by this number. Register the middleware with the lower number first, so that authentication runs before anything that reads the user.\n\nTiming Middleware\n\nMeasures request duration and adds timing headers to responses.\n\nUsage\n\nHeaders Set\n\n| Header | Description | Example |\n| ----------------- | -------------------------------------------------------- | ----------------- |\n| X-Response-Time | Total request processing time in milliseconds | 45.23ms |\n| Server-Timing | Standard Server-Timing header for performance monitoring | total;dur=45.23 |\n\nWhen to Use\nAlways recommended for production servers\nEssential for performance monitoring and debugging\nWorks with browser Developer Tools and APM systems\n\nRequest ID Middleware\n\nEnsures every request has a unique identifier for tracing and debugging.\n\nConfiguration\n\nUsage\n\nHeaders\n\n| Header | Direction | Description |\n| -------------- | --------- | ----------------------------------------------- |\n| X-Request-ID | Request | Propagates existing ID from client (if present) |\n| X-Request-ID | Response | Returns request ID for client-side correlation |\n\nWhen to Use\nAlways recommended for production servers\nEssential for distributed tracing\nEnables log correlation across services\nHelps with debugging and support tickets\n\nError Handling Middleware\n\nCatches errors and formats them consistently across all routes.\n\nConfiguration\n\nUsage\n\nError Response Format\n\nWhen to Use\nAlways recommended for production servers\nProvides consistent error responses\nPrevents leaking sensitive information in production\nEnable stack traces only in development\n\nSecurity Headers Middleware\n\nAdds common security headers to protect against various web vulnerabilities.\n\nConfiguration\n\nUsage\n\nHeaders Set\n\n| Header | Default Value | Description |\n| --------------------------- | ------------------------------------- | ----------------------------- |\n| X-Frame-Options | DENY | Prevents clickjacking |\n| X-Content-Type-Options | nosniff | Prevents MIME sniffing |\n| Strict-Transport-Security | max-age=31536000; includeSubDomains | Enforces HTTPS |\n| Referrer-Policy | strict-origin-when-cross-origin | Controls referrer information |\n| X-XSS-Protection | 1; mode=block | Legacy XSS protection |\n| Content-Security-Policy | Not set by default | Content security policy |\n\nWhen to Use\nAlways recommended for production servers\nRequired for security compliance (OWASP, PCI-DSS)\nConfigure CSP based on your application needs\nDisable HSTS initially if not ready for HTTPS-only\n\nLogging Middleware\n\nLogs request and response information with configurable detail levels.\n\nConfiguration\n\nUsage\n\nLog Output\n\nRequest Log:\n\nResponse Log:\n\nError Log:\n\nWhen to Use\nAlways recommended for production servers\nDisable body logging in production for performance and privacy\nUse ","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"","lvl3":""}},
7962
7964
  {"objectID":"85c17d817c6a2684c64cc765cb4063caad35b5c9fb934d56e6a07a9042a7c605","title":"Middleware Reference","url":"/docs/guides/server-adapters/middleware#middleware-reference","content":"NeuroLink server adapters provide a comprehensive set of middleware components for common server operations. All middleware follows a consistent pattern and can be composed together for your specific use case.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Middleware Reference","lvl3":""}},
7963
- {"objectID":"2e55beb234a0ba6d06a3a796603ba196b8c566bd4d21f3ae90c309f8e895c68d","title":"Middleware Overview","url":"/docs/guides/server-adapters/middleware#middleware-overview","content":"| Middleware | Purpose | Order |\n| ------------------------------------- | ----------------------------------------- | ----- |\n| createTimingMiddleware() | Measures request duration | 0 |\n| createRequestIdMiddleware() | Generates/propagates request IDs | 0 |\n| createErrorHandlingMiddleware() | Centralized error catching and formatting | 1 |\n| createSecurityHeadersMiddleware() | Adds security headers | 2 |\n| createLoggingMiddleware() | Request/response logging | 3 |\n| createRateLimitMiddleware() | Rate limiting | 5 |\n| createAbortSignalMiddleware() | Client disconnection detection | 5 |\n| createCompressionMiddleware() | Response compression signaling | 5 |\n| createAuthMiddleware() | Authentication | 10 |\n| createRequestValidationMiddleware() | Request body/query/params validation | 15 |\n| createCacheMiddleware() | Response caching | 20 |\n| createMCPBodyAttachmentMiddleware() | MCP SDK body compatibility | 10 |\n| createDeprecationMiddleware() | RFC 8594 deprecation headers | 100 |\n\nThe order value determines execution sequence - lower numbers run first.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Middleware Overview","lvl3":""}},
7965
+ {"objectID":"2e55beb234a0ba6d06a3a796603ba196b8c566bd4d21f3ae90c309f8e895c68d","title":"Middleware Overview","url":"/docs/guides/server-adapters/middleware#middleware-overview","content":"| Middleware | Purpose | Order |\n| ------------------------------------- | ----------------------------------------- | ----- |\n| createTimingMiddleware() | Measures request duration | 0 |\n| createRequestIdMiddleware() | Generates/propagates request IDs | 0 |\n| createErrorHandlingMiddleware() | Centralized error catching and formatting | 1 |\n| createSecurityHeadersMiddleware() | Adds security headers | 2 |\n| createLoggingMiddleware() | Request/response logging | 3 |\n| createRateLimitMiddleware() | Rate limiting | 5 |\n| createAbortSignalMiddleware() | Client disconnection detection | 5 |\n| createCompressionMiddleware() | Response compression signaling | 5 |\n| createAuthMiddleware() | Authentication | 10 |\n| createSessionMiddleware() | Sets ctx.session, scoped to the user | 12 |\n| createRequestValidationMiddleware() | Request body/query/params validation | 15 |\n| createCacheMiddleware() | Response caching | 20 |\n| createMCPBodyAttachmentMiddleware() | MCP SDK body compatibility | 10 |\n| createDeprecationMiddleware() | RFC 8594 deprecation headers | 100 |\n\nThe order value is informational: the server runs middleware in the order you register it, not by this number. Register the middleware with the lower number first, so that authentication runs before anything that reads the user.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Middleware Overview","lvl3":""}},
7964
7966
  {"objectID":"dea1350a158d30abea4a8fa4f9fb8332d17897c73848dfc17dfcb8ef67d212a8","title":"Timing Middleware","url":"/docs/guides/server-adapters/middleware#timing-middleware","content":"Measures request duration and adds timing headers to responses.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Timing Middleware","lvl3":""}},
7965
7967
  {"objectID":"ef0e2e6f086491b64279f24a0018e9d61c713c77983e6f2bf4d9e37f702367b9","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage","content":"Usage","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
7966
7968
  {"objectID":"6de1035c7a2fd89803a0093b22d725a20248e74f4c2d4238d07a2f5dad98f9e4","title":"Headers Set","url":"/docs/guides/server-adapters/middleware#headers-set","content":"| Header | Description | Example |\n| ----------------- | -------------------------------------------------------- | ----------------- |\n| X-Response-Time | Total request processing time in milliseconds | 45.23ms |\n| Server-Timing | Standard Server-Timing header for performance monitoring | total;dur=45.23 |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Headers Set","lvl3":""}},
@@ -8018,18 +8020,27 @@
8018
8020
  {"objectID":"dc019f0ad08d89054d4f68945d6855bbc6d74da0b3f8082e35f56fa5f731ec51","title":"Headers Read","url":"/docs/guides/server-adapters/middleware#headers-read","content":"| Header | Auth Type | Description |\n| --------------- | ------------- | ------------------------------------ |\n| Authorization | bearer, basic | Bearer <token> or Basic <base64> |\n| X-API-Key | api-key | Raw API key value |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Headers Read","lvl3":""}},
8019
8021
  {"objectID":"43776c9da774387f221eb7918931d5a4a59b42c949ef248c30c7afb5512ee7ea","title":"Dev Playground Support","url":"/docs/guides/server-adapters/middleware#dev-playground-support","content":"Requests with an X-NeuroLink-Dev-Playground: true (or X-NeuroLink-Playground: true) header bypass authentication and receive a default developer user context (id: \"playground\", roles: [\"developer\"]), but only when NODE_ENV is exactly development. The variable is read on every request.\n\nWith NODE_ENV unset, production, test, staging or any other value, the header is ignored and the request must carry a valid credential. The bypass is therefore off by default in a deployment that never sets NODE_ENV. Pass skipDevPlayground: false to refuse the header even in development.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Dev Playground Support","lvl3":""}},
8020
8022
  {"objectID":"a2d39b213dc8603fb3d7889b019eebc14f3705eb13b1185d7f98bf26d988f4aa","title":"When to Use","url":"/docs/guides/server-adapters/middleware#when-to-use-10","content":"Protecting API endpoints\nUser identification and authorization\nRate limiting by user\nAudit logging","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"When to Use","lvl3":""}},
8021
- {"objectID":"fb39a14f946d17f7771143d4e3c349bc51999e8aa360456371d0b8dec29a6449","title":"Request Validation Middleware","url":"/docs/guides/server-adapters/middleware#request-validation-middleware","content":"Provides schema-based request validation for body, query, params, and headers.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Request Validation Middleware","lvl3":""}},
8023
+ {"objectID":"961a2c37220a3779b5bb23e6a2a8d360f928344af801a021f6d714754e2a9e5e","title":"Session Middleware","url":"/docs/guides/server-adapters/middleware#session-middleware","content":"Sets ctx.session from a header (or an opt-in cookie) and scopes it to the authenticated user. Register it after authentication, on a server that carries middleware state.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Session Middleware","lvl3":""}},
8024
+ {"objectID":"d2deb08c40f7fc9a32db9d4b2fd251656728c465d71632f4ee15e761652ce04c","title":"The server must carry middleware state","url":"/docs/guides/server-adapters/middleware#the-server-must-carry-middleware-state","content":"The middleware sets ctx.session on the context of its own step, and it prefixes the id with the user that authentication put on the context of an earlier step. Both only work if the server carries middleware state, which is off by default (carryMiddlewareState, see Carrying middleware state). With it off, Express, Fastify and Koa build a fresh context for every middleware step and for the handler, so the session middleware sees no ctx.user and the ctx.session it sets is gone before the handler runs; Hono shares one context only for a request whose client sent its own X-Request-ID. Apart from that Hono case, a server without the carry therefore gets no sessions from this middleware, and nothing warns about it.\n\nThere are two ways to turn the carry on:\nregisterAllRoutes(server, \"/api\", { perUserAuth: true }) turns it on for the server, which is what the usage example below relies on.\ncreateServer(neurolink, { framework, config: { carryMiddlewareState: true } }) turns it on directly. Use it when your own routes read ctx.session, or when you register the routes yourself instead of with registerAllRoutes.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"The server must carry middleware state","lvl3":""}},
8025
+ {"objectID":"0509f1acb589a9fd8e4fbce928f8b5e04d7ab2b0ba93f2f40eef1e03a230ecde","title":"How it relates to perUserAuth","url":"/docs/guides/server-adapters/middleware#how-it-relates-to-peruserauth","content":"Whether the agent routes (/agent/execute, /agent/stream) trust the request body's sessionId depends on perUserAuth (see the security guide):\n\n| perUserAuth | Session the agent routes use |\n| -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| true | Only ctx.session, and only for an authenticated request; a body sessionId is ignored. registerAllRoutes turns the carry on for this mode. This middleware is how a signed-in client keeps a conversation, and without it there is no memory |\n| true, anonymous | None. A request with no ctx.user (optional authentication) gets no conversation even when it sends X-Session-Id, so anonymous callers never share one |\n| false (default) | The body's sessionId.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"How it relates to perUserAuth","lvl3":""}},
8022
8026
  {"objectID":"5030f1bc68100ad92c3ab2b6bafbbb96c9069b282976e5233f3dc1cafdf62811","title":"Configuration","url":"/docs/guides/server-adapters/middleware#configuration-9","content":"Configuration","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Configuration","lvl3":""}},
8023
- {"objectID":"0e7a4984ab1818dc1207c2dffcaebfdc635a483d79f89525da8359a301c4652e","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage-11","content":"Usage","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
8027
+ {"objectID":"0e7a4984ab1818dc1207c2dffcaebfdc635a483d79f89525da8359a301c4652e","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage-11","content":"A client sends X-Session-Id: chat-1; the agent routes then keep that conversation, separately for each signed-in user. Without conversationMemory enabled on the NeuroLink instance nothing is remembered, whatever the session id. registerAllRoutes also mounts the memory routes, and perUserAuth scopes them to the caller as well; they list, read and delete the conversations this middleware creates (see What the user prefix does and does not isolate).\n\nRegister the session middleware after authentication. The server runs middleware in registration order, and the order: 12 of this middleware is informational. Registered before authentication, it sees no user and sets the bare, unprefixed id; nothing warns about it. The same holds on a server that does not carry middleware state: there the middleware sees no user whatever the order, and the handler gets no session at all.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
8028
+ {"objectID":"2eff85cff358391e531f7222a46944f23fc08f676d6ade582e8ba98d3295d415","title":"Behaviour","url":"/docs/guides/server-adapters/middleware#behaviour","content":"| Request | ctx.session.id |\n| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |\n| Authenticated, header chat-1 | <urlencoded-userId>~chat-1, so two users who send chat-1 get different conversations |\n| Not authenticated, header chat-1 | chat-1 (the agent routes ignore it under perUserAuth: true) |\n| No header, or an empty one (and no cookie configured) | not set; no session |\n| No header or an empty one, cookieName set, cookie holds a valid id | the cookie's id, prefixed like a header's |\n| cookieName set, cookie holds an invalid id | the cookie is ignored, as if absent; no session |\n| Header that is not a valid id | 400 |\n\nA valid id is 1 to 128 characters: the first is a letter or digit, the rest are letters, digits, ., _ or -. An id that starts with ., _ or -, or contains :, is not valid.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Behaviour","lvl3":""}},
8029
+ {"objectID":"094629bc45431759611f6c3d97481975303ad413b0d82cf94a36fe7eee97a4af","title":"What the user prefix does and does not isolate","url":"/docs/guides/server-adapters/middleware#what-the-user-prefix-does-and-does-not-isolate","content":"The prefix keeps the conversations the agent routes hold apart: the in-memory conversation manager keys sessions by id alone, so without it one user could read and extend another's conversation by guessing its id. Requested ids contain no ~, so a crafted id cannot imitate another user's prefix. The delimiter is ~ rather than : because Redis session ids and the perUserAuth memory routes reject :.\n\nIt is not an access check on the memory routes. Without perUserAuth they look a session up by the id in the URL: on the in-memory manager by that id alone, on Redis by it together with the userId query parameter. Whether a server limits them to a session's owner then depends on how that server protects those routes, not on this middleware, so a caller who can reach them and knows a prefixed id such as bob~chat-1 reads that session unless the server prevents it. With perUserAuth the memory routes are scoped to the caller (see the security guide), and they refuse a session id that contains :. The ~ form this middleware writes is accepted, so a session it created can be listed, read and deleted through those routes. Memory routes report the prefixed id; treat it as opaque.\n\nThe prefix also depends on ctx.user naming one person. When every client shares one credential (one API key), they share one ctx.user and so one prefix, and the prefix does not tell them apart.\n\nUnder perUserAuth: true an anonymous request (optional authentication) is given no session by the agent routes at all, because with a bare id every anonymous caller that sent the same X-Session-Id would share one conversation. If anonymous callers need a conversation, keep perUserAuth off, where they choose it with a body sessionId (this middleware's id is ignored there except on Hono with the caller's own X-Request-ID, see the table above), or have them sign in.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"What the user prefix does and does not isolate","lvl3":""}},
8030
+ {"objectID":"085efce0ee14472c104cec33ac4ca0b7fe6260cb73f1c9bfc3ed907a1cec58b4","title":"Browser clients and CORS","url":"/docs/guides/server-adapters/middleware#browser-clients-and-cors","content":"A page on another origin can send the header only if the server's CORS allowed headers list it. The default list is Content-Type, Authorization, X-Request-ID and X-Session-Id, so the default header works once the page's origin is in cors.origins.\n\nA custom headerName is not in that list. Add it to cors.headers, and note that a list you pass replaces the default rather than extending it, so keep the others your clients send:\n\nA cookie read through cookieName is sent by the browser only when the page asks for credentials, which also needs cors.credentials: true and an explicit origin in cors.origins rather than *.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Browser clients and CORS","lvl3":""}},
8031
+ {"objectID":"2ae4cb64298f85a7c201fa225bebeb309ffa947d8012d2ffdeddc00c823ab5ee","title":"Header and cookie","url":"/docs/guides/server-adapters/middleware#header-and-cookie","content":"The header wins when both are present. A header that is present but empty counts as absent, so the cookie can still supply the id. A header holding an invalid id is a 400, because the client chose to send it. A cookie holding an invalid id is ignored instead: a browser sends cookies on its own, so a stale or foreign cookie that happens to share the name must not turn every route into a 400. cookieName is off by default for the same reason: a cookie is sent without the client choosing to, so enabling it is the operator's decision.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Header and cookie","lvl3":""}},
8032
+ {"objectID":"fb39a14f946d17f7771143d4e3c349bc51999e8aa360456371d0b8dec29a6449","title":"Request Validation Middleware","url":"/docs/guides/server-adapters/middleware#request-validation-middleware","content":"Provides schema-based request validation for body, query, params, and headers.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Request Validation Middleware","lvl3":""}},
8033
+ {"objectID":"66088f57d128691ad8eb333d1513c66a038336eb42d8c726d7171f2d42247df3","title":"Configuration","url":"/docs/guides/server-adapters/middleware#configuration-10","content":"Configuration","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Configuration","lvl3":""}},
8034
+ {"objectID":"40b5f0e3313c653f8721d60f18454928e5856afdd764174a10af91ee17244b2a","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage-12","content":"Usage","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
8024
8035
  {"objectID":"684bd819b68b5b0ca6711c9939bac94634efa74953166704af156b4df91261f3","title":"Error Response Format","url":"/docs/guides/server-adapters/middleware#error-response-format-1","content":"Error Response Format","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Error Response Format","lvl3":""}},
8025
8036
  {"objectID":"82758f32126cb9af5f9e25763494cfdbba464d89d977e292be0ad93ce5407717","title":"Common Schemas","url":"/docs/guides/server-adapters/middleware#common-schemas","content":"Pre-built schemas for common validation patterns:\n\n| Schema | Fields |\n| ------------ | ----------------------------- |\n| uuid | UUID string format |\n| email | Email string format |\n| pagination | page, limit, offset |\n| sorting | sortBy, sortOrder |\n| idParam | Required id parameter |\n| dateRange | startDate, endDate |\n| search | q (query), fields (array) |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Common Schemas","lvl3":""}},
8026
8037
  {"objectID":"c987ce4f64a434aa882c45de83d62bbd957349a779c0fb52f4984c6c75eb6a9a","title":"When to Use","url":"/docs/guides/server-adapters/middleware#when-to-use-11","content":"Input sanitization and security\nAPI contract enforcement\nEarly error detection\nDocumentation generation (with OpenAPI)","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"When to Use","lvl3":""}},
8027
8038
  {"objectID":"2d237896d0d0c4ed79ebc68e174c410558908188e6d515458a1a8417f3b02f10","title":"Cache Middleware","url":"/docs/guides/server-adapters/middleware#cache-middleware","content":"Provides response caching with LRU eviction and configurable TTL.","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Cache Middleware","lvl3":""}},
8028
- {"objectID":"66088f57d128691ad8eb333d1513c66a038336eb42d8c726d7171f2d42247df3","title":"Configuration","url":"/docs/guides/server-adapters/middleware#configuration-10","content":"Configuration","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Configuration","lvl3":""}},
8029
- {"objectID":"40b5f0e3313c653f8721d60f18454928e5856afdd764174a10af91ee17244b2a","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage-12","content":"Usage","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
8039
+ {"objectID":"2cc6a8453d17b365558fb6a604b32c3813eb4279dabae222041233bd717f9303","title":"Configuration","url":"/docs/guides/server-adapters/middleware#configuration-11","content":"Configuration","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Configuration","lvl3":""}},
8040
+ {"objectID":"72ab6d4eae18b3dbf4dddd251e1b9a3e39357bf07e3d17a934b4f69d03534977","title":"Usage","url":"/docs/guides/server-adapters/middleware#usage-13","content":"Usage","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Usage","lvl3":""}},
8030
8041
  {"objectID":"1ac8f000d65b645f6f77bcd02d6db61215a071d411e56db06f0f690d49eb1700","title":"Headers Set","url":"/docs/guides/server-adapters/middleware#headers-set-4","content":"| Header | Value | Description |\n| --------------- | ------------ | ----------------------------------- |\n| X-Cache | HIT | Response served from cache |\n| X-Cache | MISS | Response freshly generated |\n| X-Cache-Age | 45 | Seconds since cached (only on HIT) |\n| Cache-Control | max-age=60 | Browser caching directive (on MISS) |","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Headers Set","lvl3":""}},
8031
8042
  {"objectID":"75f9986be54ffb5b39930d9b1514e6a696e982fe41bbc2a600033e3254bad57b","title":"When to Use","url":"/docs/guides/server-adapters/middleware#when-to-use-12","content":"Expensive operations (database queries, AI generation)\nFrequently requested static data\nRate limit budget optimization\nReducing latency for repeated requests","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"When to Use","lvl3":""}},
8032
- {"objectID":"3e522465420d38d5c0e20166dfc374452a7c8366d592ff2cf3a9cb9afadc3b7d","title":"Composing Middleware","url":"/docs/guides/server-adapters/middleware#composing-middleware","content":"Middleware are executed in order based on their order property. Here's a recommended production setup:","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Composing Middleware","lvl3":""}},
8043
+ {"objectID":"3e522465420d38d5c0e20166dfc374452a7c8366d592ff2cf3a9cb9afadc3b7d","title":"Composing Middleware","url":"/docs/guides/server-adapters/middleware#composing-middleware","content":"Middleware run in the order they are registered (the order property is informational and nothing sorts by it). Here's a recommended production setup:","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Composing Middleware","lvl3":""}},
8033
8044
  {"objectID":"293ec2d6d2933e2f370ee73b87ee9684f64143acd21d8bbb5e7e48640ec0d2bb","title":"Next Steps","url":"/docs/guides/server-adapters/middleware#next-steps","content":"Configuration Reference - Full server configuration options\nSecurity Best Practices - Authentication and authorization patterns\nDeployment Guide - Production deployment strategies\nExpress Adapter - Express-specific middleware integration\nFastify Adapter - Fastify-specific hooks and plugins","hierarchy":{"lvl0":"Guides","lvl1":"Middleware Reference","lvl2":"Next Steps","lvl3":""}},
8034
8045
  {"objectID":"3f8ed2c1cc0b9c59fe231fb08fe10302270284784b912664350299fe0a5de458","title":"Security Best Practices","url":"/docs/guides/server-adapters/security","content":"Security Best Practices\n\nProtect your AI APIs with comprehensive security measures\n\nThis guide covers authentication, authorization, rate limiting, and other security best practices for deploying NeuroLink server adapters in production.\n\nAuthentication\n\nNeuroLink server adapters support multiple authentication strategies out of the box.\n\nBearer Token Authentication\n\nBearer tokens (JWT, OAuth tokens) are the most common authentication method for APIs:\n\nAPI Key Authentication\n\nFor service-to-service communication or simple API access:\n\nBasic Authentication\n\nFor simple username/password authentication:\n\nCustom Authentication\n\nFor OAuth 2.0, OIDC, or custom schemes:\n\nCarrying middleware state to guards and handlers (carryMiddlewareState)\n\nAuthentication middleware sets ctx.user. On the built-in adapters, whether the\nmiddleware that runs after it, and the route handler, see it depends on the\nadapter and on carryMiddlewareState, which is off by default: each adapter\nthen propagates context as it always did. Express, Fastify and Koa build a fresh\ncontext for every middleware step and for the handler and carry only the\nresponse headers; Hono shares one context between the steps and the handler only\nwhen the client sent its own X-Request-ID.\n\nThe option does not apply to a context you build yourself: a custom adapter, or a\nroute handler you call directly, can supply a context that already has ctx.user\nset.\n\nSo by default a role guard (createRoleMiddleware) registered after\ncreateAuthMiddleware sees the user on one request shape only. Measured: it\nanswers 401 to every request on Express, Fastify and Koa, and on Hono without a\nclient X-Request-ID, even for a user holding the required role, and a\nrate-limit keyGenerator reads ctx.user as undefined there. Set the option on\nthe server to carry ctx.user, ctx.session, ctx.metadata and the abort\nsignal to later middleware and the handler on every built-in adapter:\n\nWith it on, the role guard admits a user holding the role (200) and refuses one\nwithout it (403), and a keyGenerator sees ctx.user, on every built-in adapter. A key\ngenerator that keys on the user id then does what it says, so make it ignore a\nshared identity (ctx.user.shared), or every holder of one API key falls into a\nsingle bucket; the rate-limit examples below do. Turning the option on does not\nchange whose identity the agent routes trust, and registerAllRoutes turns it\non by itself when given perUserAuth, as the next section says.\n\nWho the agent routes treat as the user (perUserAuth)\n\nWhether the agent routes (/agent/execute, /agent/stream, and the skill\nmutation routes' requestedBy) and the memory routes (/memory/*) trust\nctx.user as a person is a separate choice from whether the server carries it:\na single shared API key sets the same ctx.user for every caller, and taking it\nas the user would give every client one userId and no conversation memory\n(agent routes), or make every client a non-admin of its own deployment (memory\nroutes).\n\nSo without an opt-in the agent routes resolve identity as they always have:\nOn Express, Fastify and Koa, and on Hono when the client sent no\n X-Request-ID, userId and sessionId come from the request body.\n ctx.user and ctx.session are ignored (they are not in the handler's\n context at all unless the server carries middleware state), and the skill\n routes use the body's requestedBy.\nOn Hono, when the client sent its own X-Request-ID header, an authenticated\n ctx.user wins over the body (and ctx.session over the body's\n sessionId), as it did before. Hono kept the middleware's context under that\n header, so the handler found it. That is the only built-in combination where\n the default ever guarded userId.\nA context the built-in adapters did not hand the carry to keeps the same\n rule, an authenticated ctx.user wins: an adapter you wrote that sets\n ctx.user itself, or a route handler you call directly with a context you\n built (a test harness, for one).\n\nThe memory routes have none of these exceptions: without the opt-in they ignore\nctx.user on every adapter and for every request.\n\nSet perUserAuth: true when your middleware identifies individual people (one\ncredential per person). Only this option, with carryMiddlewareState on, makes the agent routes take\nthe user from ctx.user, and ignore the body's userId, on every built-in\nadapter and for every request:\n\nregisterAllRoutes also turns on carryMiddlewareState for the server, because\nthe routes can only take identity from ctx.user if the adapter hands it to the\nhandler. With carryMiddlewareState on, a perUserAuth request that your middleware\nauthenticated reaches the handler with that user on every built-in adapter. A\nrequest that no middleware authenticated (optional authentication) runs as\nanonymous, with no userId and no session.\n\nIf you register the agent routes yourself with\ncreateAgentRoutes(\"/api\", { perUserAuth: true }), create the server with\ncarryMiddlewareState: true. Without it, whether a perUserAuth request","hierarchy":{"lvl0":"Guides","lvl1":"Security Best Practices","lvl2":"","lvl3":""}},
8035
8046
  {"objectID":"7cdb3cd74c088f4b197de4db297c2eb3b47c353b41ce1a84ed2e12548147b408","title":"Security Best Practices","url":"/docs/guides/server-adapters/security#security-best-practices","content":"Protect your AI APIs with comprehensive security measures\n\nThis guide covers authentication, authorization, rate limiting, and other security best practices for deploying NeuroLink server adapters in production.","hierarchy":{"lvl0":"Guides","lvl1":"Security Best Practices","lvl2":"Security Best Practices","lvl3":""}},
@@ -9903,7 +9914,7 @@
9903
9914
  {"objectID":"677188568d1a1f62404df0b7a4c3655f9e19f645c9918030d046d433a6429339","title":"Core Options","url":"/docs/reference/server-configuration#core-options","content":"| Option | Type | Default | Description |\n| ---------------------- | --------- | ------------- | --------------------------------------------------------------------------------------------------------------- |\n| port | number | 3000 | Server port to listen on |\n| host | string | \"127.0.0.1\" | Interface to bind; loopback by default. \"0.0.0.0\" listens on every interface — register authentication first |\n| basePath | string | \"/api\" | Base path prefix for all routes |\n| timeout | number | 30000 | Per-request timeout, on every adapter: a request past it is answered 504 REQUEST_TIMEOUT and its work aborted |\n| enableMetrics | boolean | true | Enable metrics endpoint |\n| enableSwagger | boolean | false | Enable OpenAPI/Swagger documentation (see below) |\n| disableBuiltInHealth | boolean | false | Disable built-in health routes |","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Core Options","lvl3":""}},
9904
9915
  {"objectID":"679f1af42104e68e108d5e6009e16718cab67c8d2f3712b45dc516ba333b9c27","title":"OpenAPI/Swagger Documentation (enableSwagger)","url":"/docs/reference/server-configuration#openapiswagger-documentation-enableswagger","content":"When enableSwagger is set to true, the server exposes interactive API documentation endpoints:\n\n| Endpoint | Description |\n| ----------------------------- | ---------------------------------------- |\n| GET {basePath}/openapi.json | OpenAPI 3.1 specification in JSON format |\n| GET {basePath}/openapi.yaml | OpenAPI 3.1 specification in YAML format |\n| GET {basePath}/docs | Interactive Swagger UI documentation |\n\nExample URLs (with default basePath /api):\nhttp://localhost:3000/api/openapi.json\nhttp://localhost:3000/api/openapi.yaml\nhttp://localhost:3000/api/docs\n\nThe Swagger UI provides an interactive interface where you can:\nBrowse all available API endpoints\nView request/response schemas\nTest API calls directly from the browser\nDownload the OpenAPI specification\n\nSecurity Consideration: In production environments, consider disabling enableSwagger to prevent exposing internal API structure. Alternatively, protect the documentation endpoints with authentication middleware.","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"OpenAPI/Swagger Documentation (enableSwagger)","lvl3":""}},
9905
9916
  {"objectID":"4521fc87cb580735f24e75ac3b75c56ddf87507e23597fbd438cb953ec71544a","title":"Example: Basic Configuration","url":"/docs/reference/server-configuration#example-basic-configuration","content":"Example: Basic Configuration","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Example: Basic Configuration","lvl3":""}},
9906
- {"objectID":"a70d025b0c2289499401bc2bc4e8071a199c148ac4483d5a3e646d713509c2ef","title":"CORS Configuration","url":"/docs/reference/server-configuration#cors-configuration","content":"| Option | Type | Default | Description |\n| ------------- | ---------- | ------------------------------------------------------ | ---------------------------------- |\n| enabled | boolean | true | Enable CORS support |\n| origins | string[] | [] | Allowed origins ([\"*\"] = any) |\n| methods | string[] | [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"] | Allowed HTTP methods |\n| headers | string[] | [\"Content-Type\", \"Authorization\"] | Allowed headers |\n| credentials | boolean | false | Allow credentials |\n| maxAge | number | 86400 | Preflight cache max age in seconds |\n\nSecurity note: With no origins listed, no web page can call the server cross-origin. List the origins you serve pages from, or set [\"*\"] explicitly to allow any domain (then also set an API key). neurolink serve --cors-origin https://myapp.com does the same from the command line. The wildcard is sent as the literal * on every adapter (never the request's own Origin), and [\"*\"] together with credentials: true is refused when the server is created: a browser will not send credentials to a wildcard, and reflecting the origin to make it do so would let any page act as the user.","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"CORS Configuration","lvl3":""}},
9917
+ {"objectID":"a70d025b0c2289499401bc2bc4e8071a199c148ac4483d5a3e646d713509c2ef","title":"CORS Configuration","url":"/docs/reference/server-configuration#cors-configuration","content":"| Option | Type | Default | Description |\n| ------------- | ---------- | ------------------------------------------------------------------- | ------------------------------------------------------ |\n| enabled | boolean | true | Enable CORS support |\n| origins | string[] | [] | Allowed origins ([\"*\"] = any) |\n| methods | string[] | [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"OPTIONS\"] | Allowed HTTP methods |\n| headers | string[] | [\"Content-Type\", \"Authorization\", \"X-Request-ID\", \"X-Session-Id\"] | Allowed headers (a list you pass replaces the default) |\n| credentials | boolean | false | Allow credentials |\n| maxAge | number | 86400 | Preflight cache max age in seconds |\n\nX-Session-Id is the header createSessionMiddleware() reads. That middleware does nothing on a server that does not carry middleware state (carryMiddlewareState, off by default), except on Hono for a request whose client sent its own X-Request-ID, which shares one context with the handler either way; registerAllRoutes with perUserAuth turns the carry on, or set carryMiddlewareState: true on the server. See the middleware guide.\n\nSecurity note: With no origins listed, no web page can call the server cross-origin. List the origins you serve pages from, or set [\"*\"] explicitly to allow any domain (then also set an API key). neurolink serve --cors-origin https://myapp.com does the same from the command line.","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"CORS Configuration","lvl3":""}},
9907
9918
  {"objectID":"708cea96fded6a3d6b4ae7e87e0edd070731d631cb4d87c2684792a82addbb0c","title":"Example: Restrictive CORS","url":"/docs/reference/server-configuration#example-restrictive-cors","content":"Example: Restrictive CORS","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Example: Restrictive CORS","lvl3":""}},
9908
9919
  {"objectID":"3706f16eed022d7b144945eae7c4e22925c2d8aa62896bbc81097cab7b4875e2","title":"Rate Limit Configuration","url":"/docs/reference/server-configuration#rate-limit-configuration","content":"| Option | Type | Default | Description |\n| ---------------- | ---------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| enabled | boolean | true | Enable rate limiting |\n| windowMs | number | 900000 (15 min) | Time window in milliseconds |\n| maxRequests | number | 100 | Maximum requests per window |\n| message | string | \"Too many requests...\"","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Rate Limit Configuration","lvl3":""}},
9909
9920
  {"objectID":"06f1efd322182e016ace893db5f7332ce70ca77362234b7d38a3fc3d924264b4","title":"Example: Custom Rate Limiting","url":"/docs/reference/server-configuration#example-custom-rate-limiting","content":"Example: Custom Rate Limiting","hierarchy":{"lvl0":"Reference","lvl1":"Srvr Cofiguratio Rfrc []","lvl2":"Example: Custom Rate Limiting","lvl3":""}},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "13.8.30",
3
+ "version": "13.9.0",
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": {
@@ -217,6 +217,7 @@
217
217
  "test:body-limits": "pnpm exec tsx test/continuous-test-suite-body-limits.ts",
218
218
  "test:adapter-request-context": "pnpm exec tsx test/continuous-test-suite-adapter-request-context.ts",
219
219
  "test:memory-route-scope": "pnpm exec tsx test/continuous-test-suite-memory-route-scope.ts",
220
+ "test:session-middleware": "pnpm exec tsx test/continuous-test-suite-session-middleware.ts",
220
221
  "test:websocket-agent-handler": "pnpm exec tsx test/continuous-test-suite-websocket-agent-handler.ts",
221
222
  "test:tool-reliability": "pnpm exec tsx test/continuous-test-suite-tool-reliability.ts",
222
223
  "test:video-abort": "pnpm exec tsx test/continuous-test-suite-video-abort.ts",