diff --git a/package-lock.json b/package-lock.json index a3f6ec2..98d821c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-supermemory-dev", - "version": "1.0.0", + "version": "2.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "claude-supermemory-dev", - "version": "1.0.0", + "version": "2.0.1", "dependencies": { "supermemory": "^4.0.0" }, diff --git a/package.json b/package.json index ab5f853..76686d5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { - "name": "claude-supermemory-dev", - "version": "2.0.1", - "description": "Claude code plugin by Supermemory AI", + "name": "claude-supermemory-local", + "version": "3.0.0-local", + "description": "Claude Code persistent memory plugin — local file storage fork", "private": true, "type": "commonjs", "scripts": { @@ -18,7 +18,5 @@ "@biomejs/biome": "^2.3.13", "esbuild": "^0.25.0" }, - "dependencies": { - "supermemory": "^4.0.0" - } + "dependencies": {} } diff --git a/plugin/scripts/add-memory.cjs b/plugin/scripts/add-memory.cjs index 9815735..d35c781 100755 --- a/plugin/scripts/add-memory.cjs +++ b/plugin/scripts/add-memory.cjs @@ -1,12 +1,8 @@ #!/usr/bin/env node -var Fe=Object.defineProperty;var Mr=Object.getOwnPropertyDescriptor;var Fr=Object.getOwnPropertyNames;var Dr=Object.prototype.hasOwnProperty;var Ur=(e,t)=>()=>(e&&(t=e(e=0)),t);var u=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Yr=(e,t)=>{for(var r in t)Fe(e,r,{get:t[r],enumerable:!0})},Sr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Fr(t))!Dr.call(e,s)&&s!==r&&Fe(e,s,{get:()=>t[s],enumerable:!(n=Mr(t,s))||n.enumerable});return e};var Gr=e=>Sr(Fe({},"__esModule",{value:!0}),e);var Ye=u(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=Kr;h.__classPrivateFieldGet=kr;h.__importStar=Er;h.__exportStar=Ir;function Kr(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 kr(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 Ue=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=Ue;var Dt=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};h.__setModuleDefault=Dt;var De=function(e){return De=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},De(e)};function Er(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=De(e),n=0;n{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.uuid4=void 0;var Cr=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=Cr});var Se=u(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=Jr;function Jr(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var Br=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=Br});var K=u(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 Ar=Se(),se=class extends Error{};P.SupermemoryError=se;var O=class e extends se{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,Ar.castToError)(r)});let o=r;return t===400?new oe(t,o,n,s):t===401?new ae(t,o,n,s):t===403?new fe(t,o,n,s):t===404?new ie(t,o,n,s):t===409?new ce(t,o,n,s):t===422?new ue(t,o,n,s):t===429?new de(t,o,n,s):t>=500?new ve(t,o,n,s):new e(t,o,n,s)}};P.APIError=O;var Ge=class extends O{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};P.APIUserAbortError=Ge;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 Ke=class extends G{constructor({message:t}={}){super({message:t??"Request timed out."})}};P.APIConnectionTimeoutError=Ke;var oe=class extends O{};P.BadRequestError=oe;var ae=class extends O{};P.AuthenticationError=ae;var fe=class extends O{};P.PermissionDeniedError=fe;var ie=class extends O{};P.NotFoundError=ie;var ce=class extends O{};P.ConflictError=ce;var ue=class extends O{};P.UnprocessableEntityError=ue;var de=class extends O{};P.RateLimitError=de;var ve=class extends O{};P.InternalServerError=ve});var E=u(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=en;d.isEmptyObj=tn;d.hasOwn=rn;d.isObj=nn;var k=K(),Qr=/^[a-z][a-z0-9+.-]*:/i,_r=e=>Qr.test(e);d.isAbsoluteURL=_r;var $r=e=>(d.isArray=Array.isArray,(0,d.isArray)(e));d.isArray=$r;d.isReadonlyArray=d.isArray;function en(e){return typeof e!="object"?{}:e??{}}function tn(e){if(!e)return!0;for(let t in e)return!1;return!0}function rn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function nn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var sn=e=>{if(e==null)throw new k.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};d.ensurePresent=sn;var on=(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=on;var an=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=an;var fn=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=fn;var cn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;d.coerceBoolean=cn;var un=e=>{if(e!=null)return(0,d.coerceInteger)(e)};d.maybeCoerceInteger=un;var dn=e=>{if(e!=null)return(0,d.coerceFloat)(e)};d.maybeCoerceFloat=dn;var vn=e=>{if(e!=null)return(0,d.coerceBoolean)(e)};d.maybeCoerceBoolean=vn;var ln=e=>{try{return JSON.parse(e)}catch{return}};d.safeJSON=ln});var Yt=u(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.sleep=void 0;var Pn=e=>new Promise(t=>setTimeout(t,e));le.sleep=Pn});var ke=u(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.VERSION=void 0;Pe.VERSION="4.0.0"});var kt=u(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.getPlatformHeaders=g.isRunningInBrowser=void 0;var I=ke(),pn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";g.isRunningInBrowser=pn;function zn(){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 mn=()=>{let e=zn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":Gt(Deno.build.os),"X-Stainless-Arch":St(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":Gt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":St(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=bn();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 bn(){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 St=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Gt=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,jn=()=>Kt??(Kt=mn());g.getPlatformHeaders=jn});var Ee=u(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=xn;V.makeReadableStream=Et;V.ReadableStreamFrom=Xn;V.ReadableStreamToAsyncIterable=On;V.CancelReadableStream=yn;function xn(){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 Et(...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 Xn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Et({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function On(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 yn(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 It=u(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.FallbackEncoder=void 0;var Hn=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});pe.FallbackEncoder=Hn});var C=u(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=Ie;j.getName=ze;var qn=Ee(),hn=()=>{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=hn;function Ie(e,t,r){return(0,j.checkFileSupport)(),new File(e,t??"unknown_file",r)}function ze(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";j.isAsyncIterable=Wn;var Tn=async(e,t)=>Ce(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=Tn;var Nn=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=Nn;var Ct=new WeakMap;function Ln(e){let t=typeof e=="function"?e:e.fetch,r=Ct.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 Ct.set(t,n),n}var Vn=async(e,t)=>{if(!await Ln(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])=>Je(r,n,s))),r};j.createForm=Vn;var Jt=e=>e instanceof Blob&&"name"in e,Rn=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||Jt(e)),Ce=e=>{if(Rn(e))return!0;if(Array.isArray(e))return e.some(Ce);if(e&&typeof e=="object"){for(let t in e)if(Ce(e[t]))return!0}return!1},Je=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,Ie([await r.blob()],ze(r)));else if((0,j.isAsyncIterable)(r))e.append(t,Ie([await new Response((0,qn.ReadableStreamFrom)(r)).blob()],ze(r)));else if(Jt(r))e.append(t,r,ze(r));else if(Array.isArray(r))await Promise.all(r.map(n=>Je(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>Je(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 At=u(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.toFile=Mn;var J=C(),Zn=C(),Bt=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",gn=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Bt(e),wn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Mn(e,t,r){if((0,Zn.checkFileSupport)(),e=await e,gn(e))return e instanceof File?e:(0,J.makeFile)([await e.arrayBuffer()],e.name);if(wn(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,J.makeFile)(await Be(s),t,r)}let n=await Be(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 Be(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Bt(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 Be(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Fn(e)}`)}return t}function Fn(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var Qe=u(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.toFile=void 0;var Dn=At();Object.defineProperty(me,"toFile",{enumerable:!0,get:function(){return Dn.toFile}})});var w=u(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.APIResource=void 0;var _e=class{constructor(t){this._client=t}};be.APIResource=_e});var B=u(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.isEmptyHeaders=M.buildHeaders=void 0;var Qt=E(),_t=Symbol("brand.privateNullableHeaders");function*$t(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,Qt.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,Qt.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 Un=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,a]of $t(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=Un;var Yn=e=>{for(let t of $t(e))return!1;return!0};M.isEmptyHeaders=Yn});var je=u(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=$e;var Sn=K();function $e(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var er=Object.freeze(Object.create(null)),Gn=(e=$e)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((v,m,X)=>{/[?#]/.test(m)&&(s=!0);let i=n[X],q=(s?encodeURIComponent:e)(""+i);return X!==n.length&&(i==null||typeof i=="object"&&i.toString===Object.getPrototypeOf(Object.getPrototypeOf(i.hasOwnProperty??er)??er)?.toString)&&(q=i+"",o.push({start:v.length+m.length,length:q.length,error:`Value of type ${Object.prototype.toString.call(i).slice(8,-1)} is not a valid path parameter`})),v+m+(X===n.length?"":q)},""),f=a.split(/[?#]/,1)[0],z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=z.exec(f))!==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((v,m)=>v.start-m.start),o.length>0){let v=0,m=o.reduce((X,i)=>{let q=" ".repeat(i.start-v),D="^".repeat(i.length);return v=i.start+i.length,X+q+D},"");throw new Sn.SupermemoryError(`Path parameters result in path with invalid segments: -${o.map(X=>X.error).join(` -`)} -${a} -${m}`)}return a};N.createPathTagFunction=Gn;N.path=(0,N.createPathTagFunction)($e)});var tt=u(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.Connections=void 0;var Kn=w(),kn=B(),W=je(),et=class extends Kn.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,kn.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=et});var st=u(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Documents=void 0;var En=w(),In=B(),Cn=C(),rt=je(),nt=class extends En.APIResource{update(t,r={},n){return this._client.patch((0,rt.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,rt.path)`/v3/documents/${t}`,{...r,headers:(0,In.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,rt.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,Cn.multipartFormRequestOptions)({body:t,...r},this._client))}};Xe.Documents=nt});var ft=u(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Memories=void 0;var Jn=w(),Bn=B(),An=C(),ot=je(),at=class extends Jn.APIResource{update(t,r={},n){return this._client.patch((0,ot.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,ot.path)`/v3/documents/${t}`,{...r,headers:(0,Bn.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,ot.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,An.multipartFormRequestOptions)({body:t,...r},this._client))}};Oe.Memories=at});var ct=u(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Search=void 0;var Qn=w(),it=class extends Qn.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})}};ye.Search=it});var dt=u(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Settings=void 0;var _n=w(),ut=class extends _n.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};He.Settings=ut});var tr=u(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.Settings=H.Search=H.Memories=H.Documents=H.Connections=void 0;var $n=tt();Object.defineProperty(H,"Connections",{enumerable:!0,get:function(){return $n.Connections}});var es=st();Object.defineProperty(H,"Documents",{enumerable:!0,get:function(){return es.Documents}});var ts=ft();Object.defineProperty(H,"Memories",{enumerable:!0,get:function(){return ts.Memories}});var rs=ct();Object.defineProperty(H,"Search",{enumerable:!0,get:function(){return rs.Search}});var ns=dt();Object.defineProperty(H,"Settings",{enumerable:!0,get:function(){return ns.Settings}})});var vt=u(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=nr;var ss=E(),he={off:0,error:200,warn:300,info:400,debug:500},os=(e,t,r)=>{if(e){if((0,ss.hasOwn)(he,e))return e;nr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(he))}`)}};R.parseLogLevel=os;function A(){}function qe(e,t,r){return!t||he[e]>he[r]?A:t[e].bind(t)}var as={error:A,warn:A,info:A,debug:A},rr=new WeakMap;function nr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return as;let n=rr.get(t);if(n&&n[0]===r)return n[1];let s={error:qe("error",t,r),warn:qe("warn",t,r),info:qe("info",t,r),debug:qe("debug",t,r)};return rr.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);R.formatRequestDetails=fs});var or=u(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.defaultParseResponse=is;var sr=vt();async function is(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,sr.loggerFor)(e).debug(`[${n}] response parsed`,(0,sr.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var zt=u(We=>{"use strict";var Q;Object.defineProperty(We,"__esModule",{value:!0});We.APIPromise=void 0;var Pt=Ye(),cs=or(),pt=class e extends Promise{constructor(t,r,n=cs.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,Q.set(this,void 0),Pt.__classPrivateFieldSet(this,Q,t,"f")}_thenUnwrap(t){return new e(Pt.__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(Pt.__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)}};We.APIPromise=pt;Q=new WeakMap});var ar=u(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.readEnv=void 0;var us=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()};Te.readEnv=us});var Ht=u(Le=>{"use strict";var Ot,yt,Ne,fr;Object.defineProperty(Le,"__esModule",{value:!0});Le.Supermemory=void 0;var L=Ye(),ds=Ut(),mt=E(),vs=Yt(),bt=Se(),ls=kt(),jt=L.__importStar(Ee()),Ps=L.__importStar(It()),ps=ke(),b=L.__importStar(K()),zs=L.__importStar(Qe()),_=L.__importStar(tr()),ms=zt(),bs=tt(),js=st(),xs=ft(),Xs=ct(),Os=dt(),xt=B(),Xt=ar(),x=vt(),ys=E(),p=class{constructor({baseURL:t=(0,Xt.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Xt.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Ot.add(this),Ne.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??yt.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,Xt.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??jt.getDefaultFetch(),L.__classPrivateFieldSet(this,Ne,Ps.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,xt.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 ${ps.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,ds.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,Ot,"m",fr).call(this)&&n||this.baseURL,o=(0,mt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,ys.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 ms.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 l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),v=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if((0,x.loggerFor)(this).debug(`[${l}] sending request`,(0,x.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(bt.castToError),q=Date.now();if(i instanceof globalThis.Error){let U=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let T=(0,bt.isAbortError)(i)||/timed? ?out/i.test(String(i)+("cause"in i?String(i.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:f,durationMs:q-m,message:i.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:f,durationMs:q-m,message:i.message})),T?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:i})}let D=`[${l}${v}] ${a.method} ${f} ${i.ok?"succeeded":"failed"} with status ${i.status} in ${q-m}ms`;if(!i.ok){let U=await this.shouldRetry(i);if(r&&U){let ne=`retrying, ${r} attempts remaining`;return await jt.CancelReadableStream(i.body),(0,x.loggerFor)(this).info(`${D} - ${ne}`),(0,x.loggerFor)(this).debug(`[${l}] response error (${ne})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:q-m})),this.retryRequest(s,r,n??l,i.headers)}let T=U?"error; no more retries left":"error; not retryable";(0,x.loggerFor)(this).info(`${D} - ${T}`);let wt=await i.text().catch(ne=>(0,bt.castToError)(ne).message),Mt=(0,mt.safeJSON)(wt),Ft=Mt?void 0:wt;throw(0,x.loggerFor)(this).debug(`[${l}] response error (${T})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,message:Ft,durationMs:Date.now()-m})),this.makeStatusError(i.status,Mt,Ft,i.headers)}return(0,x.loggerFor)(this).info(D),(0,x.loggerFor)(this).debug(`[${l}] response start`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:q-m})),{response:i,options:s,controller:X,requestLogID:l,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),l=globalThis.ReadableStream&&f.body instanceof globalThis.ReadableStream||typeof f.body=="object"&&f.body!==null&&Symbol.asyncIterator in f.body,v={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...f};a&&(v.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,v)}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,vs.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,mt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:v}=this.buildBody({options:n}),m=await this.buildHeaders({options:t,method:s,bodyHeaders:l,retryCount:r});return{req:{method:s,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&v instanceof globalThis.ReadableStream&&{duplex:"half"},...v&&{body:v},...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,xt.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,ls.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,xt.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:jt.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Ne,"f").call(this,{body:t,headers:n})}};Le.Supermemory=p;yt=p,Ne=new WeakMap,Ot=new WeakSet,fr=function(){return this.baseURL!=="https://api.supermemory.ai"};p.Supermemory=yt;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=zs.toFile;p.Memories=xs.Memories;p.Documents=js.Documents;p.Search=Xs.Search;p.Settings=Os.Settings;p.Connections=bs.Connections});var cr=u((c,ir)=>{"use strict";c=ir.exports=function(...e){return new c.default(...e)};Object.defineProperty(c,"__esModule",{value:!0});c.UnprocessableEntityError=c.PermissionDeniedError=c.InternalServerError=c.AuthenticationError=c.BadRequestError=c.RateLimitError=c.ConflictError=c.NotFoundError=c.APIUserAbortError=c.APIConnectionTimeoutError=c.APIConnectionError=c.APIError=c.SupermemoryError=c.Supermemory=c.APIPromise=c.toFile=c.default=void 0;var Hs=Ht();Object.defineProperty(c,"default",{enumerable:!0,get:function(){return Hs.Supermemory}});var qs=Qe();Object.defineProperty(c,"toFile",{enumerable:!0,get:function(){return qs.toFile}});var hs=zt();Object.defineProperty(c,"APIPromise",{enumerable:!0,get:function(){return hs.APIPromise}});var Ws=Ht();Object.defineProperty(c,"Supermemory",{enumerable:!0,get:function(){return Ws.Supermemory}});var y=K();Object.defineProperty(c,"SupermemoryError",{enumerable:!0,get:function(){return y.SupermemoryError}});Object.defineProperty(c,"APIError",{enumerable:!0,get:function(){return y.APIError}});Object.defineProperty(c,"APIConnectionError",{enumerable:!0,get:function(){return y.APIConnectionError}});Object.defineProperty(c,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return y.APIConnectionTimeoutError}});Object.defineProperty(c,"APIUserAbortError",{enumerable:!0,get:function(){return y.APIUserAbortError}});Object.defineProperty(c,"NotFoundError",{enumerable:!0,get:function(){return y.NotFoundError}});Object.defineProperty(c,"ConflictError",{enumerable:!0,get:function(){return y.ConflictError}});Object.defineProperty(c,"RateLimitError",{enumerable:!0,get:function(){return y.RateLimitError}});Object.defineProperty(c,"BadRequestError",{enumerable:!0,get:function(){return y.BadRequestError}});Object.defineProperty(c,"AuthenticationError",{enumerable:!0,get:function(){return y.AuthenticationError}});Object.defineProperty(c,"InternalServerError",{enumerable:!0,get:function(){return y.InternalServerError}});Object.defineProperty(c,"PermissionDeniedError",{enumerable:!0,get:function(){return y.PermissionDeniedError}});Object.defineProperty(c,"UnprocessableEntityError",{enumerable:!0,get:function(){return y.UnprocessableEntityError}})});var dr={};Yr(dr,{getRequestIntegrity:()=>Ys,sanitizeContent:()=>Vs,sanitizeMetadata:()=>Ms,validateApiKeyFormat:()=>Ts,validateContainerTag:()=>Ns,validateContentLength:()=>Rs,validateRecallConfig:()=>Fs});function Ts(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 Ns(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 Vs(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Ls)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function Rs(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Ms(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=Zs)break;n.length>gs||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,ws),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function Fs(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 qt(e){return(0,Ve.createHash)("sha256").update(e).digest("hex")}function Us(e,t){let r=[qt(e),qt(t),ur].join(":");return(0,Ve.createHmac)("sha256",Ds).update(r).digest("base64url")}function Ys(e,t){let r=qt(t),n=Us(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${ur}`,n].join(".")}}var Ve,Ls,Zs,gs,ws,ur,Ds,vr=Ur(()=>{Ve=require("node:crypto");Ls=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Zs=50,gs=128,ws=1024;ur=1,Ds="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Pr=u((ia,lr)=>{var Ss=cr().default,{getRequestIntegrity:Gs,validateApiKeyFormat:Ks,validateContainerTag:ks}=(vr(),Gr(dr)),Es="claudecode_default",Is=process.env.SUPERMEMORY_API_URL||"https://api.supermemory.ai";function Cs(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 Js=`Developer coding session transcript. Focus on USER message and intent. +var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var D=R((pe,A)=>{var g=require("node:fs"),T=require("node:path"),J=require("node:os"),X=require("node:crypto"),z=T.join(J.homedir(),".supermemory-claude","memories"),W=`Developer coding session transcript. Focus on USER message and intent. RULES: -- Extract USER's action/intent, not every detail assistant provides matter +- Extract USER's action/intent, not every detail assistant provides - Condense assistant responses into what user gained from it - Skip granular facts from assistant output @@ -17,86 +13,13 @@ EXTRACT: - Decisions: "chose SQLite for local storage" - Learnings: "learned about React Server Components" -EXAMPLES: -| Transcript | Memory | -| [role:user] research about the whisper.cpp -> https://github.com/ggml-org/whisper.cpp/blob/master/src/whisper.cpp [user:end]| " starts research about whisper.cpp" | -| [role:assistant] ## whisper.cpp Architecture Summary - This is highly relevant for your parakeet.cpp implementation. Here are the key patterns: - ### Core Architecture - **Two-level context design:** - - whisper_context - holds model weights, vocab, hyperparameters (persistent) - - whisper_state - runtime state, KV caches, backends (can have multiple per context) [assistant:end] | "Assistant did a deep dive on whisper architecture" | -| [role:user] Can we explain what we are currently doing in this repository? [user:end] | "" | - SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,Bs=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,Y=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" - Conventions: "components in PascalCase", "hooks prefixed with use" - Patterns: "all API routes use withAuth wrapper", "errors thrown as ApiError" - Setup: "requires .env with DATABASE_URL", "run pnpm db:migrate first" -- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching" - -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]" |`,ht=class{constructor(t,r){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let n=Ks(t);if(!n.valid)throw new Error(`Invalid API key: ${n.reason}`);let s=r||Es,o=ks(s);o.valid||console.warn(`Container tag warning: ${o.reason}`);let a=Gs(t,s);this.client=new Ss({apiKey:t,baseURL:Is,defaultHeaders:a}),this.containerTag=s}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code-plugin",...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:Cs(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,v=m=>m)=>l.filter(m=>{let X=String(v(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 l=n.searchResults.results.map(v=>({id:v.id,memory:v.content||v.context||"",similarity:v.similarity,title:v.title,updatedAt:v.updatedAt}));z={results:o(l,v=>v.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:f},searchResults:z}}};lr.exports={SupermemoryClient:ht,PERSONAL_ENTITY_CONTEXT:Js,REPO_ENTITY_CONTEXT:Bs}});var Wt=u((ca,pr)=>{var{execSync:Re}=require("node:child_process"),$=require("node:path");function As(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return Re("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=Re("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return Re("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):Re("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}pr.exports={getGitRoot:As}});var Tt=u((ua,Xr)=>{var ee=require("node:fs"),Ze=require("node:path"),{getGitRoot:zr}=Wt(),mr=Ze.join(".claude",".supermemory-claude"),br="config.json";function jr(e){let r=zr(e)||e;return Ze.join(r,mr,br)}function xr(e){try{let t=jr(e);if(ee.existsSync(t))return JSON.parse(ee.readFileSync(t,"utf-8"))}catch{}return null}function Qs(e,t){let n=zr(e)||e,s=Ze.join(n,mr),o=Ze.join(s,br);ee.existsSync(s)||ee.mkdirSync(s,{recursive:!0});let f={...xr(e)||{},...t};return ee.writeFileSync(o,JSON.stringify(f,null,2)),o}Xr.exports={getConfigPath:jr,loadProjectConfig:xr,saveProjectConfig:Qs}});var qr=u((da,Hr)=>{var{execSync:_s}=require("node:child_process"),$s=require("node:crypto"),{loadProjectConfig:Or}=Tt(),{getGitRoot:ge}=Wt();function yr(e){return $s.createHash("sha256").update(e).digest("hex").slice(0,16)}function Nt(e){try{let r=_s("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 eo(e){let t=Or(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=ge(e)||e;return`claudecode_project_${yr(n)}`}function to(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function ro(e){let t=Or(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=ge(e)||e,o=Nt(n)||n.split("/").pop()||"unknown";return`repo_${to(o)}`}function no(e){let r=ge(e)||e;return Nt(r)||r.split("/").pop()||"unknown"}Hr.exports={sha256:yr,getGitRoot:ge,getGitRepoName:Nt,getContainerTag:eo,getRepoContainerTag:ro,getProjectName:no}});var hr=u((va,so)=>{so.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var Wr=u((la,oo)=>{oo.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var Rr=u((Pa,Vr)=>{var ao=require("node:http"),Z=require("node:fs"),Tr=require("node:path"),fo=require("node:os"),{execFile:Lt}=require("node:child_process"),io=hr(),co=Wr(),Rt=Tr.join(fo.homedir(),".supermemory-claude"),F=Tr.join(Rt,"credentials.json"),Nr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",Vt=19876,uo=25e3;function vo(){Z.existsSync(Rt)||Z.mkdirSync(Rt,{recursive:!0})}function lo(){try{if(Z.existsSync(F)){let e=JSON.parse(Z.readFileSync(F,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Lr(e){vo();let t={apiKey:e,savedAt:new Date().toISOString()};Z.writeFileSync(F,JSON.stringify(t,null,2))}function Po(){try{Z.existsSync(F)&&Z.unlinkSync(F)}catch{}}function po(e){let t=r=>{r&&console.warn("Failed to open browser:",r.message)};process.platform==="win32"?Lt("explorer.exe",[e],t):process.platform==="darwin"?Lt("open",[e],t):Lt("xdg-open",[e],t)}function zo(){return new Promise((e,t)=>{let r=!1,n=ao.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${Vt}`);if(a.pathname==="/callback"){let f=a.searchParams.get("apikey")||a.searchParams.get("api_key");f?.startsWith("sm_")?(Lr(f),o.writeHead(200,{"Content-Type":"text/html"}),o.end(io),r=!0,n.close(),e(f)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(co))}else o.writeHead(404),o.end("Not found")});n.listen(Vt,"127.0.0.1",()=>{let s=`http://localhost:${Vt}/callback`,o=`${Nr}?callback=${encodeURIComponent(s)}&client=claude_code`;po(o)}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},uo)})}Vr.exports={AUTH_BASE_URL:Nr,CREDENTIALS_FILE:F,loadCredentials:lo,saveCredentials:Lr,clearCredentials:Po,startAuthFlow:zo}});var wr=u((pa,gr)=>{var re=require("node:fs"),Zr=require("node:path"),mo=require("node:os"),{loadCredentials:bo}=Rr(),{loadProjectConfig:Zt}=Tt(),we=Zr.join(mo.homedir(),".supermemory-claude"),te=Zr.join(we,"settings.json"),Me={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function jo(){re.existsSync(we)||re.mkdirSync(we,{recursive:!0})}function gt(){let e={...Me};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 xo(e){jo();let t={...e};delete t.apiKey,re.writeFileSync(te,JSON.stringify(t,null,2))}function Xo(e,t){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;let r=Zt(t||process.cwd());if(r?.apiKey)return r.apiKey;let n=bo();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function Oo(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function yo(e){let t=gt(),r=Zt(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Ho(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function qo(e){let t=gt(),r=Zt(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Me.signalKeywords,f=r?.signalKeywords||[],z=[...new Set([...a,...f])].map(v=>v.toLowerCase()),l=r?.signalTurnsBefore||t.signalTurnsBefore||Me.signalTurnsBefore;return{enabled:o,keywords:z,turnsBefore:l}}gr.exports={SETTINGS_DIR:we,SETTINGS_FILE:te,DEFAULT_SETTINGS:Me,loadSettings:gt,saveSettings:xo,getApiKey:Xo,debugLog:Oo,getIncludeTools:yo,shouldIncludeTool:Ho,getSignalConfig:qo}});var{SupermemoryClient:ho,PERSONAL_ENTITY_CONTEXT:Wo}=Pr(),{getContainerTag:To,getProjectName:No}=qr(),{loadSettings:Lo,getApiKey:Vo}=wr();async function Ro(){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=Lo(),r;try{r=Vo(t)}catch{console.log("Supermemory API key not configured."),console.log("Set SUPERMEMORY_CC_API_KEY environment variable.");return}let n=process.cwd(),s=To(n),o=No(n);try{let f=await new ho(r,s).addMemory(e,s,{type:"manual",project:o,timestamp:new Date().toISOString()},{entityContext:Wo});console.log(`Memory saved to project: ${o}`),console.log(`ID: ${f.id}`)}catch(a){console.log(`Error saving memory: ${a.message}`)}}Ro().catch(e=>{console.error(`Fatal error: ${e.message}`),process.exit(1)}); +- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching"`;function B(e){g.existsSync(e)||g.mkdirSync(e,{recursive:!0})}function m(e,t){return T.join(z,e,t)}function S(e){if(!g.existsSync(e))return[];let t=g.readdirSync(e).filter(o=>o.endsWith(".json")),n=[];for(let o of t)try{let r=g.readFileSync(T.join(e,o),"utf-8");n.push(JSON.parse(r))}catch{}return n}function K(e,t){let n=(e.content||"").toLowerCase(),o=0;for(let a of t)n.includes(a)&&(o+=1);let r=Date.now()-new Date(e.createdAt||0).getTime(),s=Math.max(0,1-r/(720*60*60*1e3));return o+s*.5}var j=class{constructor(t){this.containerTag=t||"default"}async addMemory(t,n,o={}){let r=n||this.containerTag,s=o.type==="project-knowledge"?"repo":"personal",a=m(s,r);B(a);let c=X.randomUUID(),l={id:c,content:t,metadata:{sm_source:"claude-code-local",...o},createdAt:new Date().toISOString()};return g.writeFileSync(T.join(a,`${c}.json`),JSON.stringify(l,null,2)),{id:c,status:"saved",containerTag:r}}async search(t,n,o={}){let r=n||this.containerTag,s=o.limit||10,a=m("personal",r),c=m("repo",r),l=[...S(a),...S(c)];if(l.length===0)return{results:[],total:0};let u=t.toLowerCase().split(/\s+/).filter(i=>i.length>2),h=l.map(i=>({memory:i.content||"",metadata:i.metadata,updatedAt:i.createdAt,similarity:u.length>0?K(i,u)/u.length:0})).filter(i=>i.similarity>0).sort((i,y)=>y.similarity-i.similarity).slice(0,s);return{results:h,total:h.length}}async getProfile(t,n,o=5){let r=t||this.containerTag,s=m("personal",r),a=m("repo",r),c=S(s),l=S(a),u=(p,G)=>new Date(G.createdAt||0).getTime()-new Date(p.createdAt||0).getTime();c.sort(u),l.sort(u);let h=l.slice(0,o).map(p=>p.content),i=c.slice(0,o).map(p=>p.content),y=[...c,...l].sort(u).slice(0,o),U={results:y.map(p=>({id:p.id,memory:p.content,similarity:1,updatedAt:p.createdAt})),total:y.length};return{profile:{static:h,dynamic:i},searchResults:U}}};A.exports={LocalMemoryClient:j,PERSONAL_ENTITY_CONTEXT:W,REPO_ENTITY_CONTEXT:Y}});var P=R((le,w)=>{var{execSync:C}=require("node:child_process"),f=require("node:path");function H(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return C("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=C("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n===".git")return C("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let o=f.resolve(e,n);return f.basename(o)===".git"&&!o.includes(`${f.sep}.git${f.sep}`)?f.dirname(o):C("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}w.exports={getGitRoot:H}});var k=R((ue,M)=>{var d=require("node:fs"),v=require("node:path"),{getGitRoot:_}=P(),O=v.join(".claude",".supermemory-claude"),q="config.json";function x(e){let n=_(e)||e;return v.join(n,O,q)}function I(e){try{let t=x(e);if(d.existsSync(t))return JSON.parse(d.readFileSync(t,"utf-8"))}catch{}return null}function Q(e,t){let o=_(e)||e,r=v.join(o,O),s=v.join(r,q);d.existsSync(r)||d.mkdirSync(r,{recursive:!0});let c={...I(e)||{},...t};return d.writeFileSync(s,JSON.stringify(c,null,2)),s}M.exports={getConfigPath:x,loadProjectConfig:I,saveProjectConfig:Q}});var $=R((ge,L)=>{var{execSync:V}=require("node:child_process"),Z=require("node:crypto"),{loadProjectConfig:b}=k(),{getGitRoot:E}=P();function F(e){return Z.createHash("sha256").update(e).digest("hex").slice(0,16)}function N(e){try{let n=V("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 ee(e){let t=b(e);if(t?.personalContainerTag)return t.personalContainerTag;let o=E(e)||e;return`claudecode_project_${F(o)}`}function te(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function oe(e){let t=b(e);if(t?.repoContainerTag)return t.repoContainerTag;let o=E(e)||e,s=N(o)||o.split("/").pop()||"unknown";return`repo_${te(s)}`}function ne(e){let n=E(e)||e;return N(n)||n.split("/").pop()||"unknown"}L.exports={sha256:F,getGitRoot:E,getGitRepoName:N,getContainerTag:ee,getRepoContainerTag:oe,getProjectName:ne}});var{LocalMemoryClient:re,PERSONAL_ENTITY_CONTEXT:me}=D(),{getContainerTag:se,getProjectName:ie}=$();async function ce(){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=process.cwd(),n=se(t),o=ie(t);try{let s=await new re(n).addMemory(e,n,{type:"manual",project:o,timestamp:new Date().toISOString()});console.log(`Memory saved to project: ${o}`),console.log(`ID: ${s.id}`)}catch(r){console.log(`Error saving memory: ${r.message}`)}}ce().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 a99c260..87dd20f 100755 --- a/plugin/scripts/context-hook.cjs +++ b/plugin/scripts/context-hook.cjs @@ -1,12 +1,8 @@ #!/usr/bin/env node -var Ye=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Br=Object.prototype.hasOwnProperty;var Ar=(e,t)=>()=>(e&&(t=e(e=0)),t);var u=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Qr=(e,t)=>{for(var r in t)Ye(e,r,{get:t[r],enumerable:!0})},_r=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Jr(t))!Br.call(e,s)&&s!==r&&Ye(e,s,{get:()=>t[s],enumerable:!(n=Ir(t,s))||n.enumerable});return e};var $r=e=>_r(Ye({},"__esModule",{value:!0}),e);var ke=u(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=en;h.__classPrivateFieldGet=tn;h.__importStar=rn;h.__exportStar=nn;function en(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 tn(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 Ge=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=Ge;var kt=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};h.__setModuleDefault=kt;var Se=function(e){return Se=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Se(e)};function rn(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Se(e),n=0;n{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.uuid4=void 0;var sn=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return S.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))};S.uuid4=sn});var Ke=u(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.castToError=void 0;G.isAbortError=on;function on(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var an=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)};G.castToError=an});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 fn=Ke(),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 k({message:n,cause:(0,fn.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 Ee=class extends y{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};z.APIUserAbortError=Ee;var k=class extends y{constructor({message:t,cause:r}){super(void 0,void 0,t||"Connection error.",void 0),r&&(this.cause=r)}};z.APIConnectionError=k;var Ce=class extends k{constructor({message:t}={}){super({message:t??"Request timed out."})}};z.APIConnectionTimeoutError=Ce;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 C=u(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.safeJSON=v.maybeCoerceBoolean=v.maybeCoerceFloat=v.maybeCoerceInteger=v.coerceBoolean=v.coerceFloat=v.coerceInteger=v.validatePositiveInteger=v.ensurePresent=v.isReadonlyArray=v.isArray=v.isAbsoluteURL=void 0;v.maybeObj=vn;v.isEmptyObj=ln;v.hasOwn=pn;v.isObj=Pn;var E=K(),cn=/^[a-z][a-z0-9+.-]*:/i,un=e=>cn.test(e);v.isAbsoluteURL=un;var dn=e=>(v.isArray=Array.isArray,(0,v.isArray)(e));v.isArray=dn;v.isReadonlyArray=v.isArray;function vn(e){return typeof e!="object"?{}:e??{}}function ln(e){if(!e)return!0;for(let t in e)return!1;return!0}function pn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Pn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var zn=e=>{if(e==null)throw new E.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};v.ensurePresent=zn;var mn=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new E.SupermemoryError(`${e} must be an integer`);if(t<0)throw new E.SupermemoryError(`${e} must be a positive integer`);return t};v.validatePositiveInteger=mn;var bn=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new E.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};v.coerceInteger=bn;var xn=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new E.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};v.coerceFloat=xn;var jn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;v.coerceBoolean=jn;var Xn=e=>{if(e!=null)return(0,v.coerceInteger)(e)};v.maybeCoerceInteger=Xn;var On=e=>{if(e!=null)return(0,v.coerceFloat)(e)};v.maybeCoerceFloat=On;var yn=e=>{if(e!=null)return(0,v.coerceBoolean)(e)};v.maybeCoerceBoolean=yn;var Hn=e=>{try{return JSON.parse(e)}catch{return}};v.safeJSON=Hn});var Et=u(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.sleep=void 0;var qn=e=>new Promise(t=>setTimeout(t,e));pe.sleep=qn});var Ie=u(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.VERSION=void 0;Pe.VERSION="4.0.0"});var Bt=u(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.getPlatformHeaders=Z.isRunningInBrowser=void 0;var I=Ie(),hn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Z.isRunningInBrowser=hn;function Wn(){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 Tn=()=>{let e=Wn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":It(Deno.build.os),"X-Stainless-Arch":Ct(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":It(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ct(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Nn();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 Nn(){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 Ct=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",It=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"),Jt,Ln=()=>Jt??(Jt=Tn());Z.getPlatformHeaders=Ln});var Je=u(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=Vn;V.makeReadableStream=At;V.ReadableStreamFrom=Rn;V.ReadableStreamToAsyncIterable=gn;V.CancelReadableStream=wn;function Vn(){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 At(...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 Rn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return At({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function gn(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 wn(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 Qt=u(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.FallbackEncoder=void 0;var Zn=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});ze.FallbackEncoder=Zn});var J=u(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=Be;j.getName=me;var Mn=Je(),Fn=()=>{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=Fn;function Be(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 Dn=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";j.isAsyncIterable=Dn;var Un=async(e,t)=>Ae(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=Un;var Yn=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=Yn;var _t=new WeakMap;function Sn(e){let t=typeof e=="function"?e:e.fetch,r=_t.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 _t.set(t,n),n}var Gn=async(e,t)=>{if(!await Sn(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])=>Qe(r,n,s))),r};j.createForm=Gn;var $t=e=>e instanceof Blob&&"name"in e,kn=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||$t(e)),Ae=e=>{if(kn(e))return!0;if(Array.isArray(e))return e.some(Ae);if(e&&typeof e=="object"){for(let t in e)if(Ae(e[t]))return!0}return!1},Qe=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,Be([await r.blob()],me(r)));else if((0,j.isAsyncIterable)(r))e.append(t,Be([await new Response((0,Mn.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=>Qe(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>Qe(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 tr=u($e=>{"use strict";Object.defineProperty($e,"__esModule",{value:!0});$e.toFile=In;var B=J(),Kn=J(),er=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",En=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&er(e),Cn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function In(e,t,r){if((0,Kn.checkFileSupport)(),e=await e,En(e))return e instanceof File?e:(0,B.makeFile)([await e.arrayBuffer()],e.name);if(Cn(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,B.makeFile)(await _e(s),t,r)}let n=await _e(e);if(t||(t=(0,B.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,B.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(er(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,B.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}`:""}${Jn(e)}`)}return t}function Jn(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var et=u(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.toFile=void 0;var Bn=tr();Object.defineProperty(be,"toFile",{enumerable:!0,get:function(){return Bn.toFile}})});var M=u(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.APIResource=void 0;var tt=class{constructor(t){this._client=t}};xe.APIResource=tt});var A=u(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.isEmptyHeaders=F.buildHeaders=void 0;var rr=C(),nr=Symbol("brand.privateNullableHeaders");function*sr(e){if(!e)return;if(nr 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,rr.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,rr.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 An=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,a]of sr(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{[nr]:!0,values:t,nulls:r}};F.buildHeaders=An;var Qn=e=>{for(let t of sr(e))return!1;return!0};F.isEmptyHeaders=Qn});var je=u(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=rt;var _n=K();function rt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var or=Object.freeze(Object.create(null)),$n=(e=rt)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((c,l,b)=>{/[?#]/.test(l)&&(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??or)??or)?.toString)&&(O=f+"",o.push({start:c.length+l.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),c+l+(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((c,l)=>c.start-l.start),o.length>0){let c=0,l=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: -${o.map(b=>b.error).join(` -`)} -${a} -${l}`)}return a};N.createPathTagFunction=$n;N.path=(0,N.createPathTagFunction)(rt)});var st=u(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Connections=void 0;var es=M(),ts=A(),W=je(),nt=class extends es.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,ts.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=nt});var it=u(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Documents=void 0;var rs=M(),ns=A(),ss=J(),ot=je(),at=class extends rs.APIResource{update(t,r={},n){return this._client.patch((0,ot.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,ot.path)`/v3/documents/${t}`,{...r,headers:(0,ns.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,ot.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,ss.multipartFormRequestOptions)({body:t,...r},this._client))}};Oe.Documents=at});var ut=u(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Memories=void 0;var os=M(),as=A(),is=J(),ft=je(),ct=class extends os.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,as.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,ft.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,is.multipartFormRequestOptions)({body:t,...r},this._client))}};ye.Memories=ct});var vt=u(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Search=void 0;var fs=M(),dt=class extends fs.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})}};He.Search=dt});var pt=u(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Settings=void 0;var cs=M(),lt=class extends cs.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};qe.Settings=lt});var ar=u(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.Settings=q.Search=q.Memories=q.Documents=q.Connections=void 0;var us=st();Object.defineProperty(q,"Connections",{enumerable:!0,get:function(){return us.Connections}});var ds=it();Object.defineProperty(q,"Documents",{enumerable:!0,get:function(){return ds.Documents}});var vs=ut();Object.defineProperty(q,"Memories",{enumerable:!0,get:function(){return vs.Memories}});var ls=vt();Object.defineProperty(q,"Search",{enumerable:!0,get:function(){return ls.Search}});var ps=pt();Object.defineProperty(q,"Settings",{enumerable:!0,get:function(){return ps.Settings}})});var Pt=u(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=fr;var Ps=C(),We={off:0,error:200,warn:300,info:400,debug:500},zs=(e,t,r)=>{if(e){if((0,Ps.hasOwn)(We,e))return e;fr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(We))}`)}};R.parseLogLevel=zs;function Q(){}function he(e,t,r){return!t||We[e]>We[r]?Q:t[e].bind(t)}var ms={error:Q,warn:Q,info:Q,debug:Q},ir=new WeakMap;function fr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return ms;let n=ir.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 ir.set(t,[r,s]),s}var bs=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=bs});var ur=u(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.defaultParseResponse=xs;var cr=Pt();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,cr.loggerFor)(e).debug(`[${n}] response parsed`,(0,cr.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var xt=u(Te=>{"use strict";var _;Object.defineProperty(Te,"__esModule",{value:!0});Te.APIPromise=void 0;var mt=ke(),js=ur(),bt=class e extends Promise{constructor(t,r,n=js.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,_.set(this,void 0),mt.__classPrivateFieldSet(this,_,t,"f")}_thenUnwrap(t){return new e(mt.__classPrivateFieldGet(this,_,"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(mt.__classPrivateFieldGet(this,_,"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=bt;_=new WeakMap});var dr=u(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.readEnv=void 0;var Xs=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=Xs});var Wt=u(Ve=>{"use strict";var qt,ht,Le,vr;Object.defineProperty(Ve,"__esModule",{value:!0});Ve.Supermemory=void 0;var L=ke(),Os=Kt(),jt=C(),ys=Et(),Xt=Ke(),Hs=Bt(),Ot=L.__importStar(Je()),qs=L.__importStar(Qt()),hs=Ie(),x=L.__importStar(K()),Ws=L.__importStar(et()),$=L.__importStar(ar()),Ts=xt(),Ns=st(),Ls=it(),Vs=ut(),Rs=vt(),gs=pt(),yt=A(),Ht=dr(),X=Pt(),ws=C(),m=class{constructor({baseURL:t=(0,Ht.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Ht.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(qt.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??ht.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??Ot.getDefaultFetch(),L.__classPrivateFieldSet(this,Le,qs.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,yt.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 ${hs.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,Os.uuid4)()}`}makeStatusError(t,r,n,s){return x.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,qt,"m",vr).call(this)&&n||this.baseURL,o=(0,jt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,ws.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 Ts.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"),c=n===void 0?"":`, retryOf: ${n}`,l=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,f=await this.fetchWithTimeout(i,a,P,b).catch(Xt.castToError),O=Date.now();if(f instanceof globalThis.Error){let Y=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new x.APIUserAbortError;let T=(0,Xt.isAbortError)(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(r)return(0,X.loggerFor)(this).info(`[${p}] connection ${T?"timed out":"failed"} - ${Y}`),(0,X.loggerFor)(this).debug(`[${p}] connection ${T?"timed out":"failed"} (${Y})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:O-l,message:f.message})),this.retryRequest(s,r,n??p);throw(0,X.loggerFor)(this).info(`[${p}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,X.loggerFor)(this).debug(`[${p}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:O-l,message:f.message})),T?new x.APIConnectionTimeoutError:new x.APIConnectionError({cause:f})}let w=`[${p}${c}] ${a.method} ${i} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${O-l}ms`;if(!f.ok){let Y=await this.shouldRetry(f);if(r&&Y){let se=`retrying, ${r} attempts remaining`;return await Ot.CancelReadableStream(f.body),(0,X.loggerFor)(this).info(`${w} - ${se}`),(0,X.loggerFor)(this).debug(`[${p}] response error (${se})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:O-l})),this.retryRequest(s,r,n??p,f.headers)}let T=Y?"error; no more retries left":"error; not retryable";(0,X.loggerFor)(this).info(`${w} - ${T}`);let Yt=await f.text().catch(se=>(0,Xt.castToError)(se).message),St=(0,jt.safeJSON)(Yt),Gt=St?void 0:Yt;throw(0,X.loggerFor)(this).debug(`[${p}] response error (${T})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:Gt,durationMs:Date.now()-l})),this.makeStatusError(f.status,St,Gt,f.headers)}return(0,X.loggerFor)(this).info(w),(0,X.loggerFor)(this).debug(`[${p}] response start`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:O-l})),{response:f,options:s,controller:b,requestLogID:p,retryOfRequestLogID:n,startTime:l}}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,c={signal:s.signal,...p?{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,ys.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,jt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:p,body:c}=this.buildBody({options:n}),l=await this.buildHeaders({options:t,method:s,bodyHeaders:p,retryCount:r});return{req:{method:s,headers:l,...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,yt.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,yt.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:Ot.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Le,"f").call(this,{body:t,headers:n})}};Ve.Supermemory=m;ht=m,Le=new WeakMap,qt=new WeakSet,vr=function(){return this.baseURL!=="https://api.supermemory.ai"};m.Supermemory=ht;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=Ws.toFile;m.Memories=Vs.Memories;m.Documents=Ls.Documents;m.Search=Rs.Search;m.Settings=gs.Settings;m.Connections=Ns.Connections});var pr=u((d,lr)=>{"use strict";d=lr.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 Zs=Wt();Object.defineProperty(d,"default",{enumerable:!0,get:function(){return Zs.Supermemory}});var Ms=et();Object.defineProperty(d,"toFile",{enumerable:!0,get:function(){return Ms.toFile}});var Fs=xt();Object.defineProperty(d,"APIPromise",{enumerable:!0,get:function(){return Fs.APIPromise}});var Ds=Wt();Object.defineProperty(d,"Supermemory",{enumerable:!0,get:function(){return Ds.Supermemory}});var H=K();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 zr={};Qr(zr,{getRequestIntegrity:()=>Qs,sanitizeContent:()=>Gs,sanitizeMetadata:()=>Is,validateApiKeyFormat:()=>Us,validateContainerTag:()=>Ys,validateContentLength:()=>ks,validateRecallConfig:()=>Js});function Us(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 Ys(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 Gs(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Ss)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function ks(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Is(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=Ks)break;n.length>Es||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,Cs),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function Js(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 Tt(e){return(0,Re.createHash)("sha256").update(e).digest("hex")}function As(e,t){let r=[Tt(e),Tt(t),Pr].join(":");return(0,Re.createHmac)("sha256",Bs).update(r).digest("base64url")}function Qs(e,t){let r=Tt(t),n=As(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${Pr}`,n].join(".")}}var Re,Ss,Ks,Es,Cs,Pr,Bs,mr=Ar(()=>{Re=require("node:crypto");Ss=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Ks=50,Es=128,Cs=1024;Pr=1,Bs="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var xr=u((Na,br)=>{var _s=pr().default,{getRequestIntegrity:$s,validateApiKeyFormat:eo,validateContainerTag:to}=(mr(),$r(zr)),ro="claudecode_default",no=process.env.SUPERMEMORY_API_URL||"https://api.supermemory.ai";function so(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 oo=`Developer coding session transcript. Focus on USER message and intent. +var m=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var L=m((Ye,F)=>{var d=require("node:fs"),x=require("node:path"),ue=require("node:os"),le=require("node:crypto"),pe=x.join(ue.homedir(),".supermemory-claude","memories"),ge=`Developer coding session transcript. Focus on USER message and intent. RULES: -- Extract USER's action/intent, not every detail assistant provides matter +- Extract USER's action/intent, not every detail assistant provides - Condense assistant responses into what user gained from it - Skip granular facts from assistant output @@ -17,124 +13,47 @@ EXTRACT: - Decisions: "chose SQLite for local storage" - Learnings: "learned about React Server Components" -EXAMPLES: -| Transcript | Memory | -| [role:user] research about the whisper.cpp -> https://github.com/ggml-org/whisper.cpp/blob/master/src/whisper.cpp [user:end]| " starts research about whisper.cpp" | -| [role:assistant] ## whisper.cpp Architecture Summary - This is highly relevant for your parakeet.cpp implementation. Here are the key patterns: - ### Core Architecture - **Two-level context design:** - - whisper_context - holds model weights, vocab, hyperparameters (persistent) - - whisper_state - runtime state, KV caches, backends (can have multiple per context) [assistant:end] | "Assistant did a deep dive on whisper architecture" | -| [role:user] Can we explain what we are currently doing in this repository? [user:end] | "" | - SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,ao=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,me=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" - Conventions: "components in PascalCase", "hooks prefixed with use" - Patterns: "all API routes use withAuth wrapper", "errors thrown as ApiError" - Setup: "requires .env with DATABASE_URL", "run pnpm db:migrate first" -- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching" - -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]" |`,Nt=class{constructor(t,r){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let n=eo(t);if(!n.valid)throw new Error(`Invalid API key: ${n.reason}`);let s=r||ro,o=to(s);o.valid||console.warn(`Container tag warning: ${o.reason}`);let a=$s(t,s);this.client=new _s({apiKey:t,baseURL:no,defaultHeaders:a}),this.containerTag=s}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code-plugin",...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:so(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,c=l=>l)=>p.filter(l=>{let b=String(c(l)).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(c=>({id:c.id,memory:c.content||c.context||"",similarity:c.similarity,title:c.title,updatedAt:c.updatedAt}));P={results:o(p,c=>c.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:i},searchResults:P}}};br.exports={SupermemoryClient:Nt,PERSONAL_ENTITY_CONTEXT:oo,REPO_ENTITY_CONTEXT:ao}});var Lt=u((La,jr)=>{var{execSync:ge}=require("node:child_process"),ee=require("node:path");function io(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=ee.resolve(e,r);return ee.basename(n)===".git"&&!n.includes(`${ee.sep}.git${ee.sep}`)?ee.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:io}});var Vt=u((Va,hr)=>{var te=require("node:fs"),we=require("node:path"),{getGitRoot:Xr}=Lt(),Or=we.join(".claude",".supermemory-claude"),yr="config.json";function Hr(e){let r=Xr(e)||e;return we.join(r,Or,yr)}function qr(e){try{let t=Hr(e);if(te.existsSync(t))return JSON.parse(te.readFileSync(t,"utf-8"))}catch{}return null}function fo(e,t){let n=Xr(e)||e,s=we.join(n,Or),o=we.join(s,yr);te.existsSync(s)||te.mkdirSync(s,{recursive:!0});let i={...qr(e)||{},...t};return te.writeFileSync(o,JSON.stringify(i,null,2)),o}hr.exports={getConfigPath:Hr,loadProjectConfig:qr,saveProjectConfig:fo}});var Lr=u((Ra,Nr)=>{var{execSync:co}=require("node:child_process"),uo=require("node:crypto"),{loadProjectConfig:Wr}=Vt(),{getGitRoot:Ze}=Lt();function Tr(e){return uo.createHash("sha256").update(e).digest("hex").slice(0,16)}function Rt(e){try{let r=co("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 vo(e){let t=Wr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Ze(e)||e;return`claudecode_project_${Tr(n)}`}function lo(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function po(e){let t=Wr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Ze(e)||e,o=Rt(n)||n.split("/").pop()||"unknown";return`repo_${lo(o)}`}function Po(e){let r=Ze(e)||e;return Rt(r)||r.split("/").pop()||"unknown"}Nr.exports={sha256:Tr,getGitRoot:Ze,getGitRepoName:Rt,getContainerTag:vo,getRepoContainerTag:po,getProjectName:Po}});var Vr=u((ga,zo)=>{zo.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var Rr=u((wa,mo)=>{mo.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var Mt=u((Za,Mr)=>{var bo=require("node:http"),g=require("node:fs"),gr=require("node:path"),xo=require("node:os"),{execFile:gt}=require("node:child_process"),jo=Vr(),Xo=Rr(),Zt=gr.join(xo.homedir(),".supermemory-claude"),D=gr.join(Zt,"credentials.json"),wr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",wt=19876,Oo=25e3;function yo(){g.existsSync(Zt)||g.mkdirSync(Zt,{recursive:!0})}function Ho(){try{if(g.existsSync(D)){let e=JSON.parse(g.readFileSync(D,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Zr(e){yo();let t={apiKey:e,savedAt:new Date().toISOString()};g.writeFileSync(D,JSON.stringify(t,null,2))}function qo(){try{g.existsSync(D)&&g.unlinkSync(D)}catch{}}function ho(e){let t=r=>{r&&console.warn("Failed to open browser:",r.message)};process.platform==="win32"?gt("explorer.exe",[e],t):process.platform==="darwin"?gt("open",[e],t):gt("xdg-open",[e],t)}function Wo(){return new Promise((e,t)=>{let r=!1,n=bo.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_")?(Zr(i),o.writeHead(200,{"Content-Type":"text/html"}),o.end(jo),r=!0,n.close(),e(i)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(Xo))}else o.writeHead(404),o.end("Not found")});n.listen(wt,"127.0.0.1",()=>{let s=`http://localhost:${wt}/callback`,o=`${wr}?callback=${encodeURIComponent(s)}&client=claude_code`;ho(o)}),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:D,loadCredentials:Ho,saveCredentials:Zr,clearCredentials:qo,startAuthFlow:Wo}});var Ur=u((Ma,Dr)=>{var ne=require("node:fs"),Fr=require("node:path"),To=require("node:os"),{loadCredentials:No}=Mt(),{loadProjectConfig:Ft}=Vt(),Me=Fr.join(To.homedir(),".supermemory-claude"),re=Fr.join(Me,"settings.json"),Fe={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Lo(){ne.existsSync(Me)||ne.mkdirSync(Me,{recursive:!0})}function Dt(){let e={...Fe};try{if(ne.existsSync(re)){let t=ne.readFileSync(re,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${re}: ${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,ne.writeFileSync(re,JSON.stringify(t,null,2))}function Ro(e,t){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;let r=Ft(t||process.cwd());if(r?.apiKey)return r.apiKey;let n=No();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function go(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function wo(e){let t=Dt(),r=Ft(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Zo(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function Mo(e){let t=Dt(),r=Ft(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Fe.signalKeywords,i=r?.signalKeywords||[],P=[...new Set([...a,...i])].map(c=>c.toLowerCase()),p=r?.signalTurnsBefore||t.signalTurnsBefore||Fe.signalTurnsBefore;return{enabled:o,keywords:P,turnsBefore:p}}Dr.exports={SETTINGS_DIR:Me,SETTINGS_FILE:re,DEFAULT_SETTINGS:Fe,loadSettings:Dt,saveSettings:Vo,getApiKey:Ro,debugLog:go,getIncludeTools:wo,shouldIncludeTool:Zo,getSignalConfig:Mo}});var Sr=u((Fa,Yr)=>{async function Fo(){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 De(e){console.log(JSON.stringify(e))}function Do(e=null){De(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function Uo(e){console.error(`Supermemory: ${e}`),De({continue:!0,suppressOutput:!0})}Yr.exports={readStdin:Fo,writeOutput:De,outputSuccess:Do,outputError:Uo}});var Er=u((Da,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 Ut(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 Yo(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(l=>`- ${l}`).join(` -`);P.push(`## User Profile (Persistent) -${c}`)}if(a.length>0){let c=a.map(l=>`- ${l}`).join(` -`);P.push(`## Recent Context -${c}`)}if(i.length>0){let c=i.map(l=>{let b=l.memory??"",f=l.updatedAt?Ut(l.updatedAt):"",O=l.similarity!=null?`[${Math.round(l.similarity*100)}%]`:"";return`- ${f?`[${f}] `:""}${b} ${O}`.trim()});P.push(`## Relevant Memories (with relevance %) -${c.join(` -`)}`)}let p=P.join(` +- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching"`;function fe(e){d.existsSync(e)||d.mkdirSync(e,{recursive:!0})}function h(e,t){return x.join(pe,e,t)}function R(e){if(!d.existsSync(e))return[];let t=d.readdirSync(e).filter(n=>n.endsWith(".json")),o=[];for(let n of t)try{let r=d.readFileSync(x.join(e,n),"utf-8");o.push(JSON.parse(r))}catch{}return o}function de(e,t){let o=(e.content||"").toLowerCase(),n=0;for(let c of t)o.includes(c)&&(n+=1);let r=Date.now()-new Date(e.createdAt||0).getTime(),s=Math.max(0,1-r/(720*60*60*1e3));return n+s*.5}var b=class{constructor(t){this.containerTag=t||"default"}async addMemory(t,o,n={}){let r=o||this.containerTag,s=n.type==="project-knowledge"?"repo":"personal",c=h(s,r);fe(c);let a=le.randomUUID(),u={id:a,content:t,metadata:{sm_source:"claude-code-local",...n},createdAt:new Date().toISOString()};return d.writeFileSync(x.join(c,`${a}.json`),JSON.stringify(u,null,2)),{id:a,status:"saved",containerTag:r}}async search(t,o,n={}){let r=o||this.containerTag,s=n.limit||10,c=h("personal",r),a=h("repo",r),u=[...R(c),...R(a)];if(u.length===0)return{results:[],total:0};let l=t.toLowerCase().split(/\s+/).filter(i=>i.length>2),p=u.map(i=>({memory:i.content||"",metadata:i.metadata,updatedAt:i.createdAt,similarity:l.length>0?de(i,l)/l.length:0})).filter(i=>i.similarity>0).sort((i,f)=>f.similarity-i.similarity).slice(0,s);return{results:p,total:p.length}}async getProfile(t,o,n=5){let r=t||this.containerTag,s=h("personal",r),c=h("repo",r),a=R(s),u=R(c),l=(g,q)=>new Date(q.createdAt||0).getTime()-new Date(g.createdAt||0).getTime();a.sort(l),u.sort(l);let p=u.slice(0,n).map(g=>g.content),i=a.slice(0,n).map(g=>g.content),f=[...a,...u].sort(l).slice(0,n),$={results:f.map(g=>({id:g.id,memory:g.content,similarity:1,updatedAt:g.createdAt})),total:f.length};return{profile:{static:p,dynamic:i},searchResults:$}}};F.exports={LocalMemoryClient:b,PERSONAL_ENTITY_CONTEXT:ge,REPO_ENTITY_CONTEXT:me}});var D=m((Xe,U)=>{var{execSync:C}=require("node:child_process"),y=require("node:path");function he(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return C("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let o=C("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(o===".git")return C("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=y.resolve(e,o);return y.basename(n)===".git"&&!n.includes(`${y.sep}.git${y.sep}`)?y.dirname(n):C("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}U.exports={getGitRoot:he}});var I=m((ze,X)=>{var S=require("node:fs"),E=require("node:path"),{getGitRoot:G}=D(),J=E.join(".claude",".supermemory-claude"),B="config.json";function K(e){let o=G(e)||e;return E.join(o,J,B)}function Y(e){try{let t=K(e);if(S.existsSync(t))return JSON.parse(S.readFileSync(t,"utf-8"))}catch{}return null}function ye(e,t){let n=G(e)||e,r=E.join(n,J),s=E.join(r,B);S.existsSync(r)||S.mkdirSync(r,{recursive:!0});let a={...Y(e)||{},...t};return S.writeFileSync(s,JSON.stringify(a,null,2)),s}X.exports={getConfigPath:K,loadProjectConfig:Y,saveProjectConfig:ye}});var Q=m((We,H)=>{var{execSync:Se}=require("node:child_process"),Te=require("node:crypto"),{loadProjectConfig:z}=I(),{getGitRoot:j}=D();function W(e){return Te.createHash("sha256").update(e).digest("hex").slice(0,16)}function A(e){try{let o=Se("git remote get-url origin",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/);return o?o[1]:null}catch{return null}}function we(e){let t=z(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=j(e)||e;return`claudecode_project_${W(n)}`}function $e(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function Re(e){let t=z(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=j(e)||e,s=A(n)||n.split("/").pop()||"unknown";return`repo_${$e(s)}`}function xe(e){let o=j(e)||e;return A(o)||o.split("/").pop()||"unknown"}H.exports={sha256:W,getGitRoot:j,getGitRepoName:A,getContainerTag:we,getRepoContainerTag:Re,getProjectName:xe}});var te=m((He,ee)=>{var w=require("node:fs"),V=require("node:path"),Ce=require("node:os"),{loadProjectConfig:Z}=I(),P=V.join(Ce.homedir(),".supermemory-claude"),T=V.join(P,"settings.json"),v={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Ee(){w.existsSync(P)||w.mkdirSync(P,{recursive:!0})}function _(){let e={...v};try{if(w.existsSync(T)){let t=w.readFileSync(T,"utf-8");Object.assign(e,JSON.parse(t))}}catch(t){console.error(`Settings: Failed to load ${T}: ${t.message}`)}return process.env.SUPERMEMORY_DEBUG==="true"&&(e.debug=!0),e}function je(e){Ee();let t={...e};w.writeFileSync(T,JSON.stringify(t,null,2))}function Pe(e,t,o){if(e.debug){let n=new Date().toISOString();console.error(o?`[${n}] ${t}: ${JSON.stringify(o)}`:`[${n}] ${t}`)}}function ve(e){let t=_(),o=Z(e||process.cwd()),n=t.includeTools||[],r=o?.includeTools||[];return[...new Set([...n,...r])].map(c=>c.toLowerCase())}function Ne(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function Oe(e){let t=_(),o=Z(e||process.cwd()),n=t.signalExtraction||!1,r=o?.signalExtraction,s=r!==void 0?r:n,c=t.signalKeywords||v.signalKeywords,a=o?.signalKeywords||[],u=[...new Set([...c,...a])].map(p=>p.toLowerCase()),l=o?.signalTurnsBefore||t.signalTurnsBefore||v.signalTurnsBefore;return{enabled:s,keywords:u,turnsBefore:l}}ee.exports={SETTINGS_DIR:P,SETTINGS_FILE:T,DEFAULT_SETTINGS:v,loadSettings:_,saveSettings:je,debugLog:Pe,getIncludeTools:ve,shouldIncludeTool:Ne,getSignalConfig:Oe}});var oe=m((Qe,ne)=>{async function be(){return new Promise((e,t)=>{let o="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{o+=n}),process.stdin.on("end",()=>{try{e(o.trim()?JSON.parse(o):{})}catch(n){t(new Error(`Failed to parse stdin JSON: ${n.message}`))}}),process.stdin.on("error",t),process.stdin.isTTY&&e({})})}function N(e){console.log(JSON.stringify(e))}function De(e=null){N(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function Ie(e){console.error(`Supermemory: ${e}`),N({continue:!0,suppressOutput:!0})}ne.exports={readStdin:be,writeOutput:N,outputSuccess:De,outputError:Ie}});var ce=m((Ve,ie)=>{var re="The following is recalled context. Reference it only when relevant to the conversation.",se="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 k(e){try{let t=new Date(e),o=new Date,n=(o.getTime()-t.getTime())/1e3,r=n/60,s=n/3600,c=n/86400;if(r<30)return"just now";if(r<60)return`${Math.floor(r)}mins ago`;if(s<24)return`${Math.floor(s)}hrs ago`;if(c<7)return`${Math.floor(c)}d ago`;let a=t.toLocaleString("en",{month:"short"});return t.getFullYear()===o.getFullYear()?`${t.getDate()} ${a}`:`${t.getDate()} ${a}, ${t.getFullYear()}`}catch{return""}}function Ae(e,t=!0,o=!1,n=10,r=!0){if(!e)return null;let s=t?(e.profile?.static||[]).slice(0,n):[],c=t?(e.profile?.dynamic||[]).slice(0,n):[],a=o?(e.searchResults?.results||[]).slice(0,n):[];if(s.length===0&&c.length===0&&a.length===0)return null;let u=[];if(s.length>0){let p=s.map(i=>`- ${i}`).join(` +`);u.push(`## User Profile (Persistent) +${p}`)}if(c.length>0){let p=c.map(i=>`- ${i}`).join(` +`);u.push(`## Recent Context +${p}`)}if(a.length>0){let p=a.map(i=>{let f=i.memory??"",$=i.updatedAt?k(i.updatedAt):"",g=i.similarity!=null?`[${Math.round(i.similarity*100)}%]`:"";return`- ${$?`[${$}] `:""}${f} ${g}`.trim()});u.push(`## Relevant Memories (with relevance %) +${p.join(` +`)}`)}let l=u.join(` -`);return s?` -${Gr} +`);return r?` +${re} -${p} +${l} -${kr} -`:p}function So(e){let t=e.filter(n=>n.content);if(t.length===0)return null;let r=t.map(n=>n.label?`${n.label} +${se} +`:l}function _e(e){let t=e.filter(n=>n.content);if(t.length===0)return null;let o=t.map(n=>n.label?`${n.label} ${n.content}`:n.content);return` -${Gr} +${re} -${r.join(` +${o.join(` --- `)} -${kr} -`}function Go(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?Ut(o.updatedAt):"",P=o.similarity!=null?`[${Math.round(o.similarity*100)}%]`:"";return`${i?`[${i}] `:""}${a} ${P}`.trim()});return`${n} -${s.join(` -`)}`}Kr.exports={formatContext:Yo,combineContexts:So,formatRelativeTime:Ut,formatSearchResults:Go}});var{SupermemoryClient:ko}=xr(),{getContainerTag:Ko,getRepoContainerTag:Eo,getProjectName:Co}=Lr(),{loadSettings:Io,getApiKey:Jo,debugLog:U}=Ur(),{readStdin:Bo,writeOutput:Ue}=Sr(),{startAuthFlow:Ao,AUTH_BASE_URL:Qo}=Mt(),{formatContext:Cr,combineContexts:_o}=Er();async function $o(){let e=Io();try{let r=(await Bo()).cwd||process.cwd(),n=Co(r);U(e,"SessionStart",{cwd:r,projectName:n});let s;try{s=Jo(e)}catch{try{U(e,"No API key found, starting browser auth flow"),s=await Ao(),U(e,"Auth flow completed successfully")}catch(f){let O=f.message==="AUTH_TIMEOUT";Ue({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:` -${O?"Authentication timed out. Please complete login in the browser window.":"Authentication failed."} -If the browser did not open, visit: ${Qo} -Or set SUPERMEMORY_CC_API_KEY environment variable manually. -`}});return}}let o=new ko(s),a=Ko(r),i=Eo(r);U(e,"Fetching contexts",{personalTag:a,repoTag:i});let[P,p]=await Promise.all([o.getProfile(a,n).catch(()=>null),o.getProfile(i,n).catch(()=>null)]),c=Cr(P,!0,!1,e.maxProfileItems,!1),l=Cr(p,!0,!1,e.maxProfileItems,!1),b=_o([{label:"### Personal Memories",content:c},{label:"### Project Knowledge (Shared across team)",content:l}]);if(!b){Ue({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:` +${se} +`}function ke(e,t,o){let n=o?`${o} memories for "${e}"`:`Memories for "${e}"`;if(!t||t.length===0)return`No ${o?`${o.toLowerCase()} `:""}memories found for "${e}"`;let r=t.map(s=>{let c=s.memory??"",a=s.updatedAt?k(s.updatedAt):"",u=s.similarity!=null?`[${Math.round(s.similarity*100)}%]`:"";return`${a?`[${a}] `:""}${c} ${u}`.trim()});return`${n} +${r.join(` +`)}`}ie.exports={formatContext:Ae,combineContexts:_e,formatRelativeTime:k,formatSearchResults:ke}});var{LocalMemoryClient:Me}=L(),{getContainerTag:qe,getRepoContainerTag:Fe,getProjectName:Le}=Q(),{loadSettings:Ue,debugLog:O}=te(),{readStdin:Ge,writeOutput:M}=oe(),{formatContext:ae,combineContexts:Je}=ce();async function Be(){let e=Ue();try{let o=(await Ge()).cwd||process.cwd(),n=Le(o);O(e,"SessionStart",{cwd:o,projectName:n});let r=new Me,s=qe(o),c=Fe(o);O(e,"Fetching contexts",{personalTag:s,repoTag:c});let[a,u]=await Promise.all([r.getProfile(s,n,e.maxProfileItems).catch(()=>null),r.getProfile(c,n,e.maxProfileItems).catch(()=>null)]),l=ae(a,!0,!1,e.maxProfileItems,!1),p=ae(u,!0,!1,e.maxProfileItems,!1),i=Je([{label:"### Personal Memories",content:l},{label:"### Project Knowledge (Shared across team)",content:p}]);if(!i){M({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:` No previous memories found for this project. Memories will be saved as you work. -`}});return}U(e,"Context generated",{length:b.length,hasPersonal:!!c,hasRepo:!!l}),Ue({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:b}})}catch(t){U(e,"Error",{error:t.message}),console.error(`Supermemory: ${t.message}`),Ue({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:` +`}});return}O(e,"Context generated",{length:i.length,hasPersonal:!!l,hasRepo:!!p}),M({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:i}})}catch(t){O(e,"Error",{error:t.message}),console.error(`Supermemory-local: ${t.message}`),M({hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:` Failed to load memories: ${t.message} Session will continue without memory context. -`}})}}$o().catch(e=>{console.error(`Supermemory fatal: ${e.message}`),process.exit(1)}); +`}})}}Be().catch(e=>{console.error(`Supermemory-local fatal: ${e.message}`),process.exit(1)}); diff --git a/plugin/scripts/save-project-memory.cjs b/plugin/scripts/save-project-memory.cjs index c0ba917..83357a5 100755 --- a/plugin/scripts/save-project-memory.cjs +++ b/plugin/scripts/save-project-memory.cjs @@ -1,12 +1,8 @@ #!/usr/bin/env node -var Fe=Object.defineProperty;var Mr=Object.getOwnPropertyDescriptor;var Fr=Object.getOwnPropertyNames;var Dr=Object.prototype.hasOwnProperty;var Ur=(e,t)=>()=>(e&&(t=e(e=0)),t);var u=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Yr=(e,t)=>{for(var r in t)Fe(e,r,{get:t[r],enumerable:!0})},Sr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Fr(t))!Dr.call(e,s)&&s!==r&&Fe(e,s,{get:()=>t[s],enumerable:!(n=Mr(t,s))||n.enumerable});return e};var Gr=e=>Sr(Fe({},"__esModule",{value:!0}),e);var Ye=u(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=Kr;h.__classPrivateFieldGet=kr;h.__importStar=Er;h.__exportStar=Ir;function Kr(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 kr(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 Ue=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=Ue;var Dt=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};h.__setModuleDefault=Dt;var De=function(e){return De=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},De(e)};function Er(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=De(e),n=0;n{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.uuid4=void 0;var Cr=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=Cr});var Se=u(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=Jr;function Jr(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var Br=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=Br});var K=u(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 Ar=Se(),se=class extends Error{};P.SupermemoryError=se;var O=class e extends se{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,Ar.castToError)(r)});let o=r;return t===400?new oe(t,o,n,s):t===401?new ae(t,o,n,s):t===403?new fe(t,o,n,s):t===404?new ie(t,o,n,s):t===409?new ce(t,o,n,s):t===422?new ue(t,o,n,s):t===429?new de(t,o,n,s):t>=500?new ve(t,o,n,s):new e(t,o,n,s)}};P.APIError=O;var Ge=class extends O{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};P.APIUserAbortError=Ge;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 Ke=class extends G{constructor({message:t}={}){super({message:t??"Request timed out."})}};P.APIConnectionTimeoutError=Ke;var oe=class extends O{};P.BadRequestError=oe;var ae=class extends O{};P.AuthenticationError=ae;var fe=class extends O{};P.PermissionDeniedError=fe;var ie=class extends O{};P.NotFoundError=ie;var ce=class extends O{};P.ConflictError=ce;var ue=class extends O{};P.UnprocessableEntityError=ue;var de=class extends O{};P.RateLimitError=de;var ve=class extends O{};P.InternalServerError=ve});var E=u(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=en;d.isEmptyObj=tn;d.hasOwn=rn;d.isObj=nn;var k=K(),Qr=/^[a-z][a-z0-9+.-]*:/i,_r=e=>Qr.test(e);d.isAbsoluteURL=_r;var $r=e=>(d.isArray=Array.isArray,(0,d.isArray)(e));d.isArray=$r;d.isReadonlyArray=d.isArray;function en(e){return typeof e!="object"?{}:e??{}}function tn(e){if(!e)return!0;for(let t in e)return!1;return!0}function rn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function nn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var sn=e=>{if(e==null)throw new k.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};d.ensurePresent=sn;var on=(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=on;var an=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=an;var fn=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=fn;var cn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;d.coerceBoolean=cn;var un=e=>{if(e!=null)return(0,d.coerceInteger)(e)};d.maybeCoerceInteger=un;var dn=e=>{if(e!=null)return(0,d.coerceFloat)(e)};d.maybeCoerceFloat=dn;var vn=e=>{if(e!=null)return(0,d.coerceBoolean)(e)};d.maybeCoerceBoolean=vn;var ln=e=>{try{return JSON.parse(e)}catch{return}};d.safeJSON=ln});var Yt=u(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.sleep=void 0;var Pn=e=>new Promise(t=>setTimeout(t,e));le.sleep=Pn});var ke=u(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.VERSION=void 0;Pe.VERSION="4.0.0"});var kt=u(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.getPlatformHeaders=g.isRunningInBrowser=void 0;var I=ke(),pn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";g.isRunningInBrowser=pn;function zn(){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 mn=()=>{let e=zn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":I.VERSION,"X-Stainless-OS":Gt(Deno.build.os),"X-Stainless-Arch":St(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":Gt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":St(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=bn();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 bn(){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 St=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Gt=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,jn=()=>Kt??(Kt=mn());g.getPlatformHeaders=jn});var Ee=u(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=xn;V.makeReadableStream=Et;V.ReadableStreamFrom=Xn;V.ReadableStreamToAsyncIterable=On;V.CancelReadableStream=yn;function xn(){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 Et(...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 Xn(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Et({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function On(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 yn(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 It=u(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.FallbackEncoder=void 0;var Hn=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});pe.FallbackEncoder=Hn});var C=u(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=Ie;j.getName=ze;var qn=Ee(),hn=()=>{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=hn;function Ie(e,t,r){return(0,j.checkFileSupport)(),new File(e,t??"unknown_file",r)}function ze(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";j.isAsyncIterable=Wn;var Tn=async(e,t)=>Ce(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=Tn;var Nn=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=Nn;var Ct=new WeakMap;function Ln(e){let t=typeof e=="function"?e:e.fetch,r=Ct.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 Ct.set(t,n),n}var Vn=async(e,t)=>{if(!await Ln(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])=>Je(r,n,s))),r};j.createForm=Vn;var Jt=e=>e instanceof Blob&&"name"in e,Rn=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||Jt(e)),Ce=e=>{if(Rn(e))return!0;if(Array.isArray(e))return e.some(Ce);if(e&&typeof e=="object"){for(let t in e)if(Ce(e[t]))return!0}return!1},Je=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,Ie([await r.blob()],ze(r)));else if((0,j.isAsyncIterable)(r))e.append(t,Ie([await new Response((0,qn.ReadableStreamFrom)(r)).blob()],ze(r)));else if(Jt(r))e.append(t,r,ze(r));else if(Array.isArray(r))await Promise.all(r.map(n=>Je(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>Je(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 At=u(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.toFile=Mn;var J=C(),Zn=C(),Bt=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",gn=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Bt(e),wn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Mn(e,t,r){if((0,Zn.checkFileSupport)(),e=await e,gn(e))return e instanceof File?e:(0,J.makeFile)([await e.arrayBuffer()],e.name);if(wn(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,J.makeFile)(await Be(s),t,r)}let n=await Be(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 Be(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Bt(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 Be(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Fn(e)}`)}return t}function Fn(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var Qe=u(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.toFile=void 0;var Dn=At();Object.defineProperty(me,"toFile",{enumerable:!0,get:function(){return Dn.toFile}})});var w=u(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.APIResource=void 0;var _e=class{constructor(t){this._client=t}};be.APIResource=_e});var B=u(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.isEmptyHeaders=M.buildHeaders=void 0;var Qt=E(),_t=Symbol("brand.privateNullableHeaders");function*$t(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,Qt.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,Qt.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 Un=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,a]of $t(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=Un;var Yn=e=>{for(let t of $t(e))return!1;return!0};M.isEmptyHeaders=Yn});var je=u(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=$e;var Sn=K();function $e(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var er=Object.freeze(Object.create(null)),Gn=(e=$e)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((v,m,X)=>{/[?#]/.test(m)&&(s=!0);let i=n[X],q=(s?encodeURIComponent:e)(""+i);return X!==n.length&&(i==null||typeof i=="object"&&i.toString===Object.getPrototypeOf(Object.getPrototypeOf(i.hasOwnProperty??er)??er)?.toString)&&(q=i+"",o.push({start:v.length+m.length,length:q.length,error:`Value of type ${Object.prototype.toString.call(i).slice(8,-1)} is not a valid path parameter`})),v+m+(X===n.length?"":q)},""),f=a.split(/[?#]/,1)[0],z=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=z.exec(f))!==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((v,m)=>v.start-m.start),o.length>0){let v=0,m=o.reduce((X,i)=>{let q=" ".repeat(i.start-v),D="^".repeat(i.length);return v=i.start+i.length,X+q+D},"");throw new Sn.SupermemoryError(`Path parameters result in path with invalid segments: -${o.map(X=>X.error).join(` -`)} -${a} -${m}`)}return a};N.createPathTagFunction=Gn;N.path=(0,N.createPathTagFunction)($e)});var tt=u(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.Connections=void 0;var Kn=w(),kn=B(),W=je(),et=class extends Kn.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,kn.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=et});var st=u(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Documents=void 0;var En=w(),In=B(),Cn=C(),rt=je(),nt=class extends En.APIResource{update(t,r={},n){return this._client.patch((0,rt.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,rt.path)`/v3/documents/${t}`,{...r,headers:(0,In.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,rt.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,Cn.multipartFormRequestOptions)({body:t,...r},this._client))}};Xe.Documents=nt});var ft=u(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Memories=void 0;var Jn=w(),Bn=B(),An=C(),ot=je(),at=class extends Jn.APIResource{update(t,r={},n){return this._client.patch((0,ot.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,ot.path)`/v3/documents/${t}`,{...r,headers:(0,Bn.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,ot.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,An.multipartFormRequestOptions)({body:t,...r},this._client))}};Oe.Memories=at});var ct=u(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Search=void 0;var Qn=w(),it=class extends Qn.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})}};ye.Search=it});var dt=u(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Settings=void 0;var _n=w(),ut=class extends _n.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};He.Settings=ut});var tr=u(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.Settings=H.Search=H.Memories=H.Documents=H.Connections=void 0;var $n=tt();Object.defineProperty(H,"Connections",{enumerable:!0,get:function(){return $n.Connections}});var es=st();Object.defineProperty(H,"Documents",{enumerable:!0,get:function(){return es.Documents}});var ts=ft();Object.defineProperty(H,"Memories",{enumerable:!0,get:function(){return ts.Memories}});var rs=ct();Object.defineProperty(H,"Search",{enumerable:!0,get:function(){return rs.Search}});var ns=dt();Object.defineProperty(H,"Settings",{enumerable:!0,get:function(){return ns.Settings}})});var vt=u(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=nr;var ss=E(),he={off:0,error:200,warn:300,info:400,debug:500},os=(e,t,r)=>{if(e){if((0,ss.hasOwn)(he,e))return e;nr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(he))}`)}};R.parseLogLevel=os;function A(){}function qe(e,t,r){return!t||he[e]>he[r]?A:t[e].bind(t)}var as={error:A,warn:A,info:A,debug:A},rr=new WeakMap;function nr(e){let t=e.logger,r=e.logLevel??"off";if(!t)return as;let n=rr.get(t);if(n&&n[0]===r)return n[1];let s={error:qe("error",t,r),warn:qe("warn",t,r),info:qe("info",t,r),debug:qe("debug",t,r)};return rr.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);R.formatRequestDetails=fs});var or=u(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.defaultParseResponse=is;var sr=vt();async function is(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,sr.loggerFor)(e).debug(`[${n}] response parsed`,(0,sr.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}});var zt=u(We=>{"use strict";var Q;Object.defineProperty(We,"__esModule",{value:!0});We.APIPromise=void 0;var Pt=Ye(),cs=or(),pt=class e extends Promise{constructor(t,r,n=cs.defaultParseResponse){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,Q.set(this,void 0),Pt.__classPrivateFieldSet(this,Q,t,"f")}_thenUnwrap(t){return new e(Pt.__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(Pt.__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)}};We.APIPromise=pt;Q=new WeakMap});var ar=u(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.readEnv=void 0;var us=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()};Te.readEnv=us});var Ht=u(Le=>{"use strict";var Ot,yt,Ne,fr;Object.defineProperty(Le,"__esModule",{value:!0});Le.Supermemory=void 0;var L=Ye(),ds=Ut(),mt=E(),vs=Yt(),bt=Se(),ls=kt(),jt=L.__importStar(Ee()),Ps=L.__importStar(It()),ps=ke(),b=L.__importStar(K()),zs=L.__importStar(Qe()),_=L.__importStar(tr()),ms=zt(),bs=tt(),js=st(),xs=ft(),Xs=ct(),Os=dt(),xt=B(),Xt=ar(),x=vt(),ys=E(),p=class{constructor({baseURL:t=(0,Xt.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Xt.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Ot.add(this),Ne.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??yt.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,Xt.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??jt.getDefaultFetch(),L.__classPrivateFieldSet(this,Ne,Ps.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,xt.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 ${ps.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,ds.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,Ot,"m",fr).call(this)&&n||this.baseURL,o=(0,mt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,ys.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 ms.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 l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),v=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if((0,x.loggerFor)(this).debug(`[${l}] sending request`,(0,x.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(bt.castToError),q=Date.now();if(i instanceof globalThis.Error){let U=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let T=(0,bt.isAbortError)(i)||/timed? ?out/i.test(String(i)+("cause"in i?String(i.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:f,durationMs:q-m,message:i.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:f,durationMs:q-m,message:i.message})),T?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:i})}let D=`[${l}${v}] ${a.method} ${f} ${i.ok?"succeeded":"failed"} with status ${i.status} in ${q-m}ms`;if(!i.ok){let U=await this.shouldRetry(i);if(r&&U){let ne=`retrying, ${r} attempts remaining`;return await jt.CancelReadableStream(i.body),(0,x.loggerFor)(this).info(`${D} - ${ne}`),(0,x.loggerFor)(this).debug(`[${l}] response error (${ne})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:q-m})),this.retryRequest(s,r,n??l,i.headers)}let T=U?"error; no more retries left":"error; not retryable";(0,x.loggerFor)(this).info(`${D} - ${T}`);let wt=await i.text().catch(ne=>(0,bt.castToError)(ne).message),Mt=(0,mt.safeJSON)(wt),Ft=Mt?void 0:wt;throw(0,x.loggerFor)(this).debug(`[${l}] response error (${T})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,message:Ft,durationMs:Date.now()-m})),this.makeStatusError(i.status,Mt,Ft,i.headers)}return(0,x.loggerFor)(this).info(D),(0,x.loggerFor)(this).debug(`[${l}] response start`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:q-m})),{response:i,options:s,controller:X,requestLogID:l,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),l=globalThis.ReadableStream&&f.body instanceof globalThis.ReadableStream||typeof f.body=="object"&&f.body!==null&&Symbol.asyncIterator in f.body,v={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...f};a&&(v.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,v)}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,vs.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,mt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:l,body:v}=this.buildBody({options:n}),m=await this.buildHeaders({options:t,method:s,bodyHeaders:l,retryCount:r});return{req:{method:s,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&v instanceof globalThis.ReadableStream&&{duplex:"half"},...v&&{body:v},...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,xt.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,ls.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,xt.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:jt.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Ne,"f").call(this,{body:t,headers:n})}};Le.Supermemory=p;yt=p,Ne=new WeakMap,Ot=new WeakSet,fr=function(){return this.baseURL!=="https://api.supermemory.ai"};p.Supermemory=yt;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=zs.toFile;p.Memories=xs.Memories;p.Documents=js.Documents;p.Search=Xs.Search;p.Settings=Os.Settings;p.Connections=bs.Connections});var cr=u((c,ir)=>{"use strict";c=ir.exports=function(...e){return new c.default(...e)};Object.defineProperty(c,"__esModule",{value:!0});c.UnprocessableEntityError=c.PermissionDeniedError=c.InternalServerError=c.AuthenticationError=c.BadRequestError=c.RateLimitError=c.ConflictError=c.NotFoundError=c.APIUserAbortError=c.APIConnectionTimeoutError=c.APIConnectionError=c.APIError=c.SupermemoryError=c.Supermemory=c.APIPromise=c.toFile=c.default=void 0;var Hs=Ht();Object.defineProperty(c,"default",{enumerable:!0,get:function(){return Hs.Supermemory}});var qs=Qe();Object.defineProperty(c,"toFile",{enumerable:!0,get:function(){return qs.toFile}});var hs=zt();Object.defineProperty(c,"APIPromise",{enumerable:!0,get:function(){return hs.APIPromise}});var Ws=Ht();Object.defineProperty(c,"Supermemory",{enumerable:!0,get:function(){return Ws.Supermemory}});var y=K();Object.defineProperty(c,"SupermemoryError",{enumerable:!0,get:function(){return y.SupermemoryError}});Object.defineProperty(c,"APIError",{enumerable:!0,get:function(){return y.APIError}});Object.defineProperty(c,"APIConnectionError",{enumerable:!0,get:function(){return y.APIConnectionError}});Object.defineProperty(c,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return y.APIConnectionTimeoutError}});Object.defineProperty(c,"APIUserAbortError",{enumerable:!0,get:function(){return y.APIUserAbortError}});Object.defineProperty(c,"NotFoundError",{enumerable:!0,get:function(){return y.NotFoundError}});Object.defineProperty(c,"ConflictError",{enumerable:!0,get:function(){return y.ConflictError}});Object.defineProperty(c,"RateLimitError",{enumerable:!0,get:function(){return y.RateLimitError}});Object.defineProperty(c,"BadRequestError",{enumerable:!0,get:function(){return y.BadRequestError}});Object.defineProperty(c,"AuthenticationError",{enumerable:!0,get:function(){return y.AuthenticationError}});Object.defineProperty(c,"InternalServerError",{enumerable:!0,get:function(){return y.InternalServerError}});Object.defineProperty(c,"PermissionDeniedError",{enumerable:!0,get:function(){return y.PermissionDeniedError}});Object.defineProperty(c,"UnprocessableEntityError",{enumerable:!0,get:function(){return y.UnprocessableEntityError}})});var dr={};Yr(dr,{getRequestIntegrity:()=>Ys,sanitizeContent:()=>Vs,sanitizeMetadata:()=>Ms,validateApiKeyFormat:()=>Ts,validateContainerTag:()=>Ns,validateContentLength:()=>Rs,validateRecallConfig:()=>Fs});function Ts(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 Ns(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 Vs(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Ls)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function Rs(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Ms(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=Zs)break;n.length>gs||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,ws),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function Fs(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 qt(e){return(0,Ve.createHash)("sha256").update(e).digest("hex")}function Us(e,t){let r=[qt(e),qt(t),ur].join(":");return(0,Ve.createHmac)("sha256",Ds).update(r).digest("base64url")}function Ys(e,t){let r=qt(t),n=Us(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${ur}`,n].join(".")}}var Ve,Ls,Zs,gs,ws,ur,Ds,vr=Ur(()=>{Ve=require("node:crypto");Ls=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Zs=50,gs=128,ws=1024;ur=1,Ds="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Pr=u((ia,lr)=>{var Ss=cr().default,{getRequestIntegrity:Gs,validateApiKeyFormat:Ks,validateContainerTag:ks}=(vr(),Gr(dr)),Es="claudecode_default",Is=process.env.SUPERMEMORY_API_URL||"https://api.supermemory.ai";function Cs(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 Js=`Developer coding session transcript. Focus on USER message and intent. +var R=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var D=R((pe,w)=>{var g=require("node:fs"),T=require("node:path"),J=require("node:os"),X=require("node:crypto"),z=T.join(J.homedir(),".supermemory-claude","memories"),W=`Developer coding session transcript. Focus on USER message and intent. RULES: -- Extract USER's action/intent, not every detail assistant provides matter +- Extract USER's action/intent, not every detail assistant provides - Condense assistant responses into what user gained from it - Skip granular facts from assistant output @@ -17,86 +13,13 @@ EXTRACT: - Decisions: "chose SQLite for local storage" - Learnings: "learned about React Server Components" -EXAMPLES: -| Transcript | Memory | -| [role:user] research about the whisper.cpp -> https://github.com/ggml-org/whisper.cpp/blob/master/src/whisper.cpp [user:end]| " starts research about whisper.cpp" | -| [role:assistant] ## whisper.cpp Architecture Summary - This is highly relevant for your parakeet.cpp implementation. Here are the key patterns: - ### Core Architecture - **Two-level context design:** - - whisper_context - holds model weights, vocab, hyperparameters (persistent) - - whisper_state - runtime state, KV caches, backends (can have multiple per context) [assistant:end] | "Assistant did a deep dive on whisper architecture" | -| [role:user] Can we explain what we are currently doing in this repository? [user:end] | "" | - SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,Bs=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,Y=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" - Conventions: "components in PascalCase", "hooks prefixed with use" - Patterns: "all API routes use withAuth wrapper", "errors thrown as ApiError" - Setup: "requires .env with DATABASE_URL", "run pnpm db:migrate first" -- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching" - -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]" |`,ht=class{constructor(t,r){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let n=Ks(t);if(!n.valid)throw new Error(`Invalid API key: ${n.reason}`);let s=r||Es,o=ks(s);o.valid||console.warn(`Container tag warning: ${o.reason}`);let a=Gs(t,s);this.client=new Ss({apiKey:t,baseURL:Is,defaultHeaders:a}),this.containerTag=s}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code-plugin",...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:Cs(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,v=m=>m)=>l.filter(m=>{let X=String(v(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 l=n.searchResults.results.map(v=>({id:v.id,memory:v.content||v.context||"",similarity:v.similarity,title:v.title,updatedAt:v.updatedAt}));z={results:o(l,v=>v.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:f},searchResults:z}}};lr.exports={SupermemoryClient:ht,PERSONAL_ENTITY_CONTEXT:Js,REPO_ENTITY_CONTEXT:Bs}});var Wt=u((ca,pr)=>{var{execSync:Re}=require("node:child_process"),$=require("node:path");function As(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return Re("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=Re("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return Re("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):Re("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}pr.exports={getGitRoot:As}});var Tt=u((ua,Xr)=>{var ee=require("node:fs"),Ze=require("node:path"),{getGitRoot:zr}=Wt(),mr=Ze.join(".claude",".supermemory-claude"),br="config.json";function jr(e){let r=zr(e)||e;return Ze.join(r,mr,br)}function xr(e){try{let t=jr(e);if(ee.existsSync(t))return JSON.parse(ee.readFileSync(t,"utf-8"))}catch{}return null}function Qs(e,t){let n=zr(e)||e,s=Ze.join(n,mr),o=Ze.join(s,br);ee.existsSync(s)||ee.mkdirSync(s,{recursive:!0});let f={...xr(e)||{},...t};return ee.writeFileSync(o,JSON.stringify(f,null,2)),o}Xr.exports={getConfigPath:jr,loadProjectConfig:xr,saveProjectConfig:Qs}});var qr=u((da,Hr)=>{var{execSync:_s}=require("node:child_process"),$s=require("node:crypto"),{loadProjectConfig:Or}=Tt(),{getGitRoot:ge}=Wt();function yr(e){return $s.createHash("sha256").update(e).digest("hex").slice(0,16)}function Nt(e){try{let r=_s("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 eo(e){let t=Or(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=ge(e)||e;return`claudecode_project_${yr(n)}`}function to(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function ro(e){let t=Or(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=ge(e)||e,o=Nt(n)||n.split("/").pop()||"unknown";return`repo_${to(o)}`}function no(e){let r=ge(e)||e;return Nt(r)||r.split("/").pop()||"unknown"}Hr.exports={sha256:yr,getGitRoot:ge,getGitRepoName:Nt,getContainerTag:eo,getRepoContainerTag:ro,getProjectName:no}});var hr=u((va,so)=>{so.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var Wr=u((la,oo)=>{oo.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var Rr=u((Pa,Vr)=>{var ao=require("node:http"),Z=require("node:fs"),Tr=require("node:path"),fo=require("node:os"),{execFile:Lt}=require("node:child_process"),io=hr(),co=Wr(),Rt=Tr.join(fo.homedir(),".supermemory-claude"),F=Tr.join(Rt,"credentials.json"),Nr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",Vt=19876,uo=25e3;function vo(){Z.existsSync(Rt)||Z.mkdirSync(Rt,{recursive:!0})}function lo(){try{if(Z.existsSync(F)){let e=JSON.parse(Z.readFileSync(F,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Lr(e){vo();let t={apiKey:e,savedAt:new Date().toISOString()};Z.writeFileSync(F,JSON.stringify(t,null,2))}function Po(){try{Z.existsSync(F)&&Z.unlinkSync(F)}catch{}}function po(e){let t=r=>{r&&console.warn("Failed to open browser:",r.message)};process.platform==="win32"?Lt("explorer.exe",[e],t):process.platform==="darwin"?Lt("open",[e],t):Lt("xdg-open",[e],t)}function zo(){return new Promise((e,t)=>{let r=!1,n=ao.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${Vt}`);if(a.pathname==="/callback"){let f=a.searchParams.get("apikey")||a.searchParams.get("api_key");f?.startsWith("sm_")?(Lr(f),o.writeHead(200,{"Content-Type":"text/html"}),o.end(io),r=!0,n.close(),e(f)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(co))}else o.writeHead(404),o.end("Not found")});n.listen(Vt,"127.0.0.1",()=>{let s=`http://localhost:${Vt}/callback`,o=`${Nr}?callback=${encodeURIComponent(s)}&client=claude_code`;po(o)}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},uo)})}Vr.exports={AUTH_BASE_URL:Nr,CREDENTIALS_FILE:F,loadCredentials:lo,saveCredentials:Lr,clearCredentials:Po,startAuthFlow:zo}});var wr=u((pa,gr)=>{var re=require("node:fs"),Zr=require("node:path"),mo=require("node:os"),{loadCredentials:bo}=Rr(),{loadProjectConfig:Zt}=Tt(),we=Zr.join(mo.homedir(),".supermemory-claude"),te=Zr.join(we,"settings.json"),Me={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function jo(){re.existsSync(we)||re.mkdirSync(we,{recursive:!0})}function gt(){let e={...Me};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 xo(e){jo();let t={...e};delete t.apiKey,re.writeFileSync(te,JSON.stringify(t,null,2))}function Xo(e,t){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;let r=Zt(t||process.cwd());if(r?.apiKey)return r.apiKey;let n=bo();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function Oo(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function yo(e){let t=gt(),r=Zt(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Ho(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function qo(e){let t=gt(),r=Zt(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Me.signalKeywords,f=r?.signalKeywords||[],z=[...new Set([...a,...f])].map(v=>v.toLowerCase()),l=r?.signalTurnsBefore||t.signalTurnsBefore||Me.signalTurnsBefore;return{enabled:o,keywords:z,turnsBefore:l}}gr.exports={SETTINGS_DIR:we,SETTINGS_FILE:te,DEFAULT_SETTINGS:Me,loadSettings:gt,saveSettings:xo,getApiKey:Xo,debugLog:Oo,getIncludeTools:yo,shouldIncludeTool:Ho,getSignalConfig:qo}});var{SupermemoryClient:ho,REPO_ENTITY_CONTEXT:Wo}=Pr(),{getRepoContainerTag:To,getProjectName:No}=qr(),{loadSettings:Lo,getApiKey:Vo}=wr();async function Ro(){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=Lo(),r;try{r=Vo(t)}catch{console.log("Supermemory API key not configured."),console.log("Set SUPERMEMORY_CC_API_KEY environment variable.");return}let n=process.cwd(),s=To(n),o=No(n);try{let f=await new ho(r,s).addMemory(e,s,{type:"project-knowledge",project:o,timestamp:new Date().toISOString()},{entityContext:Wo});console.log(`Project knowledge saved: ${o}`),console.log(`ID: ${f.id}`)}catch(a){console.log(`Error saving: ${a.message}`)}}Ro().catch(e=>{console.error(`Fatal error: ${e.message}`),process.exit(1)}); +- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching"`;function B(e){g.existsSync(e)||g.mkdirSync(e,{recursive:!0})}function m(e,t){return T.join(z,e,t)}function S(e){if(!g.existsSync(e))return[];let t=g.readdirSync(e).filter(o=>o.endsWith(".json")),n=[];for(let o of t)try{let r=g.readFileSync(T.join(e,o),"utf-8");n.push(JSON.parse(r))}catch{}return n}function K(e,t){let n=(e.content||"").toLowerCase(),o=0;for(let a of t)n.includes(a)&&(o+=1);let r=Date.now()-new Date(e.createdAt||0).getTime(),s=Math.max(0,1-r/(720*60*60*1e3));return o+s*.5}var E=class{constructor(t){this.containerTag=t||"default"}async addMemory(t,n,o={}){let r=n||this.containerTag,s=o.type==="project-knowledge"?"repo":"personal",a=m(s,r);B(a);let c=X.randomUUID(),l={id:c,content:t,metadata:{sm_source:"claude-code-local",...o},createdAt:new Date().toISOString()};return g.writeFileSync(T.join(a,`${c}.json`),JSON.stringify(l,null,2)),{id:c,status:"saved",containerTag:r}}async search(t,n,o={}){let r=n||this.containerTag,s=o.limit||10,a=m("personal",r),c=m("repo",r),l=[...S(a),...S(c)];if(l.length===0)return{results:[],total:0};let u=t.toLowerCase().split(/\s+/).filter(i=>i.length>2),h=l.map(i=>({memory:i.content||"",metadata:i.metadata,updatedAt:i.createdAt,similarity:u.length>0?K(i,u)/u.length:0})).filter(i=>i.similarity>0).sort((i,y)=>y.similarity-i.similarity).slice(0,s);return{results:h,total:h.length}}async getProfile(t,n,o=5){let r=t||this.containerTag,s=m("personal",r),a=m("repo",r),c=S(s),l=S(a),u=(p,G)=>new Date(G.createdAt||0).getTime()-new Date(p.createdAt||0).getTime();c.sort(u),l.sort(u);let h=l.slice(0,o).map(p=>p.content),i=c.slice(0,o).map(p=>p.content),y=[...c,...l].sort(u).slice(0,o),U={results:y.map(p=>({id:p.id,memory:p.content,similarity:1,updatedAt:p.createdAt})),total:y.length};return{profile:{static:h,dynamic:i},searchResults:U}}};w.exports={LocalMemoryClient:E,PERSONAL_ENTITY_CONTEXT:W,REPO_ENTITY_CONTEXT:Y}});var P=R((le,A)=>{var{execSync:C}=require("node:child_process"),f=require("node:path");function H(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return C("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=C("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(n===".git")return C("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let o=f.resolve(e,n);return f.basename(o)===".git"&&!o.includes(`${f.sep}.git${f.sep}`)?f.dirname(o):C("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}A.exports={getGitRoot:H}});var M=R((ue,k)=>{var d=require("node:fs"),j=require("node:path"),{getGitRoot:_}=P(),O=j.join(".claude",".supermemory-claude"),q="config.json";function x(e){let n=_(e)||e;return j.join(n,O,q)}function I(e){try{let t=x(e);if(d.existsSync(t))return JSON.parse(d.readFileSync(t,"utf-8"))}catch{}return null}function Q(e,t){let o=_(e)||e,r=j.join(o,O),s=j.join(r,q);d.existsSync(r)||d.mkdirSync(r,{recursive:!0});let c={...I(e)||{},...t};return d.writeFileSync(s,JSON.stringify(c,null,2)),s}k.exports={getConfigPath:x,loadProjectConfig:I,saveProjectConfig:Q}});var L=R((ge,$)=>{var{execSync:V}=require("node:child_process"),Z=require("node:crypto"),{loadProjectConfig:b}=M(),{getGitRoot:v}=P();function F(e){return Z.createHash("sha256").update(e).digest("hex").slice(0,16)}function N(e){try{let n=V("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 ee(e){let t=b(e);if(t?.personalContainerTag)return t.personalContainerTag;let o=v(e)||e;return`claudecode_project_${F(o)}`}function te(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function oe(e){let t=b(e);if(t?.repoContainerTag)return t.repoContainerTag;let o=v(e)||e,s=N(o)||o.split("/").pop()||"unknown";return`repo_${te(s)}`}function ne(e){let n=v(e)||e;return N(n)||n.split("/").pop()||"unknown"}$.exports={sha256:F,getGitRoot:v,getGitRepoName:N,getContainerTag:ee,getRepoContainerTag:oe,getProjectName:ne}});var{LocalMemoryClient:re,REPO_ENTITY_CONTEXT:me}=D(),{getRepoContainerTag:se,getProjectName:ie}=L();async function ce(){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=process.cwd(),n=se(t),o=ie(t);try{let s=await new re(n).addMemory(e,n,{type:"project-knowledge",project:o,timestamp:new Date().toISOString()});console.log(`Project knowledge saved: ${o}`),console.log(`ID: ${s.id}`)}catch(r){console.log(`Error saving: ${r.message}`)}}ce().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 1d49d0b..6c13d6f 100755 --- a/plugin/scripts/search-memory.cjs +++ b/plugin/scripts/search-memory.cjs @@ -1,12 +1,8 @@ #!/usr/bin/env node -var Fe=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 v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Cr=(e,t)=>{for(var r in t)Fe(e,r,{get:t[r],enumerable:!0})},Ir=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Kr(t))!kr.call(e,s)&&s!==r&&Fe(e,s,{get:()=>t[s],enumerable:!(n=Gr(t,s))||n.enumerable});return e};var Jr=e=>Ir(Fe({},"__esModule",{value:!0}),e);var Ue=v(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 Ye=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=Ye;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 De=function(e){return De=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},De(e)};function Qr(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=De(e),n=0;n{"use strict";Object.defineProperty(U,"__esModule",{value:!0});U.uuid4=void 0;var $r=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return U.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))};U.uuid4=$r});var Se=v(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=v(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 rn=Se(),se=class extends Error{};z.SupermemoryError=se;var y=class e extends se{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 oe(t,o,n,s):t===401?new ae(t,o,n,s):t===403?new fe(t,o,n,s):t===404?new ie(t,o,n,s):t===409?new ce(t,o,n,s):t===422?new ue(t,o,n,s):t===429?new de(t,o,n,s):t>=500?new ve(t,o,n,s):new e(t,o,n,s)}};z.APIError=y;var Ge=class extends y{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};z.APIUserAbortError=Ge;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 Ke=class extends G{constructor({message:t}={}){super({message:t??"Request timed out."})}};z.APIConnectionTimeoutError=Ke;var oe=class extends y{};z.BadRequestError=oe;var ae=class extends y{};z.AuthenticationError=ae;var fe=class extends y{};z.PermissionDeniedError=fe;var ie=class extends y{};z.NotFoundError=ie;var ce=class extends y{};z.ConflictError=ce;var ue=class extends y{};z.UnprocessableEntityError=ue;var de=class extends y{};z.RateLimitError=de;var ve=class extends y{};z.InternalServerError=ve});var E=v(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=an;p.isEmptyObj=fn;p.hasOwn=cn;p.isObj=un;var k=K(),nn=/^[a-z][a-z0-9+.-]*:/i,sn=e=>nn.test(e);p.isAbsoluteURL=sn;var on=e=>(p.isArray=Array.isArray,(0,p.isArray)(e));p.isArray=on;p.isReadonlyArray=p.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};p.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};p.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`)};p.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`)};p.coerceFloat=pn;var Pn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;p.coerceBoolean=Pn;var zn=e=>{if(e!=null)return(0,p.coerceInteger)(e)};p.maybeCoerceInteger=zn;var mn=e=>{if(e!=null)return(0,p.coerceFloat)(e)};p.maybeCoerceFloat=mn;var bn=e=>{if(e!=null)return(0,p.coerceBoolean)(e)};p.maybeCoerceBoolean=bn;var jn=e=>{try{return JSON.parse(e)}catch{return}};p.safeJSON=jn});var Gt=v(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.sleep=void 0;var xn=e=>new Promise(t=>setTimeout(t,e));le.sleep=xn});var ke=v(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.VERSION=void 0;pe.VERSION="4.0.0"});var Ct=v(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.getPlatformHeaders=Z.isRunningInBrowser=void 0;var C=ke(),Xn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Z.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":C.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":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":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":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 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,qn=()=>Et??(Et=yn());Z.getPlatformHeaders=qn});var Ee=v(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 Jt=v(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.FallbackEncoder=void 0;var Ln=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});Pe.FallbackEncoder=Ln});var I=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=Ce;j.getName=ze;var Vn=Ee(),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`.":""))}};j.checkFileSupport=Rn;function Ce(e,t,r){return(0,j.checkFileSupport)(),new File(e,t??"unknown_file",r)}function ze(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";j.isAsyncIterable=gn;var wn=async(e,t)=>Ie(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=wn;var Zn=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=Zn;var Bt=new WeakMap;function Mn(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 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])=>Je(r,n,s))),r};j.createForm=Fn;var At=e=>e instanceof Blob&&"name"in e,Dn=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||At(e)),Ie=e=>{if(Dn(e))return!0;if(Array.isArray(e))return e.some(Ie);if(e&&typeof e=="object"){for(let t in e)if(Ie(e[t]))return!0}return!1},Je=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,Ce([await r.blob()],ze(r)));else if((0,j.isAsyncIterable)(r))e.append(t,Ce([await new Response((0,Vn.ReadableStreamFrom)(r)).blob()],ze(r)));else if(At(r))e.append(t,r,ze(r));else if(Array.isArray(r))await Promise.all(r.map(n=>Je(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>Je(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=v(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.toFile=Gn;var J=I(),Yn=I(),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",Un=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Qt(e),Sn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Gn(e,t,r){if((0,Yn.checkFileSupport)(),e=await e,Un(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 Be(s),t,r)}let n=await Be(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 Be(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 Be(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 Qe=v(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.toFile=void 0;var kn=_t();Object.defineProperty(me,"toFile",{enumerable:!0,get:function(){return kn.toFile}})});var M=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.APIResource=void 0;var _e=class{constructor(t){this._client=t}};be.APIResource=_e});var B=v(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.isEmptyHeaders=F.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 En=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}};F.buildHeaders=En;var Cn=e=>{for(let t of tr(e))return!1;return!0};F.isEmptyHeaders=Cn});var je=v(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=$e;var In=K();function $e(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var rr=Object.freeze(Object.create(null)),Jn=(e=$e)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((c,P,X)=>{/[?#]/.test(P)&&(s=!0);let i=n[X],O=(s?encodeURIComponent:e)(""+i);return X!==n.length&&(i==null||typeof i=="object"&&i.toString===Object.getPrototypeOf(Object.getPrototypeOf(i.hasOwnProperty??rr)??rr)?.toString)&&(O=i+"",o.push({start:c.length+P.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(i).slice(8,-1)} is not a valid path parameter`})),c+P+(X===n.length?"":O)},""),f=a.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=l.exec(f))!==null;)o.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(o.sort((c,P)=>c.start-P.start),o.length>0){let c=0,P=o.reduce((X,i)=>{let O=" ".repeat(i.start-c),w="^".repeat(i.length);return c=i.start+i.length,X+O+w},"");throw new In.SupermemoryError(`Path parameters result in path with invalid segments: -${o.map(X=>X.error).join(` -`)} -${a} -${P}`)}return a};N.createPathTagFunction=Jn;N.path=(0,N.createPathTagFunction)($e)});var tt=v(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.Connections=void 0;var Bn=M(),An=B(),W=je(),et=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=et});var st=v(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Documents=void 0;var Qn=M(),_n=B(),$n=I(),rt=je(),nt=class extends Qn.APIResource{update(t,r={},n){return this._client.patch((0,rt.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,rt.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,rt.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))}};Xe.Documents=nt});var ft=v(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Memories=void 0;var es=M(),ts=B(),rs=I(),ot=je(),at=class extends es.APIResource{update(t,r={},n){return this._client.patch((0,ot.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,ot.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,ot.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))}};Oe.Memories=at});var ct=v(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Search=void 0;var ns=M(),it=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})}};ye.Search=it});var dt=v(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Settings=void 0;var ss=M(),ut=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=ut});var nr=v(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.Settings=q.Search=q.Memories=q.Documents=q.Connections=void 0;var os=tt();Object.defineProperty(q,"Connections",{enumerable:!0,get:function(){return os.Connections}});var as=st();Object.defineProperty(q,"Documents",{enumerable:!0,get:function(){return as.Documents}});var fs=ft();Object.defineProperty(q,"Memories",{enumerable:!0,get:function(){return fs.Memories}});var is=ct();Object.defineProperty(q,"Search",{enumerable:!0,get:function(){return is.Search}});var cs=dt();Object.defineProperty(q,"Settings",{enumerable:!0,get:function(){return cs.Settings}})});var vt=v(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=or;var us=E(),he={off:0,error:200,warn:300,info:400,debug:500},ds=(e,t,r)=>{if(e){if((0,us.hasOwn)(he,e))return e;or(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(he))}`)}};R.parseLogLevel=ds;function A(){}function qe(e,t,r){return!t||he[e]>he[r]?A:t[e].bind(t)}var vs={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 vs;let n=sr.get(t);if(n&&n[0]===r)return n[1];let s={error:qe("error",t,r),warn:qe("warn",t,r),info:qe("info",t,r),debug:qe("debug",t,r)};return sr.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 fr=v(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.defaultParseResponse=ps;var ar=vt();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 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,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 zt=v(We=>{"use strict";var Q;Object.defineProperty(We,"__esModule",{value:!0});We.APIPromise=void 0;var pt=Ue(),Ps=fr(),Pt=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),pt.__classPrivateFieldSet(this,Q,t,"f")}_thenUnwrap(t){return new e(pt.__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(pt.__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)}};We.APIPromise=Pt;Q=new WeakMap});var ir=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.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()};Te.readEnv=zs});var Ht=v(Le=>{"use strict";var Ot,yt,Ne,cr;Object.defineProperty(Le,"__esModule",{value:!0});Le.Supermemory=void 0;var L=Ue(),ms=St(),mt=E(),bs=Gt(),bt=Se(),js=Ct(),jt=L.__importStar(Ee()),xs=L.__importStar(Jt()),Xs=ke(),b=L.__importStar(K()),Os=L.__importStar(Qe()),_=L.__importStar(nr()),ys=zt(),Hs=tt(),qs=st(),hs=ft(),Ws=ct(),Ts=dt(),xt=B(),Xt=ir(),x=vt(),Ns=E(),m=class{constructor({baseURL:t=(0,Xt.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Xt.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Ot.add(this),Ne.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??yt.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,Xt.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??jt.getDefaultFetch(),L.__classPrivateFieldSet(this,Ne,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,xt.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,Ot,"m",cr).call(this)&&n||this.baseURL,o=(0,mt.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:l}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(a,{url:f,options:s});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=n===void 0?"":`, retryOf: ${n}`,P=Date.now();if((0,x.loggerFor)(this).debug(`[${u}] sending request`,(0,x.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,l,X).catch(bt.castToError),O=Date.now();if(i instanceof globalThis.Error){let Y=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let T=(0,bt.isAbortError)(i)||/timed? ?out/i.test(String(i)+("cause"in i?String(i.cause):""));if(r)return(0,x.loggerFor)(this).info(`[${u}] connection ${T?"timed out":"failed"} - ${Y}`),(0,x.loggerFor)(this).debug(`[${u}] connection ${T?"timed out":"failed"} (${Y})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:O-P,message:i.message})),this.retryRequest(s,r,n??u);throw(0,x.loggerFor)(this).info(`[${u}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,x.loggerFor)(this).debug(`[${u}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:f,durationMs:O-P,message:i.message})),T?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:i})}let w=`[${u}${c}] ${a.method} ${f} ${i.ok?"succeeded":"failed"} with status ${i.status} in ${O-P}ms`;if(!i.ok){let Y=await this.shouldRetry(i);if(r&&Y){let ne=`retrying, ${r} attempts remaining`;return await jt.CancelReadableStream(i.body),(0,x.loggerFor)(this).info(`${w} - ${ne}`),(0,x.loggerFor)(this).debug(`[${u}] response error (${ne})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:O-P})),this.retryRequest(s,r,n??u,i.headers)}let T=Y?"error; no more retries left":"error; not retryable";(0,x.loggerFor)(this).info(`${w} - ${T}`);let Ft=await i.text().catch(ne=>(0,bt.castToError)(ne).message),Dt=(0,mt.safeJSON)(Ft),Yt=Dt?void 0:Ft;throw(0,x.loggerFor)(this).debug(`[${u}] response error (${T})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,message:Yt,durationMs:Date.now()-P})),this.makeStatusError(i.status,Dt,Yt,i.headers)}return(0,x.loggerFor)(this).info(w),(0,x.loggerFor)(this).debug(`[${u}] response start`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i.url,status:i.status,headers:i.headers,durationMs:O-P})),{response:i,options:s,controller:X,requestLogID:u,retryOfRequestLogID:n,startTime:P}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:a,...f}=r||{};o&&o.addEventListener("abort",()=>s.abort());let l=setTimeout(()=>s.abort(),n),u=globalThis.ReadableStream&&f.body instanceof globalThis.ReadableStream||typeof f.body=="object"&&f.body!==null&&Symbol.asyncIterator in f.body,c={signal:s.signal,...u?{duplex:"half"}:{},method:"GET",...f};a&&(c.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,c)}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,a=s?.get("retry-after-ms");if(a){let l=parseFloat(a);Number.isNaN(l)||(o=l)}let f=s?.get("retry-after");if(f&&!o){let l=parseFloat(f);Number.isNaN(l)?o=Date.parse(f)-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,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,l=this.buildURL(o,a,f);"timeout"in n&&(0,mt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:c}=this.buildBody({options:n}),P=await this.buildHeaders({options:t,method:s,bodyHeaders:u,retryCount:r});return{req:{method:s,headers:P,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...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 a=(0,xt.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,xt.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:jt.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Ne,"f").call(this,{body:t,headers:n})}};Le.Supermemory=m;yt=m,Ne=new WeakMap,Ot=new WeakSet,cr=function(){return this.baseURL!=="https://api.supermemory.ai"};m.Supermemory=yt;m.DEFAULT_TIMEOUT=6e4;m.SupermemoryError=b.SupermemoryError;m.APIError=b.APIError;m.APIConnectionError=b.APIConnectionError;m.APIConnectionTimeoutError=b.APIConnectionTimeoutError;m.APIUserAbortError=b.APIUserAbortError;m.NotFoundError=b.NotFoundError;m.ConflictError=b.ConflictError;m.RateLimitError=b.RateLimitError;m.BadRequestError=b.BadRequestError;m.AuthenticationError=b.AuthenticationError;m.InternalServerError=b.InternalServerError;m.PermissionDeniedError=b.PermissionDeniedError;m.UnprocessableEntityError=b.UnprocessableEntityError;m.toFile=Os.toFile;m.Memories=hs.Memories;m.Documents=qs.Documents;m.Search=Ws.Search;m.Settings=Ts.Settings;m.Connections=Hs.Connections});var dr=v((d,ur)=>{"use strict";d=ur.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 Ls=Ht();Object.defineProperty(d,"default",{enumerable:!0,get:function(){return Ls.Supermemory}});var Vs=Qe();Object.defineProperty(d,"toFile",{enumerable:!0,get:function(){return Vs.toFile}});var Rs=zt();Object.defineProperty(d,"APIPromise",{enumerable:!0,get:function(){return Rs.APIPromise}});var gs=Ht();Object.defineProperty(d,"Supermemory",{enumerable:!0,get:function(){return gs.Supermemory}});var H=K();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 lr={};Cr(lr,{getRequestIntegrity:()=>Cs,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>=Ys)break;n.length>Us||/[^\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 qt(e){return(0,Ve.createHash)("sha256").update(e).digest("hex")}function Es(e,t){let r=[qt(e),qt(t),vr].join(":");return(0,Ve.createHmac)("sha256",ks).update(r).digest("base64url")}function Cs(e,t){let r=qt(t),n=Es(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${vr}`,n].join(".")}}var Ve,Ms,Ys,Us,Ss,vr,ks,pr=Er(()=>{Ve=require("node:crypto");Ms=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Ys=50,Us=128,Ss=1024;vr=1,ks="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var zr=v((ba,Pr)=>{var Is=dr().default,{getRequestIntegrity:Js,validateApiKeyFormat:Bs,validateContainerTag:As}=(pr(),Jr(lr)),Qs="claudecode_default",_s=process.env.SUPERMEMORY_API_URL||"https://api.supermemory.ai";function $s(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 eo=`Developer coding session transcript. Focus on USER message and intent. +var m=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var F=m((Oe,M)=>{var d=require("node:fs"),C=require("node:path"),re=require("node:os"),se=require("node:crypto"),ie=C.join(re.homedir(),".supermemory-claude","memories"),ce=`Developer coding session transcript. Focus on USER message and intent. RULES: -- Extract USER's action/intent, not every detail assistant provides matter +- Extract USER's action/intent, not every detail assistant provides - Condense assistant responses into what user gained from it - Skip granular facts from assistant output @@ -17,115 +13,42 @@ EXTRACT: - Decisions: "chose SQLite for local storage" - Learnings: "learned about React Server Components" -EXAMPLES: -| Transcript | Memory | -| [role:user] research about the whisper.cpp -> https://github.com/ggml-org/whisper.cpp/blob/master/src/whisper.cpp [user:end]| " starts research about whisper.cpp" | -| [role:assistant] ## whisper.cpp Architecture Summary - This is highly relevant for your parakeet.cpp implementation. Here are the key patterns: - ### Core Architecture - **Two-level context design:** - - whisper_context - holds model weights, vocab, hyperparameters (persistent) - - whisper_state - runtime state, KV caches, backends (can have multiple per context) [assistant:end] | "Assistant did a deep dive on whisper architecture" | -| [role:user] Can we explain what we are currently doing in this repository? [user:end] | "" | - SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,to=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,ae=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" - Conventions: "components in PascalCase", "hooks prefixed with use" - Patterns: "all API routes use withAuth wrapper", "errors thrown as ApiError" - Setup: "requires .env with DATABASE_URL", "run pnpm db:migrate first" -- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching" - -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]" |`,ht=class{constructor(t,r){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let n=Bs(t);if(!n.valid)throw new Error(`Invalid API key: ${n.reason}`);let s=r||Qs,o=As(s);o.valid||console.warn(`Container tag warning: ${o.reason}`);let a=Js(t,s);this.client=new Is({apiKey:t,baseURL:_s,defaultHeaders:a}),this.containerTag=s}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code-plugin",...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:$s(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=(u,c=P=>P)=>u.filter(P=>{let X=String(c(P)).toLowerCase().trim();return!X||s.has(X)?!1:(s.add(X),!0)}),a=o(n.profile?.static||[]),f=o(n.profile?.dynamic||[]),l;if(n.searchResults){let u=n.searchResults.results.map(c=>({id:c.id,memory:c.content||c.context||"",similarity:c.similarity,title:c.title,updatedAt:c.updatedAt}));l={results:o(u,c=>c.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:f},searchResults:l}}};Pr.exports={SupermemoryClient:ht,PERSONAL_ENTITY_CONTEXT:eo,REPO_ENTITY_CONTEXT:to}});var Wt=v((ja,mr)=>{var{execSync:Re}=require("node:child_process"),$=require("node:path");function ro(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return Re("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=Re("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return Re("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):Re("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}mr.exports={getGitRoot:ro}});var Tt=v((xa,yr)=>{var ee=require("node:fs"),ge=require("node:path"),{getGitRoot:br}=Wt(),jr=ge.join(".claude",".supermemory-claude"),xr="config.json";function Xr(e){let r=br(e)||e;return ge.join(r,jr,xr)}function Or(e){try{let t=Xr(e);if(ee.existsSync(t))return JSON.parse(ee.readFileSync(t,"utf-8"))}catch{}return null}function no(e,t){let n=br(e)||e,s=ge.join(n,jr),o=ge.join(s,xr);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:no}});var Wr=v((Xa,hr)=>{var{execSync:so}=require("node:child_process"),oo=require("node:crypto"),{loadProjectConfig:Hr}=Tt(),{getGitRoot:we}=Wt();function qr(e){return oo.createHash("sha256").update(e).digest("hex").slice(0,16)}function Nt(e){try{let r=so("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 ao(e){let t=Hr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=we(e)||e;return`claudecode_project_${qr(n)}`}function fo(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function io(e){let t=Hr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=we(e)||e,o=Nt(n)||n.split("/").pop()||"unknown";return`repo_${fo(o)}`}function co(e){let r=we(e)||e;return Nt(r)||r.split("/").pop()||"unknown"}hr.exports={sha256:qr,getGitRoot:we,getGitRepoName:Nt,getContainerTag:ao,getRepoContainerTag:io,getProjectName:co}});var Tr=v((Oa,uo)=>{uo.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var Nr=v((ya,vo)=>{vo.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var wr=v((Ha,gr)=>{var lo=require("node:http"),g=require("node:fs"),Lr=require("node:path"),po=require("node:os"),{execFile:Lt}=require("node:child_process"),Po=Tr(),zo=Nr(),Rt=Lr.join(po.homedir(),".supermemory-claude"),D=Lr.join(Rt,"credentials.json"),Vr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",Vt=19876,mo=25e3;function bo(){g.existsSync(Rt)||g.mkdirSync(Rt,{recursive:!0})}function jo(){try{if(g.existsSync(D)){let e=JSON.parse(g.readFileSync(D,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Rr(e){bo();let t={apiKey:e,savedAt:new Date().toISOString()};g.writeFileSync(D,JSON.stringify(t,null,2))}function xo(){try{g.existsSync(D)&&g.unlinkSync(D)}catch{}}function Xo(e){let t=r=>{r&&console.warn("Failed to open browser:",r.message)};process.platform==="win32"?Lt("explorer.exe",[e],t):process.platform==="darwin"?Lt("open",[e],t):Lt("xdg-open",[e],t)}function Oo(){return new Promise((e,t)=>{let r=!1,n=lo.createServer((s,o)=>{let a=new URL(s.url,`http://localhost:${Vt}`);if(a.pathname==="/callback"){let f=a.searchParams.get("apikey")||a.searchParams.get("api_key");f?.startsWith("sm_")?(Rr(f),o.writeHead(200,{"Content-Type":"text/html"}),o.end(Po),r=!0,n.close(),e(f)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(zo))}else o.writeHead(404),o.end("Not found")});n.listen(Vt,"127.0.0.1",()=>{let s=`http://localhost:${Vt}/callback`,o=`${Vr}?callback=${encodeURIComponent(s)}&client=claude_code`;Xo(o)}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},mo)})}gr.exports={AUTH_BASE_URL:Vr,CREDENTIALS_FILE:D,loadCredentials:jo,saveCredentials:Rr,clearCredentials:xo,startAuthFlow:Oo}});var Fr=v((qa,Mr)=>{var re=require("node:fs"),Zr=require("node:path"),yo=require("node:os"),{loadCredentials:Ho}=wr(),{loadProjectConfig:gt}=Tt(),Ze=Zr.join(yo.homedir(),".supermemory-claude"),te=Zr.join(Ze,"settings.json"),Me={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function qo(){re.existsSync(Ze)||re.mkdirSync(Ze,{recursive:!0})}function wt(){let e={...Me};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 ho(e){qo();let t={...e};delete t.apiKey,re.writeFileSync(te,JSON.stringify(t,null,2))}function Wo(e,t){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;let r=gt(t||process.cwd());if(r?.apiKey)return r.apiKey;let n=Ho();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function To(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function No(e){let t=wt(),r=gt(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(a=>a.toLowerCase())}function Lo(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function Vo(e){let t=wt(),r=gt(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,a=t.signalKeywords||Me.signalKeywords,f=r?.signalKeywords||[],l=[...new Set([...a,...f])].map(c=>c.toLowerCase()),u=r?.signalTurnsBefore||t.signalTurnsBefore||Me.signalTurnsBefore;return{enabled:o,keywords:l,turnsBefore:u}}Mr.exports={SETTINGS_DIR:Ze,SETTINGS_FILE:te,DEFAULT_SETTINGS:Me,loadSettings:wt,saveSettings:ho,getApiKey:Wo,debugLog:To,getIncludeTools:No,shouldIncludeTool:Lo,getSignalConfig:Vo}});var Sr=v((ha,Ur)=>{var Dr="The following is recalled context. Reference it only when relevant to the conversation.",Yr="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 Zt(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 f=t.toLocaleString("en",{month:"short"});return t.getFullYear()===r.getFullYear()?`${t.getDate()} ${f}`:`${t.getDate()} ${f}, ${t.getFullYear()}`}catch{return""}}function Ro(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):[],f=r?(e.searchResults?.results||[]).slice(0,n):[];if(o.length===0&&a.length===0&&f.length===0)return null;let l=[];if(o.length>0){let c=o.map(P=>`- ${P}`).join(` -`);l.push(`## User Profile (Persistent) -${c}`)}if(a.length>0){let c=a.map(P=>`- ${P}`).join(` -`);l.push(`## Recent Context -${c}`)}if(f.length>0){let c=f.map(P=>{let X=P.memory??"",i=P.updatedAt?Zt(P.updatedAt):"",O=P.similarity!=null?`[${Math.round(P.similarity*100)}%]`:"";return`- ${i?`[${i}] `:""}${X} ${O}`.trim()});l.push(`## Relevant Memories (with relevance %) -${c.join(` -`)}`)}let u=l.join(` +- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching"`;function le(t){d.existsSync(t)||d.mkdirSync(t,{recursive:!0})}function h(t,e){return C.join(ie,t,e)}function w(t){if(!d.existsSync(t))return[];let e=d.readdirSync(t).filter(n=>n.endsWith(".json")),o=[];for(let n of e)try{let r=d.readFileSync(C.join(t,n),"utf-8");o.push(JSON.parse(r))}catch{}return o}function ue(t,e){let o=(t.content||"").toLowerCase(),n=0;for(let c of e)o.includes(c)&&(n+=1);let r=Date.now()-new Date(t.createdAt||0).getTime(),s=Math.max(0,1-r/(720*60*60*1e3));return n+s*.5}var N=class{constructor(e){this.containerTag=e||"default"}async addMemory(e,o,n={}){let r=o||this.containerTag,s=n.type==="project-knowledge"?"repo":"personal",c=h(s,r);le(c);let i=se.randomUUID(),a={id:i,content:e,metadata:{sm_source:"claude-code-local",...n},createdAt:new Date().toISOString()};return d.writeFileSync(C.join(c,`${i}.json`),JSON.stringify(a,null,2)),{id:i,status:"saved",containerTag:r}}async search(e,o,n={}){let r=o||this.containerTag,s=n.limit||10,c=h("personal",r),i=h("repo",r),a=[...w(c),...w(i)];if(a.length===0)return{results:[],total:0};let u=e.toLowerCase().split(/\s+/).filter(l=>l.length>2),g=a.map(l=>({memory:l.content||"",metadata:l.metadata,updatedAt:l.createdAt,similarity:u.length>0?ue(l,u)/u.length:0})).filter(l=>l.similarity>0).sort((l,f)=>f.similarity-l.similarity).slice(0,s);return{results:g,total:g.length}}async getProfile(e,o,n=5){let r=e||this.containerTag,s=h("personal",r),c=h("repo",r),i=w(s),a=w(c),u=(p,O)=>new Date(O.createdAt||0).getTime()-new Date(p.createdAt||0).getTime();i.sort(u),a.sort(u);let g=a.slice(0,n).map(p=>p.content),l=i.slice(0,n).map(p=>p.content),f=[...i,...a].sort(u).slice(0,n),$={results:f.map(p=>({id:p.id,memory:p.content,similarity:1,updatedAt:p.createdAt})),total:f.length};return{profile:{static:g,dynamic:l},searchResults:$}}};M.exports={LocalMemoryClient:N,PERSONAL_ENTITY_CONTEXT:ce,REPO_ENTITY_CONTEXT:ae}});var b=m((Me,L)=>{var{execSync:j}=require("node:child_process"),y=require("node:path");function ge(t){let e=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(e)return j("git rev-parse --show-toplevel",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let o=j("git rev-parse --git-common-dir",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(o===".git")return j("git rev-parse --show-toplevel",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=y.resolve(t,o);return y.basename(n)===".git"&&!n.includes(`${y.sep}.git${y.sep}`)?y.dirname(n):j("git rev-parse --show-toplevel",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}L.exports={getGitRoot:ge}});var D=m((Fe,K)=>{var S=require("node:fs"),E=require("node:path"),{getGitRoot:k}=b(),U=E.join(".claude",".supermemory-claude"),G="config.json";function B(t){let o=k(t)||t;return E.join(o,U,G)}function J(t){try{let e=B(t);if(S.existsSync(e))return JSON.parse(S.readFileSync(e,"utf-8"))}catch{}return null}function pe(t,e){let n=k(t)||t,r=E.join(n,U),s=E.join(r,G);S.existsSync(r)||S.mkdirSync(r,{recursive:!0});let i={...J(t)||{},...e};return S.writeFileSync(s,JSON.stringify(i,null,2)),s}K.exports={getConfigPath:B,loadProjectConfig:J,saveProjectConfig:pe}});var W=m((Le,z)=>{var{execSync:fe}=require("node:child_process"),me=require("node:crypto"),{loadProjectConfig:Y}=D(),{getGitRoot:P}=b();function X(t){return me.createHash("sha256").update(t).digest("hex").slice(0,16)}function A(t){try{let o=fe("git remote get-url origin",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/);return o?o[1]:null}catch{return null}}function de(t){let e=Y(t);if(e?.personalContainerTag)return e.personalContainerTag;let n=P(t)||t;return`claudecode_project_${X(n)}`}function he(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function ye(t){let e=Y(t);if(e?.repoContainerTag)return e.repoContainerTag;let n=P(t)||t,s=A(n)||n.split("/").pop()||"unknown";return`repo_${he(s)}`}function Se(t){let o=P(t)||t;return A(o)||o.split("/").pop()||"unknown"}z.exports={sha256:X,getGitRoot:P,getGitRepoName:A,getContainerTag:de,getRepoContainerTag:ye,getProjectName:Se}});var Z=m((ke,V)=>{var R=require("node:fs"),H=require("node:path"),Te=require("node:os"),{loadProjectConfig:Q}=D(),v=H.join(Te.homedir(),".supermemory-claude"),T=H.join(v,"settings.json"),x={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Re(){R.existsSync(v)||R.mkdirSync(v,{recursive:!0})}function I(){let t={...x};try{if(R.existsSync(T)){let e=R.readFileSync(T,"utf-8");Object.assign(t,JSON.parse(e))}}catch(e){console.error(`Settings: Failed to load ${T}: ${e.message}`)}return process.env.SUPERMEMORY_DEBUG==="true"&&(t.debug=!0),t}function $e(t){Re();let e={...t};R.writeFileSync(T,JSON.stringify(e,null,2))}function we(t,e,o){if(t.debug){let n=new Date().toISOString();console.error(o?`[${n}] ${e}: ${JSON.stringify(o)}`:`[${n}] ${e}`)}}function Ce(t){let e=I(),o=Q(t||process.cwd()),n=e.includeTools||[],r=o?.includeTools||[];return[...new Set([...n,...r])].map(c=>c.toLowerCase())}function je(t,e){return e.length===0?!1:e.includes(t.toLowerCase())}function Ee(t){let e=I(),o=Q(t||process.cwd()),n=e.signalExtraction||!1,r=o?.signalExtraction,s=r!==void 0?r:n,c=e.signalKeywords||x.signalKeywords,i=o?.signalKeywords||[],a=[...new Set([...c,...i])].map(g=>g.toLowerCase()),u=o?.signalTurnsBefore||e.signalTurnsBefore||x.signalTurnsBefore;return{enabled:s,keywords:a,turnsBefore:u}}V.exports={SETTINGS_DIR:v,SETTINGS_FILE:T,DEFAULT_SETTINGS:x,loadSettings:I,saveSettings:$e,debugLog:we,getIncludeTools:Ce,shouldIncludeTool:je,getSignalConfig:Ee}});var oe=m((Ue,ne)=>{var ee="The following is recalled context. Reference it only when relevant to the conversation.",te="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 q(t){try{let e=new Date(t),o=new Date,n=(o.getTime()-e.getTime())/1e3,r=n/60,s=n/3600,c=n/86400;if(r<30)return"just now";if(r<60)return`${Math.floor(r)}mins ago`;if(s<24)return`${Math.floor(s)}hrs ago`;if(c<7)return`${Math.floor(c)}d ago`;let i=e.toLocaleString("en",{month:"short"});return e.getFullYear()===o.getFullYear()?`${e.getDate()} ${i}`:`${e.getDate()} ${i}, ${e.getFullYear()}`}catch{return""}}function Pe(t,e=!0,o=!1,n=10,r=!0){if(!t)return null;let s=e?(t.profile?.static||[]).slice(0,n):[],c=e?(t.profile?.dynamic||[]).slice(0,n):[],i=o?(t.searchResults?.results||[]).slice(0,n):[];if(s.length===0&&c.length===0&&i.length===0)return null;let a=[];if(s.length>0){let g=s.map(l=>`- ${l}`).join(` +`);a.push(`## User Profile (Persistent) +${g}`)}if(c.length>0){let g=c.map(l=>`- ${l}`).join(` +`);a.push(`## Recent Context +${g}`)}if(i.length>0){let g=i.map(l=>{let f=l.memory??"",$=l.updatedAt?q(l.updatedAt):"",p=l.similarity!=null?`[${Math.round(l.similarity*100)}%]`:"";return`- ${$?`[${$}] `:""}${f} ${p}`.trim()});a.push(`## Relevant Memories (with relevance %) +${g.join(` +`)}`)}let u=a.join(` -`);return s?` -${Dr} +`);return r?` +${ee} ${u} -${Yr} -`:u}function go(e){let t=e.filter(n=>n.content);if(t.length===0)return null;let r=t.map(n=>n.label?`${n.label} +${te} +`:u}function ve(t){let e=t.filter(n=>n.content);if(e.length===0)return null;let o=e.map(n=>n.label?`${n.label} ${n.content}`:n.content);return` -${Dr} +${ee} -${r.join(` +${o.join(` --- `)} -${Yr} -`}function wo(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??"",f=o.updatedAt?Zt(o.updatedAt):"",l=o.similarity!=null?`[${Math.round(o.similarity*100)}%]`:"";return`${f?`[${f}] `:""}${a} ${l}`.trim()});return`${n} -${s.join(` -`)}`}Ur.exports={formatContext:Ro,combineContexts:go,formatRelativeTime:Zt,formatSearchResults:wo}});var{SupermemoryClient:Zo}=zr(),{getProjectName:Mo,getContainerTag:Fo,getRepoContainerTag:Do}=Wr(),{loadSettings:Yo,getApiKey:Uo}=Fr(),{formatSearchResults:Mt}=Sr();function So(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 Go(){let{containerType:e,query:t}=So(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=Yo(),n;try{n=Uo(r)}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 s=process.cwd(),o=Mo(s),a=Fo(s),f=Do(s);try{let l=new Zo(n,a);if(console.log(`Project: ${o} -`),e==="both"){let[u,c]=await Promise.all([l.search(t,a,{limit:5}),l.search(t,f,{limit:5})]);u.results?.length>0&&console.log(Mt(t,u.results,"Personal")),c.results?.length>0&&(u.results?.length>0&&console.log(""),console.log(Mt(t,c.results,"Project"))),!u.results?.length&&!c.results?.length&&console.log(`No memories found for "${t}"`)}else{let u=e==="user"?a:f,c=e==="user"?"Personal":"Project",P=await l.search(t,u,{limit:10});console.log(Mt(t,P.results,c))}}catch(l){console.log(`Error searching memories: ${l.message}`)}}Go().catch(e=>{console.error(`Fatal error: ${e.message}`),process.exit(1)}); +${te} +`}function xe(t,e,o){let n=o?`${o} memories for "${t}"`:`Memories for "${t}"`;if(!e||e.length===0)return`No ${o?`${o.toLowerCase()} `:""}memories found for "${t}"`;let r=e.map(s=>{let c=s.memory??"",i=s.updatedAt?q(s.updatedAt):"",a=s.similarity!=null?`[${Math.round(s.similarity*100)}%]`:"";return`${i?`[${i}] `:""}${c} ${a}`.trim()});return`${n} +${r.join(` +`)}`}ne.exports={formatContext:Pe,combineContexts:ve,formatRelativeTime:q,formatSearchResults:xe}});var{LocalMemoryClient:Ne}=F(),{getProjectName:be,getContainerTag:De,getRepoContainerTag:Ae}=W(),{loadSettings:Ge}=Z(),{formatSearchResults:_}=oe();function Ie(t){let e="both",o=[];for(let n of t)n==="--user"?e="user":n==="--repo"?e="repo":n==="--both"?e="both":o.push(n);return{containerType:e,query:o.join(" ")}}async function qe(){let{containerType:t,query:e}=Ie(process.argv.slice(2));if(!e||!e.trim()){console.log("No search query provided. Please specify what you want to search for.");return}let o=process.cwd(),n=be(o),r=De(o),s=Ae(o);try{let c=new Ne(r);if(console.log(`Project: ${n} +`),t==="both"){let[i,a]=await Promise.all([c.search(e,r,{limit:5}),c.search(e,s,{limit:5})]);i.results?.length>0&&console.log(_(e,i.results,"Personal")),a.results?.length>0&&(i.results?.length>0&&console.log(""),console.log(_(e,a.results,"Project"))),!i.results?.length&&!a.results?.length&&console.log(`No memories found for "${e}"`)}else{let i=t==="user"?r:s,a=t==="user"?"Personal":"Project",u=await c.search(e,i,{limit:10});console.log(_(e,u.results,a))}}catch(c){console.log(`Error searching memories: ${c.message}`)}}qe().catch(t=>{console.error(`Fatal error: ${t.message}`),process.exit(1)}); diff --git a/plugin/scripts/summary-hook.cjs b/plugin/scripts/summary-hook.cjs index 0827659..b334845 100755 --- a/plugin/scripts/summary-hook.cjs +++ b/plugin/scripts/summary-hook.cjs @@ -1,12 +1,8 @@ #!/usr/bin/env node -var Ce=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var cn=Object.getOwnPropertyNames;var un=Object.prototype.hasOwnProperty;var dn=(e,t)=>()=>(e&&(t=e(e=0)),t);var v=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),vn=(e,t)=>{for(var r in t)Ce(e,r,{get:t[r],enumerable:!0})},ln=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of cn(t))!un.call(e,s)&&s!==r&&Ce(e,s,{get:()=>t[s],enumerable:!(n=fn(t,s))||n.enumerable});return e};var pn=e=>ln(Ce({},"__esModule",{value:!0}),e);var Ae=v(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.__setModuleDefault=N.__createBinding=void 0;N.__classPrivateFieldSet=Pn;N.__classPrivateFieldGet=zn;N.__importStar=mn;N.__exportStar=xn;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 zn(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 Be=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=Be;var er=Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t};N.__setModuleDefault=er;var Je=function(e){return Je=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Je(e)};function mn(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Je(e),n=0;n{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.uuid4=void 0;var bn=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=bn});var Qe=v(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.castToError=void 0;I.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)};I.castToError=Xn});var J=v(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 On=Qe(),ue=class extends Error{};z.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 C({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 ze(t,o,n,s):t===429?new me(t,o,n,s):t>=500?new xe(t,o,n,s):new e(t,o,n,s)}};z.APIError=y;var _e=class extends y{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};z.APIUserAbortError=_e;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 $e=class extends C{constructor({message:t}={}){super({message:t??"Request timed out."})}};z.APIConnectionTimeoutError=$e;var de=class extends y{};z.BadRequestError=de;var ve=class extends y{};z.AuthenticationError=ve;var le=class extends y{};z.PermissionDeniedError=le;var pe=class extends y{};z.NotFoundError=pe;var Pe=class extends y{};z.ConflictError=Pe;var ze=class extends y{};z.UnprocessableEntityError=ze;var me=class extends y{};z.RateLimitError=me;var xe=class extends y{};z.InternalServerError=xe});var A=v(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=hn;p.isEmptyObj=Wn;p.hasOwn=Tn;p.isObj=Nn;var B=J(),yn=/^[a-z][a-z0-9+.-]*:/i,Hn=e=>yn.test(e);p.isAbsoluteURL=Hn;var qn=e=>(p.isArray=Array.isArray,(0,p.isArray)(e));p.isArray=qn;p.isReadonlyArray=p.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};p.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};p.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`)};p.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`)};p.coerceFloat=gn;var wn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;p.coerceBoolean=wn;var Zn=e=>{if(e!=null)return(0,p.coerceInteger)(e)};p.maybeCoerceInteger=Zn;var Mn=e=>{if(e!=null)return(0,p.coerceFloat)(e)};p.maybeCoerceFloat=Mn;var Fn=e=>{if(e!=null)return(0,p.coerceBoolean)(e)};p.maybeCoerceBoolean=Fn;var Dn=e=>{try{return JSON.parse(e)}catch{return}};p.safeJSON=Dn});var rr=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.sleep=void 0;var Un=e=>new Promise(t=>setTimeout(t,e));be.sleep=Un});var et=v(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.VERSION=void 0;je.VERSION="4.0.0"});var ir=v(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.getPlatformHeaders=Y.isRunningInBrowser=void 0;var Q=et(),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":sr(Deno.build.os),"X-Stainless-Arch":nr(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":sr(globalThis.process.platform??"unknown"),"X-Stainless-Arch":nr(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,i=n[3]||0;return{browser:t,version:`${s}.${o}.${i}`}}}return null}var nr=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",sr=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"),or,En=()=>or??(or=Gn());Y.getPlatformHeaders=En});var tt=v(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.getDefaultFetch=Kn;w.makeReadableStream=ar;w.ReadableStreamFrom=In;w.ReadableStreamToAsyncIterable=Cn;w.CancelReadableStream=Jn;function Kn(){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 ar(...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 In(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ar({start(){},async pull(r){let{done:n,value:s}=await t.next();n?r.close():r.enqueue(s)},async cancel(){await t.return?.()}})}function Cn(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 fr=v(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 _=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=rt;j.getName=Oe;var An=tt(),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 rt(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)=>nt(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 cr=new WeakMap;function ts(e){let t=typeof e=="function"?e:e.fetch,r=cr.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 cr.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])=>st(r,n,s))),r};j.createForm=rs;var ur=e=>e instanceof Blob&&"name"in e,ns=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||ur(e)),nt=e=>{if(ns(e))return!0;if(Array.isArray(e))return e.some(nt);if(e&&typeof e=="object"){for(let t in e)if(nt(e[t]))return!0}return!1},st=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,rt([await r.blob()],Oe(r)));else if((0,j.isAsyncIterable)(r))e.append(t,rt([await new Response((0,An.ReadableStreamFrom)(r)).blob()],Oe(r)));else if(ur(r))e.append(t,r,Oe(r));else if(Array.isArray(r))await Promise.all(r.map(n=>st(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>st(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 vr=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.toFile=as;var $=_(),ss=_(),dr=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"&&dr(e),is=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function as(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(is(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,$.makeFile)(await ot(s),t,r)}let n=await ot(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 ot(e){let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(dr(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if((0,$.isAsyncIterable)(e))for await(let r of e)t.push(...await ot(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${fs(e)}`)}return t}function fs(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var at=v(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.toFile=void 0;var cs=vr();Object.defineProperty(ye,"toFile",{enumerable:!0,get:function(){return cs.toFile}})});var S=v(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=v(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.isEmptyHeaders=G.buildHeaders=void 0;var lr=A(),pr=Symbol("brand.privateNullableHeaders");function*Pr(e){if(!e)return;if(pr 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,lr.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,lr.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 us=e=>{let t=new Headers,r=new Set;for(let n of e){let s=new Set;for(let[o,i]of Pr(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{[pr]:!0,values:t,nulls:r}};G.buildHeaders=us;var ds=e=>{for(let t of Pr(e))return!1;return!0};G.isEmptyHeaders=ds});var qe=v(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.path=V.createPathTagFunction=void 0;V.encodeURIPath=ct;var vs=J();function ct(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var zr=Object.freeze(Object.create(null)),ls=(e=ct)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],i=r.reduce((d,P,x)=>{/[?#]/.test(P)&&(s=!0);let f=n[x],O=(s?encodeURIComponent:e)(""+f);return x!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??zr)??zr)?.toString)&&(O=f+"",o.push({start:d.length+P.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),d+P+(x===n.length?"":O)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=c.exec(a))!==null;)o.push({start:u.index,length:u[0].length,error:`Value "${u[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((x,f)=>{let O=" ".repeat(f.start-d),g="^".repeat(f.length);return d=f.start+f.length,x+O+g},"");throw new vs.SupermemoryError(`Path parameters result in path with invalid segments: -${o.map(x=>x.error).join(` -`)} -${i} -${P}`)}return i};V.createPathTagFunction=ls;V.path=(0,V.createPathTagFunction)(ct)});var dt=v(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.Connections=void 0;var ps=S(),Ps=ee(),L=qe(),ut=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=ut});var pt=v(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.Documents=void 0;var zs=S(),ms=ee(),xs=_(),vt=qe(),lt=class extends zs.APIResource{update(t,r={},n){return this._client.patch((0,vt.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,vt.path)`/v3/documents/${t}`,{...r,headers:(0,ms.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,vt.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,xs.multipartFormRequestOptions)({body:t,...r},this._client))}};We.Documents=lt});var mt=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.Memories=void 0;var bs=S(),js=ee(),Xs=_(),Pt=qe(),zt=class extends bs.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,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,Pt.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 bt=v(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 Xt=v(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.Settings=void 0;var ys=S(),jt=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=jt});var mr=v(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.Settings=q.Search=q.Memories=q.Documents=q.Connections=void 0;var Hs=dt();Object.defineProperty(q,"Connections",{enumerable:!0,get:function(){return Hs.Connections}});var qs=pt();Object.defineProperty(q,"Documents",{enumerable:!0,get:function(){return qs.Documents}});var hs=mt();Object.defineProperty(q,"Memories",{enumerable:!0,get:function(){return hs.Memories}});var Ws=bt();Object.defineProperty(q,"Search",{enumerable:!0,get:function(){return Ws.Search}});var Ts=Xt();Object.defineProperty(q,"Settings",{enumerable:!0,get:function(){return Ts.Settings}})});var Ot=v(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.formatRequestDetails=Z.parseLogLevel=void 0;Z.loggerFor=br;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;br(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Re))}`)}};Z.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},xr=new WeakMap;function br(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Vs;let n=xr.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 xr.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);Z.formatRequestDetails=Rs});var Xr=v(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.defaultParseResponse=gs;var jr=Ot();async function gs(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 c=r.headers.get("content-type")?.split(";")[0]?.trim();return c?.includes("application/json")||c?.endsWith("+json")?await r.json():await r.text()})();return(0,jr.loggerFor)(e).debug(`[${n}] response parsed`,(0,jr.formatRequestDetails)({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}});var ht=v(ge=>{"use strict";var re;Object.defineProperty(ge,"__esModule",{value:!0});ge.APIPromise=void 0;var Ht=Ae(),ws=Xr(),qt=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),Ht.__classPrivateFieldSet(this,re,t,"f")}_thenUnwrap(t){return new e(Ht.__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(Ht.__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=qt;re=new WeakMap});var Or=v(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.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()};we.readEnv=Zs});var wt=v(Me=>{"use strict";var Rt,gt,Ze,yr;Object.defineProperty(Me,"__esModule",{value:!0});Me.Supermemory=void 0;var R=Ae(),Ms=tr(),Wt=A(),Fs=rr(),Tt=Qe(),Ds=ir(),Nt=R.__importStar(tt()),Us=R.__importStar(fr()),Ys=et(),b=R.__importStar(J()),Ss=R.__importStar(at()),ne=R.__importStar(mr()),Gs=ht(),ks=dt(),Es=pt(),Ks=mt(),Is=bt(),Cs=Xt(),Lt=ee(),Vt=Or(),X=Ot(),Js=A(),m=class{constructor({baseURL:t=(0,Vt.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,Vt.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Rt.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 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??gt.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,Vt.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Nt.getDefaultFetch(),R.__classPrivateFieldSet(this,Ze,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,Lt.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 ${Ys.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=!R.__classPrivateFieldGet(this,Rt,"m",yr).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,Js.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 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:i,url:a,timeout:c}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:s});let u="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(`[${u}] 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 x=new AbortController,f=await this.fetchWithTimeout(a,i,c,x).catch(Tt.castToError),O=Date.now();if(f instanceof globalThis.Error){let T=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.APIUserAbortError;let h=(0,Tt.isAbortError)(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(r)return(0,X.loggerFor)(this).info(`[${u}] connection ${h?"timed out":"failed"} - ${T}`),(0,X.loggerFor)(this).debug(`[${u}] connection ${h?"timed out":"failed"} (${T})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:a,durationMs:O-P,message:f.message})),this.retryRequest(s,r,n??u);throw(0,X.loggerFor)(this).info(`[${u}] connection ${h?"timed out":"failed"} - error; no more retries left`),(0,X.loggerFor)(this).debug(`[${u}] connection ${h?"timed out":"failed"} (error; no more retries left)`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:a,durationMs:O-P,message:f.message})),h?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:f})}let g=`[${u}${d}] ${i.method} ${a} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${O-P}ms`;if(!f.ok){let T=await this.shouldRetry(f);if(r&&T){let ce=`retrying, ${r} attempts remaining`;return await Nt.CancelReadableStream(f.body),(0,X.loggerFor)(this).info(`${g} - ${ce}`),(0,X.loggerFor)(this).debug(`[${u}] response error (${ce})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:O-P})),this.retryRequest(s,r,n??u,f.headers)}let h=T?"error; no more retries left":"error; not retryable";(0,X.loggerFor)(this).info(`${g} - ${h}`);let U=await f.text().catch(ce=>(0,Tt.castToError)(ce).message),E=(0,Wt.safeJSON)(U),$t=E?void 0:U;throw(0,X.loggerFor)(this).debug(`[${u}] response error (${h})`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:$t,durationMs:Date.now()-P})),this.makeStatusError(f.status,E,$t,f.headers)}return(0,X.loggerFor)(this).info(g),(0,X.loggerFor)(this).debug(`[${u}] response start`,(0,X.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:O-P})),{response:f,options:s,controller:x,requestLogID:u,retryOfRequestLogID:n,startTime:P}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:i,...a}=r||{};o&&o.addEventListener("abort",()=>s.abort());let c=setTimeout(()=>s.abort(),n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:s.signal,...u?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,d)}finally{clearTimeout(c)}}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 c=parseFloat(i);Number.isNaN(c)||(o=c)}let a=s?.get("retry-after");if(a&&!o){let c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){let c=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,c)}return await(0,Fs.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,c=this.buildURL(o,i,a);"timeout"in n&&(0,Wt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:d}=this.buildBody({options:n}),P=await this.buildHeaders({options:t,method:s,bodyHeaders:u,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:c,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,Lt.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(i),i.values}buildBody({options:{body:t,headers:r}}){if(!t)return{bodyHeaders:void 0,body:void 0};let n=(0,Lt.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:Nt.ReadableStreamFrom(t)}:R.__classPrivateFieldGet(this,Ze,"f").call(this,{body:t,headers:n})}};Me.Supermemory=m;gt=m,Ze=new WeakMap,Rt=new WeakSet,yr=function(){return this.baseURL!=="https://api.supermemory.ai"};m.Supermemory=gt;m.DEFAULT_TIMEOUT=6e4;m.SupermemoryError=b.SupermemoryError;m.APIError=b.APIError;m.APIConnectionError=b.APIConnectionError;m.APIConnectionTimeoutError=b.APIConnectionTimeoutError;m.APIUserAbortError=b.APIUserAbortError;m.NotFoundError=b.NotFoundError;m.ConflictError=b.ConflictError;m.RateLimitError=b.RateLimitError;m.BadRequestError=b.BadRequestError;m.AuthenticationError=b.AuthenticationError;m.InternalServerError=b.InternalServerError;m.PermissionDeniedError=b.PermissionDeniedError;m.UnprocessableEntityError=b.UnprocessableEntityError;m.toFile=Ss.toFile;m.Memories=Ks.Memories;m.Documents=Es.Documents;m.Search=Is.Search;m.Settings=Cs.Settings;m.Connections=ks.Connections});var qr=v((l,Hr)=>{"use strict";l=Hr.exports=function(...e){return new l.default(...e)};Object.defineProperty(l,"__esModule",{value:!0});l.UnprocessableEntityError=l.PermissionDeniedError=l.InternalServerError=l.AuthenticationError=l.BadRequestError=l.RateLimitError=l.ConflictError=l.NotFoundError=l.APIUserAbortError=l.APIConnectionTimeoutError=l.APIConnectionError=l.APIError=l.SupermemoryError=l.Supermemory=l.APIPromise=l.toFile=l.default=void 0;var Bs=wt();Object.defineProperty(l,"default",{enumerable:!0,get:function(){return Bs.Supermemory}});var As=at();Object.defineProperty(l,"toFile",{enumerable:!0,get:function(){return As.toFile}});var Qs=ht();Object.defineProperty(l,"APIPromise",{enumerable:!0,get:function(){return Qs.APIPromise}});var _s=wt();Object.defineProperty(l,"Supermemory",{enumerable:!0,get:function(){return _s.Supermemory}});var H=J();Object.defineProperty(l,"SupermemoryError",{enumerable:!0,get:function(){return H.SupermemoryError}});Object.defineProperty(l,"APIError",{enumerable:!0,get:function(){return H.APIError}});Object.defineProperty(l,"APIConnectionError",{enumerable:!0,get:function(){return H.APIConnectionError}});Object.defineProperty(l,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return H.APIConnectionTimeoutError}});Object.defineProperty(l,"APIUserAbortError",{enumerable:!0,get:function(){return H.APIUserAbortError}});Object.defineProperty(l,"NotFoundError",{enumerable:!0,get:function(){return H.NotFoundError}});Object.defineProperty(l,"ConflictError",{enumerable:!0,get:function(){return H.ConflictError}});Object.defineProperty(l,"RateLimitError",{enumerable:!0,get:function(){return H.RateLimitError}});Object.defineProperty(l,"BadRequestError",{enumerable:!0,get:function(){return H.BadRequestError}});Object.defineProperty(l,"AuthenticationError",{enumerable:!0,get:function(){return H.AuthenticationError}});Object.defineProperty(l,"InternalServerError",{enumerable:!0,get:function(){return H.InternalServerError}});Object.defineProperty(l,"PermissionDeniedError",{enumerable:!0,get:function(){return H.PermissionDeniedError}});Object.defineProperty(l,"UnprocessableEntityError",{enumerable:!0,get:function(){return H.UnprocessableEntityError}})});var Wr={};vn(Wr,{getRequestIntegrity:()=>vo,sanitizeContent:()=>ro,sanitizeMetadata:()=>ao,validateApiKeyFormat:()=>$s,validateContainerTag:()=>eo,validateContentLength:()=>no,validateRecallConfig:()=>fo});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 ao(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,io),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function fo(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),hr].join(":");return(0,Fe.createHmac)("sha256",co).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${hr}`,n].join(".")}}var Fe,to,so,oo,io,hr,co,Tr=dn(()=>{Fe=require("node:crypto");to=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];so=50,oo=128,io=1024;hr=1,co="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var Lr=v((ta,Nr)=>{var lo=qr().default,{getRequestIntegrity:po,validateApiKeyFormat:Po,validateContainerTag:zo}=(Tr(),pn(Wr)),mo="claudecode_default",xo=process.env.SUPERMEMORY_API_URL||"https://api.supermemory.ai";function bo(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 jo=`Developer coding session transcript. Focus on USER message and intent. +var m=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var nt=m((Re,et)=>{var S=require("node:fs"),N=require("node:path"),Ot=require("node:os"),_t=require("node:crypto"),At=N.join(Ot.homedir(),".supermemory-claude","memories"),It=`Developer coding session transcript. Focus on USER message and intent. RULES: -- Extract USER's action/intent, not every detail assistant provides matter +- Extract USER's action/intent, not every detail assistant provides - Condense assistant responses into what user gained from it - Skip granular facts from assistant output @@ -17,96 +13,23 @@ EXTRACT: - Decisions: "chose SQLite for local storage" - Learnings: "learned about React Server Components" -EXAMPLES: -| Transcript | Memory | -| [role:user] research about the whisper.cpp -> https://github.com/ggml-org/whisper.cpp/blob/master/src/whisper.cpp [user:end]| " starts research about whisper.cpp" | -| [role:assistant] ## whisper.cpp Architecture Summary - This is highly relevant for your parakeet.cpp implementation. Here are the key patterns: - ### Core Architecture - **Two-level context design:** - - whisper_context - holds model weights, vocab, hyperparameters (persistent) - - whisper_state - runtime state, KV caches, backends (can have multiple per context) [assistant:end] | "Assistant did a deep dive on whisper architecture" | -| [role:user] Can we explain what we are currently doing in this repository? [user:end] | "" | - SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,Xo=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,$t=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" - Conventions: "components in PascalCase", "hooks prefixed with use" - Patterns: "all API routes use withAuth wrapper", "errors thrown as ApiError" - Setup: "requires .env with DATABASE_URL", "run pnpm db:migrate first" -- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching" - -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]" |`,Mt=class{constructor(t,r){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let n=Po(t);if(!n.valid)throw new Error(`Invalid API key: ${n.reason}`);let s=r||mo,o=zo(s);o.valid||console.warn(`Container tag warning: ${o.reason}`);let i=po(t,s);this.client=new lo({apiKey:t,baseURL:xo,defaultHeaders:i}),this.containerTag=s}async addMemory(t,r,n={},s={}){let o={content:t,containerTag:r||this.containerTag,metadata:{sm_source:"claude-code-plugin",...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:bo(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=(u,d=P=>P)=>u.filter(P=>{let x=String(d(P)).toLowerCase().trim();return!x||s.has(x)?!1:(s.add(x),!0)}),i=o(n.profile?.static||[]),a=o(n.profile?.dynamic||[]),c;if(n.searchResults){let u=n.searchResults.results.map(d=>({id:d.id,memory:d.content||d.context||"",similarity:d.similarity,title:d.title,updatedAt:d.updatedAt}));c={results:o(u,d=>d.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:i,dynamic:a},searchResults:c}}};Nr.exports={SupermemoryClient:Mt,PERSONAL_ENTITY_CONTEXT:jo,REPO_ENTITY_CONTEXT:Xo}});var Ft=v((ra,Vr)=>{var{execSync:De}=require("node:child_process"),se=require("node:path");function Oo(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}}Vr.exports={getGitRoot:Oo}});var Dt=v((na,Fr)=>{var oe=require("node:fs"),Ue=require("node:path"),{getGitRoot:Rr}=Ft(),gr=Ue.join(".claude",".supermemory-claude"),wr="config.json";function Zr(e){let r=Rr(e)||e;return Ue.join(r,gr,wr)}function Mr(e){try{let t=Zr(e);if(oe.existsSync(t))return JSON.parse(oe.readFileSync(t,"utf-8"))}catch{}return null}function yo(e,t){let n=Rr(e)||e,s=Ue.join(n,gr),o=Ue.join(s,wr);oe.existsSync(s)||oe.mkdirSync(s,{recursive:!0});let a={...Mr(e)||{},...t};return oe.writeFileSync(o,JSON.stringify(a,null,2)),o}Fr.exports={getConfigPath:Zr,loadProjectConfig:Mr,saveProjectConfig:yo}});var Sr=v((sa,Yr)=>{var{execSync:Ho}=require("node:child_process"),qo=require("node:crypto"),{loadProjectConfig:Dr}=Dt(),{getGitRoot:Ye}=Ft();function Ur(e){return qo.createHash("sha256").update(e).digest("hex").slice(0,16)}function Ut(e){try{let r=Ho("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 ho(e){let t=Dr(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Ye(e)||e;return`claudecode_project_${Ur(n)}`}function Wo(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function To(e){let t=Dr(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Ye(e)||e,o=Ut(n)||n.split("/").pop()||"unknown";return`repo_${Wo(o)}`}function No(e){let r=Ye(e)||e;return Ut(r)||r.split("/").pop()||"unknown"}Yr.exports={sha256:Ur,getGitRoot:Ye,getGitRepoName:Ut,getContainerTag:ho,getRepoContainerTag:To,getProjectName:No}});var Gr=v((oa,Lo)=>{Lo.exports=` - -Connected - Supermemory - - -
-
Connected . . .
- -
- - + - -
-

