@swifty.js/swifty 0.0.16 → 0.0.18

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 tn,h as rn}from"./chunk-4XCKINK4.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-RTOI4JAC.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-KSCFIYHH.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-ZM2V2A7B.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(`
@@ -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 Ci,A as fi,G as bi,I as ue,J as me,K as gi,L as de,M as hi,N as yi,O as xe,P as ve,Q as fe,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 Xe,aa as Ti,ba as zi,ca as _i,d as xt,da as Pi,ea as Ai,fa as Ri,ga as Oi,ha as Li,i as ri,ia as Mi,j as We,ja as Fi,k as Ze,ka as Ui,la as Ni,ma as Di,p as ci,r as pi,t as li,u as ui,v as mi,w as di,x as Ye,y as xi,z as vi}from"./chunk-FZUA4PEF.js";import{a as He,b as Za}from"./chunk-XBHVVB5A.js";import{b as Ka}from"./chunk-7IRGXEBO.js";import{a as oi,b as ti,h as J}from"./chunk-LC766IV2.js";import{a as M,d as Va,e as Qa,f as ce,g as Ge,h as ei,i as ai,j as pe,n as ii}from"./chunk-HXLSOWKW.js";import{e as Be,f as ni,g as si}from"./chunk-4XCKINK4.js";import"./chunk-FZPTNGTU.js";import{e as K}from"./chunk-RKJQNZWW.js";import{b as Ya,e as Ja}from"./chunk-YOZTZPFE.js";import"./chunk-7MHXMDYC.js";import{D as q,I as re,K as R,S as $e}from"./chunk-RTOI4JAC.js";import{a as le}from"./chunk-A3NIT2ZF.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 Qe=l((Ul,Ve)=>{"use strict";Ve.exports=gt;Ve.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 V=l((Il,Ji)=>{"use strict";var ea=Zi();Ji.exports=_;_.message=ea;_.code=Ct(ea);_.codes=Tt(ea);_.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 Ct(e){var a={};return Object.keys(e).forEach(function(n){var s=e[n],o=Number(n);a[s.toLowerCase()]=o}),a}function Tt(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 ia=l((Hl,en)=>{"use strict";var _t=x("path").relative;en.exports=Lt;var Pt=process.cwd();function Vi(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 Ot(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,I as ue,J as me,K as gi,L as de,M as hi,N as yi,O as xe,P as ve,Q as fe,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 Xe,aa as Ci,ba as Ti,ca as zi,d as xt,da as _i,ea as Pi,fa as Ai,ga as Ri,ha as Oi,i as ri,ia as Li,j as We,ja as Mi,k as Ze,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 Ye,y as xi,z as vi}from"./chunk-DTIGEOLN.js";import{a as He,b as Za}from"./chunk-XBHVVB5A.js";import{b as Ka}from"./chunk-3USGFIWF.js";import{a as oi,b as ti,h as J}from"./chunk-SUWMNSWK.js";import{a as M,d as Va,e as Qa,f as ce,g as Ge,h as ei,i as ai,j as pe,n as ii}from"./chunk-ASZMSWK5.js";import{e as Be,f as ni,g as si}from"./chunk-KSCFIYHH.js";import"./chunk-FZPTNGTU.js";import{e as K}from"./chunk-GM65WMIB.js";import{b as Ya,e as Ja}from"./chunk-P276SKAC.js";import"./chunk-7MHXMDYC.js";import{D as q,I as re,K as R,S as $e}from"./chunk-ZM2V2A7B.js";import{a as le}from"./chunk-4WQF4JIN.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 Qe=l((Ul,Ve)=>{"use strict";Ve.exports=gt;Ve.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 V=l((Il,Ji)=>{"use strict";var ea=Zi();Ji.exports=_;_.message=ea;_.code=Ct(ea);_.codes=Tt(ea);_.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 Ct(e){var a={};return Object.keys(e).forEach(function(n){var s=e[n],o=Number(n);a[s.toLowerCase()]=o}),a}function Tt(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 ia=l((Hl,en)=>{"use strict";var _t=x("path").relative;en.exports=Lt;var Pt=process.cwd();function Vi(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 Ot(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 Lt(e){if(!e)throw new TypeError("argument namespace is required");var a=ge(),i=$(a[1]),n=i[0];function s(o){be.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 Mt(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 Vi(a,e)}function Ut(e){if(process.traceDeprecation)return!0;var a=process.env.TRACE_DEPRECATION||"";return Vi(a,e)}function be(e,a){var i=Mt(process,"deprecation");if(!(!i&&this._ignored)){var n,s,o,t,r=0,c=!1,p=ge(),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?Ki(t):Ki(o)),i){var f=Qi(this._namespace,d,p.slice(r));process.emit("deprecation",f);return}var g=process.stderr.isTTY?Dt:Nt,C=g.call(this,d,n,p.slice(r));process.stderr.write(C+`
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 Ki(e){var a=e.callSite,i=e.name;i||(i="<anonymous@"+aa(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 "+aa(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=Me.Readable.from(i.stream()):i instanceof ReadableStream?s=Me.Readable.from(i):i instanceof Response?s=Me.Readable.from(i?.body||""):sl(i)&&(s=i),s)return Me.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 Cl}from"http";import{join as tt,extname as Tl,normalize as zl}from"path";import{cwd as ie}from"process";var Ma=dt(Wo(),1),Zo=Ma.default,Mu=Ma.default.HttpError;import{existsSync as Fa,statSync as Vo,readFileSync as Yo,writeFileSync as Qo,mkdirSync as rl,unlinkSync as cl,utimesSync as pl}from"fs";import{homedir as Jo}from"os";import{join as ae,basename as Ko}from"path";var et=re({module:"memory"}),ll=24,ul=5,ml=600*1e3,dl=".consolidate-lock",xl=3600*1e3,vl=200,Ue=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(!Fa(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(Jo(),".swifty","memory"),o=ae(this.workDir,".swifty","sessions"),t=wl(a,s,o,i),r=new le;r.register(new de),r.register(new fe),r.register(new me),r.register(new xe),r.register(new ve),r.register(new ue);let c=new K(this.workDir,"bypassPermissions");c.allowExtraRoot(ae(Jo(),".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());let d=kl(p.getMessages()).filter(f=>Ko(f)!=="MEMORY.md");if(d.length>0&&this.appendSystem){let f=d.map(g=>Ko(g));this.appendSystem(`Memory improved: ${f.join(", ")}`)}}};function Ua(e){return ae(e,dl)}function fl(e){let a=Ua(e);if(!Fa(a))return 0;try{return Vo(a).mtimeMs}catch{return 0}}function bl(e){let a=Ua(e),i,n;if(Fa(a))try{i=Vo(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=Ua(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 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 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}var Na=800;function jl(e){return e.length<=Na?e:`${e.slice(0,Na)}\u2026 (+${String(e.length-Na)} chars)`}var Ne=class{constructor(a){this.log=a}log;onEvent(a){switch(a.type){case"tool_result":{if(!a.isError)return;let i=R(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"),Ol={".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=Ol[Tl(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;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: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.ltmInstructions,memoryContent:this.ltmMemoryContent,notificationFn:()=>this.teamManager.drainLeads(),onPermissionRequest:i.onPermissionRequest,onLoopComplete:o=>{let t=o.getMessages().slice(-40).map(r=>`[${r.role}]: ${R(r.content)}`).filter(r=>r.length>12).join(`
23
23
  `);new Pi(this.client,this.workDir).extract(t).catch(()=>{}),new Ue(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 Ci(i,c),m=new gi,u=Ll(i,c),d=We(i);d.model=a.model;let f=Ze(d),g=await Xe(a,f),C=new M,ne=Be(a);ni(a).then(b=>{b>0&&(ne=b)}).catch(()=>{});let Ia=Ai(i),Ha=new _i(i),$a=Ha.buildSystemReminder();C.injectLongTermMemory(Ia,$a),C.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 Ti(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=>(C?.getMessages()??[]).slice(-b).map(j=>`${j.role}: ${R(j.content)}`).join(`
24
- `),runSubagent:async b=>{if(!g)throw new Error("no llm client (provider not initialized)");let{PermissionChecker:y}=await import("./checker-NVYS3GH6.js"),{Agent:j}=await import("./agent-3T6JNTAT.js"),k=new M;k.addUserMessage(b);let z=new j({client:g,registry:u,checker:new y(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 ji(se,oe,ct)),u.register(new Ni(r));let pt=(b,y)=>(j,k)=>Ye(ui[0],j,g,b,a,i,void 0,k,void 0,y),I=new bi(i);u.register(new ci(I)),u.register(new pi(I)),u.register(new li(I)),u.register(new fi(I)),u.register(new hi);let De=new mi(i,u,async(b,y,j,k,z)=>Ye(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,H=We(i);H.model=z;let Z=Ze(H),lt=k?await Xe({...a,model:z},Z):g,ut=new K(i,"acceptEdits");y.addUserMessage(b);let mt=new J({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-GWE2YS7P.js"),{Agent:j}=await import("./agent-QD6EMP2B.js"),k=new M;k.addUserMessage(b);let z=new j({client:g,registry:u,checker:new y(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 ji(se,oe,ct)),u.register(new Ni(r));let pt=(b,y)=>(j,k)=>Ye(ui[0],j,g,b,a,i,void 0,k,void 0,y),I=new bi(i);u.register(new ci(I)),u.register(new pi(I)),u.register(new li(I)),u.register(new fi(I)),u.register(new hi);let De=new mi(i,u,async(b,y,j,k,z)=>Ye(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,H=We(i);H.model=z;let Z=Ze(H),lt=k?await Xe({...a,model:z},Z):g,ut=new K(i,"acceptEdits");y.addUserMessage(b);let mt=new J({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]"});De.forkDisabled=t??!1,De.setTeamManager(I,pt),u.register(De);let Ie=Ke();for(let b of Si(i))try{Ie.register(b)}catch{}Ml(se,oe,Ie);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&&Ka(u,a.base_url,Be(a)),y.instructions.length>0&&(Wa=`# MCP Server Instructions
27
27
 
@@ -1,4 +1,4 @@
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{b as a,c as b,d as c,e as d,f as e,g as f,h as g}from"./chunk-A3NIT2ZF.js";import"./chunk-E55KH72M.js";import"./chunk-X3UA5OZL.js";export{d as ASYNC_AGENT_ALLOWED_TOOLS,c as CUSTOM_AGENT_DISALLOWED_TOOLS,f as FORK_QUERY_SOURCE,a as SUBAGENT_DISALLOWED_TOOLS,b as TEAMMATE_DISALLOWED_TOOLS,g as cloneRegistryForFork,e as filterToolsForAgent};
4
+ import{b as a,c as b,d as c,e as d,f as e,g as f,h as g}from"./chunk-4WQF4JIN.js";import"./chunk-E55KH72M.js";import"./chunk-X3UA5OZL.js";export{d as ASYNC_AGENT_ALLOWED_TOOLS,c as CUSTOM_AGENT_DISALLOWED_TOOLS,f as FORK_QUERY_SOURCE,a as SUBAGENT_DISALLOWED_TOOLS,b as TEAMMATE_DISALLOWED_TOOLS,g as cloneRegistryForFork,e as filterToolsForAgent};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swifty.js/swifty",
3
- "version": "0.0.16",
3
+ "version": "0.0.18",
4
4
  "description": "Swifty — CLI coding agent",
5
5
  "keywords": [
6
6
  "ai",
@@ -79,8 +79,8 @@
79
79
  "typescript": "^5.9.3",
80
80
  "typescript-eslint": "^8.65.0",
81
81
  "vitest": "^4.1.10",
82
- "@swifty.js/marked-terminal": "^0.0.1",
83
- "@swifty.js/glob-wasm": "0.0.1"
82
+ "@swifty.js/glob-wasm": "0.0.1",
83
+ "@swifty.js/marked-terminal": "^0.0.1"
84
84
  },
85
85
  "scripts": {
86
86
  "fe:dev": "cd src/remote/fe && tsup --watch",
@@ -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 as $}from"./chunk-7IRGXEBO.js";import{g as P}from"./chunk-H7VXSMJR.js";import{k as C}from"./chunk-HXLSOWKW.js";import{e as H,g as Y,h as R}from"./chunk-4XCKINK4.js";import{b as N,c as K,d as M,e as W,f as F,g as G}from"./chunk-FZPTNGTU.js";import"./chunk-YOZTZPFE.js";import"./chunk-7MHXMDYC.js";import{C as w,I as O,J as v,K as j,L as B,M as I,N as _,O as U,g as S}from"./chunk-RTOI4JAC.js";import"./chunk-E55KH72M.js";import"./chunk-X3UA5OZL.js";function D(o){return o.some(e=>e.defer_loading)}var x=O({module:"llm"});var J=3e3,z=w.object({max_input_tokens:w.coerce.number()});async function ct(o){if(o.protocol!=="anthropic")return 0;let e=R(o),n=`${o.base_url.replace(/\/+$/,"")}/v1/models/${encodeURIComponent(o.model)}`,s=new AbortController,r=setTimeout(()=>{s.abort()},J);try{let l=await fetch(n,{method:"GET",headers:{"anthropic-version":"2023-06-01",...e?{"x-api-key":e}:{}},signal:s.signal});if(!l.ok)return 0;let h=await l.json(),{success:g,error:f,data:d}=await S(z,h);if(!g)return x.warn({message:f.message},"model context window schema validation failed"),0;let k=d.max_input_tokens;return Math.max(k,0)}catch(l){return x.error({err:l},"failed to fetch model context window"),0}finally{clearTimeout(r)}}function V(){return!0}function E(o){return typeof o=="string"?[{type:"text",text:o}]:o}function Q(o){let e=[];for(let t of o)if(t.role==="assistant"){let n=[];if(t.thinkingBlocks)for(let r of t.thinkingBlocks)n.push({type:"thinking",thinking:r.thinking,signature:r.signature});let s=typeof t.content=="string"?t.content:j(t.content);if(s&&n.push({type:"text",text:s}),t.toolUses)for(let r of t.toolUses)n.push({type:"tool_use",id:r.toolUseId,name:r.toolName,input:r.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 s of t.toolResults)n.push({type:"tool_result",tool_use_id:s.toolUseId,is_error:s.isError,content:s.content});e.push({role:"user",content:n})}else{if(e.length===0){e.push({role:"user",content:E(t.content)});continue}let n=!1,s=e[e.length-1],r=s.content;s.role==="user"&&(typeof r=="string"||Array.isArray(r)&&r.length>0&&(r[0].type==="text"||r[0].type==="image"))&&(n=!0),n?(typeof r=="string"&&(r=s.content=r.trim().length>0?[{type:"text",text:r}]:[]),r.push(...E(t.content))):e.push({role:"user",content:E(t.content)})}return e}var q=class{client;model;thinking;systemPrompt;maxOutputTokens;contextWindow;constructor(e,t){let n=R(e);if(!n)throw new M("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=Y(e),this.contextWindow=H(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,n){let s=Q(N(e.getMessages())),r=D(t),l=t.map(c=>{let p=c.input_schema,u={name:c.name,description:c.description,input_schema:{type:"object",properties:p.properties,required:p.required??[]}};return c.defer_loading===!0&&(u.defer_loading=!0),u});l.length>0&&(l[l.length-1].cache_control={type:"ephemeral"}),X(s);let h={model:this.model,max_tokens:this.maxOutputTokens,stream:!0,system:[{type:"text",text:this.systemPrompt,cache_control:{type:"ephemeral"}}],messages:s,...l.length>0?{tools:l}:{}};this.thinking?V()&&(h.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)}):h.thinking={type:"enabled",budget_tokens:C(this.contextWindow,this.maxOutputTokens)};let g=0,f=0,d=0,k=0,L="end_turn",T="",b="",A=!1;try{let c=this.client.messages.stream(h,{...n?{signal:n}:{},...r?{headers:{"anthropic-beta":$}}:{}}),p="",u="",m="";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"&&(u=a.id,p=a.name,m="",yield{type:"tool_call_start",toolName:p,toolId:u});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"?b=a.signature:a.type==="text_delta"?yield{type:"text_delta",text:a.text}:a.type==="input_json_delta"&&(m+=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(m)try{let y=JSON.parse(m);a=B(y)?I(y):{[v]:m}}catch(y){x.error({err:y},"llm operation failed"),a={[v]:m}}yield{type:"tool_call_complete",toolId:u,toolName:p,arguments:a},p="",u="",m=""}break}case"message_delta":{i.delta.stop_reason&&(L=i.delta.stop_reason),i.usage.output_tokens&&(f=i.usage.output_tokens,i.usage.input_tokens&&(g=i.usage.input_tokens),i.usage.cache_read_input_tokens&&(d=i.usage.cache_read_input_tokens),i.usage.cache_creation_input_tokens&&(k=i.usage.cache_creation_input_tokens));break}case"message_start":{g=i.message.usage.input_tokens,f=i.message.usage.output_tokens,d=i.message.usage.cache_read_input_tokens??0,k=i.message.usage.cache_creation_input_tokens??0;break}}yield{type:"stream_end",stopReason:L,usage:{inputTokens:g,outputTokens:f,cacheReadInputTokens:d,cacheCreationInputTokens:k}}}catch(c){throw x.error({err:c},"llm operation failed"),Z(c)}}};function X(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 s=t.length-1;s>=0;s--)if(t[s].type!=="image"){n=t[s];break}Reflect.set(n,"cache_control",{type:"ephemeral"})}}function Z(o){if(o instanceof P.APIError){if(o.status===413||/prompts?\s+too\s+long/i.test(o.message))return new G(`Prompt too long: ${o.message}`);if(o.status===401)return new M(`Invalid API key: ${o.message}`);if(o.status===429){let e=I(o.headers)["retry-after"],t="Rate Limited";if(e){let n=Number.parseInt(_(e));Number.isNaN(n)&&(t+=", please wait."),t+=`, retry after ${_(n)}s.`}else t+=", please wait.";return new W(t,e?_(e):void 0)}return new K(`Anthropic API error (${_(o.status)}): ${o.message}`)}return new F(`Network error: ${U(o)}`)}export{q as AnthropicClient,Q as buildAnthropicMessages,ct as fetchModelContextWindow,X as markLastUserTailForCache,D as needsToolSearchBeta};
@@ -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 as x}from"./chunk-7MHXMDYC.js";import{C as o,I as S,b as u,c as m}from"./chunk-RTOI4JAC.js";import{existsSync as E,readFileSync as $}from"fs";import{homedir as I}from"os";import{join as l}from"path";function p(e){return!!e._zod}function c(e,n){return p(e)?u(e,n):e.safeParse(n)}async function ee(e,n){return p(e)?await m(e,n):await e.safeParseAsync(n)}function oe(e){if(!e)return;let n;if(p(e)?n=e._zod?.def?.shape:n=e.shape,!!n){if(typeof n=="function")try{return n()}catch{return}return n}}function ne(e){if(p(e)){let s=e._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let r=e.value;if(r!==void 0)return r}var g=S({module:"config"}),A={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY","openai-compat":"OPENAI_API_KEY"};function N(e){return _.has(e)}var _=new Set(Object.keys(A)),d=class extends Error{constructor(n){super(n),this.name="ConfigError"}},P=o.object({name:o.string(),protocol:o.enum(["anthropic","openai","openai-compat"]),base_url:o.string(),model:o.string(),api_key:o.string().optional(),thinking:o.boolean().optional(),context_window:o.coerce.number().optional(),max_output_tokens:o.coerce.number().optional()}),V=[["1m",1e6],["gpt-4.1",1e6],["gpt-4o",128e3],["gpt-4-turbo",128e3],["o1",2e5],["o3",2e5],["o4",2e5],["gpt-3.5",16385],["claude",2e5]];function j(e){let n=e.toLowerCase();for(let[t,r]of V)if(n.includes(t))return r;return n.includes("claude")?2e5:128e3}function de(e){return e.context_window&&e.context_window>0?e.context_window:j(e.model)}var w=new Map;async function pe(e,n){if(e.context_window&&e.context_window>0)return e.context_window;if(e.protocol==="anthropic"){let t=`${e.name}-${e.model}`,r=w.get(t);if(r===void 0){try{r=await(n??(await import("./anthropic-3NHEY4SF.js")).fetchModelContextWindow)(e)}catch(i){g.error({err:i},"config operation failed"),r=0}w.set(t,r)}if(r&&r>0)return r}return j(e.model)}function ue(e){return e.max_output_tokens&&e.max_output_tokens>0?e.max_output_tokens:e.thinking?64e3:8192}function me(e){if(e.api_key)return e.api_key;let n=N(e.protocol)?A[e.protocol]:"";return n?process.env[n]??"":""}var O=o.object({name:o.string(),command:o.string().optional(),args:o.array(o.string()).optional(),url:o.string().optional(),transport:o.string().optional(),headers:o.record(o.string(),o.string()).optional(),env:o.record(o.string(),o.string()).optional()}),z=o.object({id:o.string().optional(),event:o.string(),condition:o.string().optional(),action:o.object({type:o.string(),command:o.string().optional(),url:o.string().optional(),method:o.string().optional(),prompt:o.string().optional()}),reject:o.boolean().optional(),once:o.boolean().optional(),async:o.boolean().optional(),on_error:o.string().optional()}),M=o.object({enabled:o.boolean().optional(),auto_allow:o.boolean().optional(),network_enabled:o.boolean().optional()}),T=o.looseObject({providers:o.array(P),permission_mode:o.string().optional(),mcp_servers:o.array(O).default([]),hooks:o.array(z).default([]),sandbox:M.optional(),enable_coordinator_mode:o.boolean().optional(),enable_fork:o.boolean().optional()});function ge(e){return e.enable_fork!==!1}function Y(e){return typeof e=="object"&&e!==null}function C(e){let n=$(e,"utf-8"),t=x.load(n);if(!Y(t))return g.error({path:e},"invalid yaml"),{providers:[],mcp_servers:[],hooks:[]};let r=c(T,t);if(r.success){let a=r.data;return{providers:a.providers,permission_mode:a.permission_mode,mcp_servers:a.mcp_servers,hooks:a.hooks}}g.error({error:r.error},"config error");let i=[],s,f=[],y=[],v,b=!1,h=!0;if("providers"in t){let a=c(o.array(P),t.providers);a.success&&(i=a.data)}if("permission_mode"in t&&typeof t.permission_mode=="string"&&(s=t.permission_mode),"mcp_servers"in t){let a=c(o.array(O),t.mcp_servers);a.success&&(f=a.data)}if("hooks"in t){let a=c(o.array(z),t.hooks);a.success&&(y=a.data)}if("sandbox"in t){let a=c(M,t.sandbox);a.success&&(v=a.data)}return"enable_coordinator_mode"in t&&(b=!!t.enable_coordinator_mode),"enable_fork"in t&&(h=!!t.enable_fork),{providers:i,permission_mode:s,mcp_servers:f,hooks:y,sandbox:v,enable_coordinator_mode:b,enable_fork:h}}function K(e,n){if(n.providers.length>0&&(e.providers=n.providers),n.permission_mode&&(e.permission_mode=n.permission_mode),n.mcp_servers.length>0){let t=new Map;for(let r=0;r<e.mcp_servers.length;r++){let i=e.mcp_servers[r];t.set(i.name,r)}for(let r of n.mcp_servers){let i=t.get(r.name);i!==void 0?e.mcp_servers[i]=r:(e.mcp_servers.push(r),t.set(r.name,e.mcp_servers.length-1))}}return e.hooks=[...e.hooks,...n.hooks],n.sandbox&&(e.sandbox={...e.sandbox,...n.sandbox}),n.enable_coordinator_mode&&(e.enable_coordinator_mode=!0),n.enable_fork!==void 0&&(e.enable_fork=n.enable_fork),e}function k(e){if(e.providers.length===0)throw new d("At least one provider MUST be configured.");let n=["name","protocol","base_url","model"];for(let t=0;t<e.providers.length;t++){let r=e.providers[t],i={name:r.name,protocol:r.protocol,base_url:r.base_url,model:r.model},s=n.filter(f=>!(f in i));if(s.length>0)throw new d(`Provider #${String(t+1)}: missing fields: ${s.join(", ")}`);if(!_.has(r.protocol))throw new d(`Provider #${String(t+1)}: invalid protocol '${r.protocol}', MUST be one of: ${Array.from(_).join(", ")}`)}}function _e(e){if(e){let s=C(e);return k(s),s}let n=process.cwd(),t=I(),r=[l(t,".swifty","config.yml"),l(t,".swifty","config.yaml"),l(n,".swifty","config.yml"),l(n,".swifty","config.yaml"),l(n,".swifty","config.local.yml"),l(n,".swifty","config.local.yaml")],i=null;for(let s of r){if(!E(s))continue;let f=C(s);i?i=K(i,f):i=f}if(!i)throw new d("No config file found, expected .swifty/config.y(a)ml under project or $HOME/.swifty/config.y(a)ml.");return k(i),i}export{c as a,ee as b,oe as c,ne as d,de as e,pe as f,ue as g,me as h,ge as i,_e as j};
@@ -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 as T,b as f}from"./chunk-E55KH72M.js";var c=class{tools=new Map;discovered=new Set;mcpLoadingMode="eager";exposeToolSearch=!1;exposeMcpCall=!1;register(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}listTools(){return[...this.tools.values()]}getAllSchemas(e="anthropic"){let o=e==="openai"||e==="openai-compat",t=this.mcpLoadingMode==="native"&&!o,n=[];for(let s of this.tools.values()){if(s.name===T&&!this.exposeToolSearch||s.name===f&&!this.exposeMcpCall)continue;let i=!!s.deferred&&!this.discovered.has(s.name);if(i&&!t)continue;let r=s.schema();o?n.push({strict:!1,type:"function",name:r.name,description:r.description,parameters:r.input_schema,function:{name:r.name,description:r.description,parameters:r.input_schema}}):n.push(i?{...r,type:"custom",defer_loading:!0}:{...r,type:"custom"})}return n}getDeferredToolNames(){let e=[];for(let o of this.tools.values())o.deferred&&!this.discovered.has(o.name)&&e.push(o.name);return e}getDeferredTools(){return[...this.tools.values()].filter(e=>e.deferred&&!this.discovered.has(e.name))}searchDeferred(e,o=5){let t=e.toLowerCase(),n=[];for(let s of this.tools.values())if(!(!s.deferred||this.discovered.has(s.name))&&(s.name.toLowerCase().includes(t)||s.description.toLowerCase().includes(t))&&(n.push(s),n.length>=o))break;return n}findDeferredByNames(e){let o=new Map;for(let[t,n]of this.tools)o.set(t.toLowerCase(),n);return e.map(t=>o.get(t.toLowerCase())).filter(t=>t?.deferred??!1)}markDiscovered(e){this.discovered.add(e)}isDiscovered(e){return this.discovered.has(e)}};var h=new Set(["ExitPlanMode","Agent","AskUserQuestion","TaskStop"]),M=new Set(["TeamCreate","TeamDelete"]),m=new Set(["ExitPlanMode","Agent","AskUserQuestion","TaskStop"]),u=new Set(["ReadFile","Grep","Glob","Bash","EditFile","WriteFile","LoadSkill","SyntheticOutput","ToolSearch","EnterWorktree","ExitWorktree","McpCall"]);function g(a){return a.startsWith("mcp__")}function k(a,e,o,t,n=!1){let s=new Set(o??[]),i=new Set(e??[]),r=i.size>0&&!(i.size===1&&i.has("*")),p=new c;for(let d of a.listTools()){let l=d.name;if(g(l)){p.register(d);continue}h.has(l)||n&&m.has(l)||t&&!u.has(l)||s.has(l)||r&&!i.has(l)||p.register(d)}return p}var A="agent:builtin:fork";function E(a){let e=new c;for(let o of a.listTools())if(o.name==="Agent"&&"querySource"in o){let t=Object.create(Object.getPrototypeOf(o),Object.getOwnPropertyDescriptors(o));t.querySource=A,e.register(t)}else e.register(o);return e}export{c as a,h as b,M as c,m as d,u as e,k as f,A as g,E as h};