@puku-ai/sdk 3.0.1 → 3.0.2
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/README.md +4 -2
- package/package.json +1 -1
- package/sdk.cjs +16 -7
- package/sdk.cjs.map +11 -11
- package/sdk.d.ts +52 -29
- package/sdk.mjs +18 -18
- package/sdk.mjs.map +11 -11
package/sdk.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,"\r"]);static NEWLINE_REGEXP=/\r\n|[\n\r]/g;#B;#C;constructor(){this.#B=new Uint8Array,this.#C=null}decode(B){if(B==null)return[];let C=B instanceof ArrayBuffer?new Uint8Array(B):typeof B==="string"?
|
|
3
|
-
`)}}function
|
|
4
|
-
`);T.enqueue(x)}catch(y){T.error(y)}},async cancel(){await C.return?.()}})}}async function*
|
|
5
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],R}if(this.chunks.push(B),B.startsWith(":"))return null;let[C,T,y]=
|
|
1
|
+
var tB=function(){let{crypto:B}=globalThis;if(B?.randomUUID)return tB=B.randomUUID.bind(B),B.randomUUID();let C=new Uint8Array(1),T=B?()=>B.getRandomValues(C)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(y)=>(+y^T()&15>>+y/4).toString(16))};function b(B){return typeof B==="object"&&B!==null&&(("name"in B)&&B.name==="AbortError"||("message"in B)&&String(B.message).includes("FetchRequestCanceledException"))}var yB=(B)=>{if(B instanceof Error)return B;if(typeof B==="object"&&B!==null){try{if(Object.prototype.toString.call(B)==="[object Error]"){let C=Error(B.message,B.cause?{cause:B.cause}:{});if(B.stack)C.stack=B.stack;if(B.cause&&!C.cause)C.cause=B.cause;if(B.name)C.name=B.name;return C}}catch{}try{return Error(JSON.stringify(B))}catch{}}return Error(B)};class W extends Error{}class v extends W{constructor(B){super(B);this.name="PukuError"}}class z extends v{status;headers;error;requestID;type;constructor(B,C,T,y,R){super(`${z.makeMessage(B,C,T)}`);this.status=B,this.headers=y,this.requestID=y?.get("request-id"),this.error=C,this.type=R??null}static makeMessage(B,C,T){let y=C?.message?typeof C.message==="string"?C.message:JSON.stringify(C.message):C?JSON.stringify(C):T;if(B&&y)return`${B} ${y}`;if(B)return`${B} status code (no body)`;if(y)return y;return"(no status code or body)"}static generate(B,C,T,y){if(!B||!y)return new d({message:T,cause:yB(C)});let R=C,x=R?.error?.type;if(B===400)return new xB(B,R,T,y,x);if(B===401)return new kB(B,R,T,y,x);if(B===403)return new EB(B,R,T,y,x);if(B===404)return new SB(B,R,T,y,x);if(B===409)return new PB(B,R,T,y,x);if(B===422)return new WB(B,R,T,y,x);if(B===429)return new UB(B,R,T,y,x);if(B>=500)return new MB(B,R,T,y,x);return new z(B,R,T,y,x)}}class V extends z{constructor({message:B}={}){super(void 0,void 0,B||"Request was aborted.",void 0)}}class d extends z{constructor({message:B,cause:C}){super(void 0,void 0,B||"Connection error.",void 0);if(C)this.cause=C}}class RB extends d{constructor({message:B}={}){super({message:B??"Request timed out."})}}class xB extends z{}class kB extends z{}class EB extends z{}class SB extends z{}class PB extends z{}class WB extends z{}class UB extends z{}class MB extends z{}var q2=/^[a-z][a-z0-9+.-]*:/i,XC=(B)=>{return q2.test(B)},oB=(B)=>(oB=Array.isArray,oB(B)),vB=oB;function LB(B){if(typeof B!=="object")return{};return B??{}}function uB(B){if(!B)return!0;for(let C in B)return!1;return!0}function zC(B,C){return Object.prototype.hasOwnProperty.call(B,C)}var NC=(B,C)=>{if(typeof C!=="number"||!Number.isInteger(C))throw new W(`${B} must be an integer`);if(C<0)throw new W(`${B} must be a positive integer`);return C};var AB=(B)=>{try{return JSON.parse(B)}catch(C){return}},Y=(B,C)=>{let T=B[C];return delete B[C],T};var KC=(B)=>new Promise((C)=>setTimeout(C,B));var H="0.81.0";var QC=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function L2(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var A2=()=>{let B=L2();if(B==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":H,"X-Stainless-OS":YC(Deno.build.os),"X-Stainless-Arch":VC(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":H,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(B==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":H,"X-Stainless-OS":YC(globalThis.process.platform??"unknown"),"X-Stainless-Arch":VC(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let C=f2();if(C)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":H,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${C.browser}`,"X-Stainless-Runtime-Version":C.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":H,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function f2(){if(typeof navigator>"u"||!navigator)return null;let B=[{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(let{key:C,pattern:T}of B){let y=T.exec(navigator.userAgent);if(y){let R=y[1]||0,x=y[2]||0,k=y[3]||0;return{browser:C,version:`${R}.${x}.${k}`}}}return null}var VC=(B)=>{if(B==="x32")return"x32";if(B==="x86_64"||B==="x64")return"x64";if(B==="arm")return"arm";if(B==="aarch64"||B==="arm64")return"arm64";if(B)return`other:${B}`;return"unknown"},YC=(B)=>{if(B=B.toLowerCase(),B.includes("ios"))return"iOS";if(B==="android")return"Android";if(B==="darwin")return"MacOS";if(B==="win32")return"Windows";if(B==="freebsd")return"FreeBSD";if(B==="openbsd")return"OpenBSD";if(B==="linux")return"Linux";if(B)return`Other:${B}`;return"Unknown"},c2,OC=()=>{return c2??=A2()};function DC(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pB(...B){let C=globalThis.ReadableStream;if(typeof C>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new C(...B)}function fB(B){let C=Symbol.asyncIterator in B?B[Symbol.asyncIterator]():B[Symbol.iterator]();return pB({start(){},async pull(T){let{done:y,value:R}=await C.next();if(y)T.close();else T.enqueue(R)},async cancel(){await C.return?.()}})}function JB(B){if(B[Symbol.asyncIterator])return B;let C=B.getReader();return{async next(){try{let T=await C.read();if(T?.done)C.releaseLock();return T}catch(T){throw C.releaseLock(),T}},async return(){let T=C.cancel();return C.releaseLock(),await T,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function qC(B){if(B===null||typeof B!=="object")return;if(B[Symbol.asyncIterator]){await B[Symbol.asyncIterator]().return?.();return}let C=B.getReader(),T=C.cancel();C.releaseLock(),await T}var LC=({headers:B,body:C})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(C)}};function AC(B){return Object.entries(B).filter(([C,T])=>typeof T<"u").map(([C,T])=>{if(typeof T==="string"||typeof T==="number"||typeof T==="boolean")return`${encodeURIComponent(C)}=${encodeURIComponent(T)}`;if(T===null)return`${encodeURIComponent(C)}=`;throw new W(`Cannot stringify type ${typeof T}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function IC(B){let C=0;for(let R of B)C+=R.length;let T=new Uint8Array(C),y=0;for(let R of B)T.set(R,y),y+=R.length;return T}var fC;function u(B){let C;return(fC??(C=new globalThis.TextEncoder,fC=C.encode.bind(C)))(B)}var cC;function nB(B){let C;return(cC??(C=new globalThis.TextDecoder,cC=C.decode.bind(C)))(B)}class p{static NEWLINE_CHARS=new Set([`
|
|
2
|
+
`,"\r"]);static NEWLINE_REGEXP=/\r\n|[\n\r]/g;#B;#C;constructor(){this.#B=new Uint8Array,this.#C=null}decode(B){if(B==null)return[];let C=B instanceof ArrayBuffer?new Uint8Array(B):typeof B==="string"?u(B):B;this.#B=IC([this.#B,C]);let T=[],y;while((y=H2(this.#B,this.#C))!=null){if(y.carriage&&this.#C==null){this.#C=y.index;continue}if(this.#C!=null&&(y.index!==this.#C+1||y.carriage)){T.push(nB(this.#B.subarray(0,this.#C-1))),this.#B=this.#B.subarray(this.#C),this.#C=null;continue}let R=this.#C!==null?y.preceding-1:y.preceding,x=nB(this.#B.subarray(0,R));T.push(x),this.#B=this.#B.subarray(y.index),this.#C=null}return T}flush(){if(!this.#B.length)return[];return this.decode(`
|
|
3
|
+
`)}}function H2(B,C){for(let R=C??0;R<B.length;R++){if(B[R]===10)return{preceding:R,index:R+1,carriage:!1};if(B[R]===13)return{preceding:R,index:R+1,carriage:!0}}return null}function _C(B){for(let y=0;y<B.length-1;y++){if(B[y]===10&&B[y+1]===10)return y+2;if(B[y]===13&&B[y+1]===13)return y+2;if(B[y]===13&&B[y+1]===10&&y+3<B.length&&B[y+2]===13&&B[y+3]===10)return y+4}return-1}var IB={off:0,error:200,warn:300,info:400,debug:500},eB=(B,C,T)=>{if(!B)return;if(zC(IB,B))return B;K(T).warn(`${C} was set to ${JSON.stringify(B)}, expected one of ${JSON.stringify(Object.keys(IB))}`);return};function FB(){}function cB(B,C,T){if(!C||IB[B]>IB[T])return FB;else return C[B].bind(C)}var j2={error:FB,warn:FB,info:FB,debug:FB},HC=new WeakMap;function K(B){let C=B.logger,T=B.logLevel??"off";if(!C)return j2;let y=HC.get(C);if(y&&y[0]===T)return y[1];let R={error:cB("error",C,T),warn:cB("warn",C,T),info:cB("info",C,T),debug:cB("debug",C,T)};return HC.set(C,[T,R]),R}var l=(B)=>{if(B.options)B.options={...B.options},delete B.options.headers;if(B.headers)B.headers=Object.fromEntries((B.headers instanceof Headers?[...B.headers]:Object.entries(B.headers)).map(([C,T])=>[C,C.toLowerCase()==="x-api-key"||C.toLowerCase()==="authorization"||C.toLowerCase()==="cookie"||C.toLowerCase()==="set-cookie"?"***":T]));if("retryOfRequestLogID"in B){if(B.retryOfRequestLogID)B.retryOf=B.retryOfRequestLogID;delete B.retryOfRequestLogID}return B};class q{iterator;controller;#B;constructor(B,C,T){this.iterator=B;this.controller=C,this.#B=T}static fromSSEResponse(B,C,T){let y=!1,R=T?K(T):console;async function*x(){if(y)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");y=!0;let k=!1;try{for await(let E of g2(B,C)){if(E.event==="completion")try{yield JSON.parse(E.data)}catch(S){throw R.error("Could not parse message into JSON:",E.data),R.error("From chunk:",E.raw),S}if(E.event==="message_start"||E.event==="message_delta"||E.event==="message_stop"||E.event==="content_block_start"||E.event==="content_block_delta"||E.event==="content_block_stop")try{yield JSON.parse(E.data)}catch(S){throw R.error("Could not parse message into JSON:",E.data),R.error("From chunk:",E.raw),S}if(E.event==="ping")continue;if(E.event==="error"){let S=AB(E.data)??E.data,U=S?.error?.type;throw new z(void 0,S,void 0,B.headers,U)}}k=!0}catch(E){if(b(E))return;throw E}finally{if(!k)C.abort()}}return new q(x,C,T)}static fromReadableStream(B,C,T){let y=!1;async function*R(){let k=new p,E=JB(B);for await(let S of E)for(let U of k.decode(S))yield U;for(let S of k.flush())yield S}async function*x(){if(y)throw new W("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");y=!0;let k=!1;try{for await(let E of R()){if(k)continue;if(E)yield JSON.parse(E)}k=!0}catch(E){if(b(E))return;throw E}finally{if(!k)C.abort()}}return new q(x,C,T)}[Symbol.asyncIterator](){return this.iterator()}tee(){let B=[],C=[],T=this.iterator(),y=(R)=>{return{next:()=>{if(R.length===0){let x=T.next();B.push(x),C.push(x)}return R.shift()}}};return[new q(()=>y(B),this.controller,this.#B),new q(()=>y(C),this.controller,this.#B)]}toReadableStream(){let B=this,C;return pB({async start(){C=B[Symbol.asyncIterator]()},async pull(T){try{let{value:y,done:R}=await C.next();if(R)return T.close();let x=u(JSON.stringify(y)+`
|
|
4
|
+
`);T.enqueue(x)}catch(y){T.error(y)}},async cancel(){await C.return?.()}})}}async function*g2(B,C){if(!B.body){if(C.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new W("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new W("Attempted to iterate over a response with no body")}let T=new jC,y=new p,R=JB(B.body);for await(let x of b2(R))for(let k of y.decode(x)){let E=T.decode(k);if(E)yield E}for(let x of y.flush()){let k=T.decode(x);if(k)yield k}}async function*b2(B){let C=new Uint8Array;for await(let T of B){if(T==null)continue;let y=T instanceof ArrayBuffer?new Uint8Array(T):typeof T==="string"?u(T):T,R=new Uint8Array(C.length+y.length);R.set(C),R.set(y,C.length),C=R;let x;while((x=_C(C))!==-1)yield C.slice(0,x),C=C.slice(x)}if(C.length>0)yield C}class jC{data;event;chunks;constructor(){this.event=null,this.data=[],this.chunks=[]}decode(B){if(B.endsWith("\r"))B=B.substring(0,B.length-1);if(!B){if(!this.event&&!this.data.length)return null;let R={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],R}if(this.chunks.push(B),B.startsWith(":"))return null;let[C,T,y]=l2(B,":");if(y.startsWith(" "))y=y.substring(1);if(C==="event")this.event=y;else if(C==="data")this.data.push(y);return null}}function l2(B,C){let T=B.indexOf(C);if(T!==-1)return[B.substring(0,T),C,B.substring(T+C.length)];return[B,"",""]}async function _B(B,C){let{response:T,requestLogID:y,retryOfRequestLogID:R,startTime:x}=C,k=await(async()=>{if(C.options.stream){if(K(B).debug("response",T.status,T.url,T.headers,T.body),C.options.__streamClass)return C.options.__streamClass.fromSSEResponse(T,C.controller);return q.fromSSEResponse(T,C.controller)}if(T.status===204)return null;if(C.options.__binaryResponse)return T;let S=T.headers.get("content-type")?.split(";")[0]?.trim();if(S?.includes("application/json")||S?.endsWith("+json")){if(T.headers.get("content-length")==="0")return;let M=await T.json();return rB(M,T)}return await T.text()})();return K(B).debug(`[${y}] response parsed`,l({retryOfRequestLogID:R,url:T.url,status:T.status,body:k,durationMs:Date.now()-x})),k}function rB(B,C){if(!B||typeof B!=="object"||Array.isArray(B))return B;return Object.defineProperty(B,"_request_id",{value:C.headers.get("request-id"),enumerable:!1})}class i extends Promise{responsePromise;parseResponse;parsedPromise;#B;constructor(B,C,T=_B){super((y)=>{y(null)});this.responsePromise=C;this.parseResponse=T;this.#B=B}_thenUnwrap(B){return new i(this.#B,this.responsePromise,async(C,T)=>rB(B(await this.parseResponse(C,T),T),T.response))}asResponse(){return this.responsePromise.then((B)=>B.response)}async withResponse(){let[B,C]=await Promise.all([this.parse(),this.asResponse()]);return{data:B,response:C,request_id:C.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((B)=>this.parseResponse(this.#B,B));return this.parsedPromise}then(B,C){return this.parse().then(B,C)}catch(B){return this.parse().catch(B)}finally(B){return this.parse().finally(B)}}class sB{#B;options;response;body;constructor(B,C,T,y){this.#B=B,this.options=y,this.response=C,this.body=T}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let B=this.nextPageRequestOptions();if(!B)throw new W("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await this.#B.requestAPIList(this.constructor,B)}async*iterPages(){let B=this;yield B;while(B.hasNextPage())B=await B.getNextPage(),yield B}async*[Symbol.asyncIterator](){for await(let B of this.iterPages())for(let C of B.getPaginatedItems())yield C}}class HB extends i{constructor(B,C,T){super(B,C,async(y,R)=>new T(y,R.response,await _B(y,R),R.options))}async*[Symbol.asyncIterator](){let B=await this;for await(let C of B)yield C}}class c extends sB{data;has_more;first_id;last_id;constructor(B,C,T,y){super(B,C,T,y);this.data=T.data||[],this.has_more=T.has_more||!1,this.first_id=T.first_id||null,this.last_id=T.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let C=this.first_id;if(!C)return null;return{...this.options,query:{...LB(this.options.query),before_id:C}}}let B=this.last_id;if(!B)return null;return{...this.options,query:{...LB(this.options.query),after_id:B}}}}class $B extends sB{data;has_more;next_page;constructor(B,C,T,y){super(B,C,T,y);this.data=T.data||[],this.has_more=T.has_more||!1,this.next_page=T.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let B=this.next_page;if(!B)return null;return{...this.options,query:{...LB(this.options.query),page:B}}}}var CC=()=>{if(typeof File>"u"){let{process:B}=globalThis,C=typeof B?.versions?.node==="string"&&parseInt(B.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(C?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function m(B,C,T){return CC(),new File(B,C??"unknown_file",T)}function GB(B,C){let T=typeof B==="object"&&B!==null&&(("name"in B)&&B.name&&String(B.name)||("url"in B)&&B.url&&String(B.url)||("filename"in B)&&B.filename&&String(B.filename)||("path"in B)&&B.path&&String(B.path))||"";return C?T.split(/[\\/]/).pop()||void 0:T}var TC=(B)=>B!=null&&typeof B==="object"&&typeof B[Symbol.asyncIterator]==="function";var n=async(B,C,T=!0)=>{return{...B,body:await d2(B.body,C,T)}},gC=new WeakMap;function a2(B){let C=typeof B==="function"?B:B.fetch,T=gC.get(C);if(T)return T;let y=(async()=>{try{let R="Response"in C?C.Response:(await C("data:,")).constructor,x=new FormData;if(x.toString()===await new R(x).text())return!1;return!0}catch{return!0}})();return gC.set(C,y),y}var d2=async(B,C,T=!0)=>{if(!await a2(C))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let y=new FormData;return await Promise.all(Object.entries(B||{}).map(([R,x])=>BC(y,R,x,T))),y},i2=(B)=>B instanceof Blob&&("name"in B);var BC=async(B,C,T,y)=>{if(T===void 0)return;if(T==null)throw TypeError(`Received null for "${C}"; to pass null in FormData, you must use the string 'null'`);if(typeof T==="string"||typeof T==="number"||typeof T==="boolean")B.append(C,String(T));else if(T instanceof Response){let R={},x=T.headers.get("Content-Type");if(x)R={type:x};B.append(C,m([await T.blob()],GB(T,y),R))}else if(TC(T))B.append(C,m([await new Response(fB(T)).blob()],GB(T,y)));else if(i2(T))B.append(C,m([T],GB(T,y),{type:T.type}));else if(Array.isArray(T))await Promise.all(T.map((R)=>BC(B,C+"[]",R,y)));else if(typeof T==="object")await Promise.all(Object.entries(T).map(([R,x])=>BC(B,`${C}[${R}]`,x,y)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${T} instead`)};var bC=(B)=>B!=null&&typeof B==="object"&&typeof B.size==="number"&&typeof B.type==="string"&&typeof B.text==="function"&&typeof B.slice==="function"&&typeof B.arrayBuffer==="function",m2=(B)=>B!=null&&typeof B==="object"&&typeof B.name==="string"&&typeof B.lastModified==="number"&&bC(B),t2=(B)=>B!=null&&typeof B==="object"&&typeof B.url==="string"&&typeof B.blob==="function";async function jB(B,C,T){if(CC(),B=await B,C||=GB(B,!0),m2(B)){if(B instanceof File&&C==null&&T==null)return B;return m([await B.arrayBuffer()],C??B.name,{type:B.type,lastModified:B.lastModified,...T})}if(t2(B)){let R=await B.blob();return C||=new URL(B.url).pathname.split(/[\\/]/).pop(),m(await yC(R),C,T)}let y=await yC(B);if(!T?.type){let R=y.find((x)=>typeof x==="object"&&("type"in x)&&x.type);if(typeof R==="string")T={...T,type:R}}return m(y,C,T)}async function yC(B){let C=[];if(typeof B==="string"||ArrayBuffer.isView(B)||B instanceof ArrayBuffer)C.push(B);else if(bC(B))C.push(B instanceof Blob?B:await B.arrayBuffer());else if(TC(B))for await(let T of B)C.push(...await yC(T));else{let T=B?.constructor?.name;throw Error(`Unexpected data type: ${typeof B}${T?`; constructor: ${T}`:""}${o2(B)}`)}return C}function o2(B){if(typeof B!=="object"||B===null)return"";return`; props: [${Object.getOwnPropertyNames(B).map((T)=>`"${T}"`).join(", ")}]`}class Z{_client;constructor(B){this._client=B}}var lC=Symbol.for("brand.privateNullableHeaders");function*u2(B){if(!B)return;if(lC in B){let{values:y,nulls:R}=B;yield*y.entries();for(let x of R)yield[x,null];return}let C=!1,T;if(B instanceof Headers)T=B.entries();else if(vB(B))T=B;else C=!0,T=Object.entries(B??{});for(let y of T){let R=y[0];if(typeof R!=="string")throw TypeError("expected header name to be a string");let x=vB(y[1])?y[1]:[y[1]],k=!1;for(let E of x){if(E===void 0)continue;if(C&&!k)k=!0,yield[R,null];yield[R,E]}}}var J=(B)=>{let C=new Headers,T=new Set;for(let y of B){let R=new Set;for(let[x,k]of u2(y)){let E=x.toLowerCase();if(!R.has(E))C.delete(x),R.add(E);if(k===null)C.delete(x),T.add(E);else C.append(x,k),T.delete(E)}}return{[lC]:!0,values:C,nulls:T}};var D=Symbol("anthropic.sdk.stainlessHelper");function gB(B){return typeof B==="object"&&B!==null&&D in B}function bB(B,C){let T=new Set;if(B){for(let y of B)if(gB(y))T.add(y[D])}if(C)for(let y of C){if(gB(y))T.add(y[D]);if(Array.isArray(y.content)){for(let R of y.content)if(gB(R))T.add(R[D])}}return Array.from(T)}function ZB(B,C){let T=bB(B,C);if(T.length===0)return{};return{"x-stainless-helper":T.join(", ")}}function hC(B){if(gB(B))return{"x-stainless-helper":B[D]};return{}}function dC(B){return B.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var aC=Object.freeze(Object.create(null)),p2=(B=dC)=>function(T,...y){if(T.length===1)return T[0];let R=!1,x=[],k=T.reduce((P,$,M)=>{if(/[?#]/.test($))R=!0;let X=y[M],A=(R?encodeURIComponent:B)(""+X);if(M!==y.length&&(X==null||typeof X==="object"&&X.toString===Object.getPrototypeOf(Object.getPrototypeOf(X.hasOwnProperty??aC)??aC)?.toString))A=X+"",x.push({start:P.length+$.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(X).slice(8,-1)} is not a valid path parameter`});return P+$+(M===y.length?"":A)},""),E=k.split(/[?#]/,1)[0],S=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,U;while((U=S.exec(E))!==null)x.push({start:U.index,length:U[0].length,error:`Value "${U[0]}" can't be safely passed as a path parameter`});if(x.sort((P,$)=>P.start-$.start),x.length>0){let P=0,$=x.reduce((M,X)=>{let A=" ".repeat(X.start-P),_="^".repeat(X.length);return P=X.start+X.length,M+A+_},"");throw new W(`Path parameters result in path with invalid segments:
|
|
6
6
|
${x.map((M)=>M.error).join(`
|
|
7
7
|
`)}
|
|
8
8
|
${k}
|
|
9
|
-
${$}`)}return k},G=u2(aC);class ZB extends Z{list(B={},C){let{betas:T,...y}=B??{};return this._client.getAPIList("/v1/files",c,{query:y,...C,headers:J([{"anthropic-beta":[...T??[],"files-api-2025-04-14"].toString()},C?.headers])})}delete(B,C={},T){let{betas:y}=C??{};return this._client.delete(G`/v1/files/${B}`,{...T,headers:J([{"anthropic-beta":[...y??[],"files-api-2025-04-14"].toString()},T?.headers])})}download(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/files/${B}/content`,{...T,headers:J([{"anthropic-beta":[...y??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},T?.headers]),__binaryResponse:!0})}retrieveMetadata(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/files/${B}`,{...T,headers:J([{"anthropic-beta":[...y??[],"files-api-2025-04-14"].toString()},T?.headers])})}upload(B,C){let{betas:T,...y}=B;return this._client.post("/v1/files",p({body:y,...C,headers:J([{"anthropic-beta":[...T??[],"files-api-2025-04-14"].toString()},lC(y.file),C?.headers])},this._client))}}class wB extends Z{retrieve(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/models/${B}?beta=true`,{...T,headers:J([{...y?.toString()!=null?{"anthropic-beta":y?.toString()}:void 0},T?.headers])})}list(B={},C){let{betas:T,...y}=B??{};return this._client.getAPIList("/v1/models?beta=true",c,{query:y,...C,headers:J([{...T?.toString()!=null?{"anthropic-beta":T?.toString()}:void 0},C?.headers])})}}var bB={"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 dC(B){return B?.output_format??B?.output_config?.format}function yC(B,C,T){let y=dC(C);if(!C||!("parse"in(y??{})))return{...B,content:B.content.map((R)=>{if(R.type==="text"){let x=Object.defineProperty({...R},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(x,"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};return RC(B,C,T)}function RC(B,C,T){let y=null,R=B.content.map((x)=>{if(x.type==="text"){let k=e2(C,x.text);if(y===null)y=k;let E=Object.defineProperty({...x},"parsed_output",{value:k,enumerable:!1});return Object.defineProperty(E,"parsed",{get(){return T.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),k},enumerable:!1})}return x});return{...B,content:R,parsed_output:y}}function e2(B,C){let T=dC(B);if(T?.type!=="json_schema")return null;try{if("parse"in T)return T.parse(C);return JSON.parse(C)}catch(y){throw new W(`Failed to parse structured output: ${y}`)}}var r2=(B)=>{let C=0,T=[];while(C<B.length){let y=B[C];if(y==="\\"){C++;continue}if(y==="{"){T.push({type:"brace",value:"{"}),C++;continue}if(y==="}"){T.push({type:"brace",value:"}"}),C++;continue}if(y==="["){T.push({type:"paren",value:"["}),C++;continue}if(y==="]"){T.push({type:"paren",value:"]"}),C++;continue}if(y===":"){T.push({type:"separator",value:":"}),C++;continue}if(y===","){T.push({type:"delimiter",value:","}),C++;continue}if(y==='"'){let E="",S=!1;y=B[++C];while(y!=='"'){if(C===B.length){S=!0;break}if(y==="\\"){if(C++,C===B.length){S=!0;break}E+=y+B[C],y=B[++C]}else E+=y,y=B[++C]}if(y=B[++C],!S)T.push({type:"string",value:E});continue}if(y&&/\s/.test(y)){C++;continue}let x=/[0-9]/;if(y&&x.test(y)||y==="-"||y==="."){let E="";if(y==="-")E+=y,y=B[++C];while(y&&x.test(y)||y===".")E+=y,y=B[++C];T.push({type:"number",value:E});continue}let k=/[a-z]/i;if(y&&k.test(y)){let E="";while(y&&k.test(y)){if(C===B.length)break;E+=y,y=B[++C]}if(E=="true"||E=="false"||E==="null")T.push({type:"name",value:E});else{C++;continue}continue}C++}return T},n=(B)=>{if(B.length===0)return B;let C=B[B.length-1];switch(C.type){case"separator":return B=B.slice(0,B.length-1),n(B);break;case"number":let T=C.value[C.value.length-1];if(T==="."||T==="-")return B=B.slice(0,B.length-1),n(B);case"string":let y=B[B.length-2];if(y?.type==="delimiter")return B=B.slice(0,B.length-1),n(B);else if(y?.type==="brace"&&y.value==="{")return B=B.slice(0,B.length-1),n(B);break;case"delimiter":return B=B.slice(0,B.length-1),n(B);break}return B},s2=(B)=>{let C=[];if(B.map((T)=>{if(T.type==="brace")if(T.value==="{")C.push("}");else C.splice(C.lastIndexOf("}"),1);if(T.type==="paren")if(T.value==="[")C.push("]");else C.splice(C.lastIndexOf("]"),1)}),C.length>0)C.reverse().map((T)=>{if(T==="}")B.push({type:"brace",value:"}"});else if(T==="]")B.push({type:"paren",value:"]"})});return B},BT=(B)=>{let C="";return B.map((T)=>{switch(T.type){case"string":C+='"'+T.value+'"';break;default:C+=T.value;break}}),C},lB=(B)=>JSON.parse(BT(s2(n(r2(B)))));var iC="__json_buf";function mC(B){return B.type==="tool_use"||B.type==="server_tool_use"||B.type==="mcp_tool_use"}class XB{messages=[];receivedMessages=[];#B;#C=null;controller=new AbortController;#y;#k=()=>{};#T=()=>{};#R;#E=()=>{};#P=()=>{};#x={};#W=!1;#M=!1;#J=!1;#S=!1;#F;#$;#U;constructor(B,C){this.#y=new Promise((T,y)=>{this.#k=T,this.#T=y}),this.#R=new Promise((T,y)=>{this.#E=T,this.#P=y}),this.#y.catch(()=>{}),this.#R.catch(()=>{}),this.#C=B,this.#U=C?.logger??console}get response(){return this.#F}get request_id(){return this.#$}async withResponse(){this.#S=!0;let B=await this.#y;if(!B)throw Error("Could not resolve a `Response` object");return{data:this,response:B,request_id:B.headers.get("request-id")}}static fromReadableStream(B){let C=new XB(null);return C._run(()=>C._fromReadableStream(B)),C}static createMessage(B,C,T,{logger:y}={}){let R=new XB(C,{logger:y});for(let x of C.messages)R._addMessageParam(x);return R.#C={...C,stream:!0},R._run(()=>R._createMessage(B,{...C,stream:!0},{...T,headers:{...T?.headers,"X-Stainless-Helper-Method":"stream"}})),R}_run(B){B().then(()=>{this._emitFinal(),this._emit("end")},this.#z)}_addMessageParam(B){this.messages.push(B)}_addMessage(B,C=!0){if(this.receivedMessages.push(B),C)this._emit("message",B)}async _createMessage(B,C,T){let y=T?.signal,R;if(y){if(y.aborted)this.controller.abort();R=this.controller.abort.bind(this.controller),y.addEventListener("abort",R)}try{this.#Z();let{response:x,data:k}=await B.create({...C,stream:!0},{...T,signal:this.controller.signal}).withResponse();this._connected(x);for await(let E of k)this.#w(E);if(k.controller.signal?.aborted)throw new V;this.#X()}finally{if(y&&R)y.removeEventListener("abort",R)}}_connected(B){if(this.ended)return;this.#F=B,this.#$=B?.headers.get("request-id"),this.#k(B),this._emit("connect")}get ended(){return this.#W}get errored(){return this.#M}get aborted(){return this.#J}abort(){this.controller.abort()}on(B,C){return(this.#x[B]||(this.#x[B]=[])).push({listener:C}),this}off(B,C){let T=this.#x[B];if(!T)return this;let y=T.findIndex((R)=>R.listener===C);if(y>=0)T.splice(y,1);return this}once(B,C){return(this.#x[B]||(this.#x[B]=[])).push({listener:C,once:!0}),this}emitted(B){return new Promise((C,T)=>{if(this.#S=!0,B!=="error")this.once("error",T);this.once(B,C)})}async done(){this.#S=!0,await this.#R}get currentMessage(){return this.#B}#G(){if(this.receivedMessages.length===0)throw new W("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)}async finalMessage(){return await this.done(),this.#G()}#N(){if(this.receivedMessages.length===0)throw new W("stream ended without producing a Message with role=assistant");let B=this.receivedMessages.at(-1).content.filter((C)=>C.type==="text").map((C)=>C.text);if(B.length===0)throw new W("stream ended without producing a content block with type=text");return B.join(" ")}async finalText(){return await this.done(),this.#N()}#z=(B)=>{if(this.#M=!0,b(B))B=new V;if(B instanceof V)return this.#J=!0,this._emit("abort",B);if(B instanceof W)return this._emit("error",B);if(B instanceof Error){let C=new W(B.message);return C.cause=B,this._emit("error",C)}return this._emit("error",new W(String(B)))};_emit(B,...C){if(this.#W)return;if(B==="end")this.#W=!0,this.#E();let T=this.#x[B];if(T)this.#x[B]=T.filter((y)=>!y.once),T.forEach(({listener:y})=>y(...C));if(B==="abort"){let y=C[0];if(!this.#S&&!T?.length)Promise.reject(y);this.#T(y),this.#P(y),this._emit("end");return}if(B==="error"){let y=C[0];if(!this.#S&&!T?.length)Promise.reject(y);this.#T(y),this.#P(y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",this.#G())}#Z(){if(this.ended)return;this.#B=void 0}#w(B){if(this.ended)return;let C=this.#K(B);switch(this._emit("streamEvent",B,C),B.type){case"content_block_delta":{let T=C.content.at(-1);switch(B.delta.type){case"text_delta":{if(T.type==="text")this._emit("text",B.delta.text,T.text||"");break}case"citations_delta":{if(T.type==="text")this._emit("citation",B.delta.citation,T.citations??[]);break}case"input_json_delta":{if(mC(T)&&T.input)this._emit("inputJson",B.delta.partial_json,T.input);break}case"thinking_delta":{if(T.type==="thinking")this._emit("thinking",B.delta.thinking,T.thinking);break}case"signature_delta":{if(T.type==="thinking")this._emit("signature",T.signature);break}case"compaction_delta":{if(T.type==="compaction"&&T.content)this._emit("compaction",T.content);break}default:tC(B.delta)}break}case"message_stop":{this._addMessageParam(C),this._addMessage(yC(C,this.#C,{logger:this.#U}),!0);break}case"content_block_stop":{this._emit("contentBlock",C.content.at(-1));break}case"message_start":{this.#B=C;break}case"content_block_start":case"message_delta":break}}#X(){if(this.ended)throw new W("stream has ended, this shouldn't happen");let B=this.#B;if(!B)throw new W("request ended without sending any chunks");return this.#B=void 0,yC(B,this.#C,{logger:this.#U})}async _fromReadableStream(B,C){let T=C?.signal,y;if(T){if(T.aborted)this.controller.abort();y=this.controller.abort.bind(this.controller),T.addEventListener("abort",y)}try{this.#Z(),this._connected(null);let R=q.fromReadableStream(B,this.controller);for await(let x of R)this.#w(x);if(R.controller.signal?.aborted)throw new V;this.#X()}finally{if(T&&y)T.removeEventListener("abort",y)}}#K(B){let C=this.#B;if(B.type==="message_start"){if(C)throw new W(`Unexpected event order, got ${B.type} before receiving "message_stop"`);return B.message}if(!C)throw new W(`Unexpected event order, got ${B.type} before "message_start"`);switch(B.type){case"message_stop":return C;case"message_delta":if(C.container=B.delta.container,C.stop_reason=B.delta.stop_reason,C.stop_sequence=B.delta.stop_sequence,C.usage.output_tokens=B.usage.output_tokens,C.context_management=B.context_management,B.usage.input_tokens!=null)C.usage.input_tokens=B.usage.input_tokens;if(B.usage.cache_creation_input_tokens!=null)C.usage.cache_creation_input_tokens=B.usage.cache_creation_input_tokens;if(B.usage.cache_read_input_tokens!=null)C.usage.cache_read_input_tokens=B.usage.cache_read_input_tokens;if(B.usage.server_tool_use!=null)C.usage.server_tool_use=B.usage.server_tool_use;if(B.usage.iterations!=null)C.usage.iterations=B.usage.iterations;return C;case"content_block_start":return C.content.push(B.content_block),C;case"content_block_delta":{let T=C.content.at(B.index);switch(B.delta.type){case"text_delta":{if(T?.type==="text")C.content[B.index]={...T,text:(T.text||"")+B.delta.text};break}case"citations_delta":{if(T?.type==="text")C.content[B.index]={...T,citations:[...T.citations??[],B.delta.citation]};break}case"input_json_delta":{if(T&&mC(T)){let y=T[iC]||"";y+=B.delta.partial_json;let R={...T};if(Object.defineProperty(R,iC,{value:y,enumerable:!1,writable:!0}),y)try{R.input=lB(y)}catch(x){let k=new W(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${x}. JSON: ${y}`);this.#z(k)}C.content[B.index]=R}break}case"thinking_delta":{if(T?.type==="thinking")C.content[B.index]={...T,thinking:T.thinking+B.delta.thinking};break}case"signature_delta":{if(T?.type==="thinking")C.content[B.index]={...T,signature:B.delta.signature};break}case"compaction_delta":{if(T?.type==="compaction")C.content[B.index]={...T,content:(T.content||"")+B.delta.content};break}default:tC(B.delta)}return C}case"content_block_stop":return C}}[Symbol.asyncIterator](){let B=[],C=[],T=!1;return this.on("streamEvent",(y)=>{let R=C.shift();if(R)R.resolve(y);else B.push(y)}),this.on("end",()=>{T=!0;for(let y of C)y.resolve(void 0);C.length=0}),this.on("abort",(y)=>{T=!0;for(let R of C)R.reject(y);C.length=0}),this.on("error",(y)=>{T=!0;for(let R of C)R.reject(y);C.length=0}),{next:async()=>{if(!B.length){if(T)return{value:void 0,done:!0};return new Promise((R,x)=>C.push({resolve:R,reject:x})).then((R)=>R?{value:R,done:!1}:{value:void 0,done:!0})}return{value:B.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function tC(B){}class F extends Error{content;constructor(B){let C=typeof B==="string"?B:B.map((T)=>{if(T.type==="text")return T.text;return`[${T.type}]`}).join(" ");super(C);this.name="ToolError",this.content=B}}var oC=1e5,vC=`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:
|
|
9
|
+
${$}`)}return k},G=p2(dC);class wB extends Z{list(B={},C){let{betas:T,...y}=B??{};return this._client.getAPIList("/v1/files",c,{query:y,...C,headers:J([{"anthropic-beta":[...T??[],"files-api-2025-04-14"].toString()},C?.headers])})}delete(B,C={},T){let{betas:y}=C??{};return this._client.delete(G`/v1/files/${B}`,{...T,headers:J([{"anthropic-beta":[...y??[],"files-api-2025-04-14"].toString()},T?.headers])})}download(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/files/${B}/content`,{...T,headers:J([{"anthropic-beta":[...y??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},T?.headers]),__binaryResponse:!0})}retrieveMetadata(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/files/${B}`,{...T,headers:J([{"anthropic-beta":[...y??[],"files-api-2025-04-14"].toString()},T?.headers])})}upload(B,C){let{betas:T,...y}=B;return this._client.post("/v1/files",n({body:y,...C,headers:J([{"anthropic-beta":[...T??[],"files-api-2025-04-14"].toString()},hC(y.file),C?.headers])},this._client))}}class XB extends Z{retrieve(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/models/${B}?beta=true`,{...T,headers:J([{...y?.toString()!=null?{"anthropic-beta":y?.toString()}:void 0},T?.headers])})}list(B={},C){let{betas:T,...y}=B??{};return this._client.getAPIList("/v1/models?beta=true",c,{query:y,...C,headers:J([{...T?.toString()!=null?{"anthropic-beta":T?.toString()}:void 0},C?.headers])})}}var lB={"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 iC(B){return B?.output_format??B?.output_config?.format}function RC(B,C,T){let y=iC(C);if(!C||!("parse"in(y??{})))return{...B,content:B.content.map((R)=>{if(R.type==="text"){let x=Object.defineProperty({...R},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(x,"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};return xC(B,C,T)}function xC(B,C,T){let y=null,R=B.content.map((x)=>{if(x.type==="text"){let k=r2(C,x.text);if(y===null)y=k;let E=Object.defineProperty({...x},"parsed_output",{value:k,enumerable:!1});return Object.defineProperty(E,"parsed",{get(){return T.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),k},enumerable:!1})}return x});return{...B,content:R,parsed_output:y}}function r2(B,C){let T=iC(B);if(T?.type!=="json_schema")return null;try{if("parse"in T)return T.parse(C);return JSON.parse(C)}catch(y){throw new W(`Failed to parse structured output: ${y}`)}}var s2=(B)=>{let C=0,T=[];while(C<B.length){let y=B[C];if(y==="\\"){C++;continue}if(y==="{"){T.push({type:"brace",value:"{"}),C++;continue}if(y==="}"){T.push({type:"brace",value:"}"}),C++;continue}if(y==="["){T.push({type:"paren",value:"["}),C++;continue}if(y==="]"){T.push({type:"paren",value:"]"}),C++;continue}if(y===":"){T.push({type:"separator",value:":"}),C++;continue}if(y===","){T.push({type:"delimiter",value:","}),C++;continue}if(y==='"'){let E="",S=!1;y=B[++C];while(y!=='"'){if(C===B.length){S=!0;break}if(y==="\\"){if(C++,C===B.length){S=!0;break}E+=y+B[C],y=B[++C]}else E+=y,y=B[++C]}if(y=B[++C],!S)T.push({type:"string",value:E});continue}if(y&&/\s/.test(y)){C++;continue}let x=/[0-9]/;if(y&&x.test(y)||y==="-"||y==="."){let E="";if(y==="-")E+=y,y=B[++C];while(y&&x.test(y)||y===".")E+=y,y=B[++C];T.push({type:"number",value:E});continue}let k=/[a-z]/i;if(y&&k.test(y)){let E="";while(y&&k.test(y)){if(C===B.length)break;E+=y,y=B[++C]}if(E=="true"||E=="false"||E==="null")T.push({type:"name",value:E});else{C++;continue}continue}C++}return T},e=(B)=>{if(B.length===0)return B;let C=B[B.length-1];switch(C.type){case"separator":return B=B.slice(0,B.length-1),e(B);break;case"number":let T=C.value[C.value.length-1];if(T==="."||T==="-")return B=B.slice(0,B.length-1),e(B);case"string":let y=B[B.length-2];if(y?.type==="delimiter")return B=B.slice(0,B.length-1),e(B);else if(y?.type==="brace"&&y.value==="{")return B=B.slice(0,B.length-1),e(B);break;case"delimiter":return B=B.slice(0,B.length-1),e(B);break}return B},BT=(B)=>{let C=[];if(B.map((T)=>{if(T.type==="brace")if(T.value==="{")C.push("}");else C.splice(C.lastIndexOf("}"),1);if(T.type==="paren")if(T.value==="[")C.push("]");else C.splice(C.lastIndexOf("]"),1)}),C.length>0)C.reverse().map((T)=>{if(T==="}")B.push({type:"brace",value:"}"});else if(T==="]")B.push({type:"paren",value:"]"})});return B},CT=(B)=>{let C="";return B.map((T)=>{switch(T.type){case"string":C+='"'+T.value+'"';break;default:C+=T.value;break}}),C},hB=(B)=>JSON.parse(CT(BT(e(s2(B)))));var mC="__json_buf";function tC(B){return B.type==="tool_use"||B.type==="server_tool_use"||B.type==="mcp_tool_use"}class zB{messages=[];receivedMessages=[];#B;#C=null;controller=new AbortController;#y;#k=()=>{};#T=()=>{};#R;#E=()=>{};#P=()=>{};#x={};#W=!1;#M=!1;#J=!1;#S=!1;#F;#$;#U;constructor(B,C){this.#y=new Promise((T,y)=>{this.#k=T,this.#T=y}),this.#R=new Promise((T,y)=>{this.#E=T,this.#P=y}),this.#y.catch(()=>{}),this.#R.catch(()=>{}),this.#C=B,this.#U=C?.logger??console}get response(){return this.#F}get request_id(){return this.#$}async withResponse(){this.#S=!0;let B=await this.#y;if(!B)throw Error("Could not resolve a `Response` object");return{data:this,response:B,request_id:B.headers.get("request-id")}}static fromReadableStream(B){let C=new zB(null);return C._run(()=>C._fromReadableStream(B)),C}static createMessage(B,C,T,{logger:y}={}){let R=new zB(C,{logger:y});for(let x of C.messages)R._addMessageParam(x);return R.#C={...C,stream:!0},R._run(()=>R._createMessage(B,{...C,stream:!0},{...T,headers:{...T?.headers,"X-Stainless-Helper-Method":"stream"}})),R}_run(B){B().then(()=>{this._emitFinal(),this._emit("end")},this.#z)}_addMessageParam(B){this.messages.push(B)}_addMessage(B,C=!0){if(this.receivedMessages.push(B),C)this._emit("message",B)}async _createMessage(B,C,T){let y=T?.signal,R;if(y){if(y.aborted)this.controller.abort();R=this.controller.abort.bind(this.controller),y.addEventListener("abort",R)}try{this.#Z();let{response:x,data:k}=await B.create({...C,stream:!0},{...T,signal:this.controller.signal}).withResponse();this._connected(x);for await(let E of k)this.#w(E);if(k.controller.signal?.aborted)throw new V;this.#X()}finally{if(y&&R)y.removeEventListener("abort",R)}}_connected(B){if(this.ended)return;this.#F=B,this.#$=B?.headers.get("request-id"),this.#k(B),this._emit("connect")}get ended(){return this.#W}get errored(){return this.#M}get aborted(){return this.#J}abort(){this.controller.abort()}on(B,C){return(this.#x[B]||(this.#x[B]=[])).push({listener:C}),this}off(B,C){let T=this.#x[B];if(!T)return this;let y=T.findIndex((R)=>R.listener===C);if(y>=0)T.splice(y,1);return this}once(B,C){return(this.#x[B]||(this.#x[B]=[])).push({listener:C,once:!0}),this}emitted(B){return new Promise((C,T)=>{if(this.#S=!0,B!=="error")this.once("error",T);this.once(B,C)})}async done(){this.#S=!0,await this.#R}get currentMessage(){return this.#B}#G(){if(this.receivedMessages.length===0)throw new W("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)}async finalMessage(){return await this.done(),this.#G()}#N(){if(this.receivedMessages.length===0)throw new W("stream ended without producing a Message with role=assistant");let B=this.receivedMessages.at(-1).content.filter((C)=>C.type==="text").map((C)=>C.text);if(B.length===0)throw new W("stream ended without producing a content block with type=text");return B.join(" ")}async finalText(){return await this.done(),this.#N()}#z=(B)=>{if(this.#M=!0,b(B))B=new V;if(B instanceof V)return this.#J=!0,this._emit("abort",B);if(B instanceof W)return this._emit("error",B);if(B instanceof Error){let C=new W(B.message);return C.cause=B,this._emit("error",C)}return this._emit("error",new W(String(B)))};_emit(B,...C){if(this.#W)return;if(B==="end")this.#W=!0,this.#E();let T=this.#x[B];if(T)this.#x[B]=T.filter((y)=>!y.once),T.forEach(({listener:y})=>y(...C));if(B==="abort"){let y=C[0];if(!this.#S&&!T?.length)Promise.reject(y);this.#T(y),this.#P(y),this._emit("end");return}if(B==="error"){let y=C[0];if(!this.#S&&!T?.length)Promise.reject(y);this.#T(y),this.#P(y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",this.#G())}#Z(){if(this.ended)return;this.#B=void 0}#w(B){if(this.ended)return;let C=this.#K(B);switch(this._emit("streamEvent",B,C),B.type){case"content_block_delta":{let T=C.content.at(-1);switch(B.delta.type){case"text_delta":{if(T.type==="text")this._emit("text",B.delta.text,T.text||"");break}case"citations_delta":{if(T.type==="text")this._emit("citation",B.delta.citation,T.citations??[]);break}case"input_json_delta":{if(tC(T)&&T.input)this._emit("inputJson",B.delta.partial_json,T.input);break}case"thinking_delta":{if(T.type==="thinking")this._emit("thinking",B.delta.thinking,T.thinking);break}case"signature_delta":{if(T.type==="thinking")this._emit("signature",T.signature);break}case"compaction_delta":{if(T.type==="compaction"&&T.content)this._emit("compaction",T.content);break}default:oC(B.delta)}break}case"message_stop":{this._addMessageParam(C),this._addMessage(RC(C,this.#C,{logger:this.#U}),!0);break}case"content_block_stop":{this._emit("contentBlock",C.content.at(-1));break}case"message_start":{this.#B=C;break}case"content_block_start":case"message_delta":break}}#X(){if(this.ended)throw new W("stream has ended, this shouldn't happen");let B=this.#B;if(!B)throw new W("request ended without sending any chunks");return this.#B=void 0,RC(B,this.#C,{logger:this.#U})}async _fromReadableStream(B,C){let T=C?.signal,y;if(T){if(T.aborted)this.controller.abort();y=this.controller.abort.bind(this.controller),T.addEventListener("abort",y)}try{this.#Z(),this._connected(null);let R=q.fromReadableStream(B,this.controller);for await(let x of R)this.#w(x);if(R.controller.signal?.aborted)throw new V;this.#X()}finally{if(T&&y)T.removeEventListener("abort",y)}}#K(B){let C=this.#B;if(B.type==="message_start"){if(C)throw new W(`Unexpected event order, got ${B.type} before receiving "message_stop"`);return B.message}if(!C)throw new W(`Unexpected event order, got ${B.type} before "message_start"`);switch(B.type){case"message_stop":return C;case"message_delta":if(C.container=B.delta.container,C.stop_reason=B.delta.stop_reason,C.stop_sequence=B.delta.stop_sequence,C.usage.output_tokens=B.usage.output_tokens,C.context_management=B.context_management,B.usage.input_tokens!=null)C.usage.input_tokens=B.usage.input_tokens;if(B.usage.cache_creation_input_tokens!=null)C.usage.cache_creation_input_tokens=B.usage.cache_creation_input_tokens;if(B.usage.cache_read_input_tokens!=null)C.usage.cache_read_input_tokens=B.usage.cache_read_input_tokens;if(B.usage.server_tool_use!=null)C.usage.server_tool_use=B.usage.server_tool_use;if(B.usage.iterations!=null)C.usage.iterations=B.usage.iterations;return C;case"content_block_start":return C.content.push(B.content_block),C;case"content_block_delta":{let T=C.content.at(B.index);switch(B.delta.type){case"text_delta":{if(T?.type==="text")C.content[B.index]={...T,text:(T.text||"")+B.delta.text};break}case"citations_delta":{if(T?.type==="text")C.content[B.index]={...T,citations:[...T.citations??[],B.delta.citation]};break}case"input_json_delta":{if(T&&tC(T)){let y=T[mC]||"";y+=B.delta.partial_json;let R={...T};if(Object.defineProperty(R,mC,{value:y,enumerable:!1,writable:!0}),y)try{R.input=hB(y)}catch(x){let k=new W(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${x}. JSON: ${y}`);this.#z(k)}C.content[B.index]=R}break}case"thinking_delta":{if(T?.type==="thinking")C.content[B.index]={...T,thinking:T.thinking+B.delta.thinking};break}case"signature_delta":{if(T?.type==="thinking")C.content[B.index]={...T,signature:B.delta.signature};break}case"compaction_delta":{if(T?.type==="compaction")C.content[B.index]={...T,content:(T.content||"")+B.delta.content};break}default:oC(B.delta)}return C}case"content_block_stop":return C}}[Symbol.asyncIterator](){let B=[],C=[],T=!1;return this.on("streamEvent",(y)=>{let R=C.shift();if(R)R.resolve(y);else B.push(y)}),this.on("end",()=>{T=!0;for(let y of C)y.resolve(void 0);C.length=0}),this.on("abort",(y)=>{T=!0;for(let R of C)R.reject(y);C.length=0}),this.on("error",(y)=>{T=!0;for(let R of C)R.reject(y);C.length=0}),{next:async()=>{if(!B.length){if(T)return{value:void 0,done:!0};return new Promise((R,x)=>C.push({resolve:R,reject:x})).then((R)=>R?{value:R,done:!1}:{value:void 0,done:!0})}return{value:B.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function oC(B){}class F extends Error{content;constructor(B){let C=typeof B==="string"?B:B.map((T)=>{if(T.type==="text")return T.text;return`[${T.type}]`}).join(" ");super(C);this.name="ToolError",this.content=B}}var vC=1e5,uC=`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
10
|
1. Task Overview
|
|
11
11
|
The user's core request and success criteria
|
|
12
12
|
Any clarifications or constraints they specified
|
|
@@ -28,25 +28,25 @@ User preferences or style requirements
|
|
|
28
28
|
Domain-specific details that aren't obvious
|
|
29
29
|
Any promises made to the user
|
|
30
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.`;function
|
|
32
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(R.model in yT&&R.thinking&&R.thinking.type==="enabled")console.warn(`Using Claude with ${R.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 x=this._client._options.timeout;if(!R.stream&&x==null){let E=bB[R.model]??void 0;x=this._client.calculateNonstreamingTimeout(R.max_tokens,E)}let k=GB(R.tools,R.messages);return this._client.post("/v1/messages?beta=true",{body:R,timeout:x??600000,...C,headers:J([{...y?.toString()!=null?{"anthropic-beta":y?.toString()}:void 0},k,C?.headers]),stream:T.stream??!1})}parse(B,C){return C={...C,headers:J([{"anthropic-beta":[...B.betas??[],"structured-outputs-2025-12-15"].toString()},C?.headers])},this.create(B,C).then((T)=>RC(T,B,{logger:this._client.logger??console}))}stream(B,C){return XB.createMessage(this,B,C)}countTokens(B,C){let T=nC(B),{betas:y,...R}=T;return this._client.post("/v1/messages/count_tokens?beta=true",{body:R,...C,headers:J([{"anthropic-beta":[...y??[],"token-counting-2024-11-01"].toString()},C?.headers])})}toolRunner(B,C){return new zB(this._client,B,C)}}function nC(B){if(!B.output_format)return B;if(B.output_config?.format)throw new W("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:C,...T}=B;return{...T,output_config:{...B.output_config,format:C}}}h.Batches=NB;h.BetaToolRunner=zB;h.ToolError=F;class KB extends Z{create(B,C={},T){let{betas:y,...R}=C??{};return this._client.post(G`/v1/skills/${B}/versions?beta=true`,p({body:R,...T,headers:J([{"anthropic-beta":[...y??[],"skills-2025-10-02"].toString()},T?.headers])},this._client))}retrieve(B,C,T){let{skill_id:y,betas:R}=C;return this._client.get(G`/v1/skills/${y}/versions/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...R??[],"skills-2025-10-02"].toString()},T?.headers])})}list(B,C={},T){let{betas:y,...R}=C??{};return this._client.getAPIList(G`/v1/skills/${B}/versions?beta=true`,FB,{query:R,...T,headers:J([{"anthropic-beta":[...y??[],"skills-2025-10-02"].toString()},T?.headers])})}delete(B,C,T){let{skill_id:y,betas:R}=C;return this._client.delete(G`/v1/skills/${y}/versions/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...R??[],"skills-2025-10-02"].toString()},T?.headers])})}}class r extends Z{versions=new KB(this._client);create(B={},C){let{betas:T,...y}=B??{};return this._client.post("/v1/skills?beta=true",p({body:y,...C,headers:J([{"anthropic-beta":[...T??[],"skills-2025-10-02"].toString()},C?.headers])},this._client,!1))}retrieve(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/skills/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...y??[],"skills-2025-10-02"].toString()},T?.headers])})}list(B={},C){let{betas:T,...y}=B??{};return this._client.getAPIList("/v1/skills?beta=true",FB,{query:y,...C,headers:J([{"anthropic-beta":[...T??[],"skills-2025-10-02"].toString()},C?.headers])})}delete(B,C={},T){let{betas:y}=C??{};return this._client.delete(G`/v1/skills/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...y??[],"skills-2025-10-02"].toString()},T?.headers])})}}r.Versions=KB;class j extends Z{models=new wB(this._client);messages=new h(this._client);files=new ZB(this._client);skills=new r(this._client)}j.Models=wB;j.Messages=h;j.Files=ZB;j.Skills=r;class s extends Z{create(B,C){let{betas:T,...y}=B;return this._client.post("/v1/complete",{body:y,timeout:this._client._options.timeout??600000,...C,headers:J([{...T?.toString()!=null?{"anthropic-beta":T?.toString()}:void 0},C?.headers]),stream:B.stream??!1})}}function eC(B){return B?.output_config?.format}function xC(B,C,T){let y=eC(C);if(!C||!("parse"in(y??{})))return{...B,content:B.content.map((R)=>{if(R.type==="text")return Object.defineProperty({...R},"parsed_output",{value:null,enumerable:!1});return R}),parsed_output:null};return kC(B,C,T)}function kC(B,C,T){let y=null,R=B.content.map((x)=>{if(x.type==="text"){let k=ET(C,x.text);if(y===null)y=k;return Object.defineProperty({...x},"parsed_output",{value:k,enumerable:!1})}return x});return{...B,content:R,parsed_output:y}}function ET(B,C){let T=eC(B);if(T?.type!=="json_schema")return null;try{if("parse"in T)return T.parse(C);return JSON.parse(C)}catch(y){throw new W(`Failed to parse structured output: ${y}`)}}var rC="__json_buf";function sC(B){return B.type==="tool_use"||B.type==="server_tool_use"}class VB{messages=[];receivedMessages=[];#B;#C=null;controller=new AbortController;#y;#k=()=>{};#T=()=>{};#R;#E=()=>{};#P=()=>{};#x={};#W=!1;#M=!1;#J=!1;#S=!1;#F;#$;#U;constructor(B,C){this.#y=new Promise((T,y)=>{this.#k=T,this.#T=y}),this.#R=new Promise((T,y)=>{this.#E=T,this.#P=y}),this.#y.catch(()=>{}),this.#R.catch(()=>{}),this.#C=B,this.#U=C?.logger??console}get response(){return this.#F}get request_id(){return this.#$}async withResponse(){this.#S=!0;let B=await this.#y;if(!B)throw Error("Could not resolve a `Response` object");return{data:this,response:B,request_id:B.headers.get("request-id")}}static fromReadableStream(B){let C=new VB(null);return C._run(()=>C._fromReadableStream(B)),C}static createMessage(B,C,T,{logger:y}={}){let R=new VB(C,{logger:y});for(let x of C.messages)R._addMessageParam(x);return R.#C={...C,stream:!0},R._run(()=>R._createMessage(B,{...C,stream:!0},{...T,headers:{...T?.headers,"X-Stainless-Helper-Method":"stream"}})),R}_run(B){B().then(()=>{this._emitFinal(),this._emit("end")},this.#z)}_addMessageParam(B){this.messages.push(B)}_addMessage(B,C=!0){if(this.receivedMessages.push(B),C)this._emit("message",B)}async _createMessage(B,C,T){let y=T?.signal,R;if(y){if(y.aborted)this.controller.abort();R=this.controller.abort.bind(this.controller),y.addEventListener("abort",R)}try{this.#Z();let{response:x,data:k}=await B.create({...C,stream:!0},{...T,signal:this.controller.signal}).withResponse();this._connected(x);for await(let E of k)this.#w(E);if(k.controller.signal?.aborted)throw new V;this.#X()}finally{if(y&&R)y.removeEventListener("abort",R)}}_connected(B){if(this.ended)return;this.#F=B,this.#$=B?.headers.get("request-id"),this.#k(B),this._emit("connect")}get ended(){return this.#W}get errored(){return this.#M}get aborted(){return this.#J}abort(){this.controller.abort()}on(B,C){return(this.#x[B]||(this.#x[B]=[])).push({listener:C}),this}off(B,C){let T=this.#x[B];if(!T)return this;let y=T.findIndex((R)=>R.listener===C);if(y>=0)T.splice(y,1);return this}once(B,C){return(this.#x[B]||(this.#x[B]=[])).push({listener:C,once:!0}),this}emitted(B){return new Promise((C,T)=>{if(this.#S=!0,B!=="error")this.once("error",T);this.once(B,C)})}async done(){this.#S=!0,await this.#R}get currentMessage(){return this.#B}#G(){if(this.receivedMessages.length===0)throw new W("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)}async finalMessage(){return await this.done(),this.#G()}#N(){if(this.receivedMessages.length===0)throw new W("stream ended without producing a Message with role=assistant");let B=this.receivedMessages.at(-1).content.filter((C)=>C.type==="text").map((C)=>C.text);if(B.length===0)throw new W("stream ended without producing a content block with type=text");return B.join(" ")}async finalText(){return await this.done(),this.#N()}#z=(B)=>{if(this.#M=!0,b(B))B=new V;if(B instanceof V)return this.#J=!0,this._emit("abort",B);if(B instanceof W)return this._emit("error",B);if(B instanceof Error){let C=new W(B.message);return C.cause=B,this._emit("error",C)}return this._emit("error",new W(String(B)))};_emit(B,...C){if(this.#W)return;if(B==="end")this.#W=!0,this.#E();let T=this.#x[B];if(T)this.#x[B]=T.filter((y)=>!y.once),T.forEach(({listener:y})=>y(...C));if(B==="abort"){let y=C[0];if(!this.#S&&!T?.length)Promise.reject(y);this.#T(y),this.#P(y),this._emit("end");return}if(B==="error"){let y=C[0];if(!this.#S&&!T?.length)Promise.reject(y);this.#T(y),this.#P(y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",this.#G())}#Z(){if(this.ended)return;this.#B=void 0}#w(B){if(this.ended)return;let C=this.#K(B);switch(this._emit("streamEvent",B,C),B.type){case"content_block_delta":{let T=C.content.at(-1);switch(B.delta.type){case"text_delta":{if(T.type==="text")this._emit("text",B.delta.text,T.text||"");break}case"citations_delta":{if(T.type==="text")this._emit("citation",B.delta.citation,T.citations??[]);break}case"input_json_delta":{if(sC(T)&&T.input)this._emit("inputJson",B.delta.partial_json,T.input);break}case"thinking_delta":{if(T.type==="thinking")this._emit("thinking",B.delta.thinking,T.thinking);break}case"signature_delta":{if(T.type==="thinking")this._emit("signature",T.signature);break}default:B2(B.delta)}break}case"message_stop":{this._addMessageParam(C),this._addMessage(xC(C,this.#C,{logger:this.#U}),!0);break}case"content_block_stop":{this._emit("contentBlock",C.content.at(-1));break}case"message_start":{this.#B=C;break}case"content_block_start":case"message_delta":break;default:break}}#X(){if(this.ended)throw new W("stream has ended, this shouldn't happen");let B=this.#B;if(!B)throw new W("request ended without sending any chunks");return this.#B=void 0,xC(B,this.#C,{logger:this.#U})}async _fromReadableStream(B,C){let T=C?.signal,y;if(T){if(T.aborted)this.controller.abort();y=this.controller.abort.bind(this.controller),T.addEventListener("abort",y)}try{this.#Z(),this._connected(null);let R=q.fromReadableStream(B,this.controller);for await(let x of R)this.#w(x);if(R.controller.signal?.aborted)throw new V;this.#X()}finally{if(T&&y)T.removeEventListener("abort",y)}}#K(B){let C=this.#B;if(B.type==="message_start"){if(C)throw new W(`Unexpected event order, got ${B.type} before receiving "message_stop"`);return B.message}if(!C)throw new W(`Unexpected event order, got ${B.type} before "message_start"`);switch(B.type){case"message_stop":return C;case"message_delta":if(C.stop_reason=B.delta.stop_reason,C.stop_sequence=B.delta.stop_sequence,C.usage.output_tokens=B.usage.output_tokens,B.usage.input_tokens!=null)C.usage.input_tokens=B.usage.input_tokens;if(B.usage.cache_creation_input_tokens!=null)C.usage.cache_creation_input_tokens=B.usage.cache_creation_input_tokens;if(B.usage.cache_read_input_tokens!=null)C.usage.cache_read_input_tokens=B.usage.cache_read_input_tokens;if(B.usage.server_tool_use!=null)C.usage.server_tool_use=B.usage.server_tool_use;return C;case"content_block_start":return C.content.push({...B.content_block}),C;case"content_block_delta":{let T=C.content.at(B.index);switch(B.delta.type){case"text_delta":{if(T?.type==="text")C.content[B.index]={...T,text:(T.text||"")+B.delta.text};break}case"citations_delta":{if(T?.type==="text")C.content[B.index]={...T,citations:[...T.citations??[],B.delta.citation]};break}case"input_json_delta":{if(T&&sC(T)){let y=T[rC]||"";y+=B.delta.partial_json;let R={...T};if(Object.defineProperty(R,rC,{value:y,enumerable:!1,writable:!0}),y)R.input=lB(y);C.content[B.index]=R}break}case"thinking_delta":{if(T?.type==="thinking")C.content[B.index]={...T,thinking:T.thinking+B.delta.thinking};break}case"signature_delta":{if(T?.type==="thinking")C.content[B.index]={...T,signature:B.delta.signature};break}default:B2(B.delta)}return C}case"content_block_stop":return C}}[Symbol.asyncIterator](){let B=[],C=[],T=!1;return this.on("streamEvent",(y)=>{let R=C.shift();if(R)R.resolve(y);else B.push(y)}),this.on("end",()=>{T=!0;for(let y of C)y.resolve(void 0);C.length=0}),this.on("abort",(y)=>{T=!0;for(let R of C)R.reject(y);C.length=0}),this.on("error",(y)=>{T=!0;for(let R of C)R.reject(y);C.length=0}),{next:async()=>{if(!B.length){if(T)return{value:void 0,done:!0};return new Promise((R,x)=>C.push({resolve:R,reject:x})).then((R)=>R?{value:R,done:!1}:{value:void 0,done:!0})}return{value:B.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function B2(B){}class YB extends Z{create(B,C){return this._client.post("/v1/messages/batches",{body:B,...C})}retrieve(B,C){return this._client.get(G`/v1/messages/batches/${B}`,C)}list(B={},C){return this._client.getAPIList("/v1/messages/batches",c,{query:B,...C})}delete(B,C){return this._client.delete(G`/v1/messages/batches/${B}`,C)}cancel(B,C){return this._client.post(G`/v1/messages/batches/${B}/cancel`,C)}async results(B,C){let T=await this.retrieve(B);if(!T.results_url)throw new W(`No batch \`results_url\`; Has it finished processing? ${T.processing_status} - ${T.id}`);return this._client.get(T.results_url,{...C,headers:J([{Accept:"application/binary"},C?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((y,R)=>e.fromResponse(R.response,R.controller))}}class t extends Z{batches=new YB(this._client);create(B,C){if(B.model in C2)console.warn(`The model '${B.model}' is deprecated and will reach end-of-life on ${C2[B.model]}
|
|
33
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(B.model in
|
|
31
|
+
Wrap your summary in <summary></summary> tags.`;function pC(){let B,C;return{promise:new Promise((y,R)=>{B=y,C=R}),resolve:B,reject:C}}class NB{client;#B=!1;#C=!1;#y;#k;#T;#R;#E;#P=0;constructor(B,C,T){this.client=B;this.#y={params:{...C,messages:structuredClone(C.messages)}};let R=["BetaToolRunner",...bB(C.tools,C.messages)].join(", ");this.#k={...T,headers:J([{"x-stainless-helper":R},T?.headers])},this.#E=pC()}async#x(){let B=this.#y.params.compactionControl;if(!B||!B.enabled)return!1;let C=0;if(this.#T!==void 0)try{let E=await this.#T;C=E.usage.input_tokens+(E.usage.cache_creation_input_tokens??0)+(E.usage.cache_read_input_tokens??0)+E.usage.output_tokens}catch{return!1}let T=B.contextTokenThreshold??vC;if(C<T)return!1;let y=B.model??this.#y.params.model,R=B.summaryPrompt??uC,x=this.#y.params.messages;if(x[x.length-1].role==="assistant"){let E=x[x.length-1];if(Array.isArray(E.content)){let S=E.content.filter((U)=>U.type!=="tool_use");if(S.length===0)x.pop();else E.content=S}}let k=await this.client.beta.messages.create({model:y,messages:[...x,{role:"user",content:[{type:"text",text:R}]}],max_tokens:this.#y.params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(k.content[0]?.type!=="text")throw new W("Expected text response for compaction");return this.#y.params.messages=[{role:"user",content:k.content}],!0}async*[Symbol.asyncIterator](){if(this.#B)throw new W("Cannot iterate over a consumed stream");this.#B=!0,this.#C=!0,this.#R=void 0;try{while(!0){let B;try{if(this.#y.params.max_iterations&&this.#P>=this.#y.params.max_iterations)break;this.#C=!1,this.#R=void 0,this.#P++,this.#T=void 0;let{max_iterations:C,compactionControl:T,...y}=this.#y.params;if(y.stream)B=this.client.beta.messages.stream({...y},this.#k),this.#T=B.finalMessage(),this.#T.catch(()=>{}),yield B;else this.#T=this.client.beta.messages.create({...y,stream:!1},this.#k),yield this.#T;if(!await this.#x()){if(!this.#C){let{role:k,content:E}=await this.#T;this.#y.params.messages.push({role:k,content:E})}let x=await this.#W(this.#y.params.messages.at(-1));if(x)this.#y.params.messages.push(x);else if(!this.#C)break}}finally{if(B)B.abort()}}if(!this.#T)throw new W("ToolRunner concluded without a message from the server");this.#E.resolve(await this.#T)}catch(B){throw this.#B=!1,this.#E.promise.catch(()=>{}),this.#E.reject(B),this.#E=pC(),B}}setMessagesParams(B){if(typeof B==="function")this.#y.params=B(this.#y.params);else this.#y.params=B;this.#C=!0,this.#R=void 0}async generateToolResponse(){let B=await this.#T??this.params.messages.at(-1);if(!B)return null;return this.#W(B)}async#W(B){if(this.#R!==void 0)return this.#R;return this.#R=TT(this.#y.params,B),this.#R}done(){return this.#E.promise}async runUntilDone(){if(!this.#B)for await(let B of this);return this.done()}get params(){return this.#y.params}pushMessages(...B){this.setMessagesParams((C)=>({...C,messages:[...C.messages,...B]}))}then(B,C){return this.runUntilDone().then(B,C)}}async function TT(B,C=B.messages.at(-1)){if(!C||C.role!=="assistant"||!C.content||typeof C.content==="string")return null;let T=C.content.filter((R)=>R.type==="tool_use");if(T.length===0)return null;return{role:"user",content:await Promise.all(T.map(async(R)=>{let x=B.tools.find((k)=>("name"in k?k.name:k.mcp_server_name)===R.name);if(!x||!("run"in x))return{type:"tool_result",tool_use_id:R.id,content:`Error: Tool '${R.name}' not found`,is_error:!0};try{let k=R.input;if("parse"in x&&x.parse)k=x.parse(k);let E=await x.run(k);return{type:"tool_result",tool_use_id:R.id,content:E}}catch(k){return{type:"tool_result",tool_use_id:R.id,content:k instanceof F?k.content:`Error: ${k instanceof Error?k.message:String(k)}`,is_error:!0}}}))}}class r{iterator;controller;constructor(B,C){this.iterator=B;this.controller=C}async*decoder(){let B=new p;for await(let C of this.iterator)for(let T of B.decode(C))yield JSON.parse(T);for(let C of B.flush())yield JSON.parse(C)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(B,C){if(!B.body){if(C.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new W("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new W("Attempted to iterate over a response with no body")}return new r(JB(B.body),C)}}class KB extends Z{create(B,C){let{betas:T,...y}=B;return this._client.post("/v1/messages/batches?beta=true",{body:y,...C,headers:J([{"anthropic-beta":[...T??[],"message-batches-2024-09-24"].toString()},C?.headers])})}retrieve(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/messages/batches/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...y??[],"message-batches-2024-09-24"].toString()},T?.headers])})}list(B={},C){let{betas:T,...y}=B??{};return this._client.getAPIList("/v1/messages/batches?beta=true",c,{query:y,...C,headers:J([{"anthropic-beta":[...T??[],"message-batches-2024-09-24"].toString()},C?.headers])})}delete(B,C={},T){let{betas:y}=C??{};return this._client.delete(G`/v1/messages/batches/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...y??[],"message-batches-2024-09-24"].toString()},T?.headers])})}cancel(B,C={},T){let{betas:y}=C??{};return this._client.post(G`/v1/messages/batches/${B}/cancel?beta=true`,{...T,headers:J([{"anthropic-beta":[...y??[],"message-batches-2024-09-24"].toString()},T?.headers])})}async results(B,C={},T){let y=await this.retrieve(B);if(!y.results_url)throw new W(`No batch \`results_url\`; Has it finished processing? ${y.processing_status} - ${y.id}`);let{betas:R}=C??{};return this._client.get(y.results_url,{...T,headers:J([{"anthropic-beta":[...R??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},T?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((x,k)=>r.fromResponse(k.response,k.controller))}}var nC={"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"},RT=["claude-opus-4-6"];class h extends Z{batches=new KB(this._client);create(B,C){let T=eC(B),{betas:y,...R}=T;if(R.model in nC)console.warn(`The model '${R.model}' is deprecated and will reach end-of-life on ${nC[R.model]}
|
|
32
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(R.model in RT&&R.thinking&&R.thinking.type==="enabled")console.warn(`Using Claude with ${R.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 x=this._client._options.timeout;if(!R.stream&&x==null){let E=lB[R.model]??void 0;x=this._client.calculateNonstreamingTimeout(R.max_tokens,E)}let k=ZB(R.tools,R.messages);return this._client.post("/v1/messages?beta=true",{body:R,timeout:x??600000,...C,headers:J([{...y?.toString()!=null?{"anthropic-beta":y?.toString()}:void 0},k,C?.headers]),stream:T.stream??!1})}parse(B,C){return C={...C,headers:J([{"anthropic-beta":[...B.betas??[],"structured-outputs-2025-12-15"].toString()},C?.headers])},this.create(B,C).then((T)=>xC(T,B,{logger:this._client.logger??console}))}stream(B,C){return zB.createMessage(this,B,C)}countTokens(B,C){let T=eC(B),{betas:y,...R}=T;return this._client.post("/v1/messages/count_tokens?beta=true",{body:R,...C,headers:J([{"anthropic-beta":[...y??[],"token-counting-2024-11-01"].toString()},C?.headers])})}toolRunner(B,C){return new NB(this._client,B,C)}}function eC(B){if(!B.output_format)return B;if(B.output_config?.format)throw new W("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:C,...T}=B;return{...T,output_config:{...B.output_config,format:C}}}h.Batches=KB;h.BetaToolRunner=NB;h.ToolError=F;class VB extends Z{create(B,C={},T){let{betas:y,...R}=C??{};return this._client.post(G`/v1/skills/${B}/versions?beta=true`,n({body:R,...T,headers:J([{"anthropic-beta":[...y??[],"skills-2025-10-02"].toString()},T?.headers])},this._client))}retrieve(B,C,T){let{skill_id:y,betas:R}=C;return this._client.get(G`/v1/skills/${y}/versions/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...R??[],"skills-2025-10-02"].toString()},T?.headers])})}list(B,C={},T){let{betas:y,...R}=C??{};return this._client.getAPIList(G`/v1/skills/${B}/versions?beta=true`,$B,{query:R,...T,headers:J([{"anthropic-beta":[...y??[],"skills-2025-10-02"].toString()},T?.headers])})}delete(B,C,T){let{skill_id:y,betas:R}=C;return this._client.delete(G`/v1/skills/${y}/versions/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...R??[],"skills-2025-10-02"].toString()},T?.headers])})}}class s extends Z{versions=new VB(this._client);create(B={},C){let{betas:T,...y}=B??{};return this._client.post("/v1/skills?beta=true",n({body:y,...C,headers:J([{"anthropic-beta":[...T??[],"skills-2025-10-02"].toString()},C?.headers])},this._client,!1))}retrieve(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/skills/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...y??[],"skills-2025-10-02"].toString()},T?.headers])})}list(B={},C){let{betas:T,...y}=B??{};return this._client.getAPIList("/v1/skills?beta=true",$B,{query:y,...C,headers:J([{"anthropic-beta":[...T??[],"skills-2025-10-02"].toString()},C?.headers])})}delete(B,C={},T){let{betas:y}=C??{};return this._client.delete(G`/v1/skills/${B}?beta=true`,{...T,headers:J([{"anthropic-beta":[...y??[],"skills-2025-10-02"].toString()},T?.headers])})}}s.Versions=VB;class j extends Z{models=new XB(this._client);messages=new h(this._client);files=new wB(this._client);skills=new s(this._client)}j.Models=XB;j.Messages=h;j.Files=wB;j.Skills=s;class BB extends Z{create(B,C){let{betas:T,...y}=B;return this._client.post("/v1/complete",{body:y,timeout:this._client._options.timeout??600000,...C,headers:J([{...T?.toString()!=null?{"anthropic-beta":T?.toString()}:void 0},C?.headers]),stream:B.stream??!1})}}function rC(B){return B?.output_config?.format}function kC(B,C,T){let y=rC(C);if(!C||!("parse"in(y??{})))return{...B,content:B.content.map((R)=>{if(R.type==="text")return Object.defineProperty({...R},"parsed_output",{value:null,enumerable:!1});return R}),parsed_output:null};return EC(B,C,T)}function EC(B,C,T){let y=null,R=B.content.map((x)=>{if(x.type==="text"){let k=ST(C,x.text);if(y===null)y=k;return Object.defineProperty({...x},"parsed_output",{value:k,enumerable:!1})}return x});return{...B,content:R,parsed_output:y}}function ST(B,C){let T=rC(B);if(T?.type!=="json_schema")return null;try{if("parse"in T)return T.parse(C);return JSON.parse(C)}catch(y){throw new W(`Failed to parse structured output: ${y}`)}}var sC="__json_buf";function B2(B){return B.type==="tool_use"||B.type==="server_tool_use"}class YB{messages=[];receivedMessages=[];#B;#C=null;controller=new AbortController;#y;#k=()=>{};#T=()=>{};#R;#E=()=>{};#P=()=>{};#x={};#W=!1;#M=!1;#J=!1;#S=!1;#F;#$;#U;constructor(B,C){this.#y=new Promise((T,y)=>{this.#k=T,this.#T=y}),this.#R=new Promise((T,y)=>{this.#E=T,this.#P=y}),this.#y.catch(()=>{}),this.#R.catch(()=>{}),this.#C=B,this.#U=C?.logger??console}get response(){return this.#F}get request_id(){return this.#$}async withResponse(){this.#S=!0;let B=await this.#y;if(!B)throw Error("Could not resolve a `Response` object");return{data:this,response:B,request_id:B.headers.get("request-id")}}static fromReadableStream(B){let C=new YB(null);return C._run(()=>C._fromReadableStream(B)),C}static createMessage(B,C,T,{logger:y}={}){let R=new YB(C,{logger:y});for(let x of C.messages)R._addMessageParam(x);return R.#C={...C,stream:!0},R._run(()=>R._createMessage(B,{...C,stream:!0},{...T,headers:{...T?.headers,"X-Stainless-Helper-Method":"stream"}})),R}_run(B){B().then(()=>{this._emitFinal(),this._emit("end")},this.#z)}_addMessageParam(B){this.messages.push(B)}_addMessage(B,C=!0){if(this.receivedMessages.push(B),C)this._emit("message",B)}async _createMessage(B,C,T){let y=T?.signal,R;if(y){if(y.aborted)this.controller.abort();R=this.controller.abort.bind(this.controller),y.addEventListener("abort",R)}try{this.#Z();let{response:x,data:k}=await B.create({...C,stream:!0},{...T,signal:this.controller.signal}).withResponse();this._connected(x);for await(let E of k)this.#w(E);if(k.controller.signal?.aborted)throw new V;this.#X()}finally{if(y&&R)y.removeEventListener("abort",R)}}_connected(B){if(this.ended)return;this.#F=B,this.#$=B?.headers.get("request-id"),this.#k(B),this._emit("connect")}get ended(){return this.#W}get errored(){return this.#M}get aborted(){return this.#J}abort(){this.controller.abort()}on(B,C){return(this.#x[B]||(this.#x[B]=[])).push({listener:C}),this}off(B,C){let T=this.#x[B];if(!T)return this;let y=T.findIndex((R)=>R.listener===C);if(y>=0)T.splice(y,1);return this}once(B,C){return(this.#x[B]||(this.#x[B]=[])).push({listener:C,once:!0}),this}emitted(B){return new Promise((C,T)=>{if(this.#S=!0,B!=="error")this.once("error",T);this.once(B,C)})}async done(){this.#S=!0,await this.#R}get currentMessage(){return this.#B}#G(){if(this.receivedMessages.length===0)throw new W("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)}async finalMessage(){return await this.done(),this.#G()}#N(){if(this.receivedMessages.length===0)throw new W("stream ended without producing a Message with role=assistant");let B=this.receivedMessages.at(-1).content.filter((C)=>C.type==="text").map((C)=>C.text);if(B.length===0)throw new W("stream ended without producing a content block with type=text");return B.join(" ")}async finalText(){return await this.done(),this.#N()}#z=(B)=>{if(this.#M=!0,b(B))B=new V;if(B instanceof V)return this.#J=!0,this._emit("abort",B);if(B instanceof W)return this._emit("error",B);if(B instanceof Error){let C=new W(B.message);return C.cause=B,this._emit("error",C)}return this._emit("error",new W(String(B)))};_emit(B,...C){if(this.#W)return;if(B==="end")this.#W=!0,this.#E();let T=this.#x[B];if(T)this.#x[B]=T.filter((y)=>!y.once),T.forEach(({listener:y})=>y(...C));if(B==="abort"){let y=C[0];if(!this.#S&&!T?.length)Promise.reject(y);this.#T(y),this.#P(y),this._emit("end");return}if(B==="error"){let y=C[0];if(!this.#S&&!T?.length)Promise.reject(y);this.#T(y),this.#P(y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",this.#G())}#Z(){if(this.ended)return;this.#B=void 0}#w(B){if(this.ended)return;let C=this.#K(B);switch(this._emit("streamEvent",B,C),B.type){case"content_block_delta":{let T=C.content.at(-1);switch(B.delta.type){case"text_delta":{if(T.type==="text")this._emit("text",B.delta.text,T.text||"");break}case"citations_delta":{if(T.type==="text")this._emit("citation",B.delta.citation,T.citations??[]);break}case"input_json_delta":{if(B2(T)&&T.input)this._emit("inputJson",B.delta.partial_json,T.input);break}case"thinking_delta":{if(T.type==="thinking")this._emit("thinking",B.delta.thinking,T.thinking);break}case"signature_delta":{if(T.type==="thinking")this._emit("signature",T.signature);break}default:C2(B.delta)}break}case"message_stop":{this._addMessageParam(C),this._addMessage(kC(C,this.#C,{logger:this.#U}),!0);break}case"content_block_stop":{this._emit("contentBlock",C.content.at(-1));break}case"message_start":{this.#B=C;break}case"content_block_start":case"message_delta":break;default:break}}#X(){if(this.ended)throw new W("stream has ended, this shouldn't happen");let B=this.#B;if(!B)throw new W("request ended without sending any chunks");return this.#B=void 0,kC(B,this.#C,{logger:this.#U})}async _fromReadableStream(B,C){let T=C?.signal,y;if(T){if(T.aborted)this.controller.abort();y=this.controller.abort.bind(this.controller),T.addEventListener("abort",y)}try{this.#Z(),this._connected(null);let R=q.fromReadableStream(B,this.controller);for await(let x of R)this.#w(x);if(R.controller.signal?.aborted)throw new V;this.#X()}finally{if(T&&y)T.removeEventListener("abort",y)}}#K(B){let C=this.#B;if(B.type==="message_start"){if(C)throw new W(`Unexpected event order, got ${B.type} before receiving "message_stop"`);return B.message}if(!C)throw new W(`Unexpected event order, got ${B.type} before "message_start"`);switch(B.type){case"message_stop":return C;case"message_delta":if(C.stop_reason=B.delta.stop_reason,C.stop_sequence=B.delta.stop_sequence,C.usage.output_tokens=B.usage.output_tokens,B.usage.input_tokens!=null)C.usage.input_tokens=B.usage.input_tokens;if(B.usage.cache_creation_input_tokens!=null)C.usage.cache_creation_input_tokens=B.usage.cache_creation_input_tokens;if(B.usage.cache_read_input_tokens!=null)C.usage.cache_read_input_tokens=B.usage.cache_read_input_tokens;if(B.usage.server_tool_use!=null)C.usage.server_tool_use=B.usage.server_tool_use;return C;case"content_block_start":return C.content.push({...B.content_block}),C;case"content_block_delta":{let T=C.content.at(B.index);switch(B.delta.type){case"text_delta":{if(T?.type==="text")C.content[B.index]={...T,text:(T.text||"")+B.delta.text};break}case"citations_delta":{if(T?.type==="text")C.content[B.index]={...T,citations:[...T.citations??[],B.delta.citation]};break}case"input_json_delta":{if(T&&B2(T)){let y=T[sC]||"";y+=B.delta.partial_json;let R={...T};if(Object.defineProperty(R,sC,{value:y,enumerable:!1,writable:!0}),y)R.input=hB(y);C.content[B.index]=R}break}case"thinking_delta":{if(T?.type==="thinking")C.content[B.index]={...T,thinking:T.thinking+B.delta.thinking};break}case"signature_delta":{if(T?.type==="thinking")C.content[B.index]={...T,signature:B.delta.signature};break}default:C2(B.delta)}return C}case"content_block_stop":return C}}[Symbol.asyncIterator](){let B=[],C=[],T=!1;return this.on("streamEvent",(y)=>{let R=C.shift();if(R)R.resolve(y);else B.push(y)}),this.on("end",()=>{T=!0;for(let y of C)y.resolve(void 0);C.length=0}),this.on("abort",(y)=>{T=!0;for(let R of C)R.reject(y);C.length=0}),this.on("error",(y)=>{T=!0;for(let R of C)R.reject(y);C.length=0}),{next:async()=>{if(!B.length){if(T)return{value:void 0,done:!0};return new Promise((R,x)=>C.push({resolve:R,reject:x})).then((R)=>R?{value:R,done:!1}:{value:void 0,done:!0})}return{value:B.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function C2(B){}class QB extends Z{create(B,C){return this._client.post("/v1/messages/batches",{body:B,...C})}retrieve(B,C){return this._client.get(G`/v1/messages/batches/${B}`,C)}list(B={},C){return this._client.getAPIList("/v1/messages/batches",c,{query:B,...C})}delete(B,C){return this._client.delete(G`/v1/messages/batches/${B}`,C)}cancel(B,C){return this._client.post(G`/v1/messages/batches/${B}/cancel`,C)}async results(B,C){let T=await this.retrieve(B);if(!T.results_url)throw new W(`No batch \`results_url\`; Has it finished processing? ${T.processing_status} - ${T.id}`);return this._client.get(T.results_url,{...C,headers:J([{Accept:"application/binary"},C?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((y,R)=>r.fromResponse(R.response,R.controller))}}class t extends Z{batches=new QB(this._client);create(B,C){if(B.model in T2)console.warn(`The model '${B.model}' is deprecated and will reach end-of-life on ${T2[B.model]}
|
|
33
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(B.model in WT&&B.thinking&&B.thinking.type==="enabled")console.warn(`Using Claude with ${B.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 T=this._client._options.timeout;if(!B.stream&&T==null){let R=lB[B.model]??void 0;T=this._client.calculateNonstreamingTimeout(B.max_tokens,R)}let y=ZB(B.tools,B.messages);return this._client.post("/v1/messages",{body:B,timeout:T??600000,...C,headers:J([y,C?.headers]),stream:B.stream??!1})}parse(B,C){return this.create(B,C).then((T)=>EC(T,B,{logger:this._client.logger??console}))}stream(B,C){return YB.createMessage(this,B,C,{logger:this._client.logger??console})}countTokens(B,C){return this._client.post("/v1/messages/count_tokens",{body:B,...C})}}var T2={"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"},WT=["claude-opus-4-6"];t.Batches=QB;class CB extends Z{retrieve(B,C={},T){let{betas:y}=C??{};return this._client.get(G`/v1/models/${B}`,{...T,headers:J([{...y?.toString()!=null?{"anthropic-beta":y?.toString()}:void 0},T?.headers])})}list(B={},C){let{betas:T,...y}=B??{};return this._client.getAPIList("/v1/models",c,{query:y,...C,headers:J([{...T?.toString()!=null?{"anthropic-beta":T?.toString()}:void 0},C?.headers])})}}var aB=(B)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[B]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(B)?.trim();return};var y2="\\n\\nHuman:",R2="\\n\\nAssistant:";class dB{apiKey;baseURL;maxRetries;timeout;logger;logLevel;fetchOptions;fetch;#B;idempotencyHeader;_options;constructor({baseURL:B=aB("PUKU_BASE_URL"),apiKey:C=aB("PUKU_API_KEY")??null,...T}={}){if(!B)throw new v("Missing baseURL: pass `baseURL` to the constructor or set the PUKU_BASE_URL environment variable.");let y={apiKey:C,...T,baseURL:B};if(!y.dangerouslyAllowBrowser&&QC())throw new W(`It looks like you're running in a browser-like environment.
|
|
34
34
|
|
|
35
35
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
36
36
|
If you understand the risks and have appropriate mitigations in place,
|
|
37
37
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
38
38
|
|
|
39
39
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
40
|
-
`);if(this.baseURL=y.baseURL,this.baseURL.endsWith("/v1"))this.baseURL=this.baseURL.slice(0,-3);this.timeout=y.timeout??aB.DEFAULT_TIMEOUT,this.logger=y.logger??console;let R="warn";this.logLevel=R,this.logLevel=nB(y.logLevel,"ClientOptions.logLevel",this)??nB(hB("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??R,this.fetchOptions=y.fetchOptions,this.maxRetries=y.maxRetries??2,this.fetch=y.fetch??OC(),this.#B=qC,this._options=y,this.apiKey=typeof C==="string"?C:null}withOptions(B){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,...B})}#C(){return!0}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:B,nulls:C}){if(B.get("x-api-key"))return;if(this.apiKey&&B.get("x-api-key"))return;if(C.has("x-api-key"))return;throw Error('Could not resolve authentication method. Expected apiKey to be set, or for the "X-Api-Key" header to be explicitly omitted')}async authHeaders(B){return J([await this.apiKeyAuth(B)])}async apiKeyAuth(B){if(this.apiKey==null)return;return J([{"X-Api-Key":this.apiKey}])}stringifyQuery(B){return LC(B)}getUserAgent(){return`${this.constructor.name}/JS ${H}`}defaultIdempotencyKey(){return`stainless-node-retry-${mB()}`}makeStatusError(B,C,T,y){return z.generate(B,C,T,y)}buildURL(B,C,T){let y=!this.#C()&&T||this.baseURL,R=wC(B)?new URL(B):new URL(y+(y.endsWith("/")&&B.startsWith("/")?B.slice(1):B)),x=this.defaultQuery(),k=Object.fromEntries(R.searchParams);if(!vB(x)||!vB(k))C={...k,...x,...C};if(typeof C==="object"&&C&&!Array.isArray(C))R.search=this.stringifyQuery(C);return R.toString()}_calculateNonstreamingTimeout(B){if(3600*B/128000>600)throw new W("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 600000}async prepareOptions(B){}async prepareRequest(B,{url:C,options:T}){}get(B,C){return this.methodRequest("get",B,C)}post(B,C){return this.methodRequest("post",B,C)}patch(B,C){return this.methodRequest("patch",B,C)}put(B,C){return this.methodRequest("put",B,C)}delete(B,C){return this.methodRequest("delete",B,C)}methodRequest(B,C,T){return this.request(Promise.resolve(T).then((y)=>{return{method:B,path:C,...y}}))}request(B,C=null){return new i(this,this.makeRequest(B,C,void 0))}async makeRequest(B,C,T){let y=await B,R=y.maxRetries??this.maxRetries;if(C==null)C=R;await this.prepareOptions(y);let{req:x,url:k,timeout:E}=await this.buildRequest(y,{retryCount:R-C});await this.prepareRequest(x,{url:k,options:y});let S="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),U=T===void 0?"":`, retryOf: ${T}`,P=Date.now();if(K(this).debug(`[${S}] sending request`,l({retryOfRequestLogID:T,method:y.method,url:k,options:y,headers:x.headers})),y.signal?.aborted)throw new V;let $=new AbortController,M=await this.fetchWithTimeout(k,x,E,$).catch(TB),X=Date.now();if(M instanceof globalThis.Error){let f=`retrying, ${C} attempts remaining`;if(y.signal?.aborted)throw new V;let O=b(M)||/timed? ?out/i.test(String(M)+("cause"in M?String(M.cause):""));if(C)return K(this).info(`[${S}] connection ${O?"timed out":"failed"} - ${f}`),K(this).debug(`[${S}] connection ${O?"timed out":"failed"} (${f})`,l({retryOfRequestLogID:T,url:k,durationMs:X-P,message:M.message})),this.retryRequest(y,C,T??S);if(K(this).info(`[${S}] connection ${O?"timed out":"failed"} - error; no more retries left`),K(this).debug(`[${S}] connection ${O?"timed out":"failed"} (error; no more retries left)`,l({retryOfRequestLogID:T,url:k,durationMs:X-P,message:M.message})),O)throw new yB;throw new d({cause:M})}let A=[...M.headers.entries()].filter(([f])=>f==="request-id").map(([f,O])=>", "+f+": "+JSON.stringify(O)).join(""),_=`[${S}${U}${A}] ${x.method} ${k} ${M.ok?"succeeded":"failed"} with status ${M.status} in ${X-P}ms`;if(!M.ok){let f=await this.shouldRetry(M);if(C&&f){let DB=`retrying, ${C} attempts remaining`;return await DC(M.body),K(this).info(`${_} - ${DB}`),K(this).debug(`[${S}] response error (${DB})`,l({retryOfRequestLogID:T,url:M.url,status:M.status,headers:M.headers,durationMs:X-P})),this.retryRequest(y,C,T??S,M.headers)}let O=f?"error; no more retries left":"error; not retryable";K(this).info(`${_} - ${O}`);let $C=await M.text().catch((DB)=>TB(DB).message),GC=LB($C),ZC=GC?void 0:$C;throw K(this).debug(`[${S}] response error (${O})`,l({retryOfRequestLogID:T,url:M.url,status:M.status,headers:M.headers,message:ZC,durationMs:Date.now()-P})),this.makeStatusError(M.status,GC,ZC,M.headers)}return K(this).info(_),K(this).debug(`[${S}] response start`,l({retryOfRequestLogID:T,url:M.url,status:M.status,headers:M.headers,durationMs:X-P})),{response:M,options:y,controller:$,requestLogID:S,retryOfRequestLogID:T,startTime:P}}getAPIList(B,C,T){return this.requestAPIList(C,T&&"then"in T?T.then((y)=>({method:"get",path:B,...y})):{method:"get",path:B,...T})}requestAPIList(B,C){let T=this.makeRequest(C,null,void 0);return new _B(this,T,B)}async fetchWithTimeout(B,C,T,y){let{signal:R,method:x,...k}=C||{},E=this._makeAbort(y);if(R)R.addEventListener("abort",E,{once:!0});let S=setTimeout(E,T),U=globalThis.ReadableStream&&k.body instanceof globalThis.ReadableStream||typeof k.body==="object"&&k.body!==null&&Symbol.asyncIterator in k.body,P={signal:y.signal,...U?{duplex:"half"}:{},method:"GET",...k};if(x)P.method=x.toUpperCase();try{return await this.fetch.call(void 0,B,P)}finally{clearTimeout(S)}}async shouldRetry(B){let C=B.headers.get("x-should-retry");if(C==="true")return!0;if(C==="false")return!1;if(B.status===408)return!0;if(B.status===409)return!0;if(B.status===429)return!0;if(B.status>=500)return!0;return!1}async retryRequest(B,C,T,y){let R,x=y?.get("retry-after-ms");if(x){let E=parseFloat(x);if(!Number.isNaN(E))R=E}let k=y?.get("retry-after");if(k&&!R){let E=parseFloat(k);if(!Number.isNaN(E))R=E*1000;else R=Date.parse(k)-Date.now()}if(R===void 0){let E=B.maxRetries??this.maxRetries;R=this.calculateDefaultRetryTimeoutMillis(C,E)}return await NC(R),this.makeRequest(B,C-1,T)}calculateDefaultRetryTimeoutMillis(B,C){let R=C-B,x=Math.min(0.5*Math.pow(2,R),8),k=1-Math.random()*0.25;return x*k*1000}calculateNonstreamingTimeout(B,C){if(3600000*B/128000>600000||C!=null&&B>C)throw new W("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 600000}async buildRequest(B,{retryCount:C=0}={}){let T={...B},{method:y,path:R,query:x,defaultBaseURL:k}=T,E=this.buildURL(R,x,k);if("timeout"in T)zC("timeout",T.timeout);T.timeout=T.timeout??this.timeout;let{bodyHeaders:S,body:U}=this.buildBody({options:T}),P=await this.buildHeaders({options:B,method:y,bodyHeaders:S,retryCount:C});return{req:{method:y,headers:P,...T.signal&&{signal:T.signal},...globalThis.ReadableStream&&U instanceof globalThis.ReadableStream&&{duplex:"half"},...U&&{body:U},...this.fetchOptions??{},...T.fetchOptions??{}},url:E,timeout:T.timeout}}async buildHeaders({options:B,method:C,bodyHeaders:T,retryCount:y}){let R={};if(this.idempotencyHeader&&C!=="get"){if(!B.idempotencyKey)B.idempotencyKey=this.defaultIdempotencyKey();R[this.idempotencyHeader]=B.idempotencyKey}let x=J([R,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(y),...B.timeout?{"X-Stainless-Timeout":String(Math.trunc(B.timeout/1000))}:{},...QC(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(B),this._options.defaultHeaders,T,B.headers]);return this.validateHeaders(x),x.values}_makeAbort(B){return()=>B.abort()}buildBody({options:{body:B,headers:C}}){if(!B)return{bodyHeaders:void 0,body:void 0};let T=J([C]);if(ArrayBuffer.isView(B)||B instanceof ArrayBuffer||B instanceof DataView||typeof B==="string"&&T.values.has("content-type")||globalThis.Blob&&B instanceof globalThis.Blob||B instanceof FormData||B instanceof URLSearchParams||globalThis.ReadableStream&&B instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:B};else if(typeof B==="object"&&((Symbol.asyncIterator in B)||(Symbol.iterator in B)&&("next"in B)&&typeof B.next==="function"))return{bodyHeaders:void 0,body:AB(B)};else if(typeof B==="object"&&T.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(B)};else return this.#B({body:B,headers:T})}static Anthropic=this;static PukuAI=this;static HUMAN_PROMPT=T2;static AI_PROMPT=y2;static DEFAULT_TIMEOUT=600000;static AnthropicError=W;static APIError=z;static APIConnectionError=d;static APIConnectionTimeoutError=yB;static APIUserAbortError=V;static NotFoundError=EB;static ConflictError=SB;static RateLimitError=WB;static BadRequestError=RB;static AuthenticationError=xB;static InternalServerError=UB;static PermissionDeniedError=kB;static UnprocessableEntityError=PB;static toFile=HB}class g extends aB{completions=new s(this);messages=new t(this);models=new BB(this);beta=new j(this)}g.Completions=s;g.Messages=t;g.Models=BB;g.Beta=j;g.Anthropic=g;var EC=(B)=>{if(typeof globalThis.Buffer<"u"){let C=globalThis.Buffer.from(B,"base64");return new Uint8Array(C.buffer,C.byteOffset,C.byteLength)}if(typeof atob<"u"){let C=atob(B),T=new Uint8Array(C.length);for(let y=0;y<C.length;y++)T[y]=C.charCodeAt(y);return T}throw new W("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")};var UT=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]);function MT(B){return JSON.parse(JSON.stringify(B))}function R2(B){let C=MT(B);return o(C)}function o(B){let C={},T=Y(B,"$ref");if(T!==void 0)return C.$ref=T,C;let y=Y(B,"$defs");if(y!==void 0){let P={};C.$defs=P;for(let[$,M]of Object.entries(y))P[$]=o(M)}let R=Y(B,"type"),x=Y(B,"anyOf"),k=Y(B,"oneOf"),E=Y(B,"allOf");if(Array.isArray(x))C.anyOf=x.map((P)=>o(P));else if(Array.isArray(k))C.anyOf=k.map((P)=>o(P));else if(Array.isArray(E))C.allOf=E.map((P)=>o(P));else{if(R===void 0)throw Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used");C.type=R}let S=Y(B,"description");if(S!==void 0)C.description=S;let U=Y(B,"title");if(U!==void 0)C.title=U;if(R==="object"){let P=Y(B,"properties")||{};C.properties=Object.fromEntries(Object.entries(P).map(([M,X])=>[M,o(X)])),Y(B,"additionalProperties"),C.additionalProperties=!1;let $=Y(B,"required");if($!==void 0)C.required=$}else if(R==="string"){let P=Y(B,"format");if(P!==void 0&&UT.has(P))C.format=P;else if(P!==void 0)B.format=P}else if(R==="array"){let P=Y(B,"items");if(P!==void 0)C.items=o(P);let $=Y(B,"minItems");if($!==void 0&&($===0||$===1))C.minItems=$;else if($!==void 0)B.minItems=$}if(Object.keys(B).length>0){let P=C.description;C.description=(P?P+`
|
|
40
|
+
`);if(this.baseURL=y.baseURL,this.baseURL.endsWith("/v1"))this.baseURL=this.baseURL.slice(0,-3);this.timeout=y.timeout??dB.DEFAULT_TIMEOUT,this.logger=y.logger??console;let R="warn";this.logLevel=R,this.logLevel=eB(y.logLevel,"ClientOptions.logLevel",this)??eB(aB("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??R,this.fetchOptions=y.fetchOptions,this.maxRetries=y.maxRetries??2,this.fetch=y.fetch??DC(),this.#B=LC,this._options=y,this.apiKey=typeof C==="string"?C:null}withOptions(B){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,...B})}#C(){return!0}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:B,nulls:C}){if(B.get("x-api-key"))return;if(this.apiKey&&B.get("x-api-key"))return;if(C.has("x-api-key"))return;throw Error('Could not resolve authentication method. Expected apiKey to be set, or for the "X-Api-Key" header to be explicitly omitted')}async authHeaders(B){return J([await this.apiKeyAuth(B)])}async apiKeyAuth(B){if(this.apiKey==null)return;return J([{"X-Api-Key":this.apiKey}])}stringifyQuery(B){return AC(B)}getUserAgent(){return`${this.constructor.name}/JS ${H}`}defaultIdempotencyKey(){return`stainless-node-retry-${tB()}`}makeStatusError(B,C,T,y){return z.generate(B,C,T,y)}buildURL(B,C,T){let y=!this.#C()&&T||this.baseURL,R=XC(B)?new URL(B):new URL(y+(y.endsWith("/")&&B.startsWith("/")?B.slice(1):B)),x=this.defaultQuery(),k=Object.fromEntries(R.searchParams);if(!uB(x)||!uB(k))C={...k,...x,...C};if(typeof C==="object"&&C&&!Array.isArray(C))R.search=this.stringifyQuery(C);return R.toString()}_calculateNonstreamingTimeout(B){if(3600*B/128000>600)throw new W("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 600000}async prepareOptions(B){}async prepareRequest(B,{url:C,options:T}){}get(B,C){return this.methodRequest("get",B,C)}post(B,C){return this.methodRequest("post",B,C)}patch(B,C){return this.methodRequest("patch",B,C)}put(B,C){return this.methodRequest("put",B,C)}delete(B,C){return this.methodRequest("delete",B,C)}methodRequest(B,C,T){return this.request(Promise.resolve(T).then((y)=>{return{method:B,path:C,...y}}))}request(B,C=null){return new i(this,this.makeRequest(B,C,void 0))}async makeRequest(B,C,T){let y=await B,R=y.maxRetries??this.maxRetries;if(C==null)C=R;await this.prepareOptions(y);let{req:x,url:k,timeout:E}=await this.buildRequest(y,{retryCount:R-C});await this.prepareRequest(x,{url:k,options:y});let S="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),U=T===void 0?"":`, retryOf: ${T}`,P=Date.now();if(K(this).debug(`[${S}] sending request`,l({retryOfRequestLogID:T,method:y.method,url:k,options:y,headers:x.headers})),y.signal?.aborted)throw new V;let $=new AbortController,M=await this.fetchWithTimeout(k,x,E,$).catch(yB),X=Date.now();if(M instanceof globalThis.Error){let f=`retrying, ${C} attempts remaining`;if(y.signal?.aborted)throw new V;let O=b(M)||/timed? ?out/i.test(String(M)+("cause"in M?String(M.cause):""));if(C)return K(this).info(`[${S}] connection ${O?"timed out":"failed"} - ${f}`),K(this).debug(`[${S}] connection ${O?"timed out":"failed"} (${f})`,l({retryOfRequestLogID:T,url:k,durationMs:X-P,message:M.message})),this.retryRequest(y,C,T??S);if(K(this).info(`[${S}] connection ${O?"timed out":"failed"} - error; no more retries left`),K(this).debug(`[${S}] connection ${O?"timed out":"failed"} (error; no more retries left)`,l({retryOfRequestLogID:T,url:k,durationMs:X-P,message:M.message})),O)throw new RB;throw new d({cause:M})}let A=[...M.headers.entries()].filter(([f])=>f==="request-id").map(([f,O])=>", "+f+": "+JSON.stringify(O)).join(""),_=`[${S}${U}${A}] ${x.method} ${k} ${M.ok?"succeeded":"failed"} with status ${M.status} in ${X-P}ms`;if(!M.ok){let f=await this.shouldRetry(M);if(C&&f){let qB=`retrying, ${C} attempts remaining`;return await qC(M.body),K(this).info(`${_} - ${qB}`),K(this).debug(`[${S}] response error (${qB})`,l({retryOfRequestLogID:T,url:M.url,status:M.status,headers:M.headers,durationMs:X-P})),this.retryRequest(y,C,T??S,M.headers)}let O=f?"error; no more retries left":"error; not retryable";K(this).info(`${_} - ${O}`);let GC=await M.text().catch((qB)=>yB(qB).message),ZC=AB(GC),wC=ZC?void 0:GC;throw K(this).debug(`[${S}] response error (${O})`,l({retryOfRequestLogID:T,url:M.url,status:M.status,headers:M.headers,message:wC,durationMs:Date.now()-P})),this.makeStatusError(M.status,ZC,wC,M.headers)}return K(this).info(_),K(this).debug(`[${S}] response start`,l({retryOfRequestLogID:T,url:M.url,status:M.status,headers:M.headers,durationMs:X-P})),{response:M,options:y,controller:$,requestLogID:S,retryOfRequestLogID:T,startTime:P}}getAPIList(B,C,T){return this.requestAPIList(C,T&&"then"in T?T.then((y)=>({method:"get",path:B,...y})):{method:"get",path:B,...T})}requestAPIList(B,C){let T=this.makeRequest(C,null,void 0);return new HB(this,T,B)}async fetchWithTimeout(B,C,T,y){let{signal:R,method:x,...k}=C||{},E=this._makeAbort(y);if(R)R.addEventListener("abort",E,{once:!0});let S=setTimeout(E,T),U=globalThis.ReadableStream&&k.body instanceof globalThis.ReadableStream||typeof k.body==="object"&&k.body!==null&&Symbol.asyncIterator in k.body,P={signal:y.signal,...U?{duplex:"half"}:{},method:"GET",...k};if(x)P.method=x.toUpperCase();try{return await this.fetch.call(void 0,B,P)}finally{clearTimeout(S)}}async shouldRetry(B){let C=B.headers.get("x-should-retry");if(C==="true")return!0;if(C==="false")return!1;if(B.status===408)return!0;if(B.status===409)return!0;if(B.status===429)return!0;if(B.status>=500)return!0;return!1}async retryRequest(B,C,T,y){let R,x=y?.get("retry-after-ms");if(x){let E=parseFloat(x);if(!Number.isNaN(E))R=E}let k=y?.get("retry-after");if(k&&!R){let E=parseFloat(k);if(!Number.isNaN(E))R=E*1000;else R=Date.parse(k)-Date.now()}if(R===void 0){let E=B.maxRetries??this.maxRetries;R=this.calculateDefaultRetryTimeoutMillis(C,E)}return await KC(R),this.makeRequest(B,C-1,T)}calculateDefaultRetryTimeoutMillis(B,C){let R=C-B,x=Math.min(0.5*Math.pow(2,R),8),k=1-Math.random()*0.25;return x*k*1000}calculateNonstreamingTimeout(B,C){if(3600000*B/128000>600000||C!=null&&B>C)throw new W("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 600000}async buildRequest(B,{retryCount:C=0}={}){let T={...B},{method:y,path:R,query:x,defaultBaseURL:k}=T,E=this.buildURL(R,x,k);if("timeout"in T)NC("timeout",T.timeout);T.timeout=T.timeout??this.timeout;let{bodyHeaders:S,body:U}=this.buildBody({options:T}),P=await this.buildHeaders({options:B,method:y,bodyHeaders:S,retryCount:C});return{req:{method:y,headers:P,...T.signal&&{signal:T.signal},...globalThis.ReadableStream&&U instanceof globalThis.ReadableStream&&{duplex:"half"},...U&&{body:U},...this.fetchOptions??{},...T.fetchOptions??{}},url:E,timeout:T.timeout}}async buildHeaders({options:B,method:C,bodyHeaders:T,retryCount:y}){let R={};if(this.idempotencyHeader&&C!=="get"){if(!B.idempotencyKey)B.idempotencyKey=this.defaultIdempotencyKey();R[this.idempotencyHeader]=B.idempotencyKey}let x=J([R,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(y),...B.timeout?{"X-Stainless-Timeout":String(Math.trunc(B.timeout/1000))}:{},...OC(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(B),this._options.defaultHeaders,T,B.headers]);return this.validateHeaders(x),x.values}_makeAbort(B){return()=>B.abort()}buildBody({options:{body:B,headers:C}}){if(!B)return{bodyHeaders:void 0,body:void 0};let T=J([C]);if(ArrayBuffer.isView(B)||B instanceof ArrayBuffer||B instanceof DataView||typeof B==="string"&&T.values.has("content-type")||globalThis.Blob&&B instanceof globalThis.Blob||B instanceof FormData||B instanceof URLSearchParams||globalThis.ReadableStream&&B instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:B};else if(typeof B==="object"&&((Symbol.asyncIterator in B)||(Symbol.iterator in B)&&("next"in B)&&typeof B.next==="function"))return{bodyHeaders:void 0,body:fB(B)};else if(typeof B==="object"&&T.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(B)};else return this.#B({body:B,headers:T})}static Anthropic=this;static PukuAI=this;static HUMAN_PROMPT=y2;static AI_PROMPT=R2;static DEFAULT_TIMEOUT=600000;static AnthropicError=W;static PukuError=v;static APIError=z;static APIConnectionError=d;static APIConnectionTimeoutError=RB;static APIUserAbortError=V;static NotFoundError=SB;static ConflictError=PB;static RateLimitError=UB;static BadRequestError=xB;static AuthenticationError=kB;static InternalServerError=MB;static PermissionDeniedError=EB;static UnprocessableEntityError=WB;static toFile=jB}class g extends dB{completions=new BB(this);messages=new t(this);models=new CB(this);beta=new j(this)}g.Completions=BB;g.Messages=t;g.Models=CB;g.Beta=j;g.Anthropic=g;var SC=(B)=>{if(typeof globalThis.Buffer<"u"){let C=globalThis.Buffer.from(B,"base64");return new Uint8Array(C.buffer,C.byteOffset,C.byteLength)}if(typeof atob<"u"){let C=atob(B),T=new Uint8Array(C.length);for(let y=0;y<C.length;y++)T[y]=C.charCodeAt(y);return T}throw new W("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")};var MT=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]);function JT(B){return JSON.parse(JSON.stringify(B))}function x2(B){let C=JT(B);return o(C)}function o(B){let C={},T=Y(B,"$ref");if(T!==void 0)return C.$ref=T,C;let y=Y(B,"$defs");if(y!==void 0){let P={};C.$defs=P;for(let[$,M]of Object.entries(y))P[$]=o(M)}let R=Y(B,"type"),x=Y(B,"anyOf"),k=Y(B,"oneOf"),E=Y(B,"allOf");if(Array.isArray(x))C.anyOf=x.map((P)=>o(P));else if(Array.isArray(k))C.anyOf=k.map((P)=>o(P));else if(Array.isArray(E))C.allOf=E.map((P)=>o(P));else{if(R===void 0)throw Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used");C.type=R}let S=Y(B,"description");if(S!==void 0)C.description=S;let U=Y(B,"title");if(U!==void 0)C.title=U;if(R==="object"){let P=Y(B,"properties")||{};C.properties=Object.fromEntries(Object.entries(P).map(([M,X])=>[M,o(X)])),Y(B,"additionalProperties"),C.additionalProperties=!1;let $=Y(B,"required");if($!==void 0)C.required=$}else if(R==="string"){let P=Y(B,"format");if(P!==void 0&&MT.has(P))C.format=P;else if(P!==void 0)B.format=P}else if(R==="array"){let P=Y(B,"items");if(P!==void 0)C.items=o(P);let $=Y(B,"minItems");if($!==void 0&&($===0||$===1))C.minItems=$;else if($!==void 0)B.minItems=$}if(Object.keys(B).length>0){let P=C.description;C.description=(P?P+`
|
|
41
41
|
|
|
42
|
-
`:"")+"{"+Object.entries(B).map(([$,M])=>`${$}: ${JSON.stringify(M)}`).join(", ")+"}"}return C}function a(B){if(B.inputSchema.type!=="object")throw Error(`JSON schema for tool "${B.name}" must be an object, but got ${B.inputSchema.type}`);return{type:"custom",name:B.name,input_schema:B.inputSchema,description:B.description,run:B.run,parse:(C)=>C,...B.close?{close:B.close}:{}}}function
|
|
42
|
+
`:"")+"{"+Object.entries(B).map(([$,M])=>`${$}: ${JSON.stringify(M)}`).join(", ")+"}"}return C}function a(B){if(B.inputSchema.type!=="object")throw Error(`JSON schema for tool "${B.name}" must be an object, but got ${B.inputSchema.type}`);return{type:"custom",name:B.name,input_schema:B.inputSchema,description:B.description,run:B.run,parse:(C)=>C,...B.close?{close:B.close}:{}}}function FT(B,C){if(B.type!=="object")throw Error(`JSON schema for tool must be an object, but got ${B.type}`);let T=C?.transform??!0;return B=x2(B),{type:"json_schema",schema:{...B},parse:(y)=>{try{return JSON.parse(y)}catch(R){throw new W(`Failed to parse structured output: ${R}`)}}}}function k2(B){throw new W(`${B} is provided by @puku-ai/sdk as a stub. Install the \`zod\` peer dependency to use this helper at runtime.`)}function $T(B){k2("betaZodOutputFormat")}function GT(B){k2("betaZodTool")}function ZT(B){return{type:"memory_20250818",name:"memory",parse:(C)=>C,run:(C)=>{let T=B[C.command];if(!T)throw Error(`${C.command} not implemented`);return T.bind(B)(C)}}}var wT=["image/jpeg","image/png","image/gif","image/webp"];function PC(B){return wT.includes(B)}function XT(B){return!B||B.startsWith("text/")||B==="application/pdf"||PC(B)}class I extends Error{constructor(B){super(B);this.name="UnsupportedMCPValueError"}}function E2(B,C,T){let y={...B.inputSchema,type:"object",properties:B.inputSchema.properties??null,required:B.inputSchema.required??null};return{...{name:B.name,input_schema:y,...B.description!==void 0?{description:B.description}:{},...T},run:async(k)=>{let E=await C.callTool({name:B.name,arguments:k});if(E.isError){let S=E.content.map((U)=>iB(U));throw new F(S)}if(E.content.length===0&&typeof E.structuredContent==="object"&&E.structuredContent!==null)return JSON.stringify(E.structuredContent);return E.content.map((S)=>iB(S))},parse:(k)=>k,[D]:"mcpTool"}}function zT(B,C,T){return B.map((y)=>E2(y,C,T))}function S2(B,C){return{role:B.role,content:[iB(B.content,C)],[D]:"mcpMessage"}}function NT(B,C){return B.map((T)=>S2(T,C))}function iB(B,C){switch(B.type){case"text":return{type:"text",text:B.text,...C,[D]:"mcpContent"};case"image":{if(!PC(B.mimeType))throw new I(`Unsupported image MIME type: ${B.mimeType}`);return{type:"image",source:{type:"base64",data:B.data,media_type:B.mimeType},...C,[D]:"mcpContent"}}case"resource":return P2(B.resource,C,"mcpContent");case"resource_link":case"audio":throw new I(`Unsupported MCP content type: ${B.type}`);default:throw new I(`Unsupported MCP content type: ${B.type}`)}}function P2(B,C,T="mcpResourceToContent"){let y=B.mimeType;if(y&&PC(y)){if(!("blob"in B))throw new I(`Image resource must have blob data, not text. URI: ${B.uri}`);return{type:"image",source:{type:"base64",data:B.blob,media_type:y},...C,[D]:T}}if(y==="application/pdf"){if(!("blob"in B))throw new I(`PDF resource must have blob data, not text. URI: ${B.uri}`);return{type:"document",source:{type:"base64",data:B.blob,media_type:"application/pdf"},...C,[D]:T}}if(!y||y.startsWith("text/"))return{type:"document",source:YT(B),...C,[D]:T};throw new I(`Unsupported MIME type "${y}" for resource: ${B.uri}`)}function KT(B,C){if(B.contents.length===0)throw new I("Resource contents array must contain at least one item");let T=B.contents.find((y)=>XT(y.mimeType));if(!T){let y=B.contents.map((R)=>R.mimeType).filter((R)=>R!==void 0);throw new I(`No supported MIME type found in resource contents. Available: ${y.join(", ")}`)}return P2(T,C)}function VT(B){if("blob"in B)return SC(B.blob);return new TextEncoder().encode(B.text)}function YT(B){return{type:"text",data:"text"in B?B.text:new TextDecoder().decode(SC(B.blob)),media_type:"text/plain"}}function QT(B){if(B.contents.length===0)throw new I("Resource contents array must contain at least one item");let C=B.contents[0],T=new URL(C.uri).pathname.split("/").at(-1)||"file",y=C.mimeType,R=VT(C),x=new File([R],T,y?{type:y}:void 0);return x[D]="mcpResourceToFile",x}import*as N from"node:fs/promises";import*as mB from"node:fs";import*as w from"node:path";import*as JC from"node:child_process";import*as Z2 from"node:crypto";import*as w2 from"node:readline";function WC(){let B,C;return{promise:new Promise((y,R)=>{B=y,C=R}),resolve:B,reject:C}}import*as L from"node:fs/promises";import*as Q from"node:path";import{randomUUID as OT}from"node:crypto";var W2=493,DT=420;async function qT(B){try{return await L.realpath(B)}catch{return B}}async function LT(B){let C=[],T=B,y=0;for(;;){let R;try{R=await L.realpath(T)}catch{let x=!1;try{x=(await L.lstat(T)).isSymbolicLink()}catch{}if(x){if(++y>40)throw new F(`path ${JSON.stringify(B)} has too many levels of symbolic links`);T=Q.resolve(Q.dirname(T),await L.readlink(T));continue}let k=Q.dirname(T);if(k===T)return B;C.push(Q.basename(T)),T=k;continue}return C.length?Q.join(R,...C.reverse()):R}}async function U2(B,C,T){let y=T?.allowOutside??!1,R=await qT(Q.resolve(B)),x=Q.resolve(R,C);if(y)return x;let k=await LT(x);if(k!==R&&!k.startsWith(R+Q.sep))throw new F(`path ${JSON.stringify(C)} escapes workdir`);return k}async function UC(B,C){let T=Q.dirname(B),y=Q.join(T,`.tmp-${process.pid}-${OT()}`),R;try{R=await L.open(y,"wx",DT),await R.writeFile(C,"utf-8"),await R.sync(),await R.close(),R=void 0,await L.rename(y,B)}catch(x){if(R)await R.close().catch(()=>{});throw await L.unlink(y).catch(()=>{}),x}}function OB(B,C){switch(B?.code){case"ENOENT":return`${C}: no such file or directory`;case"EACCES":case"EPERM":return`${C}: permission denied`;case"ENOTDIR":return`${C}: not a directory`;case"EISDIR":return`${C}: is a directory`;case"ELOOP":return`${C}: too many levels of symbolic links`;case"ENAMETOOLONG":return`${C}: file name too long`;case"ENOSPC":return`${C}: no space left on device`;case"EMFILE":case"ENFILE":return`${C}: too many open files`;default:return`${C}: ${B instanceof Error?B.message:String(B)}`}}import{execFile as AT}from"node:child_process";import{promisify as fT}from"node:util";var z4=fT(AT);function MC(B){throw new W(`${B} requires the upstream /v1/skills/{id}/versions/{version} and/or /v1/sessions/{id} resources. `+"@puku-ai/sdk does not yet vendor those endpoints — the agent-toolset ships without skill auto-download. "+"Use betaAgentToolset20260401({ workdir }) without client/sessionId to get the bare tools.")}async function M2(B){let{client:C,sessionId:T}=B;if(!C||!T)return async()=>{};MC("setupSkills")}async function J2(B,C,T){if(/^\d+$/.test(T))return T;MC("resolveSkillVersion")}async function F2(B,C){MC("extractSkillArchive")}var $2=102400,X2=120000,cT=262144,DB=102400,IT=2000,_T=200;class FC extends W{timeoutMs;constructor(B){super(`bash command timed out after ${B}ms`);this.name="BashTimeoutError",this.timeoutMs=B}}var HT=/\x1b\[[0-9;?]*[ -/]*[@-~]/g,jT=N.glob;function z2(B){return B===void 0?cT:B}function gT(B){return[N2(B),K2(B),V2(B),Y2(B),Q2(B),O2(B)]}function TB(B,C){return U2(B.workdir,C,{allowOutside:B.unrestrictedPaths??!1})}function bT(){let B={};for(let[C,T]of Object.entries(process.env)){if(C.startsWith("ANTHROPIC_"))continue;B[C]=T}return B}class $C{#B;#C="";#y=!1;#k=!1;#T=null;constructor(B,C=bT()){this.#B=JC.spawn("/bin/bash",["--noprofile","--norc"],{cwd:B,env:{...C,PS1:"",PS2:"",TERM:"dumb"},stdio:["pipe","pipe","pipe"],detached:!0}),this.#B.stdout.setEncoding("utf8"),this.#B.stderr.setEncoding("utf8"),this.#B.stdout.on("data",(T)=>this.#R(T)),this.#B.stderr.on("data",(T)=>this.#R(T)),this.#B.once("close",()=>{this.#k=!0;let T=this.#T;this.#T=null,T?.resolve()})}get closed(){return this.#k}#R(B){if(this.#C+=B,this.#C.length>$2)this.#C=this.#C.slice(this.#C.length-$2),this.#y=!0;if(this.#T&&this.#C.indexOf(this.#T.sentinel)>=0){let C=this.#T;this.#T=null,C.resolve()}}async exec(B,C={}){if(this.#k)throw new W("bash session terminated");let T=C.timeoutMs??X2,y=C.signal;y?.throwIfAborted(),this.#C="",this.#y=!1;let R=`__ANT_CMD_${Z2.randomUUID()}_DONE__`,x=`${R.slice(0,8)}''${R.slice(8)}`,k=`{ ${B}
|
|
43
43
|
} </dev/null 2>&1; printf '\\n${x}%d\\n' $?
|
|
44
|
-
`;if(this.#B.stdin.write(k),this.#C.indexOf(R)<0){let{promise:M,resolve:X}=
|
|
45
|
-
${$}`;return{output:$,exitCode:P}}close(){if(this.#k)return;this.#k=!0;let B=this.#T;this.#T=null,B?.resolve(),this.#B.stdout.destroy(),this.#B.stderr.destroy(),this.#B.stdin.destroy();try{process.kill(-this.#B.pid,"SIGKILL")}catch{this.#B.kill("SIGKILL")}this.#B.unref()}}function
|
|
44
|
+
`;if(this.#B.stdin.write(k),this.#C.indexOf(R)<0){let{promise:M,resolve:X}=WC();this.#T={sentinel:R,resolve:X};let A,_;try{await Promise.race([M,new Promise((f,O)=>{A=setTimeout(()=>O(new FC(T)),T)}),new Promise((f,O)=>{if(!y)return;_=()=>O(y.reason),y.addEventListener("abort",_,{once:!0})})])}finally{if(A)clearTimeout(A);if(_&&y)y.removeEventListener("abort",_);this.#T=null}}let E=this.#C.indexOf(R);if(E<0)throw new W("bash session terminated");let U=this.#C.slice(E+R.length).match(/^(-?\d+)/),P=U?parseInt(U[1],10):-1,$=this.#C.slice(0,E).replace(HT,"").replace(/\n+$/,"");if(this.#y)$=`[output truncated]
|
|
45
|
+
${$}`;return{output:$,exitCode:P}}close(){if(this.#k)return;this.#k=!0;let B=this.#T;this.#T=null,B?.resolve(),this.#B.stdout.destroy(),this.#B.stderr.destroy(),this.#B.stdin.destroy();try{process.kill(-this.#B.pid,"SIGKILL")}catch{this.#B.kill("SIGKILL")}this.#B.unref()}}function N2(B){let C,T=Promise.resolve();return a({name:"bash",description:"Run a bash command in a persistent shell. State (cwd, env vars) persists across calls.",inputSchema:{type:"object",properties:{command:{type:"string",description:"The command to run"},restart:{type:"boolean",description:"Restart the persistent shell before running"},timeout_ms:{type:"integer",description:"Per-call timeout in milliseconds"}}},run:async({command:y,restart:R,timeout_ms:x},k)=>{let E=T,S=WC();T=S.promise;try{await E}catch{}try{if(R)C?.close(),C=void 0;if(!y){if(R)return"bash session restarted";throw new F("bash: command is required")}C??=new $C(B.workdir,B.env);try{let{output:U,exitCode:P}=await C.exec(y,{timeoutMs:x??X2,signal:k?.signal});if(P!==0)throw new F(U||`exit ${P}`);return U}catch(U){if(U instanceof F)throw U;throw C.close(),C=void 0,new F(`bash: ${U instanceof Error?U.message:String(U)}`)}}finally{S.resolve()}},close:()=>{C?.close(),C=void 0}})}function K2(B){return a({name:"read",description:"Read a UTF-8 text file relative to the workdir.",inputSchema:{type:"object",properties:{file_path:{type:"string"},view_range:{type:"array",items:{type:"integer"},description:"[start_line, end_line] 1-indexed inclusive"}},required:["file_path"]},run:async({file_path:C,view_range:T})=>{if(!C)throw new F("read: file_path is required");let y=await TB(B,C),R;try{let P=await N.stat(y);if(!P.isFile())throw new F(`read: ${C} is not a regular file`);let $=z2(B.maxFileBytes);if($!==null&&P.size>$)throw new F(`read: ${C} is ${P.size} bytes, exceeds ${$}-byte limit. Use bash (head/tail/sed) to read a slice.`);R=await N.readFile(y,"utf8")}catch(P){if(P instanceof F)throw P;throw new F(`read: ${OB(P,C)}`)}if(!T)return R;if(T.length!==2)throw new F("read: view_range must be [start_line, end_line]");let[x,k]=T,E=R.split(`
|
|
46
46
|
`),S=Math.max(0,x-1),U=k>0?k:E.length;return E.slice(S,U).join(`
|
|
47
|
-
`)}})}function
|
|
48
|
-
`)}})}function
|
|
49
|
-
[output truncated at ${
|
|
50
|
-
`)}async function
|
|
47
|
+
`)}})}function V2(B){return a({name:"write",description:"Write a UTF-8 text file relative to the workdir, creating parent directories as needed.",inputSchema:{type:"object",properties:{file_path:{type:"string"},content:{type:"string"}},required:["file_path","content"]},run:async({file_path:C,content:T})=>{if(!C)throw new F("write: file_path is required");let y=await TB(B,C);try{await N.mkdir(w.dirname(y),{recursive:!0,mode:W2}),await UC(y,T??"")}catch(R){throw new F(`write: ${OB(R,C)}`)}return`wrote ${Buffer.byteLength(T??"")} bytes to ${C}`}})}function Y2(B){return a({name:"edit",description:"Replace old_string with new_string in a file. old_string must be unique unless replace_all.",inputSchema:{type:"object",properties:{file_path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["file_path","old_string","new_string"]},run:async({file_path:C,old_string:T,new_string:y,replace_all:R})=>{if(!C)throw new F("edit: file_path is required");if(!T)throw new F("edit: old_string is required");let x=await TB(B,C),k;try{let U=await N.stat(x);if(!U.isFile())throw new F(`edit: ${C} is not a regular file`);let P=z2(B.maxFileBytes);if(P!==null&&U.size>P)throw new F(`edit: ${C} is ${U.size} bytes, exceeds ${P}-byte limit. Use bash (sed/awk) to edit a large file.`);k=await N.readFile(x,"utf8")}catch(U){if(U instanceof F)throw U;throw new F(`edit: ${OB(U,C)}`)}let E=k.split(T).length-1;if(E===0)throw new F(`edit: old_string not found in ${C}`);let S;if(R)S=k.split(T).join(y);else{if(E>1)throw new F(`edit: old_string appears ${E} times in ${C} (must be unique)`);S=k.replace(T,()=>y)}try{await UC(x,S)}catch(U){throw new F(`edit: write: ${OB(U,C)}`)}return`edited ${C} (${R?E:1} replacement(s))`}})}function Q2(B){return a({name:"glob",description:"Match files under the workdir against a glob pattern. Results are mtime-sorted, newest first.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string",description:"Directory to search in. Defaults to the workdir."}},required:["pattern"]},run:async({pattern:C,path:T})=>{if(!C)throw new F("glob: pattern is required");let y=w.resolve(B.workdir),R=C;if(w.isAbsolute(C)){if(!B.unrestrictedPaths)throw new F("glob: absolute pattern not permitted");y=w.parse(C).root,R=w.relative(y,C)}else if(T)y=await TB(B,T);if(!B.unrestrictedPaths&&R.split(/[\\/]/).includes(".."))throw new F('glob: ".." is not permitted in the pattern');let x=B.unrestrictedPaths?y:await N.realpath(y).catch(()=>y),k=[];try{for await(let E of jT(R,{cwd:y,withFileTypes:!0,exclude:(S)=>S.name===".git"||S.name==="node_modules"})){if(!E.isFile())continue;let S=w.join(E.parentPath,E.name);if(!B.unrestrictedPaths){let P;try{P=await N.realpath(S)}catch{continue}if(!aT(x,P))continue}let U=0;try{U=(await N.stat(S)).mtimeMs}catch{}k.push({path:S,mtime:U})}}catch(E){throw new F(`glob: ${E instanceof Error?E.message:String(E)}`)}if(k.length===0)return"no matches";return k.sort((E,S)=>S.mtime-E.mtime),k.slice(0,_T).map((E)=>E.path).join(`
|
|
48
|
+
`)}})}function O2(B){return a({name:"grep",description:"Search file contents for a regex. Uses ripgrep if available, otherwise a built-in walker.",inputSchema:{type:"object",properties:{pattern:{type:"string"},path:{type:"string"}},required:["pattern"]},run:async({pattern:C,path:T},y)=>{if(!C)throw new F("grep: pattern is required");let R=w.resolve(B.workdir);if(T)R=await TB(B,T);let x=await tT();return x?lT(x,C,R,y?.signal):hT(C,R,y?.signal)}})}function lT(B,C,T,y){return new Promise((R,x)=>{let k=JC.spawn(B,["-n","--no-heading","-e",C,"--",T],{...y?{signal:y}:{}}),E="",S="",U=!1;k.stdout.on("data",(P)=>{if(U)return;if(E+=P,E.length>DB)U=!0,E=E.slice(0,DB),k.kill("SIGKILL")}),k.stderr.on("data",(P)=>S+=P),k.on("close",(P)=>{if(y?.aborted)return x(new F("grep: aborted"));if(U)return R(E+`
|
|
49
|
+
[output truncated at ${DB} bytes]`);if(P===0)return R(E);if(P===1)return R("no matches");x(new F(`grep: rg failed: ${S||`exit ${P}`}`))}),k.on("error",(P)=>{if(y?.aborted)return x(new F("grep: aborted"));x(new F(`grep: rg failed: ${P.message}`))})})}async function hT(B,C,T){let y;try{y=new RegExp(B)}catch(S){throw new F(`grep: invalid regex: ${S instanceof Error?S.message:String(S)}`)}let R=[],x=DB,k=(S)=>{if(x-=S.length+1,x<0)return R.push(`[output truncated at ${DB} bytes]`),!1;return R.push(S),!0};if((await N.stat(C).catch(()=>null))?.isFile())await G2(C,y,k);else await mT(C,"",(S)=>G2(w.join(C,S),y,k),T);if(T?.aborted)throw new F("grep: aborted");if(R.length===0)return"no matches";return R.join(`
|
|
50
|
+
`)}async function G2(B,C,T){let y=mB.createReadStream(B,{encoding:"utf8"}),R=w2.createInterface({input:y,crlfDelay:1/0}),x=0;try{for await(let k of R){if(x++,k.length>IT)continue;if(C.test(k)&&!T(`${B}:${x}:${k}`))return!1}}catch{}finally{y.destroy()}return!0}function aT(B,C){let T=w.relative(B,C);return T===""||!T.startsWith(".."+w.sep)&&T!==".."&&!w.isAbsolute(T)}var dT=40,iT=50000;async function mT(B,C,T,y){let R=iT;async function x(k,E){if(E>dT)return!0;if(y?.aborted)return!1;let S;try{S=await N.readdir(w.join(B,k),{withFileTypes:!0})}catch{return!0}for(let U of S){if(U.name===".git"||U.name==="node_modules")continue;if(R--<=0)return!1;if(y?.aborted)return!1;let P=k?w.join(k,U.name):U.name;if(U.isDirectory()){if(!await x(P,E+1))return!1}else if(U.isFile()){if(await T(P)===!1)return!1}}return!0}await x(C,0)}async function tT(){let B=(process.env.PATH??"").split(w.delimiter);for(let C of B){let T=w.join(C,"rg");try{return await N.access(T,mB.constants.X_OK),T}catch{}}return null}export{jB as toFile,M2 as setupSkills,J2 as resolveSkillVersion,TB as resolvePath,zT as mcpTools,E2 as mcpTool,QT as mcpResourceToFile,KT as mcpResourceToContent,NT as mcpMessages,S2 as mcpMessage,iB as mcpContent,F2 as extractSkillArchive,g as default,GT as betaZodTool,$T as betaZodOutputFormat,V2 as betaWriteTool,a as betaTool,K2 as betaReadTool,ZT as betaMemoryTool,FT as betaJSONSchemaOutputFormat,O2 as betaGrepTool,Q2 as betaGlobTool,Y2 as betaEditTool,N2 as betaBashTool,gT as betaAgentToolset20260401,H as VERSION,I as UnsupportedMCPValueError,WB as UnprocessableEntityError,F as ToolError,UB as RateLimitError,v as PukuError,g as PukuAI,EB as PermissionDeniedError,HB as PagePromise,SB as NotFoundError,MB as InternalServerError,y2 as HUMAN_PROMPT,PB as ConflictError,FC as BashTimeoutError,$C as BashSession,dB as BasePuku,xB as BadRequestError,kB as AuthenticationError,W as AnthropicError,V as APIUserAbortError,i as APIPromise,z as APIError,RB as APIConnectionTimeoutError,d as APIConnectionError,R2 as AI_PROMPT};
|
|
51
51
|
|
|
52
|
-
//# debugId=
|
|
52
|
+
//# debugId=A2B68951AB75669D64756E2164756E21
|