@juspay/neurolink 13.8.30 → 13.8.31

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.
@@ -10,14 +10,39 @@
10
10
  * names its own files. Neither suits a request that arrived over a socket.
11
11
  *
12
12
  * So the proxy resolves every reference itself and hands the SDK nothing but
13
- * `data:` URIs and downloaded bytes:
14
- * - `data:` URIs pass through untouched, they carry their own content;
13
+ * images it has checked:
14
+ * - `data:` URIs carry their own content. The payload is decoded strictly (an
15
+ * alphabet, length or padding no decoder takes is refused) and its leading
16
+ * bytes must be a recognised image, whatever the URI says it is. The SDK is
17
+ * handed `data:<detected type>;base64,<standard payload>`: the type comes
18
+ * from the bytes, never from the client, so a JPEG labelled `image/png`
19
+ * reaches the provider as `image/jpeg`;
15
20
  * - `https://` URLs are downloaded with the same helper the agent routes use
16
21
  * (`resolveAgentInput` -> `safeDownload`): redirects refused, addresses
17
- * checked, size capped;
18
- * - everything else (local paths, `http://`, `file://`, any other scheme) is
19
- * refused before the file system or the network is touched, so the answer
20
- * for a path that exists and one that does not is the same.
22
+ * checked, size capped. The bytes must then be a recognised image too, or
23
+ * the URL is refused, so a page that answers `200 text/html` is never sent
24
+ * on as a picture. The SDK reads the type of those bytes itself, from the
25
+ * same signatures;
26
+ * - everything else (local paths, `http://`, `file://`, any other scheme, an
27
+ * empty string) is refused before the file system or the network is
28
+ * touched, so the answer for a path that exists and one that does not is the
29
+ * same.
30
+ *
31
+ * An image slot that carries nothing is refused too, never skipped. The doors
32
+ * hand over what the client sent: an empty `data:` payload (an OpenAI
33
+ * `data:image/png;base64,`, a Claude `base64` source or a Gemini `inlineData`
34
+ * of an image type whose `data` is empty or absent) is `invalid_image_data`, and
35
+ * an empty URL (an OpenAI `image_url.url` or a Claude `url` source) is
36
+ * `invalid_image_reference`.
37
+ *
38
+ * "A recognised image" is a file signature (`sniffInputImageMimeType`): PNG,
39
+ * JPEG, WebP and GIF, which every provider takes, and HEIC, HEIF, AVIF, BMP,
40
+ * TIFF, ICO and JPEG 2000, which no provider except Google (HEIC and HEIF only)
41
+ * takes. The SDK tries to convert those seven to PNG before dispatch, for every
42
+ * provider, Google included; when neither sharp nor ffmpeg can read the file it
43
+ * sends the original bytes under the detected type. SVG is markup and is
44
+ * refused. Nothing in the proxy decodes the picture: a body that is corrupt
45
+ * after a valid signature is the provider's to refuse.
21
46
  *
22
47
  * Unlike the agent routes there is no allowed-roots setting: the proxy listens
23
48
  * on loopback without credentials by default, and a path allow-list on a server
@@ -36,10 +61,52 @@
36
61
  * @module proxy/proxyImageInput
37
62
  */
38
63
  import { AgentInputError, resolveAgentInput, } from "../server/utils/agentInput.js";
64
+ import { sniffInputImageMimeType } from "../utils/imageDetection.js";
39
65
  import { logger } from "../utils/logger.js";
40
66
  import { ProxyContextPreflightError } from "./proxyContextPreflight.js";
41
67
  const INVALID_REFERENCE_MESSAGE = "Image references must be data: URIs or public https URLs. Local file paths, http URLs and other schemes are not accepted by this proxy.";
42
68
  const UNFETCHABLE_URL_MESSAGE = "An image URL could not be fetched. It must be a public https URL, answer without a redirect and fit the size limit.";
