diff --git a/plugin/scripts/add-memory.cjs b/plugin/scripts/add-memory.cjs index c61ff24..330c83b 100755 --- a/plugin/scripts/add-memory.cjs +++ b/plugin/scripts/add-memory.cjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -var Se=Object.defineProperty;var Gr=Object.getOwnPropertyDescriptor;var Kr=Object.getOwnPropertyNames;var kr=Object.prototype.hasOwnProperty;var Er=(e,t)=>()=>(e&&(t=e(e=0)),t);var c=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ir=(e,t)=>{for(var r in t)Se(e,r,{get:t[r],enumerable:!0})},Cr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Kr(t))!kr.call(e,s)&&s!==r&&Se(e,s,{get:()=>t[s],enumerable:!(n=Gr(t,s))||n.enumerable});return e};var Jr=e=>Cr(Se({},"__esModule",{value:!0}),e);var ke=c(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=Br;h.__classPrivateFieldGet=Ar;h.__importStar=Qr;h.__exportStar=_r;function Br(e,t,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(e,r):s?s.value=r:t.set(e,r),r}function Ar(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var Ke=Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]};h.__createBinding=Ke;var Ut=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};h.__setModuleDefault=Ut;var Ge=function(e){return Ge=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Ge(e)};function Qr(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Ge(e),n=0;n{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.uuid4=void 0;var $r=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Y.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};Y.uuid4=$r});var Ee=c(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=en;function en(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var tn=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};S.castToError=tn});var K=c(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.InternalServerError=P.RateLimitError=P.UnprocessableEntityError=P.ConflictError=P.NotFoundError=P.PermissionDeniedError=P.AuthenticationError=P.BadRequestError=P.APIConnectionTimeoutError=P.APIConnectionError=P.APIUserAbortError=P.APIError=P.SupermemoryError=void 0;var rn=Ee(),oe=class extends Error{};P.SupermemoryError=oe;var O=class e extends oe{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(t,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new G({message:n,cause:(0,rn.castToError)(r)});let o=r;return t===400?new ae(t,o,n,s):t===401?new fe(t,o,n,s):t===403?new ie(t,o,n,s):t===404?new ce(t,o,n,s):t===409?new ue(t,o,n,s):t===422?new de(t,o,n,s):t===429?new ve(t,o,n,s):t>=500?new le(t,o,n,s):new e(t,o,n,s)}};P.APIError=O;var Ie=class extends O{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};P.APIUserAbortError=Ie;var G=class extends O{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};P.APIConnectionError=G;var Ce=class extends G{constructor({message:t}={}){super({message:t??"Request timed out."})}};P.APIConnectionTimeoutError=Ce;var ae=class extends O{};P.BadRequestError=ae;var fe=class extends O{};P.AuthenticationError=fe;var ie=class extends O{};P.PermissionDeniedError=ie;var ce=class extends O{};P.NotFoundError=ce;var ue=class extends O{};P.ConflictError=ue;var de=class extends O{};P.UnprocessableEntityError=de;var ve=class extends O{};P.RateLimitError=ve;var le=class extends O{};P.InternalServerError=le});var E=c(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.safeJSON=d.maybeCoerceBoolean=d.maybeCoerceFloat=d.maybeCoerceInteger=d.coerceBoolean=d.coerceFloat=d.coerceInteger=d.validatePositiveInteger=d.ensurePresent=d.isReadonlyArray=d.isArray=d.isAbsoluteURL=void 0;d.maybeObj=an;d.isEmptyObj=fn;d.hasOwn=cn;d.isObj=un;var k=K(),nn=/^[a-z][a-z0-9+.-]*:/i,sn=e=>nn.test(e);d.isAbsoluteURL=sn;var on=e=>(d.isArray=Array.isArray,(0,d.isArray)(e));d.isArray=on;d.isReadonlyArray=d.isArray;function an(e){return typeof e!="object"?{}:e??{}}function fn(e){if(!e)return!0;for(let t in e)return!1;return!0}function cn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function un(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var dn=e=>{if(e==null)throw new k.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};d.ensurePresent=dn;var vn=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new k.SupermemoryError(`${e} must be an integer`);if(t<0)throw new k.SupermemoryError(`${e} must be a positive integer`);return t};d.validatePositiveInteger=vn;var ln=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};d.coerceInteger=ln;var Pn=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};d.coerceFloat=Pn;var pn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;d.coerceBoolean=pn;var zn=e=>{if(e!=null)return(0,d.coerceInteger)(e)};d.maybeCoerceInteger=zn;var mn=e=>{if(e!=null)return(0,d.coerceFloat)(e)};d.maybeCoerceFloat=mn;var bn=e=>{if(e!=null)return(0,d.coerceBoolean)(e)};d.maybeCoerceBoolean=bn;var xn=e=>{try{return JSON.parse(e)}catch{return}};d.safeJSON=xn});var St=c(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.sleep=void 0;var jn=e=>new Promise(t=>setTimeout(t,e));Pe.sleep=jn});var Je=c(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.VERSION=void 0;pe.VERSION="4.0.0"});var Et=c(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.getPlatformHeaders=w.isRunningInBrowser=void 0;var I=Je(),Xn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";w.isRunningInBrowser=Xn;function On(){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 yn=()=>{let e=On();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":Kt(Deno.build.os),"X-Stainless-Arch":Gt(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":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":Kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Gt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=qn();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function qn(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:t,version:`${s}.${o}.${a}`}}}return null}var Gt=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Kt=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),kt,Hn=()=>kt??(kt=yn());w.getPlatformHeaders=Hn});var Be=c(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=hn;V.makeReadableStream=It;V.ReadableStreamFrom=Wn;V.ReadableStreamToAsyncIterable=Tn;V.CancelReadableStream=Nn;function hn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function It(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Wn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return It({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function Tn(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Nn(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var Ct=c(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.FallbackEncoder=void 0;var Ln=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});ze.FallbackEncoder=Ln});var C=c(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.createForm=x.multipartFormRequestOptions=x.maybeMultipartFormRequestOptions=x.isAsyncIterable=x.checkFileSupport=void 0;x.makeFile=Ae;x.getName=me;var Vn=Be(),Rn=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};x.checkFileSupport=Rn;function Ae(e,t,r){return(0,x.checkFileSupport)(),new File(e,t??"unknown_file",r)}function me(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var gn=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";x.isAsyncIterable=gn;var wn=async(e,t)=>Qe(e.body)?{...e,body:await(0,x.createForm)(e.body,t)}:e;x.maybeMultipartFormRequestOptions=wn;var Zn=async(e,t)=>({...e,body:await(0,x.createForm)(e.body,t)});x.multipartFormRequestOptions=Zn;var Jt=new WeakMap;function Mn(e){let t=typeof e=="function"?e:e.fetch,r=Jt.get(t);if(r)return r;let n=(async()=>{try{let s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Jt.set(t,n),n}var Fn=async(e,t)=>{if(!await Mn(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,s])=>_e(r,n,s))),r};x.createForm=Fn;var Bt=e=>e instanceof Blob&&"name"in e,Dn=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,x.isAsyncIterable)(e)||Bt(e)),Qe=e=>{if(Dn(e))return!0;if(Array.isArray(e))return e.some(Qe);if(e&&typeof e=="object"){for(let t in e)if(Qe(e[t]))return!0}return!1},_e=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,Ae([await r.blob()],me(r)));else if((0,x.isAsyncIterable)(r))e.append(t,Ae([await new Response((0,Vn.ReadableStreamFrom)(r)).blob()],me(r)));else if(Bt(r))e.append(t,r,me(r));else if(Array.isArray(r))await Promise.all(r.map(n=>_e(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>_e(e,`${t}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var Qt=c(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.toFile=Gn;var J=C(),Un=C(),At=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",Yn=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&At(e),Sn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Gn(e,t,r){if((0,Un.checkFileSupport)(),e=await e,Yn(e))return e instanceof File?e:(0,J.makeFile)([await e.arrayBuffer()],e.name);if(Sn(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,J.makeFile)(await $e(s),t,r)}let n=await $e(e);if(t||(t=(0,J.getName)(e)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,J.makeFile)(n,t,r)}async function $e(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(At(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,J.isAsyncIterable)(e))for await(let r of e)t.push(...await $e(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Kn(e)}`)}return t}function Kn(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var tt=c(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.toFile=void 0;var kn=Qt();Object.defineProperty(be,"toFile",{enumerable:!0,get:function(){return kn.toFile}})});var Z=c(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.APIResource=void 0;var rt=class{constructor(t){this._client=t}};xe.APIResource=rt});var B=c(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.isEmptyHeaders=M.buildHeaders=void 0;var _t=E(),$t=Symbol("brand.privateNullableHeaders");function*er(e){if(!e)return;if($t in e){let{values:n,nulls:s}=e;yield*n.entries();for(let o of s)yield[o,null];return}let t=!1,r;e instanceof Headers?r=e.entries():(0,_t.isReadonlyArray)(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,_t.isReadonlyArray)(n[1])?n[1]:[n[1]],a=!1;for(let f of o)f!==void 0&&(t&&!a&&(a=!0,yield[s,null]),yield[s,f])}}var En=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,a]of er(n)){let f=o.toLowerCase();s.has(f)||(t.delete(o),s.add(f)),a===null?(t.delete(o),r.add(f)):(t.append(o,a),r.delete(f))}}return{[$t]:!0,values:t,nulls:r}};M.buildHeaders=En;var In=e=>{for(let t of er(e))return!1;return!0};M.isEmptyHeaders=In});var je=c(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=nt;var Cn=K();function nt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var tr=Object.freeze(Object.create(null)),Jn=(e=nt)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((l,m,X)=>{/[?#]/.test(m)&&(s=!0);let i=n[X],H=(s?encodeURIComponent:e)(""+i);return X!==n.length&&(i==null||typeof i=="object"&&i.toString===Object.getPrototypeOf(Object.getPrototypeOf(i.hasOwnProperty??tr)??tr)?.toString)&&(H=i+"",o.push({start:l.length+m.length,length:H.length,error:`Value of type ${Object.prototype.toString.call(i).slice(8,-1)} is not a valid path parameter`})),l+m+(X===n.length?"":H)},""),f=a.split(/[?#]/,1)[0],z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,v;for(;(v=z.exec(f))!==null;)o.push({start:v.index,length:v[0].length,error:`Value "${v[0]}" can't be safely passed as a path parameter`});if(o.sort((l,m)=>l.start-m.start),o.length>0){let l=0,m=o.reduce((X,i)=>{let H=" ".repeat(i.start-l),D="^".repeat(i.length);return l=i.start+i.length,X+H+D},"");throw new Cn.SupermemoryError(`Path parameters result in path with invalid segments: +var Ge=Object.defineProperty;var Kr=Object.getOwnPropertyDescriptor;var kr=Object.getOwnPropertyNames;var Er=Object.prototype.hasOwnProperty;var Ir=(e,t)=>()=>(e&&(t=e(e=0)),t);var c=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Cr=(e,t)=>{for(var r in t)Ge(e,r,{get:t[r],enumerable:!0})},Jr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of kr(t))!Er.call(e,s)&&s!==r&&Ge(e,s,{get:()=>t[s],enumerable:!(n=Kr(t,s))||n.enumerable});return e};var Br=e=>Jr(Ge({},"__esModule",{value:!0}),e);var Ee=c(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=Ar;h.__classPrivateFieldGet=Qr;h.__importStar=_r;h.__exportStar=$r;function Ar(e,t,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(e,r):s?s.value=r:t.set(e,r),r}function Qr(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var ke=Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]};h.__createBinding=ke;var Yt=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};h.__setModuleDefault=Yt;var Ke=function(e){return Ke=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Ke(e)};function _r(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Ke(e),n=0;n{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.uuid4=void 0;var en=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Y.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};Y.uuid4=en});var Ie=c(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=tn;function tn(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var rn=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};S.castToError=rn});var K=c(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.InternalServerError=P.RateLimitError=P.UnprocessableEntityError=P.ConflictError=P.NotFoundError=P.PermissionDeniedError=P.AuthenticationError=P.BadRequestError=P.APIConnectionTimeoutError=P.APIConnectionError=P.APIUserAbortError=P.APIError=P.SupermemoryError=void 0;var nn=Ie(),oe=class extends Error{};P.SupermemoryError=oe;var O=class e extends oe{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(t,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new G({message:n,cause:(0,nn.castToError)(r)});let o=r;return t===400?new ae(t,o,n,s):t===401?new fe(t,o,n,s):t===403?new ie(t,o,n,s):t===404?new ce(t,o,n,s):t===409?new ue(t,o,n,s):t===422?new de(t,o,n,s):t===429?new ve(t,o,n,s):t>=500?new le(t,o,n,s):new e(t,o,n,s)}};P.APIError=O;var Ce=class extends O{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};P.APIUserAbortError=Ce;var G=class extends O{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};P.APIConnectionError=G;var Je=class extends G{constructor({message:t}={}){super({message:t??"Request timed out."})}};P.APIConnectionTimeoutError=Je;var ae=class extends O{};P.BadRequestError=ae;var fe=class extends O{};P.AuthenticationError=fe;var ie=class extends O{};P.PermissionDeniedError=ie;var ce=class extends O{};P.NotFoundError=ce;var ue=class extends O{};P.ConflictError=ue;var de=class extends O{};P.UnprocessableEntityError=de;var ve=class extends O{};P.RateLimitError=ve;var le=class extends O{};P.InternalServerError=le});var E=c(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.safeJSON=d.maybeCoerceBoolean=d.maybeCoerceFloat=d.maybeCoerceInteger=d.coerceBoolean=d.coerceFloat=d.coerceInteger=d.validatePositiveInteger=d.ensurePresent=d.isReadonlyArray=d.isArray=d.isAbsoluteURL=void 0;d.maybeObj=fn;d.isEmptyObj=cn;d.hasOwn=un;d.isObj=dn;var k=K(),sn=/^[a-z][a-z0-9+.-]*:/i,on=e=>sn.test(e);d.isAbsoluteURL=on;var an=e=>(d.isArray=Array.isArray,(0,d.isArray)(e));d.isArray=an;d.isReadonlyArray=d.isArray;function fn(e){return typeof e!="object"?{}:e??{}}function cn(e){if(!e)return!0;for(let t in e)return!1;return!0}function un(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function dn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var vn=e=>{if(e==null)throw new k.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};d.ensurePresent=vn;var ln=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new k.SupermemoryError(`${e} must be an integer`);if(t<0)throw new k.SupermemoryError(`${e} must be a positive integer`);return t};d.validatePositiveInteger=ln;var Pn=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};d.coerceInteger=Pn;var pn=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};d.coerceFloat=pn;var zn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;d.coerceBoolean=zn;var mn=e=>{if(e!=null)return(0,d.coerceInteger)(e)};d.maybeCoerceInteger=mn;var bn=e=>{if(e!=null)return(0,d.coerceFloat)(e)};d.maybeCoerceFloat=bn;var xn=e=>{if(e!=null)return(0,d.coerceBoolean)(e)};d.maybeCoerceBoolean=xn;var jn=e=>{try{return JSON.parse(e)}catch{return}};d.safeJSON=jn});var Gt=c(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.sleep=void 0;var Xn=e=>new Promise(t=>setTimeout(t,e));Pe.sleep=Xn});var Be=c(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.VERSION=void 0;pe.VERSION="4.0.0"});var It=c(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.getPlatformHeaders=w.isRunningInBrowser=void 0;var I=Be(),On=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";w.isRunningInBrowser=On;function yn(){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 qn=()=>{let e=yn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":kt(Deno.build.os),"X-Stainless-Arch":Kt(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":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Kt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Hn();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Hn(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:t,version:`${s}.${o}.${a}`}}}return null}var Kt=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",kt=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),Et,hn=()=>Et??(Et=qn());w.getPlatformHeaders=hn});var Ae=c(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=Wn;V.makeReadableStream=Ct;V.ReadableStreamFrom=Tn;V.ReadableStreamToAsyncIterable=Nn;V.CancelReadableStream=Ln;function Wn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ct(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Tn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ct({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function Nn(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ln(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var Jt=c(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.FallbackEncoder=void 0;var Vn=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});ze.FallbackEncoder=Vn});var C=c(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.createForm=x.multipartFormRequestOptions=x.maybeMultipartFormRequestOptions=x.isAsyncIterable=x.checkFileSupport=void 0;x.makeFile=Qe;x.getName=me;var Rn=Ae(),gn=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};x.checkFileSupport=gn;function Qe(e,t,r){return(0,x.checkFileSupport)(),new File(e,t??"unknown_file",r)}function me(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var wn=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";x.isAsyncIterable=wn;var Zn=async(e,t)=>_e(e.body)?{...e,body:await(0,x.createForm)(e.body,t)}:e;x.maybeMultipartFormRequestOptions=Zn;var Mn=async(e,t)=>({...e,body:await(0,x.createForm)(e.body,t)});x.multipartFormRequestOptions=Mn;var Bt=new WeakMap;function Fn(e){let t=typeof e=="function"?e:e.fetch,r=Bt.get(t);if(r)return r;let n=(async()=>{try{let s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Bt.set(t,n),n}var Dn=async(e,t)=>{if(!await Fn(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,s])=>$e(r,n,s))),r};x.createForm=Dn;var At=e=>e instanceof Blob&&"name"in e,Un=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,x.isAsyncIterable)(e)||At(e)),_e=e=>{if(Un(e))return!0;if(Array.isArray(e))return e.some(_e);if(e&&typeof e=="object"){for(let t in e)if(_e(e[t]))return!0}return!1},$e=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,Qe([await r.blob()],me(r)));else if((0,x.isAsyncIterable)(r))e.append(t,Qe([await new Response((0,Rn.ReadableStreamFrom)(r)).blob()],me(r)));else if(At(r))e.append(t,r,me(r));else if(Array.isArray(r))await Promise.all(r.map(n=>$e(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>$e(e,`${t}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var _t=c(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.toFile=Kn;var J=C(),Yn=C(),Qt=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",Sn=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Qt(e),Gn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Kn(e,t,r){if((0,Yn.checkFileSupport)(),e=await e,Sn(e))return e instanceof File?e:(0,J.makeFile)([await e.arrayBuffer()],e.name);if(Gn(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,J.makeFile)(await et(s),t,r)}let n=await et(e);if(t||(t=(0,J.getName)(e)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,J.makeFile)(n,t,r)}async function et(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Qt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,J.isAsyncIterable)(e))for await(let r of e)t.push(...await et(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${kn(e)}`)}return t}function kn(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var rt=c(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.toFile=void 0;var En=_t();Object.defineProperty(be,"toFile",{enumerable:!0,get:function(){return En.toFile}})});var Z=c(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.APIResource=void 0;var nt=class{constructor(t){this._client=t}};xe.APIResource=nt});var B=c(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.isEmptyHeaders=M.buildHeaders=void 0;var $t=E(),er=Symbol("brand.privateNullableHeaders");function*tr(e){if(!e)return;if(er in e){let{values:n,nulls:s}=e;yield*n.entries();for(let o of s)yield[o,null];return}let t=!1,r;e instanceof Headers?r=e.entries():(0,$t.isReadonlyArray)(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,$t.isReadonlyArray)(n[1])?n[1]:[n[1]],a=!1;for(let f of o)f!==void 0&&(t&&!a&&(a=!0,yield[s,null]),yield[s,f])}}var In=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,a]of tr(n)){let f=o.toLowerCase();s.has(f)||(t.delete(o),s.add(f)),a===null?(t.delete(o),r.add(f)):(t.append(o,a),r.delete(f))}}return{[er]:!0,values:t,nulls:r}};M.buildHeaders=In;var Cn=e=>{for(let t of tr(e))return!1;return!0};M.isEmptyHeaders=Cn});var je=c(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=st;var Jn=K();function st(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var rr=Object.freeze(Object.create(null)),Bn=(e=st)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((l,m,X)=>{/[?#]/.test(m)&&(s=!0);let i=n[X],H=(s?encodeURIComponent:e)(""+i);return X!==n.length&&(i==null||typeof i=="object"&&i.toString===Object.getPrototypeOf(Object.getPrototypeOf(i.hasOwnProperty??rr)??rr)?.toString)&&(H=i+"",o.push({start:l.length+m.length,length:H.length,error:`Value of type ${Object.prototype.toString.call(i).slice(8,-1)} is not a valid path parameter`})),l+m+(X===n.length?"":H)},""),f=a.split(/[?#]/,1)[0],z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,v;for(;(v=z.exec(f))!==null;)o.push({start:v.index,length:v[0].length,error:`Value "${v[0]}" can't be safely passed as a path parameter`});if(o.sort((l,m)=>l.start-m.start),o.length>0){let l=0,m=o.reduce((X,i)=>{let H=" ".repeat(i.start-l),D="^".repeat(i.length);return l=i.start+i.length,X+H+D},"");throw new Jn.SupermemoryError(`Path parameters result in path with invalid segments: ${o.map(X=>X.error).join(` `)} ${a} -${m}`)}return a};N.createPathTagFunction=Jn;N.path=(0,N.createPathTagFunction)(nt)});var ot=c(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Connections=void 0;var Bn=Z(),An=B(),W=je(),st=class extends Bn.APIResource{create(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/connections/list",{body:t,...r})}configure(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/configure`,{body:r,...n})}deleteByID(t,r){return this._client.delete((0,W.path)`/v3/connections/${t}`,r)}deleteByProvider(t,r,n){return this._client.delete((0,W.path)`/v3/connections/${t}`,{body:r,...n})}getByID(t,r){return this._client.get((0,W.path)`/v3/connections/${t}`,r)}getByTag(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/connection`,{body:r,...n})}import(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/import`,{body:r,...n,headers:(0,An.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/documents`,{body:r,...n})}resources(t,r={},n){return this._client.get((0,W.path)`/v3/connections/${t}/resources`,{query:r,...n})}};Xe.Connections=st});var it=c(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Documents=void 0;var Qn=Z(),_n=B(),$n=C(),at=je(),ft=class extends Qn.APIResource{update(t,r={},n){return this._client.patch((0,at.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,at.path)`/v3/documents/${t}`,{...r,headers:(0,_n.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}batchAdd(t,r){return this._client.post("/v3/documents/batch",{body:t,...r})}deleteBulk(t={},r){return this._client.delete("/v3/documents/bulk",{body:t,...r})}get(t,r){return this._client.get((0,at.path)`/v3/documents/${t}`,r)}listProcessing(t){return this._client.get("/v3/documents/processing",t)}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,$n.multipartFormRequestOptions)({body:t,...r},this._client))}};Oe.Documents=ft});var dt=c(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Memories=void 0;var es=Z(),ts=B(),rs=C(),ct=je(),ut=class extends es.APIResource{update(t,r={},n){return this._client.patch((0,ct.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,ct.path)`/v3/documents/${t}`,{...r,headers:(0,ts.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}forget(t,r){return this._client.delete("/v4/memories",{body:t,...r})}get(t,r){return this._client.get((0,ct.path)`/v3/documents/${t}`,r)}updateMemory(t,r){return this._client.patch("/v4/memories",{body:t,...r})}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,rs.multipartFormRequestOptions)({body:t,...r},this._client))}};ye.Memories=ut});var lt=c(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Search=void 0;var ns=Z(),vt=class extends ns.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};qe.Search=vt});var pt=c(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Settings=void 0;var ss=Z(),Pt=class extends ss.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};He.Settings=Pt});var rr=c(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.Settings=q.Search=q.Memories=q.Documents=q.Connections=void 0;var os=ot();Object.defineProperty(q,"Connections",{enumerable:!0,get:function(){return os.Connections}});var as=it();Object.defineProperty(q,"Documents",{enumerable:!0,get:function(){return as.Documents}});var fs=dt();Object.defineProperty(q,"Memories",{enumerable:!0,get:function(){return fs.Memories}});var is=lt();Object.defineProperty(q,"Search",{enumerable:!0,get:function(){return is.Search}});var cs=pt();Object.defineProperty(q,"Settings",{enumerable:!0,get:function(){return cs.Settings}})});var zt=c(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=sr;var us=E(),We={off:0,error:200,warn:300,info:400,debug:500},ds=(e,t,r)=>{if(e){if((0,us.hasOwn)(We,e))return e;sr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(We))}`)}};R.parseLogLevel=ds;function A(){}function he(e,t,r){return!t||We[e]>We[r]?A:t[e].bind(t)}var vs={error:A,warn:A,info:A,debug:A},nr=new WeakMap;function sr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return vs;let n=nr.get(t);if(n&&n[0]===r)return n[1];let s={error:he("error",t,r),warn:he("warn",t,r),info:he("info",t,r),debug:he("debug",t,r)};return nr.set(t,[r,s]),s}var ls=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);R.formatRequestDetails=ls});var ar=c(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.defaultParseResponse=Ps;var or=zt();async function Ps(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,a=await(async()=>{if(r.status===204)return null;if(t.options.__binaryResponse)return r;let z=r.headers.get("content-type")?.split(";")[0]?.trim();return z?.includes("application/json")||z?.endsWith("+json")?await r.json():await r.text()})();return(0,or.loggerFor)(e).debug(`[${n}] response parsed`,(0,or.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var jt=c(Te=>{"use strict";var Q;Object.defineProperty(Te,"__esModule",{value:!0});Te.APIPromise=void 0;var bt=ke(),ps=ar(),xt=class e extends Promise{constructor(t,r,n=ps.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,Q.set(this,void 0),bt.__classPrivateFieldSet(this,Q,t,"f")}_thenUnwrap(t){return new e(bt.__classPrivateFieldGet(this,Q,"f"),this.responsePromise,async(r,n)=>t(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(bt.__classPrivateFieldGet(this,Q,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};Te.APIPromise=xt;Q=new WeakMap});var fr=c(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.readEnv=void 0;var zs=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};Ne.readEnv=zs});var Tt=c(Ve=>{"use strict";var ht,Wt,Le,ir;Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Supermemory=void 0;var L=ke(),ms=Yt(),Xt=E(),bs=St(),Ot=Ee(),xs=Et(),yt=L.__importStar(Be()),js=L.__importStar(Ct()),Xs=Je(),b=L.__importStar(K()),Os=L.__importStar(tt()),_=L.__importStar(rr()),ys=jt(),qs=ot(),Hs=it(),hs=dt(),Ws=lt(),Ts=pt(),qt=B(),Ht=fr(),j=zt(),Ns=E(),p=class{constructor({baseURL:t=(0,Ht.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Ht.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(ht.add(this),Le.set(this,void 0),this.memories=new _.Memories(this),this.documents=new _.Documents(this),this.search=new _.Search(this),this.settings=new _.Settings(this),this.connections=new _.Connections(this),r===void 0)throw new b.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:t||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??Wt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,j.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,j.parseLogLevel)((0,Ht.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??yt.getDefaultFetch(),L.__classPrivateFieldSet(this,Le,js.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,qt.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Object.entries(t).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new b.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Xs.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,ms.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,ht,"m",ir).call(this)&&n||this.baseURL,o=(0,Xt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,Ns.isEmptyObj)(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(s=>({method:t,path:r,...s})))}request(t,r=null){return new ys.APIPromise(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let s=await t,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:a,url:f,timeout:z}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(a,{url:f,options:s});let v="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if((0,j.loggerFor)(this).debug(`[${v}] sending request`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:f,options:s,headers:a.headers})),s.signal?.aborted)throw new b.APIUserAbortError;let X=new AbortController,i=await this.fetchWithTimeout(f,a,z,X).catch(Ot.castToError),H=Date.now();if(i instanceof globalThis.Error){let U=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let T=(0,Ot.isAbortError)(i)||/timed? ?out/i.test(String(i)+("cause"in i?String(i.cause):""));if(r)return(0,j.loggerFor)(this).info(`[${v}] connection ${T?"timed out":"failed"} - ${U}`),(0,j.loggerFor)(this).debug(`[${v}] connection ${T?"timed out":"failed"} (${U})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:H-m,message:i.message})),this.retryRequest(s,r,n??v);throw(0,j.loggerFor)(this).info(`[${v}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,j.loggerFor)(this).debug(`[${v}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:H-m,message:i.message})),T?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:i})}let D=`[${v}${l}] ${a.method} ${f} ${i.ok?"succeeded":"failed"} with status ${i.status} in ${H-m}ms`;if(!i.ok){let U=await this.shouldRetry(i);if(r&&U){let se=`retrying, ${r} attempts remaining`;return await yt.CancelReadableStream(i.body),(0,j.loggerFor)(this).info(`${D} - ${se}`),(0,j.loggerFor)(this).debug(`[${v}] response error (${se})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:H-m})),this.retryRequest(s,r,n??v,i.headers)}let T=U?"error; no more retries left":"error; not retryable";(0,j.loggerFor)(this).info(`${D} - ${T}`);let Mt=await i.text().catch(se=>(0,Ot.castToError)(se).message),Ft=(0,Xt.safeJSON)(Mt),Dt=Ft?void 0:Mt;throw(0,j.loggerFor)(this).debug(`[${v}] response error (${T})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,message:Dt,durationMs:Date.now()-m})),this.makeStatusError(i.status,Ft,Dt,i.headers)}return(0,j.loggerFor)(this).info(D),(0,j.loggerFor)(this).debug(`[${v}] response start`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:H-m})),{response:i,options:s,controller:X,requestLogID:v,retryOfRequestLogID:n,startTime:m}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:a,...f}=r||{};o&&o.addEventListener("abort",()=>s.abort());let z=setTimeout(()=>s.abort(),n),v=globalThis.ReadableStream&&f.body instanceof globalThis.ReadableStream||typeof f.body=="object"&&f.body!==null&&Symbol.asyncIterator in f.body,l={signal:s.signal,...v?{duplex:"half"}:{},method:"GET",...f};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,l)}finally{clearTimeout(z)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,s){let o,a=s?.get("retry-after-ms");if(a){let z=parseFloat(a);Number.isNaN(z)||(o=z)}let f=s?.get("retry-after");if(f&&!o){let z=parseFloat(f);Number.isNaN(z)?o=Date.parse(f)-Date.now():o=z*1e3}if(!(o&&0<=o&&o<60*1e3)){let z=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,z)}return await(0,bs.sleep)(o),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let o=r-t,a=Math.min(.5*Math.pow(2,o),8),f=1-Math.random()*.25;return a*f*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:s,path:o,query:a,defaultBaseURL:f}=n,z=this.buildURL(o,a,f);"timeout"in n&&(0,Xt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:v,body:l}=this.buildBody({options:n}),m=await this.buildHeaders({options:t,method:s,bodyHeaders:v,retryCount:r});return{req:{method:s,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:z,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let a=(0,qt.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...(0,xs.getPlatformHeaders)()},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,qt.buildHeaders)([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:yt.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Le,"f").call(this,{body:t,headers:n})}};Ve.Supermemory=p;Wt=p,Le=new WeakMap,ht=new WeakSet,ir=function(){return this.baseURL!=="https://api.supermemory.ai"};p.Supermemory=Wt;p.DEFAULT_TIMEOUT=6e4;p.SupermemoryError=b.SupermemoryError;p.APIError=b.APIError;p.APIConnectionError=b.APIConnectionError;p.APIConnectionTimeoutError=b.APIConnectionTimeoutError;p.APIUserAbortError=b.APIUserAbortError;p.NotFoundError=b.NotFoundError;p.ConflictError=b.ConflictError;p.RateLimitError=b.RateLimitError;p.BadRequestError=b.BadRequestError;p.AuthenticationError=b.AuthenticationError;p.InternalServerError=b.InternalServerError;p.PermissionDeniedError=b.PermissionDeniedError;p.UnprocessableEntityError=b.UnprocessableEntityError;p.toFile=Os.toFile;p.Memories=hs.Memories;p.Documents=Hs.Documents;p.Search=Ws.Search;p.Settings=Ts.Settings;p.Connections=qs.Connections});var ur=c((u,cr)=>{"use strict";u=cr.exports=function(...e){return new u.default(...e)};Object.defineProperty(u,"__esModule",{value:!0});u.UnprocessableEntityError=u.PermissionDeniedError=u.InternalServerError=u.AuthenticationError=u.BadRequestError=u.RateLimitError=u.ConflictError=u.NotFoundError=u.APIUserAbortError=u.APIConnectionTimeoutError=u.APIConnectionError=u.APIError=u.SupermemoryError=u.Supermemory=u.APIPromise=u.toFile=u.default=void 0;var Ls=Tt();Object.defineProperty(u,"default",{enumerable:!0,get:function(){return Ls.Supermemory}});var Vs=tt();Object.defineProperty(u,"toFile",{enumerable:!0,get:function(){return Vs.toFile}});var Rs=jt();Object.defineProperty(u,"APIPromise",{enumerable:!0,get:function(){return Rs.APIPromise}});var gs=Tt();Object.defineProperty(u,"Supermemory",{enumerable:!0,get:function(){return gs.Supermemory}});var y=K();Object.defineProperty(u,"SupermemoryError",{enumerable:!0,get:function(){return y.SupermemoryError}});Object.defineProperty(u,"APIError",{enumerable:!0,get:function(){return y.APIError}});Object.defineProperty(u,"APIConnectionError",{enumerable:!0,get:function(){return y.APIConnectionError}});Object.defineProperty(u,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return y.APIConnectionTimeoutError}});Object.defineProperty(u,"APIUserAbortError",{enumerable:!0,get:function(){return y.APIUserAbortError}});Object.defineProperty(u,"NotFoundError",{enumerable:!0,get:function(){return y.NotFoundError}});Object.defineProperty(u,"ConflictError",{enumerable:!0,get:function(){return y.ConflictError}});Object.defineProperty(u,"RateLimitError",{enumerable:!0,get:function(){return y.RateLimitError}});Object.defineProperty(u,"BadRequestError",{enumerable:!0,get:function(){return y.BadRequestError}});Object.defineProperty(u,"AuthenticationError",{enumerable:!0,get:function(){return y.AuthenticationError}});Object.defineProperty(u,"InternalServerError",{enumerable:!0,get:function(){return y.InternalServerError}});Object.defineProperty(u,"PermissionDeniedError",{enumerable:!0,get:function(){return y.PermissionDeniedError}});Object.defineProperty(u,"UnprocessableEntityError",{enumerable:!0,get:function(){return y.UnprocessableEntityError}})});var vr={};Ir(vr,{getRequestIntegrity:()=>Is,sanitizeContent:()=>Fs,sanitizeMetadata:()=>Gs,validateApiKeyFormat:()=>ws,validateContainerTag:()=>Zs,validateContentLength:()=>Ds,validateRecallConfig:()=>Ks});function ws(e){return!e||typeof e!="string"?{valid:!1,reason:"key is empty or not a string"}:e.startsWith("sm_")?e.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(e)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function Zs(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function Fs(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Ms)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function Ds(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Gs(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=Us)break;n.length>Ys||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,Ss),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function Ks(e,t){let r=[];return(!Number.isInteger(e)||e<1||e>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(t)||t<1||t>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Nt(e){return(0,Re.createHash)("sha256").update(e).digest("hex")}function Es(e,t){let r=[Nt(e),Nt(t),dr].join(":");return(0,Re.createHmac)("sha256",ks).update(r).digest("base64url")}function Is(e,t){let r=Nt(t),n=Es(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${dr}`,n].join(".")}}var Re,Ms,Us,Ys,Ss,dr,ks,lr=Er(()=>{Re=require("node:crypto");Ms=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Us=50,Ys=128,Ss=1024;dr=1,ks="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Lt=c((Wa,Pr)=>{var Cs="https://api.supermemory.ai";Pr.exports={BASE_URL:Cs}});var zr=c((Ta,pr)=>{var Js=ur().default,{getRequestIntegrity:Bs,validateApiKeyFormat:As,validateContainerTag:Qs}=(lr(),Jr(vr)),{BASE_URL:_s}=Lt(),$s="claudecode_default";function eo(e,t=r=>r){let r=new Set;return e.filter(n=>{let s=String(t(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var to=`Developer coding session transcript. Focus on USER message and intent. +${m}`)}return a};N.createPathTagFunction=Bn;N.path=(0,N.createPathTagFunction)(st)});var at=c(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Connections=void 0;var An=Z(),Qn=B(),W=je(),ot=class extends An.APIResource{create(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/connections/list",{body:t,...r})}configure(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/configure`,{body:r,...n})}deleteByID(t,r){return this._client.delete((0,W.path)`/v3/connections/${t}`,r)}deleteByProvider(t,r,n){return this._client.delete((0,W.path)`/v3/connections/${t}`,{body:r,...n})}getByID(t,r){return this._client.get((0,W.path)`/v3/connections/${t}`,r)}getByTag(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/connection`,{body:r,...n})}import(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/import`,{body:r,...n,headers:(0,Qn.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/documents`,{body:r,...n})}resources(t,r={},n){return this._client.get((0,W.path)`/v3/connections/${t}/resources`,{query:r,...n})}};Xe.Connections=ot});var ct=c(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Documents=void 0;var _n=Z(),$n=B(),es=C(),ft=je(),it=class extends _n.APIResource{update(t,r={},n){return this._client.patch((0,ft.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,ft.path)`/v3/documents/${t}`,{...r,headers:(0,$n.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}batchAdd(t,r){return this._client.post("/v3/documents/batch",{body:t,...r})}deleteBulk(t={},r){return this._client.delete("/v3/documents/bulk",{body:t,...r})}get(t,r){return this._client.get((0,ft.path)`/v3/documents/${t}`,r)}listProcessing(t){return this._client.get("/v3/documents/processing",t)}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,es.multipartFormRequestOptions)({body:t,...r},this._client))}};Oe.Documents=it});var vt=c(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Memories=void 0;var ts=Z(),rs=B(),ns=C(),ut=je(),dt=class extends ts.APIResource{update(t,r={},n){return this._client.patch((0,ut.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,ut.path)`/v3/documents/${t}`,{...r,headers:(0,rs.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}forget(t,r){return this._client.delete("/v4/memories",{body:t,...r})}get(t,r){return this._client.get((0,ut.path)`/v3/documents/${t}`,r)}updateMemory(t,r){return this._client.patch("/v4/memories",{body:t,...r})}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,ns.multipartFormRequestOptions)({body:t,...r},this._client))}};ye.Memories=dt});var Pt=c(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Search=void 0;var ss=Z(),lt=class extends ss.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};qe.Search=lt});var zt=c(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Settings=void 0;var os=Z(),pt=class extends os.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};He.Settings=pt});var nr=c(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.Settings=q.Search=q.Memories=q.Documents=q.Connections=void 0;var as=at();Object.defineProperty(q,"Connections",{enumerable:!0,get:function(){return as.Connections}});var fs=ct();Object.defineProperty(q,"Documents",{enumerable:!0,get:function(){return fs.Documents}});var is=vt();Object.defineProperty(q,"Memories",{enumerable:!0,get:function(){return is.Memories}});var cs=Pt();Object.defineProperty(q,"Search",{enumerable:!0,get:function(){return cs.Search}});var us=zt();Object.defineProperty(q,"Settings",{enumerable:!0,get:function(){return us.Settings}})});var mt=c(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=or;var ds=E(),We={off:0,error:200,warn:300,info:400,debug:500},vs=(e,t,r)=>{if(e){if((0,ds.hasOwn)(We,e))return e;or(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(We))}`)}};R.parseLogLevel=vs;function A(){}function he(e,t,r){return!t||We[e]>We[r]?A:t[e].bind(t)}var ls={error:A,warn:A,info:A,debug:A},sr=new WeakMap;function or(e){let t=e.logger,r=e.logLevel??"off";if(!t)return ls;let n=sr.get(t);if(n&&n[0]===r)return n[1];let s={error:he("error",t,r),warn:he("warn",t,r),info:he("info",t,r),debug:he("debug",t,r)};return sr.set(t,[r,s]),s}var Ps=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);R.formatRequestDetails=Ps});var fr=c(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.defaultParseResponse=ps;var ar=mt();async function ps(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,a=await(async()=>{if(r.status===204)return null;if(t.options.__binaryResponse)return r;let z=r.headers.get("content-type")?.split(";")[0]?.trim();return z?.includes("application/json")||z?.endsWith("+json")?await r.json():await r.text()})();return(0,ar.loggerFor)(e).debug(`[${n}] response parsed`,(0,ar.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var Xt=c(Te=>{"use strict";var Q;Object.defineProperty(Te,"__esModule",{value:!0});Te.APIPromise=void 0;var xt=Ee(),zs=fr(),jt=class e extends Promise{constructor(t,r,n=zs.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,Q.set(this,void 0),xt.__classPrivateFieldSet(this,Q,t,"f")}_thenUnwrap(t){return new e(xt.__classPrivateFieldGet(this,Q,"f"),this.responsePromise,async(r,n)=>t(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(xt.__classPrivateFieldGet(this,Q,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};Te.APIPromise=jt;Q=new WeakMap});var ir=c(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.readEnv=void 0;var ms=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};Ne.readEnv=ms});var Nt=c(Ve=>{"use strict";var Wt,Tt,Le,cr;Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Supermemory=void 0;var L=Ee(),bs=St(),Ot=E(),xs=Gt(),yt=Ie(),js=It(),qt=L.__importStar(Ae()),Xs=L.__importStar(Jt()),Os=Be(),b=L.__importStar(K()),ys=L.__importStar(rt()),_=L.__importStar(nr()),qs=Xt(),Hs=at(),hs=ct(),Ws=vt(),Ts=Pt(),Ns=zt(),Ht=B(),ht=ir(),j=mt(),Ls=E(),p=class{constructor({baseURL:t=(0,ht.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,ht.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Wt.add(this),Le.set(this,void 0),this.memories=new _.Memories(this),this.documents=new _.Documents(this),this.search=new _.Search(this),this.settings=new _.Settings(this),this.connections=new _.Connections(this),r===void 0)throw new b.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:t||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??Tt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,j.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,j.parseLogLevel)((0,ht.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??qt.getDefaultFetch(),L.__classPrivateFieldSet(this,Le,Xs.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,Ht.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Object.entries(t).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new b.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Os.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,bs.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,Wt,"m",cr).call(this)&&n||this.baseURL,o=(0,Ot.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,Ls.isEmptyObj)(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(s=>({method:t,path:r,...s})))}request(t,r=null){return new qs.APIPromise(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let s=await t,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:a,url:f,timeout:z}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(a,{url:f,options:s});let v="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if((0,j.loggerFor)(this).debug(`[${v}] sending request`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:f,options:s,headers:a.headers})),s.signal?.aborted)throw new b.APIUserAbortError;let X=new AbortController,i=await this.fetchWithTimeout(f,a,z,X).catch(yt.castToError),H=Date.now();if(i instanceof globalThis.Error){let U=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let T=(0,yt.isAbortError)(i)||/timed? ?out/i.test(String(i)+("cause"in i?String(i.cause):""));if(r)return(0,j.loggerFor)(this).info(`[${v}] connection ${T?"timed out":"failed"} - ${U}`),(0,j.loggerFor)(this).debug(`[${v}] connection ${T?"timed out":"failed"} (${U})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:H-m,message:i.message})),this.retryRequest(s,r,n??v);throw(0,j.loggerFor)(this).info(`[${v}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,j.loggerFor)(this).debug(`[${v}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:H-m,message:i.message})),T?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:i})}let D=`[${v}${l}] ${a.method} ${f} ${i.ok?"succeeded":"failed"} with status ${i.status} in ${H-m}ms`;if(!i.ok){let U=await this.shouldRetry(i);if(r&&U){let se=`retrying, ${r} attempts remaining`;return await qt.CancelReadableStream(i.body),(0,j.loggerFor)(this).info(`${D} - ${se}`),(0,j.loggerFor)(this).debug(`[${v}] response error (${se})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:H-m})),this.retryRequest(s,r,n??v,i.headers)}let T=U?"error; no more retries left":"error; not retryable";(0,j.loggerFor)(this).info(`${D} - ${T}`);let Ft=await i.text().catch(se=>(0,yt.castToError)(se).message),Dt=(0,Ot.safeJSON)(Ft),Ut=Dt?void 0:Ft;throw(0,j.loggerFor)(this).debug(`[${v}] response error (${T})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,message:Ut,durationMs:Date.now()-m})),this.makeStatusError(i.status,Dt,Ut,i.headers)}return(0,j.loggerFor)(this).info(D),(0,j.loggerFor)(this).debug(`[${v}] response start`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:H-m})),{response:i,options:s,controller:X,requestLogID:v,retryOfRequestLogID:n,startTime:m}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:a,...f}=r||{};o&&o.addEventListener("abort",()=>s.abort());let z=setTimeout(()=>s.abort(),n),v=globalThis.ReadableStream&&f.body instanceof globalThis.ReadableStream||typeof f.body=="object"&&f.body!==null&&Symbol.asyncIterator in f.body,l={signal:s.signal,...v?{duplex:"half"}:{},method:"GET",...f};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,l)}finally{clearTimeout(z)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,s){let o,a=s?.get("retry-after-ms");if(a){let z=parseFloat(a);Number.isNaN(z)||(o=z)}let f=s?.get("retry-after");if(f&&!o){let z=parseFloat(f);Number.isNaN(z)?o=Date.parse(f)-Date.now():o=z*1e3}if(!(o&&0<=o&&o<60*1e3)){let z=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,z)}return await(0,xs.sleep)(o),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let o=r-t,a=Math.min(.5*Math.pow(2,o),8),f=1-Math.random()*.25;return a*f*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:s,path:o,query:a,defaultBaseURL:f}=n,z=this.buildURL(o,a,f);"timeout"in n&&(0,Ot.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:v,body:l}=this.buildBody({options:n}),m=await this.buildHeaders({options:t,method:s,bodyHeaders:v,retryCount:r});return{req:{method:s,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:z,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let a=(0,Ht.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...(0,js.getPlatformHeaders)()},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,Ht.buildHeaders)([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:qt.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Le,"f").call(this,{body:t,headers:n})}};Ve.Supermemory=p;Tt=p,Le=new WeakMap,Wt=new WeakSet,cr=function(){return this.baseURL!=="https://api.supermemory.ai"};p.Supermemory=Tt;p.DEFAULT_TIMEOUT=6e4;p.SupermemoryError=b.SupermemoryError;p.APIError=b.APIError;p.APIConnectionError=b.APIConnectionError;p.APIConnectionTimeoutError=b.APIConnectionTimeoutError;p.APIUserAbortError=b.APIUserAbortError;p.NotFoundError=b.NotFoundError;p.ConflictError=b.ConflictError;p.RateLimitError=b.RateLimitError;p.BadRequestError=b.BadRequestError;p.AuthenticationError=b.AuthenticationError;p.InternalServerError=b.InternalServerError;p.PermissionDeniedError=b.PermissionDeniedError;p.UnprocessableEntityError=b.UnprocessableEntityError;p.toFile=ys.toFile;p.Memories=Ws.Memories;p.Documents=hs.Documents;p.Search=Ts.Search;p.Settings=Ns.Settings;p.Connections=Hs.Connections});var dr=c((u,ur)=>{"use strict";u=ur.exports=function(...e){return new u.default(...e)};Object.defineProperty(u,"__esModule",{value:!0});u.UnprocessableEntityError=u.PermissionDeniedError=u.InternalServerError=u.AuthenticationError=u.BadRequestError=u.RateLimitError=u.ConflictError=u.NotFoundError=u.APIUserAbortError=u.APIConnectionTimeoutError=u.APIConnectionError=u.APIError=u.SupermemoryError=u.Supermemory=u.APIPromise=u.toFile=u.default=void 0;var Vs=Nt();Object.defineProperty(u,"default",{enumerable:!0,get:function(){return Vs.Supermemory}});var Rs=rt();Object.defineProperty(u,"toFile",{enumerable:!0,get:function(){return Rs.toFile}});var gs=Xt();Object.defineProperty(u,"APIPromise",{enumerable:!0,get:function(){return gs.APIPromise}});var ws=Nt();Object.defineProperty(u,"Supermemory",{enumerable:!0,get:function(){return ws.Supermemory}});var y=K();Object.defineProperty(u,"SupermemoryError",{enumerable:!0,get:function(){return y.SupermemoryError}});Object.defineProperty(u,"APIError",{enumerable:!0,get:function(){return y.APIError}});Object.defineProperty(u,"APIConnectionError",{enumerable:!0,get:function(){return y.APIConnectionError}});Object.defineProperty(u,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return y.APIConnectionTimeoutError}});Object.defineProperty(u,"APIUserAbortError",{enumerable:!0,get:function(){return y.APIUserAbortError}});Object.defineProperty(u,"NotFoundError",{enumerable:!0,get:function(){return y.NotFoundError}});Object.defineProperty(u,"ConflictError",{enumerable:!0,get:function(){return y.ConflictError}});Object.defineProperty(u,"RateLimitError",{enumerable:!0,get:function(){return y.RateLimitError}});Object.defineProperty(u,"BadRequestError",{enumerable:!0,get:function(){return y.BadRequestError}});Object.defineProperty(u,"AuthenticationError",{enumerable:!0,get:function(){return y.AuthenticationError}});Object.defineProperty(u,"InternalServerError",{enumerable:!0,get:function(){return y.InternalServerError}});Object.defineProperty(u,"PermissionDeniedError",{enumerable:!0,get:function(){return y.PermissionDeniedError}});Object.defineProperty(u,"UnprocessableEntityError",{enumerable:!0,get:function(){return y.UnprocessableEntityError}})});var lr={};Cr(lr,{getRequestIntegrity:()=>Cs,sanitizeContent:()=>Ds,sanitizeMetadata:()=>Ks,validateApiKeyFormat:()=>Zs,validateContainerTag:()=>Ms,validateContentLength:()=>Us,validateRecallConfig:()=>ks});function Zs(e){return!e||typeof e!="string"?{valid:!1,reason:"key is empty or not a string"}:e.startsWith("sm_")?e.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(e)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function Ms(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function Ds(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Fs)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function Us(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Ks(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=Ys)break;n.length>Ss||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,Gs),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function ks(e,t){let r=[];return(!Number.isInteger(e)||e<1||e>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(t)||t<1||t>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Lt(e){return(0,Re.createHash)("sha256").update(e).digest("hex")}function Is(e,t){let r=[Lt(e),Lt(t),vr].join(":");return(0,Re.createHmac)("sha256",Es).update(r).digest("base64url")}function Cs(e,t){let r=Lt(t),n=Is(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${vr}`,n].join(".")}}var Re,Fs,Ys,Ss,Gs,vr,Es,Pr=Ir(()=>{Re=require("node:crypto");Fs=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Ys=50,Ss=128,Gs=1024;vr=1,Es="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Vt=c((Ta,pr)=>{var Js="https://api.supermemory.ai";pr.exports={BASE_URL:Js}});var mr=c((Na,zr)=>{var Bs=dr().default,{getRequestIntegrity:As,validateApiKeyFormat:Qs,validateContainerTag:_s}=(Pr(),Br(lr)),{BASE_URL:$s}=Vt(),eo="claudecode_default";function to(e,t=r=>r){let r=new Set;return e.filter(n=>{let s=String(t(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var ro=`Developer coding session transcript. Focus on USER message and intent. RULES: - Extract USER's action/intent, not every detail assistant provides matter @@ -30,7 +30,7 @@ EXAMPLES: SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,ro=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,no=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" @@ -43,60 +43,60 @@ EXAMPLES: | Input | Memory | | "The auth flow works by..." | "Auth flow: [description]" | | "We structure components like..." | "Component structure convention: [pattern]" | -| "To add a new API route..." | "Adding API routes: [steps]" |`,Vt=class{constructor(t,r,n={}){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=As(t);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||$s,a=Qs(o);a.valid||console.warn(`Container tag warning: ${a.reason}`);let f=Bs(t,o);this.client=new Js({apiKey:t,baseURL:n.baseUrl||_s,defaultHeaders:{...f,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let a=await this.client.add(o);return{id:a.id,status:a.status,containerTag:r||this.containerTag}}async search(t,r,n={}){let s=await this.client.search.memories({q:t,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(a=>({memory:a.content||a.memory||a.context||"",chunk:a.chunk,metadata:a.metadata,updatedAt:a.updatedAt,similarity:a.similarity}));return{results:eo(o,a=>a.memory),total:s.total,timing:s.timing}}async getProfile(t,r){let n=await this.client.profile({containerTag:t||this.containerTag,q:r}),s=new Set,o=(v,l=m=>m)=>v.filter(m=>{let X=String(l(m)).toLowerCase().trim();return!X||s.has(X)?!1:(s.add(X),!0)}),a=o(n.profile?.static||[]),f=o(n.profile?.dynamic||[]),z;if(n.searchResults){let v=n.searchResults.results.map(l=>({id:l.id,memory:l.content||l.context||"",similarity:l.similarity,title:l.title,updatedAt:l.updatedAt}));z={results:o(v,l=>l.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:f},searchResults:z}}};pr.exports={SupermemoryClient:Vt,PERSONAL_ENTITY_CONTEXT:to,REPO_ENTITY_CONTEXT:ro}});var Rt=c((Na,mr)=>{var{execSync:ge}=require("node:child_process"),$=require("node:path");function no(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=ge("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=$.resolve(e,r);return $.basename(n)===".git"&&!n.includes(`${$.sep}.git${$.sep}`)?$.dirname(n):ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}mr.exports={getGitRoot:no}});var Ze=c((La,yr)=>{var ee=require("node:fs"),we=require("node:path"),{getGitRoot:br}=Rt(),xr=we.join(".claude",".supermemory-claude"),jr="config.json";function Xr(e){let r=br(e)||e;return we.join(r,xr,jr)}function Or(e){try{let t=Xr(e);if(ee.existsSync(t))return JSON.parse(ee.readFileSync(t,"utf-8"))}catch{}return null}function so(e,t){let n=br(e)||e,s=we.join(n,xr),o=we.join(s,jr);ee.existsSync(s)||ee.mkdirSync(s,{recursive:!0});let f={...Or(e)||{},...t};return ee.writeFileSync(o,JSON.stringify(f,null,2)),o}yr.exports={getConfigPath:Xr,loadProjectConfig:Or,saveProjectConfig:so}});var Wr=c((Va,hr)=>{var{execSync:oo}=require("node:child_process"),ao=require("node:crypto"),{loadProjectConfig:qr}=Ze(),{getGitRoot:Me}=Rt();function Hr(e){return ao.createHash("sha256").update(e).digest("hex").slice(0,16)}function gt(e){try{let r=oo("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/);return r?r[1]:null}catch{return null}}function fo(e){let t=qr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Me(e)||e;return`claudecode_project_${Hr(n)}`}function io(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function co(e){let t=qr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Me(e)||e,o=gt(n)||n.split("/").pop()||"unknown";return`repo_${io(o)}`}function uo(e){let r=Me(e)||e;return gt(r)||r.split("/").pop()||"unknown"}hr.exports={sha256:Hr,getGitRoot:Me,getGitRepoName:gt,getContainerTag:fo,getRepoContainerTag:co,getProjectName:uo}});var Nr=c((Ra,Tr)=>{var{execFile:vo}=require("node:child_process");function Fe(e,t){return new Promise((r,n)=>{vo(e,t,{windowsHide:!0},s=>{s?n(s):r()})})}async function lo(e){let t=e.toString();if(!/^https?:\/\//i.test(t))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await Fe("rundll32.exe",["url.dll,FileProtocolHandler",t]);return}catch{}await Fe("cmd.exe",["/c","start",'""',t]);return}if(process.platform==="darwin"){await Fe("open",[t]);return}await Fe("xdg-open",[t])}Tr.exports={openUrl:lo}});var Lr=c((ga,Po)=>{Po.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var Vr=c((wa,po)=>{po.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var Mr=c((Za,Zr)=>{var zo=require("node:http"),g=require("node:fs"),Rr=require("node:path"),mo=require("node:os"),{openUrl:bo}=Nr(),xo=Lr(),jo=Vr(),Zt=Rr.join(mo.homedir(),".supermemory-claude"),F=Rr.join(Zt,"credentials.json"),gr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",wt=19876,Xo=25e3;function Oo(){g.existsSync(Zt)||g.mkdirSync(Zt,{recursive:!0})}function yo(){try{if(g.existsSync(F)){let e=JSON.parse(g.readFileSync(F,"utf-8"));if(e.apiKey)return e}}catch{}return null}function wr(e){Oo();let t={apiKey:e,savedAt:new Date().toISOString()};g.writeFileSync(F,JSON.stringify(t,null,2))}function qo(){try{g.existsSync(F)&&g.unlinkSync(F)}catch{}}function Ho(){return new Promise((e,t)=>{let r=!1,n=zo.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${wt}`);if(a.pathname==="/callback"){let f=a.searchParams.get("apikey")||a.searchParams.get("api_key");f?.startsWith("sm_")?(wr(f),o.writeHead(200,{"Content-Type":"text/html"}),o.end(xo),r=!0,n.close(),e(f)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(jo))}else o.writeHead(404),o.end("Not found")});n.listen(wt,"127.0.0.1",()=>{let s=`http://localhost:${wt}/callback`,o=`${gr}?callback=${encodeURIComponent(s)}&client=claude_code`;bo(o).catch(a=>{r||(n.close(),t(new Error(`Failed to open browser: ${a.message}`)))})}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},Xo)})}Zr.exports={AUTH_BASE_URL:gr,CREDENTIALS_FILE:F,loadCredentials:yo,saveCredentials:wr,clearCredentials:qo,startAuthFlow:Ho}});var Ur=c((Ma,Dr)=>{var re=require("node:fs"),Fr=require("node:path"),ho=require("node:os"),{loadCredentials:Wo}=Mr(),{loadProjectConfig:ne}=Ze(),{BASE_URL:To}=Lt(),De=Fr.join(ho.homedir(),".supermemory-claude"),te=Fr.join(De,"settings.json"),Ue={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function No(){re.existsSync(De)||re.mkdirSync(De,{recursive:!0})}function Ye(){let e={...Ue};try{if(re.existsSync(te)){let t=re.readFileSync(te,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${te}: ${t.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function Lo(e){No();let t={...e};delete t.apiKey,re.writeFileSync(te,JSON.stringify(t,null,2))}function Vo(e,t,r){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||ne(t||process.cwd()),r?.apiKey)return r.apiKey;let n=Wo();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function Ro(e){if(typeof e!="string"||!e.trim())return null;let t=e.trim();try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t}catch{return null}}function go(e,t){t=t||ne(e||process.cwd());let r=process.env.SUPERMEMORY_API_URL||t?.baseUrl||To,n=Ro(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function wo(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function Zo(e){let t=Ye(),r=ne(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Mo(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function Fo(e){let t=Ye(),r=ne(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Ue.signalKeywords,f=r?.signalKeywords||[],z=[...new Set([...a,...f])].map(l=>l.toLowerCase()),v=r?.signalTurnsBefore||t.signalTurnsBefore||Ue.signalTurnsBefore;return{enabled:o,keywords:z,turnsBefore:v}}function Do(e){let t=Ye();return{directive:ne(e||process.cwd())?.recallDirective||t.recallDirective||null}}Dr.exports={SETTINGS_DIR:De,SETTINGS_FILE:te,DEFAULT_SETTINGS:Ue,loadSettings:Ye,saveSettings:Lo,getApiKey:Vo,getBaseUrl:go,debugLog:wo,getIncludeTools:Zo,shouldIncludeTool:Mo,getSignalConfig:Fo,getRecallConfig:Do}});var Sr=c((Fa,Yr)=>{function Uo(e){let t=e?.status;return t===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":t===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":t===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":t===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof t=="number"&&t>=500?"Supermemory service is temporarily unavailable. Will retry next session.":e?.message||"Unknown error"}function Yo(e){let t=e?.status;return t===429||typeof t=="number"&&t>=500||t==null}function So(e){let t=e?.status;return t===404||t==null}Yr.exports={getUserFriendlyError:Uo,isRetryableError:Yo,isBenignError:So}});var{SupermemoryClient:Go,PERSONAL_ENTITY_CONTEXT:Ko}=zr(),{getContainerTag:ko,getProjectName:Eo}=Wr(),{loadProjectConfig:Io}=Ze(),{loadSettings:Co,getApiKey:Jo,getBaseUrl:Bo}=Ur(),{getUserFriendlyError:Ao}=Sr();async function Qo(){let e=process.argv.slice(2).join(" ");if(!e||!e.trim()){console.log('No content provided. Usage: node add-memory.cjs "content to save"');return}let t=Co(),r=process.cwd(),n=Io(r),s;try{s=Jo(t,r,n)}catch{console.log("Supermemory API key not configured."),console.log("Set SUPERMEMORY_CC_API_KEY environment variable.");return}let o=ko(r),a=Eo(r);try{let f=Bo(r,n),v=await new Go(s,o,{baseUrl:f}).addMemory(e,o,{type:"manual",project:a,timestamp:new Date().toISOString()},{entityContext:Ko});console.log(`Memory saved to project: ${a}`),console.log(`ID: ${v.id}`)}catch(f){console.log(`Error saving memory: ${Ao(f)}`)}}Qo().catch(e=>{console.error(`Fatal error: ${e.message}`),process.exit(1)}); +| "To add a new API route..." | "Adding API routes: [steps]" |`,Rt=class{constructor(t,r,n={}){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=Qs(t);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||eo,a=_s(o);a.valid||console.warn(`Container tag warning: ${a.reason}`);let f=As(t,o);this.client=new Bs({apiKey:t,baseURL:n.baseUrl||$s,defaultHeaders:{...f,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let a=await this.client.add(o);return{id:a.id,status:a.status,containerTag:r||this.containerTag}}async search(t,r,n={}){let s=await this.client.search.memories({q:t,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(a=>({memory:a.content||a.memory||a.context||"",chunk:a.chunk,metadata:a.metadata,updatedAt:a.updatedAt,similarity:a.similarity}));return{results:to(o,a=>a.memory),total:s.total,timing:s.timing}}async getProfile(t,r){let n=await this.client.profile({containerTag:t||this.containerTag,q:r}),s=new Set,o=(v,l=m=>m)=>v.filter(m=>{let X=String(l(m)).toLowerCase().trim();return!X||s.has(X)?!1:(s.add(X),!0)}),a=o(n.profile?.static||[]),f=o(n.profile?.dynamic||[]),z;if(n.searchResults){let v=n.searchResults.results.map(l=>({id:l.id,memory:l.content||l.context||"",similarity:l.similarity,title:l.title,updatedAt:l.updatedAt}));z={results:o(v,l=>l.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:f},searchResults:z}}};zr.exports={SupermemoryClient:Rt,PERSONAL_ENTITY_CONTEXT:ro,REPO_ENTITY_CONTEXT:no}});var gt=c((La,br)=>{var{execSync:ge}=require("node:child_process"),$=require("node:path");function so(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=ge("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=$.resolve(e,r);return $.basename(n)===".git"&&!n.includes(`${$.sep}.git${$.sep}`)?$.dirname(n):ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}br.exports={getGitRoot:so}});var Ze=c((Va,qr)=>{var ee=require("node:fs"),we=require("node:path"),{getGitRoot:xr}=gt(),jr=we.join(".claude",".supermemory-claude"),Xr="config.json";function Or(e){let r=xr(e)||e;return we.join(r,jr,Xr)}function yr(e){try{let t=Or(e);if(ee.existsSync(t))return JSON.parse(ee.readFileSync(t,"utf-8"))}catch{}return null}function oo(e,t){let n=xr(e)||e,s=we.join(n,jr),o=we.join(s,Xr);ee.existsSync(s)||ee.mkdirSync(s,{recursive:!0});let f={...yr(e)||{},...t};return ee.writeFileSync(o,JSON.stringify(f,null,2)),o}qr.exports={getConfigPath:Or,loadProjectConfig:yr,saveProjectConfig:oo}});var Tr=c((Ra,Wr)=>{var{execSync:ao}=require("node:child_process"),fo=require("node:crypto"),{loadProjectConfig:Hr}=Ze(),{getGitRoot:Fe}=gt();function hr(e){return fo.createHash("sha256").update(e).digest("hex").slice(0,16)}var Me=new Map;function wt(e){if(Me.has(e))return Me.get(e);try{let r=ao("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/),n=r?r[1]:null;return Me.set(e,n),n}catch{return Me.set(e,null),null}}function io(e){let t=Hr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Fe(e)||e;return`claudecode_project_${hr(n)}`}function co(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function uo(e){let t=Hr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Fe(e)||e,o=wt(n)||n.split("/").pop()||"unknown";return`repo_${co(o)}`}function vo(e){let r=Fe(e)||e;return wt(r)||r.split("/").pop()||"unknown"}Wr.exports={sha256:hr,getGitRoot:Fe,getGitRepoName:wt,getContainerTag:io,getRepoContainerTag:uo,getProjectName:vo}});var Lr=c((ga,Nr)=>{var{execFile:lo}=require("node:child_process");function De(e,t){return new Promise((r,n)=>{lo(e,t,{windowsHide:!0},s=>{s?n(s):r()})})}async function Po(e){let t=e.toString();if(!/^https?:\/\//i.test(t))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await De("rundll32.exe",["url.dll,FileProtocolHandler",t]);return}catch{}await De("cmd.exe",["/c","start",'""',t]);return}if(process.platform==="darwin"){await De("open",[t]);return}await De("xdg-open",[t])}Nr.exports={openUrl:Po}});var Vr=c((wa,po)=>{po.exports=`\r +\r +Connected - Supermemory\r +\r +\r +
\r +
Connected . . .
\r +\r +
\r + \r + +\r + \r +
\r +

Supercharge your Claude Code with Supermemory.

\r +
\r +\r +\r +`});var Rr=c((Za,zo)=>{zo.exports=`\r +\r +Error - Supermemory\r +\r +
Error . . .
\r +

Connection Failed

\r +

Invalid API key received. Please try again.

\r +\r +`});var Fr=c((Ma,Mr)=>{var mo=require("node:http"),g=require("node:fs"),gr=require("node:path"),bo=require("node:os"),{openUrl:xo}=Lr(),jo=Vr(),Xo=Rr(),Mt=gr.join(bo.homedir(),".supermemory-claude"),F=gr.join(Mt,"credentials.json"),wr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",Zt=19876,Oo=25e3;function yo(){g.existsSync(Mt)||g.mkdirSync(Mt,{recursive:!0})}function qo(){try{if(g.existsSync(F)){let e=JSON.parse(g.readFileSync(F,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Zr(e){yo();let t={apiKey:e,savedAt:new Date().toISOString()};g.writeFileSync(F,JSON.stringify(t,null,2))}function Ho(){try{g.existsSync(F)&&g.unlinkSync(F)}catch{}}function ho(){return new Promise((e,t)=>{let r=!1,n=mo.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${Zt}`);if(a.pathname==="/callback"){let f=a.searchParams.get("apikey")||a.searchParams.get("api_key");f?.startsWith("sm_")?(Zr(f),o.writeHead(200,{"Content-Type":"text/html"}),o.end(jo),r=!0,n.close(),e(f)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(Xo))}else o.writeHead(404),o.end("Not found")});n.listen(Zt,"127.0.0.1",()=>{let s=`http://localhost:${Zt}/callback`,o=`${wr}?callback=${encodeURIComponent(s)}&client=claude_code`;xo(o).catch(a=>{r||(n.close(),t(new Error(`Failed to open browser: ${a.message}`)))})}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},Oo)})}Mr.exports={AUTH_BASE_URL:wr,CREDENTIALS_FILE:F,loadCredentials:qo,saveCredentials:Zr,clearCredentials:Ho,startAuthFlow:ho}});var Yr=c((Fa,Ur)=>{var re=require("node:fs"),Dr=require("node:path"),Wo=require("node:os"),{loadCredentials:To}=Fr(),{loadProjectConfig:ne}=Ze(),{BASE_URL:No}=Vt(),Ue=Dr.join(Wo.homedir(),".supermemory-claude"),te=Dr.join(Ue,"settings.json"),Ye={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Lo(){re.existsSync(Ue)||re.mkdirSync(Ue,{recursive:!0})}function Se(){let e={...Ye};try{if(re.existsSync(te)){let t=re.readFileSync(te,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${te}: ${t.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function Vo(e){Lo();let t={...e};delete t.apiKey,re.writeFileSync(te,JSON.stringify(t,null,2))}function Ro(e,t,r){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||ne(t||process.cwd()),r?.apiKey)return r.apiKey;let n=To();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function go(e){if(typeof e!="string"||!e.trim())return null;let t=e.trim();try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t}catch{return null}}function wo(e,t){t=t||ne(e||process.cwd());let r=process.env.SUPERMEMORY_API_URL||t?.baseUrl||No,n=go(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function Zo(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function Mo(e){let t=Se(),r=ne(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Fo(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function Do(e){let t=Se(),r=ne(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Ye.signalKeywords,f=r?.signalKeywords||[],z=[...new Set([...a,...f])].map(l=>l.toLowerCase()),v=r?.signalTurnsBefore||t.signalTurnsBefore||Ye.signalTurnsBefore;return{enabled:o,keywords:z,turnsBefore:v}}function Uo(e){let t=Se();return{directive:ne(e||process.cwd())?.recallDirective||t.recallDirective||null}}Ur.exports={SETTINGS_DIR:Ue,SETTINGS_FILE:te,DEFAULT_SETTINGS:Ye,loadSettings:Se,saveSettings:Vo,getApiKey:Ro,getBaseUrl:wo,debugLog:Zo,getIncludeTools:Mo,shouldIncludeTool:Fo,getSignalConfig:Do,getRecallConfig:Uo}});var Gr=c((Da,Sr)=>{function Yo(e){let t=e?.status;return t===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":t===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":t===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":t===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof t=="number"&&t>=500?"Supermemory service is temporarily unavailable. Will retry next session.":e?.message||"Unknown error"}function So(e){let t=e?.status;return t===429||typeof t=="number"&&t>=500||t==null}function Go(e){let t=e?.status;return t===404||t==null}Sr.exports={getUserFriendlyError:Yo,isRetryableError:So,isBenignError:Go}});var{SupermemoryClient:Ko,PERSONAL_ENTITY_CONTEXT:ko}=mr(),{getContainerTag:Eo,getProjectName:Io}=Tr(),{loadProjectConfig:Co}=Ze(),{loadSettings:Jo,getApiKey:Bo,getBaseUrl:Ao}=Yr(),{getUserFriendlyError:Qo}=Gr();async function _o(){let e=process.argv.slice(2).join(" ");if(!e||!e.trim()){console.log('No content provided. Usage: node add-memory.cjs "content to save"');return}let t=Jo(),r=process.cwd(),n=Co(r),s;try{s=Bo(t,r,n)}catch{console.log("Supermemory API key not configured."),console.log("Set SUPERMEMORY_CC_API_KEY environment variable.");return}let o=Eo(r),a=Io(r);try{let f=Ao(r,n),v=await new Ko(s,o,{baseUrl:f}).addMemory(e,o,{type:"manual",project:a,timestamp:new Date().toISOString()},{entityContext:ko});console.log(`Memory saved to project: ${a}`),console.log(`ID: ${v.id}`)}catch(f){console.log(`Error saving memory: ${Qo(f)}`)}}_o().catch(e=>{console.error(`Fatal error: ${e.message}`),process.exit(1)}); diff --git a/plugin/scripts/context-hook.cjs b/plugin/scripts/context-hook.cjs index 8753daf..c79fc84 100755 --- a/plugin/scripts/context-hook.cjs +++ b/plugin/scripts/context-hook.cjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -var Je=Object.defineProperty;var cn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var un=Object.prototype.hasOwnProperty;var dn=(e,t)=>()=>(e&&(t=e(e=0)),t);var f=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),vn=(e,t)=>{for(var r in t)Je(e,r,{get:t[r],enumerable:!0})},ln=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of fn(t))!un.call(e,s)&&s!==r&&Je(e,s,{get:()=>t[s],enumerable:!(n=cn(t,s))||n.enumerable});return e};var pn=e=>ln(Je({},"__esModule",{value:!0}),e);var Qe=f(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.__setModuleDefault=T.__createBinding=void 0;T.__classPrivateFieldSet=Pn;T.__classPrivateFieldGet=mn;T.__importStar=zn;T.__exportStar=bn;function Pn(e,t,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(e,r):s?s.value=r:t.set(e,r),r}function mn(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var Ae=Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]};T.__createBinding=Ae;var Ct=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};T.__setModuleDefault=Ct;var Be=function(e){return Be=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Be(e)};function zn(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Be(e),n=0;n{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.uuid4=void 0;var xn=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return E.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};E.uuid4=xn});var _e=f(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.castToError=void 0;C.isAbortError=jn;function jn(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var Xn=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};C.castToError=Xn});var J=f(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.InternalServerError=m.RateLimitError=m.UnprocessableEntityError=m.ConflictError=m.NotFoundError=m.PermissionDeniedError=m.AuthenticationError=m.BadRequestError=m.APIConnectionTimeoutError=m.APIConnectionError=m.APIUserAbortError=m.APIError=m.SupermemoryError=void 0;var On=_e(),ue=class extends Error{};m.SupermemoryError=ue;var y=class e extends ue{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(t,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new I({message:n,cause:(0,On.castToError)(r)});let o=r;return t===400?new de(t,o,n,s):t===401?new ve(t,o,n,s):t===403?new le(t,o,n,s):t===404?new pe(t,o,n,s):t===409?new Pe(t,o,n,s):t===422?new me(t,o,n,s):t===429?new ze(t,o,n,s):t>=500?new be(t,o,n,s):new e(t,o,n,s)}};m.APIError=y;var $e=class extends y{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};m.APIUserAbortError=$e;var I=class extends y{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};m.APIConnectionError=I;var et=class extends I{constructor({message:t}={}){super({message:t??"Request timed out."})}};m.APIConnectionTimeoutError=et;var de=class extends y{};m.BadRequestError=de;var ve=class extends y{};m.AuthenticationError=ve;var le=class extends y{};m.PermissionDeniedError=le;var pe=class extends y{};m.NotFoundError=pe;var Pe=class extends y{};m.ConflictError=Pe;var me=class extends y{};m.UnprocessableEntityError=me;var ze=class extends y{};m.RateLimitError=ze;var be=class extends y{};m.InternalServerError=be});var A=f(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});l.safeJSON=l.maybeCoerceBoolean=l.maybeCoerceFloat=l.maybeCoerceInteger=l.coerceBoolean=l.coerceFloat=l.coerceInteger=l.validatePositiveInteger=l.ensurePresent=l.isReadonlyArray=l.isArray=l.isAbsoluteURL=void 0;l.maybeObj=Hn;l.isEmptyObj=Wn;l.hasOwn=Tn;l.isObj=Nn;var B=J(),yn=/^[a-z][a-z0-9+.-]*:/i,hn=e=>yn.test(e);l.isAbsoluteURL=hn;var qn=e=>(l.isArray=Array.isArray,(0,l.isArray)(e));l.isArray=qn;l.isReadonlyArray=l.isArray;function Hn(e){return typeof e!="object"?{}:e??{}}function Wn(e){if(!e)return!0;for(let t in e)return!1;return!0}function Tn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Nn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var Ln=e=>{if(e==null)throw new B.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};l.ensurePresent=Ln;var Vn=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new B.SupermemoryError(`${e} must be an integer`);if(t<0)throw new B.SupermemoryError(`${e} must be a positive integer`);return t};l.validatePositiveInteger=Vn;var Rn=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new B.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};l.coerceInteger=Rn;var gn=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new B.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};l.coerceFloat=gn;var wn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;l.coerceBoolean=wn;var Mn=e=>{if(e!=null)return(0,l.coerceInteger)(e)};l.maybeCoerceInteger=Mn;var Zn=e=>{if(e!=null)return(0,l.coerceFloat)(e)};l.maybeCoerceFloat=Zn;var Fn=e=>{if(e!=null)return(0,l.coerceBoolean)(e)};l.maybeCoerceBoolean=Fn;var Dn=e=>{try{return JSON.parse(e)}catch{return}};l.safeJSON=Dn});var Jt=f(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.sleep=void 0;var Un=e=>new Promise(t=>setTimeout(t,e));xe.sleep=Un});var tt=f(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.VERSION=void 0;je.VERSION="4.0.0"});var _t=f(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.getPlatformHeaders=Y.isRunningInBrowser=void 0;var Q=tt(),Yn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Y.isRunningInBrowser=Yn;function Sn(){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 Gn=()=>{let e=Sn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":At(Deno.build.os),"X-Stainless-Arch":Bt(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":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":At(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Bt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=kn();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function kn(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:t,version:`${s}.${o}.${a}`}}}return null}var Bt=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",At=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),Qt,Kn=()=>Qt??(Qt=Gn());Y.getPlatformHeaders=Kn});var rt=f(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.getDefaultFetch=En;F.makeReadableStream=$t;F.ReadableStreamFrom=Cn;F.ReadableStreamToAsyncIterable=In;F.CancelReadableStream=Jn;function En(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function $t(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Cn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return $t({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function In(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Jn(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var er=f(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.FallbackEncoder=void 0;var Bn=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});Xe.FallbackEncoder=Bn});var _=f(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=nt;j.getName=Oe;var An=rt(),Qn=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};j.checkFileSupport=Qn;function nt(e,t,r){return(0,j.checkFileSupport)(),new File(e,t??"unknown_file",r)}function Oe(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var _n=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";j.isAsyncIterable=_n;var $n=async(e,t)=>st(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=$n;var es=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=es;var tr=new WeakMap;function ts(e){let t=typeof e=="function"?e:e.fetch,r=tr.get(t);if(r)return r;let n=(async()=>{try{let s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return tr.set(t,n),n}var rs=async(e,t)=>{if(!await ts(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,s])=>ot(r,n,s))),r};j.createForm=rs;var rr=e=>e instanceof Blob&&"name"in e,ns=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||rr(e)),st=e=>{if(ns(e))return!0;if(Array.isArray(e))return e.some(st);if(e&&typeof e=="object"){for(let t in e)if(st(e[t]))return!0}return!1},ot=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,nt([await r.blob()],Oe(r)));else if((0,j.isAsyncIterable)(r))e.append(t,nt([await new Response((0,An.ReadableStreamFrom)(r)).blob()],Oe(r)));else if(rr(r))e.append(t,r,Oe(r));else if(Array.isArray(r))await Promise.all(r.map(n=>ot(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>ot(e,`${t}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var sr=f(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.toFile=is;var $=_(),ss=_(),nr=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",os=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&nr(e),as=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function is(e,t,r){if((0,ss.checkFileSupport)(),e=await e,os(e))return e instanceof File?e:(0,$.makeFile)([await e.arrayBuffer()],e.name);if(as(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,$.makeFile)(await at(s),t,r)}let n=await at(e);if(t||(t=(0,$.getName)(e)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,$.makeFile)(n,t,r)}async function at(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nr(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,$.isAsyncIterable)(e))for await(let r of e)t.push(...await at(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${cs(e)}`)}return t}function cs(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var ct=f(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.toFile=void 0;var fs=sr();Object.defineProperty(ye,"toFile",{enumerable:!0,get:function(){return fs.toFile}})});var S=f(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.APIResource=void 0;var ft=class{constructor(t){this._client=t}};he.APIResource=ft});var ee=f(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.isEmptyHeaders=G.buildHeaders=void 0;var or=A(),ar=Symbol("brand.privateNullableHeaders");function*ir(e){if(!e)return;if(ar in e){let{values:n,nulls:s}=e;yield*n.entries();for(let o of s)yield[o,null];return}let t=!1,r;e instanceof Headers?r=e.entries():(0,or.isReadonlyArray)(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,or.isReadonlyArray)(n[1])?n[1]:[n[1]],a=!1;for(let i of o)i!==void 0&&(t&&!a&&(a=!0,yield[s,null]),yield[s,i])}}var us=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,a]of ir(n)){let i=o.toLowerCase();s.has(i)||(t.delete(o),s.add(i)),a===null?(t.delete(o),r.add(i)):(t.append(o,a),r.delete(i))}}return{[ar]:!0,values:t,nulls:r}};G.buildHeaders=us;var ds=e=>{for(let t of ir(e))return!1;return!0};G.isEmptyHeaders=ds});var qe=f(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.path=g.createPathTagFunction=void 0;g.encodeURIPath=ut;var vs=J();function ut(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var cr=Object.freeze(Object.create(null)),ls=(e=ut)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((u,v,b)=>{/[?#]/.test(v)&&(s=!0);let c=n[b],O=(s?encodeURIComponent:e)(""+c);return b!==n.length&&(c==null||typeof c=="object"&&c.toString===Object.getPrototypeOf(Object.getPrototypeOf(c.hasOwnProperty??cr)??cr)?.toString)&&(O=c+"",o.push({start:u.length+v.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),u+v+(b===n.length?"":O)},""),i=a.split(/[?#]/,1)[0],P=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=P.exec(i))!==null;)o.push({start:p.index,length:p[0].length,error:`Value "${p[0]}" can't be safely passed as a path parameter`});if(o.sort((u,v)=>u.start-v.start),o.length>0){let u=0,v=o.reduce((b,c)=>{let O=" ".repeat(c.start-u),N="^".repeat(c.length);return u=c.start+c.length,b+O+N},"");throw new vs.SupermemoryError(`Path parameters result in path with invalid segments: +var Ae=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var pn=Object.getOwnPropertyNames;var Pn=Object.prototype.hasOwnProperty;var mn=(e,t)=>()=>(e&&(t=e(e=0)),t);var u=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),zn=(e,t)=>{for(var r in t)Ae(e,r,{get:t[r],enumerable:!0})},bn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of pn(t))!Pn.call(e,s)&&s!==r&&Ae(e,s,{get:()=>t[s],enumerable:!(n=ln(t,s))||n.enumerable});return e};var xn=e=>bn(Ae({},"__esModule",{value:!0}),e);var $e=u(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.__setModuleDefault=T.__createBinding=void 0;T.__classPrivateFieldSet=jn;T.__classPrivateFieldGet=On;T.__importStar=Xn;T.__exportStar=yn;function jn(e,t,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(e,r):s?s.value=r:t.set(e,r),r}function On(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var _e=Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]};T.__createBinding=_e;var At=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};T.__setModuleDefault=At;var Qe=function(e){return Qe=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Qe(e)};function Xn(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Qe(e),n=0;n{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.uuid4=void 0;var hn=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return E.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};E.uuid4=hn});var et=u(C=>{"use strict";Object.defineProperty(C,"__esModule",{value:!0});C.castToError=void 0;C.isAbortError=qn;function qn(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var Hn=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};C.castToError=Hn});var J=u(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.InternalServerError=m.RateLimitError=m.UnprocessableEntityError=m.ConflictError=m.NotFoundError=m.PermissionDeniedError=m.AuthenticationError=m.BadRequestError=m.APIConnectionTimeoutError=m.APIConnectionError=m.APIUserAbortError=m.APIError=m.SupermemoryError=void 0;var Wn=et(),de=class extends Error{};m.SupermemoryError=de;var y=class e extends de{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(t,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new I({message:n,cause:(0,Wn.castToError)(r)});let o=r;return t===400?new ve(t,o,n,s):t===401?new le(t,o,n,s):t===403?new pe(t,o,n,s):t===404?new Pe(t,o,n,s):t===409?new me(t,o,n,s):t===422?new ze(t,o,n,s):t===429?new be(t,o,n,s):t>=500?new xe(t,o,n,s):new e(t,o,n,s)}};m.APIError=y;var tt=class extends y{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};m.APIUserAbortError=tt;var I=class extends y{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};m.APIConnectionError=I;var rt=class extends I{constructor({message:t}={}){super({message:t??"Request timed out."})}};m.APIConnectionTimeoutError=rt;var ve=class extends y{};m.BadRequestError=ve;var le=class extends y{};m.AuthenticationError=le;var pe=class extends y{};m.PermissionDeniedError=pe;var Pe=class extends y{};m.NotFoundError=Pe;var me=class extends y{};m.ConflictError=me;var ze=class extends y{};m.UnprocessableEntityError=ze;var be=class extends y{};m.RateLimitError=be;var xe=class extends y{};m.InternalServerError=xe});var A=u(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.safeJSON=p.maybeCoerceBoolean=p.maybeCoerceFloat=p.maybeCoerceInteger=p.coerceBoolean=p.coerceFloat=p.coerceInteger=p.validatePositiveInteger=p.ensurePresent=p.isReadonlyArray=p.isArray=p.isAbsoluteURL=void 0;p.maybeObj=Vn;p.isEmptyObj=Rn;p.hasOwn=gn;p.isObj=wn;var B=J(),Tn=/^[a-z][a-z0-9+.-]*:/i,Nn=e=>Tn.test(e);p.isAbsoluteURL=Nn;var Ln=e=>(p.isArray=Array.isArray,(0,p.isArray)(e));p.isArray=Ln;p.isReadonlyArray=p.isArray;function Vn(e){return typeof e!="object"?{}:e??{}}function Rn(e){if(!e)return!0;for(let t in e)return!1;return!0}function gn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function wn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var Mn=e=>{if(e==null)throw new B.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};p.ensurePresent=Mn;var Zn=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new B.SupermemoryError(`${e} must be an integer`);if(t<0)throw new B.SupermemoryError(`${e} must be a positive integer`);return t};p.validatePositiveInteger=Zn;var Fn=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new B.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};p.coerceInteger=Fn;var Dn=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new B.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};p.coerceFloat=Dn;var Un=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;p.coerceBoolean=Un;var Sn=e=>{if(e!=null)return(0,p.coerceInteger)(e)};p.maybeCoerceInteger=Sn;var Yn=e=>{if(e!=null)return(0,p.coerceFloat)(e)};p.maybeCoerceFloat=Yn;var Gn=e=>{if(e!=null)return(0,p.coerceBoolean)(e)};p.maybeCoerceBoolean=Gn;var kn=e=>{try{return JSON.parse(e)}catch{return}};p.safeJSON=kn});var _t=u(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.sleep=void 0;var Kn=e=>new Promise(t=>setTimeout(t,e));je.sleep=Kn});var nt=u(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.VERSION=void 0;Oe.VERSION="4.0.0"});var rr=u(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.getPlatformHeaders=S.isRunningInBrowser=void 0;var Q=nt(),En=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";S.isRunningInBrowser=En;function Cn(){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 In=()=>{let e=Cn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":er(Deno.build.os),"X-Stainless-Arch":$t(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":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":er(globalThis.process.platform??"unknown"),"X-Stainless-Arch":$t(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Jn();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Jn(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:t,version:`${s}.${o}.${i}`}}}return null}var $t=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",er=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),tr,Bn=()=>tr??(tr=In());S.getPlatformHeaders=Bn});var st=u(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.getDefaultFetch=An;F.makeReadableStream=nr;F.ReadableStreamFrom=Qn;F.ReadableStreamToAsyncIterable=_n;F.CancelReadableStream=$n;function An(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function nr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Qn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return nr({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function _n(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function $n(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var sr=u(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.FallbackEncoder=void 0;var es=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});Xe.FallbackEncoder=es});var _=u(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=ot;j.getName=ye;var ts=st(),rs=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};j.checkFileSupport=rs;function ot(e,t,r){return(0,j.checkFileSupport)(),new File(e,t??"unknown_file",r)}function ye(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var ns=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";j.isAsyncIterable=ns;var ss=async(e,t)=>it(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=ss;var os=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=os;var or=new WeakMap;function is(e){let t=typeof e=="function"?e:e.fetch,r=or.get(t);if(r)return r;let n=(async()=>{try{let s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return or.set(t,n),n}var as=async(e,t)=>{if(!await is(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,s])=>at(r,n,s))),r};j.createForm=as;var ir=e=>e instanceof Blob&&"name"in e,cs=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||ir(e)),it=e=>{if(cs(e))return!0;if(Array.isArray(e))return e.some(it);if(e&&typeof e=="object"){for(let t in e)if(it(e[t]))return!0}return!1},at=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,ot([await r.blob()],ye(r)));else if((0,j.isAsyncIterable)(r))e.append(t,ot([await new Response((0,ts.ReadableStreamFrom)(r)).blob()],ye(r)));else if(ir(r))e.append(t,r,ye(r));else if(Array.isArray(r))await Promise.all(r.map(n=>at(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>at(e,`${t}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var cr=u(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.toFile=vs;var $=_(),fs=_(),ar=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",us=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&ar(e),ds=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function vs(e,t,r){if((0,fs.checkFileSupport)(),e=await e,us(e))return e instanceof File?e:(0,$.makeFile)([await e.arrayBuffer()],e.name);if(ds(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,$.makeFile)(await ct(s),t,r)}let n=await ct(e);if(t||(t=(0,$.getName)(e)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,$.makeFile)(n,t,r)}async function ct(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(ar(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,$.isAsyncIterable)(e))for await(let r of e)t.push(...await ct(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${ls(e)}`)}return t}function ls(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var ut=u(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.toFile=void 0;var ps=cr();Object.defineProperty(he,"toFile",{enumerable:!0,get:function(){return ps.toFile}})});var Y=u(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.APIResource=void 0;var dt=class{constructor(t){this._client=t}};qe.APIResource=dt});var ee=u(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.isEmptyHeaders=G.buildHeaders=void 0;var fr=A(),ur=Symbol("brand.privateNullableHeaders");function*dr(e){if(!e)return;if(ur in e){let{values:n,nulls:s}=e;yield*n.entries();for(let o of s)yield[o,null];return}let t=!1,r;e instanceof Headers?r=e.entries():(0,fr.isReadonlyArray)(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,fr.isReadonlyArray)(n[1])?n[1]:[n[1]],i=!1;for(let a of o)a!==void 0&&(t&&!i&&(i=!0,yield[s,null]),yield[s,a])}}var Ps=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,i]of dr(n)){let a=o.toLowerCase();s.has(a)||(t.delete(o),s.add(a)),i===null?(t.delete(o),r.add(a)):(t.append(o,i),r.delete(a))}}return{[ur]:!0,values:t,nulls:r}};G.buildHeaders=Ps;var ms=e=>{for(let t of dr(e))return!1;return!0};G.isEmptyHeaders=ms});var He=u(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.path=g.createPathTagFunction=void 0;g.encodeURIPath=vt;var zs=J();function vt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var vr=Object.freeze(Object.create(null)),bs=(e=vt)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],i=r.reduce((d,l,b)=>{/[?#]/.test(l)&&(s=!0);let f=n[b],X=(s?encodeURIComponent:e)(""+f);return b!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??vr)??vr)?.toString)&&(X=f+"",o.push({start:d.length+l.length,length:X.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),d+l+(b===n.length?"":X)},""),a=i.split(/[?#]/,1)[0],P=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=P.exec(a))!==null;)o.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(o.sort((d,l)=>d.start-l.start),o.length>0){let d=0,l=o.reduce((b,f)=>{let X=" ".repeat(f.start-d),N="^".repeat(f.length);return d=f.start+f.length,b+X+N},"");throw new zs.SupermemoryError(`Path parameters result in path with invalid segments: ${o.map(b=>b.error).join(` `)} -${a} -${v}`)}return a};g.createPathTagFunction=ls;g.path=(0,g.createPathTagFunction)(ut)});var vt=f(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Connections=void 0;var ps=S(),Ps=ee(),L=qe(),dt=class extends ps.APIResource{create(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/connections/list",{body:t,...r})}configure(t,r,n){return this._client.post((0,L.path)`/v3/connections/${t}/configure`,{body:r,...n})}deleteByID(t,r){return this._client.delete((0,L.path)`/v3/connections/${t}`,r)}deleteByProvider(t,r,n){return this._client.delete((0,L.path)`/v3/connections/${t}`,{body:r,...n})}getByID(t,r){return this._client.get((0,L.path)`/v3/connections/${t}`,r)}getByTag(t,r,n){return this._client.post((0,L.path)`/v3/connections/${t}/connection`,{body:r,...n})}import(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}/import`,{body:r,...n,headers:(0,Ps.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}/documents`,{body:r,...n})}resources(t,r={},n){return this._client.get((0,L.path)`/v3/connections/${t}/resources`,{query:r,...n})}};He.Connections=dt});var Pt=f(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.Documents=void 0;var ms=S(),zs=ee(),bs=_(),lt=qe(),pt=class extends ms.APIResource{update(t,r={},n){return this._client.patch((0,lt.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,lt.path)`/v3/documents/${t}`,{...r,headers:(0,zs.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}batchAdd(t,r){return this._client.post("/v3/documents/batch",{body:t,...r})}deleteBulk(t={},r){return this._client.delete("/v3/documents/bulk",{body:t,...r})}get(t,r){return this._client.get((0,lt.path)`/v3/documents/${t}`,r)}listProcessing(t){return this._client.get("/v3/documents/processing",t)}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,bs.multipartFormRequestOptions)({body:t,...r},this._client))}};We.Documents=pt});var bt=f(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.Memories=void 0;var xs=S(),js=ee(),Xs=_(),mt=qe(),zt=class extends xs.APIResource{update(t,r={},n){return this._client.patch((0,mt.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,mt.path)`/v3/documents/${t}`,{...r,headers:(0,js.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}forget(t,r){return this._client.delete("/v4/memories",{body:t,...r})}get(t,r){return this._client.get((0,mt.path)`/v3/documents/${t}`,r)}updateMemory(t,r){return this._client.patch("/v4/memories",{body:t,...r})}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,Xs.multipartFormRequestOptions)({body:t,...r},this._client))}};Te.Memories=zt});var jt=f(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.Search=void 0;var Os=S(),xt=class extends Os.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};Ne.Search=xt});var Ot=f(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.Settings=void 0;var ys=S(),Xt=class extends ys.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};Le.Settings=Xt});var fr=f(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.Settings=W.Search=W.Memories=W.Documents=W.Connections=void 0;var hs=vt();Object.defineProperty(W,"Connections",{enumerable:!0,get:function(){return hs.Connections}});var qs=Pt();Object.defineProperty(W,"Documents",{enumerable:!0,get:function(){return qs.Documents}});var Hs=bt();Object.defineProperty(W,"Memories",{enumerable:!0,get:function(){return Hs.Memories}});var Ws=jt();Object.defineProperty(W,"Search",{enumerable:!0,get:function(){return Ws.Search}});var Ts=Ot();Object.defineProperty(W,"Settings",{enumerable:!0,get:function(){return Ts.Settings}})});var yt=f(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.formatRequestDetails=D.parseLogLevel=void 0;D.loggerFor=dr;var Ns=A(),Re={off:0,error:200,warn:300,info:400,debug:500},Ls=(e,t,r)=>{if(e){if((0,Ns.hasOwn)(Re,e))return e;dr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Re))}`)}};D.parseLogLevel=Ls;function te(){}function Ve(e,t,r){return!t||Re[e]>Re[r]?te:t[e].bind(t)}var Vs={error:te,warn:te,info:te,debug:te},ur=new WeakMap;function dr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Vs;let n=ur.get(t);if(n&&n[0]===r)return n[1];let s={error:Ve("error",t,r),warn:Ve("warn",t,r),info:Ve("info",t,r),debug:Ve("debug",t,r)};return ur.set(t,[r,s]),s}var Rs=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);D.formatRequestDetails=Rs});var lr=f(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.defaultParseResponse=gs;var vr=yt();async function gs(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,a=await(async()=>{if(r.status===204)return null;if(t.options.__binaryResponse)return r;let P=r.headers.get("content-type")?.split(";")[0]?.trim();return P?.includes("application/json")||P?.endsWith("+json")?await r.json():await r.text()})();return(0,vr.loggerFor)(e).debug(`[${n}] response parsed`,(0,vr.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var Wt=f(ge=>{"use strict";var re;Object.defineProperty(ge,"__esModule",{value:!0});ge.APIPromise=void 0;var qt=Qe(),ws=lr(),Ht=class e extends Promise{constructor(t,r,n=ws.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,re.set(this,void 0),qt.__classPrivateFieldSet(this,re,t,"f")}_thenUnwrap(t){return new e(qt.__classPrivateFieldGet(this,re,"f"),this.responsePromise,async(r,n)=>t(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(qt.__classPrivateFieldGet(this,re,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};ge.APIPromise=Ht;re=new WeakMap});var pr=f(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.readEnv=void 0;var Ms=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};we.readEnv=Ms});var Mt=f(Ze=>{"use strict";var gt,wt,Me,Pr;Object.defineProperty(Ze,"__esModule",{value:!0});Ze.Supermemory=void 0;var w=Qe(),Zs=It(),Tt=A(),Fs=Jt(),Nt=_e(),Ds=_t(),Lt=w.__importStar(rt()),Us=w.__importStar(er()),Ys=tt(),x=w.__importStar(J()),Ss=w.__importStar(ct()),ne=w.__importStar(fr()),Gs=Wt(),ks=vt(),Ks=Pt(),Es=bt(),Cs=jt(),Is=Ot(),Vt=ee(),Rt=pr(),X=yt(),Js=A(),z=class{constructor({baseURL:t=(0,Rt.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Rt.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(gt.add(this),Me.set(this,void 0),this.memories=new ne.Memories(this),this.documents=new ne.Documents(this),this.search=new ne.Search(this),this.settings=new ne.Settings(this),this.connections=new ne.Connections(this),r===void 0)throw new x.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:t||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??wt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,X.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,X.parseLogLevel)((0,Rt.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Lt.getDefaultFetch(),w.__classPrivateFieldSet(this,Me,Us.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,Vt.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Object.entries(t).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new x.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Ys.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,Zs.uuid4)()}`}makeStatusError(t,r,n,s){return x.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!w.__classPrivateFieldGet(this,gt,"m",Pr).call(this)&&n||this.baseURL,o=(0,Tt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,Js.isEmptyObj)(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(s=>({method:t,path:r,...s})))}request(t,r=null){return new Gs.APIPromise(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let s=await t,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:a,url:i,timeout:P}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(a,{url:i,options:s});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,v=Date.now();if((0,X.loggerFor)(this).debug(`[${p}] sending request`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:i,options:s,headers:a.headers})),s.signal?.aborted)throw new x.APIUserAbortError;let b=new AbortController,c=await this.fetchWithTimeout(i,a,P,b).catch(Nt.castToError),O=Date.now();if(c instanceof globalThis.Error){let V=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new x.APIUserAbortError;let q=(0,Nt.isAbortError)(c)||/timed? ?out/i.test(String(c)+("cause"in c?String(c.cause):""));if(r)return(0,X.loggerFor)(this).info(`[${p}] connection ${q?"timed out":"failed"} - ${V}`),(0,X.loggerFor)(this).debug(`[${p}] connection ${q?"timed out":"failed"} (${V})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:O-v,message:c.message})),this.retryRequest(s,r,n??p);throw(0,X.loggerFor)(this).info(`[${p}] connection ${q?"timed out":"failed"} - error; no more retries left`),(0,X.loggerFor)(this).debug(`[${p}] connection ${q?"timed out":"failed"} (error; no more retries left)`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:O-v,message:c.message})),q?new x.APIConnectionTimeoutError:new x.APIConnectionError({cause:c})}let N=`[${p}${u}] ${a.method} ${i} ${c.ok?"succeeded":"failed"} with status ${c.status} in ${O-v}ms`;if(!c.ok){let V=await this.shouldRetry(c);if(r&&V){let Z=`retrying, ${r} attempts remaining`;return await Lt.CancelReadableStream(c.body),(0,X.loggerFor)(this).info(`${N} - ${Z}`),(0,X.loggerFor)(this).debug(`[${p}] response error (${Z})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:c.url,status:c.status,headers:c.headers,durationMs:O-v})),this.retryRequest(s,r,n??p,c.headers)}let q=V?"error; no more retries left":"error; not retryable";(0,X.loggerFor)(this).info(`${N} - ${q}`);let K=await c.text().catch(Z=>(0,Nt.castToError)(Z).message),fe=(0,Tt.safeJSON)(K),H=fe?void 0:K;throw(0,X.loggerFor)(this).debug(`[${p}] response error (${q})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:c.url,status:c.status,headers:c.headers,message:H,durationMs:Date.now()-v})),this.makeStatusError(c.status,fe,H,c.headers)}return(0,X.loggerFor)(this).info(N),(0,X.loggerFor)(this).debug(`[${p}] response start`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:c.url,status:c.status,headers:c.headers,durationMs:O-v})),{response:c,options:s,controller:b,requestLogID:p,retryOfRequestLogID:n,startTime:v}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:a,...i}=r||{};o&&o.addEventListener("abort",()=>s.abort());let P=setTimeout(()=>s.abort(),n),p=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,u={signal:s.signal,...p?{duplex:"half"}:{},method:"GET",...i};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,u)}finally{clearTimeout(P)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,s){let o,a=s?.get("retry-after-ms");if(a){let P=parseFloat(a);Number.isNaN(P)||(o=P)}let i=s?.get("retry-after");if(i&&!o){let P=parseFloat(i);Number.isNaN(P)?o=Date.parse(i)-Date.now():o=P*1e3}if(!(o&&0<=o&&o<60*1e3)){let P=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,P)}return await(0,Fs.sleep)(o),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let o=r-t,a=Math.min(.5*Math.pow(2,o),8),i=1-Math.random()*.25;return a*i*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:s,path:o,query:a,defaultBaseURL:i}=n,P=this.buildURL(o,a,i);"timeout"in n&&(0,Tt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:p,body:u}=this.buildBody({options:n}),v=await this.buildHeaders({options:t,method:s,bodyHeaders:p,retryCount:r});return{req:{method:s,headers:v,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:P,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let a=(0,Vt.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...(0,Ds.getPlatformHeaders)()},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,Vt.buildHeaders)([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Lt.ReadableStreamFrom(t)}:w.__classPrivateFieldGet(this,Me,"f").call(this,{body:t,headers:n})}};Ze.Supermemory=z;wt=z,Me=new WeakMap,gt=new WeakSet,Pr=function(){return this.baseURL!=="https://api.supermemory.ai"};z.Supermemory=wt;z.DEFAULT_TIMEOUT=6e4;z.SupermemoryError=x.SupermemoryError;z.APIError=x.APIError;z.APIConnectionError=x.APIConnectionError;z.APIConnectionTimeoutError=x.APIConnectionTimeoutError;z.APIUserAbortError=x.APIUserAbortError;z.NotFoundError=x.NotFoundError;z.ConflictError=x.ConflictError;z.RateLimitError=x.RateLimitError;z.BadRequestError=x.BadRequestError;z.AuthenticationError=x.AuthenticationError;z.InternalServerError=x.InternalServerError;z.PermissionDeniedError=x.PermissionDeniedError;z.UnprocessableEntityError=x.UnprocessableEntityError;z.toFile=Ss.toFile;z.Memories=Es.Memories;z.Documents=Ks.Documents;z.Search=Cs.Search;z.Settings=Is.Settings;z.Connections=ks.Connections});var zr=f((d,mr)=>{"use strict";d=mr.exports=function(...e){return new d.default(...e)};Object.defineProperty(d,"__esModule",{value:!0});d.UnprocessableEntityError=d.PermissionDeniedError=d.InternalServerError=d.AuthenticationError=d.BadRequestError=d.RateLimitError=d.ConflictError=d.NotFoundError=d.APIUserAbortError=d.APIConnectionTimeoutError=d.APIConnectionError=d.APIError=d.SupermemoryError=d.Supermemory=d.APIPromise=d.toFile=d.default=void 0;var Bs=Mt();Object.defineProperty(d,"default",{enumerable:!0,get:function(){return Bs.Supermemory}});var As=ct();Object.defineProperty(d,"toFile",{enumerable:!0,get:function(){return As.toFile}});var Qs=Wt();Object.defineProperty(d,"APIPromise",{enumerable:!0,get:function(){return Qs.APIPromise}});var _s=Mt();Object.defineProperty(d,"Supermemory",{enumerable:!0,get:function(){return _s.Supermemory}});var h=J();Object.defineProperty(d,"SupermemoryError",{enumerable:!0,get:function(){return h.SupermemoryError}});Object.defineProperty(d,"APIError",{enumerable:!0,get:function(){return h.APIError}});Object.defineProperty(d,"APIConnectionError",{enumerable:!0,get:function(){return h.APIConnectionError}});Object.defineProperty(d,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return h.APIConnectionTimeoutError}});Object.defineProperty(d,"APIUserAbortError",{enumerable:!0,get:function(){return h.APIUserAbortError}});Object.defineProperty(d,"NotFoundError",{enumerable:!0,get:function(){return h.NotFoundError}});Object.defineProperty(d,"ConflictError",{enumerable:!0,get:function(){return h.ConflictError}});Object.defineProperty(d,"RateLimitError",{enumerable:!0,get:function(){return h.RateLimitError}});Object.defineProperty(d,"BadRequestError",{enumerable:!0,get:function(){return h.BadRequestError}});Object.defineProperty(d,"AuthenticationError",{enumerable:!0,get:function(){return h.AuthenticationError}});Object.defineProperty(d,"InternalServerError",{enumerable:!0,get:function(){return h.InternalServerError}});Object.defineProperty(d,"PermissionDeniedError",{enumerable:!0,get:function(){return h.PermissionDeniedError}});Object.defineProperty(d,"UnprocessableEntityError",{enumerable:!0,get:function(){return h.UnprocessableEntityError}})});var xr={};vn(xr,{getRequestIntegrity:()=>vo,sanitizeContent:()=>ro,sanitizeMetadata:()=>io,validateApiKeyFormat:()=>$s,validateContainerTag:()=>eo,validateContentLength:()=>no,validateRecallConfig:()=>co});function $s(e){return!e||typeof e!="string"?{valid:!1,reason:"key is empty or not a string"}:e.startsWith("sm_")?e.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(e)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function eo(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function ro(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of to)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function no(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function io(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=so)break;n.length>oo||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,ao),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function co(e,t){let r=[];return(!Number.isInteger(e)||e<1||e>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(t)||t<1||t>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Zt(e){return(0,Fe.createHash)("sha256").update(e).digest("hex")}function uo(e,t){let r=[Zt(e),Zt(t),br].join(":");return(0,Fe.createHmac)("sha256",fo).update(r).digest("base64url")}function vo(e,t){let r=Zt(t),n=uo(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${br}`,n].join(".")}}var Fe,to,so,oo,ao,br,fo,jr=dn(()=>{Fe=require("node:crypto");to=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];so=50,oo=128,ao=1024;br=1,fo="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Ft=f((fi,Xr)=>{var lo="https://api.supermemory.ai";Xr.exports={BASE_URL:lo}});var yr=f((ui,Or)=>{var po=zr().default,{getRequestIntegrity:Po,validateApiKeyFormat:mo,validateContainerTag:zo}=(jr(),pn(xr)),{BASE_URL:bo}=Ft(),xo="claudecode_default";function jo(e,t=r=>r){let r=new Set;return e.filter(n=>{let s=String(t(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var Xo=`Developer coding session transcript. Focus on USER message and intent. +${i} +${l}`)}return i};g.createPathTagFunction=bs;g.path=(0,g.createPathTagFunction)(vt)});var pt=u(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.Connections=void 0;var xs=Y(),js=ee(),L=He(),lt=class extends xs.APIResource{create(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/connections/list",{body:t,...r})}configure(t,r,n){return this._client.post((0,L.path)`/v3/connections/${t}/configure`,{body:r,...n})}deleteByID(t,r){return this._client.delete((0,L.path)`/v3/connections/${t}`,r)}deleteByProvider(t,r,n){return this._client.delete((0,L.path)`/v3/connections/${t}`,{body:r,...n})}getByID(t,r){return this._client.get((0,L.path)`/v3/connections/${t}`,r)}getByTag(t,r,n){return this._client.post((0,L.path)`/v3/connections/${t}/connection`,{body:r,...n})}import(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}/import`,{body:r,...n,headers:(0,js.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}/documents`,{body:r,...n})}resources(t,r={},n){return this._client.get((0,L.path)`/v3/connections/${t}/resources`,{query:r,...n})}};We.Connections=lt});var zt=u(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.Documents=void 0;var Os=Y(),Xs=ee(),ys=_(),Pt=He(),mt=class extends Os.APIResource{update(t,r={},n){return this._client.patch((0,Pt.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,Pt.path)`/v3/documents/${t}`,{...r,headers:(0,Xs.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}batchAdd(t,r){return this._client.post("/v3/documents/batch",{body:t,...r})}deleteBulk(t={},r){return this._client.delete("/v3/documents/bulk",{body:t,...r})}get(t,r){return this._client.get((0,Pt.path)`/v3/documents/${t}`,r)}listProcessing(t){return this._client.get("/v3/documents/processing",t)}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,ys.multipartFormRequestOptions)({body:t,...r},this._client))}};Te.Documents=mt});var jt=u(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.Memories=void 0;var hs=Y(),qs=ee(),Hs=_(),bt=He(),xt=class extends hs.APIResource{update(t,r={},n){return this._client.patch((0,bt.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,bt.path)`/v3/documents/${t}`,{...r,headers:(0,qs.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}forget(t,r){return this._client.delete("/v4/memories",{body:t,...r})}get(t,r){return this._client.get((0,bt.path)`/v3/documents/${t}`,r)}updateMemory(t,r){return this._client.patch("/v4/memories",{body:t,...r})}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,Hs.multipartFormRequestOptions)({body:t,...r},this._client))}};Ne.Memories=xt});var Xt=u(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.Search=void 0;var Ws=Y(),Ot=class extends Ws.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};Le.Search=Ot});var ht=u(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Settings=void 0;var Ts=Y(),yt=class extends Ts.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};Ve.Settings=yt});var lr=u(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.Settings=W.Search=W.Memories=W.Documents=W.Connections=void 0;var Ns=pt();Object.defineProperty(W,"Connections",{enumerable:!0,get:function(){return Ns.Connections}});var Ls=zt();Object.defineProperty(W,"Documents",{enumerable:!0,get:function(){return Ls.Documents}});var Vs=jt();Object.defineProperty(W,"Memories",{enumerable:!0,get:function(){return Vs.Memories}});var Rs=Xt();Object.defineProperty(W,"Search",{enumerable:!0,get:function(){return Rs.Search}});var gs=ht();Object.defineProperty(W,"Settings",{enumerable:!0,get:function(){return gs.Settings}})});var qt=u(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.formatRequestDetails=D.parseLogLevel=void 0;D.loggerFor=Pr;var ws=A(),ge={off:0,error:200,warn:300,info:400,debug:500},Ms=(e,t,r)=>{if(e){if((0,ws.hasOwn)(ge,e))return e;Pr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(ge))}`)}};D.parseLogLevel=Ms;function te(){}function Re(e,t,r){return!t||ge[e]>ge[r]?te:t[e].bind(t)}var Zs={error:te,warn:te,info:te,debug:te},pr=new WeakMap;function Pr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Zs;let n=pr.get(t);if(n&&n[0]===r)return n[1];let s={error:Re("error",t,r),warn:Re("warn",t,r),info:Re("info",t,r),debug:Re("debug",t,r)};return pr.set(t,[r,s]),s}var Fs=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);D.formatRequestDetails=Fs});var zr=u(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.defaultParseResponse=Ds;var mr=qt();async function Ds(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,i=await(async()=>{if(r.status===204)return null;if(t.options.__binaryResponse)return r;let P=r.headers.get("content-type")?.split(";")[0]?.trim();return P?.includes("application/json")||P?.endsWith("+json")?await r.json():await r.text()})();return(0,mr.loggerFor)(e).debug(`[${n}] response parsed`,(0,mr.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}});var Nt=u(we=>{"use strict";var re;Object.defineProperty(we,"__esModule",{value:!0});we.APIPromise=void 0;var Wt=$e(),Us=zr(),Tt=class e extends Promise{constructor(t,r,n=Us.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,re.set(this,void 0),Wt.__classPrivateFieldSet(this,re,t,"f")}_thenUnwrap(t){return new e(Wt.__classPrivateFieldGet(this,re,"f"),this.responsePromise,async(r,n)=>t(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(Wt.__classPrivateFieldGet(this,re,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};we.APIPromise=Tt;re=new WeakMap});var br=u(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.readEnv=void 0;var Ss=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};Me.readEnv=Ss});var Ft=u(Fe=>{"use strict";var Mt,Zt,Ze,xr;Object.defineProperty(Fe,"__esModule",{value:!0});Fe.Supermemory=void 0;var w=$e(),Ys=Qt(),Lt=A(),Gs=_t(),Vt=et(),ks=rr(),Rt=w.__importStar(st()),Ks=w.__importStar(sr()),Es=nt(),x=w.__importStar(J()),Cs=w.__importStar(ut()),ne=w.__importStar(lr()),Is=Nt(),Js=pt(),Bs=zt(),As=jt(),Qs=Xt(),_s=ht(),gt=ee(),wt=br(),O=qt(),$s=A(),z=class{constructor({baseURL:t=(0,wt.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,wt.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Mt.add(this),Ze.set(this,void 0),this.memories=new ne.Memories(this),this.documents=new ne.Documents(this),this.search=new ne.Search(this),this.settings=new ne.Settings(this),this.connections=new ne.Connections(this),r===void 0)throw new x.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:t||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??Zt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,O.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,O.parseLogLevel)((0,wt.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Rt.getDefaultFetch(),w.__classPrivateFieldSet(this,Ze,Ks.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,gt.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Object.entries(t).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new x.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Es.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,Ys.uuid4)()}`}makeStatusError(t,r,n,s){return x.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!w.__classPrivateFieldGet(this,Mt,"m",xr).call(this)&&n||this.baseURL,o=(0,Lt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return(0,$s.isEmptyObj)(i)||(r={...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(s=>({method:t,path:r,...s})))}request(t,r=null){return new Is.APIPromise(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let s=await t,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:i,url:a,timeout:P}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:s});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,l=Date.now();if((0,O.loggerFor)(this).debug(`[${c}] sending request`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:a,options:s,headers:i.headers})),s.signal?.aborted)throw new x.APIUserAbortError;let b=new AbortController,f=await this.fetchWithTimeout(a,i,P,b).catch(Vt.castToError),X=Date.now();if(f instanceof globalThis.Error){let V=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new x.APIUserAbortError;let q=(0,Vt.isAbortError)(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(r)return(0,O.loggerFor)(this).info(`[${c}] connection ${q?"timed out":"failed"} - ${V}`),(0,O.loggerFor)(this).debug(`[${c}] connection ${q?"timed out":"failed"} (${V})`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:a,durationMs:X-l,message:f.message})),this.retryRequest(s,r,n??c);throw(0,O.loggerFor)(this).info(`[${c}] connection ${q?"timed out":"failed"} - error; no more retries left`),(0,O.loggerFor)(this).debug(`[${c}] connection ${q?"timed out":"failed"} (error; no more retries left)`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:a,durationMs:X-l,message:f.message})),q?new x.APIConnectionTimeoutError:new x.APIConnectionError({cause:f})}let N=`[${c}${d}] ${i.method} ${a} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${X-l}ms`;if(!f.ok){let V=await this.shouldRetry(f);if(r&&V){let Z=`retrying, ${r} attempts remaining`;return await Rt.CancelReadableStream(f.body),(0,O.loggerFor)(this).info(`${N} - ${Z}`),(0,O.loggerFor)(this).debug(`[${c}] response error (${Z})`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:X-l})),this.retryRequest(s,r,n??c,f.headers)}let q=V?"error; no more retries left":"error; not retryable";(0,O.loggerFor)(this).info(`${N} - ${q}`);let K=await f.text().catch(Z=>(0,Vt.castToError)(Z).message),ue=(0,Lt.safeJSON)(K),H=ue?void 0:K;throw(0,O.loggerFor)(this).debug(`[${c}] response error (${q})`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:H,durationMs:Date.now()-l})),this.makeStatusError(f.status,ue,H,f.headers)}return(0,O.loggerFor)(this).info(N),(0,O.loggerFor)(this).debug(`[${c}] response start`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:X-l})),{response:f,options:s,controller:b,requestLogID:c,retryOfRequestLogID:n,startTime:l}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:i,...a}=r||{};o&&o.addEventListener("abort",()=>s.abort());let P=setTimeout(()=>s.abort(),n),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:s.signal,...c?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,d)}finally{clearTimeout(P)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,s){let o,i=s?.get("retry-after-ms");if(i){let P=parseFloat(i);Number.isNaN(P)||(o=P)}let a=s?.get("retry-after");if(a&&!o){let P=parseFloat(a);Number.isNaN(P)?o=Date.parse(a)-Date.now():o=P*1e3}if(!(o&&0<=o&&o<60*1e3)){let P=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,P)}return await(0,Gs.sleep)(o),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let o=r-t,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:s,path:o,query:i,defaultBaseURL:a}=n,P=this.buildURL(o,i,a);"timeout"in n&&(0,Lt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:d}=this.buildBody({options:n}),l=await this.buildHeaders({options:t,method:s,bodyHeaders:c,retryCount:r});return{req:{method:s,headers:l,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:P,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let i=(0,gt.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...(0,ks.getPlatformHeaders)()},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,gt.buildHeaders)([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Rt.ReadableStreamFrom(t)}:w.__classPrivateFieldGet(this,Ze,"f").call(this,{body:t,headers:n})}};Fe.Supermemory=z;Zt=z,Ze=new WeakMap,Mt=new WeakSet,xr=function(){return this.baseURL!=="https://api.supermemory.ai"};z.Supermemory=Zt;z.DEFAULT_TIMEOUT=6e4;z.SupermemoryError=x.SupermemoryError;z.APIError=x.APIError;z.APIConnectionError=x.APIConnectionError;z.APIConnectionTimeoutError=x.APIConnectionTimeoutError;z.APIUserAbortError=x.APIUserAbortError;z.NotFoundError=x.NotFoundError;z.ConflictError=x.ConflictError;z.RateLimitError=x.RateLimitError;z.BadRequestError=x.BadRequestError;z.AuthenticationError=x.AuthenticationError;z.InternalServerError=x.InternalServerError;z.PermissionDeniedError=x.PermissionDeniedError;z.UnprocessableEntityError=x.UnprocessableEntityError;z.toFile=Cs.toFile;z.Memories=As.Memories;z.Documents=Bs.Documents;z.Search=Qs.Search;z.Settings=_s.Settings;z.Connections=Js.Connections});var Or=u((v,jr)=>{"use strict";v=jr.exports=function(...e){return new v.default(...e)};Object.defineProperty(v,"__esModule",{value:!0});v.UnprocessableEntityError=v.PermissionDeniedError=v.InternalServerError=v.AuthenticationError=v.BadRequestError=v.RateLimitError=v.ConflictError=v.NotFoundError=v.APIUserAbortError=v.APIConnectionTimeoutError=v.APIConnectionError=v.APIError=v.SupermemoryError=v.Supermemory=v.APIPromise=v.toFile=v.default=void 0;var eo=Ft();Object.defineProperty(v,"default",{enumerable:!0,get:function(){return eo.Supermemory}});var to=ut();Object.defineProperty(v,"toFile",{enumerable:!0,get:function(){return to.toFile}});var ro=Nt();Object.defineProperty(v,"APIPromise",{enumerable:!0,get:function(){return ro.APIPromise}});var no=Ft();Object.defineProperty(v,"Supermemory",{enumerable:!0,get:function(){return no.Supermemory}});var h=J();Object.defineProperty(v,"SupermemoryError",{enumerable:!0,get:function(){return h.SupermemoryError}});Object.defineProperty(v,"APIError",{enumerable:!0,get:function(){return h.APIError}});Object.defineProperty(v,"APIConnectionError",{enumerable:!0,get:function(){return h.APIConnectionError}});Object.defineProperty(v,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return h.APIConnectionTimeoutError}});Object.defineProperty(v,"APIUserAbortError",{enumerable:!0,get:function(){return h.APIUserAbortError}});Object.defineProperty(v,"NotFoundError",{enumerable:!0,get:function(){return h.NotFoundError}});Object.defineProperty(v,"ConflictError",{enumerable:!0,get:function(){return h.ConflictError}});Object.defineProperty(v,"RateLimitError",{enumerable:!0,get:function(){return h.RateLimitError}});Object.defineProperty(v,"BadRequestError",{enumerable:!0,get:function(){return h.BadRequestError}});Object.defineProperty(v,"AuthenticationError",{enumerable:!0,get:function(){return h.AuthenticationError}});Object.defineProperty(v,"InternalServerError",{enumerable:!0,get:function(){return h.InternalServerError}});Object.defineProperty(v,"PermissionDeniedError",{enumerable:!0,get:function(){return h.PermissionDeniedError}});Object.defineProperty(v,"UnprocessableEntityError",{enumerable:!0,get:function(){return h.UnprocessableEntityError}})});var yr={};zn(yr,{getRequestIntegrity:()=>zo,sanitizeContent:()=>ao,sanitizeMetadata:()=>lo,validateApiKeyFormat:()=>so,validateContainerTag:()=>oo,validateContentLength:()=>co,validateRecallConfig:()=>po});function so(e){return!e||typeof e!="string"?{valid:!1,reason:"key is empty or not a string"}:e.startsWith("sm_")?e.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(e)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function oo(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function ao(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of io)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function co(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function lo(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=fo)break;n.length>uo||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,vo),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function po(e,t){let r=[];return(!Number.isInteger(e)||e<1||e>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(t)||t<1||t>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Dt(e){return(0,De.createHash)("sha256").update(e).digest("hex")}function mo(e,t){let r=[Dt(e),Dt(t),Xr].join(":");return(0,De.createHmac)("sha256",Po).update(r).digest("base64url")}function zo(e,t){let r=Dt(t),n=mo(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${Xr}`,n].join(".")}}var De,io,fo,uo,vo,Xr,Po,hr=mn(()=>{De=require("node:crypto");io=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];fo=50,uo=128,vo=1024;Xr=1,Po="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Ut=u((ja,qr)=>{var bo="https://api.supermemory.ai";qr.exports={BASE_URL:bo}});var Wr=u((Oa,Hr)=>{var xo=Or().default,{getRequestIntegrity:jo,validateApiKeyFormat:Oo,validateContainerTag:Xo}=(hr(),xn(yr)),{BASE_URL:yo}=Ut(),ho="claudecode_default";function qo(e,t=r=>r){let r=new Set;return e.filter(n=>{let s=String(t(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var Ho=`Developer coding session transcript. Focus on USER message and intent. RULES: - Extract USER's action/intent, not every detail assistant provides matter @@ -30,7 +30,7 @@ EXAMPLES: SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,Oo=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,Wo=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" @@ -43,80 +43,80 @@ EXAMPLES: | Input | Memory | | "The auth flow works by..." | "Auth flow: [description]" | | "We structure components like..." | "Component structure convention: [pattern]" | -| "To add a new API route..." | "Adding API routes: [steps]" |`,Dt=class{constructor(t,r,n={}){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=mo(t);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||xo,a=zo(o);a.valid||console.warn(`Container tag warning: ${a.reason}`);let i=Po(t,o);this.client=new po({apiKey:t,baseURL:n.baseUrl||bo,defaultHeaders:{...i,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let a=await this.client.add(o);return{id:a.id,status:a.status,containerTag:r||this.containerTag}}async search(t,r,n={}){let s=await this.client.search.memories({q:t,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(a=>({memory:a.content||a.memory||a.context||"",chunk:a.chunk,metadata:a.metadata,updatedAt:a.updatedAt,similarity:a.similarity}));return{results:jo(o,a=>a.memory),total:s.total,timing:s.timing}}async getProfile(t,r){let n=await this.client.profile({containerTag:t||this.containerTag,q:r}),s=new Set,o=(p,u=v=>v)=>p.filter(v=>{let b=String(u(v)).toLowerCase().trim();return!b||s.has(b)?!1:(s.add(b),!0)}),a=o(n.profile?.static||[]),i=o(n.profile?.dynamic||[]),P;if(n.searchResults){let p=n.searchResults.results.map(u=>({id:u.id,memory:u.content||u.context||"",similarity:u.similarity,title:u.title,updatedAt:u.updatedAt}));P={results:o(p,u=>u.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:i},searchResults:P}}};Or.exports={SupermemoryClient:Dt,PERSONAL_ENTITY_CONTEXT:Xo,REPO_ENTITY_CONTEXT:Oo}});var Ut=f((di,hr)=>{var{execSync:De}=require("node:child_process"),se=require("node:path");function yo(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return De("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=De("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return De("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=se.resolve(e,r);return se.basename(n)===".git"&&!n.includes(`${se.sep}.git${se.sep}`)?se.dirname(n):De("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}hr.exports={getGitRoot:yo}});var Ye=f((vi,Lr)=>{var oe=require("node:fs"),Ue=require("node:path"),{getGitRoot:qr}=Ut(),Hr=Ue.join(".claude",".supermemory-claude"),Wr="config.json";function Tr(e){let r=qr(e)||e;return Ue.join(r,Hr,Wr)}function Nr(e){try{let t=Tr(e);if(oe.existsSync(t))return JSON.parse(oe.readFileSync(t,"utf-8"))}catch{}return null}function ho(e,t){let n=qr(e)||e,s=Ue.join(n,Hr),o=Ue.join(s,Wr);oe.existsSync(s)||oe.mkdirSync(s,{recursive:!0});let i={...Nr(e)||{},...t};return oe.writeFileSync(o,JSON.stringify(i,null,2)),o}Lr.exports={getConfigPath:Tr,loadProjectConfig:Nr,saveProjectConfig:ho}});var wr=f((li,gr)=>{var{execSync:qo}=require("node:child_process"),Ho=require("node:crypto"),{loadProjectConfig:Vr}=Ye(),{getGitRoot:Se}=Ut();function Rr(e){return Ho.createHash("sha256").update(e).digest("hex").slice(0,16)}function Yt(e){try{let r=qo("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/);return r?r[1]:null}catch{return null}}function Wo(e){let t=Vr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Se(e)||e;return`claudecode_project_${Rr(n)}`}function To(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function No(e){let t=Vr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Se(e)||e,o=Yt(n)||n.split("/").pop()||"unknown";return`repo_${To(o)}`}function Lo(e){let r=Se(e)||e;return Yt(r)||r.split("/").pop()||"unknown"}gr.exports={sha256:Rr,getGitRoot:Se,getGitRepoName:Yt,getContainerTag:Wo,getRepoContainerTag:No,getProjectName:Lo}});var Zr=f((pi,Mr)=>{var{execFile:Vo}=require("node:child_process");function Ge(e,t){return new Promise((r,n)=>{Vo(e,t,{windowsHide:!0},s=>{s?n(s):r()})})}async function Ro(e){let t=e.toString();if(!/^https?:\/\//i.test(t))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await Ge("rundll32.exe",["url.dll,FileProtocolHandler",t]);return}catch{}await Ge("cmd.exe",["/c","start",'""',t]);return}if(process.platform==="darwin"){await Ge("open",[t]);return}await Ge("xdg-open",[t])}Mr.exports={openUrl:Ro}});var Fr=f((Pi,go)=>{go.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var Dr=f((mi,wo)=>{wo.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var kt=f((zi,Gr)=>{var Mo=require("node:http"),U=require("node:fs"),Ur=require("node:path"),Zo=require("node:os"),{openUrl:Fo}=Zr(),Do=Fr(),Uo=Dr(),Gt=Ur.join(Zo.homedir(),".supermemory-claude"),k=Ur.join(Gt,"credentials.json"),Yr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",St=19876,Yo=25e3;function So(){U.existsSync(Gt)||U.mkdirSync(Gt,{recursive:!0})}function Go(){try{if(U.existsSync(k)){let e=JSON.parse(U.readFileSync(k,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Sr(e){So();let t={apiKey:e,savedAt:new Date().toISOString()};U.writeFileSync(k,JSON.stringify(t,null,2))}function ko(){try{U.existsSync(k)&&U.unlinkSync(k)}catch{}}function Ko(){return new Promise((e,t)=>{let r=!1,n=Mo.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${St}`);if(a.pathname==="/callback"){let i=a.searchParams.get("apikey")||a.searchParams.get("api_key");i?.startsWith("sm_")?(Sr(i),o.writeHead(200,{"Content-Type":"text/html"}),o.end(Do),r=!0,n.close(),e(i)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(Uo))}else o.writeHead(404),o.end("Not found")});n.listen(St,"127.0.0.1",()=>{let s=`http://localhost:${St}/callback`,o=`${Yr}?callback=${encodeURIComponent(s)}&client=claude_code`;Fo(o).catch(a=>{r||(n.close(),t(new Error(`Failed to open browser: ${a.message}`)))})}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},Yo)})}Gr.exports={AUTH_BASE_URL:Yr,CREDENTIALS_FILE:k,loadCredentials:Go,saveCredentials:Sr,clearCredentials:ko,startAuthFlow:Ko}});var Er=f((bi,Kr)=>{var ie=require("node:fs"),kr=require("node:path"),Eo=require("node:os"),{loadCredentials:Co}=kt(),{loadProjectConfig:ce}=Ye(),{BASE_URL:Io}=Ft(),ke=kr.join(Eo.homedir(),".supermemory-claude"),ae=kr.join(ke,"settings.json"),Ke={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Jo(){ie.existsSync(ke)||ie.mkdirSync(ke,{recursive:!0})}function Ee(){let e={...Ke};try{if(ie.existsSync(ae)){let t=ie.readFileSync(ae,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${ae}: ${t.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function Bo(e){Jo();let t={...e};delete t.apiKey,ie.writeFileSync(ae,JSON.stringify(t,null,2))}function Ao(e,t,r){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||ce(t||process.cwd()),r?.apiKey)return r.apiKey;let n=Co();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function Qo(e){if(typeof e!="string"||!e.trim())return null;let t=e.trim();try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t}catch{return null}}function _o(e,t){t=t||ce(e||process.cwd());let r=process.env.SUPERMEMORY_API_URL||t?.baseUrl||Io,n=Qo(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function $o(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function ea(e){let t=Ee(),r=ce(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function ta(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function ra(e){let t=Ee(),r=ce(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Ke.signalKeywords,i=r?.signalKeywords||[],P=[...new Set([...a,...i])].map(u=>u.toLowerCase()),p=r?.signalTurnsBefore||t.signalTurnsBefore||Ke.signalTurnsBefore;return{enabled:o,keywords:P,turnsBefore:p}}function na(e){let t=Ee();return{directive:ce(e||process.cwd())?.recallDirective||t.recallDirective||null}}Kr.exports={SETTINGS_DIR:ke,SETTINGS_FILE:ae,DEFAULT_SETTINGS:Ke,loadSettings:Ee,saveSettings:Bo,getApiKey:Ao,getBaseUrl:_o,debugLog:$o,getIncludeTools:ea,shouldIncludeTool:ta,getSignalConfig:ra,getRecallConfig:na}});var Ir=f((xi,Cr)=>{async function sa(){return new Promise((e,t)=>{let r="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{r+=n}),process.stdin.on("end",()=>{try{e(r.trim()?JSON.parse(r):{})}catch(n){t(new Error(`Failed to parse stdin JSON: ${n.message}`))}}),process.stdin.on("error",t),process.stdin.isTTY&&e({})})}function Ce(e){console.log(JSON.stringify(e))}function oa(e=null){Ce(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function aa(e){console.error(`Supermemory: ${e}`),Ce({continue:!0,suppressOutput:!0})}Cr.exports={readStdin:sa,writeOutput:Ce,outputSuccess:oa,outputError:aa}});var Qr=f((ji,Ar)=>{var Jr="The following is recalled context. Reference it only when relevant to the conversation.",Br="Use these memories naturally when relevant \u2014 including indirect connections \u2014 but don't force them into every response or make assumptions beyond what's stated.";function Kt(e){try{let t=new Date(e),r=new Date,n=(r.getTime()-t.getTime())/1e3,s=n/60,o=n/3600,a=n/86400;if(s<30)return"just now";if(s<60)return`${Math.floor(s)}mins ago`;if(o<24)return`${Math.floor(o)}hrs ago`;if(a<7)return`${Math.floor(a)}d ago`;let i=t.toLocaleString("en",{month:"short"});return t.getFullYear()===r.getFullYear()?`${t.getDate()} ${i}`:`${t.getDate()} ${i}, ${t.getFullYear()}`}catch{return""}}function ia(e,t=!0,r=!1,n=10,s=!0){if(!e)return null;let o=t?(e.profile?.static||[]).slice(0,n):[],a=t?(e.profile?.dynamic||[]).slice(0,n):[],i=r?(e.searchResults?.results||[]).slice(0,n):[];if(o.length===0&&a.length===0&&i.length===0)return null;let P=[];if(o.length>0){let u=o.map(v=>`- ${v}`).join(` +| "To add a new API route..." | "Adding API routes: [steps]" |`,St=class{constructor(t,r,n={}){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=Oo(t);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||ho,i=Xo(o);i.valid||console.warn(`Container tag warning: ${i.reason}`);let a=jo(t,o);this.client=new xo({apiKey:t,baseURL:n.baseUrl||yo,defaultHeaders:{...a,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let i=await this.client.add(o);return{id:i.id,status:i.status,containerTag:r||this.containerTag}}async search(t,r,n={}){let s=await this.client.search.memories({q:t,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(i=>({memory:i.content||i.memory||i.context||"",chunk:i.chunk,metadata:i.metadata,updatedAt:i.updatedAt,similarity:i.similarity}));return{results:qo(o,i=>i.memory),total:s.total,timing:s.timing}}async getProfile(t,r){let n=await this.client.profile({containerTag:t||this.containerTag,q:r}),s=new Set,o=(c,d=l=>l)=>c.filter(l=>{let b=String(d(l)).toLowerCase().trim();return!b||s.has(b)?!1:(s.add(b),!0)}),i=o(n.profile?.static||[]),a=o(n.profile?.dynamic||[]),P;if(n.searchResults){let c=n.searchResults.results.map(d=>({id:d.id,memory:d.content||d.context||"",similarity:d.similarity,title:d.title,updatedAt:d.updatedAt}));P={results:o(c,d=>d.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:i,dynamic:a},searchResults:P}}};Hr.exports={SupermemoryClient:St,PERSONAL_ENTITY_CONTEXT:Ho,REPO_ENTITY_CONTEXT:Wo}});var Yt=u((Xa,Tr)=>{var{execSync:Ue}=require("node:child_process"),se=require("node:path");function To(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return Ue("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=Ue("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return Ue("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=se.resolve(e,r);return se.basename(n)===".git"&&!n.includes(`${se.sep}.git${se.sep}`)?se.dirname(n):Ue("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}Tr.exports={getGitRoot:To}});var Ye=u((ya,wr)=>{var oe=require("node:fs"),Se=require("node:path"),{getGitRoot:Nr}=Yt(),Lr=Se.join(".claude",".supermemory-claude"),Vr="config.json";function Rr(e){let r=Nr(e)||e;return Se.join(r,Lr,Vr)}function gr(e){try{let t=Rr(e);if(oe.existsSync(t))return JSON.parse(oe.readFileSync(t,"utf-8"))}catch{}return null}function No(e,t){let n=Nr(e)||e,s=Se.join(n,Lr),o=Se.join(s,Vr);oe.existsSync(s)||oe.mkdirSync(s,{recursive:!0});let a={...gr(e)||{},...t};return oe.writeFileSync(o,JSON.stringify(a,null,2)),o}wr.exports={getConfigPath:Rr,loadProjectConfig:gr,saveProjectConfig:No}});var Dr=u((ha,Fr)=>{var{execSync:Lo}=require("node:child_process"),Vo=require("node:crypto"),{loadProjectConfig:Mr}=Ye(),{getGitRoot:ke}=Yt();function Zr(e){return Vo.createHash("sha256").update(e).digest("hex").slice(0,16)}var Ge=new Map;function Gt(e){if(Ge.has(e))return Ge.get(e);try{let r=Lo("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/),n=r?r[1]:null;return Ge.set(e,n),n}catch{return Ge.set(e,null),null}}function Ro(e){let t=Mr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=ke(e)||e;return`claudecode_project_${Zr(n)}`}function go(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function wo(e){let t=Mr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=ke(e)||e,o=Gt(n)||n.split("/").pop()||"unknown";return`repo_${go(o)}`}function Mo(e){let r=ke(e)||e;return Gt(r)||r.split("/").pop()||"unknown"}Fr.exports={sha256:Zr,getGitRoot:ke,getGitRepoName:Gt,getContainerTag:Ro,getRepoContainerTag:wo,getProjectName:Mo}});var Sr=u((qa,Ur)=>{var{execFile:Zo}=require("node:child_process");function Ke(e,t){return new Promise((r,n)=>{Zo(e,t,{windowsHide:!0},s=>{s?n(s):r()})})}async function Fo(e){let t=e.toString();if(!/^https?:\/\//i.test(t))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await Ke("rundll32.exe",["url.dll,FileProtocolHandler",t]);return}catch{}await Ke("cmd.exe",["/c","start",'""',t]);return}if(process.platform==="darwin"){await Ke("open",[t]);return}await Ke("xdg-open",[t])}Ur.exports={openUrl:Fo}});var Yr=u((Ha,Do)=>{Do.exports=`\r +\r +Connected - Supermemory\r +\r +\r +
\r +
Connected . . .
\r +\r +
\r + \r + +\r + \r +
\r +

Supercharge your Claude Code with Supermemory.

\r +
\r +\r +\r +`});var Gr=u((Wa,Uo)=>{Uo.exports=`\r +\r +Error - Supermemory\r +\r +
Error . . .
\r +

Connection Failed

\r +

Invalid API key received. Please try again.

\r +\r +`});var Et=u((Ta,Cr)=>{var So=require("node:http"),U=require("node:fs"),kr=require("node:path"),Yo=require("node:os"),{openUrl:Go}=Sr(),ko=Yr(),Ko=Gr(),Kt=kr.join(Yo.homedir(),".supermemory-claude"),k=kr.join(Kt,"credentials.json"),Kr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",kt=19876,Eo=25e3;function Co(){U.existsSync(Kt)||U.mkdirSync(Kt,{recursive:!0})}function Io(){try{if(U.existsSync(k)){let e=JSON.parse(U.readFileSync(k,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Er(e){Co();let t={apiKey:e,savedAt:new Date().toISOString()};U.writeFileSync(k,JSON.stringify(t,null,2))}function Jo(){try{U.existsSync(k)&&U.unlinkSync(k)}catch{}}function Bo(){return new Promise((e,t)=>{let r=!1,n=So.createServer((s,o)=>{let i=new URL(s.url,`http://localhost:${kt}`);if(i.pathname==="/callback"){let a=i.searchParams.get("apikey")||i.searchParams.get("api_key");a?.startsWith("sm_")?(Er(a),o.writeHead(200,{"Content-Type":"text/html"}),o.end(ko),r=!0,n.close(),e(a)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(Ko))}else o.writeHead(404),o.end("Not found")});n.listen(kt,"127.0.0.1",()=>{let s=`http://localhost:${kt}/callback`,o=`${Kr}?callback=${encodeURIComponent(s)}&client=claude_code`;Go(o).catch(i=>{r||(n.close(),t(new Error(`Failed to open browser: ${i.message}`)))})}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},Eo)})}Cr.exports={AUTH_BASE_URL:Kr,CREDENTIALS_FILE:k,loadCredentials:Io,saveCredentials:Er,clearCredentials:Jo,startAuthFlow:Bo}});var Br=u((Na,Jr)=>{var ae=require("node:fs"),Ir=require("node:path"),Ao=require("node:os"),{loadCredentials:Qo}=Et(),{loadProjectConfig:ce}=Ye(),{BASE_URL:_o}=Ut(),Ee=Ir.join(Ao.homedir(),".supermemory-claude"),ie=Ir.join(Ee,"settings.json"),Ce={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function $o(){ae.existsSync(Ee)||ae.mkdirSync(Ee,{recursive:!0})}function Ie(){let e={...Ce};try{if(ae.existsSync(ie)){let t=ae.readFileSync(ie,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${ie}: ${t.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function ei(e){$o();let t={...e};delete t.apiKey,ae.writeFileSync(ie,JSON.stringify(t,null,2))}function ti(e,t,r){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||ce(t||process.cwd()),r?.apiKey)return r.apiKey;let n=Qo();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function ri(e){if(typeof e!="string"||!e.trim())return null;let t=e.trim();try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t}catch{return null}}function ni(e,t){t=t||ce(e||process.cwd());let r=process.env.SUPERMEMORY_API_URL||t?.baseUrl||_o,n=ri(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function si(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function oi(e){let t=Ie(),r=ce(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(i=>i.toLowerCase())}function ii(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function ai(e){let t=Ie(),r=ce(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,i=t.signalKeywords||Ce.signalKeywords,a=r?.signalKeywords||[],P=[...new Set([...i,...a])].map(d=>d.toLowerCase()),c=r?.signalTurnsBefore||t.signalTurnsBefore||Ce.signalTurnsBefore;return{enabled:o,keywords:P,turnsBefore:c}}function ci(e){let t=Ie();return{directive:ce(e||process.cwd())?.recallDirective||t.recallDirective||null}}Jr.exports={SETTINGS_DIR:Ee,SETTINGS_FILE:ie,DEFAULT_SETTINGS:Ce,loadSettings:Ie,saveSettings:ei,getApiKey:ti,getBaseUrl:ni,debugLog:si,getIncludeTools:oi,shouldIncludeTool:ii,getSignalConfig:ai,getRecallConfig:ci}});var Qr=u((La,Ar)=>{async function fi(e=3e3){return new Promise((t,r)=>{let n="",s=!1,o=null,i=()=>{try{process.stdin.pause()}catch{}try{process.stdin.unref?.()}catch{}},a=(c,d)=>{s||(s=!0,clearTimeout(o),i(),c(d))},P=()=>{if(n.trim())try{let c=JSON.parse(n);a(t,c)}catch{}};o=setTimeout(()=>{a(t,{})},e),process.stdin.setEncoding("utf8"),process.stdin.on("data",c=>{n+=c,P()}),process.stdin.on("end",()=>{if(!s){if(!n.trim()){a(t,{});return}try{a(t,JSON.parse(n))}catch(c){a(r,new Error(`Failed to parse stdin JSON: ${c.message}`))}}}),process.stdin.on("error",c=>a(r,c)),process.stdin.isTTY&&a(t,{})})}function Je(e){console.log(JSON.stringify(e))}function ui(e=null){Je(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function di(e){console.error(`Supermemory: ${e}`),Je({continue:!0,suppressOutput:!0})}Ar.exports={readStdin:fi,writeOutput:Je,outputSuccess:ui,outputError:di}});var tn=u((Va,en)=>{var _r="The following is recalled context. Reference it only when relevant to the conversation.",$r="Use these memories naturally when relevant \u2014 including indirect connections \u2014 but don't force them into every response or make assumptions beyond what's stated.";function Ct(e){try{let t=new Date(e),r=new Date,n=(r.getTime()-t.getTime())/1e3,s=n/60,o=n/3600,i=n/86400;if(s<30)return"just now";if(s<60)return`${Math.floor(s)}mins ago`;if(o<24)return`${Math.floor(o)}hrs ago`;if(i<7)return`${Math.floor(i)}d ago`;let a=t.toLocaleString("en",{month:"short"});return t.getFullYear()===r.getFullYear()?`${t.getDate()} ${a}`:`${t.getDate()} ${a}, ${t.getFullYear()}`}catch{return""}}function vi(e,t=!0,r=!1,n=10,s=!0){if(!e)return null;let o=t?(e.profile?.static||[]).slice(0,n):[],i=t?(e.profile?.dynamic||[]).slice(0,n):[],a=r?(e.searchResults?.results||[]).slice(0,n):[];if(o.length===0&&i.length===0&&a.length===0)return null;let P=[];if(o.length>0){let d=o.map(l=>`- ${l}`).join(` `);P.push(`## User Profile (Persistent) -${u}`)}if(a.length>0){let u=a.map(v=>`- ${v}`).join(` +${d}`)}if(i.length>0){let d=i.map(l=>`- ${l}`).join(` `);P.push(`## Recent Context -${u}`)}if(i.length>0){let u=i.map(v=>{let b=v.memory??"",c=v.updatedAt?Kt(v.updatedAt):"",O=v.similarity!=null?`[${Math.round(v.similarity*100)}%]`:"";return`- ${c?`[${c}] `:""}${b} ${O}`.trim()});P.push(`## Relevant Memories (with relevance %) -${u.join(` -`)}`)}let p=P.join(` +${d}`)}if(a.length>0){let d=a.map(l=>{let b=l.memory??"",f=l.updatedAt?Ct(l.updatedAt):"",X=l.similarity!=null?`[${Math.round(l.similarity*100)}%]`:"";return`- ${f?`[${f}] `:""}${b} ${X}`.trim()});P.push(`## Relevant Memories (with relevance %) +${d.join(` +`)}`)}let c=P.join(` `);return s?` -${Jr} +${_r} -${p} +${c} -${Br} -`:p}function ca(e){let t=e.filter(n=>n.content);if(t.length===0)return null;let r=t.map(n=>n.label?`${n.label} +${$r} +`:c}function li(e){let t=e.filter(n=>n.content);if(t.length===0)return null;let r=t.map(n=>n.label?`${n.label} ${n.content}`:n.content);return` -${Jr} +${_r} ${r.join(` @@ -124,29 +124,29 @@ ${r.join(` `)} -${Br} -`}function fa(e,t,r){let n=r?`${r} memories for "${e}"`:`Memories for "${e}"`;if(!t||t.length===0)return`No ${r?`${r.toLowerCase()} `:""}memories found for "${e}"`;let s=t.map(o=>{let a=o.memory??"",i=o.updatedAt?Kt(o.updatedAt):"",P=o.similarity!=null?`[${Math.round(o.similarity*100)}%]`:"";return`${i?`[${i}] `:""}${a} ${P}`.trim()});return`${n} +${$r} +`}function pi(e,t,r){let n=r?`${r} memories for "${e}"`:`Memories for "${e}"`;if(!t||t.length===0)return`No ${r?`${r.toLowerCase()} `:""}memories found for "${e}"`;let s=t.map(o=>{let i=o.memory??"",a=o.updatedAt?Ct(o.updatedAt):"",P=o.similarity!=null?`[${Math.round(o.similarity*100)}%]`:"";return`${a?`[${a}] `:""}${i} ${P}`.trim()});return`${n} ${s.join(` -`)}`}Ar.exports={formatContext:ia,combineContexts:ca,formatRelativeTime:Kt,formatSearchResults:fa}});var $r=f((Xi,_r)=>{function ua(e){let t=e?.status;return t===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":t===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":t===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":t===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof t=="number"&&t>=500?"Supermemory service is temporarily unavailable. Will retry next session.":e?.message||"Unknown error"}function da(e){let t=e?.status;return t===429||typeof t=="number"&&t>=500||t==null}function va(e){let t=e?.status;return t===404||t==null}_r.exports={getUserFriendlyError:ua,isRetryableError:da,isBenignError:va}});var tn=f((Oi,en)=>{var la="0.0.9";en.exports={PLUGIN_VERSION:la}});var sn=f((yi,nn)=>{var pa="https://raw.githubusercontent.com/supermemoryai/claude-supermemory/main/latest.json";function rn(e){let r=String(e).trim().replace(/^v/i,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/);return r?{parts:[Number(r[1]),Number(r[2]),Number(r[3])],prerelease:r[4]||null}:null}function Pa(e,t){let r=rn(e),n=rn(t);if(!r||!n)return e!==t;for(let s=0;s<3;s++){if(r.parts[s]>n.parts[s])return!0;if(r.parts[s]t.abort(),3e3);try{let n=await fetch(pa,{signal:t.signal});if(!n.ok)return null;let s=await n.json(),o=typeof s.version=="string"?s.version:null;return!o||!Pa(o,e)?null:{currentVersion:e,latestVersion:o,updateCommand:typeof s.updateCommand=="string"?s.updateCommand:"/plugin install supermemory"}}catch{return null}finally{clearTimeout(r)}}function za(e){return` +`)}`}en.exports={formatContext:vi,combineContexts:li,formatRelativeTime:Ct,formatSearchResults:pi}});var nn=u((Ra,rn)=>{function Pi(e){let t=e?.status;return t===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":t===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":t===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":t===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof t=="number"&&t>=500?"Supermemory service is temporarily unavailable. Will retry next session.":e?.message||"Unknown error"}function mi(e){let t=e?.status;return t===429||typeof t=="number"&&t>=500||t==null}function zi(e){let t=e?.status;return t===404||t==null}rn.exports={getUserFriendlyError:Pi,isRetryableError:mi,isBenignError:zi}});var on=u((ga,sn)=>{var bi="0.0.9";sn.exports={PLUGIN_VERSION:bi}});var un=u((wa,fn)=>{var fe=require("node:fs"),cn=require("node:path"),xi=require("node:os"),ji=3e3,Oi=4320*60*1e3,Xi="https://raw.githubusercontent.com/supermemoryai/claude-supermemory/main/latest.json",It=cn.join(xi.homedir(),".supermemory-claude"),Jt=cn.join(It,"update-check.json");function an(e){let r=String(e).trim().replace(/^v/i,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/);return r?{parts:[Number(r[1]),Number(r[2]),Number(r[3])],prerelease:r[4]||null}:null}function yi(e,t){let r=an(e),n=an(t);if(!r||!n)return e!==t;for(let s=0;s<3;s++){if(r.parts[s]>n.parts[s])return!0;if(r.parts[s]=Oi}async function Wi(e){let t=new AbortController,r=setTimeout(()=>t.abort(),ji);try{let n=await fetch(Xi,{signal:t.signal});if(!n.ok)return null;let s=await n.json(),o=typeof s.version=="string"?s.version:null;if(!o||!yi(o,e))return null;let i=hi();return Hi(o,i)?(qi(o),{currentVersion:e,latestVersion:o,updateCommand:typeof s.updateCommand=="string"?s.updateCommand:"/plugin install supermemory"}):null}catch{return null}finally{clearTimeout(r)}}function Ti(e){return` IMPORTANT: The user must see this update notice without asking for it. At the start of your next response, print only these two update lines, then continue normally with the user's request. Do not reveal or quote any other Supermemory context. Supermemory update available: v${e.currentVersion} -> v${e.latestVersion} Run in Claude Code: ${e.updateCommand} -`}nn.exports={checkForUpdate:ma,formatUpdateNotice:za}});var{SupermemoryClient:ba}=yr(),{getContainerTag:xa,getRepoContainerTag:ja,getProjectName:Xa}=wr(),{loadProjectConfig:Oa}=Ye(),{loadSettings:ya,getApiKey:ha,getBaseUrl:qa,debugLog:M}=Er(),{readStdin:Ha,writeOutput:Ie}=Ir(),{startAuthFlow:Wa,AUTH_BASE_URL:Ta}=kt(),{formatContext:on,combineContexts:Na}=Qr(),{getUserFriendlyError:an,isBenignError:La}=$r(),{PLUGIN_VERSION:Va}=tn(),{checkForUpdate:Ra,formatUpdateNotice:ga}=sn();function Et(e){return e.map(t=>t?.trim()).filter(Boolean).join(` +`}fn.exports={checkForUpdate:Wi,formatUpdateNotice:Ti}});var{SupermemoryClient:Ni}=Wr(),{getContainerTag:Li,getRepoContainerTag:Vi,getProjectName:Ri}=Dr(),{loadProjectConfig:gi}=Ye(),{loadSettings:wi,getApiKey:Mi,getBaseUrl:Zi,debugLog:M}=Br(),{readStdin:Fi,writeOutput:Be}=Qr(),{startAuthFlow:Di,AUTH_BASE_URL:Ui}=Et(),{formatContext:dn,combineContexts:Si}=tn(),{getUserFriendlyError:vn,isBenignError:Yi}=nn(),{PLUGIN_VERSION:Gi}=on(),{checkForUpdate:ki,formatUpdateNotice:Ki}=un();function Bt(e){return e.map(t=>t?.trim()).filter(Boolean).join(` -`)}async function wa(){let e=ya();try{let r=(await Ha()).cwd||process.cwd(),n=Xa(r),s=Ra(Va).then(H=>H?ga(H):null),o=Oa(r);M(e,"SessionStart",{cwd:r,projectName:n});let a;try{a=ha(e,r,o)}catch{try{M(e,"No API key found, starting browser auth flow"),a=await Wa(),M(e,"Auth flow completed successfully")}catch(H){let R=H.message==="AUTH_TIMEOUT";Ie({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:Et([` +`)}async function Ei(){let e=wi();try{let r=(await Fi()).cwd||process.cwd(),n=Ri(r),s=ki(Gi).then(H=>H?Ki(H):null),o=gi(r);M(e,"SessionStart",{cwd:r,projectName:n});let i;try{i=Mi(e,r,o)}catch{try{M(e,"No API key found, starting browser auth flow"),i=await Di(),M(e,"Auth flow completed successfully")}catch(H){let R=H.message==="AUTH_TIMEOUT";Be({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:Bt([` ${R?"Authentication timed out. Please complete login in the browser window.":"Authentication failed."} -If the browser did not open, visit: ${Ta} +If the browser did not open, visit: ${Ui} Or set SUPERMEMORY_CC_API_KEY environment variable manually. -`,await s])}});return}}let i=qa(r,o),P=new ba(a,void 0,{baseUrl:i}),p=xa(r),u=ja(r);M(e,"Fetching contexts",{personalTag:p,repoTag:u});let v=[],b=H=>R=>{if(La(R))return M(e,`Benign error fetching ${H} context`,{status:R.status,message:R.message}),null;let Z=an(R);return M(e,`Error fetching ${H} context`,{status:R.status,message:Z}),v.push(Z),null},[c,O]=await Promise.all([P.getProfile(p,n).catch(b("personal")),P.getProfile(u,n).catch(b("repo"))]),N=on(c,!0,!1,e.maxProfileItems,!1),V=on(O,!0,!1,e.maxProfileItems,!1),q=Na([{label:"### Personal Memories",content:N},{label:"### Project Knowledge (Shared across team)",content:V}]),K=v.length>0?` -${[...new Set(v)].join(` +`,await s])}});return}}let a=Zi(r,o),P=new Ni(i,void 0,{baseUrl:a}),c=Li(r),d=Vi(r);M(e,"Fetching contexts",{personalTag:c,repoTag:d});let l=[],b=H=>R=>{if(Yi(R))return M(e,`Benign error fetching ${H} context`,{status:R.status,message:R.message}),null;let Z=vn(R);return M(e,`Error fetching ${H} context`,{status:R.status,message:Z}),l.push(Z),null},[f,X]=await Promise.all([P.getProfile(c,n).catch(b("personal")),P.getProfile(d,n).catch(b("repo"))]),N=dn(f,!0,!1,e.maxProfileItems,!1),V=dn(X,!0,!1,e.maxProfileItems,!1),q=Si([{label:"### Personal Memories",content:N},{label:"### Project Knowledge (Shared across team)",content:V}]),K=l.length>0?` +${[...new Set(l)].join(` `)} -`:"";if(!q){let H=await s;Ie({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:Et([v.length>0?K:` +`:"";if(!q){let H=await s;Be({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:Bt([l.length>0?K:` No previous memories found for this project. Memories will be saved as you work. -`,H])}});return}M(e,"Context generated",{length:q.length,hasPersonal:!!N,hasRepo:!!V});let fe=await s;Ie({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:Et([K+q,fe])}})}catch(t){let r=an(t);M(e,"Error",{error:r}),console.error(`Supermemory: ${r}`),Ie({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:` +`,H])}});return}M(e,"Context generated",{length:q.length,hasPersonal:!!N,hasRepo:!!V});let ue=await s;Be({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:Bt([K+q,ue])}})}catch(t){let r=vn(t);M(e,"Error",{error:r}),console.error(`Supermemory: ${r}`),Be({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:` Failed to load memories: ${r} Session will continue without memory context. -`}})}}wa().catch(e=>{console.error(`Supermemory fatal: ${e.message}`),process.exit(1)}); +`}})}}Ei().catch(e=>{console.error(`Supermemory fatal: ${e.message}`),process.exit(1)}); diff --git a/plugin/scripts/recall-approve.cjs b/plugin/scripts/recall-approve.cjs index 0219c81..010ad14 100755 --- a/plugin/scripts/recall-approve.cjs +++ b/plugin/scripts/recall-approve.cjs @@ -1,58 +1,58 @@ #!/usr/bin/env node -var c=(e,f)=>()=>(f||e((f={exports:{}}).exports,f),f.exports);var V=c((S3,T)=>{var{execFile:f3}=require("node:child_process");function O(e,f){return new Promise((v,n)=>{f3(e,f,{windowsHide:!0},r=>{r?n(r):v()})})}async function v3(e){let f=e.toString();if(!/^https?:\/\//i.test(f))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await O("rundll32.exe",["url.dll,FileProtocolHandler",f]);return}catch{}await O("cmd.exe",["/c","start",'""',f]);return}if(process.platform==="darwin"){await O("open",[f]);return}await O("xdg-open",[f])}T.exports={openUrl:v3}});var y=c((k3,n3)=>{n3.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var N=c((g3,r3)=>{r3.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var M=c((J3,h)=>{var t3=require("node:http"),d=require("node:fs"),L=require("node:path"),z3=require("node:os"),{openUrl:c3}=V(),P3=y(),d3=N(),m=L.join(z3.homedir(),".supermemory-claude"),X=L.join(m,"credentials.json"),Z=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",i=19876,X3=25e3;function u3(){d.existsSync(m)||d.mkdirSync(m,{recursive:!0})}function x3(){try{if(d.existsSync(X)){let e=JSON.parse(d.readFileSync(X,"utf-8"));if(e.apiKey)return e}}catch{}return null}function R(e){u3();let f={apiKey:e,savedAt:new Date().toISOString()};d.writeFileSync(X,JSON.stringify(f,null,2))}function a3(){try{d.existsSync(X)&&d.unlinkSync(X)}catch{}}function j3(){return new Promise((e,f)=>{let v=!1,n=t3.createServer((r,t)=>{let z=new URL(r.url,`http://localhost:${i}`);if(z.pathname==="/callback"){let P=z.searchParams.get("apikey")||z.searchParams.get("api_key");P?.startsWith("sm_")?(R(P),t.writeHead(200,{"Content-Type":"text/html"}),t.end(P3),v=!0,n.close(),e(P)):(t.writeHead(400,{"Content-Type":"text/html"}),t.end(d3))}else t.writeHead(404),t.end("Not found")});n.listen(i,"127.0.0.1",()=>{let r=`http://localhost:${i}/callback`,t=`${Z}?callback=${encodeURIComponent(r)}&client=claude_code`;c3(t).catch(z=>{v||(n.close(),f(new Error(`Failed to open browser: ${z.message}`)))})}),n.on("error",r=>{v||f(new Error(`Failed to start auth server: ${r.message}`))}),setTimeout(()=>{v||(n.close(),f(new Error("AUTH_TIMEOUT")))},X3)})}h.exports={AUTH_BASE_URL:Z,CREDENTIALS_FILE:X,loadCredentials:x3,saveCredentials:R,clearCredentials:a3,startAuthFlow:j3}});var D=c((E3,Y)=>{var{execSync:H}=require("node:child_process"),u=require("node:path");function s3(e){let f=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(f)return H("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let v=H("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(v===".git")return H("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=u.resolve(e,v);return u.basename(n)===".git"&&!n.includes(`${u.sep}.git${u.sep}`)?u.dirname(n):H("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}Y.exports={getGitRoot:s3}});var k=c((B3,S)=>{var x=require("node:fs"),q=require("node:path"),{getGitRoot:U}=D(),G=q.join(".claude",".supermemory-claude"),F="config.json";function w(e){let v=U(e)||e;return q.join(v,G,F)}function K(e){try{let f=w(e);if(x.existsSync(f))return JSON.parse(x.readFileSync(f,"utf-8"))}catch{}return null}function O3(e,f){let n=U(e)||e,r=q.join(n,G),t=q.join(r,F);x.existsSync(r)||x.mkdirSync(r,{recursive:!0});let P={...K(e)||{},...f};return x.writeFileSync(t,JSON.stringify(P,null,2)),t}S.exports={getConfigPath:w,loadProjectConfig:K,saveProjectConfig:O3}});var J=c((C3,g)=>{var H3="https://api.supermemory.ai";g.exports={BASE_URL:H3}});var C=c((I3,B)=>{var j=require("node:fs"),E=require("node:path"),q3=require("node:os"),{loadCredentials:b3}=M(),{loadProjectConfig:s}=k(),{BASE_URL:o3}=J(),b=E.join(q3.homedir(),".supermemory-claude"),a=E.join(b,"settings.json"),o={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function W3(){j.existsSync(b)||j.mkdirSync(b,{recursive:!0})}function W(){let e={...o};try{if(j.existsSync(a)){let f=j.readFileSync(a,"utf-8");Object.assign(e,JSON.parse(f))}}catch(f){console.error(`Settings: Failed to load ${a}: ${f.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function p3(e){W3();let f={...e};delete f.apiKey,j.writeFileSync(a,JSON.stringify(f,null,2))}function l3(e,f,v){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(v=v||s(f||process.cwd()),v?.apiKey)return v.apiKey;let n=b3();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function i3(e){if(typeof e!="string"||!e.trim())return null;let f=e.trim();try{let v=new URL(f);return v.protocol!=="http:"&&v.protocol!=="https:"?null:f}catch{return null}}function m3(e,f){f=f||s(e||process.cwd());let v=process.env.SUPERMEMORY_API_URL||f?.baseUrl||o3,n=i3(v);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function T3(e,f,v){if(e.debug){let n=new Date().toISOString();console.error(v?`[${n}] ${f}: ${JSON.stringify(v)}`:`[${n}] ${f}`)}}function V3(e){let f=W(),v=s(e||process.cwd()),n=f.includeTools||[],r=v?.includeTools||[];return[...new Set([...n,...r])].map(z=>z.toLowerCase())}function y3(e,f){return f.length===0?!1:f.includes(e.toLowerCase())}function N3(e){let f=W(),v=s(e||process.cwd()),n=f.signalExtraction||!1,r=v?.signalExtraction,t=r!==void 0?r:n,z=f.signalKeywords||o.signalKeywords,P=v?.signalKeywords||[],_=[...new Set([...z,...P])].map(e3=>e3.toLowerCase()),$=v?.signalTurnsBefore||f.signalTurnsBefore||o.signalTurnsBefore;return{enabled:t,keywords:_,turnsBefore:$}}function L3(e){let f=W();return{directive:s(e||process.cwd())?.recallDirective||f.recallDirective||null}}B.exports={SETTINGS_DIR:b,SETTINGS_FILE:a,DEFAULT_SETTINGS:o,loadSettings:W,saveSettings:p3,getApiKey:l3,getBaseUrl:m3,debugLog:T3,getIncludeTools:V3,shouldIncludeTool:y3,getSignalConfig:N3,getRecallConfig:L3}});var Q=c((Q3,I)=>{async function Z3(){return new Promise((e,f)=>{let v="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{v+=n}),process.stdin.on("end",()=>{try{e(v.trim()?JSON.parse(v):{})}catch(n){f(new Error(`Failed to parse stdin JSON: ${n.message}`))}}),process.stdin.on("error",f),process.stdin.isTTY&&e({})})}function p(e){console.log(JSON.stringify(e))}function R3(e=null){p(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function h3(e){console.error(`Supermemory: ${e}`),p({continue:!0,suppressOutput:!0})}I.exports={readStdin:Z3,writeOutput:p,outputSuccess:R3,outputError:h3}});var{loadSettings:M3,debugLog:A}=C(),{readStdin:Y3,writeOutput:l}=Q(),D3=/node[\s\S]*search-memory\.cjs/,U3=/[;&|`>]|\$\(/,G3="supermemory-search";function F3(e,f){if(e==="Skill")return JSON.stringify(f||{}).includes(G3);if(e==="Bash"){let v=String(f?.command||"");return D3.test(v)&&!U3.test(v)}return!1}async function w3(){let e=M3();try{let f=await Y3();if(F3(f.tool_name,f.tool_input)){A(e,"Auto-approving recall search",{toolName:f.tool_name}),l({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Supermemory reasoned recall runs automatically (read-only memory search)."}});return}l({continue:!0,suppressOutput:!0})}catch(f){A(e,"Recall approve hook error",{error:f.message}),l({continue:!0,suppressOutput:!0})}}w3().catch(()=>{l({continue:!0,suppressOutput:!0})}); +var d=(f,e)=>()=>(e||f((e={exports:{}}).exports,e),e.exports);var L=d((S3,N)=>{var{execFile:f3}=require("node:child_process");function H(f,e){return new Promise((v,n)=>{f3(f,e,{windowsHide:!0},r=>{r?n(r):v()})})}async function v3(f){let e=f.toString();if(!/^https?:\/\//i.test(e))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await H("rundll32.exe",["url.dll,FileProtocolHandler",e]);return}catch{}await H("cmd.exe",["/c","start",'""',e]);return}if(process.platform==="darwin"){await H("open",[e]);return}await H("xdg-open",[e])}N.exports={openUrl:v3}});var Z=d((k3,n3)=>{n3.exports=`\r +\r +Connected - Supermemory\r +\r +\r +
\r +
Connected . . .
\r +\r +
\r + \r + +\r + \r +
\r +

Supercharge your Claude Code with Supermemory.

\r +
\r +\r +\r +`});var R=d((g3,r3)=>{r3.exports=`\r +\r +Error - Supermemory\r +\r +
Error . . .
\r +

Connection Failed

\r +

Invalid API key received. Please try again.

\r +\r +`});var U=d((J3,D)=>{var t3=require("node:http"),u=require("node:fs"),h=require("node:path"),z3=require("node:os"),{openUrl:c3}=L(),P3=Z(),d3=R(),y=h.join(z3.homedir(),".supermemory-claude"),a=h.join(y,"credentials.json"),M=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",V=19876,u3=25e3;function a3(){u.existsSync(y)||u.mkdirSync(y,{recursive:!0})}function X3(){try{if(u.existsSync(a)){let f=JSON.parse(u.readFileSync(a,"utf-8"));if(f.apiKey)return f}}catch{}return null}function Y(f){a3();let e={apiKey:f,savedAt:new Date().toISOString()};u.writeFileSync(a,JSON.stringify(e,null,2))}function x3(){try{u.existsSync(a)&&u.unlinkSync(a)}catch{}}function j3(){return new Promise((f,e)=>{let v=!1,n=t3.createServer((r,t)=>{let c=new URL(r.url,`http://localhost:${V}`);if(c.pathname==="/callback"){let z=c.searchParams.get("apikey")||c.searchParams.get("api_key");z?.startsWith("sm_")?(Y(z),t.writeHead(200,{"Content-Type":"text/html"}),t.end(P3),v=!0,n.close(),f(z)):(t.writeHead(400,{"Content-Type":"text/html"}),t.end(d3))}else t.writeHead(404),t.end("Not found")});n.listen(V,"127.0.0.1",()=>{let r=`http://localhost:${V}/callback`,t=`${M}?callback=${encodeURIComponent(r)}&client=claude_code`;c3(t).catch(c=>{v||(n.close(),e(new Error(`Failed to open browser: ${c.message}`)))})}),n.on("error",r=>{v||e(new Error(`Failed to start auth server: ${r.message}`))}),setTimeout(()=>{v||(n.close(),e(new Error("AUTH_TIMEOUT")))},u3)})}D.exports={AUTH_BASE_URL:M,CREDENTIALS_FILE:a,loadCredentials:X3,saveCredentials:Y,clearCredentials:x3,startAuthFlow:j3}});var F=d((E3,G)=>{var{execSync:q}=require("node:child_process"),X=require("node:path");function s3(f){let e=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(e)return q("git rev-parse --show-toplevel",{cwd:f,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let v=q("git rev-parse --git-common-dir",{cwd:f,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(v===".git")return q("git rev-parse --show-toplevel",{cwd:f,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=X.resolve(f,v);return X.basename(n)===".git"&&!n.includes(`${X.sep}.git${X.sep}`)?X.dirname(n):q("git rev-parse --show-toplevel",{cwd:f,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}G.exports={getGitRoot:s3}});var E=d((B3,J)=>{var x=require("node:fs"),b=require("node:path"),{getGitRoot:w}=F(),K=b.join(".claude",".supermemory-claude"),S="config.json";function k(f){let v=w(f)||f;return b.join(v,K,S)}function g(f){try{let e=k(f);if(x.existsSync(e))return JSON.parse(x.readFileSync(e,"utf-8"))}catch{}return null}function O3(f,e){let n=w(f)||f,r=b.join(n,K),t=b.join(r,S);x.existsSync(r)||x.mkdirSync(r,{recursive:!0});let z={...g(f)||{},...e};return x.writeFileSync(t,JSON.stringify(z,null,2)),t}J.exports={getConfigPath:k,loadProjectConfig:g,saveProjectConfig:O3}});var C=d((C3,B)=>{var H3="https://api.supermemory.ai";B.exports={BASE_URL:H3}});var A=d((I3,Q)=>{var s=require("node:fs"),I=require("node:path"),q3=require("node:os"),{loadCredentials:b3}=U(),{loadProjectConfig:O}=E(),{BASE_URL:o3}=C(),o=I.join(q3.homedir(),".supermemory-claude"),j=I.join(o,"settings.json"),W={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function W3(){s.existsSync(o)||s.mkdirSync(o,{recursive:!0})}function p(){let f={...W};try{if(s.existsSync(j)){let e=s.readFileSync(j,"utf-8");Object.assign(f,JSON.parse(e))}}catch(e){console.error(`Settings: Failed to load ${j}: ${e.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(f.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(f.debug=!0),f}function p3(f){W3();let e={...f};delete e.apiKey,s.writeFileSync(j,JSON.stringify(e,null,2))}function l3(f,e,v){if(f.apiKey)return f.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(v=v||O(e||process.cwd()),v?.apiKey)return v.apiKey;let n=b3();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function i3(f){if(typeof f!="string"||!f.trim())return null;let e=f.trim();try{let v=new URL(e);return v.protocol!=="http:"&&v.protocol!=="https:"?null:e}catch{return null}}function m3(f,e){e=e||O(f||process.cwd());let v=process.env.SUPERMEMORY_API_URL||e?.baseUrl||o3,n=i3(v);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function T3(f,e,v){if(f.debug){let n=new Date().toISOString();console.error(v?`[${n}] ${e}: ${JSON.stringify(v)}`:`[${n}] ${e}`)}}function V3(f){let e=p(),v=O(f||process.cwd()),n=e.includeTools||[],r=v?.includeTools||[];return[...new Set([...n,...r])].map(c=>c.toLowerCase())}function y3(f,e){return e.length===0?!1:e.includes(f.toLowerCase())}function N3(f){let e=p(),v=O(f||process.cwd()),n=e.signalExtraction||!1,r=v?.signalExtraction,t=r!==void 0?r:n,c=e.signalKeywords||W.signalKeywords,z=v?.signalKeywords||[],m=[...new Set([...c,...z])].map(T=>T.toLowerCase()),P=v?.signalTurnsBefore||e.signalTurnsBefore||W.signalTurnsBefore;return{enabled:t,keywords:m,turnsBefore:P}}function L3(f){let e=p();return{directive:O(f||process.cwd())?.recallDirective||e.recallDirective||null}}Q.exports={SETTINGS_DIR:o,SETTINGS_FILE:j,DEFAULT_SETTINGS:W,loadSettings:p,saveSettings:p3,getApiKey:l3,getBaseUrl:m3,debugLog:T3,getIncludeTools:V3,shouldIncludeTool:y3,getSignalConfig:N3,getRecallConfig:L3}});var $=d((Q3,_)=>{async function Z3(f=3e3){return new Promise((e,v)=>{let n="",r=!1,t=null,c=()=>{try{process.stdin.pause()}catch{}try{process.stdin.unref?.()}catch{}},z=(P,T)=>{r||(r=!0,clearTimeout(t),c(),P(T))},m=()=>{if(n.trim())try{let P=JSON.parse(n);z(e,P)}catch{}};t=setTimeout(()=>{z(e,{})},f),process.stdin.setEncoding("utf8"),process.stdin.on("data",P=>{n+=P,m()}),process.stdin.on("end",()=>{if(!r){if(!n.trim()){z(e,{});return}try{z(e,JSON.parse(n))}catch(P){z(v,new Error(`Failed to parse stdin JSON: ${P.message}`))}}}),process.stdin.on("error",P=>z(v,P)),process.stdin.isTTY&&z(e,{})})}function l(f){console.log(JSON.stringify(f))}function R3(f=null){l(f?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:f}}:{continue:!0,suppressOutput:!0})}function h3(f){console.error(`Supermemory: ${f}`),l({continue:!0,suppressOutput:!0})}_.exports={readStdin:Z3,writeOutput:l,outputSuccess:R3,outputError:h3}});var{loadSettings:M3,debugLog:e3}=A(),{readStdin:Y3,writeOutput:i}=$(),D3=/node[\s\S]*search-memory\.cjs/,U3=/[;&|`>]|\$\(/,G3="supermemory-search";function F3(f,e){if(f==="Skill")return JSON.stringify(e||{}).includes(G3);if(f==="Bash"){let v=String(e?.command||"");return D3.test(v)&&!U3.test(v)}return!1}async function w3(){let f=M3();try{let e=await Y3();if(F3(e.tool_name,e.tool_input)){e3(f,"Auto-approving recall search",{toolName:e.tool_name}),i({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"allow",permissionDecisionReason:"Supermemory reasoned recall runs automatically (read-only memory search)."}});return}i({continue:!0,suppressOutput:!0})}catch(e){e3(f,"Recall approve hook error",{error:e.message}),i({continue:!0,suppressOutput:!0})}}w3().catch(()=>{i({continue:!0,suppressOutput:!0})}); diff --git a/plugin/scripts/recall-hook.cjs b/plugin/scripts/recall-hook.cjs index 6cc609e..9b3302a 100755 --- a/plugin/scripts/recall-hook.cjs +++ b/plugin/scripts/recall-hook.cjs @@ -1,61 +1,61 @@ #!/usr/bin/env node -var c=(e,f)=>()=>(f||e((f={exports:{}}).exports,f),f.exports);var y=c((Ke,T)=>{var{execFile:fe}=require("node:child_process");function O(e,f){return new Promise((n,v)=>{fe(e,f,{windowsHide:!0},r=>{r?v(r):n()})})}async function ne(e){let f=e.toString();if(!/^https?:\/\//i.test(f))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await O("rundll32.exe",["url.dll,FileProtocolHandler",f]);return}catch{}await O("cmd.exe",["/c","start",'""',f]);return}if(process.platform==="darwin"){await O("open",[f]);return}await O("xdg-open",[f])}T.exports={openUrl:ne}});var V=c((Se,ve)=>{ve.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var N=c((ke,re)=>{re.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var M=c((ge,R)=>{var te=require("node:http"),d=require("node:fs"),L=require("node:path"),ze=require("node:os"),{openUrl:ce}=y(),Pe=V(),de=N(),i=L.join(ze.homedir(),".supermemory-claude"),a=L.join(i,"credentials.json"),Z=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",W=19876,ae=25e3;function ue(){d.existsSync(i)||d.mkdirSync(i,{recursive:!0})}function Xe(){try{if(d.existsSync(a)){let e=JSON.parse(d.readFileSync(a,"utf-8"));if(e.apiKey)return e}}catch{}return null}function h(e){ue();let f={apiKey:e,savedAt:new Date().toISOString()};d.writeFileSync(a,JSON.stringify(f,null,2))}function xe(){try{d.existsSync(a)&&d.unlinkSync(a)}catch{}}function se(){return new Promise((e,f)=>{let n=!1,v=te.createServer((r,t)=>{let z=new URL(r.url,`http://localhost:${W}`);if(z.pathname==="/callback"){let P=z.searchParams.get("apikey")||z.searchParams.get("api_key");P?.startsWith("sm_")?(h(P),t.writeHead(200,{"Content-Type":"text/html"}),t.end(Pe),n=!0,v.close(),e(P)):(t.writeHead(400,{"Content-Type":"text/html"}),t.end(de))}else t.writeHead(404),t.end("Not found")});v.listen(W,"127.0.0.1",()=>{let r=`http://localhost:${W}/callback`,t=`${Z}?callback=${encodeURIComponent(r)}&client=claude_code`;ce(t).catch(z=>{n||(v.close(),f(new Error(`Failed to open browser: ${z.message}`)))})}),v.on("error",r=>{n||f(new Error(`Failed to start auth server: ${r.message}`))}),setTimeout(()=>{n||(v.close(),f(new Error("AUTH_TIMEOUT")))},ae)})}R.exports={AUTH_BASE_URL:Z,CREDENTIALS_FILE:a,loadCredentials:Xe,saveCredentials:h,clearCredentials:xe,startAuthFlow:se}});var D=c((Je,Y)=>{var{execSync:H}=require("node:child_process"),u=require("node:path");function je(e){let f=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(f)return H("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=H("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n===".git")return H("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let v=u.resolve(e,n);return u.basename(v)===".git"&&!v.includes(`${u.sep}.git${u.sep}`)?u.dirname(v):H("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}Y.exports={getGitRoot:je}});var k=c((Ee,S)=>{var X=require("node:fs"),o=require("node:path"),{getGitRoot:U}=D(),G=o.join(".claude",".supermemory-claude"),F="config.json";function w(e){let n=U(e)||e;return o.join(n,G,F)}function K(e){try{let f=w(e);if(X.existsSync(f))return JSON.parse(X.readFileSync(f,"utf-8"))}catch{}return null}function Oe(e,f){let v=U(e)||e,r=o.join(v,G),t=o.join(r,F);X.existsSync(r)||X.mkdirSync(r,{recursive:!0});let P={...K(e)||{},...f};return X.writeFileSync(t,JSON.stringify(P,null,2)),t}S.exports={getConfigPath:w,loadProjectConfig:K,saveProjectConfig:Oe}});var J=c((Be,g)=>{var He="https://api.supermemory.ai";g.exports={BASE_URL:He}});var C=c((Ce,B)=>{var s=require("node:fs"),E=require("node:path"),oe=require("node:os"),{loadCredentials:qe}=M(),{loadProjectConfig:j}=k(),{BASE_URL:be}=J(),q=E.join(oe.homedir(),".supermemory-claude"),x=E.join(q,"settings.json"),b={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function le(){s.existsSync(q)||s.mkdirSync(q,{recursive:!0})}function l(){let e={...b};try{if(s.existsSync(x)){let f=s.readFileSync(x,"utf-8");Object.assign(e,JSON.parse(f))}}catch(f){console.error(`Settings: Failed to load ${x}: ${f.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function pe(e){le();let f={...e};delete f.apiKey,s.writeFileSync(x,JSON.stringify(f,null,2))}function We(e,f,n){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(n=n||j(f||process.cwd()),n?.apiKey)return n.apiKey;let v=qe();if(v?.apiKey)return v.apiKey;throw new Error("NO_API_KEY")}function ie(e){if(typeof e!="string"||!e.trim())return null;let f=e.trim();try{let n=new URL(f);return n.protocol!=="http:"&&n.protocol!=="https:"?null:f}catch{return null}}function me(e,f){f=f||j(e||process.cwd());let n=process.env.SUPERMEMORY_API_URL||f?.baseUrl||be,v=ie(n);if(!v)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return v}function Te(e,f,n){if(e.debug){let v=new Date().toISOString();console.error(n?`[${v}] ${f}: ${JSON.stringify(n)}`:`[${v}] ${f}`)}}function ye(e){let f=l(),n=j(e||process.cwd()),v=f.includeTools||[],r=n?.includeTools||[];return[...new Set([...v,...r])].map(z=>z.toLowerCase())}function Ve(e,f){return f.length===0?!1:f.includes(e.toLowerCase())}function Ne(e){let f=l(),n=j(e||process.cwd()),v=f.signalExtraction||!1,r=n?.signalExtraction,t=r!==void 0?r:v,z=f.signalKeywords||b.signalKeywords,P=n?.signalKeywords||[],_=[...new Set([...z,...P])].map(ee=>ee.toLowerCase()),$=n?.signalTurnsBefore||f.signalTurnsBefore||b.signalTurnsBefore;return{enabled:t,keywords:_,turnsBefore:$}}function Le(e){let f=l();return{directive:j(e||process.cwd())?.recallDirective||f.recallDirective||null}}B.exports={SETTINGS_DIR:q,SETTINGS_FILE:x,DEFAULT_SETTINGS:b,loadSettings:l,saveSettings:pe,getApiKey:We,getBaseUrl:me,debugLog:Te,getIncludeTools:ye,shouldIncludeTool:Ve,getSignalConfig:Ne,getRecallConfig:Le}});var Q=c((Ie,I)=>{async function Ze(){return new Promise((e,f)=>{let n="";process.stdin.setEncoding("utf8"),process.stdin.on("data",v=>{n+=v}),process.stdin.on("end",()=>{try{e(n.trim()?JSON.parse(n):{})}catch(v){f(new Error(`Failed to parse stdin JSON: ${v.message}`))}}),process.stdin.on("error",f),process.stdin.isTTY&&e({})})}function p(e){console.log(JSON.stringify(e))}function he(e=null){p(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function Re(e){console.error(`Supermemory: ${e}`),p({continue:!0,suppressOutput:!0})}I.exports={readStdin:Ze,writeOutput:p,outputSuccess:he,outputError:Re}});var{loadSettings:Me,debugLog:A,getRecallConfig:Ye}=C(),{readStdin:De,writeOutput:m}=Q(),Ue=` +var d=(e,f)=>()=>(f||e((f={exports:{}}).exports,f),f.exports);var L=d((Ke,N)=>{var{execFile:fe}=require("node:child_process");function H(e,f){return new Promise((n,v)=>{fe(e,f,{windowsHide:!0},r=>{r?v(r):n()})})}async function ne(e){let f=e.toString();if(!/^https?:\/\//i.test(f))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await H("rundll32.exe",["url.dll,FileProtocolHandler",f]);return}catch{}await H("cmd.exe",["/c","start",'""',f]);return}if(process.platform==="darwin"){await H("open",[f]);return}await H("xdg-open",[f])}N.exports={openUrl:ne}});var Z=d((Se,ve)=>{ve.exports=`\r +\r +Connected - Supermemory\r +\r +\r +
\r +
Connected . . .
\r +\r +
\r + \r + +\r + \r +
\r +

Supercharge your Claude Code with Supermemory.

\r +
\r +\r +\r +`});var h=d((ke,re)=>{re.exports=`\r +\r +Error - Supermemory\r +\r +
Error . . .
\r +

Connection Failed

\r +

Invalid API key received. Please try again.

\r +\r +`});var U=d((ge,D)=>{var te=require("node:http"),a=require("node:fs"),R=require("node:path"),ze=require("node:os"),{openUrl:ce}=L(),Pe=Z(),de=h(),y=R.join(ze.homedir(),".supermemory-claude"),u=R.join(y,"credentials.json"),M=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",T=19876,ae=25e3;function ue(){a.existsSync(y)||a.mkdirSync(y,{recursive:!0})}function Xe(){try{if(a.existsSync(u)){let e=JSON.parse(a.readFileSync(u,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Y(e){ue();let f={apiKey:e,savedAt:new Date().toISOString()};a.writeFileSync(u,JSON.stringify(f,null,2))}function xe(){try{a.existsSync(u)&&a.unlinkSync(u)}catch{}}function se(){return new Promise((e,f)=>{let n=!1,v=te.createServer((r,t)=>{let c=new URL(r.url,`http://localhost:${T}`);if(c.pathname==="/callback"){let z=c.searchParams.get("apikey")||c.searchParams.get("api_key");z?.startsWith("sm_")?(Y(z),t.writeHead(200,{"Content-Type":"text/html"}),t.end(Pe),n=!0,v.close(),e(z)):(t.writeHead(400,{"Content-Type":"text/html"}),t.end(de))}else t.writeHead(404),t.end("Not found")});v.listen(T,"127.0.0.1",()=>{let r=`http://localhost:${T}/callback`,t=`${M}?callback=${encodeURIComponent(r)}&client=claude_code`;ce(t).catch(c=>{n||(v.close(),f(new Error(`Failed to open browser: ${c.message}`)))})}),v.on("error",r=>{n||f(new Error(`Failed to start auth server: ${r.message}`))}),setTimeout(()=>{n||(v.close(),f(new Error("AUTH_TIMEOUT")))},ae)})}D.exports={AUTH_BASE_URL:M,CREDENTIALS_FILE:u,loadCredentials:Xe,saveCredentials:Y,clearCredentials:xe,startAuthFlow:se}});var F=d((Je,G)=>{var{execSync:o}=require("node:child_process"),X=require("node:path");function je(e){let f=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(f)return o("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=o("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n===".git")return o("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let v=X.resolve(e,n);return X.basename(v)===".git"&&!v.includes(`${X.sep}.git${X.sep}`)?X.dirname(v):o("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}G.exports={getGitRoot:je}});var E=d((Ee,J)=>{var x=require("node:fs"),q=require("node:path"),{getGitRoot:w}=F(),K=q.join(".claude",".supermemory-claude"),S="config.json";function k(e){let n=w(e)||e;return q.join(n,K,S)}function g(e){try{let f=k(e);if(x.existsSync(f))return JSON.parse(x.readFileSync(f,"utf-8"))}catch{}return null}function Oe(e,f){let v=w(e)||e,r=q.join(v,K),t=q.join(r,S);x.existsSync(r)||x.mkdirSync(r,{recursive:!0});let z={...g(e)||{},...f};return x.writeFileSync(t,JSON.stringify(z,null,2)),t}J.exports={getConfigPath:k,loadProjectConfig:g,saveProjectConfig:Oe}});var C=d((Be,B)=>{var He="https://api.supermemory.ai";B.exports={BASE_URL:He}});var A=d((Ce,Q)=>{var j=require("node:fs"),I=require("node:path"),oe=require("node:os"),{loadCredentials:qe}=U(),{loadProjectConfig:O}=E(),{BASE_URL:be}=C(),b=I.join(oe.homedir(),".supermemory-claude"),s=I.join(b,"settings.json"),l={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function le(){j.existsSync(b)||j.mkdirSync(b,{recursive:!0})}function p(){let e={...l};try{if(j.existsSync(s)){let f=j.readFileSync(s,"utf-8");Object.assign(e,JSON.parse(f))}}catch(f){console.error(`Settings: Failed to load ${s}: ${f.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function pe(e){le();let f={...e};delete f.apiKey,j.writeFileSync(s,JSON.stringify(f,null,2))}function We(e,f,n){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(n=n||O(f||process.cwd()),n?.apiKey)return n.apiKey;let v=qe();if(v?.apiKey)return v.apiKey;throw new Error("NO_API_KEY")}function ie(e){if(typeof e!="string"||!e.trim())return null;let f=e.trim();try{let n=new URL(f);return n.protocol!=="http:"&&n.protocol!=="https:"?null:f}catch{return null}}function me(e,f){f=f||O(e||process.cwd());let n=process.env.SUPERMEMORY_API_URL||f?.baseUrl||be,v=ie(n);if(!v)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return v}function Te(e,f,n){if(e.debug){let v=new Date().toISOString();console.error(n?`[${v}] ${f}: ${JSON.stringify(n)}`:`[${v}] ${f}`)}}function ye(e){let f=p(),n=O(e||process.cwd()),v=f.includeTools||[],r=n?.includeTools||[];return[...new Set([...v,...r])].map(c=>c.toLowerCase())}function Ve(e,f){return f.length===0?!1:f.includes(e.toLowerCase())}function Ne(e){let f=p(),n=O(e||process.cwd()),v=f.signalExtraction||!1,r=n?.signalExtraction,t=r!==void 0?r:v,c=f.signalKeywords||l.signalKeywords,z=n?.signalKeywords||[],i=[...new Set([...c,...z])].map(m=>m.toLowerCase()),P=n?.signalTurnsBefore||f.signalTurnsBefore||l.signalTurnsBefore;return{enabled:t,keywords:i,turnsBefore:P}}function Le(e){let f=p();return{directive:O(e||process.cwd())?.recallDirective||f.recallDirective||null}}Q.exports={SETTINGS_DIR:b,SETTINGS_FILE:s,DEFAULT_SETTINGS:l,loadSettings:p,saveSettings:pe,getApiKey:We,getBaseUrl:me,debugLog:Te,getIncludeTools:ye,shouldIncludeTool:Ve,getSignalConfig:Ne,getRecallConfig:Le}});var $=d((Ie,_)=>{async function Ze(e=3e3){return new Promise((f,n)=>{let v="",r=!1,t=null,c=()=>{try{process.stdin.pause()}catch{}try{process.stdin.unref?.()}catch{}},z=(P,m)=>{r||(r=!0,clearTimeout(t),c(),P(m))},i=()=>{if(v.trim())try{let P=JSON.parse(v);z(f,P)}catch{}};t=setTimeout(()=>{z(f,{})},e),process.stdin.setEncoding("utf8"),process.stdin.on("data",P=>{v+=P,i()}),process.stdin.on("end",()=>{if(!r){if(!v.trim()){z(f,{});return}try{z(f,JSON.parse(v))}catch(P){z(n,new Error(`Failed to parse stdin JSON: ${P.message}`))}}}),process.stdin.on("error",P=>z(n,P)),process.stdin.isTTY&&z(f,{})})}function W(e){console.log(JSON.stringify(e))}function he(e=null){W(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function Re(e){console.error(`Supermemory: ${e}`),W({continue:!0,suppressOutput:!0})}_.exports={readStdin:Ze,writeOutput:W,outputSuccess:he,outputError:Re}});var{loadSettings:Me,debugLog:ee,getRecallConfig:Ye}=A(),{readStdin:De,writeOutput:V}=$(),Ue=` Before responding, silently decide whether recalling saved memory (past sessions, decisions, conventions, the user's preferences) would materially improve your answer to THIS message. Reason first \u2014 don't search reflexively, and don't narrate the decision. Recall \u2014 via the supermemory-search skill \u2014 when the message: @@ -72,4 +72,4 @@ DEBUG MODE: Begin your reply with exactly one line, then continue normally: "yes" means you are recalling saved Supermemory memory (via the supermemory-search skill, separate from any obsidian/smfs notes mount) for THIS message; "no" means you are skipping it. `;async function Fe(){let e=Me();try{let f=await De(),n=f.cwd||process.cwd(),{directive:v}=Ye(n),r=v||Ue;e.debug&&(r+=` -${Ge}`),A(e,"Injecting recall directive",{sessionId:f.session_id,custom:!!v,debugDecision:!!e.debug}),m({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:r}})}catch(f){A(e,"Recall hook error",{error:f.message}),m({continue:!0,suppressOutput:!0})}}Fe().catch(()=>{m({continue:!0,suppressOutput:!0})}); +${Ge}`),ee(e,"Injecting recall directive",{sessionId:f.session_id,custom:!!v,debugDecision:!!e.debug}),V({hookSpecificOutput:{hookEventName:"UserPromptSubmit",additionalContext:r}})}catch(f){ee(e,"Recall hook error",{error:f.message}),V({continue:!0,suppressOutput:!0})}}Fe().catch(()=>{V({continue:!0,suppressOutput:!0})}); diff --git a/plugin/scripts/save-project-memory.cjs b/plugin/scripts/save-project-memory.cjs index 3e0b571..7bb9723 100755 --- a/plugin/scripts/save-project-memory.cjs +++ b/plugin/scripts/save-project-memory.cjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -var Se=Object.defineProperty;var Gr=Object.getOwnPropertyDescriptor;var Kr=Object.getOwnPropertyNames;var kr=Object.prototype.hasOwnProperty;var Er=(e,t)=>()=>(e&&(t=e(e=0)),t);var c=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ir=(e,t)=>{for(var r in t)Se(e,r,{get:t[r],enumerable:!0})},Cr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Kr(t))!kr.call(e,s)&&s!==r&&Se(e,s,{get:()=>t[s],enumerable:!(n=Gr(t,s))||n.enumerable});return e};var Jr=e=>Cr(Se({},"__esModule",{value:!0}),e);var ke=c(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=Br;h.__classPrivateFieldGet=Ar;h.__importStar=Qr;h.__exportStar=_r;function Br(e,t,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(e,r):s?s.value=r:t.set(e,r),r}function Ar(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var Ke=Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]};h.__createBinding=Ke;var Ut=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};h.__setModuleDefault=Ut;var Ge=function(e){return Ge=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Ge(e)};function Qr(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Ge(e),n=0;n{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.uuid4=void 0;var $r=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Y.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};Y.uuid4=$r});var Ee=c(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=en;function en(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var tn=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};S.castToError=tn});var K=c(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.InternalServerError=P.RateLimitError=P.UnprocessableEntityError=P.ConflictError=P.NotFoundError=P.PermissionDeniedError=P.AuthenticationError=P.BadRequestError=P.APIConnectionTimeoutError=P.APIConnectionError=P.APIUserAbortError=P.APIError=P.SupermemoryError=void 0;var rn=Ee(),oe=class extends Error{};P.SupermemoryError=oe;var O=class e extends oe{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(t,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new G({message:n,cause:(0,rn.castToError)(r)});let o=r;return t===400?new ae(t,o,n,s):t===401?new fe(t,o,n,s):t===403?new ie(t,o,n,s):t===404?new ce(t,o,n,s):t===409?new ue(t,o,n,s):t===422?new de(t,o,n,s):t===429?new ve(t,o,n,s):t>=500?new le(t,o,n,s):new e(t,o,n,s)}};P.APIError=O;var Ie=class extends O{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};P.APIUserAbortError=Ie;var G=class extends O{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};P.APIConnectionError=G;var Ce=class extends G{constructor({message:t}={}){super({message:t??"Request timed out."})}};P.APIConnectionTimeoutError=Ce;var ae=class extends O{};P.BadRequestError=ae;var fe=class extends O{};P.AuthenticationError=fe;var ie=class extends O{};P.PermissionDeniedError=ie;var ce=class extends O{};P.NotFoundError=ce;var ue=class extends O{};P.ConflictError=ue;var de=class extends O{};P.UnprocessableEntityError=de;var ve=class extends O{};P.RateLimitError=ve;var le=class extends O{};P.InternalServerError=le});var E=c(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.safeJSON=d.maybeCoerceBoolean=d.maybeCoerceFloat=d.maybeCoerceInteger=d.coerceBoolean=d.coerceFloat=d.coerceInteger=d.validatePositiveInteger=d.ensurePresent=d.isReadonlyArray=d.isArray=d.isAbsoluteURL=void 0;d.maybeObj=an;d.isEmptyObj=fn;d.hasOwn=cn;d.isObj=un;var k=K(),nn=/^[a-z][a-z0-9+.-]*:/i,sn=e=>nn.test(e);d.isAbsoluteURL=sn;var on=e=>(d.isArray=Array.isArray,(0,d.isArray)(e));d.isArray=on;d.isReadonlyArray=d.isArray;function an(e){return typeof e!="object"?{}:e??{}}function fn(e){if(!e)return!0;for(let t in e)return!1;return!0}function cn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function un(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var dn=e=>{if(e==null)throw new k.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};d.ensurePresent=dn;var vn=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new k.SupermemoryError(`${e} must be an integer`);if(t<0)throw new k.SupermemoryError(`${e} must be a positive integer`);return t};d.validatePositiveInteger=vn;var ln=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};d.coerceInteger=ln;var Pn=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};d.coerceFloat=Pn;var pn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;d.coerceBoolean=pn;var zn=e=>{if(e!=null)return(0,d.coerceInteger)(e)};d.maybeCoerceInteger=zn;var mn=e=>{if(e!=null)return(0,d.coerceFloat)(e)};d.maybeCoerceFloat=mn;var bn=e=>{if(e!=null)return(0,d.coerceBoolean)(e)};d.maybeCoerceBoolean=bn;var xn=e=>{try{return JSON.parse(e)}catch{return}};d.safeJSON=xn});var St=c(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.sleep=void 0;var jn=e=>new Promise(t=>setTimeout(t,e));Pe.sleep=jn});var Je=c(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.VERSION=void 0;pe.VERSION="4.0.0"});var Et=c(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.getPlatformHeaders=w.isRunningInBrowser=void 0;var I=Je(),Xn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";w.isRunningInBrowser=Xn;function On(){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 yn=()=>{let e=On();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":Kt(Deno.build.os),"X-Stainless-Arch":Gt(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":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":Kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Gt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=qn();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function qn(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:t,version:`${s}.${o}.${a}`}}}return null}var Gt=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Kt=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),kt,Hn=()=>kt??(kt=yn());w.getPlatformHeaders=Hn});var Be=c(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=hn;V.makeReadableStream=It;V.ReadableStreamFrom=Wn;V.ReadableStreamToAsyncIterable=Tn;V.CancelReadableStream=Nn;function hn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function It(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Wn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return It({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function Tn(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Nn(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var Ct=c(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.FallbackEncoder=void 0;var Ln=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});ze.FallbackEncoder=Ln});var C=c(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.createForm=x.multipartFormRequestOptions=x.maybeMultipartFormRequestOptions=x.isAsyncIterable=x.checkFileSupport=void 0;x.makeFile=Ae;x.getName=me;var Vn=Be(),Rn=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};x.checkFileSupport=Rn;function Ae(e,t,r){return(0,x.checkFileSupport)(),new File(e,t??"unknown_file",r)}function me(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var gn=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";x.isAsyncIterable=gn;var wn=async(e,t)=>Qe(e.body)?{...e,body:await(0,x.createForm)(e.body,t)}:e;x.maybeMultipartFormRequestOptions=wn;var Zn=async(e,t)=>({...e,body:await(0,x.createForm)(e.body,t)});x.multipartFormRequestOptions=Zn;var Jt=new WeakMap;function Mn(e){let t=typeof e=="function"?e:e.fetch,r=Jt.get(t);if(r)return r;let n=(async()=>{try{let s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Jt.set(t,n),n}var Fn=async(e,t)=>{if(!await Mn(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,s])=>_e(r,n,s))),r};x.createForm=Fn;var Bt=e=>e instanceof Blob&&"name"in e,Dn=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,x.isAsyncIterable)(e)||Bt(e)),Qe=e=>{if(Dn(e))return!0;if(Array.isArray(e))return e.some(Qe);if(e&&typeof e=="object"){for(let t in e)if(Qe(e[t]))return!0}return!1},_e=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,Ae([await r.blob()],me(r)));else if((0,x.isAsyncIterable)(r))e.append(t,Ae([await new Response((0,Vn.ReadableStreamFrom)(r)).blob()],me(r)));else if(Bt(r))e.append(t,r,me(r));else if(Array.isArray(r))await Promise.all(r.map(n=>_e(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>_e(e,`${t}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var Qt=c(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.toFile=Gn;var J=C(),Un=C(),At=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",Yn=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&At(e),Sn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Gn(e,t,r){if((0,Un.checkFileSupport)(),e=await e,Yn(e))return e instanceof File?e:(0,J.makeFile)([await e.arrayBuffer()],e.name);if(Sn(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,J.makeFile)(await $e(s),t,r)}let n=await $e(e);if(t||(t=(0,J.getName)(e)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,J.makeFile)(n,t,r)}async function $e(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(At(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,J.isAsyncIterable)(e))for await(let r of e)t.push(...await $e(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Kn(e)}`)}return t}function Kn(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var tt=c(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.toFile=void 0;var kn=Qt();Object.defineProperty(be,"toFile",{enumerable:!0,get:function(){return kn.toFile}})});var Z=c(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.APIResource=void 0;var rt=class{constructor(t){this._client=t}};xe.APIResource=rt});var B=c(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.isEmptyHeaders=M.buildHeaders=void 0;var _t=E(),$t=Symbol("brand.privateNullableHeaders");function*er(e){if(!e)return;if($t in e){let{values:n,nulls:s}=e;yield*n.entries();for(let o of s)yield[o,null];return}let t=!1,r;e instanceof Headers?r=e.entries():(0,_t.isReadonlyArray)(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,_t.isReadonlyArray)(n[1])?n[1]:[n[1]],a=!1;for(let f of o)f!==void 0&&(t&&!a&&(a=!0,yield[s,null]),yield[s,f])}}var En=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,a]of er(n)){let f=o.toLowerCase();s.has(f)||(t.delete(o),s.add(f)),a===null?(t.delete(o),r.add(f)):(t.append(o,a),r.delete(f))}}return{[$t]:!0,values:t,nulls:r}};M.buildHeaders=En;var In=e=>{for(let t of er(e))return!1;return!0};M.isEmptyHeaders=In});var je=c(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=nt;var Cn=K();function nt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var tr=Object.freeze(Object.create(null)),Jn=(e=nt)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((l,m,X)=>{/[?#]/.test(m)&&(s=!0);let i=n[X],H=(s?encodeURIComponent:e)(""+i);return X!==n.length&&(i==null||typeof i=="object"&&i.toString===Object.getPrototypeOf(Object.getPrototypeOf(i.hasOwnProperty??tr)??tr)?.toString)&&(H=i+"",o.push({start:l.length+m.length,length:H.length,error:`Value of type ${Object.prototype.toString.call(i).slice(8,-1)} is not a valid path parameter`})),l+m+(X===n.length?"":H)},""),f=a.split(/[?#]/,1)[0],z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,v;for(;(v=z.exec(f))!==null;)o.push({start:v.index,length:v[0].length,error:`Value "${v[0]}" can't be safely passed as a path parameter`});if(o.sort((l,m)=>l.start-m.start),o.length>0){let l=0,m=o.reduce((X,i)=>{let H=" ".repeat(i.start-l),D="^".repeat(i.length);return l=i.start+i.length,X+H+D},"");throw new Cn.SupermemoryError(`Path parameters result in path with invalid segments: +var Ge=Object.defineProperty;var Kr=Object.getOwnPropertyDescriptor;var kr=Object.getOwnPropertyNames;var Er=Object.prototype.hasOwnProperty;var Ir=(e,t)=>()=>(e&&(t=e(e=0)),t);var c=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Cr=(e,t)=>{for(var r in t)Ge(e,r,{get:t[r],enumerable:!0})},Jr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of kr(t))!Er.call(e,s)&&s!==r&&Ge(e,s,{get:()=>t[s],enumerable:!(n=Kr(t,s))||n.enumerable});return e};var Br=e=>Jr(Ge({},"__esModule",{value:!0}),e);var Ee=c(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=Ar;h.__classPrivateFieldGet=Qr;h.__importStar=_r;h.__exportStar=$r;function Ar(e,t,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(e,r):s?s.value=r:t.set(e,r),r}function Qr(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var ke=Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]};h.__createBinding=ke;var Yt=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};h.__setModuleDefault=Yt;var Ke=function(e){return Ke=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Ke(e)};function _r(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Ke(e),n=0;n{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.uuid4=void 0;var en=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Y.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};Y.uuid4=en});var Ie=c(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=tn;function tn(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var rn=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};S.castToError=rn});var K=c(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.InternalServerError=P.RateLimitError=P.UnprocessableEntityError=P.ConflictError=P.NotFoundError=P.PermissionDeniedError=P.AuthenticationError=P.BadRequestError=P.APIConnectionTimeoutError=P.APIConnectionError=P.APIUserAbortError=P.APIError=P.SupermemoryError=void 0;var nn=Ie(),oe=class extends Error{};P.SupermemoryError=oe;var O=class e extends oe{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(t,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new G({message:n,cause:(0,nn.castToError)(r)});let o=r;return t===400?new ae(t,o,n,s):t===401?new fe(t,o,n,s):t===403?new ie(t,o,n,s):t===404?new ce(t,o,n,s):t===409?new ue(t,o,n,s):t===422?new de(t,o,n,s):t===429?new ve(t,o,n,s):t>=500?new le(t,o,n,s):new e(t,o,n,s)}};P.APIError=O;var Ce=class extends O{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};P.APIUserAbortError=Ce;var G=class extends O{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};P.APIConnectionError=G;var Je=class extends G{constructor({message:t}={}){super({message:t??"Request timed out."})}};P.APIConnectionTimeoutError=Je;var ae=class extends O{};P.BadRequestError=ae;var fe=class extends O{};P.AuthenticationError=fe;var ie=class extends O{};P.PermissionDeniedError=ie;var ce=class extends O{};P.NotFoundError=ce;var ue=class extends O{};P.ConflictError=ue;var de=class extends O{};P.UnprocessableEntityError=de;var ve=class extends O{};P.RateLimitError=ve;var le=class extends O{};P.InternalServerError=le});var E=c(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.safeJSON=d.maybeCoerceBoolean=d.maybeCoerceFloat=d.maybeCoerceInteger=d.coerceBoolean=d.coerceFloat=d.coerceInteger=d.validatePositiveInteger=d.ensurePresent=d.isReadonlyArray=d.isArray=d.isAbsoluteURL=void 0;d.maybeObj=fn;d.isEmptyObj=cn;d.hasOwn=un;d.isObj=dn;var k=K(),sn=/^[a-z][a-z0-9+.-]*:/i,on=e=>sn.test(e);d.isAbsoluteURL=on;var an=e=>(d.isArray=Array.isArray,(0,d.isArray)(e));d.isArray=an;d.isReadonlyArray=d.isArray;function fn(e){return typeof e!="object"?{}:e??{}}function cn(e){if(!e)return!0;for(let t in e)return!1;return!0}function un(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function dn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var vn=e=>{if(e==null)throw new k.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};d.ensurePresent=vn;var ln=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new k.SupermemoryError(`${e} must be an integer`);if(t<0)throw new k.SupermemoryError(`${e} must be a positive integer`);return t};d.validatePositiveInteger=ln;var Pn=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};d.coerceInteger=Pn;var pn=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};d.coerceFloat=pn;var zn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;d.coerceBoolean=zn;var mn=e=>{if(e!=null)return(0,d.coerceInteger)(e)};d.maybeCoerceInteger=mn;var bn=e=>{if(e!=null)return(0,d.coerceFloat)(e)};d.maybeCoerceFloat=bn;var xn=e=>{if(e!=null)return(0,d.coerceBoolean)(e)};d.maybeCoerceBoolean=xn;var jn=e=>{try{return JSON.parse(e)}catch{return}};d.safeJSON=jn});var Gt=c(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.sleep=void 0;var Xn=e=>new Promise(t=>setTimeout(t,e));Pe.sleep=Xn});var Be=c(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.VERSION=void 0;pe.VERSION="4.0.0"});var It=c(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.getPlatformHeaders=w.isRunningInBrowser=void 0;var I=Be(),On=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";w.isRunningInBrowser=On;function yn(){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 qn=()=>{let e=yn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":kt(Deno.build.os),"X-Stainless-Arch":Kt(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":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Kt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Hn();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Hn(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:t,version:`${s}.${o}.${a}`}}}return null}var Kt=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",kt=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),Et,hn=()=>Et??(Et=qn());w.getPlatformHeaders=hn});var Ae=c(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=Wn;V.makeReadableStream=Ct;V.ReadableStreamFrom=Tn;V.ReadableStreamToAsyncIterable=Nn;V.CancelReadableStream=Ln;function Wn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ct(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Tn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ct({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function Nn(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ln(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var Jt=c(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.FallbackEncoder=void 0;var Vn=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});ze.FallbackEncoder=Vn});var C=c(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.createForm=x.multipartFormRequestOptions=x.maybeMultipartFormRequestOptions=x.isAsyncIterable=x.checkFileSupport=void 0;x.makeFile=Qe;x.getName=me;var Rn=Ae(),gn=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};x.checkFileSupport=gn;function Qe(e,t,r){return(0,x.checkFileSupport)(),new File(e,t??"unknown_file",r)}function me(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var wn=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";x.isAsyncIterable=wn;var Zn=async(e,t)=>_e(e.body)?{...e,body:await(0,x.createForm)(e.body,t)}:e;x.maybeMultipartFormRequestOptions=Zn;var Mn=async(e,t)=>({...e,body:await(0,x.createForm)(e.body,t)});x.multipartFormRequestOptions=Mn;var Bt=new WeakMap;function Fn(e){let t=typeof e=="function"?e:e.fetch,r=Bt.get(t);if(r)return r;let n=(async()=>{try{let s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Bt.set(t,n),n}var Dn=async(e,t)=>{if(!await Fn(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,s])=>$e(r,n,s))),r};x.createForm=Dn;var At=e=>e instanceof Blob&&"name"in e,Un=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,x.isAsyncIterable)(e)||At(e)),_e=e=>{if(Un(e))return!0;if(Array.isArray(e))return e.some(_e);if(e&&typeof e=="object"){for(let t in e)if(_e(e[t]))return!0}return!1},$e=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,Qe([await r.blob()],me(r)));else if((0,x.isAsyncIterable)(r))e.append(t,Qe([await new Response((0,Rn.ReadableStreamFrom)(r)).blob()],me(r)));else if(At(r))e.append(t,r,me(r));else if(Array.isArray(r))await Promise.all(r.map(n=>$e(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>$e(e,`${t}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var _t=c(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.toFile=Kn;var J=C(),Yn=C(),Qt=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",Sn=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Qt(e),Gn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Kn(e,t,r){if((0,Yn.checkFileSupport)(),e=await e,Sn(e))return e instanceof File?e:(0,J.makeFile)([await e.arrayBuffer()],e.name);if(Gn(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,J.makeFile)(await et(s),t,r)}let n=await et(e);if(t||(t=(0,J.getName)(e)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,J.makeFile)(n,t,r)}async function et(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Qt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,J.isAsyncIterable)(e))for await(let r of e)t.push(...await et(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${kn(e)}`)}return t}function kn(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var rt=c(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.toFile=void 0;var En=_t();Object.defineProperty(be,"toFile",{enumerable:!0,get:function(){return En.toFile}})});var Z=c(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.APIResource=void 0;var nt=class{constructor(t){this._client=t}};xe.APIResource=nt});var B=c(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.isEmptyHeaders=M.buildHeaders=void 0;var $t=E(),er=Symbol("brand.privateNullableHeaders");function*tr(e){if(!e)return;if(er in e){let{values:n,nulls:s}=e;yield*n.entries();for(let o of s)yield[o,null];return}let t=!1,r;e instanceof Headers?r=e.entries():(0,$t.isReadonlyArray)(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,$t.isReadonlyArray)(n[1])?n[1]:[n[1]],a=!1;for(let f of o)f!==void 0&&(t&&!a&&(a=!0,yield[s,null]),yield[s,f])}}var In=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,a]of tr(n)){let f=o.toLowerCase();s.has(f)||(t.delete(o),s.add(f)),a===null?(t.delete(o),r.add(f)):(t.append(o,a),r.delete(f))}}return{[er]:!0,values:t,nulls:r}};M.buildHeaders=In;var Cn=e=>{for(let t of tr(e))return!1;return!0};M.isEmptyHeaders=Cn});var je=c(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=st;var Jn=K();function st(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var rr=Object.freeze(Object.create(null)),Bn=(e=st)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((l,m,X)=>{/[?#]/.test(m)&&(s=!0);let i=n[X],H=(s?encodeURIComponent:e)(""+i);return X!==n.length&&(i==null||typeof i=="object"&&i.toString===Object.getPrototypeOf(Object.getPrototypeOf(i.hasOwnProperty??rr)??rr)?.toString)&&(H=i+"",o.push({start:l.length+m.length,length:H.length,error:`Value of type ${Object.prototype.toString.call(i).slice(8,-1)} is not a valid path parameter`})),l+m+(X===n.length?"":H)},""),f=a.split(/[?#]/,1)[0],z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,v;for(;(v=z.exec(f))!==null;)o.push({start:v.index,length:v[0].length,error:`Value "${v[0]}" can't be safely passed as a path parameter`});if(o.sort((l,m)=>l.start-m.start),o.length>0){let l=0,m=o.reduce((X,i)=>{let H=" ".repeat(i.start-l),D="^".repeat(i.length);return l=i.start+i.length,X+H+D},"");throw new Jn.SupermemoryError(`Path parameters result in path with invalid segments: ${o.map(X=>X.error).join(` `)} ${a} -${m}`)}return a};N.createPathTagFunction=Jn;N.path=(0,N.createPathTagFunction)(nt)});var ot=c(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Connections=void 0;var Bn=Z(),An=B(),W=je(),st=class extends Bn.APIResource{create(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/connections/list",{body:t,...r})}configure(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/configure`,{body:r,...n})}deleteByID(t,r){return this._client.delete((0,W.path)`/v3/connections/${t}`,r)}deleteByProvider(t,r,n){return this._client.delete((0,W.path)`/v3/connections/${t}`,{body:r,...n})}getByID(t,r){return this._client.get((0,W.path)`/v3/connections/${t}`,r)}getByTag(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/connection`,{body:r,...n})}import(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/import`,{body:r,...n,headers:(0,An.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/documents`,{body:r,...n})}resources(t,r={},n){return this._client.get((0,W.path)`/v3/connections/${t}/resources`,{query:r,...n})}};Xe.Connections=st});var it=c(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Documents=void 0;var Qn=Z(),_n=B(),$n=C(),at=je(),ft=class extends Qn.APIResource{update(t,r={},n){return this._client.patch((0,at.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,at.path)`/v3/documents/${t}`,{...r,headers:(0,_n.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}batchAdd(t,r){return this._client.post("/v3/documents/batch",{body:t,...r})}deleteBulk(t={},r){return this._client.delete("/v3/documents/bulk",{body:t,...r})}get(t,r){return this._client.get((0,at.path)`/v3/documents/${t}`,r)}listProcessing(t){return this._client.get("/v3/documents/processing",t)}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,$n.multipartFormRequestOptions)({body:t,...r},this._client))}};Oe.Documents=ft});var dt=c(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Memories=void 0;var es=Z(),ts=B(),rs=C(),ct=je(),ut=class extends es.APIResource{update(t,r={},n){return this._client.patch((0,ct.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,ct.path)`/v3/documents/${t}`,{...r,headers:(0,ts.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}forget(t,r){return this._client.delete("/v4/memories",{body:t,...r})}get(t,r){return this._client.get((0,ct.path)`/v3/documents/${t}`,r)}updateMemory(t,r){return this._client.patch("/v4/memories",{body:t,...r})}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,rs.multipartFormRequestOptions)({body:t,...r},this._client))}};ye.Memories=ut});var lt=c(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Search=void 0;var ns=Z(),vt=class extends ns.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};qe.Search=vt});var pt=c(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Settings=void 0;var ss=Z(),Pt=class extends ss.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};He.Settings=Pt});var rr=c(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.Settings=q.Search=q.Memories=q.Documents=q.Connections=void 0;var os=ot();Object.defineProperty(q,"Connections",{enumerable:!0,get:function(){return os.Connections}});var as=it();Object.defineProperty(q,"Documents",{enumerable:!0,get:function(){return as.Documents}});var fs=dt();Object.defineProperty(q,"Memories",{enumerable:!0,get:function(){return fs.Memories}});var is=lt();Object.defineProperty(q,"Search",{enumerable:!0,get:function(){return is.Search}});var cs=pt();Object.defineProperty(q,"Settings",{enumerable:!0,get:function(){return cs.Settings}})});var zt=c(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=sr;var us=E(),We={off:0,error:200,warn:300,info:400,debug:500},ds=(e,t,r)=>{if(e){if((0,us.hasOwn)(We,e))return e;sr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(We))}`)}};R.parseLogLevel=ds;function A(){}function he(e,t,r){return!t||We[e]>We[r]?A:t[e].bind(t)}var vs={error:A,warn:A,info:A,debug:A},nr=new WeakMap;function sr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return vs;let n=nr.get(t);if(n&&n[0]===r)return n[1];let s={error:he("error",t,r),warn:he("warn",t,r),info:he("info",t,r),debug:he("debug",t,r)};return nr.set(t,[r,s]),s}var ls=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);R.formatRequestDetails=ls});var ar=c(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.defaultParseResponse=Ps;var or=zt();async function Ps(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,a=await(async()=>{if(r.status===204)return null;if(t.options.__binaryResponse)return r;let z=r.headers.get("content-type")?.split(";")[0]?.trim();return z?.includes("application/json")||z?.endsWith("+json")?await r.json():await r.text()})();return(0,or.loggerFor)(e).debug(`[${n}] response parsed`,(0,or.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var jt=c(Te=>{"use strict";var Q;Object.defineProperty(Te,"__esModule",{value:!0});Te.APIPromise=void 0;var bt=ke(),ps=ar(),xt=class e extends Promise{constructor(t,r,n=ps.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,Q.set(this,void 0),bt.__classPrivateFieldSet(this,Q,t,"f")}_thenUnwrap(t){return new e(bt.__classPrivateFieldGet(this,Q,"f"),this.responsePromise,async(r,n)=>t(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(bt.__classPrivateFieldGet(this,Q,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};Te.APIPromise=xt;Q=new WeakMap});var fr=c(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.readEnv=void 0;var zs=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};Ne.readEnv=zs});var Tt=c(Ve=>{"use strict";var ht,Wt,Le,ir;Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Supermemory=void 0;var L=ke(),ms=Yt(),Xt=E(),bs=St(),Ot=Ee(),xs=Et(),yt=L.__importStar(Be()),js=L.__importStar(Ct()),Xs=Je(),b=L.__importStar(K()),Os=L.__importStar(tt()),_=L.__importStar(rr()),ys=jt(),qs=ot(),Hs=it(),hs=dt(),Ws=lt(),Ts=pt(),qt=B(),Ht=fr(),j=zt(),Ns=E(),p=class{constructor({baseURL:t=(0,Ht.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Ht.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(ht.add(this),Le.set(this,void 0),this.memories=new _.Memories(this),this.documents=new _.Documents(this),this.search=new _.Search(this),this.settings=new _.Settings(this),this.connections=new _.Connections(this),r===void 0)throw new b.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:t||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??Wt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,j.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,j.parseLogLevel)((0,Ht.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??yt.getDefaultFetch(),L.__classPrivateFieldSet(this,Le,js.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,qt.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Object.entries(t).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new b.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Xs.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,ms.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,ht,"m",ir).call(this)&&n||this.baseURL,o=(0,Xt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,Ns.isEmptyObj)(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(s=>({method:t,path:r,...s})))}request(t,r=null){return new ys.APIPromise(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let s=await t,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:a,url:f,timeout:z}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(a,{url:f,options:s});let v="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if((0,j.loggerFor)(this).debug(`[${v}] sending request`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:f,options:s,headers:a.headers})),s.signal?.aborted)throw new b.APIUserAbortError;let X=new AbortController,i=await this.fetchWithTimeout(f,a,z,X).catch(Ot.castToError),H=Date.now();if(i instanceof globalThis.Error){let U=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let T=(0,Ot.isAbortError)(i)||/timed? ?out/i.test(String(i)+("cause"in i?String(i.cause):""));if(r)return(0,j.loggerFor)(this).info(`[${v}] connection ${T?"timed out":"failed"} - ${U}`),(0,j.loggerFor)(this).debug(`[${v}] connection ${T?"timed out":"failed"} (${U})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:H-m,message:i.message})),this.retryRequest(s,r,n??v);throw(0,j.loggerFor)(this).info(`[${v}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,j.loggerFor)(this).debug(`[${v}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:H-m,message:i.message})),T?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:i})}let D=`[${v}${l}] ${a.method} ${f} ${i.ok?"succeeded":"failed"} with status ${i.status} in ${H-m}ms`;if(!i.ok){let U=await this.shouldRetry(i);if(r&&U){let se=`retrying, ${r} attempts remaining`;return await yt.CancelReadableStream(i.body),(0,j.loggerFor)(this).info(`${D} - ${se}`),(0,j.loggerFor)(this).debug(`[${v}] response error (${se})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:H-m})),this.retryRequest(s,r,n??v,i.headers)}let T=U?"error; no more retries left":"error; not retryable";(0,j.loggerFor)(this).info(`${D} - ${T}`);let Mt=await i.text().catch(se=>(0,Ot.castToError)(se).message),Ft=(0,Xt.safeJSON)(Mt),Dt=Ft?void 0:Mt;throw(0,j.loggerFor)(this).debug(`[${v}] response error (${T})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,message:Dt,durationMs:Date.now()-m})),this.makeStatusError(i.status,Ft,Dt,i.headers)}return(0,j.loggerFor)(this).info(D),(0,j.loggerFor)(this).debug(`[${v}] response start`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:H-m})),{response:i,options:s,controller:X,requestLogID:v,retryOfRequestLogID:n,startTime:m}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:a,...f}=r||{};o&&o.addEventListener("abort",()=>s.abort());let z=setTimeout(()=>s.abort(),n),v=globalThis.ReadableStream&&f.body instanceof globalThis.ReadableStream||typeof f.body=="object"&&f.body!==null&&Symbol.asyncIterator in f.body,l={signal:s.signal,...v?{duplex:"half"}:{},method:"GET",...f};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,l)}finally{clearTimeout(z)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,s){let o,a=s?.get("retry-after-ms");if(a){let z=parseFloat(a);Number.isNaN(z)||(o=z)}let f=s?.get("retry-after");if(f&&!o){let z=parseFloat(f);Number.isNaN(z)?o=Date.parse(f)-Date.now():o=z*1e3}if(!(o&&0<=o&&o<60*1e3)){let z=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,z)}return await(0,bs.sleep)(o),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let o=r-t,a=Math.min(.5*Math.pow(2,o),8),f=1-Math.random()*.25;return a*f*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:s,path:o,query:a,defaultBaseURL:f}=n,z=this.buildURL(o,a,f);"timeout"in n&&(0,Xt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:v,body:l}=this.buildBody({options:n}),m=await this.buildHeaders({options:t,method:s,bodyHeaders:v,retryCount:r});return{req:{method:s,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:z,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let a=(0,qt.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...(0,xs.getPlatformHeaders)()},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,qt.buildHeaders)([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:yt.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Le,"f").call(this,{body:t,headers:n})}};Ve.Supermemory=p;Wt=p,Le=new WeakMap,ht=new WeakSet,ir=function(){return this.baseURL!=="https://api.supermemory.ai"};p.Supermemory=Wt;p.DEFAULT_TIMEOUT=6e4;p.SupermemoryError=b.SupermemoryError;p.APIError=b.APIError;p.APIConnectionError=b.APIConnectionError;p.APIConnectionTimeoutError=b.APIConnectionTimeoutError;p.APIUserAbortError=b.APIUserAbortError;p.NotFoundError=b.NotFoundError;p.ConflictError=b.ConflictError;p.RateLimitError=b.RateLimitError;p.BadRequestError=b.BadRequestError;p.AuthenticationError=b.AuthenticationError;p.InternalServerError=b.InternalServerError;p.PermissionDeniedError=b.PermissionDeniedError;p.UnprocessableEntityError=b.UnprocessableEntityError;p.toFile=Os.toFile;p.Memories=hs.Memories;p.Documents=Hs.Documents;p.Search=Ws.Search;p.Settings=Ts.Settings;p.Connections=qs.Connections});var ur=c((u,cr)=>{"use strict";u=cr.exports=function(...e){return new u.default(...e)};Object.defineProperty(u,"__esModule",{value:!0});u.UnprocessableEntityError=u.PermissionDeniedError=u.InternalServerError=u.AuthenticationError=u.BadRequestError=u.RateLimitError=u.ConflictError=u.NotFoundError=u.APIUserAbortError=u.APIConnectionTimeoutError=u.APIConnectionError=u.APIError=u.SupermemoryError=u.Supermemory=u.APIPromise=u.toFile=u.default=void 0;var Ls=Tt();Object.defineProperty(u,"default",{enumerable:!0,get:function(){return Ls.Supermemory}});var Vs=tt();Object.defineProperty(u,"toFile",{enumerable:!0,get:function(){return Vs.toFile}});var Rs=jt();Object.defineProperty(u,"APIPromise",{enumerable:!0,get:function(){return Rs.APIPromise}});var gs=Tt();Object.defineProperty(u,"Supermemory",{enumerable:!0,get:function(){return gs.Supermemory}});var y=K();Object.defineProperty(u,"SupermemoryError",{enumerable:!0,get:function(){return y.SupermemoryError}});Object.defineProperty(u,"APIError",{enumerable:!0,get:function(){return y.APIError}});Object.defineProperty(u,"APIConnectionError",{enumerable:!0,get:function(){return y.APIConnectionError}});Object.defineProperty(u,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return y.APIConnectionTimeoutError}});Object.defineProperty(u,"APIUserAbortError",{enumerable:!0,get:function(){return y.APIUserAbortError}});Object.defineProperty(u,"NotFoundError",{enumerable:!0,get:function(){return y.NotFoundError}});Object.defineProperty(u,"ConflictError",{enumerable:!0,get:function(){return y.ConflictError}});Object.defineProperty(u,"RateLimitError",{enumerable:!0,get:function(){return y.RateLimitError}});Object.defineProperty(u,"BadRequestError",{enumerable:!0,get:function(){return y.BadRequestError}});Object.defineProperty(u,"AuthenticationError",{enumerable:!0,get:function(){return y.AuthenticationError}});Object.defineProperty(u,"InternalServerError",{enumerable:!0,get:function(){return y.InternalServerError}});Object.defineProperty(u,"PermissionDeniedError",{enumerable:!0,get:function(){return y.PermissionDeniedError}});Object.defineProperty(u,"UnprocessableEntityError",{enumerable:!0,get:function(){return y.UnprocessableEntityError}})});var vr={};Ir(vr,{getRequestIntegrity:()=>Is,sanitizeContent:()=>Fs,sanitizeMetadata:()=>Gs,validateApiKeyFormat:()=>ws,validateContainerTag:()=>Zs,validateContentLength:()=>Ds,validateRecallConfig:()=>Ks});function ws(e){return!e||typeof e!="string"?{valid:!1,reason:"key is empty or not a string"}:e.startsWith("sm_")?e.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(e)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function Zs(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function Fs(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Ms)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function Ds(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Gs(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=Us)break;n.length>Ys||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,Ss),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function Ks(e,t){let r=[];return(!Number.isInteger(e)||e<1||e>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(t)||t<1||t>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Nt(e){return(0,Re.createHash)("sha256").update(e).digest("hex")}function Es(e,t){let r=[Nt(e),Nt(t),dr].join(":");return(0,Re.createHmac)("sha256",ks).update(r).digest("base64url")}function Is(e,t){let r=Nt(t),n=Es(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${dr}`,n].join(".")}}var Re,Ms,Us,Ys,Ss,dr,ks,lr=Er(()=>{Re=require("node:crypto");Ms=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Us=50,Ys=128,Ss=1024;dr=1,ks="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Lt=c((Wa,Pr)=>{var Cs="https://api.supermemory.ai";Pr.exports={BASE_URL:Cs}});var zr=c((Ta,pr)=>{var Js=ur().default,{getRequestIntegrity:Bs,validateApiKeyFormat:As,validateContainerTag:Qs}=(lr(),Jr(vr)),{BASE_URL:_s}=Lt(),$s="claudecode_default";function eo(e,t=r=>r){let r=new Set;return e.filter(n=>{let s=String(t(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var to=`Developer coding session transcript. Focus on USER message and intent. +${m}`)}return a};N.createPathTagFunction=Bn;N.path=(0,N.createPathTagFunction)(st)});var at=c(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Connections=void 0;var An=Z(),Qn=B(),W=je(),ot=class extends An.APIResource{create(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/connections/list",{body:t,...r})}configure(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/configure`,{body:r,...n})}deleteByID(t,r){return this._client.delete((0,W.path)`/v3/connections/${t}`,r)}deleteByProvider(t,r,n){return this._client.delete((0,W.path)`/v3/connections/${t}`,{body:r,...n})}getByID(t,r){return this._client.get((0,W.path)`/v3/connections/${t}`,r)}getByTag(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/connection`,{body:r,...n})}import(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/import`,{body:r,...n,headers:(0,Qn.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/documents`,{body:r,...n})}resources(t,r={},n){return this._client.get((0,W.path)`/v3/connections/${t}/resources`,{query:r,...n})}};Xe.Connections=ot});var ct=c(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Documents=void 0;var _n=Z(),$n=B(),es=C(),ft=je(),it=class extends _n.APIResource{update(t,r={},n){return this._client.patch((0,ft.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,ft.path)`/v3/documents/${t}`,{...r,headers:(0,$n.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}batchAdd(t,r){return this._client.post("/v3/documents/batch",{body:t,...r})}deleteBulk(t={},r){return this._client.delete("/v3/documents/bulk",{body:t,...r})}get(t,r){return this._client.get((0,ft.path)`/v3/documents/${t}`,r)}listProcessing(t){return this._client.get("/v3/documents/processing",t)}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,es.multipartFormRequestOptions)({body:t,...r},this._client))}};Oe.Documents=it});var vt=c(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Memories=void 0;var ts=Z(),rs=B(),ns=C(),ut=je(),dt=class extends ts.APIResource{update(t,r={},n){return this._client.patch((0,ut.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,ut.path)`/v3/documents/${t}`,{...r,headers:(0,rs.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}forget(t,r){return this._client.delete("/v4/memories",{body:t,...r})}get(t,r){return this._client.get((0,ut.path)`/v3/documents/${t}`,r)}updateMemory(t,r){return this._client.patch("/v4/memories",{body:t,...r})}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,ns.multipartFormRequestOptions)({body:t,...r},this._client))}};ye.Memories=dt});var Pt=c(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Search=void 0;var ss=Z(),lt=class extends ss.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};qe.Search=lt});var zt=c(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Settings=void 0;var os=Z(),pt=class extends os.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};He.Settings=pt});var nr=c(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.Settings=q.Search=q.Memories=q.Documents=q.Connections=void 0;var as=at();Object.defineProperty(q,"Connections",{enumerable:!0,get:function(){return as.Connections}});var fs=ct();Object.defineProperty(q,"Documents",{enumerable:!0,get:function(){return fs.Documents}});var is=vt();Object.defineProperty(q,"Memories",{enumerable:!0,get:function(){return is.Memories}});var cs=Pt();Object.defineProperty(q,"Search",{enumerable:!0,get:function(){return cs.Search}});var us=zt();Object.defineProperty(q,"Settings",{enumerable:!0,get:function(){return us.Settings}})});var mt=c(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=or;var ds=E(),We={off:0,error:200,warn:300,info:400,debug:500},vs=(e,t,r)=>{if(e){if((0,ds.hasOwn)(We,e))return e;or(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(We))}`)}};R.parseLogLevel=vs;function A(){}function he(e,t,r){return!t||We[e]>We[r]?A:t[e].bind(t)}var ls={error:A,warn:A,info:A,debug:A},sr=new WeakMap;function or(e){let t=e.logger,r=e.logLevel??"off";if(!t)return ls;let n=sr.get(t);if(n&&n[0]===r)return n[1];let s={error:he("error",t,r),warn:he("warn",t,r),info:he("info",t,r),debug:he("debug",t,r)};return sr.set(t,[r,s]),s}var Ps=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);R.formatRequestDetails=Ps});var fr=c(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.defaultParseResponse=ps;var ar=mt();async function ps(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,a=await(async()=>{if(r.status===204)return null;if(t.options.__binaryResponse)return r;let z=r.headers.get("content-type")?.split(";")[0]?.trim();return z?.includes("application/json")||z?.endsWith("+json")?await r.json():await r.text()})();return(0,ar.loggerFor)(e).debug(`[${n}] response parsed`,(0,ar.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var Xt=c(Te=>{"use strict";var Q;Object.defineProperty(Te,"__esModule",{value:!0});Te.APIPromise=void 0;var xt=Ee(),zs=fr(),jt=class e extends Promise{constructor(t,r,n=zs.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,Q.set(this,void 0),xt.__classPrivateFieldSet(this,Q,t,"f")}_thenUnwrap(t){return new e(xt.__classPrivateFieldGet(this,Q,"f"),this.responsePromise,async(r,n)=>t(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(xt.__classPrivateFieldGet(this,Q,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};Te.APIPromise=jt;Q=new WeakMap});var ir=c(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.readEnv=void 0;var ms=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};Ne.readEnv=ms});var Nt=c(Ve=>{"use strict";var Wt,Tt,Le,cr;Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Supermemory=void 0;var L=Ee(),bs=St(),Ot=E(),xs=Gt(),yt=Ie(),js=It(),qt=L.__importStar(Ae()),Xs=L.__importStar(Jt()),Os=Be(),b=L.__importStar(K()),ys=L.__importStar(rt()),_=L.__importStar(nr()),qs=Xt(),Hs=at(),hs=ct(),Ws=vt(),Ts=Pt(),Ns=zt(),Ht=B(),ht=ir(),j=mt(),Ls=E(),p=class{constructor({baseURL:t=(0,ht.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,ht.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Wt.add(this),Le.set(this,void 0),this.memories=new _.Memories(this),this.documents=new _.Documents(this),this.search=new _.Search(this),this.settings=new _.Settings(this),this.connections=new _.Connections(this),r===void 0)throw new b.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:t||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??Tt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,j.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,j.parseLogLevel)((0,ht.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??qt.getDefaultFetch(),L.__classPrivateFieldSet(this,Le,Xs.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,Ht.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Object.entries(t).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new b.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Os.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,bs.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,Wt,"m",cr).call(this)&&n||this.baseURL,o=(0,Ot.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,Ls.isEmptyObj)(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(s=>({method:t,path:r,...s})))}request(t,r=null){return new qs.APIPromise(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let s=await t,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:a,url:f,timeout:z}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(a,{url:f,options:s});let v="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if((0,j.loggerFor)(this).debug(`[${v}] sending request`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:f,options:s,headers:a.headers})),s.signal?.aborted)throw new b.APIUserAbortError;let X=new AbortController,i=await this.fetchWithTimeout(f,a,z,X).catch(yt.castToError),H=Date.now();if(i instanceof globalThis.Error){let U=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let T=(0,yt.isAbortError)(i)||/timed? ?out/i.test(String(i)+("cause"in i?String(i.cause):""));if(r)return(0,j.loggerFor)(this).info(`[${v}] connection ${T?"timed out":"failed"} - ${U}`),(0,j.loggerFor)(this).debug(`[${v}] connection ${T?"timed out":"failed"} (${U})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:H-m,message:i.message})),this.retryRequest(s,r,n??v);throw(0,j.loggerFor)(this).info(`[${v}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,j.loggerFor)(this).debug(`[${v}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:H-m,message:i.message})),T?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:i})}let D=`[${v}${l}] ${a.method} ${f} ${i.ok?"succeeded":"failed"} with status ${i.status} in ${H-m}ms`;if(!i.ok){let U=await this.shouldRetry(i);if(r&&U){let se=`retrying, ${r} attempts remaining`;return await qt.CancelReadableStream(i.body),(0,j.loggerFor)(this).info(`${D} - ${se}`),(0,j.loggerFor)(this).debug(`[${v}] response error (${se})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:H-m})),this.retryRequest(s,r,n??v,i.headers)}let T=U?"error; no more retries left":"error; not retryable";(0,j.loggerFor)(this).info(`${D} - ${T}`);let Ft=await i.text().catch(se=>(0,yt.castToError)(se).message),Dt=(0,Ot.safeJSON)(Ft),Ut=Dt?void 0:Ft;throw(0,j.loggerFor)(this).debug(`[${v}] response error (${T})`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,message:Ut,durationMs:Date.now()-m})),this.makeStatusError(i.status,Dt,Ut,i.headers)}return(0,j.loggerFor)(this).info(D),(0,j.loggerFor)(this).debug(`[${v}] response start`,(0,j.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:H-m})),{response:i,options:s,controller:X,requestLogID:v,retryOfRequestLogID:n,startTime:m}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:a,...f}=r||{};o&&o.addEventListener("abort",()=>s.abort());let z=setTimeout(()=>s.abort(),n),v=globalThis.ReadableStream&&f.body instanceof globalThis.ReadableStream||typeof f.body=="object"&&f.body!==null&&Symbol.asyncIterator in f.body,l={signal:s.signal,...v?{duplex:"half"}:{},method:"GET",...f};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,l)}finally{clearTimeout(z)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,s){let o,a=s?.get("retry-after-ms");if(a){let z=parseFloat(a);Number.isNaN(z)||(o=z)}let f=s?.get("retry-after");if(f&&!o){let z=parseFloat(f);Number.isNaN(z)?o=Date.parse(f)-Date.now():o=z*1e3}if(!(o&&0<=o&&o<60*1e3)){let z=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,z)}return await(0,xs.sleep)(o),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let o=r-t,a=Math.min(.5*Math.pow(2,o),8),f=1-Math.random()*.25;return a*f*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:s,path:o,query:a,defaultBaseURL:f}=n,z=this.buildURL(o,a,f);"timeout"in n&&(0,Ot.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:v,body:l}=this.buildBody({options:n}),m=await this.buildHeaders({options:t,method:s,bodyHeaders:v,retryCount:r});return{req:{method:s,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:z,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let a=(0,Ht.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...(0,js.getPlatformHeaders)()},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,Ht.buildHeaders)([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:qt.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Le,"f").call(this,{body:t,headers:n})}};Ve.Supermemory=p;Tt=p,Le=new WeakMap,Wt=new WeakSet,cr=function(){return this.baseURL!=="https://api.supermemory.ai"};p.Supermemory=Tt;p.DEFAULT_TIMEOUT=6e4;p.SupermemoryError=b.SupermemoryError;p.APIError=b.APIError;p.APIConnectionError=b.APIConnectionError;p.APIConnectionTimeoutError=b.APIConnectionTimeoutError;p.APIUserAbortError=b.APIUserAbortError;p.NotFoundError=b.NotFoundError;p.ConflictError=b.ConflictError;p.RateLimitError=b.RateLimitError;p.BadRequestError=b.BadRequestError;p.AuthenticationError=b.AuthenticationError;p.InternalServerError=b.InternalServerError;p.PermissionDeniedError=b.PermissionDeniedError;p.UnprocessableEntityError=b.UnprocessableEntityError;p.toFile=ys.toFile;p.Memories=Ws.Memories;p.Documents=hs.Documents;p.Search=Ts.Search;p.Settings=Ns.Settings;p.Connections=Hs.Connections});var dr=c((u,ur)=>{"use strict";u=ur.exports=function(...e){return new u.default(...e)};Object.defineProperty(u,"__esModule",{value:!0});u.UnprocessableEntityError=u.PermissionDeniedError=u.InternalServerError=u.AuthenticationError=u.BadRequestError=u.RateLimitError=u.ConflictError=u.NotFoundError=u.APIUserAbortError=u.APIConnectionTimeoutError=u.APIConnectionError=u.APIError=u.SupermemoryError=u.Supermemory=u.APIPromise=u.toFile=u.default=void 0;var Vs=Nt();Object.defineProperty(u,"default",{enumerable:!0,get:function(){return Vs.Supermemory}});var Rs=rt();Object.defineProperty(u,"toFile",{enumerable:!0,get:function(){return Rs.toFile}});var gs=Xt();Object.defineProperty(u,"APIPromise",{enumerable:!0,get:function(){return gs.APIPromise}});var ws=Nt();Object.defineProperty(u,"Supermemory",{enumerable:!0,get:function(){return ws.Supermemory}});var y=K();Object.defineProperty(u,"SupermemoryError",{enumerable:!0,get:function(){return y.SupermemoryError}});Object.defineProperty(u,"APIError",{enumerable:!0,get:function(){return y.APIError}});Object.defineProperty(u,"APIConnectionError",{enumerable:!0,get:function(){return y.APIConnectionError}});Object.defineProperty(u,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return y.APIConnectionTimeoutError}});Object.defineProperty(u,"APIUserAbortError",{enumerable:!0,get:function(){return y.APIUserAbortError}});Object.defineProperty(u,"NotFoundError",{enumerable:!0,get:function(){return y.NotFoundError}});Object.defineProperty(u,"ConflictError",{enumerable:!0,get:function(){return y.ConflictError}});Object.defineProperty(u,"RateLimitError",{enumerable:!0,get:function(){return y.RateLimitError}});Object.defineProperty(u,"BadRequestError",{enumerable:!0,get:function(){return y.BadRequestError}});Object.defineProperty(u,"AuthenticationError",{enumerable:!0,get:function(){return y.AuthenticationError}});Object.defineProperty(u,"InternalServerError",{enumerable:!0,get:function(){return y.InternalServerError}});Object.defineProperty(u,"PermissionDeniedError",{enumerable:!0,get:function(){return y.PermissionDeniedError}});Object.defineProperty(u,"UnprocessableEntityError",{enumerable:!0,get:function(){return y.UnprocessableEntityError}})});var lr={};Cr(lr,{getRequestIntegrity:()=>Cs,sanitizeContent:()=>Ds,sanitizeMetadata:()=>Ks,validateApiKeyFormat:()=>Zs,validateContainerTag:()=>Ms,validateContentLength:()=>Us,validateRecallConfig:()=>ks});function Zs(e){return!e||typeof e!="string"?{valid:!1,reason:"key is empty or not a string"}:e.startsWith("sm_")?e.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(e)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function Ms(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function Ds(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Fs)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function Us(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Ks(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=Ys)break;n.length>Ss||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,Gs),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function ks(e,t){let r=[];return(!Number.isInteger(e)||e<1||e>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(t)||t<1||t>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Lt(e){return(0,Re.createHash)("sha256").update(e).digest("hex")}function Is(e,t){let r=[Lt(e),Lt(t),vr].join(":");return(0,Re.createHmac)("sha256",Es).update(r).digest("base64url")}function Cs(e,t){let r=Lt(t),n=Is(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${vr}`,n].join(".")}}var Re,Fs,Ys,Ss,Gs,vr,Es,Pr=Ir(()=>{Re=require("node:crypto");Fs=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Ys=50,Ss=128,Gs=1024;vr=1,Es="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Vt=c((Ta,pr)=>{var Js="https://api.supermemory.ai";pr.exports={BASE_URL:Js}});var mr=c((Na,zr)=>{var Bs=dr().default,{getRequestIntegrity:As,validateApiKeyFormat:Qs,validateContainerTag:_s}=(Pr(),Br(lr)),{BASE_URL:$s}=Vt(),eo="claudecode_default";function to(e,t=r=>r){let r=new Set;return e.filter(n=>{let s=String(t(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var ro=`Developer coding session transcript. Focus on USER message and intent. RULES: - Extract USER's action/intent, not every detail assistant provides matter @@ -30,7 +30,7 @@ EXAMPLES: SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,ro=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,no=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" @@ -43,60 +43,60 @@ EXAMPLES: | Input | Memory | | "The auth flow works by..." | "Auth flow: [description]" | | "We structure components like..." | "Component structure convention: [pattern]" | -| "To add a new API route..." | "Adding API routes: [steps]" |`,Vt=class{constructor(t,r,n={}){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=As(t);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||$s,a=Qs(o);a.valid||console.warn(`Container tag warning: ${a.reason}`);let f=Bs(t,o);this.client=new Js({apiKey:t,baseURL:n.baseUrl||_s,defaultHeaders:{...f,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let a=await this.client.add(o);return{id:a.id,status:a.status,containerTag:r||this.containerTag}}async search(t,r,n={}){let s=await this.client.search.memories({q:t,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(a=>({memory:a.content||a.memory||a.context||"",chunk:a.chunk,metadata:a.metadata,updatedAt:a.updatedAt,similarity:a.similarity}));return{results:eo(o,a=>a.memory),total:s.total,timing:s.timing}}async getProfile(t,r){let n=await this.client.profile({containerTag:t||this.containerTag,q:r}),s=new Set,o=(v,l=m=>m)=>v.filter(m=>{let X=String(l(m)).toLowerCase().trim();return!X||s.has(X)?!1:(s.add(X),!0)}),a=o(n.profile?.static||[]),f=o(n.profile?.dynamic||[]),z;if(n.searchResults){let v=n.searchResults.results.map(l=>({id:l.id,memory:l.content||l.context||"",similarity:l.similarity,title:l.title,updatedAt:l.updatedAt}));z={results:o(v,l=>l.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:f},searchResults:z}}};pr.exports={SupermemoryClient:Vt,PERSONAL_ENTITY_CONTEXT:to,REPO_ENTITY_CONTEXT:ro}});var Rt=c((Na,mr)=>{var{execSync:ge}=require("node:child_process"),$=require("node:path");function no(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=ge("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=$.resolve(e,r);return $.basename(n)===".git"&&!n.includes(`${$.sep}.git${$.sep}`)?$.dirname(n):ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}mr.exports={getGitRoot:no}});var Ze=c((La,yr)=>{var ee=require("node:fs"),we=require("node:path"),{getGitRoot:br}=Rt(),xr=we.join(".claude",".supermemory-claude"),jr="config.json";function Xr(e){let r=br(e)||e;return we.join(r,xr,jr)}function Or(e){try{let t=Xr(e);if(ee.existsSync(t))return JSON.parse(ee.readFileSync(t,"utf-8"))}catch{}return null}function so(e,t){let n=br(e)||e,s=we.join(n,xr),o=we.join(s,jr);ee.existsSync(s)||ee.mkdirSync(s,{recursive:!0});let f={...Or(e)||{},...t};return ee.writeFileSync(o,JSON.stringify(f,null,2)),o}yr.exports={getConfigPath:Xr,loadProjectConfig:Or,saveProjectConfig:so}});var Wr=c((Va,hr)=>{var{execSync:oo}=require("node:child_process"),ao=require("node:crypto"),{loadProjectConfig:qr}=Ze(),{getGitRoot:Me}=Rt();function Hr(e){return ao.createHash("sha256").update(e).digest("hex").slice(0,16)}function gt(e){try{let r=oo("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/);return r?r[1]:null}catch{return null}}function fo(e){let t=qr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Me(e)||e;return`claudecode_project_${Hr(n)}`}function io(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function co(e){let t=qr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Me(e)||e,o=gt(n)||n.split("/").pop()||"unknown";return`repo_${io(o)}`}function uo(e){let r=Me(e)||e;return gt(r)||r.split("/").pop()||"unknown"}hr.exports={sha256:Hr,getGitRoot:Me,getGitRepoName:gt,getContainerTag:fo,getRepoContainerTag:co,getProjectName:uo}});var Nr=c((Ra,Tr)=>{var{execFile:vo}=require("node:child_process");function Fe(e,t){return new Promise((r,n)=>{vo(e,t,{windowsHide:!0},s=>{s?n(s):r()})})}async function lo(e){let t=e.toString();if(!/^https?:\/\//i.test(t))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await Fe("rundll32.exe",["url.dll,FileProtocolHandler",t]);return}catch{}await Fe("cmd.exe",["/c","start",'""',t]);return}if(process.platform==="darwin"){await Fe("open",[t]);return}await Fe("xdg-open",[t])}Tr.exports={openUrl:lo}});var Lr=c((ga,Po)=>{Po.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var Vr=c((wa,po)=>{po.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var Mr=c((Za,Zr)=>{var zo=require("node:http"),g=require("node:fs"),Rr=require("node:path"),mo=require("node:os"),{openUrl:bo}=Nr(),xo=Lr(),jo=Vr(),Zt=Rr.join(mo.homedir(),".supermemory-claude"),F=Rr.join(Zt,"credentials.json"),gr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",wt=19876,Xo=25e3;function Oo(){g.existsSync(Zt)||g.mkdirSync(Zt,{recursive:!0})}function yo(){try{if(g.existsSync(F)){let e=JSON.parse(g.readFileSync(F,"utf-8"));if(e.apiKey)return e}}catch{}return null}function wr(e){Oo();let t={apiKey:e,savedAt:new Date().toISOString()};g.writeFileSync(F,JSON.stringify(t,null,2))}function qo(){try{g.existsSync(F)&&g.unlinkSync(F)}catch{}}function Ho(){return new Promise((e,t)=>{let r=!1,n=zo.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${wt}`);if(a.pathname==="/callback"){let f=a.searchParams.get("apikey")||a.searchParams.get("api_key");f?.startsWith("sm_")?(wr(f),o.writeHead(200,{"Content-Type":"text/html"}),o.end(xo),r=!0,n.close(),e(f)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(jo))}else o.writeHead(404),o.end("Not found")});n.listen(wt,"127.0.0.1",()=>{let s=`http://localhost:${wt}/callback`,o=`${gr}?callback=${encodeURIComponent(s)}&client=claude_code`;bo(o).catch(a=>{r||(n.close(),t(new Error(`Failed to open browser: ${a.message}`)))})}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},Xo)})}Zr.exports={AUTH_BASE_URL:gr,CREDENTIALS_FILE:F,loadCredentials:yo,saveCredentials:wr,clearCredentials:qo,startAuthFlow:Ho}});var Ur=c((Ma,Dr)=>{var re=require("node:fs"),Fr=require("node:path"),ho=require("node:os"),{loadCredentials:Wo}=Mr(),{loadProjectConfig:ne}=Ze(),{BASE_URL:To}=Lt(),De=Fr.join(ho.homedir(),".supermemory-claude"),te=Fr.join(De,"settings.json"),Ue={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function No(){re.existsSync(De)||re.mkdirSync(De,{recursive:!0})}function Ye(){let e={...Ue};try{if(re.existsSync(te)){let t=re.readFileSync(te,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${te}: ${t.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function Lo(e){No();let t={...e};delete t.apiKey,re.writeFileSync(te,JSON.stringify(t,null,2))}function Vo(e,t,r){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||ne(t||process.cwd()),r?.apiKey)return r.apiKey;let n=Wo();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function Ro(e){if(typeof e!="string"||!e.trim())return null;let t=e.trim();try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t}catch{return null}}function go(e,t){t=t||ne(e||process.cwd());let r=process.env.SUPERMEMORY_API_URL||t?.baseUrl||To,n=Ro(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function wo(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function Zo(e){let t=Ye(),r=ne(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Mo(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function Fo(e){let t=Ye(),r=ne(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Ue.signalKeywords,f=r?.signalKeywords||[],z=[...new Set([...a,...f])].map(l=>l.toLowerCase()),v=r?.signalTurnsBefore||t.signalTurnsBefore||Ue.signalTurnsBefore;return{enabled:o,keywords:z,turnsBefore:v}}function Do(e){let t=Ye();return{directive:ne(e||process.cwd())?.recallDirective||t.recallDirective||null}}Dr.exports={SETTINGS_DIR:De,SETTINGS_FILE:te,DEFAULT_SETTINGS:Ue,loadSettings:Ye,saveSettings:Lo,getApiKey:Vo,getBaseUrl:go,debugLog:wo,getIncludeTools:Zo,shouldIncludeTool:Mo,getSignalConfig:Fo,getRecallConfig:Do}});var Sr=c((Fa,Yr)=>{function Uo(e){let t=e?.status;return t===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":t===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":t===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":t===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof t=="number"&&t>=500?"Supermemory service is temporarily unavailable. Will retry next session.":e?.message||"Unknown error"}function Yo(e){let t=e?.status;return t===429||typeof t=="number"&&t>=500||t==null}function So(e){let t=e?.status;return t===404||t==null}Yr.exports={getUserFriendlyError:Uo,isRetryableError:Yo,isBenignError:So}});var{SupermemoryClient:Go,REPO_ENTITY_CONTEXT:Ko}=zr(),{getRepoContainerTag:ko,getProjectName:Eo}=Wr(),{loadProjectConfig:Io}=Ze(),{loadSettings:Co,getApiKey:Jo,getBaseUrl:Bo}=Ur(),{getUserFriendlyError:Ao}=Sr();async function Qo(){let e=process.argv.slice(2).join(" ");if(!e||!e.trim()){console.log('No content provided. Usage: node save-project-memory.cjs "content to save"');return}let t=Co(),r=process.cwd(),n=Io(r),s;try{s=Jo(t,r,n)}catch{console.log("Supermemory API key not configured."),console.log("Set SUPERMEMORY_CC_API_KEY environment variable.");return}let o=ko(r),a=Eo(r);try{let f=Bo(r,n),v=await new Go(s,o,{baseUrl:f}).addMemory(e,o,{type:"project-knowledge",project:a,timestamp:new Date().toISOString()},{entityContext:Ko});console.log(`Project knowledge saved: ${a}`),console.log(`ID: ${v.id}`)}catch(f){console.log(`Error saving: ${Ao(f)}`)}}Qo().catch(e=>{console.error(`Fatal error: ${e.message}`),process.exit(1)}); +| "To add a new API route..." | "Adding API routes: [steps]" |`,Rt=class{constructor(t,r,n={}){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=Qs(t);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||eo,a=_s(o);a.valid||console.warn(`Container tag warning: ${a.reason}`);let f=As(t,o);this.client=new Bs({apiKey:t,baseURL:n.baseUrl||$s,defaultHeaders:{...f,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let a=await this.client.add(o);return{id:a.id,status:a.status,containerTag:r||this.containerTag}}async search(t,r,n={}){let s=await this.client.search.memories({q:t,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(a=>({memory:a.content||a.memory||a.context||"",chunk:a.chunk,metadata:a.metadata,updatedAt:a.updatedAt,similarity:a.similarity}));return{results:to(o,a=>a.memory),total:s.total,timing:s.timing}}async getProfile(t,r){let n=await this.client.profile({containerTag:t||this.containerTag,q:r}),s=new Set,o=(v,l=m=>m)=>v.filter(m=>{let X=String(l(m)).toLowerCase().trim();return!X||s.has(X)?!1:(s.add(X),!0)}),a=o(n.profile?.static||[]),f=o(n.profile?.dynamic||[]),z;if(n.searchResults){let v=n.searchResults.results.map(l=>({id:l.id,memory:l.content||l.context||"",similarity:l.similarity,title:l.title,updatedAt:l.updatedAt}));z={results:o(v,l=>l.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:f},searchResults:z}}};zr.exports={SupermemoryClient:Rt,PERSONAL_ENTITY_CONTEXT:ro,REPO_ENTITY_CONTEXT:no}});var gt=c((La,br)=>{var{execSync:ge}=require("node:child_process"),$=require("node:path");function so(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=ge("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=$.resolve(e,r);return $.basename(n)===".git"&&!n.includes(`${$.sep}.git${$.sep}`)?$.dirname(n):ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}br.exports={getGitRoot:so}});var Ze=c((Va,qr)=>{var ee=require("node:fs"),we=require("node:path"),{getGitRoot:xr}=gt(),jr=we.join(".claude",".supermemory-claude"),Xr="config.json";function Or(e){let r=xr(e)||e;return we.join(r,jr,Xr)}function yr(e){try{let t=Or(e);if(ee.existsSync(t))return JSON.parse(ee.readFileSync(t,"utf-8"))}catch{}return null}function oo(e,t){let n=xr(e)||e,s=we.join(n,jr),o=we.join(s,Xr);ee.existsSync(s)||ee.mkdirSync(s,{recursive:!0});let f={...yr(e)||{},...t};return ee.writeFileSync(o,JSON.stringify(f,null,2)),o}qr.exports={getConfigPath:Or,loadProjectConfig:yr,saveProjectConfig:oo}});var Tr=c((Ra,Wr)=>{var{execSync:ao}=require("node:child_process"),fo=require("node:crypto"),{loadProjectConfig:Hr}=Ze(),{getGitRoot:Fe}=gt();function hr(e){return fo.createHash("sha256").update(e).digest("hex").slice(0,16)}var Me=new Map;function wt(e){if(Me.has(e))return Me.get(e);try{let r=ao("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/),n=r?r[1]:null;return Me.set(e,n),n}catch{return Me.set(e,null),null}}function io(e){let t=Hr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Fe(e)||e;return`claudecode_project_${hr(n)}`}function co(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function uo(e){let t=Hr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Fe(e)||e,o=wt(n)||n.split("/").pop()||"unknown";return`repo_${co(o)}`}function vo(e){let r=Fe(e)||e;return wt(r)||r.split("/").pop()||"unknown"}Wr.exports={sha256:hr,getGitRoot:Fe,getGitRepoName:wt,getContainerTag:io,getRepoContainerTag:uo,getProjectName:vo}});var Lr=c((ga,Nr)=>{var{execFile:lo}=require("node:child_process");function De(e,t){return new Promise((r,n)=>{lo(e,t,{windowsHide:!0},s=>{s?n(s):r()})})}async function Po(e){let t=e.toString();if(!/^https?:\/\//i.test(t))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await De("rundll32.exe",["url.dll,FileProtocolHandler",t]);return}catch{}await De("cmd.exe",["/c","start",'""',t]);return}if(process.platform==="darwin"){await De("open",[t]);return}await De("xdg-open",[t])}Nr.exports={openUrl:Po}});var Vr=c((wa,po)=>{po.exports=`\r +\r +Connected - Supermemory\r +\r +\r +
\r +
Connected . . .
\r +\r +
\r + \r + +\r + \r +
\r +

Supercharge your Claude Code with Supermemory.

\r +
\r +\r +\r +`});var Rr=c((Za,zo)=>{zo.exports=`\r +\r +Error - Supermemory\r +\r +
Error . . .
\r +

Connection Failed

\r +

Invalid API key received. Please try again.

\r +\r +`});var Fr=c((Ma,Mr)=>{var mo=require("node:http"),g=require("node:fs"),gr=require("node:path"),bo=require("node:os"),{openUrl:xo}=Lr(),jo=Vr(),Xo=Rr(),Mt=gr.join(bo.homedir(),".supermemory-claude"),F=gr.join(Mt,"credentials.json"),wr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",Zt=19876,Oo=25e3;function yo(){g.existsSync(Mt)||g.mkdirSync(Mt,{recursive:!0})}function qo(){try{if(g.existsSync(F)){let e=JSON.parse(g.readFileSync(F,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Zr(e){yo();let t={apiKey:e,savedAt:new Date().toISOString()};g.writeFileSync(F,JSON.stringify(t,null,2))}function Ho(){try{g.existsSync(F)&&g.unlinkSync(F)}catch{}}function ho(){return new Promise((e,t)=>{let r=!1,n=mo.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${Zt}`);if(a.pathname==="/callback"){let f=a.searchParams.get("apikey")||a.searchParams.get("api_key");f?.startsWith("sm_")?(Zr(f),o.writeHead(200,{"Content-Type":"text/html"}),o.end(jo),r=!0,n.close(),e(f)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(Xo))}else o.writeHead(404),o.end("Not found")});n.listen(Zt,"127.0.0.1",()=>{let s=`http://localhost:${Zt}/callback`,o=`${wr}?callback=${encodeURIComponent(s)}&client=claude_code`;xo(o).catch(a=>{r||(n.close(),t(new Error(`Failed to open browser: ${a.message}`)))})}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},Oo)})}Mr.exports={AUTH_BASE_URL:wr,CREDENTIALS_FILE:F,loadCredentials:qo,saveCredentials:Zr,clearCredentials:Ho,startAuthFlow:ho}});var Yr=c((Fa,Ur)=>{var re=require("node:fs"),Dr=require("node:path"),Wo=require("node:os"),{loadCredentials:To}=Fr(),{loadProjectConfig:ne}=Ze(),{BASE_URL:No}=Vt(),Ue=Dr.join(Wo.homedir(),".supermemory-claude"),te=Dr.join(Ue,"settings.json"),Ye={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Lo(){re.existsSync(Ue)||re.mkdirSync(Ue,{recursive:!0})}function Se(){let e={...Ye};try{if(re.existsSync(te)){let t=re.readFileSync(te,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${te}: ${t.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function Vo(e){Lo();let t={...e};delete t.apiKey,re.writeFileSync(te,JSON.stringify(t,null,2))}function Ro(e,t,r){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||ne(t||process.cwd()),r?.apiKey)return r.apiKey;let n=To();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function go(e){if(typeof e!="string"||!e.trim())return null;let t=e.trim();try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t}catch{return null}}function wo(e,t){t=t||ne(e||process.cwd());let r=process.env.SUPERMEMORY_API_URL||t?.baseUrl||No,n=go(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function Zo(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function Mo(e){let t=Se(),r=ne(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Fo(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function Do(e){let t=Se(),r=ne(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Ye.signalKeywords,f=r?.signalKeywords||[],z=[...new Set([...a,...f])].map(l=>l.toLowerCase()),v=r?.signalTurnsBefore||t.signalTurnsBefore||Ye.signalTurnsBefore;return{enabled:o,keywords:z,turnsBefore:v}}function Uo(e){let t=Se();return{directive:ne(e||process.cwd())?.recallDirective||t.recallDirective||null}}Ur.exports={SETTINGS_DIR:Ue,SETTINGS_FILE:te,DEFAULT_SETTINGS:Ye,loadSettings:Se,saveSettings:Vo,getApiKey:Ro,getBaseUrl:wo,debugLog:Zo,getIncludeTools:Mo,shouldIncludeTool:Fo,getSignalConfig:Do,getRecallConfig:Uo}});var Gr=c((Da,Sr)=>{function Yo(e){let t=e?.status;return t===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":t===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":t===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":t===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof t=="number"&&t>=500?"Supermemory service is temporarily unavailable. Will retry next session.":e?.message||"Unknown error"}function So(e){let t=e?.status;return t===429||typeof t=="number"&&t>=500||t==null}function Go(e){let t=e?.status;return t===404||t==null}Sr.exports={getUserFriendlyError:Yo,isRetryableError:So,isBenignError:Go}});var{SupermemoryClient:Ko,REPO_ENTITY_CONTEXT:ko}=mr(),{getRepoContainerTag:Eo,getProjectName:Io}=Tr(),{loadProjectConfig:Co}=Ze(),{loadSettings:Jo,getApiKey:Bo,getBaseUrl:Ao}=Yr(),{getUserFriendlyError:Qo}=Gr();async function _o(){let e=process.argv.slice(2).join(" ");if(!e||!e.trim()){console.log('No content provided. Usage: node save-project-memory.cjs "content to save"');return}let t=Jo(),r=process.cwd(),n=Co(r),s;try{s=Bo(t,r,n)}catch{console.log("Supermemory API key not configured."),console.log("Set SUPERMEMORY_CC_API_KEY environment variable.");return}let o=Eo(r),a=Io(r);try{let f=Ao(r,n),v=await new Ko(s,o,{baseUrl:f}).addMemory(e,o,{type:"project-knowledge",project:a,timestamp:new Date().toISOString()},{entityContext:ko});console.log(`Project knowledge saved: ${a}`),console.log(`ID: ${v.id}`)}catch(f){console.log(`Error saving: ${Qo(f)}`)}}_o().catch(e=>{console.error(`Fatal error: ${e.message}`),process.exit(1)}); diff --git a/plugin/scripts/search-memory.cjs b/plugin/scripts/search-memory.cjs index 6f29004..95b6e14 100755 --- a/plugin/scripts/search-memory.cjs +++ b/plugin/scripts/search-memory.cjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -var Se=Object.defineProperty;var Jr=Object.getOwnPropertyDescriptor;var Br=Object.getOwnPropertyNames;var Ar=Object.prototype.hasOwnProperty;var Qr=(t,e)=>()=>(t&&(e=t(t=0)),e);var u=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),_r=(t,e)=>{for(var r in e)Se(t,r,{get:e[r],enumerable:!0})},$r=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Br(e))!Ar.call(t,s)&&s!==r&&Se(t,s,{get:()=>e[s],enumerable:!(n=Jr(e,s))||n.enumerable});return t};var en=t=>$r(Se({},"__esModule",{value:!0}),t);var ke=u(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=tn;h.__classPrivateFieldGet=rn;h.__importStar=nn;h.__exportStar=sn;function tn(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function rn(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var Ke=Object.create?function(t,e,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(e,r);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,s)}:function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]};h.__createBinding=Ke;var St=Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e};h.__setModuleDefault=St;var Ge=function(t){return Ge=Object.getOwnPropertyNames||function(e){var r=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(r[r.length]=n);return r},Ge(t)};function nn(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r=Ge(t),n=0;n{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.uuid4=void 0;var on=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Y.uuid4=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};Y.uuid4=on});var Ee=u(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=an;function an(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var fn=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};S.castToError=fn});var K=u(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.InternalServerError=z.RateLimitError=z.UnprocessableEntityError=z.ConflictError=z.NotFoundError=z.PermissionDeniedError=z.AuthenticationError=z.BadRequestError=z.APIConnectionTimeoutError=z.APIConnectionError=z.APIUserAbortError=z.APIError=z.SupermemoryError=void 0;var cn=Ee(),oe=class extends Error{};z.SupermemoryError=oe;var y=class t extends oe{constructor(e,r,n,s){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=s,this.error=r}static makeMessage(e,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,r,n,s){if(!e||!s)return new G({message:n,cause:(0,cn.castToError)(r)});let o=r;return e===400?new ae(e,o,n,s):e===401?new ie(e,o,n,s):e===403?new fe(e,o,n,s):e===404?new ce(e,o,n,s):e===409?new ue(e,o,n,s):e===422?new de(e,o,n,s):e===429?new ve(e,o,n,s):e>=500?new le(e,o,n,s):new t(e,o,n,s)}};z.APIError=y;var Ce=class extends y{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}};z.APIUserAbortError=Ce;var G=class extends y{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}};z.APIConnectionError=G;var Ie=class extends G{constructor({message:e}={}){super({message:e??"Request timed out."})}};z.APIConnectionTimeoutError=Ie;var ae=class extends y{};z.BadRequestError=ae;var ie=class extends y{};z.AuthenticationError=ie;var fe=class extends y{};z.PermissionDeniedError=fe;var ce=class extends y{};z.NotFoundError=ce;var ue=class extends y{};z.ConflictError=ue;var de=class extends y{};z.UnprocessableEntityError=de;var ve=class extends y{};z.RateLimitError=ve;var le=class extends y{};z.InternalServerError=le});var E=u(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.safeJSON=p.maybeCoerceBoolean=p.maybeCoerceFloat=p.maybeCoerceInteger=p.coerceBoolean=p.coerceFloat=p.coerceInteger=p.validatePositiveInteger=p.ensurePresent=p.isReadonlyArray=p.isArray=p.isAbsoluteURL=void 0;p.maybeObj=ln;p.isEmptyObj=pn;p.hasOwn=Pn;p.isObj=zn;var k=K(),un=/^[a-z][a-z0-9+.-]*:/i,dn=t=>un.test(t);p.isAbsoluteURL=dn;var vn=t=>(p.isArray=Array.isArray,(0,p.isArray)(t));p.isArray=vn;p.isReadonlyArray=p.isArray;function ln(t){return typeof t!="object"?{}:t??{}}function pn(t){if(!t)return!0;for(let e in t)return!1;return!0}function Pn(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function zn(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var mn=t=>{if(t==null)throw new k.SupermemoryError(`Expected a value to be given but received ${t} instead.`);return t};p.ensurePresent=mn;var bn=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new k.SupermemoryError(`${t} must be an integer`);if(e<0)throw new k.SupermemoryError(`${t} must be a positive integer`);return e};p.validatePositiveInteger=bn;var xn=t=>{if(typeof t=="number")return Math.round(t);if(typeof t=="string")return parseInt(t,10);throw new k.SupermemoryError(`Could not coerce ${t} (type: ${typeof t}) into a number`)};p.coerceInteger=xn;var jn=t=>{if(typeof t=="number")return t;if(typeof t=="string")return parseFloat(t);throw new k.SupermemoryError(`Could not coerce ${t} (type: ${typeof t}) into a number`)};p.coerceFloat=jn;var Xn=t=>typeof t=="boolean"?t:typeof t=="string"?t==="true":!!t;p.coerceBoolean=Xn;var On=t=>{if(t!=null)return(0,p.coerceInteger)(t)};p.maybeCoerceInteger=On;var yn=t=>{if(t!=null)return(0,p.coerceFloat)(t)};p.maybeCoerceFloat=yn;var qn=t=>{if(t!=null)return(0,p.coerceBoolean)(t)};p.maybeCoerceBoolean=qn;var Hn=t=>{try{return JSON.parse(t)}catch{return}};p.safeJSON=Hn});var Kt=u(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.sleep=void 0;var hn=t=>new Promise(e=>setTimeout(e,t));pe.sleep=hn});var Je=u(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.VERSION=void 0;Pe.VERSION="4.0.0"});var It=u(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.getPlatformHeaders=Z.isRunningInBrowser=void 0;var C=Je(),Wn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Z.isRunningInBrowser=Wn;function Tn(){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 Nn=()=>{let t=Tn();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C.VERSION,"X-Stainless-OS":Et(Deno.build.os),"X-Stainless-Arch":kt(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":C.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C.VERSION,"X-Stainless-OS":Et(globalThis.process.platform??"unknown"),"X-Stainless-Arch":kt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ln();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C.VERSION,"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":C.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ln(){if(typeof navigator>"u"||!navigator)return null;let t=[{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:r}of t){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:e,version:`${s}.${o}.${a}`}}}return null}var kt=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Et=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),Ct,Vn=()=>Ct??(Ct=Nn());Z.getPlatformHeaders=Vn});var Be=u(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=Rn;V.makeReadableStream=Jt;V.ReadableStreamFrom=gn;V.ReadableStreamToAsyncIterable=wn;V.CancelReadableStream=Zn;function Rn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Jt(...t){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(...t)}function gn(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Jt({start(){},async pull(r){let{done:n,value:s}=await e.next();n?r.close():r.enqueue(s)},async cancel(){await e.return?.()}})}function wn(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Zn(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}});var Bt=u(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.FallbackEncoder=void 0;var Mn=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});ze.FallbackEncoder=Mn});var I=u(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=Ae;j.getName=me;var Fn=Be(),Dn=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};j.checkFileSupport=Dn;function Ae(t,e,r){return(0,j.checkFileSupport)(),new File(t,e??"unknown_file",r)}function me(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Un=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";j.isAsyncIterable=Un;var Yn=async(t,e)=>Qe(t.body)?{...t,body:await(0,j.createForm)(t.body,e)}:t;j.maybeMultipartFormRequestOptions=Yn;var Sn=async(t,e)=>({...t,body:await(0,j.createForm)(t.body,e)});j.multipartFormRequestOptions=Sn;var At=new WeakMap;function Gn(t){let e=typeof t=="function"?t:t.fetch,r=At.get(e);if(r)return r;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return At.set(e,n),n}var Kn=async(t,e)=>{if(!await Gn(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,s])=>_e(r,n,s))),r};j.createForm=Kn;var Qt=t=>t instanceof Blob&&"name"in t,kn=t=>typeof t=="object"&&t!==null&&(t instanceof Response||(0,j.isAsyncIterable)(t)||Qt(t)),Qe=t=>{if(kn(t))return!0;if(Array.isArray(t))return t.some(Qe);if(t&&typeof t=="object"){for(let e in t)if(Qe(t[e]))return!0}return!1},_e=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,Ae([await r.blob()],me(r)));else if((0,j.isAsyncIterable)(r))t.append(e,Ae([await new Response((0,Fn.ReadableStreamFrom)(r)).blob()],me(r)));else if(Qt(r))t.append(e,r,me(r));else if(Array.isArray(r))await Promise.all(r.map(n=>_e(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>_e(t,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var $t=u(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.toFile=Jn;var J=I(),En=I(),_t=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Cn=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&_t(t),In=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Jn(t,e,r){if((0,En.checkFileSupport)(),t=await t,Cn(t))return t instanceof File?t:(0,J.makeFile)([await t.arrayBuffer()],t.name);if(In(t)){let s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),(0,J.makeFile)(await $e(s),e,r)}let n=await $e(t);if(e||(e=(0,J.getName)(t)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,J.makeFile)(n,e,r)}async function $e(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(_t(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if((0,J.isAsyncIterable)(t))for await(let r of t)e.push(...await $e(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Bn(t)}`)}return e}function Bn(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}});var tt=u(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.toFile=void 0;var An=$t();Object.defineProperty(be,"toFile",{enumerable:!0,get:function(){return An.toFile}})});var M=u(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.APIResource=void 0;var rt=class{constructor(e){this._client=e}};xe.APIResource=rt});var B=u(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.isEmptyHeaders=F.buildHeaders=void 0;var er=E(),tr=Symbol("brand.privateNullableHeaders");function*rr(t){if(!t)return;if(tr in t){let{values:n,nulls:s}=t;yield*n.entries();for(let o of s)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():(0,er.isReadonlyArray)(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,er.isReadonlyArray)(n[1])?n[1]:[n[1]],a=!1;for(let i of o)i!==void 0&&(e&&!a&&(a=!0,yield[s,null]),yield[s,i])}}var Qn=t=>{let e=new Headers,r=new Set;for(let n of t){let s=new Set;for(let[o,a]of rr(n)){let i=o.toLowerCase();s.has(i)||(e.delete(o),s.add(i)),a===null?(e.delete(o),r.add(i)):(e.append(o,a),r.delete(i))}}return{[tr]:!0,values:e,nulls:r}};F.buildHeaders=Qn;var _n=t=>{for(let e of rr(t))return!1;return!0};F.isEmptyHeaders=_n});var je=u(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=nt;var $n=K();function nt(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var nr=Object.freeze(Object.create(null)),es=(t=nt)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((c,d,b)=>{/[?#]/.test(d)&&(s=!0);let f=n[b],O=(s?encodeURIComponent:t)(""+f);return b!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??nr)??nr)?.toString)&&(O=f+"",o.push({start:c.length+d.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),c+d+(b===n.length?"":O)},""),i=a.split(/[?#]/,1)[0],P=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=P.exec(i))!==null;)o.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(o.sort((c,d)=>c.start-d.start),o.length>0){let c=0,d=o.reduce((b,f)=>{let O=" ".repeat(f.start-c),w="^".repeat(f.length);return c=f.start+f.length,b+O+w},"");throw new $n.SupermemoryError(`Path parameters result in path with invalid segments: +var Ge=Object.defineProperty;var Br=Object.getOwnPropertyDescriptor;var Ar=Object.getOwnPropertyNames;var Qr=Object.prototype.hasOwnProperty;var _r=(e,t)=>()=>(e&&(t=e(e=0)),t);var u=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$r=(e,t)=>{for(var r in t)Ge(e,r,{get:t[r],enumerable:!0})},en=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ar(t))!Qr.call(e,s)&&s!==r&&Ge(e,s,{get:()=>t[s],enumerable:!(n=Br(t,s))||n.enumerable});return e};var tn=e=>en(Ge({},"__esModule",{value:!0}),e);var Ee=u(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=rn;h.__classPrivateFieldGet=nn;h.__importStar=sn;h.__exportStar=on;function rn(e,t,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(e,r):s?s.value=r:t.set(e,r),r}function nn(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var ke=Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]};h.__createBinding=ke;var Gt=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};h.__setModuleDefault=Gt;var Ke=function(e){return Ke=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Ke(e)};function sn(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Ke(e),n=0;n{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.uuid4=void 0;var an=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Y.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};Y.uuid4=an});var Ce=u(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=fn;function fn(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var cn=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};S.castToError=cn});var K=u(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.InternalServerError=z.RateLimitError=z.UnprocessableEntityError=z.ConflictError=z.NotFoundError=z.PermissionDeniedError=z.AuthenticationError=z.BadRequestError=z.APIConnectionTimeoutError=z.APIConnectionError=z.APIUserAbortError=z.APIError=z.SupermemoryError=void 0;var un=Ce(),oe=class extends Error{};z.SupermemoryError=oe;var y=class e extends oe{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(t,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new G({message:n,cause:(0,un.castToError)(r)});let o=r;return t===400?new ae(t,o,n,s):t===401?new ie(t,o,n,s):t===403?new fe(t,o,n,s):t===404?new ce(t,o,n,s):t===409?new ue(t,o,n,s):t===422?new de(t,o,n,s):t===429?new ve(t,o,n,s):t>=500?new le(t,o,n,s):new e(t,o,n,s)}};z.APIError=y;var Ie=class extends y{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};z.APIUserAbortError=Ie;var G=class extends y{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};z.APIConnectionError=G;var Je=class extends G{constructor({message:t}={}){super({message:t??"Request timed out."})}};z.APIConnectionTimeoutError=Je;var ae=class extends y{};z.BadRequestError=ae;var ie=class extends y{};z.AuthenticationError=ie;var fe=class extends y{};z.PermissionDeniedError=fe;var ce=class extends y{};z.NotFoundError=ce;var ue=class extends y{};z.ConflictError=ue;var de=class extends y{};z.UnprocessableEntityError=de;var ve=class extends y{};z.RateLimitError=ve;var le=class extends y{};z.InternalServerError=le});var E=u(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.safeJSON=p.maybeCoerceBoolean=p.maybeCoerceFloat=p.maybeCoerceInteger=p.coerceBoolean=p.coerceFloat=p.coerceInteger=p.validatePositiveInteger=p.ensurePresent=p.isReadonlyArray=p.isArray=p.isAbsoluteURL=void 0;p.maybeObj=pn;p.isEmptyObj=Pn;p.hasOwn=zn;p.isObj=mn;var k=K(),dn=/^[a-z][a-z0-9+.-]*:/i,vn=e=>dn.test(e);p.isAbsoluteURL=vn;var ln=e=>(p.isArray=Array.isArray,(0,p.isArray)(e));p.isArray=ln;p.isReadonlyArray=p.isArray;function pn(e){return typeof e!="object"?{}:e??{}}function Pn(e){if(!e)return!0;for(let t in e)return!1;return!0}function zn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function mn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var bn=e=>{if(e==null)throw new k.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};p.ensurePresent=bn;var xn=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new k.SupermemoryError(`${e} must be an integer`);if(t<0)throw new k.SupermemoryError(`${e} must be a positive integer`);return t};p.validatePositiveInteger=xn;var jn=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};p.coerceInteger=jn;var Xn=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};p.coerceFloat=Xn;var On=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;p.coerceBoolean=On;var yn=e=>{if(e!=null)return(0,p.coerceInteger)(e)};p.maybeCoerceInteger=yn;var qn=e=>{if(e!=null)return(0,p.coerceFloat)(e)};p.maybeCoerceFloat=qn;var Hn=e=>{if(e!=null)return(0,p.coerceBoolean)(e)};p.maybeCoerceBoolean=Hn;var hn=e=>{try{return JSON.parse(e)}catch{return}};p.safeJSON=hn});var kt=u(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.sleep=void 0;var Wn=e=>new Promise(t=>setTimeout(t,e));pe.sleep=Wn});var Be=u(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.VERSION=void 0;Pe.VERSION="4.0.0"});var Jt=u(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.getPlatformHeaders=Z.isRunningInBrowser=void 0;var C=Be(),Tn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Z.isRunningInBrowser=Tn;function Nn(){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 Ln=()=>{let e=Nn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C.VERSION,"X-Stainless-OS":Ct(Deno.build.os),"X-Stainless-Arch":Et(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":C.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C.VERSION,"X-Stainless-OS":Ct(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Et(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Vn();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Vn(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:t,version:`${s}.${o}.${a}`}}}return null}var Et=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Ct=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),It,Rn=()=>It??(It=Ln());Z.getPlatformHeaders=Rn});var Ae=u(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=gn;V.makeReadableStream=Bt;V.ReadableStreamFrom=wn;V.ReadableStreamToAsyncIterable=Zn;V.CancelReadableStream=Mn;function gn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Bt(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function wn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Bt({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function Zn(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Mn(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var At=u(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.FallbackEncoder=void 0;var Fn=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});ze.FallbackEncoder=Fn});var I=u(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=Qe;j.getName=me;var Dn=Ae(),Un=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};j.checkFileSupport=Un;function Qe(e,t,r){return(0,j.checkFileSupport)(),new File(e,t??"unknown_file",r)}function me(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var Yn=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";j.isAsyncIterable=Yn;var Sn=async(e,t)=>_e(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=Sn;var Gn=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=Gn;var Qt=new WeakMap;function Kn(e){let t=typeof e=="function"?e:e.fetch,r=Qt.get(t);if(r)return r;let n=(async()=>{try{let s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Qt.set(t,n),n}var kn=async(e,t)=>{if(!await Kn(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,s])=>$e(r,n,s))),r};j.createForm=kn;var _t=e=>e instanceof Blob&&"name"in e,En=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||_t(e)),_e=e=>{if(En(e))return!0;if(Array.isArray(e))return e.some(_e);if(e&&typeof e=="object"){for(let t in e)if(_e(e[t]))return!0}return!1},$e=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,Qe([await r.blob()],me(r)));else if((0,j.isAsyncIterable)(r))e.append(t,Qe([await new Response((0,Dn.ReadableStreamFrom)(r)).blob()],me(r)));else if(_t(r))e.append(t,r,me(r));else if(Array.isArray(r))await Promise.all(r.map(n=>$e(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>$e(e,`${t}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var er=u(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.toFile=Bn;var J=I(),Cn=I(),$t=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",In=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&$t(e),Jn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Bn(e,t,r){if((0,Cn.checkFileSupport)(),e=await e,In(e))return e instanceof File?e:(0,J.makeFile)([await e.arrayBuffer()],e.name);if(Jn(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,J.makeFile)(await et(s),t,r)}let n=await et(e);if(t||(t=(0,J.getName)(e)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,J.makeFile)(n,t,r)}async function et(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if($t(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,J.isAsyncIterable)(e))for await(let r of e)t.push(...await et(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${An(e)}`)}return t}function An(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var rt=u(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.toFile=void 0;var Qn=er();Object.defineProperty(be,"toFile",{enumerable:!0,get:function(){return Qn.toFile}})});var M=u(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.APIResource=void 0;var nt=class{constructor(t){this._client=t}};xe.APIResource=nt});var B=u(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.isEmptyHeaders=F.buildHeaders=void 0;var tr=E(),rr=Symbol("brand.privateNullableHeaders");function*nr(e){if(!e)return;if(rr in e){let{values:n,nulls:s}=e;yield*n.entries();for(let o of s)yield[o,null];return}let t=!1,r;e instanceof Headers?r=e.entries():(0,tr.isReadonlyArray)(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,tr.isReadonlyArray)(n[1])?n[1]:[n[1]],a=!1;for(let i of o)i!==void 0&&(t&&!a&&(a=!0,yield[s,null]),yield[s,i])}}var _n=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,a]of nr(n)){let i=o.toLowerCase();s.has(i)||(t.delete(o),s.add(i)),a===null?(t.delete(o),r.add(i)):(t.append(o,a),r.delete(i))}}return{[rr]:!0,values:t,nulls:r}};F.buildHeaders=_n;var $n=e=>{for(let t of nr(e))return!1;return!0};F.isEmptyHeaders=$n});var je=u(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=st;var es=K();function st(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var sr=Object.freeze(Object.create(null)),ts=(e=st)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((c,d,b)=>{/[?#]/.test(d)&&(s=!0);let f=n[b],O=(s?encodeURIComponent:e)(""+f);return b!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??sr)??sr)?.toString)&&(O=f+"",o.push({start:c.length+d.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),c+d+(b===n.length?"":O)},""),i=a.split(/[?#]/,1)[0],P=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=P.exec(i))!==null;)o.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(o.sort((c,d)=>c.start-d.start),o.length>0){let c=0,d=o.reduce((b,f)=>{let O=" ".repeat(f.start-c),w="^".repeat(f.length);return c=f.start+f.length,b+O+w},"");throw new es.SupermemoryError(`Path parameters result in path with invalid segments: ${o.map(b=>b.error).join(` `)} ${a} -${d}`)}return a};N.createPathTagFunction=es;N.path=(0,N.createPathTagFunction)(nt)});var ot=u(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Connections=void 0;var ts=M(),rs=B(),W=je(),st=class extends ts.APIResource{create(e,r={},n){return this._client.post((0,W.path)`/v3/connections/${e}`,{body:r,...n})}list(e={},r){return this._client.post("/v3/connections/list",{body:e,...r})}configure(e,r,n){return this._client.post((0,W.path)`/v3/connections/${e}/configure`,{body:r,...n})}deleteByID(e,r){return this._client.delete((0,W.path)`/v3/connections/${e}`,r)}deleteByProvider(e,r,n){return this._client.delete((0,W.path)`/v3/connections/${e}`,{body:r,...n})}getByID(e,r){return this._client.get((0,W.path)`/v3/connections/${e}`,r)}getByTag(e,r,n){return this._client.post((0,W.path)`/v3/connections/${e}/connection`,{body:r,...n})}import(e,r={},n){return this._client.post((0,W.path)`/v3/connections/${e}/import`,{body:r,...n,headers:(0,rs.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(e,r={},n){return this._client.post((0,W.path)`/v3/connections/${e}/documents`,{body:r,...n})}resources(e,r={},n){return this._client.get((0,W.path)`/v3/connections/${e}/resources`,{query:r,...n})}};Xe.Connections=st});var ft=u(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Documents=void 0;var ns=M(),ss=B(),os=I(),at=je(),it=class extends ns.APIResource{update(e,r={},n){return this._client.patch((0,at.path)`/v3/documents/${e}`,{body:r,...n})}list(e={},r){return this._client.post("/v3/documents/list",{body:e,...r})}delete(e,r){return this._client.delete((0,at.path)`/v3/documents/${e}`,{...r,headers:(0,ss.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(e,r){return this._client.post("/v3/documents",{body:e,...r})}batchAdd(e,r){return this._client.post("/v3/documents/batch",{body:e,...r})}deleteBulk(e={},r){return this._client.delete("/v3/documents/bulk",{body:e,...r})}get(e,r){return this._client.get((0,at.path)`/v3/documents/${e}`,r)}listProcessing(e){return this._client.get("/v3/documents/processing",e)}uploadFile(e,r){return this._client.post("/v3/documents/file",(0,os.multipartFormRequestOptions)({body:e,...r},this._client))}};Oe.Documents=it});var dt=u(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Memories=void 0;var as=M(),is=B(),fs=I(),ct=je(),ut=class extends as.APIResource{update(e,r={},n){return this._client.patch((0,ct.path)`/v3/documents/${e}`,{body:r,...n})}list(e={},r){return this._client.post("/v3/documents/list",{body:e,...r})}delete(e,r){return this._client.delete((0,ct.path)`/v3/documents/${e}`,{...r,headers:(0,is.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(e,r){return this._client.post("/v3/documents",{body:e,...r})}forget(e,r){return this._client.delete("/v4/memories",{body:e,...r})}get(e,r){return this._client.get((0,ct.path)`/v3/documents/${e}`,r)}updateMemory(e,r){return this._client.patch("/v4/memories",{body:e,...r})}uploadFile(e,r){return this._client.post("/v3/documents/file",(0,fs.multipartFormRequestOptions)({body:e,...r},this._client))}};ye.Memories=ut});var lt=u(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Search=void 0;var cs=M(),vt=class extends cs.APIResource{documents(e,r){return this._client.post("/v3/search",{body:e,...r})}execute(e,r){return this._client.post("/v3/search",{body:e,...r})}memories(e,r){return this._client.post("/v4/search",{body:e,...r})}};qe.Search=vt});var Pt=u(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Settings=void 0;var us=M(),pt=class extends us.APIResource{update(e={},r){return this._client.patch("/v3/settings",{body:e,...r})}get(e){return this._client.get("/v3/settings",e)}};He.Settings=pt});var sr=u(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.Settings=H.Search=H.Memories=H.Documents=H.Connections=void 0;var ds=ot();Object.defineProperty(H,"Connections",{enumerable:!0,get:function(){return ds.Connections}});var vs=ft();Object.defineProperty(H,"Documents",{enumerable:!0,get:function(){return vs.Documents}});var ls=dt();Object.defineProperty(H,"Memories",{enumerable:!0,get:function(){return ls.Memories}});var ps=lt();Object.defineProperty(H,"Search",{enumerable:!0,get:function(){return ps.Search}});var Ps=Pt();Object.defineProperty(H,"Settings",{enumerable:!0,get:function(){return Ps.Settings}})});var zt=u(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=ar;var zs=E(),We={off:0,error:200,warn:300,info:400,debug:500},ms=(t,e,r)=>{if(t){if((0,zs.hasOwn)(We,t))return t;ar(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(We))}`)}};R.parseLogLevel=ms;function A(){}function he(t,e,r){return!e||We[t]>We[r]?A:e[t].bind(e)}var bs={error:A,warn:A,info:A,debug:A},or=new WeakMap;function ar(t){let e=t.logger,r=t.logLevel??"off";if(!e)return bs;let n=or.get(e);if(n&&n[0]===r)return n[1];let s={error:he("error",e,r),warn:he("warn",e,r),info:he("info",e,r),debug:he("debug",e,r)};return or.set(e,[r,s]),s}var xs=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);R.formatRequestDetails=xs});var fr=u(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.defaultParseResponse=js;var ir=zt();async function js(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,a=await(async()=>{if(r.status===204)return null;if(e.options.__binaryResponse)return r;let P=r.headers.get("content-type")?.split(";")[0]?.trim();return P?.includes("application/json")||P?.endsWith("+json")?await r.json():await r.text()})();return(0,ir.loggerFor)(t).debug(`[${n}] response parsed`,(0,ir.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var jt=u(Te=>{"use strict";var Q;Object.defineProperty(Te,"__esModule",{value:!0});Te.APIPromise=void 0;var bt=ke(),Xs=fr(),xt=class t extends Promise{constructor(e,r,n=Xs.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,Q.set(this,void 0),bt.__classPrivateFieldSet(this,Q,e,"f")}_thenUnwrap(e){return new t(bt.__classPrivateFieldGet(this,Q,"f"),this.responsePromise,async(r,n)=>e(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(bt.__classPrivateFieldGet(this,Q,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Te.APIPromise=xt;Q=new WeakMap});var cr=u(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.readEnv=void 0;var Os=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};Ne.readEnv=Os});var Tt=u(Ve=>{"use strict";var ht,Wt,Le,ur;Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Supermemory=void 0;var L=ke(),ys=Gt(),Xt=E(),qs=Kt(),Ot=Ee(),Hs=It(),yt=L.__importStar(Be()),hs=L.__importStar(Bt()),Ws=Je(),x=L.__importStar(K()),Ts=L.__importStar(tt()),_=L.__importStar(sr()),Ns=jt(),Ls=ot(),Vs=ft(),Rs=dt(),gs=lt(),ws=Pt(),qt=B(),Ht=cr(),X=zt(),Zs=E(),m=class{constructor({baseURL:e=(0,Ht.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Ht.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(ht.add(this),Le.set(this,void 0),this.memories=new _.Memories(this),this.documents=new _.Documents(this),this.search=new _.Search(this),this.settings=new _.Settings(this),this.connections=new _.Connections(this),r===void 0)throw new x.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:e||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??Wt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,X.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,X.parseLogLevel)((0,Ht.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??yt.getDefaultFetch(),L.__classPrivateFieldSet(this,Le,hs.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...e})}add(e,r){return this.post("/v3/documents",{body:e,...r})}profile(e,r){return this.post("/v4/profile",{body:e,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}async authHeaders(e){return(0,qt.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new x.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Ws.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,ys.uuid4)()}`}makeStatusError(e,r,n,s){return x.APIError.generate(e,r,n,s)}buildURL(e,r,n){let s=!L.__classPrivateFieldGet(this,ht,"m",ur).call(this)&&n||this.baseURL,o=(0,Xt.isAbsoluteURL)(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return(0,Zs.isEmptyObj)(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:r,...s})))}request(e,r=null){return new Ns.APIPromise(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let s=await e,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:a,url:i,timeout:P}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(a,{url:i,options:s});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if((0,X.loggerFor)(this).debug(`[${l}] sending request`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:i,options:s,headers:a.headers})),s.signal?.aborted)throw new x.APIUserAbortError;let b=new AbortController,f=await this.fetchWithTimeout(i,a,P,b).catch(Ot.castToError),O=Date.now();if(f instanceof globalThis.Error){let U=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new x.APIUserAbortError;let T=(0,Ot.isAbortError)(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(r)return(0,X.loggerFor)(this).info(`[${l}] connection ${T?"timed out":"failed"} - ${U}`),(0,X.loggerFor)(this).debug(`[${l}] connection ${T?"timed out":"failed"} (${U})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:O-d,message:f.message})),this.retryRequest(s,r,n??l);throw(0,X.loggerFor)(this).info(`[${l}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,X.loggerFor)(this).debug(`[${l}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:O-d,message:f.message})),T?new x.APIConnectionTimeoutError:new x.APIConnectionError({cause:f})}let w=`[${l}${c}] ${a.method} ${i} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${O-d}ms`;if(!f.ok){let U=await this.shouldRetry(f);if(r&&U){let se=`retrying, ${r} attempts remaining`;return await yt.CancelReadableStream(f.body),(0,X.loggerFor)(this).info(`${w} - ${se}`),(0,X.loggerFor)(this).debug(`[${l}] response error (${se})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:O-d})),this.retryRequest(s,r,n??l,f.headers)}let T=U?"error; no more retries left":"error; not retryable";(0,X.loggerFor)(this).info(`${w} - ${T}`);let Dt=await f.text().catch(se=>(0,Ot.castToError)(se).message),Ut=(0,Xt.safeJSON)(Dt),Yt=Ut?void 0:Dt;throw(0,X.loggerFor)(this).debug(`[${l}] response error (${T})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:Yt,durationMs:Date.now()-d})),this.makeStatusError(f.status,Ut,Yt,f.headers)}return(0,X.loggerFor)(this).info(w),(0,X.loggerFor)(this).debug(`[${l}] response start`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:O-d})),{response:f,options:s,controller:b,requestLogID:l,retryOfRequestLogID:n,startTime:d}}async fetchWithTimeout(e,r,n,s){let{signal:o,method:a,...i}=r||{};o&&o.addEventListener("abort",()=>s.abort());let P=setTimeout(()=>s.abort(),n),l=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,c={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...i};a&&(c.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,c)}finally{clearTimeout(P)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,s){let o,a=s?.get("retry-after-ms");if(a){let P=parseFloat(a);Number.isNaN(P)||(o=P)}let i=s?.get("retry-after");if(i&&!o){let P=parseFloat(i);Number.isNaN(P)?o=Date.parse(i)-Date.now():o=P*1e3}if(!(o&&0<=o&&o<60*1e3)){let P=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,P)}return await(0,qs.sleep)(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,a=Math.min(.5*Math.pow(2,o),8),i=1-Math.random()*.25;return a*i*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:s,path:o,query:a,defaultBaseURL:i}=n,P=this.buildURL(o,a,i);"timeout"in n&&(0,Xt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:c}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:l,retryCount:r});return{req:{method:s,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...n.fetchOptions??{}},url:P,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=(0,qt.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...(0,Hs.getPlatformHeaders)()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=(0,qt.buildHeaders)([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:yt.ReadableStreamFrom(e)}:L.__classPrivateFieldGet(this,Le,"f").call(this,{body:e,headers:n})}};Ve.Supermemory=m;Wt=m,Le=new WeakMap,ht=new WeakSet,ur=function(){return this.baseURL!=="https://api.supermemory.ai"};m.Supermemory=Wt;m.DEFAULT_TIMEOUT=6e4;m.SupermemoryError=x.SupermemoryError;m.APIError=x.APIError;m.APIConnectionError=x.APIConnectionError;m.APIConnectionTimeoutError=x.APIConnectionTimeoutError;m.APIUserAbortError=x.APIUserAbortError;m.NotFoundError=x.NotFoundError;m.ConflictError=x.ConflictError;m.RateLimitError=x.RateLimitError;m.BadRequestError=x.BadRequestError;m.AuthenticationError=x.AuthenticationError;m.InternalServerError=x.InternalServerError;m.PermissionDeniedError=x.PermissionDeniedError;m.UnprocessableEntityError=x.UnprocessableEntityError;m.toFile=Ts.toFile;m.Memories=Rs.Memories;m.Documents=Vs.Documents;m.Search=gs.Search;m.Settings=ws.Settings;m.Connections=Ls.Connections});var vr=u((v,dr)=>{"use strict";v=dr.exports=function(...t){return new v.default(...t)};Object.defineProperty(v,"__esModule",{value:!0});v.UnprocessableEntityError=v.PermissionDeniedError=v.InternalServerError=v.AuthenticationError=v.BadRequestError=v.RateLimitError=v.ConflictError=v.NotFoundError=v.APIUserAbortError=v.APIConnectionTimeoutError=v.APIConnectionError=v.APIError=v.SupermemoryError=v.Supermemory=v.APIPromise=v.toFile=v.default=void 0;var Ms=Tt();Object.defineProperty(v,"default",{enumerable:!0,get:function(){return Ms.Supermemory}});var Fs=tt();Object.defineProperty(v,"toFile",{enumerable:!0,get:function(){return Fs.toFile}});var Ds=jt();Object.defineProperty(v,"APIPromise",{enumerable:!0,get:function(){return Ds.APIPromise}});var Us=Tt();Object.defineProperty(v,"Supermemory",{enumerable:!0,get:function(){return Us.Supermemory}});var q=K();Object.defineProperty(v,"SupermemoryError",{enumerable:!0,get:function(){return q.SupermemoryError}});Object.defineProperty(v,"APIError",{enumerable:!0,get:function(){return q.APIError}});Object.defineProperty(v,"APIConnectionError",{enumerable:!0,get:function(){return q.APIConnectionError}});Object.defineProperty(v,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return q.APIConnectionTimeoutError}});Object.defineProperty(v,"APIUserAbortError",{enumerable:!0,get:function(){return q.APIUserAbortError}});Object.defineProperty(v,"NotFoundError",{enumerable:!0,get:function(){return q.NotFoundError}});Object.defineProperty(v,"ConflictError",{enumerable:!0,get:function(){return q.ConflictError}});Object.defineProperty(v,"RateLimitError",{enumerable:!0,get:function(){return q.RateLimitError}});Object.defineProperty(v,"BadRequestError",{enumerable:!0,get:function(){return q.BadRequestError}});Object.defineProperty(v,"AuthenticationError",{enumerable:!0,get:function(){return q.AuthenticationError}});Object.defineProperty(v,"InternalServerError",{enumerable:!0,get:function(){return q.InternalServerError}});Object.defineProperty(v,"PermissionDeniedError",{enumerable:!0,get:function(){return q.PermissionDeniedError}});Object.defineProperty(v,"UnprocessableEntityError",{enumerable:!0,get:function(){return q.UnprocessableEntityError}})});var pr={};_r(pr,{getRequestIntegrity:()=>_s,sanitizeContent:()=>Ks,sanitizeMetadata:()=>Js,validateApiKeyFormat:()=>Ys,validateContainerTag:()=>Ss,validateContentLength:()=>ks,validateRecallConfig:()=>Bs});function Ys(t){return!t||typeof t!="string"?{valid:!1,reason:"key is empty or not a string"}:t.startsWith("sm_")?t.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(t)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function Ss(t){return!t||typeof t!="string"?{valid:!1,reason:"tag is empty"}:t.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(t)?/^[-_]|[-_]$/.test(t)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function Ks(t,e=1e5){if(!t||typeof t!="string")return"";let r=t;for(let n of Gs)r=r.replace(n,"");return r.length>e&&(r=r.slice(0,e)),r}function ks(t,e=1,r=1e5){return t.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Js(t){let e={},r=0;for(let[n,s]of Object.entries(t)){if(r>=Es)break;n.length>Cs||/[^\w.-]/.test(n)||(typeof s=="string"?(e[n]=s.slice(0,Is),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(e[n]=s,r++))}return e}function Bs(t,e){let r=[];return(!Number.isInteger(t)||t<1||t>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(e)||e<1||e>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Nt(t){return(0,Re.createHash)("sha256").update(t).digest("hex")}function Qs(t,e){let r=[Nt(t),Nt(e),lr].join(":");return(0,Re.createHmac)("sha256",As).update(r).digest("base64url")}function _s(t,e){let r=Nt(e),n=Qs(t,e);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${lr}`,n].join(".")}}var Re,Gs,Es,Cs,Is,lr,As,Pr=Qr(()=>{Re=require("node:crypto");Gs=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Es=50,Cs=128,Is=1024;lr=1,As="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Lt=u((Fa,zr)=>{var $s="https://api.supermemory.ai";zr.exports={BASE_URL:$s}});var br=u((Da,mr)=>{var eo=vr().default,{getRequestIntegrity:to,validateApiKeyFormat:ro,validateContainerTag:no}=(Pr(),en(pr)),{BASE_URL:so}=Lt(),oo="claudecode_default";function ao(t,e=r=>r){let r=new Set;return t.filter(n=>{let s=String(e(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var io=`Developer coding session transcript. Focus on USER message and intent. +${d}`)}return a};N.createPathTagFunction=ts;N.path=(0,N.createPathTagFunction)(st)});var at=u(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Connections=void 0;var rs=M(),ns=B(),W=je(),ot=class extends rs.APIResource{create(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/connections/list",{body:t,...r})}configure(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/configure`,{body:r,...n})}deleteByID(t,r){return this._client.delete((0,W.path)`/v3/connections/${t}`,r)}deleteByProvider(t,r,n){return this._client.delete((0,W.path)`/v3/connections/${t}`,{body:r,...n})}getByID(t,r){return this._client.get((0,W.path)`/v3/connections/${t}`,r)}getByTag(t,r,n){return this._client.post((0,W.path)`/v3/connections/${t}/connection`,{body:r,...n})}import(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/import`,{body:r,...n,headers:(0,ns.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(t,r={},n){return this._client.post((0,W.path)`/v3/connections/${t}/documents`,{body:r,...n})}resources(t,r={},n){return this._client.get((0,W.path)`/v3/connections/${t}/resources`,{query:r,...n})}};Xe.Connections=ot});var ct=u(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Documents=void 0;var ss=M(),os=B(),as=I(),it=je(),ft=class extends ss.APIResource{update(t,r={},n){return this._client.patch((0,it.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,it.path)`/v3/documents/${t}`,{...r,headers:(0,os.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}batchAdd(t,r){return this._client.post("/v3/documents/batch",{body:t,...r})}deleteBulk(t={},r){return this._client.delete("/v3/documents/bulk",{body:t,...r})}get(t,r){return this._client.get((0,it.path)`/v3/documents/${t}`,r)}listProcessing(t){return this._client.get("/v3/documents/processing",t)}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,as.multipartFormRequestOptions)({body:t,...r},this._client))}};Oe.Documents=ft});var vt=u(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Memories=void 0;var is=M(),fs=B(),cs=I(),ut=je(),dt=class extends is.APIResource{update(t,r={},n){return this._client.patch((0,ut.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,ut.path)`/v3/documents/${t}`,{...r,headers:(0,fs.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}forget(t,r){return this._client.delete("/v4/memories",{body:t,...r})}get(t,r){return this._client.get((0,ut.path)`/v3/documents/${t}`,r)}updateMemory(t,r){return this._client.patch("/v4/memories",{body:t,...r})}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,cs.multipartFormRequestOptions)({body:t,...r},this._client))}};ye.Memories=dt});var pt=u(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Search=void 0;var us=M(),lt=class extends us.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};qe.Search=lt});var zt=u(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Settings=void 0;var ds=M(),Pt=class extends ds.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};He.Settings=Pt});var or=u(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.Settings=H.Search=H.Memories=H.Documents=H.Connections=void 0;var vs=at();Object.defineProperty(H,"Connections",{enumerable:!0,get:function(){return vs.Connections}});var ls=ct();Object.defineProperty(H,"Documents",{enumerable:!0,get:function(){return ls.Documents}});var ps=vt();Object.defineProperty(H,"Memories",{enumerable:!0,get:function(){return ps.Memories}});var Ps=pt();Object.defineProperty(H,"Search",{enumerable:!0,get:function(){return Ps.Search}});var zs=zt();Object.defineProperty(H,"Settings",{enumerable:!0,get:function(){return zs.Settings}})});var mt=u(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=ir;var ms=E(),We={off:0,error:200,warn:300,info:400,debug:500},bs=(e,t,r)=>{if(e){if((0,ms.hasOwn)(We,e))return e;ir(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(We))}`)}};R.parseLogLevel=bs;function A(){}function he(e,t,r){return!t||We[e]>We[r]?A:t[e].bind(t)}var xs={error:A,warn:A,info:A,debug:A},ar=new WeakMap;function ir(e){let t=e.logger,r=e.logLevel??"off";if(!t)return xs;let n=ar.get(t);if(n&&n[0]===r)return n[1];let s={error:he("error",t,r),warn:he("warn",t,r),info:he("info",t,r),debug:he("debug",t,r)};return ar.set(t,[r,s]),s}var js=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);R.formatRequestDetails=js});var cr=u(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.defaultParseResponse=Xs;var fr=mt();async function Xs(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,a=await(async()=>{if(r.status===204)return null;if(t.options.__binaryResponse)return r;let P=r.headers.get("content-type")?.split(";")[0]?.trim();return P?.includes("application/json")||P?.endsWith("+json")?await r.json():await r.text()})();return(0,fr.loggerFor)(e).debug(`[${n}] response parsed`,(0,fr.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var Xt=u(Te=>{"use strict";var Q;Object.defineProperty(Te,"__esModule",{value:!0});Te.APIPromise=void 0;var xt=Ee(),Os=cr(),jt=class e extends Promise{constructor(t,r,n=Os.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,Q.set(this,void 0),xt.__classPrivateFieldSet(this,Q,t,"f")}_thenUnwrap(t){return new e(xt.__classPrivateFieldGet(this,Q,"f"),this.responsePromise,async(r,n)=>t(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(xt.__classPrivateFieldGet(this,Q,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};Te.APIPromise=jt;Q=new WeakMap});var ur=u(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.readEnv=void 0;var ys=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};Ne.readEnv=ys});var Nt=u(Ve=>{"use strict";var Wt,Tt,Le,dr;Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Supermemory=void 0;var L=Ee(),qs=Kt(),Ot=E(),Hs=kt(),yt=Ce(),hs=Jt(),qt=L.__importStar(Ae()),Ws=L.__importStar(At()),Ts=Be(),x=L.__importStar(K()),Ns=L.__importStar(rt()),_=L.__importStar(or()),Ls=Xt(),Vs=at(),Rs=ct(),gs=vt(),ws=pt(),Zs=zt(),Ht=B(),ht=ur(),X=mt(),Ms=E(),m=class{constructor({baseURL:t=(0,ht.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,ht.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Wt.add(this),Le.set(this,void 0),this.memories=new _.Memories(this),this.documents=new _.Documents(this),this.search=new _.Search(this),this.settings=new _.Settings(this),this.connections=new _.Connections(this),r===void 0)throw new x.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:t||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??Tt.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,X.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,X.parseLogLevel)((0,ht.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??qt.getDefaultFetch(),L.__classPrivateFieldSet(this,Le,Ws.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,Ht.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Object.entries(t).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new x.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Ts.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,qs.uuid4)()}`}makeStatusError(t,r,n,s){return x.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,Wt,"m",dr).call(this)&&n||this.baseURL,o=(0,Ot.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,Ms.isEmptyObj)(a)||(r={...a,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(s=>({method:t,path:r,...s})))}request(t,r=null){return new Ls.APIPromise(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let s=await t,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:a,url:i,timeout:P}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(a,{url:i,options:s});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if((0,X.loggerFor)(this).debug(`[${l}] sending request`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:i,options:s,headers:a.headers})),s.signal?.aborted)throw new x.APIUserAbortError;let b=new AbortController,f=await this.fetchWithTimeout(i,a,P,b).catch(yt.castToError),O=Date.now();if(f instanceof globalThis.Error){let U=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new x.APIUserAbortError;let T=(0,yt.isAbortError)(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(r)return(0,X.loggerFor)(this).info(`[${l}] connection ${T?"timed out":"failed"} - ${U}`),(0,X.loggerFor)(this).debug(`[${l}] connection ${T?"timed out":"failed"} (${U})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:O-d,message:f.message})),this.retryRequest(s,r,n??l);throw(0,X.loggerFor)(this).info(`[${l}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,X.loggerFor)(this).debug(`[${l}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:O-d,message:f.message})),T?new x.APIConnectionTimeoutError:new x.APIConnectionError({cause:f})}let w=`[${l}${c}] ${a.method} ${i} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${O-d}ms`;if(!f.ok){let U=await this.shouldRetry(f);if(r&&U){let se=`retrying, ${r} attempts remaining`;return await qt.CancelReadableStream(f.body),(0,X.loggerFor)(this).info(`${w} - ${se}`),(0,X.loggerFor)(this).debug(`[${l}] response error (${se})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:O-d})),this.retryRequest(s,r,n??l,f.headers)}let T=U?"error; no more retries left":"error; not retryable";(0,X.loggerFor)(this).info(`${w} - ${T}`);let Ut=await f.text().catch(se=>(0,yt.castToError)(se).message),Yt=(0,Ot.safeJSON)(Ut),St=Yt?void 0:Ut;throw(0,X.loggerFor)(this).debug(`[${l}] response error (${T})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:St,durationMs:Date.now()-d})),this.makeStatusError(f.status,Yt,St,f.headers)}return(0,X.loggerFor)(this).info(w),(0,X.loggerFor)(this).debug(`[${l}] response start`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:O-d})),{response:f,options:s,controller:b,requestLogID:l,retryOfRequestLogID:n,startTime:d}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:a,...i}=r||{};o&&o.addEventListener("abort",()=>s.abort());let P=setTimeout(()=>s.abort(),n),l=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,c={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...i};a&&(c.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,c)}finally{clearTimeout(P)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,s){let o,a=s?.get("retry-after-ms");if(a){let P=parseFloat(a);Number.isNaN(P)||(o=P)}let i=s?.get("retry-after");if(i&&!o){let P=parseFloat(i);Number.isNaN(P)?o=Date.parse(i)-Date.now():o=P*1e3}if(!(o&&0<=o&&o<60*1e3)){let P=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,P)}return await(0,Hs.sleep)(o),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let o=r-t,a=Math.min(.5*Math.pow(2,o),8),i=1-Math.random()*.25;return a*i*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:s,path:o,query:a,defaultBaseURL:i}=n,P=this.buildURL(o,a,i);"timeout"in n&&(0,Ot.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:c}=this.buildBody({options:n}),d=await this.buildHeaders({options:t,method:s,bodyHeaders:l,retryCount:r});return{req:{method:s,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...n.fetchOptions??{}},url:P,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let a=(0,Ht.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...(0,hs.getPlatformHeaders)()},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,Ht.buildHeaders)([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:qt.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Le,"f").call(this,{body:t,headers:n})}};Ve.Supermemory=m;Tt=m,Le=new WeakMap,Wt=new WeakSet,dr=function(){return this.baseURL!=="https://api.supermemory.ai"};m.Supermemory=Tt;m.DEFAULT_TIMEOUT=6e4;m.SupermemoryError=x.SupermemoryError;m.APIError=x.APIError;m.APIConnectionError=x.APIConnectionError;m.APIConnectionTimeoutError=x.APIConnectionTimeoutError;m.APIUserAbortError=x.APIUserAbortError;m.NotFoundError=x.NotFoundError;m.ConflictError=x.ConflictError;m.RateLimitError=x.RateLimitError;m.BadRequestError=x.BadRequestError;m.AuthenticationError=x.AuthenticationError;m.InternalServerError=x.InternalServerError;m.PermissionDeniedError=x.PermissionDeniedError;m.UnprocessableEntityError=x.UnprocessableEntityError;m.toFile=Ns.toFile;m.Memories=gs.Memories;m.Documents=Rs.Documents;m.Search=ws.Search;m.Settings=Zs.Settings;m.Connections=Vs.Connections});var lr=u((v,vr)=>{"use strict";v=vr.exports=function(...e){return new v.default(...e)};Object.defineProperty(v,"__esModule",{value:!0});v.UnprocessableEntityError=v.PermissionDeniedError=v.InternalServerError=v.AuthenticationError=v.BadRequestError=v.RateLimitError=v.ConflictError=v.NotFoundError=v.APIUserAbortError=v.APIConnectionTimeoutError=v.APIConnectionError=v.APIError=v.SupermemoryError=v.Supermemory=v.APIPromise=v.toFile=v.default=void 0;var Fs=Nt();Object.defineProperty(v,"default",{enumerable:!0,get:function(){return Fs.Supermemory}});var Ds=rt();Object.defineProperty(v,"toFile",{enumerable:!0,get:function(){return Ds.toFile}});var Us=Xt();Object.defineProperty(v,"APIPromise",{enumerable:!0,get:function(){return Us.APIPromise}});var Ys=Nt();Object.defineProperty(v,"Supermemory",{enumerable:!0,get:function(){return Ys.Supermemory}});var q=K();Object.defineProperty(v,"SupermemoryError",{enumerable:!0,get:function(){return q.SupermemoryError}});Object.defineProperty(v,"APIError",{enumerable:!0,get:function(){return q.APIError}});Object.defineProperty(v,"APIConnectionError",{enumerable:!0,get:function(){return q.APIConnectionError}});Object.defineProperty(v,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return q.APIConnectionTimeoutError}});Object.defineProperty(v,"APIUserAbortError",{enumerable:!0,get:function(){return q.APIUserAbortError}});Object.defineProperty(v,"NotFoundError",{enumerable:!0,get:function(){return q.NotFoundError}});Object.defineProperty(v,"ConflictError",{enumerable:!0,get:function(){return q.ConflictError}});Object.defineProperty(v,"RateLimitError",{enumerable:!0,get:function(){return q.RateLimitError}});Object.defineProperty(v,"BadRequestError",{enumerable:!0,get:function(){return q.BadRequestError}});Object.defineProperty(v,"AuthenticationError",{enumerable:!0,get:function(){return q.AuthenticationError}});Object.defineProperty(v,"InternalServerError",{enumerable:!0,get:function(){return q.InternalServerError}});Object.defineProperty(v,"PermissionDeniedError",{enumerable:!0,get:function(){return q.PermissionDeniedError}});Object.defineProperty(v,"UnprocessableEntityError",{enumerable:!0,get:function(){return q.UnprocessableEntityError}})});var Pr={};$r(Pr,{getRequestIntegrity:()=>$s,sanitizeContent:()=>ks,sanitizeMetadata:()=>Bs,validateApiKeyFormat:()=>Ss,validateContainerTag:()=>Gs,validateContentLength:()=>Es,validateRecallConfig:()=>As});function Ss(e){return!e||typeof e!="string"?{valid:!1,reason:"key is empty or not a string"}:e.startsWith("sm_")?e.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(e)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function Gs(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function ks(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Ks)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function Es(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Bs(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=Cs)break;n.length>Is||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,Js),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function As(e,t){let r=[];return(!Number.isInteger(e)||e<1||e>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(t)||t<1||t>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Lt(e){return(0,Re.createHash)("sha256").update(e).digest("hex")}function _s(e,t){let r=[Lt(e),Lt(t),pr].join(":");return(0,Re.createHmac)("sha256",Qs).update(r).digest("base64url")}function $s(e,t){let r=Lt(t),n=_s(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${pr}`,n].join(".")}}var Re,Ks,Cs,Is,Js,pr,Qs,zr=_r(()=>{Re=require("node:crypto");Ks=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Cs=50,Is=128,Js=1024;pr=1,Qs="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Vt=u((Da,mr)=>{var eo="https://api.supermemory.ai";mr.exports={BASE_URL:eo}});var xr=u((Ua,br)=>{var to=lr().default,{getRequestIntegrity:ro,validateApiKeyFormat:no,validateContainerTag:so}=(zr(),tn(Pr)),{BASE_URL:oo}=Vt(),ao="claudecode_default";function io(e,t=r=>r){let r=new Set;return e.filter(n=>{let s=String(t(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var fo=`Developer coding session transcript. Focus on USER message and intent. RULES: - Extract USER's action/intent, not every detail assistant provides matter @@ -30,7 +30,7 @@ EXAMPLES: SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,fo=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,co=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" @@ -43,80 +43,80 @@ EXAMPLES: | Input | Memory | | "The auth flow works by..." | "Auth flow: [description]" | | "We structure components like..." | "Component structure convention: [pattern]" | -| "To add a new API route..." | "Adding API routes: [steps]" |`,Vt=class{constructor(e,r,n={}){if(!e)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=ro(e);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||oo,a=no(o);a.valid||console.warn(`Container tag warning: ${a.reason}`);let i=to(e,o);this.client=new eo({apiKey:e,baseURL:n.baseUrl||so,defaultHeaders:{...i,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(e,r,n={},s={}){let o={content:e,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let a=await this.client.add(o);return{id:a.id,status:a.status,containerTag:r||this.containerTag}}async search(e,r,n={}){let s=await this.client.search.memories({q:e,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(a=>({memory:a.content||a.memory||a.context||"",chunk:a.chunk,metadata:a.metadata,updatedAt:a.updatedAt,similarity:a.similarity}));return{results:ao(o,a=>a.memory),total:s.total,timing:s.timing}}async getProfile(e,r){let n=await this.client.profile({containerTag:e||this.containerTag,q:r}),s=new Set,o=(l,c=d=>d)=>l.filter(d=>{let b=String(c(d)).toLowerCase().trim();return!b||s.has(b)?!1:(s.add(b),!0)}),a=o(n.profile?.static||[]),i=o(n.profile?.dynamic||[]),P;if(n.searchResults){let l=n.searchResults.results.map(c=>({id:c.id,memory:c.content||c.context||"",similarity:c.similarity,title:c.title,updatedAt:c.updatedAt}));P={results:o(l,c=>c.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:i},searchResults:P}}};mr.exports={SupermemoryClient:Vt,PERSONAL_ENTITY_CONTEXT:io,REPO_ENTITY_CONTEXT:fo}});var Rt=u((Ua,xr)=>{var{execSync:ge}=require("node:child_process"),$=require("node:path");function co(t){let e=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(e)return ge("git rev-parse --show-toplevel",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=ge("git rev-parse --git-common-dir",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return ge("git rev-parse --show-toplevel",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=$.resolve(t,r);return $.basename(n)===".git"&&!n.includes(`${$.sep}.git${$.sep}`)?$.dirname(n):ge("git rev-parse --show-toplevel",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}xr.exports={getGitRoot:co}});var Ze=u((Ya,Hr)=>{var ee=require("node:fs"),we=require("node:path"),{getGitRoot:jr}=Rt(),Xr=we.join(".claude",".supermemory-claude"),Or="config.json";function yr(t){let r=jr(t)||t;return we.join(r,Xr,Or)}function qr(t){try{let e=yr(t);if(ee.existsSync(e))return JSON.parse(ee.readFileSync(e,"utf-8"))}catch{}return null}function uo(t,e){let n=jr(t)||t,s=we.join(n,Xr),o=we.join(s,Or);ee.existsSync(s)||ee.mkdirSync(s,{recursive:!0});let i={...qr(t)||{},...e};return ee.writeFileSync(o,JSON.stringify(i,null,2)),o}Hr.exports={getConfigPath:yr,loadProjectConfig:qr,saveProjectConfig:uo}});var Nr=u((Sa,Tr)=>{var{execSync:vo}=require("node:child_process"),lo=require("node:crypto"),{loadProjectConfig:hr}=Ze(),{getGitRoot:Me}=Rt();function Wr(t){return lo.createHash("sha256").update(t).digest("hex").slice(0,16)}function gt(t){try{let r=vo("git remote get-url origin",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/);return r?r[1]:null}catch{return null}}function po(t){let e=hr(t);if(e?.personalContainerTag)return e.personalContainerTag;let n=Me(t)||t;return`claudecode_project_${Wr(n)}`}function Po(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function zo(t){let e=hr(t);if(e?.repoContainerTag)return e.repoContainerTag;let n=Me(t)||t,o=gt(n)||n.split("/").pop()||"unknown";return`repo_${Po(o)}`}function mo(t){let r=Me(t)||t;return gt(r)||r.split("/").pop()||"unknown"}Tr.exports={sha256:Wr,getGitRoot:Me,getGitRepoName:gt,getContainerTag:po,getRepoContainerTag:zo,getProjectName:mo}});var Vr=u((Ga,Lr)=>{var{execFile:bo}=require("node:child_process");function Fe(t,e){return new Promise((r,n)=>{bo(t,e,{windowsHide:!0},s=>{s?n(s):r()})})}async function xo(t){let e=t.toString();if(!/^https?:\/\//i.test(e))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await Fe("rundll32.exe",["url.dll,FileProtocolHandler",e]);return}catch{}await Fe("cmd.exe",["/c","start",'""',e]);return}if(process.platform==="darwin"){await Fe("open",[e]);return}await Fe("xdg-open",[e])}Lr.exports={openUrl:xo}});var Rr=u((Ka,jo)=>{jo.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var gr=u((ka,Xo)=>{Xo.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var Dr=u((Ea,Fr)=>{var Oo=require("node:http"),g=require("node:fs"),wr=require("node:path"),yo=require("node:os"),{openUrl:qo}=Vr(),Ho=Rr(),ho=gr(),Zt=wr.join(yo.homedir(),".supermemory-claude"),D=wr.join(Zt,"credentials.json"),Zr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",wt=19876,Wo=25e3;function To(){g.existsSync(Zt)||g.mkdirSync(Zt,{recursive:!0})}function No(){try{if(g.existsSync(D)){let t=JSON.parse(g.readFileSync(D,"utf-8"));if(t.apiKey)return t}}catch{}return null}function Mr(t){To();let e={apiKey:t,savedAt:new Date().toISOString()};g.writeFileSync(D,JSON.stringify(e,null,2))}function Lo(){try{g.existsSync(D)&&g.unlinkSync(D)}catch{}}function Vo(){return new Promise((t,e)=>{let r=!1,n=Oo.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${wt}`);if(a.pathname==="/callback"){let i=a.searchParams.get("apikey")||a.searchParams.get("api_key");i?.startsWith("sm_")?(Mr(i),o.writeHead(200,{"Content-Type":"text/html"}),o.end(Ho),r=!0,n.close(),t(i)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(ho))}else o.writeHead(404),o.end("Not found")});n.listen(wt,"127.0.0.1",()=>{let s=`http://localhost:${wt}/callback`,o=`${Zr}?callback=${encodeURIComponent(s)}&client=claude_code`;qo(o).catch(a=>{r||(n.close(),e(new Error(`Failed to open browser: ${a.message}`)))})}),n.on("error",s=>{r||e(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),e(new Error("AUTH_TIMEOUT")))},Wo)})}Fr.exports={AUTH_BASE_URL:Zr,CREDENTIALS_FILE:D,loadCredentials:No,saveCredentials:Mr,clearCredentials:Lo,startAuthFlow:Vo}});var Sr=u((Ca,Yr)=>{var re=require("node:fs"),Ur=require("node:path"),Ro=require("node:os"),{loadCredentials:go}=Dr(),{loadProjectConfig:ne}=Ze(),{BASE_URL:wo}=Lt(),De=Ur.join(Ro.homedir(),".supermemory-claude"),te=Ur.join(De,"settings.json"),Ue={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Zo(){re.existsSync(De)||re.mkdirSync(De,{recursive:!0})}function Ye(){let t={...Ue};try{if(re.existsSync(te)){let e=re.readFileSync(te,"utf-8");Object.assign(t,JSON.parse(e))}}catch(e){console.error(`Settings: Failed to load ${te}: ${e.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(t.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(t.debug=!0),t}function Mo(t){Zo();let e={...t};delete e.apiKey,re.writeFileSync(te,JSON.stringify(e,null,2))}function Fo(t,e,r){if(t.apiKey)return t.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||ne(e||process.cwd()),r?.apiKey)return r.apiKey;let n=go();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function Do(t){if(typeof t!="string"||!t.trim())return null;let e=t.trim();try{let r=new URL(e);return r.protocol!=="http:"&&r.protocol!=="https:"?null:e}catch{return null}}function Uo(t,e){e=e||ne(t||process.cwd());let r=process.env.SUPERMEMORY_API_URL||e?.baseUrl||wo,n=Do(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function Yo(t,e,r){if(t.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${e}: ${JSON.stringify(r)}`:`[${n}] ${e}`)}}function So(t){let e=Ye(),r=ne(t||process.cwd()),n=e.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Go(t,e){return e.length===0?!1:e.includes(t.toLowerCase())}function Ko(t){let e=Ye(),r=ne(t||process.cwd()),n=e.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=e.signalKeywords||Ue.signalKeywords,i=r?.signalKeywords||[],P=[...new Set([...a,...i])].map(c=>c.toLowerCase()),l=r?.signalTurnsBefore||e.signalTurnsBefore||Ue.signalTurnsBefore;return{enabled:o,keywords:P,turnsBefore:l}}function ko(t){let e=Ye();return{directive:ne(t||process.cwd())?.recallDirective||e.recallDirective||null}}Yr.exports={SETTINGS_DIR:De,SETTINGS_FILE:te,DEFAULT_SETTINGS:Ue,loadSettings:Ye,saveSettings:Mo,getApiKey:Fo,getBaseUrl:Uo,debugLog:Yo,getIncludeTools:So,shouldIncludeTool:Go,getSignalConfig:Ko,getRecallConfig:ko}});var Er=u((Ia,kr)=>{var Gr="The following is recalled context. Reference it only when relevant to the conversation.",Kr="Use these memories naturally when relevant \u2014 including indirect connections \u2014 but don't force them into every response or make assumptions beyond what's stated.";function Mt(t){try{let e=new Date(t),r=new Date,n=(r.getTime()-e.getTime())/1e3,s=n/60,o=n/3600,a=n/86400;if(s<30)return"just now";if(s<60)return`${Math.floor(s)}mins ago`;if(o<24)return`${Math.floor(o)}hrs ago`;if(a<7)return`${Math.floor(a)}d ago`;let i=e.toLocaleString("en",{month:"short"});return e.getFullYear()===r.getFullYear()?`${e.getDate()} ${i}`:`${e.getDate()} ${i}, ${e.getFullYear()}`}catch{return""}}function Eo(t,e=!0,r=!1,n=10,s=!0){if(!t)return null;let o=e?(t.profile?.static||[]).slice(0,n):[],a=e?(t.profile?.dynamic||[]).slice(0,n):[],i=r?(t.searchResults?.results||[]).slice(0,n):[];if(o.length===0&&a.length===0&&i.length===0)return null;let P=[];if(o.length>0){let c=o.map(d=>`- ${d}`).join(` +| "To add a new API route..." | "Adding API routes: [steps]" |`,Rt=class{constructor(t,r,n={}){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=no(t);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||ao,a=so(o);a.valid||console.warn(`Container tag warning: ${a.reason}`);let i=ro(t,o);this.client=new to({apiKey:t,baseURL:n.baseUrl||oo,defaultHeaders:{...i,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let a=await this.client.add(o);return{id:a.id,status:a.status,containerTag:r||this.containerTag}}async search(t,r,n={}){let s=await this.client.search.memories({q:t,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(a=>({memory:a.content||a.memory||a.context||"",chunk:a.chunk,metadata:a.metadata,updatedAt:a.updatedAt,similarity:a.similarity}));return{results:io(o,a=>a.memory),total:s.total,timing:s.timing}}async getProfile(t,r){let n=await this.client.profile({containerTag:t||this.containerTag,q:r}),s=new Set,o=(l,c=d=>d)=>l.filter(d=>{let b=String(c(d)).toLowerCase().trim();return!b||s.has(b)?!1:(s.add(b),!0)}),a=o(n.profile?.static||[]),i=o(n.profile?.dynamic||[]),P;if(n.searchResults){let l=n.searchResults.results.map(c=>({id:c.id,memory:c.content||c.context||"",similarity:c.similarity,title:c.title,updatedAt:c.updatedAt}));P={results:o(l,c=>c.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:i},searchResults:P}}};br.exports={SupermemoryClient:Rt,PERSONAL_ENTITY_CONTEXT:fo,REPO_ENTITY_CONTEXT:co}});var gt=u((Ya,jr)=>{var{execSync:ge}=require("node:child_process"),$=require("node:path");function uo(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=ge("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=$.resolve(e,r);return $.basename(n)===".git"&&!n.includes(`${$.sep}.git${$.sep}`)?$.dirname(n):ge("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}jr.exports={getGitRoot:uo}});var Ze=u((Sa,hr)=>{var ee=require("node:fs"),we=require("node:path"),{getGitRoot:Xr}=gt(),Or=we.join(".claude",".supermemory-claude"),yr="config.json";function qr(e){let r=Xr(e)||e;return we.join(r,Or,yr)}function Hr(e){try{let t=qr(e);if(ee.existsSync(t))return JSON.parse(ee.readFileSync(t,"utf-8"))}catch{}return null}function vo(e,t){let n=Xr(e)||e,s=we.join(n,Or),o=we.join(s,yr);ee.existsSync(s)||ee.mkdirSync(s,{recursive:!0});let i={...Hr(e)||{},...t};return ee.writeFileSync(o,JSON.stringify(i,null,2)),o}hr.exports={getConfigPath:qr,loadProjectConfig:Hr,saveProjectConfig:vo}});var Lr=u((Ga,Nr)=>{var{execSync:lo}=require("node:child_process"),po=require("node:crypto"),{loadProjectConfig:Wr}=Ze(),{getGitRoot:Fe}=gt();function Tr(e){return po.createHash("sha256").update(e).digest("hex").slice(0,16)}var Me=new Map;function wt(e){if(Me.has(e))return Me.get(e);try{let r=lo("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/),n=r?r[1]:null;return Me.set(e,n),n}catch{return Me.set(e,null),null}}function Po(e){let t=Wr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Fe(e)||e;return`claudecode_project_${Tr(n)}`}function zo(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function mo(e){let t=Wr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Fe(e)||e,o=wt(n)||n.split("/").pop()||"unknown";return`repo_${zo(o)}`}function bo(e){let r=Fe(e)||e;return wt(r)||r.split("/").pop()||"unknown"}Nr.exports={sha256:Tr,getGitRoot:Fe,getGitRepoName:wt,getContainerTag:Po,getRepoContainerTag:mo,getProjectName:bo}});var Rr=u((Ka,Vr)=>{var{execFile:xo}=require("node:child_process");function De(e,t){return new Promise((r,n)=>{xo(e,t,{windowsHide:!0},s=>{s?n(s):r()})})}async function jo(e){let t=e.toString();if(!/^https?:\/\//i.test(t))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await De("rundll32.exe",["url.dll,FileProtocolHandler",t]);return}catch{}await De("cmd.exe",["/c","start",'""',t]);return}if(process.platform==="darwin"){await De("open",[t]);return}await De("xdg-open",[t])}Vr.exports={openUrl:jo}});var gr=u((ka,Xo)=>{Xo.exports=`\r +\r +Connected - Supermemory\r +\r +\r +
\r +
Connected . . .
\r +\r +
\r + \r + +\r + \r +
\r +

Supercharge your Claude Code with Supermemory.

\r +
\r +\r +\r +`});var wr=u((Ea,Oo)=>{Oo.exports=`\r +\r +Error - Supermemory\r +\r +
Error . . .
\r +

Connection Failed

\r +

Invalid API key received. Please try again.

\r +\r +`});var Ur=u((Ca,Dr)=>{var yo=require("node:http"),g=require("node:fs"),Zr=require("node:path"),qo=require("node:os"),{openUrl:Ho}=Rr(),ho=gr(),Wo=wr(),Mt=Zr.join(qo.homedir(),".supermemory-claude"),D=Zr.join(Mt,"credentials.json"),Mr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",Zt=19876,To=25e3;function No(){g.existsSync(Mt)||g.mkdirSync(Mt,{recursive:!0})}function Lo(){try{if(g.existsSync(D)){let e=JSON.parse(g.readFileSync(D,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Fr(e){No();let t={apiKey:e,savedAt:new Date().toISOString()};g.writeFileSync(D,JSON.stringify(t,null,2))}function Vo(){try{g.existsSync(D)&&g.unlinkSync(D)}catch{}}function Ro(){return new Promise((e,t)=>{let r=!1,n=yo.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${Zt}`);if(a.pathname==="/callback"){let i=a.searchParams.get("apikey")||a.searchParams.get("api_key");i?.startsWith("sm_")?(Fr(i),o.writeHead(200,{"Content-Type":"text/html"}),o.end(ho),r=!0,n.close(),e(i)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(Wo))}else o.writeHead(404),o.end("Not found")});n.listen(Zt,"127.0.0.1",()=>{let s=`http://localhost:${Zt}/callback`,o=`${Mr}?callback=${encodeURIComponent(s)}&client=claude_code`;Ho(o).catch(a=>{r||(n.close(),t(new Error(`Failed to open browser: ${a.message}`)))})}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},To)})}Dr.exports={AUTH_BASE_URL:Mr,CREDENTIALS_FILE:D,loadCredentials:Lo,saveCredentials:Fr,clearCredentials:Vo,startAuthFlow:Ro}});var Gr=u((Ia,Sr)=>{var re=require("node:fs"),Yr=require("node:path"),go=require("node:os"),{loadCredentials:wo}=Ur(),{loadProjectConfig:ne}=Ze(),{BASE_URL:Zo}=Vt(),Ue=Yr.join(go.homedir(),".supermemory-claude"),te=Yr.join(Ue,"settings.json"),Ye={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Mo(){re.existsSync(Ue)||re.mkdirSync(Ue,{recursive:!0})}function Se(){let e={...Ye};try{if(re.existsSync(te)){let t=re.readFileSync(te,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${te}: ${t.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function Fo(e){Mo();let t={...e};delete t.apiKey,re.writeFileSync(te,JSON.stringify(t,null,2))}function Do(e,t,r){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||ne(t||process.cwd()),r?.apiKey)return r.apiKey;let n=wo();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function Uo(e){if(typeof e!="string"||!e.trim())return null;let t=e.trim();try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t}catch{return null}}function Yo(e,t){t=t||ne(e||process.cwd());let r=process.env.SUPERMEMORY_API_URL||t?.baseUrl||Zo,n=Uo(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function So(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function Go(e){let t=Se(),r=ne(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Ko(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function ko(e){let t=Se(),r=ne(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Ye.signalKeywords,i=r?.signalKeywords||[],P=[...new Set([...a,...i])].map(c=>c.toLowerCase()),l=r?.signalTurnsBefore||t.signalTurnsBefore||Ye.signalTurnsBefore;return{enabled:o,keywords:P,turnsBefore:l}}function Eo(e){let t=Se();return{directive:ne(e||process.cwd())?.recallDirective||t.recallDirective||null}}Sr.exports={SETTINGS_DIR:Ue,SETTINGS_FILE:te,DEFAULT_SETTINGS:Ye,loadSettings:Se,saveSettings:Fo,getApiKey:Do,getBaseUrl:Yo,debugLog:So,getIncludeTools:Go,shouldIncludeTool:Ko,getSignalConfig:ko,getRecallConfig:Eo}});var Cr=u((Ja,Er)=>{var Kr="The following is recalled context. Reference it only when relevant to the conversation.",kr="Use these memories naturally when relevant \u2014 including indirect connections \u2014 but don't force them into every response or make assumptions beyond what's stated.";function Ft(e){try{let t=new Date(e),r=new Date,n=(r.getTime()-t.getTime())/1e3,s=n/60,o=n/3600,a=n/86400;if(s<30)return"just now";if(s<60)return`${Math.floor(s)}mins ago`;if(o<24)return`${Math.floor(o)}hrs ago`;if(a<7)return`${Math.floor(a)}d ago`;let i=t.toLocaleString("en",{month:"short"});return t.getFullYear()===r.getFullYear()?`${t.getDate()} ${i}`:`${t.getDate()} ${i}, ${t.getFullYear()}`}catch{return""}}function Co(e,t=!0,r=!1,n=10,s=!0){if(!e)return null;let o=t?(e.profile?.static||[]).slice(0,n):[],a=t?(e.profile?.dynamic||[]).slice(0,n):[],i=r?(e.searchResults?.results||[]).slice(0,n):[];if(o.length===0&&a.length===0&&i.length===0)return null;let P=[];if(o.length>0){let c=o.map(d=>`- ${d}`).join(` `);P.push(`## User Profile (Persistent) ${c}`)}if(a.length>0){let c=a.map(d=>`- ${d}`).join(` `);P.push(`## Recent Context -${c}`)}if(i.length>0){let c=i.map(d=>{let b=d.memory??"",f=d.updatedAt?Mt(d.updatedAt):"",O=d.similarity!=null?`[${Math.round(d.similarity*100)}%]`:"";return`- ${f?`[${f}] `:""}${b} ${O}`.trim()});P.push(`## Relevant Memories (with relevance %) +${c}`)}if(i.length>0){let c=i.map(d=>{let b=d.memory??"",f=d.updatedAt?Ft(d.updatedAt):"",O=d.similarity!=null?`[${Math.round(d.similarity*100)}%]`:"";return`- ${f?`[${f}] `:""}${b} ${O}`.trim()});P.push(`## Relevant Memories (with relevance %) ${c.join(` `)}`)}let l=P.join(` `);return s?` -${Gr} +${Kr} ${l} -${Kr} -`:l}function Co(t){let e=t.filter(n=>n.content);if(e.length===0)return null;let r=e.map(n=>n.label?`${n.label} +${kr} +`:l}function Io(e){let t=e.filter(n=>n.content);if(t.length===0)return null;let r=t.map(n=>n.label?`${n.label} ${n.content}`:n.content);return` -${Gr} +${Kr} ${r.join(` @@ -124,8 +124,8 @@ ${r.join(` `)} -${Kr} -`}function Io(t,e,r){let n=r?`${r} memories for "${t}"`:`Memories for "${t}"`;if(!e||e.length===0)return`No ${r?`${r.toLowerCase()} `:""}memories found for "${t}"`;let s=e.map(o=>{let a=o.memory??"",i=o.updatedAt?Mt(o.updatedAt):"",P=o.similarity!=null?`[${Math.round(o.similarity*100)}%]`:"";return`${i?`[${i}] `:""}${a} ${P}`.trim()});return`${n} +${kr} +`}function Jo(e,t,r){let n=r?`${r} memories for "${e}"`:`Memories for "${e}"`;if(!t||t.length===0)return`No ${r?`${r.toLowerCase()} `:""}memories found for "${e}"`;let s=t.map(o=>{let a=o.memory??"",i=o.updatedAt?Ft(o.updatedAt):"",P=o.similarity!=null?`[${Math.round(o.similarity*100)}%]`:"";return`${i?`[${i}] `:""}${a} ${P}`.trim()});return`${n} ${s.join(` -`)}`}kr.exports={formatContext:Eo,combineContexts:Co,formatRelativeTime:Mt,formatSearchResults:Io}});var Ir=u((Ja,Cr)=>{function Jo(t){let e=t?.status;return e===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":e===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":e===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":e===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof e=="number"&&e>=500?"Supermemory service is temporarily unavailable. Will retry next session.":t?.message||"Unknown error"}function Bo(t){let e=t?.status;return e===429||typeof e=="number"&&e>=500||e==null}function Ao(t){let e=t?.status;return e===404||e==null}Cr.exports={getUserFriendlyError:Jo,isRetryableError:Bo,isBenignError:Ao}});var{SupermemoryClient:Qo}=br(),{getProjectName:_o,getContainerTag:$o,getRepoContainerTag:ea}=Nr(),{loadProjectConfig:ta}=Ze(),{loadSettings:ra,getApiKey:na,getBaseUrl:sa}=Sr(),{formatSearchResults:Ft}=Er(),{getUserFriendlyError:oa}=Ir();function aa(t){let e="both",r=[];for(let n of t)n==="--user"?e="user":n==="--repo"?e="repo":n==="--both"?e="both":r.push(n);return{containerType:e,query:r.join(" ")}}async function ia(){let{containerType:t,query:e}=aa(process.argv.slice(2));if(!e||!e.trim()){console.log("No search query provided. Please specify what you want to search for.");return}let r=ra(),n=process.cwd(),s=ta(n),o;try{o=na(r,n,s)}catch{console.log("Supermemory API key not configured."),console.log("Set SUPERMEMORY_CC_API_KEY environment variable to enable memory search."),console.log("Get your key at: https://app.supermemory.ai");return}let a=_o(n),i=$o(n),P=ea(n);try{let l=sa(n,s),c=new Qo(o,i,{baseUrl:l});if(console.log(`Project: ${a} -`),t==="both"){let[d,b]=await Promise.all([c.search(e,i,{limit:5}),c.search(e,P,{limit:5})]);d.results?.length>0&&console.log(Ft(e,d.results,"Personal")),b.results?.length>0&&(d.results?.length>0&&console.log(""),console.log(Ft(e,b.results,"Project"))),!d.results?.length&&!b.results?.length&&console.log(`No memories found for "${e}"`)}else{let d=t==="user"?i:P,b=t==="user"?"Personal":"Project",f=await c.search(e,d,{limit:10});console.log(Ft(e,f.results,b))}}catch(l){console.log(`Error searching memories: ${oa(l)}`)}}ia().catch(t=>{console.error(`Fatal error: ${t.message}`),process.exit(1)}); +`)}`}Er.exports={formatContext:Co,combineContexts:Io,formatRelativeTime:Ft,formatSearchResults:Jo}});var Jr=u((Ba,Ir)=>{function Bo(e){let t=e?.status;return t===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":t===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":t===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":t===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof t=="number"&&t>=500?"Supermemory service is temporarily unavailable. Will retry next session.":e?.message||"Unknown error"}function Ao(e){let t=e?.status;return t===429||typeof t=="number"&&t>=500||t==null}function Qo(e){let t=e?.status;return t===404||t==null}Ir.exports={getUserFriendlyError:Bo,isRetryableError:Ao,isBenignError:Qo}});var{SupermemoryClient:_o}=xr(),{getProjectName:$o,getContainerTag:ea,getRepoContainerTag:ta}=Lr(),{loadProjectConfig:ra}=Ze(),{loadSettings:na,getApiKey:sa,getBaseUrl:oa}=Gr(),{formatSearchResults:Dt}=Cr(),{getUserFriendlyError:aa}=Jr();function ia(e){let t="both",r=[];for(let n of e)n==="--user"?t="user":n==="--repo"?t="repo":n==="--both"?t="both":r.push(n);return{containerType:t,query:r.join(" ")}}async function fa(){let{containerType:e,query:t}=ia(process.argv.slice(2));if(!t||!t.trim()){console.log("No search query provided. Please specify what you want to search for.");return}let r=na(),n=process.cwd(),s=ra(n),o;try{o=sa(r,n,s)}catch{console.log("Supermemory API key not configured."),console.log("Set SUPERMEMORY_CC_API_KEY environment variable to enable memory search."),console.log("Get your key at: https://app.supermemory.ai");return}let a=$o(n),i=ea(n),P=ta(n);try{let l=oa(n,s),c=new _o(o,i,{baseUrl:l});if(console.log(`Project: ${a} +`),e==="both"){let[d,b]=await Promise.all([c.search(t,i,{limit:5}),c.search(t,P,{limit:5})]);d.results?.length>0&&console.log(Dt(t,d.results,"Personal")),b.results?.length>0&&(d.results?.length>0&&console.log(""),console.log(Dt(t,b.results,"Project"))),!d.results?.length&&!b.results?.length&&console.log(`No memories found for "${t}"`)}else{let d=e==="user"?i:P,b=e==="user"?"Personal":"Project",f=await c.search(t,d,{limit:10});console.log(Dt(t,f.results,b))}}catch(l){console.log(`Error searching memories: ${aa(l)}`)}}fa().catch(e=>{console.error(`Fatal error: ${e.message}`),process.exit(1)}); diff --git a/plugin/scripts/status.cjs b/plugin/scripts/status.cjs index 26d9311..3350b12 100755 --- a/plugin/scripts/status.cjs +++ b/plugin/scripts/status.cjs @@ -1,58 +1,58 @@ #!/usr/bin/env node -var P=(e,f)=>()=>(f||e((f={exports:{}}).exports,f),f.exports);var h=P((Ae,R)=>{var{execFile:ce}=require("node:child_process");function H(e,f){return new Promise((n,v)=>{ce(e,f,{windowsHide:!0},r=>{r?v(r):n()})})}async function Pe(e){let f=e.toString();if(!/^https?:\/\//i.test(f))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await H("rundll32.exe",["url.dll,FileProtocolHandler",f]);return}catch{}await H("cmd.exe",["/c","start",'""',f]);return}if(process.platform==="darwin"){await H("open",[f]);return}await H("xdg-open",[f])}R.exports={openUrl:Pe}});var M=P((_e,de)=>{de.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var Y=P(($e,ae)=>{ae.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var y=P((e3,F)=>{var ue=require("node:http"),d=require("node:fs"),D=require("node:path"),xe=require("node:os"),{openUrl:Xe}=h(),je=M(),se=Y(),V=D.join(xe.homedir(),".supermemory-claude"),a=D.join(V,"credentials.json"),U=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",T=19876,Oe=25e3;function He(){d.existsSync(V)||d.mkdirSync(V,{recursive:!0})}function oe(){try{if(d.existsSync(a)){let e=JSON.parse(d.readFileSync(a,"utf-8"));if(e.apiKey)return e}}catch{}return null}function G(e){He();let f={apiKey:e,savedAt:new Date().toISOString()};d.writeFileSync(a,JSON.stringify(f,null,2))}function qe(){try{d.existsSync(a)&&d.unlinkSync(a)}catch{}}function be(){return new Promise((e,f)=>{let n=!1,v=ue.createServer((r,t)=>{let z=new URL(r.url,`http://localhost:${T}`);if(z.pathname==="/callback"){let c=z.searchParams.get("apikey")||z.searchParams.get("api_key");c?.startsWith("sm_")?(G(c),t.writeHead(200,{"Content-Type":"text/html"}),t.end(je),n=!0,v.close(),e(c)):(t.writeHead(400,{"Content-Type":"text/html"}),t.end(se))}else t.writeHead(404),t.end("Not found")});v.listen(T,"127.0.0.1",()=>{let r=`http://localhost:${T}/callback`,t=`${U}?callback=${encodeURIComponent(r)}&client=claude_code`;Xe(t).catch(z=>{n||(v.close(),f(new Error(`Failed to open browser: ${z.message}`)))})}),v.on("error",r=>{n||f(new Error(`Failed to start auth server: ${r.message}`))}),setTimeout(()=>{n||(v.close(),f(new Error("AUTH_TIMEOUT")))},Oe)})}F.exports={AUTH_BASE_URL:U,CREDENTIALS_FILE:a,loadCredentials:oe,saveCredentials:G,clearCredentials:qe,startAuthFlow:be}});var N=P((f3,w)=>{var{execSync:o}=require("node:child_process"),u=require("node:path");function le(e){let f=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(f)return o("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=o("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n===".git")return o("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let v=u.resolve(e,n);return u.basename(v)===".git"&&!v.includes(`${u.sep}.git${u.sep}`)?u.dirname(v):o("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}w.exports={getGitRoot:le}});var b=P((n3,E)=>{var x=require("node:fs"),q=require("node:path"),{getGitRoot:K}=N(),g=q.join(".claude",".supermemory-claude"),S="config.json";function k(e){let n=K(e)||e;return q.join(n,g,S)}function J(e){try{let f=k(e);if(x.existsSync(f))return JSON.parse(x.readFileSync(f,"utf-8"))}catch{}return null}function pe(e,f){let v=K(e)||e,r=q.join(v,g),t=q.join(r,S);x.existsSync(r)||x.mkdirSync(r,{recursive:!0});let c={...J(e)||{},...f};return x.writeFileSync(t,JSON.stringify(c,null,2)),t}E.exports={getConfigPath:k,loadProjectConfig:J,saveProjectConfig:pe}});var B=P((v3,C)=>{var We="https://api.supermemory.ai";C.exports={BASE_URL:We}});var A=P((r3,Q)=>{var j=require("node:fs"),I=require("node:path"),ie=require("node:os"),{loadCredentials:me}=y(),{loadProjectConfig:s}=b(),{BASE_URL:Te}=B(),l=I.join(ie.homedir(),".supermemory-claude"),X=I.join(l,"settings.json"),p={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Ve(){j.existsSync(l)||j.mkdirSync(l,{recursive:!0})}function W(){let e={...p};try{if(j.existsSync(X)){let f=j.readFileSync(X,"utf-8");Object.assign(e,JSON.parse(f))}}catch(f){console.error(`Settings: Failed to load ${X}: ${f.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function ye(e){Ve();let f={...e};delete f.apiKey,j.writeFileSync(X,JSON.stringify(f,null,2))}function Ne(e,f,n){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(n=n||s(f||process.cwd()),n?.apiKey)return n.apiKey;let v=me();if(v?.apiKey)return v.apiKey;throw new Error("NO_API_KEY")}function Le(e){if(typeof e!="string"||!e.trim())return null;let f=e.trim();try{let n=new URL(f);return n.protocol!=="http:"&&n.protocol!=="https:"?null:f}catch{return null}}function Ze(e,f){f=f||s(e||process.cwd());let n=process.env.SUPERMEMORY_API_URL||f?.baseUrl||Te,v=Le(n);if(!v)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return v}function Re(e,f,n){if(e.debug){let v=new Date().toISOString();console.error(n?`[${v}] ${f}: ${JSON.stringify(n)}`:`[${v}] ${f}`)}}function he(e){let f=W(),n=s(e||process.cwd()),v=f.includeTools||[],r=n?.includeTools||[];return[...new Set([...v,...r])].map(z=>z.toLowerCase())}function Me(e,f){return f.length===0?!1:f.includes(e.toLowerCase())}function Ye(e){let f=W(),n=s(e||process.cwd()),v=f.signalExtraction||!1,r=n?.signalExtraction,t=r!==void 0?r:v,z=f.signalKeywords||p.signalKeywords,c=n?.signalKeywords||[],O=[...new Set([...z,...c])].map(ze=>ze.toLowerCase()),te=n?.signalTurnsBefore||f.signalTurnsBefore||p.signalTurnsBefore;return{enabled:t,keywords:O,turnsBefore:te}}function De(e){let f=W();return{directive:s(e||process.cwd())?.recallDirective||f.recallDirective||null}}Q.exports={SETTINGS_DIR:l,SETTINGS_FILE:X,DEFAULT_SETTINGS:p,loadSettings:W,saveSettings:ye,getApiKey:Ne,getBaseUrl:Ze,debugLog:Re,getIncludeTools:he,shouldIncludeTool:Me,getSignalConfig:Ye,getRecallConfig:De}});var fe=P((t3,ee)=>{var{execSync:Ue}=require("node:child_process"),Ge=require("node:crypto"),{loadProjectConfig:_}=b(),{getGitRoot:i}=N();function $(e){return Ge.createHash("sha256").update(e).digest("hex").slice(0,16)}function L(e){try{let n=Ue("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/);return n?n[1]:null}catch{return null}}function Fe(e){let f=_(e);if(f?.personalContainerTag)return f.personalContainerTag;let v=i(e)||e;return`claudecode_project_${$(v)}`}function we(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function Ke(e){let f=_(e);if(f?.repoContainerTag)return f.repoContainerTag;let v=i(e)||e,t=L(v)||v.split("/").pop()||"unknown";return`repo_${we(t)}`}function ge(e){let n=i(e)||e;return L(n)||n.split("/").pop()||"unknown"}ee.exports={sha256:$,getGitRoot:i,getGitRepoName:L,getContainerTag:Fe,getRepoContainerTag:Ke,getProjectName:ge}});var ne=require("node:fs"),Se=require("node:os"),{CREDENTIALS_FILE:ve}=y(),{SETTINGS_FILE:re}=A(),{getProjectName:ke}=fe(),{getConfigPath:Je}=b();function Z(e){try{return ne.existsSync(e)?{exists:!0,data:JSON.parse(ne.readFileSync(e,"utf-8")),error:null}:{exists:!1,data:null,error:null}}catch(f){return{exists:!0,data:null,error:f instanceof Error?f.message:String(f)}}}function m(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ee(e){return e?e.length<=12?`${e.slice(0,3)}... masked`:`${e.slice(0,6)}...${e.slice(-4)} masked`:"not set"}function Ce(e){if(!e)return"not found";let f=Se.homedir();return e.startsWith(`${f}/`)?`~/${e.slice(f.length+1)}`:e}function Be(e){let f=Z(re),n=Je(e),v=Z(n),r=Z(ve),t=m(process.env.SUPERMEMORY_CC_API_KEY);if(t)return{apiKey:t,source:"SUPERMEMORY_CC_API_KEY environment variable"};let z=m(f.data?.apiKey);if(z)return{apiKey:z,source:re};let c=m(v.data?.apiKey);if(c)return{apiKey:c,source:n};let O=m(r.data?.apiKey);return{apiKey:O,source:O?ve:null}}function Ie(){let e=process.cwd(),f=ke(e),n=Be(e),v=n.apiKey?.startsWith("sm_")?"connected":"not authenticated";console.log(`Supermemory is ${v}.`),console.log(""),console.log("Status:"),console.log(`- Project: ${f}`),console.log(`- API key source: ${Ce(n.source)}`),console.log(`- API key: ${Ee(n.apiKey)}`)}Ie(); +var P=(e,f)=>()=>(f||e((f={exports:{}}).exports,f),f.exports);var M=P((_e,h)=>{var{execFile:Pe}=require("node:child_process");function H(e,f){return new Promise((n,v)=>{Pe(e,f,{windowsHide:!0},r=>{r?v(r):n()})})}async function ae(e){let f=e.toString();if(!/^https?:\/\//i.test(f))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await H("rundll32.exe",["url.dll,FileProtocolHandler",f]);return}catch{}await H("cmd.exe",["/c","start",'""',f]);return}if(process.platform==="darwin"){await H("open",[f]);return}await H("xdg-open",[f])}h.exports={openUrl:ae}});var Y=P(($e,de)=>{de.exports=`\r +\r +Connected - Supermemory\r +\r +\r +
\r +
Connected . . .
\r +\r +
\r + \r + +\r + \r +
\r +

Supercharge your Claude Code with Supermemory.

\r +
\r +\r +\r +`});var D=P((e3,ue)=>{ue.exports=`\r +\r +Error - Supermemory\r +\r +
Error . . .
\r +

Connection Failed

\r +

Invalid API key received. Please try again.

\r +\r +`});var N=P((f3,w)=>{var xe=require("node:http"),a=require("node:fs"),U=require("node:path"),Xe=require("node:os"),{openUrl:je}=M(),se=Y(),Oe=D(),y=U.join(Xe.homedir(),".supermemory-claude"),d=U.join(y,"credentials.json"),G=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",V=19876,He=25e3;function oe(){a.existsSync(y)||a.mkdirSync(y,{recursive:!0})}function qe(){try{if(a.existsSync(d)){let e=JSON.parse(a.readFileSync(d,"utf-8"));if(e.apiKey)return e}}catch{}return null}function F(e){oe();let f={apiKey:e,savedAt:new Date().toISOString()};a.writeFileSync(d,JSON.stringify(f,null,2))}function be(){try{a.existsSync(d)&&a.unlinkSync(d)}catch{}}function le(){return new Promise((e,f)=>{let n=!1,v=xe.createServer((r,t)=>{let z=new URL(r.url,`http://localhost:${V}`);if(z.pathname==="/callback"){let c=z.searchParams.get("apikey")||z.searchParams.get("api_key");c?.startsWith("sm_")?(F(c),t.writeHead(200,{"Content-Type":"text/html"}),t.end(se),n=!0,v.close(),e(c)):(t.writeHead(400,{"Content-Type":"text/html"}),t.end(Oe))}else t.writeHead(404),t.end("Not found")});v.listen(V,"127.0.0.1",()=>{let r=`http://localhost:${V}/callback`,t=`${G}?callback=${encodeURIComponent(r)}&client=claude_code`;je(t).catch(z=>{n||(v.close(),f(new Error(`Failed to open browser: ${z.message}`)))})}),v.on("error",r=>{n||f(new Error(`Failed to start auth server: ${r.message}`))}),setTimeout(()=>{n||(v.close(),f(new Error("AUTH_TIMEOUT")))},He)})}w.exports={AUTH_BASE_URL:G,CREDENTIALS_FILE:d,loadCredentials:qe,saveCredentials:F,clearCredentials:be,startAuthFlow:le}});var L=P((n3,K)=>{var{execSync:o}=require("node:child_process"),u=require("node:path");function pe(e){let f=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(f)return o("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=o("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n===".git")return o("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let v=u.resolve(e,n);return u.basename(v)===".git"&&!v.includes(`${u.sep}.git${u.sep}`)?u.dirname(v):o("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}K.exports={getGitRoot:pe}});var b=P((v3,C)=>{var x=require("node:fs"),q=require("node:path"),{getGitRoot:g}=L(),S=q.join(".claude",".supermemory-claude"),k="config.json";function J(e){let n=g(e)||e;return q.join(n,S,k)}function E(e){try{let f=J(e);if(x.existsSync(f))return JSON.parse(x.readFileSync(f,"utf-8"))}catch{}return null}function We(e,f){let v=g(e)||e,r=q.join(v,S),t=q.join(r,k);x.existsSync(r)||x.mkdirSync(r,{recursive:!0});let c={...E(e)||{},...f};return x.writeFileSync(t,JSON.stringify(c,null,2)),t}C.exports={getConfigPath:J,loadProjectConfig:E,saveProjectConfig:We}});var I=P((r3,B)=>{var ie="https://api.supermemory.ai";B.exports={BASE_URL:ie}});var _=P((t3,A)=>{var j=require("node:fs"),Q=require("node:path"),me=require("node:os"),{loadCredentials:Te}=N(),{loadProjectConfig:s}=b(),{BASE_URL:Ve}=I(),l=Q.join(me.homedir(),".supermemory-claude"),X=Q.join(l,"settings.json"),p={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function ye(){j.existsSync(l)||j.mkdirSync(l,{recursive:!0})}function W(){let e={...p};try{if(j.existsSync(X)){let f=j.readFileSync(X,"utf-8");Object.assign(e,JSON.parse(f))}}catch(f){console.error(`Settings: Failed to load ${X}: ${f.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function Ne(e){ye();let f={...e};delete f.apiKey,j.writeFileSync(X,JSON.stringify(f,null,2))}function Le(e,f,n){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(n=n||s(f||process.cwd()),n?.apiKey)return n.apiKey;let v=Te();if(v?.apiKey)return v.apiKey;throw new Error("NO_API_KEY")}function Ze(e){if(typeof e!="string"||!e.trim())return null;let f=e.trim();try{let n=new URL(f);return n.protocol!=="http:"&&n.protocol!=="https:"?null:f}catch{return null}}function Re(e,f){f=f||s(e||process.cwd());let n=process.env.SUPERMEMORY_API_URL||f?.baseUrl||Ve,v=Ze(n);if(!v)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return v}function he(e,f,n){if(e.debug){let v=new Date().toISOString();console.error(n?`[${v}] ${f}: ${JSON.stringify(n)}`:`[${v}] ${f}`)}}function Me(e){let f=W(),n=s(e||process.cwd()),v=f.includeTools||[],r=n?.includeTools||[];return[...new Set([...v,...r])].map(z=>z.toLowerCase())}function Ye(e,f){return f.length===0?!1:f.includes(e.toLowerCase())}function De(e){let f=W(),n=s(e||process.cwd()),v=f.signalExtraction||!1,r=n?.signalExtraction,t=r!==void 0?r:v,z=f.signalKeywords||p.signalKeywords,c=n?.signalKeywords||[],O=[...new Set([...z,...c])].map(ce=>ce.toLowerCase()),ze=n?.signalTurnsBefore||f.signalTurnsBefore||p.signalTurnsBefore;return{enabled:t,keywords:O,turnsBefore:ze}}function Ue(e){let f=W();return{directive:s(e||process.cwd())?.recallDirective||f.recallDirective||null}}A.exports={SETTINGS_DIR:l,SETTINGS_FILE:X,DEFAULT_SETTINGS:p,loadSettings:W,saveSettings:Ne,getApiKey:Le,getBaseUrl:Re,debugLog:he,getIncludeTools:Me,shouldIncludeTool:Ye,getSignalConfig:De,getRecallConfig:Ue}});var ne=P((z3,fe)=>{var{execSync:Ge}=require("node:child_process"),Fe=require("node:crypto"),{loadProjectConfig:$}=b(),{getGitRoot:m}=L();function ee(e){return Fe.createHash("sha256").update(e).digest("hex").slice(0,16)}var i=new Map;function Z(e){if(i.has(e))return i.get(e);try{let n=Ge("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/),v=n?n[1]:null;return i.set(e,v),v}catch{return i.set(e,null),null}}function we(e){let f=$(e);if(f?.personalContainerTag)return f.personalContainerTag;let v=m(e)||e;return`claudecode_project_${ee(v)}`}function Ke(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function ge(e){let f=$(e);if(f?.repoContainerTag)return f.repoContainerTag;let v=m(e)||e,t=Z(v)||v.split("/").pop()||"unknown";return`repo_${Ke(t)}`}function Se(e){let n=m(e)||e;return Z(n)||n.split("/").pop()||"unknown"}fe.exports={sha256:ee,getGitRoot:m,getGitRepoName:Z,getContainerTag:we,getRepoContainerTag:ge,getProjectName:Se}});var ve=require("node:fs"),ke=require("node:os"),{CREDENTIALS_FILE:re}=N(),{SETTINGS_FILE:te}=_(),{getProjectName:Je}=ne(),{getConfigPath:Ee}=b();function R(e){try{return ve.existsSync(e)?{exists:!0,data:JSON.parse(ve.readFileSync(e,"utf-8")),error:null}:{exists:!1,data:null,error:null}}catch(f){return{exists:!0,data:null,error:f instanceof Error?f.message:String(f)}}}function T(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ce(e){return e?e.length<=12?`${e.slice(0,3)}... masked`:`${e.slice(0,6)}...${e.slice(-4)} masked`:"not set"}function Be(e){if(!e)return"not found";let f=ke.homedir();return e.startsWith(`${f}/`)?`~/${e.slice(f.length+1)}`:e}function Ie(e){let f=R(te),n=Ee(e),v=R(n),r=R(re),t=T(process.env.SUPERMEMORY_CC_API_KEY);if(t)return{apiKey:t,source:"SUPERMEMORY_CC_API_KEY environment variable"};let z=T(f.data?.apiKey);if(z)return{apiKey:z,source:te};let c=T(v.data?.apiKey);if(c)return{apiKey:c,source:n};let O=T(r.data?.apiKey);return{apiKey:O,source:O?re:null}}function Qe(){let e=process.cwd(),f=Je(e),n=Ie(e),v=n.apiKey?.startsWith("sm_")?"connected":"not authenticated";console.log(`Supermemory is ${v}.`),console.log(""),console.log("Status:"),console.log(`- Project: ${f}`),console.log(`- API key source: ${Be(n.source)}`),console.log(`- API key: ${Ce(n.apiKey)}`)}Qe(); diff --git a/plugin/scripts/summary-hook.cjs b/plugin/scripts/summary-hook.cjs index 6abb0e8..1596d1a 100755 --- a/plugin/scripts/summary-hook.cjs +++ b/plugin/scripts/summary-hook.cjs @@ -1,9 +1,9 @@ #!/usr/bin/env node -var $e=Object.defineProperty;var Xn=Object.getOwnPropertyDescriptor;var On=Object.getOwnPropertyNames;var yn=Object.prototype.hasOwnProperty;var qn=(e,t)=>()=>(e&&(t=e(e=0)),t);var u=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),hn=(e,t)=>{for(var r in t)$e(e,r,{get:t[r],enumerable:!0})},Hn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of On(t))!yn.call(e,s)&&s!==r&&$e(e,s,{get:()=>t[s],enumerable:!(n=Xn(t,s))||n.enumerable});return e};var Wn=e=>Hn($e({},"__esModule",{value:!0}),e);var rt=u(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.__setModuleDefault=N.__createBinding=void 0;N.__classPrivateFieldSet=Tn;N.__classPrivateFieldGet=Nn;N.__importStar=Ln;N.__exportStar=Vn;function Tn(e,t,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(e,r):s?s.value=r:t.set(e,r),r}function Nn(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var tt=Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]};N.__createBinding=tt;var or=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};N.__setModuleDefault=or;var et=function(e){return et=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},et(e)};function Ln(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=et(e),n=0;n{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.uuid4=void 0;var Rn=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return K.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};K.uuid4=Rn});var nt=u(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.castToError=void 0;I.isAbortError=gn;function gn(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var wn=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};I.castToError=wn});var J=u(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.InternalServerError=z.RateLimitError=z.UnprocessableEntityError=z.ConflictError=z.NotFoundError=z.PermissionDeniedError=z.AuthenticationError=z.BadRequestError=z.APIConnectionTimeoutError=z.APIConnectionError=z.APIUserAbortError=z.APIError=z.SupermemoryError=void 0;var Zn=nt(),ve=class extends Error{};z.SupermemoryError=ve;var y=class e extends ve{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(t,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new C({message:n,cause:(0,Zn.castToError)(r)});let o=r;return t===400?new le(t,o,n,s):t===401?new pe(t,o,n,s):t===403?new Pe(t,o,n,s):t===404?new ze(t,o,n,s):t===409?new me(t,o,n,s):t===422?new xe(t,o,n,s):t===429?new be(t,o,n,s):t>=500?new je(t,o,n,s):new e(t,o,n,s)}};z.APIError=y;var st=class extends y{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};z.APIUserAbortError=st;var C=class extends y{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};z.APIConnectionError=C;var ot=class extends C{constructor({message:t}={}){super({message:t??"Request timed out."})}};z.APIConnectionTimeoutError=ot;var le=class extends y{};z.BadRequestError=le;var pe=class extends y{};z.AuthenticationError=pe;var Pe=class extends y{};z.PermissionDeniedError=Pe;var ze=class extends y{};z.NotFoundError=ze;var me=class extends y{};z.ConflictError=me;var xe=class extends y{};z.UnprocessableEntityError=xe;var be=class extends y{};z.RateLimitError=be;var je=class extends y{};z.InternalServerError=je});var A=u(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});l.safeJSON=l.maybeCoerceBoolean=l.maybeCoerceFloat=l.maybeCoerceInteger=l.coerceBoolean=l.coerceFloat=l.coerceInteger=l.validatePositiveInteger=l.ensurePresent=l.isReadonlyArray=l.isArray=l.isAbsoluteURL=void 0;l.maybeObj=Un;l.isEmptyObj=Sn;l.hasOwn=Yn;l.isObj=Gn;var B=J(),Mn=/^[a-z][a-z0-9+.-]*:/i,Fn=e=>Mn.test(e);l.isAbsoluteURL=Fn;var Dn=e=>(l.isArray=Array.isArray,(0,l.isArray)(e));l.isArray=Dn;l.isReadonlyArray=l.isArray;function Un(e){return typeof e!="object"?{}:e??{}}function Sn(e){if(!e)return!0;for(let t in e)return!1;return!0}function Yn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Gn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var kn=e=>{if(e==null)throw new B.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};l.ensurePresent=kn;var En=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new B.SupermemoryError(`${e} must be an integer`);if(t<0)throw new B.SupermemoryError(`${e} must be a positive integer`);return t};l.validatePositiveInteger=En;var Kn=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new B.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};l.coerceInteger=Kn;var In=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new B.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};l.coerceFloat=In;var Cn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;l.coerceBoolean=Cn;var Jn=e=>{if(e!=null)return(0,l.coerceInteger)(e)};l.maybeCoerceInteger=Jn;var Bn=e=>{if(e!=null)return(0,l.coerceFloat)(e)};l.maybeCoerceFloat=Bn;var An=e=>{if(e!=null)return(0,l.coerceBoolean)(e)};l.maybeCoerceBoolean=An;var Qn=e=>{try{return JSON.parse(e)}catch{return}};l.safeJSON=Qn});var ar=u(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.sleep=void 0;var _n=e=>new Promise(t=>setTimeout(t,e));Xe.sleep=_n});var it=u(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.VERSION=void 0;Oe.VERSION="4.0.0"});var dr=u(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.getPlatformHeaders=S.isRunningInBrowser=void 0;var Q=it(),$n=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";S.isRunningInBrowser=$n;function es(){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 ts=()=>{let e=es();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":cr(Deno.build.os),"X-Stainless-Arch":fr(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":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":cr(globalThis.process.platform??"unknown"),"X-Stainless-Arch":fr(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=rs();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function rs(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:t,version:`${s}.${o}.${i}`}}}return null}var fr=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",cr=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),ur,ns=()=>ur??(ur=ts());S.getPlatformHeaders=ns});var at=u(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.getDefaultFetch=ss;w.makeReadableStream=vr;w.ReadableStreamFrom=os;w.ReadableStreamToAsyncIterable=is;w.CancelReadableStream=as;function ss(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function vr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function os(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return vr({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function is(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function as(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var lr=u(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.FallbackEncoder=void 0;var fs=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});ye.FallbackEncoder=fs});var _=u(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=ft;j.getName=qe;var cs=at(),us=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};j.checkFileSupport=us;function ft(e,t,r){return(0,j.checkFileSupport)(),new File(e,t??"unknown_file",r)}function qe(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var ds=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";j.isAsyncIterable=ds;var vs=async(e,t)=>ct(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=vs;var ls=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=ls;var pr=new WeakMap;function ps(e){let t=typeof e=="function"?e:e.fetch,r=pr.get(t);if(r)return r;let n=(async()=>{try{let s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return pr.set(t,n),n}var Ps=async(e,t)=>{if(!await ps(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,s])=>ut(r,n,s))),r};j.createForm=Ps;var Pr=e=>e instanceof Blob&&"name"in e,zs=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||Pr(e)),ct=e=>{if(zs(e))return!0;if(Array.isArray(e))return e.some(ct);if(e&&typeof e=="object"){for(let t in e)if(ct(e[t]))return!0}return!1},ut=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,ft([await r.blob()],qe(r)));else if((0,j.isAsyncIterable)(r))e.append(t,ft([await new Response((0,cs.ReadableStreamFrom)(r)).blob()],qe(r)));else if(Pr(r))e.append(t,r,qe(r));else if(Array.isArray(r))await Promise.all(r.map(n=>ut(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>ut(e,`${t}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var mr=u(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.toFile=js;var $=_(),ms=_(),zr=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",xs=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&zr(e),bs=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function js(e,t,r){if((0,ms.checkFileSupport)(),e=await e,xs(e))return e instanceof File?e:(0,$.makeFile)([await e.arrayBuffer()],e.name);if(bs(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,$.makeFile)(await dt(s),t,r)}let n=await dt(e);if(t||(t=(0,$.getName)(e)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,$.makeFile)(n,t,r)}async function dt(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(zr(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,$.isAsyncIterable)(e))for await(let r of e)t.push(...await dt(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Xs(e)}`)}return t}function Xs(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var lt=u(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.toFile=void 0;var Os=mr();Object.defineProperty(he,"toFile",{enumerable:!0,get:function(){return Os.toFile}})});var Y=u(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.APIResource=void 0;var pt=class{constructor(t){this._client=t}};He.APIResource=pt});var ee=u(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.isEmptyHeaders=G.buildHeaders=void 0;var xr=A(),br=Symbol("brand.privateNullableHeaders");function*jr(e){if(!e)return;if(br in e){let{values:n,nulls:s}=e;yield*n.entries();for(let o of s)yield[o,null];return}let t=!1,r;e instanceof Headers?r=e.entries():(0,xr.isReadonlyArray)(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,xr.isReadonlyArray)(n[1])?n[1]:[n[1]],i=!1;for(let a of o)a!==void 0&&(t&&!i&&(i=!0,yield[s,null]),yield[s,a])}}var ys=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,i]of jr(n)){let a=o.toLowerCase();s.has(a)||(t.delete(o),s.add(a)),i===null?(t.delete(o),r.add(a)):(t.append(o,i),r.delete(a))}}return{[br]:!0,values:t,nulls:r}};G.buildHeaders=ys;var qs=e=>{for(let t of jr(e))return!1;return!0};G.isEmptyHeaders=qs});var We=u(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.path=V.createPathTagFunction=void 0;V.encodeURIPath=Pt;var hs=J();function Pt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Xr=Object.freeze(Object.create(null)),Hs=(e=Pt)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],i=r.reduce((d,P,m)=>{/[?#]/.test(P)&&(s=!0);let c=n[m],O=(s?encodeURIComponent:e)(""+c);return m!==n.length&&(c==null||typeof c=="object"&&c.toString===Object.getPrototypeOf(Object.getPrototypeOf(c.hasOwnProperty??Xr)??Xr)?.toString)&&(O=c+"",o.push({start:d.length+P.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),d+P+(m===n.length?"":O)},""),a=i.split(/[?#]/,1)[0],p=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,f;for(;(f=p.exec(a))!==null;)o.push({start:f.index,length:f[0].length,error:`Value "${f[0]}" can't be safely passed as a path parameter`});if(o.sort((d,P)=>d.start-P.start),o.length>0){let d=0,P=o.reduce((m,c)=>{let O=" ".repeat(c.start-d),g="^".repeat(c.length);return d=c.start+c.length,m+O+g},"");throw new hs.SupermemoryError(`Path parameters result in path with invalid segments: -${o.map(m=>m.error).join(` +var et=Object.defineProperty;var Xn=Object.getOwnPropertyDescriptor;var yn=Object.getOwnPropertyNames;var hn=Object.prototype.hasOwnProperty;var qn=(e,t)=>()=>(e&&(t=e(e=0)),t);var u=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Hn=(e,t)=>{for(var r in t)et(e,r,{get:t[r],enumerable:!0})},Wn=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yn(t))!hn.call(e,s)&&s!==r&&et(e,s,{get:()=>t[s],enumerable:!(n=Xn(t,s))||n.enumerable});return e};var Tn=e=>Wn(et({},"__esModule",{value:!0}),e);var nt=u(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.__setModuleDefault=N.__createBinding=void 0;N.__classPrivateFieldSet=Nn;N.__classPrivateFieldGet=Ln;N.__importStar=Vn;N.__exportStar=Rn;function Nn(e,t,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?e!==t||!s:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(e,r):s?s.value=r:t.set(e,r),r}function Ln(e,t,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(e):n?n.value:t.get(e)}var rt=Object.create?function(e,t,r,n){n===void 0&&(n=r);var s=Object.getOwnPropertyDescriptor(t,r);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,s)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]};N.__createBinding=rt;var ir=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};N.__setModuleDefault=ir;var tt=function(e){return tt=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},tt(e)};function Vn(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=tt(e),n=0;n{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.uuid4=void 0;var gn=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return K.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};K.uuid4=gn});var st=u(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.castToError=void 0;I.isAbortError=wn;function wn(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var Mn=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};I.castToError=Mn});var J=u(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.InternalServerError=m.RateLimitError=m.UnprocessableEntityError=m.ConflictError=m.NotFoundError=m.PermissionDeniedError=m.AuthenticationError=m.BadRequestError=m.APIConnectionTimeoutError=m.APIConnectionError=m.APIUserAbortError=m.APIError=m.SupermemoryError=void 0;var Zn=st(),ve=class extends Error{};m.SupermemoryError=ve;var y=class e extends ve{constructor(t,r,n,s){super(`${e.makeMessage(t,r,n)}`),this.status=t,this.headers=s,this.error=r}static makeMessage(t,r,n){let s=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,r,n,s){if(!t||!s)return new C({message:n,cause:(0,Zn.castToError)(r)});let o=r;return t===400?new le(t,o,n,s):t===401?new pe(t,o,n,s):t===403?new Pe(t,o,n,s):t===404?new me(t,o,n,s):t===409?new ze(t,o,n,s):t===422?new xe(t,o,n,s):t===429?new be(t,o,n,s):t>=500?new je(t,o,n,s):new e(t,o,n,s)}};m.APIError=y;var ot=class extends y{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};m.APIUserAbortError=ot;var C=class extends y{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};m.APIConnectionError=C;var it=class extends C{constructor({message:t}={}){super({message:t??"Request timed out."})}};m.APIConnectionTimeoutError=it;var le=class extends y{};m.BadRequestError=le;var pe=class extends y{};m.AuthenticationError=pe;var Pe=class extends y{};m.PermissionDeniedError=Pe;var me=class extends y{};m.NotFoundError=me;var ze=class extends y{};m.ConflictError=ze;var xe=class extends y{};m.UnprocessableEntityError=xe;var be=class extends y{};m.RateLimitError=be;var je=class extends y{};m.InternalServerError=je});var A=u(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.safeJSON=p.maybeCoerceBoolean=p.maybeCoerceFloat=p.maybeCoerceInteger=p.coerceBoolean=p.coerceFloat=p.coerceInteger=p.validatePositiveInteger=p.ensurePresent=p.isReadonlyArray=p.isArray=p.isAbsoluteURL=void 0;p.maybeObj=Sn;p.isEmptyObj=Yn;p.hasOwn=Gn;p.isObj=kn;var B=J(),Fn=/^[a-z][a-z0-9+.-]*:/i,Dn=e=>Fn.test(e);p.isAbsoluteURL=Dn;var Un=e=>(p.isArray=Array.isArray,(0,p.isArray)(e));p.isArray=Un;p.isReadonlyArray=p.isArray;function Sn(e){return typeof e!="object"?{}:e??{}}function Yn(e){if(!e)return!0;for(let t in e)return!1;return!0}function Gn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function kn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var En=e=>{if(e==null)throw new B.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};p.ensurePresent=En;var Kn=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new B.SupermemoryError(`${e} must be an integer`);if(t<0)throw new B.SupermemoryError(`${e} must be a positive integer`);return t};p.validatePositiveInteger=Kn;var In=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new B.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};p.coerceInteger=In;var Cn=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new B.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};p.coerceFloat=Cn;var Jn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;p.coerceBoolean=Jn;var Bn=e=>{if(e!=null)return(0,p.coerceInteger)(e)};p.maybeCoerceInteger=Bn;var An=e=>{if(e!=null)return(0,p.coerceFloat)(e)};p.maybeCoerceFloat=An;var Qn=e=>{if(e!=null)return(0,p.coerceBoolean)(e)};p.maybeCoerceBoolean=Qn;var _n=e=>{try{return JSON.parse(e)}catch{return}};p.safeJSON=_n});var fr=u(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.sleep=void 0;var $n=e=>new Promise(t=>setTimeout(t,e));Oe.sleep=$n});var at=u(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.VERSION=void 0;Xe.VERSION="4.0.0"});var vr=u(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.getPlatformHeaders=S.isRunningInBrowser=void 0;var Q=at(),es=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";S.isRunningInBrowser=es;function ts(){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 rs=()=>{let e=ts();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":ur(Deno.build.os),"X-Stainless-Arch":cr(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":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":ur(globalThis.process.platform??"unknown"),"X-Stainless-Arch":cr(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=ns();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Q.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ns(){if(typeof navigator>"u"||!navigator)return null;let e=[{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:t,pattern:r}of e){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:t,version:`${s}.${o}.${i}`}}}return null}var cr=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",ur=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown"),dr,ss=()=>dr??(dr=rs());S.getPlatformHeaders=ss});var ft=u(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.getDefaultFetch=os;w.makeReadableStream=lr;w.ReadableStreamFrom=is;w.ReadableStreamToAsyncIterable=as;w.CancelReadableStream=fs;function os(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Supermemory({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function lr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function is(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return lr({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function as(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();return r?.done&&t.releaseLock(),r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function fs(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var pr=u(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.FallbackEncoder=void 0;var cs=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});ye.FallbackEncoder=cs});var _=u(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=ct;j.getName=he;var us=ft(),ds=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};j.checkFileSupport=ds;function ct(e,t,r){return(0,j.checkFileSupport)(),new File(e,t??"unknown_file",r)}function he(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var vs=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";j.isAsyncIterable=vs;var ls=async(e,t)=>ut(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=ls;var ps=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=ps;var Pr=new WeakMap;function Ps(e){let t=typeof e=="function"?e:e.fetch,r=Pr.get(t);if(r)return r;let n=(async()=>{try{let s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Pr.set(t,n),n}var ms=async(e,t)=>{if(!await Ps(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,s])=>dt(r,n,s))),r};j.createForm=ms;var mr=e=>e instanceof Blob&&"name"in e,zs=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||mr(e)),ut=e=>{if(zs(e))return!0;if(Array.isArray(e))return e.some(ut);if(e&&typeof e=="object"){for(let t in e)if(ut(e[t]))return!0}return!1},dt=async(e,t,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,ct([await r.blob()],he(r)));else if((0,j.isAsyncIterable)(r))e.append(t,ct([await new Response((0,us.ReadableStreamFrom)(r)).blob()],he(r)));else if(mr(r))e.append(t,r,he(r));else if(Array.isArray(r))await Promise.all(r.map(n=>dt(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>dt(e,`${t}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}}});var xr=u(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.toFile=Os;var $=_(),xs=_(),zr=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",bs=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&zr(e),js=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Os(e,t,r){if((0,xs.checkFileSupport)(),e=await e,bs(e))return e instanceof File?e:(0,$.makeFile)([await e.arrayBuffer()],e.name);if(js(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,$.makeFile)(await vt(s),t,r)}let n=await vt(e);if(t||(t=(0,$.getName)(e)),!r?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return(0,$.makeFile)(n,t,r)}async function vt(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(zr(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,$.isAsyncIterable)(e))for await(let r of e)t.push(...await vt(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Xs(e)}`)}return t}function Xs(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var pt=u(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.toFile=void 0;var ys=xr();Object.defineProperty(qe,"toFile",{enumerable:!0,get:function(){return ys.toFile}})});var Y=u(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.APIResource=void 0;var Pt=class{constructor(t){this._client=t}};He.APIResource=Pt});var ee=u(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.isEmptyHeaders=G.buildHeaders=void 0;var br=A(),jr=Symbol("brand.privateNullableHeaders");function*Or(e){if(!e)return;if(jr in e){let{values:n,nulls:s}=e;yield*n.entries();for(let o of s)yield[o,null];return}let t=!1,r;e instanceof Headers?r=e.entries():(0,br.isReadonlyArray)(e)?r=e:(t=!0,r=Object.entries(e??{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=(0,br.isReadonlyArray)(n[1])?n[1]:[n[1]],i=!1;for(let a of o)a!==void 0&&(t&&!i&&(i=!0,yield[s,null]),yield[s,a])}}var hs=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,i]of Or(n)){let a=o.toLowerCase();s.has(a)||(t.delete(o),s.add(a)),i===null?(t.delete(o),r.add(a)):(t.append(o,i),r.delete(a))}}return{[jr]:!0,values:t,nulls:r}};G.buildHeaders=hs;var qs=e=>{for(let t of Or(e))return!1;return!0};G.isEmptyHeaders=qs});var We=u(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.path=V.createPathTagFunction=void 0;V.encodeURIPath=mt;var Hs=J();function mt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Xr=Object.freeze(Object.create(null)),Ws=(e=mt)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],i=r.reduce((d,P,z)=>{/[?#]/.test(P)&&(s=!0);let c=n[z],X=(s?encodeURIComponent:e)(""+c);return z!==n.length&&(c==null||typeof c=="object"&&c.toString===Object.getPrototypeOf(Object.getPrototypeOf(c.hasOwnProperty??Xr)??Xr)?.toString)&&(X=c+"",o.push({start:d.length+P.length,length:X.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),d+P+(z===n.length?"":X)},""),a=i.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,f;for(;(f=l.exec(a))!==null;)o.push({start:f.index,length:f[0].length,error:`Value "${f[0]}" can't be safely passed as a path parameter`});if(o.sort((d,P)=>d.start-P.start),o.length>0){let d=0,P=o.reduce((z,c)=>{let X=" ".repeat(c.start-d),g="^".repeat(c.length);return d=c.start+c.length,z+X+g},"");throw new Hs.SupermemoryError(`Path parameters result in path with invalid segments: +${o.map(z=>z.error).join(` `)} ${i} -${P}`)}return i};V.createPathTagFunction=Hs;V.path=(0,V.createPathTagFunction)(Pt)});var mt=u(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.Connections=void 0;var Ws=Y(),Ts=ee(),L=We(),zt=class extends Ws.APIResource{create(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/connections/list",{body:t,...r})}configure(t,r,n){return this._client.post((0,L.path)`/v3/connections/${t}/configure`,{body:r,...n})}deleteByID(t,r){return this._client.delete((0,L.path)`/v3/connections/${t}`,r)}deleteByProvider(t,r,n){return this._client.delete((0,L.path)`/v3/connections/${t}`,{body:r,...n})}getByID(t,r){return this._client.get((0,L.path)`/v3/connections/${t}`,r)}getByTag(t,r,n){return this._client.post((0,L.path)`/v3/connections/${t}/connection`,{body:r,...n})}import(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}/import`,{body:r,...n,headers:(0,Ts.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}/documents`,{body:r,...n})}resources(t,r={},n){return this._client.get((0,L.path)`/v3/connections/${t}/resources`,{query:r,...n})}};Te.Connections=zt});var jt=u(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.Documents=void 0;var Ns=Y(),Ls=ee(),Vs=_(),xt=We(),bt=class extends Ns.APIResource{update(t,r={},n){return this._client.patch((0,xt.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,xt.path)`/v3/documents/${t}`,{...r,headers:(0,Ls.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}batchAdd(t,r){return this._client.post("/v3/documents/batch",{body:t,...r})}deleteBulk(t={},r){return this._client.delete("/v3/documents/bulk",{body:t,...r})}get(t,r){return this._client.get((0,xt.path)`/v3/documents/${t}`,r)}listProcessing(t){return this._client.get("/v3/documents/processing",t)}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,Vs.multipartFormRequestOptions)({body:t,...r},this._client))}};Ne.Documents=bt});var yt=u(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.Memories=void 0;var Rs=Y(),gs=ee(),ws=_(),Xt=We(),Ot=class extends Rs.APIResource{update(t,r={},n){return this._client.patch((0,Xt.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,Xt.path)`/v3/documents/${t}`,{...r,headers:(0,gs.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}forget(t,r){return this._client.delete("/v4/memories",{body:t,...r})}get(t,r){return this._client.get((0,Xt.path)`/v3/documents/${t}`,r)}updateMemory(t,r){return this._client.patch("/v4/memories",{body:t,...r})}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,ws.multipartFormRequestOptions)({body:t,...r},this._client))}};Le.Memories=Ot});var ht=u(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Search=void 0;var Zs=Y(),qt=class extends Zs.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};Ve.Search=qt});var Wt=u(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.Settings=void 0;var Ms=Y(),Ht=class extends Ms.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};Re.Settings=Ht});var Or=u(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.Settings=h.Search=h.Memories=h.Documents=h.Connections=void 0;var Fs=mt();Object.defineProperty(h,"Connections",{enumerable:!0,get:function(){return Fs.Connections}});var Ds=jt();Object.defineProperty(h,"Documents",{enumerable:!0,get:function(){return Ds.Documents}});var Us=yt();Object.defineProperty(h,"Memories",{enumerable:!0,get:function(){return Us.Memories}});var Ss=ht();Object.defineProperty(h,"Search",{enumerable:!0,get:function(){return Ss.Search}});var Ys=Wt();Object.defineProperty(h,"Settings",{enumerable:!0,get:function(){return Ys.Settings}})});var Tt=u(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.formatRequestDetails=Z.parseLogLevel=void 0;Z.loggerFor=qr;var Gs=A(),we={off:0,error:200,warn:300,info:400,debug:500},ks=(e,t,r)=>{if(e){if((0,Gs.hasOwn)(we,e))return e;qr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(we))}`)}};Z.parseLogLevel=ks;function te(){}function ge(e,t,r){return!t||we[e]>we[r]?te:t[e].bind(t)}var Es={error:te,warn:te,info:te,debug:te},yr=new WeakMap;function qr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Es;let n=yr.get(t);if(n&&n[0]===r)return n[1];let s={error:ge("error",t,r),warn:ge("warn",t,r),info:ge("info",t,r),debug:ge("debug",t,r)};return yr.set(t,[r,s]),s}var Ks=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);Z.formatRequestDetails=Ks});var Hr=u(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.defaultParseResponse=Is;var hr=Tt();async function Is(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,i=await(async()=>{if(r.status===204)return null;if(t.options.__binaryResponse)return r;let p=r.headers.get("content-type")?.split(";")[0]?.trim();return p?.includes("application/json")||p?.endsWith("+json")?await r.json():await r.text()})();return(0,hr.loggerFor)(e).debug(`[${n}] response parsed`,(0,hr.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}});var Rt=u(Ze=>{"use strict";var re;Object.defineProperty(Ze,"__esModule",{value:!0});Ze.APIPromise=void 0;var Lt=rt(),Cs=Hr(),Vt=class e extends Promise{constructor(t,r,n=Cs.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,re.set(this,void 0),Lt.__classPrivateFieldSet(this,re,t,"f")}_thenUnwrap(t){return new e(Lt.__classPrivateFieldGet(this,re,"f"),this.responsePromise,async(r,n)=>t(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(Lt.__classPrivateFieldGet(this,re,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};Ze.APIPromise=Vt;re=new WeakMap});var Wr=u(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.readEnv=void 0;var Js=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};Me.readEnv=Js});var St=u(De=>{"use strict";var Dt,Ut,Fe,Tr;Object.defineProperty(De,"__esModule",{value:!0});De.Supermemory=void 0;var R=rt(),Bs=ir(),gt=A(),As=ar(),wt=nt(),Qs=dr(),Zt=R.__importStar(at()),_s=R.__importStar(lr()),$s=it(),b=R.__importStar(J()),eo=R.__importStar(lt()),ne=R.__importStar(Or()),to=Rt(),ro=mt(),no=jt(),so=yt(),oo=ht(),io=Wt(),Mt=ee(),Ft=Wr(),X=Tt(),ao=A(),x=class{constructor({baseURL:t=(0,Ft.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Ft.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Dt.add(this),Fe.set(this,void 0),this.memories=new ne.Memories(this),this.documents=new ne.Documents(this),this.search=new ne.Search(this),this.settings=new ne.Settings(this),this.connections=new ne.Connections(this),r===void 0)throw new b.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:t||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??Ut.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,X.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,X.parseLogLevel)((0,Ft.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Zt.getDefaultFetch(),R.__classPrivateFieldSet(this,Fe,_s.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,Mt.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Object.entries(t).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new b.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${$s.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,Bs.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!R.__classPrivateFieldGet(this,Dt,"m",Tr).call(this)&&n||this.baseURL,o=(0,gt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return(0,ao.isEmptyObj)(i)||(r={...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(s=>({method:t,path:r,...s})))}request(t,r=null){return new to.APIPromise(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let s=await t,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:i,url:a,timeout:p}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:s});let f="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,P=Date.now();if((0,X.loggerFor)(this).debug(`[${f}] sending request`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:a,options:s,headers:i.headers})),s.signal?.aborted)throw new b.APIUserAbortError;let m=new AbortController,c=await this.fetchWithTimeout(a,i,p,m).catch(wt.castToError),O=Date.now();if(c instanceof globalThis.Error){let T=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let H=(0,wt.isAbortError)(c)||/timed? ?out/i.test(String(c)+("cause"in c?String(c.cause):""));if(r)return(0,X.loggerFor)(this).info(`[${f}] connection ${H?"timed out":"failed"} - ${T}`),(0,X.loggerFor)(this).debug(`[${f}] connection ${H?"timed out":"failed"} (${T})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:a,durationMs:O-P,message:c.message})),this.retryRequest(s,r,n??f);throw(0,X.loggerFor)(this).info(`[${f}] connection ${H?"timed out":"failed"} - error; no more retries left`),(0,X.loggerFor)(this).debug(`[${f}] connection ${H?"timed out":"failed"} (error; no more retries left)`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:a,durationMs:O-P,message:c.message})),H?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:c})}let g=`[${f}${d}] ${i.method} ${a} ${c.ok?"succeeded":"failed"} with status ${c.status} in ${O-P}ms`;if(!c.ok){let T=await this.shouldRetry(c);if(r&&T){let de=`retrying, ${r} attempts remaining`;return await Zt.CancelReadableStream(c.body),(0,X.loggerFor)(this).info(`${g} - ${de}`),(0,X.loggerFor)(this).debug(`[${f}] response error (${de})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:c.url,status:c.status,headers:c.headers,durationMs:O-P})),this.retryRequest(s,r,n??f,c.headers)}let H=T?"error; no more retries left":"error; not retryable";(0,X.loggerFor)(this).info(`${g} - ${H}`);let U=await c.text().catch(de=>(0,wt.castToError)(de).message),E=(0,gt.safeJSON)(U),sr=E?void 0:U;throw(0,X.loggerFor)(this).debug(`[${f}] response error (${H})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:c.url,status:c.status,headers:c.headers,message:sr,durationMs:Date.now()-P})),this.makeStatusError(c.status,E,sr,c.headers)}return(0,X.loggerFor)(this).info(g),(0,X.loggerFor)(this).debug(`[${f}] response start`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:c.url,status:c.status,headers:c.headers,durationMs:O-P})),{response:c,options:s,controller:m,requestLogID:f,retryOfRequestLogID:n,startTime:P}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:i,...a}=r||{};o&&o.addEventListener("abort",()=>s.abort());let p=setTimeout(()=>s.abort(),n),f=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:s.signal,...f?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,d)}finally{clearTimeout(p)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,s){let o,i=s?.get("retry-after-ms");if(i){let p=parseFloat(i);Number.isNaN(p)||(o=p)}let a=s?.get("retry-after");if(a&&!o){let p=parseFloat(a);Number.isNaN(p)?o=Date.parse(a)-Date.now():o=p*1e3}if(!(o&&0<=o&&o<60*1e3)){let p=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,p)}return await(0,As.sleep)(o),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let o=r-t,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:s,path:o,query:i,defaultBaseURL:a}=n,p=this.buildURL(o,i,a);"timeout"in n&&(0,gt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:f,body:d}=this.buildBody({options:n}),P=await this.buildHeaders({options:t,method:s,bodyHeaders:f,retryCount:r});return{req:{method:s,headers:P,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:p,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let i=(0,Mt.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...(0,Qs.getPlatformHeaders)()},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,Mt.buildHeaders)([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Zt.ReadableStreamFrom(t)}:R.__classPrivateFieldGet(this,Fe,"f").call(this,{body:t,headers:n})}};De.Supermemory=x;Ut=x,Fe=new WeakMap,Dt=new WeakSet,Tr=function(){return this.baseURL!=="https://api.supermemory.ai"};x.Supermemory=Ut;x.DEFAULT_TIMEOUT=6e4;x.SupermemoryError=b.SupermemoryError;x.APIError=b.APIError;x.APIConnectionError=b.APIConnectionError;x.APIConnectionTimeoutError=b.APIConnectionTimeoutError;x.APIUserAbortError=b.APIUserAbortError;x.NotFoundError=b.NotFoundError;x.ConflictError=b.ConflictError;x.RateLimitError=b.RateLimitError;x.BadRequestError=b.BadRequestError;x.AuthenticationError=b.AuthenticationError;x.InternalServerError=b.InternalServerError;x.PermissionDeniedError=b.PermissionDeniedError;x.UnprocessableEntityError=b.UnprocessableEntityError;x.toFile=eo.toFile;x.Memories=so.Memories;x.Documents=no.Documents;x.Search=oo.Search;x.Settings=io.Settings;x.Connections=ro.Connections});var Lr=u((v,Nr)=>{"use strict";v=Nr.exports=function(...e){return new v.default(...e)};Object.defineProperty(v,"__esModule",{value:!0});v.UnprocessableEntityError=v.PermissionDeniedError=v.InternalServerError=v.AuthenticationError=v.BadRequestError=v.RateLimitError=v.ConflictError=v.NotFoundError=v.APIUserAbortError=v.APIConnectionTimeoutError=v.APIConnectionError=v.APIError=v.SupermemoryError=v.Supermemory=v.APIPromise=v.toFile=v.default=void 0;var fo=St();Object.defineProperty(v,"default",{enumerable:!0,get:function(){return fo.Supermemory}});var co=lt();Object.defineProperty(v,"toFile",{enumerable:!0,get:function(){return co.toFile}});var uo=Rt();Object.defineProperty(v,"APIPromise",{enumerable:!0,get:function(){return uo.APIPromise}});var vo=St();Object.defineProperty(v,"Supermemory",{enumerable:!0,get:function(){return vo.Supermemory}});var q=J();Object.defineProperty(v,"SupermemoryError",{enumerable:!0,get:function(){return q.SupermemoryError}});Object.defineProperty(v,"APIError",{enumerable:!0,get:function(){return q.APIError}});Object.defineProperty(v,"APIConnectionError",{enumerable:!0,get:function(){return q.APIConnectionError}});Object.defineProperty(v,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return q.APIConnectionTimeoutError}});Object.defineProperty(v,"APIUserAbortError",{enumerable:!0,get:function(){return q.APIUserAbortError}});Object.defineProperty(v,"NotFoundError",{enumerable:!0,get:function(){return q.NotFoundError}});Object.defineProperty(v,"ConflictError",{enumerable:!0,get:function(){return q.ConflictError}});Object.defineProperty(v,"RateLimitError",{enumerable:!0,get:function(){return q.RateLimitError}});Object.defineProperty(v,"BadRequestError",{enumerable:!0,get:function(){return q.BadRequestError}});Object.defineProperty(v,"AuthenticationError",{enumerable:!0,get:function(){return q.AuthenticationError}});Object.defineProperty(v,"InternalServerError",{enumerable:!0,get:function(){return q.InternalServerError}});Object.defineProperty(v,"PermissionDeniedError",{enumerable:!0,get:function(){return q.PermissionDeniedError}});Object.defineProperty(v,"UnprocessableEntityError",{enumerable:!0,get:function(){return q.UnprocessableEntityError}})});var Rr={};hn(Rr,{getRequestIntegrity:()=>ho,sanitizeContent:()=>zo,sanitizeMetadata:()=>Xo,validateApiKeyFormat:()=>lo,validateContainerTag:()=>po,validateContentLength:()=>mo,validateRecallConfig:()=>Oo});function lo(e){return!e||typeof e!="string"?{valid:!1,reason:"key is empty or not a string"}:e.startsWith("sm_")?e.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(e)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function po(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function zo(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Po)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function mo(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Xo(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=xo)break;n.length>bo||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,jo),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function Oo(e,t){let r=[];return(!Number.isInteger(e)||e<1||e>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(t)||t<1||t>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Yt(e){return(0,Ue.createHash)("sha256").update(e).digest("hex")}function qo(e,t){let r=[Yt(e),Yt(t),Vr].join(":");return(0,Ue.createHmac)("sha256",yo).update(r).digest("base64url")}function ho(e,t){let r=Yt(t),n=qo(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${Vr}`,n].join(".")}}var Ue,Po,xo,bo,jo,Vr,yo,gr=qn(()=>{Ue=require("node:crypto");Po=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];xo=50,bo=128,jo=1024;Vr=1,yo="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Gt=u((Va,wr)=>{var Ho="https://api.supermemory.ai";wr.exports={BASE_URL:Ho}});var Mr=u((Ra,Zr)=>{var Wo=Lr().default,{getRequestIntegrity:To,validateApiKeyFormat:No,validateContainerTag:Lo}=(gr(),Wn(Rr)),{BASE_URL:Vo}=Gt(),Ro="claudecode_default";function go(e,t=r=>r){let r=new Set;return e.filter(n=>{let s=String(t(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var wo=`Developer coding session transcript. Focus on USER message and intent. +${P}`)}return i};V.createPathTagFunction=Ws;V.path=(0,V.createPathTagFunction)(mt)});var xt=u(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.Connections=void 0;var Ts=Y(),Ns=ee(),L=We(),zt=class extends Ts.APIResource{create(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/connections/list",{body:t,...r})}configure(t,r,n){return this._client.post((0,L.path)`/v3/connections/${t}/configure`,{body:r,...n})}deleteByID(t,r){return this._client.delete((0,L.path)`/v3/connections/${t}`,r)}deleteByProvider(t,r,n){return this._client.delete((0,L.path)`/v3/connections/${t}`,{body:r,...n})}getByID(t,r){return this._client.get((0,L.path)`/v3/connections/${t}`,r)}getByTag(t,r,n){return this._client.post((0,L.path)`/v3/connections/${t}/connection`,{body:r,...n})}import(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}/import`,{body:r,...n,headers:(0,Ns.buildHeaders)([{Accept:"text/plain"},n?.headers])})}listDocuments(t,r={},n){return this._client.post((0,L.path)`/v3/connections/${t}/documents`,{body:r,...n})}resources(t,r={},n){return this._client.get((0,L.path)`/v3/connections/${t}/resources`,{query:r,...n})}};Te.Connections=zt});var Ot=u(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.Documents=void 0;var Ls=Y(),Vs=ee(),Rs=_(),bt=We(),jt=class extends Ls.APIResource{update(t,r={},n){return this._client.patch((0,bt.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,bt.path)`/v3/documents/${t}`,{...r,headers:(0,Vs.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}batchAdd(t,r){return this._client.post("/v3/documents/batch",{body:t,...r})}deleteBulk(t={},r){return this._client.delete("/v3/documents/bulk",{body:t,...r})}get(t,r){return this._client.get((0,bt.path)`/v3/documents/${t}`,r)}listProcessing(t){return this._client.get("/v3/documents/processing",t)}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,Rs.multipartFormRequestOptions)({body:t,...r},this._client))}};Ne.Documents=jt});var ht=u(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.Memories=void 0;var gs=Y(),ws=ee(),Ms=_(),Xt=We(),yt=class extends gs.APIResource{update(t,r={},n){return this._client.patch((0,Xt.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,Xt.path)`/v3/documents/${t}`,{...r,headers:(0,ws.buildHeaders)([{Accept:"*/*"},r?.headers])})}add(t,r){return this._client.post("/v3/documents",{body:t,...r})}forget(t,r){return this._client.delete("/v4/memories",{body:t,...r})}get(t,r){return this._client.get((0,Xt.path)`/v3/documents/${t}`,r)}updateMemory(t,r){return this._client.patch("/v4/memories",{body:t,...r})}uploadFile(t,r){return this._client.post("/v3/documents/file",(0,Ms.multipartFormRequestOptions)({body:t,...r},this._client))}};Le.Memories=yt});var Ht=u(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Search=void 0;var Zs=Y(),qt=class extends Zs.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};Ve.Search=qt});var Tt=u(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.Settings=void 0;var Fs=Y(),Wt=class extends Fs.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};Re.Settings=Wt});var yr=u(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.Settings=q.Search=q.Memories=q.Documents=q.Connections=void 0;var Ds=xt();Object.defineProperty(q,"Connections",{enumerable:!0,get:function(){return Ds.Connections}});var Us=Ot();Object.defineProperty(q,"Documents",{enumerable:!0,get:function(){return Us.Documents}});var Ss=ht();Object.defineProperty(q,"Memories",{enumerable:!0,get:function(){return Ss.Memories}});var Ys=Ht();Object.defineProperty(q,"Search",{enumerable:!0,get:function(){return Ys.Search}});var Gs=Tt();Object.defineProperty(q,"Settings",{enumerable:!0,get:function(){return Gs.Settings}})});var Nt=u(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.formatRequestDetails=M.parseLogLevel=void 0;M.loggerFor=qr;var ks=A(),we={off:0,error:200,warn:300,info:400,debug:500},Es=(e,t,r)=>{if(e){if((0,ks.hasOwn)(we,e))return e;qr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(we))}`)}};M.parseLogLevel=Es;function te(){}function ge(e,t,r){return!t||we[e]>we[r]?te:t[e].bind(t)}var Ks={error:te,warn:te,info:te,debug:te},hr=new WeakMap;function qr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Ks;let n=hr.get(t);if(n&&n[0]===r)return n[1];let s={error:ge("error",t,r),warn:ge("warn",t,r),info:ge("info",t,r),debug:ge("debug",t,r)};return hr.set(t,[r,s]),s}var Is=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);M.formatRequestDetails=Is});var Wr=u(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.defaultParseResponse=Cs;var Hr=Nt();async function Cs(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=t,i=await(async()=>{if(r.status===204)return null;if(t.options.__binaryResponse)return r;let l=r.headers.get("content-type")?.split(";")[0]?.trim();return l?.includes("application/json")||l?.endsWith("+json")?await r.json():await r.text()})();return(0,Hr.loggerFor)(e).debug(`[${n}] response parsed`,(0,Hr.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}});var gt=u(Me=>{"use strict";var re;Object.defineProperty(Me,"__esModule",{value:!0});Me.APIPromise=void 0;var Vt=nt(),Js=Wr(),Rt=class e extends Promise{constructor(t,r,n=Js.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,re.set(this,void 0),Vt.__classPrivateFieldSet(this,re,t,"f")}_thenUnwrap(t){return new e(Vt.__classPrivateFieldGet(this,re,"f"),this.responsePromise,async(r,n)=>t(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){let[t,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(Vt.__classPrivateFieldGet(this,re,"f"),t))),this.parsedPromise}then(t,r){return this.parse().then(t,r)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}};Me.APIPromise=Rt;re=new WeakMap});var Tr=u(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.readEnv=void 0;var Bs=e=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim()};Ze.readEnv=Bs});var Yt=u(De=>{"use strict";var Ut,St,Fe,Nr;Object.defineProperty(De,"__esModule",{value:!0});De.Supermemory=void 0;var R=nt(),As=ar(),wt=A(),Qs=fr(),Mt=st(),_s=vr(),Zt=R.__importStar(ft()),$s=R.__importStar(pr()),eo=at(),b=R.__importStar(J()),to=R.__importStar(pt()),ne=R.__importStar(yr()),ro=gt(),no=xt(),so=Ot(),oo=ht(),io=Ht(),ao=Tt(),Ft=ee(),Dt=Tr(),O=Nt(),fo=A(),x=class{constructor({baseURL:t=(0,Dt.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Dt.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Ut.add(this),Fe.set(this,void 0),this.memories=new ne.Memories(this),this.documents=new ne.Documents(this),this.search=new ne.Search(this),this.settings=new ne.Settings(this),this.connections=new ne.Connections(this),r===void 0)throw new b.SupermemoryError("The SUPERMEMORY_API_KEY environment variable is missing or empty; either provide it, or instantiate the Supermemory client with an apiKey option, like new Supermemory({ apiKey: 'My API Key' }).");let s={apiKey:r,...n,baseURL:t||"https://api.supermemory.ai"};this.baseURL=s.baseURL,this.timeout=s.timeout??St.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=(0,O.parseLogLevel)(s.logLevel,"ClientOptions.logLevel",this)??(0,O.parseLogLevel)((0,Dt.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Zt.getDefaultFetch(),R.__classPrivateFieldSet(this,Fe,$s.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,Ft.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Object.entries(t).filter(([r,n])=>typeof n<"u").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new b.SupermemoryError(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${eo.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,As.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!R.__classPrivateFieldGet(this,Ut,"m",Nr).call(this)&&n||this.baseURL,o=(0,wt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return(0,fo.isEmptyObj)(i)||(r={...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:r,options:n}){}get(t,r){return this.methodRequest("get",t,r)}post(t,r){return this.methodRequest("post",t,r)}patch(t,r){return this.methodRequest("patch",t,r)}put(t,r){return this.methodRequest("put",t,r)}delete(t,r){return this.methodRequest("delete",t,r)}methodRequest(t,r,n){return this.request(Promise.resolve(n).then(s=>({method:t,path:r,...s})))}request(t,r=null){return new ro.APIPromise(this,this.makeRequest(t,r,void 0))}async makeRequest(t,r,n){let s=await t,o=s.maxRetries??this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:i,url:a,timeout:l}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:s});let f="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,P=Date.now();if((0,O.loggerFor)(this).debug(`[${f}] sending request`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:a,options:s,headers:i.headers})),s.signal?.aborted)throw new b.APIUserAbortError;let z=new AbortController,c=await this.fetchWithTimeout(a,i,l,z).catch(Mt.castToError),X=Date.now();if(c instanceof globalThis.Error){let T=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let H=(0,Mt.isAbortError)(c)||/timed? ?out/i.test(String(c)+("cause"in c?String(c.cause):""));if(r)return(0,O.loggerFor)(this).info(`[${f}] connection ${H?"timed out":"failed"} - ${T}`),(0,O.loggerFor)(this).debug(`[${f}] connection ${H?"timed out":"failed"} (${T})`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:a,durationMs:X-P,message:c.message})),this.retryRequest(s,r,n??f);throw(0,O.loggerFor)(this).info(`[${f}] connection ${H?"timed out":"failed"} - error; no more retries left`),(0,O.loggerFor)(this).debug(`[${f}] connection ${H?"timed out":"failed"} (error; no more retries left)`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:a,durationMs:X-P,message:c.message})),H?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:c})}let g=`[${f}${d}] ${i.method} ${a} ${c.ok?"succeeded":"failed"} with status ${c.status} in ${X-P}ms`;if(!c.ok){let T=await this.shouldRetry(c);if(r&&T){let de=`retrying, ${r} attempts remaining`;return await Zt.CancelReadableStream(c.body),(0,O.loggerFor)(this).info(`${g} - ${de}`),(0,O.loggerFor)(this).debug(`[${f}] response error (${de})`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:c.url,status:c.status,headers:c.headers,durationMs:X-P})),this.retryRequest(s,r,n??f,c.headers)}let H=T?"error; no more retries left":"error; not retryable";(0,O.loggerFor)(this).info(`${g} - ${H}`);let U=await c.text().catch(de=>(0,Mt.castToError)(de).message),E=(0,wt.safeJSON)(U),or=E?void 0:U;throw(0,O.loggerFor)(this).debug(`[${f}] response error (${H})`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:c.url,status:c.status,headers:c.headers,message:or,durationMs:Date.now()-P})),this.makeStatusError(c.status,E,or,c.headers)}return(0,O.loggerFor)(this).info(g),(0,O.loggerFor)(this).debug(`[${f}] response start`,(0,O.formatRequestDetails)({retryOfRequestLogID:n,url:c.url,status:c.status,headers:c.headers,durationMs:X-P})),{response:c,options:s,controller:z,requestLogID:f,retryOfRequestLogID:n,startTime:P}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:i,...a}=r||{};o&&o.addEventListener("abort",()=>s.abort());let l=setTimeout(()=>s.abort(),n),f=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:s.signal,...f?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,d)}finally{clearTimeout(l)}}async shouldRetry(t){let r=t.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,r,n,s){let o,i=s?.get("retry-after-ms");if(i){let l=parseFloat(i);Number.isNaN(l)||(o=l)}let a=s?.get("retry-after");if(a&&!o){let l=parseFloat(a);Number.isNaN(l)?o=Date.parse(a)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,l)}return await(0,Qs.sleep)(o),this.makeRequest(t,r-1,n)}calculateDefaultRetryTimeoutMillis(t,r){let o=r-t,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(t,{retryCount:r=0}={}){let n={...t},{method:s,path:o,query:i,defaultBaseURL:a}=n,l=this.buildURL(o,i,a);"timeout"in n&&(0,wt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:f,body:d}=this.buildBody({options:n}),P=await this.buildHeaders({options:t,method:s,bodyHeaders:f,retryCount:r});return{req:{method:s,headers:P,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:t,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);let i=(0,Ft.buildHeaders)([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...(0,_s.getPlatformHeaders)()},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,Ft.buildHeaders)([r]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Zt.ReadableStreamFrom(t)}:R.__classPrivateFieldGet(this,Fe,"f").call(this,{body:t,headers:n})}};De.Supermemory=x;St=x,Fe=new WeakMap,Ut=new WeakSet,Nr=function(){return this.baseURL!=="https://api.supermemory.ai"};x.Supermemory=St;x.DEFAULT_TIMEOUT=6e4;x.SupermemoryError=b.SupermemoryError;x.APIError=b.APIError;x.APIConnectionError=b.APIConnectionError;x.APIConnectionTimeoutError=b.APIConnectionTimeoutError;x.APIUserAbortError=b.APIUserAbortError;x.NotFoundError=b.NotFoundError;x.ConflictError=b.ConflictError;x.RateLimitError=b.RateLimitError;x.BadRequestError=b.BadRequestError;x.AuthenticationError=b.AuthenticationError;x.InternalServerError=b.InternalServerError;x.PermissionDeniedError=b.PermissionDeniedError;x.UnprocessableEntityError=b.UnprocessableEntityError;x.toFile=to.toFile;x.Memories=oo.Memories;x.Documents=so.Documents;x.Search=io.Search;x.Settings=ao.Settings;x.Connections=no.Connections});var Vr=u((v,Lr)=>{"use strict";v=Lr.exports=function(...e){return new v.default(...e)};Object.defineProperty(v,"__esModule",{value:!0});v.UnprocessableEntityError=v.PermissionDeniedError=v.InternalServerError=v.AuthenticationError=v.BadRequestError=v.RateLimitError=v.ConflictError=v.NotFoundError=v.APIUserAbortError=v.APIConnectionTimeoutError=v.APIConnectionError=v.APIError=v.SupermemoryError=v.Supermemory=v.APIPromise=v.toFile=v.default=void 0;var co=Yt();Object.defineProperty(v,"default",{enumerable:!0,get:function(){return co.Supermemory}});var uo=pt();Object.defineProperty(v,"toFile",{enumerable:!0,get:function(){return uo.toFile}});var vo=gt();Object.defineProperty(v,"APIPromise",{enumerable:!0,get:function(){return vo.APIPromise}});var lo=Yt();Object.defineProperty(v,"Supermemory",{enumerable:!0,get:function(){return lo.Supermemory}});var h=J();Object.defineProperty(v,"SupermemoryError",{enumerable:!0,get:function(){return h.SupermemoryError}});Object.defineProperty(v,"APIError",{enumerable:!0,get:function(){return h.APIError}});Object.defineProperty(v,"APIConnectionError",{enumerable:!0,get:function(){return h.APIConnectionError}});Object.defineProperty(v,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return h.APIConnectionTimeoutError}});Object.defineProperty(v,"APIUserAbortError",{enumerable:!0,get:function(){return h.APIUserAbortError}});Object.defineProperty(v,"NotFoundError",{enumerable:!0,get:function(){return h.NotFoundError}});Object.defineProperty(v,"ConflictError",{enumerable:!0,get:function(){return h.ConflictError}});Object.defineProperty(v,"RateLimitError",{enumerable:!0,get:function(){return h.RateLimitError}});Object.defineProperty(v,"BadRequestError",{enumerable:!0,get:function(){return h.BadRequestError}});Object.defineProperty(v,"AuthenticationError",{enumerable:!0,get:function(){return h.AuthenticationError}});Object.defineProperty(v,"InternalServerError",{enumerable:!0,get:function(){return h.InternalServerError}});Object.defineProperty(v,"PermissionDeniedError",{enumerable:!0,get:function(){return h.PermissionDeniedError}});Object.defineProperty(v,"UnprocessableEntityError",{enumerable:!0,get:function(){return h.UnprocessableEntityError}})});var gr={};Hn(gr,{getRequestIntegrity:()=>Ho,sanitizeContent:()=>zo,sanitizeMetadata:()=>Xo,validateApiKeyFormat:()=>po,validateContainerTag:()=>Po,validateContentLength:()=>xo,validateRecallConfig:()=>yo});function po(e){return!e||typeof e!="string"?{valid:!1,reason:"key is empty or not a string"}:e.startsWith("sm_")?e.length<20?{valid:!1,reason:"key is too short"}:/\s/.test(e)?{valid:!1,reason:"key contains whitespace"}:{valid:!0}:{valid:!1,reason:"key must start with sm_ prefix"}}function Po(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function zo(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of mo)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function xo(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Xo(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=bo)break;n.length>jo||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,Oo),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function yo(e,t){let r=[];return(!Number.isInteger(e)||e<1||e>20)&&r.push("maxRecallResults must be an integer between 1 and 20"),(!Number.isInteger(t)||t<1||t>500)&&r.push("profileFrequency must be an integer between 1 and 500"),r}function Gt(e){return(0,Ue.createHash)("sha256").update(e).digest("hex")}function qo(e,t){let r=[Gt(e),Gt(t),Rr].join(":");return(0,Ue.createHmac)("sha256",ho).update(r).digest("base64url")}function Ho(e,t){let r=Gt(t),n=qo(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${Rr}`,n].join(".")}}var Ue,mo,bo,jo,Oo,Rr,ho,wr=qn(()=>{Ue=require("node:crypto");mo=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];bo=50,jo=128,Oo=1024;Rr=1,ho="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var kt=u((Ra,Mr)=>{var Wo="https://api.supermemory.ai";Mr.exports={BASE_URL:Wo}});var Fr=u((ga,Zr)=>{var To=Vr().default,{getRequestIntegrity:No,validateApiKeyFormat:Lo,validateContainerTag:Vo}=(wr(),Tn(gr)),{BASE_URL:Ro}=kt(),go="claudecode_default";function wo(e,t=r=>r){let r=new Set;return e.filter(n=>{let s=String(t(n)).toLowerCase().trim();return!s||r.has(s)?!1:(r.add(s),!0)})}var Mo=`Developer coding session transcript. Focus on USER message and intent. RULES: - Extract USER's action/intent, not every detail assistant provides matter @@ -43,70 +43,70 @@ EXAMPLES: | Input | Memory | | "The auth flow works by..." | "Auth flow: [description]" | | "We structure components like..." | "Component structure convention: [pattern]" | -| "To add a new API route..." | "Adding API routes: [steps]" |`,kt=class{constructor(t,r,n={}){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=No(t);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||Ro,i=Lo(o);i.valid||console.warn(`Container tag warning: ${i.reason}`);let a=To(t,o);this.client=new Wo({apiKey:t,baseURL:n.baseUrl||Vo,defaultHeaders:{...a,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let i=await this.client.add(o);return{id:i.id,status:i.status,containerTag:r||this.containerTag}}async search(t,r,n={}){let s=await this.client.search.memories({q:t,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(i=>({memory:i.content||i.memory||i.context||"",chunk:i.chunk,metadata:i.metadata,updatedAt:i.updatedAt,similarity:i.similarity}));return{results:go(o,i=>i.memory),total:s.total,timing:s.timing}}async getProfile(t,r){let n=await this.client.profile({containerTag:t||this.containerTag,q:r}),s=new Set,o=(f,d=P=>P)=>f.filter(P=>{let m=String(d(P)).toLowerCase().trim();return!m||s.has(m)?!1:(s.add(m),!0)}),i=o(n.profile?.static||[]),a=o(n.profile?.dynamic||[]),p;if(n.searchResults){let f=n.searchResults.results.map(d=>({id:d.id,memory:d.content||d.context||"",similarity:d.similarity,title:d.title,updatedAt:d.updatedAt}));p={results:o(f,d=>d.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:i,dynamic:a},searchResults:p}}};Zr.exports={SupermemoryClient:kt,PERSONAL_ENTITY_CONTEXT:wo,REPO_ENTITY_CONTEXT:Zo}});var Et=u((ga,Fr)=>{var{execSync:Se}=require("node:child_process"),se=require("node:path");function Mo(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return Se("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=Se("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return Se("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=se.resolve(e,r);return se.basename(n)===".git"&&!n.includes(`${se.sep}.git${se.sep}`)?se.dirname(n):Se("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}Fr.exports={getGitRoot:Mo}});var Ge=u((wa,kr)=>{var oe=require("node:fs"),Ye=require("node:path"),{getGitRoot:Dr}=Et(),Ur=Ye.join(".claude",".supermemory-claude"),Sr="config.json";function Yr(e){let r=Dr(e)||e;return Ye.join(r,Ur,Sr)}function Gr(e){try{let t=Yr(e);if(oe.existsSync(t))return JSON.parse(oe.readFileSync(t,"utf-8"))}catch{}return null}function Fo(e,t){let n=Dr(e)||e,s=Ye.join(n,Ur),o=Ye.join(s,Sr);oe.existsSync(s)||oe.mkdirSync(s,{recursive:!0});let a={...Gr(e)||{},...t};return oe.writeFileSync(o,JSON.stringify(a,null,2)),o}kr.exports={getConfigPath:Yr,loadProjectConfig:Gr,saveProjectConfig:Fo}});var Cr=u((Za,Ir)=>{var{execSync:Do}=require("node:child_process"),Uo=require("node:crypto"),{loadProjectConfig:Er}=Ge(),{getGitRoot:ke}=Et();function Kr(e){return Uo.createHash("sha256").update(e).digest("hex").slice(0,16)}function Kt(e){try{let r=Do("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/);return r?r[1]:null}catch{return null}}function So(e){let t=Er(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=ke(e)||e;return`claudecode_project_${Kr(n)}`}function Yo(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function Go(e){let t=Er(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=ke(e)||e,o=Kt(n)||n.split("/").pop()||"unknown";return`repo_${Yo(o)}`}function ko(e){let r=ke(e)||e;return Kt(r)||r.split("/").pop()||"unknown"}Ir.exports={sha256:Kr,getGitRoot:ke,getGitRepoName:Kt,getContainerTag:So,getRepoContainerTag:Go,getProjectName:ko}});var Br=u((Ma,Jr)=>{var{execFile:Eo}=require("node:child_process");function Ee(e,t){return new Promise((r,n)=>{Eo(e,t,{windowsHide:!0},s=>{s?n(s):r()})})}async function Ko(e){let t=e.toString();if(!/^https?:\/\//i.test(t))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await Ee("rundll32.exe",["url.dll,FileProtocolHandler",t]);return}catch{}await Ee("cmd.exe",["/c","start",'""',t]);return}if(process.platform==="darwin"){await Ee("open",[t]);return}await Ee("xdg-open",[t])}Jr.exports={openUrl:Ko}});var Ar=u((Fa,Io)=>{Io.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var Qr=u((Da,Co)=>{Co.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var rn=u((Ua,tn)=>{var Jo=require("node:http"),M=require("node:fs"),_r=require("node:path"),Bo=require("node:os"),{openUrl:Ao}=Br(),Qo=Ar(),_o=Qr(),Ct=_r.join(Bo.homedir(),".supermemory-claude"),k=_r.join(Ct,"credentials.json"),$r=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",It=19876,$o=25e3;function ei(){M.existsSync(Ct)||M.mkdirSync(Ct,{recursive:!0})}function ti(){try{if(M.existsSync(k)){let e=JSON.parse(M.readFileSync(k,"utf-8"));if(e.apiKey)return e}}catch{}return null}function en(e){ei();let t={apiKey:e,savedAt:new Date().toISOString()};M.writeFileSync(k,JSON.stringify(t,null,2))}function ri(){try{M.existsSync(k)&&M.unlinkSync(k)}catch{}}function ni(){return new Promise((e,t)=>{let r=!1,n=Jo.createServer((s,o)=>{let i=new URL(s.url,`http://localhost:${It}`);if(i.pathname==="/callback"){let a=i.searchParams.get("apikey")||i.searchParams.get("api_key");a?.startsWith("sm_")?(en(a),o.writeHead(200,{"Content-Type":"text/html"}),o.end(Qo),r=!0,n.close(),e(a)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(_o))}else o.writeHead(404),o.end("Not found")});n.listen(It,"127.0.0.1",()=>{let s=`http://localhost:${It}/callback`,o=`${$r}?callback=${encodeURIComponent(s)}&client=claude_code`;Ao(o).catch(i=>{r||(n.close(),t(new Error(`Failed to open browser: ${i.message}`)))})}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},$o)})}tn.exports={AUTH_BASE_URL:$r,CREDENTIALS_FILE:k,loadCredentials:ti,saveCredentials:en,clearCredentials:ri,startAuthFlow:ni}});var Jt=u((Sa,sn)=>{var ae=require("node:fs"),nn=require("node:path"),si=require("node:os"),{loadCredentials:oi}=rn(),{loadProjectConfig:fe}=Ge(),{BASE_URL:ii}=Gt(),Ke=nn.join(si.homedir(),".supermemory-claude"),ie=nn.join(Ke,"settings.json"),Ie={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function ai(){ae.existsSync(Ke)||ae.mkdirSync(Ke,{recursive:!0})}function Ce(){let e={...Ie};try{if(ae.existsSync(ie)){let t=ae.readFileSync(ie,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${ie}: ${t.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function fi(e){ai();let t={...e};delete t.apiKey,ae.writeFileSync(ie,JSON.stringify(t,null,2))}function ci(e,t,r){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||fe(t||process.cwd()),r?.apiKey)return r.apiKey;let n=oi();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function ui(e){if(typeof e!="string"||!e.trim())return null;let t=e.trim();try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t}catch{return null}}function di(e,t){t=t||fe(e||process.cwd());let r=process.env.SUPERMEMORY_API_URL||t?.baseUrl||ii,n=ui(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function vi(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function li(e){let t=Ce(),r=fe(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(i=>i.toLowerCase())}function pi(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function Pi(e){let t=Ce(),r=fe(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,i=t.signalKeywords||Ie.signalKeywords,a=r?.signalKeywords||[],p=[...new Set([...i,...a])].map(d=>d.toLowerCase()),f=r?.signalTurnsBefore||t.signalTurnsBefore||Ie.signalTurnsBefore;return{enabled:o,keywords:p,turnsBefore:f}}function zi(e){let t=Ce();return{directive:fe(e||process.cwd())?.recallDirective||t.recallDirective||null}}sn.exports={SETTINGS_DIR:Ke,SETTINGS_FILE:ie,DEFAULT_SETTINGS:Ie,loadSettings:Ce,saveSettings:fi,getApiKey:ci,getBaseUrl:di,debugLog:vi,getIncludeTools:li,shouldIncludeTool:pi,getSignalConfig:Pi,getRecallConfig:zi}});var an=u((Ya,on)=>{async function mi(){return new Promise((e,t)=>{let r="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{r+=n}),process.stdin.on("end",()=>{try{e(r.trim()?JSON.parse(r):{})}catch(n){t(new Error(`Failed to parse stdin JSON: ${n.message}`))}}),process.stdin.on("error",t),process.stdin.isTTY&&e({})})}function Je(e){console.log(JSON.stringify(e))}function xi(e=null){Je(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function bi(e){console.error(`Supermemory: ${e}`),Je({continue:!0,suppressOutput:!0})}on.exports={readStdin:mi,writeOutput:Je,outputSuccess:xi,outputError:bi}});var Pn=u((Ga,pn)=>{var F=require("node:fs"),Bt=require("node:path"),ji=require("node:os"),{getIncludeTools:fn,shouldIncludeTool:cn,getSignalConfig:Xi}=Jt(),Oi=500,Be=Bt.join(ji.homedir(),".supermemory-claude","trackers"),Ae=new Map,Qe=[];function un(){F.existsSync(Be)||F.mkdirSync(Be,{recursive:!0})}function At(e){un();let t=Bt.join(Be,`${e}.txt`);return F.existsSync(t)?F.readFileSync(t,"utf-8").trim():null}function Qt(e,t){un();let r=Bt.join(Be,`${e}.txt`);F.writeFileSync(r,t)}function _t(e){if(!F.existsSync(e))return[];let r=F.readFileSync(e,"utf-8").trim().split(` -`),n=[];for(let s of r)if(s.trim())try{n.push(JSON.parse(s))}catch{}return n}function $t(e,t){if(!t)return e.filter(s=>s.type==="user"||s.type==="assistant");let r=!1,n=[];for(let s of e){if(s.uuid===t){r=!0;continue}r&&(s.type==="user"||s.type==="assistant")&&n.push(s)}return n}function dn(e){let t=[];if(e.type==="user"){let r=yi(e.message);r&&t.push(r)}else if(e.type==="assistant"){let r=qi(e.message);r&&t.push(r)}return t.join(` -`)}function yi(e){if(!e?.content)return null;let t=e.content,r=[];if(typeof t=="string"){let n=W(t);n&&r.push(`<|start|>user<|message|>${n}<|end|>`)}else if(Array.isArray(t)){for(let n of t)if(n.type==="text"&&n.text){let s=W(n.text);s&&r.push(`<|start|>user<|message|>${s}<|end|>`)}else if(n.type==="tool_result"){let s=n.tool_use_id||"",o=Ae.get(s)||"Unknown";if(!cn(o,Qe))continue;let i=er(W(n.content||""),Oi),a=n.is_error?"error":"success";i&&r.push(`<|start|>assistant:tool_result<|message|>${o}(${a}): ${i}<|end|>`)}}return r.length>0?r.join(` -`):null}function qi(e){if(!e?.content)return null;let t=e.content,r=[];if(!Array.isArray(t))return null;for(let s of t)if(s.type!=="thinking"){if(s.type==="text"&&s.text){let o=W(s.text);o&&r.push({type:"text",content:o})}else if(s.type==="tool_use"){let o=s.name||"Unknown",i=s.id||"";if(i&&Ae.set(i,o),!cn(o,Qe))continue;let a=s.input||{},p=hi(a);r.push({type:"tool",toolName:o,inputStr:p})}}let n=r.map(s=>s.type==="text"?`<|start|>assistant<|message|>${s.content}<|end|>`:`<|start|>assistant:tool<|message|>${s.toolName}: ${s.inputStr}<|end|>`);return n.length>0?n.join(` -`):null}function hi(e){let t=[];for(let[r,n]of Object.entries(e)){let s=typeof n=="string"?n:JSON.stringify(n);s=er(s,100),t.push(`${r}="${s}"`)}return t.join(" ")}function W(e){return!e||typeof e!="string"?"":e.replace(/[\s\S]*?<\/system-reminder>/g,"").replace(/[\s\S]*?<\/supermemory-context>/g,"").trim()}function er(e,t){return!e||e.length<=t?e:`${e.slice(0,t)}...`}function tr(e){if(!e?.message?.content)return"";let t=e.message.content;if(typeof t=="string")return W(t);if(Array.isArray(t)){let r=[];for(let n of t)n.type==="text"&&n.text&&r.push(W(n.text));return r.join(" ")}return""}function Hi(e){return!e||e.isMeta?!1:tr(e).length>0}function Wi(e){let t=[],r={userEntries:[],assistantEntries:[],allEntries:[]};for(let n=0;n0&&(t.push(r),r={userEntries:[],assistantEntries:[],allEntries:[]}),r.userEntries.push(s),r.allEntries.push(s)):s.type==="assistant"&&(r.assistantEntries.push(s),r.allEntries.push(s))}return r.allEntries.length>0&&t.push(r),t}function Ti(e){let t=[],r={userEntries:[]},n=null,s=()=>{if(r.userEntries.length===0&&!n)return;let o=n?[n]:[],i=[...r.userEntries,...o];t.push({userEntries:r.userEntries,assistantEntries:o,allEntries:i}),r={userEntries:[]},n=null};for(let o=0;oo-i).map(o=>e[o])}function Li(e){return e.type==="user"?Vi(e.message):e.type==="assistant"?Ri(e.message):null}function Vi(e){if(!e?.content)return null;let t=e.content,r=[];if(typeof t=="string"){let n=W(t);n&&r.push(`<|start|>user<|message|>${n}<|end|>`)}else if(Array.isArray(t)){for(let n of t)if(n.type==="text"&&n.text){let s=W(n.text);s&&r.push(`<|start|>user<|message|>${s}<|end|>`)}}return r.length>0?r.join(` -`):null}function Ri(e){if(!e?.content)return null;let t=e.content,r=[];if(typeof t=="string"){let n=W(t);n&&r.push(`<|start|>assistant<|message|>${n}<|end|>`)}else if(Array.isArray(t)){for(let n of t)if(n.type==="text"&&n.text){let s=W(n.text);s&&r.push(`<|start|>assistant<|message|>${s}<|end|>`)}}return r.length>0?r.join(` -`):null}function gi(e,t,r){Ae=new Map,Qe=fn(r);let n=Xi(r),{keywords:s,turnsBefore:o}=n,i=_t(e);if(i.length===0)return null;let a=At(t),p=$t(i,a);if(p.length===0)return null;let f=Ti(p);if(f.length===0)return null;let d=vn(f,s);if(d.length===0)return null;let P=ln(f,d,o);if(P.length===0)return null;let m=[];for(let U of P)m.push(...U.allEntries);if(m.length===0)return null;let c=m[0],O=p[p.length-1],g=c.timestamp||new Date().toISOString(),T=[];T.push(`<|turn_start|>${g}`);for(let U of m){let E=Li(U);E&&T.push(E)}T.push("<|turn_end|>");let H=T.join(` +| "To add a new API route..." | "Adding API routes: [steps]" |`,Et=class{constructor(t,r,n={}){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let s=Lo(t);if(!s.valid)throw new Error(`Invalid API key: ${s.reason}`);let o=r||go,i=Vo(o);i.valid||console.warn(`Container tag warning: ${i.reason}`);let a=No(t,o);this.client=new To({apiKey:t,baseURL:n.baseUrl||Ro,defaultHeaders:{...a,"x-sm-source":"claude-code"}}),this.containerTag=o}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code",...n}};s.customId&&(o.customId=s.customId),s.entityContext&&(o.entityContext=s.entityContext);let i=await this.client.add(o);return{id:i.id,status:i.status,containerTag:r||this.containerTag}}async search(t,r,n={}){let s=await this.client.search.memories({q:t,containerTag:r||this.containerTag,limit:n.limit||10,searchMode:n.searchMode||"hybrid"}),o=s.results.map(i=>({memory:i.content||i.memory||i.context||"",chunk:i.chunk,metadata:i.metadata,updatedAt:i.updatedAt,similarity:i.similarity}));return{results:wo(o,i=>i.memory),total:s.total,timing:s.timing}}async getProfile(t,r){let n=await this.client.profile({containerTag:t||this.containerTag,q:r}),s=new Set,o=(f,d=P=>P)=>f.filter(P=>{let z=String(d(P)).toLowerCase().trim();return!z||s.has(z)?!1:(s.add(z),!0)}),i=o(n.profile?.static||[]),a=o(n.profile?.dynamic||[]),l;if(n.searchResults){let f=n.searchResults.results.map(d=>({id:d.id,memory:d.content||d.context||"",similarity:d.similarity,title:d.title,updatedAt:d.updatedAt}));l={results:o(f,d=>d.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:i,dynamic:a},searchResults:l}}};Zr.exports={SupermemoryClient:Et,PERSONAL_ENTITY_CONTEXT:Mo,REPO_ENTITY_CONTEXT:Zo}});var Kt=u((wa,Dr)=>{var{execSync:Se}=require("node:child_process"),se=require("node:path");function Fo(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return Se("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=Se("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return Se("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=se.resolve(e,r);return se.basename(n)===".git"&&!n.includes(`${se.sep}.git${se.sep}`)?se.dirname(n):Se("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}Dr.exports={getGitRoot:Fo}});var Ge=u((Ma,Er)=>{var oe=require("node:fs"),Ye=require("node:path"),{getGitRoot:Ur}=Kt(),Sr=Ye.join(".claude",".supermemory-claude"),Yr="config.json";function Gr(e){let r=Ur(e)||e;return Ye.join(r,Sr,Yr)}function kr(e){try{let t=Gr(e);if(oe.existsSync(t))return JSON.parse(oe.readFileSync(t,"utf-8"))}catch{}return null}function Do(e,t){let n=Ur(e)||e,s=Ye.join(n,Sr),o=Ye.join(s,Yr);oe.existsSync(s)||oe.mkdirSync(s,{recursive:!0});let a={...kr(e)||{},...t};return oe.writeFileSync(o,JSON.stringify(a,null,2)),o}Er.exports={getConfigPath:Gr,loadProjectConfig:kr,saveProjectConfig:Do}});var Jr=u((Za,Cr)=>{var{execSync:Uo}=require("node:child_process"),So=require("node:crypto"),{loadProjectConfig:Kr}=Ge(),{getGitRoot:Ee}=Kt();function Ir(e){return So.createHash("sha256").update(e).digest("hex").slice(0,16)}var ke=new Map;function It(e){if(ke.has(e))return ke.get(e);try{let r=Uo("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/),n=r?r[1]:null;return ke.set(e,n),n}catch{return ke.set(e,null),null}}function Yo(e){let t=Kr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Ee(e)||e;return`claudecode_project_${Ir(n)}`}function Go(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function ko(e){let t=Kr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Ee(e)||e,o=It(n)||n.split("/").pop()||"unknown";return`repo_${Go(o)}`}function Eo(e){let r=Ee(e)||e;return It(r)||r.split("/").pop()||"unknown"}Cr.exports={sha256:Ir,getGitRoot:Ee,getGitRepoName:It,getContainerTag:Yo,getRepoContainerTag:ko,getProjectName:Eo}});var Ar=u((Fa,Br)=>{var{execFile:Ko}=require("node:child_process");function Ke(e,t){return new Promise((r,n)=>{Ko(e,t,{windowsHide:!0},s=>{s?n(s):r()})})}async function Io(e){let t=e.toString();if(!/^https?:\/\//i.test(t))throw new Error("Refusing to open non-http URL");if(process.platform==="win32"){try{await Ke("rundll32.exe",["url.dll,FileProtocolHandler",t]);return}catch{}await Ke("cmd.exe",["/c","start",'""',t]);return}if(process.platform==="darwin"){await Ke("open",[t]);return}await Ke("xdg-open",[t])}Br.exports={openUrl:Io}});var Qr=u((Da,Co)=>{Co.exports=`\r +\r +Connected - Supermemory\r +\r +\r +
\r +
Connected . . .
\r +\r +
\r + \r + +\r + \r +
\r +

Supercharge your Claude Code with Supermemory.

\r +
\r +\r +\r +`});var _r=u((Ua,Jo)=>{Jo.exports=`\r +\r +Error - Supermemory\r +\r +
Error . . .
\r +

Connection Failed

\r +

Invalid API key received. Please try again.

\r +\r +`});var nn=u((Sa,rn)=>{var Bo=require("node:http"),Z=require("node:fs"),$r=require("node:path"),Ao=require("node:os"),{openUrl:Qo}=Ar(),_o=Qr(),$o=_r(),Jt=$r.join(Ao.homedir(),".supermemory-claude"),k=$r.join(Jt,"credentials.json"),en=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",Ct=19876,ei=25e3;function ti(){Z.existsSync(Jt)||Z.mkdirSync(Jt,{recursive:!0})}function ri(){try{if(Z.existsSync(k)){let e=JSON.parse(Z.readFileSync(k,"utf-8"));if(e.apiKey)return e}}catch{}return null}function tn(e){ti();let t={apiKey:e,savedAt:new Date().toISOString()};Z.writeFileSync(k,JSON.stringify(t,null,2))}function ni(){try{Z.existsSync(k)&&Z.unlinkSync(k)}catch{}}function si(){return new Promise((e,t)=>{let r=!1,n=Bo.createServer((s,o)=>{let i=new URL(s.url,`http://localhost:${Ct}`);if(i.pathname==="/callback"){let a=i.searchParams.get("apikey")||i.searchParams.get("api_key");a?.startsWith("sm_")?(tn(a),o.writeHead(200,{"Content-Type":"text/html"}),o.end(_o),r=!0,n.close(),e(a)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end($o))}else o.writeHead(404),o.end("Not found")});n.listen(Ct,"127.0.0.1",()=>{let s=`http://localhost:${Ct}/callback`,o=`${en}?callback=${encodeURIComponent(s)}&client=claude_code`;Qo(o).catch(i=>{r||(n.close(),t(new Error(`Failed to open browser: ${i.message}`)))})}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},ei)})}rn.exports={AUTH_BASE_URL:en,CREDENTIALS_FILE:k,loadCredentials:ri,saveCredentials:tn,clearCredentials:ni,startAuthFlow:si}});var Bt=u((Ya,on)=>{var ae=require("node:fs"),sn=require("node:path"),oi=require("node:os"),{loadCredentials:ii}=nn(),{loadProjectConfig:fe}=Ge(),{BASE_URL:ai}=kt(),Ie=sn.join(oi.homedir(),".supermemory-claude"),ie=sn.join(Ie,"settings.json"),Ce={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,recallDirective:null,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function fi(){ae.existsSync(Ie)||ae.mkdirSync(Ie,{recursive:!0})}function Je(){let e={...Ce};try{if(ae.existsSync(ie)){let t=ae.readFileSync(ie,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${ie}: ${t.message}`)}return process.env.SUPERMEMORY_CC_API_KEY&&(e.apiKey=process.env.SUPERMEMORY_CC_API_KEY),process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function ci(e){fi();let t={...e};delete t.apiKey,ae.writeFileSync(ie,JSON.stringify(t,null,2))}function ui(e,t,r){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;if(r=r||fe(t||process.cwd()),r?.apiKey)return r.apiKey;let n=ii();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function di(e){if(typeof e!="string"||!e.trim())return null;let t=e.trim();try{let r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:t}catch{return null}}function vi(e,t){t=t||fe(e||process.cwd());let r=process.env.SUPERMEMORY_API_URL||t?.baseUrl||ai,n=di(r);if(!n)throw new Error("Invalid baseUrl: expected an absolute http(s) URL");return n}function li(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function pi(e){let t=Je(),r=fe(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(i=>i.toLowerCase())}function Pi(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function mi(e){let t=Je(),r=fe(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,i=t.signalKeywords||Ce.signalKeywords,a=r?.signalKeywords||[],l=[...new Set([...i,...a])].map(d=>d.toLowerCase()),f=r?.signalTurnsBefore||t.signalTurnsBefore||Ce.signalTurnsBefore;return{enabled:o,keywords:l,turnsBefore:f}}function zi(e){let t=Je();return{directive:fe(e||process.cwd())?.recallDirective||t.recallDirective||null}}on.exports={SETTINGS_DIR:Ie,SETTINGS_FILE:ie,DEFAULT_SETTINGS:Ce,loadSettings:Je,saveSettings:ci,getApiKey:ui,getBaseUrl:vi,debugLog:li,getIncludeTools:pi,shouldIncludeTool:Pi,getSignalConfig:mi,getRecallConfig:zi}});var fn=u((Ga,an)=>{async function xi(e=3e3){return new Promise((t,r)=>{let n="",s=!1,o=null,i=()=>{try{process.stdin.pause()}catch{}try{process.stdin.unref?.()}catch{}},a=(f,d)=>{s||(s=!0,clearTimeout(o),i(),f(d))},l=()=>{if(n.trim())try{let f=JSON.parse(n);a(t,f)}catch{}};o=setTimeout(()=>{a(t,{})},e),process.stdin.setEncoding("utf8"),process.stdin.on("data",f=>{n+=f,l()}),process.stdin.on("end",()=>{if(!s){if(!n.trim()){a(t,{});return}try{a(t,JSON.parse(n))}catch(f){a(r,new Error(`Failed to parse stdin JSON: ${f.message}`))}}}),process.stdin.on("error",f=>a(r,f)),process.stdin.isTTY&&a(t,{})})}function Be(e){console.log(JSON.stringify(e))}function bi(e=null){Be(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function ji(e){console.error(`Supermemory: ${e}`),Be({continue:!0,suppressOutput:!0})}an.exports={readStdin:xi,writeOutput:Be,outputSuccess:bi,outputError:ji}});var mn=u((ka,Pn)=>{var F=require("node:fs"),At=require("node:path"),Oi=require("node:os"),{getIncludeTools:cn,shouldIncludeTool:un,getSignalConfig:Xi}=Bt(),yi=500,Ae=At.join(Oi.homedir(),".supermemory-claude","trackers"),Qe=new Map,_e=[];function dn(){F.existsSync(Ae)||F.mkdirSync(Ae,{recursive:!0})}function Qt(e){dn();let t=At.join(Ae,`${e}.txt`);return F.existsSync(t)?F.readFileSync(t,"utf-8").trim():null}function _t(e,t){dn();let r=At.join(Ae,`${e}.txt`);F.writeFileSync(r,t)}function $t(e){if(!F.existsSync(e))return[];let r=F.readFileSync(e,"utf-8").trim().split(` +`),n=[];for(let s of r)if(s.trim())try{n.push(JSON.parse(s))}catch{}return n}function er(e,t){if(!t)return e.filter(s=>s.type==="user"||s.type==="assistant");let r=!1,n=[];for(let s of e){if(s.uuid===t){r=!0;continue}r&&(s.type==="user"||s.type==="assistant")&&n.push(s)}return n}function vn(e){let t=[];if(e.type==="user"){let r=hi(e.message);r&&t.push(r)}else if(e.type==="assistant"){let r=qi(e.message);r&&t.push(r)}return t.join(` +`)}function hi(e){if(!e?.content)return null;let t=e.content,r=[];if(typeof t=="string"){let n=W(t);n&&r.push(`<|start|>user<|message|>${n}<|end|>`)}else if(Array.isArray(t)){for(let n of t)if(n.type==="text"&&n.text){let s=W(n.text);s&&r.push(`<|start|>user<|message|>${s}<|end|>`)}else if(n.type==="tool_result"){let s=n.tool_use_id||"",o=Qe.get(s)||"Unknown";if(!un(o,_e))continue;let i=tr(W(n.content||""),yi),a=n.is_error?"error":"success";i&&r.push(`<|start|>assistant:tool_result<|message|>${o}(${a}): ${i}<|end|>`)}}return r.length>0?r.join(` +`):null}function qi(e){if(!e?.content)return null;let t=e.content,r=[];if(!Array.isArray(t))return null;for(let s of t)if(s.type!=="thinking"){if(s.type==="text"&&s.text){let o=W(s.text);o&&r.push({type:"text",content:o})}else if(s.type==="tool_use"){let o=s.name||"Unknown",i=s.id||"";if(i&&Qe.set(i,o),!un(o,_e))continue;let a=s.input||{},l=Hi(a);r.push({type:"tool",toolName:o,inputStr:l})}}let n=r.map(s=>s.type==="text"?`<|start|>assistant<|message|>${s.content}<|end|>`:`<|start|>assistant:tool<|message|>${s.toolName}: ${s.inputStr}<|end|>`);return n.length>0?n.join(` +`):null}function Hi(e){let t=[];for(let[r,n]of Object.entries(e)){let s=typeof n=="string"?n:JSON.stringify(n);s=tr(s,100),t.push(`${r}="${s}"`)}return t.join(" ")}function W(e){return!e||typeof e!="string"?"":e.replace(/[\s\S]*?<\/system-reminder>/g,"").replace(/[\s\S]*?<\/supermemory-context>/g,"").trim()}function tr(e,t){return!e||e.length<=t?e:`${e.slice(0,t)}...`}function rr(e){if(!e?.message?.content)return"";let t=e.message.content;if(typeof t=="string")return W(t);if(Array.isArray(t)){let r=[];for(let n of t)n.type==="text"&&n.text&&r.push(W(n.text));return r.join(" ")}return""}function Wi(e){return!e||e.isMeta?!1:rr(e).length>0}function Ti(e){let t=[],r={userEntries:[],assistantEntries:[],allEntries:[]};for(let n=0;n0&&(t.push(r),r={userEntries:[],assistantEntries:[],allEntries:[]}),r.userEntries.push(s),r.allEntries.push(s)):s.type==="assistant"&&(r.assistantEntries.push(s),r.allEntries.push(s))}return r.allEntries.length>0&&t.push(r),t}function Ni(e){let t=[],r={userEntries:[]},n=null,s=()=>{if(r.userEntries.length===0&&!n)return;let o=n?[n]:[],i=[...r.userEntries,...o];t.push({userEntries:r.userEntries,assistantEntries:o,allEntries:i}),r={userEntries:[]},n=null};for(let o=0;oo-i).map(o=>e[o])}function Vi(e){return e.type==="user"?Ri(e.message):e.type==="assistant"?gi(e.message):null}function Ri(e){if(!e?.content)return null;let t=e.content,r=[];if(typeof t=="string"){let n=W(t);n&&r.push(`<|start|>user<|message|>${n}<|end|>`)}else if(Array.isArray(t)){for(let n of t)if(n.type==="text"&&n.text){let s=W(n.text);s&&r.push(`<|start|>user<|message|>${s}<|end|>`)}}return r.length>0?r.join(` +`):null}function gi(e){if(!e?.content)return null;let t=e.content,r=[];if(typeof t=="string"){let n=W(t);n&&r.push(`<|start|>assistant<|message|>${n}<|end|>`)}else if(Array.isArray(t)){for(let n of t)if(n.type==="text"&&n.text){let s=W(n.text);s&&r.push(`<|start|>assistant<|message|>${s}<|end|>`)}}return r.length>0?r.join(` +`):null}function wi(e,t,r){Qe=new Map,_e=cn(r);let n=Xi(r),{keywords:s,turnsBefore:o}=n,i=$t(e);if(i.length===0)return null;let a=Qt(t),l=er(i,a);if(l.length===0)return null;let f=Ni(l);if(f.length===0)return null;let d=ln(f,s);if(d.length===0)return null;let P=pn(f,d,o);if(P.length===0)return null;let z=[];for(let U of P)z.push(...U.allEntries);if(z.length===0)return null;let c=z[0],X=l[l.length-1],g=c.timestamp||new Date().toISOString(),T=[];T.push(`<|turn_start|>${g}`);for(let U of z){let E=Vi(U);E&&T.push(E)}T.push("<|turn_end|>");let H=T.join(` -`);return H.length<100?null:(Qt(t,O.uuid),H)}function wi(e,t,r){Ae=new Map,Qe=fn(r);let n=_t(e);if(n.length===0)return null;let s=At(t),o=$t(n,s);if(o.length===0)return null;let i=o[0],a=o[o.length-1],p=i.timestamp||new Date().toISOString(),f=[];f.push(`<|turn_start|>${p}`);for(let P of o){let m=dn(P);m&&f.push(m)}f.push("<|turn_end|>");let d=f.join(` +`);return H.length<100?null:(_t(t,X.uuid),H)}function Mi(e,t,r){Qe=new Map,_e=cn(r);let n=$t(e);if(n.length===0)return null;let s=Qt(t),o=er(n,s);if(o.length===0)return null;let i=o[0],a=o[o.length-1],l=i.timestamp||new Date().toISOString(),f=[];f.push(`<|turn_start|>${l}`);for(let P of o){let z=vn(P);z&&f.push(z)}f.push("<|turn_end|>");let d=f.join(` -`);return d.length<100?null:(Qt(t,a.uuid),d)}pn.exports={parseTranscript:_t,getEntriesSinceLastCapture:$t,formatEntry:dn,formatNewEntries:wi,formatSignalEntries:gi,cleanContent:W,truncate:er,getLastCapturedUuid:At,setLastCapturedUuid:Qt,getTextFromEntry:tr,groupEntriesIntoTurns:Wi,findSignalTurnIndices:vn,getTurnsAroundSignals:ln}});var mn=u((ka,zn)=>{function Zi(e){let t=e?.status;return t===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":t===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":t===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":t===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof t=="number"&&t>=500?"Supermemory service is temporarily unavailable. Will retry next session.":e?.message||"Unknown error"}function Mi(e){let t=e?.status;return t===429||typeof t=="number"&&t>=500||t==null}function Fi(e){let t=e?.status;return t===404||t==null}zn.exports={getUserFriendlyError:Zi,isRetryableError:Mi,isBenignError:Fi}});var jn=u((Ea,bn)=>{var ce=require("node:fs"),nr=require("node:path"),Di=require("node:os"),_e=nr.join(Di.homedir(),".supermemory-claude"),xn=nr.join(_e,"last-session.json"),rr=nr.join(_e,"last-session-document-id");function Ui(){ce.existsSync(_e)||ce.mkdirSync(_e,{recursive:!0})}function Si({id:e,containerTag:t}){if(!e)return;Ui();let r={id:e,containerTag:t||null,savedAt:new Date().toISOString()};ce.writeFileSync(xn,JSON.stringify(r,null,2));try{ce.existsSync(rr)&&ce.unlinkSync(rr)}catch{}}bn.exports={saveLastSession:Si,LAST_SESSION_FILE:xn,OLD_PLAIN_ID_FILE:rr}});var{SupermemoryClient:Yi,PERSONAL_ENTITY_CONTEXT:Gi}=Mr(),{getContainerTag:ki,getProjectName:Ei}=Cr(),{loadProjectConfig:Ki}=Ge(),{loadSettings:Ii,getApiKey:Ci,getBaseUrl:Ji,debugLog:D,getSignalConfig:Bi}=Jt(),{readStdin:Ai,writeOutput:ue}=an(),{formatNewEntries:Qi,formatSignalEntries:_i}=Pn(),{getUserFriendlyError:$i}=mn(),{saveLastSession:ea}=jn();async function ta(){let e=Ii();try{let t=await Ai(),r=t.cwd||process.cwd(),n=t.session_id,s=t.transcript_path,o=Ki(r);if(D(e,"Stop",{sessionId:n,transcriptPath:s}),!s||!n){D(e,"Missing transcript path or session id"),ue({continue:!0});return}let i;try{i=Ci(e,r,o)}catch{ue({continue:!0});return}let p=Bi(r).enabled;D(e,"Signal extraction",{enabled:p});let f;if(p?(f=_i(s,n,r),D(e,"Signal extraction result",{hasContent:!!f})):f=Qi(s,n,r),!f){D(e,"No new content to save"),ue({continue:!0});return}let d=Ji(r,o),P=new Yi(i,void 0,{baseUrl:d}),m=ki(r),c=Ei(r),O=await P.addMemory(f,m,{type:"session_turn",project:c,timestamp:new Date().toISOString()},{customId:n,entityContext:Gi});O?.id&&ea({id:O.id,containerTag:m}),D(e,"Session turn saved",{length:f.length}),ue({continue:!0})}catch(t){let r=$i(t);D(e,"Error",{error:r}),console.error(`Supermemory: ${r}`),ue({continue:!0})}}ta().catch(e=>{console.error(`Supermemory fatal: ${e.message}`),process.exit(1)}); +`);return d.length<100?null:(_t(t,a.uuid),d)}Pn.exports={parseTranscript:$t,getEntriesSinceLastCapture:er,formatEntry:vn,formatNewEntries:Mi,formatSignalEntries:wi,cleanContent:W,truncate:tr,getLastCapturedUuid:Qt,setLastCapturedUuid:_t,getTextFromEntry:rr,groupEntriesIntoTurns:Ti,findSignalTurnIndices:ln,getTurnsAroundSignals:pn}});var xn=u((Ea,zn)=>{function Zi(e){let t=e?.status;return t===400?"Bad request \u2014 your API key or request format may be invalid. Check your key at https://console.supermemory.ai":t===401?"Authentication failed \u2014 your API key may be expired or revoked. Re-authenticate with the supermemory login command or check https://console.supermemory.ai":t===403?"Permission denied \u2014 this feature may require a different Supermemory plan. Check https://supermemory.ai/pricing":t===429?"Rate limited \u2014 too many requests. Will retry next session.":typeof t=="number"&&t>=500?"Supermemory service is temporarily unavailable. Will retry next session.":e?.message||"Unknown error"}function Fi(e){let t=e?.status;return t===429||typeof t=="number"&&t>=500||t==null}function Di(e){let t=e?.status;return t===404||t==null}zn.exports={getUserFriendlyError:Zi,isRetryableError:Fi,isBenignError:Di}});var On=u((Ka,jn)=>{var ce=require("node:fs"),sr=require("node:path"),Ui=require("node:os"),$e=sr.join(Ui.homedir(),".supermemory-claude"),bn=sr.join($e,"last-session.json"),nr=sr.join($e,"last-session-document-id");function Si(){ce.existsSync($e)||ce.mkdirSync($e,{recursive:!0})}function Yi({id:e,containerTag:t}){if(!e)return;Si();let r={id:e,containerTag:t||null,savedAt:new Date().toISOString()};ce.writeFileSync(bn,JSON.stringify(r,null,2));try{ce.existsSync(nr)&&ce.unlinkSync(nr)}catch{}}jn.exports={saveLastSession:Yi,LAST_SESSION_FILE:bn,OLD_PLAIN_ID_FILE:nr}});var{SupermemoryClient:Gi,PERSONAL_ENTITY_CONTEXT:ki}=Fr(),{getContainerTag:Ei,getProjectName:Ki}=Jr(),{loadProjectConfig:Ii}=Ge(),{loadSettings:Ci,getApiKey:Ji,getBaseUrl:Bi,debugLog:D,getSignalConfig:Ai}=Bt(),{readStdin:Qi,writeOutput:ue}=fn(),{formatNewEntries:_i,formatSignalEntries:$i}=mn(),{getUserFriendlyError:ea}=xn(),{saveLastSession:ta}=On();async function ra(){let e=Ci();try{let t=await Qi(),r=t.cwd||process.cwd(),n=t.session_id,s=t.transcript_path,o=Ii(r);if(D(e,"Stop",{sessionId:n,transcriptPath:s}),!s||!n){D(e,"Missing transcript path or session id"),ue({continue:!0});return}let i;try{i=Ji(e,r,o)}catch{ue({continue:!0});return}let l=Ai(r).enabled;D(e,"Signal extraction",{enabled:l});let f;if(l?(f=$i(s,n,r),D(e,"Signal extraction result",{hasContent:!!f})):f=_i(s,n,r),!f){D(e,"No new content to save"),ue({continue:!0});return}let d=Bi(r,o),P=new Gi(i,void 0,{baseUrl:d}),z=Ei(r),c=Ki(r),X=await P.addMemory(f,z,{type:"session_turn",project:c,timestamp:new Date().toISOString()},{customId:n,entityContext:ki});X?.id&&ta({id:X.id,containerTag:z}),D(e,"Session turn saved",{length:f.length}),ue({continue:!0})}catch(t){let r=ea(t);D(e,"Error",{error:r}),console.error(`Supermemory: ${r}`),ue({continue:!0})}}ra().catch(e=>{console.error(`Supermemory fatal: ${e.message}`),process.exit(1)}); diff --git a/src/lib/stdin.js b/src/lib/stdin.js index 237ca59..14cf6ef 100644 --- a/src/lib/stdin.js +++ b/src/lib/stdin.js @@ -1,19 +1,66 @@ -async function readStdin() { +const DEFAULT_STDIN_TIMEOUT_MS = 3000; + +async function readStdin(timeoutMs = DEFAULT_STDIN_TIMEOUT_MS) { return new Promise((resolve, reject) => { let data = ''; + let settled = false; + let timer = null; + + // On Windows, piped stdin never emits 'end' for hook subprocesses, so we + // must stop stdin from keeping the event loop (and the process) alive + // once we've settled. + const releaseStdin = () => { + try { + process.stdin.pause(); + } catch {} + try { + process.stdin.unref?.(); + } catch {} + }; + + const settle = (fn, value) => { + if (settled) return; + settled = true; + clearTimeout(timer); + releaseStdin(); + fn(value); + }; + + // Hooks receive a single JSON object; resolve as soon as it parses so + // platforms that never emit 'end' don't wait for the timeout. + const tryParse = () => { + if (!data.trim()) return; + try { + const parsed = JSON.parse(data); + settle(resolve, parsed); + } catch { + // Incomplete JSON; keep accumulating chunks. + } + }; + + timer = setTimeout(() => { + settle(resolve, {}); + }, timeoutMs); + process.stdin.setEncoding('utf8'); process.stdin.on('data', (chunk) => { data += chunk; + tryParse(); }); process.stdin.on('end', () => { + if (settled) return; + if (!data.trim()) { + settle(resolve, {}); + return; + } try { - resolve(data.trim() ? JSON.parse(data) : {}); + settle(resolve, JSON.parse(data)); } catch (err) { - reject(new Error(`Failed to parse stdin JSON: ${err.message}`)); + settle(reject, new Error(`Failed to parse stdin JSON: ${err.message}`)); } }); - process.stdin.on('error', reject); - if (process.stdin.isTTY) resolve({}); + process.stdin.on('error', (err) => settle(reject, err)); + if (process.stdin.isTTY) settle(resolve, {}); }); }