sliccy 1.23.4 → 1.24.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 +6 -0
- package/dist/node-server/runtime-flags.d.ts +1 -0
- package/dist/node-server/runtime-flags.js +6 -0
- package/dist/ui/assets/{___vite-browser-external_commonjs-proxy-BZRJ6_X4.js → ___vite-browser-external_commonjs-proxy-BWNVNhfA.js} +1 -1
- package/dist/ui/assets/anthropic-DpIVtAz7.js +41 -0
- package/dist/ui/assets/azure-openai-responses-DM6ZhYp3.js +1 -0
- package/dist/ui/assets/{bsh-watchdog-BHj7Fs8o.js → bsh-watchdog-u_kfEll6.js} +1 -1
- package/dist/ui/assets/google-DxQyzZcF.js +1 -0
- package/dist/ui/assets/google-gemini-cli-D8wlpibe.js +2 -0
- package/dist/ui/assets/google-shared-DdOR1KIz.js +250 -0
- package/dist/ui/assets/google-vertex-EcFAaDcq.js +1 -0
- package/dist/ui/assets/{index-BbFB6aZt.js → index-BX1RqpKx.js} +2 -2
- package/dist/ui/assets/{index-C7KXlIoI.js → index-BxsPIYVT.js} +1 -1
- package/dist/ui/assets/{index-C9qsgFXA.js → index-CWnZsBG7.js} +1 -1
- package/dist/ui/assets/index-Dw4MBGs3.js +14665 -0
- package/dist/ui/assets/{index-CmZETbUD.js → index-J5ks5yhg.js} +9 -9
- package/dist/ui/assets/{json-parse-BRxcI2Wj.js → json-parse-0sc64RJd.js} +1 -1
- package/dist/ui/assets/mistral-7wTQY92Z.js +12 -0
- package/dist/ui/assets/{offscreen-client-DdMA5sAC.js → offscreen-client-Ch5qQdZk.js} +1 -1
- package/dist/ui/assets/{openai-codex-responses-DXePmJ37.js → openai-codex-responses-BKiIVXQr.js} +1 -1
- package/dist/ui/assets/{openai-completions-BJ5tXvNF.js → openai-completions-X6jnU-kX.js} +3 -3
- package/dist/ui/assets/openai-responses-BH3tsCV7.js +1 -0
- package/dist/ui/assets/{openai-responses-shared-CCp4pUoS.js → openai-responses-shared-DCfz91fA.js} +1 -1
- package/dist/ui/assets/sanitize-unicode-cmozpu7l.js +1 -0
- package/dist/ui/assets/{sql-wasm-WyohJvyK.js → sql-wasm-bQNzDNj9.js} +1 -1
- package/dist/ui/index.html +1 -1
- package/dist/ui/packages/webapp/index.html +1 -1
- package/package.json +1 -1
- package/dist/ui/assets/anthropic-CFRG0Hfe.js +0 -2
- package/dist/ui/assets/anthropic-h0YkYJvY.js +0 -2
- package/dist/ui/assets/azure-openai-responses-B72ahkq2.js +0 -1
- package/dist/ui/assets/azure-openai-responses-DiuVg7QC.js +0 -1
- package/dist/ui/assets/client-CLc9DbbF.js +0 -23
- package/dist/ui/assets/github-copilot-headers-Dz44zqGk.js +0 -1
- package/dist/ui/assets/google-CVSsY19W.js +0 -1
- package/dist/ui/assets/google-FJTEoy_e.js +0 -1
- package/dist/ui/assets/google-gemini-cli-T80C305w.js +0 -2
- package/dist/ui/assets/google-gemini-cli-gF7kFWc4.js +0 -2
- package/dist/ui/assets/google-shared-BjArPveV.js +0 -2
- package/dist/ui/assets/google-shared-CYYiav7i.js +0 -2
- package/dist/ui/assets/google-vertex-6VDNXf5n.js +0 -1
- package/dist/ui/assets/google-vertex-CjjOIg6q.js +0 -1
- package/dist/ui/assets/hash-k-C9KAKF.js +0 -1
- package/dist/ui/assets/index-BTBHJQVY.js +0 -131
- package/dist/ui/assets/index-CMitoXJI.js +0 -45
- package/dist/ui/assets/index-CYH9nDaE.js +0 -15023
- package/dist/ui/assets/index-Et7zk9Rb.js +0 -3
- package/dist/ui/assets/index-TCK0ykMx.js +0 -1
- package/dist/ui/assets/index-uz_REvSi.js +0 -5
- package/dist/ui/assets/json-parse-zqPLE5kv.js +0 -1
- package/dist/ui/assets/mistral-BnNh3LzR.js +0 -8
- package/dist/ui/assets/mistral-DBk4zmZV.js +0 -8
- package/dist/ui/assets/openai-codex-responses-BRTJp-Ny.js +0 -7
- package/dist/ui/assets/openai-completions-CFS00Zu3.js +0 -6
- package/dist/ui/assets/openai-responses-D0cbe-PZ.js +0 -1
- package/dist/ui/assets/openai-responses-GLrZ6X81.js +0 -1
- package/dist/ui/assets/openai-responses-shared-B_0Hvupy.js +0 -10
- package/dist/ui/assets/stream-lEC9OYG2.js +0 -1
- package/dist/ui/assets/transform-messages-BkE2P08Y.js +0 -1
- package/dist/ui/assets/transform-messages-DqxXnsXK.js +0 -1
|
@@ -17,6 +17,12 @@ import { CliLogDedup } from './cli-log-dedup.js';
|
|
|
17
17
|
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
|
18
18
|
const PROJECT_ROOT = resolve(__dirname, '..', '..');
|
|
19
19
|
const RUNTIME_FLAGS = parseCliRuntimeFlags(process.argv.slice(2));
|
|
20
|
+
// Version command — exit immediately, no side effects
|
|
21
|
+
if (RUNTIME_FLAGS.version) {
|
|
22
|
+
const pkg = JSON.parse(readFileSync(join(PROJECT_ROOT, 'package.json'), 'utf8'));
|
|
23
|
+
console.log(pkg.version);
|
|
24
|
+
process.exit(0);
|
|
25
|
+
}
|
|
20
26
|
const DEV_MODE = RUNTIME_FLAGS.dev;
|
|
21
27
|
const SERVE_ONLY = RUNTIME_FLAGS.serveOnly;
|
|
22
28
|
const ELECTRON_MODE = RUNTIME_FLAGS.electron;
|
|
@@ -17,6 +17,7 @@ export interface CliRuntimeFlags {
|
|
|
17
17
|
logDir: string | null;
|
|
18
18
|
/** Initial prompt to auto-submit when the UI loads */
|
|
19
19
|
prompt: string | null;
|
|
20
|
+
version: boolean;
|
|
20
21
|
}
|
|
21
22
|
export declare const DEFAULT_CLI_CDP_PORT = 9222;
|
|
22
23
|
export declare const DEFAULT_ELECTRON_ATTACH_CDP_PORT = 9223;
|
|
@@ -20,8 +20,13 @@ export function parseCliRuntimeFlags(argv) {
|
|
|
20
20
|
let logLevel = 'info';
|
|
21
21
|
let logDir = null;
|
|
22
22
|
let prompt = null;
|
|
23
|
+
let version = false;
|
|
23
24
|
for (let index = 0; index < argv.length; index += 1) {
|
|
24
25
|
const arg = argv[index];
|
|
26
|
+
if (arg === 'version' || arg === '--version' || arg === '-v') {
|
|
27
|
+
version = true;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
25
30
|
if (arg === '--dev') {
|
|
26
31
|
dev = true;
|
|
27
32
|
continue;
|
|
@@ -151,5 +156,6 @@ export function parseCliRuntimeFlags(argv) {
|
|
|
151
156
|
logLevel,
|
|
152
157
|
logDir,
|
|
153
158
|
prompt,
|
|
159
|
+
version,
|
|
154
160
|
};
|
|
155
161
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e}from"./__vite-browser-external-D7Ct-6yo.js";import{
|
|
1
|
+
import{_ as e}from"./__vite-browser-external-D7Ct-6yo.js";import{f as r}from"./index-Dw4MBGs3.js";const a=r(e);export{a as r};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import{A as Us,g as Zt,a as Mt,b as Fs,K as Ds,t as Hs}from"./index-Dw4MBGs3.js";import{p as Rt}from"./json-parse-0sc64RJd.js";import{s as j}from"./sanitize-unicode-cmozpu7l.js";import{h as Js,b as Xs}from"./github-copilot-headers-CrHPofPv.js";function f(n,e,t,s,r){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function a(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)}let es=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return es=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))};function ye(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const ot=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class g extends Error{}class S extends g{constructor(e,t,s,r){super(`${S.makeMessage(e,t,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=t}static makeMessage(e,t,s){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,s,r){if(!e||!r)return new Je({message:s,cause:ot(t)});const i=t;return e===400?new ss(e,i,s,r):e===401?new ns(e,i,s,r):e===403?new rs(e,i,s,r):e===404?new is(e,i,s,r):e===409?new as(e,i,s,r):e===422?new os(e,i,s,r):e===429?new cs(e,i,s,r):e>=500?new ls(e,i,s,r):new S(e,i,s,r)}}class v extends S{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Je extends S{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ts extends Je{constructor({message:e}={}){super({message:e??"Request timed out."})}}class ss extends S{}class ns extends S{}class rs extends S{}class is extends S{}class as extends S{}class os extends S{}class cs extends S{}class ls extends S{}const Ks=/^[a-z][a-z0-9+.-]*:/i,Vs=n=>Ks.test(n);let ct=n=>(ct=Array.isArray,ct(n)),Tt=ct;function lt(n){return typeof n!="object"?{}:n??{}}function zs(n){if(!n)return!0;for(const e in n)return!1;return!0}function Qs(n,e){return Object.prototype.hasOwnProperty.call(n,e)}const Gs=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${n} must be an integer`);if(e<0)throw new g(`${n} must be a positive integer`);return e},us=n=>{try{return JSON.parse(n)}catch{return}},Ys=n=>new Promise(e=>setTimeout(e,n)),z="0.73.0",Zs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function en(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const tn=()=>{const n=en();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":Et(Deno.build.os),"X-Stainless-Arch":Pt(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":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":Et(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Pt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=sn();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function sn(){if(typeof navigator>"u"||!navigator)return null;const n=[{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/}];for(const{key:e,pattern:t}of n){const s=t.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,o=s[3]||0;return{browser:e,version:`${r}.${i}.${o}`}}}return null}const Pt=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",Et=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let vt;const nn=()=>vt??(vt=tn());function rn(){if(typeof fetch<"u")return fetch;throw new 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 hs(...n){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function ds(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return hs({start(){},async pull(t){const{done:s,value:r}=await e.next();s?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}function pt(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function an(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const on=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function cn(n){let e=0;for(const r of n)e+=r.length;const t=new Uint8Array(e);let s=0;for(const r of n)t.set(r,s),s+=r.length;return t}let At;function gt(n){let e;return(At??(e=new globalThis.TextEncoder,At=e.encode.bind(e)))(n)}let Ot;function It(n){let e;return(Ot??(e=new globalThis.TextDecoder,Ot=e.decode.bind(e)))(n)}var R,T;class be{constructor(){R.set(this,void 0),T.set(this,void 0),f(this,R,new Uint8Array),f(this,T,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;f(this,R,cn([a(this,R,"f"),t]));const s=[];let r;for(;(r=ln(a(this,R,"f"),a(this,T,"f")))!=null;){if(r.carriage&&a(this,T,"f")==null){f(this,T,r.index);continue}if(a(this,T,"f")!=null&&(r.index!==a(this,T,"f")+1||r.carriage)){s.push(It(a(this,R,"f").subarray(0,a(this,T,"f")-1))),f(this,R,a(this,R,"f").subarray(a(this,T,"f"))),f(this,T,null);continue}const i=a(this,T,"f")!==null?r.preceding-1:r.preceding,o=It(a(this,R,"f").subarray(0,i));s.push(o),f(this,R,a(this,R,"f").subarray(r.index)),f(this,T,null)}return s}flush(){return a(this,R,"f").length?this.decode(`
|
|
2
|
+
`):[]}}R=new WeakMap,T=new WeakMap;be.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,"\r"]);be.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ln(n,e){for(let r=e??0;r<n.length;r++){if(n[r]===10)return{preceding:r,index:r+1,carriage:!1};if(n[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function un(n){for(let s=0;s<n.length-1;s++){if(n[s]===10&&n[s+1]===10||n[s]===13&&n[s+1]===13)return s+2;if(n[s]===13&&n[s+1]===10&&s+3<n.length&&n[s+2]===13&&n[s+3]===10)return s+4}return-1}const Fe={off:0,error:200,warn:300,info:400,debug:500},Bt=(n,e,t)=>{if(n){if(Qs(Fe,n))return n;x(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Fe))}`)}};function ge(){}function xe(n,e,t){return!e||Fe[n]>Fe[t]?ge:e[n].bind(e)}const hn={error:ge,warn:ge,info:ge,debug:ge};let $t=new WeakMap;function x(n){const e=n.logger,t=n.logLevel??"off";if(!e)return hn;const s=$t.get(e);if(s&&s[0]===t)return s[1];const r={error:xe("error",e,t),warn:xe("warn",e,t),info:xe("info",e,t),debug:xe("debug",e,t)};return $t.set(e,[t,r]),r}const H=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var Z;class I{constructor(e,t,s){this.iterator=e,Z.set(this,void 0),this.controller=t,f(this,Z,s)}static fromSSEResponse(e,t,s){let r=!1;const i=s?x(s):console;async function*o(){if(r)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let c=!1;try{for await(const l of dn(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(d){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),d}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(d){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),d}if(l.event!=="ping"&&l.event==="error")throw new S(void 0,us(l.data)??l.data,void 0,e.headers)}c=!0}catch(l){if(ye(l))return;throw l}finally{c||t.abort()}}return new I(o,t,s)}static fromReadableStream(e,t,s){let r=!1;async function*i(){const c=new be,l=pt(e);for await(const d of l)for(const p of c.decode(d))yield p;for(const d of c.flush())yield d}async function*o(){if(r)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let c=!1;try{for await(const l of i())c||l&&(yield JSON.parse(l));c=!0}catch(l){if(ye(l))return;throw l}finally{c||t.abort()}}return new I(o,t,s)}[(Z=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),r=i=>({next:()=>{if(i.length===0){const o=s.next();e.push(o),t.push(o)}return i.shift()}});return[new I(()=>r(e),this.controller,a(this,Z,"f")),new I(()=>r(t),this.controller,a(this,Z,"f"))]}toReadableStream(){const e=this;let t;return hs({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:i}=await t.next();if(i)return s.close();const o=gt(JSON.stringify(r)+`
|
|
4
|
+
`);s.enqueue(o)}catch(r){s.error(r)}},async cancel(){await t.return?.()}})}}async function*dn(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&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");const t=new pn,s=new be,r=pt(n.body);for await(const i of fn(r))for(const o of s.decode(i)){const c=t.decode(o);c&&(yield c)}for(const i of s.flush()){const o=t.decode(i);o&&(yield o)}}async function*fn(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?gt(t):t;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=un(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class pn{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;const i={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,r]=gn(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function gn(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function fs(n,e){const{response:t,requestLogID:s,retryOfRequestLogID:r,startTime:i}=e,o=await(async()=>{if(e.options.stream)return x(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):I.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;const m=await t.json();return ps(m,t)}return await t.text()})();return x(n).debug(`[${s}] response parsed`,H({retryOfRequestLogID:r,url:t.url,status:t.status,body:o,durationMs:Date.now()-i})),o}function ps(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var me;class Xe extends Promise{constructor(e,t,s=fs){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=s,me.set(this,void 0),f(this,me,e)}_thenUnwrap(e){return new Xe(a(this,me,"f"),this.responsePromise,async(t,s)=>ps(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[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.parsedPromise=this.responsePromise.then(e=>this.parseResponse(a(this,me,"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)}}me=new WeakMap;var Me;class gs{constructor(e,t,s,r){Me.set(this,void 0),f(this,Me,e),this.options=r,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,Me,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Me=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class mn extends Xe{constructor(e,t,s){super(e,t,async(r,i)=>new s(r,i.response,await fs(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class we extends gs{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1,this.first_id=s.first_id||null,this.last_id=s.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const t=this.first_id;return t?{...this.options,query:{...lt(this.options.query),before_id:t}}:null}const e=this.last_id;return e?{...this.options,query:{...lt(this.options.query),after_id:e}}:null}}class ms extends gs{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1,this.next_page=s.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.next_page;return e?{...this.options,query:{...lt(this.options.query),page:e}}:null}}const _s=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function G(n,e,t){return _s(),new File(n,e??"unknown_file",t)}function qe(n,e){const t=typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"";return e?t.split(/[\\/]/).pop()||void 0:t}const ys=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",mt=async(n,e,t=!0)=>({...n,body:await yn(n.body,e,t)}),Ct=new WeakMap;function _n(n){const e=typeof n=="function"?n:n.fetch,t=Ct.get(e);if(t)return t;const s=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return Ct.set(e,s),s}const yn=async(n,e,t=!0)=>{if(!await _n(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,i])=>ut(s,r,i,t))),s},bn=n=>n instanceof Blob&&"name"in n,ut=async(n,e,t,s)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response){let r={};const i=t.headers.get("Content-Type");i&&(r={type:i}),n.append(e,G([await t.blob()],qe(t,s),r))}else if(ys(t))n.append(e,G([await new Response(ds(t)).blob()],qe(t,s)));else if(bn(t))n.append(e,G([t],qe(t,s),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(r=>ut(n,e+"[]",r,s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,i])=>ut(n,`${e}[${r}]`,i,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},bs=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",wn=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&bs(n),kn=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function Sn(n,e,t){if(_s(),n=await n,e||(e=qe(n,!0)),wn(n))return n instanceof File&&e==null&&t==null?n:G([await n.arrayBuffer()],e??n.name,{type:n.type,lastModified:n.lastModified,...t});if(kn(n)){const r=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),G(await ht(r),e,t)}const s=await ht(n);if(!t?.type){const r=s.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return G(s,e,t)}async function ht(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(bs(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(ys(n))for await(const t of n)e.push(...await ht(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${xn(n)}`)}return e}function xn(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class A{constructor(e){this._client=e}}const ws=Symbol.for("brand.privateNullableHeaders");function*Mn(n){if(!n)return;if(ws in n){const{values:s,nulls:r}=n;yield*s.entries();for(const i of r)yield[i,null];return}let e=!1,t;n instanceof Headers?t=n.entries():Tt(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let s of t){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=Tt(s[1])?s[1]:[s[1]];let o=!1;for(const c of i)c!==void 0&&(e&&!o&&(o=!0,yield[r,null]),yield[r,c])}}const _=n=>{const e=new Headers,t=new Set;for(const s of n){const r=new Set;for(const[i,o]of Mn(s)){const c=i.toLowerCase();r.has(c)||(e.delete(i),r.add(c)),o===null?(e.delete(i),t.add(c)):(e.append(i,o),t.delete(c))}}return{[ws]:!0,values:e,nulls:t}},_e=Symbol("anthropic.sdk.stainlessHelper");function We(n){return typeof n=="object"&&n!==null&&_e in n}function ks(n,e){const t=new Set;if(n)for(const s of n)We(s)&&t.add(s[_e]);if(e){for(const s of e)if(We(s)&&t.add(s[_e]),Array.isArray(s.content))for(const r of s.content)We(r)&&t.add(r[_e])}return Array.from(t)}function Ss(n,e){const t=ks(n,e);return t.length===0?{}:{"x-stainless-helper":t.join(", ")}}function Rn(n){return We(n)?{"x-stainless-helper":n[_e]}:{}}function xs(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const jt=Object.freeze(Object.create(null)),Tn=(n=xs)=>function(t,...s){if(t.length===1)return t[0];let r=!1;const i=[],o=t.reduce((p,h,m)=>{/[?#]/.test(h)&&(r=!0);const u=s[m];let y=(r?encodeURIComponent:n)(""+u);return m!==s.length&&(u==null||typeof u=="object"&&u.toString===Object.getPrototypeOf(Object.getPrototypeOf(u.hasOwnProperty??jt)??jt)?.toString)&&(y=u+"",i.push({start:p.length+h.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(u).slice(8,-1)} is not a valid path parameter`})),p+h+(m===s.length?"":y)},""),c=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let d;for(;(d=l.exec(c))!==null;)i.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(i.sort((p,h)=>p.start-h.start),i.length>0){let p=0;const h=i.reduce((m,u)=>{const y=" ".repeat(u.start-p),Ve="^".repeat(u.length);return p=u.start+u.length,m+y+Ve},"");throw new g(`Path parameters result in path with invalid segments:
|
|
6
|
+
${i.map(m=>m.error).join(`
|
|
7
|
+
`)}
|
|
8
|
+
${o}
|
|
9
|
+
${h}`)}return o},k=Tn(xs);class Ms extends A{list(e={},t){const{betas:s,...r}=e??{};return this._client.getAPIList("/v1/files",we,{query:r,...t,headers:_([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},s){const{betas:r}=t??{};return this._client.delete(k`/v1/files/${e}`,{...s,headers:_([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},s?.headers])})}download(e,t={},s){const{betas:r}=t??{};return this._client.get(k`/v1/files/${e}/content`,{...s,headers:_([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},s){const{betas:r}=t??{};return this._client.get(k`/v1/files/${e}`,{...s,headers:_([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},s?.headers])})}upload(e,t){const{betas:s,...r}=e;return this._client.post("/v1/files",mt({body:r,...t,headers:_([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},Rn(r.file),t?.headers])},this._client))}}let Rs=class extends A{retrieve(e,t={},s){const{betas:r}=t??{};return this._client.get(k`/v1/models/${e}?beta=true`,{...s,headers:_([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",we,{query:r,...t,headers:_([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}};const Ts={"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 Ps(n){return n?.output_format??n?.output_config?.format}function Nt(n,e,t){const s=Ps(e);return!e||!("parse"in(s??{}))?{...n,content:n.content.map(r=>{if(r.type==="text"){const i=Object.defineProperty({...r},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return r}),parsed_output:null}:Es(n,e,t)}function Es(n,e,t){let s=null;const r=n.content.map(i=>{if(i.type==="text"){const o=Pn(e,i.text);s===null&&(s=o);const c=Object.defineProperty({...i},"parsed_output",{value:o,enumerable:!1});return Object.defineProperty(c,"parsed",{get(){return t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),o},enumerable:!1})}return i});return{...n,content:r,parsed_output:s}}function Pn(n,e){const t=Ps(n);if(t?.type!=="json_schema")return null;try{return"parse"in t?t.parse(e):JSON.parse(e)}catch(s){throw new g(`Failed to parse structured output: ${s}`)}}const En=n=>{let e=0,t=[];for(;e<n.length;){let s=n[e];if(s==="\\"){e++;continue}if(s==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(s==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(s==="["){t.push({type:"paren",value:"["}),e++;continue}if(s==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(s===":"){t.push({type:"separator",value:":"}),e++;continue}if(s===","){t.push({type:"delimiter",value:","}),e++;continue}if(s==='"'){let c="",l=!1;for(s=n[++e];s!=='"';){if(e===n.length){l=!0;break}if(s==="\\"){if(e++,e===n.length){l=!0;break}c+=s+n[e],s=n[++e]}else c+=s,s=n[++e]}s=n[++e],l||t.push({type:"string",value:c});continue}if(s&&/\s/.test(s)){e++;continue}let i=/[0-9]/;if(s&&i.test(s)||s==="-"||s==="."){let c="";for(s==="-"&&(c+=s,s=n[++e]);s&&i.test(s)||s===".";)c+=s,s=n[++e];t.push({type:"number",value:c});continue}let o=/[a-z]/i;if(s&&o.test(s)){let c="";for(;s&&o.test(s)&&e!==n.length;)c+=s,s=n[++e];if(c=="true"||c=="false"||c==="null")t.push({type:"name",value:c});else{e++;continue}continue}e++}return t},Q=n=>{if(n.length===0)return n;let e=n[n.length-1];switch(e.type){case"separator":return n=n.slice(0,n.length-1),Q(n);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return n=n.slice(0,n.length-1),Q(n);case"string":let s=n[n.length-2];if(s?.type==="delimiter")return n=n.slice(0,n.length-1),Q(n);if(s?.type==="brace"&&s.value==="{")return n=n.slice(0,n.length-1),Q(n);break;case"delimiter":return n=n.slice(0,n.length-1),Q(n)}return n},vn=n=>{let e=[];return n.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?n.push({type:"brace",value:"}"}):t==="]"&&n.push({type:"paren",value:"]"})}),n},An=n=>{let e="";return n.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},vs=n=>JSON.parse(An(vn(Q(En(n)))));var P,L,X,ee,Re,te,se,Te,ne,$,re,Pe,Ee,U,ve,Ae,ie,Qe,Lt,Oe,Ge,Ye,Ze,qt;const Wt="__json_buf";function Ut(n){return n.type==="tool_use"||n.type==="server_tool_use"||n.type==="mcp_tool_use"}class De{constructor(e,t){P.add(this),this.messages=[],this.receivedMessages=[],L.set(this,void 0),X.set(this,null),this.controller=new AbortController,ee.set(this,void 0),Re.set(this,()=>{}),te.set(this,()=>{}),se.set(this,void 0),Te.set(this,()=>{}),ne.set(this,()=>{}),$.set(this,{}),re.set(this,!1),Pe.set(this,!1),Ee.set(this,!1),U.set(this,!1),ve.set(this,void 0),Ae.set(this,void 0),ie.set(this,void 0),Oe.set(this,s=>{if(f(this,Pe,!0),ye(s)&&(s=new v),s instanceof v)return f(this,Ee,!0),this._emit("abort",s);if(s instanceof g)return this._emit("error",s);if(s instanceof Error){const r=new g(s.message);return r.cause=s,this._emit("error",r)}return this._emit("error",new g(String(s)))}),f(this,ee,new Promise((s,r)=>{f(this,Re,s,"f"),f(this,te,r,"f")})),f(this,se,new Promise((s,r)=>{f(this,Te,s,"f"),f(this,ne,r,"f")})),a(this,ee,"f").catch(()=>{}),a(this,se,"f").catch(()=>{}),f(this,X,e),f(this,ie,t?.logger??console)}get response(){return a(this,ve,"f")}get request_id(){return a(this,Ae,"f")}async withResponse(){f(this,U,!0);const e=await a(this,ee,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new De(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,s,{logger:r}={}){const i=new De(t,{logger:r});for(const o of t.messages)i._addMessageParam(o);return f(i,X,{...t,stream:!0}),i._run(()=>i._createMessage(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},a(this,Oe,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){const r=s?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{a(this,P,"m",Ge).call(this);const{response:o,data:c}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of c)a(this,P,"m",Ye).call(this,l);if(c.controller.signal?.aborted)throw new v;a(this,P,"m",Ze).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(f(this,ve,e),f(this,Ae,e?.headers.get("request-id")),a(this,Re,"f").call(this,e),this._emit("connect"))}get ended(){return a(this,re,"f")}get errored(){return a(this,Pe,"f")}get aborted(){return a(this,Ee,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,$,"f")[e]||(a(this,$,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=a(this,$,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===t);return r>=0&&s.splice(r,1),this}once(e,t){return(a(this,$,"f")[e]||(a(this,$,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{f(this,U,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){f(this,U,!0),await a(this,se,"f")}get currentMessage(){return a(this,L,"f")}async finalMessage(){return await this.done(),a(this,P,"m",Qe).call(this)}async finalText(){return await this.done(),a(this,P,"m",Lt).call(this)}_emit(e,...t){if(a(this,re,"f"))return;e==="end"&&(f(this,re,!0),a(this,Te,"f").call(this));const s=a(this,$,"f")[e];if(s&&(a(this,$,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!a(this,U,"f")&&!s?.length&&Promise.reject(r),a(this,te,"f").call(this,r),a(this,ne,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!a(this,U,"f")&&!s?.length&&Promise.reject(r),a(this,te,"f").call(this,r),a(this,ne,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",a(this,P,"m",Qe).call(this))}async _fromReadableStream(e,t){const s=t?.signal;let r;s&&(s.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),s.addEventListener("abort",r));try{a(this,P,"m",Ge).call(this),this._connected(null);const i=I.fromReadableStream(e,this.controller);for await(const o of i)a(this,P,"m",Ye).call(this,o);if(i.controller.signal?.aborted)throw new v;a(this,P,"m",Ze).call(this)}finally{s&&r&&s.removeEventListener("abort",r)}}[(L=new WeakMap,X=new WeakMap,ee=new WeakMap,Re=new WeakMap,te=new WeakMap,se=new WeakMap,Te=new WeakMap,ne=new WeakMap,$=new WeakMap,re=new WeakMap,Pe=new WeakMap,Ee=new WeakMap,U=new WeakMap,ve=new WeakMap,Ae=new WeakMap,ie=new WeakMap,Oe=new WeakMap,P=new WeakSet,Qe=function(){if(this.receivedMessages.length===0)throw new g("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Lt=function(){if(this.receivedMessages.length===0)throw new g("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(t.length===0)throw new g("stream ended without producing a content block with type=text");return t.join(" ")},Ge=function(){this.ended||f(this,L,void 0)},Ye=function(t){if(this.ended)return;const s=a(this,P,"m",qt).call(this,t);switch(this._emit("streamEvent",t,s),t.type){case"content_block_delta":{const r=s.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{Ut(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}case"compaction_delta":{r.type==="compaction"&&r.content&&this._emit("compaction",r.content);break}default:t.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(Nt(s,a(this,X,"f"),{logger:a(this,ie,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{f(this,L,s);break}}},Ze=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");const t=a(this,L,"f");if(!t)throw new g("request ended without sending any chunks");return f(this,L,void 0),Nt(t,a(this,X,"f"),{logger:a(this,ie,"f")})},qt=function(t){let s=a(this,L,"f");if(t.type==="message_start"){if(s)throw new g(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!s)throw new g(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return s;case"message_delta":return s.container=t.delta.container,s.stop_reason=t.delta.stop_reason,s.stop_sequence=t.delta.stop_sequence,s.usage.output_tokens=t.usage.output_tokens,s.context_management=t.context_management,t.usage.input_tokens!=null&&(s.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(s.usage.server_tool_use=t.usage.server_tool_use),t.usage.iterations!=null&&(s.usage.iterations=t.usage.iterations),s;case"content_block_start":return s.content.push(t.content_block),s;case"content_block_delta":{const r=s.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(s.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(s.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&Ut(r)){let i=r[Wt]||"";i+=t.delta.partial_json;const o={...r};if(Object.defineProperty(o,Wt,{value:i,enumerable:!1,writable:!0}),i)try{o.input=vs(i)}catch(c){const l=new g(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${i}`);a(this,Oe,"f").call(this,l)}s.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(s.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(s.content[t.index]={...r,signature:t.delta.signature});break}case"compaction_delta":{r?.type==="compaction"&&(s.content[t.index]={...r,content:(r.content||"")+t.delta.content});break}default:t.delta}return s}case"content_block_stop":return s}},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new I(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class As extends Error{constructor(e){const t=typeof e=="string"?e:e.map(s=>s.type==="text"?s.text:`[${s.type}]`).join(" ");super(t),this.name="ToolError",this.content=e}}const On=1e5,In=`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:
|
|
10
|
+
1. Task Overview
|
|
11
|
+
The user's core request and success criteria
|
|
12
|
+
Any clarifications or constraints they specified
|
|
13
|
+
2. Current State
|
|
14
|
+
What has been completed so far
|
|
15
|
+
Files created, modified, or analyzed (with paths if relevant)
|
|
16
|
+
Key outputs or artifacts produced
|
|
17
|
+
3. Important Discoveries
|
|
18
|
+
Technical constraints or requirements uncovered
|
|
19
|
+
Decisions made and their rationale
|
|
20
|
+
Errors encountered and how they were resolved
|
|
21
|
+
What approaches were tried that didn't work (and why)
|
|
22
|
+
4. Next Steps
|
|
23
|
+
Specific actions needed to complete the task
|
|
24
|
+
Any blockers or open questions to resolve
|
|
25
|
+
Priority order if multiple steps remain
|
|
26
|
+
5. Context to Preserve
|
|
27
|
+
User preferences or style requirements
|
|
28
|
+
Domain-specific details that aren't obvious
|
|
29
|
+
Any promises made to the user
|
|
30
|
+
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.
|
|
31
|
+
Wrap your summary in <summary></summary> tags.`;var ae,K,F,w,oe,M,N,q,ce,Ft,dt;function Dt(){let n,e;return{promise:new Promise((s,r)=>{n=s,e=r}),resolve:n,reject:e}}class Os{constructor(e,t,s){ae.add(this),this.client=e,K.set(this,!1),F.set(this,!1),w.set(this,void 0),oe.set(this,void 0),M.set(this,void 0),N.set(this,void 0),q.set(this,void 0),ce.set(this,0),f(this,w,{params:{...t,messages:structuredClone(t.messages)}});const i=["BetaToolRunner",...ks(t.tools,t.messages)].join(", ");f(this,oe,{...s,headers:_([{"x-stainless-helper":i},s?.headers])}),f(this,q,Dt())}async*[(K=new WeakMap,F=new WeakMap,w=new WeakMap,oe=new WeakMap,M=new WeakMap,N=new WeakMap,q=new WeakMap,ce=new WeakMap,ae=new WeakSet,Ft=async function(){const t=a(this,w,"f").params.compactionControl;if(!t||!t.enabled)return!1;let s=0;if(a(this,M,"f")!==void 0)try{const d=await a(this,M,"f");s=d.usage.input_tokens+(d.usage.cache_creation_input_tokens??0)+(d.usage.cache_read_input_tokens??0)+d.usage.output_tokens}catch{return!1}const r=t.contextTokenThreshold??On;if(s<r)return!1;const i=t.model??a(this,w,"f").params.model,o=t.summaryPrompt??In,c=a(this,w,"f").params.messages;if(c[c.length-1].role==="assistant"){const d=c[c.length-1];if(Array.isArray(d.content)){const p=d.content.filter(h=>h.type!=="tool_use");p.length===0?c.pop():d.content=p}}const l=await this.client.beta.messages.create({model:i,messages:[...c,{role:"user",content:[{type:"text",text:o}]}],max_tokens:a(this,w,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(l.content[0]?.type!=="text")throw new g("Expected text response for compaction");return a(this,w,"f").params.messages=[{role:"user",content:l.content}],!0},Symbol.asyncIterator)](){var e;if(a(this,K,"f"))throw new g("Cannot iterate over a consumed stream");f(this,K,!0),f(this,F,!0),f(this,N,void 0);try{for(;;){let t;try{if(a(this,w,"f").params.max_iterations&&a(this,ce,"f")>=a(this,w,"f").params.max_iterations)break;f(this,F,!1,"f"),f(this,N,void 0,"f"),f(this,ce,(e=a(this,ce,"f"),e++,e),"f"),f(this,M,void 0,"f");const{max_iterations:s,compactionControl:r,...i}=a(this,w,"f").params;if(i.stream?(t=this.client.beta.messages.stream({...i},a(this,oe,"f")),f(this,M,t.finalMessage(),"f"),a(this,M,"f").catch(()=>{}),yield t):(f(this,M,this.client.beta.messages.create({...i,stream:!1},a(this,oe,"f")),"f"),yield a(this,M,"f")),!await a(this,ae,"m",Ft).call(this)){if(!a(this,F,"f")){const{role:l,content:d}=await a(this,M,"f");a(this,w,"f").params.messages.push({role:l,content:d})}const c=await a(this,ae,"m",dt).call(this,a(this,w,"f").params.messages.at(-1));if(c)a(this,w,"f").params.messages.push(c);else if(!a(this,F,"f"))break}}finally{t&&t.abort()}}if(!a(this,M,"f"))throw new g("ToolRunner concluded without a message from the server");a(this,q,"f").resolve(await a(this,M,"f"))}catch(t){throw f(this,K,!1),a(this,q,"f").promise.catch(()=>{}),a(this,q,"f").reject(t),f(this,q,Dt()),t}}setMessagesParams(e){typeof e=="function"?a(this,w,"f").params=e(a(this,w,"f").params):a(this,w,"f").params=e,f(this,F,!0),f(this,N,void 0)}async generateToolResponse(){const e=await a(this,M,"f")??this.params.messages.at(-1);return e?a(this,ae,"m",dt).call(this,e):null}done(){return a(this,q,"f").promise}async runUntilDone(){if(!a(this,K,"f"))for await(const e of this);return this.done()}get params(){return a(this,w,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}}dt=async function(e){return a(this,N,"f")!==void 0?a(this,N,"f"):(f(this,N,Bn(a(this,w,"f").params,e)),a(this,N,"f"))};async function Bn(n,e=n.messages.at(-1)){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;const t=e.content.filter(r=>r.type==="tool_use");return t.length===0?null:{role:"user",content:await Promise.all(t.map(async r=>{const i=n.tools.find(o=>("name"in o?o.name:o.mcp_server_name)===r.name);if(!i||!("run"in i))return{type:"tool_result",tool_use_id:r.id,content:`Error: Tool '${r.name}' not found`,is_error:!0};try{let o=r.input;"parse"in i&&i.parse&&(o=i.parse(o));const c=await i.run(o);return{type:"tool_result",tool_use_id:r.id,content:c}}catch(o){return{type:"tool_result",tool_use_id:r.id,content:o instanceof As?o.content:`Error: ${o instanceof Error?o.message:String(o)}`,is_error:!0}}}))}}class Ke{constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new be;for await(const t of this.iterator)for(const s of e.decode(t))yield JSON.parse(s);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&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 Ke(pt(e.body),t)}}let Is=class extends A{create(e,t){const{betas:s,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...t,headers:_([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},s){const{betas:r}=t??{};return this._client.get(k`/v1/messages/batches/${e}?beta=true`,{...s,headers:_([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},s?.headers])})}list(e={},t){const{betas:s,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",we,{query:r,...t,headers:_([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},s){const{betas:r}=t??{};return this._client.delete(k`/v1/messages/batches/${e}?beta=true`,{...s,headers:_([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},s?.headers])})}cancel(e,t={},s){const{betas:r}=t??{};return this._client.post(k`/v1/messages/batches/${e}/cancel?beta=true`,{...s,headers:_([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},s?.headers])})}async results(e,t={},s){const 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}`);const{betas:i}=t??{};return this._client.get(r.results_url,{...s,headers:_([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},s?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,c)=>Ke.fromResponse(c.response,c.controller))}};const Ht={"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"},$n=["claude-opus-4-6"];let ke=class extends A{constructor(){super(...arguments),this.batches=new Is(this._client)}create(e,t){const s=Jt(e),{betas:r,...i}=s;i.model in Ht&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${Ht[i.model]}
|
|
32
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),i.model in $n&&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 o=this._client._options.timeout;if(!i.stream&&o==null){const l=Ts[i.model]??void 0;o=this._client.calculateNonstreamingTimeout(i.max_tokens,l)}const c=Ss(i.tools,i.messages);return this._client.post("/v1/messages?beta=true",{body:i,timeout:o??6e5,...t,headers:_([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},c,t?.headers]),stream:s.stream??!1})}parse(e,t){return t={...t,headers:_([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])},this.create(e,t).then(s=>Es(s,e,{logger:this._client.logger??console}))}stream(e,t){return De.createMessage(this,e,t)}countTokens(e,t){const s=Jt(e),{betas:r,...i}=s;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...t,headers:_([{"anthropic-beta":[...r??[],"token-counting-2024-11-01"].toString()},t?.headers])})}toolRunner(e,t){return new Os(this._client,e,t)}};function Jt(n){if(!n.output_format)return n;if(n.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).");const{output_format:e,...t}=n;return{...t,output_config:{...n.output_config,format:e}}}ke.Batches=Is;ke.BetaToolRunner=Os;ke.ToolError=As;class Bs extends A{create(e,t={},s){const{betas:r,...i}=t??{};return this._client.post(k`/v1/skills/${e}/versions?beta=true`,mt({body:i,...s,headers:_([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},s?.headers])},this._client))}retrieve(e,t,s){const{skill_id:r,betas:i}=t;return this._client.get(k`/v1/skills/${r}/versions/${e}?beta=true`,{...s,headers:_([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},s?.headers])})}list(e,t={},s){const{betas:r,...i}=t??{};return this._client.getAPIList(k`/v1/skills/${e}/versions?beta=true`,ms,{query:i,...s,headers:_([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},s?.headers])})}delete(e,t,s){const{skill_id:r,betas:i}=t;return this._client.delete(k`/v1/skills/${r}/versions/${e}?beta=true`,{...s,headers:_([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},s?.headers])})}}class _t extends A{constructor(){super(...arguments),this.versions=new Bs(this._client)}create(e={},t){const{betas:s,...r}=e??{};return this._client.post("/v1/skills?beta=true",mt({body:r,...t,headers:_([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},t?.headers])},this._client,!1))}retrieve(e,t={},s){const{betas:r}=t??{};return this._client.get(k`/v1/skills/${e}?beta=true`,{...s,headers:_([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},s?.headers])})}list(e={},t){const{betas:s,...r}=e??{};return this._client.getAPIList("/v1/skills?beta=true",ms,{query:r,...t,headers:_([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},t?.headers])})}delete(e,t={},s){const{betas:r}=t??{};return this._client.delete(k`/v1/skills/${e}?beta=true`,{...s,headers:_([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},s?.headers])})}}_t.Versions=Bs;class Y extends A{constructor(){super(...arguments),this.models=new Rs(this._client),this.messages=new ke(this._client),this.files=new Ms(this._client),this.skills=new _t(this._client)}}Y.Models=Rs;Y.Messages=ke;Y.Files=Ms;Y.Skills=_t;class $s extends A{create(e,t){const{betas:s,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...t,headers:_([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}function Cs(n){return n?.output_config?.format}function Xt(n,e,t){const s=Cs(e);return!e||!("parse"in(s??{}))?{...n,content:n.content.map(r=>r.type==="text"?Object.defineProperty({...r},"parsed_output",{value:null,enumerable:!1}):r),parsed_output:null}:js(n,e)}function js(n,e,t){let s=null;const r=n.content.map(i=>{if(i.type==="text"){const o=Cn(e,i.text);return s===null&&(s=o),Object.defineProperty({...i},"parsed_output",{value:o,enumerable:!1})}return i});return{...n,content:r,parsed_output:s}}function Cn(n,e){const t=Cs(n);if(t?.type!=="json_schema")return null;try{return"parse"in t?t.parse(e):JSON.parse(e)}catch(s){throw new g(`Failed to parse structured output: ${s}`)}}var E,W,V,le,Ie,ue,he,Be,de,C,fe,$e,Ce,D,je,Ne,pe,et,Kt,tt,st,nt,rt,Vt;const zt="__json_buf";function Qt(n){return n.type==="tool_use"||n.type==="server_tool_use"}class He{constructor(e,t){E.add(this),this.messages=[],this.receivedMessages=[],W.set(this,void 0),V.set(this,null),this.controller=new AbortController,le.set(this,void 0),Ie.set(this,()=>{}),ue.set(this,()=>{}),he.set(this,void 0),Be.set(this,()=>{}),de.set(this,()=>{}),C.set(this,{}),fe.set(this,!1),$e.set(this,!1),Ce.set(this,!1),D.set(this,!1),je.set(this,void 0),Ne.set(this,void 0),pe.set(this,void 0),tt.set(this,s=>{if(f(this,$e,!0),ye(s)&&(s=new v),s instanceof v)return f(this,Ce,!0),this._emit("abort",s);if(s instanceof g)return this._emit("error",s);if(s instanceof Error){const r=new g(s.message);return r.cause=s,this._emit("error",r)}return this._emit("error",new g(String(s)))}),f(this,le,new Promise((s,r)=>{f(this,Ie,s,"f"),f(this,ue,r,"f")})),f(this,he,new Promise((s,r)=>{f(this,Be,s,"f"),f(this,de,r,"f")})),a(this,le,"f").catch(()=>{}),a(this,he,"f").catch(()=>{}),f(this,V,e),f(this,pe,t?.logger??console)}get response(){return a(this,je,"f")}get request_id(){return a(this,Ne,"f")}async withResponse(){f(this,D,!0);const e=await a(this,le,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new He(null);return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,s,{logger:r}={}){const i=new He(t,{logger:r});for(const o of t.messages)i._addMessageParam(o);return f(i,V,{...t,stream:!0}),i._run(()=>i._createMessage(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},a(this,tt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,s){const r=s?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{a(this,E,"m",st).call(this);const{response:o,data:c}=await e.create({...t,stream:!0},{...s,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of c)a(this,E,"m",nt).call(this,l);if(c.controller.signal?.aborted)throw new v;a(this,E,"m",rt).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(f(this,je,e),f(this,Ne,e?.headers.get("request-id")),a(this,Ie,"f").call(this,e),this._emit("connect"))}get ended(){return a(this,fe,"f")}get errored(){return a(this,$e,"f")}get aborted(){return a(this,Ce,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,C,"f")[e]||(a(this,C,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=a(this,C,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===t);return r>=0&&s.splice(r,1),this}once(e,t){return(a(this,C,"f")[e]||(a(this,C,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{f(this,D,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){f(this,D,!0),await a(this,he,"f")}get currentMessage(){return a(this,W,"f")}async finalMessage(){return await this.done(),a(this,E,"m",et).call(this)}async finalText(){return await this.done(),a(this,E,"m",Kt).call(this)}_emit(e,...t){if(a(this,fe,"f"))return;e==="end"&&(f(this,fe,!0),a(this,Be,"f").call(this));const s=a(this,C,"f")[e];if(s&&(a(this,C,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!a(this,D,"f")&&!s?.length&&Promise.reject(r),a(this,ue,"f").call(this,r),a(this,de,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!a(this,D,"f")&&!s?.length&&Promise.reject(r),a(this,ue,"f").call(this,r),a(this,de,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",a(this,E,"m",et).call(this))}async _fromReadableStream(e,t){const s=t?.signal;let r;s&&(s.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),s.addEventListener("abort",r));try{a(this,E,"m",st).call(this),this._connected(null);const i=I.fromReadableStream(e,this.controller);for await(const o of i)a(this,E,"m",nt).call(this,o);if(i.controller.signal?.aborted)throw new v;a(this,E,"m",rt).call(this)}finally{s&&r&&s.removeEventListener("abort",r)}}[(W=new WeakMap,V=new WeakMap,le=new WeakMap,Ie=new WeakMap,ue=new WeakMap,he=new WeakMap,Be=new WeakMap,de=new WeakMap,C=new WeakMap,fe=new WeakMap,$e=new WeakMap,Ce=new WeakMap,D=new WeakMap,je=new WeakMap,Ne=new WeakMap,pe=new WeakMap,tt=new WeakMap,E=new WeakSet,et=function(){if(this.receivedMessages.length===0)throw new g("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Kt=function(){if(this.receivedMessages.length===0)throw new g("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(s=>s.type==="text").map(s=>s.text);if(t.length===0)throw new g("stream ended without producing a content block with type=text");return t.join(" ")},st=function(){this.ended||f(this,W,void 0)},nt=function(t){if(this.ended)return;const s=a(this,E,"m",Vt).call(this,t);switch(this._emit("streamEvent",t,s),t.type){case"content_block_delta":{const r=s.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{Qt(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(s),this._addMessage(Xt(s,a(this,V,"f"),{logger:a(this,pe,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",s.content.at(-1));break}case"message_start":{f(this,W,s);break}}},rt=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");const t=a(this,W,"f");if(!t)throw new g("request ended without sending any chunks");return f(this,W,void 0),Xt(t,a(this,V,"f"),{logger:a(this,pe,"f")})},Vt=function(t){let s=a(this,W,"f");if(t.type==="message_start"){if(s)throw new g(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!s)throw new g(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return s;case"message_delta":return s.stop_reason=t.delta.stop_reason,s.stop_sequence=t.delta.stop_sequence,s.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(s.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(s.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(s.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(s.usage.server_tool_use=t.usage.server_tool_use),s;case"content_block_start":return s.content.push({...t.content_block}),s;case"content_block_delta":{const r=s.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(s.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(s.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&Qt(r)){let i=r[zt]||"";i+=t.delta.partial_json;const o={...r};Object.defineProperty(o,zt,{value:i,enumerable:!1,writable:!0}),i&&(o.input=vs(i)),s.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(s.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(s.content[t.index]={...r,signature:t.delta.signature});break}default:t.delta}return s}case"content_block_stop":return s}},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new I(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}class Ns extends A{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",we,{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){const s=await this.retrieve(e);if(!s.results_url)throw new g(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);return this._client.get(s.results_url,{...t,headers:_([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,i)=>Ke.fromResponse(i.response,i.controller))}}class yt extends A{constructor(){super(...arguments),this.batches=new Ns(this._client)}create(e,t){e.model in Gt&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Gt[e.model]}
|
|
33
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),e.model in jn&&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 s=this._client._options.timeout;if(!e.stream&&s==null){const i=Ts[e.model]??void 0;s=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}const r=Ss(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:s??6e5,...t,headers:_([r,t?.headers]),stream:e.stream??!1})}parse(e,t){return this.create(e,t).then(s=>js(s,e,{logger:this._client.logger??console}))}stream(e,t){return He.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const Gt={"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"},jn=["claude-opus-4-6"];yt.Batches=Ns;class Ls extends A{retrieve(e,t={},s){const{betas:r}=t??{};return this._client.get(k`/v1/models/${e}`,{...s,headers:_([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},s?.headers])})}list(e={},t){const{betas:s,...r}=e??{};return this._client.getAPIList("/v1/models",we,{query:r,...t,headers:_([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},t?.headers])})}}var Nn={};const Le=n=>{if(typeof globalThis.process<"u")return Nn?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var ft,bt,Ue,qs;const Ln="\\n\\nHuman:",qn="\\n\\nAssistant:";class b{constructor({baseURL:e=Le("ANTHROPIC_BASE_URL"),apiKey:t=Le("ANTHROPIC_API_KEY")??null,authToken:s=Le("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){ft.add(this),Ue.set(this,void 0);const i={apiKey:t,authToken:s,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&Zs())throw new g(`It looks like you're running in a browser-like environment.
|
|
34
|
+
|
|
35
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
36
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
37
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
38
|
+
|
|
39
|
+
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
40
|
+
`);this.baseURL=i.baseURL,this.timeout=i.timeout??bt.DEFAULT_TIMEOUT,this.logger=i.logger??console;const o="warn";this.logLevel=o,this.logLevel=Bt(i.logLevel,"ClientOptions.logLevel",this)??Bt(Le("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??rn(),f(this,Ue,on),this._options=i,this.apiKey=typeof t=="string"?t:null,this.authToken=s}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 new 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 _([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return _([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return _([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,s])=>typeof s<"u").map(([t,s])=>{if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(s)}`;if(s===null)return`${encodeURIComponent(t)}=`;throw new g(`Cannot stringify type ${typeof s}; 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("&")}getUserAgent(){return`${this.constructor.name}/JS ${z}`}defaultIdempotencyKey(){return`stainless-node-retry-${es()}`}makeStatusError(e,t,s,r){return S.generate(e,t,s,r)}buildURL(e,t,s){const r=!a(this,ft,"m",qs).call(this)&&s||this.baseURL,i=Vs(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return zs(o)||(t={...o,...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:s}){}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,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new Xe(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const r=await e,i=r.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(r);const{req:o,url:c,timeout:l}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(o,{url:c,options:r});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),p=s===void 0?"":`, retryOf: ${s}`,h=Date.now();if(x(this).debug(`[${d}] sending request`,H({retryOfRequestLogID:s,method:r.method,url:c,options:r,headers:o.headers})),r.signal?.aborted)throw new v;const m=new AbortController,u=await this.fetchWithTimeout(c,o,l,m).catch(ot),y=Date.now();if(u instanceof globalThis.Error){const B=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new v;const O=ye(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return x(this).info(`[${d}] connection ${O?"timed out":"failed"} - ${B}`),x(this).debug(`[${d}] connection ${O?"timed out":"failed"} (${B})`,H({retryOfRequestLogID:s,url:c,durationMs:y-h,message:u.message})),this.retryRequest(r,t,s??d);throw x(this).info(`[${d}] connection ${O?"timed out":"failed"} - error; no more retries left`),x(this).debug(`[${d}] connection ${O?"timed out":"failed"} (error; no more retries left)`,H({retryOfRequestLogID:s,url:c,durationMs:y-h,message:u.message})),O?new ts:new Je({cause:u})}const Ve=[...u.headers.entries()].filter(([B])=>B==="request-id").map(([B,O])=>", "+B+": "+JSON.stringify(O)).join(""),ze=`[${d}${p}${Ve}] ${o.method} ${c} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${y-h}ms`;if(!u.ok){const B=await this.shouldRetry(u);if(t&&B){const Se=`retrying, ${t} attempts remaining`;return await an(u.body),x(this).info(`${ze} - ${Se}`),x(this).debug(`[${d}] response error (${Se})`,H({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:y-h})),this.retryRequest(r,t,s??d,u.headers)}const O=B?"error; no more retries left":"error; not retryable";x(this).info(`${ze} - ${O}`);const kt=await u.text().catch(Se=>ot(Se).message),St=us(kt),xt=St?void 0:kt;throw x(this).debug(`[${d}] response error (${O})`,H({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,message:xt,durationMs:Date.now()-h})),this.makeStatusError(u.status,St,xt,u.headers)}return x(this).info(ze),x(this).debug(`[${d}] response start`,H({retryOfRequestLogID:s,url:u.url,status:u.status,headers:u.headers,durationMs:y-h})),{response:u,options:r,controller:m,requestLogID:d,retryOfRequestLogID:s,startTime:h}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(r=>({method:"get",path:e,...r})):{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new mn(this,s,e)}async fetchWithTimeout(e,t,s,r){const{signal:i,method:o,...c}=t||{},l=this._makeAbort(r);i&&i.addEventListener("abort",l,{once:!0});const d=setTimeout(l,s),p=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,h={signal:r.signal,...p?{duplex:"half"}:{},method:"GET",...c};o&&(h.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(d)}}async shouldRetry(e){const 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,s,r){let i;const o=r?.get("retry-after-ms");if(o){const l=parseFloat(o);Number.isNaN(l)||(i=l)}const c=r?.get("retry-after");if(c&&!i){const l=parseFloat(c);Number.isNaN(l)?i=Date.parse(c)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Ys(i),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,o=Math.min(.5*Math.pow(2,i),8),c=1-Math.random()*.25;return o*c*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||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 6e5}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:r,path:i,query:o,defaultBaseURL:c}=s,l=this.buildURL(i,o,c);"timeout"in s&&Gs("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:d,body:p}=this.buildBody({options:s}),h=await this.buildHeaders({options:e,method:r,bodyHeaders:d,retryCount:t});return{req:{method:r,headers:h,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&p instanceof globalThis.ReadableStream&&{duplex:"half"},...p&&{body:p},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const 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))}:{},...nn(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=_([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.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:ds(e)}:a(this,Ue,"f").call(this,{body:e,headers:s})}}bt=b,Ue=new WeakMap,ft=new WeakSet,qs=function(){return this.baseURL!=="https://api.anthropic.com"};b.Anthropic=bt;b.HUMAN_PROMPT=Ln;b.AI_PROMPT=qn;b.DEFAULT_TIMEOUT=6e5;b.AnthropicError=g;b.APIError=S;b.APIConnectionError=Je;b.APIConnectionTimeoutError=ts;b.APIUserAbortError=v;b.NotFoundError=is;b.ConflictError=as;b.RateLimitError=cs;b.BadRequestError=ss;b.AuthenticationError=ns;b.InternalServerError=ls;b.PermissionDeniedError=rs;b.UnprocessableEntityError=os;b.toFile=Sn;class J extends b{constructor(){super(...arguments),this.completions=new $s(this),this.messages=new yt(this),this.models=new Ls(this),this.beta=new Y(this)}}J.Completions=$s;J.Messages=yt;J.Models=Ls;J.Beta=Y;var Wn={};function Un(n){return n||(typeof process<"u"&&Wn.PI_CACHE_RETENTION==="long"?"long":"short")}function Fn(n,e){const t=Un(e);if(t==="none")return{retention:t};const s=t==="long"&&n.includes("api.anthropic.com")?"1h":void 0;return{retention:t,cacheControl:{type:"ephemeral",...s&&{ttl:s}}}}const Dn="2.1.75",Hn=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"],Jn=new Map(Hn.map(n=>[n.toLowerCase(),n])),Ws=n=>Jn.get(n.toLowerCase())??n,Xn=(n,e)=>{if(e&&e.length>0){const t=n.toLowerCase(),s=e.find(r=>r.name.toLowerCase()===t);if(s)return s.name}return n};function Yt(n){if(!n.some(r=>r.type==="image"))return j(n.map(r=>r.text).join(`
|
|
41
|
+
`));const t=n.map(r=>r.type==="text"?{type:"text",text:j(r.text)}:{type:"image",source:{type:"base64",media_type:r.mimeType,data:r.data}});return t.some(r=>r.type==="text")||t.unshift({type:"text",text:"(see attached image)"}),t}function it(...n){const e={};for(const t of n)t&&Object.assign(e,t);return e}const at=(n,e,t)=>{const s=new Us;return(async()=>{const r={role:"assistant",content:[],api:n.api,provider:n.provider,model:n.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 i,o;if(t?.client)i=t.client,o=!1;else{const h=t?.apiKey??Zt(n.provider)??"";let m;if(n.provider==="github-copilot"){const y=Js(e.messages);m=Xs({messages:e.messages,hasImages:y})}const u=zn(n,h,t?.interleavedThinking??!0,t?.headers,m);i=u.client,o=u.isOAuthToken}let c=Qn(n,e,o,t);const l=await t?.onPayload?.(c,n);l!==void 0&&(c=l);const d=i.messages.stream({...c,stream:!0},{signal:t?.signal});s.push({type:"start",partial:r});const p=r.content;for await(const h of d)if(h.type==="message_start")r.responseId=h.message.id,r.usage.input=h.message.usage.input_tokens||0,r.usage.output=h.message.usage.output_tokens||0,r.usage.cacheRead=h.message.usage.cache_read_input_tokens||0,r.usage.cacheWrite=h.message.usage.cache_creation_input_tokens||0,r.usage.totalTokens=r.usage.input+r.usage.output+r.usage.cacheRead+r.usage.cacheWrite,Mt(n,r.usage);else if(h.type==="content_block_start"){if(h.content_block.type==="text"){const m={type:"text",text:"",index:h.index};r.content.push(m),s.push({type:"text_start",contentIndex:r.content.length-1,partial:r})}else if(h.content_block.type==="thinking"){const m={type:"thinking",thinking:"",thinkingSignature:"",index:h.index};r.content.push(m),s.push({type:"thinking_start",contentIndex:r.content.length-1,partial:r})}else if(h.content_block.type==="redacted_thinking"){const m={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:h.content_block.data,redacted:!0,index:h.index};r.content.push(m),s.push({type:"thinking_start",contentIndex:r.content.length-1,partial:r})}else if(h.content_block.type==="tool_use"){const m={type:"toolCall",id:h.content_block.id,name:o?Xn(h.content_block.name,e.tools):h.content_block.name,arguments:h.content_block.input??{},partialJson:"",index:h.index};r.content.push(m),s.push({type:"toolcall_start",contentIndex:r.content.length-1,partial:r})}}else if(h.type==="content_block_delta"){if(h.delta.type==="text_delta"){const m=p.findIndex(y=>y.index===h.index),u=p[m];u&&u.type==="text"&&(u.text+=h.delta.text,s.push({type:"text_delta",contentIndex:m,delta:h.delta.text,partial:r}))}else if(h.delta.type==="thinking_delta"){const m=p.findIndex(y=>y.index===h.index),u=p[m];u&&u.type==="thinking"&&(u.thinking+=h.delta.thinking,s.push({type:"thinking_delta",contentIndex:m,delta:h.delta.thinking,partial:r}))}else if(h.delta.type==="input_json_delta"){const m=p.findIndex(y=>y.index===h.index),u=p[m];u&&u.type==="toolCall"&&(u.partialJson+=h.delta.partial_json,u.arguments=Rt(u.partialJson),s.push({type:"toolcall_delta",contentIndex:m,delta:h.delta.partial_json,partial:r}))}else if(h.delta.type==="signature_delta"){const m=p.findIndex(y=>y.index===h.index),u=p[m];u&&u.type==="thinking"&&(u.thinkingSignature=u.thinkingSignature||"",u.thinkingSignature+=h.delta.signature)}}else if(h.type==="content_block_stop"){const m=p.findIndex(y=>y.index===h.index),u=p[m];u&&(delete u.index,u.type==="text"?s.push({type:"text_end",contentIndex:m,content:u.text,partial:r}):u.type==="thinking"?s.push({type:"thinking_end",contentIndex:m,content:u.thinking,partial:r}):u.type==="toolCall"&&(u.arguments=Rt(u.partialJson),delete u.partialJson,s.push({type:"toolcall_end",contentIndex:m,toolCall:u,partial:r})))}else h.type==="message_delta"&&(h.delta.stop_reason&&(r.stopReason=er(h.delta.stop_reason)),h.usage.input_tokens!=null&&(r.usage.input=h.usage.input_tokens),h.usage.output_tokens!=null&&(r.usage.output=h.usage.output_tokens),h.usage.cache_read_input_tokens!=null&&(r.usage.cacheRead=h.usage.cache_read_input_tokens),h.usage.cache_creation_input_tokens!=null&&(r.usage.cacheWrite=h.usage.cache_creation_input_tokens),r.usage.totalTokens=r.usage.input+r.usage.output+r.usage.cacheRead+r.usage.cacheWrite,Mt(n,r.usage));if(t?.signal?.aborted)throw new Error("Request was aborted");if(r.stopReason==="aborted"||r.stopReason==="error")throw new Error("An unknown error occurred");s.push({type:"done",reason:r.stopReason,message:r}),s.end()}catch(i){for(const o of r.content)delete o.index;r.stopReason=t?.signal?.aborted?"aborted":"error",r.errorMessage=i instanceof Error?i.message:JSON.stringify(i),s.push({type:"error",reason:r.stopReason,error:r}),s.end()}})(),s};function wt(n){return n.includes("opus-4-6")||n.includes("opus-4.6")||n.includes("sonnet-4-6")||n.includes("sonnet-4.6")}function Kn(n,e){switch(n){case"minimal":return"low";case"low":return"low";case"medium":return"medium";case"high":return"high";case"xhigh":return e.includes("opus-4-6")||e.includes("opus-4.6")?"max":"high";default:return"high"}}const lr=(n,e,t)=>{const s=t?.apiKey||Zt(n.provider);if(!s)throw new Error(`No API key for provider: ${n.provider}`);const r=Fs(n,t,s);if(!t?.reasoning)return at(n,e,{...r,thinkingEnabled:!1});if(wt(n.id)){const o=Kn(t.reasoning,n.id);return at(n,e,{...r,thinkingEnabled:!0,effort:o})}const i=Ds(r.maxTokens||0,n.maxTokens,t.reasoning,t.thinkingBudgets);return at(n,e,{...r,maxTokens:i.maxTokens,thinkingEnabled:!0,thinkingBudgetTokens:i.thinkingBudget})};function Vn(n){return n.includes("sk-ant-oat")}function zn(n,e,t,s,r){const i=t&&!wt(n.id);if(n.provider==="github-copilot"){const l=[];return i&&l.push("interleaved-thinking-2025-05-14"),{client:new J({apiKey:null,authToken:e,baseURL:n.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:it({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...l.length>0?{"anthropic-beta":l.join(",")}:{}},n.headers,r,s)}),isOAuthToken:!1}}const o=["fine-grained-tool-streaming-2025-05-14"];return i&&o.push("interleaved-thinking-2025-05-14"),Vn(e)?{client:new J({apiKey:null,authToken:e,baseURL:n.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:it({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":`claude-code-20250219,oauth-2025-04-20,${o.join(",")}`,"user-agent":`claude-cli/${Dn}`,"x-app":"cli"},n.headers,s)}),isOAuthToken:!0}:{client:new J({apiKey:e,baseURL:n.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:it({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":o.join(",")},n.headers,s)}),isOAuthToken:!1}}function Qn(n,e,t,s){const{cacheControl:r}=Fn(n.baseUrl,s?.cacheRetention),i={model:n.id,messages:Yn(e.messages,n,t,r),max_tokens:s?.maxTokens||n.maxTokens/3|0,stream:!0};if(t?(i.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...r?{cache_control:r}:{}}],e.systemPrompt&&i.system.push({type:"text",text:j(e.systemPrompt),...r?{cache_control:r}:{}})):e.systemPrompt&&(i.system=[{type:"text",text:j(e.systemPrompt),...r?{cache_control:r}:{}}]),s?.temperature!==void 0&&!s?.thinkingEnabled&&(i.temperature=s.temperature),e.tools&&(i.tools=Zn(e.tools,t)),n.reasoning&&(s?.thinkingEnabled?wt(n.id)?(i.thinking={type:"adaptive"},s.effort&&(i.output_config={effort:s.effort})):i.thinking={type:"enabled",budget_tokens:s.thinkingBudgetTokens||1024}:s?.thinkingEnabled===!1&&(i.thinking={type:"disabled"})),s?.metadata){const o=s.metadata.user_id;typeof o=="string"&&(i.metadata={user_id:o})}return s?.toolChoice&&(typeof s.toolChoice=="string"?i.tool_choice={type:s.toolChoice}:i.tool_choice=s.toolChoice),i}function Gn(n){return n.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Yn(n,e,t,s){const r=[],i=Hs(n,e,Gn);for(let o=0;o<i.length;o++){const c=i[o];if(c.role==="user")if(typeof c.content=="string")c.content.trim().length>0&&r.push({role:"user",content:j(c.content)});else{const l=c.content.map(p=>p.type==="text"?{type:"text",text:j(p.text)}:{type:"image",source:{type:"base64",media_type:p.mimeType,data:p.data}});let d=e?.input.includes("image")?l:l.filter(p=>p.type!=="image");if(d=d.filter(p=>p.type==="text"?p.text.trim().length>0:!0),d.length===0)continue;r.push({role:"user",content:d})}else if(c.role==="assistant"){const l=[];for(const d of c.content)if(d.type==="text"){if(d.text.trim().length===0)continue;l.push({type:"text",text:j(d.text)})}else if(d.type==="thinking"){if(d.redacted){l.push({type:"redacted_thinking",data:d.thinkingSignature});continue}if(d.thinking.trim().length===0)continue;!d.thinkingSignature||d.thinkingSignature.trim().length===0?l.push({type:"text",text:j(d.thinking)}):l.push({type:"thinking",thinking:j(d.thinking),signature:d.thinkingSignature})}else d.type==="toolCall"&&l.push({type:"tool_use",id:d.id,name:t?Ws(d.name):d.name,input:d.arguments??{}});if(l.length===0)continue;r.push({role:"assistant",content:l})}else if(c.role==="toolResult"){const l=[];l.push({type:"tool_result",tool_use_id:c.toolCallId,content:Yt(c.content),is_error:c.isError});let d=o+1;for(;d<i.length&&i[d].role==="toolResult";){const p=i[d];l.push({type:"tool_result",tool_use_id:p.toolCallId,content:Yt(p.content),is_error:p.isError}),d++}o=d-1,r.push({role:"user",content:l})}}if(s&&r.length>0){const o=r[r.length-1];if(o.role==="user")if(Array.isArray(o.content)){const c=o.content[o.content.length-1];c&&(c.type==="text"||c.type==="image"||c.type==="tool_result")&&(c.cache_control=s)}else typeof o.content=="string"&&(o.content=[{type:"text",text:o.content,cache_control:s}])}return r}function Zn(n,e){return n?n.map(t=>{const s=t.parameters;return{name:e?Ws(t.name):t.name,description:t.description,input_schema:{type:"object",properties:s.properties||{},required:s.required||[]}}}):[]}function er(n){switch(n){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 new Error(`Unhandled stop reason: ${n}`)}}export{at as streamAnthropic,lr as streamSimpleAnthropic};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{O as f,a as c,r as m,i as E,b as _}from"./client-DFw1b8C8.js";import{A as h,g as l,b as R,s as y,d as I}from"./index-Dw4MBGs3.js";import{p as O,c as N,a as g}from"./openai-responses-shared-DCfz91fA.js";import"./hash-DMDecQcg.js";import"./json-parse-0sc64RJd.js";import"./sanitize-unicode-cmozpu7l.js";var b={};class v extends f{constructor({baseURL:r=m("OPENAI_BASE_URL"),apiKey:e=m("AZURE_OPENAI_API_KEY"),apiVersion:t=m("OPENAI_API_VERSION"),endpoint:n,deployment:a,azureADTokenProvider:o,dangerouslyAllowBrowser:i,...u}={}){if(!t)throw new c("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof o=="function"&&(i=!0),!o&&!e)throw new c("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&e)throw new c("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(u.defaultQuery={...u.defaultQuery,"api-version":t},r){if(n)throw new c("baseURL and endpoint are mutually exclusive")}else{if(n||(n=b.AZURE_OPENAI_ENDPOINT),!n)throw new c("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");r=`${n}/openai`}super({apiKey:o??e,baseURL:r,...u,...i!==void 0?{dangerouslyAllowBrowser:i}:{}}),this.apiVersion="",this.apiVersion=t,this.deploymentName=a}async buildRequest(r,e={}){if(P.has(r.path)&&r.method==="post"&&r.body!==void 0){if(!E(r.body))throw new Error("Expected request body to be an object");const t=this.deploymentName||r.body.model||r.__metadata?.model;t!==void 0&&!this.baseURL.includes("/deployments")&&(r.path=`/deployments/${t}${r.path}`)}return super.buildRequest(r,e)}async authHeaders(r){return typeof this._options.apiKey=="string"?_([{"api-key":this.apiKey}]):super.authHeaders(r)}}const P=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var p={};const U="v1",w=new Set(["openai","openai-codex","opencode","azure-openai-responses"]);function S(s){const r=new Map;if(!s)return r;for(const e of s.split(",")){const t=e.trim();if(!t)continue;const[n,a]=t.split("=",2);!n||!a||r.set(n.trim(),a.trim())}return r}function z(s,r){return r?.azureDeploymentName?r.azureDeploymentName:S(p.AZURE_OPENAI_DEPLOYMENT_NAME_MAP).get(s.id)||s.id}const Z=(s,r,e)=>{const t=new h;return(async()=>{const n=z(s,e),a={role:"assistant",content:[],api:"azure-openai-responses",provider:s.provider,model:s.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{const o=e?.apiKey||l(s.provider)||"",i=L(s,o,e);let u=V(s,r,e,n);const d=await e?.onPayload?.(u,s);d!==void 0&&(u=d);const A=await i.responses.create(u,e?.signal?{signal:e.signal}:void 0);if(t.push({type:"start",partial:a}),await O(A,a,t,s),e?.signal?.aborted)throw new Error("Request was aborted");if(a.stopReason==="aborted"||a.stopReason==="error")throw new Error("An unknown error occurred");t.push({type:"done",reason:a.stopReason,message:a}),t.end()}catch(o){for(const i of a.content)delete i.index;a.stopReason=e?.signal?.aborted?"aborted":"error",a.errorMessage=o instanceof Error?o.message:JSON.stringify(o),t.push({type:"error",reason:a.stopReason,error:a}),t.end()}})(),t},Y=(s,r,e)=>{const t=e?.apiKey||l(s.provider);if(!t)throw new Error(`No API key for provider: ${s.provider}`);const n=R(s,e,t),a=y(s)?e?.reasoning:I(e?.reasoning);return Z(s,r,{...n,reasoningEffort:a})};function M(s){return s.replace(/\/+$/,"")}function D(s){return`https://${s}.openai.azure.com/openai/v1`}function K(s,r){const e=r?.azureApiVersion||p.AZURE_OPENAI_API_VERSION||U,t=r?.azureBaseUrl?.trim()||p.AZURE_OPENAI_BASE_URL?.trim()||void 0,n=r?.azureResourceName||p.AZURE_OPENAI_RESOURCE_NAME;let a=t;if(!a&&n&&(a=D(n)),!a&&s.baseUrl&&(a=s.baseUrl),!a)throw new 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:M(a),apiVersion:e}}function L(s,r,e){if(!r){if(!p.AZURE_OPENAI_API_KEY)throw new Error("Azure OpenAI API key is required. Set AZURE_OPENAI_API_KEY environment variable or pass it as an argument.");r=p.AZURE_OPENAI_API_KEY}const t={...s.headers};e?.headers&&Object.assign(t,e.headers);const{baseUrl:n,apiVersion:a}=K(s,e);return new v({apiKey:r,apiVersion:a,dangerouslyAllowBrowser:!0,defaultHeaders:t,baseURL:n})}function V(s,r,e,t){const n=N(s,r,w),a={model:t,input:n,stream:!0,prompt_cache_key:e?.sessionId};return e?.maxTokens&&(a.max_output_tokens=e?.maxTokens),e?.temperature!==void 0&&(a.temperature=e?.temperature),r.tools&&(a.tools=g(r.tools)),s.reasoning&&(e?.reasoningEffort||e?.reasoningSummary?(a.reasoning={effort:e?.reasoningEffort||"medium",summary:e?.reasoningSummary||"auto"},a.include=["reasoning.encrypted_content"]):a.reasoning={effort:"none"}),a}export{Z as streamAzureOpenAIResponses,Y as streamSimpleAzureOpenAIResponses};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as u}from"./index-
|
|
1
|
+
import{c as u}from"./index-Dw4MBGs3.js";const l=["/workspace","/shared"];async function d(s){const t=[],e=new Set;for(const r of l)await s.exists(r)&&await p(s,r,t,e);return t}async function p(s,t,e,r){for await(const n of s.walk(t)){if(!n.endsWith(".bsh")||r.has(n))continue;r.add(n);const i=g(n);if(!i)continue;const a=await s.readFile(n,{encoding:"utf-8"}),c=typeof a=="string"?a:new TextDecoder().decode(a),f=m(c);e.push({path:n,hostnamePattern:i,matchPatterns:f})}}function g(s){const t=s.split("/").pop()??"";if(!t.endsWith(".bsh"))return null;const e=t.slice(0,-4);return e?e.startsWith("-.")?"*"+e.slice(1):e:null}function m(s){const t=s.split(`
|
|
2
2
|
`).slice(0,10),e=[];for(const r of t){const n=r.match(/^\s*\/\/\s*@match\s+(.+)$/);n&&e.push(n[1].trim())}return e}function h(s,t){if(t.startsWith("*.")){const e=t.slice(1);return s.endsWith(e)&&s.length>e.length}return s===t}function v(s,t){try{const e=new URL(s),r=t.match(/^(\*|https?):\/\/([^/]+)(\/.*)?$/);if(!r)return!1;const[,n,i,a]=r;return n!=="*"&&e.protocol.slice(0,-1)!==n||!h(e.hostname,i)?!1:a?x(e.pathname+e.search,a):!0}catch{return!1}}function x(s,t){const e="^"+t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")+"$";return new RegExp(e).test(s)}function w(s,t){try{const e=new URL(t);return s.filter(r=>h(e.hostname,r.hostnamePattern)?r.matchPatterns.length>0?r.matchPatterns.some(n=>v(t,n)):!0:!1)}catch{return[]}}const o=u("bsh-watchdog");class S{transport;fs;execute;discoveryIntervalMs;entries=[];discoveryTimer=null;running=!1;executing=new Set;constructor(t){this.transport=t.transport,this.fs=t.fs,this.execute=t.execute,this.discoveryIntervalMs=t.discoveryIntervalMs??3e4}async start(){this.running||(this.running=!0,await this.discover(),this.discoveryTimer=setInterval(()=>{this.discover()},this.discoveryIntervalMs),this.transport.on("Page.frameNavigated",this.onFrameNavigated),o.info("BSH watchdog started",{scriptCount:this.entries.length}))}stop(){this.running&&(this.running=!1,this.transport.off("Page.frameNavigated",this.onFrameNavigated),this.discoveryTimer&&(clearInterval(this.discoveryTimer),this.discoveryTimer=null),this.entries=[],this.executing.clear(),o.info("BSH watchdog stopped"))}async discover(){try{this.entries=await d(this.fs),o.debug("BSH discovery complete",{count:this.entries.length})}catch(t){o.error("BSH discovery failed",{error:t instanceof Error?t.message:String(t)})}}getEntries(){return this.entries}onFrameNavigated=t=>{const e=t.frame;if(e?.parentId||!e?.url)return;const r=e.url;if(!r.startsWith("http://")&&!r.startsWith("https://")||this.entries.length===0)return;const n=w(this.entries,r);if(n.length!==0)for(const i of n){const a=`${i.path}::${r}`;this.executing.has(a)||(this.executing.add(a),o.info("BSH watchdog executing script",{script:i.path,url:r}),this.execute(i.path).then(c=>{c.exitCode!==0?o.warn("BSH script failed",{script:i.path,url:r,exitCode:c.exitCode,stderr:c.stderr.slice(0,200)}):o.info("BSH script completed",{script:i.path,url:r})}).catch(c=>{o.error("BSH script execution error",{script:i.path,url:r,error:c instanceof Error?c.message:String(c)})}).finally(()=>{this.executing.delete(a)}))}}}export{S as BshWatchdog};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{i as T,r as x,m as S,G as v,c as M,a as R,b as _}from"./google-shared-DdOR1KIz.js";import{A as G,g as b,a as L,b as O,d as A}from"./index-Dw4MBGs3.js";import{s as E}from"./sanitize-unicode-cmozpu7l.js";let P=0;const f=(e,o,n)=>{const i=new G;return(async()=>{const t={role:"assistant",content:[],api:"google-generative-ai",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{const r=n?.apiKey||b(e.provider)||"",l=N(e,r,n?.headers);let c=W(e,o,n);const m=await n?.onPayload?.(c,e);m!==void 0&&(c=m);const w=await l.models.generateContentStream(c);i.push({type:"start",partial:t});let a=null;const y=t.content,u=()=>y.length-1;for await(const g of w){t.responseId||=g.responseId;const h=g.candidates?.[0];if(h?.content?.parts)for(const s of h.content.parts){if(s.text!==void 0){const d=T(s);(!a||d&&a.type!=="thinking"||!d&&a.type!=="text")&&(a&&(a.type==="text"?i.push({type:"text_end",contentIndex:y.length-1,content:a.text,partial:t}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:t})),d?(a={type:"thinking",thinking:"",thinkingSignature:void 0},t.content.push(a),i.push({type:"thinking_start",contentIndex:u(),partial:t})):(a={type:"text",text:""},t.content.push(a),i.push({type:"text_start",contentIndex:u(),partial:t}))),a.type==="thinking"?(a.thinking+=s.text,a.thinkingSignature=x(a.thinkingSignature,s.thoughtSignature),i.push({type:"thinking_delta",contentIndex:u(),delta:s.text,partial:t})):(a.text+=s.text,a.textSignature=x(a.textSignature,s.thoughtSignature),i.push({type:"text_delta",contentIndex:u(),delta:s.text,partial:t}))}if(s.functionCall){a&&(a.type==="text"?i.push({type:"text_end",contentIndex:u(),content:a.text,partial:t}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:t}),a=null);const d=s.functionCall.id,p={type:"toolCall",id:!d||t.content.some(C=>C.type==="toolCall"&&C.id===d)?`${s.functionCall.name}_${Date.now()}_${++P}`:d,name:s.functionCall.name||"",arguments:s.functionCall.args??{},...s.thoughtSignature&&{thoughtSignature:s.thoughtSignature}};t.content.push(p),i.push({type:"toolcall_start",contentIndex:u(),partial:t}),i.push({type:"toolcall_delta",contentIndex:u(),delta:JSON.stringify(p.arguments),partial:t}),i.push({type:"toolcall_end",contentIndex:u(),toolCall:p,partial:t})}}h?.finishReason&&(t.stopReason=S(h.finishReason),t.content.some(s=>s.type==="toolCall")&&(t.stopReason="toolUse")),g.usageMetadata&&(t.usage={input:g.usageMetadata.promptTokenCount||0,output:(g.usageMetadata.candidatesTokenCount||0)+(g.usageMetadata.thoughtsTokenCount||0),cacheRead:g.usageMetadata.cachedContentTokenCount||0,cacheWrite:0,totalTokens:g.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},L(e,t.usage))}if(a&&(a.type==="text"?i.push({type:"text_end",contentIndex:u(),content:a.text,partial:t}):i.push({type:"thinking_end",contentIndex:u(),content:a.thinking,partial:t})),n?.signal?.aborted)throw new Error("Request was aborted");if(t.stopReason==="aborted"||t.stopReason==="error")throw new Error("An unknown error occurred");i.push({type:"done",reason:t.stopReason,message:t}),i.end()}catch(r){for(const l of t.content)"index"in l&&delete l.index;t.stopReason=n?.signal?.aborted?"aborted":"error",t.errorMessage=r instanceof Error?r.message:JSON.stringify(r),i.push({type:"error",reason:t.stopReason,error:t}),i.end()}})(),i},J=(e,o,n)=>{const i=n?.apiKey||b(e.provider);if(!i)throw new Error(`No API key for provider: ${e.provider}`);const t=O(e,n,i);if(!n?.reasoning)return f(e,o,{...t,thinking:{enabled:!1}});const r=A(n.reasoning),l=e;return k(l)||I(l)?f(e,o,{...t,thinking:{enabled:!0,level:K(r,l)}}):f(e,o,{...t,thinking:{enabled:!0,budgetTokens:U(l,r,n.thinkingBudgets)}})};function N(e,o,n){const i={};return e.baseUrl&&(i.baseUrl=e.baseUrl,i.apiVersion=""),(e.headers||n)&&(i.headers={...e.headers,...n}),new v({apiKey:o,httpOptions:Object.keys(i).length>0?i:void 0})}function W(e,o,n={}){const i=M(e,o),t={};n.temperature!==void 0&&(t.temperature=n.temperature),n.maxTokens!==void 0&&(t.maxOutputTokens=n.maxTokens);const r={...Object.keys(t).length>0&&t,...o.systemPrompt&&{systemInstruction:E(o.systemPrompt)},...o.tools&&o.tools.length>0&&{tools:R(o.tools)}};if(o.tools&&o.tools.length>0&&n.toolChoice?r.toolConfig={functionCallingConfig:{mode:_(n.toolChoice)}}:r.toolConfig=void 0,n.thinking?.enabled&&e.reasoning){const c={includeThoughts:!0};n.thinking.level!==void 0?c.thinkingLevel=n.thinking.level:n.thinking.budgetTokens!==void 0&&(c.thinkingBudget=n.thinking.budgetTokens),r.thinkingConfig=c}else e.reasoning&&n.thinking&&!n.thinking.enabled&&(r.thinkingConfig=B(e));if(n.signal){if(n.signal.aborted)throw new Error("Request aborted");r.abortSignal=n.signal}return{model:e.id,contents:i,config:r}}function k(e){return/gemini-3(?:\.\d+)?-pro/.test(e.id.toLowerCase())}function I(e){return/gemini-3(?:\.\d+)?-flash/.test(e.id.toLowerCase())}function B(e){return k(e)?{thinkingLevel:"LOW"}:I(e)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function K(e,o){if(k(o))switch(e){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}function U(e,o,n){return n?.[o]!==void 0?n[o]:e.id.includes("2.5-pro")?{minimal:128,low:2048,medium:8192,high:32768}[o]:e.id.includes("2.5-flash")?{minimal:128,low:2048,medium:8192,high:24576}[o]:-1}export{f as streamGoogle,J as streamSimpleGoogle};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{A as oe,a as ae,b as se,d as ie}from"./index-Dw4MBGs3.js";import{s as ce}from"./sanitize-unicode-cmozpu7l.js";import{c as le,a as ue,b as de,i as ge,r as V,d as he}from"./google-shared-DdOR1KIz.js";var fe={};const Q="https://cloudcode-pa.googleapis.com",pe="https://daily-cloudcode-pa.sandbox.googleapis.com",me="https://autopush-cloudcode-pa.sandbox.googleapis.com",ye=[pe,me,Q],we={"User-Agent":"google-cloud-sdk vscode_cloudshelleditor/0.1","X-Goog-Api-Client":"gl-node/22.17.0","Client-Metadata":JSON.stringify({ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})},ke="1.18.4";function Ie(){return{"User-Agent":`antigravity/${fe.PI_AI_ANTIGRAVITY_VERSION||ke} darwin/arm64`}}const j="You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.**Absolute paths only****Proactiveness**";let be=0;const L=3,K=1e3,z=2,Te=500,Ee="interleaved-thinking-2025-05-14";function Ae(t,s){const o=a=>a>0?Math.ceil(a+1e3):void 0,n=s instanceof Headers?s:s?.headers;if(n){const a=n.get("retry-after");if(a){const d=Number(a);if(Number.isFinite(d)){const b=o(d*1e3);if(b!==void 0)return b}const A=new Date(a).getTime();if(!Number.isNaN(A)){const b=o(A-Date.now());if(b!==void 0)return b}}const u=n.get("x-ratelimit-reset");if(u){const d=Number.parseInt(u,10);if(!Number.isNaN(d)){const p=o(d*1e3-Date.now());if(p!==void 0)return p}}const c=n.get("x-ratelimit-reset-after");if(c){const d=Number(c);if(Number.isFinite(d)){const p=o(d*1e3);if(p!==void 0)return p}}}const e=t.match(/reset after (?:(\d+)h)?(?:(\d+)m)?(\d+(?:\.\d+)?)s/i);if(e){const a=e[1]?parseInt(e[1],10):0,u=e[2]?parseInt(e[2],10):0,c=parseFloat(e[3]);if(!Number.isNaN(c)){const d=((a*60+u)*60+c)*1e3,p=o(d);if(p!==void 0)return p}}const h=t.match(/Please retry in ([0-9.]+)(ms|s)/i);if(h?.[1]){const a=parseFloat(h[1]);if(!Number.isNaN(a)&&a>0){const u=h[2].toLowerCase()==="ms"?a:a*1e3,c=o(u);if(c!==void 0)return c}}const i=t.match(/"retryDelay":\s*"([0-9.]+)(ms|s)"/i);if(i?.[1]){const a=parseFloat(i[1]);if(!Number.isNaN(a)&&a>0){const u=i[2].toLowerCase()==="ms"?a:a*1e3,c=o(u);if(c!==void 0)return c}}}function Ce(t){return t.provider==="google-antigravity"&&t.id.startsWith("claude-")&&t.reasoning}function G(t){return/gemini-3(?:\.1)?-pro/.test(t.toLowerCase())}function Z(t){return/gemini-3(?:\.1)?-flash/.test(t.toLowerCase())}function ve(t){return G(t)||Z(t)}function xe(t,s){return t===429||t===500||t===502||t===503||t===504?!0:/resource.?exhausted|rate.?limit|overloaded|service.?unavailable|other.?side.?closed/i.test(s)}function X(t){try{const s=JSON.parse(t);if(s.error?.message)return s.error.message}catch{}return t}function O(t,s){return new Promise((o,n)=>{if(s?.aborted){n(new Error("Request was aborted"));return}const e=setTimeout(o,t);s?.addEventListener("abort",()=>{clearTimeout(e),n(new Error("Request was aborted"))})})}const P=(t,s,o)=>{const n=new oe;return(async()=>{const e={role:"assistant",content:[],api:"google-gemini-cli",provider:t.provider,model:t.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{const h=o?.apiKey;if(!h)throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");let i,a;try{const g=JSON.parse(h);i=g.token,a=g.projectId}catch{throw new Error("Invalid Google Cloud Code Assist credentials. Use /login to re-authenticate.")}if(!i||!a)throw new Error("Missing token or projectId in Google Cloud credentials. Use /login to re-authenticate.");const u=t.provider==="google-antigravity",c=t.baseUrl?.trim(),d=c?[c]:u?ye:[Q];let p=Re(t,s,a,o,u);const A=await o?.onPayload?.(p,t);A!==void 0&&(p=A);const b=u?Ie():we,q={Authorization:`Bearer ${i}`,"Content-Type":"application/json",Accept:"text/event-stream",...b,...Ce(t)?{"anthropic-beta":Ee}:{},...o?.headers},U=JSON.stringify(p);let y,T,x,C=0;for(let g=0;g<=L;g++){if(o?.signal?.aborted)throw new Error("Request was aborted");try{if(x=`${d[C]}/v1internal:streamGenerateContent?alt=sse`,y=await fetch(x,{method:"POST",headers:q,body:U,signal:o?.signal}),y.ok)break;const r=await y.text();if((y.status===403||y.status===404)&&C<d.length-1){C++;continue}if(g<L&&xe(y.status,r)){C<d.length-1&&C++;const k=Ae(r,y),f=k??K*2**g,E=o?.maxRetryDelayMs??6e4;if(E>0&&k&&k>E){const M=Math.ceil(k/1e3);throw new Error(`Server requested ${M}s retry delay (max: ${Math.ceil(E/1e3)}s). ${X(r)}`)}await O(f,o?.signal);continue}throw new Error(`Cloud Code Assist API error (${y.status}): ${X(r)}`)}catch(m){if(m instanceof Error&&(m.name==="AbortError"||m.message==="Request was aborted"))throw new Error("Request was aborted");if(T=m instanceof Error?m:new Error(String(m)),T.message==="fetch failed"&&T.cause instanceof Error&&(T=new Error(`Network error: ${T.cause.message}`)),g<L){const r=K*2**g;await O(r,o?.signal);continue}throw T}}if(!y||!y.ok)throw T??new Error("Failed to get response after retries");let N=!1;const S=()=>{N||(n.push({type:"start",partial:e}),N=!0)},ee=()=>{e.content=[],e.usage={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},e.stopReason="stop",e.errorMessage=void 0,e.timestamp=Date.now(),N=!1},te=async g=>{if(!g.body)throw new Error("No response body");let m=!1,r=null;const k=e.content,f=()=>k.length-1,E=g.body.getReader(),M=new TextDecoder;let _="";const B=()=>{E.cancel().catch(()=>{})};o?.signal?.addEventListener("abort",B);try{for(;;){if(o?.signal?.aborted)throw new Error("Request was aborted");const{done:ne,value:re}=await E.read();if(ne)break;_+=M.decode(re,{stream:!0});const Y=_.split(`
|
|
2
|
+
`);_=Y.pop()||"";for(const F of Y){if(!F.startsWith("data:"))continue;const H=F.slice(5).trim();if(!H)continue;let W;try{W=JSON.parse(H)}catch{continue}const I=W.response;if(!I)continue;e.responseId||=I.responseId;const R=I.candidates?.[0];if(R?.content?.parts)for(const l of R.content.parts){if(l.text!==void 0){m=!0;const w=ge(l);(!r||w&&r.type!=="thinking"||!w&&r.type!=="text")&&(r&&(r.type==="text"?n.push({type:"text_end",contentIndex:k.length-1,content:r.text,partial:e}):n.push({type:"thinking_end",contentIndex:f(),content:r.thinking,partial:e})),w?(r={type:"thinking",thinking:"",thinkingSignature:void 0},e.content.push(r),S(),n.push({type:"thinking_start",contentIndex:f(),partial:e})):(r={type:"text",text:""},e.content.push(r),S(),n.push({type:"text_start",contentIndex:f(),partial:e}))),r.type==="thinking"?(r.thinking+=l.text,r.thinkingSignature=V(r.thinkingSignature,l.thoughtSignature),n.push({type:"thinking_delta",contentIndex:f(),delta:l.text,partial:e})):(r.text+=l.text,r.textSignature=V(r.textSignature,l.thoughtSignature),n.push({type:"text_delta",contentIndex:f(),delta:l.text,partial:e}))}if(l.functionCall){m=!0,r&&(r.type==="text"?n.push({type:"text_end",contentIndex:f(),content:r.text,partial:e}):n.push({type:"thinking_end",contentIndex:f(),content:r.thinking,partial:e}),r=null);const w=l.functionCall.id,D={type:"toolCall",id:!w||e.content.some(J=>J.type==="toolCall"&&J.id===w)?`${l.functionCall.name}_${Date.now()}_${++be}`:w,name:l.functionCall.name||"",arguments:l.functionCall.args??{},...l.thoughtSignature&&{thoughtSignature:l.thoughtSignature}};e.content.push(D),S(),n.push({type:"toolcall_start",contentIndex:f(),partial:e}),n.push({type:"toolcall_delta",contentIndex:f(),delta:JSON.stringify(D.arguments),partial:e}),n.push({type:"toolcall_end",contentIndex:f(),toolCall:D,partial:e})}}if(R?.finishReason&&(e.stopReason=he(R.finishReason),e.content.some(l=>l.type==="toolCall")&&(e.stopReason="toolUse")),I.usageMetadata){const l=I.usageMetadata.promptTokenCount||0,w=I.usageMetadata.cachedContentTokenCount||0;e.usage={input:l-w,output:(I.usageMetadata.candidatesTokenCount||0)+(I.usageMetadata.thoughtsTokenCount||0),cacheRead:w,cacheWrite:0,totalTokens:I.usageMetadata.totalTokenCount||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},ae(t,e.usage)}}}}finally{o?.signal?.removeEventListener("abort",B)}return r&&(r.type==="text"?n.push({type:"text_end",contentIndex:f(),content:r.text,partial:e}):n.push({type:"thinking_end",contentIndex:f(),content:r.thinking,partial:e})),m};let $=!1,v=y;for(let g=0;g<=z;g++){if(o?.signal?.aborted)throw new Error("Request was aborted");if(g>0){const r=Te*2**(g-1);if(await O(r,o?.signal),!x)throw new Error("Missing request URL");if(v=await fetch(x,{method:"POST",headers:q,body:U,signal:o?.signal}),!v.ok){const k=await v.text();throw new Error(`Cloud Code Assist API error (${v.status}): ${k}`)}}if(await te(v)){$=!0;break}g<z&&ee()}if(!$)throw new Error("Cloud Code Assist API returned an empty response");if(o?.signal?.aborted)throw new Error("Request was aborted");if(e.stopReason==="aborted"||e.stopReason==="error")throw new Error("An unknown error occurred");n.push({type:"done",reason:e.stopReason,message:e}),n.end()}catch(h){for(const i of e.content)"index"in i&&delete i.index;e.stopReason=o?.signal?.aborted?"aborted":"error",e.errorMessage=h instanceof Error?h.message:JSON.stringify(h),n.push({type:"error",reason:e.stopReason,error:e}),n.end()}})(),n},Pe=(t,s,o)=>{const n=o?.apiKey;if(!n)throw new Error("Google Cloud Code Assist requires OAuth authentication. Use /login to authenticate.");const e=se(t,o,n);if(!o?.reasoning)return P(t,s,{...e,thinking:{enabled:!1}});const h=ie(o.reasoning);if(ve(t.id))return P(t,s,{...e,thinking:{enabled:!0,level:Se(h,t.id)}});const a={...{minimal:1024,low:2048,medium:8192,high:16384},...o.thinkingBudgets},u=1024;let c=a[h];const d=Math.min((e.maxTokens||0)+c,t.maxTokens);return d<=c&&(c=Math.max(0,d-u)),P(t,s,{...e,maxTokens:d,thinking:{enabled:!0,budgetTokens:c}})};function Re(t,s,o,n={},e=!1){const h=le(t,s),i={};n.temperature!==void 0&&(i.temperature=n.temperature),n.maxTokens!==void 0&&(i.maxOutputTokens=n.maxTokens),n.thinking?.enabled&&t.reasoning?(i.thinkingConfig={includeThoughts:!0},n.thinking.level!==void 0?i.thinkingConfig.thinkingLevel=n.thinking.level:n.thinking.budgetTokens!==void 0&&(i.thinkingConfig.thinkingBudget=n.thinking.budgetTokens)):t.reasoning&&n.thinking&&!n.thinking.enabled&&(i.thinkingConfig=Ne(t.id));const a={contents:h};if(a.sessionId=n.sessionId,s.systemPrompt&&(a.systemInstruction={parts:[{text:ce(s.systemPrompt)}]}),Object.keys(i).length>0&&(a.generationConfig=i),s.tools&&s.tools.length>0){const u=t.id.startsWith("claude-");a.tools=ue(s.tools,u),n.toolChoice&&(a.toolConfig={functionCallingConfig:{mode:de(n.toolChoice)}})}if(e){const u=a.systemInstruction?.parts??[];a.systemInstruction={role:"user",parts:[{text:j},{text:`Please ignore following [ignore]${j}[/ignore]`},...u]}}return{project:o,model:t.id,request:a,...e?{requestType:"agent"}:{},userAgent:e?"antigravity":"pi-coding-agent",requestId:`${e?"agent":"pi"}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}}function Ne(t){return G(t)?{thinkingLevel:"LOW"}:Z(t)?{thinkingLevel:"MINIMAL"}:{thinkingBudget:0}}function Se(t,s){if(G(s))switch(t){case"minimal":case"low":return"LOW";case"medium":case"high":return"HIGH"}switch(t){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";case"high":return"HIGH"}}export{Re as buildRequest,Ae as extractRetryDelay,P as streamGoogleGeminiCli,Pe as streamSimpleGoogleGeminiCli};
|