open-mem 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/LICENSE +21 -0
  3. package/README.md +309 -0
  4. package/dist/ai/compressor.d.ts +43 -0
  5. package/dist/ai/compressor.d.ts.map +1 -0
  6. package/dist/ai/parser.d.ts +35 -0
  7. package/dist/ai/parser.d.ts.map +1 -0
  8. package/dist/ai/prompts.d.ts +15 -0
  9. package/dist/ai/prompts.d.ts.map +1 -0
  10. package/dist/ai/summarizer.d.ts +30 -0
  11. package/dist/ai/summarizer.d.ts.map +1 -0
  12. package/dist/config.d.ts +16 -0
  13. package/dist/config.d.ts.map +1 -0
  14. package/dist/context/builder.d.ts +11 -0
  15. package/dist/context/builder.d.ts.map +1 -0
  16. package/dist/context/progressive.d.ts +13 -0
  17. package/dist/context/progressive.d.ts.map +1 -0
  18. package/dist/db/database.d.ts +45 -0
  19. package/dist/db/database.d.ts.map +1 -0
  20. package/dist/db/observations.d.ts +17 -0
  21. package/dist/db/observations.d.ts.map +1 -0
  22. package/dist/db/pending.d.ts +20 -0
  23. package/dist/db/pending.d.ts.map +1 -0
  24. package/dist/db/schema.d.ts +13 -0
  25. package/dist/db/schema.d.ts.map +1 -0
  26. package/dist/db/sessions.d.ts +17 -0
  27. package/dist/db/sessions.d.ts.map +1 -0
  28. package/dist/db/summaries.d.ts +12 -0
  29. package/dist/db/summaries.d.ts.map +1 -0
  30. package/dist/hooks/compaction.d.ts +19 -0
  31. package/dist/hooks/compaction.d.ts.map +1 -0
  32. package/dist/hooks/context-inject.d.ts +19 -0
  33. package/dist/hooks/context-inject.d.ts.map +1 -0
  34. package/dist/hooks/session-events.d.ts +18 -0
  35. package/dist/hooks/session-events.d.ts.map +1 -0
  36. package/dist/hooks/tool-capture.d.ts +25 -0
  37. package/dist/hooks/tool-capture.d.ts.map +1 -0
  38. package/dist/index.d.ts +5 -0
  39. package/dist/index.d.ts.map +1 -0
  40. package/dist/index.js +361 -0
  41. package/dist/queue/processor.d.ts +52 -0
  42. package/dist/queue/processor.d.ts.map +1 -0
  43. package/dist/tools/recall.d.ts +4 -0
  44. package/dist/tools/recall.d.ts.map +1 -0
  45. package/dist/tools/save.d.ts +5 -0
  46. package/dist/tools/save.d.ts.map +1 -0
  47. package/dist/tools/search.d.ts +5 -0
  48. package/dist/tools/search.d.ts.map +1 -0
  49. package/dist/tools/timeline.d.ts +6 -0
  50. package/dist/tools/timeline.d.ts.map +1 -0
  51. package/dist/types.d.ts +177 -0
  52. package/dist/types.d.ts.map +1 -0
  53. package/package.json +60 -0
