From 73fdce09e46afb1a9e82da19159a99ac38b792fa Mon Sep 17 00:00:00 2001 From: ved015 Date: Sat, 16 May 2026 18:10:53 +0530 Subject: [PATCH 1/6] add auto container tags feature to claude supermemory --- README.md | 82 ++++++++++++++++++++++---- plugin/scripts/add-memory.cjs | 13 ++-- plugin/scripts/context-hook.cjs | 61 +++++++++++-------- plugin/scripts/save-project-memory.cjs | 13 ++-- plugin/scripts/search-memory.cjs | 41 ++++++------- plugin/scripts/summary-hook.cjs | 31 +++++----- plugin/skills/super-save/SKILL.md | 14 ++++- plugin/skills/super-search/SKILL.md | 6 ++ src/add-memory.js | 41 ++++++++++--- src/context-hook.js | 42 +++++++++---- src/lib/settings.js | 72 ++++++++++++++++++++++ src/save-project-memory.js | 41 ++++++++++--- src/search-memory.js | 40 ++++++++++--- src/summary-hook.js | 13 +++- 14 files changed, 388 insertions(+), 122 deletions(-) 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/plugin/scripts/add-memory.cjs b/plugin/scripts/add-memory.cjs index 9815735..309576c 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 Dr=Object.getOwnPropertyDescriptor;var Ur=Object.getOwnPropertyNames;var Yr=Object.prototype.hasOwnProperty;var Sr=(e,t)=>()=>(e&&(t=e(e=0)),t);var l=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Gr=(e,t)=>{for(var r in t)Ue(e,r,{get:t[r],enumerable:!0})},Kr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ur(t))!Yr.call(e,s)&&s!==r&&Ue(e,s,{get:()=>t[s],enumerable:!(n=Dr(t,s))||n.enumerable});return e};var kr=e=>Kr(Ue({},"__esModule",{value:!0}),e);var Ge=l(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.__setModuleDefault=h.__createBinding=void 0;h.__classPrivateFieldSet=Er;h.__classPrivateFieldGet=Cr;h.__importStar=Ir;h.__exportStar=Jr;function Er(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 Cr(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 Ir(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 Br=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=Br});var Ke=l(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.castToError=void 0;S.isAbortError=Ar;function Ar(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}var Qr=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=Qr});var K=l(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 _r=Ke(),ae=class extends Error{};P.SupermemoryError=ae;var O=class e extends ae{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,_r.castToError)(r)});let o=r;return t===400?new ie(t,o,n,s):t===401?new fe(t,o,n,s):t===403?new ce(t,o,n,s):t===404?new ue(t,o,n,s):t===409?new de(t,o,n,s):t===422?new ve(t,o,n,s):t===429?new le(t,o,n,s):t>=500?new pe(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 ie=class extends O{};P.BadRequestError=ie;var fe=class extends O{};P.AuthenticationError=fe;var ce=class extends O{};P.PermissionDeniedError=ce;var ue=class extends O{};P.NotFoundError=ue;var de=class extends O{};P.ConflictError=de;var ve=class extends O{};P.UnprocessableEntityError=ve;var le=class extends O{};P.RateLimitError=le;var pe=class extends O{};P.InternalServerError=pe});var E=l(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.safeJSON=p.maybeCoerceBoolean=p.maybeCoerceFloat=p.maybeCoerceInteger=p.coerceBoolean=p.coerceFloat=p.coerceInteger=p.validatePositiveInteger=p.ensurePresent=p.isReadonlyArray=p.isArray=p.isAbsoluteURL=void 0;p.maybeObj=rn;p.isEmptyObj=nn;p.hasOwn=sn;p.isObj=on;var k=K(),$r=/^[a-z][a-z0-9+.-]*:/i,en=e=>$r.test(e);p.isAbsoluteURL=en;var tn=e=>(p.isArray=Array.isArray,(0,p.isArray)(e));p.isArray=tn;p.isReadonlyArray=p.isArray;function rn(e){return typeof e!="object"?{}:e??{}}function nn(e){if(!e)return!0;for(let t in e)return!1;return!0}function sn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function on(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}var an=e=>{if(e==null)throw new k.SupermemoryError(`Expected a value to be given but received ${e} instead.`);return e};p.ensurePresent=an;var fn=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new k.SupermemoryError(`${e} must be an integer`);if(t<0)throw new k.SupermemoryError(`${e} must be a positive integer`);return t};p.validatePositiveInteger=fn;var cn=e=>{if(typeof e=="number")return Math.round(e);if(typeof e=="string")return parseInt(e,10);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};p.coerceInteger=cn;var un=e=>{if(typeof e=="number")return e;if(typeof e=="string")return parseFloat(e);throw new k.SupermemoryError(`Could not coerce ${e} (type: ${typeof e}) into a number`)};p.coerceFloat=un;var dn=e=>typeof e=="boolean"?e:typeof e=="string"?e==="true":!!e;p.coerceBoolean=dn;var vn=e=>{if(e!=null)return(0,p.coerceInteger)(e)};p.maybeCoerceInteger=vn;var ln=e=>{if(e!=null)return(0,p.coerceFloat)(e)};p.maybeCoerceFloat=ln;var pn=e=>{if(e!=null)return(0,p.coerceBoolean)(e)};p.maybeCoerceBoolean=pn;var Pn=e=>{try{return JSON.parse(e)}catch{return}};p.safeJSON=Pn});var Yt=l(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.sleep=void 0;var zn=e=>new Promise(t=>setTimeout(t,e));Pe.sleep=zn});var Ce=l(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.VERSION=void 0;ze.VERSION="4.0.0"});var kt=l(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.getPlatformHeaders=Z.isRunningInBrowser=void 0;var C=Ce(),mn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Z.isRunningInBrowser=mn;function bn(){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 jn=()=>{let e=bn();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=xn();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 xn(){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,Xn=()=>Kt??(Kt=jn());Z.getPlatformHeaders=Xn});var Ie=l(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.getDefaultFetch=On;V.makeReadableStream=Et;V.ReadableStreamFrom=yn;V.ReadableStreamToAsyncIterable=Hn;V.CancelReadableStream=qn;function On(){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 yn(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 Hn(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 qn(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=l(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.FallbackEncoder=void 0;var hn=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});me.FallbackEncoder=hn});var I=l(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=be;var Wn=Ie(),Tn=()=>{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=Tn;function Je(e,t,r){return(0,j.checkFileSupport)(),new File(e,t??"unknown_file",r)}function be(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 Nn=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";j.isAsyncIterable=Nn;var Ln=async(e,t)=>Be(e.body)?{...e,body:await(0,j.createForm)(e.body,t)}:e;j.maybeMultipartFormRequestOptions=Ln;var Vn=async(e,t)=>({...e,body:await(0,j.createForm)(e.body,t)});j.multipartFormRequestOptions=Vn;var It=new WeakMap;function Rn(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 gn=async(e,t)=>{if(!await Rn(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=gn;var Jt=e=>e instanceof Blob&&"name"in e,Zn=e=>typeof e=="object"&&e!==null&&(e instanceof Response||(0,j.isAsyncIterable)(e)||Jt(e)),Be=e=>{if(Zn(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()],be(r)));else if((0,j.isAsyncIterable)(r))e.append(t,Je([await new Response((0,Wn.ReadableStreamFrom)(r)).blob()],be(r)));else if(Jt(r))e.append(t,r,be(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=l(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.toFile=Dn;var J=I(),wn=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",Mn=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Bt(e),Fn=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Dn(e,t,r){if((0,wn.checkFileSupport)(),e=await e,Mn(e))return e instanceof File?e:(0,J.makeFile)([await e.arrayBuffer()],e.name);if(Fn(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}`:""}${Un(e)}`)}return t}function Un(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(r=>`"${r}"`).join(", ")}]`}});var $e=l(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.toFile=void 0;var Yn=At();Object.defineProperty(je,"toFile",{enumerable:!0,get:function(){return Yn.toFile}})});var w=l(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.APIResource=void 0;var et=class{constructor(t){this._client=t}};xe.APIResource=et});var B=l(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 Sn=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=Sn;var Gn=e=>{for(let t of $t(e))return!1;return!0};M.isEmptyHeaders=Gn});var Xe=l(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.path=N.createPathTagFunction=void 0;N.encodeURIPath=tt;var Kn=K();function tt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var er=Object.freeze(Object.create(null)),kn=(e=tt)=>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 f=n[X],q=(s?encodeURIComponent:e)(""+f);return X!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??er)??er)?.toString)&&(q=f+"",o.push({start:v.length+m.length,length:q.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),v+m+(X===n.length?"":q)},""),i=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=d.exec(i))!==null;)o.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(o.sort((v,m)=>v.start-m.start),o.length>0){let v=0,m=o.reduce((X,f)=>{let q=" ".repeat(f.start-v),D="^".repeat(f.length);return v=f.start+f.length,X+q+D},"");throw new Kn.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=kn;N.path=(0,N.createPathTagFunction)(tt)});var nt=l(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.Connections=void 0;var En=w(),Cn=B(),W=Xe(),rt=class extends En.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,Cn.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})}};Oe.Connections=rt});var at=l(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Documents=void 0;var In=w(),Jn=B(),Bn=I(),st=Xe(),ot=class extends In.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,Jn.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,Bn.multipartFormRequestOptions)({body:t,...r},this._client))}};ye.Documents=ot});var ct=l(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.Memories=void 0;var An=w(),Qn=B(),_n=I(),it=Xe(),ft=class extends An.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,Qn.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,_n.multipartFormRequestOptions)({body:t,...r},this._client))}};He.Memories=ft});var dt=l(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.Search=void 0;var $n=w(),ut=class extends $n.APIResource{documents(t,r){return this._client.post("/v3/search",{body:t,...r})}execute(t,r){return this._client.post("/v3/search",{body:t,...r})}memories(t,r){return this._client.post("/v4/search",{body:t,...r})}};qe.Search=ut});var lt=l(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.Settings=void 0;var es=w(),vt=class extends es.APIResource{update(t={},r){return this._client.patch("/v3/settings",{body:t,...r})}get(t){return this._client.get("/v3/settings",t)}};he.Settings=vt});var tr=l(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.Settings=H.Search=H.Memories=H.Documents=H.Connections=void 0;var ts=nt();Object.defineProperty(H,"Connections",{enumerable:!0,get:function(){return ts.Connections}});var rs=at();Object.defineProperty(H,"Documents",{enumerable:!0,get:function(){return rs.Documents}});var ns=ct();Object.defineProperty(H,"Memories",{enumerable:!0,get:function(){return ns.Memories}});var ss=dt();Object.defineProperty(H,"Search",{enumerable:!0,get:function(){return ss.Search}});var os=lt();Object.defineProperty(H,"Settings",{enumerable:!0,get:function(){return os.Settings}})});var pt=l(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.formatRequestDetails=R.parseLogLevel=void 0;R.loggerFor=nr;var as=E(),Te={off:0,error:200,warn:300,info:400,debug:500},is=(e,t,r)=>{if(e){if((0,as.hasOwn)(Te,e))return e;nr(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Te))}`)}};R.parseLogLevel=is;function A(){}function We(e,t,r){return!t||Te[e]>Te[r]?A:t[e].bind(t)}var fs={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 fs;let n=rr.get(t);if(n&&n[0]===r)return n[1];let s={error:We("error",t,r),warn:We("warn",t,r),info:We("info",t,r),debug:We("debug",t,r)};return rr.set(t,[r,s]),s}var cs=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=cs});var or=l(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.defaultParseResponse=us;var sr=pt();async function us(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 d=r.headers.get("content-type")?.split(";")[0]?.trim();return d?.includes("application/json")||d?.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=l(Ne=>{"use strict";var Q;Object.defineProperty(Ne,"__esModule",{value:!0});Ne.APIPromise=void 0;var zt=Ge(),ds=or(),mt=class e extends Promise{constructor(t,r,n=ds.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)}};Ne.APIPromise=mt;Q=new WeakMap});var ar=l(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.readEnv=void 0;var vs=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()};Le.readEnv=vs});var ht=l(Re=>{"use strict";var Ht,qt,Ve,ir;Object.defineProperty(Re,"__esModule",{value:!0});Re.Supermemory=void 0;var L=Ge(),ls=Ut(),jt=E(),ps=Yt(),xt=Ke(),Ps=kt(),Xt=L.__importStar(Ie()),zs=L.__importStar(Ct()),ms=Ce(),b=L.__importStar(K()),bs=L.__importStar($e()),_=L.__importStar(tr()),js=bt(),xs=nt(),Xs=at(),Os=ct(),ys=dt(),Hs=lt(),Ot=B(),yt=ar(),x=pt(),qs=E(),z=class{constructor({baseURL:t=(0,yt.readEnv)("SUPERMEMORY_BASE_URL"),apiKey:r=(0,yt.readEnv)("SUPERMEMORY_API_KEY"),...n}={}){if(Ht.add(this),Ve.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??qt.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,Ve,zs.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 ${ms.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,ls.uuid4)()}`}makeStatusError(t,r,n,s){return b.APIError.generate(t,r,n,s)}buildURL(t,r,n){let s=!L.__classPrivateFieldGet(this,Ht,"m",ir).call(this)&&n||this.baseURL,o=(0,jt.isAbsoluteURL)(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return(0,qs.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 js.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:d}=await this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(a,{url:i,options:s});let c="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(`[${c}] 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,d,X).catch(xt.castToError),q=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(`[${c}] connection ${T?"timed out":"failed"} - ${U}`),(0,x.loggerFor)(this).debug(`[${c}] connection ${T?"timed out":"failed"} (${U})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:q-m,message:f.message})),this.retryRequest(s,r,n??c);throw(0,x.loggerFor)(this).info(`[${c}] connection ${T?"timed out":"failed"} - error; no more retries left`),(0,x.loggerFor)(this).debug(`[${c}] connection ${T?"timed out":"failed"} (error; no more retries left)`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:i,durationMs:q-m,message:f.message})),T?new b.APIConnectionTimeoutError:new b.APIConnectionError({cause:f})}let D=`[${c}${v}] ${a.method} ${i} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${q-m}ms`;if(!f.ok){let U=await this.shouldRetry(f);if(r&&U){let oe=`retrying, ${r} attempts remaining`;return await Xt.CancelReadableStream(f.body),(0,x.loggerFor)(this).info(`${D} - ${oe}`),(0,x.loggerFor)(this).debug(`[${c}] response error (${oe})`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:q-m})),this.retryRequest(s,r,n??c,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(oe=>(0,xt.castToError)(oe).message),Mt=(0,jt.safeJSON)(wt),Ft=Mt?void 0:wt;throw(0,x.loggerFor)(this).debug(`[${c}] 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(`[${c}] response start`,(0,x.formatRequestDetails)({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:q-m})),{response:f,options:s,controller:X,requestLogID:c,retryOfRequestLogID:n,startTime:m}}async fetchWithTimeout(t,r,n,s){let{signal:o,method:a,...i}=r||{};o&&o.addEventListener("abort",()=>s.abort());let d=setTimeout(()=>s.abort(),n),c=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,v={signal:s.signal,...c?{duplex:"half"}:{},method:"GET",...i};a&&(v.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,v)}finally{clearTimeout(d)}}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 d=parseFloat(a);Number.isNaN(d)||(o=d)}let i=s?.get("retry-after");if(i&&!o){let d=parseFloat(i);Number.isNaN(d)?o=Date.parse(i)-Date.now():o=d*1e3}if(!(o&&0<=o&&o<60*1e3)){let d=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,d)}return await(0,ps.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,d=this.buildURL(o,a,i);"timeout"in n&&(0,jt.validatePositiveInteger)("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:v}=this.buildBody({options:n}),m=await this.buildHeaders({options:t,method:s,bodyHeaders:c,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:d,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,Ps.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,Ve,"f").call(this,{body:t,headers:n})}};Re.Supermemory=z;qt=z,Ve=new WeakMap,Ht=new WeakSet,ir=function(){return this.baseURL!=="https://api.supermemory.ai"};z.Supermemory=qt;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=bs.toFile;z.Memories=Os.Memories;z.Documents=Xs.Documents;z.Search=ys.Search;z.Settings=Hs.Settings;z.Connections=xs.Connections});var cr=l((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 hs=ht();Object.defineProperty(u,"default",{enumerable:!0,get:function(){return hs.Supermemory}});var Ws=$e();Object.defineProperty(u,"toFile",{enumerable:!0,get:function(){return Ws.toFile}});var Ts=bt();Object.defineProperty(u,"APIPromise",{enumerable:!0,get:function(){return Ts.APIPromise}});var Ns=ht();Object.defineProperty(u,"Supermemory",{enumerable:!0,get:function(){return Ns.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={};Gr(dr,{getRequestIntegrity:()=>Gs,sanitizeContent:()=>gs,sanitizeMetadata:()=>Ds,validateApiKeyFormat:()=>Ls,validateContainerTag:()=>Vs,validateContentLength:()=>Zs,validateRecallConfig:()=>Us});function Ls(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 Vs(e){return!e||typeof e!="string"?{valid:!1,reason:"tag is empty"}:e.length>100?{valid:!1,reason:"tag exceeds 100 characters"}:/^[a-zA-Z0-9_-]+$/.test(e)?/^[-_]|[-_]$/.test(e)?{valid:!1,reason:"tag must not start or end with - or _"}:{valid:!0}:{valid:!1,reason:"tag contains invalid characters (only alphanumeric, underscore, hyphen allowed)"}}function gs(e,t=1e5){if(!e||typeof e!="string")return"";let r=e;for(let n of Rs)r=r.replace(n,"");return r.length>t&&(r=r.slice(0,t)),r}function Zs(e,t=1,r=1e5){return e.lengthr?{valid:!1,reason:`content exceeds maximum length (${r})`}:{valid:!0}}function Ds(e){let t={},r=0;for(let[n,s]of Object.entries(e)){if(r>=ws)break;n.length>Ms||/[^\w.-]/.test(n)||(typeof s=="string"?(t[n]=s.slice(0,Fs),r++):(typeof s=="number"&&Number.isFinite(s)||typeof s=="boolean")&&(t[n]=s,r++))}return t}function Us(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,ge.createHash)("sha256").update(e).digest("hex")}function Ss(e,t){let r=[Wt(e),Wt(t),ur].join(":");return(0,ge.createHmac)("sha256",Ys).update(r).digest("base64url")}function Gs(e,t){let r=Wt(t),n=Ss(e,t);return{"X-Content-Hash":r,"X-Request-Integrity":[`v${ur}`,n].join(".")}}var ge,Rs,ws,Ms,Fs,ur,Ys,vr=Sr(()=>{ge=require("node:crypto");Rs=[/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,/\uFEFF/g,/[\uFFF0-\uFFFF]/g];ws=50,Ms=128,Fs=1024;ur=1,Ys="7f2a9c4b8e1d6f3a5c0b9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b2c1d0e9f8a"});var pr=l((ba,lr)=>{var Ks=cr().default,{getRequestIntegrity:ks,validateApiKeyFormat:Es,validateContainerTag:Cs}=(vr(),kr(dr)),Is="claudecode_default",Js=process.env.SUPERMEMORY_API_URL||"https://api.supermemory.ai";function Bs(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 As=`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`,Qs=`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=Es(t);if(!n.valid)throw new Error(`Invalid API key: ${n.reason}`);let s=r||Is,o=Cs(s);o.valid||console.warn(`Container tag warning: ${o.reason}`);let a=ks(t,s);this.client=new Ks({apiKey:t,baseURL:Js,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:Bs(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=(c,v=m=>m)=>c.filter(m=>{let X=String(v(m)).toLowerCase().trim();return!X||s.has(X)?!1:(s.add(X),!0)}),a=o(n.profile?.static||[]),i=o(n.profile?.dynamic||[]),d;if(n.searchResults){let c=n.searchResults.results.map(v=>({id:v.id,memory:v.content||v.context||"",similarity:v.similarity,title:v.title,updatedAt:v.updatedAt}));d={results:o(c,v=>v.memory),total:n.searchResults.total,timing:n.searchResults.timing}}return{profile:{static:a,dynamic:i},searchResults:d}}};lr.exports={SupermemoryClient:Tt,PERSONAL_ENTITY_CONTEXT:As,REPO_ENTITY_CONTEXT:Qs}});var Nt=l((ja,Pr)=>{var{execSync:Ze}=require("node:child_process"),$=require("node:path");function _s(e){let t=process.env.SUPERMEMORY_ISOLATE_WORKTREES==="true";try{if(t)return Ze("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null;let r=Ze("git rev-parse --git-common-dir",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(r===".git")return Ze("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):Ze("git rev-parse --show-toplevel",{cwd:e,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}Pr.exports={getGitRoot:_s}});var Lt=l((xa,Xr)=>{var ee=require("node:fs"),we=require("node:path"),{getGitRoot:zr}=Nt(),mr=we.join(".claude",".supermemory-claude"),br="config.json";function jr(e){let r=zr(e)||e;return we.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 $s(e,t){let n=zr(e)||e,s=we.join(n,mr),o=we.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:$s}});var qr=l((Xa,Hr)=>{var{execSync:eo}=require("node:child_process"),to=require("node:crypto"),{loadProjectConfig:Or}=Lt(),{getGitRoot:Me}=Nt();function yr(e){return to.createHash("sha256").update(e).digest("hex").slice(0,16)}function Vt(e){try{let r=eo("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 ro(e){let t=Or(e);if(t?.personalContainerTag)return t.personalContainerTag;let n=Me(e)||e;return`claudecode_project_${yr(n)}`}function no(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}function so(e){let t=Or(e);if(t?.repoContainerTag)return t.repoContainerTag;let n=Me(e)||e,o=Vt(n)||n.split("/").pop()||"unknown";return`repo_${no(o)}`}function oo(e){let r=Me(e)||e;return Vt(r)||r.split("/").pop()||"unknown"}Hr.exports={sha256:yr,getGitRoot:Me,getGitRepoName:Vt,getContainerTag:ro,getRepoContainerTag:so,getProjectName:oo}});var hr=l((Oa,ao)=>{ao.exports=` Connected - Supermemory