69
+ const INVALID_IMAGE_DATA_MESSAGE = "An inline image is not a recognised image. Send the bytes of a PNG, JPEG, WebP, GIF, HEIC, HEIF, AVIF, BMP, TIFF, ICO or JPEG 2000 image as base64, in a data: URI.";
70
+ const INVALID_URL_CONTENT_MESSAGE = "An image URL did not serve a recognised image. It must serve the bytes of a PNG, JPEG, WebP, GIF, HEIC, HEIF, AVIF, BMP, TIFF, ICO or JPEG 2000 image.";
71
+ /**
72
+ * Base64 characters sufficient for the longest signature probe: every format is
73
+ * recognised within its first few dozen bytes, and an ISO-BMFF `ftyp` box can
74
+ * list brands for a little longer. A multiple of four, so the prefix of a longer
75
+ * payload decodes without padding.
76
+ */
77
+ const SNIFF_BASE64_CHARS = 1024;
78
+ /** The longest `data:...;base64` header taken for one; a longer one is no header. */
79
+ const MAX_DATA_URI_HEADER_CHARS = 256;
80
+ /** Standard or URL-safe base64, the two alphabets Google's JSON `bytes` fields accept. */
81
+ const BASE64_TEXT = /^[A-Za-z0-9+/_-]+={0,2}$/;
82
+ /**
83
+ * `data` as padded standard-alphabet base64, which is what a `data:` URI carries,
84
+ * or undefined when it is not well-formed base64.
85
+ *
86
+ * The SDK forwards the base64 text of a `data:` URI to the provider as it is, so
87
+ * a URL-safe or unpadded payload would reach a provider that expects neither.
88
+ * The alphabet check alone lets through a payload no decoder takes: one
89
+ * character over a multiple of four is no base64 length at all, and padding
90
+ * must be exactly what the length calls for. An empty string is not base64.
91
+ *
92
+ * One rule for every door: the Gemini parser applies it before wrapping raw
93
+ * `inlineData`, and the vetter applies it again to every `data:` URI it is given.
94
+ */
95
+ export function toStandardBase64(data) {
96
+ if (!BASE64_TEXT.test(data)) {
97
+ return undefined;
98
+ }
99
+ const standard = /[-_]/.test(data)
100
+ ? data.replace(/-/g, "+").replace(/_/g, "/")
101
+ : data;
102
+ const body = standard.replace(/=+$/, "");
103
+ const padding = standard.length - body.length;
104
+ const missing = (4 - (body.length % 4)) % 4;
105
+ if (missing === 3 || (padding > 0 && padding !== missing)) {
106
+ return undefined;
107
+ }
108
+ return `${body}${"=".repeat(missing)}`;
109
+ }
43
110
  /** An image reference the proxy refuses; answers 400 in the client's format. */
