@swifty.js/swifty 0.0.23 → 0.0.24

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.
@@ -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 en,h as tn}from"./chunk-CV7OKXYC.js";import{b as Ys,c as Xn,d as bs,e as Gn,f as Qn,g as Yn}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{I as Vn,J as qr,K as ge,L as As,M as Zs,R as oe}from"./chunk-SIWLMWHH.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 Je=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Je=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{},N=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 ke({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 N{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ke=class extends N{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},$e=class extends ke{constructor({message:e}={}){super({message:e??"Request timed out."})}},Rt=class extends N{},St=class extends N{},Ct=class extends N{},kt=class extends N{},$t=class extends N{},Et=class extends N{},Ot=class extends N{},vt=class extends N{},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")}},de=class extends Error{constructor(e){super(e)}},Ve=class extends N{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 _i=/^[a-z][a-z0-9+.-]*:/i,Zn=s=>_i.test(s),X=s=>(X=Array.isArray,X(s)),rn=X;function ws(s){return typeof s!="object"?{}:s??{}}function sn(s){if(!s)return!0;for(let e in s)return!1;return!0}function eo(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Vr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var to=(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 ro=s=>{try{return JSON.parse(s)}catch{return}};var fe=s=>new Promise(e=>setTimeout(e,s));var Ee="6.49.0";var io=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function yi(){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 gi=()=>{let s=yi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ee,"X-Stainless-OS":no(Deno.build.os),"X-Stainless-Arch":so(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":Ee,"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":Ee,"X-Stainless-OS":no(globalThis.process.platform??"unknown"),"X-Stainless-Arch":so(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ai();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ee,"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":Ee,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ai(){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 so=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",no=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"),oo,ao=()=>oo??(oo=gi());function Is(){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 nn(...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 nn({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function Ps(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 on(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 co=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var an="RFC3986",un=s=>String(s),cn={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:un},lo="RFC1738";var xs=(s,e)=>(xs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),xs(s,e)),he=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var ln=1024,po=(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+=ln){let f=o.length>=ln?o.slice(l,l+ln):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===lo&&(m===40||m===41)){p[p.length]=f.charAt(_);continue}if(m<128){p[p.length]=he[m];continue}if(m<2048){p[p.length]=he[192|m>>6]+he[128|m&63];continue}if(m<55296||m>=57344){p[p.length]=he[224|m>>12]+he[128|m>>6&63]+he[128|m&63];continue}_+=1,m=65536+((m&1023)<<10|f.charCodeAt(_)&1023),p[p.length]=he[240|m>>18]+he[128|m>>12&63]+he[128|m>>6&63]+he[128|m&63]}a+=p.join("")}return a};function fo(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function pn(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 mo={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},_o=function(s,e){Array.prototype.push.apply(s,X(e)?e:[e])},ho,z={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:po,encodeValuesOnly:!1,format:an,formatter:un,indices:!1,serializeDate(s){return(ho??(ho=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 dn={};function yo(s,e,t,r,n,o,a,l,f,p,_,m,d,b,I,A,w,k){let y=s,P=k,R=0,v=!1;for(;(P=P.get(dn))!==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(dn)>"u"&&(R=0)}if(typeof p=="function"?y=p(e,y):y instanceof Date?y=d?.(y):t==="comma"&&X(y)&&(y=pn(y,function(T){return T instanceof Date?d?.(T):T})),y===null){if(o)return f&&!A?f(e,z.encoder,w,"key",b):e;y=""}if(wi(y)||fo(y)){if(f){let T=A?e:f(e,z.encoder,w,"key",b);return[I?.(T)+"="+I?.(f(y,z.encoder,w,"value",b))]}return[I?.(e)+"="+I?.(String(y))]}let $=[];if(typeof y>"u")return $;let L;if(t==="comma"&&X(y))A&&f&&(y=pn(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),F=r&&X(y)&&y.length===1?j+"[]":j;if(n&&X(y)&&y.length===0)return F+"[]";for(let T=0;T<L.length;++T){let W=L[T],xt=typeof W=="object"&&typeof W.value<"u"?W.value:y[W];if(a&&xt===null)continue;let J=m&&l?W.replace(/\./g,"%2E"):W,ys=X(y)?typeof t=="function"?t(F,J):F:F+(m?"."+J:"["+J+"]");k.set(s,R);let gs=new WeakMap;gs.set(dn,k),_o($,yo(xt,ys,t,r,n,o,a,l,t==="comma"&&A&&X(y)?null:f,p,_,m,d,b,I,A,w,gs))}return $}function Ii(s=z){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||z.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=an;if(typeof s.format<"u"){if(!xs(cn,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=cn[t],n=z.filter;(typeof s.filter=="function"||X(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in mo?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=z.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:z.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:z.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:z.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:z.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?z.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:z.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:z.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:z.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:z.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:z.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:z.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:z.strictNullHandling}}function go(s,e={}){let t=s,r=Ii(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=mo[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||_o(a,yo(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 Ao(s){return go(s,{arrayFormat:"brackets"})}function Io(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 bo;function ee(s){let e;return(bo??(e=new globalThis.TextEncoder,bo=e.encode.bind(e)))(s)}var wo;function fn(s){let e;return(wo??(e=new globalThis.TextDecoder,wo=e.decode.bind(e)))(s)}var te,re,Xe=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,Io([c(this,te,"f"),t]),"f");let r=[],n;for(;(n=xi(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(fn(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=fn(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 en,h as tn}from"./chunk-W37Y53LX.js";import{b as Ys,c as Xn,d as bs,e as Gn,f as Qn,g as Yn}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{I as Vn,J as qr,K as ge,L as As,M as Zs,R as oe}from"./chunk-SIWLMWHH.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 Je=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Je=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{},N=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 ke({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 N{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ke=class extends N{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},$e=class extends ke{constructor({message:e}={}){super({message:e??"Request timed out."})}},Rt=class extends N{},St=class extends N{},Ct=class extends N{},kt=class extends N{},$t=class extends N{},Et=class extends N{},Ot=class extends N{},vt=class extends N{},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")}},de=class extends Error{constructor(e){super(e)}},Ve=class extends N{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 _i=/^[a-z][a-z0-9+.-]*:/i,Zn=s=>_i.test(s),X=s=>(X=Array.isArray,X(s)),rn=X;function ws(s){return typeof s!="object"?{}:s??{}}function sn(s){if(!s)return!0;for(let e in s)return!1;return!0}function eo(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Vr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var to=(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 ro=s=>{try{return JSON.parse(s)}catch{return}};var fe=s=>new Promise(e=>setTimeout(e,s));var Ee="6.49.0";var io=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function yi(){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 gi=()=>{let s=yi();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ee,"X-Stainless-OS":no(Deno.build.os),"X-Stainless-Arch":so(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":Ee,"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":Ee,"X-Stainless-OS":no(globalThis.process.platform??"unknown"),"X-Stainless-Arch":so(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ai();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ee,"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":Ee,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ai(){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 so=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",no=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"),oo,ao=()=>oo??(oo=gi());function Is(){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 nn(...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 nn({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function Ps(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 on(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 co=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var an="RFC3986",un=s=>String(s),cn={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:un},lo="RFC1738";var xs=(s,e)=>(xs=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),xs(s,e)),he=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var ln=1024,po=(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+=ln){let f=o.length>=ln?o.slice(l,l+ln):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===lo&&(m===40||m===41)){p[p.length]=f.charAt(_);continue}if(m<128){p[p.length]=he[m];continue}if(m<2048){p[p.length]=he[192|m>>6]+he[128|m&63];continue}if(m<55296||m>=57344){p[p.length]=he[224|m>>12]+he[128|m>>6&63]+he[128|m&63];continue}_+=1,m=65536+((m&1023)<<10|f.charCodeAt(_)&1023),p[p.length]=he[240|m>>18]+he[128|m>>12&63]+he[128|m>>6&63]+he[128|m&63]}a+=p.join("")}return a};function fo(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function pn(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 mo={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},_o=function(s,e){Array.prototype.push.apply(s,X(e)?e:[e])},ho,z={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:po,encodeValuesOnly:!1,format:an,formatter:un,indices:!1,serializeDate(s){return(ho??(ho=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 dn={};function yo(s,e,t,r,n,o,a,l,f,p,_,m,d,b,I,A,w,k){let y=s,P=k,R=0,v=!1;for(;(P=P.get(dn))!==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(dn)>"u"&&(R=0)}if(typeof p=="function"?y=p(e,y):y instanceof Date?y=d?.(y):t==="comma"&&X(y)&&(y=pn(y,function(T){return T instanceof Date?d?.(T):T})),y===null){if(o)return f&&!A?f(e,z.encoder,w,"key",b):e;y=""}if(wi(y)||fo(y)){if(f){let T=A?e:f(e,z.encoder,w,"key",b);return[I?.(T)+"="+I?.(f(y,z.encoder,w,"value",b))]}return[I?.(e)+"="+I?.(String(y))]}let $=[];if(typeof y>"u")return $;let L;if(t==="comma"&&X(y))A&&f&&(y=pn(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),F=r&&X(y)&&y.length===1?j+"[]":j;if(n&&X(y)&&y.length===0)return F+"[]";for(let T=0;T<L.length;++T){let W=L[T],xt=typeof W=="object"&&typeof W.value<"u"?W.value:y[W];if(a&&xt===null)continue;let J=m&&l?W.replace(/\./g,"%2E"):W,ys=X(y)?typeof t=="function"?t(F,J):F:F+(m?"."+J:"["+J+"]");k.set(s,R);let gs=new WeakMap;gs.set(dn,k),_o($,yo(xt,ys,t,r,n,o,a,l,t==="comma"&&A&&X(y)?null:f,p,_,m,d,b,I,A,w,gs))}return $}function Ii(s=z){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||z.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=an;if(typeof s.format<"u"){if(!xs(cn,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=cn[t],n=z.filter;(typeof s.filter=="function"||X(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in mo?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=z.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:z.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:z.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:z.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:z.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?z.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:z.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:z.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:z.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:z.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:z.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:z.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:z.strictNullHandling}}function go(s,e={}){let t=s,r=Ii(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=mo[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||_o(a,yo(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 Ao(s){return go(s,{arrayFormat:"brackets"})}function Io(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 bo;function ee(s){let e;return(bo??(e=new globalThis.TextEncoder,bo=e.encode.bind(e)))(s)}var wo;function fn(s){let e;return(wo??(e=new globalThis.TextDecoder,wo=e.decode.bind(e)))(s)}var te,re,Xe=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,Io([c(this,te,"f"),t]),"f");let r=[],n;for(;(n=xi(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(fn(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=fn(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;Xe.NEWLINE_CHARS=new Set([`
6
6
  `,"\r"]);Xe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function xi(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 Po(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 Ss={off:0,error:200,warn:300,info:400,debug:500},hn=(s,e,t)=>{if(s){if(eo(Ss,s))return s;K(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(Ss))}`)}};function Gr(){}function Rs(s,e,t){return!e||Ss[s]>Ss[t]?Gr:e[s].bind(e)}var Ri={error:Gr,warn:Gr,info:Gr,debug:Gr},xo=new WeakMap;function K(s){let e=s.logger,t=s.logLevel??"off";if(!e)return Ri;let r=xo.get(e);if(r&&r[0]===t)return r[1];let n={error:Rs("error",e,t),warn:Rs("warn",e,t),info:Rs("info",e,t),debug:Rs("debug",e,t)};return xo.set(e,[t,n]),n}var Ae=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 Si(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 N(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 N(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 Xe,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 I of l.decode(d)){if(t.signal.aborted)return;yield I}}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 nn({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*Si(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 mn,r=new Xe,n=Ps(s.body);for await(let o of Ci(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*Ci(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=Po(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var mn=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(`
@@ -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{A as fi,G as bi,H as ue,I as me,J as gi,K as de,L as xe,M as hi,N as yi,O as ve,P as fe,Q as be,R as wi,T as ki,V as ji,W as Ei,X as qi,Y as Je,Z as Ke,_ as Si,a as We,aa as Ti,ba as Ci,ca as zi,d as xt,da as _i,ea as Pi,fa as Ai,ga as Ri,ha as Mi,i as ri,ia as Oi,j as Ze,ja as Li,k as Ye,ka as Fi,la as Ui,ma as Ni,na as Di,p as ci,r as pi,t as li,u as ui,v as mi,w as di,x as Ve,y as xi,z as vi}from"./chunk-Y43POSIW.js";import{a as $e,b as Za}from"./chunk-XBHVVB5A.js";import{c as Ja}from"./chunk-5KXBVL2A.js";import{a as oi,b as ti,i as V}from"./chunk-OCQ6TYLT.js";import{a as O,e as Ka,f as Qa,g as ce,h as Be,i as ei,j as ai,k as pe,o as ii}from"./chunk-MJR2C7S7.js";import{e as Xe,f as ni,g as si}from"./chunk-CV7OKXYC.js";import"./chunk-FZPTNGTU.js";import{f as J}from"./chunk-NR62AA5K.js";import{b as Ya,e as Va}from"./chunk-QN27QEFS.js";import"./chunk-7MHXMDYC.js";import{D as q,I as re,J as H,R as Ge}from"./chunk-SIWLMWHH.js";import{a as le}from"./chunk-A2VR3BC4.js";import"./chunk-E55KH72M.js";import{a as x,b as l,d as dt}from"./chunk-X3UA5OZL.js";var Hi=l((Fl,Ii)=>{"use strict";Ii.exports=vt;function vt(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=ft(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 ft(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 ea=l((Ul,Qe)=>{"use strict";Qe.exports=gt;Qe.exports.isFinished=Bi;var $i=jt(),Gi=Hi(),bt=typeof setImmediate=="function"?setImmediate:function(e){process.nextTick(e.bind.apply(e,arguments))};function gt(e,a){return Bi(e)!==!1?(bt(a,null,e),e):(yt(e,Et(a)),e)}function Bi(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 ht(e,a){var i,n,s=!1;function o(r){i.cancel(),n.cancel(),s=!0,a(r)}i=n=Gi([[e,"end","finish"]],o);function t(r){e.removeListener("socket",t),!s&&i===n&&(n=Gi([[r,"error","close"]],o))}if(e.socket){t(e.socket);return}e.on("socket",t),e.socket===void 0&&kt(e,t)}function yt(e,a){var i=e.__onFinished;(!i||!i.queue)&&(i=e.__onFinished=wt(e),ht(e,i)),i.queue.push(a)}function wt(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 kt(e,a){var i=e.assignSocket;typeof i=="function"&&(e.assignSocket=function(s){i.call(this,s),a(s)})}function jt(){try{return x("async_hooks")}catch{return{}}}function Et(e){var a;return $i.AsyncResource&&(a=new $i.AsyncResource(e.name||"bound-anonymous-fn")),!a||!a.runInAsyncScope?e:a.runInAsyncScope.bind(a,e,null)}});var Wi=l((Nl,Xi)=>{"use strict";Xi.exports=qt;function qt(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 Zi=l((Dl,St)=>{St.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 K=l((Il,Vi)=>{"use strict";var aa=Zi();Vi.exports=_;_.message=aa;_.code=Tt(aa);_.codes=Ct(aa);_.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 Tt(e){var a={};return Object.keys(e).forEach(function(n){var s=e[n],o=Number(n);a[s.toLowerCase()]=o}),a}function Ct(e){return Object.keys(e).map(function(i){return Number(i)})}function zt(e){var a=e.toLowerCase();if(!Object.prototype.hasOwnProperty.call(_.code,a))throw new Error('invalid status message: "'+e+'"');return _.code[a]}function Yi(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 Yi(e);if(typeof e!="string")throw new TypeError("code must be a number or string");var a=parseInt(e,10);return isNaN(a)?zt(e):Yi(a)}});var na=l((Hl,en)=>{"use strict";var _t=x("path").relative;en.exports=Ot;var Pt=process.cwd();function Ki(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 At(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 Rt(e){for(var a="",i=0;i<e;i++)a+=", arg"+i;return a.substr(2)}function Mt(e){var a=this.name+": "+this.namespace;this.message&&(a+=" deprecated "+this.message);for(var i=0;i<e.length;i++)a+=`
4
+ import{A as fi,G as bi,H as ue,I as me,J as gi,K as de,L as xe,M as hi,N as yi,O as ve,P as fe,Q as be,R as wi,T as ki,V as ji,W as Ei,X as qi,Y as Je,Z as Ke,_ as Si,a as We,aa as Ti,ba as Ci,ca as zi,d as xt,da as _i,ea as Pi,fa as Ai,ga as Ri,ha as Mi,i as ri,ia as Oi,j as Ze,ja as Li,k as Ye,ka as Fi,la as Ui,ma as Ni,na as Di,p as ci,r as pi,t as li,u as ui,v as mi,w as di,x as Ve,y as xi,z as vi}from"./chunk-FAJYJI6T.js";import{a as $e,b as Za}from"./chunk-XBHVVB5A.js";import{c as Ja}from"./chunk-5KXBVL2A.js";import{a as oi,b as ti,i as V}from"./chunk-VQUWSKQQ.js";import{a as O,e as Ka,f as Qa,g as ce,h as Be,i as ei,j as ai,k as pe,o as ii}from"./chunk-MWZIARZE.js";import{e as Xe,f as ni,g as si}from"./chunk-W37Y53LX.js";import"./chunk-FZPTNGTU.js";import{f as J}from"./chunk-NR62AA5K.js";import{b as Ya,e as Va}from"./chunk-QN27QEFS.js";import"./chunk-7MHXMDYC.js";import{D as q,I as re,J as H,R as Ge}from"./chunk-SIWLMWHH.js";import{a as le}from"./chunk-A2VR3BC4.js";import"./chunk-E55KH72M.js";import{a as x,b as l,d as dt}from"./chunk-X3UA5OZL.js";var Hi=l((Fl,Ii)=>{"use strict";Ii.exports=vt;function vt(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=ft(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 ft(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 ea=l((Ul,Qe)=>{"use strict";Qe.exports=gt;Qe.exports.isFinished=Bi;var $i=jt(),Gi=Hi(),bt=typeof setImmediate=="function"?setImmediate:function(e){process.nextTick(e.bind.apply(e,arguments))};function gt(e,a){return Bi(e)!==!1?(bt(a,null,e),e):(yt(e,Et(a)),e)}function Bi(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 ht(e,a){var i,n,s=!1;function o(r){i.cancel(),n.cancel(),s=!0,a(r)}i=n=Gi([[e,"end","finish"]],o);function t(r){e.removeListener("socket",t),!s&&i===n&&(n=Gi([[r,"error","close"]],o))}if(e.socket){t(e.socket);return}e.on("socket",t),e.socket===void 0&&kt(e,t)}function yt(e,a){var i=e.__onFinished;(!i||!i.queue)&&(i=e.__onFinished=wt(e),ht(e,i)),i.queue.push(a)}function wt(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 kt(e,a){var i=e.assignSocket;typeof i=="function"&&(e.assignSocket=function(s){i.call(this,s),a(s)})}function jt(){try{return x("async_hooks")}catch{return{}}}function Et(e){var a;return $i.AsyncResource&&(a=new $i.AsyncResource(e.name||"bound-anonymous-fn")),!a||!a.runInAsyncScope?e:a.runInAsyncScope.bind(a,e,null)}});var Wi=l((Nl,Xi)=>{"use strict";Xi.exports=qt;function qt(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 Zi=l((Dl,St)=>{St.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 K=l((Il,Vi)=>{"use strict";var aa=Zi();Vi.exports=_;_.message=aa;_.code=Tt(aa);_.codes=Ct(aa);_.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 Tt(e){var a={};return Object.keys(e).forEach(function(n){var s=e[n],o=Number(n);a[s.toLowerCase()]=o}),a}function Ct(e){return Object.keys(e).map(function(i){return Number(i)})}function zt(e){var a=e.toLowerCase();if(!Object.prototype.hasOwnProperty.call(_.code,a))throw new Error('invalid status message: "'+e+'"');return _.code[a]}function Yi(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 Yi(e);if(typeof e!="string")throw new TypeError("code must be a number or string");var a=parseInt(e,10);return isNaN(a)?zt(e):Yi(a)}});var na=l((Hl,en)=>{"use strict";var _t=x("path").relative;en.exports=Ot;var Pt=process.cwd();function Ki(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 At(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 Rt(e){for(var a="",i=0;i<e;i++)a+=", arg"+i;return a.substr(2)}function Mt(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 Ot(e){if(!e)throw new TypeError("argument namespace is required");var a=he(),i=$(a[1]),n=i[0];function s(o){ge.call(s,o)}return s._file=n,s._ignored=Ft(e),s._namespace=e,s._traced=Ut(e),s._warned=Object.create(null),s.function=Ht,s.property=$t,s}function Lt(e,a){var i=typeof e.listenerCount!="function"?e.listeners(a).length:e.listenerCount(a);return i>0}function Ft(e){if(process.noDeprecation)return!0;var a=process.env.NO_DEPRECATION||"";return Ki(a,e)}function Ut(e){if(process.traceDeprecation)return!0;var a=process.env.TRACE_DEPRECATION||"";return Ki(a,e)}function ge(e,a){var i=Lt(process,"deprecation");if(!(!i&&this._ignored)){var n,s,o,t,r=0,c=!1,p=he(),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?Ji(t):Ji(o)),i){var f=Qi(this._namespace,d,p.slice(r));process.emit("deprecation",f);return}var g=process.stderr.isTTY?Dt:Nt,T=g.call(this,d,n,p.slice(r));process.stderr.write(T+`
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 Ji(e){var a=e.callSite,i=e.name;i||(i="<anonymous@"+ia(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 Nt(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 "+ia(a)),s}function Dt(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 Xo}};function tl(e){if(e.respond===!1)return;let a=e.res;if(!e.writable)return a.end();let i=e.body,n=e.status;if(Qp.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=Fe.Readable.from(i.stream()):i instanceof ReadableStream?s=Fe.Readable.from(i):i instanceof Response?s=Fe.Readable.from(i?.body||""):sl(i)&&(s=i),s)return Fe.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)}La.exports.HttpError=el});import{readFileSync as El,existsSync as ql,statSync as Sl}from"fs";import{createServer as Tl}from"http";import{join as tt,extname as Cl,normalize as zl}from"path";import{cwd as ie}from"process";var Fa=dt(Wo(),1),Zo=Fa.default,Lu=Fa.default.HttpError;import{existsSync as Ua,statSync as Ko,readFileSync as Yo,writeFileSync as Qo,mkdirSync as rl,unlinkSync as cl,utimesSync as pl}from"fs";import{homedir as Vo}from"os";import{join as ae,basename as Jo}from"path";var et=re({module:"memory"}),ll=24,ul=5,ml=600*1e3,dl=".consolidate-lock",xl=3600*1e3,vl=200,Ne=class{client;workDir;lastScanAt=0;minHours;minSessions;appendSystem;constructor(a,i,n){this.client=a,this.workDir=i,this.minHours=n?.minHours??ll,this.minSessions=n?.minSessions??ul,this.appendSystem=n?.appendSystem}maybeRun(){let a=ae(this.workDir,".swifty","memory");if(!Ua(a))return Promise.resolve();let i=fl(a);if((Date.now()-i)/36e5<this.minHours)return Promise.resolve();let s=Date.now();if(s-this.lastScanAt<ml)return Promise.resolve();this.lastScanAt=s;let o=yl(this.workDir,i);if(o.length<this.minSessions)return Promise.resolve();let t=bl(a);return t===null||this.run(a,o,t).catch(()=>{gl(a,t)}),Promise.resolve()}async run(a,i,n){let s=ae(Vo(),".swifty","memory"),o=ae(this.workDir,".swifty","sessions"),t=wl(a,s,o,i),r=new le;r.register(new xe),r.register(new be),r.register(new me),r.register(new ve),r.register(new fe),r.register(new ue),r.register(new de);let c=new J(this.workDir,"bypassPermissions");c.allowExtraRoot(ae(Vo(),".swifty","memory"));let p=new O;p.addUserMessage(t);let m=new V({client:this.client,registry:r,checker:c,conversation:p,workDir:this.workDir,maxIterations:15});for await(let f of m.run());let d=kl(p.getMessages()).filter(f=>Jo(f)!=="MEMORY.md");if(d.length>0&&this.appendSystem){let f=d.map(g=>Jo(g));this.appendSystem(`Memory improved: ${f.join(", ")}`)}}};function Na(e){return ae(e,dl)}function fl(e){let a=Na(e);if(!Ua(a))return 0;try{return Ko(a).mtimeMs}catch{return 0}}function bl(e){let a=Na(e),i,n;if(Ua(a))try{i=Ko(a).mtimeMs;let s=Yo(a,"utf-8").trim(),o=parseInt(s,10);Number.isFinite(o)&&(n=o)}catch(s){et.error({err:s},"failed to read consolidation lock file")}if(i!==void 0&&Date.now()-i<xl&&n!==void 0&&hl(n))return null;rl(e,{recursive:!0}),Qo(a,String(process.pid));try{let s=Yo(a,"utf-8").trim();if(parseInt(s,10)!==process.pid)return null}catch{return null}return i??0}function gl(e,a){let i=Na(e);try{if(a===0){cl(i);return}Qo(i,"");let n=a/1e3;pl(i,n,n)}catch(n){et.error({err:n},"failed to rollback consolidation lock")}}function hl(e){try{return process.kill(e,0),!0}catch{return!1}}function yl(e,a){let i=pe(e),n=new Date(a);return i.filter(s=>s.modTime>n).map(s=>s.id)}function wl(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(vl)} 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/PowerShell are 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 kl(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}function jl(e){return e.length<=800?e:`${e.slice(0,800)}\u2026 (+${String(e.length-800)} chars)`}var De=class{constructor(a){this.log=a}log;onEvent(a){switch(a.type){case"tool_result":{if(!a.isError)return;let i=a.output;this.log.warn({event:"tool_result",tool:a.toolName,toolId:a.toolId,isError:!0,elapsedMs:Math.round(a.elapsed*1e3),outputChars:i.length,output:jl(i)});return}case"retry":this.log.warn({event:"retry",reason:a.reason,delayMs:a.delay});return;case"compact":this.log.warn({event:"compact",message:a.message});return;case"error":this.log.error({event:"error",err:a.error});return;default:return}}};var P=re({module:"remote"}),_l=q.object({type:q.string(),data:q.unknown()}),Pl=q.object({content:q.string()}),Al=q.object({id:q.string(),response:q.enum(["allow","deny","allowAlways"])}),Rl=q.object({id:q.string(),answers:q.record(q.string(),q.string())}),at=tt(import.meta.dirname,"fe","dist"),Ml={".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 it(e){let a=zl(e).replace(/^(\.\.[/\\])+/,""),i=tt(at,a);if(!i.startsWith(at)||!ql(i)||!Sl(i).isFile())return null;let n=El(i),s=Ml[Cl(i)]??"application/octet-stream";return{body:n,mime:s}}var Da=class{client;conv;registry;sessionId;fileHistory;fileStateCache;cmdRegistry;skillCatalog;activeSkills;toolFilter;mcpManager;hookEngine;recoveryState;teamManager;enableCoordinatorMode;forkDisabled;memoryManager;contextWindow;longTermMemoryInstructions;longTermMemoryMemoryContent;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.longTermMemoryInstructions=a.longTermMemoryInstructions,this.longTermMemoryMemoryContent=a.longTermMemoryMemoryContent,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 J(this.workDir,"default");yield*new V({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:si(this.provider),recoveryState:this.recoveryState,activeSkills:this.activeSkills,toolFilter:o=>xi(this.enableCoordinatorMode)(o)?this.toolFilter?this.toolFilter(o):!0:!1,coordinatorActiveFn:()=>vi(this.enableCoordinatorMode),instructions:this.longTermMemoryInstructions,memoryContent:this.longTermMemoryMemoryContent,notificationFn:()=>this.teamManager.drainLeads(),onPermissionRequest:i.onPermissionRequest,onLoopComplete:o=>{let t=o.getMessages().slice(-40).map(r=>`[${r.role}]: ${H(r.content)}`).filter(r=>r.length>12).join(`
23
23
  `);new Pi(this.client,this.workDir).extract(t).catch(()=>{}),new Ne(this.client,this.workDir,{appendSystem:r=>{o.addSystemReminder(r)}}).maybeRun().catch(()=>{})}}).run()}finally{this.abortController=null}}abort(){this.abortController?.abort()}};async function nt(e){let{provider:a,workDir:i,hooks:n,mcpServers:s,enableCoordinatorMode:o,forkDisabled:t,askUser:r}=e,c=Qa(),p=new Ti(i,c),m=new gi,u=Ol(i,c),d=Ze(i);d.model=a.model;let f=Ye(d),g=await We(a,f),T=new O,ne=Xe(a);ni(a).then(b=>{b>0&&(ne=b)}).catch(()=>{});let Ia=Ai(i),Ha=new _i(i),$a=Ha.buildSystemReminder();T.injectLongTermMemory(Ia,$a),T.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 Ga=zi(n??[]);Ga&&P.warn({message:Ga.message},"hook validation warning");let rt=new Ci(n??[]),se=new wi;se.load(i);let Ba=new Map,oe={activateSkill:(b,y)=>{Ba.set(b,y)}},ct={activateSkill:oe.activateSkill.bind(oe),snapshotParentMessages:b=>(T?.getMessages()??[]).slice(-b).map(j=>`${j.role}: ${H(j.content)}`).join(`
24
- `),runSubagent:async b=>{if(!g)throw new Error("no llm client (provider not initialized)");let{PermissionChecker:y}=await import("./checker-3RWAYF2U.js"),{Agent:j}=await import("./agent-RABW3Z3R.js"),k=new O;k.addUserMessage(b);let z=new j({client:g,registry:u,checker:new y(i,"acceptEdits"),conversation:k,workDir:i,maxIterations:200}),I="";for await(let Z of z.run())switch(Z.type){case"stream_text":I+=Z.text;break;case"loop_complete":return I||"[No output]";case"error":throw Z.error}return I||"[No output]"}};u.register(new ji(se,oe,ct)),u.register(new Ni(r));let pt=(b,y)=>(j,k)=>Ve(ui[0],j,g,b,a,i,void 0,k,void 0,y),D=new bi(i);u.register(new ci(D)),u.register(new pi(D)),u.register(new li(D)),u.register(new fi(D)),u.register(new hi);let Ie=new mi(i,u,async(b,y,j,k,z)=>Ve(b,y,g,u,a,z??i,void 0,void 0,k),void 0,async(b,y,j,k)=>{let z=k?di(k):a.model,I=Ze(i);I.model=z;let Z=Ye(I),lt=k?await We({...a,model:z},Z):g,ut=new J(i,"acceptEdits");y.addUserMessage(b);let mt=new V({client:lt,registry:j,checker:ut,conversation:y,workDir:i,maxIterations:200}),Y="";for await(let te of mt.run())switch(te.type){case"stream_text":Y+=te.text;break;case"loop_complete":return Y||"[No output]";case"error":return Y?`${Y}
24
+ `),runSubagent:async b=>{if(!g)throw new Error("no llm client (provider not initialized)");let{PermissionChecker:y}=await import("./checker-3RWAYF2U.js"),{Agent:j}=await import("./agent-24XMR2WX.js"),k=new O;k.addUserMessage(b);let z=new j({client:g,registry:u,checker:new y(i,"acceptEdits"),conversation:k,workDir:i,maxIterations:200}),I="";for await(let Z of z.run())switch(Z.type){case"stream_text":I+=Z.text;break;case"loop_complete":return I||"[No output]";case"error":throw Z.error}return I||"[No output]"}};u.register(new ji(se,oe,ct)),u.register(new Oi(r));let pt=(b,y)=>(j,k)=>Ve(ui[0],j,g,b,a,i,void 0,k,void 0,y),D=new bi(i);u.register(new ci(D)),u.register(new pi(D)),u.register(new li(D)),u.register(new fi(D)),u.register(new hi);let Ie=new mi(i,u,async(b,y,j,k,z)=>Ve(b,y,g,u,a,z??i,void 0,void 0,k),void 0,async(b,y,j,k)=>{let z=k?di(k):a.model,I=Ze(i);I.model=z;let Z=Ye(I),lt=k?await We({...a,model:z},Z):g,ut=new J(i,"acceptEdits");y.addUserMessage(b);let mt=new V({client:lt,registry:j,checker:ut,conversation:y,workDir:i,maxIterations:200}),Y="";for await(let te of mt.run())switch(te.type){case"stream_text":Y+=te.text;break;case"loop_complete":return Y||"[No output]";case"error":return Y?`${Y}
25
25
 
26
26
  [Error: ${te.error.message}]`:`Error: ${te.error.message}`}return Y||"[No output]"});Ie.forkDisabled=t??!1,Ie.setTeamManager(D,pt),u.register(Ie);let He=Ke();for(let b of Si(i))try{He.register(b)}catch{}Ll(se,oe,He);let Xa=null,Wa="";if(s&&s.length>0){let b=new ri;Xa=b;let y=await b.connectAll(s);for(let{serverName:j,tool:k}of y.tools){let z=b.getClient(j);z&&u.register(new Ya(z,j,k))}for(let{serverName:j,error:k}of y.errors)P.error({serverName:j,error:k},"MCP server connection error");y.tools.length>0&&Ja(u,a.base_url,Xe(a)),y.instructions.length>0&&(Wa=`# MCP Server Instructions
27
27
 
@@ -30,7 +30,7 @@ The following MCP servers are connected. Use their tools when the user asks.
30
30
  `+y.instructions.map(({serverName:k,text:z})=>`## ${k}
31
31
  ${z}`).join(`
32
32
 
33
- `))}return new Da({client:g,conv:T,registry:u,sessionId:c,fileHistory:p,fileStateCache:m,cmdRegistry:He,skillCatalog:se,activeSkills:Ba,toolFilter:null,mcpManager:Xa,hookEngine:rt,recoveryState:new oi,teamManager:D,forkDisabled:t,enableCoordinatorMode:o,memoryManager:Ha,contextWindow:ne,longTermMemoryInstructions:Ia,longTermMemoryMemoryContent:$a,mcpInstructions:Wa,provider:a,workDir:i})}function Ol(e,a){let i=new Ri(e,a),n=new Mi(i),s=new le;return s.register(new xe),s.register(new ue),s.register(new de),s.register(new ve),s.register(new fe),s.register(new be),s.register(new me),s.register(new yi(s)),s.register(new Va(s)),s.register(new Ei),s.register(new qi),s.register(new Di),s.register(new Oi(n)),s.register(new Li(n)),s.register(new Fi(n)),s.register(new Ui(n)),s}function Ll(e,a,i){for(let n of e.list()){if(i.find(n.name))continue;let s=e.get(n.name);if(!s)continue;let o=s.meta.mode==="fork";try{i.register({name:n.name,aliases:[],type:o?"skill_fork":"prompt",description:`${n.description} [skill]`,handler:o?()=>"":t=>ki(s,t.args,a)})}catch{}}}function st(e,a,i){let n=[];return i.reason&&n.push(i.reason),a.command?n.push(`Command: ${Ge(a,"command")}`):a.file_path&&n.push(`File: ${Ge(a,"file_path")}`),n.join(`
33
+ `))}return new Da({client:g,conv:T,registry:u,sessionId:c,fileHistory:p,fileStateCache:m,cmdRegistry:He,skillCatalog:se,activeSkills:Ba,toolFilter:null,mcpManager:Xa,hookEngine:rt,recoveryState:new oi,teamManager:D,forkDisabled:t,enableCoordinatorMode:o,memoryManager:Ha,contextWindow:ne,longTermMemoryInstructions:Ia,longTermMemoryMemoryContent:$a,mcpInstructions:Wa,provider:a,workDir:i})}function Ol(e,a){let i=new Ri(e,a),n=new Mi(i),s=new le;return s.register(new xe),s.register(new ue),s.register(new de),s.register(new ve),s.register(new fe),s.register(new be),s.register(new me),s.register(new yi(s)),s.register(new Va(s)),s.register(new Ei),s.register(new qi),s.register(new Di),s.register(new Li(n)),s.register(new Fi(n)),s.register(new Ui(n)),s.register(new Ni(n)),s}function Ll(e,a,i){for(let n of e.list()){if(i.find(n.name))continue;let s=e.get(n.name);if(!s)continue;let o=s.meta.mode==="fork";try{i.register({name:n.name,aliases:[],type:o?"skill_fork":"prompt",description:`${n.description} [skill]`,handler:o?()=>"":t=>ki(s,t.args,a)})}catch{}}}function st(e,a,i){let n=[];return i.reason&&n.push(i.reason),a.command?n.push(`Command: ${Ge(a,"command")}`):a.file_path&&n.push(`File: ${Ge(a,"file_path")}`),n.join(`
34
34
  `)}var ot=class{app;server;wss;clients=new Set;opts;agentHandle=null;streaming=!1;turnCount=0;eventLogger=new De(P);pendingPermissions=new Map;pendingAsks=new Map;constructor(a){this.opts=a,this.app=new Zo,this.server=Tl((i,n)=>{this.app.callback()(i,n)}),this.wss=new Za.default({server:this.server}),this.setupRoutes(),this.setupWebSocket()}setupRoutes(){this.app.use(async(a,i)=>{if(a.path==="/health"){a.body={status:"ok",remote:!0,clients:this.clients.size};return}await i()}),this.app.use(a=>{let i=a.path==="/"?"/index.html":a.path,n=it(i);if(n){a.type=n.mime,a.body=n.body;return}let s=it("/index.html");if(s){a.type=s.mime,a.body=s.body;return}a.status=404,a.body="Not found"})}setupWebSocket(){this.wss.on("connection",a=>{this.clients.add(a),this.agentHandle&&this.send(a,{type:"connected",data:{session:this.agentHandle.sessionId,cwd:ie()}}),this.send(a,{type:"commands",data:this.buildCommandList()}),a.on("message",i=>{let n;try{n=JSON.parse(i.toString("utf-8"))}catch{P.warn("received non-JSON WebSocket message");return}let s=_l.safeParse(n);if(!s.success){P.warn("received malformed WS message");return}this.handleWsMessage(s.data)}),a.on("close",()=>{this.clients.delete(a)}),a.on("error",()=>{this.clients.delete(a)})})}async handleWsMessage(a){switch(a.type){case"user_message":{let i=Pl.safeParse(a.data);i.success&&await this.handleUserMessage(i.data.content);break}case"permission_response":{let i=Al.safeParse(a.data);if(i.success){let n=this.pendingPermissions.get(i.data.id);n&&(n(i.data.response),this.pendingPermissions.delete(i.data.id))}break}case"ask_user_response":{let i=Rl.safeParse(a.data);if(i.success){let n=this.pendingAsks.get(i.data.id);n&&(n(i.data.answers),this.pendingAsks.delete(i.data.id))}break}case"cancel":{this.agentHandle?.abort();break}case"ping":{this.broadcast({type:"pong",data:null});break}default:P.warn({type:a.type},"unknown WS message type")}}async ensureAgent(){if(this.agentHandle)return this.agentHandle;try{return this.agentHandle=await nt({provider:this.opts.providers[0],workDir:ie(),hooks:this.opts.hookConfigs,mcpServers:this.opts.mcpServers,askUser:this.createAskUserCallback(),enableCoordinatorMode:this.opts.enableCoordinatorMode,forkDisabled:this.opts.forkDisabled}),this.broadcast({type:"connected",data:{session:this.agentHandle.sessionId,cwd:ie()}}),this.agentHandle}catch(a){return P.error({err:a},"failed to initialize agent"),this.broadcast({type:"error",data:{message:`Failed to initialize agent: ${a instanceof Error?a.message:String(a)}`}}),null}}async handleUserMessage(a){let i=a.trim();if(!i||this.streaming)return;let n=await this.ensureAgent();if(!n)return;if(this.broadcast({type:"replay_user",data:{content:i}}),i.startsWith("/")&&Je(i)!==null){await this.handleSlashCommand(i);return}this.streaming=!0;let s=Date.now(),o=n.workDir,t=n.sessionId;ce(o,t,{role:"user",content:i,timestamp:Math.floor(Date.now()/1e3)});try{let r={onPermissionRequest:async(p,m,u)=>{let d=`perm_${Date.now().toString(36)}`,f=st(p,m,u);return this.broadcast({type:"permission_request",data:{id:d,toolName:p,description:f}}),new Promise(g=>{this.pendingPermissions.set(d,g)})}},c="";for await(let p of n.run(i,r))(p.type==="tool_result"||p.type==="turn_complete"||p.type==="loop_complete")&&c&&(this.broadcast({type:"stream_end",data:{text:c}}),c=""),this.bridgeEvent(p,s,o,t,m=>{c+=m})}catch(r){P.error({err:r},"agent stream error"),this.broadcast({type:"error",data:{message:r instanceof Error?r.message:String(r)}})}finally{this.streaming=!1}}bridgeEvent(a,i,n,s,o){switch(this.eventLogger.onEvent(a),a.type){case"stream_text":o(a.text),this.broadcast({type:"stream_text",data:{text:a.text}});break;case"thinking_text":this.broadcast({type:"thinking_text",data:{text:a.text}});break;case"thinking_complete":break;case"tool_use":this.broadcast({type:"tool_use",data:{toolId:a.toolId,toolName:a.toolName,args:a.args}});break;case"tool_result":this.broadcast({type:"tool_result",data:{toolId:a.toolId,toolName:a.toolName,output:a.output,isError:a.isError,elapsed:a.elapsed}});break;case"turn_complete":this.turnCount++,this.broadcast({type:"turn_complete",data:{turn:this.turnCount}});break;case"loop_complete":{let t=(Date.now()-i)/1e3;this.broadcast({type:"loop_complete",data:{stopReason:a.stopReason,totalTurns:this.turnCount,elapsed:t}});break}case"usage":this.broadcast({type:"usage",data:{inputTokens:a.usage.inputTokens,outputTokens:a.usage.outputTokens}});break;case"error":this.broadcast({type:"error",data:{message:a.error.message}});break;case"compact":this.broadcast({type:"compact",data:{message:a.message}}),a.boundary&&Be(n,s,a.boundary);break;case"retry":this.broadcast({type:"retry",data:{reason:a.reason,waitMs:a.delay}});break;case"permission_request":break}}async handleSlashCommand(a){let i=await this.ensureAgent();if(!i){this.broadcast({type:"command_done",data:null});return}let n=Je(a);if(!n)return;let{name:s,args:o}=n,t=i.cmdRegistry.find(s);if(!t){this.broadcast({type:"error",data:{message:`Unknown command: /${s} -- type /help to see available commands`}}),this.broadcast({type:"command_done",data:null});return}let r=this.buildCommandContext(o);switch(t.type){case"local":{let c=t.handler(r);this.broadcast({type:"system",data:{message:c}}),this.broadcast({type:"command_done",data:null});break}case"local_ui":await this.handleLocalUICommand(s,o);break;case"prompt":{let c=t.handler(r),p=o?`/${s} ${o}`:`/${s}`;this.streaming=!0;let m=i.workDir,u=i.sessionId;ce(m,u,{role:"user",content:p,timestamp:Math.floor(Date.now()/1e3)});let d=Date.now();try{let f={onPermissionRequest:this.createPermissionCallback()},g="";for await(let T of i.run(c,f))(T.type==="tool_result"||T.type==="turn_complete"||T.type==="loop_complete")&&g&&(this.broadcast({type:"stream_end",data:{text:g}}),g=""),this.bridgeEvent(T,d,m,u,ne=>{g+=ne})}catch(f){P.error({err:f},"agent stream error in prompt command"),this.broadcast({type:"error",data:{message:f instanceof Error?f.message:String(f)}})}finally{this.streaming=!1}break}case"skill_fork":this.broadcast({type:"system",data:{message:"Fork-mode skills are not yet supported in remote mode."}}),this.broadcast({type:"command_done",data:null});break}}async handleLocalUICommand(a,i){if(!this.agentHandle){this.broadcast({type:"command_done",data:null});return}switch(a){case"clear":this.agentHandle.conv=new O,this.agentHandle.activeSkills.clear(),this.agentHandle.toolFilter=null,this.broadcast({type:"clear",data:null}),this.broadcast({type:"command_done",data:null});break;case"compact":await this.handleCompact();break;case"plan":await this.handlePlan(i);break;case"resume":this.handleResume(i);break;case"rewind":this.broadcast({type:"system",data:{message:"Rewind is not yet supported in remote mode."}}),this.broadcast({type:"command_done",data:null});break;case"quit":this.broadcast({type:"system",data:{message:"Quit is not supported in remote mode. Close the browser tab."}}),this.broadcast({type:"command_done",data:null});break;case"skills":{let n=this.agentHandle.skillCatalog;if(!n)this.broadcast({type:"system",data:{message:"No skills loaded."}});else{let s=n.list();if(s.length===0)this.broadcast({type:"system",data:{message:"No skills found."}});else{let o=s.map(t=>` ${t.name}: ${t.description}`);this.broadcast({type:"system",data:{message:`Available skills (${String(s.length)}):
35
35
 
36
36
  ${o.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swifty.js/swifty",
3
- "version": "0.0.23",
3
+ "version": "0.0.24",
4
4
  "description": "Swifty — CLI coding agent",
5
5
  "keywords": [
6
6
  "ai",