@swifty.js/swifty 0.0.10 → 0.0.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-NX7ND57K.js +4 -0
- package/dist/anthropic-EAEDMTTA.js +4 -0
- package/dist/checker-NNTNXNYP.js +4 -0
- package/dist/{chunk-PLNXRQQA.js → chunk-ADGTJUJZ.js} +84 -83
- package/dist/chunk-GQ2COSTQ.js +126 -0
- package/dist/{chunk-XYSBNUNB.js → chunk-M5AOLYFS.js} +19 -19
- package/dist/{chunk-OZOP4GVS.js → chunk-MSJOPX6X.js} +1 -1
- package/dist/{chunk-2BJOFNPI.js → chunk-R7VREEYH.js} +1 -1
- package/dist/{chunk-SM5OVMF6.js → chunk-RNUCVDX2.js} +4 -4
- package/dist/glob_addon.node +0 -0
- package/dist/main.js +222 -226
- package/dist/{openai-NMDB34GN.js → openai-L6LWA2MU.js} +2 -2
- package/dist/{server-MVTICJSO.js → server-4Q5ZDD7S.js} +2 -2
- package/package.json +1 -1
- package/dist/agent-4K4HNCSZ.js +0 -4
- package/dist/anthropic-DFGYPMNW.js +0 -4
- package/dist/checker-DWBNQC3N.js +0 -4
- package/dist/chunk-MQ5XOYLD.js +0 -4
- package/dist/chunk-OKI2P5FO.js +0 -126
- package/dist/cleanup-BQJDUOKA.js +0 -4
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{g as tn,h as rn}from"./chunk-OZOP4GVS.js";import{b as Zs,c as Gn,d as Is,e as Qn,f as Yn,g as Zn}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{I as Xn,J as qr,K as He,L as As,M as bs,N as en,S as xt}from"./chunk-XYSBNUNB.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function c(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var We=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return We=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Hr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Wr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var g=class extends Error{},F=class s extends g{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Se({message:r,cause:Wr(t)});let o=t?.error;return e===400?new Rt(e,o,r,n):e===401?new St(e,o,r,n):e===403?new Ct(e,o,r,n):e===404?new kt(e,o,r,n):e===409?new $t(e,o,r,n):e===422?new Et(e,o,r,n):e===429?new Ot(e,o,r,n):e>=500?new vt(e,o,r,n):new s(e,o,r,n)}},M=class extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Se=class extends F{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Ce=class extends Se{constructor({message:e}={}){super({message:e??"Request timed out."})}},Rt=class extends F{},St=class extends F{},Ct=class extends F{},kt=class extends F{},$t=class extends F{},Et=class extends F{},Ot=class extends F{},vt=class extends F{},Tt=class extends g{constructor(){super("Could not parse response content as the length limit was reached")}},jt=class extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},pe=class extends Error{constructor(e){super(e)}},Je=class extends F{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let a=t;o=a.error;let l=a.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,r),this.error_code=o}},Jr=class extends g{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var yi=/^[a-z][a-z0-9+.-]*:/i,eo=s=>yi.test(s),X=s=>(X=Array.isArray,X(s)),sn=X;function ws(s){return typeof s!="object"?{}:s??{}}function nn(s){if(!s)return!0;for(let e in s)return!1;return!0}function to(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Vr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var ro=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${s} must be an integer`);if(e<0)throw new g(`${s} must be a positive integer`);return e};var so=s=>{try{return JSON.parse(s)}catch{return}};var de=s=>new Promise(e=>setTimeout(e,s));var ke="6.49.0";var ao=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function gi(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Ai=()=>{let s=gi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":oo(Deno.build.os),"X-Stainless-Arch":no(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":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":oo(globalThis.process.platform??"unknown"),"X-Stainless-Arch":no(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=bi();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function bi(){if(typeof navigator>"u"||!navigator)return null;let s=[{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:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,a=r[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}var no=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",oo=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),io,uo=()=>io??(io=Ai());function Ps(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function on(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Xr(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return on({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function xs(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function an(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var lo=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var un="RFC3986",cn=s=>String(s),ln={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:cn},po="RFC1738";var Rs=(s,e)=>(Rs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Rs(s,e)),fe=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var pn=1024,fo=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<o.length;l+=pn){let f=o.length>=pn?o.slice(l,l+pn):o,p=[];for(let _=0;_<f.length;++_){let m=f.charCodeAt(_);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||n===po&&(m===40||m===41)){p[p.length]=f.charAt(_);continue}if(m<128){p[p.length]=fe[m];continue}if(m<2048){p[p.length]=fe[192|m>>6]+fe[128|m&63];continue}if(m<55296||m>=57344){p[p.length]=fe[224|m>>12]+fe[128|m>>6&63]+fe[128|m&63];continue}_+=1,m=65536+((m&1023)<<10|f.charCodeAt(_)&1023),p[p.length]=fe[240|m>>18]+fe[128|m>>12&63]+fe[128|m>>6&63]+fe[128|m&63]}a+=p.join("")}return a};function ho(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function dn(s,e){if(X(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var _o={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},yo=function(s,e){Array.prototype.push.apply(s,X(e)?e:[e])},mo,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fo,encodeValuesOnly:!1,format:un,formatter:cn,indices:!1,serializeDate(s){return(mo??(mo=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function wi(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var fn={};function go(s,e,t,r,n,o,a,l,f,p,_,m,d,b,w,A,I,k){let y=s,P=k,R=0,v=!1;for(;(P=P.get(fn))!==void 0&&!v;){let T=P.get(s);if(R+=1,typeof T<"u"){if(T===R)throw new RangeError("Cyclic object value");v=!0}typeof P.get(fn)>"u"&&(R=0)}if(typeof p=="function"?y=p(e,y):y instanceof Date?y=d?.(y):t==="comma"&&X(y)&&(y=dn(y,function(T){return T instanceof Date?d?.(T):T})),y===null){if(o)return f&&!A?f(e,D.encoder,I,"key",b):e;y=""}if(wi(y)||ho(y)){if(f){let T=A?e:f(e,D.encoder,I,"key",b);return[w?.(T)+"="+w?.(f(y,D.encoder,I,"value",b))]}return[w?.(e)+"="+w?.(String(y))]}let $=[];if(typeof y>"u")return $;let L;if(t==="comma"&&X(y))A&&f&&(y=dn(y,f)),L=[{value:y.length>0?y.join(",")||null:void 0}];else if(X(p))L=p;else{let T=Object.keys(y);L=_?T.sort(_):T}let j=l?String(e).replace(/\./g,"%2E"):String(e),N=r&&X(y)&&y.length===1?j+"[]":j;if(n&&X(y)&&y.length===0)return N+"[]";for(let T=0;T<L.length;++T){let W=L[T],Pt=typeof W=="object"&&typeof W.value<"u"?W.value:y[W];if(a&&Pt===null)continue;let J=m&&l?W.replace(/\./g,"%2E"):W,ys=X(y)?typeof t=="function"?t(N,J):N:N+(m?"."+J:"["+J+"]");k.set(s,R);let gs=new WeakMap;gs.set(fn,k),yo($,go(Pt,ys,t,r,n,o,a,l,t==="comma"&&A&&X(y)?null:f,p,_,m,d,b,w,A,I,gs))}return $}function Pi(s=D){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||D.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=un;if(typeof s.format<"u"){if(!Rs(ln,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=ln[t],n=D.filter;(typeof s.filter=="function"||X(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in _o?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=D.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:D.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:D.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?D.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:D.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:D.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:D.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:D.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:D.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:D.strictNullHandling}}function Ao(s,e={}){let t=s,r=Pi(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):X(r.filter)&&(o=r.filter,n=o);let a=[];if(typeof t!="object"||t===null)return"";let l=_o[r.arrayFormat],f=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let d=0;d<n.length;++d){let b=n[d];r.skipNulls&&t[b]===null||yo(a,go(t[b],b,l,f,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,p))}let _=a.join(r.delimiter),m=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),_.length>0?m+_:""}function bo(s){return Ao(s,{arrayFormat:"brackets"})}function Po(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Io;function ee(s){let e;return(Io??(e=new globalThis.TextEncoder,Io=e.encode.bind(e)))(s)}var wo;function hn(s){let e;return(wo??(e=new globalThis.TextDecoder,wo=e.decode.bind(e)))(s)}var te,re,Ve=class{constructor(){te.set(this,void 0),re.set(this,void 0),x(this,te,new Uint8Array,"f"),x(this,re,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ee(e):e;x(this,te,Po([c(this,te,"f"),t]),"f");let r=[],n;for(;(n=Ri(c(this,te,"f"),c(this,re,"f")))!=null;){if(n.carriage&&c(this,re,"f")==null){x(this,re,n.index,"f");continue}if(c(this,re,"f")!=null&&(n.index!==c(this,re,"f")+1||n.carriage)){r.push(hn(c(this,te,"f").subarray(0,c(this,re,"f")-1))),x(this,te,c(this,te,"f").subarray(c(this,re,"f")),"f"),x(this,re,null,"f");continue}let o=c(this,re,"f")!==null?n.preceding-1:n.preceding,a=hn(c(this,te,"f").subarray(0,o));r.push(a),x(this,te,c(this,te,"f").subarray(n.index),"f"),x(this,re,null,"f")}return r}flush(){return c(this,te,"f").length?this.decode(`
|
|
4
|
+
import{g as tn,h as rn}from"./chunk-MSJOPX6X.js";import{b as Zs,c as Gn,d as Is,e as Qn,f as Yn,g as Zn}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{I as Xn,J as qr,K as He,L as As,M as bs,N as en,S as xt}from"./chunk-M5AOLYFS.js";import"./chunk-X3UA5OZL.js";function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function c(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var We=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return We=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Hr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Wr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var g=class extends Error{},F=class s extends g{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Se({message:r,cause:Wr(t)});let o=t?.error;return e===400?new Rt(e,o,r,n):e===401?new St(e,o,r,n):e===403?new Ct(e,o,r,n):e===404?new kt(e,o,r,n):e===409?new $t(e,o,r,n):e===422?new Et(e,o,r,n):e===429?new Ot(e,o,r,n):e>=500?new vt(e,o,r,n):new s(e,o,r,n)}},M=class extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Se=class extends F{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Ce=class extends Se{constructor({message:e}={}){super({message:e??"Request timed out."})}},Rt=class extends F{},St=class extends F{},Ct=class extends F{},kt=class extends F{},$t=class extends F{},Et=class extends F{},Ot=class extends F{},vt=class extends F{},Tt=class extends g{constructor(){super("Could not parse response content as the length limit was reached")}},jt=class extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},pe=class extends Error{constructor(e){super(e)}},Je=class extends F{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let a=t;o=a.error;let l=a.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,r),this.error_code=o}},Jr=class extends g{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var yi=/^[a-z][a-z0-9+.-]*:/i,eo=s=>yi.test(s),X=s=>(X=Array.isArray,X(s)),sn=X;function ws(s){return typeof s!="object"?{}:s??{}}function nn(s){if(!s)return!0;for(let e in s)return!1;return!0}function to(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Vr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var ro=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${s} must be an integer`);if(e<0)throw new g(`${s} must be a positive integer`);return e};var so=s=>{try{return JSON.parse(s)}catch{return}};var de=s=>new Promise(e=>setTimeout(e,s));var ke="6.49.0";var ao=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function gi(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Ai=()=>{let s=gi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":oo(Deno.build.os),"X-Stainless-Arch":no(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":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":oo(globalThis.process.platform??"unknown"),"X-Stainless-Arch":no(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=bi();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function bi(){if(typeof navigator>"u"||!navigator)return null;let s=[{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:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,a=r[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}var no=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",oo=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),io,uo=()=>io??(io=Ai());function Ps(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function on(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Xr(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return on({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function xs(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function an(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var lo=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var un="RFC3986",cn=s=>String(s),ln={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:cn},po="RFC1738";var Rs=(s,e)=>(Rs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Rs(s,e)),fe=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var pn=1024,fo=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<o.length;l+=pn){let f=o.length>=pn?o.slice(l,l+pn):o,p=[];for(let _=0;_<f.length;++_){let m=f.charCodeAt(_);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||n===po&&(m===40||m===41)){p[p.length]=f.charAt(_);continue}if(m<128){p[p.length]=fe[m];continue}if(m<2048){p[p.length]=fe[192|m>>6]+fe[128|m&63];continue}if(m<55296||m>=57344){p[p.length]=fe[224|m>>12]+fe[128|m>>6&63]+fe[128|m&63];continue}_+=1,m=65536+((m&1023)<<10|f.charCodeAt(_)&1023),p[p.length]=fe[240|m>>18]+fe[128|m>>12&63]+fe[128|m>>6&63]+fe[128|m&63]}a+=p.join("")}return a};function ho(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function dn(s,e){if(X(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var _o={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},yo=function(s,e){Array.prototype.push.apply(s,X(e)?e:[e])},mo,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fo,encodeValuesOnly:!1,format:un,formatter:cn,indices:!1,serializeDate(s){return(mo??(mo=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function wi(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var fn={};function go(s,e,t,r,n,o,a,l,f,p,_,m,d,b,w,A,I,k){let y=s,P=k,R=0,v=!1;for(;(P=P.get(fn))!==void 0&&!v;){let T=P.get(s);if(R+=1,typeof T<"u"){if(T===R)throw new RangeError("Cyclic object value");v=!0}typeof P.get(fn)>"u"&&(R=0)}if(typeof p=="function"?y=p(e,y):y instanceof Date?y=d?.(y):t==="comma"&&X(y)&&(y=dn(y,function(T){return T instanceof Date?d?.(T):T})),y===null){if(o)return f&&!A?f(e,D.encoder,I,"key",b):e;y=""}if(wi(y)||ho(y)){if(f){let T=A?e:f(e,D.encoder,I,"key",b);return[w?.(T)+"="+w?.(f(y,D.encoder,I,"value",b))]}return[w?.(e)+"="+w?.(String(y))]}let $=[];if(typeof y>"u")return $;let L;if(t==="comma"&&X(y))A&&f&&(y=dn(y,f)),L=[{value:y.length>0?y.join(",")||null:void 0}];else if(X(p))L=p;else{let T=Object.keys(y);L=_?T.sort(_):T}let j=l?String(e).replace(/\./g,"%2E"):String(e),N=r&&X(y)&&y.length===1?j+"[]":j;if(n&&X(y)&&y.length===0)return N+"[]";for(let T=0;T<L.length;++T){let W=L[T],Pt=typeof W=="object"&&typeof W.value<"u"?W.value:y[W];if(a&&Pt===null)continue;let J=m&&l?W.replace(/\./g,"%2E"):W,ys=X(y)?typeof t=="function"?t(N,J):N:N+(m?"."+J:"["+J+"]");k.set(s,R);let gs=new WeakMap;gs.set(fn,k),yo($,go(Pt,ys,t,r,n,o,a,l,t==="comma"&&A&&X(y)?null:f,p,_,m,d,b,w,A,I,gs))}return $}function Pi(s=D){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||D.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=un;if(typeof s.format<"u"){if(!Rs(ln,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=ln[t],n=D.filter;(typeof s.filter=="function"||X(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in _o?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=D.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:D.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:D.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?D.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:D.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:D.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:D.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:D.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:D.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:D.strictNullHandling}}function Ao(s,e={}){let t=s,r=Pi(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):X(r.filter)&&(o=r.filter,n=o);let a=[];if(typeof t!="object"||t===null)return"";let l=_o[r.arrayFormat],f=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let d=0;d<n.length;++d){let b=n[d];r.skipNulls&&t[b]===null||yo(a,go(t[b],b,l,f,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,p))}let _=a.join(r.delimiter),m=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),_.length>0?m+_:""}function bo(s){return Ao(s,{arrayFormat:"brackets"})}function Po(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Io;function ee(s){let e;return(Io??(e=new globalThis.TextEncoder,Io=e.encode.bind(e)))(s)}var wo;function hn(s){let e;return(wo??(e=new globalThis.TextDecoder,wo=e.decode.bind(e)))(s)}var te,re,Ve=class{constructor(){te.set(this,void 0),re.set(this,void 0),x(this,te,new Uint8Array,"f"),x(this,re,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ee(e):e;x(this,te,Po([c(this,te,"f"),t]),"f");let r=[],n;for(;(n=Ri(c(this,te,"f"),c(this,re,"f")))!=null;){if(n.carriage&&c(this,re,"f")==null){x(this,re,n.index,"f");continue}if(c(this,re,"f")!=null&&(n.index!==c(this,re,"f")+1||n.carriage)){r.push(hn(c(this,te,"f").subarray(0,c(this,re,"f")-1))),x(this,te,c(this,te,"f").subarray(c(this,re,"f")),"f"),x(this,re,null,"f");continue}let o=c(this,re,"f")!==null?n.preceding-1:n.preceding,a=hn(c(this,te,"f").subarray(0,o));r.push(a),x(this,te,c(this,te,"f").subarray(n.index),"f"),x(this,re,null,"f")}return r}flush(){return c(this,te,"f").length?this.decode(`
|
|
5
5
|
`):[]}};te=new WeakMap,re=new WeakMap;Ve.NEWLINE_CHARS=new Set([`
|
|
6
6
|
`,"\r"]);Ve.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ri(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function xo(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var Cs={off:0,error:200,warn:300,info:400,debug:500},mn=(s,e,t)=>{if(s){if(to(Cs,s))return s;K(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(Cs))}`)}};function Gr(){}function Ss(s,e,t){return!e||Cs[s]>Cs[t]?Gr:e[s].bind(e)}var Si={error:Gr,warn:Gr,info:Gr,debug:Gr},Ro=new WeakMap;function K(s){let e=s.logger,t=s.logLevel??"off";if(!e)return Si;let r=Ro.get(e);if(r&&r[0]===t)return r[1];let n={error:Ss("error",e,t),warn:Ss("warn",e,t),info:Ss("info",e,t),debug:Ss("debug",e,t)};return Ro.set(e,[t,n]),n}var ye=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Qr,Z=class s{constructor(e,t,r){this.iterator=e,Qr.set(this,void 0),this.controller=t,x(this,Qr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,a=r?K(r):console;async function*l(){if(o)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let f=!1;try{for await(let p of Ci(e,t))if(!f){if(p.data.startsWith("[DONE]")){f=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let _;try{_=JSON.parse(p.data)}catch(m){throw a.error("Could not parse message into JSON:",p.data),a.error("From chunk:",p.raw),m}if(_&&_.error)throw new F(void 0,_.error,void 0,e.headers);yield n?{event:p.event,data:_}:_}else{let _;try{_=JSON.parse(p.data)}catch(m){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),m}if(p.event=="error")throw new F(void 0,_.error,_.message,void 0);yield{event:p.event,data:_}}}f=!0}catch(p){if(Hr(p))return;throw p}finally{f||t.abort()}}return new s(l,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let l=new Ve,f=e.getReader(),p=!1,_,m=()=>{_??(_=f.cancel()),_.catch(()=>{})};t.signal.addEventListener("abort",m,{once:!0});try{if(t.signal.aborted){m();return}for(;;){let{value:d,done:b}=await f.read();if(b){p=!0;break}if(t.signal.aborted)return;for(let w of l.decode(d)){if(t.signal.aborted)return;yield w}}if(t.signal.aborted)return;for(let d of l.flush()){if(t.signal.aborted)return;yield d}}finally{t.signal.removeEventListener("abort",m),p||m(),f.releaseLock()}}async function*a(){if(n)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{for await(let f of o())l||f&&(yield JSON.parse(f));l=!0}catch(f){if(t.signal.aborted||Hr(f))return;throw f}finally{l||t.abort()}}return new s(a,t,r)}[(Qr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let a=r.next();e.push(a),t.push(a)}return o.shift()}});return[new s(()=>n(e),this.controller,c(this,Qr,"f")),new s(()=>n(t),this.controller,c(this,Qr,"f"))]}toReadableStream(){let e=this,t;return on({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let a=ee(JSON.stringify(n)+`
|
|
7
7
|
`);r.enqueue(a)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*Ci(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new g("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new g("Attempted to iterate over a response with no body");let t=new _n,r=new Ve,n=xs(s.body);for await(let o of ki(n))for(let a of r.decode(o)){let l=t.decode(a);l&&(yield l)}for(let o of r.flush()){let a=t.decode(o);a&&(yield a)}}async function*ki(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ee(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=xo(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var _n=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
@@ -31,4 +31,4 @@ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
|
31
31
|
|
|
32
32
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
33
33
|
`);this.baseURL=d.baseURL,this.timeout=d.timeout??Vn.DEFAULT_TIMEOUT,this.logger=d.logger??console;let b="warn";this.logLevel=b,this.logLevel=mn(d.logLevel,"ClientOptions.logLevel",this)??mn(ue("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??b,this.fetchOptions=d.fetchOptions,this.maxRetries=d.maxRetries??2,this.fetch=d.fetch??Ps(),x(this,_s,lo,"f");let w=t?void 0:ue("OPENAI_CUSTOM_HEADERS");if(w){let A={};for(let I of w.split(`
|
|
34
|
-
`)){let k=I.indexOf(":");k>=0&&(A[I.substring(0,k).trim()]=I.substring(k+1).trim())}d.defaultHeaders=h([A,d.defaultHeaders])}this._options=d,this._provider=m,p&&(this._workloadIdentityAuth=new Es(p,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=a,this.project=l,this.webhookSecret=f}withOptions(e){let t=this._options.provider,r=e.provider??t,n={...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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return r&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,r!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return h([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return h([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return h([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return h([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return bo(e)}getUserAgent(){return`${this.constructor.name}/JS ${ke}`}defaultIdempotencyKey(){return`stainless-node-retry-${We()}`}makeStatusError(e,t,r,n){return F.generate(e,t,r,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof g?r:new g(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new g(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!c(this,Jn,"m",di).call(this)&&r||this.baseURL,o=eo(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!nn(a)||!nn(l))&&(t={...l,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Xe(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:a,url:l,timeout:f}=await this.buildRequest(n,{retryCount:o-t}),p=n.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:l,options:n}),await this._provider?.prepareRequest?.(a,{url:l,options:n});let _="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(K(this).debug(`[${_}] sending request`,ye({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:a.headers})),n.signal?.aborted)throw new M;let b=n.__security??{bearerAuth:!0},w=new AbortController,A=await this.fetchWithAuth(l,a,f,w,b).catch(Wr),I=Date.now();if(A instanceof globalThis.Error){let P=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new M;let R=Hr(A)||/timed? ?out/i.test(String(A)+("cause"in A?String(A.cause):""));if(t&&!p)return K(this).info(`[${_}] connection ${R?"timed out":"failed"} - ${P}`),K(this).debug(`[${_}] connection ${R?"timed out":"failed"} (${P})`,ye({retryOfRequestLogID:r,url:l,durationMs:I-d,message:A.message})),this.retryRequest(n,t,r??_);let v=p?"error; streaming body cannot be retried":"error; no more retries left";throw K(this).info(`[${_}] connection ${R?"timed out":"failed"} - ${v}`),K(this).debug(`[${_}] connection ${R?"timed out":"failed"} (${v})`,ye({retryOfRequestLogID:r,url:l,durationMs:I-d,message:A.message})),A instanceof Je||A instanceof Jr?A:R?new Ce:new Se({message:$u(A),cause:A})}let k=[...A.headers.entries()].filter(([P])=>P==="x-request-id").map(([P,R])=>", "+P+": "+JSON.stringify(R)).join(""),y=`[${_}${m}${k}] ${a.method} ${l} ${A.ok?"succeeded":"failed"} with status ${A.status} in ${I-d}ms`;if(!A.ok){if(A.status===401&&this._workloadIdentityAuth&&b.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await an(A.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??_);let P=await this.shouldRetry(A);if(t&&P&&!p){let N=`retrying, ${t} attempts remaining`;return await an(A.body),K(this).info(`${y} - ${N}`),K(this).debug(`[${_}] response error (${N})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:I-d})),this.retryRequest(n,t,r??_,A.headers)}let R=P?p?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";K(this).info(`${y} - ${R}`);let v=await A.text().catch(N=>Wr(N).message),$=so(v),L=$?void 0:v;throw K(this).debug(`[${_}] response error (${R})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,message:L,durationMs:Date.now()-d})),this.makeStatusError(A.status,$,L,A.headers)}return K(this).info(y),K(this).debug(`[${_}] response start`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:I-d})),{response:A,options:n,controller:w,requestLogID:_,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Zr(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let l=t.headers,f=l.get("Authorization");if(!f||f===`Bearer ${ku}`){let p=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${p}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:a,...l}=t||{},f=this._makeAbort(n);o&&o.addEventListener("abort",f,{once:!0});let p=setTimeout(f,r),_=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,m={signal:n.signal,..._?{duplex:"half"}:{},method:"GET",...l};a&&(m.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(p)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,n){let o,a=n?.get("retry-after-ms");if(a){let f=parseFloat(a);Number.isNaN(f)||(o=f)}let l=n?.get("retry-after");if(l&&!o){let f=parseFloat(l);Number.isNaN(f)?o=Date.parse(l)-Date.now():o=f*1e3}if(o===void 0){let f=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,f)}return await de(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return a*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:a,defaultBaseURL:l}=r,f=this.buildURL(o,a,l);"timeout"in r&&ro("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:_,isStreamingBody:m}=this.buildBody({options:r});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let d=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=h([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...uo(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...c(this,_s,"f").call(this,{body:t,headers:h([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=h([r]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,a=!o&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Xr(t),isStreamingBody:!0}:typeof t=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...c(this,_s,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};Vn=S,_s=new WeakMap,Jn=new WeakSet,di=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};S.OpenAI=Vn;S.DEFAULT_TIMEOUT=6e5;S.OpenAIError=g;S.APIError=F;S.APIConnectionError=Se;S.APIConnectionTimeoutError=Ce;S.APIUserAbortError=M;S.NotFoundError=kt;S.ConflictError=$t;S.RateLimitError=Ot;S.BadRequestError=Rt;S.AuthenticationError=St;S.InternalServerError=vt;S.PermissionDeniedError=Ct;S.UnprocessableEntityError=Et;S.InvalidWebhookSignatureError=pe;S.toFile=js;S.toStreamingFile=vs;S.Completions=ut;S.Chat=ve;S.Embeddings=lt;S.Files=dt;S.Images=_t;S.Audio=he;S.Moderations=gt;S.Models=yt;S.FineTuning=le;S.Graders=De;S.VectorStores=Re;S.Webhooks=wt;S.Beta=oe;S.Batches=st;S.Uploads=qe;S.Admin=je;S.Responses=_e;S.Realtime=Pe;S.Conversations=Be;S.Evals=Ue;S.Containers=Ke;S.Skills=xe;S.Videos=It;function $u(s){if(Eu(s))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function Eu(s){let e=s;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var Qs=Xn({module:"llm"});var fi=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=rn(e);if(!r)throw new Is("OpenAI API key not found, set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=tn(e)}async*stream(e,t,r){let n=Nu(Zs(e.getMessages())),o=[];o.push({role:"system",content:this.systemPrompt});for(let d of n)o.push(d);let a=t.map(d=>{let b=d.input_schema;return{type:"function",name:d.name,description:d.description,parameters:b,strict:!1}}),l={model:this.model,input:o,stream:!0,max_output_tokens:this.maxOutputTokens,...a.length>0?{tools:a}:{}},f=0,p=0,_=0,m=0;try{let d=await this.client.responses.create(l,{...r?{signal:r}:{}}),b="",w="",A="",I="",k="";for await(let y of d)if(y.type==="response.output_text.delta")yield{type:"text_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.delta")k+=y.delta,yield{type:"thinking_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.done")yield{type:"thinking_complete",thinking:k,signature:I};else if(y.type==="response.function_call_arguments.delta")A+=y.delta,yield{type:"tool_call_delta",text:y.delta};else if(y.type==="response.output_item.added")y.item.type==="function_call"?(b=y.item.name,w=y.item.call_id,A="",yield{type:"tool_call_start",toolName:b,toolId:w}):y.item.type==="reasoning"&&(I=y.item.id??"",k="");else if(y.type==="response.output_item.done"){if(y.item.type==="function_call"&&b){let P={};if(A)try{let R=JSON.parse(A);P=As(R)?bs(R):{[qr]:A}}catch(R){Qs.error({err:R},"llm operation failed"),P={[qr]:A}}yield{type:"tool_call_complete",toolId:w,toolName:b,arguments:P},b="",w="",A=""}}else if(y.type==="response.completed"){let P=y.response.usage;P&&(p=P.output_tokens,_=P.input_tokens_details.cached_tokens,f=Math.max(0,P.input_tokens-_));let R="end_turn",v=y.response;v.status==="incomplete"&&v.incomplete_details?.reason==="max_output_tokens"&&(R="max_tokens"),yield{type:"stream_end",stopReason:R,usage:{inputTokens:f,outputTokens:p,cacheReadInputTokens:_,cacheCreationInputTokens:m}}}}catch(d){throw Qs.error({err:d},"llm operation failed"),mi(d)}}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}};function Ys(s){if(s.type!=="image")return null;let e=s.source;if(!As(e)||e.type!=="base64")return null;let t=xt(e,"media_type"),r=xt(e,"data");return!t||!r?null:`data:${t};base64,${r}`}function Ou(s){let{toolUseId:e,content:t}=s;if(typeof t=="string")return[];let r=[];for(let n of t){let o=Ys(n);o&&r.push({type:"input_image",image_url:o,detail:"auto"})}return r.length===0?[]:[{type:"input_text",text:`[Image(s) returned by tool call ${e}]`},...r]}function vu(s){let{toolUseId:e,content:t}=s;if(typeof t=="string")return[];let r=[];for(let n of t){let o=Ys(n);o&&r.push({type:"image_url",image_url:{url:o}})}return r.length===0?[]:[{type:"text",text:`[Image(s) returned by tool call ${e}]`},...r]}function Tu(s){if(typeof s=="string")return s;let e=[];for(let t of s)if(t.type==="text")e.push({type:"input_text",text:xt(t,"text")});else{let r=Ys(t);r&&e.push({type:"input_image",image_url:r,detail:"auto"})}return e}function ju(s){if(typeof s=="string")return s;let e=[];for(let t of s)if(t.type==="text")e.push({type:"text",text:xt(t,"text")});else{let r=Ys(t);r&&e.push({type:"image_url",image_url:{url:r}})}return e}function Nu(s){let e=[];for(let t of s){if(t.thinkingBlocks)for(let r of t.thinkingBlocks)e.push({type:"reasoning",id:r.signature,summary:[{type:"summary_text",text:r.thinking}]});if(t.toolUses&&t.toolUses.length>0){let r=typeof t.content=="string"?t.content:He(t.content);r&&e.push({role:"assistant",content:r});for(let n of t.toolUses)e.push({type:"function_call",name:n.toolName,call_id:n.toolUseId,arguments:JSON.stringify(n.arguments)})}else if(t.toolResults&&t.toolResults.length>0){let r=[];for(let n of t.toolResults)e.push({type:"function_call_output",call_id:n.toolUseId,output:He(n.content)}),r.push(...Ou(n));r.length>0&&e.push({role:"user",content:r})}else t.role==="assistant"?e.push({role:"assistant",content:typeof t.content=="string"?t.content:He(t.content)}):e.push({role:t.role,content:Tu(t.content)})}return e}function Fu(s){return/context_length_exceeded/i.test(s)||/maximum\scontext\slength/i.test(s)||/prompts?\s+too\s+long/i.test(s)}var hi=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=rn(e);if(!r)throw new Is("OpenAI API key not found. Set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=tn(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,r){let n=[{role:"system",content:this.systemPrompt},...Lu(Zs(e.getMessages()))],o=t.map(m=>({type:"function",function:{name:m.name,description:m.description,arguments:m.input_schema}})),a={model:this.model,messages:n,stream:!0,stream_options:{include_usage:!0},max_tokens:this.maxOutputTokens,...o.length>0?{tools:o}:{}},l=0,f=0,p=0,_=0;try{let m=await this.client.chat.completions.create(a,{...r?{signal:r}:{}}),d=new Map,b=null,w="";for await(let I of m){if(I.usage&&(f=I.usage.completion_tokens??0,p=I.usage.prompt_tokens_details?.cached_tokens??0,l=Math.max(0,(I.usage.prompt_tokens??0)-p)),I.choices.length===0)continue;let k=I.choices[0].delta;k.content&&(yield{type:"text_delta",text:k.content});let y=xt(bs(k),"reasoning_content");if(y&&(w+=y,yield{type:"thinking_delta",text:y}),k.tool_calls)for(let P of k.tool_calls){d.has(P.index)||(d.set(P.index,{id:P.id??"",name:P.function?.name??"",args:""}),P.id&&(yield{type:"tool_call_start",toolName:P.function?.name??"",toolId:P.id??""}));let R=d.get(P.index);R&&(P.id&&(R.id=P.id),P.function?.name&&(R.name=P.function.name),P.function?.arguments&&(R.args+=P.function.arguments,yield{type:"tool_call_delta",text:P.function.arguments}))}if(I.choices[0].finish_reason){b=I.choices[0].finish_reason,w&&(yield{type:"thinking_complete",thinking:w,signature:""},w="");for(let P of d.values()){let R={},v=P.args;if(v){try{let $=JSON.parse(v);R=As($)?bs($):{[qr]:v}}catch($){Qs.error({err:$},"llm operation failed"),R={[qr]:v}}yield{type:"tool_call_complete",toolName:P.name,toolId:P.id,arguments:R}}}}}let A;b==="length"?A="max_tokens":b==="tool_calls"||d.size>0?A="tool_use":A="end_turn",yield{type:"stream_end",stopReason:A,usage:{inputTokens:l,outputTokens:f,cacheReadInputTokens:p,cacheCreationInputTokens:_}}}catch(m){throw Qs.error({err:m},"llm operation failed"),mi(m)}}};function mi(s){return s instanceof S.APIError?s.status===413||s.status===400&&Fu(s.message)?new Zn(`Context Too Long: ${s.message}`):s.status===401?new Is(`Invalid API key: ${s.message}`):s.status===429?new Qn("Rate limit error, please wait."):new Gn(`OpenAI API error (${en(s.status)}): ${s.message}`):new Yn(`Network error: ${s instanceof Error?s.message:en(s)}`)}function Lu(s){let e=[];for(let t of s){let r=t.thinkingBlocks?.map(o=>o.thinking).join("")??"",n=typeof t.content=="string"?t.content:He(t.content);if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:n||null,tool_calls:t.toolUses.map(o=>({id:o.toolUseId,type:"function",function:{name:o.toolName,arguments:JSON.stringify(o.arguments)},...r?{reasoning_content:r}:{}}))});else if(t.toolResults&&t.toolResults.length>0){let o=[];for(let a of t.toolResults)e.push({role:"tool",tool_call_id:a.toolUseId,content:He(a.content)}),o.push(...vu(a));o.length>0&&e.push({role:"user",content:o})}else t.role==="assistant"?e.push({role:"assistant",content:n,...r?{reasoning_content:r}:{}}):t.role==="system"?e.push({role:"system",content:typeof t.content=="string"?t.content:He(t.content)}):e.push({role:"user",content:ju(t.content)})}return e}export{fi as OpenAIClient,hi as OpenAICompatClient,Lu as buildChatCompletionMessages,Nu as buildOpenAIInput};
|
|
34
|
+
`)){let k=I.indexOf(":");k>=0&&(A[I.substring(0,k).trim()]=I.substring(k+1).trim())}d.defaultHeaders=h([A,d.defaultHeaders])}this._options=d,this._provider=m,p&&(this._workloadIdentityAuth=new Es(p,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=a,this.project=l,this.webhookSecret=f}withOptions(e){let t=this._options.provider,r=e.provider??t,n={...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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return r&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,r!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return h([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return h([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return h([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return h([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return bo(e)}getUserAgent(){return`${this.constructor.name}/JS ${ke}`}defaultIdempotencyKey(){return`stainless-node-retry-${We()}`}makeStatusError(e,t,r,n){return F.generate(e,t,r,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof g?r:new g(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new g(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!c(this,Jn,"m",di).call(this)&&r||this.baseURL,o=eo(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!nn(a)||!nn(l))&&(t={...l,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Xe(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:a,url:l,timeout:f}=await this.buildRequest(n,{retryCount:o-t}),p=n.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:l,options:n}),await this._provider?.prepareRequest?.(a,{url:l,options:n});let _="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(K(this).debug(`[${_}] sending request`,ye({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:a.headers})),n.signal?.aborted)throw new M;let b=n.__security??{bearerAuth:!0},w=new AbortController,A=await this.fetchWithAuth(l,a,f,w,b).catch(Wr),I=Date.now();if(A instanceof globalThis.Error){let P=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new M;let R=Hr(A)||/timed? ?out/i.test(String(A)+("cause"in A?String(A.cause):""));if(t&&!p)return K(this).info(`[${_}] connection ${R?"timed out":"failed"} - ${P}`),K(this).debug(`[${_}] connection ${R?"timed out":"failed"} (${P})`,ye({retryOfRequestLogID:r,url:l,durationMs:I-d,message:A.message})),this.retryRequest(n,t,r??_);let v=p?"error; streaming body cannot be retried":"error; no more retries left";throw K(this).info(`[${_}] connection ${R?"timed out":"failed"} - ${v}`),K(this).debug(`[${_}] connection ${R?"timed out":"failed"} (${v})`,ye({retryOfRequestLogID:r,url:l,durationMs:I-d,message:A.message})),A instanceof Je||A instanceof Jr?A:R?new Ce:new Se({message:$u(A),cause:A})}let k=[...A.headers.entries()].filter(([P])=>P==="x-request-id").map(([P,R])=>", "+P+": "+JSON.stringify(R)).join(""),y=`[${_}${m}${k}] ${a.method} ${l} ${A.ok?"succeeded":"failed"} with status ${A.status} in ${I-d}ms`;if(!A.ok){if(A.status===401&&this._workloadIdentityAuth&&b.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await an(A.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??_);let P=await this.shouldRetry(A);if(t&&P&&!p){let N=`retrying, ${t} attempts remaining`;return await an(A.body),K(this).info(`${y} - ${N}`),K(this).debug(`[${_}] response error (${N})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:I-d})),this.retryRequest(n,t,r??_,A.headers)}let R=P?p?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";K(this).info(`${y} - ${R}`);let v=await A.text().catch(N=>Wr(N).message),$=so(v),L=$?void 0:v;throw K(this).debug(`[${_}] response error (${R})`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,message:L,durationMs:Date.now()-d})),this.makeStatusError(A.status,$,L,A.headers)}return K(this).info(y),K(this).debug(`[${_}] response start`,ye({retryOfRequestLogID:r,url:A.url,status:A.status,headers:A.headers,durationMs:I-d})),{response:A,options:n,controller:w,requestLogID:_,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Zr(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let l=t.headers,f=l.get("Authorization");if(!f||f===`Bearer ${ku}`){let p=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${p}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:a,...l}=t||{},f=this._makeAbort(n);o&&o.addEventListener("abort",f,{once:!0});let p=setTimeout(f,r),_=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,m={signal:n.signal,..._?{duplex:"half"}:{},method:"GET",...l};a&&(m.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(p)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,n){let o,a=n?.get("retry-after-ms");if(a){let f=parseFloat(a);Number.isNaN(f)||(o=f)}let l=n?.get("retry-after");if(l&&!o){let f=parseFloat(l);Number.isNaN(f)?o=Date.parse(l)-Date.now():o=f*1e3}if(o===void 0){let f=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,f)}return await de(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return a*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:a,defaultBaseURL:l}=r,f=this.buildURL(o,a,l);"timeout"in r&&ro("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:_,isStreamingBody:m}=this.buildBody({options:r});m&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let d=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=h([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...uo(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...c(this,_s,"f").call(this,{body:t,headers:h([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=h([r]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,a=!o&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Xr(t),isStreamingBody:!0}:typeof t=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...c(this,_s,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};Vn=S,_s=new WeakMap,Jn=new WeakSet,di=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};S.OpenAI=Vn;S.DEFAULT_TIMEOUT=6e5;S.OpenAIError=g;S.APIError=F;S.APIConnectionError=Se;S.APIConnectionTimeoutError=Ce;S.APIUserAbortError=M;S.NotFoundError=kt;S.ConflictError=$t;S.RateLimitError=Ot;S.BadRequestError=Rt;S.AuthenticationError=St;S.InternalServerError=vt;S.PermissionDeniedError=Ct;S.UnprocessableEntityError=Et;S.InvalidWebhookSignatureError=pe;S.toFile=js;S.toStreamingFile=vs;S.Completions=ut;S.Chat=ve;S.Embeddings=lt;S.Files=dt;S.Images=_t;S.Audio=he;S.Moderations=gt;S.Models=yt;S.FineTuning=le;S.Graders=De;S.VectorStores=Re;S.Webhooks=wt;S.Beta=oe;S.Batches=st;S.Uploads=qe;S.Admin=je;S.Responses=_e;S.Realtime=Pe;S.Conversations=Be;S.Evals=Ue;S.Containers=Ke;S.Skills=xe;S.Videos=It;function $u(s){if(Eu(s))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function Eu(s){let e=s;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var Qs=Xn({module:"llm"});var fi=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=rn(e);if(!r)throw new Is("OpenAI API key not found, set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=tn(e)}async*stream(e,t,r){let n=Nu(Zs(e.getMessages())),o=[];o.push({role:"system",content:this.systemPrompt});for(let d of n)o.push(d);let a=t.map(d=>{let b=d.input_schema;return{type:"function",name:d.name,description:d.description,parameters:b,strict:!1}}),l={model:this.model,input:o,stream:!0,max_output_tokens:this.maxOutputTokens,...a.length>0?{tools:a}:{}},f=0,p=0,_=0,m=0;try{let d=await this.client.responses.create(l,{...r?{signal:r}:{}}),b="",w="",A="",I="",k="";for await(let y of d)if(y.type==="response.output_text.delta")yield{type:"text_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.delta")k+=y.delta,yield{type:"thinking_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.done")yield{type:"thinking_complete",thinking:k,signature:I};else if(y.type==="response.function_call_arguments.delta")A+=y.delta,yield{type:"tool_call_delta",text:y.delta};else if(y.type==="response.output_item.added")y.item.type==="function_call"?(b=y.item.name,w=y.item.call_id,A="",yield{type:"tool_call_start",toolName:b,toolId:w}):y.item.type==="reasoning"&&(I=y.item.id??"",k="");else if(y.type==="response.output_item.done"){if(y.item.type==="function_call"&&b){let P={};if(A)try{let R=JSON.parse(A);P=As(R)?bs(R):{[qr]:A}}catch(R){Qs.error({err:R},"llm operation failed"),P={[qr]:A}}yield{type:"tool_call_complete",toolId:w,toolName:b,arguments:P},b="",w="",A=""}}else if(y.type==="response.completed"){let P=y.response.usage;P&&(p=P.output_tokens,_=P.input_tokens_details.cached_tokens,f=Math.max(0,P.input_tokens-_));let R="end_turn",v=y.response;v.status==="incomplete"&&v.incomplete_details?.reason==="max_output_tokens"&&(R="max_tokens"),yield{type:"stream_end",stopReason:R,usage:{inputTokens:f,outputTokens:p,cacheReadInputTokens:_,cacheCreationInputTokens:m}}}}catch(d){throw Qs.error({err:d},"llm operation failed"),mi(d)}}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}};function Ys(s){if(s.type!=="image")return null;let e=s.source;if(!As(e)||e.type!=="base64")return null;let t=xt(e,"media_type"),r=xt(e,"data");return!t||!r?null:`data:${t};base64,${r}`}function Ou(s){let{toolUseId:e,content:t}=s;if(typeof t=="string")return[];let r=[];for(let n of t){let o=Ys(n);o&&r.push({type:"input_image",image_url:o,detail:"auto"})}return r.length===0?[]:[{type:"input_text",text:`[Image(s) returned by tool call ${e}]`},...r]}function vu(s){let{toolUseId:e,content:t}=s;if(typeof t=="string")return[];let r=[];for(let n of t){let o=Ys(n);o&&r.push({type:"image_url",image_url:{url:o}})}return r.length===0?[]:[{type:"text",text:`[Image(s) returned by tool call ${e}]`},...r]}function Tu(s){if(typeof s=="string")return s;let e=[];for(let t of s)if(t.type==="text")e.push({type:"input_text",text:xt(t,"text")});else{let r=Ys(t);r&&e.push({type:"input_image",image_url:r,detail:"auto"})}return e}function ju(s){if(typeof s=="string")return s;let e=[];for(let t of s)if(t.type==="text")e.push({type:"text",text:xt(t,"text")});else{let r=Ys(t);r&&e.push({type:"image_url",image_url:{url:r}})}return e}function Nu(s){let e=[];for(let t of s){if(t.thinkingBlocks)for(let r of t.thinkingBlocks)e.push({type:"reasoning",id:r.signature,summary:[{type:"summary_text",text:r.thinking}]});if(t.toolUses&&t.toolUses.length>0){let r=typeof t.content=="string"?t.content:He(t.content);r&&e.push({role:"assistant",content:r});for(let n of t.toolUses)e.push({type:"function_call",name:n.toolName,call_id:n.toolUseId,arguments:JSON.stringify(n.arguments)})}else if(t.toolResults&&t.toolResults.length>0){let r=[];for(let n of t.toolResults)e.push({type:"function_call_output",call_id:n.toolUseId,output:He(n.content)}),r.push(...Ou(n));r.length>0&&e.push({role:"user",content:r})}else t.role==="assistant"?e.push({role:"assistant",content:typeof t.content=="string"?t.content:He(t.content)}):e.push({role:t.role,content:Tu(t.content)})}return e}function Fu(s){return/context_length_exceeded/i.test(s)||/maximum\scontext\slength/i.test(s)||/prompts?\s+too\s+long/i.test(s)}var hi=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=rn(e);if(!r)throw new Is("OpenAI API key not found. Set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=tn(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,r){let n=[{role:"system",content:this.systemPrompt},...Lu(Zs(e.getMessages()))],o=t.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.input_schema,strict:!1}})),a={model:this.model,messages:n,stream:!0,stream_options:{include_usage:!0},max_tokens:this.maxOutputTokens,...o.length>0?{tools:o}:{}},l=0,f=0,p=0,_=0;try{let m=await this.client.chat.completions.create(a,{...r?{signal:r}:{}}),d=new Map,b=null,w="";for await(let I of m){if(I.usage&&(f=I.usage.completion_tokens??0,p=I.usage.prompt_tokens_details?.cached_tokens??0,l=Math.max(0,(I.usage.prompt_tokens??0)-p)),I.choices.length===0)continue;let k=I.choices[0].delta;k.content&&(yield{type:"text_delta",text:k.content});let y=xt(bs(k),"reasoning_content");if(y&&(w+=y,yield{type:"thinking_delta",text:y}),k.tool_calls)for(let P of k.tool_calls){d.has(P.index)||(d.set(P.index,{id:P.id??"",name:P.function?.name??"",args:""}),P.id&&(yield{type:"tool_call_start",toolName:P.function?.name??"",toolId:P.id??""}));let R=d.get(P.index);R&&(P.id&&(R.id=P.id),P.function?.name&&(R.name=P.function.name),P.function?.arguments&&(R.args+=P.function.arguments,yield{type:"tool_call_delta",text:P.function.arguments}))}if(I.choices[0].finish_reason){b=I.choices[0].finish_reason,w&&(yield{type:"thinking_complete",thinking:w,signature:""},w="");for(let P of d.values()){let R={},v=P.args;if(v){try{let $=JSON.parse(v);R=As($)?bs($):{[qr]:v}}catch($){Qs.error({err:$},"llm operation failed"),R={[qr]:v}}yield{type:"tool_call_complete",toolName:P.name,toolId:P.id,arguments:R}}}}}let A;b==="length"?A="max_tokens":b==="tool_calls"||d.size>0?A="tool_use":A="end_turn",yield{type:"stream_end",stopReason:A,usage:{inputTokens:l,outputTokens:f,cacheReadInputTokens:p,cacheCreationInputTokens:_}}}catch(m){throw Qs.error({err:m},"llm operation failed"),mi(m)}}};function mi(s){return s instanceof S.APIError?s.status===413||s.status===400&&Fu(s.message)?new Zn(`Context Too Long: ${s.message}`):s.status===401?new Is(`Invalid API key: ${s.message}`):s.status===429?new Qn("Rate limit error, please wait."):new Gn(`OpenAI API error (${en(s.status)}): ${s.message}`):new Yn(`Network error: ${s instanceof Error?s.message:en(s)}`)}function Lu(s){let e=[];for(let t of s){let r=t.thinkingBlocks?.map(o=>o.thinking).join("")??"",n=typeof t.content=="string"?t.content:He(t.content);if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:n||null,tool_calls:t.toolUses.map(o=>({id:o.toolUseId,type:"function",function:{name:o.toolName,arguments:JSON.stringify(o.arguments)},...r?{reasoning_content:r}:{}}))});else if(t.toolResults&&t.toolResults.length>0){let o=[];for(let a of t.toolResults)e.push({role:"tool",tool_call_id:a.toolUseId,content:He(a.content)}),o.push(...vu(a));o.length>0&&e.push({role:"user",content:o})}else t.role==="assistant"?e.push({role:"assistant",content:n,...r?{reasoning_content:r}:{}}):t.role==="system"?e.push({role:"system",content:typeof t.content=="string"?t.content:He(t.content)}):e.push({role:"user",content:ju(t.content)})}return e}export{fi as OpenAIClient,hi as OpenAICompatClient,Lu as buildChatCompletionMessages,Nu as buildOpenAIInput};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{$ as ki,A as pe,B as le,C as ue,D as me,E as ui,I as de,J as mi,K as di,L as xe,O as pt,Q as xi,R as vi,S as fi,U as bi,W as gi,X as hi,Y as yi,Z as wi,_ as Xe,a as He,aa as ji,b as $e,ba as qi,c as Ge,ca as Ei,da as Si,ea as Ci,fa as Ti,ga as zi,h as ai,ha as _i,ia as Pi,j as ii,ja as Ai,ka as Ri,l as ni,la as Oi,m as si,ma as Li,n as oi,na as Mi,o as ti,p as Be,q as ri,r as ci,s as pi,y as li}from"./chunk-
|
|
4
|
+
import{$ as ki,A as pe,B as le,C as ue,D as me,E as ui,I as de,J as mi,K as di,L as xe,O as pt,Q as xi,R as vi,S as fi,U as bi,W as gi,X as hi,Y as yi,Z as wi,_ as Xe,a as He,aa as ji,b as $e,ba as qi,c as Ge,ca as Ei,da as Si,ea as Ci,fa as Ti,ga as zi,h as ai,ha as _i,ia as Pi,j as ii,ja as Ai,ka as Ri,l as ni,la as Oi,m as si,ma as Li,n as oi,na as Mi,o as ti,p as Be,q as ri,r as ci,s as pi,y as li}from"./chunk-ADGTJUJZ.js";import{a as Ne,b as $a}from"./chunk-XBHVVB5A.js";import{a as Qa,b as ei,h as J}from"./chunk-RNUCVDX2.js";import{a as M,d as Ba,e as Xa,f as te,g as Ie,h as Wa,i as Za,j as re,n as Ya}from"./chunk-GQ2COSTQ.js";import{e as Ja,f as Ka,g as Va}from"./chunk-MSJOPX6X.js";import"./chunk-FZPTNGTU.js";import{e as K}from"./chunk-R7VREEYH.js";import"./chunk-7MHXMDYC.js";import{D as E,I as Ga,K as L,S as De}from"./chunk-M5AOLYFS.js";import{a as ce}from"./chunk-UBV5T4TV.js";import{a as x,b as l,d as ct}from"./chunk-X3UA5OZL.js";var Ui=l((Pl,Fi)=>{"use strict";Fi.exports=lt;function lt(e,a){if(!Array.isArray(e))throw new TypeError("arg must be an array of [ee, events...] arrays");for(var i=[],n=0;n<e.length;n++){var s=e[n];if(!Array.isArray(s)||s.length<2)throw new TypeError("each array member must be [ee, events...]");for(var o=s[0],t=1;t<s.length;t++){var r=s[t],c=ut(r,p);o.on(r,c),i.push({ee:o,event:r,fn:c})}}function p(){m(),a.apply(null,arguments)}function m(){for(var d,f=0;f<i.length;f++)d=i[f],d.ee.removeListener(d.event,d.fn)}function u(d){a=d}return u.cancel=m,u}function ut(e,a){return function(n){for(var s=new Array(arguments.length),o=this,t=e==="error"?n:null,r=0;r<s.length;r++)s[r]=arguments[r];a(t,o,e,s)}}});var Ze=l((Al,We)=>{"use strict";We.exports=dt;We.exports.isFinished=Ii;var Ni=gt(),Di=Ui(),mt=typeof setImmediate=="function"?setImmediate:function(e){process.nextTick(e.bind.apply(e,arguments))};function dt(e,a){return Ii(e)!==!1?(mt(a,null,e),e):(vt(e,ht(a)),e)}function Ii(e){var a=e.socket;if(typeof e.finished=="boolean")return!!(e.finished||a&&!a.writable);if(typeof e.complete=="boolean")return!!(e.upgrade||!a||!a.readable||e.complete&&!e.readable)}function xt(e,a){var i,n,s=!1;function o(r){i.cancel(),n.cancel(),s=!0,a(r)}i=n=Di([[e,"end","finish"]],o);function t(r){e.removeListener("socket",t),!s&&i===n&&(n=Di([[r,"error","close"]],o))}if(e.socket){t(e.socket);return}e.on("socket",t),e.socket===void 0&&bt(e,t)}function vt(e,a){var i=e.__onFinished;(!i||!i.queue)&&(i=e.__onFinished=ft(e),xt(e,i)),i.queue.push(a)}function ft(e){function a(i){if(e.__onFinished===a&&(e.__onFinished=null),!!a.queue){var n=a.queue;a.queue=null;for(var s=0;s<n.length;s++)n[s](i,e)}}return a.queue=[],a}function bt(e,a){var i=e.assignSocket;typeof i=="function"&&(e.assignSocket=function(s){i.call(this,s),a(s)})}function gt(){try{return x("async_hooks")}catch{return{}}}function ht(e){var a;return Ni.AsyncResource&&(a=new Ni.AsyncResource(e.name||"bound-anonymous-fn")),!a||!a.runInAsyncScope?e:a.runInAsyncScope.bind(a,e,null)}});var $i=l((Rl,Hi)=>{"use strict";Hi.exports=yt;function yt(e){if(!Array.isArray(e))throw new TypeError("Middleware stack must be an array!");for(let a of e)if(typeof a!="function")throw new TypeError("Middleware must be composed of functions!");return function(a,i){let n=-1;return s(0);function s(o){if(o<=n)return Promise.reject(new Error("next() called multiple times"));n=o;let t=e[o];if(o===e.length&&(t=i),!t)return Promise.resolve();try{return Promise.resolve(t(a,s.bind(null,o+1)))}catch(r){return Promise.reject(r)}}}}});var Gi=l((Ol,wt)=>{wt.exports={"100":"Continue","101":"Switching Protocols","102":"Processing","103":"Early Hints","200":"OK","201":"Created","202":"Accepted","203":"Non-Authoritative Information","204":"No Content","205":"Reset Content","206":"Partial Content","207":"Multi-Status","208":"Already Reported","226":"IM Used","300":"Multiple Choices","301":"Moved Permanently","302":"Found","303":"See Other","304":"Not Modified","305":"Use Proxy","307":"Temporary Redirect","308":"Permanent Redirect","400":"Bad Request","401":"Unauthorized","402":"Payment Required","403":"Forbidden","404":"Not Found","405":"Method Not Allowed","406":"Not Acceptable","407":"Proxy Authentication Required","408":"Request Timeout","409":"Conflict","410":"Gone","411":"Length Required","412":"Precondition Failed","413":"Payload Too Large","414":"URI Too Long","415":"Unsupported Media Type","416":"Range Not Satisfiable","417":"Expectation Failed","418":"I'm a Teapot","421":"Misdirected Request","422":"Unprocessable Entity","423":"Locked","424":"Failed Dependency","425":"Too Early","426":"Upgrade Required","428":"Precondition Required","429":"Too Many Requests","431":"Request Header Fields Too Large","451":"Unavailable For Legal Reasons","500":"Internal Server Error","501":"Not Implemented","502":"Bad Gateway","503":"Service Unavailable","504":"Gateway Timeout","505":"HTTP Version Not Supported","506":"Variant Also Negotiates","507":"Insufficient Storage","508":"Loop Detected","509":"Bandwidth Limit Exceeded","510":"Not Extended","511":"Network Authentication Required"}});var V=l((Ll,Xi)=>{"use strict";var Ye=Gi();Xi.exports=_;_.message=Ye;_.code=kt(Ye);_.codes=jt(Ye);_.redirect={300:!0,301:!0,302:!0,303:!0,305:!0,307:!0,308:!0};_.empty={204:!0,205:!0,304:!0};_.retry={502:!0,503:!0,504:!0};function kt(e){var a={};return Object.keys(e).forEach(function(n){var s=e[n],o=Number(n);a[s.toLowerCase()]=o}),a}function jt(e){return Object.keys(e).map(function(i){return Number(i)})}function qt(e){var a=e.toLowerCase();if(!Object.prototype.hasOwnProperty.call(_.code,a))throw new Error('invalid status message: "'+e+'"');return _.code[a]}function Bi(e){if(!Object.prototype.hasOwnProperty.call(_.message,e))throw new Error("invalid status code: "+e);return _.message[e]}function _(e){if(typeof e=="number")return Bi(e);if(typeof e!="string")throw new TypeError("code must be a number or string");var a=parseInt(e,10);return isNaN(a)?qt(e):Bi(a)}});var Ke=l((Ml,Ji)=>{"use strict";var Et=x("path").relative;Ji.exports=_t;var St=process.cwd();function Zi(e,a){for(var i=e.split(/[ ,]+/),n=String(a).toLowerCase(),s=0;s<i.length;s++){var o=i[s];if(o&&(o==="*"||o.toLowerCase()===n))return!0}return!1}function Ct(e,a,i){var n=Object.getOwnPropertyDescriptor(e,a),s=n.value;return n.get=function(){return s},n.writable&&(n.set=function(t){return s=t}),delete n.value,delete n.writable,Object.defineProperty(e,a,n),n}function Tt(e){for(var a="",i=0;i<e;i++)a+=", arg"+i;return a.substr(2)}function zt(e){var a=this.name+": "+this.namespace;this.message&&(a+=" deprecated "+this.message);for(var i=0;i<e.length;i++)a+=`
|
|
5
5
|
at `+e[i].toString();return a}function _t(e){if(!e)throw new TypeError("argument namespace is required");var a=fe(),i=$(a[1]),n=i[0];function s(o){ve.call(s,o)}return s._file=n,s._ignored=At(e),s._namespace=e,s._traced=Rt(e),s._warned=Object.create(null),s.function=Ft,s.property=Ut,s}function Pt(e,a){var i=typeof e.listenerCount!="function"?e.listeners(a).length:e.listenerCount(a);return i>0}function At(e){if(process.noDeprecation)return!0;var a=process.env.NO_DEPRECATION||"";return Zi(a,e)}function Rt(e){if(process.traceDeprecation)return!0;var a=process.env.TRACE_DEPRECATION||"";return Zi(a,e)}function ve(e,a){var i=Pt(process,"deprecation");if(!(!i&&this._ignored)){var n,s,o,t,r=0,c=!1,p=fe(),m=this._file;for(a?(t=a,o=$(p[1]),o.name=t.name,m=o[0]):(r=2,t=$(p[r]),o=t);r<p.length;r++)if(n=$(p[r]),s=n[0],s===m)c=!0;else if(s===this._file)m=this._file;else if(c)break;var u=n?t.join(":")+"__"+n.join(":"):void 0;if(!(u!==void 0&&u in this._warned)){this._warned[u]=!0;var d=e;if(d||(d=o===t||!o.name?Wi(t):Wi(o)),i){var f=Yi(this._namespace,d,p.slice(r));process.emit("deprecation",f);return}var h=process.stderr.isTTY?Lt:Ot,P=h.call(this,d,n,p.slice(r));process.stderr.write(P+`
|
|
6
6
|
`,"utf8")}}}function $(e){var a=e.getFileName()||"<anonymous>",i=e.getLineNumber(),n=e.getColumnNumber();e.isEval()&&(a=e.getEvalOrigin()+", "+a);var s=[a,i,n];return s.callSite=e,s.name=e.getFunctionName(),s}function Wi(e){var a=e.callSite,i=e.name;i||(i="<anonymous@"+Je(e)+">");var n=a.getThis(),s=n&&a.getTypeName();return s==="Object"&&(s=void 0),s==="Function"&&(s=n.name||s),s&&a.getMethodName()?s+"."+i:i}function Ot(e,a,i){var n=new Date().toUTCString(),s=n+" "+this._namespace+" deprecated "+e;if(this._traced){for(var o=0;o<i.length;o++)s+=`
|
|
7
7
|
at `+i[o].toString();return s}return a&&(s+=" at "+Je(a)),s}function Lt(e,a,i){var n="\x1B[36;1m"+this._namespace+"\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m"+e+"\x1B[39m";if(this._traced){for(var s=0;s<i.length;s++)n+=`
|
|
@@ -21,7 +21,7 @@ ${n.replace(/^/gm," ")}
|
|
|
21
21
|
`)}static get default(){return Ho}};function al(e){if(e.respond===!1)return;let a=e.res;if(!e.writable)return a.end();let i=e.body,n=e.status;if(Zp.empty[n])return e.body=null,a.end();if(e.method==="HEAD"){if(!a.headersSent&&!e.response.has("Content-Length")){let{length:o}=e.response;Number.isInteger(o)&&(e.length=o)}return a.end()}if(i==null)return e.response._explicitNullBody?(e.response.remove("Content-Type"),e.response.remove("Transfer-Encoding"),e.length=0,a.end()):(e.req.httpVersionMajor>=2?i=String(n):i=e.message||String(n),a.headersSent||(e.type="text",e.length=Buffer.byteLength(i)),a.end(i));if(Buffer.isBuffer(i)||typeof i=="string")return a.end(i);let s=null;if(i instanceof Blob?s=Oe.Readable.from(i.stream()):i instanceof ReadableStream?s=Oe.Readable.from(i):i instanceof Response?s=Oe.Readable.from(i?.body||""):Qp(i)&&(s=i),s)return Oe.pipeline(s,a,o=>{o&&e.app.listenerCount("error")&&e.onerror(o)});i=JSON.stringify(i),a.headersSent||(e.length=Buffer.byteLength(i)),a.end(i)}_a.exports.HttpError=Yp});import{readFileSync as gl,existsSync as hl,statSync as yl}from"fs";import{createServer as wl}from"http";import{join as at,extname as kl,normalize as jl}from"path";import{cwd as ie}from"process";var Pa=ct($o(),1),Go=Pa.default,_u=Pa.default.HttpError;import{existsSync as Aa,statSync as Zo,readFileSync as Bo,writeFileSync as Yo,mkdirSync as il,unlinkSync as nl,utimesSync as sl}from"fs";import{homedir as Xo}from"os";import{join as ae,basename as Wo}from"path";var ol=24,tl=5,rl=600*1e3,cl=".consolidate-lock",pl=3600*1e3,ll=200,Me=class{client;workDir;lastScanAt=0;minHours;minSessions;appendSystem;constructor(a,i,n){this.client=a,this.workDir=i,this.minHours=n?.minHours??ol,this.minSessions=n?.minSessions??tl,this.appendSystem=n?.appendSystem}maybeRun(){let a=ae(this.workDir,".swifty","memory");if(!Aa(a))return Promise.resolve();let i=ul(a);if((Date.now()-i)/36e5<this.minHours)return Promise.resolve();let s=Date.now();if(s-this.lastScanAt<rl)return Promise.resolve();this.lastScanAt=s;let o=vl(this.workDir,i);if(o.length<this.minSessions)return Promise.resolve();let t=ml(a);return t===null||this.run(a,o,t).catch(()=>{dl(a,t)}),Promise.resolve()}async run(a,i,n){let s=ae(Xo(),".swifty","memory"),o=ae(this.workDir,".swifty","sessions"),t=fl(a,s,o,i),r=new ce;r.register(new de),r.register(new xe),r.register(new me),r.register(new pe),r.register(new le),r.register(new ue);let c=new K(this.workDir,"bypassPermissions");c.allowExtraRoot(ae(Xo(),".swifty","memory"));let p=new M;p.addUserMessage(t);let m=new J({client:this.client,registry:r,checker:c,conversation:p,workDir:this.workDir,maxIterations:15});for await(let f of m.run())console.log(f.type);let d=bl(p.getMessages()).filter(f=>Wo(f)!=="MEMORY.md");if(d.length>0&&this.appendSystem){let f=d.map(h=>Wo(h));this.appendSystem(`Memory improved: ${f.join(", ")}`)}}};function Ra(e){return ae(e,cl)}function ul(e){let a=Ra(e);if(!Aa(a))return 0;try{return Zo(a).mtimeMs}catch{return 0}}function ml(e){let a=Ra(e),i,n;if(Aa(a))try{i=Zo(a).mtimeMs;let s=Bo(a,"utf-8").trim(),o=parseInt(s,10);Number.isFinite(o)&&(n=o)}catch(s){console.error(s)}if(i!==void 0&&Date.now()-i<pl&&n!==void 0&&xl(n))return null;il(e,{recursive:!0}),Yo(a,String(process.pid));try{let s=Bo(a,"utf-8").trim();if(parseInt(s,10)!==process.pid)return null}catch{return null}return i??0}function dl(e,a){let i=Ra(e);try{if(a===0){nl(i);return}Yo(i,"");let n=a/1e3;sl(i,n,n)}catch(n){console.error(n)}}function xl(e){try{return process.kill(e,0),!0}catch{return!1}}function vl(e,a){let i=re(e),n=new Date(a);return i.filter(s=>s.modTime>n).map(s=>s.id)}function fl(e,a,i,n){let s=["# Dream: Memory Consolidation","","You are performing a dream \u2014 a reflective pass over your memory files. Synthesize what you've learned recently into durable, well-organized memories so that future sessions can orient quickly.","",`Project memory directory: \`${e}\``,`User memory directory: \`${a}\``,"The memory directory already exists \u2014 write to it directly.","",`Session transcripts: \`${i}\` (large JSONL files \u2014 grep narrowly, don't read whole files)`,"","---","","## Phase 1 \u2014 Orient","","- `ls` the memory directory to see what already exists","- Read `MEMORY.md` to understand the current index","- Skim existing topic files so you improve them rather than creating duplicates","","## Phase 2 \u2014 Gather recent signal","","Look for new information worth persisting:","","1. **Existing memories that drifted** \u2014 facts that contradict something you see in the codebase now","2. **Transcript search** \u2014 if you need specific context, grep the JSONL transcripts for narrow terms","","Don't exhaustively read transcripts. Look only for things you already suspect matter.","","## Phase 3 \u2014 Consolidate","","For each thing worth remembering, write or update a memory file. Each memory file uses YAML frontmatter with name, description, and metadata.type fields, followed by a Markdown body.","","Focus on:","- Merging new signal into existing topic files rather than creating near-duplicates",'- Converting relative dates ("yesterday", "last week") to absolute dates so they remain interpretable after time passes',"- Deleting contradicted facts \u2014 if today's investigation disproves an old memory, fix it at the source","","## Phase 4 \u2014 Prune and index","",`Update \`MEMORY.md\` so it stays under ${String(ll)} lines AND under ~25KB. It's an **index**, not a dump \u2014 each entry should be one line under ~150 characters: \`- [Title](file.md) \u2014 one-line hook\`. Never write memory content directly into it.`,"","- Remove pointers to memories that are now stale, wrong, or superseded","- Demote verbose entries: if an index line is over ~200 chars, it's carrying content that belongs in the topic file \u2014 shorten the line, move the detail","- Add pointers to newly important memories","- Resolve contradictions \u2014 if two files disagree, fix the wrong one","","---","","**Tool constraints for this run:** Bash is restricted to read-only commands (`ls`, `find`, `grep`, `cat`, `stat`, `wc`, `head`, `tail`, and similar). Anything that writes, redirects to a file, or modifies state will be denied.",""];if(n.length>0){s.push(`Sessions since last consolidation (${String(n.length)}):`);for(let o of n)s.push(`- ${o}`)}return s.push("","Return a brief summary of what you consolidated, updated, or pruned. If nothing changed (memories are already tight), say so."),s.join(`
|
|
22
22
|
`)}function bl(e){let a=[],i=new Set;for(let n of e){if(n.role!=="assistant"||typeof n.content!="string")continue;let s=n.content.matchAll(/"file_path"\s*:\s*"([^"]+)"/g);for(let o of s)o[1]&&!i.has(o[1])&&(i.add(o[1]),a.push(o[1]))}return a}var C=Ga({module:"remote"}),ql=E.object({type:E.string(),data:E.unknown()}),El=E.object({content:E.string()}),Sl=E.object({id:E.string(),response:E.enum(["allow","deny","allowAlways"])}),Cl=E.object({id:E.string(),answers:E.record(E.string(),E.string())}),Jo=at(import.meta.dirname,"fe","dist"),Tl={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".png":"image/png",".svg":"image/svg+xml",".ico":"image/x-icon",".json":"application/json; charset=utf-8",".woff2":"font/woff2"};function Ko(e){let a=jl(e).replace(/^(\.\.[/\\])+/,""),i=at(Jo,a);if(!i.startsWith(Jo)||!hl(i)||!yl(i).isFile())return null;let n=gl(i),s=Tl[kl(i)]??"application/octet-stream";return{body:n,mime:s}}var Oa=class{client;conv;registry;sessionId;fileHistory;fileStateCache;cmdRegistry;skillCatalog;activeSkills;toolFilter;mcpManager;hookEngine;recoveryState;teamManager;enableCoordinatorMode;forkDisabled;memoryManager;contextWindow;ltmInstructions;ltmMemoryContent;mcpInstructions;provider;workDir;abortController=null;constructor(a){this.client=a.client,this.conv=a.conv,this.registry=a.registry,this.sessionId=a.sessionId,this.fileHistory=a.fileHistory,this.fileStateCache=a.fileStateCache,this.cmdRegistry=a.cmdRegistry,this.skillCatalog=a.skillCatalog,this.activeSkills=a.activeSkills,this.toolFilter=a.toolFilter,this.mcpManager=a.mcpManager,this.hookEngine=a.hookEngine,this.recoveryState=a.recoveryState,this.teamManager=a.teamManager,this.enableCoordinatorMode=a.enableCoordinatorMode,this.forkDisabled=a.forkDisabled,this.memoryManager=a.memoryManager,this.contextWindow=a.contextWindow,this.ltmInstructions=a.ltmInstructions,this.ltmMemoryContent=a.ltmMemoryContent,this.mcpInstructions=a.mcpInstructions,this.provider=a.provider,this.workDir=a.workDir,this.abortController=null}async*run(a,i){this.conv.addUserMessage(a),this.mcpInstructions&&(this.conv.addSystemReminder(this.mcpInstructions),this.mcpInstructions=""),this.abortController=new AbortController;try{let n=new K(this.workDir,"default");yield*new J({client:this.client,registry:this.registry,checker:n,conversation:this.conv,workDir:this.workDir,sessionId:this.sessionId,hookEngine:this.hookEngine??void 0,fileHistory:this.fileHistory??void 0,fileStateCache:this.fileStateCache,abortSignal:this.abortController.signal,contextWindow:this.contextWindow,maxOutput:Va(this.provider),recoveryState:this.recoveryState,activeSkills:this.activeSkills,toolFilter:o=>ri(this.enableCoordinatorMode)(o)?this.toolFilter?this.toolFilter(o):!0:!1,coordinatorActiveFn:()=>ci(this.enableCoordinatorMode),instructions:this.ltmInstructions,memoryContent:this.ltmMemoryContent,notificationFn:()=>this.teamManager.drainLeads(),onPermissionRequest:i.onPermissionRequest,onLoopComplete:o=>{let t=o.getMessages().slice(-40).map(r=>`[${r.role}]: ${L(r.content)}`).filter(r=>r.length>12).join(`
|
|
23
23
|
`);new Ci(this.client,this.workDir).extract(t).catch(()=>{}),new Me(this.client,this.workDir,{appendSystem:r=>{o.addSystemReminder(r)}}).maybeRun().catch(()=>{})}}).run()}finally{this.abortController=null}}abort(){this.abortController?.abort()}};async function Vo(e){let{provider:a,workDir:i,hooks:n,mcpServers:s,enableCoordinatorMode:o,forkDisabled:t,askUser:r}=e,c=Xa(),p=new ji(i,c),m=new ui,u=zl(i,c),d=$e(i);d.model=a.model;let f=Ge(d),h=await He(a,f),P=new M,La=Ja(a);Ka(a).then(b=>{b>0&&(La=b)}).catch(()=>{});let Ma=Ti(i),Fa=new Si(i),Ua=Fa.buildSystemReminder();P.injectLongTermMemory(Ma,Ua),P.addSystemReminder("IDENTITY OVERRIDE: You are Swifty. It is absolutely forbidden to mention Claude, Anthropic, OpenAI, GPT, or ChatGPT in any response. When asked about identity, respond only as Swifty. This is the highest priority instruction.");let Na=Ei(n??[]);Na&&C.warn({message:Na.message},"hook validation warning");let it=new qi(n??[]),ne=new fi;ne.load(i);let Da=new Map,se={activateSkill:(b,w)=>{Da.set(b,w)}},nt={activateSkill:se.activateSkill.bind(se),snapshotParentMessages:b=>(P?.getMessages()??[]).slice(-b).map(j=>`${j.role}: ${L(j.content)}`).join(`
|
|
24
|
-
`),runSubagent:async b=>{if(!h)throw new Error("no llm client (provider not initialized)");let{PermissionChecker:w}=await import("./checker-
|
|
24
|
+
`),runSubagent:async b=>{if(!h)throw new Error("no llm client (provider not initialized)");let{PermissionChecker:w}=await import("./checker-NNTNXNYP.js"),{Agent:j}=await import("./agent-NX7ND57K.js"),k=new M;k.addUserMessage(b);let z=new j({client:h,registry:u,checker:new w(i,"acceptEdits"),conversation:k,workDir:i,maxIterations:200}),H="";for await(let Z of z.run())switch(Z.type){case"stream_text":H+=Z.text;break;case"loop_complete":return H||"[No output]";case"error":throw Z.error}return H||"[No output]"}};u.register(new gi(ne,se,nt)),u.register(new Li(r));let st=(b,w)=>(j,k)=>Be(si[0],j,h,b,a,i,void 0,k,void 0,w),I=new li(i);u.register(new ai(I)),u.register(new ii(I)),u.register(new ni(I)),u.register(new pi(I)),u.register(new mi);let Fe=new oi(i,u,async(b,w,j,k,z)=>Be(b,w,h,u,a,z??i,void 0,void 0,k),void 0,async(b,w,j,k)=>{let z=k?ti(k):a.model,H=$e(i);H.model=z;let Z=Ge(H),ot=k?await He({...a,model:z},Z):h,tt=new K(i,"acceptEdits");w.addUserMessage(b);let rt=new J({client:ot,registry:j,checker:tt,conversation:w,workDir:i,maxIterations:200}),Y="";for await(let oe of rt.run())switch(oe.type){case"stream_text":Y+=oe.text;break;case"loop_complete":return Y||"[No output]";case"error":return Y?`${Y}
|
|
25
25
|
|
|
26
26
|
[Error: ${oe.error.message}]`:`Error: ${oe.error.message}`}return Y||"[No output]"});Fe.forkDisabled=t??!1,Fe.setTeamManager(I,st),u.register(Fe);let Ue=Xe();for(let b of ki(i))try{Ue.register(b)}catch{}_l(ne,se,Ue);let Ia=null,Ha="";if(s&&s.length>0){let b=new xi;Ia=b;let w=await b.connectAll(s);for(let{serverName:j,tool:k}of w.tools){let z=b.getClient(j);z&&u.register(new vi(z,j,k))}for(let{serverName:j,error:k}of w.errors)C.error({serverName:j,error:k},"MCP server connection error");w.instructions.length>0&&(Ha=`# MCP Server Instructions
|
|
27
27
|
|
package/package.json
CHANGED
package/dist/agent-4K4HNCSZ.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
-
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{h as a}from"./chunk-SM5OVMF6.js";import"./chunk-OKI2P5FO.js";import"./chunk-FZPTNGTU.js";import"./chunk-XYSBNUNB.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{a as Agent};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
-
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{g as P}from"./chunk-H7VXSMJR.js";import{l as C}from"./chunk-OKI2P5FO.js";import{e as F,g as G,h as R}from"./chunk-OZOP4GVS.js";import{b as O,c as $,d as I,e as K,f as W,g as D}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{C as w,I as N,J as v,K as j,L as B,M,N as k,O as U,g as S}from"./chunk-XYSBNUNB.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";var x=N({module:"llm"});var Y=3e3,q=w.object({max_input_tokens:w.coerce.number()});async function at(o){if(o.protocol!=="anthropic")return 0;let e=R(o),n=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,r=new AbortController,s=setTimeout(()=>{r.abort()},Y);try{let l=await fetch(n,{method:"GET",headers:{"anthropic-version":"2023-06-01",...e?{"x-api-key":e}:{}},signal:r.signal});if(!l.ok)return 0;let g=await l.json(),{success:h,error:f,data:d}=await S(q,g);if(!h)return console.error(f.message),0;let y=d.max_input_tokens;return Math.max(y,0)}catch(l){return console.error(l),0}finally{clearTimeout(s)}}function J(){return!0}function L(o){return typeof o=="string"?[{type:"text",text:o}]:o}function z(o){let e=[];for(let t of o)if(t.role==="assistant"){let n=[];if(t.thinkingBlocks)for(let s of t.thinkingBlocks)n.push({type:"thinking",thinking:s.thinking,signature:s.signature});let r=typeof t.content=="string"?t.content:j(t.content);if(r&&n.push({type:"text",text:r}),t.toolUses)for(let s of t.toolUses)n.push({type:"tool_use",id:s.toolUseId,name:s.toolName,input:s.arguments});n.length===0&&n.push({type:"text",text:""}),e.push({role:"assistant",content:n})}else if(t.toolResults&&t.toolResults.length>0){let n=[];for(let r of t.toolResults)n.push({type:"tool_result",tool_use_id:r.toolUseId,is_error:r.isError,content:r.content});e.push({role:"user",content:n})}else{if(e.length===0){e.push({role:"user",content:L(t.content)});continue}let n=!1,r=e[e.length-1],s=r.content;r.role==="user"&&(typeof s=="string"||Array.isArray(s)&&s.length>0&&(s[0].type==="text"||s[0].type==="image"))&&(n=!0),n?(typeof s=="string"&&(s=r.content=s.trim().length>0?[{type:"text",text:s}]:[]),s.push(...L(t.content))):e.push({role:"user",content:L(t.content)})}return e}var H=class{client;model;thinking;systemPrompt;maxOutputTokens;contextWindow;constructor(e,t){let n=R(e);if(!n)throw new I("Anthropic API key not found, set ANTHROPIC_API_KEY in .swifty/config.y(a)ml, or via ANTHROPIC_API_KEY env variable.");this.client=new P({apiKey:n,baseURL:e.base_url}),this.model=e.model,this.thinking=e.thinking??!0,this.systemPrompt=t,this.maxOutputTokens=G(e),this.contextWindow=F(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,n){let r=z(O(e.getMessages())),s=t.map(c=>{let p=c.input_schema;return{name:c.name,description:c.description,input_schema:{type:"object",properties:p.properties,required:p.required??[]}}});s.length>0&&(s[s.length-1].cache_control={type:"ephemeral"}),Q(r);let l={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:r,...s.length>0?{tools:s}:{}};this.thinking?J()&&(l.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)}):l.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)};let g=0,h=0,f=0,d=0,y="end_turn",T="",b="",A=!1,E=0;try{let c=this.client.messages.stream(l,{...n?{signal:n}:{}}),p="",_="",u="";for await(let i of c)switch(i.type){case"content_block_start":{let a=i.content_block;a.type==="thinking"?(A=!0,T="",b=""):a.type==="tool_use"&&(_=a.id,p=a.name,u="",yield{type:"tool_call_start",toolName:p,toolId:_});break}case"content_block_delta":{let a=i.delta;a.type==="thinking_delta"?(T+=a.thinking,yield{type:"thinking_delta",text:a.thinking}):a.type==="signature_delta"?(x.debug({signature:a.signature},"thinking signature received"),b=a.signature):a.type==="text_delta"?yield{type:"text_delta",text:a.text}:a.type==="input_json_delta"&&(u+=a.partial_json,yield{type:"tool_call_delta",text:a.partial_json});break}case"content_block_stop":{if(A&&(yield{type:"thinking_complete",thinking:T,signature:b},A=!1),p){let a={};if(u)try{let m=JSON.parse(u);a=B(m)?M(m):{[v]:u}}catch(m){x.error({err:m},"llm operation failed"),a={[v]:u}}yield{type:"tool_call_complete",toolId:_,toolName:p,arguments:a},p="",_="",u=""}break}case"message_delta":{i.delta.stop_reason&&(y=i.delta.stop_reason),i.usage.output_tokens&&(h=i.usage.output_tokens,i.usage.input_tokens&&(g=i.usage.input_tokens),i.usage.cache_read_input_tokens&&(f=i.usage.cache_read_input_tokens),i.usage.cache_creation_input_tokens&&(d=i.usage.cache_creation_input_tokens));break}case"message_start":{E=Date.now(),g=i.message.usage.input_tokens,h=i.message.usage.output_tokens,f=i.message.usage.cache_read_input_tokens??0,d=i.message.usage.cache_creation_input_tokens??0;break}case"message_stop":{let m=Date.now()-E;x.debug({elapsedMs:m},"message stream complete");break}}yield{type:"stream_end",stopReason:y,usage:{inputTokens:g,outputTokens:h,cacheReadInputTokens:f,cacheCreationInputTokens:d}}}catch(c){throw x.error({err:c},"llm operation failed"),V(c)}}};function Q(o){for(let e=o.length-1;e>=0;e--){if(o[e].role!=="user")continue;let t=o[e].content;if(typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0)return;typeof t=="string"&&(t=o[e].content=[{type:"text",text:t}]);let n=t[t.length-1];for(let r=t.length-1;r>=0;r--)if(t[r].type!=="image"){n=t[r];break}Reflect.set(n,"cache_control",{type:"ephemeral"})}}function V(o){if(o instanceof P.APIError){if(o.status===413||/prompts?\s+too\s+long/i.test(o.message))return new D(`Prompt too long: ${o.message}`);if(o.status===401)return new I(`Invalid API key: ${o.message}`);if(o.status===429){let e=M(o.headers)["retry-after"],t="Rate Limited";if(e){let n=Number.parseInt(k(e));Number.isNaN(n)&&(t+=", please wait."),t+=`, retry after ${k(n)}s.`}else t+=", please wait.";return new K(t,e?k(e):void 0)}return new $(`Anthropic API error (${k(o.status)}): ${o.message}`)}return new W(`Network error: ${U(o)}`)}export{H as AnthropicClient,z as buildAnthropicMessages,at as fetchModelContextWindow,Q as markLastUserTailForCache};
|
package/dist/checker-DWBNQC3N.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
-
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{a,b,c,d,e}from"./chunk-2BJOFNPI.js";import"./chunk-7MHXMDYC.js";import"./chunk-XYSBNUNB.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";export{b as PathSandbox,e as PermissionChecker,d as RuleEngine,c as evaluateRules,a as extractContent};
|
package/dist/chunk-MQ5XOYLD.js
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
-
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{readdir as c,stat as l,unlink as u,access as w}from"fs/promises";import{join as s}from"path";var y=30,g=y*24*60*60*1e3;async function f(t){try{return await w(t),!0}catch{return!1}}async function o(t){if(!await f(t))return 0;let n;try{n=(await c(t)).filter(a=>a.endsWith(".jsonl"))}catch{return 0}let r=Date.now(),e=0;for(let a of n){let i=s(t,a);try{let m=await l(i);r-m.mtimeMs>g&&(await u(i),e++)}catch{}}return e}async function p(t){let n=0;n+=await o(s(t,".swifty","logs"));let r=s(t,".swifty","teams");if(!await f(r))return n;let e;try{e=await c(r)}catch{return n}for(let a of e)n+=await o(s(r,a,"logs"));return n}export{p as a};
|
package/dist/chunk-OKI2P5FO.js
DELETED
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
-
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{D as a,I as y,K as T,L as A,O as E,S as B,e as w,f as P}from"./chunk-XYSBNUNB.js";var R=class{history=[];longTermMemoryInjected=!1;baselineTokens=0;_anchorCount=0;addUserMessage(e){this.history.push({role:"user",content:e})}addAssistantMessage(e){this.history.push({role:"assistant",content:e})}addToolUseMessage(e,s,o,n){this.history.push({role:"assistant",content:e,toolUses:[{toolUseId:s,toolName:o,arguments:n}]})}addAssistantMessageWithTools(e,s){this.history.push({role:"assistant",content:e,toolUses:s})}addAssistantFull(e,s,o){this.history.push({role:"assistant",content:e,thinkingBlocks:s.length>0?s:void 0,toolUses:o.length>0?o:void 0})}addToolResultMessage(e,s,o){this.history.push({role:"user",content:"",toolResults:[{toolUseId:e,content:s,isError:o}]})}addToolResultsMessage(e){this.history.push({role:"user",content:"",toolResults:e})}addSystemReminder(e){this.history.push({role:"user",content:`<system-reminder>
|
|
5
|
-
${e}
|
|
6
|
-
</system-reminder>`})}injectLongTermMemory(e,s,o=""){if(this.longTermMemoryInjected)return;let n=[];if(e&&n.push(`# SWIFTY.md
|
|
7
|
-
Codebase and user instructions are shown below. Be sure to adhere to these instructions. IMPORTANT: These instructions OVERRIDE any default behavior and you MUST follow them exactly as written.
|
|
8
|
-
|
|
9
|
-
`+e),s&&n.push(`# Auto Memory
|
|
10
|
-
`+s),o&&n.push(`# availableSkills
|
|
11
|
-
`+o),n.length===0)return;let r=new Date().toISOString().split("T")[0];n.push(`# Current Date
|
|
12
|
-
Today's date is `+r+".");let i=`
|
|
13
|
-
<system-reminder>
|
|
14
|
-
As you answer the user's questions, you can use the following context:
|
|
15
|
-
|
|
16
|
-
${n.join(`
|
|
17
|
-
|
|
18
|
-
`)}
|
|
19
|
-
|
|
20
|
-
IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.
|
|
21
|
-
</system-reminder>`;this.history.unshift({role:"user",content:i}),this.longTermMemoryInjected=!0}len(){return this.history.length}truncateTo(e){e<0&&(e=0),!(e>this.history.length)&&(this.history=this.history.slice(0,e))}getMessages(){return[...this.history]}replaceWithCompacted(e,s){this.history=[{role:"user",content:e},...s],this.longTermMemoryInjected=!1,this.clearUsageAnchor()}recordUsageAnchor(e,s,o,n){let r=e+o+n+s;r<=0||(this.baselineTokens=r,this._anchorCount=this.history.length)}clearUsageAnchor(){this.baselineTokens=0,this._anchorCount=0}usageAnchorState(){return this.baselineTokens<=0?null:{baselineTokens:this.baselineTokens,anchorCount:this._anchorCount}}};import{randomBytes as me}from"crypto";import{readFileSync as $,writeFileSync as de,readdirSync as pe,mkdirSync as fe,statSync as he,existsSync as Y,unlinkSync as Ze,rmSync as et}from"fs";import{basename as k,dirname as x,join as h}from"path";import{createHash as ne}from"crypto";import{existsSync as re,mkdirSync as ie,readFileSync as ae,writeFileSync as ce}from"fs";import{join as j}from"path";function oe(t){if(t==="image/png"||t==="image/jpeg"||t==="image/gif"||t==="image/webp")return t;throw new Error(`Unsupported image media type: "${t}"`)}var N=y({module:"images"}),le={"image/png":"png","image/jpeg":"jpg","image/gif":"gif","image/webp":"webp"};function ue(t,e){return j(t,".swifty","sessions",e||"default","images")}function ge(t,e,s,o){let n=Buffer.from(s,"base64"),r=ne("sha256").update(n).digest("hex").slice(0,16),c=le[o]??"png",i=ue(t,e),l=j(i,`${r}.${c}`);return re(l)||(ie(i,{recursive:!0}),ce(l,n)),l}var L="image_ref";function O(t,e,s){return s.map(o=>{if(o.type!=="image"||!A(o.source)||o.source.type!=="base64")return o;let n=o.source.data,r=o.source.media_type;if(typeof n!="string"||typeof r!="string")return o;try{let c=ge(t,e,n,r);return{type:L,path:c,media_type:r}}catch(c){return N.error({err:c},"failed to persist session image"),o}})}function F(t){return t.map(e=>{if(e.type!==L||typeof e.path!="string")return e;try{let s=ae(e.path);return{type:"image",source:{type:"base64",media_type:typeof e.media_type=="string"?e.media_type:"image/png",data:s.toString("base64")}}}catch(s){return N.warn({err:s,path:e.path},"failed to restore session image"),{type:"text",text:"[note: an image from this tool result could not be restored]"}}})}var _="compact_boundary";var q=a.object({tool_use_id:a.string(),tool_name:a.string(),arguments:a.record(a.string(),a.unknown()).optional()}),C=a.union([a.string(),a.array(a.record(a.string(),a.unknown()))]),K=a.object({tool_use_id:a.string(),content:C,is_error:a.boolean().optional()}),z=a.object({role:a.string(),content:C.default(""),timestamp:a.number(),type:a.string().optional(),tool_uses:a.array(q).optional(),tool_results:a.array(K).optional()}),ye=a.object({role:a.string(),content:C,tool_uses:a.array(q).optional(),tool_results:a.array(K).optional()});function H(t){return(t??[]).map(e=>({tool_use_id:e.toolUseId,tool_name:e.toolName,...e.arguments&&Object.keys(e.arguments).length?{arguments:e.arguments}:{}}))}function W(t,e){return(e??[]).map(s=>({tool_use_id:s.toolUseId,content:M(s.content,t),...s.isError?{is_error:!0}:{}}))}function M(t,e){return typeof t=="string"?t:e?O(e.workDir,e.sessionId,t):t.map(s=>s.type==="image"?{type:"text",text:"[note: image omitted (no session storage available)]"}:s)}var Te=a.object({summary:a.string(),keep:a.array(ye)}),b=y({module:"session"});function S(t){return h(t,".swifty","sessions")}function it(t,e){return h(S(t),e+".jsonl")}function J(t){let e=k(t);if(!e.endsWith(".jsonl"))return null;let s=x(t),o=x(s);return k(s)!=="sessions"||k(o)!==".swifty"?null:{workDir:x(o),sessionId:e.slice(0,-6)}}function at(){let t=Date.now().toString(36),e=me(4).toString("hex");return`${t}-${e}`}function Re(t,e,s){let o=S(t);fe(o,{recursive:!0});let n=h(o,`${e}.jsonl`),r={...s,content:M(s.content,{workDir:t,sessionId:e})},c=JSON.stringify(r)+`
|
|
22
|
-
`;de(n,c,{flag:"a",encoding:"utf-8"})}function ct(t,e,s){Re(t,e,{role:"system",content:JSON.stringify(s),timestamp:Math.floor(Date.now()/1e3),type:_})}function lt(t,e){let s=h(S(t),`${e}.jsonl`);if(!Y(s))return[];let o=[];for(let n of $(s,"utf-8").split(`
|
|
23
|
-
`))if(n.trim())try{let r=JSON.parse(n),{success:c,data:i,error:l}=P(z,r);c?!i.content&&!(i.tool_uses?.length??0)&&!(i.tool_results?.length??0)||o.push(i):b.error({err:l},"session operation failed")}catch(r){b.error({err:r},"session operation failed")}return o}function v(t){return typeof t=="string"?t:F(t)}function G(t){return t?.map(e=>({toolUseId:e.tool_use_id,toolName:e.tool_name,arguments:e.arguments}))}function X(t){return t?.map(e=>({toolUseId:e.tool_use_id,content:v(e.content),isError:e.is_error}))}function ut(t){let e=-1;for(let o=t.length-1;o>=0;o--)if(t[o].type===_){e=o;break}let s=[];if(e>=0){let o=null;try{let n=t[e].content,r=typeof n=="string"?JSON.parse(n):null;o=w(Te,r)}catch{o=null}if(o){let n=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
|
|
24
|
-
|
|
25
|
-
`+o.summary;o.keep.length>0&&(n+=`
|
|
26
|
-
|
|
27
|
-
Recent messages have been preserved verbatim.`),s.push({role:"user",content:n});for(let r of o.keep)r.role!=="user"&&r.role!=="assistant"||!r.content&&!(r.tool_uses?.length??0)&&!(r.tool_results?.length??0)||s.push({role:r.role,content:v(r.content),toolUses:G(r.tool_uses),toolResults:X(r.tool_results)})}for(let n=e+1;n<t.length;n++){let r=t[n];if(r.type===_)continue;let c=D(r);c&&s.push(c)}return s}for(let o of t){let n=D(o);n&&s.push(n)}return s}function D(t){return t.role!=="user"&&t.role!=="assistant"||!t.content&&!(t.tool_uses?.length??0)&&!(t.tool_results?.length??0)?null:{role:t.role,content:v(t.content),toolUses:G(t.tool_uses),toolResults:X(t.tool_results)}}function gt(t){let e=S(t);if(!Y(e))return[];let s=pe(e).filter(n=>n.endsWith(".jsonl")),o=[];for(let n of s){let r=h(e,n),c=he(r),i=n.replace(".jsonl",""),l="",u=0;try{for(let g of $(r,"utf-8").split(`
|
|
28
|
-
`)){if(!g.trim())continue;let m;try{let p=JSON.parse(g);m=w(z,p)}catch(p){b.error({err:p},"session operation failed");continue}u++,!l&&m.role==="user"&&m.content&&(l=T(m.content).slice(0,100))}}catch(g){b.error({err:g},"session operation failed");continue}o.push({id:i,firstMessage:l,messageCount:u,size:c.size,modTime:c.mtime})}return o.sort((n,r)=>r.modTime.getTime()-n.modTime.getTime()),o}var V=3,be=3,Me="[earlier conversation truncated for compaction retry]",Se=3.5,we=1e4,ke=5,xe=4e4,_e=2,Ce=2e4,ve=13e3,Ie=3e3;function Q(t,e,s=!1){return t-Math.min(e,Ce)-(s?Ie:ve)}var Z=class{consecutiveFailures=0},Ue=7e3;function ee(t){if(typeof t=="string")return t.length;let e=0;for(let s of t)s.type==="text"?e+=B(s,"text").length:s.type==="image"&&(e+=Ue);return e}function I(t){let e=0;for(let s of t){if(e+=ee(s.content),s.toolUses&&(e+=JSON.stringify(s.toolUses).length),s.toolResults)for(let o of s.toolResults)e+=ee(o.content);if(s.thinkingBlocks)for(let o of s.thinkingBlocks)e+=o.thinking.length}return Math.ceil(e/Se)}function Pe(t){return I(t.getMessages())}function U(t){return I([t])}function Ae(t){return t.role==="user"&&!!t.toolResults&&t.toolResults.length>0}function Ee(t){let e=0,s=0,o=t.length;for(let n=t.length-1;n>=0;n--){let r=U(t[n]);if(s>0&&e+r>xe||(o=n,e+=r,s++,e>=we||s>=ke))break}return o=Be(t,o),o}function Be(t,e){if(e<=0||e>=t.length||!Ae(t[e]))return e;let s=new Set((t[e].toolResults??[]).map(o=>o.toolUseId));for(let o=e-1;o>=0;o--){let n=t[o];if(n.role==="assistant"&&n.toolUses?.some(r=>s.has(r.toolUseId)))return o}return e}function je(t,e){let s=e??t.usageAnchorState();if(!s)return Pe(t);let o=t.getMessages(),n=Math.min(s.anchorCount,o.length);return s.baselineTokens+I(o.slice(n))}async function ht(t,e,s,o,n,r,c,i,l=""){let u=je(t),g=Q(s,o),m=Q(s,o,!0);if(u<g)return{compacted:!1,message:""};if(!(u>=m)&&n.consecutiveFailures>=V)return{compacted:!1,message:`Auto-compact circuit breaker: ${String(V)} consecutive failures`};try{let f=await te(t,e,r,c,i,l);return n.consecutiveFailures=0,f}catch(f){return n.consecutiveFailures++,{compacted:!1,message:`Auto-compact failed: ${E(f)}`}}}async function yt(t,e,s,o,n,r=""){return te(t,e,s,o,n,r)}var Ne=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
29
|
-
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
30
|
-
|
|
31
|
-
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
32
|
-
|
|
33
|
-
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
34
|
-
- The user's explicit requests and intents
|
|
35
|
-
- Your approach to addressing the user's requests
|
|
36
|
-
- Key decisions, technical concepts and code patterns
|
|
37
|
-
- Specific details like:
|
|
38
|
-
- file names
|
|
39
|
-
- full code snippets
|
|
40
|
-
- function signatures
|
|
41
|
-
- file edits
|
|
42
|
-
- Errors that you ran into and how you fixed them
|
|
43
|
-
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
44
|
-
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
45
|
-
|
|
46
|
-
After your analysis, output your final summary wrapped in <summary> tags. Your summary should include the following sections:
|
|
47
|
-
|
|
48
|
-
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
49
|
-
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
50
|
-
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
|
|
51
|
-
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
52
|
-
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
53
|
-
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
54
|
-
7. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
55
|
-
8. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
|
|
56
|
-
9. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
|
|
57
|
-
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
|
|
58
|
-
|
|
59
|
-
Here's an example of how your output should be structured:
|
|
60
|
-
|
|
61
|
-
<example>
|
|
62
|
-
<analysis>
|
|
63
|
-
[Your thought process, ensuring all points are covered thoroughly and accurately]
|
|
64
|
-
</analysis>
|
|
65
|
-
|
|
66
|
-
<summary>
|
|
67
|
-
1. Primary Request and Intent:
|
|
68
|
-
[Detailed description]
|
|
69
|
-
|
|
70
|
-
2. Key Technical Concepts:
|
|
71
|
-
- [Concept 1]
|
|
72
|
-
- [Concept 2]
|
|
73
|
-
- [...]
|
|
74
|
-
|
|
75
|
-
3. Files and Code Sections:
|
|
76
|
-
- [File Name 1]
|
|
77
|
-
- [Summary of why this file is important]
|
|
78
|
-
- [Summary of the changes made to this file, if any]
|
|
79
|
-
- [Important Code Snippet]
|
|
80
|
-
- [File Name 2]
|
|
81
|
-
- [Important Code Snippet]
|
|
82
|
-
- [...]
|
|
83
|
-
|
|
84
|
-
4. Errors and fixes:
|
|
85
|
-
- [Detailed description of error 1]:
|
|
86
|
-
- [How you fixed the error]
|
|
87
|
-
- [User feedback on the error if any]
|
|
88
|
-
- [...]
|
|
89
|
-
|
|
90
|
-
5. Problem Solving:
|
|
91
|
-
[Description of solved problems and ongoing troubleshooting]
|
|
92
|
-
|
|
93
|
-
6. All user messages:
|
|
94
|
-
- [Detailed non tool use user message]
|
|
95
|
-
- [...]
|
|
96
|
-
|
|
97
|
-
7. Pending Tasks:
|
|
98
|
-
- [Task 1]
|
|
99
|
-
- [Task 2]
|
|
100
|
-
- [...]
|
|
101
|
-
|
|
102
|
-
8. Current Work:
|
|
103
|
-
[Precise description of current work]
|
|
104
|
-
|
|
105
|
-
9. Optional Next Step:
|
|
106
|
-
[Optional Next step to take]
|
|
107
|
-
|
|
108
|
-
</summary>
|
|
109
|
-
</example>
|
|
110
|
-
|
|
111
|
-
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.`;function Le(t){return Ne+`
|
|
112
|
-
|
|
113
|
-
`+t}function Oe(t){let e=[],s=[],o=!1;for(let n of t)n.role==="assistant"&&o&&s.length>0&&(e.push(s),s=[]),s.push(n),o=!!(n.toolResults&&n.toolResults.length>0);return s.length>0&&e.push(s),e}function Fe(t,e){let s=Oe(t);if(s.length<2)return null;let o;if(e>0){let r=0;o=0;for(let c of s)if(r+=c.reduce((i,l)=>i+U(l),0),o++,r>=e)break}else o=Math.max(1,Math.floor(s.length/5));if(o=Math.min(o,s.length-1),o<1)return null;let n=s.slice(o).flat();return n.length>0&&n[0].role!=="user"&&n.unshift({role:"user",content:Me}),n}function De(t){return t.map(e=>{let s=`[${e.role}]: ${T(e.content)}`;return e.toolUses&&(s+=`
|
|
114
|
-
[tools: ${e.toolUses.map(o=>o.toolName).join(", ")}]`),s}).join(`
|
|
115
|
-
|
|
116
|
-
`)}async function $e(t,e,s){let o=e;for(let n=0;;n++){let r=De(o),c=new R;c.addUserMessage(Le(r));try{let i="",l=t.stream(c,s);for await(let g of l)g.type==="text_delta"&&(i+=g.text);let u=/<summary>([\s\S]*?)<\/summary>/.exec(i);return u?u[1].trim():i}catch(i){let l=i instanceof Error?i.message.toLowerCase():"";if(!(l.includes("prompt")&&l.includes("long")||l.includes("too many")||l.includes("context_length"))||n>=be)throw i;let g=o.reduce((p,f)=>p+U(f),0)/5,m=Fe(o,g);if(!m)throw i;o=m}}}async function te(t,e,s,o,n,r=""){let c=t.getMessages(),i=Ee(c);if(i<=0||i<_e)return{compacted:!1,message:`Compaction skipped: only ${String(i)} message(s) to summarize, kept verbatim`};let l=c.slice(0,i),u=c.slice(i),g=await $e(e,l,n),m=s?s.buildRecoveryAttachment(o):"",p=`This session continues from a previous conversation, which has been compressed due to context limitations. Here is a summary of the earlier messages:
|
|
117
|
-
|
|
118
|
-
`+g;u.length>0&&(p+=`
|
|
119
|
-
|
|
120
|
-
Recent messages have been preserved verbatim.`),r&&(p+=`
|
|
121
|
-
|
|
122
|
-
If you need specific details from before compaction (code snippets, error messages, etc.), use ReadFile to read the full session transcript: ${r}`),m&&(p+=`
|
|
123
|
-
|
|
124
|
-
---
|
|
125
|
-
|
|
126
|
-
${m}`),t.replaceWithCompacted(p,u);let f=r?J(r)??void 0:void 0,se=u.filter(d=>(d.role==="user"||d.role==="assistant")&&(d.content||(d.toolUses?.length??0)||(d.toolResults?.length??0))).map(d=>({role:d.role,content:M(d.content,f),...d.toolUses?.length?{tool_uses:H(d.toolUses)}:{},...d.toolResults?.length?{tool_results:W(f,d.toolResults)}:{}}));return{compacted:!0,message:`Compacted ${String(l.length)} messages into summary (${String(g.length)} chars), kept ${String(u.length)} recent messages verbatim`,boundary:{summary:g,keep:se}}}export{R as a,oe as b,H as c,W as d,it as e,at as f,Re as g,ct as h,lt as i,ut as j,gt as k,Q as l,Z as m,ht as n,yt as o};
|
package/dist/cleanup-BQJDUOKA.js
DELETED