diff --git a/README.md b/README.md index ff4a3f8..e01b54e 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Your agent remembers what you worked on - across sessions, across projects. - **Team Memory** — Project knowledge shared across your team, separate from personal memories - **Auto Capture** — Conversations saved when session ends - **Project Config** — Per-repo settings, API keys, and container tags +- **Custom Container Tags** — Define custom memory containers (e.g., `work`, `personal`, `code_style`). The AI automatically routes memories to the right container based on your descriptions ## Installation @@ -31,6 +32,8 @@ export SUPERMEMORY_CC_API_KEY="sm_..." - **super-search** — Ask about past work or previous sessions, Claude searches your memories - **super-save** — Ask to save something important, Claude saves it for the team +All memory commands support `--container ` to target a specific custom container when custom containers are enabled. + ## Commands | Command | Description | @@ -60,13 +63,16 @@ SUPERMEMORY_DEBUG=true # Optional: enable debug logging } ``` -| Option | Description | -| ------------------- | --------------------------------------------- | -| `maxProfileItems` | Max memories in context (default: 5) | -| `signalExtraction` | Only capture important turns (default: false) | -| `signalKeywords` | Keywords that trigger capture | -| `signalTurnsBefore` | Context turns before signal (default: 3) | -| `includeTools` | Tools to explicitly capture | +| Option | Description | +| ---------------------------- | --------------------------------------------- | +| `maxProfileItems` | Max memories in context (default: 5) | +| `signalExtraction` | Only capture important turns (default: false) | +| `signalKeywords` | Keywords that trigger capture | +| `signalTurnsBefore` | Context turns before signal (default: 3) | +| `includeTools` | Tools to explicitly capture | +| `enableCustomContainers` | Enable AI-driven container routing (default: false) | +| `customContainers` | Array of `{tag, description}` container definitions | +| `customContainerInstructions`| Free-text instructions for AI on routing | **Project Config** — `.claude/.supermemory-claude/config.json` @@ -80,11 +86,63 @@ Per-repo overrides. Run `/claude-supermemory:project-config` or create manually: } ``` -| Option | Description | -| ---------------------- | --------------------------- | -| `apiKey` | Project-specific API key | -| `personalContainerTag` | Override personal container | -| `repoContainerTag` | Override team container tag | +| Option | Description | +| ---------------------------- | ------------------------------------ | +| `apiKey` | Project-specific API key | +| `personalContainerTag` | Override personal container | +| `repoContainerTag` | Override team container tag | +| `enableCustomContainers` | Enable custom container routing | +| `customContainers` | Project-specific container definitions | +| `customContainerInstructions`| Project-specific routing instructions | + +## Custom Container Tags + +Custom container tags let you organize memories into separate buckets (e.g., `work`, +`personal`, `code_style`). The AI reads the container descriptions from your config +and automatically picks the right container when saving memories. + +### Setup + +Add these fields to `~/.supermemory-claude/settings.json`: + +```json +{ + "enableCustomContainers": true, + "customContainers": [ + { "tag": "personal", "description": "Personal life — family, health, hobbies, routines" }, + { "tag": "work", "description": "Work-related — projects, deadlines, meetings, colleagues" }, + { "tag": "code_style", "description": "Coding preferences — languages, tools, patterns, conventions" } + ], + "customContainerInstructions": "Route coding preferences to code_style. Personal topics to personal. Default to project container for ambiguous content." +} +``` + +You can also set these per-project in `.claude/.supermemory-claude/config.json`. + +### How it works + +1. You define containers with a `tag` (identifier) and a `description` (plain English + explaining what belongs there). +2. On session start, the container catalog is injected into the AI's context so it knows + what containers are available. +3. When the AI saves a memory, it picks the best matching container based on the + descriptions and uses `--container `. +4. When searching, the AI can also target specific containers. +5. Auto-capture (background saving at session end) always goes to the default + personal/repo containers — only explicit saves get routed to custom containers. +6. Invalid container tags are rejected with a list of valid options, preventing + orphaned spaces. + +Each container tag automatically becomes a **Space** on the +[Supermemory dashboard](https://app.supermemory.ai), so you can view and manage +memories organized by category. + +### Container config reference + +| Field | Type | Description | +| ------------------ | -------- | -------------------------------------------------- | +| `tag` | `string` | Unique identifier for the container (e.g. `work`). | +| `description` | `string` | Plain English description for AI routing. | ## License diff --git a/package-lock.json b/package-lock.json index a3f6ec2..7895410 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-supermemory-dev", - "version": "1.0.0", + "version": "2.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "claude-supermemory-dev", - "version": "1.0.0", + "version": "2.1.0", "dependencies": { "supermemory": "^4.0.0" }, diff --git a/package.json b/package.json index ab5f853..3305986 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-supermemory-dev", - "version": "2.0.1", + "version": "2.1.0", "description": "Claude code plugin by Supermemory AI", "private": true, "type": "commonjs", diff --git a/plugin/scripts/add-memory.cjs b/plugin/scripts/add-memory.cjs index 9815735..adeda2a 100755 --- a/plugin/scripts/add-memory.cjs +++ b/plugin/scripts/add-memory.cjs @@ -1,9 +1,9 @@ #!/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: +var Ue=Object.defineProperty;var Sr=Object.getOwnPropertyDescriptor;var Gr=Object.getOwnPropertyNames;var Kr=Object.prototype.hasOwnProperty;var kr=(e,t)=>()=>(e&&(t=e(e=0)),t);var c=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Er=(e,t)=>{for(var r in t)Ue(e,r,{get:t[r],enumerable:!0})},Cr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Gr(t))!Kr.call(e,s)&&s!==r&&Ue(e,s,{get:()=>t[s],enumerable:!(n=Sr(t,s))||n.enumerable});return e};var Ir=e=>Cr(Ue({},"__esModule",{value:!0}),e);var Ge=c(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=Jr;h.__classPrivateFieldGet=Br;h.__importStar=Ar;h.__exportStar=Qr;function Jr(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 Br(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 Se=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=Se;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 Ye=function(e){return Ye=Object.getOwnPropertyNames||function(t){var r=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[r.length]=n);return r},Ye(e)};function Ar(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var r=Ye(e),n=0;n{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.uuid4=void 0;var _r=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Y.uuid4=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};Y.uuid4=_r});var Ke=c(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=$r;function $r(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var en=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=en});var K=c(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.InternalServerError=p.RateLimitError=p.UnprocessableEntityError=p.ConflictError=p.NotFoundError=p.PermissionDeniedError=p.AuthenticationError=p.BadRequestError=p.APIConnectionTimeoutError=p.APIConnectionError=p.APIUserAbortError=p.APIError=p.SupermemoryError=void 0;var tn=Ke(),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,tn.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 ie(t,o,n,s):t===404?new fe(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 ke=class extends O{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}};p.APIUserAbortError=ke;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 Ee=class extends G{constructor({message:t}={}){super({message:t??"Request timed out."})}};p.APIConnectionTimeoutError=Ee;var oe=class extends O{};p.BadRequestError=oe;var ae=class extends O{};p.AuthenticationError=ae;var ie=class extends O{};p.PermissionDeniedError=ie;var fe=class extends O{};p.NotFoundError=fe;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=c(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=on;v.isEmptyObj=an;v.hasOwn=fn;v.isObj=cn;var k=K(),rn=/^[a-z][a-z0-9+.-]*:/i,nn=e=>rn.test(e);v.isAbsoluteURL=nn;var sn=e=>(v.isArray=Array.isArray,(0,v.isArray)(e));v.isArray=sn;v.isReadonlyArray=v.isArray;function on(e){return typeof e!="object"?{}:e??{}}function an(e){if(!e)return!0;for(let t in e)return!1;return!0}function fn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function cn(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var un=e=>{if(e==null)throw new k.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};v.ensurePresent=un;var dn=(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};v.validatePositiveInteger=dn;var vn=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`)};v.coerceInteger=vn;var ln=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`)};v.coerceFloat=ln;var pn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;v.coerceBoolean=pn;var Pn=e=>{if(e!=null)return(0,v.coerceInteger)(e)};v.maybeCoerceInteger=Pn;var zn=e=>{if(e!=null)return(0,v.coerceFloat)(e)};v.maybeCoerceFloat=zn;var mn=e=>{if(e!=null)return(0,v.coerceBoolean)(e)};v.maybeCoerceBoolean=mn;var bn=e=>{try{return JSON.parse(e)}catch{return}};v.safeJSON=bn});var Yt=c(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.sleep=void 0;var jn=e=>new Promise(t=>setTimeout(t,e));le.sleep=jn});var Ce=c(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.VERSION=void 0;pe.VERSION="4.0.0"});var kt=c(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.getPlatformHeaders=Z.isRunningInBrowser=void 0;var C=Ce(),xn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Z.isRunningInBrowser=xn;function Xn(){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 On=()=>{let e=Xn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C.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":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":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=yn();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 yn(){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,qn=()=>Kt??(Kt=On());Z.getPlatformHeaders=qn});var Ie=c(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=Hn;V.makeReadableStream=Et;V.ReadableStreamFrom=hn;V.ReadableStreamToAsyncIterable=Wn;V.CancelReadableStream=Tn;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 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 hn(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 Wn(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 Tn(e){if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}});var Ct=c(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.FallbackEncoder=void 0;var Nn=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});Pe.FallbackEncoder=Nn});var I=c(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.createForm=j.multipartFormRequestOptions=j.maybeMultipartFormRequestOptions=j.isAsyncIterable=j.checkFileSupport=void 0;j.makeFile=Je;j.getName=ze;var Ln=Ie(),Vn=()=>{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=Vn;function Je(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 Rn=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";j.isAsyncIterable=Rn;var gn=async(e,t)=>Be(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=gn;var Zn=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=Zn;var It=new WeakMap;function wn(e){let t=typeof e=="function"?e:e.fetch,r=It.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 It.set(t,n),n}var Mn=async(e,t)=>{if(!await wn(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])=>Ae(r,n,s))),r};j.createForm=Mn;var Jt=e=>e instanceof Blob&&"name"in e,Fn=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||Jt(e)),Be=e=>{if(Fn(e))return!0;if(Array.isArray(e))return e.some(Be);if(e&&typeof e=="object"){for(let t in e)if(Be(e[t]))return!0}return!1},Ae=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,Je([await r.blob()],ze(r)));else if((0,j.isAsyncIterable)(r))e.append(t,Je([await new Response((0,Ln.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=>Ae(e,t+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>Ae(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=c(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.toFile=Sn;var J=I(),Dn=I(),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",Un=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Bt(e),Yn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Sn(e,t,r){if((0,Dn.checkFileSupport)(),e=await e,Un(e))return e instanceof File?e:(0,J.makeFile)([await e.arrayBuffer()],e.name);if(Yn(e)){let s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),(0,J.makeFile)(await Qe(s),t,r)}let n=await Qe(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 Qe(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 Qe(r));else{let r=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Gn(e)}`)}return t}function Gn(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var $e=c(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.toFile=void 0;var Kn=At();Object.defineProperty(me,"toFile",{enumerable:!0,get:function(){return Kn.toFile}})});var w=c(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.APIResource=void 0;var et=class{constructor(t){this._client=t}};be.APIResource=et});var B=c(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 i of o)i!==void 0&&(t&&!a&&(a=!0,yield[s,null]),yield[s,i])}}var kn=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 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{[_t]:!0,values:t,nulls:r}};M.buildHeaders=kn;var En=e=>{for(let t of $t(e))return!1;return!0};M.isEmptyHeaders=En});var je=c(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=tt;var Cn=K();function tt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var er=Object.freeze(Object.create(null)),In=(e=tt)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],a=r.reduce((l,m,X)=>{/[?#]/.test(m)&&(s=!0);let f=n[X],H=(s?encodeURIComponent:e)(""+f);return X!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??er)??er)?.toString)&&(H=f+"",o.push({start:l.length+m.length,length:H.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),l+m+(X===n.length?"":H)},""),i=a.split(/[?#]/,1)[0],P=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=P.exec(i))!==null;)o.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(o.sort((l,m)=>l.start-m.start),o.length>0){let l=0,m=o.reduce((X,f)=>{let H=" ".repeat(f.start-l),D="^".repeat(f.length);return l=f.start+f.length,X+H+D},"");throw new Cn.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. +${m}`)}return a};N.createPathTagFunction=In;N.path=(0,N.createPathTagFunction)(tt)});var nt=c(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.Connections=void 0;var Jn=w(),Bn=B(),W=je(),rt=class extends Jn.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,Bn.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=rt});var at=c(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.Documents=void 0;var An=w(),Qn=B(),_n=I(),st=je(),ot=class extends An.APIResource{update(t,r={},n){return this._client.patch((0,st.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,st.path)`/v3/documents/${t}`,{...r,headers:(0,Qn.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,st.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=ot});var ct=c(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Memories=void 0;var $n=w(),es=B(),ts=I(),it=je(),ft=class extends $n.APIResource{update(t,r={},n){return this._client.patch((0,it.path)`/v3/documents/${t}`,{body:r,...n})}list(t={},r){return this._client.post("/v3/documents/list",{body:t,...r})}delete(t,r){return this._client.delete((0,it.path)`/v3/documents/${t}`,{...r,headers:(0,es.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,it.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,ts.multipartFormRequestOptions)({body:t,...r},this._client))}};Oe.Memories=ft});var dt=c(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Search=void 0;var rs=w(),ut=class extends rs.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=ut});var lt=c(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Settings=void 0;var ns=w(),vt=class extends ns.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};qe.Settings=vt});var tr=c(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.Settings=q.Search=q.Memories=q.Documents=q.Connections=void 0;var ss=nt();Object.defineProperty(q,"Connections",{enumerable:!0,get:function(){return ss.Connections}});var os=at();Object.defineProperty(q,"Documents",{enumerable:!0,get:function(){return os.Documents}});var as=ct();Object.defineProperty(q,"Memories",{enumerable:!0,get:function(){return as.Memories}});var is=dt();Object.defineProperty(q,"Search",{enumerable:!0,get:function(){return is.Search}});var fs=lt();Object.defineProperty(q,"Settings",{enumerable:!0,get:function(){return fs.Settings}})});var pt=c(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=nr;var cs=E(),he={off:0,error:200,warn:300,info:400,debug:500},us=(e,t,r)=>{if(e){if((0,cs.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=us;function A(){}function He(e,t,r){return!t||he[e]>he[r]?A:t[e].bind(t)}var ds={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 ds;let n=rr.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 rr.set(t,[r,s]),s}var vs=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=vs});var or=c(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.defaultParseResponse=ls;var sr=pt();async function ls(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,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 bt=c(We=>{"use strict";var Q;Object.defineProperty(We,"__esModule",{value:!0});We.APIPromise=void 0;var zt=Ge(),ps=or(),mt=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),zt.__classPrivateFieldSet(this,Q,t,"f")}_thenUnwrap(t){return new e(zt.__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(zt.__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=mt;Q=new WeakMap});var ar=c(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.readEnv=void 0;var Ps=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=Ps});var ht=c(Le=>{"use strict";var qt,Ht,Ne,ir;Object.defineProperty(Le,"__esModule",{value:!0});Le.Supermemory=void 0;var L=Ge(),zs=Ut(),jt=E(),ms=Yt(),xt=Ke(),bs=kt(),Xt=L.__importStar(Ie()),js=L.__importStar(Ct()),xs=Ce(),b=L.__importStar(K()),Xs=L.__importStar($e()),_=L.__importStar(tr()),Os=bt(),ys=nt(),qs=at(),Hs=ct(),hs=dt(),Ws=lt(),Ot=B(),yt=ar(),x=pt(),Ts=E(),z=class{constructor({baseURL:t=(0,yt.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,yt.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(qt.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??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,yt.readEnv)("SUPERMEMORY_LOG"),"process.env['SUPERMEMORY_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Xt.getDefaultFetch(),L.__classPrivateFieldSet(this,Ne,js.FallbackEncoder,"f"),this._options=s,this.apiKey=r}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,...t})}add(t,r){return this.post("/v3/documents",{body:t,...r})}profile(t,r){return this.post("/v4/profile",{body:t,...r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:r}){}async authHeaders(t){return(0,Ot.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,zs.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,qt,"m",ir).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,Ts.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 Os.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 d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=n===void 0?"":`, retryOf: ${n}`,m=Date.now();if((0,x.loggerFor)(this).debug(`[${d}] sending request`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,method:s.method,url:i,options:s,headers:a.headers})),s.signal?.aborted)throw new b.APIUserAbortError;let X=new AbortController,f=await this.fetchWithTimeout(i,a,P,X).catch(xt.castToError),H=Date.now();if(f instanceof globalThis.Error){let U=`retrying, ${r} attempts remaining`;if(s.signal?.aborted)throw new b.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(`[${d}] connection ${T?"timed out":"failed"} - ${U}`),(0,x.loggerFor)(this).debug(`[${d}] connection ${T?"timed out":"failed"} (${U})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:H-m,message:f.message})),this.retryRequest(s,r,n??d);throw(0,x.loggerFor)(this).info(`[${d}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,x.loggerFor)(this).debug(`[${d}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:H-m,message:f.message})),T?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:f})}let D=`[${d}${l}] ${a.method} ${i} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${H-m}ms`;if(!f.ok){let U=await this.shouldRetry(f);if(r&&U){let ne=`retrying, ${r} attempts remaining`;return await Xt.CancelReadableStream(f.body),(0,x.loggerFor)(this).info(`${D} - ${ne}`),(0,x.loggerFor)(this).debug(`[${d}] response error (${ne})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:H-m})),this.retryRequest(s,r,n??d,f.headers)}let T=U?"error; no more retries left":"error; not retryable";(0,x.loggerFor)(this).info(`${D} - ${T}`);let wt=await f.text().catch(ne=>(0,xt.castToError)(ne).message),Mt=(0,jt.safeJSON)(wt),Ft=Mt?void 0:wt;throw(0,x.loggerFor)(this).debug(`[${d}] response error (${T})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:Ft,durationMs:Date.now()-m})),this.makeStatusError(f.status,Mt,Ft,f.headers)}return(0,x.loggerFor)(this).info(D),(0,x.loggerFor)(this).debug(`[${d}] response start`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:H-m})),{response:f,options:s,controller:X,requestLogID:d,retryOfRequestLogID:n,startTime:m}}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),d=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,l={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...i};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,l)}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,ms.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:d,body:l}=this.buildBody({options:n}),m=await this.buildHeaders({options:t,method:s,bodyHeaders:d,retryCount:r});return{req:{method:s,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url: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,Ot.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,bs.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,Ot.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:Xt.ReadableStreamFrom(t)}:L.__classPrivateFieldGet(this,Ne,"f").call(this,{body:t,headers:n})}};Le.Supermemory=z;Ht=z,Ne=new WeakMap,qt=new WeakSet,ir=function(){return this.baseURL!=="https://api.supermemory.ai"};z.Supermemory=Ht;z.DEFAULT_TIMEOUT=6e4;z.SupermemoryError=b.SupermemoryError;z.APIError=b.APIError;z.APIConnectionError=b.APIConnectionError;z.APIConnectionTimeoutError=b.APIConnectionTimeoutError;z.APIUserAbortError=b.APIUserAbortError;z.NotFoundError=b.NotFoundError;z.ConflictError=b.ConflictError;z.RateLimitError=b.RateLimitError;z.BadRequestError=b.BadRequestError;z.AuthenticationError=b.AuthenticationError;z.InternalServerError=b.InternalServerError;z.PermissionDeniedError=b.PermissionDeniedError;z.UnprocessableEntityError=b.UnprocessableEntityError;z.toFile=Xs.toFile;z.Memories=Hs.Memories;z.Documents=qs.Documents;z.Search=hs.Search;z.Settings=Ws.Settings;z.Connections=ys.Connections});var cr=c((u,fr)=>{"use strict";u=fr.exports=function(...e){return new u.default(...e)};Object.defineProperty(u,"__esModule",{value:!0});u.UnprocessableEntityError=u.PermissionDeniedError=u.InternalServerError=u.AuthenticationError=u.BadRequestError=u.RateLimitError=u.ConflictError=u.NotFoundError=u.APIUserAbortError=u.APIConnectionTimeoutError=u.APIConnectionError=u.APIError=u.SupermemoryError=u.Supermemory=u.APIPromise=u.toFile=u.default=void 0;var Ns=ht();Object.defineProperty(u,"default",{enumerable:!0,get:function(){return Ns.Supermemory}});var Ls=$e();Object.defineProperty(u,"toFile",{enumerable:!0,get:function(){return Ls.toFile}});var Vs=bt();Object.defineProperty(u,"APIPromise",{enumerable:!0,get:function(){return Vs.APIPromise}});var Rs=ht();Object.defineProperty(u,"Supermemory",{enumerable:!0,get:function(){return Rs.Supermemory}});var y=K();Object.defineProperty(u,"SupermemoryError",{enumerable:!0,get:function(){return y.SupermemoryError}});Object.defineProperty(u,"APIError",{enumerable:!0,get:function(){return y.APIError}});Object.defineProperty(u,"APIConnectionError",{enumerable:!0,get:function(){return y.APIConnectionError}});Object.defineProperty(u,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return y.APIConnectionTimeoutError}});Object.defineProperty(u,"APIUserAbortError",{enumerable:!0,get:function(){return y.APIUserAbortError}});Object.defineProperty(u,"NotFoundError",{enumerable:!0,get:function(){return y.NotFoundError}});Object.defineProperty(u,"ConflictError",{enumerable:!0,get:function(){return y.ConflictError}});Object.defineProperty(u,"RateLimitError",{enumerable:!0,get:function(){return y.RateLimitError}});Object.defineProperty(u,"BadRequestError",{enumerable:!0,get:function(){return y.BadRequestError}});Object.defineProperty(u,"AuthenticationError",{enumerable:!0,get:function(){return y.AuthenticationError}});Object.defineProperty(u,"InternalServerError",{enumerable:!0,get:function(){return y.InternalServerError}});Object.defineProperty(u,"PermissionDeniedError",{enumerable:!0,get:function(){return y.PermissionDeniedError}});Object.defineProperty(u,"UnprocessableEntityError",{enumerable:!0,get:function(){return y.UnprocessableEntityError}})});var dr={};Er(dr,{getRequestIntegrity:()=>Es,sanitizeContent:()=>Ms,sanitizeMetadata:()=>Ss,validateApiKeyFormat:()=>gs,validateContainerTag:()=>Zs,validateContentLength:()=>Fs,validateRecallConfig:()=>Gs});function gs(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 Ms(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of ws)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function Fs(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Ss(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=Ds)break;n.length>Us||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,Ys),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function Gs(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 Wt(e){return(0,Ve.createHash)("sha256").update(e).digest("hex")}function ks(e,t){let r=[Wt(e),Wt(t),ur].join(":");return(0,Ve.createHmac)("sha256",Ks).update(r).digest("base64url")}function Es(e,t){let r=Wt(t),n=ks(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${ur}`,n].join(".")}}var Ve,ws,Ds,Us,Ys,ur,Ks,vr=kr(()=>{Ve=require("node:crypto");ws=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];Ds=50,Us=128,Ys=1024;ur=1,Ks="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var pr=c((ya,lr)=>{var Cs=cr().default,{getRequestIntegrity:Is,validateApiKeyFormat:Js,validateContainerTag:Bs}=(vr(),Ir(dr)),As="claudecode_default",Qs=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 $s=`Developer coding session transcript. Focus on USER message and intent. RULES: - Extract USER's action/intent, not every detail assistant provides matter @@ -30,7 +30,7 @@ EXAMPLES: SKIP: - Every fact assistant mentions (condense to user's action) -- Generic assistant explanations user didn't confirm/use`,Bs=`Project/codebase knowledge for team sharing. +- Generic assistant explanations user didn't confirm/use`,eo=`Project/codebase knowledge for team sharing. EXTRACT: - Architecture: "uses monorepo with turborepo", "API in /apps/api" @@ -43,7 +43,7 @@ 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=` +| "To add a new API route..." | "Adding API routes: [steps]" |`,Tt=class{constructor(t,r){if(!t)throw new Error("SUPERMEMORY_CC_API_KEY is required");let n=Js(t);if(!n.valid)throw new Error(`Invalid API key: ${n.reason}`);let s=r||As,o=Bs(s);o.valid||console.warn(`Container tag warning: ${o.reason}`);let a=Is(t,s);this.client=new Cs({apiKey:t,baseURL:Qs,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=(d,l=m=>m)=>d.filter(m=>{let X=String(l(m)).toLowerCase().trim();return!X||s.has(X)?!1:(s.add(X),!0)}),a=o(n.profile?.static||[]),i=o(n.profile?.dynamic||[]),P;if(n.searchResults){let d=n.searchResults.results.map(l=>({id:l.id,memory:l.content||l.context||"",similarity:l.similarity,title:l.title,updatedAt:l.updatedAt}));P={results:o(d,l=>l.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:i},searchResults:P}}};lr.exports={SupermemoryClient:Tt,PERSONAL_ENTITY_CONTEXT:$s,REPO_ENTITY_CONTEXT:eo}});var Nt=c((qa,Pr)=>{var{execSync:Re}=require("node:child_process"),$=require("node:path");function to(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:to}});var Lt=c((Ha,Xr)=>{var ee=require("node:fs"),ge=require("node:path"),{getGitRoot:zr}=Nt(),mr=ge.join(".claude",".supermemory-claude"),br="config.json";function jr(e){let r=zr(e)||e;return ge.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 ro(e,t){let n=zr(e)||e,s=ge.join(n,mr),o=ge.join(s,br);ee.existsSync(s)||ee.mkdirSync(s,{recursive:!0});let i={...xr(e)||{},...t};return ee.writeFileSync(o,JSON.stringify(i,null,2)),o}Xr.exports={getConfigPath:jr,loadProjectConfig:xr,saveProjectConfig:ro}});var Hr=c((ha,qr)=>{var{execSync:no}=require("node:child_process"),so=require("node:crypto"),{loadProjectConfig:Or}=Lt(),{getGitRoot:Ze}=Nt();function yr(e){return so.createHash("sha256").update(e).digest("hex").slice(0,16)}function Vt(e){try{let r=no("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 oo(e){let t=Or(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Ze(e)||e;return`claudecode_project_${yr(n)}`}function ao(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function io(e){let t=Or(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Ze(e)||e,o=Vt(n)||n.split("/").pop()||"unknown";return`repo_${ao(o)}`}function fo(e){let r=Ze(e)||e;return Vt(r)||r.split("/").pop()||"unknown"}qr.exports={sha256:yr,getGitRoot:Ze,getGitRepoName:Vt,getContainerTag:oo,getRepoContainerTag:io,getProjectName:fo}});var hr=c((Wa,co)=>{co.exports=` Connected - Supermemory