sliccy 2.22.1 → 2.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node-server/index.js +136 -18
- package/dist/node-server/release-package.d.ts +0 -1
- package/dist/node-server/release-package.js +1 -8
- package/dist/ui/assets/anthropic-DzA7ID1f.js +39 -0
- package/dist/ui/assets/azure-openai-responses-L-g8xGN9.js +1 -0
- package/dist/ui/assets/{dist-DEU7LMsW.js → dist-BETSJsV5.js} +1 -1
- package/dist/ui/assets/{dist-BOSN53wj2.js → dist-BVxswsnA.js} +2 -2
- package/dist/ui/assets/{dist-Bsu1jCSL.js → dist-C_pwrhfY.js} +1 -1
- package/dist/ui/assets/{dist-UfV1NDbo.js → dist-Ck3Vla0r.js} +1 -1
- package/dist/ui/assets/{dist-DfXP7YfQ.js → dist-DB19jrs9.js} +1 -1
- package/dist/ui/assets/{es-B7F4vMGM.js → es-ANbLTHCW.js} +3 -3
- package/dist/ui/assets/{fs-C8YYTJOZ.js → fs-B0gD1h31.js} +1 -1
- package/dist/ui/assets/github-copilot-headers-DGaOrqaW.js +1 -0
- package/dist/ui/assets/google-BFrczX47.js +1 -0
- package/dist/ui/assets/google-shared-tCK79d6s.js +11 -0
- package/dist/ui/assets/google-vertex-DVupsUV0.js +1 -0
- package/dist/ui/assets/{index-C_F1DRoS.js → index-BVA4YIGJ.js} +1021 -941
- package/dist/ui/assets/{magick-wasm-kVMRnisO.js → magick-wasm-DpuDwl7G.js} +1 -1
- package/dist/ui/assets/{mistral-Psfiyuyg.js → mistral-BytTBgnp.js} +4 -4
- package/dist/ui/assets/{onboarding-orchestrator-C2nsOQmV.js → onboarding-orchestrator-De86ExKz.js} +1 -1
- package/dist/ui/assets/openai-codex-responses-DpZthon5.js +7 -0
- package/dist/ui/assets/openai-completions-C9gJOWvK.js +5 -0
- package/dist/ui/assets/openai-responses-De-ZNw7W.js +1 -0
- package/dist/ui/assets/provider-settings-ciu6URbL.js +95 -0
- package/dist/ui/assets/{pyodide-CYVFNkgG.js → pyodide-DCMrvZhT.js} +2 -2
- package/dist/ui/assets/simple-options-CDIijiMb.js +1 -0
- package/dist/ui/assets/{skills-DBi1lWWR.js → skills-DShRVTVQ.js} +1 -1
- package/dist/ui/assets/{slicc-editor-CuCrLc0u.js → slicc-editor-C9a_yd9R.js} +2 -2
- package/dist/ui/assets/{sql-wasm-CjYU-RUL.js → sql-wasm-GAMLdFdJ.js} +1 -1
- package/dist/ui/index.html +17 -13
- package/dist/ui/llm-proxy-sw.js +1 -0
- package/dist/ui/packages/webapp/index.html +17 -13
- package/package.json +4 -3
- package/dist/node-server/sync-release-version.d.ts +0 -4
- package/dist/node-server/sync-release-version.js +0 -44
- package/dist/ui/assets/anthropic-BBdzKe_5.js +0 -39
- package/dist/ui/assets/azure-openai-responses-C_P8NgJ8.js +0 -1
- package/dist/ui/assets/github-copilot-headers-BuUn5v2j.js +0 -1
- package/dist/ui/assets/google-BJYq8RB-.js +0 -1
- package/dist/ui/assets/google-gemini-cli-BZEjJgF7.js +0 -2
- package/dist/ui/assets/google-shared-Cu4bgtNm.js +0 -11
- package/dist/ui/assets/google-vertex-CfBb7__M.js +0 -1
- package/dist/ui/assets/openai-codex-responses-BqWXAH5A.js +0 -7
- package/dist/ui/assets/openai-completions-CbSb9DNR.js +0 -5
- package/dist/ui/assets/openai-responses-32eOEVfr.js +0 -1
- package/dist/ui/assets/openai-responses-shared-D7Iy5EFQ.js +0 -10
- package/dist/ui/assets/provider-settings-DCcbCHgM.js +0 -95
- package/dist/ui/assets/sanitize-unicode-BD2XKRoV.js +0 -1
- package/dist/ui/assets/simple-options-p0Mmb-pN.js +0 -1
- /package/dist/ui/assets/{__vite-browser-external-zdR8bj89.js → __vite-browser-external-BD_HvDfc.js} +0 -0
- /package/dist/ui/assets/{addon-fit-Dq6sROpn.js → addon-fit-CniRnSyE.js} +0 -0
- /package/dist/ui/assets/{browser-Cpl52X72.js → browser-CFDl2kC3.js} +0 -0
- /package/dist/ui/assets/{bsh-watchdog-B07eNo5F.js → bsh-watchdog-DWN1spIr.js} +0 -0
- /package/dist/ui/assets/{chat-fixture-BPoXQA7f.js → chat-fixture-BGLmPevX.js} +0 -0
- /package/dist/ui/assets/{db-Dir1_tnZ.js → db-QbwB670D.js} +0 -0
- /package/dist/ui/assets/{dist-BByiYVMV.js → dist-CkF25Z3T.js} +0 -0
- /package/dist/ui/assets/{dist-D6ztLqPA.js → dist-uJp2dR6X.js} +0 -0
- /package/dist/ui/assets/{fetch-body-T80zl4z4.js → fetch-body-DPMYsjzA.js} +0 -0
- /package/dist/ui/assets/{global-db-DVnWv0oM.js → global-db-Cui6Md0w.js} +0 -0
- /package/dist/ui/assets/{hash-Dit8ENAX.js → hash-BN8UQrrC.js} +0 -0
- /package/dist/ui/assets/{headers-DkHU-pcw.js → headers-qDMOQQGF.js} +0 -0
- /package/dist/ui/assets/{lick-manager-proxy-BZUMVDTP.js → lick-manager-proxy-Dw3D3AzG.js} +0 -0
- /package/dist/ui/assets/{oauth-service-38tFqQEB.js → oauth-service-DUXASG7L.js} +0 -0
- /package/dist/ui/assets/{offscreen-client-82Pn8cmc.js → offscreen-client-DRN1fwvT.js} +0 -0
- /package/dist/ui/assets/{openai-BSNYAgA1.js → openai-D4NSaQIs.js} +0 -0
- /package/dist/ui/assets/{path-utils-BqLAyaya.js → path-utils-DAY6ORUp.js} +0 -0
- /package/dist/ui/assets/{pdfjs-CFev-Ohh.js → pdfjs-C0bwNEC1.js} +0 -0
- /package/dist/ui/assets/{rum-wVO4iYd-.js → rum-sVedwbc1.js} +0 -0
- /package/dist/ui/assets/{secret-masking-DYVLKOtn.js → secret-masking-ZNVanUmG.js} +0 -0
- /package/dist/ui/assets/{src-CtySarJL.js → src-DSYf97Eh.js} +0 -0
- /package/dist/ui/assets/{xterm-BS-IjYp6.js → xterm-BaLOnk9X.js} +0 -0
|
@@ -4,6 +4,8 @@ import { createServer as createNetServer } from 'net';
|
|
|
4
4
|
import { spawn } from 'child_process';
|
|
5
5
|
import { existsSync, readFileSync } from 'fs';
|
|
6
6
|
import { join, resolve } from 'path';
|
|
7
|
+
import { Readable, Transform } from 'stream';
|
|
8
|
+
import { StringDecoder } from 'string_decoder';
|
|
7
9
|
import { fileURLToPath } from 'url';
|
|
8
10
|
import express from 'express';
|
|
9
11
|
import { WebSocketServer, WebSocket } from 'ws';
|
|
@@ -831,6 +833,10 @@ async function main() {
|
|
|
831
833
|
res.status(400).json({ error: 'Missing X-Target-URL header' });
|
|
832
834
|
return;
|
|
833
835
|
}
|
|
836
|
+
// Hoisted so the catch handler below can detach it on early
|
|
837
|
+
// failures (e.g. fetch threw before the success-path detach
|
|
838
|
+
// could run).
|
|
839
|
+
let onClientClose = null;
|
|
834
840
|
try {
|
|
835
841
|
const fetchInit = {
|
|
836
842
|
method: req.method,
|
|
@@ -940,46 +946,148 @@ async function main() {
|
|
|
940
946
|
// Buffer extends Uint8Array which is a valid fetch body at runtime.
|
|
941
947
|
fetchInit.body = rawBody;
|
|
942
948
|
}
|
|
949
|
+
// Propagate client disconnect to the upstream request so that
|
|
950
|
+
// long-lived streams (LLM SSE completions) are torn down promptly
|
|
951
|
+
// when the SW or the page aborts. Listen on `res.on('close')` —
|
|
952
|
+
// not `req.on('close')` — because Node fires `req` close as soon
|
|
953
|
+
// as the readable side of the request is consumed (right after
|
|
954
|
+
// express.json() parses the body), which would abort the upstream
|
|
955
|
+
// fetch before it could even start. `res` close only fires when
|
|
956
|
+
// the response is sent OR the connection is killed mid-stream;
|
|
957
|
+
// in the first case the abort is harmless (the fetch already
|
|
958
|
+
// settled), in the second it's exactly what we want. Guard with
|
|
959
|
+
// `res.writableEnded` to be safe.
|
|
960
|
+
const abortController = new AbortController();
|
|
961
|
+
onClientClose = () => {
|
|
962
|
+
if (!res.writableEnded)
|
|
963
|
+
abortController.abort();
|
|
964
|
+
};
|
|
965
|
+
res.on('close', onClientClose);
|
|
966
|
+
fetchInit.signal = abortController.signal;
|
|
943
967
|
const upstream = await fetch(targetUrl, fetchInit);
|
|
944
968
|
// Forward status, prevent browser caching of proxy responses
|
|
945
969
|
res.status(upstream.status);
|
|
946
970
|
res.setHeader('Cache-Control', 'no-store, no-cache');
|
|
947
971
|
// Forward response headers (strip www-authenticate to prevent
|
|
948
972
|
// the browser from showing a native Basic Auth dialog — isomorphic-git
|
|
949
|
-
// handles 401s through its own onAuth callback)
|
|
950
|
-
//
|
|
951
|
-
// responses. Collect all Set-Cookie values and encode as JSON in a
|
|
952
|
-
// transport header the browser can read.
|
|
973
|
+
// handles 401s through its own onAuth callback). Drop Content-Length
|
|
974
|
+
// so the response can be chunk-encoded transparently.
|
|
953
975
|
const setCookieValues = upstream.headers.getSetCookie();
|
|
954
976
|
upstream.headers.forEach((v, k) => {
|
|
955
977
|
const lower = k.toLowerCase();
|
|
956
978
|
if (lower !== 'transfer-encoding' &&
|
|
957
979
|
lower !== 'content-encoding' &&
|
|
980
|
+
lower !== 'content-length' &&
|
|
958
981
|
lower !== 'www-authenticate' &&
|
|
959
982
|
lower !== 'set-cookie' &&
|
|
960
983
|
!lower.startsWith('x-proxy-')) {
|
|
961
|
-
// Scrub real secret values from response headers
|
|
984
|
+
// Scrub real secret values from response headers (one-shot,
|
|
985
|
+
// headers are always small so per-chunk semantics don't apply).
|
|
962
986
|
res.setHeader(k, secretProxy.scrubResponse(v));
|
|
963
987
|
}
|
|
964
988
|
});
|
|
965
989
|
if (setCookieValues.length > 0) {
|
|
966
990
|
res.setHeader('X-Proxy-Set-Cookie', secretProxy.scrubResponse(JSON.stringify(setCookieValues)));
|
|
967
991
|
}
|
|
968
|
-
//
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
992
|
+
// Stream the upstream body straight through to the client so that
|
|
993
|
+
// LLM SSE completions reach the browser token-by-token instead of
|
|
994
|
+
// arriving in one giant burst at the end. Per-chunk secret-scrub
|
|
995
|
+
// runs on text responses; secrets that span a chunk boundary slip
|
|
996
|
+
// through unscrubbed (documented limitation — the scrub primitive
|
|
997
|
+
// is best-effort on streamed bodies).
|
|
998
|
+
if (!upstream.body) {
|
|
999
|
+
res.end();
|
|
1000
|
+
if (onClientClose)
|
|
1001
|
+
res.off('close', onClientClose);
|
|
1002
|
+
return;
|
|
978
1003
|
}
|
|
979
|
-
|
|
980
|
-
|
|
1004
|
+
const ct = (upstream.headers.get('content-type') ?? '').toLowerCase();
|
|
1005
|
+
const isText = ct.startsWith('text/') ||
|
|
1006
|
+
ct.startsWith('application/json') ||
|
|
1007
|
+
ct.includes('charset=') ||
|
|
1008
|
+
ct.includes('event-stream');
|
|
1009
|
+
const upstreamStream = Readable.fromWeb(upstream.body);
|
|
1010
|
+
// Buffer-aware UTF-8 scrubber. Naive `Buffer.from(chunk).toString('utf-8')`
|
|
1011
|
+
// corrupts multi-byte codepoints whenever a sequence straddles a chunk
|
|
1012
|
+
// boundary — Node replaces the partial bytes with U+FFFD, which is fatal
|
|
1013
|
+
// for any non-ASCII model output (CJK, emoji, even some accented Latin).
|
|
1014
|
+
// `StringDecoder` keeps the trailing partial bytes in a private buffer
|
|
1015
|
+
// and prepends them to the next chunk, guaranteeing valid UTF-8 every
|
|
1016
|
+
// call. The flush() in `flush(cb)` releases any tail bytes (replacing
|
|
1017
|
+
// truly invalid trailing bytes with U+FFFD, same as before but only at
|
|
1018
|
+
// EOF where it can't span a real codepoint).
|
|
1019
|
+
const utf8Decoder = new StringDecoder('utf8');
|
|
1020
|
+
const scrubChunk = new Transform({
|
|
1021
|
+
transform(chunk, _enc, cb) {
|
|
1022
|
+
if (!isText || !secretProxy.hasSecrets()) {
|
|
1023
|
+
cb(null, chunk);
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
try {
|
|
1027
|
+
const decoded = utf8Decoder.write(chunk);
|
|
1028
|
+
if (decoded.length === 0) {
|
|
1029
|
+
// All bytes were buffered as a partial codepoint — no output yet.
|
|
1030
|
+
cb(null, Buffer.alloc(0));
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
const scrubbed = secretProxy.scrubResponse(decoded);
|
|
1034
|
+
cb(null, Buffer.from(scrubbed, 'utf-8'));
|
|
1035
|
+
}
|
|
1036
|
+
catch (err) {
|
|
1037
|
+
cb(err);
|
|
1038
|
+
}
|
|
1039
|
+
},
|
|
1040
|
+
flush(cb) {
|
|
1041
|
+
if (!isText || !secretProxy.hasSecrets()) {
|
|
1042
|
+
cb();
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
try {
|
|
1046
|
+
const tail = utf8Decoder.end();
|
|
1047
|
+
if (tail.length === 0) {
|
|
1048
|
+
cb();
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
const scrubbed = secretProxy.scrubResponse(tail);
|
|
1052
|
+
cb(null, Buffer.from(scrubbed, 'utf-8'));
|
|
1053
|
+
}
|
|
1054
|
+
catch (err) {
|
|
1055
|
+
cb(err);
|
|
1056
|
+
}
|
|
1057
|
+
},
|
|
1058
|
+
});
|
|
1059
|
+
const cleanup = () => {
|
|
1060
|
+
if (onClientClose) {
|
|
1061
|
+
res.off('close', onClientClose);
|
|
1062
|
+
onClientClose = null;
|
|
1063
|
+
}
|
|
1064
|
+
};
|
|
1065
|
+
upstreamStream.on('error', (err) => {
|
|
1066
|
+
cleanup();
|
|
1067
|
+
if (!res.headersSent) {
|
|
1068
|
+
res.setHeader('X-Proxy-Error', '1');
|
|
1069
|
+
res
|
|
1070
|
+
.status(502)
|
|
1071
|
+
.json({ error: `Proxy stream failed: ${err instanceof Error ? err.message : err}` });
|
|
1072
|
+
}
|
|
1073
|
+
else {
|
|
1074
|
+
res.destroy(err);
|
|
1075
|
+
}
|
|
1076
|
+
});
|
|
1077
|
+
// Belt-and-braces cleanup: 'finish' fires once the response is fully
|
|
1078
|
+
// flushed; 'close' fires regardless of how the response ended (success,
|
|
1079
|
+
// abort, or pipe error). Either way we want the abort listener gone.
|
|
1080
|
+
res.on('finish', cleanup);
|
|
1081
|
+
res.on('close', cleanup);
|
|
1082
|
+
upstreamStream.pipe(scrubChunk).pipe(res);
|
|
981
1083
|
}
|
|
982
1084
|
catch (err) {
|
|
1085
|
+
// Best-effort cleanup so an early failure (e.g. fetch threw) doesn't
|
|
1086
|
+
// leave the close listener attached to the response object.
|
|
1087
|
+
if (onClientClose) {
|
|
1088
|
+
res.off('close', onClientClose);
|
|
1089
|
+
onClientClose = null;
|
|
1090
|
+
}
|
|
983
1091
|
const message = err instanceof Error ? err.message : String(err);
|
|
984
1092
|
res.setHeader('X-Proxy-Error', '1');
|
|
985
1093
|
res.status(502).json({ error: `Proxy fetch failed: ${message}` });
|
|
@@ -1029,7 +1137,17 @@ async function main() {
|
|
|
1029
1137
|
else {
|
|
1030
1138
|
// Production mode: serve built static files
|
|
1031
1139
|
const uiDir = resolve(__dirname, '..', 'ui');
|
|
1032
|
-
app.use(express.static(uiDir
|
|
1140
|
+
app.use(express.static(uiDir, {
|
|
1141
|
+
setHeaders: (res, path) => {
|
|
1142
|
+
// Service workers must declare a maximum scope; without
|
|
1143
|
+
// `Service-Worker-Allowed: /`, the browser refuses to register
|
|
1144
|
+
// a root-scoped SW served from `/llm-proxy-sw.js`.
|
|
1145
|
+
if (path.endsWith('llm-proxy-sw.js')) {
|
|
1146
|
+
res.setHeader('Service-Worker-Allowed', '/');
|
|
1147
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
1148
|
+
}
|
|
1149
|
+
},
|
|
1150
|
+
}));
|
|
1033
1151
|
// SPA fallback — serve index.html for all non-file routes
|
|
1034
1152
|
app.get('/{*path}', (_req, res) => {
|
|
1035
1153
|
res.sendFile(join(uiDir, 'index.html'));
|
|
@@ -9,7 +9,6 @@ interface ReleaseManifest {
|
|
|
9
9
|
npmPackageTarball: string;
|
|
10
10
|
}
|
|
11
11
|
export declare function sanitizeArtifactName(value: string): string;
|
|
12
|
-
export declare function assertMatchingVersions(packageVersion: string, extensionVersion: string): void;
|
|
13
12
|
export declare function collectZipEntries(rootDir: string): ZipEntry[];
|
|
14
13
|
export declare function createDeterministicZip(entries: readonly ZipEntry[]): Buffer;
|
|
15
14
|
export declare function parseNpmPackFilename(output: string): string;
|
|
@@ -29,11 +29,6 @@ export function sanitizeArtifactName(value) {
|
|
|
29
29
|
.replace(/-+/g, '-')
|
|
30
30
|
.replace(/^-|-$/g, '');
|
|
31
31
|
}
|
|
32
|
-
export function assertMatchingVersions(packageVersion, extensionVersion) {
|
|
33
|
-
if (packageVersion !== extensionVersion) {
|
|
34
|
-
throw new Error(`package.json version (${packageVersion}) must match manifest.json version (${extensionVersion}) before packaging release artifacts.`);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
32
|
export function collectZipEntries(rootDir) {
|
|
38
33
|
const entries = [];
|
|
39
34
|
const walk = (currentDir) => {
|
|
@@ -198,11 +193,9 @@ function writeReleaseManifest(manifest) {
|
|
|
198
193
|
}
|
|
199
194
|
export function packageReleaseArtifacts() {
|
|
200
195
|
const packageJson = readJsonFile(resolve(PROJECT_ROOT, 'package.json'));
|
|
201
|
-
const extensionManifest = readJsonFile(resolve(PROJECT_ROOT, 'packages/chrome-extension/manifest.json'));
|
|
202
|
-
assertMatchingVersions(packageJson.version, extensionManifest.version);
|
|
203
196
|
rmSync(RELEASE_DIR, { recursive: true, force: true });
|
|
204
197
|
mkdirSync(RELEASE_DIR, { recursive: true });
|
|
205
|
-
const extensionArchive = createExtensionArchive(
|
|
198
|
+
const extensionArchive = createExtensionArchive(packageJson);
|
|
206
199
|
const npmPackageTarball = createNpmPackageTarball();
|
|
207
200
|
const manifest = {
|
|
208
201
|
version: packageJson.version,
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import{a as e,c as t,i as n,n as r,o as i,t as a}from"./simple-options-CDIijiMb.js";import{t as o}from"./headers-qDMOQQGF.js";import{f as s,m as c,p as l}from"./index-BVA4YIGJ.js";import{i as u,n as ee,t as d}from"./github-copilot-headers-DGaOrqaW.js";function f(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function p(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var te=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return te=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function m(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var h=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},g=class extends Error{},_=class e extends g{constructor(t,n,r,i,a){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`request-id`),this.error=n,this.type=a??null}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new ne({message:r,cause:h(n)});let a=n,o=a?.error?.type;return t===400?new ie(t,a,r,i,o):t===401?new ae(t,a,r,i,o):t===403?new oe(t,a,r,i,o):t===404?new se(t,a,r,i,o):t===409?new ce(t,a,r,i,o):t===422?new le(t,a,r,i,o):t===429?new ue(t,a,r,i,o):t>=500?new de(t,a,r,i,o):new e(t,a,r,i,o)}},v=class extends _{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},ne=class extends _{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},re=class extends ne{constructor({message:e}={}){super({message:e??`Request timed out.`})}},ie=class extends _{},ae=class extends _{},oe=class extends _{},se=class extends _{},ce=class extends _{},le=class extends _{},ue=class extends _{},de=class extends _{},fe=/^[a-z][a-z0-9+.-]*:/i,pe=e=>fe.test(e),me=e=>(me=Array.isArray,me(e)),he=me;function ge(e){return typeof e==`object`?e??{}:{}}function _e(e){if(!e)return!0;for(let t in e)return!1;return!0}function ve(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var ye=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new g(`${e} must be an integer`);if(t<0)throw new g(`${e} must be a positive integer`);return t},be=e=>{try{return JSON.parse(e)}catch{return}},xe=e=>new Promise(t=>setTimeout(t,e)),y=`0.91.1`,Se=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function Ce(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var we=()=>{let e=Ce();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":De(Deno.build.os),"X-Stainless-Arch":Ee(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":De(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Ee(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Te();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":y,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Te(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var Ee=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,De=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),Oe,ke=()=>Oe??=we();function Ae(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function je(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Me(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return je({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ne(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Pe(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Fe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)});function Ie(e){return Object.entries(e).filter(([e,t])=>t!==void 0).map(([e,t])=>{if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(t===null)return`${encodeURIComponent(e)}=`;throw new g(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join(`&`)}function Le(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Re;function ze(e){let t;return(Re??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Be;function Ve(e){let t;return(Be??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var b,x,He=class{constructor(){b.set(this,void 0),x.set(this,void 0),f(this,b,new Uint8Array,`f`),f(this,x,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?ze(e):e;f(this,b,Le([p(this,b,`f`),t]),`f`);let n=[],r;for(;(r=Ue(p(this,b,`f`),p(this,x,`f`)))!=null;){if(r.carriage&&p(this,x,`f`)==null){f(this,x,r.index,`f`);continue}if(p(this,x,`f`)!=null&&(r.index!==p(this,x,`f`)+1||r.carriage)){n.push(Ve(p(this,b,`f`).subarray(0,p(this,x,`f`)-1))),f(this,b,p(this,b,`f`).subarray(p(this,x,`f`)),`f`),f(this,x,null,`f`);continue}let e=p(this,x,`f`)===null?r.preceding:r.preceding-1,t=Ve(p(this,b,`f`).subarray(0,e));n.push(t),f(this,b,p(this,b,`f`).subarray(r.index),`f`),f(this,x,null,`f`)}return n}flush(){return p(this,b,`f`).length?this.decode(`
|
|
2
|
+
`):[]}};b=new WeakMap,x=new WeakMap,He.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,`\r`]),He.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ue(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function We(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var Ge={off:0,error:200,warn:300,info:400,debug:500},Ke=(e,t,n)=>{if(e){if(ve(Ge,e))return e;S(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ge))}`)}};function qe(){}function Je(e,t,n){return!t||Ge[e]>Ge[n]?qe:t[e].bind(t)}var Ye={error:qe,warn:qe,info:qe,debug:qe},Xe=new WeakMap;function S(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Ye;let r=Xe.get(t);if(r&&r[0]===n)return r[1];let i={error:Je(`error`,t,n),warn:Je(`warn`,t,n),info:Je(`info`,t,n),debug:Je(`debug`,t,n)};return Xe.set(t,[n,i]),i}var C=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`x-api-key`||e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),Ze,Qe=class e{constructor(e,t,n){this.iterator=e,Ze.set(this,void 0),this.controller=t,f(this,Ze,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?S(r):console;async function*o(){if(i)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of $e(t,n)){if(e.event===`completion`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event===`message_start`||e.event===`message_delta`||e.event===`message_stop`||e.event===`content_block_start`||e.event===`content_block_delta`||e.event===`content_block_stop`||e.event===`message`||e.event===`user.message`||e.event===`user.interrupt`||e.event===`user.tool_confirmation`||e.event===`user.custom_tool_result`||e.event===`agent.message`||e.event===`agent.thinking`||e.event===`agent.tool_use`||e.event===`agent.tool_result`||e.event===`agent.mcp_tool_use`||e.event===`agent.mcp_tool_result`||e.event===`agent.custom_tool_use`||e.event===`agent.thread_context_compacted`||e.event===`session.status_running`||e.event===`session.status_idle`||e.event===`session.status_rescheduled`||e.event===`session.status_terminated`||e.event===`session.error`||e.event===`session.deleted`||e.event===`span.model_request_start`||e.event===`span.model_request_end`)try{yield JSON.parse(e.data)}catch(t){throw a.error(`Could not parse message into JSON:`,e.data),a.error(`From chunk:`,e.raw),t}if(e.event!==`ping`&&e.event===`error`){let n=be(e.data)??e.data,r=n?.error?.type;throw new _(void 0,n,void 0,t.headers,r)}}e=!0}catch(e){if(m(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new He,n=Ne(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(m(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Ze=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,p(this,Ze,`f`)),new e(()=>i(n),this.controller,p(this,Ze,`f`))]}toReadableStream(){let e=this,t;return je({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=ze(JSON.stringify(n)+`
|
|
4
|
+
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*$e(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new g(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new g(`Attempted to iterate over a response with no body`);let n=new tt,r=new He,i=Ne(e.body);for await(let e of et(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*et(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?ze(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=We(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var tt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=nt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function nt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function rt(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return S(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):Qe.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:it(await n.json(),n):await n.text()})();return S(e).debug(`[${r}] response parsed`,C({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function it(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`request-id`),enumerable:!1})}var at,ot=class e extends Promise{constructor(e,t,n=rt){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,at.set(this,void 0),f(this,at,e,`f`)}_thenUnwrap(t){return new e(p(this,at,`f`),this.responsePromise,async(e,n)=>it(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(p(this,at,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};at=new WeakMap;var st,ct=class{constructor(e,t,n,r){st.set(this,void 0),f(this,st,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await p(this,st,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(st=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},lt=class extends ot{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await rt(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},w=class extends ct{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let e=this.first_id;return e?{...this.options,query:{...ge(this.options.query),before_id:e}}:null}let e=this.last_id;return e?{...this.options,query:{...ge(this.options.query),after_id:e}}:null}},T=class extends ct{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.next_page=n.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...ge(this.options.query),page:e}}:null}},ut=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function E(e,t,n){return ut(),new File(e,t??`unknown_file`,n)}function dt(e,t){let n=typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``;return t?n.split(/[\\/]/).pop()||void 0:n}var ft=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,pt=async(e,t,n=!0)=>({...e,body:await gt(e.body,t,n)}),mt=new WeakMap;function ht(e){let t=typeof e==`function`?e:e.fetch,n=mt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return mt.set(t,r),r}var gt=async(e,t,n=!0)=>{if(!await ht(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>vt(r,e,t,n))),r},_t=e=>e instanceof Blob&&`name`in e,vt=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i={},a=n.headers.get(`Content-Type`);a&&(i={type:a}),e.append(t,E([await n.blob()],dt(n,r),i))}else if(ft(n))e.append(t,E([await new Response(Me(n)).blob()],dt(n,r)));else if(_t(n))e.append(t,E([n],dt(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(n=>vt(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>vt(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},yt=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,bt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&yt(e),xt=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function St(e,t,n){if(ut(),e=await e,t||=dt(e,!0),bt(e))return e instanceof File&&t==null&&n==null?e:E([await e.arrayBuffer()],t??e.name,{type:e.type,lastModified:e.lastModified,...n});if(xt(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),E(await Ct(r),t,n)}let r=await Ct(e);if(!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return E(r,t,n)}async function Ct(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(yt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(ft(e))for await(let n of e)t.push(...await Ct(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${wt(e)}`)}return t}function wt(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var D=class{constructor(e){this._client=e}},Tt=Symbol.for(`brand.privateNullableHeaders`);function*Et(e){if(!e)return;if(Tt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():he(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=he(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var O=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Et(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Tt]:!0,values:t,nulls:n}};function Dt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Ot=Object.freeze(Object.create(null)),k=((e=Dt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Ot)??Ot)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new g(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
6
|
+
`)}\n${a}\n${t}`)}return a})(Dt),kt=class extends D{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/environments?beta=true`,{body:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/environments/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(k`/v1/environments/${e}?beta=true`,{body:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/environments?beta=true`,T,{query:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(k`/v1/environments/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(k`/v1/environments/${e}/archive?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},At=Symbol(`anthropic.sdk.stainlessHelper`);function jt(e){return typeof e==`object`&&!!e&&At in e}function Mt(e,t){let n=new Set;if(e)for(let t of e)jt(t)&&n.add(t[At]);if(t){for(let e of t)if(jt(e)&&n.add(e[At]),Array.isArray(e.content))for(let t of e.content)jt(t)&&n.add(t[At])}return Array.from(n)}function Nt(e,t){let n=Mt(e,t);return n.length===0?{}:{"x-stainless-helper":n.join(`, `)}}function Pt(e){return jt(e)?{"x-stainless-helper":e[At]}:{}}var Ft=class extends D{list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/files?beta=true`,w,{query:r,...t,headers:O([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(k`/v1/files/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}download(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/files/${e}/content?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString(),Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/files/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`files-api-2025-04-14`].toString()},n?.headers])})}upload(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/files?beta=true`,pt({body:r,...t,headers:O([{"anthropic-beta":[...n??[],`files-api-2025-04-14`].toString()},Pt(r.file),t?.headers])},this._client))}},It=class extends D{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/models/${e}?beta=true`,{...n,headers:O([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models?beta=true`,w,{query:r,...t,headers:O([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},Lt=class extends D{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/user_profiles?beta=true`,{body:r,...t,headers:O([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/user_profiles/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(k`/v1/user_profiles/${e}?beta=true`,{body:i,...n,headers:O([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/user_profiles?beta=true`,T,{query:r,...t,headers:O([{"anthropic-beta":[...n??[],`user-profiles-2026-03-24`].toString()},t?.headers])})}createEnrollmentURL(e,t={},n){let{betas:r}=t??{};return this._client.post(k`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`user-profiles-2026-03-24`].toString()},n?.headers])})}},Rt=class extends D{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(k`/v1/agents/${e}/versions?beta=true`,T,{query:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},zt=class extends D{constructor(){super(...arguments),this.versions=new Rt(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/agents?beta=true`,{body:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(k`/v1/agents/${e}?beta=true`,{query:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(k`/v1/agents/${e}?beta=true`,{body:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/agents?beta=true`,T,{query:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(k`/v1/agents/${e}/archive?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};zt.Versions=Rt;var Bt=class extends D{create(e,t,n){let{view:r,betas:i,...a}=t;return this._client.post(k`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:r},body:a,...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(k`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:a,...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{memory_store_id:r,view:i,betas:a,...o}=t;return this._client.post(k`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{view:i},body:o,...n,headers:O([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(k`/v1/memory_stores/${e}/memories?beta=true`,T,{query:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{memory_store_id:r,expected_content_sha256:i,betas:a}=t;return this._client.delete(k`/v1/memory_stores/${r}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...n,headers:O([{"anthropic-beta":[...a??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Vt=class extends D{retrieve(e,t,n){let{memory_store_id:r,betas:i,...a}=t;return this._client.get(k`/v1/memory_stores/${r}/memory_versions/${e}?beta=true`,{query:a,...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(k`/v1/memory_stores/${e}/memory_versions?beta=true`,T,{query:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}redact(e,t,n){let{memory_store_id:r,betas:i}=t;return this._client.post(k`/v1/memory_stores/${r}/memory_versions/${e}/redact?beta=true`,{...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Ht=class extends D{constructor(){super(...arguments),this.memories=new Bt(this._client),this.memoryVersions=new Vt(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/memory_stores?beta=true`,{body:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/memory_stores/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(k`/v1/memory_stores/${e}?beta=true`,{body:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/memory_stores?beta=true`,T,{query:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(k`/v1/memory_stores/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(k`/v1/memory_stores/${e}/archive?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Ht.Memories=Bt,Ht.MemoryVersions=Vt;var Ut={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function Wt(e){return e?.output_format??e?.output_config?.format}function Gt(e,t,n){let r=Wt(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>{if(e.type===`text`){let t=Object.defineProperty({...e},`parsed_output`,{value:null,enumerable:!1});return Object.defineProperty(t,`parsed`,{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return e}),parsed_output:null}:Kt(e,t,n)}function Kt(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let i=qt(t,e.text);r===null&&(r=i);let a=Object.defineProperty({...e},`parsed_output`,{value:i,enumerable:!1});return Object.defineProperty(a,`parsed`,{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),i},enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function qt(e,t){let n=Wt(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new g(`Failed to parse structured output: ${e}`)}}var Jt=e=>{let t=0,n=[];for(;t<e.length;){let r=e[t];if(r===`\\`){t++;continue}if(r===`{`){n.push({type:`brace`,value:`{`}),t++;continue}if(r===`}`){n.push({type:`brace`,value:`}`}),t++;continue}if(r===`[`){n.push({type:`paren`,value:`[`}),t++;continue}if(r===`]`){n.push({type:`paren`,value:`]`}),t++;continue}if(r===`:`){n.push({type:`separator`,value:`:`}),t++;continue}if(r===`,`){n.push({type:`delimiter`,value:`,`}),t++;continue}if(r===`"`){let i=``,a=!1;for(r=e[++t];r!==`"`;){if(t===e.length){a=!0;break}if(r===`\\`){if(t++,t===e.length){a=!0;break}i+=r+e[t],r=e[++t]}else i+=r,r=e[++t]}r=e[++t],a||n.push({type:`string`,value:i});continue}if(r&&/\s/.test(r)){t++;continue}let i=/[0-9]/;if(r&&i.test(r)||r===`-`||r===`.`){let a=``;for(r===`-`&&(a+=r,r=e[++t]);r&&i.test(r)||r===`.`;)a+=r,r=e[++t];n.push({type:`number`,value:a});continue}let a=/[a-z]/i;if(r&&a.test(r)){let i=``;for(;r&&a.test(r)&&t!==e.length;)i+=r,r=e[++t];if(i==`true`||i==`false`||i===`null`)n.push({type:`name`,value:i});else{t++;continue}continue}t++}return n},Yt=e=>{if(e.length===0)return e;let t=e[e.length-1];switch(t.type){case`separator`:return e=e.slice(0,e.length-1),Yt(e);case`number`:let n=t.value[t.value.length-1];if(n===`.`||n===`-`)return e=e.slice(0,e.length-1),Yt(e);case`string`:let r=e[e.length-2];if(r?.type===`delimiter`||r?.type===`brace`&&r.value===`{`)return e=e.slice(0,e.length-1),Yt(e);break;case`delimiter`:return e=e.slice(0,e.length-1),Yt(e)}return e},Xt=e=>{let t=[];return e.map(e=>{e.type===`brace`&&(e.value===`{`?t.push(`}`):t.splice(t.lastIndexOf(`}`),1)),e.type===`paren`&&(e.value===`[`?t.push(`]`):t.splice(t.lastIndexOf(`]`),1))}),t.length>0&&t.reverse().map(t=>{t===`}`?e.push({type:`brace`,value:`}`}):t===`]`&&e.push({type:`paren`,value:`]`})}),e},Zt=e=>{let t=``;return e.map(e=>{switch(e.type){case`string`:t+=`"`+e.value+`"`;break;default:t+=e.value;break}}),t},Qt=e=>JSON.parse(Zt(Xt(Yt(Jt(e))))),A,j,M,$t,en,N,tn,nn,P,F,I,rn,an,L,on,sn,R,cn,ln,un,dn,fn,pn,mn,hn=`__json_buf`;function gn(e){return e.type===`tool_use`||e.type===`server_tool_use`||e.type===`mcp_tool_use`}var _n=class e{constructor(e,t){A.add(this),this.messages=[],this.receivedMessages=[],j.set(this,void 0),M.set(this,null),this.controller=new AbortController,$t.set(this,void 0),en.set(this,()=>{}),N.set(this,()=>{}),tn.set(this,void 0),nn.set(this,()=>{}),P.set(this,()=>{}),F.set(this,{}),I.set(this,!1),rn.set(this,!1),an.set(this,!1),L.set(this,!1),on.set(this,void 0),sn.set(this,void 0),R.set(this,void 0),un.set(this,e=>{if(f(this,rn,!0,`f`),m(e)&&(e=new v),e instanceof v)return f(this,an,!0,`f`),this._emit(`abort`,e);if(e instanceof g)return this._emit(`error`,e);if(e instanceof Error){let t=new g(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new g(String(e)))}),f(this,$t,new Promise((e,t)=>{f(this,en,e,`f`),f(this,N,t,`f`)}),`f`),f(this,tn,new Promise((e,t)=>{f(this,nn,e,`f`),f(this,P,t,`f`)}),`f`),p(this,$t,`f`).catch(()=>{}),p(this,tn,`f`).catch(()=>{}),f(this,M,e,`f`),f(this,R,t?.logger??console,`f`)}get response(){return p(this,on,`f`)}get request_id(){return p(this,sn,`f`)}async withResponse(){f(this,L,!0,`f`);let e=await p(this,$t,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return f(a,M,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},p(this,un,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{p(this,A,`m`,dn).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)p(this,A,`m`,fn).call(this,e);if(i.controller.signal?.aborted)throw new v;p(this,A,`m`,pn).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(f(this,on,e,`f`),f(this,sn,e?.headers.get(`request-id`),`f`),p(this,en,`f`).call(this,e),this._emit(`connect`))}get ended(){return p(this,I,`f`)}get errored(){return p(this,rn,`f`)}get aborted(){return p(this,an,`f`)}abort(){this.controller.abort()}on(e,t){return(p(this,F,`f`)[e]||(p(this,F,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=p(this,F,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(p(this,F,`f`)[e]||(p(this,F,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{f(this,L,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){f(this,L,!0,`f`),await p(this,tn,`f`)}get currentMessage(){return p(this,j,`f`)}async finalMessage(){return await this.done(),p(this,A,`m`,cn).call(this)}async finalText(){return await this.done(),p(this,A,`m`,ln).call(this)}_emit(e,...t){if(p(this,I,`f`))return;e===`end`&&(f(this,I,!0,`f`),p(this,nn,`f`).call(this));let n=p(this,F,`f`)[e];if(n&&(p(this,F,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!p(this,L,`f`)&&!n?.length&&Promise.reject(e),p(this,N,`f`).call(this,e),p(this,P,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!p(this,L,`f`)&&!n?.length&&Promise.reject(e),p(this,N,`f`).call(this,e),p(this,P,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,p(this,A,`m`,cn).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{p(this,A,`m`,dn).call(this),this._connected(null);let t=Qe.fromReadableStream(e,this.controller);for await(let e of t)p(this,A,`m`,fn).call(this,e);if(t.controller.signal?.aborted)throw new v;p(this,A,`m`,pn).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(j=new WeakMap,M=new WeakMap,$t=new WeakMap,en=new WeakMap,N=new WeakMap,tn=new WeakMap,nn=new WeakMap,P=new WeakMap,F=new WeakMap,I=new WeakMap,rn=new WeakMap,an=new WeakMap,L=new WeakMap,on=new WeakMap,sn=new WeakMap,R=new WeakMap,un=new WeakMap,A=new WeakSet,cn=function(){if(this.receivedMessages.length===0)throw new g(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},ln=function(){if(this.receivedMessages.length===0)throw new g(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new g(`stream ended without producing a content block with type=text`);return e.join(` `)},dn=function(){this.ended||f(this,j,void 0,`f`)},fn=function(e){if(this.ended)return;let t=p(this,A,`m`,mn).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:gn(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;case`compaction_delta`:n.type===`compaction`&&n.content&&this._emit(`compaction`,n.content);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(Gt(t,p(this,M,`f`),{logger:p(this,R,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:f(this,j,t,`f`);break;case`content_block_start`:case`message_delta`:break}},pn=function(){if(this.ended)throw new g(`stream has ended, this shouldn't happen`);let e=p(this,j,`f`);if(!e)throw new g(`request ended without sending any chunks`);return f(this,j,void 0,`f`),Gt(e,p(this,M,`f`),{logger:p(this,R,`f`)})},mn=function(e){let t=p(this,j,`f`);if(e.type===`message_start`){if(t)throw new g(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new g(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.container=e.delta.container,t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,t.context_management=e.context_management,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),e.usage.iterations!=null&&(t.usage.iterations=e.usage.iterations),t;case`content_block_start`:return t.content.push(e.content_block),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&gn(n)){let r=n[hn]||``;r+=e.delta.partial_json;let i={...n};if(Object.defineProperty(i,hn,{value:r,enumerable:!1,writable:!0}),r)try{i.input=Qt(r)}catch(e){let t=new g(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${e}. JSON: ${r}`);p(this,un,`f`).call(this,t)}t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;case`compaction_delta`:n?.type===`compaction`&&(t.content[e.index]={...n,content:(n.content||``)+e.delta.content});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Qe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},vn=class extends Error{constructor(e){let t=typeof e==`string`?e:e.map(e=>e.type===`text`?e.text:`[${e.type}]`).join(` `);super(t),this.name=`ToolError`,this.content=e}},yn=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
|
|
7
|
+
1. Task Overview
|
|
8
|
+
The user's core request and success criteria
|
|
9
|
+
Any clarifications or constraints they specified
|
|
10
|
+
2. Current State
|
|
11
|
+
What has been completed so far
|
|
12
|
+
Files created, modified, or analyzed (with paths if relevant)
|
|
13
|
+
Key outputs or artifacts produced
|
|
14
|
+
3. Important Discoveries
|
|
15
|
+
Technical constraints or requirements uncovered
|
|
16
|
+
Decisions made and their rationale
|
|
17
|
+
Errors encountered and how they were resolved
|
|
18
|
+
What approaches were tried that didn't work (and why)
|
|
19
|
+
4. Next Steps
|
|
20
|
+
Specific actions needed to complete the task
|
|
21
|
+
Any blockers or open questions to resolve
|
|
22
|
+
Priority order if multiple steps remain
|
|
23
|
+
5. Context to Preserve
|
|
24
|
+
User preferences or style requirements
|
|
25
|
+
Domain-specific details that aren't obvious
|
|
26
|
+
Any promises made to the user
|
|
27
|
+
Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
|
|
28
|
+
Wrap your summary in <summary></summary> tags.`,bn,z,B,V,H,U,W,G,xn,Sn,Cn;function wn(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}var Tn=class{constructor(e,t,n){bn.add(this),this.client=e,z.set(this,!1),B.set(this,!1),V.set(this,void 0),H.set(this,void 0),U.set(this,void 0),W.set(this,void 0),G.set(this,void 0),xn.set(this,0),f(this,V,{params:{...t,messages:structuredClone(t.messages)}},`f`);let r=[`BetaToolRunner`,...Mt(t.tools,t.messages)].join(`, `);f(this,H,{...n,headers:O([{"x-stainless-helper":r},n?.headers])},`f`),f(this,G,wn(),`f`),t.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[(z=new WeakMap,B=new WeakMap,V=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,G=new WeakMap,xn=new WeakMap,bn=new WeakSet,Sn=async function(){let e=p(this,V,`f`).params.compactionControl;if(!e||!e.enabled)return!1;let t=0;if(p(this,U,`f`)!==void 0)try{let e=await p(this,U,`f`);t=e.usage.input_tokens+(e.usage.cache_creation_input_tokens??0)+(e.usage.cache_read_input_tokens??0)+e.usage.output_tokens}catch{return!1}let n=e.contextTokenThreshold??1e5;if(t<n)return!1;let r=e.model??p(this,V,`f`).params.model,i=e.summaryPrompt??yn,a=p(this,V,`f`).params.messages;if(a[a.length-1].role===`assistant`){let e=a[a.length-1];if(Array.isArray(e.content)){let t=e.content.filter(e=>e.type!==`tool_use`);t.length===0?a.pop():e.content=t}}let o=await this.client.beta.messages.create({model:r,messages:[...a,{role:`user`,content:[{type:`text`,text:i}]}],max_tokens:p(this,V,`f`).params.max_tokens},{signal:p(this,H,`f`).signal,headers:O([p(this,H,`f`).headers,{"x-stainless-helper":`compaction`}])});if(o.content[0]?.type!==`text`)throw new g(`Expected text response for compaction`);return p(this,V,`f`).params.messages=[{role:`user`,content:o.content}],!0},Symbol.asyncIterator)](){var e;if(p(this,z,`f`))throw new g(`Cannot iterate over a consumed stream`);f(this,z,!0,`f`),f(this,B,!0,`f`),f(this,W,void 0,`f`);try{for(;;){let t;try{if(p(this,V,`f`).params.max_iterations&&p(this,xn,`f`)>=p(this,V,`f`).params.max_iterations)break;f(this,B,!1,`f`),f(this,W,void 0,`f`),f(this,xn,(e=p(this,xn,`f`),e++,e),`f`),f(this,U,void 0,`f`);let{max_iterations:n,compactionControl:r,...i}=p(this,V,`f`).params;if(i.stream?(t=this.client.beta.messages.stream({...i},p(this,H,`f`)),f(this,U,t.finalMessage(),`f`),p(this,U,`f`).catch(()=>{}),yield t):(f(this,U,this.client.beta.messages.create({...i,stream:!1},p(this,H,`f`)),`f`),yield p(this,U,`f`)),!await p(this,bn,`m`,Sn).call(this)){if(!p(this,B,`f`)){let{role:e,content:t}=await p(this,U,`f`);p(this,V,`f`).params.messages.push({role:e,content:t})}let e=await p(this,bn,`m`,Cn).call(this,p(this,V,`f`).params.messages.at(-1));if(e)p(this,V,`f`).params.messages.push(e);else if(!p(this,B,`f`))break}}finally{t&&t.abort()}}if(!p(this,U,`f`))throw new g(`ToolRunner concluded without a message from the server`);p(this,G,`f`).resolve(await p(this,U,`f`))}catch(e){throw f(this,z,!1,`f`),p(this,G,`f`).promise.catch(()=>{}),p(this,G,`f`).reject(e),f(this,G,wn(),`f`),e}}setMessagesParams(e){typeof e==`function`?p(this,V,`f`).params=e(p(this,V,`f`).params):p(this,V,`f`).params=e,f(this,B,!0,`f`),f(this,W,void 0,`f`)}setRequestOptions(e){typeof e==`function`?f(this,H,e(p(this,H,`f`)),`f`):f(this,H,{...p(this,H,`f`),...e},`f`)}async generateToolResponse(e=p(this,H,`f`).signal){let t=await p(this,U,`f`)??this.params.messages.at(-1);return t?p(this,bn,`m`,Cn).call(this,t,e):null}done(){return p(this,G,`f`).promise}async runUntilDone(){if(!p(this,z,`f`))for await(let e of this);return this.done()}get params(){return p(this,V,`f`).params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};Cn=async function(e,t=p(this,H,`f`).signal){return p(this,W,`f`)===void 0&&f(this,W,En(p(this,V,`f`).params,e,{...p(this,H,`f`),signal:t}),`f`),p(this,W,`f`)};async function En(e,t=e.messages.at(-1),n){if(!t||t.role!==`assistant`||!t.content||typeof t.content==`string`)return null;let r=t.content.filter(e=>e.type===`tool_use`);return r.length===0?null:{role:`user`,content:await Promise.all(r.map(async t=>{let r=e.tools.find(e=>(`name`in e?e.name:e.mcp_server_name)===t.name);if(!r||!(`run`in r))return{type:`tool_result`,tool_use_id:t.id,content:`Error: Tool '${t.name}' not found`,is_error:!0};try{let e=t.input;`parse`in r&&r.parse&&(e=r.parse(e));let i=await r.run(e,{toolUseBlock:t,signal:n?.signal});return{type:`tool_result`,tool_use_id:t.id,content:i}}catch(e){return{type:`tool_result`,tool_use_id:t.id,content:e instanceof vn?e.content:`Error: ${e instanceof Error?e.message:String(e)}`,is_error:!0}}}))}}var Dn=class e{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){let e=new He;for await(let t of this.iterator)for(let n of e.decode(t))yield JSON.parse(n);for(let t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(t,n){if(!t.body)throw n.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new g(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new g(`Attempted to iterate over a response with no body`);return new e(Ne(t.body),n)}},On=class extends D{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/messages/batches?beta=true`,{body:r,...t,headers:O([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/messages/batches/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/messages/batches?beta=true`,w,{query:r,...t,headers:O([{"anthropic-beta":[...n??[],`message-batches-2024-09-24`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(k`/v1/messages/batches/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(k`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`message-batches-2024-09-24`].toString()},n?.headers])})}async results(e,t={},n){let r=await this.retrieve(e);if(!r.results_url)throw new g(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);let{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:O([{"anthropic-beta":[...i??[],`message-batches-2024-09-24`].toString(),Accept:`application/binary`},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Dn.fromResponse(t.response,t.controller))}},kn={"claude-1.3":`November 6th, 2024`,"claude-1.3-100k":`November 6th, 2024`,"claude-instant-1.1":`November 6th, 2024`,"claude-instant-1.1-100k":`November 6th, 2024`,"claude-instant-1.2":`November 6th, 2024`,"claude-3-sonnet-20240229":`July 21st, 2025`,"claude-3-opus-20240229":`January 5th, 2026`,"claude-2.1":`July 21st, 2025`,"claude-2.0":`July 21st, 2025`,"claude-3-7-sonnet-latest":`February 19th, 2026`,"claude-3-7-sonnet-20250219":`February 19th, 2026`},An=[`claude-mythos-preview`,`claude-opus-4-6`],jn=class extends D{constructor(){super(...arguments),this.batches=new On(this._client)}create(e,t){let n=Mn(e),{betas:r,...i}=n;i.model in kn&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${kn[i.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),An.includes(i.model)&&i.thinking&&i.thinking.type===`enabled`&&console.warn(`Using Claude with ${i.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let a=this._client._options.timeout;if(!i.stream&&a==null){let e=Ut[i.model]??void 0;a=this._client.calculateNonstreamingTimeout(i.max_tokens,e)}let o=Nt(i.tools,i.messages);return this._client.post(`/v1/messages?beta=true`,{body:i,timeout:a??6e5,...t,headers:O([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},o,t?.headers]),stream:n.stream??!1})}parse(e,t){return t={...t,headers:O([{"anthropic-beta":[...e.betas??[],`structured-outputs-2025-12-15`].toString()},t?.headers])},this.create(e,t).then(t=>Kt(t,e,{logger:this._client.logger??console}))}stream(e,t){return _n.createMessage(this,e,t)}countTokens(e,t){let{betas:n,...r}=Mn(e);return this._client.post(`/v1/messages/count_tokens?beta=true`,{body:r,...t,headers:O([{"anthropic-beta":[...n??[],`token-counting-2024-11-01`].toString()},t?.headers])})}toolRunner(e,t){return new Tn(this._client,e,t)}};function Mn(e){if(!e.output_format)return e;if(e.output_config?.format)throw new g(`Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).`);let{output_format:t,...n}=e;return{...n,output_config:{...e.output_config,format:t}}}jn.Batches=On,jn.BetaToolRunner=Tn,jn.ToolError=vn;var Nn=class extends D{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(k`/v1/sessions/${e}/events?beta=true`,T,{query:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}send(e,t,n){let{betas:r,...i}=t;return this._client.post(k`/v1/sessions/${e}/events?beta=true`,{body:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}stream(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/sessions/${e}/events/stream?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers]),stream:!0})}},Pn=class extends D{retrieve(e,t,n){let{session_id:r,betas:i}=t;return this._client.get(k`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{session_id:r,betas:i,...a}=t;return this._client.post(k`/v1/sessions/${r}/resources/${e}?beta=true`,{body:a,...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(k`/v1/sessions/${e}/resources?beta=true`,T,{query:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{session_id:r,betas:i}=t;return this._client.delete(k`/v1/sessions/${r}/resources/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}add(e,t,n){let{betas:r,...i}=t;return this._client.post(k`/v1/sessions/${e}/resources?beta=true`,{body:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},Fn=class extends D{constructor(){super(...arguments),this.events=new Nn(this._client),this.resources=new Pn(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/sessions?beta=true`,{body:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/sessions/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(k`/v1/sessions/${e}?beta=true`,{body:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/sessions?beta=true`,T,{query:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(k`/v1/sessions/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(k`/v1/sessions/${e}/archive?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};Fn.Events=Nn,Fn.Resources=Pn;var In=class extends D{create(e,t={},n){let{betas:r,...i}=t??{};return this._client.post(k`/v1/skills/${e}/versions?beta=true`,pt({body:i,...n,headers:O([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])},this._client))}retrieve(e,t,n){let{skill_id:r,betas:i}=t;return this._client.get(k`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(k`/v1/skills/${e}/versions?beta=true`,T,{query:i,...n,headers:O([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}delete(e,t,n){let{skill_id:r,betas:i}=t;return this._client.delete(k`/v1/skills/${r}/versions/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...i??[],`skills-2025-10-02`].toString()},n?.headers])})}},Ln=class extends D{constructor(){super(...arguments),this.versions=new In(this._client)}create(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/v1/skills?beta=true`,pt({body:r,...t,headers:O([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/skills/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/skills?beta=true`,T,{query:r,...t,headers:O([{"anthropic-beta":[...n??[],`skills-2025-10-02`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(k`/v1/skills/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`skills-2025-10-02`].toString()},n?.headers])})}};Ln.Versions=In;var Rn=class extends D{create(e,t,n){let{betas:r,...i}=t;return this._client.post(k`/v1/vaults/${e}/credentials?beta=true`,{body:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}retrieve(e,t,n){let{vault_id:r,betas:i}=t;return this._client.get(k`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{vault_id:r,betas:i,...a}=t;return this._client.post(k`/v1/vaults/${r}/credentials/${e}?beta=true`,{body:a,...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(k`/v1/vaults/${e}/credentials?beta=true`,T,{query:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}delete(e,t,n){let{vault_id:r,betas:i}=t;return this._client.delete(k`/v1/vaults/${r}/credentials/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t,n){let{vault_id:r,betas:i}=t;return this._client.post(k`/v1/vaults/${r}/credentials/${e}/archive?beta=true`,{...n,headers:O([{"anthropic-beta":[...i??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}},zn=class extends D{constructor(){super(...arguments),this.credentials=new Rn(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/vaults?beta=true`,{body:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/vaults/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}update(e,t,n){let{betas:r,...i}=t;return this._client.post(k`/v1/vaults/${e}?beta=true`,{body:i,...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/vaults?beta=true`,T,{query:r,...t,headers:O([{"anthropic-beta":[...n??[],`managed-agents-2026-04-01`].toString()},t?.headers])})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(k`/v1/vaults/${e}?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}archive(e,t={},n){let{betas:r}=t??{};return this._client.post(k`/v1/vaults/${e}/archive?beta=true`,{...n,headers:O([{"anthropic-beta":[...r??[],`managed-agents-2026-04-01`].toString()},n?.headers])})}};zn.Credentials=Rn;var K=class extends D{constructor(){super(...arguments),this.models=new It(this._client),this.messages=new jn(this._client),this.agents=new zt(this._client),this.environments=new kt(this._client),this.sessions=new Fn(this._client),this.vaults=new zn(this._client),this.memoryStores=new Ht(this._client),this.files=new Ft(this._client),this.skills=new Ln(this._client),this.userProfiles=new Lt(this._client)}};K.Models=It,K.Messages=jn,K.Agents=zt,K.Environments=kt,K.Sessions=Fn,K.Vaults=zn,K.MemoryStores=Ht,K.Files=Ft,K.Skills=Ln,K.UserProfiles=Lt;var Bn=class extends D{create(e,t){let{betas:n,...r}=e;return this._client.post(`/v1/complete`,{body:r,timeout:this._client._options.timeout??6e5,...t,headers:O([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers]),stream:e.stream??!1})}};function Vn(e){return e?.output_config?.format}function Hn(e,t,n){let r=Vn(t);return!t||!(`parse`in(r??{}))?{...e,content:e.content.map(e=>e.type===`text`?Object.defineProperty({...e},`parsed_output`,{value:null,enumerable:!1}):e),parsed_output:null}:Un(e,t,n)}function Un(e,t,n){let r=null,i=e.content.map(e=>{if(e.type===`text`){let n=Wn(t,e.text);return r===null&&(r=n),Object.defineProperty({...e},`parsed_output`,{value:n,enumerable:!1})}return e});return{...e,content:i,parsed_output:r}}function Wn(e,t){let n=Vn(e);if(n?.type!==`json_schema`)return null;try{return`parse`in n?n.parse(t):JSON.parse(t)}catch(e){throw new g(`Failed to parse structured output: ${e}`)}}var q,J,Y,Gn,Kn,qn,Jn,Yn,Xn,X,Zn,Qn,$n,Z,er,tr,nr,rr,ir,ar,or,sr,cr,lr,ur=`__json_buf`;function dr(e){return e.type===`tool_use`||e.type===`server_tool_use`}var fr=class e{constructor(e,t){q.add(this),this.messages=[],this.receivedMessages=[],J.set(this,void 0),Y.set(this,null),this.controller=new AbortController,Gn.set(this,void 0),Kn.set(this,()=>{}),qn.set(this,()=>{}),Jn.set(this,void 0),Yn.set(this,()=>{}),Xn.set(this,()=>{}),X.set(this,{}),Zn.set(this,!1),Qn.set(this,!1),$n.set(this,!1),Z.set(this,!1),er.set(this,void 0),tr.set(this,void 0),nr.set(this,void 0),ar.set(this,e=>{if(f(this,Qn,!0,`f`),m(e)&&(e=new v),e instanceof v)return f(this,$n,!0,`f`),this._emit(`abort`,e);if(e instanceof g)return this._emit(`error`,e);if(e instanceof Error){let t=new g(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new g(String(e)))}),f(this,Gn,new Promise((e,t)=>{f(this,Kn,e,`f`),f(this,qn,t,`f`)}),`f`),f(this,Jn,new Promise((e,t)=>{f(this,Yn,e,`f`),f(this,Xn,t,`f`)}),`f`),p(this,Gn,`f`).catch(()=>{}),p(this,Jn,`f`).catch(()=>{}),f(this,Y,e,`f`),f(this,nr,t?.logger??console,`f`)}get response(){return p(this,er,`f`)}get request_id(){return p(this,tr,`f`)}async withResponse(){f(this,Z,!0,`f`);let e=await p(this,Gn,`f`);if(!e)throw Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get(`request-id`)}}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createMessage(t,n,r,{logger:i}={}){let a=new e(n,{logger:i});for(let e of n.messages)a._addMessageParam(e);return f(a,Y,{...n,stream:!0},`f`),a._run(()=>a._createMessage(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),a}_run(e){e().then(()=>{this._emitFinal(),this._emit(`end`)},p(this,ar,`f`))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit(`message`,e)}async _createMessage(e,t,n){let r=n?.signal,i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener(`abort`,i));try{p(this,q,`m`,or).call(this);let{response:r,data:i}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(r);for await(let e of i)p(this,q,`m`,sr).call(this,e);if(i.controller.signal?.aborted)throw new v;p(this,q,`m`,cr).call(this)}finally{r&&i&&r.removeEventListener(`abort`,i)}}_connected(e){this.ended||(f(this,er,e,`f`),f(this,tr,e?.headers.get(`request-id`),`f`),p(this,Kn,`f`).call(this,e),this._emit(`connect`))}get ended(){return p(this,Zn,`f`)}get errored(){return p(this,Qn,`f`)}get aborted(){return p(this,$n,`f`)}abort(){this.controller.abort()}on(e,t){return(p(this,X,`f`)[e]||(p(this,X,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=p(this,X,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(p(this,X,`f`)[e]||(p(this,X,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{f(this,Z,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){f(this,Z,!0,`f`),await p(this,Jn,`f`)}get currentMessage(){return p(this,J,`f`)}async finalMessage(){return await this.done(),p(this,q,`m`,rr).call(this)}async finalText(){return await this.done(),p(this,q,`m`,ir).call(this)}_emit(e,...t){if(p(this,Zn,`f`))return;e===`end`&&(f(this,Zn,!0,`f`),p(this,Yn,`f`).call(this));let n=p(this,X,`f`)[e];if(n&&(p(this,X,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!p(this,Z,`f`)&&!n?.length&&Promise.reject(e),p(this,qn,`f`).call(this,e),p(this,Xn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!p(this,Z,`f`)&&!n?.length&&Promise.reject(e),p(this,qn,`f`).call(this,e),p(this,Xn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit(`finalMessage`,p(this,q,`m`,rr).call(this))}async _fromReadableStream(e,t){let n=t?.signal,r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener(`abort`,r));try{p(this,q,`m`,or).call(this),this._connected(null);let t=Qe.fromReadableStream(e,this.controller);for await(let e of t)p(this,q,`m`,sr).call(this,e);if(t.controller.signal?.aborted)throw new v;p(this,q,`m`,cr).call(this)}finally{n&&r&&n.removeEventListener(`abort`,r)}}[(J=new WeakMap,Y=new WeakMap,Gn=new WeakMap,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,X=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,Z=new WeakMap,er=new WeakMap,tr=new WeakMap,nr=new WeakMap,ar=new WeakMap,q=new WeakSet,rr=function(){if(this.receivedMessages.length===0)throw new g(`stream ended without producing a Message with role=assistant`);return this.receivedMessages.at(-1)},ir=function(){if(this.receivedMessages.length===0)throw new g(`stream ended without producing a Message with role=assistant`);let e=this.receivedMessages.at(-1).content.filter(e=>e.type===`text`).map(e=>e.text);if(e.length===0)throw new g(`stream ended without producing a content block with type=text`);return e.join(` `)},or=function(){this.ended||f(this,J,void 0,`f`)},sr=function(e){if(this.ended)return;let t=p(this,q,`m`,lr).call(this,e);switch(this._emit(`streamEvent`,e,t),e.type){case`content_block_delta`:{let n=t.content.at(-1);switch(e.delta.type){case`text_delta`:n.type===`text`&&this._emit(`text`,e.delta.text,n.text||``);break;case`citations_delta`:n.type===`text`&&this._emit(`citation`,e.delta.citation,n.citations??[]);break;case`input_json_delta`:dr(n)&&n.input&&this._emit(`inputJson`,e.delta.partial_json,n.input);break;case`thinking_delta`:n.type===`thinking`&&this._emit(`thinking`,e.delta.thinking,n.thinking);break;case`signature_delta`:n.type===`thinking`&&this._emit(`signature`,n.signature);break;default:e.delta}break}case`message_stop`:this._addMessageParam(t),this._addMessage(Hn(t,p(this,Y,`f`),{logger:p(this,nr,`f`)}),!0);break;case`content_block_stop`:this._emit(`contentBlock`,t.content.at(-1));break;case`message_start`:f(this,J,t,`f`);break;case`content_block_start`:case`message_delta`:break}},cr=function(){if(this.ended)throw new g(`stream has ended, this shouldn't happen`);let e=p(this,J,`f`);if(!e)throw new g(`request ended without sending any chunks`);return f(this,J,void 0,`f`),Hn(e,p(this,Y,`f`),{logger:p(this,nr,`f`)})},lr=function(e){let t=p(this,J,`f`);if(e.type===`message_start`){if(t)throw new g(`Unexpected event order, got ${e.type} before receiving "message_stop"`);return e.message}if(!t)throw new g(`Unexpected event order, got ${e.type} before "message_start"`);switch(e.type){case`message_stop`:return t;case`message_delta`:return t.stop_reason=e.delta.stop_reason,t.stop_sequence=e.delta.stop_sequence,t.usage.output_tokens=e.usage.output_tokens,e.usage.input_tokens!=null&&(t.usage.input_tokens=e.usage.input_tokens),e.usage.cache_creation_input_tokens!=null&&(t.usage.cache_creation_input_tokens=e.usage.cache_creation_input_tokens),e.usage.cache_read_input_tokens!=null&&(t.usage.cache_read_input_tokens=e.usage.cache_read_input_tokens),e.usage.server_tool_use!=null&&(t.usage.server_tool_use=e.usage.server_tool_use),t;case`content_block_start`:return t.content.push({...e.content_block}),t;case`content_block_delta`:{let n=t.content.at(e.index);switch(e.delta.type){case`text_delta`:n?.type===`text`&&(t.content[e.index]={...n,text:(n.text||``)+e.delta.text});break;case`citations_delta`:n?.type===`text`&&(t.content[e.index]={...n,citations:[...n.citations??[],e.delta.citation]});break;case`input_json_delta`:if(n&&dr(n)){let r=n[ur]||``;r+=e.delta.partial_json;let i={...n};Object.defineProperty(i,ur,{value:r,enumerable:!1,writable:!0}),r&&(i.input=Qt(r)),t.content[e.index]=i}break;case`thinking_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,thinking:n.thinking+e.delta.thinking});break;case`signature_delta`:n?.type===`thinking`&&(t.content[e.index]={...n,signature:e.delta.signature});break;default:e.delta}return t}case`content_block_stop`:return t}},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`streamEvent`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Qe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}},pr=class extends D{create(e,t){return this._client.post(`/v1/messages/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(k`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/v1/messages/batches`,w,{query:e,...t})}delete(e,t){return this._client.delete(k`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(k`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){let n=await this.retrieve(e);if(!n.results_url)throw new g(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:O([{Accept:`application/binary`},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((e,t)=>Dn.fromResponse(t.response,t.controller))}},mr=class extends D{constructor(){super(...arguments),this.batches=new pr(this._client)}create(e,t){e.model in hr&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${hr[e.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),gr.includes(e.model)&&e.thinking&&e.thinking.type===`enabled`&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let n=this._client._options.timeout;if(!e.stream&&n==null){let t=Ut[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,t)}let r=Nt(e.tools,e.messages);return this._client.post(`/v1/messages`,{body:e,timeout:n??6e5,...t,headers:O([r,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(t=>Un(t,e,{logger:this._client.logger??console}))}stream(e,t){return fr.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post(`/v1/messages/count_tokens`,{body:e,...t})}},hr={"claude-1.3":`November 6th, 2024`,"claude-1.3-100k":`November 6th, 2024`,"claude-instant-1.1":`November 6th, 2024`,"claude-instant-1.1-100k":`November 6th, 2024`,"claude-instant-1.2":`November 6th, 2024`,"claude-3-sonnet-20240229":`July 21st, 2025`,"claude-3-opus-20240229":`January 5th, 2026`,"claude-2.1":`July 21st, 2025`,"claude-2.0":`July 21st, 2025`,"claude-3-7-sonnet-latest":`February 19th, 2026`,"claude-3-7-sonnet-20250219":`February 19th, 2026`,"claude-3-5-haiku-latest":`February 19th, 2026`,"claude-3-5-haiku-20241022":`February 19th, 2026`,"claude-opus-4-0":`June 15th, 2026`,"claude-opus-4-20250514":`June 15th, 2026`,"claude-sonnet-4-0":`June 15th, 2026`,"claude-sonnet-4-20250514":`June 15th, 2026`},gr=[`claude-mythos-preview`,`claude-opus-4-6`];mr.Batches=pr;var _r=class extends D{retrieve(e,t={},n){let{betas:r}=t??{};return this._client.get(k`/v1/models/${e}`,{...n,headers:O([{...r?.toString()==null?void 0:{"anthropic-beta":r?.toString()}},n?.headers])})}list(e={},t){let{betas:n,...r}=e??{};return this._client.getAPIList(`/v1/models`,w,{query:r,...t,headers:O([{...n?.toString()==null?void 0:{"anthropic-beta":n?.toString()}},t?.headers])})}},vr=e=>{if(globalThis.process!==void 0)return{}?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},yr,br,xr,Sr,Cr=`\\n\\nHuman:`,wr=`\\n\\nAssistant:`,Q=class{constructor({baseURL:e=vr(`ANTHROPIC_BASE_URL`),apiKey:t=vr(`ANTHROPIC_API_KEY`)??null,authToken:n=vr(`ANTHROPIC_AUTH_TOKEN`)??null,...r}={}){yr.add(this),xr.set(this,void 0);let i={apiKey:t,authToken:n,...r,baseURL:e||`https://api.anthropic.com`};if(!i.dangerouslyAllowBrowser&&Se())throw new g(`It looks like you're running in a browser-like environment.
|
|
29
|
+
|
|
30
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
31
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
32
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
33
|
+
|
|
34
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
35
|
+
`);this.baseURL=i.baseURL,this.timeout=i.timeout??br.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=Ke(i.logLevel,`ClientOptions.logLevel`,this)??Ke(vr(`ANTHROPIC_LOG`),`process.env['ANTHROPIC_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Ae(),f(this,xr,Fe,`f`),this._options=i,this.apiKey=typeof t==`string`?t:null,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.get(`x-api-key`)||e.get(`authorization`))&&!(this.apiKey&&e.get(`x-api-key`))&&!t.has(`x-api-key`)&&!(this.authToken&&e.get(`authorization`))&&!t.has(`authorization`))throw Error(`Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted`)}async authHeaders(e){return O([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return O([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return O([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Ie(e)}getUserAgent(){return`${this.constructor.name}/JS ${y}`}defaultIdempotencyKey(){return`stainless-node-retry-${te()}`}makeStatusError(e,t,n,r){return _.generate(e,t,n,r)}buildURL(e,t,n){let r=!p(this,yr,`m`,Sr).call(this)&&n||this.baseURL,i=pe(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!_e(a)||!_e(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new g(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details`);return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ot(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(S(this).debug(`[${c}] sending request`,C({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new v;let ee=new AbortController,d=await this.fetchWithTimeout(o,a,s,ee).catch(h),f=Date.now();if(d instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new v;let i=m(d)||/timed? ?out/i.test(String(d)+(`cause`in d?String(d.cause):``));if(t)return S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),this.retryRequest(r,t,n??c);throw S(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),S(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,C({retryOfRequestLogID:n,url:o,durationMs:f-u,message:d.message})),i?new re:new ne({cause:d})}let p=`[${c}${l}${[...d.headers.entries()].filter(([e])=>e===`request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${d.ok?`succeeded`:`failed`} with status ${d.status} in ${f-u}ms`;if(!d.ok){let e=await this.shouldRetry(d);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Pe(d.body),S(this).info(`${p} - ${e}`),S(this).debug(`[${c}] response error (${e})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),this.retryRequest(r,t,n??c,d.headers)}let i=e?`error; no more retries left`:`error; not retryable`;S(this).info(`${p} - ${i}`);let a=await d.text().catch(e=>h(e).message),o=be(a),s=o?void 0:a;throw S(this).debug(`[${c}] response error (${i})`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(d.status,o,s,d.headers)}return S(this).info(p),S(this).debug(`[${c}] response start`,C({retryOfRequestLogID:n,url:d.url,status:d.status,headers:d.headers,durationMs:f-u})),{response:d,options:r,controller:ee,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new lt(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await xe(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}calculateNonstreamingTimeout(e,t){let n=600*1e3;if(36e5*e/128e3>n||t!=null&&e>t)throw new g(`Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details`);return n}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ye(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=O([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ke(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":`true`}:void 0,"anthropic-version":`2023-06-01`},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=O([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:Me(e)}:typeof e==`object`&&n.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:p(this,xr,`f`).call(this,{body:e,headers:n})}};br=Q,xr=new WeakMap,yr=new WeakSet,Sr=function(){return this.baseURL!==`https://api.anthropic.com`},Q.Anthropic=br,Q.HUMAN_PROMPT=Cr,Q.AI_PROMPT=wr,Q.DEFAULT_TIMEOUT=6e5,Q.AnthropicError=g,Q.APIError=_,Q.APIConnectionError=ne,Q.APIConnectionTimeoutError=re,Q.APIUserAbortError=v,Q.NotFoundError=se,Q.ConflictError=ce,Q.RateLimitError=ue,Q.BadRequestError=ie,Q.AuthenticationError=ae,Q.InternalServerError=de,Q.PermissionDeniedError=oe,Q.UnprocessableEntityError=le,Q.toFile=St;var $=class extends Q{constructor(){super(...arguments),this.completions=new Bn(this),this.messages=new mr(this),this.models=new _r(this),this.beta=new K(this)}};$.Completions=Bn,$.Messages=mr,$.Models=_r,$.Beta=K;function Tr(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function Er(e,t){let n=Tr(t);if(n===`none`)return{retention:n};let r=n===`long`&&Pr(e).supportsLongCacheRetention?`1h`:void 0;return{retention:n,cacheControl:{type:`ephemeral`,...r&&{ttl:r}}}}var Dr=`2.1.75`,Or=new Map([`Read`,`Write`,`Edit`,`Bash`,`Grep`,`Glob`,`AskUserQuestion`,`EnterPlanMode`,`ExitPlanMode`,`KillShell`,`NotebookEdit`,`Skill`,`Task`,`TaskOutput`,`TodoWrite`,`WebFetch`,`WebSearch`].map(e=>[e.toLowerCase(),e])),kr=e=>Or.get(e.toLowerCase())??e,Ar=(e,t)=>{if(t&&t.length>0){let n=e.toLowerCase(),r=t.find(e=>e.name.toLowerCase()===n);if(r)return r.name}return e};function jr(t){if(!t.some(e=>e.type===`image`))return e(t.map(e=>e.text).join(`
|
|
36
|
+
`));let n=t.map(t=>t.type===`text`?{type:`text`,text:e(t.text)}:{type:`image`,source:{type:`base64`,media_type:t.mimeType,data:t.data}});return n.some(e=>e.type===`text`)||n.unshift({type:`text`,text:`(see attached image)`}),n}var Mr=`fine-grained-tool-streaming-2025-05-14`,Nr=`interleaved-thinking-2025-05-14`;function Pr(e){return{supportsEagerToolInputStreaming:e.compat?.supportsEagerToolInputStreaming??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function Fr(...e){let t={};for(let n of e)n&&Object.assign(t,n);return t}var Ir=new Set([`message_start`,`message_delta`,`message_stop`,`content_block_start`,`content_block_delta`,`content_block_stop`]);function Lr(e){if(!e.event&&e.data.length===0)return null;let t={event:e.event,data:e.data.join(`
|
|
37
|
+
`),raw:[...e.raw]};return e.event=null,e.data=[],e.raw=[],t}function Rr(e,t){if(e===``)return Lr(t);if(t.raw.push(e),e.startsWith(`:`))return null;let n=e.indexOf(`:`),r=n===-1?e:e.slice(0,n),i=n===-1?``:e.slice(n+1);return i.startsWith(` `)&&(i=i.slice(1)),r===`event`?t.event=i:r===`data`&&t.data.push(i),null}function zr(e){let t=e.indexOf(`\r`),n=e.indexOf(`
|
|
38
|
+
`);return t===-1?n:n===-1?t:Math.min(t,n)}function Br(e){let t=zr(e);if(t===-1)return null;let n=t+1;return e[t]===`\r`&&e[n]===`
|
|
39
|
+
`&&(n+=1),{line:e.slice(0,t),rest:e.slice(n)}}async function*Vr(e,t){let n=e.getReader(),r=new TextDecoder,i={event:null,data:[],raw:[]},a=``;try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{value:e,done:o}=await n.read();if(o)break;a+=r.decode(e,{stream:!0});let s=Br(a);for(;s;){a=s.rest;let e=Rr(s.line,i);e&&(yield e),s=Br(a)}}a+=r.decode();let e=Br(a);for(;e;){a=e.rest;let t=Rr(e.line,i);t&&(yield t),e=Br(a)}if(a.length>0){let e=Rr(a,i);e&&(yield e)}let o=Lr(i);o&&(yield o)}finally{n.releaseLock()}}async function*Hr(e,t){if(!e.body)throw Error(`Attempted to iterate over an Anthropic response with no body`);let n=!1,r=!1;for await(let i of Vr(e.body,t)){if(i.event===`error`)throw Error(i.data);if(Ir.has(i.event??``))try{let e=s(i.data);e.type===`message_start`?n=!0:e.type===`message_stop`&&(r=!0),yield e}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Could not parse Anthropic SSE event ${i.event}: ${t}; data=${i.data}; raw=${i.raw.join(`\\n`)}`)}}if(n&&!r)throw Error(`Anthropic stream ended before message_stop`)}var Ur=(e,n,r)=>{let a=new i;return(async()=>{let i={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s,u;if(r?.client)s=r.client,u=!1;else{let t=r?.apiKey??c(e.provider)??``,i;if(e.provider===`github-copilot`){let e=ee(n.messages);i=d({messages:n.messages,hasImages:e})}let a=Jr(e,t,r?.interleavedThinking??!0,Qr(e,n),r?.headers,i);s=a.client,u=a.isOAuthToken}let f=Yr(e,n,u,r),p=await r?.onPayload?.(f,e);p!==void 0&&(f=p);let te={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},...r?.maxRetries===void 0?{}:{maxRetries:r.maxRetries}},m=await s.messages.create({...f,stream:!0},te).asResponse();await r?.onResponse?.({status:m.status,headers:o(m.headers)},e),a.push({type:`start`,partial:i});let h=i.content;for await(let o of Hr(m,r?.signal))if(o.type===`message_start`)i.responseId=o.message.id,i.usage.input=o.message.usage.input_tokens||0,i.usage.output=o.message.usage.output_tokens||0,i.usage.cacheRead=o.message.usage.cache_read_input_tokens||0,i.usage.cacheWrite=o.message.usage.cache_creation_input_tokens||0,i.usage.totalTokens=i.usage.input+i.usage.output+i.usage.cacheRead+i.usage.cacheWrite,t(e,i.usage);else if(o.type===`content_block_start`){if(o.content_block.type===`text`){let e={type:`text`,text:``,index:o.index};i.content.push(e),a.push({type:`text_start`,contentIndex:i.content.length-1,partial:i})}else if(o.content_block.type===`thinking`){let e={type:`thinking`,thinking:``,thinkingSignature:``,index:o.index};i.content.push(e),a.push({type:`thinking_start`,contentIndex:i.content.length-1,partial:i})}else if(o.content_block.type===`redacted_thinking`){let e={type:`thinking`,thinking:`[Reasoning redacted]`,thinkingSignature:o.content_block.data,redacted:!0,index:o.index};i.content.push(e),a.push({type:`thinking_start`,contentIndex:i.content.length-1,partial:i})}else if(o.content_block.type===`tool_use`){let e={type:`toolCall`,id:o.content_block.id,name:u?Ar(o.content_block.name,n.tools):o.content_block.name,arguments:o.content_block.input??{},partialJson:``,index:o.index};i.content.push(e),a.push({type:`toolcall_start`,contentIndex:i.content.length-1,partial:i})}}else if(o.type===`content_block_delta`){if(o.delta.type===`text_delta`){let e=h.findIndex(e=>e.index===o.index),t=h[e];t&&t.type===`text`&&(t.text+=o.delta.text,a.push({type:`text_delta`,contentIndex:e,delta:o.delta.text,partial:i}))}else if(o.delta.type===`thinking_delta`){let e=h.findIndex(e=>e.index===o.index),t=h[e];t&&t.type===`thinking`&&(t.thinking+=o.delta.thinking,a.push({type:`thinking_delta`,contentIndex:e,delta:o.delta.thinking,partial:i}))}else if(o.delta.type===`input_json_delta`){let e=h.findIndex(e=>e.index===o.index),t=h[e];t&&t.type===`toolCall`&&(t.partialJson+=o.delta.partial_json,t.arguments=l(t.partialJson),a.push({type:`toolcall_delta`,contentIndex:e,delta:o.delta.partial_json,partial:i}))}else if(o.delta.type===`signature_delta`){let e=h[h.findIndex(e=>e.index===o.index)];e&&e.type===`thinking`&&(e.thinkingSignature=e.thinkingSignature||``,e.thinkingSignature+=o.delta.signature)}}else if(o.type===`content_block_stop`){let e=h.findIndex(e=>e.index===o.index),t=h[e];t&&(delete t.index,t.type===`text`?a.push({type:`text_end`,contentIndex:e,content:t.text,partial:i}):t.type===`thinking`?a.push({type:`thinking_end`,contentIndex:e,content:t.thinking,partial:i}):t.type===`toolCall`&&(t.arguments=l(t.partialJson),delete t.partialJson,a.push({type:`toolcall_end`,contentIndex:e,toolCall:t,partial:i})))}else o.type===`message_delta`&&(o.delta.stop_reason&&(i.stopReason=ei(o.delta.stop_reason)),o.usage.input_tokens!=null&&(i.usage.input=o.usage.input_tokens),o.usage.output_tokens!=null&&(i.usage.output=o.usage.output_tokens),o.usage.cache_read_input_tokens!=null&&(i.usage.cacheRead=o.usage.cache_read_input_tokens),o.usage.cache_creation_input_tokens!=null&&(i.usage.cacheWrite=o.usage.cache_creation_input_tokens),i.usage.totalTokens=i.usage.input+i.usage.output+i.usage.cacheRead+i.usage.cacheWrite,t(e,i.usage));if(r?.signal?.aborted)throw Error(`Request was aborted`);if(i.stopReason===`aborted`||i.stopReason===`error`)throw Error(`An unknown error occurred`);a.push({type:`done`,reason:i.stopReason,message:i}),a.end()}catch(e){for(let e of i.content)delete e.index,delete e.partialJson;i.stopReason=r?.signal?.aborted?`aborted`:`error`,i.errorMessage=e instanceof Error?e.message:JSON.stringify(e),a.push({type:`error`,reason:i.stopReason,error:i}),a.end()}})(),a};function Wr(e){return e.includes(`opus-4-6`)||e.includes(`opus-4.6`)||e.includes(`opus-4-7`)||e.includes(`opus-4.7`)||e.includes(`sonnet-4-6`)||e.includes(`sonnet-4.6`)}function Gr(e,t){let n=t?e.thinkingLevelMap?.[t]:void 0;if(typeof n==`string`)return n;switch(t){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`high`:return`high`;default:return`high`}}var Kr=(e,t,n)=>{let i=n?.apiKey||c(e.provider);if(!i)throw Error(`No API key for provider: ${e.provider}`);let o=r(e,n,i);if(!n?.reasoning)return Ur(e,t,{...o,thinkingEnabled:!1});if(Wr(e.id)){let r=Gr(e,n.reasoning);return Ur(e,t,{...o,thinkingEnabled:!0,effort:r})}let s=a(o.maxTokens||0,e.maxTokens,n.reasoning,n.thinkingBudgets);return Ur(e,t,{...o,maxTokens:s.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:s.thinkingBudget})};function qr(e){return e.includes(`sk-ant-oat`)}function Jr(e,t,n,r,i,a){let o=n&&!Wr(e.id),s=[];return r&&s.push(Mr),o&&s.push(Nr),e.provider===`cloudflare-ai-gateway`?{client:new $({apiKey:null,authToken:null,baseURL:u(e),dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"cf-aig-authorization":`Bearer ${t}`,"x-api-key":null,Authorization:null,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,i)}),isOAuthToken:!1}:e.provider===`github-copilot`?{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,a,i)}),isOAuthToken:!1}:qr(t)?{client:new $({apiKey:null,authToken:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,"anthropic-beta":[`claude-code-20250219`,`oauth-2025-04-20`,...s].join(`,`),"user-agent":`claude-cli/${Dr}`,"x-app":`cli`},e.headers,i)}),isOAuthToken:!0}:{client:new $({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:Fr({accept:`application/json`,"anthropic-dangerous-direct-browser-access":`true`,...s.length>0?{"anthropic-beta":s.join(`,`)}:{}},e.headers,i)}),isOAuthToken:!1}}function Yr(t,n,r,i){let{cacheControl:a}=Er(t,i?.cacheRetention),o={model:t.id,messages:Zr(n.messages,t,r,a),max_tokens:i?.maxTokens||t.maxTokens/3|0,stream:!0};if(r?(o.system=[{type:`text`,text:`You are Claude Code, Anthropic's official CLI for Claude.`,...a?{cache_control:a}:{}}],n.systemPrompt&&o.system.push({type:`text`,text:e(n.systemPrompt),...a?{cache_control:a}:{}})):n.systemPrompt&&(o.system=[{type:`text`,text:e(n.systemPrompt),...a?{cache_control:a}:{}}]),i?.temperature!==void 0&&!i?.thinkingEnabled&&(o.temperature=i.temperature),n.tools&&n.tools.length>0&&(o.tools=$r(n.tools,r,Pr(t).supportsEagerToolInputStreaming,a)),t.reasoning)if(i?.thinkingEnabled){let e=i.thinkingDisplay??`summarized`;Wr(t.id)?(o.thinking={type:`adaptive`,display:e},i.effort&&(o.output_config=(i.effort,{effort:i.effort}))):o.thinking={type:`enabled`,budget_tokens:i.thinkingBudgetTokens||1024,display:e}}else i?.thinkingEnabled===!1&&(o.thinking={type:`disabled`});if(i?.metadata){let e=i.metadata.user_id;typeof e==`string`&&(o.metadata={user_id:e})}return i?.toolChoice&&(typeof i.toolChoice==`string`?o.tool_choice={type:i.toolChoice}:o.tool_choice=i.toolChoice),o}function Xr(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function Zr(t,r,i,a){let o=[],s=n(t,r,Xr);for(let t=0;t<s.length;t++){let n=s[t];if(n.role===`user`)if(typeof n.content==`string`)n.content.trim().length>0&&o.push({role:`user`,content:e(n.content)});else{let t=n.content.map(t=>t.type===`text`?{type:`text`,text:e(t.text)}:{type:`image`,source:{type:`base64`,media_type:t.mimeType,data:t.data}}).filter(e=>e.type===`text`?e.text.trim().length>0:!0);if(t.length===0)continue;o.push({role:`user`,content:t})}else if(n.role===`assistant`){let t=[];for(let r of n.content)if(r.type===`text`){if(r.text.trim().length===0)continue;t.push({type:`text`,text:e(r.text)})}else if(r.type===`thinking`){if(r.redacted){t.push({type:`redacted_thinking`,data:r.thinkingSignature});continue}if(r.thinking.trim().length===0)continue;!r.thinkingSignature||r.thinkingSignature.trim().length===0?t.push({type:`text`,text:e(r.thinking)}):t.push({type:`thinking`,thinking:e(r.thinking),signature:r.thinkingSignature})}else r.type===`toolCall`&&t.push({type:`tool_use`,id:r.id,name:i?kr(r.name):r.name,input:r.arguments??{}});if(t.length===0)continue;o.push({role:`assistant`,content:t})}else if(n.role===`toolResult`){let e=[];e.push({type:`tool_result`,tool_use_id:n.toolCallId,content:jr(n.content),is_error:n.isError});let r=t+1;for(;r<s.length&&s[r].role===`toolResult`;){let t=s[r];e.push({type:`tool_result`,tool_use_id:t.toolCallId,content:jr(t.content),is_error:t.isError}),r++}t=r-1,o.push({role:`user`,content:e})}}if(a&&o.length>0){let e=o[o.length-1];if(e.role===`user`)if(Array.isArray(e.content)){let t=e.content[e.content.length-1];t&&(t.type===`text`||t.type===`image`||t.type===`tool_result`)&&(t.cache_control=a)}else typeof e.content==`string`&&(e.content=[{type:`text`,text:e.content,cache_control:a}])}return o}function Qr(e,t){return!!t.tools?.length&&!Pr(e).supportsEagerToolInputStreaming}function $r(e,t,n,r){return e?e.map((i,a)=>{let o=i.parameters;return{name:t?kr(i.name):i.name,description:i.description,...n?{eager_input_streaming:!0}:{},input_schema:{type:`object`,properties:o.properties??{},required:o.required??[]},...r&&a===e.length-1?{cache_control:r}:{}}}):[]}function ei(e){switch(e){case`end_turn`:return`stop`;case`max_tokens`:return`length`;case`tool_use`:return`toolUse`;case`refusal`:return`error`;case`pause_turn`:return`stop`;case`stop_sequence`:return`stop`;case`sensitive`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}export{Ur as streamAnthropic,Kr as streamSimpleAnthropic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{l as e,n as t,o as n}from"./simple-options-CDIijiMb.js";import{t as r}from"./headers-qDMOQQGF.js";import{t as i}from"./openai-D4NSaQIs.js";import{d as a,l as o,m as s,u as c}from"./index-BVA4YIGJ.js";var l=`v1`,u=new Set([`openai`,`openai-codex`,`opencode`,`azure-openai-responses`]);function d(e){let t=new Map;if(!e)return t;for(let n of e.split(`,`)){let e=n.trim();if(!e)continue;let[r,i]=e.split(`=`,2);!r||!i||t.set(r.trim(),i.trim())}return t}function f(e,t){return t?.azureDeploymentName?t.azureDeploymentName:d({}.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(e.id)||e.id}var p=(e,t,i)=>{let o=new n;return(async()=>{let n=f(e,i),c={role:`assistant`,content:[],api:`azure-openai-responses`,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let l=v(e,i?.apiKey||s(e.provider)||``,i),u=y(e,t,i,n),d=await i?.onPayload?.(u,e);d!==void 0&&(u=d);let f={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},...i?.maxRetries===void 0?{}:{maxRetries:i.maxRetries}},{data:p,response:m}=await l.responses.create(u,f).withResponse();if(await i?.onResponse?.({status:m.status,headers:r(m.headers)},e),o.push({type:`start`,partial:c}),await a(p,c,o,e),i?.signal?.aborted)throw Error(`Request was aborted`);if(c.stopReason===`aborted`||c.stopReason===`error`)throw Error(`An unknown error occurred`);o.push({type:`done`,reason:c.stopReason,message:c}),o.end()}catch(e){for(let e of c.content)delete e.index,delete e.partialJson;c.stopReason=i?.signal?.aborted?`aborted`:`error`,c.errorMessage=e instanceof Error?e.message:JSON.stringify(e),o.push({type:`error`,reason:c.stopReason,error:c}),o.end()}})(),o},m=(n,r,i)=>{let a=i?.apiKey||s(n.provider);if(!a)throw Error(`No API key for provider: ${n.provider}`);let o=t(n,i,a),c=i?.reasoning?e(n,i.reasoning):void 0,l=c===`off`?void 0:c;return p(n,r,{...o,reasoningEffort:l})};function h(e){let t=e.trim().replace(/\/+$/,``),n;try{n=new URL(t)}catch{throw Error(`Invalid Azure OpenAI base URL: ${e}`)}let r=n.hostname.endsWith(`.openai.azure.com`)||n.hostname.endsWith(`.cognitiveservices.azure.com`),i=n.pathname.replace(/\/+$/,``);return r&&(i===``||i===`/`||i===`/openai`)&&(n.pathname=`/openai/v1`,n.search=``),n.toString().replace(/\/+$/,``)}function g(e){return`https://${e}.openai.azure.com/openai/v1`}function _(e,t){let n=t?.azureApiVersion||{}.AZURE_OPENAI_API_VERSION||l,r=t?.azureBaseUrl?.trim()||{}.AZURE_OPENAI_BASE_URL?.trim()||void 0,i=t?.azureResourceName||{}.AZURE_OPENAI_RESOURCE_NAME,a=r;if(!a&&i&&(a=g(i)),!a&&e.baseUrl&&(a=e.baseUrl),!a)throw Error(`Azure OpenAI base URL is required. Set AZURE_OPENAI_BASE_URL or AZURE_OPENAI_RESOURCE_NAME, or pass azureBaseUrl, azureResourceName, or model.baseUrl.`);return{baseUrl:h(a),apiVersion:n}}function v(e,t,n){if(!t){if(!{}.AZURE_OPENAI_API_KEY)throw Error(`Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.`);t={}.AZURE_OPENAI_API_KEY}let r={...e.headers};n?.headers&&Object.assign(r,n.headers);let{baseUrl:a,apiVersion:o}=_(e,n);return new i({apiKey:t,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:r,baseURL:a})}function y(e,t,n,r){let i={model:r,input:o(e,t,u),stream:!0,prompt_cache_key:n?.sessionId};return n?.maxTokens&&(i.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(i.temperature=n?.temperature),t.tools&&t.tools.length>0&&(i.tools=c(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(i.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},i.include=[`reasoning.encrypted_content`]):e.thinkingLevelMap?.off!==null&&(i.reasoning={effort:e.thinkingLevelMap?.off??`none`})),i}export{p as streamAzureOpenAIResponses,m as streamSimpleAzureOpenAIResponses};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as e,C as t,D as n,G as r,H as i,P as a,Q as o,S as s,V as c,_ as l,a as u,at as d,b as f,dt as p,et as m,f as h,g,i as ee,lt as te,nt as _,o as ne,ot as re,s as ie,st as v,tt as y,ut as b}from"./dist-D6ztLqPA.js";import{html as ae,htmlCompletionSource as oe,t as se}from"./dist-UfV1NDbo.js";var ce=class e{static create(t,n,r,i,a){return new e(t,n,r,i+(i<<8)+t+(n<<4)|0,a,[],[])}constructor(e,t,n,r,i,a,o){this.type=e,this.value=t,this.from=n,this.hash=r,this.end=i,this.children=a,this.positions=o,this.hashProp=[[d.contextHash,r]]}addChild(e,t){e.prop(d.contextHash)!=this.hash&&(e=new b(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let n=this.children.length-1;return n>=0&&(t=Math.max(t,this.positions[n]+this.children[n].length+this.from)),new b(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(e,t,n)=>new b(v.none,e,t,n,this.hashProp)})}},x;(function(e){e[e.Document=1]=`Document`,e[e.CodeBlock=2]=`CodeBlock`,e[e.FencedCode=3]=`FencedCode`,e[e.Blockquote=4]=`Blockquote`,e[e.HorizontalRule=5]=`HorizontalRule`,e[e.BulletList=6]=`BulletList`,e[e.OrderedList=7]=`OrderedList`,e[e.ListItem=8]=`ListItem`,e[e.ATXHeading1=9]=`ATXHeading1`,e[e.ATXHeading2=10]=`ATXHeading2`,e[e.ATXHeading3=11]=`ATXHeading3`,e[e.ATXHeading4=12]=`ATXHeading4`,e[e.ATXHeading5=13]=`ATXHeading5`,e[e.ATXHeading6=14]=`ATXHeading6`,e[e.SetextHeading1=15]=`SetextHeading1`,e[e.SetextHeading2=16]=`SetextHeading2`,e[e.HTMLBlock=17]=`HTMLBlock`,e[e.LinkReference=18]=`LinkReference`,e[e.Paragraph=19]=`Paragraph`,e[e.CommentBlock=20]=`CommentBlock`,e[e.ProcessingInstructionBlock=21]=`ProcessingInstructionBlock`,e[e.Escape=22]=`Escape`,e[e.Entity=23]=`Entity`,e[e.HardBreak=24]=`HardBreak`,e[e.Emphasis=25]=`Emphasis`,e[e.StrongEmphasis=26]=`StrongEmphasis`,e[e.Link=27]=`Link`,e[e.Image=28]=`Image`,e[e.InlineCode=29]=`InlineCode`,e[e.HTMLTag=30]=`HTMLTag`,e[e.Comment=31]=`Comment`,e[e.ProcessingInstruction=32]=`ProcessingInstruction`,e[e.Autolink=33]=`Autolink`,e[e.HeaderMark=34]=`HeaderMark`,e[e.QuoteMark=35]=`QuoteMark`,e[e.ListMark=36]=`ListMark`,e[e.LinkMark=37]=`LinkMark`,e[e.EmphasisMark=38]=`EmphasisMark`,e[e.CodeMark=39]=`CodeMark`,e[e.CodeText=40]=`CodeText`,e[e.CodeInfo=41]=`CodeInfo`,e[e.LinkTitle=42]=`LinkTitle`,e[e.LinkLabel=43]=`LinkLabel`,e[e.URL=44]=`URL`})(x||={});var le=class{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}},ue=class{constructor(){this.text=``,this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return C(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(e){this.basePos=e,this.baseIndent=this.countIndent(e,this.pos,this.indent)}moveBaseColumn(e){this.baseIndent=e,this.basePos=this.findColumn(e)}addMarker(e){this.markers.push(e)}countIndent(e,t=0,n=0){for(let r=t;r<e;r++)n+=this.text.charCodeAt(r)==9?4-n%4:1;return n}findColumn(e){let t=0;for(let n=0;t<this.text.length&&n<e;t++)n+=this.text.charCodeAt(t)==9?4-n%4:1;return t}scrub(){if(!this.baseIndent)return this.text;let e=``;for(let t=0;t<this.basePos;t++)e+=` `;return e+this.text.slice(this.basePos)}};function de(e,t,n){if(n.pos==n.text.length||e!=t.block&&n.indent>=t.stack[n.depth+1].value+n.baseIndent)return!0;if(n.indent>=n.baseIndent+4)return!1;let r=(e.type==x.OrderedList?D:E)(n,t,!1);return r>0&&(e.type!=x.BulletList||w(n,t,!1)<0)&&n.text.charCodeAt(n.pos+r-1)==e.value}var fe={[x.Blockquote](e,t,n){return n.next==62?(n.markers.push(R(x.QuoteMark,t.lineStart+n.pos,t.lineStart+n.pos+1)),n.moveBase(n.pos+(S(n.text.charCodeAt(n.pos+1))?2:1)),e.end=t.lineStart+n.text.length,!0):!1},[x.ListItem](e,t,n){return n.indent<n.baseIndent+e.value&&n.next>-1?!1:(n.moveBaseColumn(n.baseIndent+e.value),!0)},[x.OrderedList]:de,[x.BulletList]:de,[x.Document](){return!0}};function S(e){return e==32||e==9||e==10||e==13}function C(e,t=0){for(;t<e.length&&S(e.charCodeAt(t));)t++;return t}function pe(e,t,n){for(;t>n&&S(e.charCodeAt(t-1));)t--;return t}function me(e){if(e.next!=96&&e.next!=126)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;if(t<e.pos+3)return-1;if(e.next==96){for(let n=t;n<e.text.length;n++)if(e.text.charCodeAt(n)==96)return-1}return t}function he(e){return e.next==62?e.text.charCodeAt(e.pos+1)==32?2:1:-1}function w(e,t,n){if(e.next!=42&&e.next!=45&&e.next!=95)return-1;let r=1;for(let t=e.pos+1;t<e.text.length;t++){let n=e.text.charCodeAt(t);if(n==e.next)r++;else if(!S(n))return-1}return n&&e.next==45&&_e(e)>-1&&e.depth==t.stack.length&&t.parser.leafBlockParsers.indexOf(we.SetextHeading)>-1||r<3?-1:1}function T(e,t){for(let n=e.stack.length-1;n>=0;n--)if(e.stack[n].type==t)return!0;return!1}function E(e,t,n){return(e.next==45||e.next==43||e.next==42)&&(e.pos==e.text.length-1||S(e.text.charCodeAt(e.pos+1)))&&(!n||T(t,x.BulletList)||e.skipSpace(e.pos+2)<e.text.length)?1:-1}function D(e,t,n){let r=e.pos,i=e.next;for(;i>=48&&i<=57;){if(r++,r==e.text.length)return-1;i=e.text.charCodeAt(r)}return r==e.pos||r>e.pos+9||i!=46&&i!=41||r<e.text.length-1&&!S(e.text.charCodeAt(r+1))||n&&!T(t,x.OrderedList)&&(e.skipSpace(r+1)==e.text.length||r>e.pos+1||e.next!=49)?-1:r+1-e.pos}function ge(e){if(e.next!=35)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==35;)t++;if(t<e.text.length&&e.text.charCodeAt(t)!=32)return-1;let n=t-e.pos;return n>6?-1:n}function _e(e){if(e.next!=45&&e.next!=61||e.indent>=e.baseIndent+4)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;let n=t;for(;t<e.text.length&&S(e.text.charCodeAt(t));)t++;return t==e.text.length?n:-1}var O=/^[ \t]*$/,ve=/-->/,ye=/\?>/,k=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*<!--/,ve],[/^\s*<\?/,ye],[/^\s*<![A-Z]/,/>/],[/^\s*<!\[CDATA\[/,/\]\]>/],[/^\s*<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|\/?>|$)/i,O],[/^\s*(?:<\/[a-z][\w-]*\s*>|<[a-z][\w-]*(\s+[a-z:_][\w-.]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*>)\s*$/i,O]];function be(e,t,n){if(e.next!=60)return-1;let r=e.text.slice(e.pos);for(let e=0,t=k.length-+!!n;e<t;e++)if(k[e][0].test(r))return e;return-1}function xe(e,t){let n=e.countIndent(t,e.pos,e.indent),r=e.countIndent(e.skipSpace(t),t,n);return r>=n+5?n+1:r}function A(e,t,n){let r=e.length-1;r>=0&&e[r].to==t&&e[r].type==x.CodeText?e[r].to=n:e.push(R(x.CodeText,t,n))}var j={LinkReference:void 0,IndentedCode(e,t){let n=t.baseIndent+4;if(t.indent<n)return!1;let r=t.findColumn(n),i=e.lineStart+r,a=e.lineStart+t.text.length,o=[],s=[];for(A(o,i,a);e.nextLine()&&t.depth>=e.stack.length;)if(t.pos==t.text.length){A(s,e.lineStart-1,e.lineStart);for(let e of t.markers)s.push(e)}else if(t.indent<n)break;else{if(s.length){for(let e of s)e.type==x.CodeText?A(o,e.from,e.to):o.push(e);s=[]}A(o,e.lineStart-1,e.lineStart);for(let e of t.markers)o.push(e);a=e.lineStart+t.text.length;let n=e.lineStart+t.findColumn(t.baseIndent+4);n<a&&A(o,n,a)}return s.length&&(s=s.filter(e=>e.type!=x.CodeText),s.length&&(t.markers=s.concat(t.markers))),e.addNode(e.buffer.writeElements(o,-i).finish(x.CodeBlock,a-i),i),!0},FencedCode(e,t){let n=me(t);if(n<0)return!1;let r=e.lineStart+t.pos,i=t.next,a=n-t.pos,o=t.skipSpace(n),s=pe(t.text,t.text.length,o),c=[R(x.CodeMark,r,r+a)];o<s&&c.push(R(x.CodeInfo,e.lineStart+o,e.lineStart+s));for(let n=!0,r=!0,o=!1;e.nextLine()&&t.depth>=e.stack.length;n=!1){let s=t.pos;if(t.indent-t.baseIndent<4)for(;s<t.text.length&&t.text.charCodeAt(s)==i;)s++;if(s-t.pos>=a&&t.skipSpace(s)==t.text.length){for(let e of t.markers)c.push(e);r&&o&&A(c,e.lineStart-1,e.lineStart),c.push(R(x.CodeMark,e.lineStart+t.pos,e.lineStart+s)),e.nextLine();break}else{o=!0,n||(A(c,e.lineStart-1,e.lineStart),r=!1);for(let e of t.markers)c.push(e);let i=e.lineStart+t.basePos,a=e.lineStart+t.text.length;i<a&&(A(c,i,a),r=!1)}}return e.addNode(e.buffer.writeElements(c,-r).finish(x.FencedCode,e.prevLineEnd()-r),r),!0},Blockquote(e,t){let n=he(t);return n<0?!1:(e.startContext(x.Blockquote,t.pos),e.addNode(x.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1),t.moveBase(t.pos+n),null)},HorizontalRule(e,t){if(w(t,e,!1)<0)return!1;let n=e.lineStart+t.pos;return e.nextLine(),e.addNode(x.HorizontalRule,n),!0},BulletList(e,t){let n=E(t,e,!1);if(n<0)return!1;e.block.type!=x.BulletList&&e.startContext(x.BulletList,t.basePos,t.next);let r=xe(t,t.pos+1);return e.startContext(x.ListItem,t.basePos,r-t.baseIndent),e.addNode(x.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},OrderedList(e,t){let n=D(t,e,!1);if(n<0)return!1;e.block.type!=x.OrderedList&&e.startContext(x.OrderedList,t.basePos,t.text.charCodeAt(t.pos+n-1));let r=xe(t,t.pos+n);return e.startContext(x.ListItem,t.basePos,r-t.baseIndent),e.addNode(x.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},ATXHeading(e,t){let n=ge(t);if(n<0)return!1;let r=t.pos,i=e.lineStart+r,a=pe(t.text,t.text.length,r),o=a;for(;o>r&&t.text.charCodeAt(o-1)==t.next;)o--;(o==a||o==r||!S(t.text.charCodeAt(o-1)))&&(o=t.text.length);let s=e.buffer.write(x.HeaderMark,0,n).writeElements(e.parser.parseInline(t.text.slice(r+n+1,o),i+n+1),-i);o<t.text.length&&s.write(x.HeaderMark,o-r,a-r);let c=s.finish(x.ATXHeading1-1+n,t.text.length-r);return e.nextLine(),e.addNode(c,i),!0},HTMLBlock(e,t){let n=be(t,e,!1);if(n<0)return!1;let r=e.lineStart+t.pos,i=k[n][1],a=[],o=i!=O;for(;!i.test(t.text)&&e.nextLine();){if(t.depth<e.stack.length){o=!1;break}for(let e of t.markers)a.push(e)}o&&e.nextLine();let s=i==ve?x.CommentBlock:i==ye?x.ProcessingInstructionBlock:x.HTMLBlock,c=e.prevLineEnd();return e.addNode(e.buffer.writeElements(a,-r).finish(s,c-r),r),!0},SetextHeading:void 0},Se=class{constructor(e){this.stage=0,this.elts=[],this.pos=0,this.start=e.start,this.advance(e.content)}nextLine(e,t,n){if(this.stage==-1)return!1;let r=n.content+`
|
|
1
|
+
import{A as e,C as t,D as n,G as r,H as i,P as a,Q as o,S as s,V as c,_ as l,a as u,at as d,b as f,dt as p,et as m,f as h,g,i as ee,lt as te,nt as _,o as ne,ot as re,s as ie,st as v,tt as y,ut as b}from"./dist-uJp2dR6X.js";import{html as ae,htmlCompletionSource as oe,t as se}from"./dist-Ck3Vla0r.js";var ce=class e{static create(t,n,r,i,a){return new e(t,n,r,i+(i<<8)+t+(n<<4)|0,a,[],[])}constructor(e,t,n,r,i,a,o){this.type=e,this.value=t,this.from=n,this.hash=r,this.end=i,this.children=a,this.positions=o,this.hashProp=[[d.contextHash,r]]}addChild(e,t){e.prop(d.contextHash)!=this.hash&&(e=new b(e.type,e.children,e.positions,e.length,this.hashProp)),this.children.push(e),this.positions.push(t)}toTree(e,t=this.end){let n=this.children.length-1;return n>=0&&(t=Math.max(t,this.positions[n]+this.children[n].length+this.from)),new b(e.types[this.type],this.children,this.positions,t-this.from).balance({makeTree:(e,t,n)=>new b(v.none,e,t,n,this.hashProp)})}},x;(function(e){e[e.Document=1]=`Document`,e[e.CodeBlock=2]=`CodeBlock`,e[e.FencedCode=3]=`FencedCode`,e[e.Blockquote=4]=`Blockquote`,e[e.HorizontalRule=5]=`HorizontalRule`,e[e.BulletList=6]=`BulletList`,e[e.OrderedList=7]=`OrderedList`,e[e.ListItem=8]=`ListItem`,e[e.ATXHeading1=9]=`ATXHeading1`,e[e.ATXHeading2=10]=`ATXHeading2`,e[e.ATXHeading3=11]=`ATXHeading3`,e[e.ATXHeading4=12]=`ATXHeading4`,e[e.ATXHeading5=13]=`ATXHeading5`,e[e.ATXHeading6=14]=`ATXHeading6`,e[e.SetextHeading1=15]=`SetextHeading1`,e[e.SetextHeading2=16]=`SetextHeading2`,e[e.HTMLBlock=17]=`HTMLBlock`,e[e.LinkReference=18]=`LinkReference`,e[e.Paragraph=19]=`Paragraph`,e[e.CommentBlock=20]=`CommentBlock`,e[e.ProcessingInstructionBlock=21]=`ProcessingInstructionBlock`,e[e.Escape=22]=`Escape`,e[e.Entity=23]=`Entity`,e[e.HardBreak=24]=`HardBreak`,e[e.Emphasis=25]=`Emphasis`,e[e.StrongEmphasis=26]=`StrongEmphasis`,e[e.Link=27]=`Link`,e[e.Image=28]=`Image`,e[e.InlineCode=29]=`InlineCode`,e[e.HTMLTag=30]=`HTMLTag`,e[e.Comment=31]=`Comment`,e[e.ProcessingInstruction=32]=`ProcessingInstruction`,e[e.Autolink=33]=`Autolink`,e[e.HeaderMark=34]=`HeaderMark`,e[e.QuoteMark=35]=`QuoteMark`,e[e.ListMark=36]=`ListMark`,e[e.LinkMark=37]=`LinkMark`,e[e.EmphasisMark=38]=`EmphasisMark`,e[e.CodeMark=39]=`CodeMark`,e[e.CodeText=40]=`CodeText`,e[e.CodeInfo=41]=`CodeInfo`,e[e.LinkTitle=42]=`LinkTitle`,e[e.LinkLabel=43]=`LinkLabel`,e[e.URL=44]=`URL`})(x||={});var le=class{constructor(e,t){this.start=e,this.content=t,this.marks=[],this.parsers=[]}},ue=class{constructor(){this.text=``,this.baseIndent=0,this.basePos=0,this.depth=0,this.markers=[],this.pos=0,this.indent=0,this.next=-1}forward(){this.basePos>this.pos&&this.forwardInner()}forwardInner(){let e=this.skipSpace(this.basePos);this.indent=this.countIndent(e,this.pos,this.indent),this.pos=e,this.next=e==this.text.length?-1:this.text.charCodeAt(e)}skipSpace(e){return C(this.text,e)}reset(e){for(this.text=e,this.baseIndent=this.basePos=this.pos=this.indent=0,this.forwardInner(),this.depth=1;this.markers.length;)this.markers.pop()}moveBase(e){this.basePos=e,this.baseIndent=this.countIndent(e,this.pos,this.indent)}moveBaseColumn(e){this.baseIndent=e,this.basePos=this.findColumn(e)}addMarker(e){this.markers.push(e)}countIndent(e,t=0,n=0){for(let r=t;r<e;r++)n+=this.text.charCodeAt(r)==9?4-n%4:1;return n}findColumn(e){let t=0;for(let n=0;t<this.text.length&&n<e;t++)n+=this.text.charCodeAt(t)==9?4-n%4:1;return t}scrub(){if(!this.baseIndent)return this.text;let e=``;for(let t=0;t<this.basePos;t++)e+=` `;return e+this.text.slice(this.basePos)}};function de(e,t,n){if(n.pos==n.text.length||e!=t.block&&n.indent>=t.stack[n.depth+1].value+n.baseIndent)return!0;if(n.indent>=n.baseIndent+4)return!1;let r=(e.type==x.OrderedList?D:E)(n,t,!1);return r>0&&(e.type!=x.BulletList||w(n,t,!1)<0)&&n.text.charCodeAt(n.pos+r-1)==e.value}var fe={[x.Blockquote](e,t,n){return n.next==62?(n.markers.push(R(x.QuoteMark,t.lineStart+n.pos,t.lineStart+n.pos+1)),n.moveBase(n.pos+(S(n.text.charCodeAt(n.pos+1))?2:1)),e.end=t.lineStart+n.text.length,!0):!1},[x.ListItem](e,t,n){return n.indent<n.baseIndent+e.value&&n.next>-1?!1:(n.moveBaseColumn(n.baseIndent+e.value),!0)},[x.OrderedList]:de,[x.BulletList]:de,[x.Document](){return!0}};function S(e){return e==32||e==9||e==10||e==13}function C(e,t=0){for(;t<e.length&&S(e.charCodeAt(t));)t++;return t}function pe(e,t,n){for(;t>n&&S(e.charCodeAt(t-1));)t--;return t}function me(e){if(e.next!=96&&e.next!=126)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;if(t<e.pos+3)return-1;if(e.next==96){for(let n=t;n<e.text.length;n++)if(e.text.charCodeAt(n)==96)return-1}return t}function he(e){return e.next==62?e.text.charCodeAt(e.pos+1)==32?2:1:-1}function w(e,t,n){if(e.next!=42&&e.next!=45&&e.next!=95)return-1;let r=1;for(let t=e.pos+1;t<e.text.length;t++){let n=e.text.charCodeAt(t);if(n==e.next)r++;else if(!S(n))return-1}return n&&e.next==45&&_e(e)>-1&&e.depth==t.stack.length&&t.parser.leafBlockParsers.indexOf(we.SetextHeading)>-1||r<3?-1:1}function T(e,t){for(let n=e.stack.length-1;n>=0;n--)if(e.stack[n].type==t)return!0;return!1}function E(e,t,n){return(e.next==45||e.next==43||e.next==42)&&(e.pos==e.text.length-1||S(e.text.charCodeAt(e.pos+1)))&&(!n||T(t,x.BulletList)||e.skipSpace(e.pos+2)<e.text.length)?1:-1}function D(e,t,n){let r=e.pos,i=e.next;for(;i>=48&&i<=57;){if(r++,r==e.text.length)return-1;i=e.text.charCodeAt(r)}return r==e.pos||r>e.pos+9||i!=46&&i!=41||r<e.text.length-1&&!S(e.text.charCodeAt(r+1))||n&&!T(t,x.OrderedList)&&(e.skipSpace(r+1)==e.text.length||r>e.pos+1||e.next!=49)?-1:r+1-e.pos}function ge(e){if(e.next!=35)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==35;)t++;if(t<e.text.length&&e.text.charCodeAt(t)!=32)return-1;let n=t-e.pos;return n>6?-1:n}function _e(e){if(e.next!=45&&e.next!=61||e.indent>=e.baseIndent+4)return-1;let t=e.pos+1;for(;t<e.text.length&&e.text.charCodeAt(t)==e.next;)t++;let n=t;for(;t<e.text.length&&S(e.text.charCodeAt(t));)t++;return t==e.text.length?n:-1}var O=/^[ \t]*$/,ve=/-->/,ye=/\?>/,k=[[/^<(?:script|pre|style)(?:\s|>|$)/i,/<\/(?:script|pre|style)>/i],[/^\s*<!--/,ve],[/^\s*<\?/,ye],[/^\s*<![A-Z]/,/>/],[/^\s*<!\[CDATA\[/,/\]\]>/],[/^\s*<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?:\s|\/?>|$)/i,O],[/^\s*(?:<\/[a-z][\w-]*\s*>|<[a-z][\w-]*(\s+[a-z:_][\w-.]*(?:\s*=\s*(?:[^\s"'=<>`]+|'[^']*'|"[^"]*"))?)*\s*>)\s*$/i,O]];function be(e,t,n){if(e.next!=60)return-1;let r=e.text.slice(e.pos);for(let e=0,t=k.length-+!!n;e<t;e++)if(k[e][0].test(r))return e;return-1}function xe(e,t){let n=e.countIndent(t,e.pos,e.indent),r=e.countIndent(e.skipSpace(t),t,n);return r>=n+5?n+1:r}function A(e,t,n){let r=e.length-1;r>=0&&e[r].to==t&&e[r].type==x.CodeText?e[r].to=n:e.push(R(x.CodeText,t,n))}var j={LinkReference:void 0,IndentedCode(e,t){let n=t.baseIndent+4;if(t.indent<n)return!1;let r=t.findColumn(n),i=e.lineStart+r,a=e.lineStart+t.text.length,o=[],s=[];for(A(o,i,a);e.nextLine()&&t.depth>=e.stack.length;)if(t.pos==t.text.length){A(s,e.lineStart-1,e.lineStart);for(let e of t.markers)s.push(e)}else if(t.indent<n)break;else{if(s.length){for(let e of s)e.type==x.CodeText?A(o,e.from,e.to):o.push(e);s=[]}A(o,e.lineStart-1,e.lineStart);for(let e of t.markers)o.push(e);a=e.lineStart+t.text.length;let n=e.lineStart+t.findColumn(t.baseIndent+4);n<a&&A(o,n,a)}return s.length&&(s=s.filter(e=>e.type!=x.CodeText),s.length&&(t.markers=s.concat(t.markers))),e.addNode(e.buffer.writeElements(o,-i).finish(x.CodeBlock,a-i),i),!0},FencedCode(e,t){let n=me(t);if(n<0)return!1;let r=e.lineStart+t.pos,i=t.next,a=n-t.pos,o=t.skipSpace(n),s=pe(t.text,t.text.length,o),c=[R(x.CodeMark,r,r+a)];o<s&&c.push(R(x.CodeInfo,e.lineStart+o,e.lineStart+s));for(let n=!0,r=!0,o=!1;e.nextLine()&&t.depth>=e.stack.length;n=!1){let s=t.pos;if(t.indent-t.baseIndent<4)for(;s<t.text.length&&t.text.charCodeAt(s)==i;)s++;if(s-t.pos>=a&&t.skipSpace(s)==t.text.length){for(let e of t.markers)c.push(e);r&&o&&A(c,e.lineStart-1,e.lineStart),c.push(R(x.CodeMark,e.lineStart+t.pos,e.lineStart+s)),e.nextLine();break}else{o=!0,n||(A(c,e.lineStart-1,e.lineStart),r=!1);for(let e of t.markers)c.push(e);let i=e.lineStart+t.basePos,a=e.lineStart+t.text.length;i<a&&(A(c,i,a),r=!1)}}return e.addNode(e.buffer.writeElements(c,-r).finish(x.FencedCode,e.prevLineEnd()-r),r),!0},Blockquote(e,t){let n=he(t);return n<0?!1:(e.startContext(x.Blockquote,t.pos),e.addNode(x.QuoteMark,e.lineStart+t.pos,e.lineStart+t.pos+1),t.moveBase(t.pos+n),null)},HorizontalRule(e,t){if(w(t,e,!1)<0)return!1;let n=e.lineStart+t.pos;return e.nextLine(),e.addNode(x.HorizontalRule,n),!0},BulletList(e,t){let n=E(t,e,!1);if(n<0)return!1;e.block.type!=x.BulletList&&e.startContext(x.BulletList,t.basePos,t.next);let r=xe(t,t.pos+1);return e.startContext(x.ListItem,t.basePos,r-t.baseIndent),e.addNode(x.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},OrderedList(e,t){let n=D(t,e,!1);if(n<0)return!1;e.block.type!=x.OrderedList&&e.startContext(x.OrderedList,t.basePos,t.text.charCodeAt(t.pos+n-1));let r=xe(t,t.pos+n);return e.startContext(x.ListItem,t.basePos,r-t.baseIndent),e.addNode(x.ListMark,e.lineStart+t.pos,e.lineStart+t.pos+n),t.moveBaseColumn(r),null},ATXHeading(e,t){let n=ge(t);if(n<0)return!1;let r=t.pos,i=e.lineStart+r,a=pe(t.text,t.text.length,r),o=a;for(;o>r&&t.text.charCodeAt(o-1)==t.next;)o--;(o==a||o==r||!S(t.text.charCodeAt(o-1)))&&(o=t.text.length);let s=e.buffer.write(x.HeaderMark,0,n).writeElements(e.parser.parseInline(t.text.slice(r+n+1,o),i+n+1),-i);o<t.text.length&&s.write(x.HeaderMark,o-r,a-r);let c=s.finish(x.ATXHeading1-1+n,t.text.length-r);return e.nextLine(),e.addNode(c,i),!0},HTMLBlock(e,t){let n=be(t,e,!1);if(n<0)return!1;let r=e.lineStart+t.pos,i=k[n][1],a=[],o=i!=O;for(;!i.test(t.text)&&e.nextLine();){if(t.depth<e.stack.length){o=!1;break}for(let e of t.markers)a.push(e)}o&&e.nextLine();let s=i==ve?x.CommentBlock:i==ye?x.ProcessingInstructionBlock:x.HTMLBlock,c=e.prevLineEnd();return e.addNode(e.buffer.writeElements(a,-r).finish(s,c-r),r),!0},SetextHeading:void 0},Se=class{constructor(e){this.stage=0,this.elts=[],this.pos=0,this.start=e.start,this.advance(e.content)}nextLine(e,t,n){if(this.stage==-1)return!1;let r=n.content+`
|
|
2
2
|
`+t.scrub(),i=this.advance(r);return i>-1&&i<r.length?this.complete(e,n,i):!1}finish(e,t){return(this.stage==2||this.stage==3)&&C(t.content,this.pos)==t.content.length?this.complete(e,t,t.content.length):!1}complete(e,t,n){return e.addLeafElement(t,R(x.LinkReference,this.start,this.start+n,this.elts)),!0}nextStage(e){return e?(this.pos=e.to-this.start,this.elts.push(e),this.stage++,!0):(e===!1&&(this.stage=-1),!1)}advance(e){for(;;)if(this.stage==-1)return-1;else if(this.stage==0){if(!this.nextStage(ze(e,this.pos,this.start,!0)))return-1;if(e.charCodeAt(this.pos)!=58)return this.stage=-1;this.elts.push(R(x.LinkMark,this.pos+this.start,this.pos+this.start+1)),this.pos++}else if(this.stage==1){if(!this.nextStage(Le(e,C(e,this.pos),this.start)))return-1}else if(this.stage==2){let t=C(e,this.pos),n=0;if(t>this.pos){let r=Re(e,t,this.start);if(r){let t=M(e,r.to-this.start);t>0&&(this.nextStage(r),n=t)}}return n||=M(e,this.pos),n>0&&n<e.length?n:-1}else return M(e,this.pos)}};function M(e,t){for(;t<e.length;t++){let n=e.charCodeAt(t);if(n==10)break;if(!S(n))return-1}return t}var Ce=class{nextLine(e,t,n){let r=t.depth<e.stack.length?-1:_e(t),i=t.next;if(r<0)return!1;let a=R(x.HeaderMark,e.lineStart+t.pos,e.lineStart+r);return e.nextLine(),e.addLeafElement(n,R(i==61?x.SetextHeading1:x.SetextHeading2,n.start,e.prevLineEnd(),[...e.parser.parseInline(n.content,n.start),a])),!0}finish(){return!1}},we={LinkReference(e,t){return t.content.charCodeAt(0)==91?new Se(t):null},SetextHeading(){return new Ce}},Te=[(e,t)=>ge(t)>=0,(e,t)=>me(t)>=0,(e,t)=>he(t)>=0,(e,t)=>E(t,e,!0)>=0,(e,t)=>D(t,e,!0)>=0,(e,t)=>w(t,e,!0)>=0,(e,t)=>be(t,e,!0)>=0],Ee={text:``,end:0},De=class{constructor(e,t,n,r){this.parser=e,this.input=t,this.ranges=r,this.line=new ue,this.atEnd=!1,this.reusePlaceholders=new Map,this.stoppedAt=null,this.rangeI=0,this.to=r[r.length-1].to,this.lineStart=this.absoluteLineStart=this.absoluteLineEnd=r[0].from,this.block=ce.create(x.Document,0,this.lineStart,0,0),this.stack=[this.block],this.fragments=n.length?new Ve(n,t):null,this.readLine()}get parsedPos(){return this.absoluteLineStart}advance(){if(this.stoppedAt!=null&&this.absoluteLineStart>this.stoppedAt)return this.finish();let{line:e}=this;for(;;){for(let t=0;;){let n=e.depth<this.stack.length?this.stack[this.stack.length-1]:null;for(;t<e.markers.length&&(!n||e.markers[t].from<n.end);){let n=e.markers[t++];this.addNode(n.type,n.from,n.to)}if(!n)break;this.finishContext()}if(e.pos<e.text.length)break;if(!this.nextLine())return this.finish()}if(this.fragments&&this.reuseFragment(e.basePos))return null;start:for(;;){for(let t of this.parser.blockParsers)if(t){let n=t(this,e);if(n!=0){if(n==1)return null;e.forward();continue start}}break}let t=new le(this.lineStart+e.pos,e.text.slice(e.pos));for(let e of this.parser.leafBlockParsers)if(e){let n=e(this,t);n&&t.parsers.push(n)}lines:for(;this.nextLine()&&e.pos!=e.text.length;){if(e.indent<e.baseIndent+4){for(let n of this.parser.endLeafBlock)if(n(this,e,t))break lines}for(let n of t.parsers)if(n.nextLine(this,e,t))return null;t.content+=`
|
|
3
3
|
`+e.scrub();for(let n of e.markers)t.marks.push(n)}return this.finishLeaf(t),null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw RangeError(`Can't move stoppedAt forward`);this.stoppedAt=e}reuseFragment(e){if(!this.fragments.moveTo(this.absoluteLineStart+e,this.absoluteLineStart)||!this.fragments.matches(this.block.hash))return!1;let t=this.fragments.takeNodes(this);return t?(this.absoluteLineStart+=t,this.lineStart=He(this.absoluteLineStart,this.ranges),this.moveRangeI(),this.absoluteLineStart<this.to?(this.lineStart++,this.absoluteLineStart++,this.readLine()):(this.atEnd=!0,this.readLine()),!0):!1}get depth(){return this.stack.length}parentType(e=this.depth-1){return this.parser.nodeSet.types[this.stack[e].type]}nextLine(){return this.lineStart+=this.line.text.length,this.absoluteLineEnd>=this.to?(this.absoluteLineStart=this.absoluteLineEnd,this.atEnd=!0,this.readLine(),!1):(this.lineStart++,this.absoluteLineStart=this.absoluteLineEnd+1,this.moveRangeI(),this.readLine(),!0)}peekLine(){return this.scanLine(this.absoluteLineEnd+1).text}moveRangeI(){for(;this.rangeI<this.ranges.length-1&&this.absoluteLineStart>=this.ranges[this.rangeI].to;)this.rangeI++,this.absoluteLineStart=Math.max(this.absoluteLineStart,this.ranges[this.rangeI].from)}scanLine(e){let t=Ee;if(t.end=e,e>=this.to)t.text=``;else if(t.text=this.lineChunkAt(e),t.end+=t.text.length,this.ranges.length>1){let e=this.absoluteLineStart,n=this.rangeI;for(;this.ranges[n].to<t.end;){n++;let r=this.ranges[n].from,i=this.lineChunkAt(r);t.end=r+i.length,t.text=t.text.slice(0,this.ranges[n-1].to-e)+i,e=t.end-t.text.length}}return t}readLine(){let{line:e}=this,{text:t,end:n}=this.scanLine(this.absoluteLineStart);for(this.absoluteLineEnd=n,e.reset(t);e.depth<this.stack.length;e.depth++){let t=this.stack[e.depth],n=this.parser.skipContextMarkup[t.type];if(!n)throw Error(`Unhandled block context `+x[t.type]);let r=this.line.markers.length;if(!n(t,this,e)){this.line.markers.length>r&&(t.end=this.line.markers[this.line.markers.length-1].to),e.forward();break}e.forward()}}lineChunkAt(e){let t=this.input.chunk(e),n;if(this.input.lineChunks)n=t==`
|
|
4
4
|
`?``:t;else{let e=t.indexOf(`
|