Supercharge your Claude Code with Supermemory.

-
- - -`});var kr=v((ia,Vo)=>{Vo.exports=` - -Error - Supermemory - -
Error . . .
-

Connection Failed

-

Invalid API key received. Please try again.

- -`});var Jr=v((aa,Cr)=>{var Ro=require("node:http"),M=require("node:fs"),Er=require("node:path"),go=require("node:os"),{execFile:Yt}=require("node:child_process"),wo=Gr(),Zo=kr(),Gt=Er.join(go.homedir(),".supermemory-claude"),k=Er.join(Gt,"credentials.json"),Kr=process.env.SUPERMEMORY_AUTH_URL||"https://app.supermemory.ai/auth/connect",St=19876,Mo=25e3;function Fo(){M.existsSync(Gt)||M.mkdirSync(Gt,{recursive:!0})}function Do(){try{if(M.existsSync(k)){let e=JSON.parse(M.readFileSync(k,"utf-8"));if(e.apiKey)return e}}catch{}return null}function Ir(e){Fo();let t={apiKey:e,savedAt:new Date().toISOString()};M.writeFileSync(k,JSON.stringify(t,null,2))}function Uo(){try{M.existsSync(k)&&M.unlinkSync(k)}catch{}}function Yo(e){let t=r=>{r&&console.warn("Failed to open browser:",r.message)};process.platform==="win32"?Yt("explorer.exe",[e],t):process.platform==="darwin"?Yt("open",[e],t):Yt("xdg-open",[e],t)}function So(){return new Promise((e,t)=>{let r=!1,n=Ro.createServer((s,o)=>{let i=new URL(s.url,`http://localhost:${St}`);if(i.pathname==="/callback"){let a=i.searchParams.get("apikey")||i.searchParams.get("api_key");a?.startsWith("sm_")?(Ir(a),o.writeHead(200,{"Content-Type":"text/html"}),o.end(wo),r=!0,n.close(),e(a)):(o.writeHead(400,{"Content-Type":"text/html"}),o.end(Zo))}else o.writeHead(404),o.end("Not found")});n.listen(St,"127.0.0.1",()=>{let s=`http://localhost:${St}/callback`,o=`${Kr}?callback=${encodeURIComponent(s)}&client=claude_code`;Yo(o)}),n.on("error",s=>{r||t(new Error(`Failed to start auth server: ${s.message}`))}),setTimeout(()=>{r||(n.close(),t(new Error("AUTH_TIMEOUT")))},Mo)})}Cr.exports={AUTH_BASE_URL:Kr,CREDENTIALS_FILE:k,loadCredentials:Do,saveCredentials:Ir,clearCredentials:Uo,startAuthFlow:So}});var Kt=v((fa,Ar)=>{var ae=require("node:fs"),Br=require("node:path"),Go=require("node:os"),{loadCredentials:ko}=Jr(),{loadProjectConfig:kt}=Dt(),Se=Br.join(Go.homedir(),".supermemory-claude"),ie=Br.join(Se,"settings.json"),Ge={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Eo(){ae.existsSync(Se)||ae.mkdirSync(Se,{recursive:!0})}function Et(){let e={...Ge};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 Ko(e){Eo();let t={...e};delete t.apiKey,ae.writeFileSync(ie,JSON.stringify(t,null,2))}function Io(e,t){if(e.apiKey)return e.apiKey;if(process.env.SUPERMEMORY_CC_API_KEY)return process.env.SUPERMEMORY_CC_API_KEY;let r=kt(t||process.cwd());if(r?.apiKey)return r.apiKey;let n=ko();if(n?.apiKey)return n.apiKey;throw new Error("NO_API_KEY")}function Co(e,t,r){if(e.debug){let n=new Date().toISOString();console.error(r?`[${n}] ${t}: ${JSON.stringify(r)}`:`[${n}] ${t}`)}}function Jo(e){let t=Et(),r=kt(e||process.cwd()),n=t.includeTools||[],s=r?.includeTools||[];return[...new Set([...n,...s])].map(i=>i.toLowerCase())}function Bo(e,t){return t.length===0?!1:t.includes(e.toLowerCase())}function Ao(e){let t=Et(),r=kt(e||process.cwd()),n=t.signalExtraction||!1,s=r?.signalExtraction,o=s!==void 0?s:n,i=t.signalKeywords||Ge.signalKeywords,a=r?.signalKeywords||[],c=[...new Set([...i,...a])].map(d=>d.toLowerCase()),u=r?.signalTurnsBefore||t.signalTurnsBefore||Ge.signalTurnsBefore;return{enabled:o,keywords:c,turnsBefore:u}}Ar.exports={SETTINGS_DIR:Se,SETTINGS_FILE:ie,DEFAULT_SETTINGS:Ge,loadSettings:Et,saveSettings:Ko,getApiKey:Io,debugLog:Co,getIncludeTools:Jo,shouldIncludeTool:Bo,getSignalConfig:Ao}});var _r=v((ca,Qr)=>{async function Qo(){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 ke(e){console.log(JSON.stringify(e))}function _o(e=null){ke(e?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e}}:{continue:!0,suppressOutput:!0})}function $o(e){console.error(`Supermemory: ${e}`),ke({continue:!0,suppressOutput:!0})}Qr.exports={readStdin:Qo,writeOutput:ke,outputSuccess:_o,outputError:$o}});var an=v((ua,on)=>{var F=require("node:fs"),It=require("node:path"),ei=require("node:os"),{getIncludeTools:$r,shouldIncludeTool:en,getSignalConfig:ti}=Kt(),ri=500,Ee=It.join(ei.homedir(),".supermemory-claude","trackers"),Ke=new Map,Ie=[];function tn(){F.existsSync(Ee)||F.mkdirSync(Ee,{recursive:!0})}function Ct(e){tn();let t=It.join(Ee,`${e}.txt`);return F.existsSync(t)?F.readFileSync(t,"utf-8").trim():null}function Jt(e,t){tn();let r=It.join(Ee,`${e}.txt`);F.writeFileSync(r,t)}function Bt(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 At(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 rn(e){let t=[];if(e.type==="user"){let r=ni(e.message);r&&t.push(r)}else if(e.type==="assistant"){let r=si(e.message);r&&t.push(r)}return t.join(` -`)}function ni(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=Ke.get(s)||"Unknown";if(!en(o,Ie))continue;let i=Qt(W(n.content||""),ri),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 si(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&&Ke.set(i,o),!en(o,Ie))continue;let a=s.input||{},c=oi(a);r.push({type:"tool",toolName:o,inputStr:c})}}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 oi(e){let t=[];for(let[r,n]of Object.entries(e)){let s=typeof n=="string"?n:JSON.stringify(n);s=Qt(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 Qt(e,t){return!e||e.length<=t?e:`${e.slice(0,t)}...`}function _t(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 ii(e){return!e||e.isMeta?!1:_t(e).length>0}function ai(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 fi(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 ui(e){return e.type==="user"?di(e.message):e.type==="assistant"?vi(e.message):null}function di(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 vi(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 li(e,t,r){Ke=new Map,Ie=$r(r);let n=ti(r),{keywords:s,turnsBefore:o}=n,i=Bt(e);if(i.length===0)return null;let a=Ct(t),c=At(i,a);if(c.length===0)return null;let u=fi(c);if(u.length===0)return null;let d=nn(u,s);if(d.length===0)return null;let P=sn(u,d,o);if(P.length===0)return null;let x=[];for(let U of P)x.push(...U.allEntries);if(x.length===0)return null;let f=x[0],O=c[c.length-1],g=f.timestamp||new Date().toISOString(),T=[];T.push(`<|turn_start|>${g}`);for(let U of x){let E=ui(U);E&&T.push(E)}T.push("<|turn_end|>");let h=T.join(` +- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching"`;function bt(t){S.existsSync(t)||S.mkdirSync(t,{recursive:!0})}function E(t,e){return N.join(At,t,e)}function j(t){if(!S.existsSync(t))return[];let e=S.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let r=S.readFileSync(N.join(t,n),"utf-8");s.push(JSON.parse(r))}catch{}return s}function Pt(t,e){let s=(t.content||"").toLowerCase(),n=0;for(let i of e)s.includes(i)&&(n+=1);let r=Date.now()-new Date(t.createdAt||0).getTime(),o=Math.max(0,1-r/(720*60*60*1e3));return n+o*.5}var F=class{constructor(e){this.containerTag=e||"default"}async addMemory(e,s,n={}){let r=s||this.containerTag,o=n.type==="project-knowledge"?"repo":"personal",i=E(o,r);bt(i);let c=_t.randomUUID(),a={id:c,content:e,metadata:{sm_source:"claude-code-local",...n},createdAt:new Date().toISOString()};return S.writeFileSync(N.join(i,`${c}.json`),JSON.stringify(a,null,2)),{id:c,status:"saved",containerTag:r}}async search(e,s,n={}){let r=s||this.containerTag,o=n.limit||10,i=E("personal",r),c=E("repo",r),a=[...j(i),...j(c)];if(a.length===0)return{results:[],total:0};let u=e.toLowerCase().split(/\s+/).filter(l=>l.length>2),f=a.map(l=>({memory:l.content||"",metadata:l.metadata,updatedAt:l.createdAt,similarity:u.length>0?Pt(l,u)/u.length:0})).filter(l=>l.similarity>0).sort((l,p)=>p.similarity-l.similarity).slice(0,o);return{results:f,total:f.length}}async getProfile(e,s,n=5){let r=e||this.containerTag,o=E("personal",r),i=E("repo",r),c=j(o),a=j(i),u=(g,M)=>new Date(M.createdAt||0).getTime()-new Date(g.createdAt||0).getTime();c.sort(u),a.sort(u);let f=a.slice(0,n).map(g=>g.content),l=c.slice(0,n).map(g=>g.content),p=[...c,...a].sort(u).slice(0,n),q={results:p.map(g=>({id:g.id,memory:g.content,similarity:1,updatedAt:g.createdAt})),total:p.length};return{profile:{static:f,dynamic:l},searchResults:q}}};et.exports={LocalMemoryClient:F,PERSONAL_ENTITY_CONTEXT:It,REPO_ENTITY_CONTEXT:$t}});var U=m((Ce,st)=>{var{execSync:O}=require("node:child_process"),T=require("node:path");function kt(t){let e=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(e)return O("git rev-parse --show-toplevel",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let s=O("git rev-parse --git-common-dir",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(s===".git")return O("git rev-parse --show-toplevel",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let n=T.resolve(t,s);return T.basename(n)===".git"&&!n.includes(`${T.sep}.git${T.sep}`)?T.dirname(n):O("git rev-parse --show-toplevel",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}st.exports={getGitRoot:kt}});var J=m((je,ut)=>{var w=require("node:fs"),_=require("node:path"),{getGitRoot:rt}=U(),ot=_.join(".claude",".supermemory-claude"),it="config.json";function ct(t){let s=rt(t)||t;return _.join(s,ot,it)}function at(t){try{let e=ct(t);if(w.existsSync(e))return JSON.parse(w.readFileSync(e,"utf-8"))}catch{}return null}function vt(t,e){let n=rt(t)||t,r=_.join(n,ot),o=_.join(r,it);w.existsSync(r)||w.mkdirSync(r,{recursive:!0});let c={...at(t)||{},...e};return w.writeFileSync(o,JSON.stringify(c,null,2)),o}ut.exports={getConfigPath:ct,loadProjectConfig:at,saveProjectConfig:vt}});var gt=m((Ne,pt)=>{var{execSync:Dt}=require("node:child_process"),qt=require("node:crypto"),{loadProjectConfig:lt}=J(),{getGitRoot:A}=U();function ft(t){return qt.createHash("sha256").update(t).digest("hex").slice(0,16)}function G(t){try{let s=Dt("git remote get-url origin",{cwd:t,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim().match(/[/:]([^/]+?)(?:\.git)?$/);return s?s[1]:null}catch{return null}}function Mt(t){let e=lt(t);if(e?.personalContainerTag)return e.personalContainerTag;let n=A(t)||t;return`claudecode_project_${ft(n)}`}function Lt(t){return t.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function Ft(t){let e=lt(t);if(e?.repoContainerTag)return e.repoContainerTag;let n=A(t)||t,o=G(n)||n.split("/").pop()||"unknown";return`repo_${Lt(o)}`}function Ut(t){let s=A(t)||t;return G(s)||s.split("/").pop()||"unknown"}pt.exports={sha256:ft,getGitRoot:A,getGitRepoName:G,getContainerTag:Mt,getRepoContainerTag:Ft,getProjectName:Ut}});var K=m((Oe,ht)=>{var R=require("node:fs"),dt=require("node:path"),Jt=require("node:os"),{loadProjectConfig:mt}=J(),I=dt.join(Jt.homedir(),".supermemory-claude"),x=dt.join(I,"settings.json"),$={includeTools:[],maxProfileItems:5,debug:!1,injectProfile:!0,signalExtraction:!1,signalKeywords:["remember","implementation","refactor","architecture","decision","important","bug","fix","solved","solution","pattern","approach","design","tradeoff","migrate","upgrade","deprecate"],signalTurnsBefore:3};function Gt(){R.existsSync(I)||R.mkdirSync(I,{recursive:!0})}function B(){let t={...$};try{if(R.existsSync(x)){let e=R.readFileSync(x,"utf-8");Object.assign(t,JSON.parse(e))}}catch(e){console.error(`Settings: Failed to load ${x}: ${e.message}`)}return process.env.SUPERMEMORY_DEBUG==="true"&&(t.debug=!0),t}function Bt(t){Gt();let e={...t};R.writeFileSync(x,JSON.stringify(e,null,2))}function Kt(t,e,s){if(t.debug){let n=new Date().toISOString();console.error(s?`[${n}] ${e}: ${JSON.stringify(s)}`:`[${n}] ${e}`)}}function Xt(t){let e=B(),s=mt(t||process.cwd()),n=e.includeTools||[],r=s?.includeTools||[];return[...new Set([...n,...r])].map(i=>i.toLowerCase())}function Yt(t,e){return e.length===0?!1:e.includes(t.toLowerCase())}function zt(t){let e=B(),s=mt(t||process.cwd()),n=e.signalExtraction||!1,r=s?.signalExtraction,o=r!==void 0?r:n,i=e.signalKeywords||$.signalKeywords,c=s?.signalKeywords||[],a=[...new Set([...i,...c])].map(f=>f.toLowerCase()),u=s?.signalTurnsBefore||e.signalTurnsBefore||$.signalTurnsBefore;return{enabled:o,keywords:a,turnsBefore:u}}ht.exports={SETTINGS_DIR:I,SETTINGS_FILE:x,DEFAULT_SETTINGS:$,loadSettings:B,saveSettings:Bt,debugLog:Kt,getIncludeTools:Xt,shouldIncludeTool:Yt,getSignalConfig:zt}});var St=m((_e,yt)=>{async function Wt(){return new Promise((t,e)=>{let s="";process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{s+=n}),process.stdin.on("end",()=>{try{t(s.trim()?JSON.parse(s):{})}catch(n){e(new Error(`Failed to parse stdin JSON: ${n.message}`))}}),process.stdin.on("error",e),process.stdin.isTTY&&t({})})}function b(t){console.log(JSON.stringify(t))}function Ht(t=null){b(t?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:t}}:{continue:!0,suppressOutput:!0})}function Qt(t){console.error(`Supermemory: ${t}`),b({continue:!0,suppressOutput:!0})}yt.exports={readStdin:Wt,writeOutput:b,outputSuccess:Ht,outputError:Qt}});var Nt=m((Ae,jt)=>{var h=require("node:fs"),X=require("node:path"),Vt=require("node:os"),{getIncludeTools:Et,shouldIncludeTool:Tt,getSignalConfig:Zt}=K(),te=500,P=X.join(Vt.homedir(),".supermemory-claude","trackers"),k=new Map,v=[];function wt(){h.existsSync(P)||h.mkdirSync(P,{recursive:!0})}function Y(t){wt();let e=X.join(P,`${t}.txt`);return h.existsSync(e)?h.readFileSync(e,"utf-8").trim():null}function z(t,e){wt();let s=X.join(P,`${t}.txt`);h.writeFileSync(s,e)}function W(t){if(!h.existsSync(t))return[];let s=h.readFileSync(t,"utf-8").trim().split(` +`),n=[];for(let r of s)if(r.trim())try{n.push(JSON.parse(r))}catch{}return n}function H(t,e){if(!e)return t.filter(r=>r.type==="user"||r.type==="assistant");let s=!1,n=[];for(let r of t){if(r.uuid===e){s=!0;continue}s&&(r.type==="user"||r.type==="assistant")&&n.push(r)}return n}function xt(t){let e=[];if(t.type==="user"){let s=ee(t.message);s&&e.push(s)}else if(t.type==="assistant"){let s=ne(t.message);s&&e.push(s)}return e.join(` +`)}function ee(t){if(!t?.content)return null;let e=t.content,s=[];if(typeof e=="string"){let n=d(e);n&&s.push(`<|start|>user<|message|>${n}<|end|>`)}else if(Array.isArray(e)){for(let n of e)if(n.type==="text"&&n.text){let r=d(n.text);r&&s.push(`<|start|>user<|message|>${r}<|end|>`)}else if(n.type==="tool_result"){let r=n.tool_use_id||"",o=k.get(r)||"Unknown";if(!Tt(o,v))continue;let i=Q(d(n.content||""),te),c=n.is_error?"error":"success";i&&s.push(`<|start|>assistant:tool_result<|message|>${o}(${c}): ${i}<|end|>`)}}return s.length>0?s.join(` +`):null}function ne(t){if(!t?.content)return null;let e=t.content,s=[];if(!Array.isArray(e))return null;for(let r of e)if(r.type!=="thinking"){if(r.type==="text"&&r.text){let o=d(r.text);o&&s.push({type:"text",content:o})}else if(r.type==="tool_use"){let o=r.name||"Unknown",i=r.id||"";if(i&&k.set(i,o),!Tt(o,v))continue;let c=r.input||{},a=se(c);s.push({type:"tool",toolName:o,inputStr:a})}}let n=s.map(r=>r.type==="text"?`<|start|>assistant<|message|>${r.content}<|end|>`:`<|start|>assistant:tool<|message|>${r.toolName}: ${r.inputStr}<|end|>`);return n.length>0?n.join(` +`):null}function se(t){let e=[];for(let[s,n]of Object.entries(t)){let r=typeof n=="string"?n:JSON.stringify(n);r=Q(r,100),e.push(`${s}="${r}"`)}return e.join(" ")}function d(t){return!t||typeof t!="string"?"":t.replace(/[\s\S]*?<\/system-reminder>/g,"").replace(/[\s\S]*?<\/supermemory-context>/g,"").trim()}function Q(t,e){return!t||t.length<=e?t:`${t.slice(0,e)}...`}function V(t){if(!t?.message?.content)return"";let e=t.message.content;if(typeof e=="string")return d(e);if(Array.isArray(e)){let s=[];for(let n of e)n.type==="text"&&n.text&&s.push(d(n.text));return s.join(" ")}return""}function re(t){return!t||t.isMeta?!1:V(t).length>0}function oe(t){let e=[],s={userEntries:[],assistantEntries:[],allEntries:[]};for(let n=0;n0&&(e.push(s),s={userEntries:[],assistantEntries:[],allEntries:[]}),s.userEntries.push(r),s.allEntries.push(r)):r.type==="assistant"&&(s.assistantEntries.push(r),s.allEntries.push(r))}return s.allEntries.length>0&&e.push(s),e}function ie(t){let e=[],s={userEntries:[]},n=null,r=()=>{if(s.userEntries.length===0&&!n)return;let o=n?[n]:[],i=[...s.userEntries,...o];e.push({userEntries:s.userEntries,assistantEntries:o,allEntries:i}),s={userEntries:[]},n=null};for(let o=0;oo-i).map(o=>t[o])}function ae(t){return t.type==="user"?ue(t.message):t.type==="assistant"?le(t.message):null}function ue(t){if(!t?.content)return null;let e=t.content,s=[];if(typeof e=="string"){let n=d(e);n&&s.push(`<|start|>user<|message|>${n}<|end|>`)}else if(Array.isArray(e)){for(let n of e)if(n.type==="text"&&n.text){let r=d(n.text);r&&s.push(`<|start|>user<|message|>${r}<|end|>`)}}return s.length>0?s.join(` +`):null}function le(t){if(!t?.content)return null;let e=t.content,s=[];if(typeof e=="string"){let n=d(e);n&&s.push(`<|start|>assistant<|message|>${n}<|end|>`)}else if(Array.isArray(e)){for(let n of e)if(n.type==="text"&&n.text){let r=d(n.text);r&&s.push(`<|start|>assistant<|message|>${r}<|end|>`)}}return s.length>0?s.join(` +`):null}function fe(t,e,s){k=new Map,v=Et(s);let n=Zt(s),{keywords:r,turnsBefore:o}=n,i=W(t);if(i.length===0)return null;let c=Y(e),a=H(i,c);if(a.length===0)return null;let u=ie(a);if(u.length===0)return null;let f=Rt(u,r);if(f.length===0)return null;let l=Ct(u,f,o);if(l.length===0)return null;let p=[];for(let L of l)p.push(...L.allEntries);if(p.length===0)return null;let q=p[0],g=a[a.length-1],M=q.timestamp||new Date().toISOString(),C=[];C.push(`<|turn_start|>${M}`);for(let L of p){let tt=ae(L);tt&&C.push(tt)}C.push("<|turn_end|>");let Z=C.join(` -`);return h.length<100?null:(Jt(t,O.uuid),h)}function pi(e,t,r){Ke=new Map,Ie=$r(r);let n=Bt(e);if(n.length===0)return null;let s=Ct(t),o=At(n,s);if(o.length===0)return null;let i=o[0],a=o[o.length-1],c=i.timestamp||new Date().toISOString(),u=[];u.push(`<|turn_start|>${c}`);for(let P of o){let x=rn(P);x&&u.push(x)}u.push("<|turn_end|>");let d=u.join(` +`);return Z.length<100?null:(z(e,g.uuid),Z)}function pe(t,e,s){k=new Map,v=Et(s);let n=W(t);if(n.length===0)return null;let r=Y(e),o=H(n,r);if(o.length===0)return null;let i=o[0],c=o[o.length-1],a=i.timestamp||new Date().toISOString(),u=[];u.push(`<|turn_start|>${a}`);for(let l of o){let p=xt(l);p&&u.push(p)}u.push("<|turn_end|>");let f=u.join(` -`);return d.length<100?null:(Jt(t,a.uuid),d)}on.exports={parseTranscript:Bt,getEntriesSinceLastCapture:At,formatEntry:rn,formatNewEntries:pi,formatSignalEntries:li,cleanContent:W,truncate:Qt,getLastCapturedUuid:Ct,setLastCapturedUuid:Jt,getTextFromEntry:_t,groupEntriesIntoTurns:ai,findSignalTurnIndices:nn,getTurnsAroundSignals:sn}});var{SupermemoryClient:Pi,PERSONAL_ENTITY_CONTEXT:zi}=Lr(),{getContainerTag:mi,getProjectName:xi}=Sr(),{loadSettings:bi,getApiKey:ji,debugLog:D,getSignalConfig:Xi}=Kt(),{readStdin:Oi,writeOutput:fe}=_r(),{formatNewEntries:yi,formatSignalEntries:Hi}=an();async function qi(){let e=bi();try{let t=await Oi(),r=t.cwd||process.cwd(),n=t.session_id,s=t.transcript_path;if(D(e,"Stop",{sessionId:n,transcriptPath:s}),!s||!n){D(e,"Missing transcript path or session id"),fe({continue:!0});return}let o;try{o=ji(e)}catch{fe({continue:!0});return}let a=Xi(r).enabled;D(e,"Signal extraction",{enabled:a});let c;if(a?(c=Hi(s,n,r),D(e,"Signal extraction result",{hasContent:!!c})):c=yi(s,n,r),!c){D(e,"No new content to save"),fe({continue:!0});return}let u=new Pi(o),d=mi(r),P=xi(r);await u.addMemory(c,d,{type:"session_turn",project:P,timestamp:new Date().toISOString()},{customId:n,entityContext:zi}),D(e,"Session turn saved",{length:c.length}),fe({continue:!0})}catch(t){D(e,"Error",{error:t.message}),console.error(`Supermemory: ${t.message}`),fe({continue:!0})}}qi().catch(e=>{console.error(`Supermemory fatal: ${e.message}`),process.exit(1)}); +`);return f.length<100?null:(z(e,c.uuid),f)}jt.exports={parseTranscript:W,getEntriesSinceLastCapture:H,formatEntry:xt,formatNewEntries:pe,formatSignalEntries:fe,cleanContent:d,truncate:Q,getLastCapturedUuid:Y,setLastCapturedUuid:z,getTextFromEntry:V,groupEntriesIntoTurns:oe,findSignalTurnIndices:Rt,getTurnsAroundSignals:Ct}});var{LocalMemoryClient:ge,PERSONAL_ENTITY_CONTEXT:Ie}=nt(),{getContainerTag:de,getProjectName:me}=gt(),{loadSettings:he,debugLog:y,getSignalConfig:ye}=K(),{readStdin:Se,writeOutput:D}=St(),{formatNewEntries:Ee,formatSignalEntries:Te}=Nt();async function we(){let t=he();try{let e=await Se(),s=e.cwd||process.cwd(),n=e.session_id,r=e.transcript_path;if(y(t,"Stop",{sessionId:n,transcriptPath:r}),!r||!n){y(t,"Missing transcript path or session id"),D({continue:!0});return}let i=ye(s).enabled;y(t,"Signal extraction",{enabled:i});let c;if(i?(c=Te(r,n,s),y(t,"Signal extraction result",{hasContent:!!c})):c=Ee(r,n,s),!c){y(t,"No new content to save"),D({continue:!0});return}let a=new ge,u=de(s),f=me(s);await a.addMemory(c,u,{type:"session_turn",project:f,timestamp:new Date().toISOString()}),y(t,"Session turn saved",{length:c.length}),D({continue:!0})}catch(e){y(t,"Error",{error:e.message}),console.error(`Supermemory-local: ${e.message}`),D({continue:!0})}}we().catch(t=>{console.error(`Supermemory-local fatal: ${t.message}`),process.exit(1)}); diff --git a/src/add-memory.js b/src/add-memory.js index 454d470..b4a6751 100644 --- a/src/add-memory.js +++ b/src/add-memory.js @@ -1,10 +1,8 @@ const { - SupermemoryClient, + LocalMemoryClient, PERSONAL_ENTITY_CONTEXT, -} = require('./lib/supermemory-client'); +} = require('./lib/local-memory-client'); const { getContainerTag, getProjectName } = require('./lib/container-tag'); -const { loadSettings, getApiKey } = require('./lib/settings'); -const { getUserFriendlyError } = require('./lib/error-helpers'); async function main() { const content = process.argv.slice(2).join(' '); @@ -16,23 +14,12 @@ async function main() { return; } - const settings = loadSettings(); - - let apiKey; - try { - apiKey = getApiKey(settings); - } catch { - console.log('Supermemory API key not configured.'); - console.log('Set SUPERMEMORY_CC_API_KEY environment variable.'); - return; - } - const cwd = process.cwd(); const containerTag = getContainerTag(cwd); const projectName = getProjectName(cwd); try { - const client = new SupermemoryClient(apiKey, containerTag); + const client = new LocalMemoryClient(containerTag); const result = await client.addMemory( content, containerTag, @@ -41,13 +28,12 @@ async function main() { project: projectName, timestamp: new Date().toISOString(), }, - { entityContext: PERSONAL_ENTITY_CONTEXT }, ); console.log(`Memory saved to project: ${projectName}`); console.log(`ID: ${result.id}`); } catch (err) { - console.log(`Error saving memory: ${getUserFriendlyError(err)}`); + console.log(`Error saving memory: ${err.message}`); } } diff --git a/src/context-hook.js b/src/context-hook.js index 2cde1b2..fd6d400 100644 --- a/src/context-hook.js +++ b/src/context-hook.js @@ -1,14 +1,12 @@ -const { SupermemoryClient } = require('./lib/supermemory-client'); +const { LocalMemoryClient } = require('./lib/local-memory-client'); const { getContainerTag, getRepoContainerTag, getProjectName, } = require('./lib/container-tag'); -const { loadSettings, getApiKey, debugLog } = require('./lib/settings'); +const { loadSettings, debugLog } = require('./lib/settings'); const { readStdin, writeOutput } = require('./lib/stdin'); -const { startAuthFlow, AUTH_BASE_URL } = require('./lib/auth'); const { formatContext, combineContexts } = require('./lib/format-context'); -const { getUserFriendlyError, isBenignError } = require('./lib/error-helpers'); async function main() { const settings = loadSettings(); @@ -20,62 +18,15 @@ async function main() { debugLog(settings, 'SessionStart', { cwd, projectName }); - let apiKey; - try { - apiKey = getApiKey(settings); - } catch { - try { - debugLog(settings, 'No API key found, starting browser auth flow'); - apiKey = await startAuthFlow(); - debugLog(settings, 'Auth flow completed successfully'); - } catch (authErr) { - const isTimeout = authErr.message === 'AUTH_TIMEOUT'; - writeOutput({ - hookSpecificOutput: { - hookEventName: 'SessionStart', - additionalContext: ` -${isTimeout ? 'Authentication timed out. Please complete login in the browser window.' : 'Authentication failed.'} -If the browser did not open, visit: ${AUTH_BASE_URL} -Or set SUPERMEMORY_CC_API_KEY environment variable manually. -`, - }, - }); - return; - } - } - - const client = new SupermemoryClient(apiKey); + const client = new LocalMemoryClient(); const personalTag = getContainerTag(cwd); const repoTag = getRepoContainerTag(cwd); debugLog(settings, 'Fetching contexts', { personalTag, repoTag }); - const apiErrors = []; - - const handleProfileError = (label) => (err) => { - if (isBenignError(err)) { - debugLog(settings, `Benign error fetching ${label} context`, { - status: err.status, - message: err.message, - }); - return null; - } - const friendly = getUserFriendlyError(err); - debugLog(settings, `Error fetching ${label} context`, { - status: err.status, - message: friendly, - }); - apiErrors.push(friendly); - return null; - }; - const [personalResult, repoResult] = await Promise.all([ - client - .getProfile(personalTag, projectName) - .catch(handleProfileError('personal')), - client - .getProfile(repoTag, projectName) - .catch(handleProfileError('repo')), + client.getProfile(personalTag, projectName, settings.maxProfileItems).catch(() => null), + client.getProfile(repoTag, projectName, settings.maxProfileItems).catch(() => null), ]); const personalContext = formatContext( @@ -102,18 +53,11 @@ Or set SUPERMEMORY_CC_API_KEY environment variable manually. }, ]); - const errorNotice = - apiErrors.length > 0 - ? `\n${[...new Set(apiErrors)].join('\n')}\n\n` - : ''; - if (!additionalContext) { writeOutput({ hookSpecificOutput: { hookEventName: 'SessionStart', - additionalContext: apiErrors.length > 0 - ? errorNotice - : ` + additionalContext: ` No previous memories found for this project. Memories will be saved as you work. `, @@ -131,18 +75,17 @@ Memories will be saved as you work. writeOutput({ hookSpecificOutput: { hookEventName: 'SessionStart', - additionalContext: errorNotice + additionalContext, + additionalContext, }, }); } catch (err) { - const friendly = getUserFriendlyError(err); - debugLog(settings, 'Error', { error: friendly }); - console.error(`Supermemory: ${friendly}`); + debugLog(settings, 'Error', { error: err.message }); + console.error(`Supermemory-local: ${err.message}`); writeOutput({ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: ` -Failed to load memories: ${friendly} +Failed to load memories: ${err.message} Session will continue without memory context. `, }, @@ -151,6 +94,6 @@ Session will continue without memory context. } main().catch((err) => { - console.error(`Supermemory fatal: ${err.message}`); + console.error(`Supermemory-local fatal: ${err.message}`); process.exit(1); }); diff --git a/src/lib/local-memory-client.js b/src/lib/local-memory-client.js new file mode 100644 index 0000000..139b1c2 --- /dev/null +++ b/src/lib/local-memory-client.js @@ -0,0 +1,174 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const os = require('node:os'); +const crypto = require('node:crypto'); + +const MEMORIES_DIR = path.join(os.homedir(), '.supermemory-claude', 'memories'); + +const PERSONAL_ENTITY_CONTEXT = `Developer coding session transcript. Focus on USER message and intent. + +RULES: +- Extract USER's action/intent, not every detail assistant provides +- Condense assistant responses into what user gained from it +- Skip granular facts from assistant output + +EXTRACT: +- Research: "researched whisper.cpp for speech recognition" +- Actions: "built auth flow with JWT", "fixed memory leak in useEffect" +- Preferences: "prefers Tailwind over CSS modules" +- Decisions: "chose SQLite for local storage" +- Learnings: "learned about React Server Components" + +SKIP: +- Every fact assistant mentions (condense to user's action) +- Generic assistant explanations user didn't confirm/use`; + +const REPO_ENTITY_CONTEXT = `Project/codebase knowledge for team sharing. + +EXTRACT: +- Architecture: "uses monorepo with turborepo", "API in /apps/api" +- Conventions: "components in PascalCase", "hooks prefixed with use" +- Patterns: "all API routes use withAuth wrapper", "errors thrown as ApiError" +- Setup: "requires .env with DATABASE_URL", "run pnpm db:migrate first" +- Decisions: "chose Drizzle over Prisma for performance", "using RSC for data fetching"`; + +function ensureDir(dir) { + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } +} + +function containerDir(type, containerTag) { + return path.join(MEMORIES_DIR, type, containerTag); +} + +function loadAllMemories(dir) { + if (!fs.existsSync(dir)) return []; + const files = fs.readdirSync(dir).filter((f) => f.endsWith('.json')); + const memories = []; + for (const file of files) { + try { + const raw = fs.readFileSync(path.join(dir, file), 'utf-8'); + memories.push(JSON.parse(raw)); + } catch { + // skip corrupt files + } + } + return memories; +} + +function scoreMemory(memory, queryTokens) { + const content = (memory.content || '').toLowerCase(); + let score = 0; + for (const token of queryTokens) { + if (content.includes(token)) { + score += 1; + } + } + // Boost recent memories + const age = Date.now() - new Date(memory.createdAt || 0).getTime(); + const recencyBonus = Math.max(0, 1 - age / (30 * 24 * 60 * 60 * 1000)); // decay over 30 days + return score + recencyBonus * 0.5; +} + +class LocalMemoryClient { + constructor(containerTag) { + this.containerTag = containerTag || 'default'; + } + + async addMemory(content, containerTag, metadata = {}) { + const tag = containerTag || this.containerTag; + const type = metadata.type === 'project-knowledge' ? 'repo' : 'personal'; + const dir = containerDir(type, tag); + ensureDir(dir); + + const id = crypto.randomUUID(); + const entry = { + id, + content, + metadata: { sm_source: 'claude-code-local', ...metadata }, + createdAt: new Date().toISOString(), + }; + + fs.writeFileSync(path.join(dir, `${id}.json`), JSON.stringify(entry, null, 2)); + return { id, status: 'saved', containerTag: tag }; + } + + async search(query, containerTag, options = {}) { + const tag = containerTag || this.containerTag; + const limit = options.limit || 10; + + // Search both personal and repo for this tag + const personalDir = containerDir('personal', tag); + const repoDir = containerDir('repo', tag); + const allMemories = [...loadAllMemories(personalDir), ...loadAllMemories(repoDir)]; + + if (allMemories.length === 0) { + return { results: [], total: 0 }; + } + + const queryTokens = query + .toLowerCase() + .split(/\s+/) + .filter((t) => t.length > 2); + + const scored = allMemories + .map((m) => ({ + memory: m.content || '', + metadata: m.metadata, + updatedAt: m.createdAt, + similarity: queryTokens.length > 0 ? scoreMemory(m, queryTokens) / queryTokens.length : 0, + })) + .filter((m) => m.similarity > 0) + .sort((a, b) => b.similarity - a.similarity) + .slice(0, limit); + + return { results: scored, total: scored.length }; + } + + async getProfile(containerTag, projectName, maxItems = 5) { + const tag = containerTag || this.containerTag; + const personalDir = containerDir('personal', tag); + const repoDir = containerDir('repo', tag); + + const personalMemories = loadAllMemories(personalDir); + const repoMemories = loadAllMemories(repoDir); + + // Sort by date descending + const sortByDate = (a, b) => + new Date(b.createdAt || 0).getTime() - new Date(a.createdAt || 0).getTime(); + + personalMemories.sort(sortByDate); + repoMemories.sort(sortByDate); + + // Static = repo knowledge, Dynamic = recent personal + const staticFacts = repoMemories.slice(0, maxItems).map((m) => m.content); + const dynamicFacts = personalMemories.slice(0, maxItems).map((m) => m.content); + + // Recent search results (most recent memories from both) + const allRecent = [...personalMemories, ...repoMemories] + .sort(sortByDate) + .slice(0, maxItems); + + const searchResults = { + results: allRecent.map((m) => ({ + id: m.id, + memory: m.content, + similarity: 1, + updatedAt: m.createdAt, + })), + total: allRecent.length, + }; + + return { + profile: { static: staticFacts, dynamic: dynamicFacts }, + searchResults, + }; + } +} + +module.exports = { + LocalMemoryClient, + PERSONAL_ENTITY_CONTEXT, + REPO_ENTITY_CONTEXT, +}; diff --git a/src/lib/settings.js b/src/lib/settings.js index 2c017d8..932fc4c 100644 --- a/src/lib/settings.js +++ b/src/lib/settings.js @@ -1,15 +1,11 @@ const fs = require('node:fs'); const path = require('node:path'); const os = require('node:os'); -const { loadCredentials } = require('./auth'); const { loadProjectConfig } = require('./project-config'); const SETTINGS_DIR = path.join(os.homedir(), '.supermemory-claude'); const SETTINGS_FILE = path.join(SETTINGS_DIR, 'settings.json'); -// Available tools: Read, Write, Edit, Glob, Grep, Bash, WebSearch, WebFetch, -// Task, TaskOutput, TodoWrite, AskUserQuestion, ExitPlanMode, NotebookEdit, -// LSP, MCPSearch, KillShell, Skill, EnterPlanMode const DEFAULT_SETTINGS = { includeTools: [], maxProfileItems: 5, @@ -54,8 +50,6 @@ function loadSettings() { } catch (err) { console.error(`Settings: Failed to load ${SETTINGS_FILE}: ${err.message}`); } - if (process.env.SUPERMEMORY_CC_API_KEY) - settings.apiKey = process.env.SUPERMEMORY_CC_API_KEY; if (process.env.SUPERMEMORY_DEBUG === 'true') settings.debug = true; return settings; } @@ -63,24 +57,9 @@ function loadSettings() { function saveSettings(settings) { ensureSettingsDir(); const toSave = { ...settings }; - delete toSave.apiKey; fs.writeFileSync(SETTINGS_FILE, JSON.stringify(toSave, null, 2)); } -function getApiKey(settings, cwd) { - if (settings.apiKey) return settings.apiKey; - if (process.env.SUPERMEMORY_CC_API_KEY) - return process.env.SUPERMEMORY_CC_API_KEY; - - const projectConfig = loadProjectConfig(cwd || process.cwd()); - if (projectConfig?.apiKey) return projectConfig.apiKey; - - const credentials = loadCredentials(); - if (credentials?.apiKey) return credentials.apiKey; - - throw new Error('NO_API_KEY'); -} - function debugLog(settings, message, data) { if (settings.debug) { const timestamp = new Date().toISOString(); @@ -139,7 +118,6 @@ module.exports = { DEFAULT_SETTINGS, loadSettings, saveSettings, - getApiKey, debugLog, getIncludeTools, shouldIncludeTool, diff --git a/src/save-project-memory.js b/src/save-project-memory.js index 456a462..3bab976 100644 --- a/src/save-project-memory.js +++ b/src/save-project-memory.js @@ -1,10 +1,8 @@ const { - SupermemoryClient, + LocalMemoryClient, REPO_ENTITY_CONTEXT, -} = require('./lib/supermemory-client'); +} = require('./lib/local-memory-client'); const { getRepoContainerTag, getProjectName } = require('./lib/container-tag'); -const { loadSettings, getApiKey } = require('./lib/settings'); -const { getUserFriendlyError } = require('./lib/error-helpers'); async function main() { const content = process.argv.slice(2).join(' '); @@ -16,23 +14,12 @@ async function main() { return; } - const settings = loadSettings(); - - let apiKey; - try { - apiKey = getApiKey(settings); - } catch { - console.log('Supermemory API key not configured.'); - console.log('Set SUPERMEMORY_CC_API_KEY environment variable.'); - return; - } - const cwd = process.cwd(); const containerTag = getRepoContainerTag(cwd); const projectName = getProjectName(cwd); try { - const client = new SupermemoryClient(apiKey, containerTag); + const client = new LocalMemoryClient(containerTag); const result = await client.addMemory( content, containerTag, @@ -41,13 +28,12 @@ async function main() { project: projectName, timestamp: new Date().toISOString(), }, - { entityContext: REPO_ENTITY_CONTEXT }, ); console.log(`Project knowledge saved: ${projectName}`); console.log(`ID: ${result.id}`); } catch (err) { - console.log(`Error saving: ${getUserFriendlyError(err)}`); + console.log(`Error saving: ${err.message}`); } } diff --git a/src/search-memory.js b/src/search-memory.js index 4d27e3f..c82e363 100644 --- a/src/search-memory.js +++ b/src/search-memory.js @@ -1,12 +1,11 @@ -const { SupermemoryClient } = require('./lib/supermemory-client'); +const { LocalMemoryClient } = require('./lib/local-memory-client'); const { getProjectName, getContainerTag, getRepoContainerTag, } = require('./lib/container-tag'); -const { loadSettings, getApiKey } = require('./lib/settings'); +const { loadSettings } = require('./lib/settings'); const { formatSearchResults } = require('./lib/format-context'); -const { getUserFriendlyError } = require('./lib/error-helpers'); function parseArgs(args) { let containerType = 'both'; @@ -37,27 +36,13 @@ async function main() { return; } - const settings = loadSettings(); - - let apiKey; - try { - apiKey = getApiKey(settings); - } 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; - } - const cwd = process.cwd(); const projectName = getProjectName(cwd); const personalTag = getContainerTag(cwd); const repoTag = getRepoContainerTag(cwd); try { - const client = new SupermemoryClient(apiKey, personalTag); + const client = new LocalMemoryClient(personalTag); console.log(`Project: ${projectName}\n`); @@ -86,7 +71,7 @@ async function main() { console.log(formatSearchResults(query, searchResult.results, label)); } } catch (err) { - console.log(`Error searching memories: ${getUserFriendlyError(err)}`); + console.log(`Error searching memories: ${err.message}`); } } diff --git a/src/summary-hook.js b/src/summary-hook.js index c1f0c95..850e03f 100644 --- a/src/summary-hook.js +++ b/src/summary-hook.js @@ -1,11 +1,10 @@ const { - SupermemoryClient, + LocalMemoryClient, PERSONAL_ENTITY_CONTEXT, -} = require('./lib/supermemory-client'); +} = require('./lib/local-memory-client'); const { getContainerTag, getProjectName } = require('./lib/container-tag'); const { loadSettings, - getApiKey, debugLog, getSignalConfig, } = require('./lib/settings'); @@ -14,7 +13,6 @@ const { formatNewEntries, formatSignalEntries, } = require('./lib/transcript-formatter'); -const { getUserFriendlyError } = require('./lib/error-helpers'); async function main() { const settings = loadSettings(); @@ -33,14 +31,6 @@ async function main() { return; } - let apiKey; - try { - apiKey = getApiKey(settings); - } catch { - writeOutput({ continue: true }); - return; - } - const signalConfig = getSignalConfig(cwd); const useSignalExtraction = signalConfig.enabled; @@ -62,7 +52,7 @@ async function main() { return; } - const client = new SupermemoryClient(apiKey); + const client = new LocalMemoryClient(); const containerTag = getContainerTag(cwd); const projectName = getProjectName(cwd); @@ -74,20 +64,18 @@ async function main() { project: projectName, timestamp: new Date().toISOString(), }, - { customId: sessionId, entityContext: PERSONAL_ENTITY_CONTEXT }, ); debugLog(settings, 'Session turn saved', { length: formatted.length }); writeOutput({ continue: true }); } catch (err) { - const friendly = getUserFriendlyError(err); - debugLog(settings, 'Error', { error: friendly }); - console.error(`Supermemory: ${friendly}`); + debugLog(settings, 'Error', { error: err.message }); + console.error(`Supermemory-local: ${err.message}`); writeOutput({ continue: true }); } } main().catch((err) => { - console.error(`Supermemory fatal: ${err.message}`); + console.error(`Supermemory-local fatal: ${err.message}`); process.exit(1); });