diff --git a/package.json b/package.json index 6adb1713..27e1047b 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "sync-marketplace:force": "node scripts/sync-marketplace.cjs --force", "build:binaries": "node scripts/build-worker-binary.js", "worker:logs": "tail -n 50 ~/.claude-mem/logs/worker-$(date +%Y-%m-%d).log", + "worker:tail": "tail -f 50 ~/.claude-mem/logs/worker-$(date +%Y-%m-%d).log", "changelog:generate": "node scripts/generate-changelog.js", "discord:notify": "node scripts/discord-release-notify.js", "worker:start": "bun plugin/scripts/worker-cli.js start", diff --git a/plugin/scripts/context-generator.cjs b/plugin/scripts/context-generator.cjs index 58a244a5..333aacf1 100644 --- a/plugin/scripts/context-generator.cjs +++ b/plugin/scripts/context-generator.cjs @@ -1,13 +1,13 @@ -"use strict";var je=Object.create;var J=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var Ye=(d,e)=>{for(var s in e)J(d,s,{get:e[s],enumerable:!0})},ge=(d,e,s,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of He(e))!Be.call(d,n)&&n!==s&&J(d,n,{get:()=>e[n],enumerable:!(t=We(e,n))||t.enumerable});return d};var ie=(d,e,s)=>(s=d!=null?je(Ge(d)):{},ge(e||!d||!d.__esModule?J(s,"default",{value:d,enumerable:!0}):s,d)),Ve=d=>ge(J({},"__esModule",{value:!0}),d);var ns={};Ye(ns,{generateContext:()=>rs});module.exports=Ve(ns);var ee=ie(require("path"),1),se=require("os"),H=require("fs");var Ce=require("bun:sqlite");var f=require("path"),Re=require("os"),Oe=require("fs");var Ne=require("url");var j=require("fs"),be=require("path"),fe=require("os");var he="bugfix,feature,refactor,discovery,decision,change",Se="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off";var oe=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(oe||{}),ae=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let e=$.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=oe[e]??1}return this.level}correlationId(e,s){return`obs-${e}-${s}`}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} -${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Object.keys(e);return s.length===0?"{}":s.length<=3?JSON.stringify(e):`{${s.length} keys: ${s.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,s){if(!s)return e;let t=typeof s=="string"?JSON.parse(s):s;if(e==="Bash"&&t.command)return`${e}(${t.command})`;if(t.file_path)return`${e}(${t.file_path})`;if(t.notebook_path)return`${e}(${t.notebook_path})`;if(e==="Glob"&&t.pattern)return`${e}(${t.pattern})`;if(e==="Grep"&&t.pattern)return`${e}(${t.pattern})`;if(t.url)return`${e}(${t.url})`;if(t.query)return`${e}(${t.query})`;if(e==="Task"){if(t.subagent_type)return`${e}(${t.subagent_type})`;if(t.description)return`${e}(${t.description})`}return e==="Skill"&&t.skill?`${e}(${t.skill})`:e==="LSP"&&t.operation?`${e}(${t.operation})`:e}formatTimestamp(e){let s=e.getFullYear(),t=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),p=String(e.getMilliseconds()).padStart(3,"0");return`${s}-${t}-${n} ${i}:${a}:${c}.${p}`}log(e,s,t,n,i){if(e0&&(E=` {${Object.entries(r).map(([O,D])=>`${O}=${D}`).join(", ")}}`)}let R=`[${a}] [${c}] [${p}] ${u}${t}${E}${l}`;e===3?console.error(R):console.log(R)}debug(e,s,t,n){this.log(0,e,s,t,n)}info(e,s,t,n){this.log(1,e,s,t,n)}warn(e,s,t,n){this.log(2,e,s,t,n)}error(e,s,t,n){this.log(3,e,s,t,n)}dataIn(e,s,t,n){this.info(e,`\u2192 ${s}`,t,n)}dataOut(e,s,t,n){this.info(e,`\u2190 ${s}`,t,n)}success(e,s,t,n){this.info(e,`\u2713 ${s}`,t,n)}failure(e,s,t,n){this.error(e,`\u2717 ${s}`,t,n)}timing(e,s,t,n){this.info(e,`\u23F1 ${s}`,n,{duration:`${t}ms`})}happyPathError(e,s,t,n,i=""){let u=((new Error().stack||"").split(` -`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),l=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",E={...t,location:l};return this.warn(e,`[HAPPY-PATH] ${s}`,E,n),i}},h=new ae;var $=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_DATA_DIR:(0,be.join)((0,fe.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:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:he,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:Se,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",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"};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return this.DEFAULTS[e]}static getInt(e){let s=this.get(e);return parseInt(s,10)}static getBool(e){return this.get(e)==="true"}static loadFromFile(e){try{if(!(0,j.existsSync)(e))return this.getAllDefaults();let s=(0,j.readFileSync)(e,"utf-8"),t=JSON.parse(s),n=t;if(t.env&&typeof t.env=="object"){n=t.env;try{(0,j.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),h.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:e})}catch(a){h.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:e},a)}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))n[a]!==void 0&&(i[a]=n[a]);return i}catch(s){return h.warn("SETTINGS","Failed to load settings, using defaults",{settingsPath:e},s),this.getAllDefaults()}}};var Je={};function Ke(){return typeof __dirname<"u"?__dirname:(0,f.dirname)((0,Ne.fileURLToPath)(Je.url))}var qe=Ke(),v=$.get("CLAUDE_MEM_DATA_DIR"),de=process.env.CLAUDE_CONFIG_DIR||(0,f.join)((0,Re.homedir)(),".claude"),gs=(0,f.join)(v,"archives"),hs=(0,f.join)(v,"logs"),Ss=(0,f.join)(v,"trash"),bs=(0,f.join)(v,"backups"),fs=(0,f.join)(v,"modes"),Rs=(0,f.join)(v,"settings.json"),Ae=(0,f.join)(v,"claude-mem.db"),Os=(0,f.join)(v,"vector-db"),Ns=(0,f.join)(de,"settings.json"),As=(0,f.join)(de,"commands"),Is=(0,f.join)(de,"CLAUDE.md");function Ie(d){(0,Oe.mkdirSync)(d,{recursive:!0})}function Le(){return(0,f.join)(qe,"..")}var Q=class{db;constructor(){Ie(v),this.db=new Ce.Database(Ae),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()}initializeSchema(){try{this.db.run(` +"use strict";var je=Object.create;var J=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var He=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Be=Object.prototype.hasOwnProperty;var Ye=(d,e)=>{for(var t in e)J(d,t,{get:e[t],enumerable:!0})},ge=(d,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of He(e))!Be.call(d,n)&&n!==t&&J(d,n,{get:()=>e[n],enumerable:!(s=We(e,n))||s.enumerable});return d};var ie=(d,e,t)=>(t=d!=null?je(Ge(d)):{},ge(e||!d||!d.__esModule?J(t,"default",{value:d,enumerable:!0}):t,d)),Ve=d=>ge(J({},"__esModule",{value:!0}),d);var nt={};Ye(nt,{generateContext:()=>rt});module.exports=Ve(nt);var ee=ie(require("path"),1),te=require("os"),H=require("fs");var Ce=require("bun:sqlite");var f=require("path"),Re=require("os"),Oe=require("fs");var Ne=require("url");var W=require("fs"),be=require("path"),fe=require("os");var he="bugfix,feature,refactor,discovery,decision,change",Se="how-it-works,why-it-exists,what-changed,problem-solution,gotcha,pattern,trade-off";var oe=(i=>(i[i.DEBUG=0]="DEBUG",i[i.INFO=1]="INFO",i[i.WARN=2]="WARN",i[i.ERROR=3]="ERROR",i[i.SILENT=4]="SILENT",i))(oe||{}),ae=class{level=null;useColor;constructor(){this.useColor=process.stdout.isTTY??!1}getLevel(){if(this.level===null){let e=$.get("CLAUDE_MEM_LOG_LEVEL").toUpperCase();this.level=oe[e]??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} +${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=typeof t=="string"?JSON.parse(t):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"),i=String(e.getHours()).padStart(2,"0"),a=String(e.getMinutes()).padStart(2,"0"),c=String(e.getSeconds()).padStart(2,"0"),p=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${s}-${n} ${i}:${a}:${c}.${p}`}log(e,t,s,n,i){if(e0&&(E=` {${Object.entries(r).map(([O,D])=>`${O}=${D}`).join(", ")}}`)}let R=`[${a}] [${c}] [${p}] ${u}${s}${E}${l}`;e===3?console.error(R):console.log(R)}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,i=""){let u=((new Error().stack||"").split(` +`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),l=u?`${u[1].split("/").pop()}:${u[2]}`:"unknown",E={...s,location:l};return this.warn(e,`[HAPPY-PATH] ${t}`,E,n),i}},h=new ae;var $=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_DATA_DIR:(0,be.join)((0,fe.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:"true",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"true",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES:he,CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS:Se,CLAUDE_MEM_CONTEXT_FULL_COUNT:"5",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"};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){return this.get(e)==="true"}static loadFromFile(e){try{if(!(0,W.existsSync)(e))return this.getAllDefaults();let t=(0,W.readFileSync)(e,"utf-8"),s=JSON.parse(t),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{(0,W.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),h.info("SETTINGS","Migrated settings file from nested to flat schema",{settingsPath:e})}catch(a){h.warn("SETTINGS","Failed to auto-migrate settings file",{settingsPath:e},a)}}let i={...this.DEFAULTS};for(let a of Object.keys(this.DEFAULTS))n[a]!==void 0&&(i[a]=n[a]);return i}catch(t){return h.warn("SETTINGS","Failed to load settings, using defaults",{settingsPath:e},t),this.getAllDefaults()}}};var Je={};function Ke(){return typeof __dirname<"u"?__dirname:(0,f.dirname)((0,Ne.fileURLToPath)(Je.url))}var qe=Ke(),v=$.get("CLAUDE_MEM_DATA_DIR"),de=process.env.CLAUDE_CONFIG_DIR||(0,f.join)((0,Re.homedir)(),".claude"),gt=(0,f.join)(v,"archives"),ht=(0,f.join)(v,"logs"),St=(0,f.join)(v,"trash"),bt=(0,f.join)(v,"backups"),ft=(0,f.join)(v,"modes"),Rt=(0,f.join)(v,"settings.json"),Ae=(0,f.join)(v,"claude-mem.db"),Ot=(0,f.join)(v,"vector-db"),Nt=(0,f.join)(de,"settings.json"),At=(0,f.join)(de,"commands"),It=(0,f.join)(de,"CLAUDE.md");function Ie(d){(0,Oe.mkdirSync)(d,{recursive:!0})}function Le(){return(0,f.join)(qe,"..")}var Q=class{db;constructor(){Ie(v),this.db=new Ce.Database(Ae),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()}initializeSchema(){try{this.db.run(` CREATE TABLE IF NOT EXISTS schema_versions ( id INTEGER PRIMARY KEY, version INTEGER UNIQUE NOT NULL, applied_at TEXT NOT NULL ) - `);let e=this.db.prepare("SELECT version FROM schema_versions ORDER BY version").all();(e.length>0?Math.max(...e.map(t=>t.version)):0)===0&&(console.log("[SessionStore] Initializing fresh database with migration004..."),this.db.run(` + `);let e=this.db.prepare("SELECT version FROM schema_versions ORDER BY version").all();(e.length>0?Math.max(...e.map(s=>s.version)):0)===0&&(console.log("[SessionStore] Initializing fresh database with migration004..."),this.db.run(` CREATE TABLE IF NOT EXISTS sdk_sessions ( id INTEGER PRIMARY KEY AUTOINCREMENT, claude_session_id TEXT UNIQUE NOT NULL, @@ -99,7 +99,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje ALTER TABLE observations ADD COLUMN concepts TEXT; ALTER TABLE observations ADD COLUMN files_read TEXT; ALTER TABLE observations ADD COLUMN files_modified TEXT; - `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString()),console.log("[SessionStore] Successfully added hierarchical fields to observations table")}makeObservationsTextNullable(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(9))return;let t=this.db.query("PRAGMA table_info(observations)").all().find(n=>n.name==="text");if(!t||t.notnull===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString());return}console.log("[SessionStore] Making observations.text nullable..."),this.db.run("BEGIN TRANSACTION");try{this.db.run(` + `),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString()),console.log("[SessionStore] Successfully added hierarchical fields to observations table")}makeObservationsTextNullable(){if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(9))return;let s=this.db.query("PRAGMA table_info(observations)").all().find(n=>n.name==="text");if(!s||s.notnull===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString());return}console.log("[SessionStore] Making observations.text nullable..."),this.db.run("BEGIN TRANSACTION");try{this.db.run(` CREATE TABLE observations_new ( id INTEGER PRIMARY KEY AUTOINCREMENT, sdk_session_id TEXT NOT NULL, @@ -167,7 +167,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje INSERT INTO user_prompts_fts(rowid, prompt_text) VALUES (new.id, new.prompt_text); END; - `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),console.log("[SessionStore] Successfully created user_prompts table with FTS5 support")}catch(t){throw this.db.run("ROLLBACK"),t}}ensureDiscoveryTokensColumn(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(11))return;this.db.query("PRAGMA table_info(observations)").all().some(a=>a.name==="discovery_tokens")||(this.db.run("ALTER TABLE observations ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),console.log("[SessionStore] Added discovery_tokens column to observations table")),this.db.query("PRAGMA table_info(session_summaries)").all().some(a=>a.name==="discovery_tokens")||(this.db.run("ALTER TABLE session_summaries ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),console.log("[SessionStore] Added discovery_tokens column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(11,new Date().toISOString())}catch(e){throw console.error("[SessionStore] Discovery tokens migration error:",e.message),e}}createPendingMessagesTable(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(16))return;if(this.db.query("SELECT name FROM sqlite_master WHERE type='table' AND name='pending_messages'").all().length>0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(16,new Date().toISOString());return}console.log("[SessionStore] Creating pending_messages table..."),this.db.run(` + `),this.db.run("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),console.log("[SessionStore] Successfully created user_prompts table with FTS5 support")}catch(s){throw this.db.run("ROLLBACK"),s}}ensureDiscoveryTokensColumn(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(11))return;this.db.query("PRAGMA table_info(observations)").all().some(a=>a.name==="discovery_tokens")||(this.db.run("ALTER TABLE observations ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),console.log("[SessionStore] Added discovery_tokens column to observations table")),this.db.query("PRAGMA table_info(session_summaries)").all().some(a=>a.name==="discovery_tokens")||(this.db.run("ALTER TABLE session_summaries ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),console.log("[SessionStore] Added discovery_tokens column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(11,new Date().toISOString())}catch(e){throw console.error("[SessionStore] Discovery tokens migration error:",e.message),e}}createPendingMessagesTable(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(16))return;if(this.db.query("SELECT name FROM sqlite_master WHERE type='table' AND name='pending_messages'").all().length>0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(16,new Date().toISOString());return}console.log("[SessionStore] Creating pending_messages table..."),this.db.run(` CREATE TABLE pending_messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_db_id INTEGER NOT NULL, @@ -187,7 +187,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje completed_at_epoch INTEGER, FOREIGN KEY (session_db_id) REFERENCES sdk_sessions(id) ON DELETE CASCADE ) - `),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_session ON pending_messages(session_db_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_status ON pending_messages(status)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_claude_session ON pending_messages(claude_session_id)"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(16,new Date().toISOString()),console.log("[SessionStore] pending_messages table created successfully")}catch(e){throw console.error("[SessionStore] Pending messages table migration error:",e.message),e}}getRecentSummaries(e,s=10){return this.db.prepare(` + `),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_session ON pending_messages(session_db_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_status ON pending_messages(status)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_pending_messages_claude_session ON pending_messages(claude_session_id)"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(16,new Date().toISOString()),console.log("[SessionStore] pending_messages table created successfully")}catch(e){throw console.error("[SessionStore] Pending messages table migration error:",e.message),e}}getRecentSummaries(e,t=10){return this.db.prepare(` SELECT request, investigated, learned, completed, next_steps, files_read, files_edited, notes, prompt_number, created_at @@ -195,7 +195,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ? - `).all(e,s)}getRecentSummariesWithSessionInfo(e,s=3){return this.db.prepare(` + `).all(e,t)}getRecentSummariesWithSessionInfo(e,t=3){return this.db.prepare(` SELECT sdk_session_id, request, learned, completed, next_steps, prompt_number, created_at @@ -203,13 +203,13 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ? - `).all(e,s)}getRecentObservations(e,s=20){return this.db.prepare(` + `).all(e,t)}getRecentObservations(e,t=20){return this.db.prepare(` SELECT type, text, prompt_number, created_at FROM observations WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ? - `).all(e,s)}getAllRecentObservations(e=100){return this.db.prepare(` + `).all(e,t)}getAllRecentObservations(e=100){return this.db.prepare(` SELECT id, type, title, subtitle, text, project, prompt_number, created_at, created_at_epoch FROM observations ORDER BY created_at_epoch DESC @@ -239,7 +239,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje FROM sdk_sessions WHERE project IS NOT NULL AND project != '' ORDER BY project ASC - `).all().map(t=>t.project)}getLatestUserPrompt(e){return this.db.prepare(` + `).all().map(s=>s.project)}getLatestUserPrompt(e){return this.db.prepare(` SELECT up.*, s.sdk_session_id, @@ -249,7 +249,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje WHERE up.claude_session_id = ? ORDER BY up.created_at_epoch DESC LIMIT 1 - `).get(e)}getRecentSessionsWithStatus(e,s=3){return this.db.prepare(` + `).get(e)}getRecentSessionsWithStatus(e,t=3){return this.db.prepare(` SELECT * FROM ( SELECT s.sdk_session_id, @@ -266,7 +266,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje LIMIT ? ) ORDER BY started_at_epoch ASC - `).all(e,s)}getObservationsForSession(e){return this.db.prepare(` + `).all(e,t)}getObservationsForSession(e){return this.db.prepare(` SELECT title, subtitle, type, prompt_number FROM observations WHERE sdk_session_id = ? @@ -275,7 +275,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje SELECT * FROM observations WHERE id = ? - `).get(e)||null}getObservationsByIds(e,s={}){if(e.length===0)return[];let{orderBy:t="date_desc",limit:n,project:i,type:a,concepts:c,files:p}=s,u=t==="date_asc"?"ASC":"DESC",l=n?`LIMIT ${n}`:"",E=e.map(()=>"?").join(","),R=[...e],T=[];if(i&&(T.push("project = ?"),R.push(i)),a)if(Array.isArray(a)){let r=a.map(()=>"?").join(",");T.push(`type IN (${r})`),R.push(...a)}else T.push("type = ?"),R.push(a);if(c){let r=Array.isArray(c)?c:[c],I=r.map(()=>"EXISTS (SELECT 1 FROM json_each(concepts) WHERE value = ?)");R.push(...r),T.push(`(${I.join(" OR ")})`)}if(p){let r=Array.isArray(p)?p:[p],I=r.map(()=>"(EXISTS (SELECT 1 FROM json_each(files_read) WHERE value LIKE ?) OR EXISTS (SELECT 1 FROM json_each(files_modified) WHERE value LIKE ?))");r.forEach(O=>{R.push(`%${O}%`,`%${O}%`)}),T.push(`(${I.join(" OR ")})`)}let A=T.length>0?`WHERE id IN (${E}) AND ${T.join(" AND ")}`:`WHERE id IN (${E})`;return this.db.prepare(` + `).get(e)||null}getObservationsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:i,type:a,concepts:c,files:p}=t,u=s==="date_asc"?"ASC":"DESC",l=n?`LIMIT ${n}`:"",E=e.map(()=>"?").join(","),R=[...e],T=[];if(i&&(T.push("project = ?"),R.push(i)),a)if(Array.isArray(a)){let r=a.map(()=>"?").join(",");T.push(`type IN (${r})`),R.push(...a)}else T.push("type = ?"),R.push(a);if(c){let r=Array.isArray(c)?c:[c],I=r.map(()=>"EXISTS (SELECT 1 FROM json_each(concepts) WHERE value = ?)");R.push(...r),T.push(`(${I.join(" OR ")})`)}if(p){let r=Array.isArray(p)?p:[p],I=r.map(()=>"(EXISTS (SELECT 1 FROM json_each(files_read) WHERE value LIKE ?) OR EXISTS (SELECT 1 FROM json_each(files_modified) WHERE value LIKE ?))");r.forEach(O=>{R.push(`%${O}%`,`%${O}%`)}),T.push(`(${I.join(" OR ")})`)}let A=T.length>0?`WHERE id IN (${E}) AND ${T.join(" AND ")}`:`WHERE id IN (${E})`;return this.db.prepare(` SELECT * FROM observations ${A} @@ -289,20 +289,20 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje WHERE sdk_session_id = ? ORDER BY created_at_epoch DESC LIMIT 1 - `).get(e)||null}getFilesForSession(e){let t=this.db.prepare(` + `).get(e)||null}getFilesForSession(e){let s=this.db.prepare(` SELECT files_read, files_modified FROM observations WHERE sdk_session_id = ? - `).all(e),n=new Set,i=new Set;for(let a of t){if(a.files_read){let c=JSON.parse(a.files_read);Array.isArray(c)&&c.forEach(p=>n.add(p))}if(a.files_modified){let c=JSON.parse(a.files_modified);Array.isArray(c)&&c.forEach(p=>i.add(p))}}return{filesRead:Array.from(n),filesModified:Array.from(i)}}getSessionById(e){return this.db.prepare(` + `).all(e),n=new Set,i=new Set;for(let a of s){if(a.files_read){let c=JSON.parse(a.files_read);Array.isArray(c)&&c.forEach(p=>n.add(p))}if(a.files_modified){let c=JSON.parse(a.files_modified);Array.isArray(c)&&c.forEach(p=>i.add(p))}}return{filesRead:Array.from(n),filesModified:Array.from(i)}}getSessionById(e){return this.db.prepare(` SELECT id, claude_session_id, sdk_session_id, project, user_prompt FROM sdk_sessions WHERE id = ? LIMIT 1 - `).get(e)||null}getSdkSessionsBySessionIds(e){if(e.length===0)return[];let s=e.map(()=>"?").join(",");return this.db.prepare(` + `).get(e)||null}getSdkSessionsBySessionIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.db.prepare(` SELECT id, claude_session_id, sdk_session_id, project, user_prompt, started_at, started_at_epoch, completed_at, completed_at_epoch, status FROM sdk_sessions - WHERE sdk_session_id IN (${s}) + WHERE sdk_session_id IN (${t}) ORDER BY started_at_epoch DESC `).all(...e)}findActiveSDKSession(e){return this.db.prepare(` SELECT id, sdk_session_id, project, worker_port @@ -314,11 +314,11 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje FROM sdk_sessions WHERE claude_session_id = ? LIMIT 1 - `).get(e)||null}reactivateSession(e,s){this.db.prepare(` + `).get(e)||null}reactivateSession(e,t){this.db.prepare(` UPDATE sdk_sessions SET status = 'active', user_prompt = ?, worker_port = NULL WHERE id = ? - `).run(s,e)}incrementPromptCounter(e){return this.db.prepare(` + `).run(t,e)}incrementPromptCounter(e){return this.db.prepare(` UPDATE sdk_sessions SET prompt_counter = COALESCE(prompt_counter, 0) + 1 WHERE id = ? @@ -326,74 +326,74 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje SELECT prompt_counter FROM sdk_sessions WHERE id = ? `).get(e)?.prompt_counter||1}getPromptCounter(e){return this.db.prepare(` SELECT prompt_counter FROM sdk_sessions WHERE id = ? - `).get(e)?.prompt_counter||0}createSDKSession(e,s,t){let n=new Date,i=n.getTime(),c=this.db.prepare(` + `).get(e)?.prompt_counter||0}createSDKSession(e,t,s){let n=new Date,i=n.getTime(),c=this.db.prepare(` INSERT OR IGNORE INTO sdk_sessions (claude_session_id, sdk_session_id, project, user_prompt, started_at, started_at_epoch, status) VALUES (?, ?, ?, ?, ?, ?, 'active') - `).run(e,e,s,t,n.toISOString(),i);return c.lastInsertRowid===0||c.changes===0?(s&&s.trim()!==""&&this.db.prepare(` + `).run(e,e,t,s,n.toISOString(),i);return c.lastInsertRowid===0||c.changes===0?(t&&t.trim()!==""&&this.db.prepare(` UPDATE sdk_sessions SET project = ?, user_prompt = ? WHERE claude_session_id = ? - `).run(s,t,e),this.db.prepare(` + `).run(t,s,e),this.db.prepare(` SELECT id FROM sdk_sessions WHERE claude_session_id = ? LIMIT 1 - `).get(e).id):c.lastInsertRowid}updateSDKSessionId(e,s){return this.db.prepare(` + `).get(e).id):c.lastInsertRowid}updateSDKSessionId(e,t){return this.db.prepare(` UPDATE sdk_sessions SET sdk_session_id = ? WHERE id = ? AND sdk_session_id IS NULL - `).run(s,e).changes===0?(h.debug("DB","sdk_session_id already set, skipping update",{sessionId:e,sdkSessionId:s}),!1):!0}setWorkerPort(e,s){this.db.prepare(` + `).run(t,e).changes===0?(h.debug("DB","sdk_session_id already set, skipping update",{sessionId:e,sdkSessionId:t}),!1):!0}setWorkerPort(e,t){this.db.prepare(` UPDATE sdk_sessions SET worker_port = ? WHERE id = ? - `).run(s,e)}getWorkerPort(e){return this.db.prepare(` + `).run(t,e)}getWorkerPort(e){return this.db.prepare(` SELECT worker_port FROM sdk_sessions WHERE id = ? LIMIT 1 - `).get(e)?.worker_port||null}saveUserPrompt(e,s,t){let n=new Date,i=n.getTime();return this.db.prepare(` + `).get(e)?.worker_port||null}saveUserPrompt(e,t,s){let n=new Date,i=n.getTime();return this.db.prepare(` INSERT INTO user_prompts (claude_session_id, prompt_number, prompt_text, created_at, created_at_epoch) VALUES (?, ?, ?, ?, ?) - `).run(e,s,t,n.toISOString(),i).lastInsertRowid}getUserPrompt(e,s){return this.db.prepare(` + `).run(e,t,s,n.toISOString(),i).lastInsertRowid}getUserPrompt(e,t){return this.db.prepare(` SELECT prompt_text FROM user_prompts WHERE claude_session_id = ? AND prompt_number = ? LIMIT 1 - `).get(e,s)?.prompt_text??null}storeObservation(e,s,t,n,i=0){let a=new Date,c=a.getTime();this.db.prepare(` + `).get(e,t)?.prompt_text??null}storeObservation(e,t,s,n,i=0){let a=new Date,c=a.getTime();this.db.prepare(` SELECT id FROM sdk_sessions WHERE sdk_session_id = ? `).get(e)||(this.db.prepare(` INSERT INTO sdk_sessions (claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status) VALUES (?, ?, ?, ?, ?, 'active') - `).run(e,e,s,a.toISOString(),c),console.log(`[SessionStore] Auto-created session record for session_id: ${e}`));let E=this.db.prepare(` + `).run(e,e,t,a.toISOString(),c),console.log(`[SessionStore] Auto-created session record for session_id: ${e}`));let E=this.db.prepare(` INSERT INTO observations (sdk_session_id, project, type, title, subtitle, facts, narrative, concepts, files_read, files_modified, prompt_number, discovery_tokens, created_at, created_at_epoch) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(e,s,t.type,t.title,t.subtitle,JSON.stringify(t.facts),t.narrative,JSON.stringify(t.concepts),JSON.stringify(t.files_read),JSON.stringify(t.files_modified),n||null,i,a.toISOString(),c);return{id:Number(E.lastInsertRowid),createdAtEpoch:c}}storeSummary(e,s,t,n,i=0){let a=new Date,c=a.getTime();this.db.prepare(` + `).run(e,t,s.type,s.title,s.subtitle,JSON.stringify(s.facts),s.narrative,JSON.stringify(s.concepts),JSON.stringify(s.files_read),JSON.stringify(s.files_modified),n||null,i,a.toISOString(),c);return{id:Number(E.lastInsertRowid),createdAtEpoch:c}}storeSummary(e,t,s,n,i=0){let a=new Date,c=a.getTime();this.db.prepare(` SELECT id FROM sdk_sessions WHERE sdk_session_id = ? `).get(e)||(this.db.prepare(` INSERT INTO sdk_sessions (claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status) VALUES (?, ?, ?, ?, ?, 'active') - `).run(e,e,s,a.toISOString(),c),console.log(`[SessionStore] Auto-created session record for session_id: ${e}`));let E=this.db.prepare(` + `).run(e,e,t,a.toISOString(),c),console.log(`[SessionStore] Auto-created session record for session_id: ${e}`));let E=this.db.prepare(` INSERT INTO session_summaries (sdk_session_id, project, request, investigated, learned, completed, next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(e,s,t.request,t.investigated,t.learned,t.completed,t.next_steps,t.notes,n||null,i,a.toISOString(),c);return{id:Number(E.lastInsertRowid),createdAtEpoch:c}}markSessionCompleted(e){let s=new Date,t=s.getTime();this.db.prepare(` + `).run(e,t,s.request,s.investigated,s.learned,s.completed,s.next_steps,s.notes,n||null,i,a.toISOString(),c);return{id:Number(E.lastInsertRowid),createdAtEpoch:c}}markSessionCompleted(e){let t=new Date,s=t.getTime();this.db.prepare(` UPDATE sdk_sessions SET status = 'completed', completed_at = ?, completed_at_epoch = ? WHERE id = ? - `).run(s.toISOString(),t,e)}markSessionFailed(e){let s=new Date,t=s.getTime();this.db.prepare(` + `).run(t.toISOString(),s,e)}markSessionFailed(e){let t=new Date,s=t.getTime();this.db.prepare(` UPDATE sdk_sessions SET status = 'failed', completed_at = ?, completed_at_epoch = ? WHERE id = ? - `).run(s.toISOString(),t,e)}getSessionSummariesByIds(e,s={}){if(e.length===0)return[];let{orderBy:t="date_desc",limit:n,project:i}=s,a=t==="date_asc"?"ASC":"DESC",c=n?`LIMIT ${n}`:"",p=e.map(()=>"?").join(","),u=[...e],l=i?`WHERE id IN (${p}) AND project = ?`:`WHERE id IN (${p})`;return i&&u.push(i),this.db.prepare(` + `).run(t.toISOString(),s,e)}getSessionSummariesByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:i}=t,a=s==="date_asc"?"ASC":"DESC",c=n?`LIMIT ${n}`:"",p=e.map(()=>"?").join(","),u=[...e],l=i?`WHERE id IN (${p}) AND project = ?`:`WHERE id IN (${p})`;return i&&u.push(i),this.db.prepare(` SELECT * FROM session_summaries ${l} ORDER BY created_at_epoch ${a} ${c} - `).all(...u)}getUserPromptsByIds(e,s={}){if(e.length===0)return[];let{orderBy:t="date_desc",limit:n,project:i}=s,a=t==="date_asc"?"ASC":"DESC",c=n?`LIMIT ${n}`:"",p=e.map(()=>"?").join(","),u=[...e],l=i?"AND s.project = ?":"";return i&&u.push(i),this.db.prepare(` + `).all(...u)}getUserPromptsByIds(e,t={}){if(e.length===0)return[];let{orderBy:s="date_desc",limit:n,project:i}=t,a=s==="date_asc"?"ASC":"DESC",c=n?`LIMIT ${n}`:"",p=e.map(()=>"?").join(","),u=[...e],l=i?"AND s.project = ?":"";return i&&u.push(i),this.db.prepare(` SELECT up.*, s.project, @@ -403,7 +403,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje WHERE up.id IN (${p}) ${l} ORDER BY up.created_at_epoch ${a} ${c} - `).all(...u)}getTimelineAroundTimestamp(e,s=10,t=10,n){return this.getTimelineAroundObservation(null,e,s,t,n)}getTimelineAroundObservation(e,s,t=10,n=10,i){let a=i?"AND project = ?":"",c=i?[i]:[],p,u;if(e!==null){let T=` + `).all(...u)}getTimelineAroundTimestamp(e,t=10,s=10,n){return this.getTimelineAroundObservation(null,e,t,s,n)}getTimelineAroundObservation(e,t,s=10,n=10,i){let a=i?"AND project = ?":"",c=i?[i]:[],p,u;if(e!==null){let T=` SELECT id, created_at_epoch FROM observations WHERE id <= ? ${a} @@ -415,7 +415,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje WHERE id >= ? ${a} ORDER BY id ASC LIMIT ? - `;try{let g=this.db.prepare(T).all(e,...c,t+1),r=this.db.prepare(A).all(e,...c,n+1);if(g.length===0&&r.length===0)return{observations:[],sessions:[],prompts:[]};p=g.length>0?g[g.length-1].created_at_epoch:s,u=r.length>0?r[r.length-1].created_at_epoch:s}catch(g){return console.error("[SessionStore] Error getting boundary observations:",g.message,i?`(project: ${i})`:"(all projects)"),{observations:[],sessions:[],prompts:[]}}}else{let T=` + `;try{let g=this.db.prepare(T).all(e,...c,s+1),r=this.db.prepare(A).all(e,...c,n+1);if(g.length===0&&r.length===0)return{observations:[],sessions:[],prompts:[]};p=g.length>0?g[g.length-1].created_at_epoch:t,u=r.length>0?r[r.length-1].created_at_epoch:t}catch(g){return console.error("[SessionStore] Error getting boundary observations:",g.message,i?`(project: ${i})`:"(all projects)"),{observations:[],sessions:[],prompts:[]}}}else{let T=` SELECT created_at_epoch FROM observations WHERE created_at_epoch <= ? ${a} @@ -427,7 +427,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje WHERE created_at_epoch >= ? ${a} ORDER BY created_at_epoch ASC LIMIT ? - `;try{let g=this.db.prepare(T).all(s,...c,t),r=this.db.prepare(A).all(s,...c,n+1);if(g.length===0&&r.length===0)return{observations:[],sessions:[],prompts:[]};p=g.length>0?g[g.length-1].created_at_epoch:s,u=r.length>0?r[r.length-1].created_at_epoch:s}catch(g){return console.error("[SessionStore] Error getting boundary timestamps:",g.message,i?`(project: ${i})`:"(all projects)"),{observations:[],sessions:[],prompts:[]}}}let l=` + `;try{let g=this.db.prepare(T).all(t,...c,s),r=this.db.prepare(A).all(t,...c,n+1);if(g.length===0&&r.length===0)return{observations:[],sessions:[],prompts:[]};p=g.length>0?g[g.length-1].created_at_epoch:t,u=r.length>0?r[r.length-1].created_at_epoch:t}catch(g){return console.error("[SessionStore] Error getting boundary timestamps:",g.message,i?`(project: ${i})`:"(all projects)"),{observations:[],sessions:[],prompts:[]}}}let l=` SELECT * FROM observations WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${a} @@ -456,7 +456,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje LEFT JOIN sdk_sessions s ON p.claude_session_id = s.claude_session_id WHERE p.id = ? LIMIT 1 - `).get(e)||null}getPromptsByIds(e){if(e.length===0)return[];let s=e.map(()=>"?").join(",");return this.db.prepare(` + `).get(e)||null}getPromptsByIds(e){if(e.length===0)return[];let t=e.map(()=>"?").join(",");return this.db.prepare(` SELECT p.id, p.claude_session_id, @@ -467,7 +467,7 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje p.created_at_epoch FROM user_prompts p LEFT JOIN sdk_sessions s ON p.claude_session_id = s.claude_session_id - WHERE p.id IN (${s}) + WHERE p.id IN (${t}) ORDER BY p.created_at_epoch DESC `).all(...e)}getSessionSummaryById(e){return this.db.prepare(` SELECT @@ -484,36 +484,36 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje FROM sdk_sessions WHERE id = ? LIMIT 1 - `).get(e)||null}close(){this.db.close()}importSdkSession(e){let s=this.db.prepare("SELECT id FROM sdk_sessions WHERE claude_session_id = ?").get(e.claude_session_id);return s?{imported:!1,id:s.id}:{imported:!0,id:this.db.prepare(` + `).get(e)||null}close(){this.db.close()}importSdkSession(e){let t=this.db.prepare("SELECT id FROM sdk_sessions WHERE claude_session_id = ?").get(e.claude_session_id);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(` INSERT INTO sdk_sessions ( claude_session_id, sdk_session_id, project, user_prompt, started_at, started_at_epoch, completed_at, completed_at_epoch, status ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(e.claude_session_id,e.sdk_session_id,e.project,e.user_prompt,e.started_at,e.started_at_epoch,e.completed_at,e.completed_at_epoch,e.status).lastInsertRowid}}importSessionSummary(e){let s=this.db.prepare("SELECT id FROM session_summaries WHERE sdk_session_id = ?").get(e.sdk_session_id);return s?{imported:!1,id:s.id}:{imported:!0,id:this.db.prepare(` + `).run(e.claude_session_id,e.sdk_session_id,e.project,e.user_prompt,e.started_at,e.started_at_epoch,e.completed_at,e.completed_at_epoch,e.status).lastInsertRowid}}importSessionSummary(e){let t=this.db.prepare("SELECT id FROM session_summaries WHERE sdk_session_id = ?").get(e.sdk_session_id);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(` INSERT INTO session_summaries ( sdk_session_id, project, request, investigated, learned, completed, next_steps, files_read, files_edited, notes, prompt_number, discovery_tokens, created_at, created_at_epoch ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(e.sdk_session_id,e.project,e.request,e.investigated,e.learned,e.completed,e.next_steps,e.files_read,e.files_edited,e.notes,e.prompt_number,e.discovery_tokens||0,e.created_at,e.created_at_epoch).lastInsertRowid}}importObservation(e){let s=this.db.prepare(` + `).run(e.sdk_session_id,e.project,e.request,e.investigated,e.learned,e.completed,e.next_steps,e.files_read,e.files_edited,e.notes,e.prompt_number,e.discovery_tokens||0,e.created_at,e.created_at_epoch).lastInsertRowid}}importObservation(e){let t=this.db.prepare(` SELECT id FROM observations WHERE sdk_session_id = ? AND title = ? AND created_at_epoch = ? - `).get(e.sdk_session_id,e.title,e.created_at_epoch);return s?{imported:!1,id:s.id}:{imported:!0,id:this.db.prepare(` + `).get(e.sdk_session_id,e.title,e.created_at_epoch);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(` INSERT INTO observations ( sdk_session_id, project, text, type, title, subtitle, facts, narrative, concepts, files_read, files_modified, prompt_number, discovery_tokens, created_at, created_at_epoch ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `).run(e.sdk_session_id,e.project,e.text,e.type,e.title,e.subtitle,e.facts,e.narrative,e.concepts,e.files_read,e.files_modified,e.prompt_number,e.discovery_tokens||0,e.created_at,e.created_at_epoch).lastInsertRowid}}importUserPrompt(e){let s=this.db.prepare(` + `).run(e.sdk_session_id,e.project,e.text,e.type,e.title,e.subtitle,e.facts,e.narrative,e.concepts,e.files_read,e.files_modified,e.prompt_number,e.discovery_tokens||0,e.created_at,e.created_at_epoch).lastInsertRowid}}importUserPrompt(e){let t=this.db.prepare(` SELECT id FROM user_prompts WHERE claude_session_id = ? AND prompt_number = ? - `).get(e.claude_session_id,e.prompt_number);return s?{imported:!1,id:s.id}:{imported:!0,id:this.db.prepare(` + `).get(e.claude_session_id,e.prompt_number);return t?{imported:!1,id:t.id}:{imported:!0,id:this.db.prepare(` INSERT INTO user_prompts ( claude_session_id, prompt_number, prompt_text, created_at, created_at_epoch ) VALUES (?, ?, ?, ?, ?) - `).run(e.claude_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var ce=ie(require("path"),1);function pe(d){if(!d)return[];try{let e=JSON.parse(d);return Array.isArray(e)?e:[]}catch{return[]}}function ve(d){return new Date(d).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function ye(d){return new Date(d).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function De(d){return new Date(d).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function Qe(d,e){return ce.default.isAbsolute(d)?ce.default.relative(e,d):d}function Me(d,e){let s=pe(d);return s.length>0?Qe(s[0],e):"General"}var ke=ie(require("path"),1);function $e(d){if(!d||d.trim()==="")return h.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:d}),"unknown-project";let e=ke.default.basename(d);if(e===""){if(process.platform==="win32"){let t=d.match(/^([A-Z]):\\/i);if(t){let i=`drive-${t[1].toUpperCase()}`;return h.info("PROJECT_NAME","Drive root detected",{cwd:d,projectName:i}),i}}return h.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:d}),"unknown-project"}return e}var G=require("fs"),z=require("path");var W=class d{static instance=null;activeMode=null;modesDir;constructor(){let e=Le(),s=[(0,z.join)(e,"modes"),(0,z.join)(e,"..","plugin","modes")],t=s.find(n=>(0,G.existsSync)(n));this.modesDir=t||s[0]}static getInstance(){return d.instance||(d.instance=new d),d.instance}parseInheritance(e){let s=e.split("--");if(s.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(s.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:s[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,s){let t={...e};for(let n in s){let i=s[n],a=e[n];this.isPlainObject(i)&&this.isPlainObject(a)?t[n]=this.deepMerge(a,i):t[n]=i}return t}loadModeFile(e){let s=(0,z.join)(this.modesDir,`${e}.json`);if(!(0,G.existsSync)(s))throw new Error(`Mode file not found: ${s}`);let t=(0,G.readFileSync)(s,"utf-8");return JSON.parse(t)}loadMode(e){let s=this.parseInheritance(e);if(!s.hasParent)try{let p=this.loadModeFile(e);return this.activeMode=p,h.debug("SYSTEM",`Loaded mode: ${p.name} (${e})`,void 0,{types:p.observation_types.map(u=>u.id),concepts:p.observation_concepts.map(u=>u.id)}),p}catch{if(h.warn("SYSTEM",`Mode file not found: ${e}, falling back to 'code'`),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:t,overrideId:n}=s,i;try{i=this.loadMode(t)}catch{h.warn("SYSTEM",`Parent mode '${t}' not found for ${e}, falling back to 'code'`),i=this.loadMode("code")}let a;try{a=this.loadModeFile(n),h.debug("SYSTEM",`Loaded override file: ${n} for parent ${t}`)}catch{return h.warn("SYSTEM",`Override file '${n}' not found, using parent mode '${t}' only`),this.activeMode=i,i}if(!a)return h.warn("SYSTEM",`Invalid override file: ${n}, using parent mode '${t}' only`),this.activeMode=i,i;let c=this.deepMerge(i,a);return this.activeMode=c,h.debug("SYSTEM",`Loaded mode with inheritance: ${c.name} (${e} = ${t} + ${n})`,void 0,{parent:t,override:n,types:c.observation_types.map(p=>p.id),concepts:c.observation_concepts.map(p=>p.id)}),c}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(t=>t.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(t=>t.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(s=>s.id===e)}getTypeLabel(e){return this.getObservationTypes().find(t=>t.id===e)?.label||e}};var ze=ee.default.join((0,se.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function Ze(){let d=ee.default.join((0,se.homedir)(),".claude-mem","settings.json"),e=$.loadFromFile(d);return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(s=>s.trim()).filter(Boolean)),observationConcepts:new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(s=>s.trim()).filter(Boolean)),fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var Ue=4,es=1,o={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"};function Z(d,e,s,t){return e?t?[`${s}${d}:${o.reset} ${e}`,""]:[`**${d}**: ${e}`,""]:[]}function ss(d){return d.replace(/\//g,"-")}function ts(d){try{if(!(0,H.existsSync)(d))return{userMessage:"",assistantMessage:""};let e=(0,H.readFileSync)(d,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let s=e.split(` -`).filter(n=>n.trim()),t="";for(let n=s.length-1;n>=0;n--)try{let i=s[n];if(!i.includes('"type":"assistant"'))continue;let a=JSON.parse(i);if(a.type==="assistant"&&a.message?.content&&Array.isArray(a.message.content)){let c="";for(let p of a.message.content)p.type==="text"&&(c+=p.text);if(c=c.replace(/[\s\S]*?<\/system-reminder>/g,"").trim(),c){t=c;break}}}catch{continue}return{userMessage:"",assistantMessage:t}}catch(e){return h.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:d},e),{userMessage:"",assistantMessage:""}}}async function rs(d,e=!1){let s=Ze(),t=d?.cwd??process.cwd(),n=$e(t),i=null;try{i=new Q}catch(I){if(I.code==="ERR_DLOPEN_FAILED"){try{(0,H.unlinkSync)(ze)}catch{}return console.error("Native module rebuild needed - restart Claude Code to auto-fix"),""}throw I}let a=Array.from(s.observationTypes),c=a.map(()=>"?").join(","),p=Array.from(s.observationConcepts),u=p.map(()=>"?").join(","),l=i.db.prepare(` + `).run(e.claude_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var ce=ie(require("path"),1);function pe(d){if(!d)return[];try{let e=JSON.parse(d);return Array.isArray(e)?e:[]}catch{return[]}}function ve(d){return new Date(d).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function ye(d){return new Date(d).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function De(d){return new Date(d).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function Qe(d,e){return ce.default.isAbsolute(d)?ce.default.relative(e,d):d}function Me(d,e){let t=pe(d);return t.length>0?Qe(t[0],e):"General"}var ke=ie(require("path"),1);function $e(d){if(!d||d.trim()==="")return h.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:d}),"unknown-project";let e=ke.default.basename(d);if(e===""){if(process.platform==="win32"){let s=d.match(/^([A-Z]):\\/i);if(s){let i=`drive-${s[1].toUpperCase()}`;return h.info("PROJECT_NAME","Drive root detected",{cwd:d,projectName:i}),i}}return h.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:d}),"unknown-project"}return e}var G=require("fs"),z=require("path");var X=class d{static instance=null;activeMode=null;modesDir;constructor(){let e=Le(),t=[(0,z.join)(e,"modes"),(0,z.join)(e,"..","plugin","modes")],s=t.find(n=>(0,G.existsSync)(n));this.modesDir=s||t[0]}static getInstance(){return d.instance||(d.instance=new d),d.instance}parseInheritance(e){let t=e.split("--");if(t.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(t.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:t[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,t){let s={...e};for(let n in t){let i=t[n],a=e[n];this.isPlainObject(i)&&this.isPlainObject(a)?s[n]=this.deepMerge(a,i):s[n]=i}return s}loadModeFile(e){let t=(0,z.join)(this.modesDir,`${e}.json`);if(!(0,G.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,G.readFileSync)(t,"utf-8");return JSON.parse(s)}loadMode(e){let t=this.parseInheritance(e);if(!t.hasParent)try{let p=this.loadModeFile(e);return this.activeMode=p,h.debug("SYSTEM",`Loaded mode: ${p.name} (${e})`,void 0,{types:p.observation_types.map(u=>u.id),concepts:p.observation_concepts.map(u=>u.id)}),p}catch{if(h.warn("SYSTEM",`Mode file not found: ${e}, falling back to 'code'`),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:s,overrideId:n}=t,i;try{i=this.loadMode(s)}catch{h.warn("SYSTEM",`Parent mode '${s}' not found for ${e}, falling back to 'code'`),i=this.loadMode("code")}let a;try{a=this.loadModeFile(n),h.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch{return h.warn("SYSTEM",`Override file '${n}' not found, using parent mode '${s}' only`),this.activeMode=i,i}if(!a)return h.warn("SYSTEM",`Invalid override file: ${n}, using parent mode '${s}' only`),this.activeMode=i,i;let c=this.deepMerge(i,a);return this.activeMode=c,h.debug("SYSTEM",`Loaded mode with inheritance: ${c.name} (${e} = ${s} + ${n})`,void 0,{parent:s,override:n,types:c.observation_types.map(p=>p.id),concepts:c.observation_concepts.map(p=>p.id)}),c}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(s=>s.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(s=>s.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(t=>t.id===e)}getTypeLabel(e){return this.getObservationTypes().find(s=>s.id===e)?.label||e}};var ze=ee.default.join((0,te.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");function Ze(){let d=ee.default.join((0,te.homedir)(),".claude-mem","settings.json"),e=$.loadFromFile(d),t=e.CLAUDE_MEM_MODE,s=t==="code"||t.startsWith("code--"),n,i;if(s)n=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(a=>a.trim()).filter(Boolean)),i=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(a=>a.trim()).filter(Boolean));else{let a=X.getInstance().getActiveMode();n=new Set(a.observation_types.map(c=>c.id)),i=new Set(a.observation_concepts.map(c=>c.id))}return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:n,observationConcepts:i,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}var Ue=4,et=1,o={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"};function Z(d,e,t,s){return e?s?[`${t}${d}:${o.reset} ${e}`,""]:[`**${d}**: ${e}`,""]:[]}function tt(d){return d.replace(/\//g,"-")}function st(d){try{if(!(0,H.existsSync)(d))return{userMessage:"",assistantMessage:""};let e=(0,H.readFileSync)(d,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(` +`).filter(n=>n.trim()),s="";for(let n=t.length-1;n>=0;n--)try{let i=t[n];if(!i.includes('"type":"assistant"'))continue;let a=JSON.parse(i);if(a.type==="assistant"&&a.message?.content&&Array.isArray(a.message.content)){let c="";for(let p of a.message.content)p.type==="text"&&(c+=p.text);if(c=c.replace(/[\s\S]*?<\/system-reminder>/g,"").trim(),c){s=c;break}}}catch{continue}return{userMessage:"",assistantMessage:s}}catch(e){return h.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:d},e),{userMessage:"",assistantMessage:""}}}async function rt(d,e=!1){let t=Ze(),s=d?.cwd??process.cwd(),n=$e(s),i=null;try{i=new Q}catch(I){if(I.code==="ERR_DLOPEN_FAILED"){try{(0,H.unlinkSync)(ze)}catch{}return console.error("Native module rebuild needed - restart Claude Code to auto-fix"),""}throw I}let a=Array.from(t.observationTypes),c=a.map(()=>"?").join(","),p=Array.from(t.observationConcepts),u=p.map(()=>"?").join(","),l=i.db.prepare(` SELECT id, sdk_session_id, type, title, subtitle, narrative, facts, concepts, files_read, files_modified, discovery_tokens, @@ -527,19 +527,19 @@ ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let s=Obje ) ORDER BY created_at_epoch DESC LIMIT ? - `).all(n,...a,...p,s.totalObservationCount),E=i.db.prepare(` + `).all(n,...a,...p,t.totalObservationCount),E=i.db.prepare(` SELECT id, sdk_session_id, request, investigated, learned, completed, next_steps, created_at, created_at_epoch FROM session_summaries WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ? - `).all(n,s.sessionCount+es),R="",T="";if(s.showLastMessage&&l.length>0){let I=d?.session_id,O=l.find(D=>D.sdk_session_id!==I);if(O){let D=O.sdk_session_id,U=ss(t),N=ee.default.join((0,se.homedir)(),".claude","projects",U,`${D}.jsonl`),y=ts(N);R=y.userMessage,T=y.assistantMessage}}if(l.length===0&&E.length===0)return i?.close(),e?` + `).all(n,t.sessionCount+et),R="",T="";if(t.showLastMessage&&l.length>0){let I=d?.session_id,O=l.find(D=>D.sdk_session_id!==I);if(O){let D=O.sdk_session_id,U=tt(s),N=ee.default.join((0,te.homedir)(),".claude","projects",U,`${D}.jsonl`),y=st(N);R=y.userMessage,T=y.assistantMessage}}if(l.length===0&&E.length===0)return i?.close(),e?` ${o.bright}${o.cyan}[${n}] recent context${o.reset} ${o.gray}${"\u2500".repeat(60)}${o.reset} ${o.dim}No previous sessions found for this project yet.${o.reset} `:`# [${n}] recent context -No previous sessions found for this project yet.`;let A=E.slice(0,s.sessionCount),g=l,r=[];if(e?(r.push(""),r.push(`${o.bright}${o.cyan}[${n}] recent context${o.reset}`),r.push(`${o.gray}${"\u2500".repeat(60)}${o.reset}`),r.push("")):(r.push(`# [${n}] recent context`),r.push("")),g.length>0){let O=W.getInstance().getActiveMode().observation_types.map(_=>`${_.emoji} ${_.id}`).join(" | ");e?r.push(`${o.dim}Legend: \u{1F3AF} session-request | ${O}${o.reset}`):r.push(`**Legend:** \u{1F3AF} session-request | ${O}`),r.push(""),e?(r.push(`${o.bright}\u{1F4A1} Column Key${o.reset}`),r.push(`${o.dim} Read: Tokens to read this observation (cost to learn it now)${o.reset}`),r.push(`${o.dim} Work: Tokens spent on work that produced this record (\u{1F50D} research, \u{1F6E0}\uFE0F building, \u2696\uFE0F deciding)${o.reset}`)):(r.push("\u{1F4A1} **Column Key**:"),r.push("- **Read**: Tokens to read this observation (cost to learn it now)"),r.push("- **Work**: Tokens spent on work that produced this record (\u{1F50D} research, \u{1F6E0}\uFE0F building, \u2696\uFE0F deciding)")),r.push(""),e?(r.push(`${o.dim}\u{1F4A1} Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${o.reset}`),r.push(""),r.push(`${o.dim}When you need implementation details, rationale, or debugging context:${o.reset}`),r.push(`${o.dim} - Use the mem-search skill to fetch full observations on-demand${o.reset}`),r.push(`${o.dim} - Critical types (\u{1F534} bugfix, \u2696\uFE0F decision) often need detailed fetching${o.reset}`),r.push(`${o.dim} - Trust this index over re-reading code for past decisions and learnings${o.reset}`)):(r.push("\u{1F4A1} **Context Index:** This semantic index (titles, types, files, tokens) is usually sufficient to understand past work."),r.push(""),r.push("When you need implementation details, rationale, or debugging context:"),r.push("- Use the mem-search skill to fetch full observations on-demand"),r.push("- Critical types (\u{1F534} bugfix, \u2696\uFE0F decision) often need detailed fetching"),r.push("- Trust this index over re-reading code for past decisions and learnings")),r.push("");let D=l.length,U=l.reduce((_,S)=>{let b=(S.title?.length||0)+(S.subtitle?.length||0)+(S.narrative?.length||0)+JSON.stringify(S.facts||[]).length;return _+Math.ceil(b/Ue)},0),N=l.reduce((_,S)=>_+(S.discovery_tokens||0),0),y=N-U,B=N>0?Math.round(y/N*100):0,_e=s.showReadTokens||s.showWorkTokens||s.showSavingsAmount||s.showSavingsPercent;if(_e)if(e){if(r.push(`${o.bright}${o.cyan}\u{1F4CA} Context Economics${o.reset}`),r.push(`${o.dim} Loading: ${D} observations (${U.toLocaleString()} tokens to read)${o.reset}`),r.push(`${o.dim} Work investment: ${N.toLocaleString()} tokens spent on research, building, and decisions${o.reset}`),N>0&&(s.showSavingsAmount||s.showSavingsPercent)){let _=" Your savings: ";s.showSavingsAmount&&s.showSavingsPercent?_+=`${y.toLocaleString()} tokens (${B}% reduction from reuse)`:s.showSavingsAmount?_+=`${y.toLocaleString()} tokens`:_+=`${B}% reduction from reuse`,r.push(`${o.green}${_}${o.reset}`)}r.push("")}else{if(r.push("\u{1F4CA} **Context Economics**:"),r.push(`- Loading: ${D} observations (${U.toLocaleString()} tokens to read)`),r.push(`- Work investment: ${N.toLocaleString()} tokens spent on research, building, and decisions`),N>0&&(s.showSavingsAmount||s.showSavingsPercent)){let _="- Your savings: ";s.showSavingsAmount&&s.showSavingsPercent?_+=`${y.toLocaleString()} tokens (${B}% reduction from reuse)`:s.showSavingsAmount?_+=`${y.toLocaleString()} tokens`:_+=`${B}% reduction from reuse`,r.push(_)}r.push("")}let xe=E[0]?.id,we=A.map((_,S)=>{let b=S===0?null:E[S+1];return{..._,displayEpoch:b?b.created_at_epoch:_.created_at_epoch,displayTime:b?b.created_at:_.created_at,shouldShowLink:_.id!==xe}}),Fe=new Set(l.slice(0,s.fullObservationCount).map(_=>_.id)),ue=[...g.map(_=>({type:"observation",data:_})),...we.map(_=>({type:"summary",data:_}))];ue.sort((_,S)=>{let b=_.type==="observation"?_.data.created_at_epoch:_.data.displayEpoch,M=S.type==="observation"?S.data.created_at_epoch:S.data.displayEpoch;return b-M});let Y=new Map;for(let _ of ue){let S=_.type==="observation"?_.data.created_at:_.data.displayTime,b=De(S);Y.has(b)||Y.set(b,[]),Y.get(b).push(_)}let Xe=Array.from(Y.entries()).sort((_,S)=>{let b=new Date(_[0]).getTime(),M=new Date(S[0]).getTime();return b-M});for(let[_,S]of Xe){e?(r.push(`${o.bright}${o.cyan}${_}${o.reset}`),r.push("")):(r.push(`### ${_}`),r.push(""));let b=null,M="",x=!1;for(let te of S)if(te.type==="summary"){x&&(r.push(""),x=!1,b=null,M="");let m=te.data,w=`${m.request||"Session started"} (${ve(m.displayTime)})`;e?r.push(`\u{1F3AF} ${o.yellow}#S${m.id}${o.reset} ${w}`):r.push(`**\u{1F3AF} #S${m.id}** ${w}`),r.push("")}else{let m=te.data,w=Me(m.files_modified,t);w!==b&&(x&&r.push(""),e?r.push(`${o.dim}${w}${o.reset}`):r.push(`**${w}**`),e||(r.push("| ID | Time | T | Title | Read | Work |"),r.push("|----|------|---|-------|------|------|")),b=w,x=!0,M="");let F=ye(m.created_at),V=m.title||"Untitled",K=W.getInstance().getTypeIcon(m.type),Pe=(m.title?.length||0)+(m.subtitle?.length||0)+(m.narrative?.length||0)+JSON.stringify(m.facts||[]).length,X=Math.ceil(Pe/Ue),P=m.discovery_tokens||0,re=W.getInstance().getWorkEmoji(m.type),me=P>0?`${re} ${P.toLocaleString()}`:"-",ne=F!==M,Ee=ne?F:"";if(M=F,Fe.has(m.id)){let k=s.fullObservationField==="narrative"?m.narrative:m.facts?pe(m.facts).join(` -`):null;if(e){let C=ne?`${o.dim}${F}${o.reset}`:" ".repeat(F.length),q=s.showReadTokens&&X>0?`${o.dim}(~${X}t)${o.reset}`:"",Te=s.showWorkTokens&&P>0?`${o.dim}(${re} ${P.toLocaleString()}t)${o.reset}`:"";r.push(` ${o.dim}#${m.id}${o.reset} ${C} ${K} ${o.bright}${V}${o.reset}`),k&&r.push(` ${o.dim}${k}${o.reset}`),(q||Te)&&r.push(` ${q} ${Te}`),r.push("")}else{x&&(r.push(""),x=!1),r.push(`**#${m.id}** ${Ee||"\u2033"} ${K} **${V}**`),k&&(r.push(""),r.push(k),r.push(""));let C=[];s.showReadTokens&&C.push(`Read: ~${X}`),s.showWorkTokens&&C.push(`Work: ${me}`),C.length>0&&r.push(C.join(", ")),r.push(""),b=null}}else if(e){let k=ne?`${o.dim}${F}${o.reset}`:" ".repeat(F.length),C=s.showReadTokens&&X>0?`${o.dim}(~${X}t)${o.reset}`:"",q=s.showWorkTokens&&P>0?`${o.dim}(${re} ${P.toLocaleString()}t)${o.reset}`:"";r.push(` ${o.dim}#${m.id}${o.reset} ${k} ${K} ${V} ${C} ${q}`)}else{let k=s.showReadTokens?`~${X}`:"",C=s.showWorkTokens?me:"";r.push(`| #${m.id} | ${Ee||"\u2033"} | ${K} | ${V} | ${k} | ${C} |`)}}x&&r.push("")}let L=E[0],le=l[0];if(s.showLastSummary&&L&&(L.investigated||L.learned||L.completed||L.next_steps)&&(!le||L.created_at_epoch>le.created_at_epoch)&&(r.push(...Z("Investigated",L.investigated,o.blue,e)),r.push(...Z("Learned",L.learned,o.yellow,e)),r.push(...Z("Completed",L.completed,o.green,e)),r.push(...Z("Next Steps",L.next_steps,o.magenta,e))),T&&(r.push(""),r.push("---"),r.push(""),e?(r.push(`${o.bright}${o.magenta}\u{1F4CB} Previously${o.reset}`),r.push(""),r.push(`${o.dim}A: ${T}${o.reset}`)):(r.push("**\u{1F4CB} Previously**"),r.push(""),r.push(`A: ${T}`)),r.push("")),_e&&N>0&&y>0){let _=Math.round(N/1e3);r.push(""),e?r.push(`${o.dim}\u{1F4B0} Access ${_}k tokens of past research & decisions for just ${U.toLocaleString()}t. Use the mem-search skill to access memories by ID instead of re-reading files.${o.reset}`):r.push(`\u{1F4B0} Access ${_}k tokens of past research & decisions for just ${U.toLocaleString()}t. Use the mem-search skill to access memories by ID instead of re-reading files.`)}}return i?.close(),r.join(` +No previous sessions found for this project yet.`;let A=E.slice(0,t.sessionCount),g=l,r=[];if(e?(r.push(""),r.push(`${o.bright}${o.cyan}[${n}] recent context${o.reset}`),r.push(`${o.gray}${"\u2500".repeat(60)}${o.reset}`),r.push("")):(r.push(`# [${n}] recent context`),r.push("")),g.length>0){let O=X.getInstance().getActiveMode().observation_types.map(_=>`${_.emoji} ${_.id}`).join(" | ");e?r.push(`${o.dim}Legend: \u{1F3AF} session-request | ${O}${o.reset}`):r.push(`**Legend:** \u{1F3AF} session-request | ${O}`),r.push(""),e?(r.push(`${o.bright}\u{1F4A1} Column Key${o.reset}`),r.push(`${o.dim} Read: Tokens to read this observation (cost to learn it now)${o.reset}`),r.push(`${o.dim} Work: Tokens spent on work that produced this record (\u{1F50D} research, \u{1F6E0}\uFE0F building, \u2696\uFE0F deciding)${o.reset}`)):(r.push("\u{1F4A1} **Column Key**:"),r.push("- **Read**: Tokens to read this observation (cost to learn it now)"),r.push("- **Work**: Tokens spent on work that produced this record (\u{1F50D} research, \u{1F6E0}\uFE0F building, \u2696\uFE0F deciding)")),r.push(""),e?(r.push(`${o.dim}\u{1F4A1} Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${o.reset}`),r.push(""),r.push(`${o.dim}When you need implementation details, rationale, or debugging context:${o.reset}`),r.push(`${o.dim} - Use the mem-search skill to fetch full observations on-demand${o.reset}`),r.push(`${o.dim} - Critical types (\u{1F534} bugfix, \u2696\uFE0F decision) often need detailed fetching${o.reset}`),r.push(`${o.dim} - Trust this index over re-reading code for past decisions and learnings${o.reset}`)):(r.push("\u{1F4A1} **Context Index:** This semantic index (titles, types, files, tokens) is usually sufficient to understand past work."),r.push(""),r.push("When you need implementation details, rationale, or debugging context:"),r.push("- Use the mem-search skill to fetch full observations on-demand"),r.push("- Critical types (\u{1F534} bugfix, \u2696\uFE0F decision) often need detailed fetching"),r.push("- Trust this index over re-reading code for past decisions and learnings")),r.push("");let D=l.length,U=l.reduce((_,S)=>{let b=(S.title?.length||0)+(S.subtitle?.length||0)+(S.narrative?.length||0)+JSON.stringify(S.facts||[]).length;return _+Math.ceil(b/Ue)},0),N=l.reduce((_,S)=>_+(S.discovery_tokens||0),0),y=N-U,B=N>0?Math.round(y/N*100):0,_e=t.showReadTokens||t.showWorkTokens||t.showSavingsAmount||t.showSavingsPercent;if(_e)if(e){if(r.push(`${o.bright}${o.cyan}\u{1F4CA} Context Economics${o.reset}`),r.push(`${o.dim} Loading: ${D} observations (${U.toLocaleString()} tokens to read)${o.reset}`),r.push(`${o.dim} Work investment: ${N.toLocaleString()} tokens spent on research, building, and decisions${o.reset}`),N>0&&(t.showSavingsAmount||t.showSavingsPercent)){let _=" Your savings: ";t.showSavingsAmount&&t.showSavingsPercent?_+=`${y.toLocaleString()} tokens (${B}% reduction from reuse)`:t.showSavingsAmount?_+=`${y.toLocaleString()} tokens`:_+=`${B}% reduction from reuse`,r.push(`${o.green}${_}${o.reset}`)}r.push("")}else{if(r.push("\u{1F4CA} **Context Economics**:"),r.push(`- Loading: ${D} observations (${U.toLocaleString()} tokens to read)`),r.push(`- Work investment: ${N.toLocaleString()} tokens spent on research, building, and decisions`),N>0&&(t.showSavingsAmount||t.showSavingsPercent)){let _="- Your savings: ";t.showSavingsAmount&&t.showSavingsPercent?_+=`${y.toLocaleString()} tokens (${B}% reduction from reuse)`:t.showSavingsAmount?_+=`${y.toLocaleString()} tokens`:_+=`${B}% reduction from reuse`,r.push(_)}r.push("")}let xe=E[0]?.id,we=A.map((_,S)=>{let b=S===0?null:E[S+1];return{..._,displayEpoch:b?b.created_at_epoch:_.created_at_epoch,displayTime:b?b.created_at:_.created_at,shouldShowLink:_.id!==xe}}),Fe=new Set(l.slice(0,t.fullObservationCount).map(_=>_.id)),ue=[...g.map(_=>({type:"observation",data:_})),...we.map(_=>({type:"summary",data:_}))];ue.sort((_,S)=>{let b=_.type==="observation"?_.data.created_at_epoch:_.data.displayEpoch,M=S.type==="observation"?S.data.created_at_epoch:S.data.displayEpoch;return b-M});let Y=new Map;for(let _ of ue){let S=_.type==="observation"?_.data.created_at:_.data.displayTime,b=De(S);Y.has(b)||Y.set(b,[]),Y.get(b).push(_)}let Xe=Array.from(Y.entries()).sort((_,S)=>{let b=new Date(_[0]).getTime(),M=new Date(S[0]).getTime();return b-M});for(let[_,S]of Xe){e?(r.push(`${o.bright}${o.cyan}${_}${o.reset}`),r.push("")):(r.push(`### ${_}`),r.push(""));let b=null,M="",x=!1;for(let se of S)if(se.type==="summary"){x&&(r.push(""),x=!1,b=null,M="");let m=se.data,w=`${m.request||"Session started"} (${ve(m.displayTime)})`;e?r.push(`\u{1F3AF} ${o.yellow}#S${m.id}${o.reset} ${w}`):r.push(`**\u{1F3AF} #S${m.id}** ${w}`),r.push("")}else{let m=se.data,w=Me(m.files_modified,s);w!==b&&(x&&r.push(""),e?r.push(`${o.dim}${w}${o.reset}`):r.push(`**${w}**`),e||(r.push("| ID | Time | T | Title | Read | Work |"),r.push("|----|------|---|-------|------|------|")),b=w,x=!0,M="");let F=ye(m.created_at),V=m.title||"Untitled",K=X.getInstance().getTypeIcon(m.type),Pe=(m.title?.length||0)+(m.subtitle?.length||0)+(m.narrative?.length||0)+JSON.stringify(m.facts||[]).length,P=Math.ceil(Pe/Ue),j=m.discovery_tokens||0,re=X.getInstance().getWorkEmoji(m.type),me=j>0?`${re} ${j.toLocaleString()}`:"-",ne=F!==M,Ee=ne?F:"";if(M=F,Fe.has(m.id)){let k=t.fullObservationField==="narrative"?m.narrative:m.facts?pe(m.facts).join(` +`):null;if(e){let C=ne?`${o.dim}${F}${o.reset}`:" ".repeat(F.length),q=t.showReadTokens&&P>0?`${o.dim}(~${P}t)${o.reset}`:"",Te=t.showWorkTokens&&j>0?`${o.dim}(${re} ${j.toLocaleString()}t)${o.reset}`:"";r.push(` ${o.dim}#${m.id}${o.reset} ${C} ${K} ${o.bright}${V}${o.reset}`),k&&r.push(` ${o.dim}${k}${o.reset}`),(q||Te)&&r.push(` ${q} ${Te}`),r.push("")}else{x&&(r.push(""),x=!1),r.push(`**#${m.id}** ${Ee||"\u2033"} ${K} **${V}**`),k&&(r.push(""),r.push(k),r.push(""));let C=[];t.showReadTokens&&C.push(`Read: ~${P}`),t.showWorkTokens&&C.push(`Work: ${me}`),C.length>0&&r.push(C.join(", ")),r.push(""),b=null}}else if(e){let k=ne?`${o.dim}${F}${o.reset}`:" ".repeat(F.length),C=t.showReadTokens&&P>0?`${o.dim}(~${P}t)${o.reset}`:"",q=t.showWorkTokens&&j>0?`${o.dim}(${re} ${j.toLocaleString()}t)${o.reset}`:"";r.push(` ${o.dim}#${m.id}${o.reset} ${k} ${K} ${V} ${C} ${q}`)}else{let k=t.showReadTokens?`~${P}`:"",C=t.showWorkTokens?me:"";r.push(`| #${m.id} | ${Ee||"\u2033"} | ${K} | ${V} | ${k} | ${C} |`)}}x&&r.push("")}let L=E[0],le=l[0];if(t.showLastSummary&&L&&(L.investigated||L.learned||L.completed||L.next_steps)&&(!le||L.created_at_epoch>le.created_at_epoch)&&(r.push(...Z("Investigated",L.investigated,o.blue,e)),r.push(...Z("Learned",L.learned,o.yellow,e)),r.push(...Z("Completed",L.completed,o.green,e)),r.push(...Z("Next Steps",L.next_steps,o.magenta,e))),T&&(r.push(""),r.push("---"),r.push(""),e?(r.push(`${o.bright}${o.magenta}\u{1F4CB} Previously${o.reset}`),r.push(""),r.push(`${o.dim}A: ${T}${o.reset}`)):(r.push("**\u{1F4CB} Previously**"),r.push(""),r.push(`A: ${T}`)),r.push("")),_e&&N>0&&y>0){let _=Math.round(N/1e3);r.push(""),e?r.push(`${o.dim}\u{1F4B0} Access ${_}k tokens of past research & decisions for just ${U.toLocaleString()}t. Use the mem-search skill to access memories by ID instead of re-reading files.${o.reset}`):r.push(`\u{1F4B0} Access ${_}k tokens of past research & decisions for just ${U.toLocaleString()}t. Use the mem-search skill to access memories by ID instead of re-reading files.`)}}return i?.close(),r.join(` `).trimEnd()}0&&(module.exports={generateContext}); diff --git a/plugin/scripts/worker-service.cjs b/plugin/scripts/worker-service.cjs index 301fae31..36870521 100755 --- a/plugin/scripts/worker-service.cjs +++ b/plugin/scripts/worker-service.cjs @@ -1,5 +1,5 @@ #!/usr/bin/env bun -"use strict";var N$=Object.create;var Ho=Object.defineProperty;var j$=Object.getOwnPropertyDescriptor;var M$=Object.getOwnPropertyNames;var D$=Object.getPrototypeOf,q$=Object.prototype.hasOwnProperty;var ca=(t,e)=>()=>(t&&(e=t(t=0)),e);var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Jn=(t,e)=>{for(var r in e)Ho(t,r,{get:e[r],enumerable:!0})},lh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of M$(e))!q$.call(t,a)&&a!==r&&Ho(t,a,{get:()=>e[a],enumerable:!(n=j$(e,a))||n.enumerable});return t};var kt=(t,e,r)=>(r=t!=null?N$(D$(t)):{},lh(e||!t||!t.__esModule?Ho(r,"default",{value:t,enumerable:!0}):r,t)),L$=t=>lh(Ho({},"__esModule",{value:!0}),t);var Vr=V((K7,mh)=>{var F$=require("path").relative;mh.exports=V$;var z$=process.cwd();function ph(t,e){for(var r=t.split(/[ ,]+/),n=String(e).toLowerCase(),a=0;a()=>(t&&(e=t(t=0)),e);var V=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Jn=(t,e)=>{for(var r in e)Ho(t,r,{get:e[r],enumerable:!0})},lh=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of M$(e))!q$.call(t,a)&&a!==r&&Ho(t,a,{get:()=>e[a],enumerable:!(n=j$(e,a))||n.enumerable});return t};var $t=(t,e,r)=>(r=t!=null?N$(D$(t)):{},lh(e||!t||!t.__esModule?Ho(r,"default",{value:t,enumerable:!0}):r,t)),L$=t=>lh(Ho({},"__esModule",{value:!0}),t);var Vr=V((K7,mh)=>{var F$=require("path").relative;mh.exports=V$;var z$=process.cwd();function ph(t,e){for(var r=t.split(/[ ,]+/),n=String(e).toLowerCase(),a=0;a0}function G$(t){if(process.noDeprecation)return!0;var e=process.env.NO_DEPRECATION||"";return ph(e,t)}function W$(t){if(process.traceDeprecation)return!0;var e=process.env.TRACE_DEPRECATION||"";return ph(e,t)}function Bo(t,e){var r=Z$(process,"deprecation");if(!(!r&&this._ignored)){var n,a,s,i,o=0,c=!1,u=Vo(),l=this._file;for(e?(i=e,s=Yn(u[1]),s.name=i.name,l=s[0]):(o=2,i=Yn(u[o]),s=i);o",r=t.getLineNumber(),n=t.getColumnNumber();t.isEval()&&(e=t.getEvalOrigin()+", "+e);var a=[e,r,n];return a.callSite=t,a.name=t.getFunctionName(),a}function dh(t){var e=t.callSite,r=t.name;r||(r="");var n=e.getThis(),a=n&&e.getTypeName();return a==="Object"&&(a=void 0),a==="Function"&&(a=n.name||a),a&&e.getMethodName()?a+"."+r:r}function K$(t,e,r){var n=new Date().toUTCString(),a=n+" "+this._namespace+" deprecated "+t;if(this._traced){for(var s=0;s$t});var po,Lu,$t,La=ca(()=>{"use strict";po=require("fs"),Lu=require("path");mt();dr();$t=class t{static instance=null;activeMode=null;modesDir;constructor(){let e=nr(),r=[(0,Lu.join)(e,"modes"),(0,Lu.join)(e,"..","plugin","modes")],n=r.find(a=>(0,po.existsSync)(a));this.modesDir=n||r[0]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let a in r){let s=r[a],i=e[a];this.isPlainObject(s)&&this.isPlainObject(i)?n[a]=this.deepMerge(i,s):n[a]=s}return n}loadModeFile(e){let r=(0,Lu.join)(this.modesDir,`${e}.json`);if(!(0,po.existsSync)(r))throw new Error(`Mode file not found: ${r}`);let n=(0,po.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let c=this.loadModeFile(e);return this.activeMode=c,U.debug("SYSTEM",`Loaded mode: ${c.name} (${e})`,void 0,{types:c.observation_types.map(u=>u.id),concepts:c.observation_concepts.map(u=>u.id)}),c}catch{if(U.warn("SYSTEM",`Mode file not found: ${e}, falling back to 'code'`),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:a}=r,s;try{s=this.loadMode(n)}catch{U.warn("SYSTEM",`Parent mode '${n}' not found for ${e}, falling back to 'code'`),s=this.loadMode("code")}let i;try{i=this.loadModeFile(a),U.debug("SYSTEM",`Loaded override file: ${a} for parent ${n}`)}catch{return U.warn("SYSTEM",`Override file '${a}' not found, using parent mode '${n}' only`),this.activeMode=s,s}if(!i)return U.warn("SYSTEM",`Invalid override file: ${a}, using parent mode '${n}' only`),this.activeMode=s,s;let o=this.deepMerge(s,i);return this.activeMode=o,U.debug("SYSTEM",`Loaded mode with inheritance: ${o.name} (${e} = ${n} + ${a})`,void 0,{parent:n,override:a,types:o.observation_types.map(c=>c.id),concepts:o.observation_concepts.map(c=>c.id)}),o}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(r=>r.id===e)}getTypeLabel(e){return this.getObservationTypes().find(n=>n.id===e)?.label||e}}});function Hm(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function xa(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function ci(t){return new Date(t).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Ln(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function E7(t,e){return Um.default.isAbsolute(t)?Um.default.relative(e,t):t}function Fn(t,e){let r=Hm(t);return r.length>0?E7(r[0],e):"General"}function El(t){return t?Math.ceil(t.length/4):0}function Hk(t,e){let r=new Map;for(let a of t){let s=e(a),i=Ln(s);r.has(i)||r.set(i,[]),r.get(i).push(a)}let n=Array.from(r.entries()).sort((a,s)=>{let i=new Date(a[0]).getTime(),o=new Date(s[0]).getTime();return i-o});return new Map(n)}var Um,Bm=ca(()=>{"use strict";Um=kt(require("path"),1)});var Gk=V((GJ,Zk)=>{"use strict";var Vk=Object.getOwnPropertySymbols,$7=Object.prototype.hasOwnProperty,R7=Object.prototype.propertyIsEnumerable;function P7(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function O7(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var a={};return"abcdefghijklmnopqrst".split("").forEach(function(s){a[s]=s}),Object.keys(Object.assign({},a)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}Zk.exports=O7()?Object.assign:function(t,e){for(var r,n=P7(t),a,s=1;s{(function(){"use strict";var t=Gk(),e=Bp(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(g){return typeof g=="string"||g instanceof String}function a(g,b){if(Array.isArray(b)){for(var p=0;p{"use strict";s$=kt(require("path"),1);mt()});var ql={};Jn(ql,{generateContext:()=>D7});function A7(){let t=Ml.default.join((0,Dl.homedir)(),".claude-mem","settings.json"),e=ct.loadFromFile(t);return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(r=>r.trim()).filter(Boolean)),observationConcepts:new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(r=>r.trim()).filter(Boolean)),fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}function jl(t,e,r,n){return e?n?[`${r}${t}:${pe.reset} ${e}`,""]:[`**${t}**: ${e}`,""]:[]}function j7(t){return t.replace(/\//g,"-")}function M7(t){try{if(!(0,di.existsSync)(t))return{userMessage:"",assistantMessage:""};let e=(0,di.readFileSync)(t,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let r=e.split(` + `).run(e.claude_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}}});var s1={};Jn(s1,{ModeManager:()=>kt});var po,Lu,kt,La=ca(()=>{"use strict";po=require("fs"),Lu=require("path");mt();dr();kt=class t{static instance=null;activeMode=null;modesDir;constructor(){let e=nr(),r=[(0,Lu.join)(e,"modes"),(0,Lu.join)(e,"..","plugin","modes")],n=r.find(a=>(0,po.existsSync)(a));this.modesDir=n||r[0]}static getInstance(){return t.instance||(t.instance=new t),t.instance}parseInheritance(e){let r=e.split("--");if(r.length===1)return{hasParent:!1,parentId:"",overrideId:""};if(r.length>2)throw new Error(`Invalid mode inheritance: ${e}. Only one level of inheritance supported (parent--override)`);return{hasParent:!0,parentId:r[0],overrideId:e}}isPlainObject(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}deepMerge(e,r){let n={...e};for(let a in r){let s=r[a],i=e[a];this.isPlainObject(s)&&this.isPlainObject(i)?n[a]=this.deepMerge(i,s):n[a]=s}return n}loadModeFile(e){let r=(0,Lu.join)(this.modesDir,`${e}.json`);if(!(0,po.existsSync)(r))throw new Error(`Mode file not found: ${r}`);let n=(0,po.readFileSync)(r,"utf-8");return JSON.parse(n)}loadMode(e){let r=this.parseInheritance(e);if(!r.hasParent)try{let c=this.loadModeFile(e);return this.activeMode=c,U.debug("SYSTEM",`Loaded mode: ${c.name} (${e})`,void 0,{types:c.observation_types.map(u=>u.id),concepts:c.observation_concepts.map(u=>u.id)}),c}catch{if(U.warn("SYSTEM",`Mode file not found: ${e}, falling back to 'code'`),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:n,overrideId:a}=r,s;try{s=this.loadMode(n)}catch{U.warn("SYSTEM",`Parent mode '${n}' not found for ${e}, falling back to 'code'`),s=this.loadMode("code")}let i;try{i=this.loadModeFile(a),U.debug("SYSTEM",`Loaded override file: ${a} for parent ${n}`)}catch{return U.warn("SYSTEM",`Override file '${a}' not found, using parent mode '${n}' only`),this.activeMode=s,s}if(!i)return U.warn("SYSTEM",`Invalid override file: ${a}, using parent mode '${n}' only`),this.activeMode=s,s;let o=this.deepMerge(s,i);return this.activeMode=o,U.debug("SYSTEM",`Loaded mode with inheritance: ${o.name} (${e} = ${n} + ${a})`,void 0,{parent:n,override:a,types:o.observation_types.map(c=>c.id),concepts:o.observation_concepts.map(c=>c.id)}),o}getActiveMode(){if(!this.activeMode)throw new Error("No mode loaded. Call loadMode() first.");return this.activeMode}getObservationTypes(){return this.getActiveMode().observation_types}getObservationConcepts(){return this.getActiveMode().observation_concepts}getTypeIcon(e){return this.getObservationTypes().find(n=>n.id===e)?.emoji||"\u{1F4DD}"}getWorkEmoji(e){return this.getObservationTypes().find(n=>n.id===e)?.work_emoji||"\u{1F4DD}"}validateType(e){return this.getObservationTypes().some(r=>r.id===e)}getTypeLabel(e){return this.getObservationTypes().find(n=>n.id===e)?.label||e}}});function Hm(t){if(!t)return[];try{let e=JSON.parse(t);return Array.isArray(e)?e:[]}catch{return[]}}function xa(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function ci(t){return new Date(t).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function Ln(t){return new Date(t).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function E7(t,e){return Um.default.isAbsolute(t)?Um.default.relative(e,t):t}function Fn(t,e){let r=Hm(t);return r.length>0?E7(r[0],e):"General"}function El(t){return t?Math.ceil(t.length/4):0}function Hk(t,e){let r=new Map;for(let a of t){let s=e(a),i=Ln(s);r.has(i)||r.set(i,[]),r.get(i).push(a)}let n=Array.from(r.entries()).sort((a,s)=>{let i=new Date(a[0]).getTime(),o=new Date(s[0]).getTime();return i-o});return new Map(n)}var Um,Bm=ca(()=>{"use strict";Um=$t(require("path"),1)});var Gk=V((GJ,Zk)=>{"use strict";var Vk=Object.getOwnPropertySymbols,$7=Object.prototype.hasOwnProperty,R7=Object.prototype.propertyIsEnumerable;function P7(t){if(t==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}function O7(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de",Object.getOwnPropertyNames(t)[0]==="5")return!1;for(var e={},r=0;r<10;r++)e["_"+String.fromCharCode(r)]=r;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var a={};return"abcdefghijklmnopqrst".split("").forEach(function(s){a[s]=s}),Object.keys(Object.assign({},a)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}Zk.exports=O7()?Object.assign:function(t,e){for(var r,n=P7(t),a,s=1;s{(function(){"use strict";var t=Gk(),e=Bp(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(g){return typeof g=="string"||g instanceof String}function a(g,b){if(Array.isArray(b)){for(var p=0;p{"use strict";s$=$t(require("path"),1);mt()});var ql={};Jn(ql,{generateContext:()=>D7});function A7(){let t=Ml.default.join((0,Dl.homedir)(),".claude-mem","settings.json"),e=ct.loadFromFile(t),r=e.CLAUDE_MEM_MODE,n=r==="code"||r.startsWith("code--"),a,s;if(n)a=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(",").map(i=>i.trim()).filter(Boolean)),s=new Set(e.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(",").map(i=>i.trim()).filter(Boolean));else{let i=kt.getInstance().getActiveMode();a=new Set(i.observation_types.map(o=>o.id)),s=new Set(i.observation_concepts.map(o=>o.id))}return{totalObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10),fullObservationCount:parseInt(e.CLAUDE_MEM_CONTEXT_FULL_COUNT,10),sessionCount:parseInt(e.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10),showReadTokens:e.CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS==="true",showWorkTokens:e.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS==="true",showSavingsAmount:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT==="true",showSavingsPercent:e.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT==="true",observationTypes:a,observationConcepts:s,fullObservationField:e.CLAUDE_MEM_CONTEXT_FULL_FIELD,showLastSummary:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY==="true",showLastMessage:e.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE==="true"}}function jl(t,e,r,n){return e?n?[`${r}${t}:${pe.reset} ${e}`,""]:[`**${t}**: ${e}`,""]:[]}function j7(t){return t.replace(/\//g,"-")}function M7(t){try{if(!(0,di.existsSync)(t))return{userMessage:"",assistantMessage:""};let e=(0,di.readFileSync)(t,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let r=e.split(` `).filter(a=>a.trim()),n="";for(let a=r.length-1;a>=0;a--)try{let s=r[a];if(!s.includes('"type":"assistant"'))continue;let i=JSON.parse(s);if(i.type==="assistant"&&i.message?.content&&Array.isArray(i.message.content)){let o="";for(let c of i.message.content)c.type==="text"&&(o+=c.text);if(o=o.replace(/[\s\S]*?<\/system-reminder>/g,"").trim(),o){n=o;break}}}catch{continue}return{userMessage:"",assistantMessage:n}}catch(e){return U.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:t},e),{userMessage:"",assistantMessage:""}}}async function D7(t,e=!1){let r=A7(),n=t?.cwd??process.cwd(),a=i$(n),s=null;try{s=new qa}catch(h){if(h.code==="ERR_DLOPEN_FAILED"){try{(0,di.unlinkSync)(I7)}catch{}return console.error("Native module rebuild needed - restart Claude Code to auto-fix"),""}throw h}let i=Array.from(r.observationTypes),o=i.map(()=>"?").join(","),c=Array.from(r.observationConcepts),u=c.map(()=>"?").join(","),l=s.db.prepare(` SELECT id, sdk_session_id, type, title, subtitle, narrative, @@ -591,11 +591,11 @@ ${pe.gray}${"\u2500".repeat(60)}${pe.reset} ${pe.dim}No previous sessions found for this project yet.${pe.reset} `:`# [${a}] recent context -No previous sessions found for this project yet.`;let g=d.slice(0,r.sessionCount),b=l,p=[];if(e?(p.push(""),p.push(`${pe.bright}${pe.cyan}[${a}] recent context${pe.reset}`),p.push(`${pe.gray}${"\u2500".repeat(60)}${pe.reset}`),p.push("")):(p.push(`# [${a}] recent context`),p.push("")),b.length>0){let y=$t.getInstance().getActiveMode().observation_types.map(ne=>`${ne.emoji} ${ne.id}`).join(" | ");e?p.push(`${pe.dim}Legend: \u{1F3AF} session-request | ${y}${pe.reset}`):p.push(`**Legend:** \u{1F3AF} session-request | ${y}`),p.push(""),e?(p.push(`${pe.bright}\u{1F4A1} Column Key${pe.reset}`),p.push(`${pe.dim} Read: Tokens to read this observation (cost to learn it now)${pe.reset}`),p.push(`${pe.dim} Work: Tokens spent on work that produced this record (\u{1F50D} research, \u{1F6E0}\uFE0F building, \u2696\uFE0F deciding)${pe.reset}`)):(p.push("\u{1F4A1} **Column Key**:"),p.push("- **Read**: Tokens to read this observation (cost to learn it now)"),p.push("- **Work**: Tokens spent on work that produced this record (\u{1F50D} research, \u{1F6E0}\uFE0F building, \u2696\uFE0F deciding)")),p.push(""),e?(p.push(`${pe.dim}\u{1F4A1} Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${pe.reset}`),p.push(""),p.push(`${pe.dim}When you need implementation details, rationale, or debugging context:${pe.reset}`),p.push(`${pe.dim} - Use the mem-search skill to fetch full observations on-demand${pe.reset}`),p.push(`${pe.dim} - Critical types (\u{1F534} bugfix, \u2696\uFE0F decision) often need detailed fetching${pe.reset}`),p.push(`${pe.dim} - Trust this index over re-reading code for past decisions and learnings${pe.reset}`)):(p.push("\u{1F4A1} **Context Index:** This semantic index (titles, types, files, tokens) is usually sufficient to understand past work."),p.push(""),p.push("When you need implementation details, rationale, or debugging context:"),p.push("- Use the mem-search skill to fetch full observations on-demand"),p.push("- Critical types (\u{1F534} bugfix, \u2696\uFE0F decision) often need detailed fetching"),p.push("- Trust this index over re-reading code for past decisions and learnings")),p.push("");let v=l.length,_=l.reduce((ne,re)=>{let F=(re.title?.length||0)+(re.subtitle?.length||0)+(re.narrative?.length||0)+JSON.stringify(re.facts||[]).length;return ne+Math.ceil(F/c$)},0),S=l.reduce((ne,re)=>ne+(re.discovery_tokens||0),0),x=S-_,E=S>0?Math.round(x/S*100):0,T=r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent;if(T)if(e){if(p.push(`${pe.bright}${pe.cyan}\u{1F4CA} Context Economics${pe.reset}`),p.push(`${pe.dim} Loading: ${v} observations (${_.toLocaleString()} tokens to read)${pe.reset}`),p.push(`${pe.dim} Work investment: ${S.toLocaleString()} tokens spent on research, building, and decisions${pe.reset}`),S>0&&(r.showSavingsAmount||r.showSavingsPercent)){let ne=" Your savings: ";r.showSavingsAmount&&r.showSavingsPercent?ne+=`${x.toLocaleString()} tokens (${E}% reduction from reuse)`:r.showSavingsAmount?ne+=`${x.toLocaleString()} tokens`:ne+=`${E}% reduction from reuse`,p.push(`${pe.green}${ne}${pe.reset}`)}p.push("")}else{if(p.push("\u{1F4CA} **Context Economics**:"),p.push(`- Loading: ${v} observations (${_.toLocaleString()} tokens to read)`),p.push(`- Work investment: ${S.toLocaleString()} tokens spent on research, building, and decisions`),S>0&&(r.showSavingsAmount||r.showSavingsPercent)){let ne="- Your savings: ";r.showSavingsAmount&&r.showSavingsPercent?ne+=`${x.toLocaleString()} tokens (${E}% reduction from reuse)`:r.showSavingsAmount?ne+=`${x.toLocaleString()} tokens`:ne+=`${E}% reduction from reuse`,p.push(ne)}p.push("")}let $=d[0]?.id,N=g.map((ne,re)=>{let F=re===0?null:d[re+1];return{...ne,displayEpoch:F?F.created_at_epoch:ne.created_at_epoch,displayTime:F?F.created_at:ne.created_at,shouldShowLink:ne.id!==$}}),j=new Set(l.slice(0,r.fullObservationCount).map(ne=>ne.id)),q=[...b.map(ne=>({type:"observation",data:ne})),...N.map(ne=>({type:"summary",data:ne}))];q.sort((ne,re)=>{let F=ne.type==="observation"?ne.data.created_at_epoch:ne.data.displayEpoch,R=re.type==="observation"?re.data.created_at_epoch:re.data.displayEpoch;return F-R});let H=new Map;for(let ne of q){let re=ne.type==="observation"?ne.data.created_at:ne.data.displayTime,F=Ln(re);H.has(F)||H.set(F,[]),H.get(F).push(ne)}let A=Array.from(H.entries()).sort((ne,re)=>{let F=new Date(ne[0]).getTime(),R=new Date(re[0]).getTime();return F-R});for(let[ne,re]of A){e?(p.push(`${pe.bright}${pe.cyan}${ne}${pe.reset}`),p.push("")):(p.push(`### ${ne}`),p.push(""));let F=null,R="",z=!1;for(let I of re)if(I.type==="summary"){z&&(p.push(""),z=!1,F=null,R="");let w=I.data,k=`${w.request||"Session started"} (${xa(w.displayTime)})`;e?p.push(`\u{1F3AF} ${pe.yellow}#S${w.id}${pe.reset} ${k}`):p.push(`**\u{1F3AF} #S${w.id}** ${k}`),p.push("")}else{let w=I.data,k=Fn(w.files_modified,n);k!==F&&(z&&p.push(""),e?p.push(`${pe.dim}${k}${pe.reset}`):p.push(`**${k}**`),e||(p.push("| ID | Time | T | Title | Read | Work |"),p.push("|----|------|---|-------|------|------|")),F=k,z=!0,R="");let M=ci(w.created_at),K=w.title||"Untitled",J=$t.getInstance().getTypeIcon(w.type),de=(w.title?.length||0)+(w.subtitle?.length||0)+(w.narrative?.length||0)+JSON.stringify(w.facts||[]).length,se=Math.ceil(de/c$),me=w.discovery_tokens||0,O=$t.getInstance().getWorkEmoji(w.type),C=me>0?`${O} ${me.toLocaleString()}`:"-",L=M!==R,G=L?M:"";if(R=M,j.has(w.id)){let ce=r.fullObservationField==="narrative"?w.narrative:w.facts?Hm(w.facts).join(` +No previous sessions found for this project yet.`;let g=d.slice(0,r.sessionCount),b=l,p=[];if(e?(p.push(""),p.push(`${pe.bright}${pe.cyan}[${a}] recent context${pe.reset}`),p.push(`${pe.gray}${"\u2500".repeat(60)}${pe.reset}`),p.push("")):(p.push(`# [${a}] recent context`),p.push("")),b.length>0){let y=kt.getInstance().getActiveMode().observation_types.map(ne=>`${ne.emoji} ${ne.id}`).join(" | ");e?p.push(`${pe.dim}Legend: \u{1F3AF} session-request | ${y}${pe.reset}`):p.push(`**Legend:** \u{1F3AF} session-request | ${y}`),p.push(""),e?(p.push(`${pe.bright}\u{1F4A1} Column Key${pe.reset}`),p.push(`${pe.dim} Read: Tokens to read this observation (cost to learn it now)${pe.reset}`),p.push(`${pe.dim} Work: Tokens spent on work that produced this record (\u{1F50D} research, \u{1F6E0}\uFE0F building, \u2696\uFE0F deciding)${pe.reset}`)):(p.push("\u{1F4A1} **Column Key**:"),p.push("- **Read**: Tokens to read this observation (cost to learn it now)"),p.push("- **Work**: Tokens spent on work that produced this record (\u{1F50D} research, \u{1F6E0}\uFE0F building, \u2696\uFE0F deciding)")),p.push(""),e?(p.push(`${pe.dim}\u{1F4A1} Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${pe.reset}`),p.push(""),p.push(`${pe.dim}When you need implementation details, rationale, or debugging context:${pe.reset}`),p.push(`${pe.dim} - Use the mem-search skill to fetch full observations on-demand${pe.reset}`),p.push(`${pe.dim} - Critical types (\u{1F534} bugfix, \u2696\uFE0F decision) often need detailed fetching${pe.reset}`),p.push(`${pe.dim} - Trust this index over re-reading code for past decisions and learnings${pe.reset}`)):(p.push("\u{1F4A1} **Context Index:** This semantic index (titles, types, files, tokens) is usually sufficient to understand past work."),p.push(""),p.push("When you need implementation details, rationale, or debugging context:"),p.push("- Use the mem-search skill to fetch full observations on-demand"),p.push("- Critical types (\u{1F534} bugfix, \u2696\uFE0F decision) often need detailed fetching"),p.push("- Trust this index over re-reading code for past decisions and learnings")),p.push("");let v=l.length,_=l.reduce((ne,re)=>{let F=(re.title?.length||0)+(re.subtitle?.length||0)+(re.narrative?.length||0)+JSON.stringify(re.facts||[]).length;return ne+Math.ceil(F/c$)},0),S=l.reduce((ne,re)=>ne+(re.discovery_tokens||0),0),x=S-_,E=S>0?Math.round(x/S*100):0,T=r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent;if(T)if(e){if(p.push(`${pe.bright}${pe.cyan}\u{1F4CA} Context Economics${pe.reset}`),p.push(`${pe.dim} Loading: ${v} observations (${_.toLocaleString()} tokens to read)${pe.reset}`),p.push(`${pe.dim} Work investment: ${S.toLocaleString()} tokens spent on research, building, and decisions${pe.reset}`),S>0&&(r.showSavingsAmount||r.showSavingsPercent)){let ne=" Your savings: ";r.showSavingsAmount&&r.showSavingsPercent?ne+=`${x.toLocaleString()} tokens (${E}% reduction from reuse)`:r.showSavingsAmount?ne+=`${x.toLocaleString()} tokens`:ne+=`${E}% reduction from reuse`,p.push(`${pe.green}${ne}${pe.reset}`)}p.push("")}else{if(p.push("\u{1F4CA} **Context Economics**:"),p.push(`- Loading: ${v} observations (${_.toLocaleString()} tokens to read)`),p.push(`- Work investment: ${S.toLocaleString()} tokens spent on research, building, and decisions`),S>0&&(r.showSavingsAmount||r.showSavingsPercent)){let ne="- Your savings: ";r.showSavingsAmount&&r.showSavingsPercent?ne+=`${x.toLocaleString()} tokens (${E}% reduction from reuse)`:r.showSavingsAmount?ne+=`${x.toLocaleString()} tokens`:ne+=`${E}% reduction from reuse`,p.push(ne)}p.push("")}let $=d[0]?.id,N=g.map((ne,re)=>{let F=re===0?null:d[re+1];return{...ne,displayEpoch:F?F.created_at_epoch:ne.created_at_epoch,displayTime:F?F.created_at:ne.created_at,shouldShowLink:ne.id!==$}}),j=new Set(l.slice(0,r.fullObservationCount).map(ne=>ne.id)),q=[...b.map(ne=>({type:"observation",data:ne})),...N.map(ne=>({type:"summary",data:ne}))];q.sort((ne,re)=>{let F=ne.type==="observation"?ne.data.created_at_epoch:ne.data.displayEpoch,R=re.type==="observation"?re.data.created_at_epoch:re.data.displayEpoch;return F-R});let H=new Map;for(let ne of q){let re=ne.type==="observation"?ne.data.created_at:ne.data.displayTime,F=Ln(re);H.has(F)||H.set(F,[]),H.get(F).push(ne)}let A=Array.from(H.entries()).sort((ne,re)=>{let F=new Date(ne[0]).getTime(),R=new Date(re[0]).getTime();return F-R});for(let[ne,re]of A){e?(p.push(`${pe.bright}${pe.cyan}${ne}${pe.reset}`),p.push("")):(p.push(`### ${ne}`),p.push(""));let F=null,R="",z=!1;for(let I of re)if(I.type==="summary"){z&&(p.push(""),z=!1,F=null,R="");let w=I.data,k=`${w.request||"Session started"} (${xa(w.displayTime)})`;e?p.push(`\u{1F3AF} ${pe.yellow}#S${w.id}${pe.reset} ${k}`):p.push(`**\u{1F3AF} #S${w.id}** ${k}`),p.push("")}else{let w=I.data,k=Fn(w.files_modified,n);k!==F&&(z&&p.push(""),e?p.push(`${pe.dim}${k}${pe.reset}`):p.push(`**${k}**`),e||(p.push("| ID | Time | T | Title | Read | Work |"),p.push("|----|------|---|-------|------|------|")),F=k,z=!0,R="");let M=ci(w.created_at),K=w.title||"Untitled",J=kt.getInstance().getTypeIcon(w.type),de=(w.title?.length||0)+(w.subtitle?.length||0)+(w.narrative?.length||0)+JSON.stringify(w.facts||[]).length,se=Math.ceil(de/c$),me=w.discovery_tokens||0,O=kt.getInstance().getWorkEmoji(w.type),C=me>0?`${O} ${me.toLocaleString()}`:"-",L=M!==R,G=L?M:"";if(R=M,j.has(w.id)){let ce=r.fullObservationField==="narrative"?w.narrative:w.facts?Hm(w.facts).join(` `):null;if(e){let Te=L?`${pe.dim}${M}${pe.reset}`:" ".repeat(M.length),Ie=r.showReadTokens&&se>0?`${pe.dim}(~${se}t)${pe.reset}`:"",Ae=r.showWorkTokens&&me>0?`${pe.dim}(${O} ${me.toLocaleString()}t)${pe.reset}`:"";p.push(` ${pe.dim}#${w.id}${pe.reset} ${Te} ${J} ${pe.bright}${K}${pe.reset}`),ce&&p.push(` ${pe.dim}${ce}${pe.reset}`),(Ie||Ae)&&p.push(` ${Ie} ${Ae}`),p.push("")}else{z&&(p.push(""),z=!1),p.push(`**#${w.id}** ${G||"\u2033"} ${J} **${K}**`),ce&&(p.push(""),p.push(ce),p.push(""));let Te=[];r.showReadTokens&&Te.push(`Read: ~${se}`),r.showWorkTokens&&Te.push(`Work: ${C}`),Te.length>0&&p.push(Te.join(", ")),p.push(""),F=null}}else if(e){let ce=L?`${pe.dim}${M}${pe.reset}`:" ".repeat(M.length),Te=r.showReadTokens&&se>0?`${pe.dim}(~${se}t)${pe.reset}`:"",Ie=r.showWorkTokens&&me>0?`${pe.dim}(${O} ${me.toLocaleString()}t)${pe.reset}`:"";p.push(` ${pe.dim}#${w.id}${pe.reset} ${ce} ${J} ${K} ${Te} ${Ie}`)}else{let ce=r.showReadTokens?`~${se}`:"",Te=r.showWorkTokens?C:"";p.push(`| #${w.id} | ${G||"\u2033"} | ${J} | ${K} | ${ce} | ${Te} |`)}}z&&p.push("")}let W=d[0],oe=l[0];if(r.showLastSummary&&W&&(W.investigated||W.learned||W.completed||W.next_steps)&&(!oe||W.created_at_epoch>oe.created_at_epoch)&&(p.push(...jl("Investigated",W.investigated,pe.blue,e)),p.push(...jl("Learned",W.learned,pe.yellow,e)),p.push(...jl("Completed",W.completed,pe.green,e)),p.push(...jl("Next Steps",W.next_steps,pe.magenta,e))),m&&(p.push(""),p.push("---"),p.push(""),e?(p.push(`${pe.bright}${pe.magenta}\u{1F4CB} Previously${pe.reset}`),p.push(""),p.push(`${pe.dim}A: ${m}${pe.reset}`)):(p.push("**\u{1F4CB} Previously**"),p.push(""),p.push(`A: ${m}`)),p.push("")),T&&S>0&&x>0){let ne=Math.round(S/1e3);p.push(""),e?p.push(`${pe.dim}\u{1F4B0} Access ${ne}k tokens of past research & decisions for just ${_.toLocaleString()}t. Use the mem-search skill to access memories by ID instead of re-reading files.${pe.reset}`):p.push(`\u{1F4B0} Access ${ne}k tokens of past research & decisions for just ${_.toLocaleString()}t. Use the mem-search skill to access memories by ID instead of re-reading files.`)}}return s?.close(),p.join(` -`).trimEnd()}var Ml,Dl,di,I7,c$,N7,pe,Ll=ca(()=>{"use strict";Ml=kt(require("path"),1),Dl=require("os"),di=require("fs");Iu();mt();Dr();Bm();o$();La();I7=Ml.default.join((0,Dl.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");c$=4,N7=1,pe={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"}});var L7={};Jn(L7,{WorkerService:()=>Hl});module.exports=L$(L7);var f$=kt(Kc(),1),pi=kt(require("path"),1),Qm=kt(require("fs"),1);var P={};Jn(P,{BRAND:()=>c2,DIRTY:()=>fn,EMPTY_PATH:()=>FM,INVALID:()=>$e,NEVER:()=>Z2,OK:()=>Ut,ParseStatus:()=>Lt,Schema:()=>qe,ZodAny:()=>Aa,ZodArray:()=>ma,ZodBigInt:()=>hn,ZodBoolean:()=>vn,ZodBranded:()=>eo,ZodCatch:()=>$n,ZodDate:()=>gn,ZodDefault:()=>kn,ZodDiscriminatedUnion:()=>Yc,ZodEffects:()=>wr,ZodEnum:()=>En,ZodError:()=>er,ZodFirstPartyTypeKind:()=>Pe,ZodFunction:()=>eu,ZodIntersection:()=>xn,ZodIssueCode:()=>ie,ZodLazy:()=>wn,ZodLiteral:()=>Sn,ZodMap:()=>Os,ZodNaN:()=>Is,ZodNativeEnum:()=>Tn,ZodNever:()=>Mr,ZodNull:()=>_n,ZodNullable:()=>ea,ZodNumber:()=>mn,ZodObject:()=>tr,ZodOptional:()=>br,ZodParsedType:()=>ge,ZodPipeline:()=>to,ZodPromise:()=>Na,ZodReadonly:()=>Rn,ZodRecord:()=>Qc,ZodSchema:()=>qe,ZodSet:()=>Cs,ZodString:()=>Ia,ZodSymbol:()=>Rs,ZodTransformer:()=>wr,ZodTuple:()=>Qr,ZodType:()=>qe,ZodUndefined:()=>yn,ZodUnion:()=>bn,ZodUnknown:()=>fa,ZodVoid:()=>Ps,addIssueToContext:()=>fe,any:()=>g2,array:()=>x2,bigint:()=>p2,boolean:()=>xx,coerce:()=>V2,custom:()=>yx,date:()=>f2,datetimeRegex:()=>vx,defaultErrorMap:()=>da,discriminatedUnion:()=>T2,effect:()=>D2,enum:()=>N2,function:()=>C2,getErrorMap:()=>Ts,getParsedType:()=>Yr,instanceof:()=>l2,intersection:()=>k2,isAborted:()=>Xc,isAsync:()=>ks,isDirty:()=>Jc,isValid:()=>Ca,late:()=>u2,lazy:()=>I2,literal:()=>A2,makeIssue:()=>Qi,map:()=>P2,nan:()=>d2,nativeEnum:()=>j2,never:()=>_2,null:()=>v2,nullable:()=>L2,number:()=>bx,object:()=>w2,objectUtil:()=>Wp,oboolean:()=>B2,onumber:()=>H2,optional:()=>q2,ostring:()=>U2,pipeline:()=>z2,preprocess:()=>F2,promise:()=>M2,quotelessJson:()=>DM,record:()=>R2,set:()=>O2,setErrorMap:()=>LM,strictObject:()=>S2,string:()=>_x,symbol:()=>m2,transformer:()=>D2,tuple:()=>$2,undefined:()=>h2,union:()=>E2,unknown:()=>y2,util:()=>He,void:()=>b2});var He;(function(t){t.assertEqual=a=>{};function e(a){}t.assertIs=e;function r(a){throw new Error}t.assertNever=r,t.arrayToEnum=a=>{let s={};for(let i of a)s[i]=i;return s},t.getValidEnumValues=a=>{let s=t.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(let o of s)i[o]=a[o];return t.objectValues(i)},t.objectValues=a=>t.objectKeys(a).map(function(s){return a[s]}),t.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let s=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&s.push(i);return s},t.find=(a,s)=>{for(let i of a)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(a,s)=>typeof s=="bigint"?s.toString():s})(He||(He={}));var Wp;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Wp||(Wp={}));var ge=He.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Yr=t=>{switch(typeof t){case"undefined":return ge.undefined;case"string":return ge.string;case"number":return Number.isNaN(t)?ge.nan:ge.number;case"boolean":return ge.boolean;case"function":return ge.function;case"bigint":return ge.bigint;case"symbol":return ge.symbol;case"object":return Array.isArray(t)?ge.array:t===null?ge.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ge.promise:typeof Map<"u"&&t instanceof Map?ge.map:typeof Set<"u"&&t instanceof Set?ge.set:typeof Date<"u"&&t instanceof Date?ge.date:ge.object;default:return ge.unknown}};var ie=He.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),DM=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),er=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},a=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;cr.message){let r={},n=[];for(let a of this.issues)if(a.path.length>0){let s=a.path[0];r[s]=r[s]||[],r[s].push(e(a))}else n.push(e(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};er.create=t=>new er(t);var qM=(t,e)=>{let r;switch(t.code){case ie.invalid_type:t.received===ge.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case ie.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,He.jsonStringifyReplacer)}`;break;case ie.unrecognized_keys:r=`Unrecognized key(s) in object: ${He.joinValues(t.keys,", ")}`;break;case ie.invalid_union:r="Invalid input";break;case ie.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${He.joinValues(t.options)}`;break;case ie.invalid_enum_value:r=`Invalid enum value. Expected ${He.joinValues(t.options)}, received '${t.received}'`;break;case ie.invalid_arguments:r="Invalid function arguments";break;case ie.invalid_return_type:r="Invalid function return type";break;case ie.invalid_date:r="Invalid date";break;case ie.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:He.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case ie.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case ie.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case ie.custom:r="Invalid input";break;case ie.invalid_intersection_types:r="Intersection results could not be merged";break;case ie.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case ie.not_finite:r="Number must be finite";break;default:r=e.defaultError,He.assertNever(t)}return{message:r}},da=qM;var dx=da;function LM(t){dx=t}function Ts(){return dx}var Qi=t=>{let{data:e,path:r,errorMaps:n,issueData:a}=t,s=[...r,...a.path||[]],i={...a,path:s};if(a.message!==void 0)return{...a,path:s,message:a.message};let o="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:e,defaultError:o}).message;return{...a,path:s,message:o}},FM=[];function fe(t,e){let r=Ts(),n=Qi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===da?void 0:da].filter(a=>!!a)});t.common.issues.push(n)}var Lt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let a of r){if(a.status==="aborted")return $e;a.status==="dirty"&&e.dirty(),n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let a of r){let s=await a.key,i=await a.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let a of r){let{key:s,value:i}=a;if(s.status==="aborted"||i.status==="aborted")return $e;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},$e=Object.freeze({status:"aborted"}),fn=t=>({status:"dirty",value:t}),Ut=t=>({status:"valid",value:t}),Xc=t=>t.status==="aborted",Jc=t=>t.status==="dirty",Ca=t=>t.status==="valid",ks=t=>typeof Promise<"u"&&t instanceof Promise;var be;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(be||(be={}));var xr=class{constructor(e,r,n,a){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},px=(t,e)=>{if(Ca(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new er(t.common.issues);return this._error=r,this._error}}};function je(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:a}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(i,o)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}var qe=class{get description(){return this._def.description}_getType(e){return Yr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Lt,ctx:{common:e.parent.common,data:e.data,parsedType:Yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ks(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Yr(e)},a=this._parseSync({data:e,path:n.path,parent:n});return px(n,a)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Yr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Ca(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Ca(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Yr(e)},a=this._parse({data:e,path:n.path,parent:n}),s=await(ks(a)?a:Promise.resolve(a));return px(n,s)}refine(e,r){let n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,s)=>{let i=e(a),o=()=>s.addIssue({code:ie.custom,...n(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,a)=>e(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(e){return new wr({schema:this,typeName:Pe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return br.create(this,this._def)}nullable(){return ea.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ma.create(this)}promise(){return Na.create(this,this._def)}or(e){return bn.create([this,e],this._def)}and(e){return xn.create(this,e,this._def)}transform(e){return new wr({...je(this._def),schema:this,typeName:Pe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new kn({...je(this._def),innerType:this,defaultValue:r,typeName:Pe.ZodDefault})}brand(){return new eo({typeName:Pe.ZodBranded,type:this,...je(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new $n({...je(this._def),innerType:this,catchValue:r,typeName:Pe.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return to.create(this,e)}readonly(){return Rn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zM=/^c[^\s-]{8,}$/i,UM=/^[0-9a-z]+$/,HM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,BM=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,VM=/^[a-z0-9_-]{21}$/i,ZM=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,GM=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,WM=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,KM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Kp,XM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,JM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,YM=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,QM=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,e2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,t2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mx="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",r2=new RegExp(`^${mx}$`);function hx(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function a2(t){return new RegExp(`^${hx(t)}$`)}function vx(t){let e=`${mx}T${hx(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function n2(t,e){return!!((e==="v4"||!e)&&XM.test(t)||(e==="v6"||!e)&&YM.test(t))}function s2(t,e){if(!ZM.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function i2(t,e){return!!((e==="v4"||!e)&&JM.test(t)||(e==="v6"||!e)&&QM.test(t))}var Ia=class t extends qe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ge.string){let s=this._getOrReturnCtx(e);return fe(s,{code:ie.invalid_type,expected:ge.string,received:s.parsedType}),$e}let n=new Lt,a;for(let s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(a=this._getOrReturnCtx(e,a),fe(a,{code:ie.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,o=e.data.lengthe.test(a),{validation:r,code:ie.invalid_string,...be.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...be.errToObj(e)})}url(e){return this._addCheck({kind:"url",...be.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...be.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...be.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...be.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...be.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...be.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...be.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...be.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...be.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...be.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...be.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...be.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...be.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...be.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...be.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...be.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...be.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...be.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...be.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...be.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...be.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...be.errToObj(r)})}nonempty(e){return this.min(1,be.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Ia({checks:[],typeName:Pe.ZodString,coerce:t?.coerce??!1,...je(t)});function o2(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,a=r>n?r:n,s=Number.parseInt(t.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return s%i/10**a}var mn=class t extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ge.number){let s=this._getOrReturnCtx(e);return fe(s,{code:ie.invalid_type,expected:ge.number,received:s.parsedType}),$e}let n,a=new Lt;for(let s of this._def.checks)s.kind==="int"?He.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="multipleOf"?o2(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.not_finite,message:s.message}),a.dirty()):He.assertNever(s);return{status:a.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,be.toString(r))}gt(e,r){return this.setLimit("min",e,!1,be.toString(r))}lte(e,r){return this.setLimit("max",e,!0,be.toString(r))}lt(e,r){return this.setLimit("max",e,!1,be.toString(r))}setLimit(e,r,n,a){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:be.toString(a)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:be.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:be.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:be.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:be.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:be.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:be.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:be.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:be.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:be.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&He.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.valuenew mn({checks:[],typeName:Pe.ZodNumber,coerce:t?.coerce||!1,...je(t)});var hn=class t extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ge.bigint)return this._getInvalidInput(e);let n,a=new Lt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):He.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return fe(r,{code:ie.invalid_type,expected:ge.bigint,received:r.parsedType}),$e}gte(e,r){return this.setLimit("min",e,!0,be.toString(r))}gt(e,r){return this.setLimit("min",e,!1,be.toString(r))}lte(e,r){return this.setLimit("max",e,!0,be.toString(r))}lt(e,r){return this.setLimit("max",e,!1,be.toString(r))}setLimit(e,r,n,a){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:be.toString(a)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:be.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:be.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:be.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:be.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:be.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew hn({checks:[],typeName:Pe.ZodBigInt,coerce:t?.coerce??!1,...je(t)});var vn=class extends qe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ge.boolean){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.boolean,received:n.parsedType}),$e}return Ut(e.data)}};vn.create=t=>new vn({typeName:Pe.ZodBoolean,coerce:t?.coerce||!1,...je(t)});var gn=class t extends qe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ge.date){let s=this._getOrReturnCtx(e);return fe(s,{code:ie.invalid_type,expected:ge.date,received:s.parsedType}),$e}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return fe(s,{code:ie.invalid_date}),$e}let n=new Lt,a;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(a=this._getOrReturnCtx(e,a),fe(a,{code:ie.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):He.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:be.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:be.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew gn({checks:[],coerce:t?.coerce||!1,typeName:Pe.ZodDate,...je(t)});var Rs=class extends qe{_parse(e){if(this._getType(e)!==ge.symbol){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.symbol,received:n.parsedType}),$e}return Ut(e.data)}};Rs.create=t=>new Rs({typeName:Pe.ZodSymbol,...je(t)});var yn=class extends qe{_parse(e){if(this._getType(e)!==ge.undefined){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.undefined,received:n.parsedType}),$e}return Ut(e.data)}};yn.create=t=>new yn({typeName:Pe.ZodUndefined,...je(t)});var _n=class extends qe{_parse(e){if(this._getType(e)!==ge.null){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.null,received:n.parsedType}),$e}return Ut(e.data)}};_n.create=t=>new _n({typeName:Pe.ZodNull,...je(t)});var Aa=class extends qe{constructor(){super(...arguments),this._any=!0}_parse(e){return Ut(e.data)}};Aa.create=t=>new Aa({typeName:Pe.ZodAny,...je(t)});var fa=class extends qe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ut(e.data)}};fa.create=t=>new fa({typeName:Pe.ZodUnknown,...je(t)});var Mr=class extends qe{_parse(e){let r=this._getOrReturnCtx(e);return fe(r,{code:ie.invalid_type,expected:ge.never,received:r.parsedType}),$e}};Mr.create=t=>new Mr({typeName:Pe.ZodNever,...je(t)});var Ps=class extends qe{_parse(e){if(this._getType(e)!==ge.undefined){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.void,received:n.parsedType}),$e}return Ut(e.data)}};Ps.create=t=>new Ps({typeName:Pe.ZodVoid,...je(t)});var ma=class t extends qe{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),a=this._def;if(r.parsedType!==ge.array)return fe(r,{code:ie.invalid_type,expected:ge.array,received:r.parsedType}),$e;if(a.exactLength!==null){let i=r.data.length>a.exactLength.value,o=r.data.lengtha.maxLength.value&&(fe(r,{code:ie.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>a.type._parseAsync(new xr(r,i,r.path,o)))).then(i=>Lt.mergeArray(n,i));let s=[...r.data].map((i,o)=>a.type._parseSync(new xr(r,i,r.path,o)));return Lt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:be.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:be.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:be.toString(r)}})}nonempty(e){return this.min(1,e)}};ma.create=(t,e)=>new ma({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Pe.ZodArray,...je(e)});function $s(t){if(t instanceof tr){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=br.create($s(n))}return new tr({...t._def,shape:()=>e})}else return t instanceof ma?new ma({...t._def,type:$s(t.element)}):t instanceof br?br.create($s(t.unwrap())):t instanceof ea?ea.create($s(t.unwrap())):t instanceof Qr?Qr.create(t.items.map(e=>$s(e))):t}var tr=class t extends qe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=He.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ge.object){let u=this._getOrReturnCtx(e);return fe(u,{code:ie.invalid_type,expected:ge.object,received:u.parsedType}),$e}let{status:n,ctx:a}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Mr&&this._def.unknownKeys==="strip"))for(let u in a.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let l=s[u],d=a.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new xr(a,d,a.path,u)),alwaysSet:u in a.data})}if(this._def.catchall instanceof Mr){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:a.data[l]}});else if(u==="strict")o.length>0&&(fe(a,{code:ie.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of o){let d=a.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new xr(a,d,a.path,l)),alwaysSet:l in a.data})}}return a.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Lt.mergeObjectSync(n,u)):Lt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return be.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let a=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:be.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Pe.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of He.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of He.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return $s(this)}partial(e){let r={};for(let n of He.objectKeys(this.shape)){let a=this.shape[n];e&&!e[n]?r[n]=a:r[n]=a.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of He.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof br;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return gx(He.objectKeys(this.shape))}};tr.create=(t,e)=>new tr({shape:()=>t,unknownKeys:"strip",catchall:Mr.create(),typeName:Pe.ZodObject,...je(e)});tr.strictCreate=(t,e)=>new tr({shape:()=>t,unknownKeys:"strict",catchall:Mr.create(),typeName:Pe.ZodObject,...je(e)});tr.lazycreate=(t,e)=>new tr({shape:t,unknownKeys:"strip",catchall:Mr.create(),typeName:Pe.ZodObject,...je(e)});var bn=class extends qe{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function a(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let i=s.map(o=>new er(o.ctx.common.issues));return fe(r,{code:ie.invalid_union,unionErrors:i}),$e}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let o=i.map(c=>new er(c));return fe(r,{code:ie.invalid_union,unionErrors:o}),$e}}get options(){return this._def.options}};bn.create=(t,e)=>new bn({options:t,typeName:Pe.ZodUnion,...je(e)});var pa=t=>t instanceof wn?pa(t.schema):t instanceof wr?pa(t.innerType()):t instanceof Sn?[t.value]:t instanceof En?t.options:t instanceof Tn?He.objectValues(t.enum):t instanceof kn?pa(t._def.innerType):t instanceof yn?[void 0]:t instanceof _n?[null]:t instanceof br?[void 0,...pa(t.unwrap())]:t instanceof ea?[null,...pa(t.unwrap())]:t instanceof eo||t instanceof Rn?pa(t.unwrap()):t instanceof $n?pa(t._def.innerType):[],Yc=class t extends qe{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.object)return fe(r,{code:ie.invalid_type,expected:ge.object,received:r.parsedType}),$e;let n=this.discriminator,a=r.data[n],s=this.optionsMap.get(a);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(fe(r,{code:ie.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),$e)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let a=new Map;for(let s of r){let i=pa(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(a.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);a.set(o,s)}}return new t({typeName:Pe.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:a,...je(n)})}};function Xp(t,e){let r=Yr(t),n=Yr(e);if(t===e)return{valid:!0,data:t};if(r===ge.object&&n===ge.object){let a=He.objectKeys(e),s=He.objectKeys(t).filter(o=>a.indexOf(o)!==-1),i={...t,...e};for(let o of s){let c=Xp(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===ge.array&&n===ge.array){if(t.length!==e.length)return{valid:!1};let a=[];for(let s=0;s{if(Xc(s)||Xc(i))return $e;let o=Xp(s.value,i.value);return o.valid?((Jc(s)||Jc(i))&&r.dirty(),{status:r.value,value:o.data}):(fe(n,{code:ie.invalid_intersection_types}),$e)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>a(s,i)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};xn.create=(t,e,r)=>new xn({left:t,right:e,typeName:Pe.ZodIntersection,...je(r)});var Qr=class t extends qe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ge.array)return fe(n,{code:ie.invalid_type,expected:ge.array,received:n.parsedType}),$e;if(n.data.lengththis._def.items.length&&(fe(n,{code:ie.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new xr(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Lt.mergeArray(r,i)):Lt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Qr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qr({items:t,typeName:Pe.ZodTuple,rest:null,...je(e)})};var Qc=class t extends qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ge.object)return fe(n,{code:ie.invalid_type,expected:ge.object,received:n.parsedType}),$e;let a=[],s=this._def.keyType,i=this._def.valueType;for(let o in n.data)a.push({key:s._parse(new xr(n,o,n.path,o)),value:i._parse(new xr(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?Lt.mergeObjectAsync(r,a):Lt.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof qe?new t({keyType:e,valueType:r,typeName:Pe.ZodRecord,...je(n)}):new t({keyType:Ia.create(),valueType:e,typeName:Pe.ZodRecord,...je(r)})}},Os=class extends qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ge.map)return fe(n,{code:ie.invalid_type,expected:ge.map,received:n.parsedType}),$e;let a=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:a._parse(new xr(n,o,n.path,[u,"key"])),value:s._parse(new xr(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return $e;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return $e;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}}}};Os.create=(t,e,r)=>new Os({valueType:e,keyType:t,typeName:Pe.ZodMap,...je(r)});var Cs=class t extends qe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ge.set)return fe(n,{code:ie.invalid_type,expected:ge.set,received:n.parsedType}),$e;let a=this._def;a.minSize!==null&&n.data.sizea.maxSize.value&&(fe(n,{code:ie.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return $e;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let o=[...n.data.values()].map((c,u)=>s._parse(new xr(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new t({...this._def,minSize:{value:e,message:be.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:be.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Cs.create=(t,e)=>new Cs({valueType:t,minSize:null,maxSize:null,typeName:Pe.ZodSet,...je(e)});var eu=class t extends qe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.function)return fe(r,{code:ie.invalid_type,expected:ge.function,received:r.parsedType}),$e;function n(o,c){return Qi({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ts(),da].filter(u=>!!u),issueData:{code:ie.invalid_arguments,argumentsError:c}})}function a(o,c){return Qi({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ts(),da].filter(u=>!!u),issueData:{code:ie.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Na){let o=this;return Ut(async function(...c){let u=new er([]),l=await o._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(n(c,m)),u}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(a(d,m)),u})})}else{let o=this;return Ut(function(...c){let u=o._def.args.safeParse(c,s);if(!u.success)throw new er([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,s);if(!d.success)throw new er([a(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Qr.create(e).rest(fa.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Qr.create([]).rest(fa.create()),returns:r||fa.create(),typeName:Pe.ZodFunction,...je(n)})}},wn=class extends qe{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};wn.create=(t,e)=>new wn({getter:t,typeName:Pe.ZodLazy,...je(e)});var Sn=class extends qe{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return fe(r,{received:r.data,code:ie.invalid_literal,expected:this._def.value}),$e}return{status:"valid",value:e.data}}get value(){return this._def.value}};Sn.create=(t,e)=>new Sn({value:t,typeName:Pe.ZodLiteral,...je(e)});function gx(t,e){return new En({values:t,typeName:Pe.ZodEnum,...je(e)})}var En=class t extends qe{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return fe(r,{expected:He.joinValues(n),received:r.parsedType,code:ie.invalid_type}),$e}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return fe(r,{received:r.data,code:ie.invalid_enum_value,options:n}),$e}return Ut(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};En.create=gx;var Tn=class extends qe{_parse(e){let r=He.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ge.string&&n.parsedType!==ge.number){let a=He.objectValues(r);return fe(n,{expected:He.joinValues(a),received:n.parsedType,code:ie.invalid_type}),$e}if(this._cache||(this._cache=new Set(He.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let a=He.objectValues(r);return fe(n,{received:n.data,code:ie.invalid_enum_value,options:a}),$e}return Ut(e.data)}get enum(){return this._def.values}};Tn.create=(t,e)=>new Tn({values:t,typeName:Pe.ZodNativeEnum,...je(e)});var Na=class extends qe{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.promise&&r.common.async===!1)return fe(r,{code:ie.invalid_type,expected:ge.promise,received:r.parsedType}),$e;let n=r.parsedType===ge.promise?r.data:Promise.resolve(r.data);return Ut(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Na.create=(t,e)=>new Na({type:t,typeName:Pe.ZodPromise,...je(e)});var wr=class extends qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Pe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:i=>{fe(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),a.type==="preprocess"){let i=a.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return $e;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?$e:c.status==="dirty"?fn(c.value):r.value==="dirty"?fn(c.value):c});{if(r.value==="aborted")return $e;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?$e:o.status==="dirty"?fn(o.value):r.value==="dirty"?fn(o.value):o}}if(a.type==="refinement"){let i=o=>{let c=a.refinement(o,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?$e:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?$e:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ca(i))return $e;let o=a.transform(i.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Ca(i)?Promise.resolve(a.transform(i.value,s)).then(o=>({status:r.value,value:o})):$e);He.assertNever(a)}};wr.create=(t,e,r)=>new wr({schema:t,typeName:Pe.ZodEffects,effect:e,...je(r)});wr.createWithPreprocess=(t,e,r)=>new wr({schema:e,effect:{type:"preprocess",transform:t},typeName:Pe.ZodEffects,...je(r)});var br=class extends qe{_parse(e){return this._getType(e)===ge.undefined?Ut(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};br.create=(t,e)=>new br({innerType:t,typeName:Pe.ZodOptional,...je(e)});var ea=class extends qe{_parse(e){return this._getType(e)===ge.null?Ut(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ea.create=(t,e)=>new ea({innerType:t,typeName:Pe.ZodNullable,...je(e)});var kn=class extends qe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===ge.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};kn.create=(t,e)=>new kn({innerType:t,typeName:Pe.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...je(e)});var $n=class extends qe{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ks(a)?a.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new er(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new er(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};$n.create=(t,e)=>new $n({innerType:t,typeName:Pe.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...je(e)});var Is=class extends qe{_parse(e){if(this._getType(e)!==ge.nan){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.nan,received:n.parsedType}),$e}return{status:"valid",value:e.data}}};Is.create=t=>new Is({typeName:Pe.ZodNaN,...je(t)});var c2=Symbol("zod_brand"),eo=class extends qe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},to=class t extends qe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?$e:s.status==="dirty"?(r.dirty(),fn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?$e:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Pe.ZodPipeline})}},Rn=class extends qe{_parse(e){let r=this._def.innerType._parse(e),n=a=>(Ca(a)&&(a.value=Object.freeze(a.value)),a);return ks(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}};Rn.create=(t,e)=>new Rn({innerType:t,typeName:Pe.ZodReadonly,...je(e)});function fx(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function yx(t,e={},r){return t?Aa.create().superRefine((n,a)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let o=fx(e,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){let i=fx(e,n),o=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:o})}}):Aa.create()}var u2={object:tr.lazycreate},Pe;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Pe||(Pe={}));var l2=(t,e={message:`Input not instance of ${t.name}`})=>yx(r=>r instanceof t,e),_x=Ia.create,bx=mn.create,d2=Is.create,p2=hn.create,xx=vn.create,f2=gn.create,m2=Rs.create,h2=yn.create,v2=_n.create,g2=Aa.create,y2=fa.create,_2=Mr.create,b2=Ps.create,x2=ma.create,w2=tr.create,S2=tr.strictCreate,E2=bn.create,T2=Yc.create,k2=xn.create,$2=Qr.create,R2=Qc.create,P2=Os.create,O2=Cs.create,C2=eu.create,I2=wn.create,A2=Sn.create,N2=En.create,j2=Tn.create,M2=Na.create,D2=wr.create,q2=br.create,L2=ea.create,F2=wr.createWithPreprocess,z2=to.create,U2=()=>_x().optional(),H2=()=>bx().optional(),B2=()=>xx().optional(),V2={string:(t=>Ia.create({...t,coerce:!0})),number:(t=>mn.create({...t,coerce:!0})),boolean:(t=>vn.create({...t,coerce:!0})),bigint:(t=>hn.create({...t,coerce:!0})),date:(t=>gn.create({...t,coerce:!0}))};var Z2=$e;var Jp="2025-06-18";var wx=[Jp,"2025-03-26","2024-11-05","2024-10-07"],tu="2.0",Sx=P.union([P.string(),P.number().int()]),Ex=P.string(),G2=P.object({progressToken:P.optional(Sx)}).passthrough(),Tr=P.object({_meta:P.optional(G2)}).passthrough(),rr=P.object({method:P.string(),params:P.optional(Tr)}),ro=P.object({_meta:P.optional(P.object({}).passthrough())}).passthrough(),ta=P.object({method:P.string(),params:P.optional(ro)}),kr=P.object({_meta:P.optional(P.object({}).passthrough())}).passthrough(),ru=P.union([P.string(),P.number().int()]),Tx=P.object({jsonrpc:P.literal(tu),id:ru}).merge(rr).strict(),kx=t=>Tx.safeParse(t).success,$x=P.object({jsonrpc:P.literal(tu)}).merge(ta).strict(),Rx=t=>$x.safeParse(t).success,Px=P.object({jsonrpc:P.literal(tu),id:ru,result:kr}).strict(),Yp=t=>Px.safeParse(t).success,Sr;(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"})(Sr||(Sr={}));var Ox=P.object({jsonrpc:P.literal(tu),id:ru,error:P.object({code:P.number().int(),message:P.string(),data:P.optional(P.unknown())})}).strict(),Cx=t=>Ox.safeParse(t).success,Ix=P.union([Tx,$x,Px,Ox]),Pn=kr.strict(),au=ta.extend({method:P.literal("notifications/cancelled"),params:ro.extend({requestId:ru,reason:P.string().optional()})}),W2=P.object({src:P.string(),mimeType:P.optional(P.string()),sizes:P.optional(P.array(P.string()))}).passthrough(),ao=P.object({icons:P.array(W2).optional()}).passthrough(),no=P.object({name:P.string(),title:P.optional(P.string())}).passthrough(),Ax=no.extend({version:P.string(),websiteUrl:P.optional(P.string())}).merge(ao),K2=P.object({experimental:P.optional(P.object({}).passthrough()),sampling:P.optional(P.object({}).passthrough()),elicitation:P.optional(P.object({}).passthrough()),roots:P.optional(P.object({listChanged:P.optional(P.boolean())}).passthrough())}).passthrough(),X2=rr.extend({method:P.literal("initialize"),params:Tr.extend({protocolVersion:P.string(),capabilities:K2,clientInfo:Ax})});var J2=P.object({experimental:P.optional(P.object({}).passthrough()),logging:P.optional(P.object({}).passthrough()),completions:P.optional(P.object({}).passthrough()),prompts:P.optional(P.object({listChanged:P.optional(P.boolean())}).passthrough()),resources:P.optional(P.object({subscribe:P.optional(P.boolean()),listChanged:P.optional(P.boolean())}).passthrough()),tools:P.optional(P.object({listChanged:P.optional(P.boolean())}).passthrough())}).passthrough(),Qp=kr.extend({protocolVersion:P.string(),capabilities:J2,serverInfo:Ax,instructions:P.optional(P.string())}),Y2=ta.extend({method:P.literal("notifications/initialized")});var nu=rr.extend({method:P.literal("ping")}),Q2=P.object({progress:P.number(),total:P.optional(P.number()),message:P.optional(P.string())}).passthrough(),su=ta.extend({method:P.literal("notifications/progress"),params:ro.merge(Q2).extend({progressToken:Sx})}),iu=rr.extend({params:Tr.extend({cursor:P.optional(Ex)}).optional()}),ou=kr.extend({nextCursor:P.optional(Ex)}),Nx=P.object({uri:P.string(),mimeType:P.optional(P.string()),_meta:P.optional(P.object({}).passthrough())}).passthrough(),jx=Nx.extend({text:P.string()}),ef=P.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mx=Nx.extend({blob:ef}),Dx=no.extend({uri:P.string(),description:P.optional(P.string()),mimeType:P.optional(P.string()),_meta:P.optional(P.object({}).passthrough())}).merge(ao),eD=no.extend({uriTemplate:P.string(),description:P.optional(P.string()),mimeType:P.optional(P.string()),_meta:P.optional(P.object({}).passthrough())}).merge(ao),tD=iu.extend({method:P.literal("resources/list")}),tf=ou.extend({resources:P.array(Dx)}),rD=iu.extend({method:P.literal("resources/templates/list")}),rf=ou.extend({resourceTemplates:P.array(eD)}),aD=rr.extend({method:P.literal("resources/read"),params:Tr.extend({uri:P.string()})}),af=kr.extend({contents:P.array(P.union([jx,Mx]))}),nD=ta.extend({method:P.literal("notifications/resources/list_changed")}),sD=rr.extend({method:P.literal("resources/subscribe"),params:Tr.extend({uri:P.string()})}),iD=rr.extend({method:P.literal("resources/unsubscribe"),params:Tr.extend({uri:P.string()})}),oD=ta.extend({method:P.literal("notifications/resources/updated"),params:ro.extend({uri:P.string()})}),cD=P.object({name:P.string(),description:P.optional(P.string()),required:P.optional(P.boolean())}).passthrough(),uD=no.extend({description:P.optional(P.string()),arguments:P.optional(P.array(cD)),_meta:P.optional(P.object({}).passthrough())}).merge(ao),lD=iu.extend({method:P.literal("prompts/list")}),nf=ou.extend({prompts:P.array(uD)}),dD=rr.extend({method:P.literal("prompts/get"),params:Tr.extend({name:P.string(),arguments:P.optional(P.record(P.string()))})}),sf=P.object({type:P.literal("text"),text:P.string(),_meta:P.optional(P.object({}).passthrough())}).passthrough(),of=P.object({type:P.literal("image"),data:ef,mimeType:P.string(),_meta:P.optional(P.object({}).passthrough())}).passthrough(),cf=P.object({type:P.literal("audio"),data:ef,mimeType:P.string(),_meta:P.optional(P.object({}).passthrough())}).passthrough(),pD=P.object({type:P.literal("resource"),resource:P.union([jx,Mx]),_meta:P.optional(P.object({}).passthrough())}).passthrough(),fD=Dx.extend({type:P.literal("resource_link")}),qx=P.union([sf,of,cf,fD,pD]),mD=P.object({role:P.enum(["user","assistant"]),content:qx}).passthrough(),uf=kr.extend({description:P.optional(P.string()),messages:P.array(mD)}),hD=ta.extend({method:P.literal("notifications/prompts/list_changed")}),vD=P.object({title:P.optional(P.string()),readOnlyHint:P.optional(P.boolean()),destructiveHint:P.optional(P.boolean()),idempotentHint:P.optional(P.boolean()),openWorldHint:P.optional(P.boolean())}).passthrough(),gD=no.extend({description:P.optional(P.string()),inputSchema:P.object({type:P.literal("object"),properties:P.optional(P.object({}).passthrough()),required:P.optional(P.array(P.string()))}).passthrough(),outputSchema:P.optional(P.object({type:P.literal("object"),properties:P.optional(P.object({}).passthrough()),required:P.optional(P.array(P.string()))}).passthrough()),annotations:P.optional(vD),_meta:P.optional(P.object({}).passthrough())}).merge(ao),yD=iu.extend({method:P.literal("tools/list")}),lf=ou.extend({tools:P.array(gD)}),cu=kr.extend({content:P.array(qx).default([]),structuredContent:P.object({}).passthrough().optional(),isError:P.optional(P.boolean())}),WG=cu.or(kr.extend({toolResult:P.unknown()})),_D=rr.extend({method:P.literal("tools/call"),params:Tr.extend({name:P.string(),arguments:P.optional(P.record(P.unknown()))})}),bD=ta.extend({method:P.literal("notifications/tools/list_changed")}),Lx=P.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),xD=rr.extend({method:P.literal("logging/setLevel"),params:Tr.extend({level:Lx})}),wD=ta.extend({method:P.literal("notifications/message"),params:ro.extend({level:Lx,logger:P.optional(P.string()),data:P.unknown()})}),SD=P.object({name:P.string().optional()}).passthrough(),ED=P.object({hints:P.optional(P.array(SD)),costPriority:P.optional(P.number().min(0).max(1)),speedPriority:P.optional(P.number().min(0).max(1)),intelligencePriority:P.optional(P.number().min(0).max(1))}).passthrough(),TD=P.object({role:P.enum(["user","assistant"]),content:P.union([sf,of,cf])}).passthrough(),kD=rr.extend({method:P.literal("sampling/createMessage"),params:Tr.extend({messages:P.array(TD),systemPrompt:P.optional(P.string()),includeContext:P.optional(P.enum(["none","thisServer","allServers"])),temperature:P.optional(P.number()),maxTokens:P.number().int(),stopSequences:P.optional(P.array(P.string())),metadata:P.optional(P.object({}).passthrough()),modelPreferences:P.optional(ED)})}),$D=kr.extend({model:P.string(),stopReason:P.optional(P.enum(["endTurn","stopSequence","maxTokens"]).or(P.string())),role:P.enum(["user","assistant"]),content:P.discriminatedUnion("type",[sf,of,cf])}),RD=P.object({type:P.literal("boolean"),title:P.optional(P.string()),description:P.optional(P.string()),default:P.optional(P.boolean())}).passthrough(),PD=P.object({type:P.literal("string"),title:P.optional(P.string()),description:P.optional(P.string()),minLength:P.optional(P.number()),maxLength:P.optional(P.number()),format:P.optional(P.enum(["email","uri","date","date-time"]))}).passthrough(),OD=P.object({type:P.enum(["number","integer"]),title:P.optional(P.string()),description:P.optional(P.string()),minimum:P.optional(P.number()),maximum:P.optional(P.number())}).passthrough(),CD=P.object({type:P.literal("string"),title:P.optional(P.string()),description:P.optional(P.string()),enum:P.array(P.string()),enumNames:P.optional(P.array(P.string()))}).passthrough(),ID=P.union([RD,PD,OD,CD]),AD=rr.extend({method:P.literal("elicitation/create"),params:Tr.extend({message:P.string(),requestedSchema:P.object({type:P.literal("object"),properties:P.record(P.string(),ID),required:P.optional(P.array(P.string()))}).passthrough()})}),ND=kr.extend({action:P.enum(["accept","decline","cancel"]),content:P.optional(P.record(P.string(),P.unknown()))}),jD=P.object({type:P.literal("ref/resource"),uri:P.string()}).passthrough();var MD=P.object({type:P.literal("ref/prompt"),name:P.string()}).passthrough(),DD=rr.extend({method:P.literal("completion/complete"),params:Tr.extend({ref:P.union([MD,jD]),argument:P.object({name:P.string(),value:P.string()}).passthrough(),context:P.optional(P.object({arguments:P.optional(P.record(P.string(),P.string()))}))})}),df=kr.extend({completion:P.object({values:P.array(P.string()).max(100),total:P.optional(P.number().int()),hasMore:P.optional(P.boolean())}).passthrough()}),qD=P.object({uri:P.string().startsWith("file://"),name:P.optional(P.string()),_meta:P.optional(P.object({}).passthrough())}).passthrough(),LD=rr.extend({method:P.literal("roots/list")}),FD=kr.extend({roots:P.array(qD)}),zD=ta.extend({method:P.literal("notifications/roots/list_changed")}),KG=P.union([nu,X2,DD,xD,dD,lD,tD,rD,aD,sD,iD,_D,yD]),XG=P.union([au,su,Y2,zD]),JG=P.union([Pn,$D,ND,FD]),YG=P.union([nu,kD,AD,LD]),QG=P.union([au,su,wD,oD,nD,bD,hD]),eW=P.union([Pn,Qp,df,uf,nf,tf,rf,af,cu,lf]),Er=class extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}};var UD=6e4,uu=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.setNotificationHandler(au,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(su,r=>{this._onprogress(r)}),this.setRequestHandler(nu,r=>({}))}_setupTimeout(e,r,n,a,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:a})}_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),new Er(Sr.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){var r,n,a;this._transport=e;let s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};let i=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{i?.(c),this._onerror(c)};let o=(a=this._transport)===null||a===void 0?void 0:a.onmessage;this._transport.onmessage=(c,u)=>{o?.(c,u),Yp(c)||Cx(c)?this._onresponse(c):kx(c)?this._onrequest(c,u):Rx(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new Er(Sr.ConnectionClosed,"Connection closed");for(let a of r.values())a(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,r){var n,a;let s=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,i=this._transport;if(s===void 0){i?.send({jsonrpc:"2.0",id:e.id,error:{code:Sr.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let c={signal:o.signal,sessionId:i?.sessionId,_meta:(a=e.params)===null||a===void 0?void 0:a._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,l,d)=>this.request(u,l,{...d,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>s(e,c)).then(u=>{if(!o.signal.aborted)return i?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var l;if(!o.signal.aborted)return i?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Sr.InternalError,message:(l=u.message)!==null&&l!==void 0?l:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,a=Number(r),s=this._progressHandlers.get(a);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(a),o=this._timeoutInfo.get(a);if(o&&i&&o.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(c){i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Yp(e))n(e);else{let a=new Er(e.error.code,e.error.message,e.error.data);n(a)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}=n??{};return new Promise((o,c)=>{var u,l,d,f,m,g;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(l=n?.signal)===null||l===void 0||l.throwIfAborted();let b=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),p.params={...e.params,_meta:{...((d=e.params)===null||d===void 0?void 0:d._meta)||{},progressToken:b}});let h=_=>{var S;this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(_)}},{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`))),c(_)};this._responseHandlers.set(b,_=>{var S;if(!(!((S=n?.signal)===null||S===void 0)&&S.aborted)){if(_ instanceof Error)return c(_);try{let x=r.parse(_.result);o(x)}catch(x){c(x)}}}),(f=n?.signal)===null||f===void 0||f.addEventListener("abort",()=>{var _;h((_=n?.signal)===null||_===void 0?void 0:_.reason)});let y=(m=n?.timeout)!==null&&m!==void 0?m:UD,v=()=>h(new Er(Sr.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(b,y,n?.maxTotalTimeout,v,(g=n?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(p,{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(b),c(_)})})}async notification(e,r){var n,a;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((a=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&a!==void 0?a:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,r).catch(l=>this._onerror(l))});return}let o={...e,jsonrpc:"2.0"};await this._transport.send(o,r)}setRequestHandler(e,r){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,s)=>Promise.resolve(r(e.parse(a),s)))}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){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(r(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Fx(t,e){return Object.entries(e).reduce((r,[n,a])=>(a&&typeof a=="object"?r[n]=r[n]?{...r[n],...a}:a:r[n]=a,r),{...t})}var US=kt(zS(),1),As=class extends uu{constructor(e,r){var n;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._ajv=new US.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fx(this._capabilities,e)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Jp,capabilities:this._capabilities,clientInfo:this._clientInfo}},Qp,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!wx.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,a,s,i;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},Pn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},df,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Pn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},uf,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},nf,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},tf,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},rf,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},af,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Pn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Pn,r)}async callTool(e,r=cu,n){let a=await this.request({method:"tools/call",params:e},r,n),s=this.getToolOutputValidator(e.name);if(s){if(!a.structuredContent&&!a.isError)throw new Er(Sr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(a.structuredContent)try{if(!s(a.structuredContent))throw new Er(Sr.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(i){throw i instanceof Er?i:new Er(Sr.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return a}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let r of e)if(r.outputSchema)try{let n=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},lf,r);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var IE=kt(OE(),1),io=kt(require("node:process"),1),AE=require("node:stream");var Pu=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` +`).trimEnd()}var Ml,Dl,di,I7,c$,N7,pe,Ll=ca(()=>{"use strict";Ml=$t(require("path"),1),Dl=require("os"),di=require("fs");Iu();mt();Dr();Bm();o$();La();I7=Ml.default.join((0,Dl.homedir)(),".claude","plugins","marketplaces","thedotmack","plugin",".install-version");c$=4,N7=1,pe={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",cyan:"\x1B[36m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",gray:"\x1B[90m",red:"\x1B[31m"}});var L7={};Jn(L7,{WorkerService:()=>Hl});module.exports=L$(L7);var f$=$t(Kc(),1),pi=$t(require("path"),1),Qm=$t(require("fs"),1);var P={};Jn(P,{BRAND:()=>c2,DIRTY:()=>fn,EMPTY_PATH:()=>FM,INVALID:()=>$e,NEVER:()=>Z2,OK:()=>Ut,ParseStatus:()=>Lt,Schema:()=>qe,ZodAny:()=>Aa,ZodArray:()=>ma,ZodBigInt:()=>hn,ZodBoolean:()=>vn,ZodBranded:()=>eo,ZodCatch:()=>$n,ZodDate:()=>gn,ZodDefault:()=>kn,ZodDiscriminatedUnion:()=>Yc,ZodEffects:()=>wr,ZodEnum:()=>En,ZodError:()=>er,ZodFirstPartyTypeKind:()=>Pe,ZodFunction:()=>eu,ZodIntersection:()=>xn,ZodIssueCode:()=>ie,ZodLazy:()=>wn,ZodLiteral:()=>Sn,ZodMap:()=>Os,ZodNaN:()=>Is,ZodNativeEnum:()=>Tn,ZodNever:()=>Mr,ZodNull:()=>_n,ZodNullable:()=>ea,ZodNumber:()=>mn,ZodObject:()=>tr,ZodOptional:()=>br,ZodParsedType:()=>ge,ZodPipeline:()=>to,ZodPromise:()=>Na,ZodReadonly:()=>Rn,ZodRecord:()=>Qc,ZodSchema:()=>qe,ZodSet:()=>Cs,ZodString:()=>Ia,ZodSymbol:()=>Rs,ZodTransformer:()=>wr,ZodTuple:()=>Qr,ZodType:()=>qe,ZodUndefined:()=>yn,ZodUnion:()=>bn,ZodUnknown:()=>fa,ZodVoid:()=>Ps,addIssueToContext:()=>fe,any:()=>g2,array:()=>x2,bigint:()=>p2,boolean:()=>xx,coerce:()=>V2,custom:()=>yx,date:()=>f2,datetimeRegex:()=>vx,defaultErrorMap:()=>da,discriminatedUnion:()=>T2,effect:()=>D2,enum:()=>N2,function:()=>C2,getErrorMap:()=>Ts,getParsedType:()=>Yr,instanceof:()=>l2,intersection:()=>k2,isAborted:()=>Xc,isAsync:()=>ks,isDirty:()=>Jc,isValid:()=>Ca,late:()=>u2,lazy:()=>I2,literal:()=>A2,makeIssue:()=>Qi,map:()=>P2,nan:()=>d2,nativeEnum:()=>j2,never:()=>_2,null:()=>v2,nullable:()=>L2,number:()=>bx,object:()=>w2,objectUtil:()=>Wp,oboolean:()=>B2,onumber:()=>H2,optional:()=>q2,ostring:()=>U2,pipeline:()=>z2,preprocess:()=>F2,promise:()=>M2,quotelessJson:()=>DM,record:()=>R2,set:()=>O2,setErrorMap:()=>LM,strictObject:()=>S2,string:()=>_x,symbol:()=>m2,transformer:()=>D2,tuple:()=>$2,undefined:()=>h2,union:()=>E2,unknown:()=>y2,util:()=>He,void:()=>b2});var He;(function(t){t.assertEqual=a=>{};function e(a){}t.assertIs=e;function r(a){throw new Error}t.assertNever=r,t.arrayToEnum=a=>{let s={};for(let i of a)s[i]=i;return s},t.getValidEnumValues=a=>{let s=t.objectKeys(a).filter(o=>typeof a[a[o]]!="number"),i={};for(let o of s)i[o]=a[o];return t.objectValues(i)},t.objectValues=a=>t.objectKeys(a).map(function(s){return a[s]}),t.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let s=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&s.push(i);return s},t.find=(a,s)=>{for(let i of a)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,s=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(a,s)=>typeof s=="bigint"?s.toString():s})(He||(He={}));var Wp;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Wp||(Wp={}));var ge=He.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Yr=t=>{switch(typeof t){case"undefined":return ge.undefined;case"string":return ge.string;case"number":return Number.isNaN(t)?ge.nan:ge.number;case"boolean":return ge.boolean;case"function":return ge.function;case"bigint":return ge.bigint;case"symbol":return ge.symbol;case"object":return Array.isArray(t)?ge.array:t===null?ge.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ge.promise:typeof Map<"u"&&t instanceof Map?ge.map:typeof Set<"u"&&t instanceof Set?ge.set:typeof Date<"u"&&t instanceof Date?ge.date:ge.object;default:return ge.unknown}};var ie=He.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),DM=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),er=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},a=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;cr.message){let r={},n=[];for(let a of this.issues)if(a.path.length>0){let s=a.path[0];r[s]=r[s]||[],r[s].push(e(a))}else n.push(e(a));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};er.create=t=>new er(t);var qM=(t,e)=>{let r;switch(t.code){case ie.invalid_type:t.received===ge.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case ie.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,He.jsonStringifyReplacer)}`;break;case ie.unrecognized_keys:r=`Unrecognized key(s) in object: ${He.joinValues(t.keys,", ")}`;break;case ie.invalid_union:r="Invalid input";break;case ie.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${He.joinValues(t.options)}`;break;case ie.invalid_enum_value:r=`Invalid enum value. Expected ${He.joinValues(t.options)}, received '${t.received}'`;break;case ie.invalid_arguments:r="Invalid function arguments";break;case ie.invalid_return_type:r="Invalid function return type";break;case ie.invalid_date:r="Invalid date";break;case ie.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:He.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case ie.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case ie.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case ie.custom:r="Invalid input";break;case ie.invalid_intersection_types:r="Intersection results could not be merged";break;case ie.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case ie.not_finite:r="Number must be finite";break;default:r=e.defaultError,He.assertNever(t)}return{message:r}},da=qM;var dx=da;function LM(t){dx=t}function Ts(){return dx}var Qi=t=>{let{data:e,path:r,errorMaps:n,issueData:a}=t,s=[...r,...a.path||[]],i={...a,path:s};if(a.message!==void 0)return{...a,path:s,message:a.message};let o="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:e,defaultError:o}).message;return{...a,path:s,message:o}},FM=[];function fe(t,e){let r=Ts(),n=Qi({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===da?void 0:da].filter(a=>!!a)});t.common.issues.push(n)}var Lt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let a of r){if(a.status==="aborted")return $e;a.status==="dirty"&&e.dirty(),n.push(a.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let a of r){let s=await a.key,i=await a.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let a of r){let{key:s,value:i}=a;if(s.status==="aborted"||i.status==="aborted")return $e;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},$e=Object.freeze({status:"aborted"}),fn=t=>({status:"dirty",value:t}),Ut=t=>({status:"valid",value:t}),Xc=t=>t.status==="aborted",Jc=t=>t.status==="dirty",Ca=t=>t.status==="valid",ks=t=>typeof Promise<"u"&&t instanceof Promise;var be;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(be||(be={}));var xr=class{constructor(e,r,n,a){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},px=(t,e)=>{if(Ca(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new er(t.common.issues);return this._error=r,this._error}}};function je(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:a}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(i,o)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:a}}var qe=class{get description(){return this._def.description}_getType(e){return Yr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Lt,ctx:{common:e.parent.common,data:e.data,parsedType:Yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ks(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Yr(e)},a=this._parseSync({data:e,path:n.path,parent:n});return px(n,a)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Yr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Ca(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Ca(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Yr(e)},a=this._parse({data:e,path:n.path,parent:n}),s=await(ks(a)?a:Promise.resolve(a));return px(n,s)}refine(e,r){let n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,s)=>{let i=e(a),o=()=>s.addIssue({code:ie.custom,...n(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,a)=>e(n)?!0:(a.addIssue(typeof r=="function"?r(n,a):r),!1))}_refinement(e){return new wr({schema:this,typeName:Pe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return br.create(this,this._def)}nullable(){return ea.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ma.create(this)}promise(){return Na.create(this,this._def)}or(e){return bn.create([this,e],this._def)}and(e){return xn.create(this,e,this._def)}transform(e){return new wr({...je(this._def),schema:this,typeName:Pe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new kn({...je(this._def),innerType:this,defaultValue:r,typeName:Pe.ZodDefault})}brand(){return new eo({typeName:Pe.ZodBranded,type:this,...je(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new $n({...je(this._def),innerType:this,catchValue:r,typeName:Pe.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return to.create(this,e)}readonly(){return Rn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zM=/^c[^\s-]{8,}$/i,UM=/^[0-9a-z]+$/,HM=/^[0-9A-HJKMNP-TV-Z]{26}$/i,BM=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,VM=/^[a-z0-9_-]{21}$/i,ZM=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,GM=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,WM=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,KM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Kp,XM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,JM=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,YM=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,QM=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,e2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,t2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mx="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",r2=new RegExp(`^${mx}$`);function hx(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function a2(t){return new RegExp(`^${hx(t)}$`)}function vx(t){let e=`${mx}T${hx(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function n2(t,e){return!!((e==="v4"||!e)&&XM.test(t)||(e==="v6"||!e)&&YM.test(t))}function s2(t,e){if(!ZM.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function i2(t,e){return!!((e==="v4"||!e)&&JM.test(t)||(e==="v6"||!e)&&QM.test(t))}var Ia=class t extends qe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ge.string){let s=this._getOrReturnCtx(e);return fe(s,{code:ie.invalid_type,expected:ge.string,received:s.parsedType}),$e}let n=new Lt,a;for(let s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(a=this._getOrReturnCtx(e,a),fe(a,{code:ie.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,o=e.data.lengthe.test(a),{validation:r,code:ie.invalid_string,...be.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...be.errToObj(e)})}url(e){return this._addCheck({kind:"url",...be.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...be.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...be.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...be.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...be.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...be.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...be.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...be.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...be.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...be.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...be.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...be.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...be.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...be.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...be.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...be.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...be.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...be.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...be.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...be.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...be.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...be.errToObj(r)})}nonempty(e){return this.min(1,be.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Ia({checks:[],typeName:Pe.ZodString,coerce:t?.coerce??!1,...je(t)});function o2(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,a=r>n?r:n,s=Number.parseInt(t.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return s%i/10**a}var mn=class t extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ge.number){let s=this._getOrReturnCtx(e);return fe(s,{code:ie.invalid_type,expected:ge.number,received:s.parsedType}),$e}let n,a=new Lt;for(let s of this._def.checks)s.kind==="int"?He.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.invalid_type,expected:"integer",received:"float",message:s.message}),a.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),a.dirty()):s.kind==="multipleOf"?o2(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.not_finite,message:s.message}),a.dirty()):He.assertNever(s);return{status:a.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,be.toString(r))}gt(e,r){return this.setLimit("min",e,!1,be.toString(r))}lte(e,r){return this.setLimit("max",e,!0,be.toString(r))}lt(e,r){return this.setLimit("max",e,!1,be.toString(r))}setLimit(e,r,n,a){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:be.toString(a)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:be.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:be.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:be.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:be.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:be.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:be.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:be.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:be.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:be.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&He.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.valuenew mn({checks:[],typeName:Pe.ZodNumber,coerce:t?.coerce||!1,...je(t)});var hn=class t extends qe{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==ge.bigint)return this._getInvalidInput(e);let n,a=new Lt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),a.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),fe(n,{code:ie.not_multiple_of,multipleOf:s.value,message:s.message}),a.dirty()):He.assertNever(s);return{status:a.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return fe(r,{code:ie.invalid_type,expected:ge.bigint,received:r.parsedType}),$e}gte(e,r){return this.setLimit("min",e,!0,be.toString(r))}gt(e,r){return this.setLimit("min",e,!1,be.toString(r))}lte(e,r){return this.setLimit("max",e,!0,be.toString(r))}lt(e,r){return this.setLimit("max",e,!1,be.toString(r))}setLimit(e,r,n,a){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:be.toString(a)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:be.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:be.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:be.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:be.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:be.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew hn({checks:[],typeName:Pe.ZodBigInt,coerce:t?.coerce??!1,...je(t)});var vn=class extends qe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ge.boolean){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.boolean,received:n.parsedType}),$e}return Ut(e.data)}};vn.create=t=>new vn({typeName:Pe.ZodBoolean,coerce:t?.coerce||!1,...je(t)});var gn=class t extends qe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ge.date){let s=this._getOrReturnCtx(e);return fe(s,{code:ie.invalid_type,expected:ge.date,received:s.parsedType}),$e}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return fe(s,{code:ie.invalid_date}),$e}let n=new Lt,a;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(a=this._getOrReturnCtx(e,a),fe(a,{code:ie.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):He.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:be.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:be.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew gn({checks:[],coerce:t?.coerce||!1,typeName:Pe.ZodDate,...je(t)});var Rs=class extends qe{_parse(e){if(this._getType(e)!==ge.symbol){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.symbol,received:n.parsedType}),$e}return Ut(e.data)}};Rs.create=t=>new Rs({typeName:Pe.ZodSymbol,...je(t)});var yn=class extends qe{_parse(e){if(this._getType(e)!==ge.undefined){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.undefined,received:n.parsedType}),$e}return Ut(e.data)}};yn.create=t=>new yn({typeName:Pe.ZodUndefined,...je(t)});var _n=class extends qe{_parse(e){if(this._getType(e)!==ge.null){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.null,received:n.parsedType}),$e}return Ut(e.data)}};_n.create=t=>new _n({typeName:Pe.ZodNull,...je(t)});var Aa=class extends qe{constructor(){super(...arguments),this._any=!0}_parse(e){return Ut(e.data)}};Aa.create=t=>new Aa({typeName:Pe.ZodAny,...je(t)});var fa=class extends qe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ut(e.data)}};fa.create=t=>new fa({typeName:Pe.ZodUnknown,...je(t)});var Mr=class extends qe{_parse(e){let r=this._getOrReturnCtx(e);return fe(r,{code:ie.invalid_type,expected:ge.never,received:r.parsedType}),$e}};Mr.create=t=>new Mr({typeName:Pe.ZodNever,...je(t)});var Ps=class extends qe{_parse(e){if(this._getType(e)!==ge.undefined){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.void,received:n.parsedType}),$e}return Ut(e.data)}};Ps.create=t=>new Ps({typeName:Pe.ZodVoid,...je(t)});var ma=class t extends qe{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),a=this._def;if(r.parsedType!==ge.array)return fe(r,{code:ie.invalid_type,expected:ge.array,received:r.parsedType}),$e;if(a.exactLength!==null){let i=r.data.length>a.exactLength.value,o=r.data.lengtha.maxLength.value&&(fe(r,{code:ie.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>a.type._parseAsync(new xr(r,i,r.path,o)))).then(i=>Lt.mergeArray(n,i));let s=[...r.data].map((i,o)=>a.type._parseSync(new xr(r,i,r.path,o)));return Lt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:be.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:be.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:be.toString(r)}})}nonempty(e){return this.min(1,e)}};ma.create=(t,e)=>new ma({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Pe.ZodArray,...je(e)});function $s(t){if(t instanceof tr){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=br.create($s(n))}return new tr({...t._def,shape:()=>e})}else return t instanceof ma?new ma({...t._def,type:$s(t.element)}):t instanceof br?br.create($s(t.unwrap())):t instanceof ea?ea.create($s(t.unwrap())):t instanceof Qr?Qr.create(t.items.map(e=>$s(e))):t}var tr=class t extends qe{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=He.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==ge.object){let u=this._getOrReturnCtx(e);return fe(u,{code:ie.invalid_type,expected:ge.object,received:u.parsedType}),$e}let{status:n,ctx:a}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof Mr&&this._def.unknownKeys==="strip"))for(let u in a.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let l=s[u],d=a.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new xr(a,d,a.path,u)),alwaysSet:u in a.data})}if(this._def.catchall instanceof Mr){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:a.data[l]}});else if(u==="strict")o.length>0&&(fe(a,{code:ie.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of o){let d=a.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new xr(a,d,a.path,l)),alwaysSet:l in a.data})}}return a.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Lt.mergeObjectSync(n,u)):Lt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return be.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let a=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:be.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Pe.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of He.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of He.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return $s(this)}partial(e){let r={};for(let n of He.objectKeys(this.shape)){let a=this.shape[n];e&&!e[n]?r[n]=a:r[n]=a.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of He.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof br;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return gx(He.objectKeys(this.shape))}};tr.create=(t,e)=>new tr({shape:()=>t,unknownKeys:"strip",catchall:Mr.create(),typeName:Pe.ZodObject,...je(e)});tr.strictCreate=(t,e)=>new tr({shape:()=>t,unknownKeys:"strict",catchall:Mr.create(),typeName:Pe.ZodObject,...je(e)});tr.lazycreate=(t,e)=>new tr({shape:t,unknownKeys:"strip",catchall:Mr.create(),typeName:Pe.ZodObject,...je(e)});var bn=class extends qe{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function a(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let i=s.map(o=>new er(o.ctx.common.issues));return fe(r,{code:ie.invalid_union,unionErrors:i}),$e}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let o=i.map(c=>new er(c));return fe(r,{code:ie.invalid_union,unionErrors:o}),$e}}get options(){return this._def.options}};bn.create=(t,e)=>new bn({options:t,typeName:Pe.ZodUnion,...je(e)});var pa=t=>t instanceof wn?pa(t.schema):t instanceof wr?pa(t.innerType()):t instanceof Sn?[t.value]:t instanceof En?t.options:t instanceof Tn?He.objectValues(t.enum):t instanceof kn?pa(t._def.innerType):t instanceof yn?[void 0]:t instanceof _n?[null]:t instanceof br?[void 0,...pa(t.unwrap())]:t instanceof ea?[null,...pa(t.unwrap())]:t instanceof eo||t instanceof Rn?pa(t.unwrap()):t instanceof $n?pa(t._def.innerType):[],Yc=class t extends qe{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.object)return fe(r,{code:ie.invalid_type,expected:ge.object,received:r.parsedType}),$e;let n=this.discriminator,a=r.data[n],s=this.optionsMap.get(a);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(fe(r,{code:ie.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),$e)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let a=new Map;for(let s of r){let i=pa(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(a.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);a.set(o,s)}}return new t({typeName:Pe.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:a,...je(n)})}};function Xp(t,e){let r=Yr(t),n=Yr(e);if(t===e)return{valid:!0,data:t};if(r===ge.object&&n===ge.object){let a=He.objectKeys(e),s=He.objectKeys(t).filter(o=>a.indexOf(o)!==-1),i={...t,...e};for(let o of s){let c=Xp(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===ge.array&&n===ge.array){if(t.length!==e.length)return{valid:!1};let a=[];for(let s=0;s{if(Xc(s)||Xc(i))return $e;let o=Xp(s.value,i.value);return o.valid?((Jc(s)||Jc(i))&&r.dirty(),{status:r.value,value:o.data}):(fe(n,{code:ie.invalid_intersection_types}),$e)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>a(s,i)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};xn.create=(t,e,r)=>new xn({left:t,right:e,typeName:Pe.ZodIntersection,...je(r)});var Qr=class t extends qe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ge.array)return fe(n,{code:ie.invalid_type,expected:ge.array,received:n.parsedType}),$e;if(n.data.lengththis._def.items.length&&(fe(n,{code:ie.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new xr(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Lt.mergeArray(r,i)):Lt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Qr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qr({items:t,typeName:Pe.ZodTuple,rest:null,...je(e)})};var Qc=class t extends qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ge.object)return fe(n,{code:ie.invalid_type,expected:ge.object,received:n.parsedType}),$e;let a=[],s=this._def.keyType,i=this._def.valueType;for(let o in n.data)a.push({key:s._parse(new xr(n,o,n.path,o)),value:i._parse(new xr(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?Lt.mergeObjectAsync(r,a):Lt.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof qe?new t({keyType:e,valueType:r,typeName:Pe.ZodRecord,...je(n)}):new t({keyType:Ia.create(),valueType:e,typeName:Pe.ZodRecord,...je(r)})}},Os=class extends qe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ge.map)return fe(n,{code:ie.invalid_type,expected:ge.map,received:n.parsedType}),$e;let a=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:a._parse(new xr(n,o,n.path,[u,"key"])),value:s._parse(new xr(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return $e;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return $e;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),o.set(u.value,l.value)}return{status:r.value,value:o}}}};Os.create=(t,e,r)=>new Os({valueType:e,keyType:t,typeName:Pe.ZodMap,...je(r)});var Cs=class t extends qe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ge.set)return fe(n,{code:ie.invalid_type,expected:ge.set,received:n.parsedType}),$e;let a=this._def;a.minSize!==null&&n.data.sizea.maxSize.value&&(fe(n,{code:ie.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return $e;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let o=[...n.data.values()].map((c,u)=>s._parse(new xr(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new t({...this._def,minSize:{value:e,message:be.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:be.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Cs.create=(t,e)=>new Cs({valueType:t,minSize:null,maxSize:null,typeName:Pe.ZodSet,...je(e)});var eu=class t extends qe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.function)return fe(r,{code:ie.invalid_type,expected:ge.function,received:r.parsedType}),$e;function n(o,c){return Qi({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ts(),da].filter(u=>!!u),issueData:{code:ie.invalid_arguments,argumentsError:c}})}function a(o,c){return Qi({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ts(),da].filter(u=>!!u),issueData:{code:ie.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Na){let o=this;return Ut(async function(...c){let u=new er([]),l=await o._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(n(c,m)),u}),d=await Reflect.apply(i,this,l);return await o._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(a(d,m)),u})})}else{let o=this;return Ut(function(...c){let u=o._def.args.safeParse(c,s);if(!u.success)throw new er([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=o._def.returns.safeParse(l,s);if(!d.success)throw new er([a(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Qr.create(e).rest(fa.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||Qr.create([]).rest(fa.create()),returns:r||fa.create(),typeName:Pe.ZodFunction,...je(n)})}},wn=class extends qe{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};wn.create=(t,e)=>new wn({getter:t,typeName:Pe.ZodLazy,...je(e)});var Sn=class extends qe{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return fe(r,{received:r.data,code:ie.invalid_literal,expected:this._def.value}),$e}return{status:"valid",value:e.data}}get value(){return this._def.value}};Sn.create=(t,e)=>new Sn({value:t,typeName:Pe.ZodLiteral,...je(e)});function gx(t,e){return new En({values:t,typeName:Pe.ZodEnum,...je(e)})}var En=class t extends qe{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return fe(r,{expected:He.joinValues(n),received:r.parsedType,code:ie.invalid_type}),$e}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return fe(r,{received:r.data,code:ie.invalid_enum_value,options:n}),$e}return Ut(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};En.create=gx;var Tn=class extends qe{_parse(e){let r=He.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ge.string&&n.parsedType!==ge.number){let a=He.objectValues(r);return fe(n,{expected:He.joinValues(a),received:n.parsedType,code:ie.invalid_type}),$e}if(this._cache||(this._cache=new Set(He.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let a=He.objectValues(r);return fe(n,{received:n.data,code:ie.invalid_enum_value,options:a}),$e}return Ut(e.data)}get enum(){return this._def.values}};Tn.create=(t,e)=>new Tn({values:t,typeName:Pe.ZodNativeEnum,...je(e)});var Na=class extends qe{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==ge.promise&&r.common.async===!1)return fe(r,{code:ie.invalid_type,expected:ge.promise,received:r.parsedType}),$e;let n=r.parsedType===ge.promise?r.data:Promise.resolve(r.data);return Ut(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Na.create=(t,e)=>new Na({type:t,typeName:Pe.ZodPromise,...je(e)});var wr=class extends qe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Pe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),a=this._def.effect||null,s={addIssue:i=>{fe(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),a.type==="preprocess"){let i=a.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return $e;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?$e:c.status==="dirty"?fn(c.value):r.value==="dirty"?fn(c.value):c});{if(r.value==="aborted")return $e;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?$e:o.status==="dirty"?fn(o.value):r.value==="dirty"?fn(o.value):o}}if(a.type==="refinement"){let i=o=>{let c=a.refinement(o,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?$e:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?$e:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(a.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ca(i))return $e;let o=a.transform(i.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Ca(i)?Promise.resolve(a.transform(i.value,s)).then(o=>({status:r.value,value:o})):$e);He.assertNever(a)}};wr.create=(t,e,r)=>new wr({schema:t,typeName:Pe.ZodEffects,effect:e,...je(r)});wr.createWithPreprocess=(t,e,r)=>new wr({schema:e,effect:{type:"preprocess",transform:t},typeName:Pe.ZodEffects,...je(r)});var br=class extends qe{_parse(e){return this._getType(e)===ge.undefined?Ut(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};br.create=(t,e)=>new br({innerType:t,typeName:Pe.ZodOptional,...je(e)});var ea=class extends qe{_parse(e){return this._getType(e)===ge.null?Ut(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ea.create=(t,e)=>new ea({innerType:t,typeName:Pe.ZodNullable,...je(e)});var kn=class extends qe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===ge.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};kn.create=(t,e)=>new kn({innerType:t,typeName:Pe.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...je(e)});var $n=class extends qe{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ks(a)?a.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new er(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new er(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};$n.create=(t,e)=>new $n({innerType:t,typeName:Pe.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...je(e)});var Is=class extends qe{_parse(e){if(this._getType(e)!==ge.nan){let n=this._getOrReturnCtx(e);return fe(n,{code:ie.invalid_type,expected:ge.nan,received:n.parsedType}),$e}return{status:"valid",value:e.data}}};Is.create=t=>new Is({typeName:Pe.ZodNaN,...je(t)});var c2=Symbol("zod_brand"),eo=class extends qe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},to=class t extends qe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?$e:s.status==="dirty"?(r.dirty(),fn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?$e:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:Pe.ZodPipeline})}},Rn=class extends qe{_parse(e){let r=this._def.innerType._parse(e),n=a=>(Ca(a)&&(a.value=Object.freeze(a.value)),a);return ks(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}};Rn.create=(t,e)=>new Rn({innerType:t,typeName:Pe.ZodReadonly,...je(e)});function fx(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function yx(t,e={},r){return t?Aa.create().superRefine((n,a)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let o=fx(e,n),c=o.fatal??r??!0;a.addIssue({code:"custom",...o,fatal:c})}});if(!s){let i=fx(e,n),o=i.fatal??r??!0;a.addIssue({code:"custom",...i,fatal:o})}}):Aa.create()}var u2={object:tr.lazycreate},Pe;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Pe||(Pe={}));var l2=(t,e={message:`Input not instance of ${t.name}`})=>yx(r=>r instanceof t,e),_x=Ia.create,bx=mn.create,d2=Is.create,p2=hn.create,xx=vn.create,f2=gn.create,m2=Rs.create,h2=yn.create,v2=_n.create,g2=Aa.create,y2=fa.create,_2=Mr.create,b2=Ps.create,x2=ma.create,w2=tr.create,S2=tr.strictCreate,E2=bn.create,T2=Yc.create,k2=xn.create,$2=Qr.create,R2=Qc.create,P2=Os.create,O2=Cs.create,C2=eu.create,I2=wn.create,A2=Sn.create,N2=En.create,j2=Tn.create,M2=Na.create,D2=wr.create,q2=br.create,L2=ea.create,F2=wr.createWithPreprocess,z2=to.create,U2=()=>_x().optional(),H2=()=>bx().optional(),B2=()=>xx().optional(),V2={string:(t=>Ia.create({...t,coerce:!0})),number:(t=>mn.create({...t,coerce:!0})),boolean:(t=>vn.create({...t,coerce:!0})),bigint:(t=>hn.create({...t,coerce:!0})),date:(t=>gn.create({...t,coerce:!0}))};var Z2=$e;var Jp="2025-06-18";var wx=[Jp,"2025-03-26","2024-11-05","2024-10-07"],tu="2.0",Sx=P.union([P.string(),P.number().int()]),Ex=P.string(),G2=P.object({progressToken:P.optional(Sx)}).passthrough(),Tr=P.object({_meta:P.optional(G2)}).passthrough(),rr=P.object({method:P.string(),params:P.optional(Tr)}),ro=P.object({_meta:P.optional(P.object({}).passthrough())}).passthrough(),ta=P.object({method:P.string(),params:P.optional(ro)}),kr=P.object({_meta:P.optional(P.object({}).passthrough())}).passthrough(),ru=P.union([P.string(),P.number().int()]),Tx=P.object({jsonrpc:P.literal(tu),id:ru}).merge(rr).strict(),kx=t=>Tx.safeParse(t).success,$x=P.object({jsonrpc:P.literal(tu)}).merge(ta).strict(),Rx=t=>$x.safeParse(t).success,Px=P.object({jsonrpc:P.literal(tu),id:ru,result:kr}).strict(),Yp=t=>Px.safeParse(t).success,Sr;(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"})(Sr||(Sr={}));var Ox=P.object({jsonrpc:P.literal(tu),id:ru,error:P.object({code:P.number().int(),message:P.string(),data:P.optional(P.unknown())})}).strict(),Cx=t=>Ox.safeParse(t).success,Ix=P.union([Tx,$x,Px,Ox]),Pn=kr.strict(),au=ta.extend({method:P.literal("notifications/cancelled"),params:ro.extend({requestId:ru,reason:P.string().optional()})}),W2=P.object({src:P.string(),mimeType:P.optional(P.string()),sizes:P.optional(P.array(P.string()))}).passthrough(),ao=P.object({icons:P.array(W2).optional()}).passthrough(),no=P.object({name:P.string(),title:P.optional(P.string())}).passthrough(),Ax=no.extend({version:P.string(),websiteUrl:P.optional(P.string())}).merge(ao),K2=P.object({experimental:P.optional(P.object({}).passthrough()),sampling:P.optional(P.object({}).passthrough()),elicitation:P.optional(P.object({}).passthrough()),roots:P.optional(P.object({listChanged:P.optional(P.boolean())}).passthrough())}).passthrough(),X2=rr.extend({method:P.literal("initialize"),params:Tr.extend({protocolVersion:P.string(),capabilities:K2,clientInfo:Ax})});var J2=P.object({experimental:P.optional(P.object({}).passthrough()),logging:P.optional(P.object({}).passthrough()),completions:P.optional(P.object({}).passthrough()),prompts:P.optional(P.object({listChanged:P.optional(P.boolean())}).passthrough()),resources:P.optional(P.object({subscribe:P.optional(P.boolean()),listChanged:P.optional(P.boolean())}).passthrough()),tools:P.optional(P.object({listChanged:P.optional(P.boolean())}).passthrough())}).passthrough(),Qp=kr.extend({protocolVersion:P.string(),capabilities:J2,serverInfo:Ax,instructions:P.optional(P.string())}),Y2=ta.extend({method:P.literal("notifications/initialized")});var nu=rr.extend({method:P.literal("ping")}),Q2=P.object({progress:P.number(),total:P.optional(P.number()),message:P.optional(P.string())}).passthrough(),su=ta.extend({method:P.literal("notifications/progress"),params:ro.merge(Q2).extend({progressToken:Sx})}),iu=rr.extend({params:Tr.extend({cursor:P.optional(Ex)}).optional()}),ou=kr.extend({nextCursor:P.optional(Ex)}),Nx=P.object({uri:P.string(),mimeType:P.optional(P.string()),_meta:P.optional(P.object({}).passthrough())}).passthrough(),jx=Nx.extend({text:P.string()}),ef=P.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Mx=Nx.extend({blob:ef}),Dx=no.extend({uri:P.string(),description:P.optional(P.string()),mimeType:P.optional(P.string()),_meta:P.optional(P.object({}).passthrough())}).merge(ao),eD=no.extend({uriTemplate:P.string(),description:P.optional(P.string()),mimeType:P.optional(P.string()),_meta:P.optional(P.object({}).passthrough())}).merge(ao),tD=iu.extend({method:P.literal("resources/list")}),tf=ou.extend({resources:P.array(Dx)}),rD=iu.extend({method:P.literal("resources/templates/list")}),rf=ou.extend({resourceTemplates:P.array(eD)}),aD=rr.extend({method:P.literal("resources/read"),params:Tr.extend({uri:P.string()})}),af=kr.extend({contents:P.array(P.union([jx,Mx]))}),nD=ta.extend({method:P.literal("notifications/resources/list_changed")}),sD=rr.extend({method:P.literal("resources/subscribe"),params:Tr.extend({uri:P.string()})}),iD=rr.extend({method:P.literal("resources/unsubscribe"),params:Tr.extend({uri:P.string()})}),oD=ta.extend({method:P.literal("notifications/resources/updated"),params:ro.extend({uri:P.string()})}),cD=P.object({name:P.string(),description:P.optional(P.string()),required:P.optional(P.boolean())}).passthrough(),uD=no.extend({description:P.optional(P.string()),arguments:P.optional(P.array(cD)),_meta:P.optional(P.object({}).passthrough())}).merge(ao),lD=iu.extend({method:P.literal("prompts/list")}),nf=ou.extend({prompts:P.array(uD)}),dD=rr.extend({method:P.literal("prompts/get"),params:Tr.extend({name:P.string(),arguments:P.optional(P.record(P.string()))})}),sf=P.object({type:P.literal("text"),text:P.string(),_meta:P.optional(P.object({}).passthrough())}).passthrough(),of=P.object({type:P.literal("image"),data:ef,mimeType:P.string(),_meta:P.optional(P.object({}).passthrough())}).passthrough(),cf=P.object({type:P.literal("audio"),data:ef,mimeType:P.string(),_meta:P.optional(P.object({}).passthrough())}).passthrough(),pD=P.object({type:P.literal("resource"),resource:P.union([jx,Mx]),_meta:P.optional(P.object({}).passthrough())}).passthrough(),fD=Dx.extend({type:P.literal("resource_link")}),qx=P.union([sf,of,cf,fD,pD]),mD=P.object({role:P.enum(["user","assistant"]),content:qx}).passthrough(),uf=kr.extend({description:P.optional(P.string()),messages:P.array(mD)}),hD=ta.extend({method:P.literal("notifications/prompts/list_changed")}),vD=P.object({title:P.optional(P.string()),readOnlyHint:P.optional(P.boolean()),destructiveHint:P.optional(P.boolean()),idempotentHint:P.optional(P.boolean()),openWorldHint:P.optional(P.boolean())}).passthrough(),gD=no.extend({description:P.optional(P.string()),inputSchema:P.object({type:P.literal("object"),properties:P.optional(P.object({}).passthrough()),required:P.optional(P.array(P.string()))}).passthrough(),outputSchema:P.optional(P.object({type:P.literal("object"),properties:P.optional(P.object({}).passthrough()),required:P.optional(P.array(P.string()))}).passthrough()),annotations:P.optional(vD),_meta:P.optional(P.object({}).passthrough())}).merge(ao),yD=iu.extend({method:P.literal("tools/list")}),lf=ou.extend({tools:P.array(gD)}),cu=kr.extend({content:P.array(qx).default([]),structuredContent:P.object({}).passthrough().optional(),isError:P.optional(P.boolean())}),WG=cu.or(kr.extend({toolResult:P.unknown()})),_D=rr.extend({method:P.literal("tools/call"),params:Tr.extend({name:P.string(),arguments:P.optional(P.record(P.unknown()))})}),bD=ta.extend({method:P.literal("notifications/tools/list_changed")}),Lx=P.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),xD=rr.extend({method:P.literal("logging/setLevel"),params:Tr.extend({level:Lx})}),wD=ta.extend({method:P.literal("notifications/message"),params:ro.extend({level:Lx,logger:P.optional(P.string()),data:P.unknown()})}),SD=P.object({name:P.string().optional()}).passthrough(),ED=P.object({hints:P.optional(P.array(SD)),costPriority:P.optional(P.number().min(0).max(1)),speedPriority:P.optional(P.number().min(0).max(1)),intelligencePriority:P.optional(P.number().min(0).max(1))}).passthrough(),TD=P.object({role:P.enum(["user","assistant"]),content:P.union([sf,of,cf])}).passthrough(),kD=rr.extend({method:P.literal("sampling/createMessage"),params:Tr.extend({messages:P.array(TD),systemPrompt:P.optional(P.string()),includeContext:P.optional(P.enum(["none","thisServer","allServers"])),temperature:P.optional(P.number()),maxTokens:P.number().int(),stopSequences:P.optional(P.array(P.string())),metadata:P.optional(P.object({}).passthrough()),modelPreferences:P.optional(ED)})}),$D=kr.extend({model:P.string(),stopReason:P.optional(P.enum(["endTurn","stopSequence","maxTokens"]).or(P.string())),role:P.enum(["user","assistant"]),content:P.discriminatedUnion("type",[sf,of,cf])}),RD=P.object({type:P.literal("boolean"),title:P.optional(P.string()),description:P.optional(P.string()),default:P.optional(P.boolean())}).passthrough(),PD=P.object({type:P.literal("string"),title:P.optional(P.string()),description:P.optional(P.string()),minLength:P.optional(P.number()),maxLength:P.optional(P.number()),format:P.optional(P.enum(["email","uri","date","date-time"]))}).passthrough(),OD=P.object({type:P.enum(["number","integer"]),title:P.optional(P.string()),description:P.optional(P.string()),minimum:P.optional(P.number()),maximum:P.optional(P.number())}).passthrough(),CD=P.object({type:P.literal("string"),title:P.optional(P.string()),description:P.optional(P.string()),enum:P.array(P.string()),enumNames:P.optional(P.array(P.string()))}).passthrough(),ID=P.union([RD,PD,OD,CD]),AD=rr.extend({method:P.literal("elicitation/create"),params:Tr.extend({message:P.string(),requestedSchema:P.object({type:P.literal("object"),properties:P.record(P.string(),ID),required:P.optional(P.array(P.string()))}).passthrough()})}),ND=kr.extend({action:P.enum(["accept","decline","cancel"]),content:P.optional(P.record(P.string(),P.unknown()))}),jD=P.object({type:P.literal("ref/resource"),uri:P.string()}).passthrough();var MD=P.object({type:P.literal("ref/prompt"),name:P.string()}).passthrough(),DD=rr.extend({method:P.literal("completion/complete"),params:Tr.extend({ref:P.union([MD,jD]),argument:P.object({name:P.string(),value:P.string()}).passthrough(),context:P.optional(P.object({arguments:P.optional(P.record(P.string(),P.string()))}))})}),df=kr.extend({completion:P.object({values:P.array(P.string()).max(100),total:P.optional(P.number().int()),hasMore:P.optional(P.boolean())}).passthrough()}),qD=P.object({uri:P.string().startsWith("file://"),name:P.optional(P.string()),_meta:P.optional(P.object({}).passthrough())}).passthrough(),LD=rr.extend({method:P.literal("roots/list")}),FD=kr.extend({roots:P.array(qD)}),zD=ta.extend({method:P.literal("notifications/roots/list_changed")}),KG=P.union([nu,X2,DD,xD,dD,lD,tD,rD,aD,sD,iD,_D,yD]),XG=P.union([au,su,Y2,zD]),JG=P.union([Pn,$D,ND,FD]),YG=P.union([nu,kD,AD,LD]),QG=P.union([au,su,wD,oD,nD,bD,hD]),eW=P.union([Pn,Qp,df,uf,nf,tf,rf,af,cu,lf]),Er=class extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}};var UD=6e4,uu=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.setNotificationHandler(au,r=>{let n=this._requestHandlerAbortControllers.get(r.params.requestId);n?.abort(r.params.reason)}),this.setNotificationHandler(su,r=>{this._onprogress(r)}),this.setRequestHandler(nu,r=>({}))}_setupTimeout(e,r,n,a,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(a,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:a})}_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),new Er(Sr.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){var r,n,a;this._transport=e;let s=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{s?.(),this._onclose()};let i=(n=this.transport)===null||n===void 0?void 0:n.onerror;this._transport.onerror=c=>{i?.(c),this._onerror(c)};let o=(a=this._transport)===null||a===void 0?void 0:a.onmessage;this._transport.onmessage=(c,u)=>{o?.(c,u),Yp(c)||Cx(c)?this._onresponse(c):kx(c)?this._onrequest(c,u):Rx(c)?this._onnotification(c):this._onerror(new Error(`Unknown message type: ${JSON.stringify(c)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let n=new Er(Sr.ConnectionClosed,"Connection closed");for(let a of r.values())a(n)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let n=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(a=>this._onerror(new Error(`Uncaught error in notification handler: ${a}`)))}_onrequest(e,r){var n,a;let s=(n=this._requestHandlers.get(e.method))!==null&&n!==void 0?n:this.fallbackRequestHandler,i=this._transport;if(s===void 0){i?.send({jsonrpc:"2.0",id:e.id,error:{code:Sr.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let c={signal:o.signal,sessionId:i?.sessionId,_meta:(a=e.params)===null||a===void 0?void 0:a._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,l,d)=>this.request(u,l,{...d,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>s(e,c)).then(u=>{if(!o.signal.aborted)return i?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var l;if(!o.signal.aborted)return i?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Sr.InternalError,message:(l=u.message)!==null&&l!==void 0?l:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,a=Number(r),s=this._progressHandlers.get(a);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(a),o=this._timeoutInfo.get(a);if(o&&i&&o.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(c){i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._responseHandlers.get(r);if(n===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Yp(e))n(e);else{let a=new Er(e.error.code,e.error.message,e.error.data);n(a)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,n){let{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}=n??{};return new Promise((o,c)=>{var u,l,d,f,m,g;if(!this._transport){c(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(l=n?.signal)===null||l===void 0||l.throwIfAborted();let b=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),p.params={...e.params,_meta:{...((d=e.params)===null||d===void 0?void 0:d._meta)||{},progressToken:b}});let h=_=>{var S;this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),(S=this._transport)===null||S===void 0||S.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(_)}},{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}).catch(x=>this._onerror(new Error(`Failed to send cancellation: ${x}`))),c(_)};this._responseHandlers.set(b,_=>{var S;if(!(!((S=n?.signal)===null||S===void 0)&&S.aborted)){if(_ instanceof Error)return c(_);try{let x=r.parse(_.result);o(x)}catch(x){c(x)}}}),(f=n?.signal)===null||f===void 0||f.addEventListener("abort",()=>{var _;h((_=n?.signal)===null||_===void 0?void 0:_.reason)});let y=(m=n?.timeout)!==null&&m!==void 0?m:UD,v=()=>h(new Er(Sr.RequestTimeout,"Request timed out",{timeout:y}));this._setupTimeout(b,y,n?.maxTotalTimeout,v,(g=n?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(p,{relatedRequestId:a,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(b),c(_)})})}async notification(e,r){var n,a;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((a=(n=this._options)===null||n===void 0?void 0:n.debouncedNotificationMethods)!==null&&a!==void 0?a:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var c;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(c=this._transport)===null||c===void 0||c.send(u,r).catch(l=>this._onerror(l))});return}let o={...e,jsonrpc:"2.0"};await this._transport.send(o,r)}setRequestHandler(e,r){let n=e.shape.method.value;this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,s)=>Promise.resolve(r(e.parse(a),s)))}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){this._notificationHandlers.set(e.shape.method.value,n=>Promise.resolve(r(e.parse(n))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function Fx(t,e){return Object.entries(e).reduce((r,[n,a])=>(a&&typeof a=="object"?r[n]=r[n]?{...r[n],...a}:a:r[n]=a,r),{...t})}var US=$t(zS(),1),As=class extends uu{constructor(e,r){var n;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(n=r?.capabilities)!==null&&n!==void 0?n:{},this._ajv=new US.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Fx(this._capabilities,e)}assertCapability(e,r){var n;if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Jp,capabilities:this._capabilities,clientInfo:this._clientInfo}},Qp,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!wx.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"})}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,n,a,s,i;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((s=this._serverCapabilities)===null||s===void 0)&&s.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((i=this._serverCapabilities)===null||i===void 0)&&i.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},Pn,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},df,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Pn,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},uf,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},nf,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},tf,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},rf,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},af,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Pn,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Pn,r)}async callTool(e,r=cu,n){let a=await this.request({method:"tools/call",params:e},r,n),s=this.getToolOutputValidator(e.name);if(s){if(!a.structuredContent&&!a.isError)throw new Er(Sr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(a.structuredContent)try{if(!s(a.structuredContent))throw new Er(Sr.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(s.errors)}`)}catch(i){throw i instanceof Er?i:new Er(Sr.InvalidParams,`Failed to validate structured content: ${i instanceof Error?i.message:String(i)}`)}}return a}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let r of e)if(r.outputSchema)try{let n=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,n)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let n=await this.request({method:"tools/list",params:e},lf,r);return this.cacheToolOutputSchemas(n.tools),n}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var IE=$t(OE(),1),io=$t(require("node:process"),1),AE=require("node:stream");var Pu=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(` `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),G9(r)}clear(){this._buffer=void 0}};function G9(t){return Ix.parse(JSON.parse(t))}function CE(t){return JSON.stringify(t)+` -`}var W9=io.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function K9(){let t={};for(let e of W9){let r=io.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Ms=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new Pu,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new AE.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{var n,a,s,i,o;this._process=(0,IE.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...K9(),...this._serverParams.env},stdio:["pipe","pipe",(a=this._serverParams.stderr)!==null&&a!==void 0?a:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:io.default.platform==="win32"&&X9(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var u,l;if(c.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}r(c),(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(s=this._process.stdin)===null||s===void 0||s.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),(i=this._process.stdout)===null||i===void 0||i.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(o=this._process.stdout)===null||o===void 0||o.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,r;return this._stderrStream?this._stderrStream:(r=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&r!==void 0?r:null}get pid(){var e,r;return(r=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&r!==void 0?r:null}processReadBuffer(){for(var e,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(r=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let a=CE(e);this._process.stdin.write(a)?r():this._process.stdin.once("drain",r)})}};function X9(){return"type"in io.default}var Cu=kt(require("path"),1),JE=require("os");mt();var Gf={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,PRE_RESTART_SETTLE_DELAY:2e3,WINDOWS_MULTIPLIER:1.5};function FE(t){return process.platform==="win32"?Math.round(t*Gf.WINDOWS_MULTIPLIER):t}var Ou=require("path");var XE=require("os");dr();Dr();var CK=(0,Ou.join)(qt,"worker.pid"),IK=(0,Ou.join)(qt,"logs"),AK=(0,Ou.join)((0,XE.homedir)(),".claude","plugins","marketplaces","thedotmack");Dr();var HK=Cu.default.join((0,JE.homedir)(),".claude","plugins","marketplaces","thedotmack"),BK=FE(Gf.HEALTH_CHECK),uo=null,lo=null;function qs(){if(uo!==null)return uo;let t=Cu.default.join(ct.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=ct.loadFromFile(t);return uo=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),uo}function YE(){if(lo!==null)return lo;let t=Cu.default.join(ct.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return lo=ct.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,lo}function QE(){uo=null,lo=null}mt();var Bl=require("child_process"),m$=require("util");Iu();var t1=require("bun:sqlite");dr();var Au=class{db;constructor(e){e||(ar(qt),e=co),this.db=new t1.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(n=>n.name==="observations_fts"||n.name==="session_summaries_fts")||(console.log("[SessionSearch] Creating FTS5 tables..."),this.db.run(` +`}var W9=io.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function K9(){let t={};for(let e of W9){let r=io.default.env[e];r!==void 0&&(r.startsWith("()")||(t[e]=r))}return t}var Ms=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new Pu,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new AE.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{var n,a,s,i,o;this._process=(0,IE.default)(this._serverParams.command,(n=this._serverParams.args)!==null&&n!==void 0?n:[],{env:{...K9(),...this._serverParams.env},stdio:["pipe","pipe",(a=this._serverParams.stderr)!==null&&a!==void 0?a:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:io.default.platform==="win32"&&X9(),cwd:this._serverParams.cwd}),this._process.on("error",c=>{var u,l;if(c.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}r(c),(l=this.onerror)===null||l===void 0||l.call(this,c)}),this._process.on("spawn",()=>{e()}),this._process.on("close",c=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(s=this._process.stdin)===null||s===void 0||s.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),(i=this._process.stdout)===null||i===void 0||i.on("data",c=>{this._readBuffer.append(c),this.processReadBuffer()}),(o=this._process.stdout)===null||o===void 0||o.on("error",c=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,c)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,r;return this._stderrStream?this._stderrStream:(r=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&r!==void 0?r:null}get pid(){var e,r;return(r=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&r!==void 0?r:null}processReadBuffer(){for(var e,r;;)try{let n=this._readBuffer.readMessage();if(n===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,n)}catch(n){(r=this.onerror)===null||r===void 0||r.call(this,n)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(r=>{var n;if(!(!((n=this._process)===null||n===void 0)&&n.stdin))throw new Error("Not connected");let a=CE(e);this._process.stdin.write(a)?r():this._process.stdin.once("drain",r)})}};function X9(){return"type"in io.default}var Cu=$t(require("path"),1),JE=require("os");mt();var Gf={DEFAULT:5e3,HEALTH_CHECK:1e3,WORKER_STARTUP_WAIT:1e3,WORKER_STARTUP_RETRIES:15,PRE_RESTART_SETTLE_DELAY:2e3,WINDOWS_MULTIPLIER:1.5};function FE(t){return process.platform==="win32"?Math.round(t*Gf.WINDOWS_MULTIPLIER):t}var Ou=require("path");var XE=require("os");dr();Dr();var CK=(0,Ou.join)(qt,"worker.pid"),IK=(0,Ou.join)(qt,"logs"),AK=(0,Ou.join)((0,XE.homedir)(),".claude","plugins","marketplaces","thedotmack");Dr();var HK=Cu.default.join((0,JE.homedir)(),".claude","plugins","marketplaces","thedotmack"),BK=FE(Gf.HEALTH_CHECK),uo=null,lo=null;function qs(){if(uo!==null)return uo;let t=Cu.default.join(ct.get("CLAUDE_MEM_DATA_DIR"),"settings.json"),e=ct.loadFromFile(t);return uo=parseInt(e.CLAUDE_MEM_WORKER_PORT,10),uo}function YE(){if(lo!==null)return lo;let t=Cu.default.join(ct.get("CLAUDE_MEM_DATA_DIR"),"settings.json");return lo=ct.loadFromFile(t).CLAUDE_MEM_WORKER_HOST,lo}function QE(){uo=null,lo=null}mt();var Bl=require("child_process"),m$=require("util");Iu();var t1=require("bun:sqlite");dr();var Au=class{db;constructor(e){e||(ar(qt),e=co),this.db=new t1.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(n=>n.name==="observations_fts"||n.name==="session_summaries_fts")||(console.log("[SessionSearch] Creating FTS5 tables..."),this.db.run(` CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5( title, subtitle, @@ -719,7 +719,7 @@ No previous sessions found for this project yet.`;let g=d.slice(0,r.sessionCount FROM user_prompts WHERE claude_session_id = ? ORDER BY prompt_number ASC - `).all(e)}close(){this.db.close()}};Iu();mt();Dr();dr();var r1=kt(require("path"),1),a1=kt(require("os"),1),Nu=class{client=null;transport=null;connected=!1;project;collectionName;VECTOR_DB_DIR;BATCH_SIZE=100;constructor(e){this.project=e,this.collectionName=`cm__${e}`,this.VECTOR_DB_DIR=r1.default.join(a1.default.homedir(),".claude-mem","vector-db")}async ensureConnection(){if(!(this.connected&&this.client)){U.info("CHROMA_SYNC","Connecting to Chroma MCP server...",{project:this.project});try{let r=ct.loadFromFile(In).CLAUDE_MEM_PYTHON_VERSION,n=process.platform==="win32",a={command:"uvx",args:["--python",r,"chroma-mcp","--client-type","persistent","--data-dir",this.VECTOR_DB_DIR],stderr:"ignore"};n&&(a.windowsHide=!0,U.debug("CHROMA_SYNC","Windows detected, attempting to hide console window",{project:this.project})),this.transport=new Ms(a),this.client=new As({name:"claude-mem-chroma-sync",version:"1.0.0"},{capabilities:{}}),await this.client.connect(this.transport),this.connected=!0,U.info("CHROMA_SYNC","Connected to Chroma MCP server",{project:this.project})}catch(e){throw U.error("CHROMA_SYNC","Failed to connect to Chroma MCP server",{project:this.project},e),new Error(`Chroma connection failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureCollection(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_get_collection_info",arguments:{collection_name:this.collectionName}}),U.debug("CHROMA_SYNC","Collection exists",{collection:this.collectionName})}catch{U.info("CHROMA_SYNC","Creating collection",{collection:this.collectionName});try{await this.client.callTool({name:"chroma_create_collection",arguments:{collection_name:this.collectionName,embedding_function_name:"default"}}),U.info("CHROMA_SYNC","Collection created",{collection:this.collectionName})}catch(r){throw U.error("CHROMA_SYNC","Failed to create collection",{collection:this.collectionName},r),new Error(`Collection creation failed: ${r instanceof Error?r.message:String(r)}`)}}}formatObservationDocs(e){let r=[],n=e.facts?JSON.parse(e.facts):[],a=e.concepts?JSON.parse(e.concepts):[],s=e.files_read?JSON.parse(e.files_read):[],i=e.files_modified?JSON.parse(e.files_modified):[],o={sqlite_id:e.id,doc_type:"observation",sdk_session_id:e.sdk_session_id,project:e.project,created_at_epoch:e.created_at_epoch,type:e.type||"discovery",title:e.title||"Untitled"};return e.subtitle&&(o.subtitle=e.subtitle),a.length>0&&(o.concepts=a.join(",")),s.length>0&&(o.files_read=s.join(",")),i.length>0&&(o.files_modified=i.join(",")),e.narrative&&r.push({id:`obs_${e.id}_narrative`,document:e.narrative,metadata:{...o,field_type:"narrative"}}),e.text&&r.push({id:`obs_${e.id}_text`,document:e.text,metadata:{...o,field_type:"text"}}),n.forEach((c,u)=>{r.push({id:`obs_${e.id}_fact_${u}`,document:c,metadata:{...o,field_type:"fact",fact_index:u}})}),r}formatSummaryDocs(e){let r=[],n={sqlite_id:e.id,doc_type:"session_summary",sdk_session_id:e.sdk_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number||0};return e.request&&r.push({id:`summary_${e.id}_request`,document:e.request,metadata:{...n,field_type:"request"}}),e.investigated&&r.push({id:`summary_${e.id}_investigated`,document:e.investigated,metadata:{...n,field_type:"investigated"}}),e.learned&&r.push({id:`summary_${e.id}_learned`,document:e.learned,metadata:{...n,field_type:"learned"}}),e.completed&&r.push({id:`summary_${e.id}_completed`,document:e.completed,metadata:{...n,field_type:"completed"}}),e.next_steps&&r.push({id:`summary_${e.id}_next_steps`,document:e.next_steps,metadata:{...n,field_type:"next_steps"}}),e.notes&&r.push({id:`summary_${e.id}_notes`,document:e.notes,metadata:{...n,field_type:"notes"}}),r}async addDocuments(e){if(e.length!==0){if(await this.ensureCollection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_add_documents",arguments:{collection_name:this.collectionName,documents:e.map(r=>r.document),ids:e.map(r=>r.id),metadatas:e.map(r=>r.metadata)}}),U.debug("CHROMA_SYNC","Documents added",{collection:this.collectionName,count:e.length})}catch(r){throw U.error("CHROMA_SYNC","Failed to add documents",{collection:this.collectionName,count:e.length},r),new Error(`Document add failed: ${r instanceof Error?r.message:String(r)}`)}}}async syncObservation(e,r,n,a,s,i,o=0){let c={id:e,sdk_session_id:r,project:n,text:null,type:a.type,title:a.title,subtitle:a.subtitle,facts:JSON.stringify(a.facts),narrative:a.narrative,concepts:JSON.stringify(a.concepts),files_read:JSON.stringify(a.files_read),files_modified:JSON.stringify(a.files_modified),prompt_number:s,discovery_tokens:o,created_at:new Date(i*1e3).toISOString(),created_at_epoch:i},u=this.formatObservationDocs(c);U.info("CHROMA_SYNC","Syncing observation",{observationId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}async syncSummary(e,r,n,a,s,i,o=0){let c={id:e,sdk_session_id:r,project:n,request:a.request,investigated:a.investigated,learned:a.learned,completed:a.completed,next_steps:a.next_steps,notes:a.notes,prompt_number:s,discovery_tokens:o,created_at:new Date(i*1e3).toISOString(),created_at_epoch:i},u=this.formatSummaryDocs(c);U.info("CHROMA_SYNC","Syncing summary",{summaryId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}formatUserPromptDoc(e){return{id:`prompt_${e.id}`,document:e.prompt_text,metadata:{sqlite_id:e.id,doc_type:"user_prompt",sdk_session_id:e.sdk_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number}}}async syncUserPrompt(e,r,n,a,s,i){let o={id:e,claude_session_id:"",prompt_number:s,prompt_text:a,created_at:new Date(i*1e3).toISOString(),created_at_epoch:i,sdk_session_id:r,project:n},c=this.formatUserPromptDoc(o);U.info("CHROMA_SYNC","Syncing user prompt",{promptId:e,project:n}),await this.addDocuments([c])}async getExistingChromaIds(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);let e=new Set,r=new Set,n=new Set,a=0,s=1e3;for(U.info("CHROMA_SYNC","Fetching existing Chroma document IDs...",{project:this.project});;)try{let o=(await this.client.callTool({name:"chroma_get_documents",arguments:{collection_name:this.collectionName,limit:s,offset:a,where:{project:this.project},include:["metadatas"]}})).content[0];if(o.type!=="text")throw new Error("Unexpected response type from chroma_get_documents");let u=JSON.parse(o.text).metadatas||[];if(u.length===0)break;for(let l of u)l.sqlite_id&&(l.doc_type==="observation"?e.add(l.sqlite_id):l.doc_type==="session_summary"?r.add(l.sqlite_id):l.doc_type==="user_prompt"&&n.add(l.sqlite_id));a+=s,U.debug("CHROMA_SYNC","Fetched batch of existing IDs",{project:this.project,offset:a,batchSize:u.length})}catch(i){throw U.error("CHROMA_SYNC","Failed to fetch existing IDs",{project:this.project},i),i}return U.info("CHROMA_SYNC","Existing IDs fetched",{project:this.project,observations:e.size,summaries:r.size,prompts:n.size}),{observations:e,summaries:r,prompts:n}}async ensureBackfilled(){U.info("CHROMA_SYNC","Starting smart backfill",{project:this.project}),await this.ensureCollection();let e=await this.getExistingChromaIds(),r=new qa;try{let n=Array.from(e.observations),a=n.length>0?`AND id NOT IN (${n.join(",")})`:"",s=r.db.prepare(` + `).all(e)}close(){this.db.close()}};Iu();mt();Dr();dr();var r1=$t(require("path"),1),a1=$t(require("os"),1),Nu=class{client=null;transport=null;connected=!1;project;collectionName;VECTOR_DB_DIR;BATCH_SIZE=100;constructor(e){this.project=e,this.collectionName=`cm__${e}`,this.VECTOR_DB_DIR=r1.default.join(a1.default.homedir(),".claude-mem","vector-db")}async ensureConnection(){if(!(this.connected&&this.client)){U.info("CHROMA_SYNC","Connecting to Chroma MCP server...",{project:this.project});try{let r=ct.loadFromFile(In).CLAUDE_MEM_PYTHON_VERSION,n=process.platform==="win32",a={command:"uvx",args:["--python",r,"chroma-mcp","--client-type","persistent","--data-dir",this.VECTOR_DB_DIR],stderr:"ignore"};n&&(a.windowsHide=!0,U.debug("CHROMA_SYNC","Windows detected, attempting to hide console window",{project:this.project})),this.transport=new Ms(a),this.client=new As({name:"claude-mem-chroma-sync",version:"1.0.0"},{capabilities:{}}),await this.client.connect(this.transport),this.connected=!0,U.info("CHROMA_SYNC","Connected to Chroma MCP server",{project:this.project})}catch(e){throw U.error("CHROMA_SYNC","Failed to connect to Chroma MCP server",{project:this.project},e),new Error(`Chroma connection failed: ${e instanceof Error?e.message:String(e)}`)}}}async ensureCollection(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_get_collection_info",arguments:{collection_name:this.collectionName}}),U.debug("CHROMA_SYNC","Collection exists",{collection:this.collectionName})}catch{U.info("CHROMA_SYNC","Creating collection",{collection:this.collectionName});try{await this.client.callTool({name:"chroma_create_collection",arguments:{collection_name:this.collectionName,embedding_function_name:"default"}}),U.info("CHROMA_SYNC","Collection created",{collection:this.collectionName})}catch(r){throw U.error("CHROMA_SYNC","Failed to create collection",{collection:this.collectionName},r),new Error(`Collection creation failed: ${r instanceof Error?r.message:String(r)}`)}}}formatObservationDocs(e){let r=[],n=e.facts?JSON.parse(e.facts):[],a=e.concepts?JSON.parse(e.concepts):[],s=e.files_read?JSON.parse(e.files_read):[],i=e.files_modified?JSON.parse(e.files_modified):[],o={sqlite_id:e.id,doc_type:"observation",sdk_session_id:e.sdk_session_id,project:e.project,created_at_epoch:e.created_at_epoch,type:e.type||"discovery",title:e.title||"Untitled"};return e.subtitle&&(o.subtitle=e.subtitle),a.length>0&&(o.concepts=a.join(",")),s.length>0&&(o.files_read=s.join(",")),i.length>0&&(o.files_modified=i.join(",")),e.narrative&&r.push({id:`obs_${e.id}_narrative`,document:e.narrative,metadata:{...o,field_type:"narrative"}}),e.text&&r.push({id:`obs_${e.id}_text`,document:e.text,metadata:{...o,field_type:"text"}}),n.forEach((c,u)=>{r.push({id:`obs_${e.id}_fact_${u}`,document:c,metadata:{...o,field_type:"fact",fact_index:u}})}),r}formatSummaryDocs(e){let r=[],n={sqlite_id:e.id,doc_type:"session_summary",sdk_session_id:e.sdk_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number||0};return e.request&&r.push({id:`summary_${e.id}_request`,document:e.request,metadata:{...n,field_type:"request"}}),e.investigated&&r.push({id:`summary_${e.id}_investigated`,document:e.investigated,metadata:{...n,field_type:"investigated"}}),e.learned&&r.push({id:`summary_${e.id}_learned`,document:e.learned,metadata:{...n,field_type:"learned"}}),e.completed&&r.push({id:`summary_${e.id}_completed`,document:e.completed,metadata:{...n,field_type:"completed"}}),e.next_steps&&r.push({id:`summary_${e.id}_next_steps`,document:e.next_steps,metadata:{...n,field_type:"next_steps"}}),e.notes&&r.push({id:`summary_${e.id}_notes`,document:e.notes,metadata:{...n,field_type:"notes"}}),r}async addDocuments(e){if(e.length!==0){if(await this.ensureCollection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);try{await this.client.callTool({name:"chroma_add_documents",arguments:{collection_name:this.collectionName,documents:e.map(r=>r.document),ids:e.map(r=>r.id),metadatas:e.map(r=>r.metadata)}}),U.debug("CHROMA_SYNC","Documents added",{collection:this.collectionName,count:e.length})}catch(r){throw U.error("CHROMA_SYNC","Failed to add documents",{collection:this.collectionName,count:e.length},r),new Error(`Document add failed: ${r instanceof Error?r.message:String(r)}`)}}}async syncObservation(e,r,n,a,s,i,o=0){let c={id:e,sdk_session_id:r,project:n,text:null,type:a.type,title:a.title,subtitle:a.subtitle,facts:JSON.stringify(a.facts),narrative:a.narrative,concepts:JSON.stringify(a.concepts),files_read:JSON.stringify(a.files_read),files_modified:JSON.stringify(a.files_modified),prompt_number:s,discovery_tokens:o,created_at:new Date(i*1e3).toISOString(),created_at_epoch:i},u=this.formatObservationDocs(c);U.info("CHROMA_SYNC","Syncing observation",{observationId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}async syncSummary(e,r,n,a,s,i,o=0){let c={id:e,sdk_session_id:r,project:n,request:a.request,investigated:a.investigated,learned:a.learned,completed:a.completed,next_steps:a.next_steps,notes:a.notes,prompt_number:s,discovery_tokens:o,created_at:new Date(i*1e3).toISOString(),created_at_epoch:i},u=this.formatSummaryDocs(c);U.info("CHROMA_SYNC","Syncing summary",{summaryId:e,documentCount:u.length,project:n}),await this.addDocuments(u)}formatUserPromptDoc(e){return{id:`prompt_${e.id}`,document:e.prompt_text,metadata:{sqlite_id:e.id,doc_type:"user_prompt",sdk_session_id:e.sdk_session_id,project:e.project,created_at_epoch:e.created_at_epoch,prompt_number:e.prompt_number}}}async syncUserPrompt(e,r,n,a,s,i){let o={id:e,claude_session_id:"",prompt_number:s,prompt_text:a,created_at:new Date(i*1e3).toISOString(),created_at_epoch:i,sdk_session_id:r,project:n},c=this.formatUserPromptDoc(o);U.info("CHROMA_SYNC","Syncing user prompt",{promptId:e,project:n}),await this.addDocuments([c])}async getExistingChromaIds(){if(await this.ensureConnection(),!this.client)throw new Error(`Chroma client not initialized. Call ensureConnection() before using client methods. Project: ${this.project}`);let e=new Set,r=new Set,n=new Set,a=0,s=1e3;for(U.info("CHROMA_SYNC","Fetching existing Chroma document IDs...",{project:this.project});;)try{let o=(await this.client.callTool({name:"chroma_get_documents",arguments:{collection_name:this.collectionName,limit:s,offset:a,where:{project:this.project},include:["metadatas"]}})).content[0];if(o.type!=="text")throw new Error("Unexpected response type from chroma_get_documents");let u=JSON.parse(o.text).metadatas||[];if(u.length===0)break;for(let l of u)l.sqlite_id&&(l.doc_type==="observation"?e.add(l.sqlite_id):l.doc_type==="session_summary"?r.add(l.sqlite_id):l.doc_type==="user_prompt"&&n.add(l.sqlite_id));a+=s,U.debug("CHROMA_SYNC","Fetched batch of existing IDs",{project:this.project,offset:a,batchSize:u.length})}catch(i){throw U.error("CHROMA_SYNC","Failed to fetch existing IDs",{project:this.project},i),i}return U.info("CHROMA_SYNC","Existing IDs fetched",{project:this.project,observations:e.size,summaries:r.size,prompts:n.size}),{observations:e,summaries:r,prompts:n}}async ensureBackfilled(){U.info("CHROMA_SYNC","Starting smart backfill",{project:this.project}),await this.ensureCollection();let e=await this.getExistingChromaIds(),r=new qa;try{let n=Array.from(e.observations),a=n.length>0?`AND id NOT IN (${n.join(",")})`:"",s=r.db.prepare(` SELECT * FROM observations WHERE project = ? ${a} ORDER BY id ASC @@ -843,7 +843,7 @@ No previous sessions found for this project yet.`;let g=d.slice(0,r.sessionCount `;U.debug("WORKER","SSE broadcast sent",{eventType:e.type,clients:this.sseClients.size});for(let a of this.sseClients)a.write(n)}getClientCount(){return this.sseClients.size}sendToClient(e,r){let n=`data: ${JSON.stringify(r)} -`;e.write(n)}};var Fk=require("child_process"),zk=require("os"),Uk=kt(require("path"),1);mt();mt();La();function i1(t,e){let r=[],n=/([\s\S]*?)<\/observation>/g,a;for(;(a=n.exec(t))!==null;){let s=a[1],i=ra(s,"type"),o=ra(s,"title"),c=ra(s,"subtitle"),u=ra(s,"narrative"),l=Fu(s,"facts","fact"),d=Fu(s,"concepts","concept"),f=Fu(s,"files_read","file"),m=Fu(s,"files_modified","file"),b=$t.getInstance().getActiveMode().observation_types.map(v=>v.id),p=b[0],h=p;i?b.includes(i.trim())?h=i.trim():U.warn("PARSER",`Invalid observation type: ${i}, using "${p}"`,{correlationId:e}):U.warn("PARSER",`Observation missing type field, using "${p}"`,{correlationId:e});let y=d.filter(v=>v!==h);y.length!==d.length&&U.warn("PARSER","Removed observation type from concepts array",{correlationId:e,type:h,originalConcepts:d,cleanedConcepts:y}),r.push({type:h,title:o,subtitle:c,facts:l,narrative:u,concepts:y,files_read:f,files_modified:m})}return r}function o1(t,e){let n=//.exec(t);if(n)return U.info("PARSER","Summary skipped",{sessionId:e,reason:n[1]}),null;let s=/([\s\S]*?)<\/summary>/.exec(t);if(!s)return null;let i=s[1],o=ra(i,"request"),c=ra(i,"investigated"),u=ra(i,"learned"),l=ra(i,"completed"),d=ra(i,"next_steps"),f=ra(i,"notes");return{request:o,investigated:c,learned:u,completed:l,next_steps:d,notes:f}}function ra(t,e){let n=new RegExp(`<${e}>([^<]*)`).exec(t);if(!n)return null;let a=n[1].trim();return a===""?null:a}function Fu(t,e,r){let n=[],s=new RegExp(`<${e}>(.*?)`,"s").exec(t);if(!s)return n;let i=s[1],o=new RegExp(`<${r}>([^<]+)`,"g"),c;for(;(c=o.exec(i))!==null;)n.push(c[1].trim());return n}mt();function c1(t,e,r,n){return`${n.prompts.system_identity} +`;e.write(n)}};var Fk=require("child_process"),zk=require("os"),Uk=$t(require("path"),1);mt();mt();La();function i1(t,e){let r=[],n=/([\s\S]*?)<\/observation>/g,a;for(;(a=n.exec(t))!==null;){let s=a[1],i=ra(s,"type"),o=ra(s,"title"),c=ra(s,"subtitle"),u=ra(s,"narrative"),l=Fu(s,"facts","fact"),d=Fu(s,"concepts","concept"),f=Fu(s,"files_read","file"),m=Fu(s,"files_modified","file"),b=kt.getInstance().getActiveMode().observation_types.map(v=>v.id),p=b[0],h=p;i?b.includes(i.trim())?h=i.trim():U.warn("PARSER",`Invalid observation type: ${i}, using "${p}"`,{correlationId:e}):U.warn("PARSER",`Observation missing type field, using "${p}"`,{correlationId:e});let y=d.filter(v=>v!==h);y.length!==d.length&&U.warn("PARSER","Removed observation type from concepts array",{correlationId:e,type:h,originalConcepts:d,cleanedConcepts:y}),r.push({type:h,title:o,subtitle:c,facts:l,narrative:u,concepts:y,files_read:f,files_modified:m})}return r}function o1(t,e){let n=//.exec(t);if(n)return U.info("PARSER","Summary skipped",{sessionId:e,reason:n[1]}),null;let s=/([\s\S]*?)<\/summary>/.exec(t);if(!s)return null;let i=s[1],o=ra(i,"request"),c=ra(i,"investigated"),u=ra(i,"learned"),l=ra(i,"completed"),d=ra(i,"next_steps"),f=ra(i,"notes");return{request:o,investigated:c,learned:u,completed:l,next_steps:d,notes:f}}function ra(t,e){let n=new RegExp(`<${e}>([^<]*)`).exec(t);if(!n)return null;let a=n[1].trim();return a===""?null:a}function Fu(t,e,r){let n=[],s=new RegExp(`<${e}>(.*?)`,"s").exec(t);if(!s)return n;let i=s[1],o=new RegExp(`<${r}>([^<]+)`,"g"),c;for(;(c=o.exec(i))!==null;)n.push(c[1].trim());return n}mt();function c1(t,e,r,n){return`${n.prompts.system_identity} ${r} @@ -979,7 +979,7 @@ ${n.prompts.format_examples} ${n.prompts.footer} -${n.prompts.header_memory_continued}`}Dr();dr();La();var tm=require("path"),aT=require("url"),nT=require("events"),iT=require("child_process"),oT=require("readline"),Ee=kt(require("fs"),1),cT=require("fs/promises"),fT=require("path"),mT=require("os"),jn=require("path"),vT=require("process"),gT=require("fs"),yT=require("crypto"),wT=require("crypto"),si=require("fs"),rm=require("path"),ST=require("crypto");var S7={},dq=Object.create,pq=Object.getPrototypeOf,em=Object.defineProperty,fq=Object.getOwnPropertyNames,mq=Object.prototype.hasOwnProperty,B1=(t,e,r)=>{r=t!=null?dq(pq(t)):{};let n=e||!t||!t.__esModule?em(r,"default",{value:t,enumerable:!0}):r;for(let a of fq(t))mq.call(n,a)||em(n,a,{get:()=>t[a],enumerable:!0});return n},Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),V1=(t,e)=>{for(var r in e)em(t,r,{get:e[r],enumerable:!0,configurable:!0,set:n=>e[r]=()=>n})};var Zu=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(y){if(super(),!t.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((v,_)=>`${v}${_}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((v,_)=>(_ instanceof r&&(v[_.str]=(v[_.str]||0)+1),v),{})}}t._Code=n,t.nil=new n("");function a(h,...y){let v=[h[0]],_=0;for(;_{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var e=Zu();class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class a{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){let l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=a;class s extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=s;var i=(0,e._)`\n`;class o extends a{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:e.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let f=this.toName(u),{prefix:m}=f,g=(d=l.key)!==null&&d!==void 0?d:l.ref,b=this._values[m];if(b){let y=b.get(g);if(y)return y}else b=this._values[m]=new Map;b.set(g,f);let p=this._scope[m]||(this._scope[m]=[]),h=p.length;return p[h]=l.ref,f.setValue(l,{property:m,itemIndex:h}),f}getValue(u,l){let d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},l,d)}_reduceValues(u,l,d={},f){let m=e.nil;for(let g in u){let b=u[g];if(!b)continue;let p=d[g]=d[g]||new Map;b.forEach(h=>{if(p.has(h))return;p.set(h,n.Started);let y=l(h);if(y){let v=this.opts.es5?t.varKinds.var:t.varKinds.const;m=(0,e._)`${m}${v} ${h} = ${y};${this.opts._n}`}else if(y=f?.(h))m=(0,e._)`${m}${y}${this.opts._n}`;else throw new r(h);p.set(h,n.Completed)})}return m}}t.ValueScope=o}),Be=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;var e=Zu(),r=p1(),n=Zu();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var a=p1();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(w,k){return this}}class i extends s{constructor(w,k,M){super(),this.varKind=w,this.name=k,this.rhs=M}render({es5:w,_n:k}){let M=w?r.varKinds.var:this.varKind,K=this.rhs===void 0?"":` = ${this.rhs}`;return`${M} ${this.name}${K};`+k}optimizeNames(w,k){if(w[this.name.str])return this.rhs&&(this.rhs=A(this.rhs,w,k)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class o extends s{constructor(w,k,M){super(),this.lhs=w,this.rhs=k,this.sideEffects=M}render({_n:w}){return`${this.lhs} = ${this.rhs};`+w}optimizeNames(w,k){if(!(this.lhs instanceof e.Name&&!w[this.lhs.str]&&!this.sideEffects))return this.rhs=A(this.rhs,w,k),this}get names(){let w=this.lhs instanceof e.Name?{}:{...this.lhs.names};return H(w,this.rhs)}}class c extends o{constructor(w,k,M,K){super(w,M,K),this.op=k}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class u extends s{constructor(w){super(),this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class l extends s{constructor(w){super(),this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class d extends s{constructor(w){super(),this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class f extends s{constructor(w){super(),this.code=w}render({_n:w}){return`${this.code};`+w}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(w,k){return this.code=A(this.code,w,k),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class m extends s{constructor(w=[]){super(),this.nodes=w}render(w){return this.nodes.reduce((k,M)=>k+M.render(w),"")}optimizeNodes(){let{nodes:w}=this,k=w.length;for(;k--;){let M=w[k].optimizeNodes();Array.isArray(M)?w.splice(k,1,...M):M?w[k]=M:w.splice(k,1)}return w.length>0?this:void 0}optimizeNames(w,k){let{nodes:M}=this,K=M.length;for(;K--;){let J=M[K];J.optimizeNames(w,k)||(W(w,J.names),M.splice(K,1))}return M.length>0?this:void 0}get names(){return this.nodes.reduce((w,k)=>q(w,k.names),{})}}class g extends m{render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class b extends m{}class p extends g{}p.kind="else";class h extends g{constructor(w,k){super(k),this.condition=w}render(w){let k=`if(${this.condition})`+super.render(w);return this.else&&(k+="else "+this.else.render(w)),k}optimizeNodes(){super.optimizeNodes();let w=this.condition;if(w===!0)return this.nodes;let k=this.else;if(k){let M=k.optimizeNodes();k=this.else=Array.isArray(M)?new p(M):M}if(k)return w===!1?k instanceof h?k:k.nodes:this.nodes.length?this:new h(oe(w),k instanceof h?[k]:k.nodes);if(!(w===!1||!this.nodes.length))return this}optimizeNames(w,k){var M;if(this.else=(M=this.else)===null||M===void 0?void 0:M.optimizeNames(w,k),!!(super.optimizeNames(w,k)||this.else))return this.condition=A(this.condition,w,k),this}get names(){let w=super.names;return H(w,this.condition),this.else&&q(w,this.else.names),w}}h.kind="if";class y extends g{}y.kind="for";class v extends y{constructor(w){super(),this.iteration=w}render(w){return`for(${this.iteration})`+super.render(w)}optimizeNames(w,k){if(super.optimizeNames(w,k))return this.iteration=A(this.iteration,w,k),this}get names(){return q(super.names,this.iteration.names)}}class _ extends y{constructor(w,k,M,K){super(),this.varKind=w,this.name=k,this.from=M,this.to=K}render(w){let k=w.es5?r.varKinds.var:this.varKind,{name:M,from:K,to:J}=this;return`for(${k} ${M}=${K}; ${M}<${J}; ${M}++)`+super.render(w)}get names(){let w=H(super.names,this.from);return H(w,this.to)}}class S extends y{constructor(w,k,M,K){super(),this.loop=w,this.varKind=k,this.name=M,this.iterable=K}render(w){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(w)}optimizeNames(w,k){if(super.optimizeNames(w,k))return this.iterable=A(this.iterable,w,k),this}get names(){return q(super.names,this.iterable.names)}}class x extends g{constructor(w,k,M){super(),this.name=w,this.args=k,this.async=M}render(w){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(w)}}x.kind="func";class E extends m{render(w){return"return "+super.render(w)}}E.kind="return";class T extends g{render(w){let k="try"+super.render(w);return this.catch&&(k+=this.catch.render(w)),this.finally&&(k+=this.finally.render(w)),k}optimizeNodes(){var w,k;return super.optimizeNodes(),(w=this.catch)===null||w===void 0||w.optimizeNodes(),(k=this.finally)===null||k===void 0||k.optimizeNodes(),this}optimizeNames(w,k){var M,K;return super.optimizeNames(w,k),(M=this.catch)===null||M===void 0||M.optimizeNames(w,k),(K=this.finally)===null||K===void 0||K.optimizeNames(w,k),this}get names(){let w=super.names;return this.catch&&q(w,this.catch.names),this.finally&&q(w,this.finally.names),w}}class $ extends g{constructor(w){super(),this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}$.kind="catch";class N extends g{render(w){return"finally"+super.render(w)}}N.kind="finally";class j{constructor(w,k={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...k,_n:k.lines?` +${n.prompts.header_memory_continued}`}Dr();dr();La();var tm=require("path"),aT=require("url"),nT=require("events"),iT=require("child_process"),oT=require("readline"),Ee=$t(require("fs"),1),cT=require("fs/promises"),fT=require("path"),mT=require("os"),jn=require("path"),vT=require("process"),gT=require("fs"),yT=require("crypto"),wT=require("crypto"),si=require("fs"),rm=require("path"),ST=require("crypto");var S7={},dq=Object.create,pq=Object.getPrototypeOf,em=Object.defineProperty,fq=Object.getOwnPropertyNames,mq=Object.prototype.hasOwnProperty,B1=(t,e,r)=>{r=t!=null?dq(pq(t)):{};let n=e||!t||!t.__esModule?em(r,"default",{value:t,enumerable:!0}):r;for(let a of fq(t))mq.call(n,a)||em(n,a,{get:()=>t[a],enumerable:!0});return n},Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),V1=(t,e)=>{for(var r in e)em(t,r,{get:e[r],enumerable:!0,configurable:!0,set:n=>e[r]=()=>n})};var Zu=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class r extends e{constructor(y){if(super(),!t.IDENTIFIER.test(y))throw new Error("CodeGen: name must be a valid identifier");this.str=y}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=r;class n extends e{constructor(y){super(),this._items=typeof y=="string"?[y]:y}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let y=this._items[0];return y===""||y==='""'}get str(){var y;return(y=this._str)!==null&&y!==void 0?y:this._str=this._items.reduce((v,_)=>`${v}${_}`,"")}get names(){var y;return(y=this._names)!==null&&y!==void 0?y:this._names=this._items.reduce((v,_)=>(_ instanceof r&&(v[_.str]=(v[_.str]||0)+1),v),{})}}t._Code=n,t.nil=new n("");function a(h,...y){let v=[h[0]],_=0;for(;_{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;var e=Zu();class r extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var n;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(n||(t.UsedValueState=n={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class a{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){let l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=a;class s extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=s;var i=(0,e._)`\n`;class o extends a{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:e.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let f=this.toName(u),{prefix:m}=f,g=(d=l.key)!==null&&d!==void 0?d:l.ref,b=this._values[m];if(b){let y=b.get(g);if(y)return y}else b=this._values[m]=new Map;b.set(g,f);let p=this._scope[m]||(this._scope[m]=[]),h=p.length;return p[h]=l.ref,f.setValue(l,{property:m,itemIndex:h}),f}getValue(u,l){let d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},l,d)}_reduceValues(u,l,d={},f){let m=e.nil;for(let g in u){let b=u[g];if(!b)continue;let p=d[g]=d[g]||new Map;b.forEach(h=>{if(p.has(h))return;p.set(h,n.Started);let y=l(h);if(y){let v=this.opts.es5?t.varKinds.var:t.varKinds.const;m=(0,e._)`${m}${v} ${h} = ${y};${this.opts._n}`}else if(y=f?.(h))m=(0,e._)`${m}${y}${this.opts._n}`;else throw new r(h);p.set(h,n.Completed)})}return m}}t.ValueScope=o}),Be=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;var e=Zu(),r=p1(),n=Zu();Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return n.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return n.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return n.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}});var a=p1();Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return a.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return a.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return a.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return a.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(w,k){return this}}class i extends s{constructor(w,k,M){super(),this.varKind=w,this.name=k,this.rhs=M}render({es5:w,_n:k}){let M=w?r.varKinds.var:this.varKind,K=this.rhs===void 0?"":` = ${this.rhs}`;return`${M} ${this.name}${K};`+k}optimizeNames(w,k){if(w[this.name.str])return this.rhs&&(this.rhs=A(this.rhs,w,k)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class o extends s{constructor(w,k,M){super(),this.lhs=w,this.rhs=k,this.sideEffects=M}render({_n:w}){return`${this.lhs} = ${this.rhs};`+w}optimizeNames(w,k){if(!(this.lhs instanceof e.Name&&!w[this.lhs.str]&&!this.sideEffects))return this.rhs=A(this.rhs,w,k),this}get names(){let w=this.lhs instanceof e.Name?{}:{...this.lhs.names};return H(w,this.rhs)}}class c extends o{constructor(w,k,M,K){super(w,M,K),this.op=k}render({_n:w}){return`${this.lhs} ${this.op}= ${this.rhs};`+w}}class u extends s{constructor(w){super(),this.label=w,this.names={}}render({_n:w}){return`${this.label}:`+w}}class l extends s{constructor(w){super(),this.label=w,this.names={}}render({_n:w}){return`break${this.label?` ${this.label}`:""};`+w}}class d extends s{constructor(w){super(),this.error=w}render({_n:w}){return`throw ${this.error};`+w}get names(){return this.error.names}}class f extends s{constructor(w){super(),this.code=w}render({_n:w}){return`${this.code};`+w}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(w,k){return this.code=A(this.code,w,k),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class m extends s{constructor(w=[]){super(),this.nodes=w}render(w){return this.nodes.reduce((k,M)=>k+M.render(w),"")}optimizeNodes(){let{nodes:w}=this,k=w.length;for(;k--;){let M=w[k].optimizeNodes();Array.isArray(M)?w.splice(k,1,...M):M?w[k]=M:w.splice(k,1)}return w.length>0?this:void 0}optimizeNames(w,k){let{nodes:M}=this,K=M.length;for(;K--;){let J=M[K];J.optimizeNames(w,k)||(W(w,J.names),M.splice(K,1))}return M.length>0?this:void 0}get names(){return this.nodes.reduce((w,k)=>q(w,k.names),{})}}class g extends m{render(w){return"{"+w._n+super.render(w)+"}"+w._n}}class b extends m{}class p extends g{}p.kind="else";class h extends g{constructor(w,k){super(k),this.condition=w}render(w){let k=`if(${this.condition})`+super.render(w);return this.else&&(k+="else "+this.else.render(w)),k}optimizeNodes(){super.optimizeNodes();let w=this.condition;if(w===!0)return this.nodes;let k=this.else;if(k){let M=k.optimizeNodes();k=this.else=Array.isArray(M)?new p(M):M}if(k)return w===!1?k instanceof h?k:k.nodes:this.nodes.length?this:new h(oe(w),k instanceof h?[k]:k.nodes);if(!(w===!1||!this.nodes.length))return this}optimizeNames(w,k){var M;if(this.else=(M=this.else)===null||M===void 0?void 0:M.optimizeNames(w,k),!!(super.optimizeNames(w,k)||this.else))return this.condition=A(this.condition,w,k),this}get names(){let w=super.names;return H(w,this.condition),this.else&&q(w,this.else.names),w}}h.kind="if";class y extends g{}y.kind="for";class v extends y{constructor(w){super(),this.iteration=w}render(w){return`for(${this.iteration})`+super.render(w)}optimizeNames(w,k){if(super.optimizeNames(w,k))return this.iteration=A(this.iteration,w,k),this}get names(){return q(super.names,this.iteration.names)}}class _ extends y{constructor(w,k,M,K){super(),this.varKind=w,this.name=k,this.from=M,this.to=K}render(w){let k=w.es5?r.varKinds.var:this.varKind,{name:M,from:K,to:J}=this;return`for(${k} ${M}=${K}; ${M}<${J}; ${M}++)`+super.render(w)}get names(){let w=H(super.names,this.from);return H(w,this.to)}}class S extends y{constructor(w,k,M,K){super(),this.loop=w,this.varKind=k,this.name=M,this.iterable=K}render(w){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(w)}optimizeNames(w,k){if(super.optimizeNames(w,k))return this.iterable=A(this.iterable,w,k),this}get names(){return q(super.names,this.iterable.names)}}class x extends g{constructor(w,k,M){super(),this.name=w,this.args=k,this.async=M}render(w){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(w)}}x.kind="func";class E extends m{render(w){return"return "+super.render(w)}}E.kind="return";class T extends g{render(w){let k="try"+super.render(w);return this.catch&&(k+=this.catch.render(w)),this.finally&&(k+=this.finally.render(w)),k}optimizeNodes(){var w,k;return super.optimizeNodes(),(w=this.catch)===null||w===void 0||w.optimizeNodes(),(k=this.finally)===null||k===void 0||k.optimizeNodes(),this}optimizeNames(w,k){var M,K;return super.optimizeNames(w,k),(M=this.catch)===null||M===void 0||M.optimizeNames(w,k),(K=this.finally)===null||K===void 0||K.optimizeNames(w,k),this}get names(){let w=super.names;return this.catch&&q(w,this.catch.names),this.finally&&q(w,this.finally.names),w}}class $ extends g{constructor(w){super(),this.error=w}render(w){return`catch(${this.error})`+super.render(w)}}$.kind="catch";class N extends g{render(w){return"finally"+super.render(w)}}N.kind="finally";class j{constructor(w,k={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...k,_n:k.lines?` `:""},this._extScope=w,this._scope=new r.Scope({parent:w}),this._nodes=[new b]}toString(){return this._root.render(this.opts)}name(w){return this._scope.name(w)}scopeName(w){return this._extScope.name(w)}scopeValue(w,k){let M=this._extScope.value(w,k);return(this._values[M.prefix]||(this._values[M.prefix]=new Set)).add(M),M}getScopeValue(w,k){return this._extScope.getValue(w,k)}scopeRefs(w){return this._extScope.scopeRefs(w,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(w,k,M,K){let J=this._scope.toName(k);return M!==void 0&&K&&(this._constants[J.str]=M),this._leafNode(new i(w,J,M)),J}const(w,k,M){return this._def(r.varKinds.const,w,k,M)}let(w,k,M){return this._def(r.varKinds.let,w,k,M)}var(w,k,M){return this._def(r.varKinds.var,w,k,M)}assign(w,k,M){return this._leafNode(new o(w,k,M))}add(w,k){return this._leafNode(new c(w,t.operators.ADD,k))}code(w){return typeof w=="function"?w():w!==e.nil&&this._leafNode(new f(w)),this}object(...w){let k=["{"];for(let[M,K]of w)k.length>1&&k.push(","),k.push(M),(M!==K||this.opts.es5)&&(k.push(":"),(0,e.addCodeArg)(k,K));return k.push("}"),new e._Code(k)}if(w,k,M){if(this._blockNode(new h(w)),k&&M)this.code(k).else().code(M).endIf();else if(k)this.code(k).endIf();else if(M)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(w){return this._elseNode(new h(w))}else(){return this._elseNode(new p)}endIf(){return this._endBlockNode(h,p)}_for(w,k){return this._blockNode(w),k&&this.code(k).endFor(),this}for(w,k){return this._for(new v(w),k)}forRange(w,k,M,K,J=this.opts.es5?r.varKinds.var:r.varKinds.let){let de=this._scope.toName(w);return this._for(new _(J,de,k,M),()=>K(de))}forOf(w,k,M,K=r.varKinds.const){let J=this._scope.toName(w);if(this.opts.es5){let de=k instanceof e.Name?k:this.var("_arr",k);return this.forRange("_i",0,(0,e._)`${de}.length`,se=>{this.var(J,(0,e._)`${de}[${se}]`),M(J)})}return this._for(new S("of",K,J,k),()=>M(J))}forIn(w,k,M,K=this.opts.es5?r.varKinds.var:r.varKinds.const){if(this.opts.ownProperties)return this.forOf(w,(0,e._)`Object.keys(${k})`,M);let J=this._scope.toName(w);return this._for(new S("in",K,J,k),()=>M(J))}endFor(){return this._endBlockNode(y)}label(w){return this._leafNode(new u(w))}break(w){return this._leafNode(new l(w))}return(w){let k=new E;if(this._blockNode(k),this.code(w),k.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(E)}try(w,k,M){if(!k&&!M)throw new Error('CodeGen: "try" without "catch" and "finally"');let K=new T;if(this._blockNode(K),this.code(w),k){let J=this.name("e");this._currNode=K.catch=new $(J),k(J)}return M&&(this._currNode=K.finally=new N,this.code(M)),this._endBlockNode($,N)}throw(w){return this._leafNode(new d(w))}block(w,k){return this._blockStarts.push(this._nodes.length),w&&this.code(w).endBlock(k),this}endBlock(w){let k=this._blockStarts.pop();if(k===void 0)throw new Error("CodeGen: not in self-balancing block");let M=this._nodes.length-k;if(M<0||w!==void 0&&M!==w)throw new Error(`CodeGen: wrong number of nodes: ${M} vs ${w} expected`);return this._nodes.length=k,this}func(w,k=e.nil,M,K){return this._blockNode(new x(w,k,M)),K&&this.code(K).endFunc(),this}endFunc(){return this._endBlockNode(x)}optimize(w=1){for(;w-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(w){return this._currNode.nodes.push(w),this}_blockNode(w){this._currNode.nodes.push(w),this._nodes.push(w)}_endBlockNode(w,k){let M=this._currNode;if(M instanceof w||k&&M instanceof k)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${k?`${w.kind}/${k.kind}`:w.kind}"`)}_elseNode(w){let k=this._currNode;if(!(k instanceof h))throw new Error('CodeGen: "else" without "if"');return this._currNode=k.else=w,this}get _root(){return this._nodes[0]}get _currNode(){let w=this._nodes;return w[w.length-1]}set _currNode(w){let k=this._nodes;k[k.length-1]=w}}t.CodeGen=j;function q(I,w){for(let k in w)I[k]=(I[k]||0)+(w[k]||0);return I}function H(I,w){return w instanceof e._CodeOrName?q(I,w.names):I}function A(I,w,k){if(I instanceof e.Name)return M(I);if(!K(I))return I;return new e._Code(I._items.reduce((J,de)=>(de instanceof e.Name&&(de=M(de)),de instanceof e._Code?J.push(...de._items):J.push(de),J),[]));function M(J){let de=k[J.str];return de===void 0||w[J.str]!==1?J:(delete w[J.str],de)}function K(J){return J instanceof e._Code&&J._items.some(de=>de instanceof e.Name&&w[de.str]===1&&k[de.str]!==void 0)}}function W(I,w){for(let k in w)I[k]=(I[k]||0)-(w[k]||0)}function oe(I){return typeof I=="boolean"||typeof I=="number"||I===null?!I:(0,e._)`!${z(I)}`}t.not=oe;var he=R(t.operators.AND);function ne(...I){return I.reduce(he)}t.and=ne;var re=R(t.operators.OR);function F(...I){return I.reduce(re)}t.or=F;function R(I){return(w,k)=>w===e.nil?k:k===e.nil?w:(0,e._)`${z(w)} ${I} ${z(k)}`}function z(I){return I instanceof e.Name?I:(0,e._)`(${I})`}}),Xe=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.checkStrictMode=t.getErrorPath=t.Type=t.useFunc=t.setEvaluated=t.evaluatedPropsToName=t.mergeEvaluated=t.eachItem=t.unescapeJsonPointer=t.escapeJsonPointer=t.escapeFragment=t.unescapeFragment=t.schemaRefOrVal=t.schemaHasRulesButRef=t.schemaHasRules=t.checkUnknownRules=t.alwaysValidSchema=t.toHash=void 0;var e=Be(),r=Zu();function n(x){let E={};for(let T of x)E[T]=!0;return E}t.toHash=n;function a(x,E){return typeof E=="boolean"?E:Object.keys(E).length===0?!0:(s(x,E),!i(E,x.self.RULES.all))}t.alwaysValidSchema=a;function s(x,E=x.schema){let{opts:T,self:$}=x;if(!T.strictSchema||typeof E=="boolean")return;let N=$.RULES.keywords;for(let j in E)N[j]||S(x,`unknown keyword: "${j}"`)}t.checkUnknownRules=s;function i(x,E){if(typeof x=="boolean")return!x;for(let T in x)if(E[T])return!0;return!1}t.schemaHasRules=i;function o(x,E){if(typeof x=="boolean")return!x;for(let T in x)if(T!=="$ref"&&E.all[T])return!0;return!1}t.schemaHasRulesButRef=o;function c({topSchemaRef:x,schemaPath:E},T,$,N){if(!N){if(typeof T=="number"||typeof T=="boolean")return T;if(typeof T=="string")return(0,e._)`${T}`}return(0,e._)`${x}${E}${(0,e.getProperty)($)}`}t.schemaRefOrVal=c;function u(x){return f(decodeURIComponent(x))}t.unescapeFragment=u;function l(x){return encodeURIComponent(d(x))}t.escapeFragment=l;function d(x){return typeof x=="number"?`${x}`:x.replace(/~/g,"~0").replace(/\//g,"~1")}t.escapeJsonPointer=d;function f(x){return x.replace(/~1/g,"/").replace(/~0/g,"~")}t.unescapeJsonPointer=f;function m(x,E){if(Array.isArray(x))for(let T of x)E(T);else E(x)}t.eachItem=m;function g({mergeNames:x,mergeToName:E,mergeValues:T,resultToName:$}){return(N,j,q,H)=>{let A=q===void 0?j:q instanceof e.Name?(j instanceof e.Name?x(N,j,q):E(N,j,q),q):j instanceof e.Name?(E(N,q,j),j):T(j,q);return H===e.Name&&!(A instanceof e.Name)?$(N,A):A}}t.mergeEvaluated={props:g({mergeNames:(x,E,T)=>x.if((0,e._)`${T} !== true && ${E} !== undefined`,()=>{x.if((0,e._)`${E} === true`,()=>x.assign(T,!0),()=>x.assign(T,(0,e._)`${T} || {}`).code((0,e._)`Object.assign(${T}, ${E})`))}),mergeToName:(x,E,T)=>x.if((0,e._)`${T} !== true`,()=>{E===!0?x.assign(T,!0):(x.assign(T,(0,e._)`${T} || {}`),p(x,T,E))}),mergeValues:(x,E)=>x===!0?!0:{...x,...E},resultToName:b}),items:g({mergeNames:(x,E,T)=>x.if((0,e._)`${T} !== true && ${E} !== undefined`,()=>x.assign(T,(0,e._)`${E} === true ? true : ${T} > ${E} ? ${T} : ${E}`)),mergeToName:(x,E,T)=>x.if((0,e._)`${T} !== true`,()=>x.assign(T,E===!0?!0:(0,e._)`${T} > ${E} ? ${T} : ${E}`)),mergeValues:(x,E)=>x===!0?!0:Math.max(x,E),resultToName:(x,E)=>x.var("items",E)})};function b(x,E){if(E===!0)return x.var("props",!0);let T=x.var("props",(0,e._)`{}`);return E!==void 0&&p(x,T,E),T}t.evaluatedPropsToName=b;function p(x,E,T){Object.keys(T).forEach($=>x.assign((0,e._)`${E}${(0,e.getProperty)($)}`,!0))}t.setEvaluated=p;var h={};function y(x,E){return x.scopeValue("func",{ref:E,code:h[E.code]||(h[E.code]=new r._Code(E.code))})}t.useFunc=y;var v;(function(x){x[x.Num=0]="Num",x[x.Str=1]="Str"})(v||(t.Type=v={}));function _(x,E,T){if(x instanceof e.Name){let $=E===v.Num;return T?$?(0,e._)`"[" + ${x} + "]"`:(0,e._)`"['" + ${x} + "']"`:$?(0,e._)`"/" + ${x}`:(0,e._)`"/" + ${x}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return T?(0,e.getProperty)(x).toString():"/"+d(x)}t.getErrorPath=_;function S(x,E,T=x.opts.strictSchema){if(T){if(E=`strict mode: ${E}`,T===!0)throw new Error(E);x.self.logger.warn(E)}}t.checkStrictMode=S}),Va=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0});var e=Be(),r={data:new e.Name("data"),valCxt:new e.Name("valCxt"),instancePath:new e.Name("instancePath"),parentData:new e.Name("parentData"),parentDataProperty:new e.Name("parentDataProperty"),rootData:new e.Name("rootData"),dynamicAnchors:new e.Name("dynamicAnchors"),vErrors:new e.Name("vErrors"),errors:new e.Name("errors"),this:new e.Name("this"),self:new e.Name("self"),scope:new e.Name("scope"),json:new e.Name("json"),jsonPos:new e.Name("jsonPos"),jsonLen:new e.Name("jsonLen"),jsonPart:new e.Name("jsonPart")};t.default=r}),rl=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;var e=Be(),r=Xe(),n=Va();t.keywordError={message:({keyword:p})=>(0,e.str)`must pass "${p}" keyword validation`},t.keyword$DataError={message:({keyword:p,schemaType:h})=>h?(0,e.str)`"${p}" keyword must be ${h} ($data)`:(0,e.str)`"${p}" keyword is invalid ($data)`};function a(p,h=t.keywordError,y,v){let{it:_}=p,{gen:S,compositeRule:x,allErrors:E}=_,T=d(p,h,y);v??(x||E)?c(S,T):u(_,(0,e._)`[${T}]`)}t.reportError=a;function s(p,h=t.keywordError,y){let{it:v}=p,{gen:_,compositeRule:S,allErrors:x}=v,E=d(p,h,y);c(_,E),S||x||u(v,n.default.vErrors)}t.reportExtraError=s;function i(p,h){p.assign(n.default.errors,h),p.if((0,e._)`${n.default.vErrors} !== null`,()=>p.if(h,()=>p.assign((0,e._)`${n.default.vErrors}.length`,h),()=>p.assign(n.default.vErrors,null)))}t.resetErrorsCount=i;function o({gen:p,keyword:h,schemaValue:y,data:v,errsCount:_,it:S}){if(_===void 0)throw new Error("ajv implementation error");let x=p.name("err");p.forRange("i",_,n.default.errors,E=>{p.const(x,(0,e._)`${n.default.vErrors}[${E}]`),p.if((0,e._)`${x}.instancePath === undefined`,()=>p.assign((0,e._)`${x}.instancePath`,(0,e.strConcat)(n.default.instancePath,S.errorPath))),p.assign((0,e._)`${x}.schemaPath`,(0,e.str)`${S.errSchemaPath}/${h}`),S.opts.verbose&&(p.assign((0,e._)`${x}.schema`,y),p.assign((0,e._)`${x}.data`,v))})}t.extendErrors=o;function c(p,h){let y=p.const("err",h);p.if((0,e._)`${n.default.vErrors} === null`,()=>p.assign(n.default.vErrors,(0,e._)`[${y}]`),(0,e._)`${n.default.vErrors}.push(${y})`),p.code((0,e._)`${n.default.errors}++`)}function u(p,h){let{gen:y,validateName:v,schemaEnv:_}=p;_.$async?y.throw((0,e._)`new ${p.ValidationError}(${h})`):(y.assign((0,e._)`${v}.errors`,h),y.return(!1))}var l={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function d(p,h,y){let{createErrors:v}=p.it;return v===!1?(0,e._)`{}`:f(p,h,y)}function f(p,h,y={}){let{gen:v,it:_}=p,S=[m(_,y),g(p,y)];return b(p,h,S),v.object(...S)}function m({errorPath:p},{instancePath:h}){let y=h?(0,e.str)`${p}${(0,r.getErrorPath)(h,r.Type.Str)}`:p;return[n.default.instancePath,(0,e.strConcat)(n.default.instancePath,y)]}function g({keyword:p,it:{errSchemaPath:h}},{schemaPath:y,parentSchema:v}){let _=v?h:(0,e.str)`${h}/${p}`;return y&&(_=(0,e.str)`${_}${(0,r.getErrorPath)(y,r.Type.Str)}`),[l.schemaPath,_]}function b(p,{params:h,message:y},v){let{keyword:_,data:S,schemaValue:x,it:E}=p,{opts:T,propertyName:$,topSchemaRef:N,schemaPath:j}=E;v.push([l.keyword,_],[l.params,typeof h=="function"?h(p):h||(0,e._)`{}`]),T.messages&&v.push([l.message,typeof y=="function"?y(p):y]),T.verbose&&v.push([l.schema,x],[l.parentSchema,(0,e._)`${N}${j}`],[n.default.data,S]),$&&v.push([l.propertyName,$])}}),hq=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.boolOrEmptySchema=t.topBoolOrEmptySchema=void 0;var e=rl(),r=Be(),n=Va(),a={message:"boolean schema is false"};function s(c){let{gen:u,schema:l,validateName:d}=c;l===!1?o(c,!1):typeof l=="object"&&l.$async===!0?u.return(n.default.data):(u.assign((0,r._)`${d}.errors`,null),u.return(!0))}t.topBoolOrEmptySchema=s;function i(c,u){let{gen:l,schema:d}=c;d===!1?(l.var(u,!1),o(c)):l.var(u,!0)}t.boolOrEmptySchema=i;function o(c,u){let{gen:l,data:d}=c,f={gen:l,keyword:"false schema",data:d,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:c};(0,e.reportError)(f,a,void 0,u)}}),Z1=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRules=t.isJSONType=void 0;var e=["string","number","integer","boolean","null","object","array"],r=new Set(e);function n(s){return typeof s=="string"&&r.has(s)}t.isJSONType=n;function a(){let s={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...s,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},s.number,s.string,s.array,s.object],post:{rules:[]},all:{},keywords:{}}}t.getRules=a}),G1=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shouldUseRule=t.shouldUseGroup=t.schemaHasRulesForType=void 0;function e({schema:a,self:s},i){let o=s.RULES.types[i];return o&&o!==!0&&r(a,o)}t.schemaHasRulesForType=e;function r(a,s){return s.rules.some(i=>n(a,i))}t.shouldUseGroup=r;function n(a,s){var i;return a[s.keyword]!==void 0||((i=s.definition.implements)===null||i===void 0?void 0:i.some(o=>a[o]!==void 0))}t.shouldUseRule=n}),Gu=Q(t=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reportTypeError=t.checkDataTypes=t.checkDataType=t.coerceAndCheckDataType=t.getJSONTypes=t.getSchemaTypes=t.DataType=void 0;var e=Z1(),r=G1(),n=rl(),a=Be(),s=Xe(),i;(function(v){v[v.Correct=0]="Correct",v[v.Wrong=1]="Wrong"})(i||(t.DataType=i={}));function o(v){let _=c(v.type);if(_.includes("null")){if(v.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!_.length&&v.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');v.nullable===!0&&_.push("null")}return _}t.getSchemaTypes=o;function c(v){let _=Array.isArray(v)?v:v?[v]:[];if(_.every(e.isJSONType))return _;throw new Error("type must be JSONType or JSONType[]: "+_.join(","))}t.getJSONTypes=c;function u(v,_){let{gen:S,data:x,opts:E}=v,T=d(_,E.coerceTypes),$=_.length>0&&!(T.length===0&&_.length===1&&(0,r.schemaHasRulesForType)(v,_[0]));if($){let N=b(_,x,E.strictNumbers,i.Wrong);S.if(N,()=>{T.length?f(v,_,T):h(v)})}return $}t.coerceAndCheckDataType=u;var l=new Set(["string","number","integer","boolean","null"]);function d(v,_){return _?v.filter(S=>l.has(S)||_==="array"&&S==="array"):[]}function f(v,_,S){let{gen:x,data:E,opts:T}=v,$=x.let("dataType",(0,a._)`typeof ${E}`),N=x.let("coerced",(0,a._)`undefined`);T.coerceTypes==="array"&&x.if((0,a._)`${$} == 'object' && Array.isArray(${E}) && ${E}.length == 1`,()=>x.assign(E,(0,a._)`${E}[0]`).assign($,(0,a._)`typeof ${E}`).if(b(_,E,T.strictNumbers),()=>x.assign(N,E))),x.if((0,a._)`${N} !== undefined`);for(let q of S)(l.has(q)||q==="array"&&T.coerceTypes==="array")&&j(q);x.else(),h(v),x.endIf(),x.if((0,a._)`${N} !== undefined`,()=>{x.assign(E,N),m(v,N)});function j(q){switch(q){case"string":x.elseIf((0,a._)`${$} == "number" || ${$} == "boolean"`).assign(N,(0,a._)`"" + ${E}`).elseIf((0,a._)`${E} === null`).assign(N,(0,a._)`""`);return;case"number":x.elseIf((0,a._)`${$} == "boolean" || ${E} === null || (${$} == "string" && ${E} && ${E} == +${E})`).assign(N,(0,a._)`+${E}`);return;case"integer":x.elseIf((0,a._)`${$} === "boolean" || ${E} === null || (${$} === "string" && ${E} && ${E} == +${E} && !(${E} % 1))`).assign(N,(0,a._)`+${E}`);return;case"boolean":x.elseIf((0,a._)`${E} === "false" || ${E} === 0 || ${E} === null`).assign(N,!1).elseIf((0,a._)`${E} === "true" || ${E} === 1`).assign(N,!0);return;case"null":x.elseIf((0,a._)`${E} === "" || ${E} === 0 || ${E} === false`),x.assign(N,null);return;case"array":x.elseIf((0,a._)`${$} === "string" || ${$} === "number" @@ -1029,7 +1029,7 @@ ${n.prompts.header_memory_continued}`}Dr();dr();La();var tm=require("path"),aT=r path: iss.path ? [${Fs(y)}, ...iss.path] : [${Fs(y)}] })));`),f.write(`newResult[${Fs(y)}] = ${v}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let h=f.compile();return(y,v)=>h(d,y,v)},a,s=Ro,i=!fm.jitless,c=i&&OT.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let g=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)a||(a=n(e.shape)),d=a(d,f);else{d.value={};let v=l.shape;for(let _ of l.keys){let S=v[_],x=S._zod.run({value:m[_],issues:[]},f),E=S._zod.optin==="optional"&&S._zod.optout==="optional";x instanceof Promise?g.push(x.then(T=>E?$1(T,d,_,m):Hu(T,d,_))):E?$1(x,d,_,m):Hu(x,d,_)}}if(!u)return g.length?Promise.all(g).then(()=>d):d;let b=[],p=l.keySet,h=u._zod,y=h.def.type;for(let v of Object.keys(m)){if(p.has(v))continue;if(y==="never"){b.push(v);continue}let _=h.run({value:m[v],issues:[]},f);_ instanceof Promise?g.push(_.then(S=>Hu(S,d,v))):Hu(_,d,v)}return b.length&&d.issues.push({code:"unrecognized_keys",keys:b,input:m,inst:t}),g.length?Promise.all(g).then(()=>d):d}});function R1(t,e,r,n){for(let a of t)if(a.issues.length===0)return e.value=a.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(a=>a.issues.map(s=>ba(s,n,_a())))}),e}var WT=ae("$ZodUnion",(t,e)=>{dt.init(t,e),lt(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),lt(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),lt(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),lt(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>hl(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let a=!1,s=[];for(let i of e.options){let o=i._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)s.push(o),a=!0;else{if(o.issues.length===0)return o;s.push(o)}}return a?Promise.all(s).then(i=>R1(i,r,t,n)):R1(s,r,t,n)}}),RU=ae("$ZodDiscriminatedUnion",(t,e)=>{WT.init(t,e);let r=t._zod.parse;lt(t._zod,"propValues",()=>{let a={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[o,c]of Object.entries(i)){a[o]||(a[o]=new Set);for(let u of c)a[o].add(u)}}return a});let n=fl(()=>{let a=e.options,s=new Map;for(let i of a){let o=i._zod.propValues[e.discriminator];if(!o||o.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of o){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(a,s)=>{let i=a.value;if(!Ro(i))return a.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),a;let o=n.value.get(i?.[e.discriminator]);return o?o._zod.run(a,s):e.unionFallback?r(a,s):(a.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),a)}}),PU=ae("$ZodIntersection",(t,e)=>{dt.init(t,e),t._zod.parse=(r,n)=>{let a=r.value,s=e.left._zod.run({value:a,issues:[]},n),i=e.right._zod.run({value:a,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>P1(r,c,u)):P1(r,s,i)}});function gm(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Po(t)&&Po(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),a={...t,...e};for(let s of n){let i=gm(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};a[s]=i.data}return{valid:!0,data:a}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n{dt.init(t,e),t._zod.parse=(r,n)=>{let a=r.value;if(!Po(a))return r.issues.push({expected:"record",code:"invalid_type",input:a,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:a[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...Ua(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...Ua(c,u.issues)),r.value[c]=u.value)}let o;for(let c in a)i.has(c)||(o=o??[],o.push(c));o&&o.length>0&&r.issues.push({code:"unrecognized_keys",input:a,inst:t,keys:o})}else{r.value={};for(let i of Reflect.ownKeys(a)){if(i==="__proto__")continue;let o=e.keyType._zod.run({value:i,issues:[]},n);if(o instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(o.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:o.issues.map(u=>ba(u,n,_a())),input:i,path:[i],inst:t}),r.value[o.value]=o.value;continue}let c=e.valueType._zod.run({value:a[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...Ua(i,u.issues)),r.value[o.value]=u.value})):(c.issues.length&&r.issues.push(...Ua(i,c.issues)),r.value[o.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),CU=ae("$ZodEnum",(t,e)=>{dt.init(t,e);let r=$T(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>CT.has(typeof n)).map(n=>typeof n=="string"?ii(n):n.toString()).join("|")})$`),t._zod.parse=(n,a)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),IU=ae("$ZodLiteral",(t,e)=>{dt.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?ii(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let a=r.value;return t._zod.values.has(a)||r.issues.push({code:"invalid_value",values:e.values,input:a,inst:t}),r}}),AU=ae("$ZodTransform",(t,e)=>{dt.init(t,e),t._zod.parse=(r,n)=>{let a=e.transform(r.value,r);if(n.async)return(a instanceof Promise?a:Promise.resolve(a)).then(i=>(r.value=i,r));if(a instanceof Promise)throw new Dn;return r.value=a,r}}),NU=ae("$ZodOptional",(t,e)=>{dt.init(t,e),t._zod.optin="optional",t._zod.optout="optional",lt(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),lt(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${hl(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),jU=ae("$ZodNullable",(t,e)=>{dt.init(t,e),lt(t._zod,"optin",()=>e.innerType._zod.optin),lt(t._zod,"optout",()=>e.innerType._zod.optout),lt(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${hl(r.source)}|null)$`):void 0}),lt(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),MU=ae("$ZodDefault",(t,e)=>{dt.init(t,e),t._zod.optin="optional",lt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let a=e.innerType._zod.run(r,n);return a instanceof Promise?a.then(s=>O1(s,e)):O1(a,e)}});function O1(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var DU=ae("$ZodPrefault",(t,e)=>{dt.init(t,e),t._zod.optin="optional",lt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),qU=ae("$ZodNonOptional",(t,e)=>{dt.init(t,e),lt(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let a=e.innerType._zod.run(r,n);return a instanceof Promise?a.then(s=>C1(s,t)):C1(a,t)}});function C1(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var LU=ae("$ZodCatch",(t,e)=>{dt.init(t,e),t._zod.optin="optional",lt(t._zod,"optout",()=>e.innerType._zod.optout),lt(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let a=e.innerType._zod.run(r,n);return a instanceof Promise?a.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>ba(i,n,_a()))},input:r.value}),r.issues=[]),r)):(r.value=a.value,a.issues.length&&(r.value=e.catchValue({...r,error:{issues:a.issues.map(s=>ba(s,n,_a()))},input:r.value}),r.issues=[]),r)}}),FU=ae("$ZodPipe",(t,e)=>{dt.init(t,e),lt(t._zod,"values",()=>e.in._zod.values),lt(t._zod,"optin",()=>e.in._zod.optin),lt(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let a=e.in._zod.run(r,n);return a instanceof Promise?a.then(s=>I1(s,e,n)):I1(a,e,n)}});function I1(t,e,r){return zs(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var zU=ae("$ZodReadonly",(t,e)=>{dt.init(t,e),lt(t._zod,"propValues",()=>e.innerType._zod.propValues),lt(t._zod,"values",()=>e.innerType._zod.values),lt(t._zod,"optin",()=>e.innerType._zod.optin),lt(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let a=e.innerType._zod.run(r,n);return a instanceof Promise?a.then(A1):A1(a)}});function A1(t){return t.value=Object.freeze(t.value),t}var UU=ae("$ZodCustom",(t,e)=>{ir.init(t,e),dt.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,a=e.fn(n);if(a instanceof Promise)return a.then(s=>N1(s,r,n,t));N1(a,r,n,t)}});function N1(t,e,r,n){if(!t){let a={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(a.params=n._zod.def.params),e.issues.push(NT(a))}}var HU=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},BU=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${HU(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Cm(n.values[0])}`:`Invalid option: expected one of ${mm(n.values,"|")}`;case"too_big":{let a=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${a}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${a}${n.maximum.toString()}`}case"too_small":{let a=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${a}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${a}${n.minimum.toString()}`}case"invalid_format":{let a=n;return a.format==="starts_with"?`Invalid string: must start with "${a.prefix}"`:a.format==="ends_with"?`Invalid string: must end with "${a.suffix}"`:a.format==="includes"?`Invalid string: must include "${a.includes}"`:a.format==="regex"?`Invalid string: must match pattern ${a.pattern}`:`Invalid ${r[a.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${mm(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function VU(){return{localeError:BU()}}var oJ=Symbol("ZodOutput"),cJ=Symbol("ZodInput"),ym=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}remove(e){return this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function ZU(){return new ym}var Bu=ZU();function GU(t,e){return new t({type:"string",...Re(e)})}function WU(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Re(e)})}function j1(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Re(e)})}function KU(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Re(e)})}function XU(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Re(e)})}function JU(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Re(e)})}function YU(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Re(e)})}function QU(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Re(e)})}function e3(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Re(e)})}function t3(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Re(e)})}function r3(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Re(e)})}function a3(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Re(e)})}function n3(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Re(e)})}function s3(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Re(e)})}function i3(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Re(e)})}function o3(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Re(e)})}function c3(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Re(e)})}function u3(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Re(e)})}function l3(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Re(e)})}function d3(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Re(e)})}function p3(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Re(e)})}function f3(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Re(e)})}function m3(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Re(e)})}function h3(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Re(e)})}function v3(t,e){return new t({type:"string",format:"date",check:"string_format",...Re(e)})}function g3(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Re(e)})}function y3(t,e){return new t({type:"string",format:"duration",check:"string_format",...Re(e)})}function _3(t,e){return new t({type:"number",checks:[],...Re(e)})}function b3(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Re(e)})}function x3(t,e){return new t({type:"boolean",...Re(e)})}function w3(t,e){return new t({type:"null",...Re(e)})}function S3(t){return new t({type:"unknown"})}function E3(t,e){return new t({type:"never",...Re(e)})}function M1(t,e){return new BT({check:"less_than",...Re(e),value:t,inclusive:!1})}function Yf(t,e){return new BT({check:"less_than",...Re(e),value:t,inclusive:!0})}function D1(t,e){return new VT({check:"greater_than",...Re(e),value:t,inclusive:!1})}function Qf(t,e){return new VT({check:"greater_than",...Re(e),value:t,inclusive:!0})}function q1(t,e){return new Dz({check:"multiple_of",...Re(e),value:t})}function KT(t,e){return new Lz({check:"max_length",...Re(e),maximum:t})}function el(t,e){return new Fz({check:"min_length",...Re(e),minimum:t})}function XT(t,e){return new zz({check:"length_equals",...Re(e),length:t})}function T3(t,e){return new Uz({check:"string_format",format:"regex",...Re(e),pattern:t})}function k3(t){return new Hz({check:"string_format",format:"lowercase",...Re(t)})}function $3(t){return new Bz({check:"string_format",format:"uppercase",...Re(t)})}function R3(t,e){return new Vz({check:"string_format",format:"includes",...Re(e),includes:t})}function P3(t,e){return new Zz({check:"string_format",format:"starts_with",...Re(e),prefix:t})}function O3(t,e){return new Gz({check:"string_format",format:"ends_with",...Re(e),suffix:t})}function Co(t){return new Wz({check:"overwrite",tx:t})}function C3(t){return Co(e=>e.normalize(t))}function I3(){return Co(t=>t.trim())}function A3(){return Co(t=>t.toLowerCase())}function N3(){return Co(t=>t.toUpperCase())}function j3(t,e,r){return new t({type:"array",element:e,...Re(r)})}function M3(t,e,r){let n=Re(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function D3(t,e,r){return new t({type:"custom",check:"custom",fn:e,...Re(r)})}var JT={};V1(JT,{time:()=>ak,duration:()=>sk,datetime:()=>QT,date:()=>tk,ZodISOTime:()=>rk,ZodISODuration:()=>nk,ZodISODateTime:()=>YT,ZodISODate:()=>ek});var YT=ae("ZodISODateTime",(t,e)=>{oU.init(t,e),xt.init(t,e)});function QT(t){return h3(YT,t)}var ek=ae("ZodISODate",(t,e)=>{cU.init(t,e),xt.init(t,e)});function tk(t){return v3(ek,t)}var rk=ae("ZodISOTime",(t,e)=>{uU.init(t,e),xt.init(t,e)});function ak(t){return g3(rk,t)}var nk=ae("ZodISODuration",(t,e)=>{lU.init(t,e),xt.init(t,e)});function sk(t){return y3(nk,t)}var ik=(t,e)=>{MT.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>nz(t,r)},flatten:{value:r=>az(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},uJ=ae("ZodError",ik),yl=ae("ZodError",ik,{Parent:Error}),q3=sz(yl),L3=iz(yl),F3=qT(yl),z3=LT(yl),bt=ae("ZodType",(t,e)=>(dt.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>Ga(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>q3(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>F3(t,r,n),t.parseAsync=async(r,n)=>L3(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>z3(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(CH(r,n)),t.superRefine=r=>t.check(IH(r)),t.overwrite=r=>t.check(Co(r)),t.optional=()=>we(t),t.nullable=()=>z1(t),t.nullish=()=>we(z1(t)),t.nonoptional=r=>SH(t,r),t.array=()=>Ze(t),t.or=r=>vt([t,r]),t.and=r=>Am(t,r),t.transform=r=>bm(t,fk(r)),t.default=r=>bH(t,r),t.prefault=r=>wH(t,r),t.catch=r=>TH(t,r),t.pipe=r=>bm(t,r),t.readonly=()=>RH(t),t.describe=r=>{let n=t.clone();return Bu.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Bu.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Bu.get(t);let n=t.clone();return Bu.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),ok=ae("_ZodString",(t,e)=>{Im.init(t,e),bt.init(t,e);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(T3(...n)),t.includes=(...n)=>t.check(R3(...n)),t.startsWith=(...n)=>t.check(P3(...n)),t.endsWith=(...n)=>t.check(O3(...n)),t.min=(...n)=>t.check(el(...n)),t.max=(...n)=>t.check(KT(...n)),t.length=(...n)=>t.check(XT(...n)),t.nonempty=(...n)=>t.check(el(1,...n)),t.lowercase=n=>t.check(k3(n)),t.uppercase=n=>t.check($3(n)),t.trim=()=>t.check(I3()),t.normalize=(...n)=>t.check(C3(...n)),t.toLowerCase=()=>t.check(A3()),t.toUpperCase=()=>t.check(N3())}),U3=ae("ZodString",(t,e)=>{Im.init(t,e),ok.init(t,e),t.email=r=>t.check(WU(H3,r)),t.url=r=>t.check(QU(B3,r)),t.jwt=r=>t.check(m3(sH,r)),t.emoji=r=>t.check(e3(V3,r)),t.guid=r=>t.check(j1(L1,r)),t.uuid=r=>t.check(KU(Vu,r)),t.uuidv4=r=>t.check(XU(Vu,r)),t.uuidv6=r=>t.check(JU(Vu,r)),t.uuidv7=r=>t.check(YU(Vu,r)),t.nanoid=r=>t.check(t3(Z3,r)),t.guid=r=>t.check(j1(L1,r)),t.cuid=r=>t.check(r3(G3,r)),t.cuid2=r=>t.check(a3(W3,r)),t.ulid=r=>t.check(n3(K3,r)),t.base64=r=>t.check(d3(rH,r)),t.base64url=r=>t.check(p3(aH,r)),t.xid=r=>t.check(s3(X3,r)),t.ksuid=r=>t.check(i3(J3,r)),t.ipv4=r=>t.check(o3(Y3,r)),t.ipv6=r=>t.check(c3(Q3,r)),t.cidrv4=r=>t.check(u3(eH,r)),t.cidrv6=r=>t.check(l3(tH,r)),t.e164=r=>t.check(f3(nH,r)),t.datetime=r=>t.check(QT(r)),t.date=r=>t.check(tk(r)),t.time=r=>t.check(ak(r)),t.duration=r=>t.check(sk(r))});function te(t){return GU(U3,t)}var xt=ae("ZodStringFormat",(t,e)=>{ht.init(t,e),ok.init(t,e)}),H3=ae("ZodEmail",(t,e)=>{Yz.init(t,e),xt.init(t,e)}),L1=ae("ZodGUID",(t,e)=>{Xz.init(t,e),xt.init(t,e)}),Vu=ae("ZodUUID",(t,e)=>{Jz.init(t,e),xt.init(t,e)}),B3=ae("ZodURL",(t,e)=>{Qz.init(t,e),xt.init(t,e)}),V3=ae("ZodEmoji",(t,e)=>{eU.init(t,e),xt.init(t,e)}),Z3=ae("ZodNanoID",(t,e)=>{tU.init(t,e),xt.init(t,e)}),G3=ae("ZodCUID",(t,e)=>{rU.init(t,e),xt.init(t,e)}),W3=ae("ZodCUID2",(t,e)=>{aU.init(t,e),xt.init(t,e)}),K3=ae("ZodULID",(t,e)=>{nU.init(t,e),xt.init(t,e)}),X3=ae("ZodXID",(t,e)=>{sU.init(t,e),xt.init(t,e)}),J3=ae("ZodKSUID",(t,e)=>{iU.init(t,e),xt.init(t,e)}),Y3=ae("ZodIPv4",(t,e)=>{dU.init(t,e),xt.init(t,e)}),Q3=ae("ZodIPv6",(t,e)=>{pU.init(t,e),xt.init(t,e)}),eH=ae("ZodCIDRv4",(t,e)=>{fU.init(t,e),xt.init(t,e)}),tH=ae("ZodCIDRv6",(t,e)=>{mU.init(t,e),xt.init(t,e)}),rH=ae("ZodBase64",(t,e)=>{hU.init(t,e),xt.init(t,e)}),aH=ae("ZodBase64URL",(t,e)=>{gU.init(t,e),xt.init(t,e)}),nH=ae("ZodE164",(t,e)=>{yU.init(t,e),xt.init(t,e)}),sH=ae("ZodJWT",(t,e)=>{bU.init(t,e),xt.init(t,e)}),ck=ae("ZodNumber",(t,e)=>{GT.init(t,e),bt.init(t,e),t.gt=(n,a)=>t.check(D1(n,a)),t.gte=(n,a)=>t.check(Qf(n,a)),t.min=(n,a)=>t.check(Qf(n,a)),t.lt=(n,a)=>t.check(M1(n,a)),t.lte=(n,a)=>t.check(Yf(n,a)),t.max=(n,a)=>t.check(Yf(n,a)),t.int=n=>t.check(F1(n)),t.safe=n=>t.check(F1(n)),t.positive=n=>t.check(D1(0,n)),t.nonnegative=n=>t.check(Qf(0,n)),t.negative=n=>t.check(M1(0,n)),t.nonpositive=n=>t.check(Yf(0,n)),t.multipleOf=(n,a)=>t.check(q1(n,a)),t.step=(n,a)=>t.check(q1(n,a)),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 ot(t){return _3(ck,t)}var iH=ae("ZodNumberFormat",(t,e)=>{xU.init(t,e),ck.init(t,e)});function F1(t){return b3(iH,t)}var oH=ae("ZodBoolean",(t,e)=>{wU.init(t,e),bt.init(t,e)});function Ht(t){return x3(oH,t)}var cH=ae("ZodNull",(t,e)=>{SU.init(t,e),bt.init(t,e)});function uk(t){return w3(cH,t)}var uH=ae("ZodUnknown",(t,e)=>{EU.init(t,e),bt.init(t,e)});function Nt(){return S3(uH)}var lH=ae("ZodNever",(t,e)=>{TU.init(t,e),bt.init(t,e)});function dH(t){return E3(lH,t)}var pH=ae("ZodArray",(t,e)=>{kU.init(t,e),bt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(el(r,n)),t.nonempty=r=>t.check(el(1,r)),t.max=(r,n)=>t.check(KT(r,n)),t.length=(r,n)=>t.check(XT(r,n)),t.unwrap=()=>t.element});function Ze(t,e){return j3(pH,t,e)}var lk=ae("ZodObject",(t,e)=>{$U.init(t,e),bt.init(t,e),ut.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Bt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Nt()}),t.loose=()=>t.clone({...t._zod.def,catchall:Nt()}),t.strict=()=>t.clone({...t._zod.def,catchall:dH()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ut.extend(t,r),t.merge=r=>ut.merge(t,r),t.pick=r=>ut.pick(t,r),t.omit=r=>ut.omit(t,r),t.partial=(...r)=>ut.partial(mk,t,r[0]),t.required=(...r)=>ut.required(hk,t,r[0])});function le(t,e){let r={type:"object",get shape(){return ut.assignProp(this,"shape",{...t}),this.shape},...ut.normalizeParams(e)};return new lk(r)}function Fr(t,e){return new lk({type:"object",get shape(){return ut.assignProp(this,"shape",{...t}),this.shape},catchall:Nt(),...ut.normalizeParams(e)})}var dk=ae("ZodUnion",(t,e)=>{WT.init(t,e),bt.init(t,e),t.options=e.options});function vt(t,e){return new dk({type:"union",options:t,...ut.normalizeParams(e)})}var fH=ae("ZodDiscriminatedUnion",(t,e)=>{dk.init(t,e),RU.init(t,e)});function pk(t,e,r){return new fH({type:"union",options:e,discriminator:t,...ut.normalizeParams(r)})}var mH=ae("ZodIntersection",(t,e)=>{PU.init(t,e),bt.init(t,e)});function Am(t,e){return new mH({type:"intersection",left:t,right:e})}var hH=ae("ZodRecord",(t,e)=>{OU.init(t,e),bt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function jt(t,e,r){return new hH({type:"record",keyType:t,valueType:e,...ut.normalizeParams(r)})}var _m=ae("ZodEnum",(t,e)=>{CU.init(t,e),bt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,a)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new _m({...e,checks:[],...ut.normalizeParams(a),entries:s})},t.exclude=(n,a)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new _m({...e,checks:[],...ut.normalizeParams(a),entries:s})}});function Bt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new _m({type:"enum",entries:r,...ut.normalizeParams(e)})}var vH=ae("ZodLiteral",(t,e)=>{IU.init(t,e),bt.init(t,e),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 Se(t,e){return new vH({type:"literal",values:Array.isArray(t)?t:[t],...ut.normalizeParams(e)})}var gH=ae("ZodTransform",(t,e)=>{AU.init(t,e),bt.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ut.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(ut.issue(i))}};let a=e.transform(r.value,r);return a instanceof Promise?a.then(s=>(r.value=s,r)):(r.value=a,r)}});function fk(t){return new gH({type:"transform",transform:t})}var mk=ae("ZodOptional",(t,e)=>{NU.init(t,e),bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function we(t){return new mk({type:"optional",innerType:t})}var yH=ae("ZodNullable",(t,e)=>{jU.init(t,e),bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function z1(t){return new yH({type:"nullable",innerType:t})}var _H=ae("ZodDefault",(t,e)=>{MU.init(t,e),bt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function bH(t,e){return new _H({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var xH=ae("ZodPrefault",(t,e)=>{DU.init(t,e),bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function wH(t,e){return new xH({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var hk=ae("ZodNonOptional",(t,e)=>{qU.init(t,e),bt.init(t,e),t.unwrap=()=>t._zod.def.innerType});function SH(t,e){return new hk({type:"nonoptional",innerType:t,...ut.normalizeParams(e)})}var EH=ae("ZodCatch",(t,e)=>{LU.init(t,e),bt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function TH(t,e){return new EH({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var kH=ae("ZodPipe",(t,e)=>{FU.init(t,e),bt.init(t,e),t.in=e.in,t.out=e.out});function bm(t,e){return new kH({type:"pipe",in:t,out:e})}var $H=ae("ZodReadonly",(t,e)=>{zU.init(t,e),bt.init(t,e)});function RH(t){return new $H({type:"readonly",innerType:t})}var vk=ae("ZodCustom",(t,e)=>{UU.init(t,e),bt.init(t,e)});function PH(t,e){let r=new ir({check:"custom",...ut.normalizeParams(e)});return r._zod.check=t,r}function OH(t,e){return M3(vk,t??(()=>!0),e)}function CH(t,e={}){return D3(vk,t,e)}function IH(t,e){let r=PH(n=>(n.addIssue=a=>{if(typeof a=="string")n.issues.push(ut.issue(a,n.value,r._zod.def));else{let s=a;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(ut.issue(s))}},t(n.value,n)),e);return r}function gk(t,e){return bm(fk(t),e)}_a(VU());var Nm="io.modelcontextprotocol/related-task",_l="2.0",aa=OH(t=>t!==null&&(typeof t=="object"||typeof t=="function")),yk=vt([te(),ot().int()]),_k=te(),AH=Fr({ttl:vt([ot(),uk()]).optional(),pollInterval:ot().optional()}),jm=Fr({taskId:te()}),NH=Fr({progressToken:yk.optional(),[Nm]:jm.optional()}),or=Fr({task:AH.optional(),_meta:NH.optional()}),Ft=le({method:te(),params:or.optional()}),qn=Fr({_meta:le({[Nm]:we(jm)}).passthrough().optional()}),Pr=le({method:te(),params:qn.optional()}),Vt=Fr({_meta:Fr({[Nm]:jm.optional()}).optional()}),bl=vt([te(),ot().int()]),jH=le({jsonrpc:Se(_l),id:bl,...Ft.shape}).strict();var MH=le({jsonrpc:Se(_l),...Pr.shape}).strict();var DH=le({jsonrpc:Se(_l),id:bl,result:Vt}).strict();var U1;(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"})(U1||(U1={}));var qH=le({jsonrpc:Se(_l),id:bl,error:le({code:ot().int(),message:te(),data:we(Nt())})}).strict();var lJ=vt([jH,MH,DH,qH]),bk=Vt.strict(),LH=qn.extend({requestId:bl,reason:te().optional()}),xk=Pr.extend({method:Se("notifications/cancelled"),params:LH}),FH=le({src:te(),mimeType:te().optional(),sizes:Ze(te()).optional()}),Io=le({icons:Ze(FH).optional()}),ti=le({name:te(),title:te().optional()}),wk=ti.extend({...ti.shape,...Io.shape,version:te(),websiteUrl:te().optional()}),zH=Am(le({applyDefaults:Ht().optional()}),jt(te(),Nt())),UH=gk(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Am(le({form:zH.optional(),url:aa.optional()}),jt(te(),Nt()).optional())),HH=le({list:we(le({}).passthrough()),cancel:we(le({}).passthrough()),requests:we(le({sampling:we(le({createMessage:we(le({}).passthrough())}).passthrough()),elicitation:we(le({create:we(le({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),BH=le({list:we(le({}).passthrough()),cancel:we(le({}).passthrough()),requests:we(le({tools:we(le({call:we(le({}).passthrough())}).passthrough())}).passthrough())}).passthrough(),VH=le({experimental:jt(te(),aa).optional(),sampling:le({context:aa.optional(),tools:aa.optional()}).optional(),elicitation:UH.optional(),roots:le({listChanged:Ht().optional()}).optional(),tasks:we(HH)}),ZH=or.extend({protocolVersion:te(),capabilities:VH,clientInfo:wk}),GH=Ft.extend({method:Se("initialize"),params:ZH}),WH=le({experimental:jt(te(),aa).optional(),logging:aa.optional(),completions:aa.optional(),prompts:we(le({listChanged:we(Ht())})),resources:le({subscribe:Ht().optional(),listChanged:Ht().optional()}).optional(),tools:le({listChanged:Ht().optional()}).optional(),tasks:we(BH)}).passthrough(),KH=Vt.extend({protocolVersion:te(),capabilities:WH,serverInfo:wk,instructions:te().optional()}),XH=Pr.extend({method:Se("notifications/initialized")}),Sk=Ft.extend({method:Se("ping")}),JH=le({progress:ot(),total:we(ot()),message:we(te())}),YH=le({...qn.shape,...JH.shape,progressToken:yk}),Ek=Pr.extend({method:Se("notifications/progress"),params:YH}),QH=or.extend({cursor:_k.optional()}),Ao=Ft.extend({params:QH.optional()}),No=Vt.extend({nextCursor:we(_k)}),jo=le({taskId:te(),status:Bt(["working","input_required","completed","failed","cancelled"]),ttl:vt([ot(),uk()]),createdAt:te(),lastUpdatedAt:te(),pollInterval:we(ot()),statusMessage:we(te())}),Tk=Vt.extend({task:jo}),eB=qn.merge(jo),kk=Pr.extend({method:Se("notifications/tasks/status"),params:eB}),$k=Ft.extend({method:Se("tasks/get"),params:or.extend({taskId:te()})}),Rk=Vt.merge(jo),Pk=Ft.extend({method:Se("tasks/result"),params:or.extend({taskId:te()})}),Ok=Ao.extend({method:Se("tasks/list")}),Ck=No.extend({tasks:Ze(jo)}),dJ=Ft.extend({method:Se("tasks/cancel"),params:or.extend({taskId:te()})}),pJ=Vt.merge(jo),Ik=le({uri:te(),mimeType:we(te()),_meta:jt(te(),Nt()).optional()}),Ak=Ik.extend({text:te()}),Mm=te().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Nk=Ik.extend({blob:Mm}),oi=le({audience:Ze(Bt(["user","assistant"])).optional(),priority:ot().min(0).max(1).optional(),lastModified:JT.datetime({offset:!0}).optional()}),jk=le({...ti.shape,...Io.shape,uri:te(),description:we(te()),mimeType:we(te()),annotations:oi.optional(),_meta:we(Fr({}))}),tB=le({...ti.shape,...Io.shape,uriTemplate:te(),description:we(te()),mimeType:we(te()),annotations:oi.optional(),_meta:we(Fr({}))}),rB=Ao.extend({method:Se("resources/list")}),aB=No.extend({resources:Ze(jk)}),nB=Ao.extend({method:Se("resources/templates/list")}),sB=No.extend({resourceTemplates:Ze(tB)}),Dm=or.extend({uri:te()}),iB=Dm,oB=Ft.extend({method:Se("resources/read"),params:iB}),cB=Vt.extend({contents:Ze(vt([Ak,Nk]))}),uB=Pr.extend({method:Se("notifications/resources/list_changed")}),lB=Dm,dB=Ft.extend({method:Se("resources/subscribe"),params:lB}),pB=Dm,fB=Ft.extend({method:Se("resources/unsubscribe"),params:pB}),mB=qn.extend({uri:te()}),hB=Pr.extend({method:Se("notifications/resources/updated"),params:mB}),vB=le({name:te(),description:we(te()),required:we(Ht())}),gB=le({...ti.shape,...Io.shape,description:we(te()),arguments:we(Ze(vB)),_meta:we(Fr({}))}),yB=Ao.extend({method:Se("prompts/list")}),_B=No.extend({prompts:Ze(gB)}),bB=or.extend({name:te(),arguments:jt(te(),te()).optional()}),xB=Ft.extend({method:Se("prompts/get"),params:bB}),qm=le({type:Se("text"),text:te(),annotations:oi.optional(),_meta:jt(te(),Nt()).optional()}),Lm=le({type:Se("image"),data:Mm,mimeType:te(),annotations:oi.optional(),_meta:jt(te(),Nt()).optional()}),Fm=le({type:Se("audio"),data:Mm,mimeType:te(),annotations:oi.optional(),_meta:jt(te(),Nt()).optional()}),wB=le({type:Se("tool_use"),name:te(),id:te(),input:le({}).passthrough(),_meta:we(le({}).passthrough())}).passthrough(),SB=le({type:Se("resource"),resource:vt([Ak,Nk]),annotations:oi.optional(),_meta:jt(te(),Nt()).optional()}),EB=jk.extend({type:Se("resource_link")}),zm=vt([qm,Lm,Fm,EB,SB]),TB=le({role:Bt(["user","assistant"]),content:zm}),kB=Vt.extend({description:we(te()),messages:Ze(TB)}),$B=Pr.extend({method:Se("notifications/prompts/list_changed")}),RB=le({title:te().optional(),readOnlyHint:Ht().optional(),destructiveHint:Ht().optional(),idempotentHint:Ht().optional(),openWorldHint:Ht().optional()}),PB=le({taskSupport:Bt(["required","optional","forbidden"]).optional()}),Mk=le({...ti.shape,...Io.shape,description:te().optional(),inputSchema:le({type:Se("object"),properties:jt(te(),aa).optional(),required:Ze(te()).optional()}).catchall(Nt()),outputSchema:le({type:Se("object"),properties:jt(te(),aa).optional(),required:Ze(te()).optional()}).catchall(Nt()).optional(),annotations:we(RB),execution:we(PB),_meta:jt(te(),Nt()).optional()}),OB=Ao.extend({method:Se("tools/list")}),CB=No.extend({tools:Ze(Mk)}),Dk=Vt.extend({content:Ze(zm).default([]),structuredContent:jt(te(),Nt()).optional(),isError:we(Ht())}),fJ=Dk.or(Vt.extend({toolResult:Nt()})),IB=or.extend({name:te(),arguments:we(jt(te(),Nt()))}),AB=Ft.extend({method:Se("tools/call"),params:IB}),NB=Pr.extend({method:Se("notifications/tools/list_changed")}),qk=Bt(["debug","info","notice","warning","error","critical","alert","emergency"]),jB=or.extend({level:qk}),MB=Ft.extend({method:Se("logging/setLevel"),params:jB}),DB=qn.extend({level:qk,logger:te().optional(),data:Nt()}),qB=Pr.extend({method:Se("notifications/message"),params:DB}),LB=le({name:te().optional()}),FB=le({hints:we(Ze(LB)),costPriority:we(ot().min(0).max(1)),speedPriority:we(ot().min(0).max(1)),intelligencePriority:we(ot().min(0).max(1))}),zB=le({mode:we(Bt(["auto","required","none"]))}),UB=le({type:Se("tool_result"),toolUseId:te().describe("The unique identifier for the corresponding tool call."),content:Ze(zm).default([]),structuredContent:le({}).passthrough().optional(),isError:we(Ht()),_meta:we(le({}).passthrough())}).passthrough(),HB=pk("type",[qm,Lm,Fm]),tl=pk("type",[qm,Lm,Fm,wB,UB]),BB=le({role:Bt(["user","assistant"]),content:vt([tl,Ze(tl)]),_meta:we(le({}).passthrough())}).passthrough(),VB=or.extend({messages:Ze(BB),modelPreferences:FB.optional(),systemPrompt:te().optional(),includeContext:Bt(["none","thisServer","allServers"]).optional(),temperature:ot().optional(),maxTokens:ot().int(),stopSequences:Ze(te()).optional(),metadata:aa.optional(),tools:we(Ze(Mk)),toolChoice:we(zB)}),ZB=Ft.extend({method:Se("sampling/createMessage"),params:VB}),GB=Vt.extend({model:te(),stopReason:we(Bt(["endTurn","stopSequence","maxTokens"]).or(te())),role:Bt(["user","assistant"]),content:HB}),WB=Vt.extend({model:te(),stopReason:we(Bt(["endTurn","stopSequence","maxTokens","toolUse"]).or(te())),role:Bt(["user","assistant"]),content:vt([tl,Ze(tl)])}),KB=le({type:Se("boolean"),title:te().optional(),description:te().optional(),default:Ht().optional()}),XB=le({type:Se("string"),title:te().optional(),description:te().optional(),minLength:ot().optional(),maxLength:ot().optional(),format:Bt(["email","uri","date","date-time"]).optional(),default:te().optional()}),JB=le({type:Bt(["number","integer"]),title:te().optional(),description:te().optional(),minimum:ot().optional(),maximum:ot().optional(),default:ot().optional()}),YB=le({type:Se("string"),title:te().optional(),description:te().optional(),enum:Ze(te()),default:te().optional()}),QB=le({type:Se("string"),title:te().optional(),description:te().optional(),oneOf:Ze(le({const:te(),title:te()})),default:te().optional()}),e7=le({type:Se("string"),title:te().optional(),description:te().optional(),enum:Ze(te()),enumNames:Ze(te()).optional(),default:te().optional()}),t7=vt([YB,QB]),r7=le({type:Se("array"),title:te().optional(),description:te().optional(),minItems:ot().optional(),maxItems:ot().optional(),items:le({type:Se("string"),enum:Ze(te())}),default:Ze(te()).optional()}),a7=le({type:Se("array"),title:te().optional(),description:te().optional(),minItems:ot().optional(),maxItems:ot().optional(),items:le({anyOf:Ze(le({const:te(),title:te()}))}),default:Ze(te()).optional()}),n7=vt([r7,a7]),s7=vt([e7,t7,n7]),i7=vt([s7,KB,XB,JB]),o7=or.extend({mode:Se("form").optional(),message:te(),requestedSchema:le({type:Se("object"),properties:jt(te(),i7),required:Ze(te()).optional()})}),c7=or.extend({mode:Se("url"),message:te(),elicitationId:te(),url:te().url()}),u7=vt([o7,c7]),l7=Ft.extend({method:Se("elicitation/create"),params:u7}),d7=qn.extend({elicitationId:te()}),p7=Pr.extend({method:Se("notifications/elicitation/complete"),params:d7}),f7=Vt.extend({action:Bt(["accept","decline","cancel"]),content:gk(t=>t===null?void 0:t,jt(te(),vt([te(),ot(),Ht(),Ze(te())])).optional())}),m7=le({type:Se("ref/resource"),uri:te()}),h7=le({type:Se("ref/prompt"),name:te()}),v7=or.extend({ref:vt([h7,m7]),argument:le({name:te(),value:te()}),context:le({arguments:jt(te(),te()).optional()}).optional()}),g7=Ft.extend({method:Se("completion/complete"),params:v7});var y7=Vt.extend({completion:Fr({values:Ze(te()).max(100),total:we(ot().int()),hasMore:we(Ht())})}),_7=le({uri:te().startsWith("file://"),name:te().optional(),_meta:jt(te(),Nt()).optional()}),b7=Ft.extend({method:Se("roots/list")}),x7=Vt.extend({roots:Ze(_7)}),w7=Pr.extend({method:Se("notifications/roots/list_changed")}),mJ=vt([Sk,GH,g7,MB,xB,yB,rB,nB,oB,dB,fB,AB,OB,$k,Pk,Ok]),hJ=vt([xk,Ek,XH,w7,kk]),vJ=vt([bk,GB,WB,f7,x7,Rk,Ck,Tk]),gJ=vt([Sk,ZB,l7,b7,$k,Pk,Ok]),yJ=vt([xk,Ek,qB,hB,uB,NB,$B,kk,p7]),_J=vt([bk,KH,y7,kB,_B,aB,sB,cB,Dk,CB,Rk,Ck,Tk]);var bJ=Symbol("Let zodToJsonSchema decide on which parser to use");var xJ=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var wJ=B1(cL(),1),SJ=B1(r6(),1);var EJ=Symbol.for("mcp.completable");var H1;(function(t){t.Completable="McpCompletable"})(H1||(H1={}));function Lk({prompt:t,options:e}){let{systemPrompt:r,settingSources:n,sandbox:a,...s}=e??{},i,o;r===void 0?i="":typeof r=="string"?i=r:r.type==="preset"&&(o=r.append);let c=s.pathToClaudeCodeExecutable;if(!c){let G=(0,aT.fileURLToPath)(S7.url),ee=(0,tm.join)(G,"..");c=(0,tm.join)(ee,"cli.js")}process.env.CLAUDE_AGENT_SDK_VERSION="0.1.75";let{abortController:u=sT(),additionalDirectories:l=[],agents:d,allowedTools:f=[],betas:m,canUseTool:g,continue:b,cwd:p,disallowedTools:h=[],tools:y,env:v,executable:_=xT()?"bun":"node",executableArgs:S=[],extraArgs:x={},fallbackModel:E,enableFileCheckpointing:T,forkSession:$,hooks:N,includePartialMessages:j,persistSession:q,maxThinkingTokens:H,maxTurns:A,maxBudgetUsd:W,mcpServers:oe,model:he,outputFormat:ne,permissionMode:re="default",allowDangerouslySkipPermissions:F=!1,permissionPromptToolName:R,plugins:z,resume:I,resumeSessionAt:w,stderr:k,strictMcpConfig:M}=s,K=ne?.type==="json_schema"?ne.schema:void 0,J=v;if(J||(J={...process.env}),J.CLAUDE_CODE_ENTRYPOINT||(J.CLAUDE_CODE_ENTRYPOINT="sdk-ts"),T&&(J.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="true"),!c)throw new Error("pathToClaudeCodeExecutable is required");let de={},se=new Map;if(oe)for(let[G,ee]of Object.entries(oe))ee.type==="sdk"&&"instance"in ee?(se.set(G,ee.instance),de[G]={type:"sdk",name:G}):de[G]=ee;let me=typeof t=="string",O=new am({abortController:u,additionalDirectories:l,betas:m,cwd:p,executable:_,executableArgs:S,extraArgs:x,pathToClaudeCodeExecutable:c,env:J,forkSession:$,stderr:k,maxThinkingTokens:H,maxTurns:A,maxBudgetUsd:W,model:he,fallbackModel:E,jsonSchema:K,permissionMode:re,allowDangerouslySkipPermissions:F,permissionPromptToolName:R,continueConversation:b,resume:I,resumeSessionAt:w,settingSources:n??[],allowedTools:f,disallowedTools:h,tools:y,mcpServers:de,strictMcpConfig:M,canUseTool:!!g,hooks:!!N,includePartialMessages:j,persistSession:q,plugins:z,sandbox:a,spawnClaudeCodeProcess:s.spawnClaudeCodeProcess}),C={systemPrompt:i,appendSystemPrompt:o,agents:d},L=new im(O,me,g,N,u,se,K,C);return typeof t=="string"?O.write(JSON.stringify({type:"user",session_id:"",message:{role:"user",content:[{type:"text",text:t}]},parent_tool_use_id:null})+` `):L.streamInput(t),L}var xl=class{dbManager;sessionManager;constructor(e,r){this.dbManager=e,this.sessionManager=r}async startSession(e,r){try{let n=this.findClaudeExecutable(),a=this.getModelId(),s=["Bash","Read","Write","Edit","Grep","Glob","WebFetch","WebSearch","Task","NotebookEdit","AskUserQuestion","TodoWrite"],i=this.createMessageGenerator(e),o=Lk({prompt:i,options:{model:a,disallowedTools:s,abortController:e.abortController,pathToClaudeCodeExecutable:n}});for await(let u of o){if(u.type==="assistant"){let l=u.message.content,d=Array.isArray(l)?l.filter(p=>p.type==="text").map(p=>p.text).join(` -`):typeof l=="string"?l:"",f=d.length,m=e.cumulativeInputTokens+e.cumulativeOutputTokens,g=u.message.usage;g&&(e.cumulativeInputTokens+=g.input_tokens||0,e.cumulativeOutputTokens+=g.output_tokens||0,g.cache_creation_input_tokens&&(e.cumulativeInputTokens+=g.cache_creation_input_tokens),U.debug("SDK","Token usage captured",{sessionId:e.sessionDbId,inputTokens:g.input_tokens,outputTokens:g.output_tokens,cacheCreation:g.cache_creation_input_tokens||0,cacheRead:g.cache_read_input_tokens||0,cumulativeInput:e.cumulativeInputTokens,cumulativeOutput:e.cumulativeOutputTokens}));let b=e.cumulativeInputTokens+e.cumulativeOutputTokens-m;if(f>0){let p=f>100?d.substring(0,100)+"...":d;U.dataOut("SDK",`Response received (${f} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber},p),await this.processSDKResponse(e,d,r,b)}else await this.markMessagesProcessed(e,r)}u.type==="result"&&u.subtype}let c=Date.now()-e.startTime;U.success("SDK","Agent completed",{sessionId:e.sessionDbId,duration:`${(c/1e3).toFixed(1)}s`}),this.dbManager.getSessionStore().markSessionCompleted(e.sessionDbId)}catch(n){throw n.name==="AbortError"?U.warn("SDK","Agent aborted",{sessionId:e.sessionDbId}):U.failure("SDK","Agent error",{sessionDbId:e.sessionDbId},n),n}finally{this.sessionManager.deleteSession(e.sessionDbId).catch(()=>{})}}async*createMessageGenerator(e){let r=$t.getInstance().getActiveMode();yield{type:"user",message:{role:"user",content:e.lastPromptNumber===1?c1(e.project,e.claudeSessionId,e.userPrompt,r):d1(e.userPrompt,e.lastPromptNumber,e.claudeSessionId,r)},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0};for await(let n of this.sessionManager.getMessageIterator(e.sessionDbId))n.type==="observation"?(n.prompt_number!==void 0&&(e.lastPromptNumber=n.prompt_number),yield{type:"user",message:{role:"user",content:u1({id:0,tool_name:n.tool_name,tool_input:JSON.stringify(n.tool_input),tool_output:JSON.stringify(n.tool_response),created_at_epoch:Date.now(),cwd:n.cwd})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0}):n.type==="summarize"&&(yield{type:"user",message:{role:"user",content:l1({id:e.sessionDbId,sdk_session_id:e.sdkSessionId,project:e.project,user_prompt:e.userPrompt,last_user_message:n.last_user_message||"",last_assistant_message:n.last_assistant_message||""},r)},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0})}async processSDKResponse(e,r,n,a){let s=i1(r,e.claudeSessionId);for(let o of s){let{id:c,createdAtEpoch:u}=this.dbManager.getSessionStore().storeObservation(e.claudeSessionId,e.project,o,e.lastPromptNumber,a);U.info("SDK","Observation saved",{sessionId:e.sessionDbId,obsId:c,type:o.type,title:o.title||"(untitled)",filesRead:o.files_read?.length??0,filesModified:o.files_modified?.length??0,concepts:o.concepts?.length??0});let l=Date.now(),d=o.type,f=o.title||"(untitled)";this.dbManager.getChromaSync().syncObservation(c,e.claudeSessionId,e.project,o,e.lastPromptNumber,u,a).then(()=>{let m=Date.now()-l;U.debug("CHROMA","Observation synced",{obsId:c,duration:`${m}ms`,type:d,title:f})}),n&&n.sseBroadcaster&&n.sseBroadcaster.broadcast({type:"new_observation",observation:{id:c,sdk_session_id:e.sdkSessionId,session_id:e.claudeSessionId,type:o.type,title:o.title,subtitle:o.subtitle,text:o.text||null,narrative:o.narrative||null,facts:JSON.stringify(o.facts||[]),concepts:JSON.stringify(o.concepts||[]),files_read:JSON.stringify(o.files||[]),files_modified:JSON.stringify([]),project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:u}})}let i=o1(r,e.sessionDbId);if(i){let{id:o,createdAtEpoch:c}=this.dbManager.getSessionStore().storeSummary(e.claudeSessionId,e.project,i,e.lastPromptNumber,a);U.info("SDK","Summary saved",{sessionId:e.sessionDbId,summaryId:o,request:i.request||"(no request)",hasCompleted:!!i.completed,hasNextSteps:!!i.next_steps});let u=Date.now(),l=i.request||"(no request)";this.dbManager.getChromaSync().syncSummary(o,e.claudeSessionId,e.project,i,e.lastPromptNumber,c,a).then(()=>{let d=Date.now()-u;U.debug("CHROMA","Summary synced",{summaryId:o,duration:`${d}ms`,request:l})}),n&&n.sseBroadcaster&&n.sseBroadcaster.broadcast({type:"new_summary",summary:{id:o,session_id:e.claudeSessionId,request:i.request,investigated:i.investigated,learned:i.learned,completed:i.completed,next_steps:i.next_steps,notes:i.notes,project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:c}})}await this.markMessagesProcessed(e,n)}async markMessagesProcessed(e,r){let n=this.sessionManager.getPendingMessageStore();if(e.pendingProcessingIds.size>0){for(let s of e.pendingProcessingIds)n.markProcessed(s);U.debug("SDK","Messages marked as processed",{sessionId:e.sessionDbId,messageIds:Array.from(e.pendingProcessingIds),count:e.pendingProcessingIds.size}),e.pendingProcessingIds.clear();let a=n.cleanupProcessed(100);a>0&&U.debug("SDK","Cleaned up old processed messages",{deletedCount:a})}r&&typeof r.broadcastProcessingStatus=="function"&&r.broadcastProcessingStatus()}findClaudeExecutable(){let e=ct.loadFromFile(In);if(e.CLAUDE_CODE_PATH){let{existsSync:r}=require("fs");if(!r(e.CLAUDE_CODE_PATH))throw new Error(`CLAUDE_CODE_PATH is set to "${e.CLAUDE_CODE_PATH}" but the file does not exist.`);return e.CLAUDE_CODE_PATH}try{let r=(0,Fk.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}).trim().split(` +`):typeof l=="string"?l:"",f=d.length,m=e.cumulativeInputTokens+e.cumulativeOutputTokens,g=u.message.usage;g&&(e.cumulativeInputTokens+=g.input_tokens||0,e.cumulativeOutputTokens+=g.output_tokens||0,g.cache_creation_input_tokens&&(e.cumulativeInputTokens+=g.cache_creation_input_tokens),U.debug("SDK","Token usage captured",{sessionId:e.sessionDbId,inputTokens:g.input_tokens,outputTokens:g.output_tokens,cacheCreation:g.cache_creation_input_tokens||0,cacheRead:g.cache_read_input_tokens||0,cumulativeInput:e.cumulativeInputTokens,cumulativeOutput:e.cumulativeOutputTokens}));let b=e.cumulativeInputTokens+e.cumulativeOutputTokens-m;if(f>0){let p=f>100?d.substring(0,100)+"...":d;U.dataOut("SDK",`Response received (${f} chars)`,{sessionId:e.sessionDbId,promptNumber:e.lastPromptNumber},p),await this.processSDKResponse(e,d,r,b)}else await this.markMessagesProcessed(e,r)}u.type==="result"&&u.subtype}let c=Date.now()-e.startTime;U.success("SDK","Agent completed",{sessionId:e.sessionDbId,duration:`${(c/1e3).toFixed(1)}s`}),this.dbManager.getSessionStore().markSessionCompleted(e.sessionDbId)}catch(n){throw n.name==="AbortError"?U.warn("SDK","Agent aborted",{sessionId:e.sessionDbId}):U.failure("SDK","Agent error",{sessionDbId:e.sessionDbId},n),n}finally{this.sessionManager.deleteSession(e.sessionDbId).catch(()=>{})}}async*createMessageGenerator(e){let r=kt.getInstance().getActiveMode();yield{type:"user",message:{role:"user",content:e.lastPromptNumber===1?c1(e.project,e.claudeSessionId,e.userPrompt,r):d1(e.userPrompt,e.lastPromptNumber,e.claudeSessionId,r)},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0};for await(let n of this.sessionManager.getMessageIterator(e.sessionDbId))n.type==="observation"?(n.prompt_number!==void 0&&(e.lastPromptNumber=n.prompt_number),yield{type:"user",message:{role:"user",content:u1({id:0,tool_name:n.tool_name,tool_input:JSON.stringify(n.tool_input),tool_output:JSON.stringify(n.tool_response),created_at_epoch:Date.now(),cwd:n.cwd})},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0}):n.type==="summarize"&&(yield{type:"user",message:{role:"user",content:l1({id:e.sessionDbId,sdk_session_id:e.sdkSessionId,project:e.project,user_prompt:e.userPrompt,last_user_message:n.last_user_message||"",last_assistant_message:n.last_assistant_message||""},r)},session_id:e.claudeSessionId,parent_tool_use_id:null,isSynthetic:!0})}async processSDKResponse(e,r,n,a){let s=i1(r,e.claudeSessionId);for(let o of s){let{id:c,createdAtEpoch:u}=this.dbManager.getSessionStore().storeObservation(e.claudeSessionId,e.project,o,e.lastPromptNumber,a);U.info("SDK","Observation saved",{sessionId:e.sessionDbId,obsId:c,type:o.type,title:o.title||"(untitled)",filesRead:o.files_read?.length??0,filesModified:o.files_modified?.length??0,concepts:o.concepts?.length??0});let l=Date.now(),d=o.type,f=o.title||"(untitled)";this.dbManager.getChromaSync().syncObservation(c,e.claudeSessionId,e.project,o,e.lastPromptNumber,u,a).then(()=>{let m=Date.now()-l;U.debug("CHROMA","Observation synced",{obsId:c,duration:`${m}ms`,type:d,title:f})}),n&&n.sseBroadcaster&&n.sseBroadcaster.broadcast({type:"new_observation",observation:{id:c,sdk_session_id:e.sdkSessionId,session_id:e.claudeSessionId,type:o.type,title:o.title,subtitle:o.subtitle,text:o.text||null,narrative:o.narrative||null,facts:JSON.stringify(o.facts||[]),concepts:JSON.stringify(o.concepts||[]),files_read:JSON.stringify(o.files||[]),files_modified:JSON.stringify([]),project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:u}})}let i=o1(r,e.sessionDbId);if(i){let{id:o,createdAtEpoch:c}=this.dbManager.getSessionStore().storeSummary(e.claudeSessionId,e.project,i,e.lastPromptNumber,a);U.info("SDK","Summary saved",{sessionId:e.sessionDbId,summaryId:o,request:i.request||"(no request)",hasCompleted:!!i.completed,hasNextSteps:!!i.next_steps});let u=Date.now(),l=i.request||"(no request)";this.dbManager.getChromaSync().syncSummary(o,e.claudeSessionId,e.project,i,e.lastPromptNumber,c,a).then(()=>{let d=Date.now()-u;U.debug("CHROMA","Summary synced",{summaryId:o,duration:`${d}ms`,request:l})}),n&&n.sseBroadcaster&&n.sseBroadcaster.broadcast({type:"new_summary",summary:{id:o,session_id:e.claudeSessionId,request:i.request,investigated:i.investigated,learned:i.learned,completed:i.completed,next_steps:i.next_steps,notes:i.notes,project:e.project,prompt_number:e.lastPromptNumber,created_at_epoch:c}})}await this.markMessagesProcessed(e,n)}async markMessagesProcessed(e,r){let n=this.sessionManager.getPendingMessageStore();if(e.pendingProcessingIds.size>0){for(let s of e.pendingProcessingIds)n.markProcessed(s);U.debug("SDK","Messages marked as processed",{sessionId:e.sessionDbId,messageIds:Array.from(e.pendingProcessingIds),count:e.pendingProcessingIds.size}),e.pendingProcessingIds.clear();let a=n.cleanupProcessed(100);a>0&&U.debug("SDK","Cleaned up old processed messages",{deletedCount:a})}r&&typeof r.broadcastProcessingStatus=="function"&&r.broadcastProcessingStatus()}findClaudeExecutable(){let e=ct.loadFromFile(In);if(e.CLAUDE_CODE_PATH){let{existsSync:r}=require("fs");if(!r(e.CLAUDE_CODE_PATH))throw new Error(`CLAUDE_CODE_PATH is set to "${e.CLAUDE_CODE_PATH}" but the file does not exist.`);return e.CLAUDE_CODE_PATH}try{let r=(0,Fk.execSync)(process.platform==="win32"?"where claude":"which claude",{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","ignore"]}).trim().split(` `)[0].trim();if(r)return r}catch(r){U.debug("SDK","Claude executable auto-detection failed",r)}throw new Error(`Claude executable not found. Please either: 1. Add "claude" to your system PATH, or 2. Set CLAUDE_CODE_PATH in ~/.claude-mem/settings.json`)}getModelId(){let e=Uk.default.join((0,zk.homedir)(),".claude-mem","settings.json");return ct.loadFromFile(e).CLAUDE_MEM_MODEL}};var wl=class{dbManager;constructor(e){this.dbManager=e}stripProjectPath(e,r){let n=`/${r}/`,a=e.indexOf(n);return a!==-1?e.substring(a+n.length):e}stripProjectPaths(e,r){if(!e)return e;try{let a=JSON.parse(e).map(s=>this.stripProjectPath(s,r));return JSON.stringify(a)}catch{return e}}sanitizeObservation(e){return{...e,files_read:this.stripProjectPaths(e.files_read,e.project),files_modified:this.stripProjectPaths(e.files_modified,e.project)}}getObservations(e,r,n){let a=this.paginate("observations","id, sdk_session_id, project, type, title, subtitle, narrative, text, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch",e,r,n);return{...a,items:a.items.map(s=>this.sanitizeObservation(s))}}getSummaries(e,r,n){let a=this.dbManager.getSessionStore().db,s=` @@ -1060,7 +1060,7 @@ To enable semantic search: 2. Restart the worker: npm run worker:restart Note: You can still use filter-only searches (date ranges, types, files) without a query term.`}]}:{content:[{type:"text",text:`No results found matching "${n}"`}]};let y=[...l.map(E=>({type:"observation",data:E,epoch:E.created_at_epoch,created_at:E.created_at})),...d.map(E=>({type:"session",data:E,epoch:E.created_at_epoch,created_at:E.created_at})),...f.map(E=>({type:"prompt",data:E,epoch:E.created_at_epoch,created_at:E.created_at}))];u.orderBy==="date_desc"?y.sort((E,T)=>T.epoch-E.epoch):u.orderBy==="date_asc"&&y.sort((E,T)=>E.epoch-T.epoch);let v=y.slice(0,u.limit||20),_=process.cwd(),S=Hk(v,E=>E.created_at),x=[];x.push(`Found ${h} result(s) matching "${n}" (${l.length} obs, ${d.length} sessions, ${f.length} prompts)`),x.push("");for(let[E,T]of S){x.push(`### ${E}`),x.push("");let $=new Map;for(let N of T){let j="General";N.type==="observation"&&(j=Fn(N.data.files_modified,_)),$.has(j)||$.set(j,[]),$.get(j).push(N)}for(let[N,j]of $){x.push(`**${N}**`),x.push(this.formatter.formatSearchTableHeader());let q="";for(let H of j)if(H.type==="observation"){let A=this.formatter.formatObservationSearchRow(H.data,q);x.push(A.row),q=A.time}else if(H.type==="session"){let A=this.formatter.formatSessionSearchRow(H.data,q);x.push(A.row),q=A.time}else{let A=this.formatter.formatUserPromptSearchRow(H.data,q);x.push(A.row),q=A.time}x.push("")}}return{content:[{type:"text",text:x.join(` -`)}]}}catch(r){return{content:[{type:"text",text:`Search failed: ${r.message}`}],isError:!0}}}async timeline(e){try{let{anchor:r,query:n,depth_before:a=10,depth_after:s=10,project:i}=e,o=process.cwd();if(!r&&!n)return{content:[{type:"text",text:'Error: Must provide either "anchor" or "query" parameter'}],isError:!0};if(r&&n)return{content:[{type:"text",text:'Error: Cannot provide both "anchor" and "query" parameters. Use one or the other.'}],isError:!0};let c,u,l;if(n){let p=[];if(this.chromaSync)try{U.debug("SEARCH","Using hybrid semantic search for timeline query",{});let y=await this.queryChroma(n,100);if(U.debug("SEARCH","Chroma returned semantic matches for timeline",{matchCount:y?.ids?.length??0}),y?.ids&&y.ids.length>0){let v=Date.now()-ui,_=y.ids.filter((S,x)=>{let E=y.metadatas[x];return E&&E.created_at_epoch>v});_.length>0&&(p=this.sessionStore.getObservationsByIds(_,{orderBy:"date_desc",limit:1}))}}catch(y){U.debug("SEARCH","Chroma query failed - no results (FTS5 fallback removed)",{error:y.message})}if(p.length===0)return{content:[{type:"text",text:`No observations found matching "${n}". Try a different search query.`}]};let h=p[0];c=h.id,u=h.created_at_epoch,U.debug("SEARCH","Query mode: Using observation as timeline anchor",{observationId:h.id}),l=this.sessionStore.getTimelineAroundObservation(h.id,h.created_at_epoch,a,s,i)}else if(typeof r=="number"){let p=this.sessionStore.getObservationById(r);if(!p)return{content:[{type:"text",text:`Observation #${r} not found`}],isError:!0};c=r,u=p.created_at_epoch,l=this.sessionStore.getTimelineAroundObservation(r,u,a,s,i)}else if(typeof r=="string")if(r.startsWith("S")||r.startsWith("#S")){let p=r.replace(/^#?S/,""),h=parseInt(p,10),y=this.sessionStore.getSessionSummariesByIds([h]);if(y.length===0)return{content:[{type:"text",text:`Session #${h} not found`}],isError:!0};u=y[0].created_at_epoch,c=`S${h}`,l=this.sessionStore.getTimelineAroundTimestamp(u,a,s,i)}else{let p=new Date(r);if(isNaN(p.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${r}`}],isError:!0};u=p.getTime(),c=r,l=this.sessionStore.getTimelineAroundTimestamp(u,a,s,i)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let d=[...(l.observations||[]).map(p=>({type:"observation",data:p,epoch:p.created_at_epoch})),...(l.sessions||[]).map(p=>({type:"session",data:p,epoch:p.created_at_epoch})),...(l.prompts||[]).map(p=>({type:"prompt",data:p,epoch:p.created_at_epoch}))];d.sort((p,h)=>p.epoch-h.epoch);let f=this.timelineService.filterByDepth(d,c,u,a,s);if(!f||f.length===0)return{content:[{type:"text",text:n?`Found observation matching "${n}", but no timeline context available (${a} records before, ${s} records after).`:`No context found around anchor (${a} records before, ${s} records after)`}]};let m=[];if(n){let p=f.find(y=>y.type==="observation"&&y.data.id===c),h=p&&p.type==="observation"?p.data.title||"Untitled":"Unknown";m.push(`# Timeline for query: "${n}"`),m.push(`**Anchor:** Observation #${c} - ${h}`)}else m.push(`# Timeline around anchor: ${c}`);m.push(`**Window:** ${a} records before \u2192 ${s} records after | **Items:** ${f?.length??0}`),m.push("");let g=new Map;for(let p of f){let h=Ln(p.epoch);g.has(h)||g.set(h,[]),g.get(h).push(p)}let b=Array.from(g.entries()).sort((p,h)=>{let y=new Date(p[0]).getTime(),v=new Date(h[0]).getTime();return y-v});for(let[p,h]of b){m.push(`### ${p}`),m.push("");let y=null,v="",_=!1;for(let S of h){let x=typeof c=="number"&&S.type==="observation"&&S.data.id===c||typeof c=="string"&&c.startsWith("S")&&S.type==="session"&&`S${S.data.id}`===c;if(S.type==="session"){_&&(m.push(""),_=!1,y=null,v="");let E=S.data,T=E.request||"Session summary",$=x?" \u2190 **ANCHOR**":"";m.push(`**\u{1F3AF} #S${E.id}** ${T} (${xa(S.epoch)})${$}`),m.push("")}else if(S.type==="prompt"){_&&(m.push(""),_=!1,y=null,v="");let E=S.data,T=E.prompt_text.length>100?E.prompt_text.substring(0,100)+"...":E.prompt_text;m.push(`**\u{1F4AC} User Prompt #${E.prompt_number}** (${xa(S.epoch)})`),m.push(`> ${T}`),m.push("")}else if(S.type==="observation"){let E=S.data,T=Fn(E.files_modified,o);T!==y&&(_&&m.push(""),m.push(`**${T}**`),m.push("| ID | Time | T | Title | Tokens |"),m.push("|----|------|---|-------|--------|"),y=T,_=!0,v="");let $=$t.getInstance().getTypeIcon(E.type),N=ci(S.epoch),j=E.title||"Untitled",q=El(E.narrative),A=N!==v?N:"\u2033";v=N;let W=x?" \u2190 **ANCHOR**":"";m.push(`| #${E.id} | ${A} | ${$} | ${j}${W} | ~${q} |`)}}_&&m.push("")}return{content:[{type:"text",text:m.join(` +`)}]}}catch(r){return{content:[{type:"text",text:`Search failed: ${r.message}`}],isError:!0}}}async timeline(e){try{let{anchor:r,query:n,depth_before:a=10,depth_after:s=10,project:i}=e,o=process.cwd();if(!r&&!n)return{content:[{type:"text",text:'Error: Must provide either "anchor" or "query" parameter'}],isError:!0};if(r&&n)return{content:[{type:"text",text:'Error: Cannot provide both "anchor" and "query" parameters. Use one or the other.'}],isError:!0};let c,u,l;if(n){let p=[];if(this.chromaSync)try{U.debug("SEARCH","Using hybrid semantic search for timeline query",{});let y=await this.queryChroma(n,100);if(U.debug("SEARCH","Chroma returned semantic matches for timeline",{matchCount:y?.ids?.length??0}),y?.ids&&y.ids.length>0){let v=Date.now()-ui,_=y.ids.filter((S,x)=>{let E=y.metadatas[x];return E&&E.created_at_epoch>v});_.length>0&&(p=this.sessionStore.getObservationsByIds(_,{orderBy:"date_desc",limit:1}))}}catch(y){U.debug("SEARCH","Chroma query failed - no results (FTS5 fallback removed)",{error:y.message})}if(p.length===0)return{content:[{type:"text",text:`No observations found matching "${n}". Try a different search query.`}]};let h=p[0];c=h.id,u=h.created_at_epoch,U.debug("SEARCH","Query mode: Using observation as timeline anchor",{observationId:h.id}),l=this.sessionStore.getTimelineAroundObservation(h.id,h.created_at_epoch,a,s,i)}else if(typeof r=="number"){let p=this.sessionStore.getObservationById(r);if(!p)return{content:[{type:"text",text:`Observation #${r} not found`}],isError:!0};c=r,u=p.created_at_epoch,l=this.sessionStore.getTimelineAroundObservation(r,u,a,s,i)}else if(typeof r=="string")if(r.startsWith("S")||r.startsWith("#S")){let p=r.replace(/^#?S/,""),h=parseInt(p,10),y=this.sessionStore.getSessionSummariesByIds([h]);if(y.length===0)return{content:[{type:"text",text:`Session #${h} not found`}],isError:!0};u=y[0].created_at_epoch,c=`S${h}`,l=this.sessionStore.getTimelineAroundTimestamp(u,a,s,i)}else{let p=new Date(r);if(isNaN(p.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${r}`}],isError:!0};u=p.getTime(),c=r,l=this.sessionStore.getTimelineAroundTimestamp(u,a,s,i)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let d=[...(l.observations||[]).map(p=>({type:"observation",data:p,epoch:p.created_at_epoch})),...(l.sessions||[]).map(p=>({type:"session",data:p,epoch:p.created_at_epoch})),...(l.prompts||[]).map(p=>({type:"prompt",data:p,epoch:p.created_at_epoch}))];d.sort((p,h)=>p.epoch-h.epoch);let f=this.timelineService.filterByDepth(d,c,u,a,s);if(!f||f.length===0)return{content:[{type:"text",text:n?`Found observation matching "${n}", but no timeline context available (${a} records before, ${s} records after).`:`No context found around anchor (${a} records before, ${s} records after)`}]};let m=[];if(n){let p=f.find(y=>y.type==="observation"&&y.data.id===c),h=p&&p.type==="observation"?p.data.title||"Untitled":"Unknown";m.push(`# Timeline for query: "${n}"`),m.push(`**Anchor:** Observation #${c} - ${h}`)}else m.push(`# Timeline around anchor: ${c}`);m.push(`**Window:** ${a} records before \u2192 ${s} records after | **Items:** ${f?.length??0}`),m.push("");let g=new Map;for(let p of f){let h=Ln(p.epoch);g.has(h)||g.set(h,[]),g.get(h).push(p)}let b=Array.from(g.entries()).sort((p,h)=>{let y=new Date(p[0]).getTime(),v=new Date(h[0]).getTime();return y-v});for(let[p,h]of b){m.push(`### ${p}`),m.push("");let y=null,v="",_=!1;for(let S of h){let x=typeof c=="number"&&S.type==="observation"&&S.data.id===c||typeof c=="string"&&c.startsWith("S")&&S.type==="session"&&`S${S.data.id}`===c;if(S.type==="session"){_&&(m.push(""),_=!1,y=null,v="");let E=S.data,T=E.request||"Session summary",$=x?" \u2190 **ANCHOR**":"";m.push(`**\u{1F3AF} #S${E.id}** ${T} (${xa(S.epoch)})${$}`),m.push("")}else if(S.type==="prompt"){_&&(m.push(""),_=!1,y=null,v="");let E=S.data,T=E.prompt_text.length>100?E.prompt_text.substring(0,100)+"...":E.prompt_text;m.push(`**\u{1F4AC} User Prompt #${E.prompt_number}** (${xa(S.epoch)})`),m.push(`> ${T}`),m.push("")}else if(S.type==="observation"){let E=S.data,T=Fn(E.files_modified,o);T!==y&&(_&&m.push(""),m.push(`**${T}**`),m.push("| ID | Time | T | Title | Tokens |"),m.push("|----|------|---|-------|--------|"),y=T,_=!0,v="");let $=kt.getInstance().getTypeIcon(E.type),N=ci(S.epoch),j=E.title||"Untitled",q=El(E.narrative),A=N!==v?N:"\u2033";v=N;let W=x?" \u2190 **ANCHOR**":"";m.push(`| #${E.id} | ${A} | ${$} | ${j}${W} | ~${q} |`)}}_&&m.push("")}return{content:[{type:"text",text:m.join(` `)}]}}catch(r){return{content:[{type:"text",text:`Timeline query failed: ${r.message}`}],isError:!0}}}async decisions(e){try{let r=this.normalizeParams(e),{query:n,...a}=r,s=[];if(this.chromaSync)try{if(n){U.debug("SEARCH","Using Chroma semantic search with type=decision filter",{});let u=(await this.queryChroma(n,Math.min((a.limit||20)*2,100),{type:"decision"})).ids;u.length>0&&(s=this.sessionStore.getObservationsByIds(u,{...a,type:"decision"}),s.sort((l,d)=>u.indexOf(l.id)-u.indexOf(d.id)))}else{U.debug("SEARCH","Using metadata-first + semantic ranking for decisions",{});let c=this.sessionSearch.findByType("decision",a);if(c.length>0){let u=c.map(f=>f.id),l=await this.queryChroma("decision",Math.min(u.length,100)),d=[];for(let f of l.ids)u.includes(f)&&!d.includes(f)&&d.push(f);d.length>0&&(s=this.sessionStore.getObservationsByIds(d,{limit:a.limit||20}),s.sort((f,m)=>d.indexOf(f.id)-d.indexOf(m.id)))}}}catch(c){U.debug("SEARCH","Chroma search failed, using SQLite fallback",{error:c.message})}if(s.length===0&&(s=this.sessionSearch.findByType("decision",a)),s.length===0)return{content:[{type:"text",text:"No decision observations found"}]};let i=`Found ${s.length} decision(s) ${this.formatter.formatTableHeader()}`,o=s.map((c,u)=>this.formatter.formatObservationIndex(c,u));return{content:[{type:"text",text:i+` @@ -1100,9 +1100,9 @@ ${this.formatter.formatTableHeader()}`,c=i.map((u,l)=>this.formatter.formatObser `)}]}}catch(r){return{content:[{type:"text",text:`Search failed: ${r.message}`}],isError:!0}}}async getRecentContext(e){try{let r=e.project||(0,Bk.basename)(process.cwd()),n=e.limit||3,a=this.sessionStore.getRecentSessionsWithStatus(r,n);if(a.length===0)return{content:[{type:"text",text:`# Recent Session Context No previous sessions found for project "${r}".`}]};let s=[];s.push("# Recent Session Context"),s.push(""),s.push(`Showing last ${a.length} session(s) for **${r}**:`),s.push("");for(let i of a)if(i.sdk_session_id){if(s.push("---"),s.push(""),i.has_summary){let o=this.sessionStore.getSummaryForSession(i.sdk_session_id);if(o){let c=o.prompt_number?` (Prompt #${o.prompt_number})`:"";if(s.push(`**Summary${c}**`),s.push(""),o.request&&s.push(`**Request:** ${o.request}`),o.completed&&s.push(`**Completed:** ${o.completed}`),o.learned&&s.push(`**Learned:** ${o.learned}`),o.next_steps&&s.push(`**Next Steps:** ${o.next_steps}`),o.files_read)try{let l=JSON.parse(o.files_read);Array.isArray(l)&&l.length>0&&s.push(`**Files Read:** ${l.join(", ")}`)}catch{o.files_read.trim()&&s.push(`**Files Read:** ${o.files_read}`)}if(o.files_edited)try{let l=JSON.parse(o.files_edited);Array.isArray(l)&&l.length>0&&s.push(`**Files Edited:** ${l.join(", ")}`)}catch{o.files_edited.trim()&&s.push(`**Files Edited:** ${o.files_edited}`)}let u=new Date(o.created_at).toLocaleString();s.push(`**Date:** ${u}`)}}else if(i.status==="active"){s.push("**In Progress**"),s.push(""),i.user_prompt&&s.push(`**Request:** ${i.user_prompt}`);let o=this.sessionStore.getObservationsForSession(i.sdk_session_id);if(o.length>0){s.push(""),s.push(`**Observations (${o.length}):**`);for(let u of o)s.push(`- ${u.title}`)}else s.push(""),s.push("*No observations yet*");s.push(""),s.push("**Status:** Active - summary pending");let c=new Date(i.started_at).toLocaleString();s.push(`**Date:** ${c}`)}else{s.push(`**${i.status.charAt(0).toUpperCase()+i.status.slice(1)}**`),s.push(""),i.user_prompt&&s.push(`**Request:** ${i.user_prompt}`),s.push(""),s.push(`**Status:** ${i.status} - no summary available`);let o=new Date(i.started_at).toLocaleString();s.push(`**Date:** ${o}`)}s.push("")}return{content:[{type:"text",text:s.join(` -`)}]}}catch(r){return{content:[{type:"text",text:`Failed to get recent context: ${r.message}`}],isError:!0}}}async getContextTimeline(e){try{let{anchor:r,depth_before:n=10,depth_after:a=10,project:s}=e,i=process.cwd(),o,c=r,u;if(typeof r=="number"){let b=this.sessionStore.getObservationById(r);if(!b)return{content:[{type:"text",text:`Observation #${r} not found`}],isError:!0};o=b.created_at_epoch,u=this.sessionStore.getTimelineAroundObservation(r,o,n,a,s)}else if(typeof r=="string")if(r.startsWith("S")||r.startsWith("#S")){let b=r.replace(/^#?S/,""),p=parseInt(b,10),h=this.sessionStore.getSessionSummariesByIds([p]);if(h.length===0)return{content:[{type:"text",text:`Session #${p} not found`}],isError:!0};o=h[0].created_at_epoch,c=`S${p}`,u=this.sessionStore.getTimelineAroundTimestamp(o,n,a,s)}else{let b=new Date(r);if(isNaN(b.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${r}`}],isError:!0};o=b.getTime(),u=this.sessionStore.getTimelineAroundTimestamp(o,n,a,s)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let l=[...u.observations.map(b=>({type:"observation",data:b,epoch:b.created_at_epoch})),...u.sessions.map(b=>({type:"session",data:b,epoch:b.created_at_epoch})),...u.prompts.map(b=>({type:"prompt",data:b,epoch:b.created_at_epoch}))];l.sort((b,p)=>b.epoch-p.epoch);let d=this.timelineService.filterByDepth(l,c,o,n,a);if(!d||d.length===0)return{content:[{type:"text",text:`No context found around ${new Date(o).toLocaleString()} (${n} records before, ${a} records after)`}]};let f=[];f.push(`# Timeline around anchor: ${c}`),f.push(`**Window:** ${n} records before \u2192 ${a} records after | **Items:** ${d?.length??0}`),f.push("");let m=new Map;for(let b of d){let p=Ln(b.epoch);m.has(p)||m.set(p,[]),m.get(p).push(b)}let g=Array.from(m.entries()).sort((b,p)=>{let h=new Date(b[0]).getTime(),y=new Date(p[0]).getTime();return h-y});for(let[b,p]of g){f.push(`### ${b}`),f.push("");let h=null,y="",v=!1;for(let _ of p){let S=typeof c=="number"&&_.type==="observation"&&_.data.id===c||typeof c=="string"&&c.startsWith("S")&&_.type==="session"&&`S${_.data.id}`===c;if(_.type==="session"){v&&(f.push(""),v=!1,h=null,y="");let x=_.data,E=x.request||"Session summary",T=S?" \u2190 **ANCHOR**":"";f.push(`**\u{1F3AF} #S${x.id}** ${E} (${xa(_.epoch)})${T}`),f.push("")}else if(_.type==="prompt"){v&&(f.push(""),v=!1,h=null,y="");let x=_.data,E=x.prompt_text.length>100?x.prompt_text.substring(0,100)+"...":x.prompt_text;f.push(`**\u{1F4AC} User Prompt #${x.prompt_number}** (${xa(_.epoch)})`),f.push(`> ${E}`),f.push("")}else if(_.type==="observation"){let x=_.data,E=Fn(x.files_modified,i);E!==h&&(v&&f.push(""),f.push(`**${E}**`),f.push("| ID | Time | T | Title | Tokens |"),f.push("|----|------|---|-------|--------|"),h=E,v=!0,y="");let T=$t.getInstance().getTypeIcon(x.type),$=ci(_.epoch),N=x.title||"Untitled",j=El(x.narrative),H=$!==y?$:"\u2033";y=$;let A=S?" \u2190 **ANCHOR**":"";f.push(`| #${x.id} | ${H} | ${T} | ${N}${A} | ~${j} |`)}}v&&f.push("")}return{content:[{type:"text",text:f.join(` +`)}]}}catch(r){return{content:[{type:"text",text:`Failed to get recent context: ${r.message}`}],isError:!0}}}async getContextTimeline(e){try{let{anchor:r,depth_before:n=10,depth_after:a=10,project:s}=e,i=process.cwd(),o,c=r,u;if(typeof r=="number"){let b=this.sessionStore.getObservationById(r);if(!b)return{content:[{type:"text",text:`Observation #${r} not found`}],isError:!0};o=b.created_at_epoch,u=this.sessionStore.getTimelineAroundObservation(r,o,n,a,s)}else if(typeof r=="string")if(r.startsWith("S")||r.startsWith("#S")){let b=r.replace(/^#?S/,""),p=parseInt(b,10),h=this.sessionStore.getSessionSummariesByIds([p]);if(h.length===0)return{content:[{type:"text",text:`Session #${p} not found`}],isError:!0};o=h[0].created_at_epoch,c=`S${p}`,u=this.sessionStore.getTimelineAroundTimestamp(o,n,a,s)}else{let b=new Date(r);if(isNaN(b.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${r}`}],isError:!0};o=b.getTime(),u=this.sessionStore.getTimelineAroundTimestamp(o,n,a,s)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let l=[...u.observations.map(b=>({type:"observation",data:b,epoch:b.created_at_epoch})),...u.sessions.map(b=>({type:"session",data:b,epoch:b.created_at_epoch})),...u.prompts.map(b=>({type:"prompt",data:b,epoch:b.created_at_epoch}))];l.sort((b,p)=>b.epoch-p.epoch);let d=this.timelineService.filterByDepth(l,c,o,n,a);if(!d||d.length===0)return{content:[{type:"text",text:`No context found around ${new Date(o).toLocaleString()} (${n} records before, ${a} records after)`}]};let f=[];f.push(`# Timeline around anchor: ${c}`),f.push(`**Window:** ${n} records before \u2192 ${a} records after | **Items:** ${d?.length??0}`),f.push("");let m=new Map;for(let b of d){let p=Ln(b.epoch);m.has(p)||m.set(p,[]),m.get(p).push(b)}let g=Array.from(m.entries()).sort((b,p)=>{let h=new Date(b[0]).getTime(),y=new Date(p[0]).getTime();return h-y});for(let[b,p]of g){f.push(`### ${b}`),f.push("");let h=null,y="",v=!1;for(let _ of p){let S=typeof c=="number"&&_.type==="observation"&&_.data.id===c||typeof c=="string"&&c.startsWith("S")&&_.type==="session"&&`S${_.data.id}`===c;if(_.type==="session"){v&&(f.push(""),v=!1,h=null,y="");let x=_.data,E=x.request||"Session summary",T=S?" \u2190 **ANCHOR**":"";f.push(`**\u{1F3AF} #S${x.id}** ${E} (${xa(_.epoch)})${T}`),f.push("")}else if(_.type==="prompt"){v&&(f.push(""),v=!1,h=null,y="");let x=_.data,E=x.prompt_text.length>100?x.prompt_text.substring(0,100)+"...":x.prompt_text;f.push(`**\u{1F4AC} User Prompt #${x.prompt_number}** (${xa(_.epoch)})`),f.push(`> ${E}`),f.push("")}else if(_.type==="observation"){let x=_.data,E=Fn(x.files_modified,i);E!==h&&(v&&f.push(""),f.push(`**${E}**`),f.push("| ID | Time | T | Title | Tokens |"),f.push("|----|------|---|-------|--------|"),h=E,v=!0,y="");let T=kt.getInstance().getTypeIcon(x.type),$=ci(_.epoch),N=x.title||"Untitled",j=El(x.narrative),H=$!==y?$:"\u2033";y=$;let A=S?" \u2190 **ANCHOR**":"";f.push(`| #${x.id} | ${H} | ${T} | ${N}${A} | ~${j} |`)}}v&&f.push("")}return{content:[{type:"text",text:f.join(` `)}]}}catch(r){return{content:[{type:"text",text:`Timeline query failed: ${r.message}`}],isError:!0}}}async getTimelineByQuery(e){try{let{query:r,mode:n="auto",depth_before:a=10,depth_after:s=10,limit:i=5,project:o}=e,c=process.cwd(),u=[];if(this.chromaSync)try{U.debug("SEARCH","Using hybrid semantic search for timeline query",{});let l=await this.queryChroma(r,100);if(U.debug("SEARCH","Chroma returned semantic matches for timeline",{matchCount:l.ids.length}),l.ids.length>0){let d=Date.now()-ui,f=l.ids.filter((m,g)=>{let b=l.metadatas[g];return b&&b.created_at_epoch>d});U.debug("SEARCH","Results within 90-day window",{count:f.length}),f.length>0&&(u=this.sessionStore.getObservationsByIds(f,{orderBy:"date_desc",limit:n==="auto"?1:i}),U.debug("SEARCH","Hydrated observations from SQLite",{count:u.length}))}}catch(l){U.debug("SEARCH","Chroma query failed - no results (FTS5 fallback removed)",{error:l.message})}if(u.length===0)return{content:[{type:"text",text:`No observations found matching "${r}". Try a different search query.`}]};if(n==="interactive"){let l=[];l.push("# Timeline Anchor Search Results"),l.push(""),l.push(`Found ${u.length} observation(s) matching "${r}"`),l.push(""),l.push("To get timeline context around any of these observations, use the `get_context_timeline` tool with the observation ID as the anchor."),l.push(""),l.push(`**Top ${u.length} matches:**`),l.push("");for(let d=0;d({type:"observation",data:h,epoch:h.created_at_epoch})),...(d.sessions||[]).map(h=>({type:"session",data:h,epoch:h.created_at_epoch})),...(d.prompts||[]).map(h=>({type:"prompt",data:h,epoch:h.created_at_epoch}))];f.sort((h,y)=>h.epoch-y.epoch);let m=this.timelineService.filterByDepth(f,l.id,0,a,s);if(!m||m.length===0)return{content:[{type:"text",text:`Found observation #${l.id} matching "${r}", but no timeline context available (${a} records before, ${s} records after).`}]};let g=[];g.push(`# Timeline for query: "${r}"`),g.push(`**Anchor:** Observation #${l.id} - ${l.title||"Untitled"}`),g.push(`**Window:** ${a} records before \u2192 ${s} records after | **Items:** ${m?.length??0}`),g.push("");let b=new Map;for(let h of m){let y=Ln(h.epoch);b.has(y)||b.set(y,[]),b.get(y).push(h)}let p=Array.from(b.entries()).sort((h,y)=>{let v=new Date(h[0]).getTime(),_=new Date(y[0]).getTime();return v-_});for(let[h,y]of p){g.push(`### ${h}`),g.push("");let v=null,_="",S=!1;for(let x of y){let E=x.type==="observation"&&x.data.id===l.id;if(x.type==="session"){S&&(g.push(""),S=!1,v=null,_="");let T=x.data,$=T.request||"Session summary";g.push(`**\u{1F3AF} #S${T.id}** ${$} (${xa(x.epoch)})`),g.push("")}else if(x.type==="prompt"){S&&(g.push(""),S=!1,v=null,_="");let T=x.data,$=T.prompt_text.length>100?T.prompt_text.substring(0,100)+"...":T.prompt_text;g.push(`**\u{1F4AC} User Prompt #${T.prompt_number}** (${xa(x.epoch)})`),g.push(`> ${$}`),g.push("")}else if(x.type==="observation"){let T=x.data,$=Fn(T.files_modified,c);$!==v&&(S&&g.push(""),g.push(`**${$}**`),g.push("| ID | Time | T | Title | Tokens |"),g.push("|----|------|---|-------|--------|"),v=$,S=!0,_="");let N=$t.getInstance().getTypeIcon(T.type),j=ci(x.epoch),q=T.title||"Untitled",H=El(T.narrative),W=j!==_?j:"\u2033";_=j;let oe=E?" \u2190 **ANCHOR**":"";g.push(`| #${T.id} | ${W} | ${N} | ${q}${oe} | ~${H} |`)}}S&&g.push("")}return{content:[{type:"text",text:g.join(` +`)}]}}else{let l=u[0];U.debug("SEARCH","Auto mode: Using observation as timeline anchor",{observationId:l.id});let d=this.sessionStore.getTimelineAroundObservation(l.id,l.created_at_epoch,a,s,o),f=[...(d.observations||[]).map(h=>({type:"observation",data:h,epoch:h.created_at_epoch})),...(d.sessions||[]).map(h=>({type:"session",data:h,epoch:h.created_at_epoch})),...(d.prompts||[]).map(h=>({type:"prompt",data:h,epoch:h.created_at_epoch}))];f.sort((h,y)=>h.epoch-y.epoch);let m=this.timelineService.filterByDepth(f,l.id,0,a,s);if(!m||m.length===0)return{content:[{type:"text",text:`Found observation #${l.id} matching "${r}", but no timeline context available (${a} records before, ${s} records after).`}]};let g=[];g.push(`# Timeline for query: "${r}"`),g.push(`**Anchor:** Observation #${l.id} - ${l.title||"Untitled"}`),g.push(`**Window:** ${a} records before \u2192 ${s} records after | **Items:** ${m?.length??0}`),g.push("");let b=new Map;for(let h of m){let y=Ln(h.epoch);b.has(y)||b.set(y,[]),b.get(y).push(h)}let p=Array.from(b.entries()).sort((h,y)=>{let v=new Date(h[0]).getTime(),_=new Date(y[0]).getTime();return v-_});for(let[h,y]of p){g.push(`### ${h}`),g.push("");let v=null,_="",S=!1;for(let x of y){let E=x.type==="observation"&&x.data.id===l.id;if(x.type==="session"){S&&(g.push(""),S=!1,v=null,_="");let T=x.data,$=T.request||"Session summary";g.push(`**\u{1F3AF} #S${T.id}** ${$} (${xa(x.epoch)})`),g.push("")}else if(x.type==="prompt"){S&&(g.push(""),S=!1,v=null,_="");let T=x.data,$=T.prompt_text.length>100?T.prompt_text.substring(0,100)+"...":T.prompt_text;g.push(`**\u{1F4AC} User Prompt #${T.prompt_number}** (${xa(x.epoch)})`),g.push(`> ${$}`),g.push("")}else if(x.type==="observation"){let T=x.data,$=Fn(T.files_modified,c);$!==v&&(S&&g.push(""),g.push(`**${$}**`),g.push("| ID | Time | T | Title | Tokens |"),g.push("|----|------|---|-------|--------|"),v=$,S=!0,_="");let N=kt.getInstance().getTypeIcon(T.type),j=ci(x.epoch),q=T.title||"Untitled",H=El(T.narrative),W=j!==_?j:"\u2033";_=j;let oe=E?" \u2190 **ANCHOR**":"";g.push(`| #${T.id} | ${W} | ${N} | ${q}${oe} | ~${H} |`)}}S&&g.push("")}return{content:[{type:"text",text:g.join(` `)}]}}}catch(r){return{content:[{type:"text",text:`Timeline query failed: ${r.message}`}],isError:!0}}}};La();var k7=4,kl=class{formatSearchTips(){return` --- \u{1F4A1} Search Strategy: @@ -1113,16 +1113,16 @@ No previous sessions found for project "${r}".`}]};let s=[];s.push("# Recent Ses Tips: \u2022 Filter by type: obs_type="bugfix,feature" \u2022 Filter by date: dateStart="2025-01-01" -\u2022 Sort: orderBy="date_desc" or "date_asc"`}formatTime(e){return new Date(e).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}estimateReadTokens(e){let r=(e.title?.length||0)+(e.subtitle?.length||0)+(e.narrative?.length||0)+(e.facts?.length||0);return Math.ceil(r/k7)}formatObservationIndex(e,r){let n=`#${e.id}`,a=this.formatTime(e.created_at_epoch),s=$t.getInstance().getTypeIcon(e.type),i=e.title||"Untitled",o=this.estimateReadTokens(e),c=$t.getInstance().getWorkEmoji(e.type),u=e.discovery_tokens||0,l=u>0?`${c} ${u}`:"-";return`| ${n} | ${a} | ${s} | ${i} | ~${o} | ${l} |`}formatSessionIndex(e,r){let n=`#S${e.id}`,a=this.formatTime(e.created_at_epoch),s="\u{1F3AF}",i=e.request||`Session ${e.sdk_session_id?.substring(0,8)||"unknown"}`;return`| ${n} | ${a} | ${s} | ${i} | - | - |`}formatUserPromptIndex(e,r){let n=`#P${e.id}`,a=this.formatTime(e.created_at_epoch),s="\u{1F4AC}",i=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return`| ${n} | ${a} | ${s} | ${i} | - | - |`}formatTableHeader(){return`| ID | Time | T | Title | Read | Work | +\u2022 Sort: orderBy="date_desc" or "date_asc"`}formatTime(e){return new Date(e).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}estimateReadTokens(e){let r=(e.title?.length||0)+(e.subtitle?.length||0)+(e.narrative?.length||0)+(e.facts?.length||0);return Math.ceil(r/k7)}formatObservationIndex(e,r){let n=`#${e.id}`,a=this.formatTime(e.created_at_epoch),s=kt.getInstance().getTypeIcon(e.type),i=e.title||"Untitled",o=this.estimateReadTokens(e),c=kt.getInstance().getWorkEmoji(e.type),u=e.discovery_tokens||0,l=u>0?`${c} ${u}`:"-";return`| ${n} | ${a} | ${s} | ${i} | ~${o} | ${l} |`}formatSessionIndex(e,r){let n=`#S${e.id}`,a=this.formatTime(e.created_at_epoch),s="\u{1F3AF}",i=e.request||`Session ${e.sdk_session_id?.substring(0,8)||"unknown"}`;return`| ${n} | ${a} | ${s} | ${i} | - | - |`}formatUserPromptIndex(e,r){let n=`#P${e.id}`,a=this.formatTime(e.created_at_epoch),s="\u{1F4AC}",i=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return`| ${n} | ${a} | ${s} | ${i} | - | - |`}formatTableHeader(){return`| ID | Time | T | Title | Read | Work | |-----|------|---|-------|------|------|`}formatSearchTableHeader(){return`| ID | Time | T | Title | Read | -|----|------|---|-------|------|`}formatObservationSearchRow(e,r){let n=`#${e.id}`,a=this.formatTime(e.created_at_epoch),s=$t.getInstance().getTypeIcon(e.type),i=e.title||"Untitled",o=this.estimateReadTokens(e);return{row:`| ${n} | ${a===r?"\u2033":a} | ${s} | ${i} | ~${o} |`,time:a}}formatSessionSearchRow(e,r){let n=`#S${e.id}`,a=this.formatTime(e.created_at_epoch),s="\u{1F3AF}",i=e.request||`Session ${e.sdk_session_id?.substring(0,8)||"unknown"}`;return{row:`| ${n} | ${a===r?"\u2033":a} | ${s} | ${i} | - |`,time:a}}formatUserPromptSearchRow(e,r){let n=`#P${e.id}`,a=this.formatTime(e.created_at_epoch),s="\u{1F4AC}",i=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return{row:`| ${n} | ${a===r?"\u2033":a} | ${s} | ${i} | - |`,time:a}}};La();var $l=class{buildTimeline(e){let r=[...e.observations.map(n=>({type:"observation",data:n,epoch:n.created_at_epoch})),...e.sessions.map(n=>({type:"session",data:n,epoch:n.created_at_epoch})),...e.prompts.map(n=>({type:"prompt",data:n,epoch:n.created_at_epoch}))];return r.sort((n,a)=>n.epoch-a.epoch),r}filterByDepth(e,r,n,a,s){if(e.length===0)return e;let i=-1;if(typeof r=="number")i=e.findIndex(u=>u.type==="observation"&&u.data.id===r);else if(typeof r=="string"&&r.startsWith("S")){let u=parseInt(r.slice(1),10);i=e.findIndex(l=>l.type==="session"&&l.data.id===u)}else i=e.findIndex(u=>u.epoch>=n),i===-1&&(i=e.length-1);if(i===-1)return e;let o=Math.max(0,i-a),c=Math.min(e.length,i+s+1);return e.slice(o,c)}formatTimeline(e,r,n,a,s){if(e.length===0)return n?`Found observation matching "${n}", but no timeline context available.`:"No timeline items found";let i=[];if(n&&r){let u=e.find(d=>d.type==="observation"&&d.data.id===r),l=u?u.data.title||"Untitled":"Unknown";i.push(`# Timeline for query: "${n}"`),i.push(`**Anchor:** Observation #${r} - ${l}`)}else r?i.push(`# Timeline around anchor: ${r}`):i.push("# Timeline");a!==void 0&&s!==void 0?i.push(`**Window:** ${a} records before \u2192 ${s} records after | **Items:** ${e.length}`):i.push(`**Items:** ${e.length}`),i.push(""),i.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),i.push("");let o=new Map;for(let u of e){let l=this.formatDate(u.epoch);o.has(l)||o.set(l,[]),o.get(l).push(u)}let c=Array.from(o.entries()).sort((u,l)=>{let d=new Date(u[0]).getTime(),f=new Date(l[0]).getTime();return d-f});for(let[u,l]of c){i.push(`### ${u}`),i.push("");let d=null,f="",m=!1;for(let g of l){let b=typeof r=="number"&&g.type==="observation"&&g.data.id===r||typeof r=="string"&&r.startsWith("S")&&g.type==="session"&&`S${g.data.id}`===r;if(g.type==="session"){m&&(i.push(""),m=!1,d=null,f="");let p=g.data,h=p.request||"Session summary",y=b?" \u2190 **ANCHOR**":"";i.push(`**\u{1F3AF} #S${p.id}** ${h} (${this.formatDateTime(g.epoch)})${y}`),i.push("")}else if(g.type==="prompt"){m&&(i.push(""),m=!1,d=null,f="");let p=g.data,h=p.prompt_text.length>100?p.prompt_text.substring(0,100)+"...":p.prompt_text;i.push(`**\u{1F4AC} User Prompt #${p.prompt_number}** (${this.formatDateTime(g.epoch)})`),i.push(`> ${h}`),i.push("")}else if(g.type==="observation"){let p=g.data,h="General";h!==d&&(m&&i.push(""),i.push(`**${h}**`),i.push("| ID | Time | T | Title | Tokens |"),i.push("|----|------|---|-------|--------|"),d=h,m=!0,f="");let y=this.getTypeIcon(p.type),v=this.formatTime(g.epoch),_=p.title||"Untitled",S=this.estimateTokens(p.narrative),E=v!==f?v:"\u2033";f=v;let T=b?" \u2190 **ANCHOR**":"";i.push(`| #${p.id} | ${E} | ${y} | ${_}${T} | ~${S} |`)}}m&&i.push("")}return i.join(` -`)}getTypeIcon(e){return $t.getInstance().getTypeIcon(e)}formatDate(e){return new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}formatTime(e){return new Date(e).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}formatDateTime(e){return new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}estimateTokens(e){return e?Math.ceil(e.length/4):0}};var Rl=class{constructor(e,r){this.sseBroadcaster=e;this.workerService=r}broadcastNewPrompt(e){this.sseBroadcaster.broadcast({type:"new_prompt",prompt:e}),this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:!0}),this.workerService.broadcastProcessingStatus()}broadcastSessionStarted(e,r){this.sseBroadcaster.broadcast({type:"session_started",sessionDbId:e,project:r}),this.workerService.broadcastProcessingStatus()}broadcastObservationQueued(e){this.sseBroadcaster.broadcast({type:"observation_queued",sessionDbId:e}),this.workerService.broadcastProcessingStatus()}broadcastSessionCompleted(e){this.sseBroadcaster.broadcast({type:"session_completed",timestamp:Date.now(),sessionDbId:e}),this.workerService.broadcastProcessingStatus()}broadcastSummarizeQueued(){this.workerService.broadcastProcessingStatus()}};var Vm=kt(Kc(),1),Xk=kt(Kk(),1),Jk=kt(require("path"),1);dr();mt();function Yk(t){let e=[];e.push(Vm.default.json({limit:"50mb"})),e.push((0,Xk.default)()),e.push((a,s,i)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(m=>a.path.endsWith(m));if(a.path.startsWith("/health")||a.path==="/"||c)return i();let u=Date.now(),l=`${a.method}-${Date.now()}`,d=t(a.method,a.path,a.body);U.info("HTTP",`\u2192 ${a.method} ${a.path}`,{requestId:l},d);let f=s.send.bind(s);s.send=function(m){let g=Date.now()-u;return U.info("HTTP",`\u2190 ${s.statusCode} ${a.path}`,{requestId:l,duration:`${g}ms`}),f(m)},i()});let r=nr(),n=Jk.default.join(r,"plugin","ui");return e.push(Vm.default.static(n)),e}function Zm(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){U.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function Qk(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",a=r.tool_input;return`tool=${U.formatTool(n,a)}`}return e.includes("/summarize")?"requesting summary":""}var e$=kt(Kc(),1),Pl=kt(require("path"),1),Cl=require("fs");dr();mt();var Or=class{wrapHandler(e){return(r,n)=>{try{let a=e(r,n);a instanceof Promise&&a.catch(s=>this.handleError(n,s))}catch(a){this.handleError(n,a)}}}parseIntParam(e,r,n){let a=parseInt(e.params[n],10);return isNaN(a)?(this.badRequest(r,`Invalid ${n}`),null):a}validateRequired(e,r,n){for(let a of n)if(e.body[a]===void 0||e.body[a]===null)return this.badRequest(r,`Missing ${a}`),!1;return!0}badRequest(e,r){e.status(400).json({error:r})}notFound(e,r){e.status(404).json({error:r})}handleError(e,r,n){U.failure("WORKER",n||"Request failed",{},r),e.status(500).json({error:r.message})}};var Ol=class extends Or{constructor(r,n,a){super();this.sseBroadcaster=r;this.dbManager=n;this.sessionManager=a}setupRoutes(r){let n=nr();r.use(e$.default.static(Pl.default.join(n,"ui"))),r.get("/health",this.handleHealth.bind(this)),r.get("/",this.handleViewerUI.bind(this)),r.get("/stream",this.handleSSEStream.bind(this))}handleHealth=this.wrapHandler((r,n)=>{n.json({status:"ok",timestamp:Date.now()})});handleViewerUI=this.wrapHandler((r,n)=>{let a=nr(),i=[Pl.default.join(a,"ui","viewer.html"),Pl.default.join(a,"plugin","ui","viewer.html")].find(c=>(0,Cl.existsSync)(c));if(!i)throw new Error("Viewer UI not found at any expected location");let o=(0,Cl.readFileSync)(i,"utf-8");n.setHeader("Content-Type","text/html"),n.send(o)});handleSSEStream=this.wrapHandler((r,n)=>{n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),this.sseBroadcaster.addClient(n);let a=this.dbManager.getSessionStore().getAllProjects();this.sseBroadcaster.broadcast({type:"initial_load",projects:a,timestamp:Date.now()});let s=this.sessionManager.isAnySessionProcessing(),i=this.sessionManager.getTotalActiveWork();this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:s,queueDepth:i})})};mt();mt();var t$=100;function C7(t){let e=(t.match(//g)||[]).length,r=(t.match(//g)||[]).length;return e+r}function r$(t){let e=C7(t);return e>t$&&U.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:e,maxAllowed:t$,contentLength:t.length}),t.replace(/[\s\S]*?<\/claude-mem-context>/g,"").replace(/[\s\S]*?<\/private>/g,"").trim()}function Gm(t){return r$(t)}function a$(t){return r$(t)}var Il=class{constructor(e,r,n){this.sessionManager=e;this.dbManager=r;this.eventBroadcaster=n}async completeByDbId(e){await this.sessionManager.deleteSession(e),this.dbManager.markSessionComplete(e),this.eventBroadcaster.broadcastSessionCompleted(e)}async completeByClaudeId(e){let n=this.dbManager.getSessionStore().findActiveSDKSession(e);if(!n)return!1;let a=n.id;return await this.completeByDbId(a),!0}};mt();var Mo=class{static checkUserPromptPrivacy(e,r,n,a,s,i){let o=e.getUserPrompt(r,n);return!o||o.trim()===""?(U.debug("HOOK",`Skipping ${a} - user prompt was entirely private`,{sessionId:s,promptNumber:n,...i}),null):o}};Dr();dr();var Al=class extends Or{constructor(r,n,a,s,i){super();this.sessionManager=r;this.dbManager=n;this.sdkAgent=a;this.eventBroadcaster=s;this.workerService=i;this.completionHandler=new Il(r,n,s)}completionHandler;ensureGeneratorRunning(r,n){let a=this.sessionManager.getSession(r);a&&!a.generatorPromise&&(U.info("SESSION",`Generator auto-starting (${n})`,{sessionId:r,queueDepth:a.pendingMessages.length}),a.generatorPromise=this.sdkAgent.startSession(a,this.workerService).finally(()=>{U.info("SESSION","Generator finished",{sessionId:r}),a.generatorPromise=null,this.workerService.broadcastProcessingStatus()}))}setupRoutes(r){r.post("/sessions/:sessionDbId/init",this.handleSessionInit.bind(this)),r.post("/sessions/:sessionDbId/observations",this.handleObservations.bind(this)),r.post("/sessions/:sessionDbId/summarize",this.handleSummarize.bind(this)),r.get("/sessions/:sessionDbId/status",this.handleSessionStatus.bind(this)),r.delete("/sessions/:sessionDbId",this.handleSessionDelete.bind(this)),r.post("/sessions/:sessionDbId/complete",this.handleSessionComplete.bind(this)),r.post("/api/sessions/init",this.handleSessionInitByClaudeId.bind(this)),r.post("/api/sessions/observations",this.handleObservationsByClaudeId.bind(this)),r.post("/api/sessions/summarize",this.handleSummarizeByClaudeId.bind(this)),r.post("/api/sessions/complete",this.handleSessionCompleteByClaudeId.bind(this))}handleSessionInit=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");if(a===null)return;let{userPrompt:s,promptNumber:i}=r.body,o=this.sessionManager.initializeSession(a,s,i),c=this.dbManager.getSessionStore().getLatestUserPrompt(o.claudeSessionId);if(c){this.eventBroadcaster.broadcastNewPrompt({id:c.id,claude_session_id:c.claude_session_id,project:c.project,prompt_number:c.prompt_number,prompt_text:c.prompt_text,created_at_epoch:c.created_at_epoch});let u=Date.now(),l=c.prompt_text;this.dbManager.getChromaSync().syncUserPrompt(c.id,c.sdk_session_id,c.project,l,c.prompt_number,c.created_at_epoch).then(()=>{let d=Date.now()-u,f=l.length>60?l.substring(0,60)+"...":l;U.debug("CHROMA","User prompt synced",{promptId:c.id,duration:`${d}ms`,prompt:f})})}U.info("SESSION","Generator starting",{sessionId:a,project:o.project,promptNum:o.lastPromptNumber}),o.generatorPromise=this.sdkAgent.startSession(o,this.workerService).finally(()=>{U.info("SESSION","Generator finished",{sessionId:a}),o.generatorPromise=null,this.workerService.broadcastProcessingStatus()}),this.eventBroadcaster.broadcastSessionStarted(a,o.project),n.json({status:"initialized",sessionDbId:a,port:qs()})});handleObservations=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");if(a===null)return;let{tool_name:s,tool_input:i,tool_response:o,prompt_number:c,cwd:u}=r.body;this.sessionManager.queueObservation(a,{tool_name:s,tool_input:i,tool_response:o,prompt_number:c,cwd:u}),this.ensureGeneratorRunning(a,"observation"),this.eventBroadcaster.broadcastObservationQueued(a),n.json({status:"queued"})});handleSummarize=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");if(a===null)return;let{last_user_message:s,last_assistant_message:i}=r.body;this.sessionManager.queueSummarize(a,s,i),this.ensureGeneratorRunning(a,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleSessionStatus=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");if(a===null)return;let s=this.sessionManager.getSession(a);if(!s){n.json({status:"not_found"});return}n.json({status:"active",sessionDbId:a,project:s.project,queueLength:s.pendingMessages.length,uptime:Date.now()-s.startTime})});handleSessionDelete=this.wrapHandler(async(r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");a!==null&&(await this.completionHandler.completeByDbId(a),n.json({status:"deleted"}))});handleSessionComplete=this.wrapHandler(async(r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");a!==null&&(await this.completionHandler.completeByDbId(a),n.json({success:!0}))});handleObservationsByClaudeId=this.wrapHandler((r,n)=>{let{claudeSessionId:a,tool_name:s,tool_input:i,tool_response:o,cwd:c}=r.body;if(!a)return this.badRequest(n,"Missing claudeSessionId");let u=ct.loadFromFile(In);if(new Set(u.CLAUDE_MEM_SKIP_TOOLS.split(",").map(y=>y.trim()).filter(Boolean)).has(s)){U.debug("SESSION","Skipping observation for tool",{tool_name:s}),n.json({status:"skipped",reason:"tool_excluded"});return}if(new Set(["Edit","Write","Read","NotebookEdit"]).has(s)&&i){let y=i.file_path||i.notebook_path;if(y&&y.includes("session-memory")){U.debug("SESSION","Skipping meta-observation for session-memory file",{tool_name:s,file_path:y}),n.json({status:"skipped",reason:"session_memory_meta"});return}}let f=this.dbManager.getSessionStore(),m=f.createSDKSession(a,"",""),g=f.getPromptCounter(m);if(!Mo.checkUserPromptPrivacy(f,a,g,"observation",m,{tool_name:s})){n.json({status:"skipped",reason:"private"});return}let p=i!==void 0?Gm(JSON.stringify(i)):"{}",h=o!==void 0?Gm(JSON.stringify(o)):"{}";this.sessionManager.queueObservation(m,{tool_name:s,tool_input:p,tool_response:h,prompt_number:g,cwd:c||U.happyPathError("SESSION","Missing cwd when queueing observation in SessionRoutes",{sessionId:m},{tool_name:s},"")}),this.ensureGeneratorRunning(m,"observation"),this.eventBroadcaster.broadcastObservationQueued(m),n.json({status:"queued"})});handleSummarizeByClaudeId=this.wrapHandler((r,n)=>{let{claudeSessionId:a,last_user_message:s,last_assistant_message:i}=r.body;if(!a)return this.badRequest(n,"Missing claudeSessionId");let o=this.dbManager.getSessionStore(),c=o.createSDKSession(a,"",""),u=o.getPromptCounter(c);if(!Mo.checkUserPromptPrivacy(o,a,u,"summarize",c)){n.json({status:"skipped",reason:"private"});return}this.sessionManager.queueSummarize(c,s||U.happyPathError("SESSION","Missing last_user_message when queueing summary in SessionRoutes",{sessionId:c},void 0,""),i),this.ensureGeneratorRunning(c,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleSessionCompleteByClaudeId=this.wrapHandler(async(r,n)=>{let{claudeSessionId:a}=r.body;if(!a)return this.badRequest(n,"Missing claudeSessionId");if(!await this.completionHandler.completeByClaudeId(a)){n.json({success:!0,message:"No active session found"});return}n.json({success:!0})});handleSessionInitByClaudeId=this.wrapHandler((r,n)=>{let{claudeSessionId:a,project:s,prompt:i}=r.body;if(!this.validateRequired(r,n,["claudeSessionId","project","prompt"]))return;let o=this.dbManager.getSessionStore(),c=o.createSDKSession(a,s,i),u=o.incrementPromptCounter(c),l=a$(i);if(!l||l.trim()===""){U.debug("HOOK","Session init - prompt entirely private",{sessionId:c,promptNumber:u,originalLength:i.length}),n.json({sessionDbId:c,promptNumber:u,skipped:!0,reason:"private"});return}o.saveUserPrompt(a,u,l),U.info("SESSION","Session initialized via HTTP",{sessionId:c,promptNumber:u,project:s}),n.json({sessionDbId:c,promptNumber:u,skipped:!1})})};var Wm=kt(require("path"),1),li=require("fs"),n$=require("os");dr();var Nl=class extends Or{constructor(r,n,a,s,i,o){super();this.paginationHelper=r;this.dbManager=n;this.sessionManager=a;this.sseBroadcaster=s;this.workerService=i;this.startTime=o}setupRoutes(r){r.get("/api/observations",this.handleGetObservations.bind(this)),r.get("/api/summaries",this.handleGetSummaries.bind(this)),r.get("/api/prompts",this.handleGetPrompts.bind(this)),r.get("/api/observation/:id",this.handleGetObservationById.bind(this)),r.post("/api/observations/batch",this.handleGetObservationsByIds.bind(this)),r.get("/api/session/:id",this.handleGetSessionById.bind(this)),r.post("/api/sdk-sessions/batch",this.handleGetSdkSessionsByIds.bind(this)),r.get("/api/prompt/:id",this.handleGetPromptById.bind(this)),r.get("/api/stats",this.handleGetStats.bind(this)),r.get("/api/projects",this.handleGetProjects.bind(this)),r.get("/api/processing-status",this.handleGetProcessingStatus.bind(this)),r.post("/api/processing",this.handleSetProcessing.bind(this)),r.post("/api/import",this.handleImport.bind(this))}handleGetObservations=this.wrapHandler((r,n)=>{let{offset:a,limit:s,project:i}=this.parsePaginationParams(r),o=this.paginationHelper.getObservations(a,s,i);n.json(o)});handleGetSummaries=this.wrapHandler((r,n)=>{let{offset:a,limit:s,project:i}=this.parsePaginationParams(r),o=this.paginationHelper.getSummaries(a,s,i);n.json(o)});handleGetPrompts=this.wrapHandler((r,n)=>{let{offset:a,limit:s,project:i}=this.parsePaginationParams(r),o=this.paginationHelper.getPrompts(a,s,i);n.json(o)});handleGetObservationById=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"id");if(a===null)return;let i=this.dbManager.getSessionStore().getObservationById(a);if(!i){this.notFound(n,`Observation #${a} not found`);return}n.json(i)});handleGetObservationsByIds=this.wrapHandler((r,n)=>{let{ids:a,orderBy:s,limit:i,project:o}=r.body;if(!a||!Array.isArray(a)){this.badRequest(n,"ids must be an array of numbers");return}if(a.length===0){n.json([]);return}if(!a.every(l=>typeof l=="number"&&Number.isInteger(l))){this.badRequest(n,"All ids must be integers");return}let u=this.dbManager.getSessionStore().getObservationsByIds(a,{orderBy:s,limit:i,project:o});n.json(u)});handleGetSessionById=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"id");if(a===null)return;let i=this.dbManager.getSessionStore().getSessionSummariesByIds([a]);if(i.length===0){this.notFound(n,`Session #${a} not found`);return}n.json(i[0])});handleGetSdkSessionsByIds=this.wrapHandler((r,n)=>{let{sdkSessionIds:a}=r.body;if(!Array.isArray(a)){this.badRequest(n,"sdkSessionIds must be an array");return}let i=this.dbManager.getSessionStore().getSdkSessionsBySessionIds(a);n.json(i)});handleGetPromptById=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"id");if(a===null)return;let i=this.dbManager.getSessionStore().getUserPromptsByIds([a]);if(i.length===0){this.notFound(n,`Prompt #${a} not found`);return}n.json(i[0])});handleGetStats=this.wrapHandler((r,n)=>{let a=this.dbManager.getSessionStore().db,s=nr(),i=Wm.default.join(s,"package.json"),c=JSON.parse((0,li.readFileSync)(i,"utf-8")).version,u=a.prepare("SELECT COUNT(*) as count FROM observations").get(),l=a.prepare("SELECT COUNT(*) as count FROM sdk_sessions").get(),d=a.prepare("SELECT COUNT(*) as count FROM session_summaries").get(),f=Wm.default.join((0,n$.homedir)(),".claude-mem","claude-mem.db"),m=0;(0,li.existsSync)(f)&&(m=(0,li.statSync)(f).size);let g=Math.floor((Date.now()-this.startTime)/1e3),b=this.sessionManager.getActiveSessionCount(),p=this.sseBroadcaster.getClientCount();n.json({worker:{version:c,uptime:g,activeSessions:b,sseClients:p,port:qs()},database:{path:f,size:m,observations:u.count,sessions:l.count,summaries:d.count}})});handleGetProjects=this.wrapHandler((r,n)=>{let i=this.dbManager.getSessionStore().db.prepare(` +|----|------|---|-------|------|`}formatObservationSearchRow(e,r){let n=`#${e.id}`,a=this.formatTime(e.created_at_epoch),s=kt.getInstance().getTypeIcon(e.type),i=e.title||"Untitled",o=this.estimateReadTokens(e);return{row:`| ${n} | ${a===r?"\u2033":a} | ${s} | ${i} | ~${o} |`,time:a}}formatSessionSearchRow(e,r){let n=`#S${e.id}`,a=this.formatTime(e.created_at_epoch),s="\u{1F3AF}",i=e.request||`Session ${e.sdk_session_id?.substring(0,8)||"unknown"}`;return{row:`| ${n} | ${a===r?"\u2033":a} | ${s} | ${i} | - |`,time:a}}formatUserPromptSearchRow(e,r){let n=`#P${e.id}`,a=this.formatTime(e.created_at_epoch),s="\u{1F4AC}",i=e.prompt_text.length>60?e.prompt_text.substring(0,57)+"...":e.prompt_text;return{row:`| ${n} | ${a===r?"\u2033":a} | ${s} | ${i} | - |`,time:a}}};La();var $l=class{buildTimeline(e){let r=[...e.observations.map(n=>({type:"observation",data:n,epoch:n.created_at_epoch})),...e.sessions.map(n=>({type:"session",data:n,epoch:n.created_at_epoch})),...e.prompts.map(n=>({type:"prompt",data:n,epoch:n.created_at_epoch}))];return r.sort((n,a)=>n.epoch-a.epoch),r}filterByDepth(e,r,n,a,s){if(e.length===0)return e;let i=-1;if(typeof r=="number")i=e.findIndex(u=>u.type==="observation"&&u.data.id===r);else if(typeof r=="string"&&r.startsWith("S")){let u=parseInt(r.slice(1),10);i=e.findIndex(l=>l.type==="session"&&l.data.id===u)}else i=e.findIndex(u=>u.epoch>=n),i===-1&&(i=e.length-1);if(i===-1)return e;let o=Math.max(0,i-a),c=Math.min(e.length,i+s+1);return e.slice(o,c)}formatTimeline(e,r,n,a,s){if(e.length===0)return n?`Found observation matching "${n}", but no timeline context available.`:"No timeline items found";let i=[];if(n&&r){let u=e.find(d=>d.type==="observation"&&d.data.id===r),l=u?u.data.title||"Untitled":"Unknown";i.push(`# Timeline for query: "${n}"`),i.push(`**Anchor:** Observation #${r} - ${l}`)}else r?i.push(`# Timeline around anchor: ${r}`):i.push("# Timeline");a!==void 0&&s!==void 0?i.push(`**Window:** ${a} records before \u2192 ${s} records after | **Items:** ${e.length}`):i.push(`**Items:** ${e.length}`),i.push(""),i.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),i.push("");let o=new Map;for(let u of e){let l=this.formatDate(u.epoch);o.has(l)||o.set(l,[]),o.get(l).push(u)}let c=Array.from(o.entries()).sort((u,l)=>{let d=new Date(u[0]).getTime(),f=new Date(l[0]).getTime();return d-f});for(let[u,l]of c){i.push(`### ${u}`),i.push("");let d=null,f="",m=!1;for(let g of l){let b=typeof r=="number"&&g.type==="observation"&&g.data.id===r||typeof r=="string"&&r.startsWith("S")&&g.type==="session"&&`S${g.data.id}`===r;if(g.type==="session"){m&&(i.push(""),m=!1,d=null,f="");let p=g.data,h=p.request||"Session summary",y=b?" \u2190 **ANCHOR**":"";i.push(`**\u{1F3AF} #S${p.id}** ${h} (${this.formatDateTime(g.epoch)})${y}`),i.push("")}else if(g.type==="prompt"){m&&(i.push(""),m=!1,d=null,f="");let p=g.data,h=p.prompt_text.length>100?p.prompt_text.substring(0,100)+"...":p.prompt_text;i.push(`**\u{1F4AC} User Prompt #${p.prompt_number}** (${this.formatDateTime(g.epoch)})`),i.push(`> ${h}`),i.push("")}else if(g.type==="observation"){let p=g.data,h="General";h!==d&&(m&&i.push(""),i.push(`**${h}**`),i.push("| ID | Time | T | Title | Tokens |"),i.push("|----|------|---|-------|--------|"),d=h,m=!0,f="");let y=this.getTypeIcon(p.type),v=this.formatTime(g.epoch),_=p.title||"Untitled",S=this.estimateTokens(p.narrative),E=v!==f?v:"\u2033";f=v;let T=b?" \u2190 **ANCHOR**":"";i.push(`| #${p.id} | ${E} | ${y} | ${_}${T} | ~${S} |`)}}m&&i.push("")}return i.join(` +`)}getTypeIcon(e){return kt.getInstance().getTypeIcon(e)}formatDate(e){return new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}formatTime(e){return new Date(e).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}formatDateTime(e){return new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}estimateTokens(e){return e?Math.ceil(e.length/4):0}};var Rl=class{constructor(e,r){this.sseBroadcaster=e;this.workerService=r}broadcastNewPrompt(e){this.sseBroadcaster.broadcast({type:"new_prompt",prompt:e}),this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:!0}),this.workerService.broadcastProcessingStatus()}broadcastSessionStarted(e,r){this.sseBroadcaster.broadcast({type:"session_started",sessionDbId:e,project:r}),this.workerService.broadcastProcessingStatus()}broadcastObservationQueued(e){this.sseBroadcaster.broadcast({type:"observation_queued",sessionDbId:e}),this.workerService.broadcastProcessingStatus()}broadcastSessionCompleted(e){this.sseBroadcaster.broadcast({type:"session_completed",timestamp:Date.now(),sessionDbId:e}),this.workerService.broadcastProcessingStatus()}broadcastSummarizeQueued(){this.workerService.broadcastProcessingStatus()}};var Vm=$t(Kc(),1),Xk=$t(Kk(),1),Jk=$t(require("path"),1);dr();mt();function Yk(t){let e=[];e.push(Vm.default.json({limit:"50mb"})),e.push((0,Xk.default)()),e.push((a,s,i)=>{let c=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(m=>a.path.endsWith(m));if(a.path.startsWith("/health")||a.path==="/"||c)return i();let u=Date.now(),l=`${a.method}-${Date.now()}`,d=t(a.method,a.path,a.body);U.info("HTTP",`\u2192 ${a.method} ${a.path}`,{requestId:l},d);let f=s.send.bind(s);s.send=function(m){let g=Date.now()-u;return U.info("HTTP",`\u2190 ${s.statusCode} ${a.path}`,{requestId:l,duration:`${g}ms`}),f(m)},i()});let r=nr(),n=Jk.default.join(r,"plugin","ui");return e.push(Vm.default.static(n)),e}function Zm(t,e,r){let n=t.ip||t.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){U.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:t.path,clientIp:n,method:t.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}r()}function Qk(t,e,r){if(!r||Object.keys(r).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=r.tool_name||"?",a=r.tool_input;return`tool=${U.formatTool(n,a)}`}return e.includes("/summarize")?"requesting summary":""}var e$=$t(Kc(),1),Pl=$t(require("path"),1),Cl=require("fs");dr();mt();var Or=class{wrapHandler(e){return(r,n)=>{try{let a=e(r,n);a instanceof Promise&&a.catch(s=>this.handleError(n,s))}catch(a){this.handleError(n,a)}}}parseIntParam(e,r,n){let a=parseInt(e.params[n],10);return isNaN(a)?(this.badRequest(r,`Invalid ${n}`),null):a}validateRequired(e,r,n){for(let a of n)if(e.body[a]===void 0||e.body[a]===null)return this.badRequest(r,`Missing ${a}`),!1;return!0}badRequest(e,r){e.status(400).json({error:r})}notFound(e,r){e.status(404).json({error:r})}handleError(e,r,n){U.failure("WORKER",n||"Request failed",{},r),e.status(500).json({error:r.message})}};var Ol=class extends Or{constructor(r,n,a){super();this.sseBroadcaster=r;this.dbManager=n;this.sessionManager=a}setupRoutes(r){let n=nr();r.use(e$.default.static(Pl.default.join(n,"ui"))),r.get("/health",this.handleHealth.bind(this)),r.get("/",this.handleViewerUI.bind(this)),r.get("/stream",this.handleSSEStream.bind(this))}handleHealth=this.wrapHandler((r,n)=>{n.json({status:"ok",timestamp:Date.now()})});handleViewerUI=this.wrapHandler((r,n)=>{let a=nr(),i=[Pl.default.join(a,"ui","viewer.html"),Pl.default.join(a,"plugin","ui","viewer.html")].find(c=>(0,Cl.existsSync)(c));if(!i)throw new Error("Viewer UI not found at any expected location");let o=(0,Cl.readFileSync)(i,"utf-8");n.setHeader("Content-Type","text/html"),n.send(o)});handleSSEStream=this.wrapHandler((r,n)=>{n.setHeader("Content-Type","text/event-stream"),n.setHeader("Cache-Control","no-cache"),n.setHeader("Connection","keep-alive"),this.sseBroadcaster.addClient(n);let a=this.dbManager.getSessionStore().getAllProjects();this.sseBroadcaster.broadcast({type:"initial_load",projects:a,timestamp:Date.now()});let s=this.sessionManager.isAnySessionProcessing(),i=this.sessionManager.getTotalActiveWork();this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:s,queueDepth:i})})};mt();mt();var t$=100;function C7(t){let e=(t.match(//g)||[]).length,r=(t.match(//g)||[]).length;return e+r}function r$(t){let e=C7(t);return e>t$&&U.warn("SYSTEM","tag count exceeds limit",void 0,{tagCount:e,maxAllowed:t$,contentLength:t.length}),t.replace(/[\s\S]*?<\/claude-mem-context>/g,"").replace(/[\s\S]*?<\/private>/g,"").trim()}function Gm(t){return r$(t)}function a$(t){return r$(t)}var Il=class{constructor(e,r,n){this.sessionManager=e;this.dbManager=r;this.eventBroadcaster=n}async completeByDbId(e){await this.sessionManager.deleteSession(e),this.dbManager.markSessionComplete(e),this.eventBroadcaster.broadcastSessionCompleted(e)}async completeByClaudeId(e){let n=this.dbManager.getSessionStore().findActiveSDKSession(e);if(!n)return!1;let a=n.id;return await this.completeByDbId(a),!0}};mt();var Mo=class{static checkUserPromptPrivacy(e,r,n,a,s,i){let o=e.getUserPrompt(r,n);return!o||o.trim()===""?(U.debug("HOOK",`Skipping ${a} - user prompt was entirely private`,{sessionId:s,promptNumber:n,...i}),null):o}};Dr();dr();var Al=class extends Or{constructor(r,n,a,s,i){super();this.sessionManager=r;this.dbManager=n;this.sdkAgent=a;this.eventBroadcaster=s;this.workerService=i;this.completionHandler=new Il(r,n,s)}completionHandler;ensureGeneratorRunning(r,n){let a=this.sessionManager.getSession(r);a&&!a.generatorPromise&&(U.info("SESSION",`Generator auto-starting (${n})`,{sessionId:r,queueDepth:a.pendingMessages.length}),a.generatorPromise=this.sdkAgent.startSession(a,this.workerService).finally(()=>{U.info("SESSION","Generator finished",{sessionId:r}),a.generatorPromise=null,this.workerService.broadcastProcessingStatus()}))}setupRoutes(r){r.post("/sessions/:sessionDbId/init",this.handleSessionInit.bind(this)),r.post("/sessions/:sessionDbId/observations",this.handleObservations.bind(this)),r.post("/sessions/:sessionDbId/summarize",this.handleSummarize.bind(this)),r.get("/sessions/:sessionDbId/status",this.handleSessionStatus.bind(this)),r.delete("/sessions/:sessionDbId",this.handleSessionDelete.bind(this)),r.post("/sessions/:sessionDbId/complete",this.handleSessionComplete.bind(this)),r.post("/api/sessions/init",this.handleSessionInitByClaudeId.bind(this)),r.post("/api/sessions/observations",this.handleObservationsByClaudeId.bind(this)),r.post("/api/sessions/summarize",this.handleSummarizeByClaudeId.bind(this)),r.post("/api/sessions/complete",this.handleSessionCompleteByClaudeId.bind(this))}handleSessionInit=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");if(a===null)return;let{userPrompt:s,promptNumber:i}=r.body,o=this.sessionManager.initializeSession(a,s,i),c=this.dbManager.getSessionStore().getLatestUserPrompt(o.claudeSessionId);if(c){this.eventBroadcaster.broadcastNewPrompt({id:c.id,claude_session_id:c.claude_session_id,project:c.project,prompt_number:c.prompt_number,prompt_text:c.prompt_text,created_at_epoch:c.created_at_epoch});let u=Date.now(),l=c.prompt_text;this.dbManager.getChromaSync().syncUserPrompt(c.id,c.sdk_session_id,c.project,l,c.prompt_number,c.created_at_epoch).then(()=>{let d=Date.now()-u,f=l.length>60?l.substring(0,60)+"...":l;U.debug("CHROMA","User prompt synced",{promptId:c.id,duration:`${d}ms`,prompt:f})})}U.info("SESSION","Generator starting",{sessionId:a,project:o.project,promptNum:o.lastPromptNumber}),o.generatorPromise=this.sdkAgent.startSession(o,this.workerService).finally(()=>{U.info("SESSION","Generator finished",{sessionId:a}),o.generatorPromise=null,this.workerService.broadcastProcessingStatus()}),this.eventBroadcaster.broadcastSessionStarted(a,o.project),n.json({status:"initialized",sessionDbId:a,port:qs()})});handleObservations=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");if(a===null)return;let{tool_name:s,tool_input:i,tool_response:o,prompt_number:c,cwd:u}=r.body;this.sessionManager.queueObservation(a,{tool_name:s,tool_input:i,tool_response:o,prompt_number:c,cwd:u}),this.ensureGeneratorRunning(a,"observation"),this.eventBroadcaster.broadcastObservationQueued(a),n.json({status:"queued"})});handleSummarize=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");if(a===null)return;let{last_user_message:s,last_assistant_message:i}=r.body;this.sessionManager.queueSummarize(a,s,i),this.ensureGeneratorRunning(a,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleSessionStatus=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");if(a===null)return;let s=this.sessionManager.getSession(a);if(!s){n.json({status:"not_found"});return}n.json({status:"active",sessionDbId:a,project:s.project,queueLength:s.pendingMessages.length,uptime:Date.now()-s.startTime})});handleSessionDelete=this.wrapHandler(async(r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");a!==null&&(await this.completionHandler.completeByDbId(a),n.json({status:"deleted"}))});handleSessionComplete=this.wrapHandler(async(r,n)=>{let a=this.parseIntParam(r,n,"sessionDbId");a!==null&&(await this.completionHandler.completeByDbId(a),n.json({success:!0}))});handleObservationsByClaudeId=this.wrapHandler((r,n)=>{let{claudeSessionId:a,tool_name:s,tool_input:i,tool_response:o,cwd:c}=r.body;if(!a)return this.badRequest(n,"Missing claudeSessionId");let u=ct.loadFromFile(In);if(new Set(u.CLAUDE_MEM_SKIP_TOOLS.split(",").map(y=>y.trim()).filter(Boolean)).has(s)){U.debug("SESSION","Skipping observation for tool",{tool_name:s}),n.json({status:"skipped",reason:"tool_excluded"});return}if(new Set(["Edit","Write","Read","NotebookEdit"]).has(s)&&i){let y=i.file_path||i.notebook_path;if(y&&y.includes("session-memory")){U.debug("SESSION","Skipping meta-observation for session-memory file",{tool_name:s,file_path:y}),n.json({status:"skipped",reason:"session_memory_meta"});return}}let f=this.dbManager.getSessionStore(),m=f.createSDKSession(a,"",""),g=f.getPromptCounter(m);if(!Mo.checkUserPromptPrivacy(f,a,g,"observation",m,{tool_name:s})){n.json({status:"skipped",reason:"private"});return}let p=i!==void 0?Gm(JSON.stringify(i)):"{}",h=o!==void 0?Gm(JSON.stringify(o)):"{}";this.sessionManager.queueObservation(m,{tool_name:s,tool_input:p,tool_response:h,prompt_number:g,cwd:c||U.happyPathError("SESSION","Missing cwd when queueing observation in SessionRoutes",{sessionId:m},{tool_name:s},"")}),this.ensureGeneratorRunning(m,"observation"),this.eventBroadcaster.broadcastObservationQueued(m),n.json({status:"queued"})});handleSummarizeByClaudeId=this.wrapHandler((r,n)=>{let{claudeSessionId:a,last_user_message:s,last_assistant_message:i}=r.body;if(!a)return this.badRequest(n,"Missing claudeSessionId");let o=this.dbManager.getSessionStore(),c=o.createSDKSession(a,"",""),u=o.getPromptCounter(c);if(!Mo.checkUserPromptPrivacy(o,a,u,"summarize",c)){n.json({status:"skipped",reason:"private"});return}this.sessionManager.queueSummarize(c,s||U.happyPathError("SESSION","Missing last_user_message when queueing summary in SessionRoutes",{sessionId:c},void 0,""),i),this.ensureGeneratorRunning(c,"summarize"),this.eventBroadcaster.broadcastSummarizeQueued(),n.json({status:"queued"})});handleSessionCompleteByClaudeId=this.wrapHandler(async(r,n)=>{let{claudeSessionId:a}=r.body;if(!a)return this.badRequest(n,"Missing claudeSessionId");if(!await this.completionHandler.completeByClaudeId(a)){n.json({success:!0,message:"No active session found"});return}n.json({success:!0})});handleSessionInitByClaudeId=this.wrapHandler((r,n)=>{let{claudeSessionId:a,project:s,prompt:i}=r.body;if(!this.validateRequired(r,n,["claudeSessionId","project","prompt"]))return;let o=this.dbManager.getSessionStore(),c=o.createSDKSession(a,s,i),u=o.incrementPromptCounter(c),l=a$(i);if(!l||l.trim()===""){U.debug("HOOK","Session init - prompt entirely private",{sessionId:c,promptNumber:u,originalLength:i.length}),n.json({sessionDbId:c,promptNumber:u,skipped:!0,reason:"private"});return}o.saveUserPrompt(a,u,l),U.info("SESSION","Session initialized via HTTP",{sessionId:c,promptNumber:u,project:s}),n.json({sessionDbId:c,promptNumber:u,skipped:!1})})};var Wm=$t(require("path"),1),li=require("fs"),n$=require("os");dr();var Nl=class extends Or{constructor(r,n,a,s,i,o){super();this.paginationHelper=r;this.dbManager=n;this.sessionManager=a;this.sseBroadcaster=s;this.workerService=i;this.startTime=o}setupRoutes(r){r.get("/api/observations",this.handleGetObservations.bind(this)),r.get("/api/summaries",this.handleGetSummaries.bind(this)),r.get("/api/prompts",this.handleGetPrompts.bind(this)),r.get("/api/observation/:id",this.handleGetObservationById.bind(this)),r.post("/api/observations/batch",this.handleGetObservationsByIds.bind(this)),r.get("/api/session/:id",this.handleGetSessionById.bind(this)),r.post("/api/sdk-sessions/batch",this.handleGetSdkSessionsByIds.bind(this)),r.get("/api/prompt/:id",this.handleGetPromptById.bind(this)),r.get("/api/stats",this.handleGetStats.bind(this)),r.get("/api/projects",this.handleGetProjects.bind(this)),r.get("/api/processing-status",this.handleGetProcessingStatus.bind(this)),r.post("/api/processing",this.handleSetProcessing.bind(this)),r.post("/api/import",this.handleImport.bind(this))}handleGetObservations=this.wrapHandler((r,n)=>{let{offset:a,limit:s,project:i}=this.parsePaginationParams(r),o=this.paginationHelper.getObservations(a,s,i);n.json(o)});handleGetSummaries=this.wrapHandler((r,n)=>{let{offset:a,limit:s,project:i}=this.parsePaginationParams(r),o=this.paginationHelper.getSummaries(a,s,i);n.json(o)});handleGetPrompts=this.wrapHandler((r,n)=>{let{offset:a,limit:s,project:i}=this.parsePaginationParams(r),o=this.paginationHelper.getPrompts(a,s,i);n.json(o)});handleGetObservationById=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"id");if(a===null)return;let i=this.dbManager.getSessionStore().getObservationById(a);if(!i){this.notFound(n,`Observation #${a} not found`);return}n.json(i)});handleGetObservationsByIds=this.wrapHandler((r,n)=>{let{ids:a,orderBy:s,limit:i,project:o}=r.body;if(!a||!Array.isArray(a)){this.badRequest(n,"ids must be an array of numbers");return}if(a.length===0){n.json([]);return}if(!a.every(l=>typeof l=="number"&&Number.isInteger(l))){this.badRequest(n,"All ids must be integers");return}let u=this.dbManager.getSessionStore().getObservationsByIds(a,{orderBy:s,limit:i,project:o});n.json(u)});handleGetSessionById=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"id");if(a===null)return;let i=this.dbManager.getSessionStore().getSessionSummariesByIds([a]);if(i.length===0){this.notFound(n,`Session #${a} not found`);return}n.json(i[0])});handleGetSdkSessionsByIds=this.wrapHandler((r,n)=>{let{sdkSessionIds:a}=r.body;if(!Array.isArray(a)){this.badRequest(n,"sdkSessionIds must be an array");return}let i=this.dbManager.getSessionStore().getSdkSessionsBySessionIds(a);n.json(i)});handleGetPromptById=this.wrapHandler((r,n)=>{let a=this.parseIntParam(r,n,"id");if(a===null)return;let i=this.dbManager.getSessionStore().getUserPromptsByIds([a]);if(i.length===0){this.notFound(n,`Prompt #${a} not found`);return}n.json(i[0])});handleGetStats=this.wrapHandler((r,n)=>{let a=this.dbManager.getSessionStore().db,s=nr(),i=Wm.default.join(s,"package.json"),c=JSON.parse((0,li.readFileSync)(i,"utf-8")).version,u=a.prepare("SELECT COUNT(*) as count FROM observations").get(),l=a.prepare("SELECT COUNT(*) as count FROM sdk_sessions").get(),d=a.prepare("SELECT COUNT(*) as count FROM session_summaries").get(),f=Wm.default.join((0,n$.homedir)(),".claude-mem","claude-mem.db"),m=0;(0,li.existsSync)(f)&&(m=(0,li.statSync)(f).size);let g=Math.floor((Date.now()-this.startTime)/1e3),b=this.sessionManager.getActiveSessionCount(),p=this.sseBroadcaster.getClientCount();n.json({worker:{version:c,uptime:g,activeSessions:b,sseClients:p,port:qs()},database:{path:f,size:m,observations:u.count,sessions:l.count,summaries:d.count}})});handleGetProjects=this.wrapHandler((r,n)=>{let i=this.dbManager.getSessionStore().db.prepare(` SELECT DISTINCT project FROM observations WHERE project IS NOT NULL GROUP BY project ORDER BY MAX(created_at_epoch) DESC - `).all().map(o=>o.project);n.json({projects:i})});handleGetProcessingStatus=this.wrapHandler((r,n)=>{let a=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalActiveWork();n.json({isProcessing:a,queueDepth:s})});handleSetProcessing=this.wrapHandler((r,n)=>{this.workerService.broadcastProcessingStatus();let a=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalQueueDepth(),i=this.sessionManager.getActiveSessionCount();n.json({status:"ok",isProcessing:a,queueDepth:s,activeSessions:i})});parsePaginationParams(r){let n=parseInt(r.query.offset,10)||0,a=Math.min(parseInt(r.query.limit,10)||20,100),s=r.query.project;return{offset:n,limit:a,project:s}}handleImport=this.wrapHandler((r,n)=>{let{sessions:a,summaries:s,observations:i,prompts:o}=r.body,c={sessionsImported:0,sessionsSkipped:0,summariesImported:0,summariesSkipped:0,observationsImported:0,observationsSkipped:0,promptsImported:0,promptsSkipped:0},u=this.dbManager.getSessionStore();if(Array.isArray(a))for(let l of a)u.importSdkSession(l).imported?c.sessionsImported++:c.sessionsSkipped++;if(Array.isArray(s))for(let l of s)u.importSessionSummary(l).imported?c.summariesImported++:c.summariesSkipped++;if(Array.isArray(i))for(let l of i)u.importObservation(l).imported?c.observationsImported++:c.observationsSkipped++;if(Array.isArray(o))for(let l of o)u.importUserPrompt(l).imported?c.promptsImported++:c.promptsSkipped++;n.json({success:!0,stats:c})})};var Fl=class extends Or{constructor(r){super();this.searchManager=r}setupRoutes(r){r.get("/api/search",this.handleUnifiedSearch.bind(this)),r.get("/api/timeline",this.handleUnifiedTimeline.bind(this)),r.get("/api/decisions",this.handleDecisions.bind(this)),r.get("/api/changes",this.handleChanges.bind(this)),r.get("/api/how-it-works",this.handleHowItWorks.bind(this)),r.get("/api/search/observations",this.handleSearchObservations.bind(this)),r.get("/api/search/sessions",this.handleSearchSessions.bind(this)),r.get("/api/search/prompts",this.handleSearchPrompts.bind(this)),r.get("/api/search/by-concept",this.handleSearchByConcept.bind(this)),r.get("/api/search/by-file",this.handleSearchByFile.bind(this)),r.get("/api/search/by-type",this.handleSearchByType.bind(this)),r.get("/api/context/recent",this.handleGetRecentContext.bind(this)),r.get("/api/context/timeline",this.handleGetContextTimeline.bind(this)),r.get("/api/context/preview",this.handleContextPreview.bind(this)),r.get("/api/context/inject",this.handleContextInject.bind(this)),r.get("/api/timeline/by-query",this.handleGetTimelineByQuery.bind(this)),r.get("/api/search/help",this.handleSearchHelp.bind(this))}handleUnifiedSearch=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.search(r.query);n.json(a)});handleUnifiedTimeline=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.timeline(r.query);n.json(a)});handleDecisions=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.decisions(r.query);n.json(a)});handleChanges=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.changes(r.query);n.json(a)});handleHowItWorks=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.howItWorks(r.query);n.json(a)});handleSearchObservations=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.searchObservations(r.query);n.json(a)});handleSearchSessions=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.searchSessions(r.query);n.json(a)});handleSearchPrompts=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.searchUserPrompts(r.query);n.json(a)});handleSearchByConcept=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.findByConcept(r.query);n.json(a)});handleSearchByFile=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.findByFile(r.query);n.json(a)});handleSearchByType=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.findByType(r.query);n.json(a)});handleGetRecentContext=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.getRecentContext(r.query);n.json(a)});handleGetContextTimeline=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.getContextTimeline(r.query);n.json(a)});handleContextPreview=this.wrapHandler(async(r,n)=>{let a=r.query.project;if(!a){this.badRequest(n,"Project parameter is required");return}let{generateContext:s}=await Promise.resolve().then(()=>(Ll(),ql)),i=`/preview/${a}`,o=await s({session_id:"preview-"+Date.now(),cwd:i},!0);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(o)});handleContextInject=this.wrapHandler(async(r,n)=>{let a=r.query.project,s=r.query.colors==="true";if(!a){this.badRequest(n,"Project parameter is required");return}let{generateContext:i}=await Promise.resolve().then(()=>(Ll(),ql)),o=`/context/${a}`,c=await i({session_id:"context-inject-"+Date.now(),cwd:o},s);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(c)});handleGetTimelineByQuery=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.getTimelineByQuery(r.query);n.json(a)});handleSearchHelp=this.wrapHandler((r,n)=>{n.json({title:"Claude-Mem Search API",description:"HTTP API for searching persistent memory",endpoints:[{path:"/api/search/observations",method:"GET",description:"Search observations using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/sessions",method:"GET",description:"Search session summaries using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)"}},{path:"/api/search/prompts",method:"GET",description:"Search user prompts using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/by-concept",method:"GET",description:"Find observations by concept tag",parameters:{concept:"Concept tag (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-file",method:"GET",description:"Find observations and sessions by file path",parameters:{filePath:"File path or partial path (required)",limit:"Number of results per type (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-type",method:"GET",description:"Find observations by type",parameters:{type:"Observation type (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/context/recent",method:"GET",description:"Get recent session context including summaries and observations",parameters:{project:"Project name (default: current directory)",limit:"Number of recent sessions (default: 3)"}},{path:"/api/context/timeline",method:"GET",description:"Get unified timeline around a specific point in time",parameters:{anchor:'Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp (required)',depth_before:"Number of records before anchor (default: 10)",depth_after:"Number of records after anchor (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/timeline/by-query",method:"GET",description:"Search for best match, then get timeline around it",parameters:{query:"Search query (required)",mode:'Search mode: "auto", "observations", or "sessions" (default: "auto")',depth_before:"Number of records before match (default: 10)",depth_after:"Number of records after match (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/help",method:"GET",description:"Get this help documentation"}],examples:['curl "http://localhost:37777/api/search/observations?query=authentication&limit=5"','curl "http://localhost:37777/api/search/by-type?type=bugfix&limit=10"','curl "http://localhost:37777/api/context/recent?project=claude-mem&limit=3"','curl "http://localhost:37777/api/context/timeline?anchor=123&depth_before=5&depth_after=5"']})})};var Un=kt(require("path"),1),zt=require("fs"),Ym=require("os");dr();mt();var Xm=require("child_process"),zn=require("fs"),u$=require("os"),Do=require("path");mt();var qo=(0,Do.join)((0,u$.homedir)(),".claude","plugins","marketplaces","thedotmack");function Km(t){return!t||typeof t!="string"?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.includes("..")}var q7=3e4,Jm=12e4;function Cr(t){let e=(0,Xm.spawnSync)("git",t,{cwd:qo,encoding:"utf-8",timeout:q7,windowsHide:!0,shell:!1});if(e.error)throw e.error;if(e.status!==0)throw new Error(e.stderr||e.stdout||"Git command failed");return e.stdout.trim()}function l$(t,e=Jm){let n=process.platform==="win32"?"npm.cmd":"npm",a=(0,Xm.spawnSync)(n,t,{cwd:qo,encoding:"utf-8",timeout:e,windowsHide:!0,shell:!1});if(a.error)throw a.error;if(a.status!==0)throw new Error(a.stderr||a.stdout||"npm command failed");return a.stdout.trim()}function zl(){let t=(0,Do.join)(qo,".git");if(!(0,zn.existsSync)(t))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=Cr(["rev-parse","--abbrev-ref","HEAD"]),n=Cr(["status","--porcelain"]).length>0,a=e.startsWith("beta");return{branch:e,isBeta:a,isGitRepo:!0,isDirty:n,canSwitch:!0}}catch(e){return U.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function d$(t){if(!Km(t))return{success:!1,error:`Invalid branch name: ${t}. Branch names must be alphanumeric with hyphens, underscores, slashes, or dots.`};let e=zl();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===t)return{success:!0,branch:t,message:`Already on branch ${t}`};try{U.info("BRANCH","Starting branch switch",{from:e.branch,to:t}),U.debug("BRANCH","Discarding local changes"),Cr(["checkout","--","."]),Cr(["clean","-fd"]),U.debug("BRANCH","Fetching from origin"),Cr(["fetch","origin"]),U.debug("BRANCH","Checking out branch",{branch:t});try{Cr(["checkout",t])}catch{Cr(["checkout","-b",t,`origin/${t}`])}U.debug("BRANCH","Pulling latest"),Cr(["pull","origin",t]);let r=(0,Do.join)(qo,".install-version");return(0,zn.existsSync)(r)&&(0,zn.unlinkSync)(r),U.debug("BRANCH","Running npm install"),l$(["install"],Jm),U.success("BRANCH","Branch switch complete",{branch:t}),{success:!0,branch:t,message:`Switched to ${t}. Worker will restart automatically.`}}catch(r){U.error("BRANCH","Branch switch failed",{targetBranch:t},r);try{e.branch&&Km(e.branch)&&Cr(["checkout",e.branch])}catch{}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function p$(){let t=zl();if(!t.isGitRepo||!t.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{if(!Km(t.branch))return{success:!1,error:`Invalid current branch name: ${t.branch}`};U.info("BRANCH","Pulling updates",{branch:t.branch}),Cr(["checkout","--","."]),Cr(["fetch","origin"]),Cr(["pull","origin",t.branch]);let e=(0,Do.join)(qo,".install-version");return(0,zn.existsSync)(e)&&(0,zn.unlinkSync)(e),l$(["install"],Jm),U.success("BRANCH","Updates pulled",{branch:t.branch}),{success:!0,branch:t.branch,message:`Updated ${t.branch}. Worker will restart automatically.`}}catch(e){return U.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}Dr();var Ul=class extends Or{constructor(r){super();this.settingsManager=r}setupRoutes(r){r.get("/api/settings",this.handleGetSettings.bind(this)),r.post("/api/settings",this.handleUpdateSettings.bind(this)),r.get("/api/mcp/status",this.handleGetMcpStatus.bind(this)),r.post("/api/mcp/toggle",this.handleToggleMcp.bind(this)),r.get("/api/branch/status",this.handleGetBranchStatus.bind(this)),r.post("/api/branch/switch",this.handleSwitchBranch.bind(this)),r.post("/api/branch/update",this.handleUpdateBranch.bind(this))}handleGetSettings=this.wrapHandler((r,n)=>{let a=Un.default.join((0,Ym.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(a);let s=ct.loadFromFile(a);n.json(s)});handleUpdateSettings=this.wrapHandler((r,n)=>{let a=this.validateSettings(r.body);if(!a.valid){n.status(400).json({success:!1,error:a.error});return}let s=Un.default.join((0,Ym.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(s);let i={};if((0,zt.existsSync)(s)){let c=(0,zt.readFileSync)(s,"utf-8");i=JSON.parse(c)}let o=["CLAUDE_MEM_MODEL","CLAUDE_MEM_CONTEXT_OBSERVATIONS","CLAUDE_MEM_WORKER_PORT","CLAUDE_MEM_WORKER_HOST","CLAUDE_MEM_DATA_DIR","CLAUDE_MEM_LOG_LEVEL","CLAUDE_MEM_PYTHON_VERSION","CLAUDE_CODE_PATH","CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES","CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS","CLAUDE_MEM_CONTEXT_FULL_COUNT","CLAUDE_MEM_CONTEXT_FULL_FIELD","CLAUDE_MEM_CONTEXT_SESSION_COUNT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let c of o)r.body[c]!==void 0&&(i[c]=r.body[c]);(0,zt.writeFileSync)(s,JSON.stringify(i,null,2),"utf-8"),QE(),U.info("WORKER","Settings updated"),n.json({success:!0,message:"Settings updated successfully"})});handleGetMcpStatus=this.wrapHandler((r,n)=>{let a=this.isMcpEnabled();n.json({enabled:a})});handleToggleMcp=this.wrapHandler((r,n)=>{let{enabled:a}=r.body;if(typeof a!="boolean"){this.badRequest(n,"enabled must be a boolean");return}this.toggleMcp(a),n.json({success:!0,enabled:this.isMcpEnabled()})});handleGetBranchStatus=this.wrapHandler((r,n)=>{let a=zl();n.json(a)});handleSwitchBranch=this.wrapHandler(async(r,n)=>{let{branch:a}=r.body;if(!a){n.status(400).json({success:!1,error:"Missing branch parameter"});return}let s=["main","beta/7.0","feature/bun-executable"];if(!s.includes(a)){n.status(400).json({success:!1,error:`Invalid branch. Allowed: ${s.join(", ")}`});return}U.info("WORKER","Branch switch requested",{branch:a});let i=await d$(a);i.success&&setTimeout(()=>{U.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),n.json(i)});handleUpdateBranch=this.wrapHandler(async(r,n)=>{U.info("WORKER","Branch update requested");let a=await p$();a.success&&setTimeout(()=>{U.info("WORKER","Restarting worker after branch update"),process.exit(0)},1e3),n.json(a)});validateSettings(r){if(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS){let a=parseInt(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10);if(isNaN(a)||a<1||a>200)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_OBSERVATIONS must be between 1 and 200"}}if(r.CLAUDE_MEM_WORKER_PORT){let a=parseInt(r.CLAUDE_MEM_WORKER_PORT,10);if(isNaN(a)||a<1024||a>65535)return{valid:!1,error:"CLAUDE_MEM_WORKER_PORT must be between 1024 and 65535"}}if(r.CLAUDE_MEM_WORKER_HOST){let a=r.CLAUDE_MEM_WORKER_HOST;if(!/^(127\.0\.0\.1|0\.0\.0\.0|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(a))return{valid:!1,error:"CLAUDE_MEM_WORKER_HOST must be a valid IP address (e.g., 127.0.0.1, 0.0.0.0)"}}if(r.CLAUDE_MEM_LOG_LEVEL&&!["DEBUG","INFO","WARN","ERROR","SILENT"].includes(r.CLAUDE_MEM_LOG_LEVEL.toUpperCase()))return{valid:!1,error:"CLAUDE_MEM_LOG_LEVEL must be one of: DEBUG, INFO, WARN, ERROR, SILENT"};if(r.CLAUDE_MEM_PYTHON_VERSION&&!/^3\.\d{1,2}$/.test(r.CLAUDE_MEM_PYTHON_VERSION))return{valid:!1,error:'CLAUDE_MEM_PYTHON_VERSION must be in format "3.X" or "3.XX" (e.g., "3.13")'};let n=["CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let a of n)if(r[a]&&!["true","false"].includes(r[a]))return{valid:!1,error:`${a} must be "true" or "false"`};if(r.CLAUDE_MEM_CONTEXT_FULL_COUNT){let a=parseInt(r.CLAUDE_MEM_CONTEXT_FULL_COUNT,10);if(isNaN(a)||a<0||a>20)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_FULL_COUNT must be between 0 and 20"}}if(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT){let a=parseInt(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10);if(isNaN(a)||a<1||a>50)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_SESSION_COUNT must be between 1 and 50"}}return r.CLAUDE_MEM_CONTEXT_FULL_FIELD&&!["narrative","facts"].includes(r.CLAUDE_MEM_CONTEXT_FULL_FIELD)?{valid:!1,error:'CLAUDE_MEM_CONTEXT_FULL_FIELD must be "narrative" or "facts"'}:{valid:!0}}isMcpEnabled(){let r=nr(),n=Un.default.join(r,"plugin",".mcp.json");return(0,zt.existsSync)(n)}toggleMcp(r){let n=nr(),a=Un.default.join(n,"plugin",".mcp.json"),s=Un.default.join(n,"plugin",".mcp.json.disabled");r&&(0,zt.existsSync)(s)?((0,zt.renameSync)(s,a),U.info("WORKER","MCP search server enabled")):!r&&(0,zt.existsSync)(a)?((0,zt.renameSync)(a,s),U.info("WORKER","MCP search server disabled")):U.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}ensureSettingsFile(r){if(!(0,zt.existsSync)(r)){let n=ct.getAllDefaults(),a=Un.default.dirname(r);(0,zt.existsSync)(a)||(0,zt.mkdirSync)(a,{recursive:!0}),(0,zt.writeFileSync)(r,JSON.stringify(n,null,2),"utf-8"),U.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var Lo=(0,m$.promisify)(Bl.exec),Hl=class{app;server=null;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;paginationHelper;settingsManager;sessionEventBroadcaster;viewerRoutes;sessionRoutes;dataRoutes;searchRoutes;settingsRoutes;initializationComplete;resolveInitialization;constructor(){this.app=(0,f$.default)(),this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new ju,this.sessionManager=new Du(this.dbManager),this.sseBroadcaster=new qu,this.sdkAgent=new xl(this.dbManager,this.sessionManager),this.paginationHelper=new wl(this.dbManager),this.settingsManager=new Sl(this.dbManager),this.sessionEventBroadcaster=new Rl(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new As({name:"worker-search-proxy",version:"1.0.0"},{capabilities:{}}),this.viewerRoutes=new Ol(this.sseBroadcaster,this.dbManager,this.sessionManager),this.sessionRoutes=new Al(this.sessionManager,this.dbManager,this.sdkAgent,this.sessionEventBroadcaster,this),this.dataRoutes=new Nl(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime),this.searchRoutes=null,this.settingsRoutes=new Ul(this.settingsManager),this.setupMiddleware(),this.setupRoutes()}setupMiddleware(){Yk(this.summarizeRequestBody.bind(this)).forEach(r=>this.app.use(r))}setupRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,n)=>{n.status(200).json({status:"ok",build:e,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.initializationCompleteFlag,mcpReady:this.mcpReady})}),this.app.get("/api/readiness",(r,n)=>{this.initializationCompleteFlag?n.status(200).json({status:"ready",mcpReady:this.mcpReady}):n.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,n)=>{let{homedir:a}=require("os"),{readFileSync:s}=require("fs"),i=pi.default.join(a(),".claude","plugins","marketplaces","thedotmack"),o=pi.default.join(i,"package.json"),c=JSON.parse(s(o,"utf-8"));n.status(200).json({version:c.version})}),this.app.get("/api/instructions",async(r,n)=>{let a=r.query.topic||"all",s=r.query.operation;try{let i;if(s){let o=pi.default.join(__dirname,"../skills/mem-search/operations",`${s}.md`);i=await Qm.promises.readFile(o,"utf-8")}else{let o=pi.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await Qm.promises.readFile(o,"utf-8");i=this.extractInstructionSection(c,a)}n.json({content:[{type:"text",text:i}]})}catch(i){U.error("WORKER","Failed to load instructions",{topic:a,operation:s},i),n.status(500).json({content:[{type:"text",text:`Error loading instructions: ${i instanceof Error?i.message:"Unknown error"}`}],isError:!0})}}),this.app.post("/api/admin/restart",Zm,async(r,n)=>{n.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(U.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.app.post("/api/admin/shutdown",Zm,async(r,n)=>{n.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(U.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.viewerRoutes.setupRoutes(this.app),this.sessionRoutes.setupRoutes(this.app),this.dataRoutes.setupRoutes(this.app),this.settingsRoutes.setupRoutes(this.app),this.app.get("/api/context/inject",async(r,n,a)=>{try{let i=new Promise((f,m)=>setTimeout(()=>m(new Error("Initialization timeout")),3e4));if(await Promise.race([this.initializationComplete,i]),!this.searchRoutes){n.status(503).json({error:"Search routes not initialized"});return}let o=r.query.project,c=r.query.colors==="true";if(!o){n.status(400).json({error:"Project parameter is required"});return}let{generateContext:u}=await Promise.resolve().then(()=>(Ll(),ql)),l=`/context/${o}`,d=await u({session_id:"context-inject-"+Date.now(),cwd:l},c);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(d)}catch(s){U.error("WORKER","Context inject handler failed",{},s),n.status(500).json({error:s instanceof Error?s.message:"Internal server error"})}})}async cleanupOrphanedProcesses(){let e=process.platform==="win32",r=[];if(e){let n=`powershell -Command "Get-CimInstance Win32_Process | Where-Object { $_.Name -like '*python*' -and $_.CommandLine -like '*chroma-mcp*' } | Select-Object -ExpandProperty ProcessId"`,{stdout:a}=await Lo(n,{timeout:5e3});if(!a.trim()){U.debug("SYSTEM","No orphaned chroma-mcp processes found (Windows)");return}let s=a.trim().split(` + `).all().map(o=>o.project);n.json({projects:i})});handleGetProcessingStatus=this.wrapHandler((r,n)=>{let a=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalActiveWork();n.json({isProcessing:a,queueDepth:s})});handleSetProcessing=this.wrapHandler((r,n)=>{this.workerService.broadcastProcessingStatus();let a=this.sessionManager.isAnySessionProcessing(),s=this.sessionManager.getTotalQueueDepth(),i=this.sessionManager.getActiveSessionCount();n.json({status:"ok",isProcessing:a,queueDepth:s,activeSessions:i})});parsePaginationParams(r){let n=parseInt(r.query.offset,10)||0,a=Math.min(parseInt(r.query.limit,10)||20,100),s=r.query.project;return{offset:n,limit:a,project:s}}handleImport=this.wrapHandler((r,n)=>{let{sessions:a,summaries:s,observations:i,prompts:o}=r.body,c={sessionsImported:0,sessionsSkipped:0,summariesImported:0,summariesSkipped:0,observationsImported:0,observationsSkipped:0,promptsImported:0,promptsSkipped:0},u=this.dbManager.getSessionStore();if(Array.isArray(a))for(let l of a)u.importSdkSession(l).imported?c.sessionsImported++:c.sessionsSkipped++;if(Array.isArray(s))for(let l of s)u.importSessionSummary(l).imported?c.summariesImported++:c.summariesSkipped++;if(Array.isArray(i))for(let l of i)u.importObservation(l).imported?c.observationsImported++:c.observationsSkipped++;if(Array.isArray(o))for(let l of o)u.importUserPrompt(l).imported?c.promptsImported++:c.promptsSkipped++;n.json({success:!0,stats:c})})};var Fl=class extends Or{constructor(r){super();this.searchManager=r}setupRoutes(r){r.get("/api/search",this.handleUnifiedSearch.bind(this)),r.get("/api/timeline",this.handleUnifiedTimeline.bind(this)),r.get("/api/decisions",this.handleDecisions.bind(this)),r.get("/api/changes",this.handleChanges.bind(this)),r.get("/api/how-it-works",this.handleHowItWorks.bind(this)),r.get("/api/search/observations",this.handleSearchObservations.bind(this)),r.get("/api/search/sessions",this.handleSearchSessions.bind(this)),r.get("/api/search/prompts",this.handleSearchPrompts.bind(this)),r.get("/api/search/by-concept",this.handleSearchByConcept.bind(this)),r.get("/api/search/by-file",this.handleSearchByFile.bind(this)),r.get("/api/search/by-type",this.handleSearchByType.bind(this)),r.get("/api/context/recent",this.handleGetRecentContext.bind(this)),r.get("/api/context/timeline",this.handleGetContextTimeline.bind(this)),r.get("/api/context/preview",this.handleContextPreview.bind(this)),r.get("/api/context/inject",this.handleContextInject.bind(this)),r.get("/api/timeline/by-query",this.handleGetTimelineByQuery.bind(this)),r.get("/api/search/help",this.handleSearchHelp.bind(this))}handleUnifiedSearch=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.search(r.query);n.json(a)});handleUnifiedTimeline=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.timeline(r.query);n.json(a)});handleDecisions=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.decisions(r.query);n.json(a)});handleChanges=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.changes(r.query);n.json(a)});handleHowItWorks=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.howItWorks(r.query);n.json(a)});handleSearchObservations=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.searchObservations(r.query);n.json(a)});handleSearchSessions=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.searchSessions(r.query);n.json(a)});handleSearchPrompts=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.searchUserPrompts(r.query);n.json(a)});handleSearchByConcept=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.findByConcept(r.query);n.json(a)});handleSearchByFile=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.findByFile(r.query);n.json(a)});handleSearchByType=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.findByType(r.query);n.json(a)});handleGetRecentContext=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.getRecentContext(r.query);n.json(a)});handleGetContextTimeline=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.getContextTimeline(r.query);n.json(a)});handleContextPreview=this.wrapHandler(async(r,n)=>{let a=r.query.project;if(!a){this.badRequest(n,"Project parameter is required");return}let{generateContext:s}=await Promise.resolve().then(()=>(Ll(),ql)),i=`/preview/${a}`,o=await s({session_id:"preview-"+Date.now(),cwd:i},!0);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(o)});handleContextInject=this.wrapHandler(async(r,n)=>{let a=r.query.project,s=r.query.colors==="true";if(!a){this.badRequest(n,"Project parameter is required");return}let{generateContext:i}=await Promise.resolve().then(()=>(Ll(),ql)),o=`/context/${a}`,c=await i({session_id:"context-inject-"+Date.now(),cwd:o},s);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(c)});handleGetTimelineByQuery=this.wrapHandler(async(r,n)=>{let a=await this.searchManager.getTimelineByQuery(r.query);n.json(a)});handleSearchHelp=this.wrapHandler((r,n)=>{n.json({title:"Claude-Mem Search API",description:"HTTP API for searching persistent memory",endpoints:[{path:"/api/search/observations",method:"GET",description:"Search observations using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/sessions",method:"GET",description:"Search session summaries using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)"}},{path:"/api/search/prompts",method:"GET",description:"Search user prompts using full-text search",parameters:{query:"Search query (required)",limit:"Number of results (default: 20)",project:"Filter by project name (optional)"}},{path:"/api/search/by-concept",method:"GET",description:"Find observations by concept tag",parameters:{concept:"Concept tag (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-file",method:"GET",description:"Find observations and sessions by file path",parameters:{filePath:"File path or partial path (required)",limit:"Number of results per type (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/by-type",method:"GET",description:"Find observations by type",parameters:{type:"Observation type (required): discovery, decision, bugfix, feature, refactor",limit:"Number of results (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/context/recent",method:"GET",description:"Get recent session context including summaries and observations",parameters:{project:"Project name (default: current directory)",limit:"Number of recent sessions (default: 3)"}},{path:"/api/context/timeline",method:"GET",description:"Get unified timeline around a specific point in time",parameters:{anchor:'Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp (required)',depth_before:"Number of records before anchor (default: 10)",depth_after:"Number of records after anchor (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/timeline/by-query",method:"GET",description:"Search for best match, then get timeline around it",parameters:{query:"Search query (required)",mode:'Search mode: "auto", "observations", or "sessions" (default: "auto")',depth_before:"Number of records before match (default: 10)",depth_after:"Number of records after match (default: 10)",project:"Filter by project name (optional)"}},{path:"/api/search/help",method:"GET",description:"Get this help documentation"}],examples:['curl "http://localhost:37777/api/search/observations?query=authentication&limit=5"','curl "http://localhost:37777/api/search/by-type?type=bugfix&limit=10"','curl "http://localhost:37777/api/context/recent?project=claude-mem&limit=3"','curl "http://localhost:37777/api/context/timeline?anchor=123&depth_before=5&depth_after=5"']})})};var Un=$t(require("path"),1),zt=require("fs"),Ym=require("os");dr();mt();var Xm=require("child_process"),zn=require("fs"),u$=require("os"),Do=require("path");mt();var qo=(0,Do.join)((0,u$.homedir)(),".claude","plugins","marketplaces","thedotmack");function Km(t){return!t||typeof t!="string"?!1:/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(t)&&!t.includes("..")}var q7=3e4,Jm=12e4;function Cr(t){let e=(0,Xm.spawnSync)("git",t,{cwd:qo,encoding:"utf-8",timeout:q7,windowsHide:!0,shell:!1});if(e.error)throw e.error;if(e.status!==0)throw new Error(e.stderr||e.stdout||"Git command failed");return e.stdout.trim()}function l$(t,e=Jm){let n=process.platform==="win32"?"npm.cmd":"npm",a=(0,Xm.spawnSync)(n,t,{cwd:qo,encoding:"utf-8",timeout:e,windowsHide:!0,shell:!1});if(a.error)throw a.error;if(a.status!==0)throw new Error(a.stderr||a.stdout||"npm command failed");return a.stdout.trim()}function zl(){let t=(0,Do.join)(qo,".git");if(!(0,zn.existsSync)(t))return{branch:null,isBeta:!1,isGitRepo:!1,isDirty:!1,canSwitch:!1,error:"Installed plugin is not a git repository"};try{let e=Cr(["rev-parse","--abbrev-ref","HEAD"]),n=Cr(["status","--porcelain"]).length>0,a=e.startsWith("beta");return{branch:e,isBeta:a,isGitRepo:!0,isDirty:n,canSwitch:!0}}catch(e){return U.error("BRANCH","Failed to get branch info",{},e),{branch:null,isBeta:!1,isGitRepo:!0,isDirty:!1,canSwitch:!1,error:e.message}}}async function d$(t){if(!Km(t))return{success:!1,error:`Invalid branch name: ${t}. Branch names must be alphanumeric with hyphens, underscores, slashes, or dots.`};let e=zl();if(!e.isGitRepo)return{success:!1,error:"Installed plugin is not a git repository. Please reinstall."};if(e.branch===t)return{success:!0,branch:t,message:`Already on branch ${t}`};try{U.info("BRANCH","Starting branch switch",{from:e.branch,to:t}),U.debug("BRANCH","Discarding local changes"),Cr(["checkout","--","."]),Cr(["clean","-fd"]),U.debug("BRANCH","Fetching from origin"),Cr(["fetch","origin"]),U.debug("BRANCH","Checking out branch",{branch:t});try{Cr(["checkout",t])}catch{Cr(["checkout","-b",t,`origin/${t}`])}U.debug("BRANCH","Pulling latest"),Cr(["pull","origin",t]);let r=(0,Do.join)(qo,".install-version");return(0,zn.existsSync)(r)&&(0,zn.unlinkSync)(r),U.debug("BRANCH","Running npm install"),l$(["install"],Jm),U.success("BRANCH","Branch switch complete",{branch:t}),{success:!0,branch:t,message:`Switched to ${t}. Worker will restart automatically.`}}catch(r){U.error("BRANCH","Branch switch failed",{targetBranch:t},r);try{e.branch&&Km(e.branch)&&Cr(["checkout",e.branch])}catch{}return{success:!1,error:`Branch switch failed: ${r.message}`}}}async function p$(){let t=zl();if(!t.isGitRepo||!t.branch)return{success:!1,error:"Cannot pull updates: not a git repository"};try{if(!Km(t.branch))return{success:!1,error:`Invalid current branch name: ${t.branch}`};U.info("BRANCH","Pulling updates",{branch:t.branch}),Cr(["checkout","--","."]),Cr(["fetch","origin"]),Cr(["pull","origin",t.branch]);let e=(0,Do.join)(qo,".install-version");return(0,zn.existsSync)(e)&&(0,zn.unlinkSync)(e),l$(["install"],Jm),U.success("BRANCH","Updates pulled",{branch:t.branch}),{success:!0,branch:t.branch,message:`Updated ${t.branch}. Worker will restart automatically.`}}catch(e){return U.error("BRANCH","Pull failed",{},e),{success:!1,error:`Pull failed: ${e.message}`}}}Dr();var Ul=class extends Or{constructor(r){super();this.settingsManager=r}setupRoutes(r){r.get("/api/settings",this.handleGetSettings.bind(this)),r.post("/api/settings",this.handleUpdateSettings.bind(this)),r.get("/api/mcp/status",this.handleGetMcpStatus.bind(this)),r.post("/api/mcp/toggle",this.handleToggleMcp.bind(this)),r.get("/api/branch/status",this.handleGetBranchStatus.bind(this)),r.post("/api/branch/switch",this.handleSwitchBranch.bind(this)),r.post("/api/branch/update",this.handleUpdateBranch.bind(this))}handleGetSettings=this.wrapHandler((r,n)=>{let a=Un.default.join((0,Ym.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(a);let s=ct.loadFromFile(a);n.json(s)});handleUpdateSettings=this.wrapHandler((r,n)=>{let a=this.validateSettings(r.body);if(!a.valid){n.status(400).json({success:!1,error:a.error});return}let s=Un.default.join((0,Ym.homedir)(),".claude-mem","settings.json");this.ensureSettingsFile(s);let i={};if((0,zt.existsSync)(s)){let c=(0,zt.readFileSync)(s,"utf-8");i=JSON.parse(c)}let o=["CLAUDE_MEM_MODEL","CLAUDE_MEM_CONTEXT_OBSERVATIONS","CLAUDE_MEM_WORKER_PORT","CLAUDE_MEM_WORKER_HOST","CLAUDE_MEM_DATA_DIR","CLAUDE_MEM_LOG_LEVEL","CLAUDE_MEM_PYTHON_VERSION","CLAUDE_CODE_PATH","CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES","CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS","CLAUDE_MEM_CONTEXT_FULL_COUNT","CLAUDE_MEM_CONTEXT_FULL_FIELD","CLAUDE_MEM_CONTEXT_SESSION_COUNT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let c of o)r.body[c]!==void 0&&(i[c]=r.body[c]);(0,zt.writeFileSync)(s,JSON.stringify(i,null,2),"utf-8"),QE(),U.info("WORKER","Settings updated"),n.json({success:!0,message:"Settings updated successfully"})});handleGetMcpStatus=this.wrapHandler((r,n)=>{let a=this.isMcpEnabled();n.json({enabled:a})});handleToggleMcp=this.wrapHandler((r,n)=>{let{enabled:a}=r.body;if(typeof a!="boolean"){this.badRequest(n,"enabled must be a boolean");return}this.toggleMcp(a),n.json({success:!0,enabled:this.isMcpEnabled()})});handleGetBranchStatus=this.wrapHandler((r,n)=>{let a=zl();n.json(a)});handleSwitchBranch=this.wrapHandler(async(r,n)=>{let{branch:a}=r.body;if(!a){n.status(400).json({success:!1,error:"Missing branch parameter"});return}let s=["main","beta/7.0","feature/bun-executable"];if(!s.includes(a)){n.status(400).json({success:!1,error:`Invalid branch. Allowed: ${s.join(", ")}`});return}U.info("WORKER","Branch switch requested",{branch:a});let i=await d$(a);i.success&&setTimeout(()=>{U.info("WORKER","Restarting worker after branch switch"),process.exit(0)},1e3),n.json(i)});handleUpdateBranch=this.wrapHandler(async(r,n)=>{U.info("WORKER","Branch update requested");let a=await p$();a.success&&setTimeout(()=>{U.info("WORKER","Restarting worker after branch update"),process.exit(0)},1e3),n.json(a)});validateSettings(r){if(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS){let a=parseInt(r.CLAUDE_MEM_CONTEXT_OBSERVATIONS,10);if(isNaN(a)||a<1||a>200)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_OBSERVATIONS must be between 1 and 200"}}if(r.CLAUDE_MEM_WORKER_PORT){let a=parseInt(r.CLAUDE_MEM_WORKER_PORT,10);if(isNaN(a)||a<1024||a>65535)return{valid:!1,error:"CLAUDE_MEM_WORKER_PORT must be between 1024 and 65535"}}if(r.CLAUDE_MEM_WORKER_HOST){let a=r.CLAUDE_MEM_WORKER_HOST;if(!/^(127\.0\.0\.1|0\.0\.0\.0|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(a))return{valid:!1,error:"CLAUDE_MEM_WORKER_HOST must be a valid IP address (e.g., 127.0.0.1, 0.0.0.0)"}}if(r.CLAUDE_MEM_LOG_LEVEL&&!["DEBUG","INFO","WARN","ERROR","SILENT"].includes(r.CLAUDE_MEM_LOG_LEVEL.toUpperCase()))return{valid:!1,error:"CLAUDE_MEM_LOG_LEVEL must be one of: DEBUG, INFO, WARN, ERROR, SILENT"};if(r.CLAUDE_MEM_PYTHON_VERSION&&!/^3\.\d{1,2}$/.test(r.CLAUDE_MEM_PYTHON_VERSION))return{valid:!1,error:'CLAUDE_MEM_PYTHON_VERSION must be in format "3.X" or "3.XX" (e.g., "3.13")'};let n=["CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT","CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT","CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY","CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE"];for(let a of n)if(r[a]&&!["true","false"].includes(r[a]))return{valid:!1,error:`${a} must be "true" or "false"`};if(r.CLAUDE_MEM_CONTEXT_FULL_COUNT){let a=parseInt(r.CLAUDE_MEM_CONTEXT_FULL_COUNT,10);if(isNaN(a)||a<0||a>20)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_FULL_COUNT must be between 0 and 20"}}if(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT){let a=parseInt(r.CLAUDE_MEM_CONTEXT_SESSION_COUNT,10);if(isNaN(a)||a<1||a>50)return{valid:!1,error:"CLAUDE_MEM_CONTEXT_SESSION_COUNT must be between 1 and 50"}}return r.CLAUDE_MEM_CONTEXT_FULL_FIELD&&!["narrative","facts"].includes(r.CLAUDE_MEM_CONTEXT_FULL_FIELD)?{valid:!1,error:'CLAUDE_MEM_CONTEXT_FULL_FIELD must be "narrative" or "facts"'}:{valid:!0}}isMcpEnabled(){let r=nr(),n=Un.default.join(r,"plugin",".mcp.json");return(0,zt.existsSync)(n)}toggleMcp(r){let n=nr(),a=Un.default.join(n,"plugin",".mcp.json"),s=Un.default.join(n,"plugin",".mcp.json.disabled");r&&(0,zt.existsSync)(s)?((0,zt.renameSync)(s,a),U.info("WORKER","MCP search server enabled")):!r&&(0,zt.existsSync)(a)?((0,zt.renameSync)(a,s),U.info("WORKER","MCP search server disabled")):U.debug("WORKER","MCP toggle no-op (already in desired state)",{enabled:r})}ensureSettingsFile(r){if(!(0,zt.existsSync)(r)){let n=ct.getAllDefaults(),a=Un.default.dirname(r);(0,zt.existsSync)(a)||(0,zt.mkdirSync)(a,{recursive:!0}),(0,zt.writeFileSync)(r,JSON.stringify(n,null,2),"utf-8"),U.info("SETTINGS","Created settings file with defaults",{settingsPath:r})}}};var Lo=(0,m$.promisify)(Bl.exec),Hl=class{app;server=null;startTime=Date.now();mcpClient;mcpReady=!1;initializationCompleteFlag=!1;dbManager;sessionManager;sseBroadcaster;sdkAgent;paginationHelper;settingsManager;sessionEventBroadcaster;viewerRoutes;sessionRoutes;dataRoutes;searchRoutes;settingsRoutes;initializationComplete;resolveInitialization;constructor(){this.app=(0,f$.default)(),this.initializationComplete=new Promise(e=>{this.resolveInitialization=e}),this.dbManager=new ju,this.sessionManager=new Du(this.dbManager),this.sseBroadcaster=new qu,this.sdkAgent=new xl(this.dbManager,this.sessionManager),this.paginationHelper=new wl(this.dbManager),this.settingsManager=new Sl(this.dbManager),this.sessionEventBroadcaster=new Rl(this.sseBroadcaster,this),this.sessionManager.setOnSessionDeleted(()=>{this.broadcastProcessingStatus()}),this.mcpClient=new As({name:"worker-search-proxy",version:"1.0.0"},{capabilities:{}}),this.viewerRoutes=new Ol(this.sseBroadcaster,this.dbManager,this.sessionManager),this.sessionRoutes=new Al(this.sessionManager,this.dbManager,this.sdkAgent,this.sessionEventBroadcaster,this),this.dataRoutes=new Nl(this.paginationHelper,this.dbManager,this.sessionManager,this.sseBroadcaster,this,this.startTime),this.searchRoutes=null,this.settingsRoutes=new Ul(this.settingsManager),this.setupMiddleware(),this.setupRoutes()}setupMiddleware(){Yk(this.summarizeRequestBody.bind(this)).forEach(r=>this.app.use(r))}setupRoutes(){let e="TEST-008-wrapper-ipc";this.app.get("/api/health",(r,n)=>{n.status(200).json({status:"ok",build:e,managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.initializationCompleteFlag,mcpReady:this.mcpReady})}),this.app.get("/api/readiness",(r,n)=>{this.initializationCompleteFlag?n.status(200).json({status:"ready",mcpReady:this.mcpReady}):n.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(r,n)=>{let{homedir:a}=require("os"),{readFileSync:s}=require("fs"),i=pi.default.join(a(),".claude","plugins","marketplaces","thedotmack"),o=pi.default.join(i,"package.json"),c=JSON.parse(s(o,"utf-8"));n.status(200).json({version:c.version})}),this.app.get("/api/instructions",async(r,n)=>{let a=r.query.topic||"all",s=r.query.operation;try{let i;if(s){let o=pi.default.join(__dirname,"../skills/mem-search/operations",`${s}.md`);i=await Qm.promises.readFile(o,"utf-8")}else{let o=pi.default.join(__dirname,"../skills/mem-search/SKILL.md"),c=await Qm.promises.readFile(o,"utf-8");i=this.extractInstructionSection(c,a)}n.json({content:[{type:"text",text:i}]})}catch(i){U.error("WORKER","Failed to load instructions",{topic:a,operation:s},i),n.status(500).json({content:[{type:"text",text:`Error loading instructions: ${i instanceof Error?i.message:"Unknown error"}`}],isError:!0})}}),this.app.post("/api/admin/restart",Zm,async(r,n)=>{n.json({status:"restarting"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(U.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.app.post("/api/admin/shutdown",Zm,async(r,n)=>{n.json({status:"shutting_down"}),process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(U.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):setTimeout(async()=>{await this.shutdown(),process.exit(0)},100)}),this.viewerRoutes.setupRoutes(this.app),this.sessionRoutes.setupRoutes(this.app),this.dataRoutes.setupRoutes(this.app),this.settingsRoutes.setupRoutes(this.app),this.app.get("/api/context/inject",async(r,n,a)=>{try{let i=new Promise((f,m)=>setTimeout(()=>m(new Error("Initialization timeout")),3e4));if(await Promise.race([this.initializationComplete,i]),!this.searchRoutes){n.status(503).json({error:"Search routes not initialized"});return}let o=r.query.project,c=r.query.colors==="true";if(!o){n.status(400).json({error:"Project parameter is required"});return}let{generateContext:u}=await Promise.resolve().then(()=>(Ll(),ql)),l=`/context/${o}`,d=await u({session_id:"context-inject-"+Date.now(),cwd:l},c);n.setHeader("Content-Type","text/plain; charset=utf-8"),n.send(d)}catch(s){U.error("WORKER","Context inject handler failed",{},s),n.status(500).json({error:s instanceof Error?s.message:"Internal server error"})}})}async cleanupOrphanedProcesses(){let e=process.platform==="win32",r=[];if(e){let n=`powershell -Command "Get-CimInstance Win32_Process | Where-Object { $_.Name -like '*python*' -and $_.CommandLine -like '*chroma-mcp*' } | Select-Object -ExpandProperty ProcessId"`,{stdout:a}=await Lo(n,{timeout:5e3});if(!a.trim()){U.debug("SYSTEM","No orphaned chroma-mcp processes found (Windows)");return}let s=a.trim().split(` `);for(let i of s){let o=parseInt(i.trim(),10);!isNaN(o)&&Number.isInteger(o)&&o>0&&r.push(o)}}else{let{stdout:n}=await Lo('ps aux | grep "chroma-mcp" | grep -v grep || true');if(!n.trim()){U.debug("SYSTEM","No orphaned chroma-mcp processes found (Unix)");return}let a=n.trim().split(` `);for(let s of a){let i=s.trim().split(/\s+/);if(i.length>1){let o=parseInt(i[1],10);!isNaN(o)&&Number.isInteger(o)&&o>0&&r.push(o)}}}if(r.length!==0){if(U.info("SYSTEM","Cleaning up orphaned chroma-mcp processes",{platform:e?"Windows":"Unix",count:r.length,pids:r}),e)for(let n of r){if(!Number.isInteger(n)||n<=0){U.warn("SYSTEM","Skipping invalid PID",{pid:n});continue}(0,Bl.execSync)(`taskkill /PID ${n} /T /F`,{timeout:5e3,stdio:"ignore"})}else await Lo(`kill ${r.join(" ")}`);U.info("SYSTEM","Orphaned processes cleaned up",{count:r.length})}}async start(){let e=qs(),r=YE();this.server=await new Promise((n,a)=>{let s=this.app.listen(e,r,()=>n(s));s.on("error",a)}),U.info("SYSTEM","Worker started",{host:r,port:e,pid:process.pid}),this.initializeBackground().catch(n=>{U.error("SYSTEM","Background initialization failed",{},n)})}async initializeBackground(){try{await this.cleanupOrphanedProcesses();let{ModeManager:e}=await Promise.resolve().then(()=>(La(),s1)),{SettingsDefaultsManager:r}=await Promise.resolve().then(()=>(Dr(),LE)),{USER_SETTINGS_PATH:n}=await Promise.resolve().then(()=>(dr(),KE)),s=r.loadFromFile(n).CLAUDE_MEM_MODE;e.getInstance().loadMode(s),U.info("SYSTEM",`Mode loaded: ${s}`),await this.dbManager.initialize();let i=new kl,o=new $l,c=new Tl(this.dbManager.getSessionSearch(),this.dbManager.getSessionStore(),this.dbManager.getChromaSync(),i,o);this.searchRoutes=new Fl(c),this.searchRoutes.setupRoutes(this.app),U.info("WORKER","SearchManager initialized and search routes registered");let u=pi.default.join(__dirname,"mcp-server.cjs"),l=new Ms({command:"node",args:[u],env:process.env}),d=15e3,f=this.mcpClient.connect(l),m=new Promise((g,b)=>setTimeout(()=>b(new Error("MCP connection timeout after 15s")),d));await Promise.race([f,m]),this.mcpReady=!0,U.success("WORKER","Connected to MCP server"),this.initializationCompleteFlag=!0,this.resolveInitialization(),U.info("SYSTEM","Background initialization complete")}catch(e){throw U.error("SYSTEM","Background initialization failed",{},e),e}}extractInstructionSection(e,r){let n={workflow:this.extractBetween(e,"## The Workflow","## Search Parameters"),search_params:this.extractBetween(e,"## Search Parameters","## Examples"),examples:this.extractBetween(e,"## Examples","## Why This Workflow"),all:e};return n[r]||n.all}extractBetween(e,r,n){let a=e.indexOf(r),s=e.indexOf(n);return a===-1?e:s===-1?e.substring(a):e.substring(a,s).trim()}async shutdown(){U.info("SYSTEM","Shutdown initiated");let e=await this.getChildProcesses(process.pid);if(U.info("SYSTEM","Found child processes",{count:e.length,pids:e}),this.server&&(this.server.closeAllConnections(),await new Promise((r,n)=>{this.server.close(a=>a?n(a):r())}),this.server=null,U.info("SYSTEM","HTTP server closed")),await this.sessionManager.shutdownAll(),this.mcpClient&&(await this.mcpClient.close(),U.info("SYSTEM","MCP client closed")),await this.dbManager.close(),e.length>0){U.info("SYSTEM","Force killing remaining children");for(let r of e)await this.forceKillProcess(r);await this.waitForProcessesExit(e,5e3)}U.info("SYSTEM","Worker shutdown complete")}async getChildProcesses(e){if(process.platform!=="win32")return[];if(!Number.isInteger(e)||e<=0)return U.warn("SYSTEM","Invalid parent PID for child process enumeration",{parentPid:e}),[];let r=`powershell -Command "Get-CimInstance Win32_Process | Where-Object { $_.ParentProcessId -eq ${e} } | Select-Object -ExpandProperty ProcessId"`,{stdout:n}=await Lo(r,{timeout:5e3});return n.trim().split(` `).map(a=>parseInt(a.trim(),10)).filter(a=>!isNaN(a)&&Number.isInteger(a)&&a>0)}async forceKillProcess(e){if(!Number.isInteger(e)||e<=0){U.warn("SYSTEM","Invalid PID for force kill",{pid:e});return}process.platform==="win32"?(await Lo(`taskkill /PID ${e} /T /F`,{timeout:5e3}),U.info("SYSTEM","Killed process",{pid:e})):process.kill(e,"SIGKILL")}async waitForProcessesExit(e,r){let n=Date.now();for(;Date.now()-n(process.kill(s,0),!0));if(a.length===0){U.info("SYSTEM","All child processes exited");return}U.debug("SYSTEM","Waiting for processes to exit",{stillAlive:a}),await new Promise(s=>setTimeout(s,100))}U.warn("SYSTEM","Timeout waiting for child processes to exit")}summarizeRequestBody(e,r,n){return Qk(e,r,n)}broadcastProcessingStatus(){let e=this.sessionManager.isAnySessionProcessing(),r=this.sessionManager.getTotalActiveWork(),n=this.sessionManager.getActiveSessionCount();U.info("WORKER","Broadcasting processing status",{isProcessing:e,queueDepth:r,activeSessions:n}),this.sseBroadcaster.broadcast({type:"processing_status",isProcessing:e,queueDepth:r})}};if(require.main===module||!module.parent){let t=new Hl;process.on("SIGTERM",async()=>{U.info("SYSTEM","Received SIGTERM, shutting down gracefully"),await t.shutdown(),process.exit(0)}),process.on("SIGINT",async()=>{U.info("SYSTEM","Received SIGINT, shutting down gracefully"),await t.shutdown(),process.exit(0)}),t.start().catch(e=>{U.failure("SYSTEM","Worker failed to start",{},e),process.exit(1)})}0&&(module.exports={WorkerService}); diff --git a/ragtime/ragtime.ts b/ragtime/ragtime.ts new file mode 100644 index 00000000..85219a4a --- /dev/null +++ b/ragtime/ragtime.ts @@ -0,0 +1,39 @@ +import { query } from "@anthropic-ai/claude-agent-sdk"; +import * as fs from "fs"; +import * as path from "path"; + +const pathToFolder = "/Users/alexnewman/Scripts/claude-mem/datasets/emails-markdown/"; +const pathToPlugin = "/Users/alexnewman/Scripts/claude-mem/plugin/"; + +// Or read from a directory +const filesToProcess = fs + .readdirSync(pathToFolder) + .filter((f) => f.endsWith(".md")) + .map((f) => path.join(pathToFolder, f)); + +var i = 0; + +for (const file of filesToProcess) { + i++; + // Limit for testing + if (i > 3) break; + + console.log(`\n=== Processing ${file} ===\n`); + + for await (const message of query({ + prompt: `Read ${file} and think about how it relates to the injected context above (if any).`, + options: { + cwd: pathToFolder, + plugins: [{ type: "local", path: pathToPlugin }], + }, + })) { + if (message.type === "system" && message.subtype === "init") { + console.log("Plugins:", message.plugins); + console.log("Commands:", message.slash_commands); + } + + if (message.type === "assistant") { + console.log("Assistant:", message.message.content); + } + } +} diff --git a/src/services/context-generator.ts b/src/services/context-generator.ts index fcf2941d..2ad3aa6b 100644 --- a/src/services/context-generator.ts +++ b/src/services/context-generator.ts @@ -55,6 +55,28 @@ function loadContextConfig(): ContextConfig { const settingsPath = path.join(homedir(), '.claude-mem', 'settings.json'); const settings = SettingsDefaultsManager.loadFromFile(settingsPath); + // For non-code modes, use all types/concepts from active mode instead of settings + const modeId = settings.CLAUDE_MEM_MODE; + const isCodeMode = modeId === 'code' || modeId.startsWith('code--'); + + let observationTypes: Set; + let observationConcepts: Set; + + if (isCodeMode) { + // Code mode: use settings-based filtering + observationTypes = new Set( + settings.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(',').map((t: string) => t.trim()).filter(Boolean) + ); + observationConcepts = new Set( + settings.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(',').map((c: string) => c.trim()).filter(Boolean) + ); + } else { + // Non-code modes: use all types/concepts from active mode + const mode = ModeManager.getInstance().getActiveMode(); + observationTypes = new Set(mode.observation_types.map(t => t.id)); + observationConcepts = new Set(mode.observation_concepts.map(c => c.id)); + } + return { totalObservationCount: parseInt(settings.CLAUDE_MEM_CONTEXT_OBSERVATIONS, 10), fullObservationCount: parseInt(settings.CLAUDE_MEM_CONTEXT_FULL_COUNT, 10), @@ -63,12 +85,8 @@ function loadContextConfig(): ContextConfig { showWorkTokens: settings.CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS === 'true', showSavingsAmount: settings.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT === 'true', showSavingsPercent: settings.CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT === 'true', - observationTypes: new Set( - settings.CLAUDE_MEM_CONTEXT_OBSERVATION_TYPES.split(',').map((t: string) => t.trim()).filter(Boolean) - ), - observationConcepts: new Set( - settings.CLAUDE_MEM_CONTEXT_OBSERVATION_CONCEPTS.split(',').map((c: string) => c.trim()).filter(Boolean) - ), + observationTypes, + observationConcepts, fullObservationField: settings.CLAUDE_MEM_CONTEXT_FULL_FIELD as 'narrative' | 'facts', showLastSummary: settings.CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY === 'true', showLastMessage: settings.CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE === 'true',