stitchkit 0.135.0 → 0.135.1

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/agent-runtime/providers/openrouter-audio.d.ts +122 -0
  3. package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -0
  4. package/dist/agent-runtime/providers/openrouter-catalog-cache.d.ts.map +1 -1
  5. package/dist/agent-runtime/providers/openrouter-catalog.d.ts +2 -0
  6. package/dist/agent-runtime/providers/openrouter-catalog.d.ts.map +1 -1
  7. package/dist/agent-runtime/providers/openrouter-http.d.ts +100 -0
  8. package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -0
  9. package/dist/agent-runtime/providers/openrouter-media.d.ts +160 -0
  10. package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -0
  11. package/dist/agent-runtime/providers/openrouter-models.d.ts +1 -1
  12. package/dist/agent-runtime/providers/openrouter-models.d.ts.map +1 -1
  13. package/dist/agent-runtime/providers/openrouter-options.d.ts +2 -0
  14. package/dist/agent-runtime/providers/openrouter-options.d.ts.map +1 -1
  15. package/dist/agent-runtime/providers/openrouter-response.d.ts.map +1 -1
  16. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts +114 -0
  17. package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -0
  18. package/dist/agent-runtime/providers/openrouter-spend.d.ts +5 -1
  19. package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
  20. package/dist/agent-runtime/providers/openrouter-stream.d.ts +29 -0
  21. package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -0
  22. package/dist/agent-runtime/providers/openrouter-systemone.d.ts +82 -0
  23. package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -0
  24. package/dist/agent-runtime/providers/openrouter-url.d.ts +13 -0
  25. package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -0
  26. package/dist/agent-runtime/providers/openrouter.d.ts +4 -1
  27. package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -1
  28. package/dist/agent-runtime/providers/provider-http.d.ts +15 -1
  29. package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -1
  30. package/dist/agent-runtime/stores/branch-observations.d.ts +42 -42
  31. package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts +20 -20
  32. package/dist/agent-runtime/testing/store-conformance-support.d.ts +10 -10
  33. package/dist/entrypoints/agent-runtime/anthropic.js +1 -1
  34. package/dist/entrypoints/agent-runtime/openai.js +1 -1
  35. package/dist/entrypoints/agent-runtime/openrouter.d.ts +7 -0
  36. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
  37. package/dist/entrypoints/agent-runtime/openrouter.js +1444 -241
  38. package/dist/{index-zfrysr1e.js → index-ht71v1ag.js} +52 -32
  39. package/llms/agent-runtime-openrouter.txt +11 -3
  40. package/llms/agent-runtime.2.txt +333 -224
  41. package/llms/agent-runtime.3.txt +225 -380
  42. package/llms/agent-runtime.4.txt +381 -158
  43. package/llms/agent-runtime.5.txt +157 -152
  44. package/llms/agent-runtime.6.txt +164 -0
  45. package/llms/agent-runtime.txt +30 -332
  46. package/llms/spend.txt +17 -1
  47. package/llms-full.txt +54 -4
  48. package/llms.txt +3 -3
  49. package/package.json +1 -1
@@ -157,6 +157,50 @@ async function readErrorBodyPrefix(response, maxBytes, signal) {
157
157
  const text = keptBytes === 0 ? "" : new TextDecoder().decode(concatChunks(kept, keptBytes));
158
158
  return { text, truncated: result.kind === "over-limit" };
159
159
  }
