@juspay/neurolink 13.8.29 → 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
+ }
@@ -10,7 +10,7 @@ declare const MODEL_CONFIGS: {
10
10
  readonly fast: {
11
11
  readonly primary: {
12
12
  readonly provider: "vertex";
13
- readonly model: "gemini-2.5-flash";
13
+ readonly model: "gemini-3.8-flash";
14
14
  readonly capabilities: readonly ["speed", "general", "code", "basic-reasoning"];
15
15
  readonly avgResponseTime: 800;
16
16
  readonly costPerToken: 0.0001;
@@ -20,7 +20,7 @@ const MODEL_CONFIGS = {
20
20
  fast: {
21
21
  primary: {
22
22
  provider: "vertex",
23
- model: "gemini-2.5-flash",
23
+ model: "gemini-3.8-flash",
24
24
  capabilities: ["speed", "general", "code", "basic-reasoning"],
25
25
  avgResponseTime: 800,
26
26
  costPerToken: 0.0001,
@@ -542,6 +542,14 @@ const PRICING = {
542
542
  output: 1.5 / 1_000_000,
543
543
  cacheRead: 0.025 / 1_000_000,
544
544
  },
545
+ // Gemini 3.8 Flash (default Vertex model). Standard paid-tier rate through
546
+ // 2026-12-31 (input $1.50 / output $7.50 / cache $0.15 per 1M from 2027-01-01):
547
+ // https://ai.google.dev/gemini-api/docs/pricing
548
+ "gemini-3.8-flash": {
549
+ input: 0.75 / 1_000_000,
550
+ output: 3.75 / 1_000_000,
551
+ cacheRead: 0.075 / 1_000_000,
552
+ },
545
553
  // Gemini 3.1 preview family
546
554
  // cacheRead = 0.25x input (cached content tokens; explicit-cache storage is
547
555
  // billed separately by TTL/time, so no per-token cacheCreation rate here).
@@ -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) {
@@ -50,7 +50,7 @@ export async function executeVideoAnalysis(messages, options) {
50
50
  ? undefined
51
51
  : process.env.GOOGLE_VERTEX_PROJECT || process.env.GOOGLE_CLOUD_PROJECT,
52
52
  location: options.region || process.env.GOOGLE_VERTEX_LOCATION,
53
- model: options.model || "gemini-2.5-flash",
53
+ model: options.model || "gemini-3.8-flash",
54
54
  });
55
55
  logger.debug("[VideoAnalysisProcessor] Video analysis completed", {
56
56
  hasResult: !!videoAnalysisText,
@@ -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.