package/dist/index.js ADDED
@@ -0,0 +1,361 @@
1
+ // @bun
2
+ var nW=Object.create;var{getPrototypeOf:aW,defineProperty:z8,getOwnPropertyNames:oW}=Object;var rW=Object.prototype.hasOwnProperty;var tW=($,W,X)=>{X=$!=null?nW(aW($)):{};let G=W||!$||!$.__esModule?z8(X,"default",{value:$,enumerable:!0}):X;for(let J of oW($))if(!rW.call(G,J))z8(G,J,{get:()=>$[J],enumerable:!0});return G};var sW=($,W)=>{for(var X in W)z8($,X,{get:W[X],enumerable:!0,configurable:!0,set:(G)=>W[X]=()=>G})};var eW=import.meta.require;var U$="0.39.0";var h8=!1,N$=void 0,H8=void 0,$X=void 0,WX=void 0,XX=void 0,m8=void 0,GX=void 0,R0=void 0,V8=void 0,l8=void 0,q8=void 0,A0=void 0,c8=void 0;function u8($,W={auto:!1}){if(h8)throw Error(`you must \`import '@anthropic-ai/sdk/shims/${$.kind}'\` before importing anything else from @anthropic-ai/sdk`);if(N$)throw Error(`can't \`import '@anthropic-ai/sdk/shims/${$.kind}'\` after \`import '@anthropic-ai/sdk/shims/${N$}'\``);h8=W.auto,N$=$.kind,H8=$.fetch,$X=$.Request,WX=$.Response,XX=$.Headers,m8=$.FormData,GX=$.Blob,R0=$.File,V8=$.ReadableStream,l8=$.getMultipartRequestOptions,q8=$.getDefaultAgent,A0=$.fileFromPath,c8=$.isFsReadStream}class _8{constructor($){this.body=$}get[Symbol.toStringTag](){return"MultipartBody"}}function p8({manuallyImported:$}={}){let W=$?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from '@anthropic-ai/sdk'`:\n- `import '@anthropic-ai/sdk/shims/node'` (if you're running on Node)\n- `import '@anthropic-ai/sdk/shims/web'` (otherwise)\n",X,G,J,Y;try{X=fetch,G=Request,J=Response,Y=Headers}catch(Q){throw Error(`this environment is missing the following Web Fetch API type: ${Q.message}. ${W}`)}return{kind:"web",fetch:X,Request:G,Response:J,Headers:Y,FormData:typeof FormData<"u"?FormData:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${W}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${W}`)}},File:typeof File<"u"?File:class{constructor(){throw Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${W}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${W}`)}},getMultipartRequestOptions:async(Q,z)=>({...z,body:new _8(Q)}),getDefaultAgent:(Q)=>{return},fileFromPath:()=>{throw Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/anthropics/anthropic-sdk-typescript#file-uploads")},isFsReadStream:(Q)=>!1}}import{ReadStream as YX}from"fs";function d8(){let $=p8();function W(X){return X instanceof YX}return{...$,isFsReadStream:W}}if(!N$)u8(d8(),{auto:!0});class K extends Error{}class C extends K{constructor($,W,X,G){super(`${C.makeMessage($,W,X)}`);this.status=$,this.headers=G,this.request_id=G?.["request-id"],this.error=W}static makeMessage($,W,X){let G=W?.message?typeof W.message==="string"?W.message:JSON.stringify(W.message):W?JSON.stringify(W):X;if($&&G)return`${$} ${G}`;if($)return`${$} status code (no body)`;if(G)return G;return"(no status code or body)"}static generate($,W,X,G){if(!$||!G)return new K$({message:X,cause:Z0(W)});let J=W;if($===400)return new C0($,J,X,G);if($===401)return new f0($,J,X,G);if($===403)return new T0($,J,X,G);if($===404)return new P0($,J,X,G);if($===409)return new k0($,J,X,G);if($===422)return new I0($,J,X,G);if($===429)return new b0($,J,X,G);if($>=500)return new x0($,J,X,G);return new C($,J,X,G)}}class k extends C{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class K$ extends C{constructor({message:$,cause:W}){super(void 0,void 0,$||"Connection error.",void 0);if(W)this.cause=W}}class t$ extends K${constructor({message:$}={}){super({message:$??"Request timed out."})}}class C0 extends C{}class f0 extends C{}class T0 extends C{}class P0 extends C{}class k0 extends C{}class I0 extends C{}class b0 extends C{}class x0 extends C{}var v0=function($,W,X,G,J){if(G==="m")throw TypeError("Private method is not writable");if(G==="a"&&!J)throw TypeError("Private accessor was defined without a setter");if(typeof W==="function"?$!==W||!J:!W.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return G==="a"?J.call($,X):J?J.value=X:W.set($,X),X},O$=function($,W,X,G){if(X==="a"&&!G)throw TypeError("Private accessor was defined without a getter");if(typeof W==="function"?$!==W||!G:!W.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?G:X==="a"?G.call($):G?G.value:W.get($)},v;class J${constructor(){v.set(this,void 0),this.buffer=new Uint8Array,v0(this,v,null,"f")}decode($){if($==null)return[];let W=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,X=new Uint8Array(this.buffer.length+W.length);X.set(this.buffer),X.set(W,this.buffer.length),this.buffer=X;let G=[],J;while((J=zX(this.buffer,O$(this,v,"f")))!=null){if(J.carriage&&O$(this,v,"f")==null){v0(this,v,J.index,"f");continue}if(O$(this,v,"f")!=null&&(J.index!==O$(this,v,"f")+1||J.carriage)){G.push(this.decodeText(this.buffer.slice(0,O$(this,v,"f")-1))),this.buffer=this.buffer.slice(O$(this,v,"f")),v0(this,v,null,"f");continue}let Y=O$(this,v,"f")!==null?J.preceding-1:J.preceding,Q=this.decodeText(this.buffer.slice(0,Y));G.push(Q),this.buffer=this.buffer.slice(J.index),v0(this,v,null,"f")}return G}decodeText($){if($==null)return"";if(typeof $==="string")return $;if(typeof Buffer<"u"){if($ instanceof Buffer)return $.toString();if($ instanceof Uint8Array)return Buffer.from($).toString();throw new K(`Unexpected: received non-Uint8Array (${$.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if($ instanceof Uint8Array||$ instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode($);throw new K(`Unexpected: received non-Uint8Array/ArrayBuffer (${$.constructor.name}) in a web platform. Please report this error.`)}throw new K("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length)return[];return this.decode(`
3
+ `)}}v=new WeakMap;J$.NEWLINE_CHARS=new Set([`
4
+ `,"\r"]);J$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zX($,W){for(let J=W??0;J<$.length;J++){if($[J]===10)return{preceding:J,index:J+1,carriage:!1};if($[J]===13)return{preceding:J,index:J+1,carriage:!0}}return null}function i8($){for(let G=0;G<$.length-1;G++){if($[G]===10&&$[G+1]===10)return G+2;if($[G]===13&&$[G+1]===13)return G+2;if($[G]===13&&$[G+1]===10&&G+3<$.length&&$[G+2]===13&&$[G+3]===10)return G+4}return-1}function s$($){if($[Symbol.asyncIterator])return $;let W=$.getReader();return{async next(){try{let X=await W.read();if(X?.done)W.releaseLock();return X}catch(X){throw W.releaseLock(),X}},async return(){let X=W.cancel();return W.releaseLock(),await X,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class g{constructor($,W){this.iterator=$,this.controller=W}static fromSSEResponse($,W){let X=!1;async function*G(){if(X)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let J=!1;try{for await(let Y of HX($,W)){if(Y.event==="completion")try{yield JSON.parse(Y.data)}catch(Q){throw console.error("Could not parse message into JSON:",Y.data),console.error("From chunk:",Y.raw),Q}if(Y.event==="message_start"||Y.event==="message_delta"||Y.event==="message_stop"||Y.event==="content_block_start"||Y.event==="content_block_delta"||Y.event==="content_block_stop")try{yield JSON.parse(Y.data)}catch(Q){throw console.error("Could not parse message into JSON:",Y.data),console.error("From chunk:",Y.raw),Q}if(Y.event==="ping")continue;if(Y.event==="error")throw C.generate(void 0,`SSE Error: ${Y.data}`,Y.data,B8($.headers))}J=!0}catch(Y){if(Y instanceof Error&&Y.name==="AbortError")return;throw Y}finally{if(!J)W.abort()}}return new g(G,W)}static fromReadableStream($,W){let X=!1;async function*G(){let Y=new J$,Q=s$($);for await(let z of Q)for(let H of Y.decode(z))yield H;for(let z of Y.flush())yield z}async function*J(){if(X)throw Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");X=!0;let Y=!1;try{for await(let Q of G()){if(Y)continue;if(Q)yield JSON.parse(Q)}Y=!0}catch(Q){if(Q instanceof Error&&Q.name==="AbortError")return;throw Q}finally{if(!Y)W.abort()}}return new g(J,W)}[Symbol.asyncIterator](){return this.iterator()}tee(){let $=[],W=[],X=this.iterator(),G=(J)=>{return{next:()=>{if(J.length===0){let Y=X.next();$.push(Y),W.push(Y)}return J.shift()}}};return[new g(()=>G($),this.controller),new g(()=>G(W),this.controller)]}toReadableStream(){let $=this,W,X=new TextEncoder;return new V8({async start(){W=$[Symbol.asyncIterator]()},async pull(G){try{let{value:J,done:Y}=await W.next();if(Y)return G.close();let Q=X.encode(JSON.stringify(J)+`
5
+ `);G.enqueue(Q)}catch(J){G.error(J)}},async cancel(){await W.return?.()}})}}async function*HX($,W){if(!$.body)throw W.abort(),new K("Attempted to iterate over a response with no body");let X=new n8,G=new J$,J=s$($.body);for await(let Y of VX(J))for(let Q of G.decode(Y)){let z=X.decode(Q);if(z)yield z}for(let Y of G.flush()){let Q=X.decode(Y);if(Q)yield Q}}async function*VX($){let W=new Uint8Array;for await(let X of $){if(X==null)continue;let G=X instanceof ArrayBuffer?new Uint8Array(X):typeof X==="string"?new TextEncoder().encode(X):X,J=new Uint8Array(W.length+G.length);J.set(W),J.set(G,W.length),W=J;let Y;while((Y=i8(W))!==-1)yield W.slice(0,Y),W=W.slice(Y)}if(W.length>0)yield W}class n8{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let J={event:this.event,data:this.data.join(`
6
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],J}if(this.chunks.push($),$.startsWith(":"))return null;let[W,X,G]=qX($,":");if(G.startsWith(" "))G=G.substring(1);if(W==="event")this.event=G;else if(W==="data")this.data.push(G);return null}}function qX($,W){let X=$.indexOf(W);if(X!==-1)return[$.substring(0,X),W,$.substring(X+W.length)];return[$,"",""]}var _X=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function",BX=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&e$($),e$=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function";async function a8($,W,X){if($=await $,BX($))return $;if(_X($)){let J=await $.blob();W||(W=new URL($.url).pathname.split(/[\\/]/).pop()??"unknown_file");let Y=e$(J)?[await J.arrayBuffer()]:[J];return new R0(Y,W,X)}let G=await MX($);if(W||(W=NX($)??"unknown_file"),!X?.type){let J=G[0]?.type;if(typeof J==="string")X={...X,type:J}}return new R0(G,W,X)}async function MX($){let W=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)W.push($);else if(e$($))W.push(await $.arrayBuffer());else if(KX($))for await(let X of $)W.push(X);else throw Error(`Unexpected data type: ${typeof $}; constructor: ${$?.constructor?.name}; props: ${UX($)}`);return W}function UX($){return`[${Object.getOwnPropertyNames($).map((X)=>`"${X}"`).join(", ")}]`}function NX($){return M8($.name)||M8($.filename)||M8($.path)?.split(/[\\/]/).pop()}var M8=($)=>{if(typeof $==="string")return $;if(typeof Buffer<"u"&&$ instanceof Buffer)return String($);return},KX=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function",U8=($)=>$&&typeof $==="object"&&$.body&&$[Symbol.toStringTag]==="MultipartBody";var wX=function($,W,X,G,J){if(G==="m")throw TypeError("Private method is not writable");if(G==="a"&&!J)throw TypeError("Private accessor was defined without a setter");if(typeof W==="function"?$!==W||!J:!W.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return G==="a"?J.call($,X):J?J.value=X:W.set($,X),X},DX=function($,W,X,G){if(X==="a"&&!G)throw TypeError("Private accessor was defined without a getter");if(typeof W==="function"?$!==W||!G:!W.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?G:X==="a"?G.call($):G?G.value:W.get($)},g0;async function e8($){let{response:W}=$;if($.options.stream){if(A$("response",W.status,W.url,W.headers,W.body),$.options.__streamClass)return $.options.__streamClass.fromSSEResponse(W,$.controller);return g.fromSSEResponse(W,$.controller)}if(W.status===204)return null;if($.options.__binaryResponse)return W;let X=W.headers.get("content-type");if(X?.includes("application/json")||X?.includes("application/vnd.api+json")){let Y=await W.json();return A$("response",W.status,W.url,W.headers,Y),$W(Y,W)}let J=await W.text();return A$("response",W.status,W.url,W.headers,J),J}function $W($,W){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:W.headers.get("request-id"),enumerable:!1})}class h0 extends Promise{constructor($,W=e8){super((X)=>{X(null)});this.responsePromise=$,this.parseResponse=W}_thenUnwrap($){return new h0(this.responsePromise,async(W)=>$W($(await this.parseResponse(W),W),W.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,W]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:W,request_id:W.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then($,W){return this.parse().then($,W)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}class K8{constructor({baseURL:$,maxRetries:W=2,timeout:X=600000,httpAgent:G,fetch:J}){this.baseURL=$,this.maxRetries=N8("maxRetries",W),this.timeout=N8("timeout",X),this.httpAgent=G,this.fetch=J??H8}authHeaders($){return{}}defaultHeaders($){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...SX(),...this.authHeaders($)}}validateHeaders($,W){}defaultIdempotencyKey(){return`stainless-node-retry-${fX()}`}get($,W){return this.methodRequest("get",$,W)}post($,W){return this.methodRequest("post",$,W)}patch($,W){return this.methodRequest("patch",$,W)}put($,W){return this.methodRequest("put",$,W)}delete($,W){return this.methodRequest("delete",$,W)}methodRequest($,W,X){return this.request(Promise.resolve(X).then(async(G)=>{let J=G&&e$(G?.body)?new DataView(await G.body.arrayBuffer()):G?.body instanceof DataView?G.body:G?.body instanceof ArrayBuffer?new DataView(G.body):G&&ArrayBuffer.isView(G?.body)?new DataView(G.body.buffer):G?.body;return{method:$,path:W,...G,body:J}}))}getAPIList($,W,X){return this.requestAPIList(W,{method:"get",path:$,...X})}calculateContentLength($){if(typeof $==="string"){if(typeof Buffer<"u")return Buffer.byteLength($,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode($).length.toString()}else if(ArrayBuffer.isView($))return $.byteLength.toString();return null}buildRequest($,{retryCount:W=0}={}){$={...$};let{method:X,path:G,query:J,headers:Y={}}=$,Q=ArrayBuffer.isView($.body)||$.__binaryRequest&&typeof $.body==="string"?$.body:U8($.body)?$.body.body:$.body?JSON.stringify($.body,null,2):null,z=this.calculateContentLength(Q),H=this.buildURL(G,J);if("timeout"in $)N8("timeout",$.timeout);$.timeout=$.timeout??this.timeout;let q=$.httpAgent??this.httpAgent??q8(H),O=$.timeout+1000;if(typeof q?.options?.timeout==="number"&&O>(q.options.timeout??0))q.options.timeout=O;if(this.idempotencyHeader&&X!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();Y[this.idempotencyHeader]=$.idempotencyKey}let R=this.buildHeaders({options:$,headers:Y,contentLength:z,retryCount:W});return{req:{method:X,...Q&&{body:Q},headers:R,...q&&{agent:q},signal:$.signal??null},url:H,timeout:$.timeout}}buildHeaders({options:$,headers:W,contentLength:X,retryCount:G}){let J={};if(X)J["content-length"]=X;let Y=this.defaultHeaders($);if(s8(J,Y),s8(J,W),U8($.body)&&N$!=="node")delete J["content-type"];if(y0(Y,"x-stainless-retry-count")===void 0&&y0(W,"x-stainless-retry-count")===void 0)J["x-stainless-retry-count"]=String(G);if(y0(Y,"x-stainless-timeout")===void 0&&y0(W,"x-stainless-timeout")===void 0&&$.timeout)J["x-stainless-timeout"]=String($.timeout);return this.validateHeaders(J,W),J}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new K("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-python#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:W,options:X}){}parseHeaders($){return!$?{}:(Symbol.iterator in $)?Object.fromEntries(Array.from($).map((W)=>[...W])):{...$}}makeStatusError($,W,X,G){return C.generate($,W,X,G)}request($,W=null){return new h0(this.makeRequest($,W))}async makeRequest($,W){let X=await $,G=X.maxRetries??this.maxRetries;if(W==null)W=G;await this.prepareOptions(X);let{req:J,url:Y,timeout:Q}=this.buildRequest(X,{retryCount:G-W});if(await this.prepareRequest(J,{url:Y,options:X}),A$("request",Y,X,J.headers),X.signal?.aborted)throw new k;let z=new AbortController,H=await this.fetchWithTimeout(Y,J,Q,z).catch(Z0);if(H instanceof Error){if(X.signal?.aborted)throw new k;if(W)return this.retryRequest(X,W);if(H.name==="AbortError")throw new t$;throw new K$({cause:H})}let q=B8(H.headers);if(!H.ok){if(W&&this.shouldRetry(H)){let Q8=`retrying, ${W} attempts remaining`;return A$(`response (error; ${Q8})`,H.status,Y,q),this.retryRequest(X,W,q)}let O=await H.text().catch((Q8)=>Z0(Q8).message),R=EX(O),l=R?void 0:O;throw A$(`response (error; ${W?"(error; no more retries left)":"(error; not retryable)"})`,H.status,Y,q,l),this.makeStatusError(H.status,R,l,q)}return{response:H,options:X,controller:z}}requestAPIList($,W){let X=this.makeRequest(W,null);return new WW(this,X,$)}buildURL($,W){let X=AX($)?new URL($):new URL(this.baseURL+(this.baseURL.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),G=this.defaultQuery();if(!$0(G))W={...G,...W};if(typeof W==="object"&&W&&!Array.isArray(W))X.search=this.stringifyQuery(W);return X.toString()}stringifyQuery($){return Object.entries($).filter(([W,X])=>typeof X<"u").map(([W,X])=>{if(typeof X==="string"||typeof X==="number"||typeof X==="boolean")return`${encodeURIComponent(W)}=${encodeURIComponent(X)}`;if(X===null)return`${encodeURIComponent(W)}=`;throw new K(`Cannot stringify type ${typeof X}; 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("&")}async fetchWithTimeout($,W,X,G){let{signal:J,...Y}=W||{};if(J)J.addEventListener("abort",()=>G.abort());let Q=setTimeout(()=>G.abort(),X),z={signal:G.signal,...Y};if(z.method)z.method=z.method.toUpperCase();let H=60000,q=setTimeout(()=>{if(z&&z?.agent?.sockets){for(let O of Object.values(z?.agent?.sockets).flat())if(O?.setKeepAlive)O.setKeepAlive(!0,H)}},H);return this.fetch.call(void 0,$,z).finally(()=>{clearTimeout(Q),clearTimeout(q)})}shouldRetry($){let W=$.headers.get("x-should-retry");if(W==="true")return!0;if(W==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,W,X){let G,J=X?.["retry-after-ms"];if(J){let Q=parseFloat(J);if(!Number.isNaN(Q))G=Q}let Y=X?.["retry-after"];if(Y&&!G){let Q=parseFloat(Y);if(!Number.isNaN(Q))G=Q*1000;else G=Date.parse(Y)-Date.now()}if(!(G&&0<=G&&G<60000)){let Q=$.maxRetries??this.maxRetries;G=this.calculateDefaultRetryTimeoutMillis(W,Q)}return await CX(G),this.makeRequest($,W-1)}calculateDefaultRetryTimeoutMillis($,W){let J=W-$,Y=Math.min(0.5*Math.pow(2,J),8),Q=1-Math.random()*0.25;return Y*Q*1000}getUserAgent(){return`${this.constructor.name}/JS ${U$}`}}class O8{constructor($,W,X,G){g0.set(this,void 0),wX(this,g0,$,"f"),this.options=G,this.response=W,this.body=X}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let $=this.nextPageInfo();if(!$)throw new K("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let W={...this.options};if("params"in $&&typeof W.query==="object")W.query={...W.query,...$.params};else if("url"in $){let X=[...Object.entries(W.query||{}),...$.url.searchParams.entries()];for(let[G,J]of X)$.url.searchParams.set(G,J);W.query=void 0,W.path=$.url.toString()}return await DX(this,g0,"f").requestAPIList(this.constructor,W)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(g0=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let W of $.getPaginatedItems())yield W}}class WW extends h0{constructor($,W,X){super(W,async(G)=>new X($,G.response,await e8(G),G.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let W of $)yield W}}var B8=($)=>{return new Proxy(Object.fromEntries($.entries()),{get(W,X){let G=X.toString();return W[G.toLowerCase()]||W[G]}})},LX={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},y=($)=>{return typeof $==="object"&&$!==null&&!$0($)&&Object.keys($).every((W)=>XW(LX,W))},FX=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U$,"X-Stainless-OS":r8(Deno.build.os),"X-Stainless-Arch":o8(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":U$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U$,"X-Stainless-OS":r8(process.platform),"X-Stainless-Arch":o8(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let $=jX();if($)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${$.browser}`,"X-Stainless-Runtime-Version":$.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":U$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function jX(){if(typeof navigator>"u"||!navigator)return null;let $=[{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:W,pattern:X}of $){let G=X.exec(navigator.userAgent);if(G){let J=G[1]||0,Y=G[2]||0,Q=G[3]||0;return{browser:W,version:`${J}.${Y}.${Q}`}}}return null}var o8=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},r8=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},t8,SX=()=>{return t8??(t8=FX())},EX=($)=>{try{return JSON.parse($)}catch(W){return}},RX=/^[a-z][a-z0-9+.-]*:/i,AX=($)=>{return RX.test($)},CX=($)=>new Promise((W)=>setTimeout(W,$)),N8=($,W)=>{if(typeof W!=="number"||!Number.isInteger(W))throw new K(`${$} must be an integer`);if(W<0)throw new K(`${$} must be a positive integer`);return W},Z0=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null)try{return Error(JSON.stringify($))}catch{}return Error(String($))};var m0=($)=>{if(typeof process<"u")return process.env?.[$]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.($)?.trim();return};function $0($){if(!$)return!0;for(let W in $)return!1;return!0}function XW($,W){return Object.prototype.hasOwnProperty.call($,W)}function s8($,W){for(let X in W){if(!XW(W,X))continue;let G=X.toLowerCase();if(!G)continue;let J=W[X];if(J===null)delete $[G];else if(J!==void 0)$[G]=J}}function A$($,...W){if(typeof process<"u"&&process?.env?.DEBUG==="true")console.log(`Anthropic:DEBUG:${$}`,...W)}var fX=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,($)=>{let W=Math.random()*16|0;return($==="x"?W:W&3|8).toString(16)})},GW=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"},TX=($)=>{return typeof $?.get==="function"};var y0=($,W)=>{let X=W.toLowerCase();if(TX($)){let G=W[0]?.toUpperCase()+W.substring(1).replace(/([^\w])(\w)/g,(J,Y,Q)=>Y+Q.toUpperCase());for(let J of[W,X,W.toUpperCase(),G]){let Y=$.get(J);if(Y)return Y}}for(let[G,J]of Object.entries($))if(G.toLowerCase()===X){if(Array.isArray(J)){if(J.length<=1)return J[0];return console.warn(`Received ${J.length} entries for the ${W} header, using the first entry.`),J[0]}return J}return};class t extends O8{constructor($,W,X,G){super($,W,X,G);this.data=X.data||[],this.has_more=X.has_more||!1,this.first_id=X.first_id||null,this.last_id=X.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageParams(){let $=this.nextPageInfo();if(!$)return null;if("params"in $)return $.params;let W=Object.fromEntries($.url.searchParams);if(!Object.keys(W).length)return null;return W}nextPageInfo(){if(this.options.query?.before_id){let W=this.first_id;if(!W)return null;return{params:{before_id:W}}}let $=this.last_id;if(!$)return null;return{params:{after_id:$}}}}class T{constructor($){this._client=$}}class C$ extends T{retrieve($,W){return this._client.get(`/v1/models/${$}?beta=true`,W)}list($={},W){if(y($))return this.list({},$);return this._client.getAPIList("/v1/models?beta=true",W0,{query:$,...W})}}class W0 extends t{}C$.BetaModelInfosPage=W0;class f${constructor($,W){this.iterator=$,this.controller=W}async*decoder(){let $=new J$;for await(let W of this.iterator)for(let X of $.decode(W))yield JSON.parse(X);for(let W of $.flush())yield JSON.parse(W)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,W){if(!$.body)throw W.abort(),new K("Attempted to iterate over a response with no body");return new f$(s$($.body),W)}}class T$ extends T{create($,W){let{betas:X,...G}=$;return this._client.post("/v1/messages/batches?beta=true",{body:G,...W,headers:{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),...W?.headers}})}retrieve($,W={},X){if(y(W))return this.retrieve($,{},W);let{betas:G}=W;return this._client.get(`/v1/messages/batches/${$}?beta=true`,{...X,headers:{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString(),...X?.headers}})}list($={},W){if(y($))return this.list({},$);let{betas:X,...G}=$;return this._client.getAPIList("/v1/messages/batches?beta=true",X0,{query:G,...W,headers:{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),...W?.headers}})}delete($,W={},X){if(y(W))return this.delete($,{},W);let{betas:G}=W;return this._client.delete(`/v1/messages/batches/${$}?beta=true`,{...X,headers:{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString(),...X?.headers}})}cancel($,W={},X){if(y(W))return this.cancel($,{},W);let{betas:G}=W;return this._client.post(`/v1/messages/batches/${$}/cancel?beta=true`,{...X,headers:{"anthropic-beta":[...G??[],"message-batches-2024-09-24"].toString(),...X?.headers}})}async results($,W={},X){if(y(W))return this.results($,{},W);let G=await this.retrieve($);if(!G.results_url)throw new K(`No batch \`results_url\`; Has it finished processing? ${G.processing_status} - ${G.id}`);let{betas:J}=W;return this._client.get(G.results_url,{...X,headers:{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary",...X?.headers},__binaryResponse:!0})._thenUnwrap((Y,Q)=>f$.fromResponse(Q.response,Q.controller))}}class X0 extends t{}T$.BetaMessageBatchesPage=X0;var bX=($)=>{let W=0,X=[];while(W<$.length){let G=$[W];if(G==="\\"){W++;continue}if(G==="{"){X.push({type:"brace",value:"{"}),W++;continue}if(G==="}"){X.push({type:"brace",value:"}"}),W++;continue}if(G==="["){X.push({type:"paren",value:"["}),W++;continue}if(G==="]"){X.push({type:"paren",value:"]"}),W++;continue}if(G===":"){X.push({type:"separator",value:":"}),W++;continue}if(G===","){X.push({type:"delimiter",value:","}),W++;continue}if(G==='"'){let z="",H=!1;G=$[++W];while(G!=='"'){if(W===$.length){H=!0;break}if(G==="\\"){if(W++,W===$.length){H=!0;break}z+=G+$[W],G=$[++W]}else z+=G,G=$[++W]}if(G=$[++W],!H)X.push({type:"string",value:z});continue}if(G&&/\s/.test(G)){W++;continue}let Y=/[0-9]/;if(G&&Y.test(G)||G==="-"||G==="."){let z="";if(G==="-")z+=G,G=$[++W];while(G&&Y.test(G)||G===".")z+=G,G=$[++W];X.push({type:"number",value:z});continue}let Q=/[a-z]/i;if(G&&Q.test(G)){let z="";while(G&&Q.test(G)){if(W===$.length)break;z+=G,G=$[++W]}if(z=="true"||z=="false"||z==="null")X.push({type:"name",value:z});else{W++;continue}continue}W++}return X},P$=($)=>{if($.length===0)return $;let W=$[$.length-1];switch(W.type){case"separator":return $=$.slice(0,$.length-1),P$($);break;case"number":let X=W.value[W.value.length-1];if(X==="."||X==="-")return $=$.slice(0,$.length-1),P$($);case"string":let G=$[$.length-2];if(G?.type==="delimiter")return $=$.slice(0,$.length-1),P$($);else if(G?.type==="brace"&&G.value==="{")return $=$.slice(0,$.length-1),P$($);break;case"delimiter":return $=$.slice(0,$.length-1),P$($);break}return $},xX=($)=>{let W=[];if($.map((X)=>{if(X.type==="brace")if(X.value==="{")W.push("}");else W.splice(W.lastIndexOf("}"),1);if(X.type==="paren")if(X.value==="[")W.push("]");else W.splice(W.lastIndexOf("]"),1)}),W.length>0)W.reverse().map((X)=>{if(X==="}")$.push({type:"brace",value:"}"});else if(X==="]")$.push({type:"paren",value:"]"})});return $},ZX=($)=>{let W="";return $.map((X)=>{switch(X.type){case"string":W+='"'+X.value+'"';break;default:W+=X.value;break}}),W},l0=($)=>JSON.parse(ZX(xX(P$(bX($)))));var I=function($,W,X,G,J){if(G==="m")throw TypeError("Private method is not writable");if(G==="a"&&!J)throw TypeError("Private accessor was defined without a setter");if(typeof W==="function"?$!==W||!J:!W.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return G==="a"?J.call($,X):J?J.value=X:W.set($,X),X},D=function($,W,X,G){if(X==="a"&&!G)throw TypeError("Private accessor was defined without a getter");if(typeof W==="function"?$!==W||!G:!W.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?G:X==="a"?G.call($):G?G.value:W.get($)},h,Y$,G0,c0,J0,Y0,u0,Q0,s,z0,p0,d0,k$,i0,n0,w8,JW,D8,L8,F8,j8,YW,QW="__json_buf";class H0{constructor(){h.add(this),this.messages=[],this.receivedMessages=[],Y$.set(this,void 0),this.controller=new AbortController,G0.set(this,void 0),c0.set(this,()=>{}),J0.set(this,()=>{}),Y0.set(this,void 0),u0.set(this,()=>{}),Q0.set(this,()=>{}),s.set(this,{}),z0.set(this,!1),p0.set(this,!1),d0.set(this,!1),k$.set(this,!1),i0.set(this,void 0),n0.set(this,void 0),D8.set(this,($)=>{if(I(this,p0,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new k;if($ instanceof k)return I(this,d0,!0,"f"),this._emit("abort",$);if($ instanceof K)return this._emit("error",$);if($ instanceof Error){let W=new K($.message);return W.cause=$,this._emit("error",W)}return this._emit("error",new K(String($)))}),I(this,G0,new Promise(($,W)=>{I(this,c0,$,"f"),I(this,J0,W,"f")}),"f"),I(this,Y0,new Promise(($,W)=>{I(this,u0,$,"f"),I(this,Q0,W,"f")}),"f"),D(this,G0,"f").catch(()=>{}),D(this,Y0,"f").catch(()=>{})}get response(){return D(this,i0,"f")}get request_id(){return D(this,n0,"f")}async withResponse(){let $=await D(this,G0,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let W=new H0;return W._run(()=>W._fromReadableStream($)),W}static createMessage($,W,X){let G=new H0;for(let J of W.messages)G._addMessageParam(J);return G._run(()=>G._createMessage($,{...W,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),G}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},D(this,D8,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,W=!0){if(this.receivedMessages.push($),W)this._emit("message",$)}async _createMessage($,W,X){let G=X?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}D(this,h,"m",L8).call(this);let{response:J,data:Y}=await $.create({...W,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(J);for await(let Q of Y)D(this,h,"m",F8).call(this,Q);if(Y.controller.signal?.aborted)throw new k;D(this,h,"m",j8).call(this)}_connected($){if(this.ended)return;I(this,i0,$,"f"),I(this,n0,$?.headers.get("request-id"),"f"),D(this,c0,"f").call(this,$),this._emit("connect")}get ended(){return D(this,z0,"f")}get errored(){return D(this,p0,"f")}get aborted(){return D(this,d0,"f")}abort(){this.controller.abort()}on($,W){return(D(this,s,"f")[$]||(D(this,s,"f")[$]=[])).push({listener:W}),this}off($,W){let X=D(this,s,"f")[$];if(!X)return this;let G=X.findIndex((J)=>J.listener===W);if(G>=0)X.splice(G,1);return this}once($,W){return(D(this,s,"f")[$]||(D(this,s,"f")[$]=[])).push({listener:W,once:!0}),this}emitted($){return new Promise((W,X)=>{if(I(this,k$,!0,"f"),$!=="error")this.once("error",X);this.once($,W)})}async done(){I(this,k$,!0,"f"),await D(this,Y0,"f")}get currentMessage(){return D(this,Y$,"f")}async finalMessage(){return await this.done(),D(this,h,"m",w8).call(this)}async finalText(){return await this.done(),D(this,h,"m",JW).call(this)}_emit($,...W){if(D(this,z0,"f"))return;if($==="end")I(this,z0,!0,"f"),D(this,u0,"f").call(this);let X=D(this,s,"f")[$];if(X)D(this,s,"f")[$]=X.filter((G)=>!G.once),X.forEach(({listener:G})=>G(...W));if($==="abort"){let G=W[0];if(!D(this,k$,"f")&&!X?.length)Promise.reject(G);D(this,J0,"f").call(this,G),D(this,Q0,"f").call(this,G),this._emit("end");return}if($==="error"){let G=W[0];if(!D(this,k$,"f")&&!X?.length)Promise.reject(G);D(this,J0,"f").call(this,G),D(this,Q0,"f").call(this,G),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",D(this,h,"m",w8).call(this))}async _fromReadableStream($,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}D(this,h,"m",L8).call(this),this._connected(null);let G=g.fromReadableStream($,this.controller);for await(let J of G)D(this,h,"m",F8).call(this,J);if(G.controller.signal?.aborted)throw new k;D(this,h,"m",j8).call(this)}[(Y$=new WeakMap,G0=new WeakMap,c0=new WeakMap,J0=new WeakMap,Y0=new WeakMap,u0=new WeakMap,Q0=new WeakMap,s=new WeakMap,z0=new WeakMap,p0=new WeakMap,d0=new WeakMap,k$=new WeakMap,i0=new WeakMap,n0=new WeakMap,D8=new WeakMap,h=new WeakSet,w8=function(){if(this.receivedMessages.length===0)throw new K("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},JW=function(){if(this.receivedMessages.length===0)throw new K("stream ended without producing a Message with role=assistant");let W=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(W.length===0)throw new K("stream ended without producing a content block with type=text");return W.join(" ")},L8=function(){if(this.ended)return;I(this,Y$,void 0,"f")},F8=function(W){if(this.ended)return;let X=D(this,h,"m",YW).call(this,W);switch(this._emit("streamEvent",W,X),W.type){case"content_block_delta":{let G=X.content.at(-1);switch(W.delta.type){case"text_delta":{if(G.type==="text")this._emit("text",W.delta.text,G.text||"");break}case"citations_delta":{if(G.type==="text")this._emit("citation",W.delta.citation,G.citations??[]);break}case"input_json_delta":{if(G.type==="tool_use"&&G.input)this._emit("inputJson",W.delta.partial_json,G.input);break}case"thinking_delta":{if(G.type==="thinking")this._emit("thinking",W.delta.thinking,G.thinking);break}case"signature_delta":{if(G.type==="thinking")this._emit("signature",G.signature);break}default:zW(W.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(X,!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{I(this,Y$,X,"f");break}case"content_block_start":case"message_delta":break}},j8=function(){if(this.ended)throw new K("stream has ended, this shouldn't happen");let W=D(this,Y$,"f");if(!W)throw new K("request ended without sending any chunks");return I(this,Y$,void 0,"f"),W},YW=function(W){let X=D(this,Y$,"f");if(W.type==="message_start"){if(X)throw new K(`Unexpected event order, got ${W.type} before receiving "message_stop"`);return W.message}if(!X)throw new K(`Unexpected event order, got ${W.type} before "message_start"`);switch(W.type){case"message_stop":return X;case"message_delta":return X.stop_reason=W.delta.stop_reason,X.stop_sequence=W.delta.stop_sequence,X.usage.output_tokens=W.usage.output_tokens,X;case"content_block_start":return X.content.push(W.content_block),X;case"content_block_delta":{let G=X.content.at(W.index);switch(W.delta.type){case"text_delta":{if(G?.type==="text")G.text+=W.delta.text;break}case"citations_delta":{if(G?.type==="text")G.citations??(G.citations=[]),G.citations.push(W.delta.citation);break}case"input_json_delta":{if(G?.type==="tool_use"){let J=G[QW]||"";if(J+=W.delta.partial_json,Object.defineProperty(G,QW,{value:J,enumerable:!1,writable:!0}),J)G.input=l0(J)}break}case"thinking_delta":{if(G?.type==="thinking")G.thinking+=W.delta.thinking;break}case"signature_delta":{if(G?.type==="thinking")G.signature=W.delta.signature;break}default:zW(W.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let $=[],W=[],X=!1;return this.on("streamEvent",(G)=>{let J=W.shift();if(J)J.resolve(G);else $.push(G)}),this.on("end",()=>{X=!0;for(let G of W)G.resolve(void 0);W.length=0}),this.on("abort",(G)=>{X=!0;for(let J of W)J.reject(G);W.length=0}),this.on("error",(G)=>{X=!0;for(let J of W)J.reject(G);W.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((J,Y)=>W.push({resolve:J,reject:Y})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new g(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function zW($){}var HW={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};class w$ extends T{constructor(){super(...arguments);this.batches=new T$(this._client)}create($,W){let{betas:X,...G}=$;if(G.model in HW)console.warn(`The model '${G.model}' is deprecated and will reach end-of-life on ${HW[G.model]}
7
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);return this._client.post("/v1/messages?beta=true",{body:G,timeout:this._client._options.timeout??(G.stream?600000:this._client._calculateNonstreamingTimeout(G.max_tokens)),...W,headers:{...X?.toString()!=null?{"anthropic-beta":X?.toString()}:void 0,...W?.headers},stream:$.stream??!1})}stream($,W){return H0.createMessage(this,$,W)}countTokens($,W){let{betas:X,...G}=$;return this._client.post("/v1/messages/count_tokens?beta=true",{body:G,...W,headers:{"anthropic-beta":[...X??[],"token-counting-2024-11-01"].toString(),...W?.headers}})}}w$.Batches=T$;w$.BetaMessageBatchesPage=X0;class e extends T{constructor(){super(...arguments);this.models=new C$(this._client),this.messages=new w$(this._client)}}e.Models=C$;e.BetaModelInfosPage=W0;e.Messages=w$;class I$ extends T{create($,W){return this._client.post("/v1/complete",{body:$,timeout:this._client._options.timeout??600000,...W,stream:$.stream??!1})}}class b$ extends T{create($,W){return this._client.post("/v1/messages/batches",{body:$,...W})}retrieve($,W){return this._client.get(`/v1/messages/batches/${$}`,W)}list($={},W){if(y($))return this.list({},$);return this._client.getAPIList("/v1/messages/batches",V0,{query:$,...W})}delete($,W){return this._client.delete(`/v1/messages/batches/${$}`,W)}cancel($,W){return this._client.post(`/v1/messages/batches/${$}/cancel`,W)}async results($,W){let X=await this.retrieve($);if(!X.results_url)throw new K(`No batch \`results_url\`; Has it finished processing? ${X.processing_status} - ${X.id}`);return this._client.get(X.results_url,{...W,headers:{Accept:"application/binary",...W?.headers},__binaryResponse:!0})._thenUnwrap((G,J)=>f$.fromResponse(J.response,J.controller))}}class V0 extends t{}b$.MessageBatchesPage=V0;var b=function($,W,X,G,J){if(G==="m")throw TypeError("Private method is not writable");if(G==="a"&&!J)throw TypeError("Private accessor was defined without a setter");if(typeof W==="function"?$!==W||!J:!W.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return G==="a"?J.call($,X):J?J.value=X:W.set($,X),X},L=function($,W,X,G){if(X==="a"&&!G)throw TypeError("Private accessor was defined without a getter");if(typeof W==="function"?$!==W||!G:!W.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return X==="m"?G:X==="a"?G.call($):G?G.value:W.get($)},m,Q$,q0,a0,_0,B0,o0,M0,$$,U0,r0,t0,x$,s0,e0,S8,VW,E8,R8,A8,C8,qW,_W="__json_buf";class N0{constructor(){m.add(this),this.messages=[],this.receivedMessages=[],Q$.set(this,void 0),this.controller=new AbortController,q0.set(this,void 0),a0.set(this,()=>{}),_0.set(this,()=>{}),B0.set(this,void 0),o0.set(this,()=>{}),M0.set(this,()=>{}),$$.set(this,{}),U0.set(this,!1),r0.set(this,!1),t0.set(this,!1),x$.set(this,!1),s0.set(this,void 0),e0.set(this,void 0),E8.set(this,($)=>{if(b(this,r0,!0,"f"),$ instanceof Error&&$.name==="AbortError")$=new k;if($ instanceof k)return b(this,t0,!0,"f"),this._emit("abort",$);if($ instanceof K)return this._emit("error",$);if($ instanceof Error){let W=new K($.message);return W.cause=$,this._emit("error",W)}return this._emit("error",new K(String($)))}),b(this,q0,new Promise(($,W)=>{b(this,a0,$,"f"),b(this,_0,W,"f")}),"f"),b(this,B0,new Promise(($,W)=>{b(this,o0,$,"f"),b(this,M0,W,"f")}),"f"),L(this,q0,"f").catch(()=>{}),L(this,B0,"f").catch(()=>{})}get response(){return L(this,s0,"f")}get request_id(){return L(this,e0,"f")}async withResponse(){let $=await L(this,q0,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let W=new N0;return W._run(()=>W._fromReadableStream($)),W}static createMessage($,W,X){let G=new N0;for(let J of W.messages)G._addMessageParam(J);return G._run(()=>G._createMessage($,{...W,stream:!0},{...X,headers:{...X?.headers,"X-Stainless-Helper-Method":"stream"}})),G}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},L(this,E8,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,W=!0){if(this.receivedMessages.push($),W)this._emit("message",$)}async _createMessage($,W,X){let G=X?.signal;if(G){if(G.aborted)this.controller.abort();G.addEventListener("abort",()=>this.controller.abort())}L(this,m,"m",R8).call(this);let{response:J,data:Y}=await $.create({...W,stream:!0},{...X,signal:this.controller.signal}).withResponse();this._connected(J);for await(let Q of Y)L(this,m,"m",A8).call(this,Q);if(Y.controller.signal?.aborted)throw new k;L(this,m,"m",C8).call(this)}_connected($){if(this.ended)return;b(this,s0,$,"f"),b(this,e0,$?.headers.get("request-id"),"f"),L(this,a0,"f").call(this,$),this._emit("connect")}get ended(){return L(this,U0,"f")}get errored(){return L(this,r0,"f")}get aborted(){return L(this,t0,"f")}abort(){this.controller.abort()}on($,W){return(L(this,$$,"f")[$]||(L(this,$$,"f")[$]=[])).push({listener:W}),this}off($,W){let X=L(this,$$,"f")[$];if(!X)return this;let G=X.findIndex((J)=>J.listener===W);if(G>=0)X.splice(G,1);return this}once($,W){return(L(this,$$,"f")[$]||(L(this,$$,"f")[$]=[])).push({listener:W,once:!0}),this}emitted($){return new Promise((W,X)=>{if(b(this,x$,!0,"f"),$!=="error")this.once("error",X);this.once($,W)})}async done(){b(this,x$,!0,"f"),await L(this,B0,"f")}get currentMessage(){return L(this,Q$,"f")}async finalMessage(){return await this.done(),L(this,m,"m",S8).call(this)}async finalText(){return await this.done(),L(this,m,"m",VW).call(this)}_emit($,...W){if(L(this,U0,"f"))return;if($==="end")b(this,U0,!0,"f"),L(this,o0,"f").call(this);let X=L(this,$$,"f")[$];if(X)L(this,$$,"f")[$]=X.filter((G)=>!G.once),X.forEach(({listener:G})=>G(...W));if($==="abort"){let G=W[0];if(!L(this,x$,"f")&&!X?.length)Promise.reject(G);L(this,_0,"f").call(this,G),L(this,M0,"f").call(this,G),this._emit("end");return}if($==="error"){let G=W[0];if(!L(this,x$,"f")&&!X?.length)Promise.reject(G);L(this,_0,"f").call(this,G),L(this,M0,"f").call(this,G),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",L(this,m,"m",S8).call(this))}async _fromReadableStream($,W){let X=W?.signal;if(X){if(X.aborted)this.controller.abort();X.addEventListener("abort",()=>this.controller.abort())}L(this,m,"m",R8).call(this),this._connected(null);let G=g.fromReadableStream($,this.controller);for await(let J of G)L(this,m,"m",A8).call(this,J);if(G.controller.signal?.aborted)throw new k;L(this,m,"m",C8).call(this)}[(Q$=new WeakMap,q0=new WeakMap,a0=new WeakMap,_0=new WeakMap,B0=new WeakMap,o0=new WeakMap,M0=new WeakMap,$$=new WeakMap,U0=new WeakMap,r0=new WeakMap,t0=new WeakMap,x$=new WeakMap,s0=new WeakMap,e0=new WeakMap,E8=new WeakMap,m=new WeakSet,S8=function(){if(this.receivedMessages.length===0)throw new K("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},VW=function(){if(this.receivedMessages.length===0)throw new K("stream ended without producing a Message with role=assistant");let W=this.receivedMessages.at(-1).content.filter((X)=>X.type==="text").map((X)=>X.text);if(W.length===0)throw new K("stream ended without producing a content block with type=text");return W.join(" ")},R8=function(){if(this.ended)return;b(this,Q$,void 0,"f")},A8=function(W){if(this.ended)return;let X=L(this,m,"m",qW).call(this,W);switch(this._emit("streamEvent",W,X),W.type){case"content_block_delta":{let G=X.content.at(-1);switch(W.delta.type){case"text_delta":{if(G.type==="text")this._emit("text",W.delta.text,G.text||"");break}case"citations_delta":{if(G.type==="text")this._emit("citation",W.delta.citation,G.citations??[]);break}case"input_json_delta":{if(G.type==="tool_use"&&G.input)this._emit("inputJson",W.delta.partial_json,G.input);break}case"thinking_delta":{if(G.type==="thinking")this._emit("thinking",W.delta.thinking,G.thinking);break}case"signature_delta":{if(G.type==="thinking")this._emit("signature",G.signature);break}default:BW(W.delta)}break}case"message_stop":{this._addMessageParam(X),this._addMessage(X,!0);break}case"content_block_stop":{this._emit("contentBlock",X.content.at(-1));break}case"message_start":{b(this,Q$,X,"f");break}case"content_block_start":case"message_delta":break}},C8=function(){if(this.ended)throw new K("stream has ended, this shouldn't happen");let W=L(this,Q$,"f");if(!W)throw new K("request ended without sending any chunks");return b(this,Q$,void 0,"f"),W},qW=function(W){let X=L(this,Q$,"f");if(W.type==="message_start"){if(X)throw new K(`Unexpected event order, got ${W.type} before receiving "message_stop"`);return W.message}if(!X)throw new K(`Unexpected event order, got ${W.type} before "message_start"`);switch(W.type){case"message_stop":return X;case"message_delta":return X.stop_reason=W.delta.stop_reason,X.stop_sequence=W.delta.stop_sequence,X.usage.output_tokens=W.usage.output_tokens,X;case"content_block_start":return X.content.push(W.content_block),X;case"content_block_delta":{let G=X.content.at(W.index);switch(W.delta.type){case"text_delta":{if(G?.type==="text")G.text+=W.delta.text;break}case"citations_delta":{if(G?.type==="text")G.citations??(G.citations=[]),G.citations.push(W.delta.citation);break}case"input_json_delta":{if(G?.type==="tool_use"){let J=G[_W]||"";if(J+=W.delta.partial_json,Object.defineProperty(G,_W,{value:J,enumerable:!1,writable:!0}),J)G.input=l0(J)}break}case"thinking_delta":{if(G?.type==="thinking")G.thinking+=W.delta.thinking;break}case"signature_delta":{if(G?.type==="thinking")G.signature=W.delta.signature;break}default:BW(W.delta)}return X}case"content_block_stop":return X}},Symbol.asyncIterator)](){let $=[],W=[],X=!1;return this.on("streamEvent",(G)=>{let J=W.shift();if(J)J.resolve(G);else $.push(G)}),this.on("end",()=>{X=!0;for(let G of W)G.resolve(void 0);W.length=0}),this.on("abort",(G)=>{X=!0;for(let J of W)J.reject(G);W.length=0}),this.on("error",(G)=>{X=!0;for(let J of W)J.reject(G);W.length=0}),{next:async()=>{if(!$.length){if(X)return{value:void 0,done:!0};return new Promise((J,Y)=>W.push({resolve:J,reject:Y})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new g(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function BW($){}class z$ extends T{constructor(){super(...arguments);this.batches=new b$(this._client)}create($,W){if($.model in MW)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${MW[$.model]}
8
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);return this._client.post("/v1/messages",{body:$,timeout:this._client._options.timeout??($.stream?600000:this._client._calculateNonstreamingTimeout($.max_tokens)),...W,stream:$.stream??!1})}stream($,W){return N0.createMessage(this,$,W)}countTokens($,W){return this._client.post("/v1/messages/count_tokens",{body:$,...W})}}var MW={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};z$.Batches=b$;z$.MessageBatchesPage=V0;class D$ extends T{retrieve($,W){return this._client.get(`/v1/models/${$}`,W)}list($={},W){if(y($))return this.list({},$);return this._client.getAPIList("/v1/models",Z$,{query:$,...W})}}class Z$ extends t{}D$.ModelInfosPage=Z$;var UW;class S extends K8{constructor({baseURL:$=m0("ANTHROPIC_BASE_URL"),apiKey:W=m0("ANTHROPIC_API_KEY")??null,authToken:X=m0("ANTHROPIC_AUTH_TOKEN")??null,...G}={}){let J={apiKey:W,authToken:X,...G,baseURL:$||"https://api.anthropic.com"};if(!J.dangerouslyAllowBrowser&&GW())throw new K(`It looks like you're running in a browser-like environment.
9
+
10
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
11
+ If you understand the risks and have appropriate mitigations in place,
12
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
13
+
14
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
15
+ `);super({baseURL:J.baseURL,timeout:J.timeout??600000,httpAgent:J.httpAgent,maxRetries:J.maxRetries,fetch:J.fetch});this.completions=new I$(this),this.messages=new z$(this),this.models=new D$(this),this.beta=new e(this),this._options=J,this.apiKey=W,this.authToken=X}defaultQuery(){return this._options.defaultQuery}defaultHeaders($){return{...super.defaultHeaders($),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders($,W){if(this.apiKey&&$["x-api-key"])return;if(W["x-api-key"]===null)return;if(this.authToken&&$.authorization)return;if(W.authorization===null)return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders($){let W=this.apiKeyAuth($),X=this.bearerAuth($);if(W!=null&&!$0(W))return W;if(X!=null&&!$0(X))return X;return{}}apiKeyAuth($){if(this.apiKey==null)return{};return{"X-Api-Key":this.apiKey}}bearerAuth($){if(this.authToken==null)return{};return{Authorization:`Bearer ${this.authToken}`}}}UW=S;S.Anthropic=UW;S.HUMAN_PROMPT=`
16
+
17
+ Human:`;S.AI_PROMPT=`
18
+
19
+ Assistant:`;S.DEFAULT_TIMEOUT=600000;S.AnthropicError=K;S.APIError=C;S.APIConnectionError=K$;S.APIConnectionTimeoutError=t$;S.APIUserAbortError=k;S.NotFoundError=P0;S.ConflictError=k0;S.RateLimitError=b0;S.BadRequestError=C0;S.AuthenticationError=f0;S.InternalServerError=x0;S.PermissionDeniedError=T0;S.UnprocessableEntityError=I0;S.toFile=a8;S.fileFromPath=A0;S.Completions=I$;S.Messages=z$;S.Models=D$;S.ModelInfosPage=Z$;S.Beta=e;var $8=S;var hX=new Set(["decision","bugfix","feature","refactor","discovery","change"]);function f($,W){let X=new RegExp(`<${W}[^>]*>([\\s\\S]*?)</${W}>`,"i"),G=$.match(X);return G?G[1].trim():""}function L$($,W){let X=new RegExp(`<${W}[^>]*>([\\s\\S]*?)</${W}>`,"gi"),G=[];for(let J of $.matchAll(X)){let Y=J[1].trim();if(Y)G.push(Y)}return G}function NW($){let W=f($,"observation");if(!W)return null;let X=f(W,"type").toLowerCase(),G=hX.has(X)?X:"discovery",J=f(W,"title")||"Untitled observation",Y=f(W,"subtitle"),Q=f(W,"narrative"),z=L$(f(W,"facts"),"fact"),H=L$(f(W,"concepts"),"concept"),q=L$(f(W,"files_read"),"file"),O=L$(f(W,"files_modified"),"file");return{type:G,title:J,subtitle:Y,facts:z,narrative:Q,concepts:H,filesRead:q,filesModified:O}}function KW($){let W=f($,"session_summary");if(!W)return null;let X=f(W,"summary")||"No summary available",G=L$(f(W,"key_decisions"),"decision"),J=L$(f(W,"files_modified"),"file"),Y=L$(f(W,"concepts"),"concept"),Q=f(W,"request")||void 0,z=f(W,"investigated")||void 0,H=f(W,"learned")||void 0,q=f(W,"completed")||void 0,O=f(W,"next_steps")||void 0;return{summary:X,keyDecisions:G,filesModified:J,concepts:Y,request:Q,investigated:z,learned:H,completed:q,nextSteps:O}}function H$($){return Math.ceil($.length/4)}function OW($,W,X){let G=X?`<session_context>
20
+ ${X}
21
+ </session_context>
22
+
23
+ `:"";return`<task>
24
+ Analyze the following tool output and extract a structured observation.
25
+ </task>
26
+
27
+ <tool_name>${$}</tool_name>
28
+
29
+ <tool_output>
30
+ ${W}
31
+ </tool_output>
32
+
33
+ ${G}<instructions>
34
+ Extract a structured observation from the tool output. Determine the most appropriate type and provide a concise but informative summary.
35
+
36
+ When extracting concepts, prefer established vocabulary where appropriate:
37
+ - how-it-works: Technical mechanisms and behaviors
38
+ - why-it-exists: Rationale and motivations
39
+ - what-changed: Modifications and their effects
40
+ - problem-solution: Issues encountered and how they were resolved
41
+ - gotcha: Surprising behaviors, edge cases, or pitfalls
42
+ - pattern: Recurring design patterns or approaches
43
+ - trade-off: Deliberate compromises between competing concerns
44
+ You may also use any domain-specific concepts relevant to the observation.
45
+
46
+ Respond with EXACTLY this XML format:
47
+ <observation>
48
+ <type>decision|bugfix|feature|refactor|discovery|change</type>
49
+ <title>Brief descriptive title (max 80 chars)</title>
50
+ <subtitle>One-line elaboration</subtitle>
51
+ <facts>
52
+ <fact>Specific factual detail 1</fact>
53
+ <fact>Specific factual detail 2</fact>
54
+ </facts>
55
+ <narrative>2-3 sentence narrative explaining what happened and why it matters</narrative>
56
+ <concepts>
57
+ <concept>relevant-concept-1</concept>
58
+ <concept>relevant-concept-2</concept>
59
+ </concepts>
60
+ <files_read>
61
+ <file>path/to/file/read</file>
62
+ </files_read>
63
+ <files_modified>
64
+ <file>path/to/file/modified</file>
65
+ </files_modified>
66
+ </observation>
67
+ </instructions>`}function wW($,W){let X=$.map((G,J)=>` <obs index="${J+1}" type="${G.type}">
68
+ <title>${G.title}</title>
69
+ <narrative>${G.narrative}</narrative>
70
+ </obs>`).join(`
71
+ `);return`<task>
72
+ Summarize the following coding session based on its observations.
73
+ </task>
74
+
75
+ <session_id>${W}</session_id>
76
+
77
+ <observations>
78
+ ${X}
79
+ </observations>
80
+
81
+ <instructions>
82
+ Create a concise session summary. Focus on key decisions, outcomes, and patterns.
83
+
84
+ Respond with EXACTLY this XML format:
85
+ <session_summary>
86
+ <request>What the user asked for (1-2 sentences)</request>
87
+ <investigated>What was explored or researched</investigated>
88
+ <learned>Key discoveries and insights</learned>
89
+ <completed>What was accomplished</completed>
90
+ <next_steps>What to do next (if any)</next_steps>
91
+ <summary>2-4 sentence summary of the entire session</summary>
92
+ <key_decisions>
93
+ <decision>Important decision made during session</decision>
94
+ </key_decisions>
95
+ <files_modified>
96
+ <file>path/to/modified/file</file>
97
+ </files_modified>
98
+ <concepts>
99
+ <concept>key-concept</concept>
100
+ </concepts>
101
+ </session_summary>
102
+ </instructions>`}class K0{client;config;constructor($){this.config=$,this.client=$.apiKey&&$.compressionEnabled?new $8({apiKey:$.apiKey}):null}static MAX_INPUT_LENGTH=50000;async compress($,W,X){if(!this.config.compressionEnabled||!this.client)return null;if(W.length<this.config.minOutputLength)return null;let G=W.length>K0.MAX_INPUT_LENGTH?`${W.substring(0,K0.MAX_INPUT_LENGTH)}
103
+
104
+ [... truncated ...]`:W,J=OW($,G,X),Y=2;for(let Q=0;Q<=Y;Q++)try{let H=(await this.client.messages.create({model:this.config.model,max_tokens:this.config.maxTokensPerCompression,messages:[{role:"user",content:J}]})).content.filter((q)=>q.type==="text").map((q)=>q.text).join("");return NW(H)}catch(z){if(uX(z)&&Q<Y){let H=2**Q*1000;await DW(H);continue}return null}return null}async compressBatch($){let W=new Map;for(let X=0;X<$.length;X++){let G=$[X],J=await this.compress(G.toolName,G.toolOutput,G.sessionContext);if(W.set(G.callId,J),X<$.length-1)await DW(200)}return W}createFallbackObservation($,W){let X=cX(W),G=mX[$]??"discovery";return{type:G,title:`${$} execution`,subtitle:W.substring(0,100).replace(/\n/g," "),facts:[],narrative:`Tool ${$} was executed. Output length: ${W.length} chars.`,concepts:[],filesRead:G==="discovery"?X:[],filesModified:G==="change"?X:[]}}async isAvailable(){if(!this.client)return!1;try{return await this.client.messages.create({model:this.config.model,max_tokens:10,messages:[{role:"user",content:"ping"}]}),!0}catch{return!1}}}var mX={Read:"discovery",Write:"change",Edit:"change",Bash:"change",Glob:"discovery",Grep:"discovery"},lX=/(?:^|\s)((?:\.\/|\/|src\/|tests\/|lib\/)\S+\.\w+)/gm;function cX($){let W=[];for(let X of $.matchAll(lX))W.push(X[1]);return[...new Set(W)]}function uX($){if(typeof $!=="object"||$===null)return!1;let W=$.status;if(W===429||W===500||W===503)return!0;let X=$.error;if(typeof X==="object"&&X!==null&&X.type==="overloaded_error")return!0;return!1}function DW($){return new Promise((W)=>setTimeout(W,$))}class f8{client;config;constructor($){this.config=$,this.client=$.apiKey&&$.compressionEnabled?new $8({apiKey:$.apiKey}):null}async summarize($,W){if(W.length===0)return null;if(!this.config.compressionEnabled||!this.client)return this.createFallbackSummary(W);let X=wW(W.map((G)=>({type:G.type,title:G.title,narrative:G.narrative})),$);try{let J=(await this.client.messages.create({model:this.config.model,max_tokens:this.config.maxTokensPerCompression,messages:[{role:"user",content:X}]})).content.filter((Q)=>Q.type==="text").map((Q)=>Q.text).join(""),Y=KW(J);if(!Y)return this.createFallbackSummary(W);return Y}catch{return this.createFallbackSummary(W)}}createFallbackSummary($){let W=new Set,X=new Set,G=[];for(let z of $){for(let H of z.filesModified)W.add(H);for(let H of z.concepts)X.add(H);if(z.type==="decision")G.push(z.title)}let J=new Map;for(let z of $)J.set(z.type,(J.get(z.type)??0)+1);let Y=Array.from(J.entries()).map(([z,H])=>`${H} ${z}${H>1?"s":""}`).join(", "),Q=Array.from(X).slice(0,5).join(", ");return{summary:`Session with ${$.length} observations: ${Y}. Files modified: ${W.size}. Key concepts: ${Q}.`,keyDecisions:G.slice(0,5),filesModified:Array.from(W),concepts:Array.from(X)}}shouldSummarize($){return $>=2}}var LW={dbPath:".open-mem/memory.db",apiKey:void 0,model:"claude-sonnet-4-20250514",maxTokensPerCompression:1024,compressionEnabled:!0,contextInjectionEnabled:!0,maxContextTokens:4000,batchSize:5,batchIntervalMs:30000,ignoredTools:[],minOutputLength:50,maxIndexEntries:20,sensitivePatterns:[],retentionDays:90,maxDatabaseSizeMb:500,logLevel:"warn",contextShowTokenCosts:!0,contextObservationTypes:"all",contextFullObservationCount:3,maxObservations:50,contextShowLastSummary:!0};function pX(){let $={};if(process.env.OPEN_MEM_DB_PATH)$.dbPath=process.env.OPEN_MEM_DB_PATH;if(process.env.ANTHROPIC_API_KEY)$.apiKey=process.env.ANTHROPIC_API_KEY;if(process.env.OPEN_MEM_MODEL)$.model=process.env.OPEN_MEM_MODEL;if(process.env.OPEN_MEM_MAX_CONTEXT_TOKENS)$.maxContextTokens=Number.parseInt(process.env.OPEN_MEM_MAX_CONTEXT_TOKENS,10);if(process.env.OPEN_MEM_COMPRESSION==="false")$.compressionEnabled=!1;if(process.env.OPEN_MEM_CONTEXT_INJECTION==="false")$.contextInjectionEnabled=!1;if(process.env.OPEN_MEM_IGNORED_TOOLS)$.ignoredTools=process.env.OPEN_MEM_IGNORED_TOOLS.split(",").map((W)=>W.trim());if(process.env.OPEN_MEM_BATCH_SIZE)$.batchSize=Number.parseInt(process.env.OPEN_MEM_BATCH_SIZE,10);if(process.env.OPEN_MEM_RETENTION_DAYS)$.retentionDays=Number.parseInt(process.env.OPEN_MEM_RETENTION_DAYS,10);if(process.env.OPEN_MEM_LOG_LEVEL)$.logLevel=process.env.OPEN_MEM_LOG_LEVEL;if(process.env.OPEN_MEM_CONTEXT_SHOW_TOKEN_COSTS==="false")$.contextShowTokenCosts=!1;if(process.env.OPEN_MEM_CONTEXT_TYPES)$.contextObservationTypes=process.env.OPEN_MEM_CONTEXT_TYPES==="all"?"all":process.env.OPEN_MEM_CONTEXT_TYPES.split(",").map((W)=>W.trim());if(process.env.OPEN_MEM_CONTEXT_FULL_COUNT)$.contextFullObservationCount=Number.parseInt(process.env.OPEN_MEM_CONTEXT_FULL_COUNT,10);if(process.env.OPEN_MEM_MAX_OBSERVATIONS)$.maxObservations=Number.parseInt(process.env.OPEN_MEM_MAX_OBSERVATIONS,10);if(process.env.OPEN_MEM_CONTEXT_SHOW_LAST_SUMMARY==="false")$.contextShowLastSummary=!1;return $}function T8($,W){let X=pX(),G={...LW,...X,...W};if(!G.dbPath.startsWith("/"))G.dbPath=`${$}/${G.dbPath}`;if(!G.apiKey)G.apiKey=process.env.ANTHROPIC_API_KEY;return G}function FW($){let W=[];if($.compressionEnabled&&!$.apiKey)W.push("AI compression enabled but no ANTHROPIC_API_KEY found. Set ANTHROPIC_API_KEY env var or disable compression.");if($.maxContextTokens<500)W.push("maxContextTokens must be at least 500");if($.batchSize<1)W.push("batchSize must be at least 1");if($.minOutputLength<0)W.push("minOutputLength must be non-negative");return W}function dX(){return{...LW}}async function jW($){let W=$.dbPath.substring(0,$.dbPath.lastIndexOf("/")),{mkdir:X}=await import("fs/promises");await X(W,{recursive:!0})}import{Database as iX}from"bun:sqlite";import{mkdirSync as nX}from"fs";class SW{db;constructor($){this.db=this.open($),this.configure()}open($){let W=$.lastIndexOf("/");if(W>0){let X=$.substring(0,W);nX(X,{recursive:!0})}return new iX($,{create:!0})}configure(){this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA synchronous = NORMAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.db.exec("PRAGMA busy_timeout = 5000")}ensureMigrationTable(){this.db.exec(`
105
+ CREATE TABLE IF NOT EXISTS _migrations (
106
+ version INTEGER PRIMARY KEY,
107
+ name TEXT NOT NULL,
108
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
109
+ )
110
+ `)}migrate($){this.ensureMigrationTable();let W=this.db.query("SELECT version FROM _migrations ORDER BY version").all(),X=new Set(W.map((J)=>J.version)),G=$.filter((J)=>!X.has(J.version)).sort((J,Y)=>J.version-Y.version);for(let J of G)this.db.transaction(()=>{this.db.exec(J.up),this.db.query("INSERT INTO _migrations (version, name) VALUES ($version, $name)").run({$version:J.version,$name:J.name})})()}run($,W){let X=this.db.query($);if(W)X.run(...W);else X.run()}get($,W){let X=this.db.query($);return W?X.get(...W):X.get()}all($,W){let X=this.db.query($);return W?X.all(...W):X.all()}exec($){this.db.exec($)}transaction($){return this.db.transaction($)()}close(){this.db.close()}get isOpen(){try{return this.db.query("SELECT 1").get(),!0}catch{return!1}}get raw(){return this.db}}function EW($){return new SW($)}import{randomUUID as aX}from"crypto";class P8{db;constructor($){this.db=$}create($){let W=aX(),X=new Date().toISOString();return this.db.run(`INSERT INTO observations
111
+ (id, session_id, type, title, subtitle, facts, narrative,
112
+ concepts, files_read, files_modified, raw_tool_output,
113
+ tool_name, created_at, token_count)
114
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[W,$.sessionId,$.type,$.title,$.subtitle,JSON.stringify($.facts),$.narrative,JSON.stringify($.concepts),JSON.stringify($.filesRead),JSON.stringify($.filesModified),$.rawToolOutput,$.toolName,X,$.tokenCount]),{...$,id:W,createdAt:X}}getById($){let W=this.db.get("SELECT * FROM observations WHERE id = ?",[$]);return W?this.mapRow(W):null}getBySession($){return this.db.all("SELECT * FROM observations WHERE session_id = ? ORDER BY created_at ASC",[$]).map((W)=>this.mapRow(W))}getCount($){if($)return this.db.get("SELECT COUNT(*) as count FROM observations WHERE session_id = ?",[$])?.count??0;return this.db.get("SELECT COUNT(*) as count FROM observations")?.count??0}getIndex($,W=20){return this.db.all(`SELECT o.id, o.session_id, o.type, o.title, o.token_count, o.created_at
115
+ FROM observations o
116
+ JOIN sessions s ON o.session_id = s.id
117
+ WHERE s.project_path = ?
118
+ ORDER BY o.created_at DESC
119
+ LIMIT ?`,[$,W]).map((X)=>({id:X.id,sessionId:X.session_id,type:X.type,title:X.title,tokenCount:X.token_count,createdAt:X.created_at}))}search($){let W=`
120
+ SELECT o.*, rank
121
+ FROM observations o
122
+ JOIN observations_fts fts ON o._rowid = fts.rowid
123
+ WHERE observations_fts MATCH ?
124
+ `,X=[$.query];if($.sessionId)W+=" AND o.session_id = ?",X.push($.sessionId);if($.type)W+=" AND o.type = ?",X.push($.type);return W+=" ORDER BY rank LIMIT ? OFFSET ?",X.push($.limit??10),X.push($.offset??0),this.db.all(W,X).map((G)=>({observation:this.mapRow(G),rank:G.rank,snippet:G.title}))}searchByConcept($,W=10){return this.db.all(`SELECT o.*
125
+ FROM observations o
126
+ JOIN observations_fts fts ON o._rowid = fts.rowid
127
+ WHERE observations_fts MATCH ?
128
+ ORDER BY rank
129
+ LIMIT ?`,[`concepts:${$}`,W]).map((X)=>this.mapRow(X))}searchByFile($,W=10){return this.db.all(`SELECT o.*
130
+ FROM observations o
131
+ JOIN observations_fts fts ON o._rowid = fts.rowid
132
+ WHERE observations_fts MATCH ?
133
+ ORDER BY rank
134
+ LIMIT ?`,[`files_read:"${$}" OR files_modified:"${$}"`,W]).map((X)=>this.mapRow(X))}mapRow($){return{id:$.id,sessionId:$.session_id,type:$.type,title:$.title,subtitle:$.subtitle,facts:JSON.parse($.facts),narrative:$.narrative,concepts:JSON.parse($.concepts),filesRead:JSON.parse($.files_read),filesModified:JSON.parse($.files_modified),rawToolOutput:$.raw_tool_output,toolName:$.tool_name,createdAt:$.created_at,tokenCount:$.token_count}}}import{randomUUID as oX}from"crypto";class k8{db;constructor($){this.db=$}create($){let W=oX(),X=new Date().toISOString();return this.db.run(`INSERT INTO pending_messages
135
+ (id, session_id, tool_name, tool_output, call_id, created_at)
136
+ VALUES (?, ?, ?, ?, ?, ?)`,[W,$.sessionId,$.toolName,$.toolOutput,$.callId,X]),{...$,id:W,createdAt:X,status:"pending",retryCount:0,error:null}}getPending($=10){return this.db.all("SELECT * FROM pending_messages WHERE status = 'pending' ORDER BY created_at ASC LIMIT ?",[$]).map((W)=>this.mapRow(W))}getByStatus($){return this.db.all("SELECT * FROM pending_messages WHERE status = ? ORDER BY created_at ASC",[$]).map((W)=>this.mapRow(W))}markProcessing($){this.db.run("UPDATE pending_messages SET status = 'processing' WHERE id = ?",[$])}markCompleted($){this.db.run("UPDATE pending_messages SET status = 'completed' WHERE id = ?",[$])}markFailed($,W){this.db.run("UPDATE pending_messages SET status = 'failed', error = ?, retry_count = retry_count + 1 WHERE id = ?",[W,$])}resetStale($=5){return this.db.all(`UPDATE pending_messages SET status = 'pending'
137
+ WHERE status = 'processing'
138
+ AND created_at < datetime('now', ? || ' minutes')
139
+ RETURNING id`,[`-${$}`]).length}mapRow($){return{id:$.id,sessionId:$.session_id,toolName:$.tool_name,toolOutput:$.tool_output,callId:$.call_id,createdAt:$.created_at,status:$.status,retryCount:$.retry_count,error:$.error??null}}}var rX=[{version:1,name:"create-core-tables",up:`
140
+ -- Sessions table
141
+ CREATE TABLE IF NOT EXISTS sessions (
142
+ _rowid INTEGER PRIMARY KEY AUTOINCREMENT,
143
+ id TEXT UNIQUE NOT NULL,
144
+ project_path TEXT NOT NULL,
145
+ started_at TEXT NOT NULL DEFAULT (datetime('now')),
146
+ ended_at TEXT,
147
+ status TEXT NOT NULL DEFAULT 'active'
148
+ CHECK (status IN ('active', 'idle', 'completed')),
149
+ observation_count INTEGER NOT NULL DEFAULT 0,
150
+ summary_id TEXT
151
+ );
152
+
153
+ CREATE INDEX IF NOT EXISTS idx_sessions_project
154
+ ON sessions(project_path);
155
+ CREATE INDEX IF NOT EXISTS idx_sessions_status
156
+ ON sessions(status);
157
+ CREATE INDEX IF NOT EXISTS idx_sessions_started
158
+ ON sessions(started_at DESC);
159
+
160
+ -- Observations table
161
+ CREATE TABLE IF NOT EXISTS observations (
162
+ _rowid INTEGER PRIMARY KEY AUTOINCREMENT,
163
+ id TEXT UNIQUE NOT NULL,
164
+ session_id TEXT NOT NULL,
165
+ type TEXT NOT NULL
166
+ CHECK (type IN ('decision','bugfix','feature','refactor','discovery','change')),
167
+ title TEXT NOT NULL,
168
+ subtitle TEXT NOT NULL DEFAULT '',
169
+ facts TEXT NOT NULL DEFAULT '[]',
170
+ narrative TEXT NOT NULL DEFAULT '',
171
+ concepts TEXT NOT NULL DEFAULT '[]',
172
+ files_read TEXT NOT NULL DEFAULT '[]',
173
+ files_modified TEXT NOT NULL DEFAULT '[]',
174
+ raw_tool_output TEXT NOT NULL,
175
+ tool_name TEXT NOT NULL,
176
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
177
+ token_count INTEGER NOT NULL DEFAULT 0,
178
+ FOREIGN KEY (session_id) REFERENCES sessions(id)
179
+ );
180
+
181
+ CREATE INDEX IF NOT EXISTS idx_observations_session
182
+ ON observations(session_id);
183
+ CREATE INDEX IF NOT EXISTS idx_observations_type
184
+ ON observations(type);
185
+ CREATE INDEX IF NOT EXISTS idx_observations_created
186
+ ON observations(created_at DESC);
187
+
188
+ -- Session summaries table
189
+ CREATE TABLE IF NOT EXISTS session_summaries (
190
+ _rowid INTEGER PRIMARY KEY AUTOINCREMENT,
191
+ id TEXT UNIQUE NOT NULL,
192
+ session_id TEXT NOT NULL UNIQUE,
193
+ summary TEXT NOT NULL,
194
+ key_decisions TEXT NOT NULL DEFAULT '[]',
195
+ files_modified TEXT NOT NULL DEFAULT '[]',
196
+ concepts TEXT NOT NULL DEFAULT '[]',
197
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
198
+ token_count INTEGER NOT NULL DEFAULT 0,
199
+ FOREIGN KEY (session_id) REFERENCES sessions(id)
200
+ );
201
+
202
+ -- Pending messages (queue persistence)
203
+ CREATE TABLE IF NOT EXISTS pending_messages (
204
+ _rowid INTEGER PRIMARY KEY AUTOINCREMENT,
205
+ id TEXT UNIQUE NOT NULL,
206
+ session_id TEXT NOT NULL,
207
+ tool_name TEXT NOT NULL,
208
+ tool_output TEXT NOT NULL,
209
+ call_id TEXT NOT NULL,
210
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
211
+ status TEXT NOT NULL DEFAULT 'pending'
212
+ CHECK (status IN ('pending','processing','completed','failed')),
213
+ retry_count INTEGER NOT NULL DEFAULT 0,
214
+ error TEXT,
215
+ FOREIGN KEY (session_id) REFERENCES sessions(id)
216
+ );
217
+
218
+ CREATE INDEX IF NOT EXISTS idx_pending_status
219
+ ON pending_messages(status);
220
+ CREATE INDEX IF NOT EXISTS idx_pending_session
221
+ ON pending_messages(session_id);
222
+ `},{version:2,name:"create-fts5-tables",up:`
223
+ -- FTS5 for observations (title, subtitle, narrative, facts, concepts, files)
224
+ CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5(
225
+ title,
226
+ subtitle,
227
+ narrative,
228
+ facts,
229
+ concepts,
230
+ files_read,
231
+ files_modified,
232
+ content=observations,
233
+ content_rowid=_rowid,
234
+ tokenize='porter unicode61'
235
+ );
236
+
237
+ -- Triggers to keep FTS5 in sync with observations table
238
+ CREATE TRIGGER observations_ai AFTER INSERT ON observations BEGIN
239
+ INSERT INTO observations_fts(
240
+ rowid, title, subtitle, narrative, facts, concepts,
241
+ files_read, files_modified
242
+ )
243
+ VALUES (
244
+ new._rowid, new.title, new.subtitle, new.narrative,
245
+ new.facts, new.concepts, new.files_read, new.files_modified
246
+ );
247
+ END;
248
+
249
+ CREATE TRIGGER observations_ad AFTER DELETE ON observations BEGIN
250
+ INSERT INTO observations_fts(
251
+ observations_fts, rowid, title, subtitle, narrative,
252
+ facts, concepts, files_read, files_modified
253
+ )
254
+ VALUES (
255
+ 'delete', old._rowid, old.title, old.subtitle, old.narrative,
256
+ old.facts, old.concepts, old.files_read, old.files_modified
257
+ );
258
+ END;
259
+
260
+ CREATE TRIGGER observations_au AFTER UPDATE ON observations BEGIN
261
+ INSERT INTO observations_fts(
262
+ observations_fts, rowid, title, subtitle, narrative,
263
+ facts, concepts, files_read, files_modified
264
+ )
265
+ VALUES (
266
+ 'delete', old._rowid, old.title, old.subtitle, old.narrative,
267
+ old.facts, old.concepts, old.files_read, old.files_modified
268
+ );
269
+ INSERT INTO observations_fts(
270
+ rowid, title, subtitle, narrative, facts, concepts,
271
+ files_read, files_modified
272
+ )
273
+ VALUES (
274
+ new._rowid, new.title, new.subtitle, new.narrative,
275
+ new.facts, new.concepts, new.files_read, new.files_modified
276
+ );
277
+ END;
278
+
279
+ -- FTS5 for session summaries
280
+ CREATE VIRTUAL TABLE IF NOT EXISTS summaries_fts USING fts5(
281
+ summary,
282
+ key_decisions,
283
+ concepts,
284
+ content=session_summaries,
285
+ content_rowid=_rowid,
286
+ tokenize='porter unicode61'
287
+ );
288
+
289
+ CREATE TRIGGER summaries_ai AFTER INSERT ON session_summaries BEGIN
290
+ INSERT INTO summaries_fts(rowid, summary, key_decisions, concepts)
291
+ VALUES (new._rowid, new.summary, new.key_decisions, new.concepts);
292
+ END;
293
+
294
+ CREATE TRIGGER summaries_ad AFTER DELETE ON session_summaries BEGIN
295
+ INSERT INTO summaries_fts(
296
+ summaries_fts, rowid, summary, key_decisions, concepts
297
+ )
298
+ VALUES (
299
+ 'delete', old._rowid, old.summary, old.key_decisions, old.concepts
300
+ );
301
+ END;
302
+ `},{version:3,name:"add-structured-summary-columns",up:`
303
+ ALTER TABLE session_summaries ADD COLUMN request TEXT NOT NULL DEFAULT '';
304
+ ALTER TABLE session_summaries ADD COLUMN investigated TEXT NOT NULL DEFAULT '';
305
+ ALTER TABLE session_summaries ADD COLUMN learned TEXT NOT NULL DEFAULT '';
306
+ ALTER TABLE session_summaries ADD COLUMN completed TEXT NOT NULL DEFAULT '';
307
+ ALTER TABLE session_summaries ADD COLUMN next_steps TEXT NOT NULL DEFAULT '';
308
+ `}];function RW($){$.migrate(rX)}class I8{db;constructor($){this.db=$}create($,W){let X=new Date().toISOString();return this.db.run(`INSERT INTO sessions (id, project_path, started_at, status)
309
+ VALUES (?, ?, ?, 'active')`,[$,W,X]),this.getById($)}getOrCreate($,W){let X=this.getById($);if(X)return X;return this.create($,W)}getById($){let W=this.db.get("SELECT * FROM sessions WHERE id = ?",[$]);return W?this.mapRow(W):null}getRecent($,W=10){return this.db.all("SELECT * FROM sessions WHERE project_path = ? ORDER BY started_at DESC LIMIT ?",[$,W]).map((X)=>this.mapRow(X))}getActive(){return this.db.all("SELECT * FROM sessions WHERE status = 'active' ORDER BY started_at DESC").map(($)=>this.mapRow($))}updateStatus($,W){this.db.run("UPDATE sessions SET status = ? WHERE id = ?",[W,$])}markCompleted($){this.db.run("UPDATE sessions SET status = 'completed', ended_at = datetime('now') WHERE id = ?",[$])}incrementObservationCount($){this.db.run("UPDATE sessions SET observation_count = observation_count + 1 WHERE id = ?",[$])}setSummary($,W){this.db.run("UPDATE sessions SET summary_id = ? WHERE id = ?",[W,$])}mapRow($){return{id:$.id,projectPath:$.project_path,startedAt:$.started_at,endedAt:$.ended_at??null,status:$.status,observationCount:$.observation_count,summaryId:$.summary_id??null}}}import{randomUUID as tX}from"crypto";class b8{db;constructor($){this.db=$}create($){let W=tX(),X=new Date().toISOString();return this.db.run(`INSERT INTO session_summaries
310
+ (id, session_id, summary, key_decisions, files_modified,
311
+ concepts, created_at, token_count,
312
+ request, investigated, learned, completed, next_steps)
313
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[W,$.sessionId,$.summary,JSON.stringify($.keyDecisions),JSON.stringify($.filesModified),JSON.stringify($.concepts),X,$.tokenCount,$.request??"",$.investigated??"",$.learned??"",$.completed??"",$.nextSteps??""]),{...$,id:W,createdAt:X}}getBySessionId($){let W=this.db.get("SELECT * FROM session_summaries WHERE session_id = ?",[$]);return W?this.mapRow(W):null}getRecent($=10){return this.db.all("SELECT * FROM session_summaries ORDER BY created_at DESC LIMIT ?",[$]).map((W)=>this.mapRow(W))}search($,W=10){return this.db.all(`SELECT ss.*
314
+ FROM session_summaries ss
315
+ JOIN summaries_fts fts ON ss._rowid = fts.rowid
316
+ WHERE summaries_fts MATCH ?
317
+ ORDER BY rank
318
+ LIMIT ?`,[$,W]).map((X)=>this.mapRow(X))}mapRow($){return{id:$.id,sessionId:$.session_id,summary:$.summary,keyDecisions:JSON.parse($.key_decisions),filesModified:JSON.parse($.files_modified),concepts:JSON.parse($.concepts),createdAt:$.created_at,tokenCount:$.token_count,request:$.request||void 0,investigated:$.investigated||void 0,learned:$.learned||void 0,completed:$.completed||void 0,nextSteps:$.next_steps||void 0}}}var sX={showTokenCosts:!0,observationTypes:"all",fullObservationCount:3,showLastSummary:!0},x8={bugfix:"\uD83D\uDD34",feature:"\uD83D\uDFE3",refactor:"\uD83D\uDD04",change:"\u2705",discovery:"\uD83D\uDD35",decision:"\u2696\uFE0F"};function AW($,W=sX){let X=[];if(X.push("## open-mem: Past Session Memory"),X.push(""),X.push("**\uD83D\uDCA1 Progressive Disclosure:** This is a compact index showing WHAT was observed and retrieval COST."),X.push("Use `mem-search` to find observations by query, then `mem-recall` with IDs to fetch full details."),W.showLastSummary&&$.recentSummaries.length>0){X.push(""),X.push("### Recent Sessions"),X.push("| Session | Summary | Decisions |"),X.push("|---------|---------|-----------|");for(let Y of $.recentSummaries){let Q=Y.keyDecisions.length>0?Y.keyDecisions.join("; "):"\u2014";X.push(`| ${Y.sessionId} | ${Y.summary} | ${Q} |`)}}let G=W.observationTypes==="all"?$.observationIndex:$.observationIndex.filter((Y)=>W.observationTypes.includes(Y.type));if(G.length>0){X.push(""),X.push(`### Recent Observations (${G.length} entries)`);let Y=eX(G,$.fullObservations);for(let[Q,z]of Y){if(X.push(""),X.push(`**${Q}**`),W.showTokenCosts)X.push("| ID | Type | Title | ~Tokens |"),X.push("|----|------|-------|---------|");else X.push("| ID | Type | Title |"),X.push("|----|------|-------|");for(let H of z){let q=x8[H.type]||"\uD83D\uDCDD";if(W.showTokenCosts)X.push(`| ${H.id} | ${q} | ${H.title} | ~${H.tokenCount} |`);else X.push(`| ${H.id} | ${q} | ${H.title} |`)}}}let J=$.fullObservations.slice(0,W.fullObservationCount);if(J.length>0){X.push(""),X.push("### Full Details (most recent)");for(let Y of J){let Q=x8[Y.type]||"\uD83D\uDCDD";if(X.push(""),X.push(`#### ${Q} ${Y.title} (${Y.id})`),X.push(Y.narrative),Y.facts.length>0)X.push(`**Facts:** ${Y.facts.map((H)=>`- ${H}`).join(" ")}`);if(Y.concepts.length>0)X.push(`**Concepts:** ${Y.concepts.join(", ")}`);let z=[...Y.filesRead,...Y.filesModified];if(z.length>0)X.push(`**Files:** ${z.join(", ")}`)}}return X.join(`
319
+ `)}function eX($,W){let X=new Map;for(let J of W){let Y=J.filesModified[0]||J.filesRead[0];if(Y)X.set(J.id,Y)}let G=new Map;for(let J of $){let Y=X.get(J.id)??"General",Q=G.get(Y)??[];Q.push(J),G.set(Y,Q)}return G}function CW($){let W=[];if(W.push("[open-mem] Memory context:"),$.recentSummaries.length>0){W.push(`
320
+ Recent sessions:`);for(let X of $.recentSummaries)W.push(`- ${X.summary}`)}if($.observationIndex.length>0){W.push(`
321
+ Recent observations (${$.observationIndex.length} entries):`);for(let X of $.observationIndex)W.push(`- ${x8[X.type]||"\uD83D\uDCDD"} ${X.title}`)}return W.join(`
322
+ `)}function W8($,W,X,G,J=[]){let Y=G,Q=[],z=[];for(let H of W){let q=H.tokenCount||H$(H.summary);if(Y-q<0)break;Q.push(H),Y-=q}for(let H of X){let q=H.tokenCount||H$(H.title);if(Y-q<0)break;z.push(H),Y-=q}return{recentSummaries:Q,observationIndex:z,fullObservations:[...J],totalTokens:G-Y}}function fW($,W,X,G,J){return async(Y,Q)=>{try{if(!$.contextInjectionEnabled)return;let z=X.getRecent(J,3),H=z.map((R)=>R.summaryId?G.getBySessionId(R.id):null).filter((R)=>R!==null),q=W.getIndex(J,10);if(H.length===0&&q.length===0)return;let O=W8(z,H,q,Math.floor($.maxContextTokens/2));Q.context.push(CW(O))}catch(z){console.error("[open-mem] Compaction hook error:",z)}}}function TW($,W,X,G,J){return async(Y,Q)=>{try{if(!$.contextInjectionEnabled)return;let z=X.getRecent(J,5);if(z.length===0)return;let H=z.map((c)=>c.summaryId?G.getBySessionId(c.id):null).filter((c)=>c!==null),q=W.getIndex(J,$.maxObservations);if(H.length===0&&q.length===0)return;let R=q.slice(0,$.contextFullObservationCount).map((c)=>c.id).map((c)=>W.getById(c)).filter((c)=>c!==null),l=W8(z,H,q,$.maxContextTokens,R),E0={showTokenCosts:$.contextShowTokenCosts,observationTypes:$.contextObservationTypes,fullObservationCount:$.contextFullObservationCount,showLastSummary:$.contextShowLastSummary};Q.system.push(AW(l,E0))}catch(z){console.error("[open-mem] Context injection error:",z)}}}function PW($,W,X){return async(G)=>{try{let{event:J}=G,Y=J.properties.sessionID;switch(J.type){case"session.created":{if(Y)W.getOrCreate(Y,X);break}case"session.idle":{if(await $.processBatch(),Y)W.updateStatus(Y,"idle");break}case"session.completed":case"session.ended":{if(Y)await $.processBatch(),await $.summarizeSession(Y),W.markCompleted(Y);break}default:break}}catch(J){console.error("[open-mem] Event handler error:",J)}}}function kW($,W,X,G){return async(J,Y)=>{try{let{tool:Q,sessionID:z,callID:H}=J,{output:q}=Y;if($.ignoredTools.includes(Q))return;if(!q||q.length<$.minOutputLength)return;let O=q;for(let R of $.sensitivePatterns)try{O=O.replace(new RegExp(R,"g"),"[REDACTED]")}catch{}O=O.replace(/<private>[\s\S]*?<\/private>/g,"[PRIVATE]"),X.getOrCreate(z,G),W.enqueue(z,Q,O,H)}catch(Q){console.error("[open-mem] Tool capture error:",Q)}}}class Z8{config;compressor;summarizer;pendingRepo;observationRepo;sessionRepo;summaryRepo;processing=!1;timer=null;constructor($,W,X,G,J,Y,Q){this.config=$;this.compressor=W;this.summarizer=X;this.pendingRepo=G;this.observationRepo=J;this.sessionRepo=Y;this.summaryRepo=Q}enqueue($,W,X,G){this.pendingRepo.create({sessionId:$,toolName:W,toolOutput:X,callId:G})}async processBatch(){if(this.processing)return 0;this.processing=!0;let $=0;try{this.pendingRepo.resetStale(5);let W=this.pendingRepo.getPending(this.config.batchSize);if(W.length===0)return 0;for(let X of W)try{this.pendingRepo.markProcessing(X.id);let J=await this.compressor.compress(X.toolName,X.toolOutput)??this.compressor.createFallbackObservation(X.toolName,X.toolOutput);this.observationRepo.create({sessionId:X.sessionId,type:J.type,title:J.title,subtitle:J.subtitle,facts:J.facts,narrative:J.narrative,concepts:J.concepts,filesRead:J.filesRead,filesModified:J.filesModified,rawToolOutput:X.toolOutput,toolName:X.toolName,tokenCount:H$(`${J.title} ${J.narrative} ${J.facts.join(" ")}`)}),this.sessionRepo.incrementObservationCount(X.sessionId),this.pendingRepo.markCompleted(X.id),$++}catch(G){this.pendingRepo.markFailed(X.id,String(G))}return $}finally{this.processing=!1}}async summarizeSession($){let W=this.observationRepo.getBySession($);if(!this.summarizer.shouldSummarize(W.length))return;if(this.summaryRepo.getBySessionId($))return;let G=await this.summarizer.summarize($,W);if(!G)return;let J=this.summaryRepo.create({sessionId:$,summary:G.summary,keyDecisions:G.keyDecisions,filesModified:G.filesModified,concepts:G.concepts,tokenCount:H$(G.summary)});this.sessionRepo.setSummary($,J.id)}start(){if(this.timer)return;this.timer=setInterval(async()=>{try{await this.processBatch()}catch{}},this.config.batchIntervalMs)}stop(){if(this.timer)clearInterval(this.timer),this.timer=null}get isRunning(){return this.timer!==null}get isProcessing(){return this.processing}getStats(){return{pending:this.pendingRepo.getPending(1000).length,processing:this.processing}}}var A={};sW(A,{void:()=>g6,util:()=>j,unknown:()=>Z6,union:()=>l6,undefined:()=>I6,tuple:()=>p6,transformer:()=>$9,symbol:()=>k6,string:()=>mW,strictObject:()=>m6,setErrorMap:()=>X6,set:()=>n6,record:()=>d6,quotelessJson:()=>$6,promise:()=>e6,preprocess:()=>G9,pipeline:()=>J9,ostring:()=>Y9,optional:()=>W9,onumber:()=>Q9,oboolean:()=>z9,objectUtil:()=>v8,object:()=>h6,number:()=>lW,nullable:()=>X9,null:()=>b6,never:()=>v6,nativeEnum:()=>s6,nan:()=>f6,map:()=>i6,makeIssue:()=>O0,literal:()=>r6,lazy:()=>o6,late:()=>A6,isValid:()=>V$,isDirty:()=>G8,isAsync:()=>g$,isAborted:()=>X8,intersection:()=>u6,instanceof:()=>C6,getParsedType:()=>a,getErrorMap:()=>v$,function:()=>a6,enum:()=>t6,effect:()=>$9,discriminatedUnion:()=>c6,defaultErrorMap:()=>W$,datetimeRegex:()=>gW,date:()=>P6,custom:()=>hW,coerce:()=>H9,boolean:()=>cW,bigint:()=>T6,array:()=>y6,any:()=>x6,addIssueToContext:()=>B,ZodVoid:()=>D0,ZodUnknown:()=>q$,ZodUnion:()=>u$,ZodUndefined:()=>l$,ZodType:()=>F,ZodTuple:()=>r,ZodTransformer:()=>n,ZodSymbol:()=>w0,ZodString:()=>u,ZodSet:()=>E$,ZodSchema:()=>F,ZodRecord:()=>L0,ZodReadonly:()=>r$,ZodPromise:()=>R$,ZodPipeline:()=>S0,ZodParsedType:()=>_,ZodOptional:()=>d,ZodObject:()=>E,ZodNumber:()=>_$,ZodNullable:()=>G$,ZodNull:()=>c$,ZodNever:()=>o,ZodNativeEnum:()=>n$,ZodNaN:()=>j0,ZodMap:()=>F0,ZodLiteral:()=>i$,ZodLazy:()=>d$,ZodIssueCode:()=>V,ZodIntersection:()=>p$,ZodFunction:()=>h$,ZodFirstPartyTypeKind:()=>N,ZodError:()=>Z,ZodEnum:()=>M$,ZodEffects:()=>n,ZodDiscriminatedUnion:()=>J8,ZodDefault:()=>a$,ZodDate:()=>j$,ZodCatch:()=>o$,ZodBranded:()=>Y8,ZodBoolean:()=>m$,ZodBigInt:()=>B$,ZodArray:()=>p,ZodAny:()=>S$,Schema:()=>F,ParseStatus:()=>P,OK:()=>x,NEVER:()=>V9,INVALID:()=>U,EMPTY_PATH:()=>G6,DIRTY:()=>F$,BRAND:()=>R6});var j;(function($){$.assertEqual=(J)=>{};function W(J){}$.assertIs=W;function X(J){throw Error()}$.assertNever=X,$.arrayToEnum=(J)=>{let Y={};for(let Q of J)Y[Q]=Q;return Y},$.getValidEnumValues=(J)=>{let Y=$.objectKeys(J).filter((z)=>typeof J[J[z]]!=="number"),Q={};for(let z of Y)Q[z]=J[z];return $.objectValues(Q)},$.objectValues=(J)=>{return $.objectKeys(J).map(function(Y){return J[Y]})},$.objectKeys=typeof Object.keys==="function"?(J)=>Object.keys(J):(J)=>{let Y=[];for(let Q in J)if(Object.prototype.hasOwnProperty.call(J,Q))Y.push(Q);return Y},$.find=(J,Y)=>{for(let Q of J)if(Y(Q))return Q;return},$.isInteger=typeof Number.isInteger==="function"?(J)=>Number.isInteger(J):(J)=>typeof J==="number"&&Number.isFinite(J)&&Math.floor(J)===J;function G(J,Y=" | "){return J.map((Q)=>typeof Q==="string"?`'${Q}'`:Q).join(Y)}$.joinValues=G,$.jsonStringifyReplacer=(J,Y)=>{if(typeof Y==="bigint")return Y.toString();return Y}})(j||(j={}));var v8;(function($){$.mergeShapes=(W,X)=>{return{...W,...X}}})(v8||(v8={}));var _=j.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),a=($)=>{switch(typeof $){case"undefined":return _.undefined;case"string":return _.string;case"number":return Number.isNaN($)?_.nan:_.number;case"boolean":return _.boolean;case"function":return _.function;case"bigint":return _.bigint;case"symbol":return _.symbol;case"object":if(Array.isArray($))return _.array;if($===null)return _.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return _.promise;if(typeof Map<"u"&&$ instanceof Map)return _.map;if(typeof Set<"u"&&$ instanceof Set)return _.set;if(typeof Date<"u"&&$ instanceof Date)return _.date;return _.object;default:return _.unknown}};var V=j.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$6=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class Z extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(X)=>{this.issues=[...this.issues,X]},this.addIssues=(X=[])=>{this.issues=[...this.issues,...X]};let W=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,W);else this.__proto__=W;this.name="ZodError",this.issues=$}format($){let W=$||function(J){return J.message},X={_errors:[]},G=(J)=>{for(let Y of J.issues)if(Y.code==="invalid_union")Y.unionErrors.map(G);else if(Y.code==="invalid_return_type")G(Y.returnTypeError);else if(Y.code==="invalid_arguments")G(Y.argumentsError);else if(Y.path.length===0)X._errors.push(W(Y));else{let Q=X,z=0;while(z<Y.path.length){let H=Y.path[z];if(z!==Y.path.length-1)Q[H]=Q[H]||{_errors:[]};else Q[H]=Q[H]||{_errors:[]},Q[H]._errors.push(W(Y));Q=Q[H],z++}}};return G(this),X}static assert($){if(!($ instanceof Z))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(W)=>W.message){let W={},X=[];for(let G of this.issues)if(G.path.length>0){let J=G.path[0];W[J]=W[J]||[],W[J].push($(G))}else X.push($(G));return{formErrors:X,fieldErrors:W}}get formErrors(){return this.flatten()}}Z.create=($)=>{return new Z($)};var W6=($,W)=>{let X;switch($.code){case V.invalid_type:if($.received===_.undefined)X="Required";else X=`Expected ${$.expected}, received ${$.received}`;break;case V.invalid_literal:X=`Invalid literal value, expected ${JSON.stringify($.expected,j.jsonStringifyReplacer)}`;break;case V.unrecognized_keys:X=`Unrecognized key(s) in object: ${j.joinValues($.keys,", ")}`;break;case V.invalid_union:X="Invalid input";break;case V.invalid_union_discriminator:X=`Invalid discriminator value. Expected ${j.joinValues($.options)}`;break;case V.invalid_enum_value:X=`Invalid enum value. Expected ${j.joinValues($.options)}, received '${$.received}'`;break;case V.invalid_arguments:X="Invalid function arguments";break;case V.invalid_return_type:X="Invalid function return type";break;case V.invalid_date:X="Invalid date";break;case V.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(X=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")X=`${X} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)X=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)X=`Invalid input: must end with "${$.validation.endsWith}"`;else j.assertNever($.validation);else if($.validation!=="regex")X=`Invalid ${$.validation}`;else X="Invalid";break;case V.too_small:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")X=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else X="Invalid input";break;case V.too_big:if($.type==="array")X=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")X=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")X=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")X=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")X=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else X="Invalid input";break;case V.custom:X="Invalid input";break;case V.invalid_intersection_types:X="Intersection results could not be merged";break;case V.not_multiple_of:X=`Number must be a multiple of ${$.multipleOf}`;break;case V.not_finite:X="Number must be finite";break;default:X=W.defaultError,j.assertNever($)}return{message:X}},W$=W6;var IW=W$;function X6($){IW=$}function v$(){return IW}var O0=($)=>{let{data:W,path:X,errorMaps:G,issueData:J}=$,Y=[...X,...J.path||[]],Q={...J,path:Y};if(J.message!==void 0)return{...J,path:Y,message:J.message};let z="",H=G.filter((q)=>!!q).slice().reverse();for(let q of H)z=q(Q,{data:W,defaultError:z}).message;return{...J,path:Y,message:z}},G6=[];function B($,W){let X=v$(),G=O0({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,X,X===W$?void 0:W$].filter((J)=>!!J)});$.common.issues.push(G)}class P{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,W){let X=[];for(let G of W){if(G.status==="aborted")return U;if(G.status==="dirty")$.dirty();X.push(G.value)}return{status:$.value,value:X}}static async mergeObjectAsync($,W){let X=[];for(let G of W){let J=await G.key,Y=await G.value;X.push({key:J,value:Y})}return P.mergeObjectSync($,X)}static mergeObjectSync($,W){let X={};for(let G of W){let{key:J,value:Y}=G;if(J.status==="aborted")return U;if(Y.status==="aborted")return U;if(J.status==="dirty")$.dirty();if(Y.status==="dirty")$.dirty();if(J.value!=="__proto__"&&(typeof Y.value<"u"||G.alwaysSet))X[J.value]=Y.value}return{status:$.value,value:X}}}var U=Object.freeze({status:"aborted"}),F$=($)=>({status:"dirty",value:$}),x=($)=>({status:"valid",value:$}),X8=($)=>$.status==="aborted",G8=($)=>$.status==="dirty",V$=($)=>$.status==="valid",g$=($)=>typeof Promise<"u"&&$ instanceof Promise;var M;(function($){$.errToObj=(W)=>typeof W==="string"?{message:W}:W||{},$.toString=(W)=>typeof W==="string"?W:W?.message})(M||(M={}));class i{constructor($,W,X,G){this._cachedPath=[],this.parent=$,this.data=W,this._path=X,this._key=G}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var bW=($,W)=>{if(V$(W))return{success:!0,data:W.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let X=new Z($.common.issues);return this._error=X,this._error}}}};function w($){if(!$)return{};let{errorMap:W,invalid_type_error:X,required_error:G,description:J}=$;if(W&&(X||G))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(W)return{errorMap:W,description:J};return{errorMap:(Q,z)=>{let{message:H}=$;if(Q.code==="invalid_enum_value")return{message:H??z.defaultError};if(typeof z.data>"u")return{message:H??G??z.defaultError};if(Q.code!=="invalid_type")return{message:z.defaultError};return{message:H??X??z.defaultError}},description:J}}class F{get description(){return this._def.description}_getType($){return a($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:a($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new P,ctx:{common:$.parent.common,data:$.data,parsedType:a($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(g$(W))throw Error("Synchronous parse encountered promise.");return W}_parseAsync($){let W=this._parse($);return Promise.resolve(W)}parse($,W){let X=this.safeParse($,W);if(X.success)return X.data;throw X.error}safeParse($,W){let X={common:{issues:[],async:W?.async??!1,contextualErrorMap:W?.errorMap},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:a($)},G=this._parseSync({data:$,path:X.path,parent:X});return bW(X,G)}"~validate"($){let W={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:a($)};if(!this["~standard"].async)try{let X=this._parseSync({data:$,path:[],parent:W});return V$(X)?{value:X.value}:{issues:W.common.issues}}catch(X){if(X?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;W.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:W}).then((X)=>V$(X)?{value:X.value}:{issues:W.common.issues})}async parseAsync($,W){let X=await this.safeParseAsync($,W);if(X.success)return X.data;throw X.error}async safeParseAsync($,W){let X={common:{issues:[],contextualErrorMap:W?.errorMap,async:!0},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:a($)},G=this._parse({data:$,path:X.path,parent:X}),J=await(g$(G)?G:Promise.resolve(G));return bW(X,J)}refine($,W){let X=(G)=>{if(typeof W==="string"||typeof W>"u")return{message:W};else if(typeof W==="function")return W(G);else return W};return this._refinement((G,J)=>{let Y=$(G),Q=()=>J.addIssue({code:V.custom,...X(G)});if(typeof Promise<"u"&&Y instanceof Promise)return Y.then((z)=>{if(!z)return Q(),!1;else return!0});if(!Y)return Q(),!1;else return!0})}refinement($,W){return this._refinement((X,G)=>{if(!$(X))return G.addIssue(typeof W==="function"?W(X,G):W),!1;else return!0})}_refinement($){return new n({schema:this,typeName:N.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(W)=>this["~validate"](W)}}optional(){return d.create(this,this._def)}nullable(){return G$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return p.create(this)}promise(){return R$.create(this,this._def)}or($){return u$.create([this,$],this._def)}and($){return p$.create(this,$,this._def)}transform($){return new n({...w(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new a$({...w(this._def),innerType:this,defaultValue:W,typeName:N.ZodDefault})}brand(){return new Y8({typeName:N.ZodBranded,type:this,...w(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new o$({...w(this._def),innerType:this,catchValue:W,typeName:N.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return S0.create(this,$)}readonly(){return r$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var J6=/^c[^\s-]{8,}$/i,Y6=/^[0-9a-z]+$/,Q6=/^[0-9A-HJKMNP-TV-Z]{26}$/i,z6=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,H6=/^[a-z0-9_-]{21}$/i,V6=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,q6=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,_6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,B6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",g8,M6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,U6=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,N6=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,K6=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,O6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,w6=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ZW="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",D6=new RegExp(`^${ZW}$`);function vW($){let W="[0-5]\\d";if($.precision)W=`${W}\\.\\d{${$.precision}}`;else if($.precision==null)W=`${W}(\\.\\d+)?`;let X=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${W})${X}`}function L6($){return new RegExp(`^${vW($)}$`)}function gW($){let W=`${ZW}T${vW($)}`,X=[];if(X.push($.local?"Z?":"Z"),$.offset)X.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${X.join("|")})`,new RegExp(`^${W}$`)}function F6($,W){if((W==="v4"||!W)&&M6.test($))return!0;if((W==="v6"||!W)&&N6.test($))return!0;return!1}function j6($,W){if(!V6.test($))return!1;try{let[X]=$.split(".");if(!X)return!1;let G=X.replace(/-/g,"+").replace(/_/g,"/").padEnd(X.length+(4-X.length%4)%4,"="),J=JSON.parse(atob(G));if(typeof J!=="object"||J===null)return!1;if("typ"in J&&J?.typ!=="JWT")return!1;if(!J.alg)return!1;if(W&&J.alg!==W)return!1;return!0}catch{return!1}}function S6($,W){if((W==="v4"||!W)&&U6.test($))return!0;if((W==="v6"||!W)&&K6.test($))return!0;return!1}class u extends F{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==_.string){let J=this._getOrReturnCtx($);return B(J,{code:V.invalid_type,expected:_.string,received:J.parsedType}),U}let X=new P,G=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.length<J.value)G=this._getOrReturnCtx($,G),B(G,{code:V.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="max"){if($.data.length>J.value)G=this._getOrReturnCtx($,G),B(G,{code:V.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="length"){let Y=$.data.length>J.value,Q=$.data.length<J.value;if(Y||Q){if(G=this._getOrReturnCtx($,G),Y)B(G,{code:V.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});else if(Q)B(G,{code:V.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});X.dirty()}}else if(J.kind==="email"){if(!_6.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"email",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="emoji"){if(!g8)g8=new RegExp(B6,"u");if(!g8.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"emoji",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="uuid"){if(!z6.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"uuid",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="nanoid"){if(!H6.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"nanoid",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="cuid"){if(!J6.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"cuid",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="cuid2"){if(!Y6.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"cuid2",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="ulid"){if(!Q6.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"ulid",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="url")try{new URL($.data)}catch{G=this._getOrReturnCtx($,G),B(G,{validation:"url",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="regex"){if(J.regex.lastIndex=0,!J.regex.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"regex",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="trim")$.data=$.data.trim();else if(J.kind==="includes"){if(!$.data.includes(J.value,J.position))G=this._getOrReturnCtx($,G),B(G,{code:V.invalid_string,validation:{includes:J.value,position:J.position},message:J.message}),X.dirty()}else if(J.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(J.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(J.kind==="startsWith"){if(!$.data.startsWith(J.value))G=this._getOrReturnCtx($,G),B(G,{code:V.invalid_string,validation:{startsWith:J.value},message:J.message}),X.dirty()}else if(J.kind==="endsWith"){if(!$.data.endsWith(J.value))G=this._getOrReturnCtx($,G),B(G,{code:V.invalid_string,validation:{endsWith:J.value},message:J.message}),X.dirty()}else if(J.kind==="datetime"){if(!gW(J).test($.data))G=this._getOrReturnCtx($,G),B(G,{code:V.invalid_string,validation:"datetime",message:J.message}),X.dirty()}else if(J.kind==="date"){if(!D6.test($.data))G=this._getOrReturnCtx($,G),B(G,{code:V.invalid_string,validation:"date",message:J.message}),X.dirty()}else if(J.kind==="time"){if(!L6(J).test($.data))G=this._getOrReturnCtx($,G),B(G,{code:V.invalid_string,validation:"time",message:J.message}),X.dirty()}else if(J.kind==="duration"){if(!q6.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"duration",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="ip"){if(!F6($.data,J.version))G=this._getOrReturnCtx($,G),B(G,{validation:"ip",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="jwt"){if(!j6($.data,J.alg))G=this._getOrReturnCtx($,G),B(G,{validation:"jwt",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="cidr"){if(!S6($.data,J.version))G=this._getOrReturnCtx($,G),B(G,{validation:"cidr",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="base64"){if(!O6.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"base64",code:V.invalid_string,message:J.message}),X.dirty()}else if(J.kind==="base64url"){if(!w6.test($.data))G=this._getOrReturnCtx($,G),B(G,{validation:"base64url",code:V.invalid_string,message:J.message}),X.dirty()}else j.assertNever(J);return{status:X.value,value:$.data}}_regex($,W,X){return this.refinement((G)=>$.test(G),{validation:W,code:V.invalid_string,...M.errToObj(X)})}_addCheck($){return new u({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...M.errToObj($)})}url($){return this._addCheck({kind:"url",...M.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...M.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...M.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...M.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...M.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...M.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...M.errToObj($)})}base64($){return this._addCheck({kind:"base64",...M.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...M.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...M.errToObj($)})}ip($){return this._addCheck({kind:"ip",...M.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...M.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...M.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...M.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...M.errToObj($)})}regex($,W){return this._addCheck({kind:"regex",regex:$,...M.errToObj(W)})}includes($,W){return this._addCheck({kind:"includes",value:$,position:W?.position,...M.errToObj(W?.message)})}startsWith($,W){return this._addCheck({kind:"startsWith",value:$,...M.errToObj(W)})}endsWith($,W){return this._addCheck({kind:"endsWith",value:$,...M.errToObj(W)})}min($,W){return this._addCheck({kind:"min",value:$,...M.errToObj(W)})}max($,W){return this._addCheck({kind:"max",value:$,...M.errToObj(W)})}length($,W){return this._addCheck({kind:"length",value:$,...M.errToObj(W)})}nonempty($){return this.min(1,M.errToObj($))}trim(){return new u({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new u({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new u({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxLength(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}u.create=($)=>{return new u({checks:[],typeName:N.ZodString,coerce:$?.coerce??!1,...w($)})};function E6($,W){let X=($.toString().split(".")[1]||"").length,G=(W.toString().split(".")[1]||"").length,J=X>G?X:G,Y=Number.parseInt($.toFixed(J).replace(".","")),Q=Number.parseInt(W.toFixed(J).replace(".",""));return Y%Q/10**J}class _$ extends F{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==_.number){let J=this._getOrReturnCtx($);return B(J,{code:V.invalid_type,expected:_.number,received:J.parsedType}),U}let X=void 0,G=new P;for(let J of this._def.checks)if(J.kind==="int"){if(!j.isInteger($.data))X=this._getOrReturnCtx($,X),B(X,{code:V.invalid_type,expected:"integer",received:"float",message:J.message}),G.dirty()}else if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)X=this._getOrReturnCtx($,X),B(X,{code:V.too_small,minimum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),G.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)X=this._getOrReturnCtx($,X),B(X,{code:V.too_big,maximum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),G.dirty()}else if(J.kind==="multipleOf"){if(E6($.data,J.value)!==0)X=this._getOrReturnCtx($,X),B(X,{code:V.not_multiple_of,multipleOf:J.value,message:J.message}),G.dirty()}else if(J.kind==="finite"){if(!Number.isFinite($.data))X=this._getOrReturnCtx($,X),B(X,{code:V.not_finite,message:J.message}),G.dirty()}else j.assertNever(J);return{status:G.value,value:$.data}}gte($,W){return this.setLimit("min",$,!0,M.toString(W))}gt($,W){return this.setLimit("min",$,!1,M.toString(W))}lte($,W){return this.setLimit("max",$,!0,M.toString(W))}lt($,W){return this.setLimit("max",$,!1,M.toString(W))}setLimit($,W,X,G){return new _$({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:X,message:M.toString(G)}]})}_addCheck($){return new _$({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:M.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:M.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:M.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:M.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:M.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:M.toString(W)})}finite($){return this._addCheck({kind:"finite",message:M.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:M.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:M.toString($)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&j.isInteger($.value))}get isFinite(){let $=null,W=null;for(let X of this._def.checks)if(X.kind==="finite"||X.kind==="int"||X.kind==="multipleOf")return!0;else if(X.kind==="min"){if(W===null||X.value>W)W=X.value}else if(X.kind==="max"){if($===null||X.value<$)$=X.value}return Number.isFinite(W)&&Number.isFinite($)}}_$.create=($)=>{return new _$({checks:[],typeName:N.ZodNumber,coerce:$?.coerce||!1,...w($)})};class B$ extends F{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==_.bigint)return this._getInvalidInput($);let X=void 0,G=new P;for(let J of this._def.checks)if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)X=this._getOrReturnCtx($,X),B(X,{code:V.too_small,type:"bigint",minimum:J.value,inclusive:J.inclusive,message:J.message}),G.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)X=this._getOrReturnCtx($,X),B(X,{code:V.too_big,type:"bigint",maximum:J.value,inclusive:J.inclusive,message:J.message}),G.dirty()}else if(J.kind==="multipleOf"){if($.data%J.value!==BigInt(0))X=this._getOrReturnCtx($,X),B(X,{code:V.not_multiple_of,multipleOf:J.value,message:J.message}),G.dirty()}else j.assertNever(J);return{status:G.value,value:$.data}}_getInvalidInput($){let W=this._getOrReturnCtx($);return B(W,{code:V.invalid_type,expected:_.bigint,received:W.parsedType}),U}gte($,W){return this.setLimit("min",$,!0,M.toString(W))}gt($,W){return this.setLimit("min",$,!1,M.toString(W))}lte($,W){return this.setLimit("max",$,!0,M.toString(W))}lt($,W){return this.setLimit("max",$,!1,M.toString(W))}setLimit($,W,X,G){return new B$({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:X,message:M.toString(G)}]})}_addCheck($){return new B$({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:M.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:M.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:M.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:M.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:M.toString(W)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}B$.create=($)=>{return new B$({checks:[],typeName:N.ZodBigInt,coerce:$?.coerce??!1,...w($)})};class m$ extends F{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==_.boolean){let X=this._getOrReturnCtx($);return B(X,{code:V.invalid_type,expected:_.boolean,received:X.parsedType}),U}return x($.data)}}m$.create=($)=>{return new m$({typeName:N.ZodBoolean,coerce:$?.coerce||!1,...w($)})};class j$ extends F{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==_.date){let J=this._getOrReturnCtx($);return B(J,{code:V.invalid_type,expected:_.date,received:J.parsedType}),U}if(Number.isNaN($.data.getTime())){let J=this._getOrReturnCtx($);return B(J,{code:V.invalid_date}),U}let X=new P,G=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.getTime()<J.value)G=this._getOrReturnCtx($,G),B(G,{code:V.too_small,message:J.message,inclusive:!0,exact:!1,minimum:J.value,type:"date"}),X.dirty()}else if(J.kind==="max"){if($.data.getTime()>J.value)G=this._getOrReturnCtx($,G),B(G,{code:V.too_big,message:J.message,inclusive:!0,exact:!1,maximum:J.value,type:"date"}),X.dirty()}else j.assertNever(J);return{status:X.value,value:new Date($.data.getTime())}}_addCheck($){return new j$({...this._def,checks:[...this._def.checks,$]})}min($,W){return this._addCheck({kind:"min",value:$.getTime(),message:M.toString(W)})}max($,W){return this._addCheck({kind:"max",value:$.getTime(),message:M.toString(W)})}get minDate(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $!=null?new Date($):null}}j$.create=($)=>{return new j$({checks:[],coerce:$?.coerce||!1,typeName:N.ZodDate,...w($)})};class w0 extends F{_parse($){if(this._getType($)!==_.symbol){let X=this._getOrReturnCtx($);return B(X,{code:V.invalid_type,expected:_.symbol,received:X.parsedType}),U}return x($.data)}}w0.create=($)=>{return new w0({typeName:N.ZodSymbol,...w($)})};class l$ extends F{_parse($){if(this._getType($)!==_.undefined){let X=this._getOrReturnCtx($);return B(X,{code:V.invalid_type,expected:_.undefined,received:X.parsedType}),U}return x($.data)}}l$.create=($)=>{return new l$({typeName:N.ZodUndefined,...w($)})};class c$ extends F{_parse($){if(this._getType($)!==_.null){let X=this._getOrReturnCtx($);return B(X,{code:V.invalid_type,expected:_.null,received:X.parsedType}),U}return x($.data)}}c$.create=($)=>{return new c$({typeName:N.ZodNull,...w($)})};class S$ extends F{constructor(){super(...arguments);this._any=!0}_parse($){return x($.data)}}S$.create=($)=>{return new S$({typeName:N.ZodAny,...w($)})};class q$ extends F{constructor(){super(...arguments);this._unknown=!0}_parse($){return x($.data)}}q$.create=($)=>{return new q$({typeName:N.ZodUnknown,...w($)})};class o extends F{_parse($){let W=this._getOrReturnCtx($);return B(W,{code:V.invalid_type,expected:_.never,received:W.parsedType}),U}}o.create=($)=>{return new o({typeName:N.ZodNever,...w($)})};class D0 extends F{_parse($){if(this._getType($)!==_.undefined){let X=this._getOrReturnCtx($);return B(X,{code:V.invalid_type,expected:_.void,received:X.parsedType}),U}return x($.data)}}D0.create=($)=>{return new D0({typeName:N.ZodVoid,...w($)})};class p extends F{_parse($){let{ctx:W,status:X}=this._processInputParams($),G=this._def;if(W.parsedType!==_.array)return B(W,{code:V.invalid_type,expected:_.array,received:W.parsedType}),U;if(G.exactLength!==null){let Y=W.data.length>G.exactLength.value,Q=W.data.length<G.exactLength.value;if(Y||Q)B(W,{code:Y?V.too_big:V.too_small,minimum:Q?G.exactLength.value:void 0,maximum:Y?G.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:G.exactLength.message}),X.dirty()}if(G.minLength!==null){if(W.data.length<G.minLength.value)B(W,{code:V.too_small,minimum:G.minLength.value,type:"array",inclusive:!0,exact:!1,message:G.minLength.message}),X.dirty()}if(G.maxLength!==null){if(W.data.length>G.maxLength.value)B(W,{code:V.too_big,maximum:G.maxLength.value,type:"array",inclusive:!0,exact:!1,message:G.maxLength.message}),X.dirty()}if(W.common.async)return Promise.all([...W.data].map((Y,Q)=>{return G.type._parseAsync(new i(W,Y,W.path,Q))})).then((Y)=>{return P.mergeArray(X,Y)});let J=[...W.data].map((Y,Q)=>{return G.type._parseSync(new i(W,Y,W.path,Q))});return P.mergeArray(X,J)}get element(){return this._def.type}min($,W){return new p({...this._def,minLength:{value:$,message:M.toString(W)}})}max($,W){return new p({...this._def,maxLength:{value:$,message:M.toString(W)}})}length($,W){return new p({...this._def,exactLength:{value:$,message:M.toString(W)}})}nonempty($){return this.min(1,$)}}p.create=($,W)=>{return new p({type:$,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...w(W)})};function y$($){if($ instanceof E){let W={};for(let X in $.shape){let G=$.shape[X];W[X]=d.create(y$(G))}return new E({...$._def,shape:()=>W})}else if($ instanceof p)return new p({...$._def,type:y$($.element)});else if($ instanceof d)return d.create(y$($.unwrap()));else if($ instanceof G$)return G$.create(y$($.unwrap()));else if($ instanceof r)return r.create($.items.map((W)=>y$(W)));else return $}class E extends F{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),W=j.objectKeys($);return this._cached={shape:$,keys:W},this._cached}_parse($){if(this._getType($)!==_.object){let H=this._getOrReturnCtx($);return B(H,{code:V.invalid_type,expected:_.object,received:H.parsedType}),U}let{status:X,ctx:G}=this._processInputParams($),{shape:J,keys:Y}=this._getCached(),Q=[];if(!(this._def.catchall instanceof o&&this._def.unknownKeys==="strip")){for(let H in G.data)if(!Y.includes(H))Q.push(H)}let z=[];for(let H of Y){let q=J[H],O=G.data[H];z.push({key:{status:"valid",value:H},value:q._parse(new i(G,O,G.path,H)),alwaysSet:H in G.data})}if(this._def.catchall instanceof o){let H=this._def.unknownKeys;if(H==="passthrough")for(let q of Q)z.push({key:{status:"valid",value:q},value:{status:"valid",value:G.data[q]}});else if(H==="strict"){if(Q.length>0)B(G,{code:V.unrecognized_keys,keys:Q}),X.dirty()}else if(H==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let H=this._def.catchall;for(let q of Q){let O=G.data[q];z.push({key:{status:"valid",value:q},value:H._parse(new i(G,O,G.path,q)),alwaysSet:q in G.data})}}if(G.common.async)return Promise.resolve().then(async()=>{let H=[];for(let q of z){let O=await q.key,R=await q.value;H.push({key:O,value:R,alwaysSet:q.alwaysSet})}return H}).then((H)=>{return P.mergeObjectSync(X,H)});else return P.mergeObjectSync(X,z)}get shape(){return this._def.shape()}strict($){return M.errToObj,new E({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(W,X)=>{let G=this._def.errorMap?.(W,X).message??X.defaultError;if(W.code==="unrecognized_keys")return{message:M.errToObj($).message??G};return{message:G}}}:{}})}strip(){return new E({...this._def,unknownKeys:"strip"})}passthrough(){return new E({...this._def,unknownKeys:"passthrough"})}extend($){return new E({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new E({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:N.ZodObject})}setKey($,W){return this.augment({[$]:W})}catchall($){return new E({...this._def,catchall:$})}pick($){let W={};for(let X of j.objectKeys($))if($[X]&&this.shape[X])W[X]=this.shape[X];return new E({...this._def,shape:()=>W})}omit($){let W={};for(let X of j.objectKeys(this.shape))if(!$[X])W[X]=this.shape[X];return new E({...this._def,shape:()=>W})}deepPartial(){return y$(this)}partial($){let W={};for(let X of j.objectKeys(this.shape)){let G=this.shape[X];if($&&!$[X])W[X]=G;else W[X]=G.optional()}return new E({...this._def,shape:()=>W})}required($){let W={};for(let X of j.objectKeys(this.shape))if($&&!$[X])W[X]=this.shape[X];else{let J=this.shape[X];while(J instanceof d)J=J._def.innerType;W[X]=J}return new E({...this._def,shape:()=>W})}keyof(){return yW(j.objectKeys(this.shape))}}E.create=($,W)=>{return new E({shape:()=>$,unknownKeys:"strip",catchall:o.create(),typeName:N.ZodObject,...w(W)})};E.strictCreate=($,W)=>{return new E({shape:()=>$,unknownKeys:"strict",catchall:o.create(),typeName:N.ZodObject,...w(W)})};E.lazycreate=($,W)=>{return new E({shape:$,unknownKeys:"strip",catchall:o.create(),typeName:N.ZodObject,...w(W)})};class u$ extends F{_parse($){let{ctx:W}=this._processInputParams($),X=this._def.options;function G(J){for(let Q of J)if(Q.result.status==="valid")return Q.result;for(let Q of J)if(Q.result.status==="dirty")return W.common.issues.push(...Q.ctx.common.issues),Q.result;let Y=J.map((Q)=>new Z(Q.ctx.common.issues));return B(W,{code:V.invalid_union,unionErrors:Y}),U}if(W.common.async)return Promise.all(X.map(async(J)=>{let Y={...W,common:{...W.common,issues:[]},parent:null};return{result:await J._parseAsync({data:W.data,path:W.path,parent:Y}),ctx:Y}})).then(G);else{let J=void 0,Y=[];for(let z of X){let H={...W,common:{...W.common,issues:[]},parent:null},q=z._parseSync({data:W.data,path:W.path,parent:H});if(q.status==="valid")return q;else if(q.status==="dirty"&&!J)J={result:q,ctx:H};if(H.common.issues.length)Y.push(H.common.issues)}if(J)return W.common.issues.push(...J.ctx.common.issues),J.result;let Q=Y.map((z)=>new Z(z));return B(W,{code:V.invalid_union,unionErrors:Q}),U}}get options(){return this._def.options}}u$.create=($,W)=>{return new u$({options:$,typeName:N.ZodUnion,...w(W)})};var X$=($)=>{if($ instanceof d$)return X$($.schema);else if($ instanceof n)return X$($.innerType());else if($ instanceof i$)return[$.value];else if($ instanceof M$)return $.options;else if($ instanceof n$)return j.objectValues($.enum);else if($ instanceof a$)return X$($._def.innerType);else if($ instanceof l$)return[void 0];else if($ instanceof c$)return[null];else if($ instanceof d)return[void 0,...X$($.unwrap())];else if($ instanceof G$)return[null,...X$($.unwrap())];else if($ instanceof Y8)return X$($.unwrap());else if($ instanceof r$)return X$($.unwrap());else if($ instanceof o$)return X$($._def.innerType);else return[]};class J8 extends F{_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==_.object)return B(W,{code:V.invalid_type,expected:_.object,received:W.parsedType}),U;let X=this.discriminator,G=W.data[X],J=this.optionsMap.get(G);if(!J)return B(W,{code:V.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[X]}),U;if(W.common.async)return J._parseAsync({data:W.data,path:W.path,parent:W});else return J._parseSync({data:W.data,path:W.path,parent:W})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,W,X){let G=new Map;for(let J of W){let Y=X$(J.shape[$]);if(!Y.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let Q of Y){if(G.has(Q))throw Error(`Discriminator property ${String($)} has duplicate value ${String(Q)}`);G.set(Q,J)}}return new J8({typeName:N.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:G,...w(X)})}}function y8($,W){let X=a($),G=a(W);if($===W)return{valid:!0,data:$};else if(X===_.object&&G===_.object){let J=j.objectKeys(W),Y=j.objectKeys($).filter((z)=>J.indexOf(z)!==-1),Q={...$,...W};for(let z of Y){let H=y8($[z],W[z]);if(!H.valid)return{valid:!1};Q[z]=H.data}return{valid:!0,data:Q}}else if(X===_.array&&G===_.array){if($.length!==W.length)return{valid:!1};let J=[];for(let Y=0;Y<$.length;Y++){let Q=$[Y],z=W[Y],H=y8(Q,z);if(!H.valid)return{valid:!1};J.push(H.data)}return{valid:!0,data:J}}else if(X===_.date&&G===_.date&&+$===+W)return{valid:!0,data:$};else return{valid:!1}}class p$ extends F{_parse($){let{status:W,ctx:X}=this._processInputParams($),G=(J,Y)=>{if(X8(J)||X8(Y))return U;let Q=y8(J.value,Y.value);if(!Q.valid)return B(X,{code:V.invalid_intersection_types}),U;if(G8(J)||G8(Y))W.dirty();return{status:W.value,value:Q.data}};if(X.common.async)return Promise.all([this._def.left._parseAsync({data:X.data,path:X.path,parent:X}),this._def.right._parseAsync({data:X.data,path:X.path,parent:X})]).then(([J,Y])=>G(J,Y));else return G(this._def.left._parseSync({data:X.data,path:X.path,parent:X}),this._def.right._parseSync({data:X.data,path:X.path,parent:X}))}}p$.create=($,W,X)=>{return new p$({left:$,right:W,typeName:N.ZodIntersection,...w(X)})};class r extends F{_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==_.array)return B(X,{code:V.invalid_type,expected:_.array,received:X.parsedType}),U;if(X.data.length<this._def.items.length)return B(X,{code:V.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),U;if(!this._def.rest&&X.data.length>this._def.items.length)B(X,{code:V.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W.dirty();let J=[...X.data].map((Y,Q)=>{let z=this._def.items[Q]||this._def.rest;if(!z)return null;return z._parse(new i(X,Y,X.path,Q))}).filter((Y)=>!!Y);if(X.common.async)return Promise.all(J).then((Y)=>{return P.mergeArray(W,Y)});else return P.mergeArray(W,J)}get items(){return this._def.items}rest($){return new r({...this._def,rest:$})}}r.create=($,W)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new r({items:$,typeName:N.ZodTuple,rest:null,...w(W)})};class L0 extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==_.object)return B(X,{code:V.invalid_type,expected:_.object,received:X.parsedType}),U;let G=[],J=this._def.keyType,Y=this._def.valueType;for(let Q in X.data)G.push({key:J._parse(new i(X,Q,X.path,Q)),value:Y._parse(new i(X,X.data[Q],X.path,Q)),alwaysSet:Q in X.data});if(X.common.async)return P.mergeObjectAsync(W,G);else return P.mergeObjectSync(W,G)}get element(){return this._def.valueType}static create($,W,X){if(W instanceof F)return new L0({keyType:$,valueType:W,typeName:N.ZodRecord,...w(X)});return new L0({keyType:u.create(),valueType:$,typeName:N.ZodRecord,...w(W)})}}class F0 extends F{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==_.map)return B(X,{code:V.invalid_type,expected:_.map,received:X.parsedType}),U;let G=this._def.keyType,J=this._def.valueType,Y=[...X.data.entries()].map(([Q,z],H)=>{return{key:G._parse(new i(X,Q,X.path,[H,"key"])),value:J._parse(new i(X,z,X.path,[H,"value"]))}});if(X.common.async){let Q=new Map;return Promise.resolve().then(async()=>{for(let z of Y){let H=await z.key,q=await z.value;if(H.status==="aborted"||q.status==="aborted")return U;if(H.status==="dirty"||q.status==="dirty")W.dirty();Q.set(H.value,q.value)}return{status:W.value,value:Q}})}else{let Q=new Map;for(let z of Y){let{key:H,value:q}=z;if(H.status==="aborted"||q.status==="aborted")return U;if(H.status==="dirty"||q.status==="dirty")W.dirty();Q.set(H.value,q.value)}return{status:W.value,value:Q}}}}F0.create=($,W,X)=>{return new F0({valueType:W,keyType:$,typeName:N.ZodMap,...w(X)})};class E$ extends F{_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.parsedType!==_.set)return B(X,{code:V.invalid_type,expected:_.set,received:X.parsedType}),U;let G=this._def;if(G.minSize!==null){if(X.data.size<G.minSize.value)B(X,{code:V.too_small,minimum:G.minSize.value,type:"set",inclusive:!0,exact:!1,message:G.minSize.message}),W.dirty()}if(G.maxSize!==null){if(X.data.size>G.maxSize.value)B(X,{code:V.too_big,maximum:G.maxSize.value,type:"set",inclusive:!0,exact:!1,message:G.maxSize.message}),W.dirty()}let J=this._def.valueType;function Y(z){let H=new Set;for(let q of z){if(q.status==="aborted")return U;if(q.status==="dirty")W.dirty();H.add(q.value)}return{status:W.value,value:H}}let Q=[...X.data.values()].map((z,H)=>J._parse(new i(X,z,X.path,H)));if(X.common.async)return Promise.all(Q).then((z)=>Y(z));else return Y(Q)}min($,W){return new E$({...this._def,minSize:{value:$,message:M.toString(W)}})}max($,W){return new E$({...this._def,maxSize:{value:$,message:M.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}E$.create=($,W)=>{return new E$({valueType:$,minSize:null,maxSize:null,typeName:N.ZodSet,...w(W)})};class h$ extends F{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==_.function)return B(W,{code:V.invalid_type,expected:_.function,received:W.parsedType}),U;function X(Q,z){return O0({data:Q,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,v$(),W$].filter((H)=>!!H),issueData:{code:V.invalid_arguments,argumentsError:z}})}function G(Q,z){return O0({data:Q,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,v$(),W$].filter((H)=>!!H),issueData:{code:V.invalid_return_type,returnTypeError:z}})}let J={errorMap:W.common.contextualErrorMap},Y=W.data;if(this._def.returns instanceof R$){let Q=this;return x(async function(...z){let H=new Z([]),q=await Q._def.args.parseAsync(z,J).catch((l)=>{throw H.addIssue(X(z,l)),H}),O=await Reflect.apply(Y,this,q);return await Q._def.returns._def.type.parseAsync(O,J).catch((l)=>{throw H.addIssue(G(O,l)),H})})}else{let Q=this;return x(function(...z){let H=Q._def.args.safeParse(z,J);if(!H.success)throw new Z([X(z,H.error)]);let q=Reflect.apply(Y,this,H.data),O=Q._def.returns.safeParse(q,J);if(!O.success)throw new Z([G(q,O.error)]);return O.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new h$({...this._def,args:r.create($).rest(q$.create())})}returns($){return new h$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,X){return new h$({args:$?$:r.create([]).rest(q$.create()),returns:W||q$.create(),typeName:N.ZodFunction,...w(X)})}}class d$ extends F{get schema(){return this._def.getter()}_parse($){let{ctx:W}=this._processInputParams($);return this._def.getter()._parse({data:W.data,path:W.path,parent:W})}}d$.create=($,W)=>{return new d$({getter:$,typeName:N.ZodLazy,...w(W)})};class i$ extends F{_parse($){if($.data!==this._def.value){let W=this._getOrReturnCtx($);return B(W,{received:W.data,code:V.invalid_literal,expected:this._def.value}),U}return{status:"valid",value:$.data}}get value(){return this._def.value}}i$.create=($,W)=>{return new i$({value:$,typeName:N.ZodLiteral,...w(W)})};function yW($,W){return new M$({values:$,typeName:N.ZodEnum,...w(W)})}class M$ extends F{_parse($){if(typeof $.data!=="string"){let W=this._getOrReturnCtx($),X=this._def.values;return B(W,{expected:j.joinValues(X),received:W.parsedType,code:V.invalid_type}),U}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let W=this._getOrReturnCtx($),X=this._def.values;return B(W,{received:W.data,code:V.invalid_enum_value,options:X}),U}return x($.data)}get options(){return this._def.values}get enum(){let $={};for(let W of this._def.values)$[W]=W;return $}get Values(){let $={};for(let W of this._def.values)$[W]=W;return $}get Enum(){let $={};for(let W of this._def.values)$[W]=W;return $}extract($,W=this._def){return M$.create($,{...this._def,...W})}exclude($,W=this._def){return M$.create(this.options.filter((X)=>!$.includes(X)),{...this._def,...W})}}M$.create=yW;class n$ extends F{_parse($){let W=j.getValidEnumValues(this._def.values),X=this._getOrReturnCtx($);if(X.parsedType!==_.string&&X.parsedType!==_.number){let G=j.objectValues(W);return B(X,{expected:j.joinValues(G),received:X.parsedType,code:V.invalid_type}),U}if(!this._cache)this._cache=new Set(j.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let G=j.objectValues(W);return B(X,{received:X.data,code:V.invalid_enum_value,options:G}),U}return x($.data)}get enum(){return this._def.values}}n$.create=($,W)=>{return new n$({values:$,typeName:N.ZodNativeEnum,...w(W)})};class R$ extends F{unwrap(){return this._def.type}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==_.promise&&W.common.async===!1)return B(W,{code:V.invalid_type,expected:_.promise,received:W.parsedType}),U;let X=W.parsedType===_.promise?W.data:Promise.resolve(W.data);return x(X.then((G)=>{return this._def.type.parseAsync(G,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}R$.create=($,W)=>{return new R$({type:$,typeName:N.ZodPromise,...w(W)})};class n extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:W,ctx:X}=this._processInputParams($),G=this._def.effect||null,J={addIssue:(Y)=>{if(B(X,Y),Y.fatal)W.abort();else W.dirty()},get path(){return X.path}};if(J.addIssue=J.addIssue.bind(J),G.type==="preprocess"){let Y=G.transform(X.data,J);if(X.common.async)return Promise.resolve(Y).then(async(Q)=>{if(W.value==="aborted")return U;let z=await this._def.schema._parseAsync({data:Q,path:X.path,parent:X});if(z.status==="aborted")return U;if(z.status==="dirty")return F$(z.value);if(W.value==="dirty")return F$(z.value);return z});else{if(W.value==="aborted")return U;let Q=this._def.schema._parseSync({data:Y,path:X.path,parent:X});if(Q.status==="aborted")return U;if(Q.status==="dirty")return F$(Q.value);if(W.value==="dirty")return F$(Q.value);return Q}}if(G.type==="refinement"){let Y=(Q)=>{let z=G.refinement(Q,J);if(X.common.async)return Promise.resolve(z);if(z instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Q};if(X.common.async===!1){let Q=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(Q.status==="aborted")return U;if(Q.status==="dirty")W.dirty();return Y(Q.value),{status:W.value,value:Q.value}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((Q)=>{if(Q.status==="aborted")return U;if(Q.status==="dirty")W.dirty();return Y(Q.value).then(()=>{return{status:W.value,value:Q.value}})})}if(G.type==="transform")if(X.common.async===!1){let Y=this._def.schema._parseSync({data:X.data,path:X.path,parent:X});if(!V$(Y))return U;let Q=G.transform(Y.value,J);if(Q instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:W.value,value:Q}}else return this._def.schema._parseAsync({data:X.data,path:X.path,parent:X}).then((Y)=>{if(!V$(Y))return U;return Promise.resolve(G.transform(Y.value,J)).then((Q)=>({status:W.value,value:Q}))});j.assertNever(G)}}n.create=($,W,X)=>{return new n({schema:$,typeName:N.ZodEffects,effect:W,...w(X)})};n.createWithPreprocess=($,W,X)=>{return new n({schema:W,effect:{type:"preprocess",transform:$},typeName:N.ZodEffects,...w(X)})};class d extends F{_parse($){if(this._getType($)===_.undefined)return x(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}d.create=($,W)=>{return new d({innerType:$,typeName:N.ZodOptional,...w(W)})};class G$ extends F{_parse($){if(this._getType($)===_.null)return x(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}G$.create=($,W)=>{return new G$({innerType:$,typeName:N.ZodNullable,...w(W)})};class a$ extends F{_parse($){let{ctx:W}=this._processInputParams($),X=W.data;if(W.parsedType===_.undefined)X=this._def.defaultValue();return this._def.innerType._parse({data:X,path:W.path,parent:W})}removeDefault(){return this._def.innerType}}a$.create=($,W)=>{return new a$({innerType:$,typeName:N.ZodDefault,defaultValue:typeof W.default==="function"?W.default:()=>W.default,...w(W)})};class o$ extends F{_parse($){let{ctx:W}=this._processInputParams($),X={...W,common:{...W.common,issues:[]}},G=this._def.innerType._parse({data:X.data,path:X.path,parent:{...X}});if(g$(G))return G.then((J)=>{return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new Z(X.common.issues)},input:X.data})}});else return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new Z(X.common.issues)},input:X.data})}}removeCatch(){return this._def.innerType}}o$.create=($,W)=>{return new o$({innerType:$,typeName:N.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...w(W)})};class j0 extends F{_parse($){if(this._getType($)!==_.nan){let X=this._getOrReturnCtx($);return B(X,{code:V.invalid_type,expected:_.nan,received:X.parsedType}),U}return{status:"valid",value:$.data}}}j0.create=($)=>{return new j0({typeName:N.ZodNaN,...w($)})};var R6=Symbol("zod_brand");class Y8 extends F{_parse($){let{ctx:W}=this._processInputParams($),X=W.data;return this._def.type._parse({data:X,path:W.path,parent:W})}unwrap(){return this._def.type}}class S0 extends F{_parse($){let{status:W,ctx:X}=this._processInputParams($);if(X.common.async)return(async()=>{let J=await this._def.in._parseAsync({data:X.data,path:X.path,parent:X});if(J.status==="aborted")return U;if(J.status==="dirty")return W.dirty(),F$(J.value);else return this._def.out._parseAsync({data:J.value,path:X.path,parent:X})})();else{let G=this._def.in._parseSync({data:X.data,path:X.path,parent:X});if(G.status==="aborted")return U;if(G.status==="dirty")return W.dirty(),{status:"dirty",value:G.value};else return this._def.out._parseSync({data:G.value,path:X.path,parent:X})}}static create($,W){return new S0({in:$,out:W,typeName:N.ZodPipeline})}}class r$ extends F{_parse($){let W=this._def.innerType._parse($),X=(G)=>{if(V$(G))G.value=Object.freeze(G.value);return G};return g$(W)?W.then((G)=>X(G)):X(W)}unwrap(){return this._def.innerType}}r$.create=($,W)=>{return new r$({innerType:$,typeName:N.ZodReadonly,...w(W)})};function xW($,W){let X=typeof $==="function"?$(W):typeof $==="string"?{message:$}:$;return typeof X==="string"?{message:X}:X}function hW($,W={},X){if($)return S$.create().superRefine((G,J)=>{let Y=$(G);if(Y instanceof Promise)return Y.then((Q)=>{if(!Q){let z=xW(W,G),H=z.fatal??X??!0;J.addIssue({code:"custom",...z,fatal:H})}});if(!Y){let Q=xW(W,G),z=Q.fatal??X??!0;J.addIssue({code:"custom",...Q,fatal:z})}return});return S$.create()}var A6={object:E.lazycreate},N;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(N||(N={}));var C6=($,W={message:`Input not instance of ${$.name}`})=>hW((X)=>X instanceof $,W),mW=u.create,lW=_$.create,f6=j0.create,T6=B$.create,cW=m$.create,P6=j$.create,k6=w0.create,I6=l$.create,b6=c$.create,x6=S$.create,Z6=q$.create,v6=o.create,g6=D0.create,y6=p.create,h6=E.create,m6=E.strictCreate,l6=u$.create,c6=J8.create,u6=p$.create,p6=r.create,d6=L0.create,i6=F0.create,n6=E$.create,a6=h$.create,o6=d$.create,r6=i$.create,t6=M$.create,s6=n$.create,e6=R$.create,$9=n.create,W9=d.create,X9=G$.create,G9=n.createWithPreprocess,J9=S0.create,Y9=()=>mW().optional(),Q9=()=>lW().optional(),z9=()=>cW().optional(),H9={string:($)=>u.create({...$,coerce:!0}),number:($)=>_$.create({...$,coerce:!0}),boolean:($)=>m$.create({...$,coerce:!0}),bigint:($)=>B$.create({...$,coerce:!0}),date:($)=>j$.create({...$,coerce:!0})};var V9=U;function uW($){return{name:"mem-recall",description:"Fetch full observation details by ID. Use after mem-search to get complete narratives, facts, concepts, and file lists for specific observations.",args:{ids:A.array(A.string()).describe("Observation IDs to fetch"),limit:A.number().min(1).max(50).default(10).describe("Maximum number of results")},execute:async(W)=>{try{let X=W.ids,G=W.limit||10,J=X.slice(0,G),Y=[];for(let Q of J){let z=$.getById(Q);if(z)Y.push(q9(z));else Y.push(`## ID: ${Q}
323
+ *Not found*`)}if(Y.length===0)return"No observation IDs provided.";return`Recalled ${Y.length} observation(s):
324
+
325
+ ${Y.join(`
326
+ ---
327
+ `)}`}catch(X){return`Recall error: ${X}`}}}}function q9($){let W=[];if(W.push(`## [${$.type.toUpperCase()}] ${$.title}`),$.subtitle)W.push(`*${$.subtitle}*`);if(W.push(`
328
+ ${$.narrative}`),$.facts.length>0){W.push(`
329
+ **Facts:**`);for(let X of $.facts)W.push(`- ${X}`)}if($.concepts.length>0)W.push(`
330
+ **Concepts:** ${$.concepts.join(", ")}`);if($.filesRead.length>0)W.push(`**Files read:** ${$.filesRead.join(", ")}`);if($.filesModified.length>0)W.push(`**Files modified:** ${$.filesModified.join(", ")}`);return W.push(`
331
+ *ID: ${$.id} | Created: ${$.createdAt} | Tokens: ${$.tokenCount}*`),W.join(`
332
+ `)}function pW($,W,X){return{name:"mem-save",description:`Manually save an observation to memory.
333
+ Use this to explicitly record important decisions, discoveries, or context
334
+ that should be remembered across sessions.`,args:{title:A.string().describe("Brief title for the observation (max 80 chars)"),type:A.enum(["decision","bugfix","feature","refactor","discovery","change"]).describe("Type of observation"),narrative:A.string().describe("Detailed description of what to remember"),concepts:A.array(A.string()).optional().describe("Related concepts/tags"),files:A.array(A.string()).optional().describe("Related file paths")},execute:async(G,J)=>{try{let{title:Y,type:Q,narrative:z}=G,H=G.concepts??[],q=G.files??[];W.getOrCreate(J.sessionID,X);let O=$.create({sessionId:J.sessionID,type:Q,title:Y,subtitle:"",facts:[],narrative:z,concepts:H,filesRead:[],filesModified:q,rawToolOutput:`[Manual save] ${z}`,toolName:"mem-save",tokenCount:H$(`${Y} ${z}`)});return W.incrementObservationCount(J.sessionID),`Saved observation: [${Q}] "${Y}" (ID: ${O.id})`}catch(Y){return`Save error: ${Y}`}}}}function dW($,W){return{name:"mem-search",description:`Search through past coding session observations and memories.
335
+ Use this tool to find relevant context from previous sessions, including:
336
+ - Past decisions and their rationale
337
+ - Bug fixes and their solutions
338
+ - Code patterns and discoveries
339
+ - File modification history
340
+ - Concept-based knowledge retrieval
341
+
342
+ Supports full-text search with FTS5.`,args:{query:A.string().describe("Search query (supports keywords, phrases, file paths)"),type:A.enum(["decision","bugfix","feature","refactor","discovery","change"]).optional().describe("Filter by observation type"),limit:A.number().min(1).max(50).default(10).describe("Maximum number of results")},execute:async(X)=>{try{let{query:G,type:J}=X,Y=X.limit||10,Q=$.search({query:G,type:J,limit:Y});if(Q.length===0){let z=W.search(G,Y);if(z.length===0)return"No matching observations or session summaries found.";return B9(z)}return _9(Q)}catch(G){return`Search error: ${G}`}}}}function _9($){let W=[`Found ${$.length} observation(s):
343
+ `];for(let{observation:X}of $){if(W.push(`## [${X.type.toUpperCase()}] ${X.title}`),X.subtitle)W.push(`*${X.subtitle}*`);if(W.push(`
344
+ ${X.narrative}`),X.facts.length>0){W.push(`
345
+ **Facts:**`);for(let G of X.facts)W.push(`- ${G}`)}if(X.concepts.length>0)W.push(`
346
+ **Concepts:** ${X.concepts.join(", ")}`);if(X.filesModified.length>0)W.push(`**Files modified:** ${X.filesModified.join(", ")}`);if(X.filesRead.length>0)W.push(`**Files read:** ${X.filesRead.join(", ")}`);W.push(`
347
+ *Session: ${X.sessionId} | ${X.createdAt}*`),W.push("---")}return W.join(`
348
+ `)}function B9($){let W=[`Found ${$.length} session summary(ies):
349
+ `];for(let X of $){if(W.push(`## Session: ${X.sessionId}`),W.push(X.summary),X.keyDecisions.length>0){W.push(`
350
+ **Key decisions:**`);for(let G of X.keyDecisions)W.push(`- ${G}`)}W.push("---")}return W.join(`
351
+ `)}function iW($,W,X,G){return{name:"mem-timeline",description:`View a timeline of past coding sessions for this project.
352
+ Shows recent sessions with summaries, observation counts, and key decisions.`,args:{limit:A.number().min(1).max(20).default(5).describe("Number of recent sessions to show"),sessionId:A.string().optional().describe("Show details for a specific session ID")},execute:async(J)=>{try{let Y=J.limit||5,Q=J.sessionId;if(Q)return M9(Q,$,W,X);let z=$.getRecent(G,Y);if(z.length===0)return"No past sessions found for this project.";let H=[`# Session Timeline (${z.length} sessions)
353
+ `];for(let q of z){let O=q.summaryId?W.getBySessionId(q.id):null;if(H.push(`## Session: ${q.id}`),H.push(`- **Started**: ${q.startedAt}`),H.push(`- **Status**: ${q.status}`),H.push(`- **Observations**: ${q.observationCount}`),O){if(H.push(`- **Summary**: ${O.summary}`),O.keyDecisions.length>0)H.push(`- **Key decisions**: ${O.keyDecisions.join("; ")}`)}H.push("")}return H.join(`
354
+ `)}catch(Y){return`Timeline error: ${Y}`}}}}function M9($,W,X,G){let J=W.getById($);if(!J)return`Session ${$} not found.`;let Y=J.summaryId?X.getBySessionId($):null,Q=G.getBySession($),z=[`# Session Detail: ${$}
355
+ `];if(z.push(`- **Started**: ${J.startedAt}`),z.push(`- **Ended**: ${J.endedAt??"Active"}`),z.push(`- **Status**: ${J.status}`),z.push(`- **Observations**: ${J.observationCount}`),Y){if(z.push(`
356
+ ## Summary
357
+ ${Y.summary}`),Y.keyDecisions.length>0){z.push(`
358
+ **Key decisions:**`);for(let H of Y.keyDecisions)z.push(`- ${H}`)}}if(Q.length>0){z.push(`
359
+ ## Observations`);for(let H of Q)if(z.push(`
360
+ ### [${H.type.toUpperCase()}] ${H.title}`),z.push(H.narrative),H.concepts.length>0)z.push(`*Concepts: ${H.concepts.join(", ")}*`)}return z.join(`
361
+ `)}async function U9($){let{directory:W}=$,X=T8(W),G=FW(X);for(let E0 of G)console.warn(`[open-mem] ${E0}`);await jW(X);let J=EW(X.dbPath);RW(J);let Y=new I8(J),Q=new P8(J),z=new b8(J),H=new k8(J),q=new K0(X),O=new f8(X),R=new Z8(X,q,O,H,Q,Y,z);R.start();let l=()=>{R.stop(),J.close()};return process.on("beforeExit",l),{"tool.execute.after":kW(X,R,Y,W),event:PW(R,Y,W),"experimental.chat.system.transform":TW(X,Q,Y,z,W),"experimental.session.compacting":fW(X,Q,Y,z,W),tools:[dW(Q,z),pW(Q,Y,W),iW(Y,z,Q,W),uW(Q)]}}export{T8 as resolveConfig,dX as getDefaultConfig,U9 as default};