160
+ function extractProviderRequestId(headers) {
161
+ for (const key of ["x-request-id", "request-id"]) {
162
+ const value = headers.get(key)?.trim();
163
+ if (value && value.length > 0)
164
+ return value;
165
+ }
166
+ return;
167
+ }
168
+ async function buildProviderHttpError(input) {
169
+ const { response, signal } = input;
170
+ const requestId = extractProviderRequestId(response.headers);
171
+ const retryAfterMs = parseRetryAfterMs(response.headers);
172
+ const responseHeaders = headersToRecord(response.headers);
173
+ const shouldRetryHeader = response.headers.get("x-should-retry")?.trim().toLowerCase();
174
+ const retryableOverride = shouldRetryHeader === "false" ? false : undefined;
175
+ const maxErrorBytes = input.maxErrorBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES;
176
+ const prefix = await readErrorBodyPrefix(response, maxErrorBytes, signal);
177
+ const truncationNote = prefix.truncated ? ` [truncated after ${maxErrorBytes} bytes]` : "";
178
+ const rawText = prefix.truncated ? `${prefix.text}${truncationNote}` : prefix.text;
179
+ let parsed;
180
+ if (!prefix.truncated && prefix.text.length > 0) {
181
+ try {
182
+ parsed = JSON.parse(prefix.text);
183
+ } catch {
184
+ parsed = undefined;
185
+ }
186
+ }
187
+ const details = input.parseError(parsed, rawText, response.status);
188
+ const redactedMessage = redactProviderFailureText(details.message || `${input.provider} HTTP ${response.status}`);
189
+ const redactedBody = rawText.length > 0 ? prefix.truncated ? `${redactProviderFailureText(prefix.text, Math.max(64, 4096 - truncationNote.length))}${truncationNote}` : redactProviderFailureText(rawText, 4096) : undefined;
190
+ return new AgentProviderError2(redactedMessage, {
191
+ provider: input.provider,
192
+ statusCode: response.status,
193
+ ...details.code !== undefined && { code: details.code },
194
+ ...details.errorType !== undefined && { errorType: details.errorType },
195
+ ...details.failureReason !== undefined && { failureReason: details.failureReason },
196
+ ...details.metadata !== undefined && { metadata: details.metadata },
197
+ ...requestId !== undefined && { requestId },
198
+ ...retryAfterMs !== undefined && { retryAfterMs },
199
+ ...retryableOverride !== undefined && { retryable: retryableOverride },
200
+ responseHeaders,
201
+ ...redactedBody !== undefined && { responseBody: redactedBody }
202
+ });
203
+ }
160
204
  async function postProviderStream(input) {
161
205
  const headers = new Headers;
162
206
  headers.set("content-type", "application/json");
@@ -188,41 +232,17 @@ async function postProviderStream(input) {
188
232
  });
189
233
  input.signal.throwIfAborted();
190
234
  }
