claude-mem 10.3.1 → 10.3.2
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.
- package/README.md +1 -7
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/hooks/hooks.json +6 -1
- package/plugin/package.json +1 -1
- package/plugin/scripts/claude-mem +0 -0
- package/plugin/scripts/context-generator.cjs +6 -6
- package/plugin/scripts/mcp-server.cjs +2 -2
- package/plugin/scripts/worker-service.cjs +87 -87
- package/plugin/skills/mem-search/SKILL.md +0 -14
package/README.md
CHANGED
|
@@ -198,7 +198,7 @@ See [Architecture Overview](https://docs.claude-mem.ai/architecture/overview) fo
|
|
|
198
198
|
|
|
199
199
|
## MCP Search Tools
|
|
200
200
|
|
|
201
|
-
Claude-Mem provides intelligent memory search through **
|
|
201
|
+
Claude-Mem provides intelligent memory search through **4 MCP tools** following a token-efficient **3-layer workflow pattern**:
|
|
202
202
|
|
|
203
203
|
**The 3-Layer Workflow:**
|
|
204
204
|
|
|
@@ -211,7 +211,6 @@ Claude-Mem provides intelligent memory search through **5 MCP tools** following
|
|
|
211
211
|
- Start with `search` to get an index of results
|
|
212
212
|
- Use `timeline` to see what was happening around specific observations
|
|
213
213
|
- Use `get_observations` to fetch full details for relevant IDs
|
|
214
|
-
- Use `save_memory` to manually store important information
|
|
215
214
|
- **~10x token savings** by filtering before fetching details
|
|
216
215
|
|
|
217
216
|
**Available MCP Tools:**
|
|
@@ -219,8 +218,6 @@ Claude-Mem provides intelligent memory search through **5 MCP tools** following
|
|
|
219
218
|
1. **`search`** - Search memory index with full-text queries, filters by type/date/project
|
|
220
219
|
2. **`timeline`** - Get chronological context around a specific observation or query
|
|
221
220
|
3. **`get_observations`** - Fetch full observation details by IDs (always batch multiple IDs)
|
|
222
|
-
4. **`save_memory`** - Manually save a memory/observation for semantic search
|
|
223
|
-
5. **`__IMPORTANT`** - Workflow documentation (always visible to Claude)
|
|
224
221
|
|
|
225
222
|
**Example Usage:**
|
|
226
223
|
|
|
@@ -232,9 +229,6 @@ search(query="authentication bug", type="bugfix", limit=10)
|
|
|
232
229
|
|
|
233
230
|
// Step 3: Fetch full details
|
|
234
231
|
get_observations(ids=[123, 456])
|
|
235
|
-
|
|
236
|
-
// Save important information manually
|
|
237
|
-
save_memory(text="API requires auth header X-API-Key", title="API Auth")
|
|
238
232
|
```
|
|
239
233
|
|
|
240
234
|
See [Search Tools Guide](https://docs.claude-mem.ai/usage/search-tools) for detailed examples.
|
package/package.json
CHANGED
package/plugin/hooks/hooks.json
CHANGED
|
@@ -21,7 +21,12 @@
|
|
|
21
21
|
"type": "command",
|
|
22
22
|
"command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/smart-install.js\"",
|
|
23
23
|
"timeout": 300
|
|
24
|
-
}
|
|
24
|
+
}
|
|
25
|
+
]
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"matcher": "startup|clear|compact",
|
|
29
|
+
"hooks": [
|
|
25
30
|
{
|
|
26
31
|
"type": "command",
|
|
27
32
|
"command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/bun-runner.js\" \"${CLAUDE_PLUGIN_ROOT}/scripts/worker-service.cjs\" start",
|
package/plugin/package.json
CHANGED
|
Binary file
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var lt=Object.create;var k=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var Et=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,gt=Object.prototype.hasOwnProperty;var ft=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},se=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Et(e))!gt.call(r,n)&&n!==t&&k(r,n,{get:()=>e[n],enumerable:!(s=ut(e,n))||s.enumerable});return r};var L=(r,e,t)=>(t=r!=null?lt(Tt(r)):{},se(e||!r||!r.__esModule?k(t,"default",{value:r,enumerable:!0}):t,r)),St=r=>se(k({},"__esModule",{value:!0}),r);var xt={};ft(xt,{generateContext:()=>te});module.exports=St(xt);var ct=L(require("path"),1),_t=require("os"),mt=require("fs");var ue=require("bun:sqlite");var b=require("path"),de=require("os"),pe=require("fs");var ce=require("url");var
|
|
1
|
+
"use strict";var lt=Object.create;var k=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var Et=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,gt=Object.prototype.hasOwnProperty;var ft=(r,e)=>{for(var t in e)k(r,t,{get:e[t],enumerable:!0})},se=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Et(e))!gt.call(r,n)&&n!==t&&k(r,n,{get:()=>e[n],enumerable:!(s=ut(e,n))||s.enumerable});return r};var L=(r,e,t)=>(t=r!=null?lt(Tt(r)):{},se(e||!r||!r.__esModule?k(t,"default",{value:r,enumerable:!0}):t,r)),St=r=>se(k({},"__esModule",{value:!0}),r);var xt={};ft(xt,{generateContext:()=>te});module.exports=St(xt);var ct=L(require("path"),1),_t=require("os"),mt=require("fs");var ue=require("bun:sqlite");var b=require("path"),de=require("os"),pe=require("fs");var ce=require("url");var C=require("fs"),w=require("path"),oe=require("os");var re="bugfix,feature,refactor,discovery,decision,change",ne="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off";var I=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,w.join)((0,oe.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:re,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:ne,CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static getBool(e){let t=this.get(e);return t==="true"||t===!0}static applyEnvOverrides(e){let t={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(t[s]=process.env[s]);return t}static loadFromFile(e){try{if(!(0,C.existsSync)(e)){let i=this.getAllDefaults();try{let a=(0,w.dirname)(e);(0,C.existsSync)(a)||(0,C.mkdirSync)(a,{recursive:!0}),(0,C.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a)}return this.applyEnvOverrides(i)}let t=(0,C.readFileSync)(e,"utf-8"),s=JSON.parse(t),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{(0,C.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(i){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,i)}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(o[i]=n[i]);return this.applyEnvOverrides(o)}catch(t){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,t),this.applyEnvOverrides(this.getAllDefaults())}}};var A=require("fs"),v=require("path"),ae=require("os"),H=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(H||{}),ie=(0,v.join)((0,ae.homedir)(),".claude-mem"),W=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=(0,v.join)(ie,"logs");(0,A.existsSync)(e)||(0,A.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,v.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=(0,v.join)(ie,"settings.json");if((0,A.existsSync)(e)){let t=(0,A.readFileSync)(e,"utf-8"),n=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=H[n]??1}else this.level=1}catch{this.level=1}return this.level}correlationId(e,t){return`obs-${e}-${t}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
|
|
2
2
|
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let s=t;if(typeof t=="string")try{s=JSON.parse(t)}catch{s=t}if(e==="Bash"&&s.command)return`${e}(${s.command})`;if(s.file_path)return`${e}(${s.file_path})`;if(s.notebook_path)return`${e}(${s.notebook_path})`;if(e==="Glob"&&s.pattern)return`${e}(${s.pattern})`;if(e==="Grep"&&s.pattern)return`${e}(${s.pattern})`;if(s.url)return`${e}(${s.url})`;if(s.query)return`${e}(${s.query})`;if(e==="Task"){if(s.subagent_type)return`${e}(${s.subagent_type})`;if(s.description)return`${e}(${s.description})`}return e==="Skill"&&s.skill?`${e}(${s.skill})`:e==="LSP"&&s.operation?`${e}(${s.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),d=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${s}-${n} ${o}:${i}:${a}.${d}`}log(e,t,s,n,o){if(e<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),a=H[e].padEnd(5),d=t.padEnd(6),c="";n?.correlationId?c=`[${n.correlationId}] `:n?.sessionId&&(c=`[session-${n.sessionId}] `);let m="";o!=null&&(o instanceof Error?m=this.getLevel()===0?`
|
|
3
3
|
${o.message}
|
|
4
4
|
${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
|
|
@@ -6,7 +6,7 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
|
|
|
6
6
|
`,"utf8")}catch(E){process.stderr.write(`[LOGGER] Failed to write to log file: ${E}
|
|
7
7
|
`)}else process.stderr.write(T+`
|
|
8
8
|
`)}debug(e,t,s,n){this.log(0,e,t,s,n)}info(e,t,s,n){this.log(1,e,t,s,n)}warn(e,t,s,n){this.log(2,e,t,s,n)}error(e,t,s,n){this.log(3,e,t,s,n)}dataIn(e,t,s,n){this.info(e,`\u2192 ${t}`,s,n)}dataOut(e,t,s,n){this.info(e,`\u2190 ${t}`,s,n)}success(e,t,s,n){this.info(e,`\u2713 ${t}`,s,n)}failure(e,t,s,n){this.error(e,`\u2717 ${t}`,s,n)}timing(e,t,s,n){this.info(e,`\u23F1 ${t}`,n,{duration:`${s}ms`})}happyPathError(e,t,s,n,o=""){let c=((new Error().stack||"").split(`
|
|
9
|
-
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),m=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",l={...s,location:m};return this.warn(e,`[HAPPY-PATH] ${t}`,l,n),o}},_=new W;var Ot={};function bt(){return typeof __dirname<"u"?__dirname:(0,b.dirname)((0,ce.fileURLToPath)(Ot.url))}var ht=bt(),
|
|
9
|
+
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),m=c?`${c[1].split("/").pop()}:${c[2]}`:"unknown",l={...s,location:m};return this.warn(e,`[HAPPY-PATH] ${t}`,l,n),o}},_=new W;var Ot={};function bt(){return typeof __dirname<"u"?__dirname:(0,b.dirname)((0,ce.fileURLToPath)(Ot.url))}var ht=bt(),N=I.get("CLAUDE_MEM_DATA_DIR"),y=process.env.CLAUDE_CONFIG_DIR||(0,b.join)((0,de.homedir)(),".claude"),Bt=(0,b.join)(y,"plugins","marketplaces","thedotmack"),Ht=(0,b.join)(N,"archives"),Wt=(0,b.join)(N,"logs"),Yt=(0,b.join)(N,"trash"),Vt=(0,b.join)(N,"backups"),qt=(0,b.join)(N,"modes"),Kt=(0,b.join)(N,"settings.json"),_e=(0,b.join)(N,"claude-mem.db"),Jt=(0,b.join)(N,"vector-db"),Qt=(0,b.join)(N,"observer-sessions"),zt=(0,b.join)(y,"settings.json"),Zt=(0,b.join)(y,"commands"),es=(0,b.join)(y,"CLAUDE.md");function me(r){(0,pe.mkdirSync)(r,{recursive:!0})}function le(){return(0,b.join)(ht,"..")}var $=class{db;constructor(e=_e){e!==":memory:"&&me(N),this.db=new ue.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn(),this.createPendingMessagesTable(),this.renameSessionIdColumns(),this.repairSessionIdColumnRename(),this.addFailedAtEpochColumn(),this.addOnUpdateCascadeToForeignKeys()}initializeSchema(){this.db.run(`
|
|
10
10
|
CREATE TABLE IF NOT EXISTS schema_versions (
|
|
11
11
|
id INTEGER PRIMARY KEY,
|
|
12
12
|
version INTEGER UNIQUE NOT NULL,
|
|
@@ -637,14 +637,14 @@ ${o.stack}`:` ${o.message}`:this.getLevel()===0&&typeof o=="object"?m=`
|
|
|
637
637
|
WHERE project IN (${s})
|
|
638
638
|
ORDER BY created_at_epoch DESC
|
|
639
639
|
LIMIT ?
|
|
640
|
-
`).all(...e,t.sessionCount+V)}function
|
|
641
|
-
`).filter(n=>n.trim()),s="";for(let n=t.length-1;n>=0;n--)try{let o=t[n];if(!o.includes('"type":"assistant"'))continue;let i=JSON.parse(o);if(i.type==="assistant"&&i.message?.content&&Array.isArray(i.message.content)){let a="";for(let d of i.message.content)d.type==="text"&&(a+=d.text);if(a=a.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"").trim(),a){s=a;break}}}catch(o){_.debug("PARSER","Skipping malformed transcript line",{lineIndex:n},o);continue}return{userMessage:"",assistantMessage:s}}catch(e){return _.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e),{userMessage:"",assistantMessage:""}}}function z(r,e,t,s){if(!e.showLastMessage||r.length===0)return{userMessage:"",assistantMessage:""};let n=r.find(d=>d.memory_session_id!==t);if(!n)return{userMessage:"",assistantMessage:""};let o=n.memory_session_id,i=
|
|
640
|
+
`).all(...e,t.sessionCount+V)}function Nt(r){return r.replace(/\//g,"-")}function Ct(r){try{if(!(0,X.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,X.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(`
|
|
641
|
+
`).filter(n=>n.trim()),s="";for(let n=t.length-1;n>=0;n--)try{let o=t[n];if(!o.includes('"type":"assistant"'))continue;let i=JSON.parse(o);if(i.type==="assistant"&&i.message?.content&&Array.isArray(i.message.content)){let a="";for(let d of i.message.content)d.type==="text"&&(a+=d.text);if(a=a.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g,"").trim(),a){s=a;break}}}catch(o){_.debug("PARSER","Skipping malformed transcript line",{lineIndex:n},o);continue}return{userMessage:"",assistantMessage:s}}catch(e){return _.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e),{userMessage:"",assistantMessage:""}}}function z(r,e,t,s){if(!e.showLastMessage||r.length===0)return{userMessage:"",assistantMessage:""};let n=r.find(d=>d.memory_session_id!==t);if(!n)return{userMessage:"",assistantMessage:""};let o=n.memory_session_id,i=Nt(s),a=be.default.join(y,"projects",i,`${o}.jsonl`);return Ct(a)}function Re(r,e){let t=e[0]?.id;return r.map((s,n)=>{let o=n===0?null:e[n+1];return{...s,displayEpoch:o?o.created_at_epoch:s.created_at_epoch,displayTime:o?o.created_at:s.created_at,shouldShowLink:s.id!==t}})}function Z(r,e){let t=[...r.map(s=>({type:"observation",data:s})),...e.map(s=>({type:"summary",data:s}))];return t.sort((s,n)=>{let o=s.type==="observation"?s.data.created_at_epoch:s.data.displayEpoch,i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch;return o-i}),t}function Ne(r,e){return new Set(r.slice(0,e).map(t=>t.id))}function Ce(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function Ae(r){return[`# [${r}] recent context, ${Ce()}`,""]}function Ie(){return[`**Legend:** session-request | ${O.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ")}`,""]}function ye(){return["**Column Key**:","- **Read**: Tokens to read this observation (cost to learn it now)","- **Work**: Tokens spent on work that produced this record ( research, building, deciding)",""]}function Me(){return["**Context Index:** This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.","","When you need implementation details, rationale, or debugging context:","- Fetch by ID: get_observations([IDs]) for observations visible in this index","- Search history: Use the mem-search skill for past decisions, bugs, and deeper research","- Trust this index over re-reading code for past decisions and learnings",""]}function Le(r,e){let t=[];if(t.push("**Context Economics**:"),t.push(`- Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)`),t.push(`- Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions`),r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let s="- Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?s+=`${r.savings.toLocaleString()} tokens (${r.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?s+=`${r.savings.toLocaleString()} tokens`:s+=`${r.savingsPercent}% reduction from reuse`,t.push(s)}return t.push(""),t}function ve(r){return[`### ${r}`,""]}function De(r){return[`**${r}**`,"| ID | Time | T | Title | Read | Work |","|----|------|---|-------|------|------|"]}function xe(r,e,t){let s=r.title||"Untitled",n=O.getInstance().getTypeIcon(r.type),{readTokens:o,discoveryDisplay:i}=M(r,t),a=t.showReadTokens?`~${o}`:"",d=t.showWorkTokens?i:"";return`| #${r.id} | ${e||'"'} | ${n} | ${s} | ${a} | ${d} |`}function Ue(r,e,t,s){let n=[],o=r.title||"Untitled",i=O.getInstance().getTypeIcon(r.type),{readTokens:a,discoveryDisplay:d}=M(r,s);n.push(`**#${r.id}** ${e||'"'} ${i} **${o}**`),t&&(n.push(""),n.push(t),n.push(""));let c=[];return s.showReadTokens&&c.push(`Read: ~${a}`),s.showWorkTokens&&c.push(`Work: ${d}`),c.length>0&&n.push(c.join(", ")),n.push(""),n}function ke(r,e){let t=`${r.request||"Session started"} (${e})`;return[`**#S${r.id}** ${t}`,""]}function x(r,e){return e?[`**${r}**: ${e}`,""]:[]}function we(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function $e(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use MCP search tools to access memories by ID.`]}function Fe(r){return`# [${r}] recent context, ${Ce()}
|
|
642
642
|
|
|
643
|
-
No previous sessions found for this project yet.`}function Pe(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function Xe(r){return["",`${p.bright}${p.cyan}[${r}] recent context, ${Pe()}${p.reset}`,`${p.gray}${"\u2500".repeat(60)}${p.reset}`,""]}function je(){let e=O.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${p.dim}Legend: session-request | ${e}${p.reset}`,""]}function Ge(){return[`${p.bright}Column Key${p.reset}`,`${p.dim} Read: Tokens to read this observation (cost to learn it now)${p.reset}`,`${p.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${p.reset}`,""]}function Be(){return[`${p.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${p.reset}`,"",`${p.dim}When you need implementation details, rationale, or debugging context:${p.reset}`,`${p.dim} -
|
|
643
|
+
No previous sessions found for this project yet.`}function Pe(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function Xe(r){return["",`${p.bright}${p.cyan}[${r}] recent context, ${Pe()}${p.reset}`,`${p.gray}${"\u2500".repeat(60)}${p.reset}`,""]}function je(){let e=O.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${p.dim}Legend: session-request | ${e}${p.reset}`,""]}function Ge(){return[`${p.bright}Column Key${p.reset}`,`${p.dim} Read: Tokens to read this observation (cost to learn it now)${p.reset}`,`${p.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${p.reset}`,""]}function Be(){return[`${p.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${p.reset}`,"",`${p.dim}When you need implementation details, rationale, or debugging context:${p.reset}`,`${p.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${p.reset}`,`${p.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${p.reset}`,`${p.dim} - Trust this index over re-reading code for past decisions and learnings${p.reset}`,""]}function He(r,e){let t=[];if(t.push(`${p.bright}${p.cyan}Context Economics${p.reset}`),t.push(`${p.dim} Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)${p.reset}`),t.push(`${p.dim} Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${p.reset}`),r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let s=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?s+=`${r.savings.toLocaleString()} tokens (${r.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?s+=`${r.savings.toLocaleString()} tokens`:s+=`${r.savingsPercent}% reduction from reuse`,t.push(`${p.green}${s}${p.reset}`)}return t.push(""),t}function We(r){return[`${p.bright}${p.cyan}${r}${p.reset}`,""]}function Ye(r){return[`${p.dim}${r}${p.reset}`]}function Ve(r,e,t,s){let n=r.title||"Untitled",o=O.getInstance().getTypeIcon(r.type),{readTokens:i,discoveryTokens:a,workEmoji:d}=M(r,s),c=t?`${p.dim}${e}${p.reset}`:" ".repeat(e.length),m=s.showReadTokens&&i>0?`${p.dim}(~${i}t)${p.reset}`:"",l=s.showWorkTokens&&a>0?`${p.dim}(${d} ${a.toLocaleString()}t)${p.reset}`:"";return` ${p.dim}#${r.id}${p.reset} ${c} ${o} ${n} ${m} ${l}`}function qe(r,e,t,s,n){let o=[],i=r.title||"Untitled",a=O.getInstance().getTypeIcon(r.type),{readTokens:d,discoveryTokens:c,workEmoji:m}=M(r,n),l=t?`${p.dim}${e}${p.reset}`:" ".repeat(e.length),T=n.showReadTokens&&d>0?`${p.dim}(~${d}t)${p.reset}`:"",E=n.showWorkTokens&&c>0?`${p.dim}(${m} ${c.toLocaleString()}t)${p.reset}`:"";return o.push(` ${p.dim}#${r.id}${p.reset} ${l} ${a} ${p.bright}${i}${p.reset}`),s&&o.push(` ${p.dim}${s}${p.reset}`),(T||E)&&o.push(` ${T} ${E}`),o.push(""),o}function Ke(r,e){let t=`${r.request||"Session started"} (${e})`;return[`${p.yellow}#S${r.id}${p.reset} ${t}`,""]}function U(r,e,t){return e?[`${t}${r}:${p.reset} ${e}`,""]:[]}function Je(r){return r.assistantMessage?["","---","",`${p.bright}${p.magenta}Previously${p.reset}`,"",`${p.dim}A: ${r.assistantMessage}${p.reset}`,""]:[]}function Qe(r,e){let t=Math.round(r/1e3);return["",`${p.dim}Access ${t}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use MCP search tools to access memories by ID.${p.reset}`]}function ze(r){return`
|
|
644
644
|
${p.bright}${p.cyan}[${r}] recent context, ${Pe()}${p.reset}
|
|
645
645
|
${p.gray}${"\u2500".repeat(60)}${p.reset}
|
|
646
646
|
|
|
647
647
|
${p.dim}No previous sessions found for this project yet.${p.reset}
|
|
648
648
|
`}function Ze(r,e,t,s){let n=[];return s?n.push(...Xe(r)):n.push(...Ae(r)),s?n.push(...je()):n.push(...Ie()),s?n.push(...Ge()):n.push(...ye()),s?n.push(...Be()):n.push(...Me()),P(t)&&(s?n.push(...He(e,t)):n.push(...Le(e,t))),n}var ee=L(require("path"),1);function B(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return _.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e),[]}}function tt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function st(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function rt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function et(r,e){return ee.default.isAbsolute(r)?ee.default.relative(e,r):r}function nt(r,e,t){let s=B(r);if(s.length>0)return et(s[0],e);if(t){let n=B(t);if(n.length>0)return et(n[0],e)}return"General"}function At(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=rt(n);e.has(o)||e.set(o,[]),e.get(o).push(s)}let t=Array.from(e.entries()).sort((s,n)=>{let o=new Date(s[0]).getTime(),i=new Date(n[0]).getTime();return o-i});return new Map(t)}function It(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?B(r.facts).join(`
|
|
649
|
-
`):null}function yt(r,e,t,s,n,o){let i=[];o?i.push(...We(r)):i.push(...ve(r));let a=null,d="",c=!1;for(let m of e)if(m.type==="summary"){c&&(i.push(""),c=!1,a=null,d="");let l=m.data,T=tt(l.displayTime);o?i.push(...Ke(l,T)):i.push(...ke(l,T))}else{let l=m.data,T=nt(l.files_modified,n,l.files_read),E=st(l.created_at),g=E!==d,h=g?E:"";d=E;let u=t.has(l.id);if(T!==a&&(c&&i.push(""),o?i.push(...Ye(T)):i.push(...De(T)),a=T,c=!0),u){let S=It(l,s);o?i.push(...qe(l,E,g,S,s)):(c&&!o&&(i.push(""),c=!1),i.push(...Ue(l,h,S,s)),a=null)}else o?i.push(Ve(l,E,g,s)):i.push(xe(l,h,s))}return c&&i.push(""),i}function ot(r,e,t,s,n){let o=[],i=At(r);for(let[a,d]of i)o.push(...yt(a,d,e,t,s,n));return o}function it(r,e,t){return!(!r.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||t&&e.created_at_epoch<=t.created_at_epoch)}function at(r,e){let t=[];return e?(t.push(...U("Investigated",r.investigated,p.blue)),t.push(...U("Learned",r.learned,p.yellow)),t.push(...U("Completed",r.completed,p.green)),t.push(...U("Next Steps",r.next_steps,p.magenta))):(t.push(...x("Investigated",r.investigated)),t.push(...x("Learned",r.learned)),t.push(...x("Completed",r.completed)),t.push(...x("Next Steps",r.next_steps))),t}function dt(r,e){return e?Je(r):we(r)}function pt(r,e,t){return!P(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?Qe(r.totalDiscoveryTokens,r.totalReadTokens):$e(r.totalDiscoveryTokens,r.totalReadTokens)}var Mt=ct.default.join((0,_t.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function Lt(){try{return new $}catch(r){if(r.code==="ERR_DLOPEN_FAILED"){try{(0,mt.unlinkSync)(Mt)}catch(e){_.debug("SYSTEM","Marker file cleanup failed (may not exist)",{},e)}return _.error("SYSTEM","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function vt(r,e){return e?ze(r):Fe(r)}function Dt(r,e,t,s,n,o,i){let a=[],d=K(e);a.push(...Ze(r,d,s,i));let c=t.slice(0,s.sessionCount),m=Re(c,t),l=Z(e,m),T=
|
|
649
|
+
`):null}function yt(r,e,t,s,n,o){let i=[];o?i.push(...We(r)):i.push(...ve(r));let a=null,d="",c=!1;for(let m of e)if(m.type==="summary"){c&&(i.push(""),c=!1,a=null,d="");let l=m.data,T=tt(l.displayTime);o?i.push(...Ke(l,T)):i.push(...ke(l,T))}else{let l=m.data,T=nt(l.files_modified,n,l.files_read),E=st(l.created_at),g=E!==d,h=g?E:"";d=E;let u=t.has(l.id);if(T!==a&&(c&&i.push(""),o?i.push(...Ye(T)):i.push(...De(T)),a=T,c=!0),u){let S=It(l,s);o?i.push(...qe(l,E,g,S,s)):(c&&!o&&(i.push(""),c=!1),i.push(...Ue(l,h,S,s)),a=null)}else o?i.push(Ve(l,E,g,s)):i.push(xe(l,h,s))}return c&&i.push(""),i}function ot(r,e,t,s,n){let o=[],i=At(r);for(let[a,d]of i)o.push(...yt(a,d,e,t,s,n));return o}function it(r,e,t){return!(!r.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||t&&e.created_at_epoch<=t.created_at_epoch)}function at(r,e){let t=[];return e?(t.push(...U("Investigated",r.investigated,p.blue)),t.push(...U("Learned",r.learned,p.yellow)),t.push(...U("Completed",r.completed,p.green)),t.push(...U("Next Steps",r.next_steps,p.magenta))):(t.push(...x("Investigated",r.investigated)),t.push(...x("Learned",r.learned)),t.push(...x("Completed",r.completed)),t.push(...x("Next Steps",r.next_steps))),t}function dt(r,e){return e?Je(r):we(r)}function pt(r,e,t){return!P(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?Qe(r.totalDiscoveryTokens,r.totalReadTokens):$e(r.totalDiscoveryTokens,r.totalReadTokens)}var Mt=ct.default.join((0,_t.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function Lt(){try{return new $}catch(r){if(r.code==="ERR_DLOPEN_FAILED"){try{(0,mt.unlinkSync)(Mt)}catch(e){_.debug("SYSTEM","Marker file cleanup failed (may not exist)",{},e)}return _.error("SYSTEM","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function vt(r,e){return e?ze(r):Fe(r)}function Dt(r,e,t,s,n,o,i){let a=[],d=K(e);a.push(...Ze(r,d,s,i));let c=t.slice(0,s.sessionCount),m=Re(c,t),l=Z(e,m),T=Ne(e,s.fullObservationCount);a.push(...ot(l,T,s,n,i));let E=t[0],g=e[0];it(s,E,g)&&a.push(...at(E,i));let h=z(e,s,o,n);return a.push(...dt(h,i)),a.push(...pt(d,s,i)),a.join(`
|
|
650
650
|
`).trimEnd()}async function te(r,e=!1){let t=Y(),s=r?.cwd??process.cwd(),n=Te(s),o=r?.projects||[n],i=Lt();if(!i)return"";try{let a=o.length>1?he(i,o,t):J(i,n,t),d=o.length>1?Oe(i,o,t):Q(i,n,t);return a.length===0&&d.length===0?vt(n,e):Dt(n,a,d,t,s,r?.session_id,e)}finally{i.close()}}0&&(module.exports={generateContext});
|
|
@@ -54,7 +54,7 @@ ${i.stack}`:` ${i.message}`:this.getLevel()===0&&typeof i=="object"?l=`
|
|
|
54
54
|
|
|
55
55
|
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let a of t.seen.entries()){let s=a[1];if(e===a[0]){i(a);continue}if(t.external){let u=t.external.registry.get(a[0])?.id;if(e!==a[0]&&u){i(a);continue}}if(t.metadataRegistry.get(a[0])?.id){i(a);continue}if(s.cycle){i(a);continue}if(s.count>1&&t.reused==="ref"){i(a);continue}}}function Qi(t,e){let r=t.seen.get(e);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let s=t.seen.get(a);if(s.ref===null)return;let c=s.def??s.schema,u={...c},l=s.ref;if(s.ref=null,l){n(l);let m=t.seen.get(l),f=m.schema;if(f.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(f)):Object.assign(c,f),Object.assign(c,u),a._zod.parent===l)for(let v in c)v==="$ref"||v==="allOf"||v in u||delete c[v];if(f.$ref&&m.def)for(let v in c)v==="$ref"||v==="allOf"||v in m.def&&JSON.stringify(c[v])===JSON.stringify(m.def[v])&&delete c[v]}let d=a._zod.parent;if(d&&d!==l){n(d);let m=t.seen.get(d);if(m?.schema.$ref&&(c.$ref=m.schema.$ref,m.def))for(let f in c)f==="$ref"||f==="allOf"||f in m.def&&JSON.stringify(c[f])===JSON.stringify(m.def[f])&&delete c[f]}t.override({zodSchema:a,jsonSchema:c,path:s.path??[]})};for(let a of[...t.seen.entries()].reverse())n(a[0]);let o={};if(t.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":t.target,t.external?.uri){let a=t.external.registry.get(e)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=t.external.uri(a)}Object.assign(o,r.def??r.schema);let i=t.external?.defs??{};for(let a of t.seen.entries()){let s=a[1];s.def&&s.defId&&(i[s.defId]=s.def)}t.external||Object.keys(i).length>0&&(t.target==="draft-2020-12"?o.$defs=i:o.definitions=i);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...e["~standard"],jsonSchema:{input:mo(e,"input",t.processors),output:mo(e,"output",t.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function Ue(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let n=t._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return Ue(n.element,r);if(n.type==="set")return Ue(n.valueType,r);if(n.type==="lazy")return Ue(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return Ue(n.innerType,r);if(n.type==="intersection")return Ue(n.left,r)||Ue(n.right,r);if(n.type==="record"||n.type==="map")return Ue(n.keyType,r)||Ue(n.valueType,r);if(n.type==="pipe")return Ue(n.in,r)||Ue(n.out,r);if(n.type==="object"){for(let o in n.shape)if(Ue(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(Ue(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(Ue(o,r))return!0;return!!(n.rest&&Ue(n.rest,r))}return!1}var Am=(t,e={})=>r=>{let n=Xi({...r,processors:e});return de(t,n),Yi(n,t),Qi(n,t)},mo=(t,e,r={})=>n=>{let{libraryOptions:o,target:i}=n??{},a=Xi({...o??{},target:i,io:e,processors:r});return de(t,a),Yi(a,t),Qi(a,t)};var wb={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Um=(t,e,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:a,format:s,patterns:c,contentEncoding:u}=t._zod.bag;if(typeof i=="number"&&(o.minLength=i),typeof a=="number"&&(o.maxLength=a),s&&(o.format=wb[s]??s,o.format===""&&delete o.format,s==="time"&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let l=[...c];l.length===1?o.pattern=l[0].source:l.length>1&&(o.allOf=[...l.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},Cm=(t,e,r,n)=>{let o=r,{minimum:i,maximum:a,format:s,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:l}=t._zod.bag;typeof s=="string"&&s.includes("int")?o.type="integer":o.type="number",typeof l=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(o.minimum=l,o.exclusiveMinimum=!0):o.exclusiveMinimum=l),typeof i=="number"&&(o.minimum=i,typeof l=="number"&&e.target!=="draft-04"&&(l>=i?delete o.minimum:delete o.exclusiveMinimum)),typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(o.maximum=u,o.exclusiveMaximum=!0):o.exclusiveMaximum=u),typeof a=="number"&&(o.maximum=a,typeof u=="number"&&e.target!=="draft-04"&&(u<=a?delete o.maximum:delete o.exclusiveMaximum)),typeof c=="number"&&(o.multipleOf=c)},Mm=(t,e,r,n)=>{r.type="boolean"},Zm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},Lm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},qm=(t,e,r,n)=>{e.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},Fm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},Vm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},Jm=(t,e,r,n)=>{r.not={}},Km=(t,e,r,n)=>{},Hm=(t,e,r,n)=>{},Wm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},Gm=(t,e,r,n)=>{let o=t._zod.def,i=Rn(o.entries);i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),r.enum=i},Bm=(t,e,r,n)=>{let o=t._zod.def,i=[];for(let a of o.values)if(a===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(a))}else i.push(a);if(i.length!==0)if(i.length===1){let a=i[0];r.type=a===null?"null":typeof a,e.target==="draft-04"||e.target==="openapi-3.0"?r.enum=[a]:r.const=a}else i.every(a=>typeof a=="number")&&(r.type="number"),i.every(a=>typeof a=="string")&&(r.type="string"),i.every(a=>typeof a=="boolean")&&(r.type="boolean"),i.every(a=>a===null)&&(r.type="null"),r.enum=i},Xm=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},Ym=(t,e,r,n)=>{let o=r,i=t._zod.pattern;if(!i)throw new Error("Pattern not found in template literal");o.type="string",o.pattern=i.source},Qm=(t,e,r,n)=>{let o=r,i={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:s,mime:c}=t._zod.bag;a!==void 0&&(i.minLength=a),s!==void 0&&(i.maxLength=s),c?c.length===1?(i.contentMediaType=c[0],Object.assign(o,i)):(Object.assign(o,i),o.anyOf=c.map(u=>({contentMediaType:u}))):Object.assign(o,i)},eh=(t,e,r,n)=>{r.type="boolean"},th=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},rh=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},nh=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},oh=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},ih=(t,e,r,n)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},ah=(t,e,r,n)=>{let o=r,i=t._zod.def,{minimum:a,maximum:s}=t._zod.bag;typeof a=="number"&&(o.minItems=a),typeof s=="number"&&(o.maxItems=s),o.type="array",o.items=de(i.element,e,{...n,path:[...n.path,"items"]})},sh=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="object",o.properties={};let a=i.shape;for(let u in a)o.properties[u]=de(a[u],e,{...n,path:[...n.path,"properties",u]});let s=new Set(Object.keys(a)),c=new Set([...s].filter(u=>{let l=i.shape[u]._zod;return e.io==="input"?l.optin===void 0:l.optout===void 0}));c.size>0&&(o.required=Array.from(c)),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=de(i.catchall,e,{...n,path:[...n.path,"additionalProperties"]})):e.io==="output"&&(o.additionalProperties=!1)},gl=(t,e,r,n)=>{let o=t._zod.def,i=o.inclusive===!1,a=o.options.map((s,c)=>de(s,e,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=a:r.anyOf=a},ch=(t,e,r,n)=>{let o=t._zod.def,i=de(o.left,e,{...n,path:[...n.path,"allOf",0]}),a=de(o.right,e,{...n,path:[...n.path,"allOf",1]}),s=u=>"allOf"in u&&Object.keys(u).length===1,c=[...s(i)?i.allOf:[i],...s(a)?a.allOf:[a]];r.allOf=c},uh=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="array";let a=e.target==="draft-2020-12"?"prefixItems":"items",s=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",c=i.items.map((m,f)=>de(m,e,{...n,path:[...n.path,a,f]})),u=i.rest?de(i.rest,e,{...n,path:[...n.path,s,...e.target==="openapi-3.0"?[i.items.length]:[]]}):null;e.target==="draft-2020-12"?(o.prefixItems=c,u&&(o.items=u)):e.target==="openapi-3.0"?(o.items={anyOf:c},u&&o.items.anyOf.push(u),o.minItems=c.length,u||(o.maxItems=c.length)):(o.items=c,u&&(o.additionalItems=u));let{minimum:l,maximum:d}=t._zod.bag;typeof l=="number"&&(o.minItems=l),typeof d=="number"&&(o.maxItems=d)},lh=(t,e,r,n)=>{let o=r,i=t._zod.def;o.type="object";let a=i.keyType,c=a._zod.bag?.patterns;if(i.mode==="loose"&&c&&c.size>0){let l=de(i.valueType,e,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let d of c)o.patternProperties[d.source]=l}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(o.propertyNames=de(i.keyType,e,{...n,path:[...n.path,"propertyNames"]})),o.additionalProperties=de(i.valueType,e,{...n,path:[...n.path,"additionalProperties"]});let u=a._zod.values;if(u){let l=[...u].filter(d=>typeof d=="string"||typeof d=="number");l.length>0&&(o.required=l)}},dh=(t,e,r,n)=>{let o=t._zod.def,i=de(o.innerType,e,n),a=e.seen.get(t);e.target==="openapi-3.0"?(a.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},ph=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},fh=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.default=JSON.parse(JSON.stringify(o.defaultValue))},mh=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,e.io==="input"&&(r._prefault=JSON.parse(JSON.stringify(o.defaultValue)))},hh=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType;let a;try{a=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a},gh=(t,e,r,n)=>{let o=t._zod.def,i=e.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;de(i,e,n);let a=e.seen.get(t);a.ref=i},vh=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType,r.readOnly=!0},_h=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},vl=(t,e,r,n)=>{let o=t._zod.def;de(o.innerType,e,n);let i=e.seen.get(t);i.ref=o.innerType},yh=(t,e,r,n)=>{let o=t._zod.innerType;de(o,e,n);let i=e.seen.get(t);i.ref=o};function Br(t){return!!t._zod}function Yt(t,e){return Br(t)?Jr(t,e):t.safeParse(e)}function ea(t){if(!t)return;let e;if(Br(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function kh(t){if(Br(t)){let i=t._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var ho={};$n(ho,{ZodAny:()=>Lh,ZodArray:()=>Jh,ZodBase64:()=>Ll,ZodBase64URL:()=>ql,ZodBigInt:()=>ua,ZodBigIntFormat:()=>Jl,ZodBoolean:()=>ca,ZodCIDRv4:()=>Ml,ZodCIDRv6:()=>Zl,ZodCUID:()=>jl,ZodCUID2:()=>Dl,ZodCatch:()=>dg,ZodCodec:()=>Yl,ZodCustom:()=>ma,ZodCustomStringFormat:()=>vo,ZodDate:()=>Hl,ZodDefault:()=>ig,ZodDiscriminatedUnion:()=>Hh,ZodE164:()=>Fl,ZodEmail:()=>Tl,ZodEmoji:()=>Pl,ZodEnum:()=>go,ZodExactOptional:()=>rg,ZodFile:()=>eg,ZodFunction:()=>$g,ZodGUID:()=>ra,ZodIPv4:()=>Ul,ZodIPv6:()=>Cl,ZodIntersection:()=>Wh,ZodJWT:()=>Vl,ZodKSUID:()=>Al,ZodLazy:()=>vg,ZodLiteral:()=>Qh,ZodMAC:()=>Uh,ZodMap:()=>Xh,ZodNaN:()=>fg,ZodNanoID:()=>Ol,ZodNever:()=>Fh,ZodNonOptional:()=>Bl,ZodNull:()=>Zh,ZodNullable:()=>og,ZodNumber:()=>sa,ZodNumberFormat:()=>Xr,ZodObject:()=>la,ZodOptional:()=>Gl,ZodPipe:()=>Xl,ZodPrefault:()=>sg,ZodPromise:()=>yg,ZodReadonly:()=>mg,ZodRecord:()=>fa,ZodSet:()=>Yh,ZodString:()=>ia,ZodStringFormat:()=>ce,ZodSuccess:()=>lg,ZodSymbol:()=>Ch,ZodTemplateLiteral:()=>gg,ZodTransform:()=>tg,ZodTuple:()=>Gh,ZodType:()=>F,ZodULID:()=>Nl,ZodURL:()=>aa,ZodUUID:()=>Rt,ZodUndefined:()=>Mh,ZodUnion:()=>da,ZodUnknown:()=>qh,ZodVoid:()=>Vh,ZodXID:()=>Rl,ZodXor:()=>Kh,_ZodString:()=>El,_default:()=>ag,_function:()=>Fx,any:()=>wx,array:()=>G,base64:()=>cx,base64url:()=>ux,bigint:()=>$x,boolean:()=>_e,catch:()=>pg,check:()=>Vx,cidrv4:()=>ax,cidrv6:()=>sx,codec:()=>Zx,cuid:()=>Yb,cuid2:()=>Qb,custom:()=>Ql,date:()=>Ix,describe:()=>Jx,discriminatedUnion:()=>pa,e164:()=>lx,email:()=>qb,emoji:()=>Bb,enum:()=>Te,exactOptional:()=>ng,file:()=>Ax,float32:()=>gx,float64:()=>vx,function:()=>Fx,guid:()=>Fb,hash:()=>hx,hex:()=>mx,hostname:()=>fx,httpUrl:()=>Gb,instanceof:()=>Hx,int:()=>Il,int32:()=>_x,int64:()=>bx,intersection:()=>yo,ipv4:()=>nx,ipv6:()=>ix,json:()=>Gx,jwt:()=>dx,keyof:()=>Ex,ksuid:()=>rx,lazy:()=>_g,literal:()=>T,looseObject:()=>Ee,looseRecord:()=>jx,mac:()=>ox,map:()=>Dx,meta:()=>Kx,nan:()=>Mx,nanoid:()=>Xb,nativeEnum:()=>Rx,never:()=>Kl,nonoptional:()=>ug,null:()=>_o,nullable:()=>na,nullish:()=>Ux,number:()=>ne,object:()=>z,optional:()=>fe,partialRecord:()=>Ox,pipe:()=>oa,prefault:()=>cg,preprocess:()=>ha,promise:()=>qx,readonly:()=>hg,record:()=>pe,refine:()=>bg,set:()=>Nx,strictObject:()=>Tx,string:()=>h,stringFormat:()=>px,stringbool:()=>Wx,success:()=>Cx,superRefine:()=>xg,symbol:()=>kx,templateLiteral:()=>Lx,transform:()=>Wl,tuple:()=>Bh,uint32:()=>yx,uint64:()=>xx,ulid:()=>ex,undefined:()=>Sx,union:()=>ie,unknown:()=>ue,url:()=>Wb,uuid:()=>Vb,uuidv4:()=>Jb,uuidv6:()=>Kb,uuidv7:()=>Hb,void:()=>zx,xid:()=>tx,xor:()=>Px});var ta={};$n(ta,{endsWith:()=>so,gt:()=>Dt,gte:()=>Ae,includes:()=>io,length:()=>Wr,lowercase:()=>no,lt:()=>jt,lte:()=>We,maxLength:()=>Hr,maxSize:()=>gr,mime:()=>co,minLength:()=>Xt,minSize:()=>Nt,multipleOf:()=>hr,negative:()=>il,nonnegative:()=>sl,nonpositive:()=>al,normalize:()=>uo,overwrite:()=>_t,positive:()=>ol,property:()=>cl,regex:()=>ro,size:()=>Kr,slugify:()=>Bi,startsWith:()=>ao,toLowerCase:()=>po,toUpperCase:()=>fo,trim:()=>lo,uppercase:()=>oo});var vr={};$n(vr,{ZodISODate:()=>bl,ZodISODateTime:()=>yl,ZodISODuration:()=>wl,ZodISOTime:()=>kl,date:()=>xl,datetime:()=>$l,duration:()=>zl,time:()=>Sl});var yl=p("ZodISODateTime",(t,e)=>{Dc.init(t,e),ce.init(t,e)});function $l(t){return Ru(yl,t)}var bl=p("ZodISODate",(t,e)=>{Nc.init(t,e),ce.init(t,e)});function xl(t){return Au(bl,t)}var kl=p("ZodISOTime",(t,e)=>{Rc.init(t,e),ce.init(t,e)});function Sl(t){return Uu(kl,t)}var wl=p("ZodISODuration",(t,e)=>{Ac.init(t,e),ce.init(t,e)});function zl(t){return Cu(wl,t)}var Sh=(t,e)=>{hi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>vi(t,r)},flatten:{value:r=>gi(t,r)},addIssue:{value:r=>{t.issues.push(r),t.message=JSON.stringify(t.issues,qr,2)}},addIssues:{value:r=>{t.issues.push(...r),t.message=JSON.stringify(t.issues,qr,2)}},isEmpty:{get(){return t.issues.length===0}}})},MN=p("ZodError",Sh),Ge=p("ZodError",Sh,{Parent:Error});var wh=Ln(Ge),zh=Fn(Ge),Ih=Jn(Ge),Eh=Kn(Ge),Th=Mf(Ge),Ph=Zf(Ge),Oh=Lf(Ge),jh=qf(Ge),Dh=Ff(Ge),Nh=Vf(Ge),Rh=Jf(Ge),Ah=Kf(Ge);var F=p("ZodType",(t,e)=>(Z.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:mo(t,"input"),output:mo(t,"output")}}),t.toJSONSchema=Am(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone(y.mergeDefs(e,{checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),t.with=t.check,t.clone=(r,n)=>Ne(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>wh(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Ih(t,r,n),t.parseAsync=async(r,n)=>zh(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Eh(t,r,n),t.spa=t.safeParseAsync,t.encode=(r,n)=>Th(t,r,n),t.decode=(r,n)=>Ph(t,r,n),t.encodeAsync=async(r,n)=>Oh(t,r,n),t.decodeAsync=async(r,n)=>jh(t,r,n),t.safeEncode=(r,n)=>Dh(t,r,n),t.safeDecode=(r,n)=>Nh(t,r,n),t.safeEncodeAsync=async(r,n)=>Rh(t,r,n),t.safeDecodeAsync=async(r,n)=>Ah(t,r,n),t.refine=(r,n)=>t.check(bg(r,n)),t.superRefine=r=>t.check(xg(r)),t.overwrite=r=>t.check(_t(r)),t.optional=()=>fe(t),t.exactOptional=()=>ng(t),t.nullable=()=>na(t),t.nullish=()=>fe(na(t)),t.nonoptional=r=>ug(t,r),t.array=()=>G(t),t.or=r=>ie([t,r]),t.and=r=>yo(t,r),t.transform=r=>oa(t,Wl(r)),t.default=r=>ag(t,r),t.prefault=r=>cg(t,r),t.catch=r=>pg(t,r),t.pipe=r=>oa(t,r),t.readonly=()=>hg(t),t.describe=r=>{let n=t.clone();return Re.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Re.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Re.get(t);let n=t.clone();return Re.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t.apply=r=>r(t),t)),El=p("_ZodString",(t,e)=>{mr.init(t,e),F.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Um(t,n,o,i);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(ro(...n)),t.includes=(...n)=>t.check(io(...n)),t.startsWith=(...n)=>t.check(ao(...n)),t.endsWith=(...n)=>t.check(so(...n)),t.min=(...n)=>t.check(Xt(...n)),t.max=(...n)=>t.check(Hr(...n)),t.length=(...n)=>t.check(Wr(...n)),t.nonempty=(...n)=>t.check(Xt(1,...n)),t.lowercase=n=>t.check(no(n)),t.uppercase=n=>t.check(oo(n)),t.trim=()=>t.check(lo()),t.normalize=(...n)=>t.check(uo(...n)),t.toLowerCase=()=>t.check(po()),t.toUpperCase=()=>t.check(fo()),t.slugify=()=>t.check(Bi())}),ia=p("ZodString",(t,e)=>{mr.init(t,e),El.init(t,e),t.email=r=>t.check(Pi(Tl,r)),t.url=r=>t.check(to(aa,r)),t.jwt=r=>t.check(Gi(Vl,r)),t.emoji=r=>t.check(Ri(Pl,r)),t.guid=r=>t.check(eo(ra,r)),t.uuid=r=>t.check(Oi(Rt,r)),t.uuidv4=r=>t.check(ji(Rt,r)),t.uuidv6=r=>t.check(Di(Rt,r)),t.uuidv7=r=>t.check(Ni(Rt,r)),t.nanoid=r=>t.check(Ai(Ol,r)),t.guid=r=>t.check(eo(ra,r)),t.cuid=r=>t.check(Ui(jl,r)),t.cuid2=r=>t.check(Ci(Dl,r)),t.ulid=r=>t.check(Mi(Nl,r)),t.base64=r=>t.check(Ki(Ll,r)),t.base64url=r=>t.check(Hi(ql,r)),t.xid=r=>t.check(Zi(Rl,r)),t.ksuid=r=>t.check(Li(Al,r)),t.ipv4=r=>t.check(qi(Ul,r)),t.ipv6=r=>t.check(Fi(Cl,r)),t.cidrv4=r=>t.check(Vi(Ml,r)),t.cidrv6=r=>t.check(Ji(Zl,r)),t.e164=r=>t.check(Wi(Fl,r)),t.datetime=r=>t.check($l(r)),t.date=r=>t.check(xl(r)),t.time=r=>t.check(Sl(r)),t.duration=r=>t.check(zl(r))});function h(t){return Du(ia,t)}var ce=p("ZodStringFormat",(t,e)=>{oe.init(t,e),El.init(t,e)}),Tl=p("ZodEmail",(t,e)=>{Sc.init(t,e),ce.init(t,e)});function qb(t){return Pi(Tl,t)}var ra=p("ZodGUID",(t,e)=>{xc.init(t,e),ce.init(t,e)});function Fb(t){return eo(ra,t)}var Rt=p("ZodUUID",(t,e)=>{kc.init(t,e),ce.init(t,e)});function Vb(t){return Oi(Rt,t)}function Jb(t){return ji(Rt,t)}function Kb(t){return Di(Rt,t)}function Hb(t){return Ni(Rt,t)}var aa=p("ZodURL",(t,e)=>{wc.init(t,e),ce.init(t,e)});function Wb(t){return to(aa,t)}function Gb(t){return to(aa,{protocol:/^https?$/,hostname:Qe.domain,...y.normalizeParams(t)})}var Pl=p("ZodEmoji",(t,e)=>{zc.init(t,e),ce.init(t,e)});function Bb(t){return Ri(Pl,t)}var Ol=p("ZodNanoID",(t,e)=>{Ic.init(t,e),ce.init(t,e)});function Xb(t){return Ai(Ol,t)}var jl=p("ZodCUID",(t,e)=>{Ec.init(t,e),ce.init(t,e)});function Yb(t){return Ui(jl,t)}var Dl=p("ZodCUID2",(t,e)=>{Tc.init(t,e),ce.init(t,e)});function Qb(t){return Ci(Dl,t)}var Nl=p("ZodULID",(t,e)=>{Pc.init(t,e),ce.init(t,e)});function ex(t){return Mi(Nl,t)}var Rl=p("ZodXID",(t,e)=>{Oc.init(t,e),ce.init(t,e)});function tx(t){return Zi(Rl,t)}var Al=p("ZodKSUID",(t,e)=>{jc.init(t,e),ce.init(t,e)});function rx(t){return Li(Al,t)}var Ul=p("ZodIPv4",(t,e)=>{Uc.init(t,e),ce.init(t,e)});function nx(t){return qi(Ul,t)}var Uh=p("ZodMAC",(t,e)=>{Mc.init(t,e),ce.init(t,e)});function ox(t){return Nu(Uh,t)}var Cl=p("ZodIPv6",(t,e)=>{Cc.init(t,e),ce.init(t,e)});function ix(t){return Fi(Cl,t)}var Ml=p("ZodCIDRv4",(t,e)=>{Zc.init(t,e),ce.init(t,e)});function ax(t){return Vi(Ml,t)}var Zl=p("ZodCIDRv6",(t,e)=>{Lc.init(t,e),ce.init(t,e)});function sx(t){return Ji(Zl,t)}var Ll=p("ZodBase64",(t,e)=>{qc.init(t,e),ce.init(t,e)});function cx(t){return Ki(Ll,t)}var ql=p("ZodBase64URL",(t,e)=>{Fc.init(t,e),ce.init(t,e)});function ux(t){return Hi(ql,t)}var Fl=p("ZodE164",(t,e)=>{Vc.init(t,e),ce.init(t,e)});function lx(t){return Wi(Fl,t)}var Vl=p("ZodJWT",(t,e)=>{Jc.init(t,e),ce.init(t,e)});function dx(t){return Gi(Vl,t)}var vo=p("ZodCustomStringFormat",(t,e)=>{Kc.init(t,e),ce.init(t,e)});function px(t,e,r={}){return Gr(vo,t,e,r)}function fx(t){return Gr(vo,"hostname",Qe.hostname,t)}function mx(t){return Gr(vo,"hex",Qe.hex,t)}function hx(t,e){let r=e?.enc??"hex",n=`${t}_${r}`,o=Qe[n];if(!o)throw new Error(`Unrecognized hash format: ${n}`);return Gr(vo,n,o,e)}var sa=p("ZodNumber",(t,e)=>{zi.init(t,e),F.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Cm(t,n,o,i),t.gt=(n,o)=>t.check(Dt(n,o)),t.gte=(n,o)=>t.check(Ae(n,o)),t.min=(n,o)=>t.check(Ae(n,o)),t.lt=(n,o)=>t.check(jt(n,o)),t.lte=(n,o)=>t.check(We(n,o)),t.max=(n,o)=>t.check(We(n,o)),t.int=n=>t.check(Il(n)),t.safe=n=>t.check(Il(n)),t.positive=n=>t.check(Dt(0,n)),t.nonnegative=n=>t.check(Ae(0,n)),t.negative=n=>t.check(jt(0,n)),t.nonpositive=n=>t.check(We(0,n)),t.multipleOf=(n,o)=>t.check(hr(n,o)),t.step=(n,o)=>t.check(hr(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function ne(t){return Mu(sa,t)}var Xr=p("ZodNumberFormat",(t,e)=>{Hc.init(t,e),sa.init(t,e)});function Il(t){return Zu(Xr,t)}function gx(t){return Lu(Xr,t)}function vx(t){return qu(Xr,t)}function _x(t){return Fu(Xr,t)}function yx(t){return Vu(Xr,t)}var ca=p("ZodBoolean",(t,e)=>{Xn.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Mm(t,r,n,o)});function _e(t){return Ju(ca,t)}var ua=p("ZodBigInt",(t,e)=>{Ii.init(t,e),F.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Zm(t,n,o,i),t.gte=(n,o)=>t.check(Ae(n,o)),t.min=(n,o)=>t.check(Ae(n,o)),t.gt=(n,o)=>t.check(Dt(n,o)),t.gte=(n,o)=>t.check(Ae(n,o)),t.min=(n,o)=>t.check(Ae(n,o)),t.lt=(n,o)=>t.check(jt(n,o)),t.lte=(n,o)=>t.check(We(n,o)),t.max=(n,o)=>t.check(We(n,o)),t.positive=n=>t.check(Dt(BigInt(0),n)),t.negative=n=>t.check(jt(BigInt(0),n)),t.nonpositive=n=>t.check(We(BigInt(0),n)),t.nonnegative=n=>t.check(Ae(BigInt(0),n)),t.multipleOf=(n,o)=>t.check(hr(n,o));let r=t._zod.bag;t.minValue=r.minimum??null,t.maxValue=r.maximum??null,t.format=r.format??null});function $x(t){return Ku(ua,t)}var Jl=p("ZodBigIntFormat",(t,e)=>{Wc.init(t,e),ua.init(t,e)});function bx(t){return Hu(Jl,t)}function xx(t){return Wu(Jl,t)}var Ch=p("ZodSymbol",(t,e)=>{Gc.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Lm(t,r,n,o)});function kx(t){return Gu(Ch,t)}var Mh=p("ZodUndefined",(t,e)=>{Bc.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Fm(t,r,n,o)});function Sx(t){return Bu(Mh,t)}var Zh=p("ZodNull",(t,e)=>{Xc.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>qm(t,r,n,o)});function _o(t){return Xu(Zh,t)}var Lh=p("ZodAny",(t,e)=>{Yc.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Km(t,r,n,o)});function wx(){return Yu(Lh)}var qh=p("ZodUnknown",(t,e)=>{Qc.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Hm(t,r,n,o)});function ue(){return Qu(qh)}var Fh=p("ZodNever",(t,e)=>{eu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Jm(t,r,n,o)});function Kl(t){return el(Fh,t)}var Vh=p("ZodVoid",(t,e)=>{tu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Vm(t,r,n,o)});function zx(t){return tl(Vh,t)}var Hl=p("ZodDate",(t,e)=>{ru.init(t,e),F.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Wm(t,n,o,i),t.min=(n,o)=>t.check(Ae(n,o)),t.max=(n,o)=>t.check(We(n,o));let r=t._zod.bag;t.minDate=r.minimum?new Date(r.minimum):null,t.maxDate=r.maximum?new Date(r.maximum):null});function Ix(t){return rl(Hl,t)}var Jh=p("ZodArray",(t,e)=>{nu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ah(t,r,n,o),t.element=e.element,t.min=(r,n)=>t.check(Xt(r,n)),t.nonempty=r=>t.check(Xt(1,r)),t.max=(r,n)=>t.check(Hr(r,n)),t.length=(r,n)=>t.check(Wr(r,n)),t.unwrap=()=>t.element});function G(t,e){return Rm(Jh,t,e)}function Ex(t){let e=t._zod.def.shape;return Te(Object.keys(e))}var la=p("ZodObject",(t,e)=>{Dm.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>sh(t,r,n,o),y.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Te(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ue()}),t.loose=()=>t.clone({...t._zod.def,catchall:ue()}),t.strict=()=>t.clone({...t._zod.def,catchall:Kl()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>y.extend(t,r),t.safeExtend=r=>y.safeExtend(t,r),t.merge=r=>y.merge(t,r),t.pick=r=>y.pick(t,r),t.omit=r=>y.omit(t,r),t.partial=(...r)=>y.partial(Gl,t,r[0]),t.required=(...r)=>y.required(Bl,t,r[0])});function z(t,e){let r={type:"object",shape:t??{},...y.normalizeParams(e)};return new la(r)}function Tx(t,e){return new la({type:"object",shape:t,catchall:Kl(),...y.normalizeParams(e)})}function Ee(t,e){return new la({type:"object",shape:t,catchall:ue(),...y.normalizeParams(e)})}var da=p("ZodUnion",(t,e)=>{Yn.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>gl(t,r,n,o),t.options=e.options});function ie(t,e){return new da({type:"union",options:t,...y.normalizeParams(e)})}var Kh=p("ZodXor",(t,e)=>{da.init(t,e),ou.init(t,e),t._zod.processJSONSchema=(r,n,o)=>gl(t,r,n,o),t.options=e.options});function Px(t,e){return new Kh({type:"union",options:t,inclusive:!1,...y.normalizeParams(e)})}var Hh=p("ZodDiscriminatedUnion",(t,e)=>{da.init(t,e),iu.init(t,e)});function pa(t,e,r){return new Hh({type:"union",options:e,discriminator:t,...y.normalizeParams(r)})}var Wh=p("ZodIntersection",(t,e)=>{au.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ch(t,r,n,o)});function yo(t,e){return new Wh({type:"intersection",left:t,right:e})}var Gh=p("ZodTuple",(t,e)=>{Ei.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>uh(t,r,n,o),t.rest=r=>t.clone({...t._zod.def,rest:r})});function Bh(t,e,r){let n=e instanceof Z,o=n?r:e,i=n?e:null;return new Gh({type:"tuple",items:t,rest:i,...y.normalizeParams(o)})}var fa=p("ZodRecord",(t,e)=>{su.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>lh(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType});function pe(t,e,r){return new fa({type:"record",keyType:t,valueType:e,...y.normalizeParams(r)})}function Ox(t,e,r){let n=Ne(t);return n._zod.values=void 0,new fa({type:"record",keyType:n,valueType:e,...y.normalizeParams(r)})}function jx(t,e,r){return new fa({type:"record",keyType:t,valueType:e,mode:"loose",...y.normalizeParams(r)})}var Xh=p("ZodMap",(t,e)=>{cu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>oh(t,r,n,o),t.keyType=e.keyType,t.valueType=e.valueType,t.min=(...r)=>t.check(Nt(...r)),t.nonempty=r=>t.check(Nt(1,r)),t.max=(...r)=>t.check(gr(...r)),t.size=(...r)=>t.check(Kr(...r))});function Dx(t,e,r){return new Xh({type:"map",keyType:t,valueType:e,...y.normalizeParams(r)})}var Yh=p("ZodSet",(t,e)=>{uu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ih(t,r,n,o),t.min=(...r)=>t.check(Nt(...r)),t.nonempty=r=>t.check(Nt(1,r)),t.max=(...r)=>t.check(gr(...r)),t.size=(...r)=>t.check(Kr(...r))});function Nx(t,e){return new Yh({type:"set",valueType:t,...y.normalizeParams(e)})}var go=p("ZodEnum",(t,e)=>{lu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(n,o,i)=>Gm(t,n,o,i),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let i={};for(let a of n)if(r.has(a))i[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new go({...e,checks:[],...y.normalizeParams(o),entries:i})},t.exclude=(n,o)=>{let i={...e.entries};for(let a of n)if(r.has(a))delete i[a];else throw new Error(`Key ${a} not found in enum`);return new go({...e,checks:[],...y.normalizeParams(o),entries:i})}});function Te(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new go({type:"enum",entries:r,...y.normalizeParams(e)})}function Rx(t,e){return new go({type:"enum",entries:t,...y.normalizeParams(e)})}var Qh=p("ZodLiteral",(t,e)=>{du.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Bm(t,r,n,o),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function T(t,e){return new Qh({type:"literal",values:Array.isArray(t)?t:[t],...y.normalizeParams(e)})}var eg=p("ZodFile",(t,e)=>{pu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Qm(t,r,n,o),t.min=(r,n)=>t.check(Nt(r,n)),t.max=(r,n)=>t.check(gr(r,n)),t.mime=(r,n)=>t.check(co(Array.isArray(r)?r:[r],n))});function Ax(t){return ul(eg,t)}var tg=p("ZodTransform",(t,e)=>{fu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>nh(t,r,n,o),t._zod.parse=(r,n)=>{if(n.direction==="backward")throw new dr(t.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(y.issue(i,r.value,e));else{let a=i;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=r.value),a.inst??(a.inst=t),r.issues.push(y.issue(a))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function Wl(t){return new tg({type:"transform",transform:t})}var Gl=p("ZodOptional",(t,e)=>{Ti.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function fe(t){return new Gl({type:"optional",innerType:t})}var rg=p("ZodExactOptional",(t,e)=>{mu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vl(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ng(t){return new rg({type:"optional",innerType:t})}var og=p("ZodNullable",(t,e)=>{hu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>dh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function na(t){return new og({type:"nullable",innerType:t})}function Ux(t){return fe(na(t))}var ig=p("ZodDefault",(t,e)=>{gu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>fh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function ag(t,e){return new ig({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():y.shallowClone(e)}})}var sg=p("ZodPrefault",(t,e)=>{vu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>mh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function cg(t,e){return new sg({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():y.shallowClone(e)}})}var Bl=p("ZodNonOptional",(t,e)=>{_u.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>ph(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function ug(t,e){return new Bl({type:"nonoptional",innerType:t,...y.normalizeParams(e)})}var lg=p("ZodSuccess",(t,e)=>{yu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>eh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function Cx(t){return new lg({type:"success",innerType:t})}var dg=p("ZodCatch",(t,e)=>{$u.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>hh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function pg(t,e){return new dg({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var fg=p("ZodNaN",(t,e)=>{bu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Xm(t,r,n,o)});function Mx(t){return nl(fg,t)}var Xl=p("ZodPipe",(t,e)=>{xu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>gh(t,r,n,o),t.in=e.in,t.out=e.out});function oa(t,e){return new Xl({type:"pipe",in:t,out:e})}var Yl=p("ZodCodec",(t,e)=>{Xl.init(t,e),Qn.init(t,e)});function Zx(t,e,r){return new Yl({type:"pipe",in:t,out:e,transform:r.decode,reverseTransform:r.encode})}var mg=p("ZodReadonly",(t,e)=>{ku.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>vh(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function hg(t){return new mg({type:"readonly",innerType:t})}var gg=p("ZodTemplateLiteral",(t,e)=>{Su.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>Ym(t,r,n,o)});function Lx(t,e){return new gg({type:"template_literal",parts:t,...y.normalizeParams(e)})}var vg=p("ZodLazy",(t,e)=>{Iu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>yh(t,r,n,o),t.unwrap=()=>t._zod.def.getter()});function _g(t){return new vg({type:"lazy",getter:t})}var yg=p("ZodPromise",(t,e)=>{zu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>_h(t,r,n,o),t.unwrap=()=>t._zod.def.innerType});function qx(t){return new yg({type:"promise",innerType:t})}var $g=p("ZodFunction",(t,e)=>{wu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>rh(t,r,n,o)});function Fx(t){return new $g({type:"function",input:Array.isArray(t?.input)?Bh(t?.input):t?.input??G(ue()),output:t?.output??ue()})}var ma=p("ZodCustom",(t,e)=>{Eu.init(t,e),F.init(t,e),t._zod.processJSONSchema=(r,n,o)=>th(t,r,n,o)});function Vx(t){let e=new se({check:"custom"});return e._zod.check=t,e}function Ql(t,e){return ll(ma,t??(()=>!0),e)}function bg(t,e={}){return dl(ma,t,e)}function xg(t){return pl(t)}var Jx=fl,Kx=ml;function Hx(t,e={}){let r=new ma({type:"custom",check:"custom",fn:n=>n instanceof t,abort:!0,...y.normalizeParams(e)});return r._zod.bag.Class=t,r._zod.check=n=>{n.value instanceof t||n.issues.push({code:"invalid_type",expected:t.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}var Wx=(...t)=>hl({Codec:Yl,Boolean:ca,String:ia},...t);function Gx(t){let e=_g(()=>ie([h(t),ne(),_e(),_o(),G(e),pe(h(),e)]));return e}function ha(t,e){return oa(Wl(t),e)}var kg;kg||(kg={});var HN={...ho,...ta,iso:vr};ye(Tu());var td="2025-11-25";var Sg=[td,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Qt="io.modelcontextprotocol/related-task",va="2.0",be=Ql(t=>t!==null&&(typeof t=="object"||typeof t=="function")),wg=ie([h(),ne().int()]),zg=h(),p4=Ee({ttl:ie([ne(),_o()]).optional(),pollInterval:ne().optional()}),Qx=z({ttl:ne().optional()}),ek=z({taskId:h()}),rd=Ee({progressToken:wg.optional(),[Qt]:ek.optional()}),Be=z({_meta:rd.optional()}),$o=Be.extend({task:Qx.optional()}),Ig=t=>$o.safeParse(t).success,xe=z({method:h(),params:Be.loose().optional()}),et=z({_meta:rd.optional()}),tt=z({method:h(),params:et.loose().optional()}),ke=Ee({_meta:rd.optional()}),_a=ie([h(),ne().int()]),Eg=z({jsonrpc:T(va),id:_a,...xe.shape}).strict(),nd=t=>Eg.safeParse(t).success,Tg=z({jsonrpc:T(va),...tt.shape}).strict(),Pg=t=>Tg.safeParse(t).success,od=z({jsonrpc:T(va),id:_a,result:ke}).strict(),bo=t=>od.safeParse(t).success;var Y;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Y||(Y={}));var id=z({jsonrpc:T(va),id:_a.optional(),error:z({code:ne().int(),message:h(),data:ue().optional()})}).strict();var Og=t=>id.safeParse(t).success;var jg=ie([Eg,Tg,od,id]),f4=ie([od,id]),ya=ke.strict(),tk=et.extend({requestId:_a.optional(),reason:h().optional()}),$a=tt.extend({method:T("notifications/cancelled"),params:tk}),rk=z({src:h(),mimeType:h().optional(),sizes:G(h()).optional(),theme:Te(["light","dark"]).optional()}),xo=z({icons:G(rk).optional()}),Yr=z({name:h(),title:h().optional()}),Dg=Yr.extend({...Yr.shape,...xo.shape,version:h(),websiteUrl:h().optional(),description:h().optional()}),nk=yo(z({applyDefaults:_e().optional()}),pe(h(),ue())),ok=ha(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,yo(z({form:nk.optional(),url:be.optional()}),pe(h(),ue()).optional())),ik=Ee({list:be.optional(),cancel:be.optional(),requests:Ee({sampling:Ee({createMessage:be.optional()}).optional(),elicitation:Ee({create:be.optional()}).optional()}).optional()}),ak=Ee({list:be.optional(),cancel:be.optional(),requests:Ee({tools:Ee({call:be.optional()}).optional()}).optional()}),sk=z({experimental:pe(h(),be).optional(),sampling:z({context:be.optional(),tools:be.optional()}).optional(),elicitation:ok.optional(),roots:z({listChanged:_e().optional()}).optional(),tasks:ik.optional()}),ck=Be.extend({protocolVersion:h(),capabilities:sk,clientInfo:Dg}),ad=xe.extend({method:T("initialize"),params:ck});var uk=z({experimental:pe(h(),be).optional(),logging:be.optional(),completions:be.optional(),prompts:z({listChanged:_e().optional()}).optional(),resources:z({subscribe:_e().optional(),listChanged:_e().optional()}).optional(),tools:z({listChanged:_e().optional()}).optional(),tasks:ak.optional()}),lk=ke.extend({protocolVersion:h(),capabilities:uk,serverInfo:Dg,instructions:h().optional()}),sd=tt.extend({method:T("notifications/initialized"),params:et.optional()});var ba=xe.extend({method:T("ping"),params:Be.optional()}),dk=z({progress:ne(),total:fe(ne()),message:fe(h())}),pk=z({...et.shape,...dk.shape,progressToken:wg}),xa=tt.extend({method:T("notifications/progress"),params:pk}),fk=Be.extend({cursor:zg.optional()}),ko=xe.extend({params:fk.optional()}),So=ke.extend({nextCursor:zg.optional()}),mk=Te(["working","input_required","completed","failed","cancelled"]),wo=z({taskId:h(),status:mk,ttl:ie([ne(),_o()]),createdAt:h(),lastUpdatedAt:h(),pollInterval:fe(ne()),statusMessage:fe(h())}),Qr=ke.extend({task:wo}),hk=et.merge(wo),zo=tt.extend({method:T("notifications/tasks/status"),params:hk}),ka=xe.extend({method:T("tasks/get"),params:Be.extend({taskId:h()})}),Sa=ke.merge(wo),wa=xe.extend({method:T("tasks/result"),params:Be.extend({taskId:h()})}),m4=ke.loose(),za=ko.extend({method:T("tasks/list")}),Ia=So.extend({tasks:G(wo)}),Ea=xe.extend({method:T("tasks/cancel"),params:Be.extend({taskId:h()})}),Ng=ke.merge(wo),Rg=z({uri:h(),mimeType:fe(h()),_meta:pe(h(),ue()).optional()}),Ag=Rg.extend({text:h()}),cd=h().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Ug=Rg.extend({blob:cd}),Io=Te(["user","assistant"]),en=z({audience:G(Io).optional(),priority:ne().min(0).max(1).optional(),lastModified:vr.datetime({offset:!0}).optional()}),Cg=z({...Yr.shape,...xo.shape,uri:h(),description:fe(h()),mimeType:fe(h()),annotations:en.optional(),_meta:fe(Ee({}))}),gk=z({...Yr.shape,...xo.shape,uriTemplate:h(),description:fe(h()),mimeType:fe(h()),annotations:en.optional(),_meta:fe(Ee({}))}),vk=ko.extend({method:T("resources/list")}),_k=So.extend({resources:G(Cg)}),yk=ko.extend({method:T("resources/templates/list")}),$k=So.extend({resourceTemplates:G(gk)}),ud=Be.extend({uri:h()}),bk=ud,xk=xe.extend({method:T("resources/read"),params:bk}),kk=ke.extend({contents:G(ie([Ag,Ug]))}),Sk=tt.extend({method:T("notifications/resources/list_changed"),params:et.optional()}),wk=ud,zk=xe.extend({method:T("resources/subscribe"),params:wk}),Ik=ud,Ek=xe.extend({method:T("resources/unsubscribe"),params:Ik}),Tk=et.extend({uri:h()}),Pk=tt.extend({method:T("notifications/resources/updated"),params:Tk}),Ok=z({name:h(),description:fe(h()),required:fe(_e())}),jk=z({...Yr.shape,...xo.shape,description:fe(h()),arguments:fe(G(Ok)),_meta:fe(Ee({}))}),Dk=ko.extend({method:T("prompts/list")}),Nk=So.extend({prompts:G(jk)}),Rk=Be.extend({name:h(),arguments:pe(h(),h()).optional()}),Ak=xe.extend({method:T("prompts/get"),params:Rk}),ld=z({type:T("text"),text:h(),annotations:en.optional(),_meta:pe(h(),ue()).optional()}),dd=z({type:T("image"),data:cd,mimeType:h(),annotations:en.optional(),_meta:pe(h(),ue()).optional()}),pd=z({type:T("audio"),data:cd,mimeType:h(),annotations:en.optional(),_meta:pe(h(),ue()).optional()}),Uk=z({type:T("tool_use"),name:h(),id:h(),input:pe(h(),ue()),_meta:pe(h(),ue()).optional()}),Ck=z({type:T("resource"),resource:ie([Ag,Ug]),annotations:en.optional(),_meta:pe(h(),ue()).optional()}),Mk=Cg.extend({type:T("resource_link")}),fd=ie([ld,dd,pd,Mk,Ck]),Zk=z({role:Io,content:fd}),Lk=ke.extend({description:h().optional(),messages:G(Zk)}),qk=tt.extend({method:T("notifications/prompts/list_changed"),params:et.optional()}),Fk=z({title:h().optional(),readOnlyHint:_e().optional(),destructiveHint:_e().optional(),idempotentHint:_e().optional(),openWorldHint:_e().optional()}),Vk=z({taskSupport:Te(["required","optional","forbidden"]).optional()}),Mg=z({...Yr.shape,...xo.shape,description:h().optional(),inputSchema:z({type:T("object"),properties:pe(h(),be).optional(),required:G(h()).optional()}).catchall(ue()),outputSchema:z({type:T("object"),properties:pe(h(),be).optional(),required:G(h()).optional()}).catchall(ue()).optional(),annotations:Fk.optional(),execution:Vk.optional(),_meta:pe(h(),ue()).optional()}),md=ko.extend({method:T("tools/list")}),Jk=So.extend({tools:G(Mg)}),Ta=ke.extend({content:G(fd).default([]),structuredContent:pe(h(),ue()).optional(),isError:_e().optional()}),h4=Ta.or(ke.extend({toolResult:ue()})),Kk=$o.extend({name:h(),arguments:pe(h(),ue()).optional()}),Eo=xe.extend({method:T("tools/call"),params:Kk}),Hk=tt.extend({method:T("notifications/tools/list_changed"),params:et.optional()}),g4=z({autoRefresh:_e().default(!0),debounceMs:ne().int().nonnegative().default(300)}),To=Te(["debug","info","notice","warning","error","critical","alert","emergency"]),Wk=Be.extend({level:To}),hd=xe.extend({method:T("logging/setLevel"),params:Wk}),Gk=et.extend({level:To,logger:h().optional(),data:ue()}),Bk=tt.extend({method:T("notifications/message"),params:Gk}),Xk=z({name:h().optional()}),Yk=z({hints:G(Xk).optional(),costPriority:ne().min(0).max(1).optional(),speedPriority:ne().min(0).max(1).optional(),intelligencePriority:ne().min(0).max(1).optional()}),Qk=z({mode:Te(["auto","required","none"]).optional()}),eS=z({type:T("tool_result"),toolUseId:h().describe("The unique identifier for the corresponding tool call."),content:G(fd).default([]),structuredContent:z({}).loose().optional(),isError:_e().optional(),_meta:pe(h(),ue()).optional()}),tS=pa("type",[ld,dd,pd]),ga=pa("type",[ld,dd,pd,Uk,eS]),rS=z({role:Io,content:ie([ga,G(ga)]),_meta:pe(h(),ue()).optional()}),nS=$o.extend({messages:G(rS),modelPreferences:Yk.optional(),systemPrompt:h().optional(),includeContext:Te(["none","thisServer","allServers"]).optional(),temperature:ne().optional(),maxTokens:ne().int(),stopSequences:G(h()).optional(),metadata:be.optional(),tools:G(Mg).optional(),toolChoice:Qk.optional()}),oS=xe.extend({method:T("sampling/createMessage"),params:nS}),gd=ke.extend({model:h(),stopReason:fe(Te(["endTurn","stopSequence","maxTokens"]).or(h())),role:Io,content:tS}),vd=ke.extend({model:h(),stopReason:fe(Te(["endTurn","stopSequence","maxTokens","toolUse"]).or(h())),role:Io,content:ie([ga,G(ga)])}),iS=z({type:T("boolean"),title:h().optional(),description:h().optional(),default:_e().optional()}),aS=z({type:T("string"),title:h().optional(),description:h().optional(),minLength:ne().optional(),maxLength:ne().optional(),format:Te(["email","uri","date","date-time"]).optional(),default:h().optional()}),sS=z({type:Te(["number","integer"]),title:h().optional(),description:h().optional(),minimum:ne().optional(),maximum:ne().optional(),default:ne().optional()}),cS=z({type:T("string"),title:h().optional(),description:h().optional(),enum:G(h()),default:h().optional()}),uS=z({type:T("string"),title:h().optional(),description:h().optional(),oneOf:G(z({const:h(),title:h()})),default:h().optional()}),lS=z({type:T("string"),title:h().optional(),description:h().optional(),enum:G(h()),enumNames:G(h()).optional(),default:h().optional()}),dS=ie([cS,uS]),pS=z({type:T("array"),title:h().optional(),description:h().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:z({type:T("string"),enum:G(h())}),default:G(h()).optional()}),fS=z({type:T("array"),title:h().optional(),description:h().optional(),minItems:ne().optional(),maxItems:ne().optional(),items:z({anyOf:G(z({const:h(),title:h()}))}),default:G(h()).optional()}),mS=ie([pS,fS]),hS=ie([lS,dS,mS]),gS=ie([hS,iS,aS,sS]),vS=$o.extend({mode:T("form").optional(),message:h(),requestedSchema:z({type:T("object"),properties:pe(h(),gS),required:G(h()).optional()})}),_S=$o.extend({mode:T("url"),message:h(),elicitationId:h(),url:h().url()}),yS=ie([vS,_S]),$S=xe.extend({method:T("elicitation/create"),params:yS}),bS=et.extend({elicitationId:h()}),xS=tt.extend({method:T("notifications/elicitation/complete"),params:bS}),Pa=ke.extend({action:Te(["accept","decline","cancel"]),content:ha(t=>t===null?void 0:t,pe(h(),ie([h(),ne(),_e(),G(h())])).optional())}),kS=z({type:T("ref/resource"),uri:h()});var SS=z({type:T("ref/prompt"),name:h()}),wS=Be.extend({ref:ie([SS,kS]),argument:z({name:h(),value:h()}),context:z({arguments:pe(h(),h()).optional()}).optional()}),zS=xe.extend({method:T("completion/complete"),params:wS});var IS=ke.extend({completion:Ee({values:G(h()).max(100),total:fe(ne().int()),hasMore:fe(_e())})}),ES=z({uri:h().startsWith("file://"),name:h().optional(),_meta:pe(h(),ue()).optional()}),TS=xe.extend({method:T("roots/list"),params:Be.optional()}),_d=ke.extend({roots:G(ES)}),PS=tt.extend({method:T("notifications/roots/list_changed"),params:et.optional()}),v4=ie([ba,ad,zS,hd,Ak,Dk,vk,yk,xk,zk,Ek,Eo,md,ka,wa,za,Ea]),_4=ie([$a,xa,sd,PS,zo]),y4=ie([ya,gd,vd,Pa,_d,Sa,Ia,Qr]),$4=ie([ba,oS,$S,TS,ka,wa,za,Ea]),b4=ie([$a,xa,Bk,Pk,Sk,Hk,qk,zo,xS]),x4=ie([ya,lk,IS,Lk,Nk,_k,$k,kk,Ta,Jk,Sa,Ia,Qr]),V=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===Y.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ed(o.elicitations,r)}return new t(e,r,n)}},ed=class extends V{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Y.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function er(t){return t==="completed"||t==="failed"||t==="cancelled"}var r1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function yd(t){let r=ea(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=kh(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function $d(t,e){let r=Yt(t,e);if(!r.success)throw r.error;return r.data}var AS=6e4,Oa=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler($a,r=>{this._oncancel(r)}),this.setNotificationHandler(xa,r=>{this._onprogress(r)}),this.setRequestHandler(ba,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ka,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new V(Y.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(wa,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),s.type==="response")l(c);else{let d=c,m=new V(d.error.code,d.error.message,d.error.data);l(m)}else{let d=s.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(i,n.sessionId);if(!a)throw new V(Y.InvalidParams,`Task not found: ${i}`);if(!er(a.status))return await this._waitForTaskUpdate(i,n.signal),await o();if(er(a.status)){let s=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...s,_meta:{...s._meta,[Qt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(za,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new V(Y.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ea,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new V(Y.InvalidParams,`Task not found: ${r.params.taskId}`);if(er(o.status))throw new V(Y.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new V(Y.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof V?o:new V(Y.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),V.fromError(Y.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,a)=>{o?.(i,a),bo(i)||Og(i)?this._onresponse(i):nd(i)?this._onrequest(i,a):Pg(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=V.fromError(Y.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,i=e.params?._meta?.[Qt]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Y.MethodNotFound,message:"Method not found"}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=Ig(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:a.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};i&&(d.relatedTask={taskId:i}),await this.notification(l,d)},sendRequest:async(l,d,m)=>{if(a.signal.aborted)throw new V(Y.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};i&&!f.relatedTask&&(f.relatedTask={taskId:i});let g=f.relatedTask?.taskId??i;return g&&c&&await c.updateTaskStatus(g,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:i,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(a.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Y.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(o),s=this._timeoutInfo.get(o);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),a(c);return}i(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),bo(e))n(e);else{let a=new V(e.error.code,e.error.message,e.error.data);n(a)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(bo(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(i=!0,this._taskProgressTokens.set(s.taskId,r))}}if(i||this._progressHandlers.delete(r),bo(e))o(e);else{let a=V.fromError(e.error.code,e.error.message,e.error.data);o(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof V?a:new V(Y.InternalError,String(a))}}return}let i;try{let a=await this.request(e,Qr,n);if(a.task)i=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new V(Y.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:s},er(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:s.status==="failed"?yield{type:"error",error:new V(Y.InternalError,`Task ${i} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new V(Y.InternalError,`Task ${i} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof V?a:new V(Y.InternalError,String(a))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a,task:s,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=O=>{l(O)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(O){d(O);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),s&&(f.params={...f.params,task:s}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Qt]:c}});let g=O=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(O)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(C=>this._onerror(new Error(`Failed to send cancellation: ${C}`)));let I=O instanceof V?O:new V(Y.RequestTimeout,String(O));l(I)};this._responseHandlers.set(m,O=>{if(!n?.signal?.aborted){if(O instanceof Error)return l(O);try{let I=Yt(r,O.result);I.success?u(I.data):l(I.error)}catch(I){l(I)}}}),n?.signal?.addEventListener("abort",()=>{g(n?.signal?.reason)});let v=n?.timeout??AS,$=()=>g(V.fromError(Y.RequestTimeout,"Request timed out",{timeout:v}));this._setupTimeout(m,v,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let k=c?.taskId;if(k){let O=I=>{let C=this._responseHandlers.get(m);C?C(I):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,O),this._enqueueTaskMessage(k,{type:"request",message:f,timestamp:Date.now()}).catch(I=>{this._cleanupTimeout(m),l(I)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:a}).catch(O=>{this._cleanupTimeout(m),l(O)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Sa,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ia,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Ng,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Qt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Qt]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Qt]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let n=yd(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let a=$d(e,o);return Promise.resolve(r(a,i))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=yd(e);this._notificationHandlers.set(n,o=>{let i=$d(e,o);return Promise.resolve(r(i))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&nd(o.message)){let i=o.message.id,a=this._requestResolvers.get(i);a?(a(new V(Y.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,i)=>{if(r.aborted){i(new V(Y.InvalidRequest,"Request cancelled"));return}let a=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(a),i(new V(Y.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new V(Y.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,a)=>{await n.storeTaskResult(o,i,a,r);let s=await n.getTask(o,r);if(s){let c=zo.parse({method:"notifications/tasks/status",params:s});await this.notification(c),er(s.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,a)=>{let s=await n.getTask(o,r);if(!s)throw new V(Y.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(er(s.status))throw new V(Y.InvalidParams,`Cannot update task "${o}" from terminal status "${s.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,a,r);let c=await n.getTask(o,r);if(c){let u=zo.parse({method:"notifications/tasks/status",params:c});await this.notification(u),er(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function Zg(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Lg(t,e){let r={...t};for(let n in e){let o=n,i=e[o];if(i===void 0)continue;let a=r[o];Zg(a)&&Zg(i)?r[o]={...a,...i}:r[o]=i}return r}var Iy=ci(af(),1),Ey=ci(zy(),1);function IT(){let t=new Iy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ey.default)(t),t}var fs=class{constructor(e){this._ajv=e??IT()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var ms=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function Ty(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Py(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var hs=class extends Oa{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(To.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new fs,this.setRequestHandler(ad,n=>this._oninitialize(n)),this.setNotificationHandler(sd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(hd,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,s=To.safeParse(a);return s.success&&this._loggingLevels.set(i,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ms(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Lg(this._capabilities,e)}setRequestHandler(e,r){let o=ea(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(Br(o)){let s=o;i=s._zod?.def?.value??s.value}else{let s=o;i=s._def?.value??s.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let s=async(c,u)=>{let l=Yt(Eo,c);if(!l.success){let g=l.error instanceof Error?l.error.message:String(l.error);throw new V(Y.InvalidParams,`Invalid tools/call request: ${g}`)}let{params:d}=l.data,m=await Promise.resolve(r(c,u));if(d.task){let g=Yt(Qr,m);if(!g.success){let v=g.error instanceof Error?g.error.message:String(g.error);throw new V(Y.InvalidParams,`Invalid task creation result: ${v}`)}return g.data}let f=Yt(Ta,m);if(!f.success){let g=f.error instanceof Error?f.error.message:String(f.error);throw new V(Y.InvalidParams,`Invalid tools/call result: ${g}`)}return f.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Py(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Ty(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Sg.includes(r)?r:td,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ya)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(s.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},vd,r):this.request({method:"sampling/createMessage",params:e},gd,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Pa,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Pa,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!s.valid)throw new V(Y.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof V?a:new V(Y.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return i}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},_d,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var mf=ci(require("node:process"),1);var gs=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
56
56
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),ET(r)}clear(){this._buffer=void 0}};function ET(t){return jg.parse(JSON.parse(t))}function Oy(t){return JSON.stringify(t)+`
|
|
57
|
-
`}var vs=class{constructor(e=mf.default.stdin,r=mf.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new gs,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Oy(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var gf=ci(require("path"),1);var hf={DEFAULT:3e5,HEALTH_CHECK:3e3,POST_SPAWN_WAIT:5e3,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function jy(t){return process.platform==="win32"?Math.round(t*hf.WINDOWS_MULTIPLIER):t}var wt=require("fs"),_s=require("path"),Ry=require("os");var Dy="bugfix,feature,refactor,discovery,decision,change",Ny="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off";var qt=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,_s.join)((0,Ry.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:Dy,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:Ny,CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e){try{if(!(0,wt.existsSync)(e)){let a=this.getAllDefaults();try{let s=(0,_s.dirname)(e);(0,wt.existsSync)(s)||(0,wt.mkdirSync)(s,{recursive:!0}),(0,wt.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(s){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,s)}return this.applyEnvOverrides(a)}let r=(0,wt.readFileSync)(e,"utf-8"),n=JSON.parse(r),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{(0,wt.writeFileSync)(e,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a)}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))o[a]!==void 0&&(i[a]=o[a]);return this.applyEnvOverrides(i)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.applyEnvOverrides(this.getAllDefaults())}}};var $e=require("path"),Ay=require("os");var Uy=require("url");var OT={};function TT(){return typeof __dirname<"u"?__dirname:(0,$e.dirname)((0,Uy.fileURLToPath)(OT.url))}var MC=TT(),Ft=qt.get("CLAUDE_MEM_DATA_DIR"),ys=process.env.CLAUDE_CONFIG_DIR||(0,$e.join)((0,Ay.homedir)(),".claude"),PT=(0,$e.join)(ys,"plugins","marketplaces","thedotmack"),ZC=(0,$e.join)(Ft,"archives"),LC=(0,$e.join)(Ft,"logs"),qC=(0,$e.join)(Ft,"trash"),FC=(0,$e.join)(Ft,"backups"),VC=(0,$e.join)(Ft,"modes"),JC=(0,$e.join)(Ft,"settings.json"),KC=(0,$e.join)(Ft,"claude-mem.db"),HC=(0,$e.join)(Ft,"vector-db"),WC=(0,$e.join)(Ft,"observer-sessions"),GC=(0,$e.join)(ys,"settings.json"),BC=(0,$e.join)(ys,"commands"),XC=(0,$e.join)(ys,"CLAUDE.md");var nM=(()=>{let t=process.env.CLAUDE_MEM_HEALTH_TIMEOUT_MS;if(t){let e=parseInt(t,10);if(Number.isFinite(e)&&e>=500&&e<=3e5)return e;ge.warn("SYSTEM","Invalid CLAUDE_MEM_HEALTH_TIMEOUT_MS, using default",{value:t,min:500,max:3e5})}return jy(hf.HEALTH_CHECK)})();var $s=null,bs=null;function Cy(){if($s!==null)return $s;let t=gf.default.join(qt.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=qt.loadFromFile(t);return $s=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),$s}function My(){if(bs!==null)return bs;let t=gf.default.join(qt.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return bs=qt.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,bs}var jT="10.3.
|
|
57
|
+
`}var vs=class{constructor(e=mf.default.stdin,r=mf.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new gs,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Oy(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var gf=ci(require("path"),1);var hf={DEFAULT:3e5,HEALTH_CHECK:3e3,POST_SPAWN_WAIT:5e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5};function jy(t){return process.platform==="win32"?Math.round(t*hf.WINDOWS_MULTIPLIER):t}var wt=require("fs"),_s=require("path"),Ry=require("os");var Dy="bugfix,feature,refactor,discovery,decision,change",Ny="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off";var qt=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-sonnet-4-5",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:"37777",CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"cli",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,_s.join)((0,Ry.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:Dy,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:Ny,CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let r=this.get(e);return parseInt(r,10)}static getBool(e){let r=this.get(e);return r==="true"||r===!0}static applyEnvOverrides(e){let r={...e};for(let n of Object.keys(this.DEFAULTS))process.env[n]!==void 0&&(r[n]=process.env[n]);return r}static loadFromFile(e){try{if(!(0,wt.existsSync)(e)){let a=this.getAllDefaults();try{let s=(0,_s.dirname)(e);(0,wt.existsSync)(s)||(0,wt.mkdirSync)(s,{recursive:!0}),(0,wt.writeFileSync)(e,JSON.stringify(a,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(s){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,s)}return this.applyEnvOverrides(a)}let r=(0,wt.readFileSync)(e,"utf-8"),n=JSON.parse(r),o=n;if(n.env&&typeof n.env=="object"){o=n.env;try{(0,wt.writeFileSync)(e,JSON.stringify(o,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(a){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,a)}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))o[a]!==void 0&&(i[a]=o[a]);return this.applyEnvOverrides(i)}catch(r){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,r),this.applyEnvOverrides(this.getAllDefaults())}}};var $e=require("path"),Ay=require("os");var Uy=require("url");var OT={};function TT(){return typeof __dirname<"u"?__dirname:(0,$e.dirname)((0,Uy.fileURLToPath)(OT.url))}var MC=TT(),Ft=qt.get("CLAUDE_MEM_DATA_DIR"),ys=process.env.CLAUDE_CONFIG_DIR||(0,$e.join)((0,Ay.homedir)(),".claude"),PT=(0,$e.join)(ys,"plugins","marketplaces","thedotmack"),ZC=(0,$e.join)(Ft,"archives"),LC=(0,$e.join)(Ft,"logs"),qC=(0,$e.join)(Ft,"trash"),FC=(0,$e.join)(Ft,"backups"),VC=(0,$e.join)(Ft,"modes"),JC=(0,$e.join)(Ft,"settings.json"),KC=(0,$e.join)(Ft,"claude-mem.db"),HC=(0,$e.join)(Ft,"vector-db"),WC=(0,$e.join)(Ft,"observer-sessions"),GC=(0,$e.join)(ys,"settings.json"),BC=(0,$e.join)(ys,"commands"),XC=(0,$e.join)(ys,"CLAUDE.md");var nM=(()=>{let t=process.env.CLAUDE_MEM_HEALTH_TIMEOUT_MS;if(t){let e=parseInt(t,10);if(Number.isFinite(e)&&e>=500&&e<=3e5)return e;ge.warn("SYSTEM","Invalid CLAUDE_MEM_HEALTH_TIMEOUT_MS, using default",{value:t,min:500,max:3e5})}return jy(hf.HEALTH_CHECK)})();var $s=null,bs=null;function Cy(){if($s!==null)return $s;let t=gf.default.join(qt.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=qt.loadFromFile(t);return $s=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),$s}function My(){if(bs!==null)return bs;let t=gf.default.join(qt.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return bs=qt.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,bs}var jT="10.3.2";console.log=(...t)=>{ge.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var DT=Cy(),NT=My(),si=`http://${NT}:${DT}`,Zy={search:"/api/search",timeline:"/api/timeline"};async function Ly(t,e){ge.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});try{let r=new URLSearchParams;for(let[a,s]of Object.entries(e))s!=null&&r.append(a,String(s));let n=`${si}${t}?${r}`,o=await fetch(n);if(!o.ok){let a=await o.text();throw new Error(`Worker API error (${o.status}): ${a}`)}let i=await o.json();return ge.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),i}catch(r){return ge.error("SYSTEM","\u2190 Worker API error",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function qy(t,e){ge.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{let r=`${si}${t}`,n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok){let i=await n.text();throw new Error(`Worker API error (${n.status}): ${i}`)}let o=await n.json();return ge.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(o,null,2)}]}}catch(r){return ge.error("HTTP","Worker API error (POST)",{endpoint:t},r),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function RT(){try{return(await fetch(`${si}/api/health`)).ok}catch(t){return ge.debug("SYSTEM","Worker health check failed",{},t),!1}}var Fy=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
|
|
58
58
|
1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
|
|
59
59
|
2. timeline(anchor=ID) \u2192 Get context around interesting results
|
|
60
60
|
3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
|
|
@@ -74,4 +74,4 @@ NEVER fetch full details without filtering first. 10x token savings.`,inputSchem
|
|
|
74
74
|
\`get_observations(ids=[...])\` # ALWAYS batch for 2+ items
|
|
75
75
|
Returns: Complete details (~500-1000 tokens/result)
|
|
76
76
|
|
|
77
|
-
**Why:** 10x token savings. Never fetch full details without filtering first.`}]})},{name:"search",description:"Step 1: Search memory. Returns index with IDs. Params: query, limit, project, type, obs_type, dateStart, dateEnd, offset, orderBy",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>{let e=Zy.search;return await Ly(e,t)}},{name:"timeline",description:"Step 2: Get context around results. Params: anchor (observation ID) OR query (finds anchor automatically), depth_before, depth_after, project",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>{let e=Zy.timeline;return await Ly(e,t)}},{name:"get_observations",description:"Step 3: Fetch full details for filtered IDs. Params: ids (array of observation IDs, required), orderBy, limit, project",inputSchema:{type:"object",properties:{ids:{type:"array",items:{type:"number"},description:"Array of observation IDs to fetch (required)"}},required:["ids"],additionalProperties:!0},handler:async t=>await qy("/api/observations/batch",t)},{name:"
|
|
77
|
+
**Why:** 10x token savings. Never fetch full details without filtering first.`}]})},{name:"search",description:"Step 1: Search memory. Returns index with IDs. Params: query, limit, project, type, obs_type, dateStart, dateEnd, offset, orderBy",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>{let e=Zy.search;return await Ly(e,t)}},{name:"timeline",description:"Step 2: Get context around results. Params: anchor (observation ID) OR query (finds anchor automatically), depth_before, depth_after, project",inputSchema:{type:"object",properties:{},additionalProperties:!0},handler:async t=>{let e=Zy.timeline;return await Ly(e,t)}},{name:"get_observations",description:"Step 3: Fetch full details for filtered IDs. Params: ids (array of observation IDs, required), orderBy, limit, project",inputSchema:{type:"object",properties:{ids:{type:"array",items:{type:"number"},description:"Array of observation IDs to fetch (required)"}},required:["ids"],additionalProperties:!0},handler:async t=>await qy("/api/observations/batch",t)},{name:"save_observation",description:"Save an observation to the database. Params: text (required), title, project",inputSchema:{type:"object",properties:{text:{type:"string",description:"Content to remember (required)"},title:{type:"string",description:"Short title (auto-generated from text if omitted)"},project:{type:"string",description:'Project name (uses "claude-mem" if omitted)'}},required:["text"]},handler:async t=>await qy("/api/memory/save",t)}],vf=new hs({name:"claude-mem",version:jT},{capabilities:{tools:{}}});vf.setRequestHandler(md,async()=>({tools:Fy.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))}));vf.setRequestHandler(Eo,async t=>{let e=Fy.find(r=>r.name===t.params.name);if(!e)throw new Error(`Unknown tool: ${t.params.name}`);try{return await e.handler(t.params.arguments||{})}catch(r){return ge.error("SYSTEM","Tool execution failed",{tool:t.params.name},r),{content:[{type:"text",text:`Tool execution failed: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}});var AT=3e4,ai=null;function UT(){if(process.platform==="win32")return;let t=process.ppid;ai=setInterval(()=>{(process.ppid===1||process.ppid!==t)&&(ge.info("SYSTEM","Parent process died, self-exiting to prevent orphan",{initialPpid:t,currentPpid:process.ppid}),_f())},AT),ai.unref&&ai.unref()}function _f(){ai&&clearInterval(ai),ge.info("SYSTEM","MCP server shutting down"),process.exit(0)}process.on("SIGTERM",_f);process.on("SIGINT",_f);async function CT(){let t=new vs;await vf.connect(t),ge.info("SYSTEM","Claude-mem search server started"),UT(),setTimeout(async()=>{await RT()?ge.info("SYSTEM","Worker available",void 0,{workerUrl:si}):(ge.error("SYSTEM","Worker not available",void 0,{workerUrl:si}),ge.error("SYSTEM","Tools will fail until Worker is started"),ge.error("SYSTEM","Start Worker with: npm run worker:restart"))},0)}CT().catch(t=>{ge.error("SYSTEM","Fatal error",void 0,t),process.exit(0)});
|