44
111
  export class ProxyImageInputError extends ProxyContextPreflightError {
45
112
  constructor(code, message) {
@@ -57,6 +124,9 @@ function describeRefusal(entry) {
57
124
  if (typeof entry !== "string") {
58
125
  return "non-string";
59
126
  }
127
+ if (entry === "") {
128
+ return "empty";
129
+ }
60
130
  if (/^https?:\/\//i.test(entry)) {
61
131
  return "http-url";
62
132
  }
@@ -71,6 +141,67 @@ function refuseReference(entry) {
71
141
  });
72
142
  return new ProxyImageInputError("invalid_image_reference", INVALID_REFERENCE_MESSAGE);
73
143
  }
144
+ /**
145
+ * `reason` names which check failed, for the operator's log; the data itself is
146
+ * never logged, nor echoed to the client.
147
+ */
148
+ function refuseImageData(reason, message = INVALID_IMAGE_DATA_MESSAGE) {
149
+ logger.warn("[proxy] refused image bytes that are not a recognised image", {
150
+ reason,
151
+ });
152
+ return new ProxyImageInputError("invalid_image_data", message);
153
+ }
154
+ /** A declared type safe to put in a log line; anything else is `malformed`. */
155
+ const loggableType = (declared) => declared.length <= 64 && /^[\w./+-]*$/.test(declared)
156
+ ? declared.toLowerCase()
157
+ : "malformed";
158
+ /**
159
+ * Check one `data:` URI and return it as `data:<detected type>;base64,<payload>`.
160
+ *
161
+ * The header's parameters and declared type are discarded: the type is read
162
+ * from the decoded bytes. Only the leading bytes are decoded to find it; the
163
+ * rest of the payload has been checked as base64 text and is forwarded as is.
164
+ *
165
+ * @throws {ProxyImageInputError} `invalid_image_data` when the URI is not a
166
+ * base64 data URI, its payload is empty or not strict base64, or its bytes are
167
+ * not a recognised image.
168
+ */
169
+ function verifyInlineImage(entry) {
170
+ const comma = entry.indexOf(",");
171
+ if (comma === -1 || comma > MAX_DATA_URI_HEADER_CHARS) {
172
+ throw refuseImageData("data-uri-shape");
173
+ }
174
+ const header = entry.slice("data:".length, comma);
175
+ if (!/;base64$/i.test(header)) {
176
+ throw refuseImageData("data-uri-shape");
177
+ }
178
+ if (comma + 1 === entry.length) {
179
+ throw refuseImageData("empty-payload");
180
+ }
181
+ const payload = toStandardBase64(entry.slice(comma + 1));
182
+ if (payload === undefined) {
183
+ throw refuseImageData("not-base64");
184
+ }
185
+ const detected = sniffInputImageMimeType(Buffer.from(payload.slice(0, SNIFF_BASE64_CHARS), "base64"));
186
+ if (detected === null) {
187
+ throw refuseImageData("not-an-image");
188
+ }
189
+ const declared = header.slice(0, header.indexOf(";"));
190
+ if (declared.toLowerCase() !== detected) {
191
+ logger.debug("[proxy] corrected the declared type of an inline image", {
192
+ declared: loggableType(declared),
193
+ detected,
194
+ });
195
+ }
196
+ return `data:${detected};base64,${payload}`;
197
+ }
198
+ /** The bytes of a downloaded image, or a refusal when they are not one. */
199
+ function verifyDownloadedImage(bytes) {
200
+ if (sniffInputImageMimeType(bytes) === null) {
201
+ throw refuseImageData("url-content", INVALID_URL_CONTENT_MESSAGE);
202
+ }
203
+ return bytes;
204
+ }
74
205
  function asProxyImageInputError(error) {
75
206
  if (!(error instanceof AgentInputError)) {
76
207
  return error;
@@ -83,14 +214,23 @@ function asProxyImageInputError(error) {
83
214
  return new ProxyImageInputError("image_url_unfetchable", UNFETCHABLE_URL_MESSAGE);
84
215
  }
85
216
  /**
86
- * Resolve one list of client image references to what the SDK may be given.
217
+ * Resolve one list of client image references to what the SDK may be given:
218
+ * `data:` URIs rewritten to carry the type their bytes have, and downloaded
219
+ * bytes that are an image.
220
+ *
221
+ * Inline images are judged before anything is downloaded, so a request already
222
+ * doomed by one costs no network. Size and count are judged on the `data:` URIs
223
+ * as the client sent them (their string length), then on the downloads (their
224
+ * bytes), exactly as the agent routes judge them.
87
225
  *
88
226
  * `signal` cancels the work: a download in flight is aborted and no further
89
227
  * reference is started. A cancellation rejects with the signal's own error, not
90
228
  * with a {@link ProxyImageInputError}, since nothing was refused.
91
229
  *
92
- * @throws {ProxyImageInputError} for the first reference that is refused, or
93
- * for a list that carries too many images or too many bytes.
230
+ * @throws {ProxyImageInputError} for the first reference that is refused
231
+ * (`invalid_image_reference`, `invalid_image_data`, `image_url_unfetchable`),
232
+ * or for a list that carries too many images or too many bytes
233
+ * (`image_input_too_large`).
94
234
  */
95
235
  export async function vetProxyImages(images, signal) {
96
236
  const references = [];
@@ -100,9 +240,21 @@ export async function vetProxyImages(images, signal) {
100
240
  }
101
241
  references.push(entry);
102
242
  }
243
+ const inline = references.map((entry) => isDataUri(entry) ? verifyInlineImage(entry) : undefined);
103
244
  try {
245
+ // The client's own strings are what is measured against the limits; the
246
+ // rewritten ones replace them afterwards.
104
247
  const resolved = await resolveAgentInput({ text: "", images: references }, { signal });
105
- return resolved.images ?? [];
248
+ return (resolved.images ?? []).map((item, index) => {
249
+ const verified = inline[index];
250
+ if (verified !== undefined) {
251
+ return verified;
252
+ }
253
+ if (typeof item === "string") {
254
+ throw refuseReference(item);
255
+ }
256
+ return verifyDownloadedImage(item);
257
+ });
106
258
  }
107
259
  catch (error) {
108
260
  throw asProxyImageInputError(error);
@@ -0,0 +1,29 @@
1
+ # Proxy pool engines (src/lib/server/routes)
2
+
3
+ Loaded automatically when working under `src/lib/server/routes/`. Moved out of the root CLAUDE.md.
4
+
5
+ The proxy runs two independent subscription pool engines that share the token
6
+ store and the cooldown/quota persistence layer:
7
+
8
+ | | Anthropic (Claude) | Codex (ChatGPT) |
9
+ | ------------------ | ------------------------------- | ----------------------------------------- |
10
+ | Inbound route | `POST /v1/messages` | `POST /backend-api/codex/responses` |
11
+ | Upstream | `api.anthropic.com/v1/messages` | `chatgpt.com/backend-api/codex/responses` |
12
+ | Wire format | Anthropic Messages | OpenAI Responses |
13
+ | Token-store prefix | `anthropic:` | `codex:` |
14
+ | Quota windows | unified 5h / 7d | primary / secondary |
15
+
16
+ Both engines key **cooldowns** and **quota** by the full account key
17
+ (`anthropic:foo`, `codex:foo`). The Anthropic side used to key quota by the bare
18
+ label (`foo`), and snapshots saved that way are still in
19
+ `~/.neurolink/account-quotas.json` on users' machines, so it reads
20
+ `persisted[account.key] ?? persisted[account.label]` and writes under
21
+ `account.key`: a legacy snapshot is picked up, and replaced on the next save.
22
+ `codex:foo` cannot collide with a bare Anthropic label, because no bare label
23
+ contains a `:` prefix. Use the full key in new code, and keep the label fallback
24
+ when reading Anthropic quota until the legacy snapshots are gone.
25
+
26
+ When adding a third provider, follow the Codex pattern: a new
27
+ `<provider>OAuth.ts`, a `<provider>AccountUsage.ts` quota parser, and a
28
+ `<provider>ProxyRoutes.ts` engine — do not modify the Anthropic hot path.
29
+ See `docs/features/codex-proxy-support.md`.
@@ -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":""}},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "13.8.30",
3
+ "version": "13.8.31",
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": {