191
- const requestId = response.headers.get("x-request-id") ?? response.headers.get("request-id") ?? undefined;
192
- const retryAfterMs = parseRetryAfterMs(response.headers);
193
- const responseHeaders = headersToRecord(response.headers);
194
- const shouldRetryHeader = response.headers.get("x-should-retry")?.trim().toLowerCase();
195
- const retryableOverride = shouldRetryHeader === "false" ? false : undefined;
196
235
  if (!response.ok) {
197
- const maxErrorBytes = input.maxErrorBytes ?? DEFAULT_MAX_ERROR_BODY_BYTES;
198
- const prefix = await readErrorBodyPrefix(response, maxErrorBytes, input.signal);
199
- const truncationNote = prefix.truncated ? ` [truncated after ${maxErrorBytes} bytes]` : "";
200
- const rawText = prefix.truncated ? `${prefix.text}${truncationNote}` : prefix.text;
201
- let parsed;
202
- if (!prefix.truncated && prefix.text.length > 0) {
203
- try {
204
- parsed = JSON.parse(prefix.text);
205
- } catch {
206
- parsed = undefined;
207
- }
208
- }
209
- const details = input.parseError(parsed, rawText, response.status);
210
- const redactedMessage = redactProviderFailureText(details.message || `${input.provider} HTTP ${response.status}`);
211
- const redactedBody = rawText.length > 0 ? prefix.truncated ? `${redactProviderFailureText(prefix.text, Math.max(64, 4096 - truncationNote.length))}${truncationNote}` : redactProviderFailureText(rawText, 4096) : undefined;
212
- throw new AgentProviderError2(redactedMessage, {
236
+ throw await buildProviderHttpError({
213
237
  provider: input.provider,
214
- statusCode: response.status,
215
- ...details.code !== undefined && { code: details.code },
216
- ...details.errorType !== undefined && { errorType: details.errorType },
217
- ...details.failureReason !== undefined && { failureReason: details.failureReason },
218
- ...details.metadata !== undefined && { metadata: details.metadata },
219
- ...requestId !== undefined && { requestId },
220
- ...retryAfterMs !== undefined && { retryAfterMs },
221
- ...retryableOverride !== undefined && { retryable: retryableOverride },
222
- responseHeaders,
223
- ...redactedBody !== undefined && { responseBody: redactedBody }
238
+ response,
239
+ signal: input.signal,
240
+ parseError: input.parseError,
241
+ ...input.maxErrorBytes !== undefined && { maxErrorBytes: input.maxErrorBytes }
224
242
  });
225
243
  }
244
+ const requestId = extractProviderRequestId(response.headers);
245
+ const responseHeaders = headersToRecord(response.headers);
226
246
  const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
227
247
  if (contentType.includes("application/json")) {
228
248
  const maxJsonBytes = input.maxJsonBytes ?? DEFAULT_MAX_JSON_BODY_BYTES;
@@ -707,4 +727,4 @@ function parseSseJson(provider, data) {
707
727
  }
708
728
  }
709
729
 
710
- export { redactProviderFailureText, joinProviderUrl, assertNoExtraBodyClash, resolveProviderApiKey, parseHttpDateHeader, postProviderStream, nonEmptyString2, recordField, reportedInt, computedInt, reportedUsd, computedUsd, nonNegativeNumber, buildProviderUsage, normalizeProviderHistory, historyHasToolTraffic, parseSseStream, parseSseJson };
730
+ export { DEFAULT_MAX_ERROR_BODY_BYTES, DEFAULT_MAX_JSON_BODY_BYTES, redactProviderFailureText, headersToRecord, joinProviderUrl, assertNoExtraBodyClash, resolveProviderApiKey, parseHttpDateHeader, extractProviderRequestId, buildProviderHttpError, postProviderStream, nonEmptyString2, recordField, reportedInt, computedInt, reportedUsd, computedUsd, nonNegativeNumber, buildProviderUsage, normalizeProviderHistory, historyHasToolTraffic, parseSseStream, parseSseJson };
@@ -32,7 +32,15 @@ Server-only, peer-free native OpenRouter provider over Web `fetch` and Chat Comp
32
32
  | `findOpenRouterModel` / `listOpenRouterModels` / `OpenRouterModelFilter` | functions / _type_ | query an `OpenRouterCatalogSnapshot` by exact `id` or `canonicalSlug`, or filter models by `tools`, `reasoning` (`reasoning`, `include_reasoning`, or declared efforts), `inputModalities`, `outputModalities`, `minContextLength` (via effective context `min(contextLength, topProviderContextLength)`), `maxPromptUsdPerMillion`, `maxCompletionUsdPerMillion`, `maxCacheWriteUsdPerMillion` (using the same ceiling semantics as `evaluateOpenRouterModelAdmission`), `freeOnly`, and `author` |
33
33
  | `createOpenRouterCatalogCache` / `OpenRouterCatalogCache` / `OpenRouterCatalogCacheOptions` / `OpenRouterCatalogCacheReadResult` / `OpenRouterCatalogStore` | function / _types_ | Web Fetch-clean cached OpenRouter catalog reader with single-flight coalescing, per-caller `AbortSignal` isolation, `freshMs` TTL, `retryBackoffMs` stale fallback, optional pluggable persistence (`store`), and `read`/`refresh`/`getModel`/`listModels`; `OpenRouterCatalogCacheReadResult` is a discriminated union on `status` (`'current' \| 'stale' \| 'unavailable'`) narrowing `snapshot`, `observedAt`, `models`, and `lastError` without casts (use `read()` for admission/billing decisions; `getModel`/`listModels` map `'unavailable'` to `undefined`/`[]`) |
34
34
  | `evaluateOpenRouterModelAdmission` / `OpenRouterAdmissionPolicySchema` / `OpenRouterAdmissionPolicy` / `OpenRouterModelAdmissionSchema` / `OpenRouterModelAdmission` / `OpenRouterAdmissionReasonSchema` / `OpenRouterAdmissionReason` | function / schemas / _types_ | decide one model from a stored snapshot: `admitted`, `unverified` (stale or future-dated snapshot, `'context-unknown'`, `'price-unknown'`, `'endpoints-unknown'`) or `rejected` with a reason (`requiredParameters`, `requiredInputModalities`, effective context `min(contextLength, topProviderContextLength)`, separated worst-case pricing ceilings `maxPromptUsdPerMillion` / `maxCompletionUsdPerMillion` / `maxCacheWriteUsdPerMillion` via `resolveOpenRouterModelCeiling`, live endpoint); `~`, `-latest`, `:batch`, `stealth/`, `openrouter/auto`, `aliasOf`, and `aliasTarget` models are always refused as `'floating-alias'`; the result is a schema, so a stored decision reads back |
35
- | `openRouterSpendProvider` / `createOpenRouterSpendReconciler` | functions | OpenRouter for `stitchkit/spend`: the gateway provider (origin, key read per call, usage format) and the reconciler that prices an attempt by its generation id (`GET /api/v1/generation`; a 404 is "not yet"; `apiKey` may be a function of the record, since OpenRouter prices a generation only for the key that made it) |
35
+ | `openRouterSpendProvider` / `createOpenRouterSpendReconciler` | functions | OpenRouter for `stitchkit/spend`: the gateway provider (origin derived from optional `baseUrl` override, key read per call, chat + non-chat usage facts including `x-generation-id`, `input_tokens`/`output_tokens`, `generation_id`, and `usage.seconds` as `workUnit: 'seconds'`) and the reconciler that prices an attempt by its generation id (`GET /api/v1/generation`, optional `baseUrl` override; a 404 is "not yet"; `apiKey` may be a function of the record, since OpenRouter prices a generation only for the key that made it) |
36
36
  | `OpenRouterHttpError` | class | a non-2xx answer from OpenRouter, with its `status` |
37
- | `openRouterModelCatalog` | function | complete tool-capable text catalog (`sort=top-weekly`) plus independent weekly popularity and available benchmark observations (optional static or async `apiKey`); a `timeoutMs` that is not an integer from 1 to 2147483647 ms (the timer range) is refused when the catalog is created (`RangeError`) |
38
- | `OpenRouterModelCatalogOptions` / `OpenRouterCatalogFetch` | _type_ | optional static/dynamic credential, timeout, clock and injected fetch boundary for catalog loading |
37
+ | `openRouterModelCatalog` | function | complete tool-capable text catalog (`sort=top-weekly`) plus independent weekly popularity and available benchmark observations (optional static or async `apiKey` and `baseUrl` override); a `timeoutMs` that is not an integer from 1 to 2147483647 ms (the timer range) is refused when the catalog is created (`RangeError`) |
38
+ | `OpenRouterModelCatalogOptions` / `OpenRouterCatalogFetch` | _type_ | optional static/dynamic credential, `baseUrl` override, timeout, clock and injected fetch boundary for catalog loading |
39
+ | `OPENROUTER_API_BASE_URL` / `OpenRouterFetch` | const / _type_ | canonical default OpenRouter API v1 base URL (`https://openrouter.ai/api/v1`) and Web Fetch-compatible transport type shared by `openRouterProvider` and non-chat endpoint helpers |
40
+ | `openRouterRequestJson` / `openRouterRequestStream` / `OpenRouterTransportOptions` / `OpenRouterRequestJsonOptions` / `OpenRouterRequestStreamOptions` / `OpenRouterJsonResponse` / `OpenRouterStreamResponse` / `OpenRouterHttpMethod` / `OpenRouterQueryParams` | functions / _types_ | peer-free, Web Fetch-clean transport for any OpenRouter API v1 JSON, multipart (`FormData`), or binary streaming endpoint: validates `baseUrl` and relative `path` against traversal or origin override, enforces `redirect: 'error'` plus defense-in-depth redirect refusal, bounds response/error bodies, throws redacted `AgentProviderError` on non-2xx or invalid JSON/schema, extracts `generationId`, `requestId`, and BYOK-aware `costUsd`, and disarms `openRouterRequestStream`'s open-phase `timeoutMs` once 2xx headers arrive while keeping caller `signal` linked to stream cancellation |
41
+ | `openRouterSystemOne` / `OpenRouterSystemOneInput` / `OpenRouterSystemOneQuestion` / `OpenRouterSystemOneResponseSchema` / `OpenRouterSystemOneResponse` / `OpenRouterSystemOneResult` | function / schema / _types_ | typed client for OpenRouter's `POST /systemone` decision endpoint (`noul`, `choice`, and `score` questions over text or structured `state`, optional `provider` routing and `extraBody`, calibrated probability answers plus `generationId` and `costUsd`) |
42
+ | `openRouterAudioTranscription` / `OpenRouterAudioTranscriptionInput` / `OpenRouterAudioSource` / `OpenRouterAudioTranscriptionResponseSchema` / `OpenRouterAudioTranscriptionResponse` / `OpenRouterAudioTranscriptionResult` | function / schema / _types_ | typed client for OpenRouter's `POST /audio/transcriptions` speech-to-text endpoint supporting `base64` JSON (`input_audio`), remote `url` (`source_url`), and multipart `file` uploads (`Blob` / `Uint8Array` / `ArrayBuffer`), `verbose_json`, `timestampGranularities`, `diarize` (enforcing `verbose_json`), `provider` routing, `generationId`, and `costUsd` |
43
+ | `openRouterAudioSpeech` / `OpenRouterAudioSpeechInput` / `OpenRouterSpeechFormat` / `OpenRouterAudioSpeechResult` | function / _types_ | streaming text-to-speech client for OpenRouter's `POST /audio/speech` endpoint returning binary audio `ReadableStream<Uint8Array>`, `contentType`, and `generationId` |
44
+ | `openRouterGenerateImages` / `OpenRouterImageGenerationInput` / `OpenRouterImageGenerationResponseSchema` / `OpenRouterImageGenerationResponse` / `OpenRouterImageGenerationResult` | function / schema / _types_ | typed client for OpenRouter's Unified Image API (`POST /images`) supporting `prompt`, `n`, `aspectRatio`, `resolution`, `responseFormat` (`'b64_json' \| 'url'`), `inputReferences`, `provider` routing, `generationId`, and `costUsd` |
45
+ | `openRouterSubmitVideo` / `openRouterGetVideo` / `openRouterDownloadVideo` / `OpenRouterVideoSubmitInput` / `OpenRouterVideoJobInput` / `OpenRouterVideoSubmitResponse` / `OpenRouterVideoSubmitResult` / `OpenRouterVideoStatusResponse` / `OpenRouterVideoStatusResult` | functions / _types_ | typed submit (`POST /videos`), status poll (`GET /videos/{jobId}`), and authenticated binary stream download (`GET /videos/{jobId}/content`) clients for OpenRouter's asynchronous Video Generation API with `jobId` path-segment validation, `frameImages`, `inputReferences`, `generateAudio`, `callbackUrl`, `generationId`, and `costUsd` |
46
+ | `openRouterEmbeddings` / `OpenRouterEmbeddingsInput` / `OpenRouterEmbeddingsResponse` / `OpenRouterEmbeddingsResult` / `openRouterRerank` / `OpenRouterRerankInput` / `OpenRouterRerankResponse` / `OpenRouterRerankResult` | functions / _types_ | typed clients for OpenRouter's `POST /embeddings` vector generation and `POST /rerank` document rescoring endpoints with `provider` routing, `generationId`, and `costUsd` |