@bjlee2024/claude-mem 13.4.6 → 13.4.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ {
2
+ "name": "bjlee2024",
3
+ "owner": {
4
+ "name": "Alex Newman"
5
+ },
6
+ "metadata": {
7
+ "description": "Plugins by Alex Newman (bjlee2024)",
8
+ "homepage": "https://github.com/bjlee2024/claude-mem"
9
+ },
10
+ "plugins": [
11
+ {
12
+ "name": "claude-mem",
13
+ "version": "13.4.0",
14
+ "source": "./plugin",
15
+ "description": "Persistent memory system for Claude Code - context compression across sessions"
16
+ }
17
+ ]
18
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bjlee2024/claude-mem",
3
- "version": "13.4.6",
3
+ "version": "13.4.9",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bjlee2024/claude-mem",
3
- "version": "13.4.6",
3
+ "version": "13.4.9",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "keywords": [
6
6
  "claude",
@@ -42,6 +42,7 @@
42
42
  },
43
43
  "files": [
44
44
  "dist",
45
+ ".claude-plugin/marketplace.json",
45
46
  ".agents/plugins/marketplace.json",
46
47
  ".codex-plugin",
47
48
  "plugin/.claude-plugin",
@@ -125,7 +126,6 @@
125
126
  "dependencies": {
126
127
  "@anthropic-ai/claude-agent-sdk": "^0.2.138",
127
128
  "@better-auth/api-key": "^1.6.9",
128
- "@bjlee2024/claude-mem": "^13.4.0",
129
129
  "@clack/prompts": "^1.3.0",
130
130
  "@modelcontextprotocol/sdk": "^1.29.0",
131
131
  "ansi-to-html": "^0.7.2",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bjlee2024/claude-mem",
3
- "version": "13.4.6",
3
+ "version": "13.4.9",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bjlee2024/claude-mem",
3
- "version": "13.4.6",
3
+ "version": "13.4.9",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "author": {
6
6
  "name": "Alex Newman",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-plugin",
3
- "version": "13.4.6",
3
+ "version": "13.4.9",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for claude-mem bundled hooks",
6
6
  "type": "module",
@@ -1,4 +1,4 @@
1
- "use strict";var vt=Object.create;var G=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,wt=Object.prototype.hasOwnProperty;var kt=(r,e)=>{for(var t in e)G(r,t,{get:e[t],enumerable:!0})},Oe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ut(e))!wt.call(r,n)&&n!==t&&G(r,n,{get:()=>e[n],enumerable:!(s=yt(e,n))||s.enumerable});return r};var U=(r,e,t)=>(t=r!=null?vt(xt(r)):{},Oe(e||!r||!r.__esModule?G(t,"default",{value:r,enumerable:!0}):t,r)),Ft=r=>Oe(G({},"__esModule",{value:!0}),r);var ps={};kt(ps,{generateContext:()=>Se});module.exports=Ft(ps);var Lt=U(require("path"),1),Mt=require("os"),Dt=require("fs");var ie=require("bun:sqlite");var g=require("path"),se=require("os"),D=require("fs");var Ae=require("url");var L=require("fs"),Re=require("path");var $t=null;function Pt(r){return($t??process.stderr.write.bind(process.stderr))(r)}function Z(r){Pt(r)}var ee=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(ee||{}),te=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=x.logsDir();(0,L.existsSync)(e)||(0,L.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,Re.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=x.settings();if((0,L.existsSync)(e)){let t=(0,L.readFileSync)(e,"utf-8"),n=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=ee[n]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}correlationId(e,t){return`obs-${e}-${t}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
1
+ "use strict";var vt=Object.create;var j=Object.defineProperty;var yt=Object.getOwnPropertyDescriptor;var Ut=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,wt=Object.prototype.hasOwnProperty;var kt=(r,e)=>{for(var t in e)j(r,t,{get:e[t],enumerable:!0})},Oe=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ut(e))!wt.call(r,n)&&n!==t&&j(r,n,{get:()=>e[n],enumerable:!(s=yt(e,n))||s.enumerable});return r};var U=(r,e,t)=>(t=r!=null?vt(xt(r)):{},Oe(e||!r||!r.__esModule?j(t,"default",{value:r,enumerable:!0}):t,r)),Ft=r=>Oe(j({},"__esModule",{value:!0}),r);var Es={};kt(Es,{generateContext:()=>Se});module.exports=Ft(Es);var Lt=U(require("path"),1),Mt=require("os"),Dt=require("fs");var ie=require("bun:sqlite");var g=require("path"),se=require("os"),D=require("fs");var Ae=require("url");var L=require("fs"),Re=require("path");var Pt=null;function $t(r){return(Pt??process.stderr.write.bind(process.stderr))(r)}function Z(r){$t(r)}var ee=(o=>(o[o.DEBUG=0]="DEBUG",o[o.INFO=1]="INFO",o[o.WARN=2]="WARN",o[o.ERROR=3]="ERROR",o[o.SILENT=4]="SILENT",o))(ee||{}),te=class{level=null;useColor;logFilePath=null;logFileInitialized=!1;constructor(){this.useColor=process.stdout.isTTY??!1}ensureLogFileInitialized(){if(!this.logFileInitialized){this.logFileInitialized=!0;try{let e=x.logsDir();(0,L.existsSync)(e)||(0,L.mkdirSync)(e,{recursive:!0});let t=new Date().toISOString().split("T")[0];this.logFilePath=(0,Re.join)(e,`claude-mem-${t}.log`)}catch(e){console.error("[LOGGER] Failed to initialize log file:",e instanceof Error?e.message:String(e)),this.logFilePath=null}}}getLevel(){if(this.level===null)try{let e=x.settings();if((0,L.existsSync)(e)){let t=(0,L.readFileSync)(e,"utf-8"),n=(JSON.parse(t).CLAUDE_MEM_LOG_LEVEL||"INFO").toUpperCase();this.level=ee[n]??1}else this.level=1}catch(e){console.error("[LOGGER] Failed to load log level from settings:",e instanceof Error?e.message:String(e)),this.level=1}return this.level}correlationId(e,t){return`obs-${e}-${t}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.getLevel()===0?`${e.message}
2
2
  ${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let t=Object.keys(e);return t.length===0?"{}":t.length<=3?JSON.stringify(e):`{${t.length} keys: ${t.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,t){if(!t)return e;let s=t;if(typeof t=="string")try{s=JSON.parse(t)}catch{s=t}if(e==="Bash"&&s.command)return`${e}(${s.command})`;if(s.file_path)return`${e}(${s.file_path})`;if(s.notebook_path)return`${e}(${s.notebook_path})`;if(e==="Glob"&&s.pattern)return`${e}(${s.pattern})`;if(e==="Grep"&&s.pattern)return`${e}(${s.pattern})`;if(s.url)return`${e}(${s.url})`;if(s.query)return`${e}(${s.query})`;if(e==="Task"){if(s.subagent_type)return`${e}(${s.subagent_type})`;if(s.description)return`${e}(${s.description})`}return e==="Skill"&&s.skill?`${e}(${s.skill})`:e==="LSP"&&s.operation?`${e}(${s.operation})`:e}formatTimestamp(e){let t=e.getFullYear(),s=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0"),o=String(e.getHours()).padStart(2,"0"),i=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0"),d=String(e.getMilliseconds()).padStart(3,"0");return`${t}-${s}-${n} ${o}:${i}:${a}.${d}`}log(e,t,s,n,o){if(e<this.getLevel())return;this.ensureLogFileInitialized();let i=this.formatTimestamp(new Date),a=ee[e].padEnd(5),d=t.padEnd(6),l="";n?.correlationId?l=`[${n.correlationId}] `:n?.sessionId&&(l=`[session-${n.sessionId}] `);let c="";if(o!=null)if(o instanceof Error)c=this.getLevel()===0?`
3
3
  ${o.message}
4
4
  ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{c=`
@@ -6,7 +6,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
6
6
  `,"utf8")}catch(E){Z(`[LOGGER] Failed to write to log file: ${E instanceof Error?E.message:String(E)}
7
7
  `)}else Z(p+`
8
8
  `)}debug(e,t,s,n){this.log(0,e,t,s,n)}info(e,t,s,n){this.log(1,e,t,s,n)}warn(e,t,s,n){this.log(2,e,t,s,n)}error(e,t,s,n){this.log(3,e,t,s,n)}dataIn(e,t,s,n){this.info(e,`\u2192 ${t}`,s,n)}dataOut(e,t,s,n){this.info(e,`\u2190 ${t}`,s,n)}success(e,t,s,n){this.info(e,`\u2713 ${t}`,s,n)}failure(e,t,s,n){this.error(e,`\u2717 ${t}`,s,n)}timing(e,t,s,n){this.info(e,`\u23F1 ${t}`,n,{duration:`${s}ms`})}happyPathError(e,t,s,n,o=""){let l=((new Error().stack||"").split(`
9
- `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),c=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",T={...s,location:c};return this.warn(e,`[HAPPY-PATH] ${t}`,T,n),o}},u=new te;var Kt={};function Ht(){return typeof __dirname<"u"?__dirname:(0,g.dirname)((0,Ae.fileURLToPath)(Kt.url))}var Gt=Ht();function jt(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let r=(0,g.join)((0,se.homedir)(),".claude-mem"),e=(0,g.join)(r,"settings.json");try{if((0,D.existsSync)(e)){let t=JSON.parse((0,D.readFileSync)(e,"utf-8")),s=t.env??t;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return r}var O=jt(),v=process.env.CLAUDE_CONFIG_DIR||(0,g.join)((0,se.homedir)(),".claude"),Os=(0,g.join)(v,"plugins","marketplaces","bjlee2024"),Xt=(0,g.join)(O,"archives"),Bt=(0,g.join)(O,"logs"),Wt=(0,g.join)(O,"trash"),Vt=(0,g.join)(O,"backups"),qt=(0,g.join)(O,"modes"),Rs=(0,g.join)(O,"settings.json"),Ne=(0,g.join)(O,"claude-mem.db"),Yt=(0,g.join)(O,"vector-db"),Ce=(0,g.join)(O,"observer-sessions"),re=(0,g.basename)(Ce),As=(0,g.join)(v,"settings.json"),Ns=(0,g.join)(v,"commands"),Cs=(0,g.join)(v,"CLAUDE.md");function Ie(r){(0,D.mkdirSync)(r,{recursive:!0})}function Le(){return(0,g.join)(Gt,"..")}var x={dataDir:()=>O,workerPid:()=>(0,g.join)(O,"worker.pid"),serverBetaPid:()=>(0,g.join)(O,".server-beta.pid"),serverBetaPort:()=>(0,g.join)(O,".server-beta.port"),serverBetaRuntime:()=>(0,g.join)(O,".server-beta.runtime.json"),settings:()=>(0,g.join)(O,"settings.json"),database:()=>(0,g.join)(O,"claude-mem.db"),chroma:()=>(0,g.join)(O,"chroma"),combinedCerts:()=>(0,g.join)(O,"combined_certs.pem"),transcriptsConfig:()=>(0,g.join)(O,"transcript-watch.json"),transcriptsState:()=>(0,g.join)(O,"transcript-watch-state.json"),corpora:()=>(0,g.join)(O,"corpora"),supervisorRegistry:()=>(0,g.join)(O,"supervisor.json"),envFile:()=>(0,g.join)(O,".env"),logsDir:()=>Bt,archives:()=>Xt,trash:()=>Wt,backups:()=>Vt,modes:()=>qt,vectorDb:()=>Yt,observerSessions:()=>Ce};var xe=require("crypto");var De=require("os"),ve=U(require("path"),1),ye=require("child_process");var X=require("fs"),j=U(require("path"),1);var w={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Me(r){let e=j.default.join(r,".git"),t;try{t=(0,X.statSync)(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&u.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),w}if(!t.isFile())return w;let s;try{s=(0,X.readFileSync)(e,"utf-8").trim()}catch(c){return u.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),w}let n=s.match(/^gitdir:\s*(.+)$/);if(!n)return w;let i=n[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!i)return w;let a=i[1],d=j.default.basename(r),l=j.default.basename(a);return{isWorktree:!0,worktreeName:d,parentRepoPath:a,parentProjectName:l}}function Ue(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,De.homedir)()):r}function Jt(r){try{return(0,ye.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function Qt(r){if(!r||r.trim()==="")return u.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Ue(r),s=Jt(e)??e,n=ve.default.basename(s);if(n===""){if(process.platform==="win32"){let i=r.match(/^([A-Z]):\\/i);if(i){let d=`drive-${i[1].toUpperCase()}`;return u.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:d}),d}}return u.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return n}function ne(r){let e=Qt(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Ue(r),s=Me(t);if(s.isWorktree&&s.parentProjectName){let n=`${s.parentProjectName}/${e}`;return{primary:n,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,n]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}function B(r,e,t){return(0,xe.createHash)("sha256").update([r||"",e||"",t||""].join("\0")).digest("hex").slice(0,16)}function oe(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[String(e)]}catch{return[r]}}var N="claude";function zt(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function y(r){if(!r)return N;let e=zt(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:N}function we(r){let e=["claude","codex","cursor"];return[...r].sort((t,s)=>{let n=e.indexOf(t),o=e.indexOf(s);return n!==-1||o!==-1?n===-1?1:o===-1?-1:n-o:t.localeCompare(s)})}function Zt(r,e){return{customTitle:r,platformSource:e?y(e):void 0}}var W=class{db;constructor(e=Ne){e instanceof ie.Database?this.db=e:(e!==":memory:"&&Ie(O),this.db=new ie.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON"),this.db.run("PRAGMA journal_size_limit = 4194304")),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn(),this.createPendingMessagesTable(),this.renameSessionIdColumns(),this.repairSessionIdColumnRename(),this.addFailedAtEpochColumn(),this.addOnUpdateCascadeToForeignKeys(),this.addObservationContentHashColumn(),this.addSessionCustomTitleColumn(),this.addSessionPlatformSourceColumn(),this.addObservationModelColumns(),this.ensureMergedIntoProjectColumns(),this.addObservationSubagentColumns(),this.addObservationsUniqueContentHashIndex(),this.addObservationsMetadataColumn(),this.dropDeadPendingMessagesColumns(),this.ensurePendingMessagesToolUseIdColumn(),this.dropWorkerPidColumn()}dropWorkerPidColumn(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(32),s=this.db.query("PRAGMA table_info(pending_messages)").all().some(n=>n.name==="worker_pid");if(!(e&&!s)){if(s)try{this.db.run("DROP INDEX IF EXISTS idx_pending_messages_worker_pid"),this.db.run("ALTER TABLE pending_messages DROP COLUMN worker_pid"),u.debug("DB","Dropped worker_pid column and its index from pending_messages")}catch(n){u.warn("DB","Failed to drop worker_pid column from pending_messages",{},n instanceof Error?n:new Error(String(n)));return}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(32,new Date().toISOString())}}dropDeadPendingMessagesColumns(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(31),t=this.db.query("PRAGMA table_info(pending_messages)").all(),s=new Set(t.map(i=>i.name)),o=["retry_count","failed_at_epoch","completed_at_epoch"].filter(i=>s.has(i));if(!(e&&o.length===0)){if(o.length>0){this.db.run("BEGIN TRANSACTION");try{this.db.run("DELETE FROM pending_messages WHERE status NOT IN ('pending', 'processing')");for(let i of o)this.db.run(`ALTER TABLE pending_messages DROP COLUMN ${i}`),u.debug("DB",`Dropped dead column ${i} from pending_messages`);e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(31,new Date().toISOString()),this.db.run("COMMIT")}catch(i){this.db.run("ROLLBACK"),u.warn("DB","Failed to drop dead columns from pending_messages",{},i instanceof Error?i:new Error(String(i)));return}return}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(31,new Date().toISOString())}}initializeSchema(){this.db.run(`
9
+ `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),c=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",T={...s,location:c};return this.warn(e,`[HAPPY-PATH] ${t}`,T,n),o}},u=new te;var Jt={};function Ht(){return typeof __dirname<"u"?__dirname:(0,g.dirname)((0,Ae.fileURLToPath)(Jt.url))}var Gt=Ht();function jt(){if(process.env.CLAUDE_MEM_DATA_DIR)return process.env.CLAUDE_MEM_DATA_DIR;let r=(0,g.join)((0,se.homedir)(),".claude-mem"),e=(0,g.join)(r,"settings.json");try{if((0,D.existsSync)(e)){let t=JSON.parse((0,D.readFileSync)(e,"utf-8")),s=t.env??t;if(s.CLAUDE_MEM_DATA_DIR)return s.CLAUDE_MEM_DATA_DIR}}catch{}return r}var O=jt(),v=process.env.CLAUDE_CONFIG_DIR||(0,g.join)((0,se.homedir)(),".claude"),Rs=(0,g.join)(v,"plugins","marketplaces","bjlee2024"),Xt=(0,g.join)(O,"archives"),Bt=(0,g.join)(O,"logs"),Wt=(0,g.join)(O,"trash"),Vt=(0,g.join)(O,"backups"),qt=(0,g.join)(O,"modes"),Yt=(0,g.join)(O,"settings.json"),Ne=(0,g.join)(O,"claude-mem.db"),Kt=(0,g.join)(O,"vector-db"),Ce=(0,g.join)(O,"observer-sessions"),re=(0,g.basename)(Ce),As=(0,g.join)(v,"settings.json"),Ns=(0,g.join)(v,"commands"),Cs=(0,g.join)(v,"CLAUDE.md");function Ie(r){(0,D.mkdirSync)(r,{recursive:!0})}function Le(){return(0,g.join)(Gt,"..")}var x={dataDir:()=>O,workerPid:()=>(0,g.join)(O,"worker.pid"),serverBetaPid:()=>(0,g.join)(O,".server-beta.pid"),serverBetaPort:()=>(0,g.join)(O,".server-beta.port"),serverBetaRuntime:()=>(0,g.join)(O,".server-beta.runtime.json"),settings:()=>(0,g.join)(O,"settings.json"),database:()=>(0,g.join)(O,"claude-mem.db"),chroma:()=>(0,g.join)(O,"chroma"),combinedCerts:()=>(0,g.join)(O,"combined_certs.pem"),transcriptsConfig:()=>(0,g.join)(O,"transcript-watch.json"),transcriptsState:()=>(0,g.join)(O,"transcript-watch-state.json"),corpora:()=>(0,g.join)(O,"corpora"),supervisorRegistry:()=>(0,g.join)(O,"supervisor.json"),envFile:()=>(0,g.join)(O,".env"),logsDir:()=>Bt,archives:()=>Xt,trash:()=>Wt,backups:()=>Vt,modes:()=>qt,vectorDb:()=>Kt,observerSessions:()=>Ce};var xe=require("crypto");var De=require("os"),ve=U(require("path"),1),ye=require("child_process");var B=require("fs"),X=U(require("path"),1);var w={isWorktree:!1,worktreeName:null,parentRepoPath:null,parentProjectName:null};function Me(r){let e=X.default.join(r,".git"),t;try{t=(0,B.statSync)(e)}catch(c){return c instanceof Error&&c.code!=="ENOENT"&&u.warn("GIT","Unexpected error checking .git",{error:c instanceof Error?c.message:String(c)}),w}if(!t.isFile())return w;let s;try{s=(0,B.readFileSync)(e,"utf-8").trim()}catch(c){return u.warn("GIT","Failed to read .git file",{error:c instanceof Error?c.message:String(c)}),w}let n=s.match(/^gitdir:\s*(.+)$/);if(!n)return w;let i=n[1].match(/^(.+)[/\\]\.git[/\\]worktrees[/\\]([^/\\]+)$/);if(!i)return w;let a=i[1],d=X.default.basename(r),l=X.default.basename(a);return{isWorktree:!0,worktreeName:d,parentRepoPath:a,parentProjectName:l}}function Ue(r){return r==="~"||r.startsWith("~/")?r.replace(/^~/,(0,De.homedir)()):r}function Qt(r){try{return(0,ye.execFileSync)("git",["rev-parse","--show-toplevel"],{cwd:r,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}function zt(r){if(!r||r.trim()==="")return u.warn("PROJECT_NAME","Empty cwd provided, using fallback",{cwd:r}),"unknown-project";let e=Ue(r),s=Qt(e)??e,n=ve.default.basename(s);if(n===""){if(process.platform==="win32"){let i=r.match(/^([A-Z]):\\/i);if(i){let d=`drive-${i[1].toUpperCase()}`;return u.info("PROJECT_NAME","Drive root detected",{cwd:r,projectName:d}),d}}return u.warn("PROJECT_NAME","Root directory detected, using fallback",{cwd:r}),"unknown-project"}return n}function ne(r){let e=zt(r);if(!r)return{primary:e,parent:null,isWorktree:!1,allProjects:[e]};let t=Ue(r),s=Me(t);if(s.isWorktree&&s.parentProjectName){let n=`${s.parentProjectName}/${e}`;return{primary:n,parent:s.parentProjectName,isWorktree:!0,allProjects:[s.parentProjectName,n]}}return{primary:e,parent:null,isWorktree:!1,allProjects:[e]}}function W(r,e,t){return(0,xe.createHash)("sha256").update([r||"",e||"",t||""].join("\0")).digest("hex").slice(0,16)}function oe(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[String(e)]}catch{return[r]}}var N="claude";function Zt(r){return r.trim().toLowerCase().replace(/\s+/g,"-")}function y(r){if(!r)return N;let e=Zt(r);return e?e==="transcript"||e.includes("codex")?"codex":e.includes("cursor")?"cursor":e.includes("claude")?"claude":e:N}function we(r){let e=["claude","codex","cursor"];return[...r].sort((t,s)=>{let n=e.indexOf(t),o=e.indexOf(s);return n!==-1||o!==-1?n===-1?1:o===-1?-1:n-o:t.localeCompare(s)})}function es(r,e){return{customTitle:r,platformSource:e?y(e):void 0}}var V=class{db;constructor(e=Ne){e instanceof ie.Database?this.db=e:(e!==":memory:"&&Ie(O),this.db=new ie.Database(e),this.db.run("PRAGMA journal_mode = WAL"),this.db.run("PRAGMA synchronous = NORMAL"),this.db.run("PRAGMA foreign_keys = ON"),this.db.run("PRAGMA journal_size_limit = 4194304")),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn(),this.createPendingMessagesTable(),this.renameSessionIdColumns(),this.repairSessionIdColumnRename(),this.addFailedAtEpochColumn(),this.addOnUpdateCascadeToForeignKeys(),this.addObservationContentHashColumn(),this.addSessionCustomTitleColumn(),this.addSessionPlatformSourceColumn(),this.addObservationModelColumns(),this.ensureMergedIntoProjectColumns(),this.addObservationSubagentColumns(),this.addObservationsUniqueContentHashIndex(),this.addObservationsMetadataColumn(),this.dropDeadPendingMessagesColumns(),this.ensurePendingMessagesToolUseIdColumn(),this.dropWorkerPidColumn()}dropWorkerPidColumn(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(32),s=this.db.query("PRAGMA table_info(pending_messages)").all().some(n=>n.name==="worker_pid");if(!(e&&!s)){if(s)try{this.db.run("DROP INDEX IF EXISTS idx_pending_messages_worker_pid"),this.db.run("ALTER TABLE pending_messages DROP COLUMN worker_pid"),u.debug("DB","Dropped worker_pid column and its index from pending_messages")}catch(n){u.warn("DB","Failed to drop worker_pid column from pending_messages",{},n instanceof Error?n:new Error(String(n)));return}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(32,new Date().toISOString())}}dropDeadPendingMessagesColumns(){let e=this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(31),t=this.db.query("PRAGMA table_info(pending_messages)").all(),s=new Set(t.map(i=>i.name)),o=["retry_count","failed_at_epoch","completed_at_epoch"].filter(i=>s.has(i));if(!(e&&o.length===0)){if(o.length>0){this.db.run("BEGIN TRANSACTION");try{this.db.run("DELETE FROM pending_messages WHERE status NOT IN ('pending', 'processing')");for(let i of o)this.db.run(`ALTER TABLE pending_messages DROP COLUMN ${i}`),u.debug("DB",`Dropped dead column ${i} from pending_messages`);e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(31,new Date().toISOString()),this.db.run("COMMIT")}catch(i){this.db.run("ROLLBACK"),u.warn("DB","Failed to drop dead columns from pending_messages",{},i instanceof Error?i:new Error(String(i)));return}return}e||this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(31,new Date().toISOString())}}initializeSchema(){this.db.run(`
10
10
  CREATE TABLE IF NOT EXISTS schema_versions (
11
11
  id INTEGER PRIMARY KEY,
12
12
  version INTEGER UNIQUE NOT NULL,
@@ -497,7 +497,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
497
497
  ORDER BY started_at_epoch DESC
498
498
  `).all(...e)}getPromptNumberFromUserPrompts(e){return this.db.prepare(`
499
499
  SELECT COUNT(*) as count FROM user_prompts WHERE content_session_id = ?
500
- `).get(e).count}createSDKSession(e,t,s,n,o){let i=new Date,a=i.getTime(),d=Zt(n,o),l=d.platformSource??N,c=this.db.prepare(`
500
+ `).get(e).count}createSDKSession(e,t,s,n,o){let i=new Date,a=i.getTime(),d=es(n,o),l=d.platformSource??N,c=this.db.prepare(`
501
501
  SELECT id, platform_source FROM sdk_sessions WHERE content_session_id = ?
502
502
  `).get(e);if(c){if(t&&this.db.prepare(`
503
503
  UPDATE sdk_sessions SET project = ?
@@ -522,7 +522,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
522
522
  FROM user_prompts
523
523
  WHERE content_session_id = ? AND prompt_number = ?
524
524
  LIMIT 1
525
- `).get(e,t)?.prompt_text??null}storeObservation(e,t,s,n,o=0,i,a){let d=i??Date.now(),l=new Date(d).toISOString(),c=B(e,s.title,s.narrative),p=this.db.prepare(`
525
+ `).get(e,t)?.prompt_text??null}storeObservation(e,t,s,n,o=0,i,a){let d=i??Date.now(),l=new Date(d).toISOString(),c=W(e,s.title,s.narrative),p=this.db.prepare(`
526
526
  INSERT INTO observations
527
527
  (memory_session_id, project, type, title, subtitle, facts, narrative, concepts,
528
528
  files_read, files_modified, prompt_number, discovery_tokens, agent_type, agent_id, content_hash, created_at, created_at_epoch,
@@ -543,7 +543,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
543
543
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
544
544
  ON CONFLICT(memory_session_id, content_hash) DO NOTHING
545
545
  RETURNING id
546
- `),f=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let m of s){let A=B(e,m.title,m.narrative),h=E.get(e,t,m.type,m.title,m.subtitle,JSON.stringify(m.facts),m.narrative,JSON.stringify(m.concepts),JSON.stringify(m.files_read),JSON.stringify(m.files_modified),o||null,i,m.agent_type??null,m.agent_id??null,A,c,l,d||null);if(h){p.push(h.id);continue}let S=f.get(e,A);if(!S)throw new Error(`storeObservations: ON CONFLICT without existing row for content_hash=${A}`);p.push(S.id)}let b=null;if(n){let A=this.db.prepare(`
546
+ `),f=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let m of s){let A=W(e,m.title,m.narrative),h=E.get(e,t,m.type,m.title,m.subtitle,JSON.stringify(m.facts),m.narrative,JSON.stringify(m.concepts),JSON.stringify(m.files_read),JSON.stringify(m.files_modified),o||null,i,m.agent_type??null,m.agent_id??null,A,c,l,d||null);if(h){p.push(h.id);continue}let S=f.get(e,A);if(!S)throw new Error(`storeObservations: ON CONFLICT without existing row for content_hash=${A}`);p.push(S.id)}let b=null;if(n){let A=this.db.prepare(`
547
547
  INSERT INTO session_summaries
548
548
  (memory_session_id, project, request, investigated, learned, completed,
549
549
  next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
@@ -556,7 +556,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
556
556
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
557
557
  ON CONFLICT(memory_session_id, content_hash) DO NOTHING
558
558
  RETURNING id
559
- `),m=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let R of s){let M=B(e,R.title,R.narrative),be=b.get(e,t,R.type,R.title,R.subtitle,JSON.stringify(R.facts),R.narrative,JSON.stringify(R.concepts),JSON.stringify(R.files_read),JSON.stringify(R.files_modified),a||null,d,R.agent_type??null,R.agent_id??null,M,p,T,c||null);if(be){f.push(be.id);continue}let he=m.get(e,M);if(!he)throw new Error(`storeObservationsAndMarkComplete: ON CONFLICT without existing row for content_hash=${M}`);f.push(he.id)}let A;if(n){let M=this.db.prepare(`
559
+ `),m=this.db.prepare("SELECT id FROM observations WHERE memory_session_id = ? AND content_hash = ?");for(let R of s){let M=W(e,R.title,R.narrative),be=b.get(e,t,R.type,R.title,R.subtitle,JSON.stringify(R.facts),R.narrative,JSON.stringify(R.concepts),JSON.stringify(R.files_read),JSON.stringify(R.files_modified),a||null,d,R.agent_type??null,R.agent_id??null,M,p,T,c||null);if(be){f.push(be.id);continue}let he=m.get(e,M);if(!he)throw new Error(`storeObservationsAndMarkComplete: ON CONFLICT without existing row for content_hash=${M}`);f.push(he.id)}let A;if(n){let M=this.db.prepare(`
560
560
  INSERT INTO session_summaries
561
561
  (memory_session_id, project, request, investigated, learned, completed,
562
562
  next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
@@ -692,7 +692,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
692
692
  content_session_id, prompt_number, prompt_text,
693
693
  created_at, created_at_epoch
694
694
  ) VALUES (?, ?, ?, ?, ?)
695
- `).run(e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var I=require("fs"),k=require("path"),ae=require("os"),V=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,k.join)((0,ae.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,k.join)((0,ae.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static getBool(e){let t=this.get(e);return t==="true"||t===!0}static applyEnvOverrides(e){let t={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(t[s]=process.env[s]);return t}static loadFromFile(e){try{if(!(0,I.existsSync)(e)){let i=this.getAllDefaults();try{let a=(0,k.dirname)(e);(0,I.existsSync)(a)||(0,I.mkdirSync)(a,{recursive:!0}),(0,I.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a instanceof Error?a.message:String(a))}return this.applyEnvOverrides(i)}let t=(0,I.readFileSync)(e,"utf-8"),s=JSON.parse(t),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{(0,I.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(i){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,i instanceof Error?i.message:String(i))}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(o[i]=n[i]);return this.applyEnvOverrides(o)}catch(t){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,t instanceof Error?t.message:String(t)),this.applyEnvOverrides(this.getAllDefaults())}}};var F=require("fs"),q=require("path");var C=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=Le(),t=[(0,q.join)(e,"modes"),(0,q.join)(e,"..","plugin","modes")],s=t.find(n=>(0,F.existsSync)(n));this.modesDir=s||t[0]}static getInstance(){return r.instance||(r.instance=new r),r.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 o=t[n],i=e[n];this.isPlainObject(o)&&this.isPlainObject(i)?s[n]=this.deepMerge(i,o):s[n]=o}return s}loadModeFile(e){let t=(0,q.join)(this.modesDir,`${e}.json`);if(!(0,F.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,F.readFileSync)(t,"utf-8");return JSON.parse(s)}loadMode(e){let t=this.parseInheritance(e);if(!t.hasParent)try{let d=this.loadModeFile(e);return this.activeMode=d,u.debug("SYSTEM",`Loaded mode: ${d.name} (${e})`,void 0,{types:d.observation_types.map(l=>l.id),concepts:d.observation_concepts.map(l=>l.id)}),d}catch(d){if(d instanceof Error?u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(d)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:s,overrideId:n}=t,o;try{o=this.loadMode(s)}catch(d){d instanceof Error?u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{error:String(d)}),o=this.loadMode("code")}let i;try{i=this.loadModeFile(n),u.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch(d){return d instanceof Error?u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{message:d.message}):u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{error:String(d)}),this.activeMode=o,o}if(!i)return u.warn("SYSTEM",`Invalid override file: ${n}, using parent mode '${s}' only`),this.activeMode=o,o;let a=this.deepMerge(o,i);return this.activeMode=a,u.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${s} + ${n})`,void 0,{parent:s,override:n,types:a.observation_types.map(d=>d.id),concepts:a.observation_concepts.map(d=>d.id)}),a}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}};function de(){let r=x.settings(),e=V.loadFromFile(r),t=C.getInstance().getActiveMode(),s=new Set(t.observation_types.map(o=>o.id)),n=new Set(t.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:s,observationConcepts:n,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 _={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"},ke=4,_e=1;function ue(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/ke)}function ce(r){let e=r.length,t=r.reduce((i,a)=>i+ue(a),0),s=r.reduce((i,a)=>i+(a.discovery_tokens||0),0),n=s-t,o=s>0?Math.round(n/s*100):0;return{totalObservations:e,totalReadTokens:t,totalDiscoveryTokens:s,savings:n,savingsPercent:o}}function es(r){return C.getInstance().getWorkEmoji(r)}function $(r,e){let t=ue(r),s=r.discovery_tokens||0,n=es(r.type),o=s>0?`${n} ${s.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:s,discoveryDisplay:o,workEmoji:n}}function Y(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var $e=U(require("path"),1),K=require("fs");var ts=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],rr=new RegExp(`<(${ts.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Fe=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var ss=["task-notification"],nr=new RegExp(`^\\s*<(${ss.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),or=256*1024;function le(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(",");return r.db.prepare(`
695
+ `).run(e.content_session_id,e.prompt_number,e.prompt_text,e.created_at,e.created_at_epoch).lastInsertRowid}}};var k=require("fs"),q=require("path");var C=class r{static instance=null;activeMode=null;modesDir;constructor(){let e=Le(),t=[(0,q.join)(e,"modes"),(0,q.join)(e,"..","plugin","modes")],s=t.find(n=>(0,k.existsSync)(n));this.modesDir=s||t[0]}static getInstance(){return r.instance||(r.instance=new r),r.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 o=t[n],i=e[n];this.isPlainObject(o)&&this.isPlainObject(i)?s[n]=this.deepMerge(i,o):s[n]=o}return s}loadModeFile(e){let t=(0,q.join)(this.modesDir,`${e}.json`);if(!(0,k.existsSync)(t))throw new Error(`Mode file not found: ${t}`);let s=(0,k.readFileSync)(t,"utf-8");return JSON.parse(s)}loadMode(e){let t=this.parseInheritance(e);if(!t.hasParent)try{let d=this.loadModeFile(e);return this.activeMode=d,u.debug("SYSTEM",`Loaded mode: ${d.name} (${e})`,void 0,{types:d.observation_types.map(l=>l.id),concepts:d.observation_concepts.map(l=>l.id)}),d}catch(d){if(d instanceof Error?u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Mode file not found: ${e}, falling back to 'code'`,{error:String(d)}),e==="code")throw new Error("Critical: code.json mode file missing");return this.loadMode("code")}let{parentId:s,overrideId:n}=t,o;try{o=this.loadMode(s)}catch(d){d instanceof Error?u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{message:d.message}):u.warn("WORKER",`Parent mode '${s}' not found for ${e}, falling back to 'code'`,{error:String(d)}),o=this.loadMode("code")}let i;try{i=this.loadModeFile(n),u.debug("SYSTEM",`Loaded override file: ${n} for parent ${s}`)}catch(d){return d instanceof Error?u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{message:d.message}):u.warn("WORKER",`Override file '${n}' not found, using parent mode '${s}' only`,{error:String(d)}),this.activeMode=o,o}if(!i)return u.warn("SYSTEM",`Invalid override file: ${n}, using parent mode '${s}' only`),this.activeMode=o,o;let a=this.deepMerge(o,i);return this.activeMode=a,u.debug("SYSTEM",`Loaded mode with inheritance: ${a.name} (${e} = ${s} + ${n})`,void 0,{parent:s,override:n,types:a.observation_types.map(d=>d.id),concepts:a.observation_concepts.map(d=>d.id)}),a}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 I=require("fs"),F=require("path"),ae=require("os"),P=class{static DEFAULTS={CLAUDE_MEM_MODEL:"claude-haiku-4-5-20251001",CLAUDE_MEM_CONTEXT_OBSERVATIONS:"50",CLAUDE_MEM_WORKER_PORT:String(37700+(process.getuid?.()??77)%100),CLAUDE_MEM_WORKER_HOST:"127.0.0.1",CLAUDE_MEM_SKIP_TOOLS:"ListMcpResourcesTool,SlashCommand,Skill,TodoWrite,AskUserQuestion",CLAUDE_MEM_PROVIDER:"claude",CLAUDE_MEM_CLAUDE_AUTH_METHOD:"subscription",CLAUDE_MEM_GEMINI_API_KEY:"",CLAUDE_MEM_GEMINI_MODEL:"gemini-2.5-flash-lite",CLAUDE_MEM_GEMINI_RATE_LIMITING_ENABLED:"true",CLAUDE_MEM_GEMINI_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_GEMINI_MAX_TOKENS:"100000",CLAUDE_MEM_OPENROUTER_API_KEY:"",CLAUDE_MEM_OPENROUTER_MODEL:"xiaomi/mimo-v2-flash:free",CLAUDE_MEM_OPENROUTER_BASE_URL:"",CLAUDE_MEM_OPENROUTER_SITE_URL:"",CLAUDE_MEM_OPENROUTER_APP_NAME:"claude-mem",CLAUDE_MEM_OPENROUTER_MAX_CONTEXT_MESSAGES:"20",CLAUDE_MEM_OPENROUTER_MAX_TOKENS:"100000",CLAUDE_MEM_DATA_DIR:(0,F.join)((0,ae.homedir)(),".claude-mem"),CLAUDE_MEM_LOG_LEVEL:"INFO",CLAUDE_MEM_PYTHON_VERSION:"3.13",CLAUDE_CODE_PATH:"",CLAUDE_MEM_MODE:"code",CLAUDE_MEM_CONTEXT_SHOW_READ_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_WORK_TOKENS:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_AMOUNT:"false",CLAUDE_MEM_CONTEXT_SHOW_SAVINGS_PERCENT:"true",CLAUDE_MEM_CONTEXT_FULL_COUNT:"0",CLAUDE_MEM_CONTEXT_FULL_FIELD:"narrative",CLAUDE_MEM_CONTEXT_SESSION_COUNT:"10",CLAUDE_MEM_CONTEXT_SHOW_LAST_SUMMARY:"true",CLAUDE_MEM_CONTEXT_SHOW_LAST_MESSAGE:"false",CLAUDE_MEM_CONTEXT_SHOW_TERMINAL_OUTPUT:"true",CLAUDE_MEM_WELCOME_HINT_ENABLED:"true",CLAUDE_MEM_FOLDER_CLAUDEMD_ENABLED:"false",CLAUDE_MEM_FOLDER_USE_LOCAL_MD:"false",CLAUDE_MEM_TRANSCRIPTS_ENABLED:"true",CLAUDE_MEM_TRANSCRIPTS_CONFIG_PATH:(0,F.join)((0,ae.homedir)(),".claude-mem","transcript-watch.json"),CLAUDE_MEM_CODEX_TRANSCRIPT_INGESTION:"false",CLAUDE_MEM_MAX_CONCURRENT_AGENTS:"2",CLAUDE_MEM_HOOK_FAIL_LOUD_THRESHOLD:"3",CLAUDE_MEM_EXCLUDED_PROJECTS:"",CLAUDE_MEM_FOLDER_MD_EXCLUDE:"[]",CLAUDE_MEM_FOLDER_MD_SKELETON_DENYLIST:"[]",CLAUDE_MEM_SEMANTIC_INJECT:"false",CLAUDE_MEM_SEMANTIC_INJECT_LIMIT:"5",CLAUDE_MEM_TIER_ROUTING_ENABLED:"true",CLAUDE_MEM_TIER_SIMPLE_MODEL:"haiku",CLAUDE_MEM_TIER_SUMMARY_MODEL:"",CLAUDE_MEM_TIER_FAST_MODEL:"haiku",CLAUDE_MEM_TIER_SMART_MODEL:"sonnet",CLAUDE_MEM_CHROMA_ENABLED:"true",CLAUDE_MEM_CHROMA_MODE:"local",CLAUDE_MEM_CHROMA_HOST:"127.0.0.1",CLAUDE_MEM_CHROMA_PORT:"8000",CLAUDE_MEM_CHROMA_SSL:"false",CLAUDE_MEM_CHROMA_API_KEY:"",CLAUDE_MEM_CHROMA_TENANT:"default_tenant",CLAUDE_MEM_CHROMA_DATABASE:"default_database",CLAUDE_MEM_TELEGRAM_ENABLED:"true",CLAUDE_MEM_TELEGRAM_BOT_TOKEN:"",CLAUDE_MEM_TELEGRAM_CHAT_ID:"",CLAUDE_MEM_TELEGRAM_TRIGGER_TYPES:"security_alert",CLAUDE_MEM_TELEGRAM_TRIGGER_CONCEPTS:"",CLAUDE_MEM_QUEUE_ENGINE:"sqlite",CLAUDE_MEM_REDIS_URL:"",CLAUDE_MEM_REDIS_HOST:"127.0.0.1",CLAUDE_MEM_REDIS_PORT:"6379",CLAUDE_MEM_REDIS_MODE:"external",CLAUDE_MEM_QUEUE_REDIS_PREFIX:`claude_mem_${process.env.CLAUDE_MEM_WORKER_PORT??String(37700+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_AUTH_MODE:"api-key",CLAUDE_MEM_RUNTIME:"worker",CLAUDE_MEM_SERVER_BETA_URL:`http://127.0.0.1:${process.env.CLAUDE_MEM_SERVER_PORT??String(37877+(process.getuid?.()??77)%100)}`,CLAUDE_MEM_SERVER_BETA_API_KEY:"",CLAUDE_MEM_SERVER_BETA_PROJECT_ID:""};static getAllDefaults(){return{...this.DEFAULTS}}static get(e){return process.env[e]??this.DEFAULTS[e]}static getInt(e){let t=this.get(e);return parseInt(t,10)}static getBool(e){let t=this.get(e);return t==="true"||t===!0}static applyEnvOverrides(e){let t={...e};for(let s of Object.keys(this.DEFAULTS))process.env[s]!==void 0&&(t[s]=process.env[s]);return t}static loadFromFile(e){try{if(!(0,I.existsSync)(e)){let i=this.getAllDefaults();try{let a=(0,F.dirname)(e);(0,I.existsSync)(a)||(0,I.mkdirSync)(a,{recursive:!0}),(0,I.writeFileSync)(e,JSON.stringify(i,null,2),"utf-8"),console.log("[SETTINGS] Created settings file with defaults:",e)}catch(a){console.warn("[SETTINGS] Failed to create settings file, using in-memory defaults:",e,a instanceof Error?a.message:String(a))}return this.applyEnvOverrides(i)}let t=(0,I.readFileSync)(e,"utf-8"),s=JSON.parse(t),n=s;if(s.env&&typeof s.env=="object"){n=s.env;try{(0,I.writeFileSync)(e,JSON.stringify(n,null,2),"utf-8"),console.log("[SETTINGS] Migrated settings file from nested to flat schema:",e)}catch(i){console.warn("[SETTINGS] Failed to auto-migrate settings file:",e,i instanceof Error?i.message:String(i))}}let o={...this.DEFAULTS};for(let i of Object.keys(this.DEFAULTS))n[i]!==void 0&&(o[i]=n[i]);return this.applyEnvOverrides(o)}catch(t){return console.warn("[SETTINGS] Failed to load settings, using defaults:",e,t instanceof Error?t.message:String(t)),this.applyEnvOverrides(this.getAllDefaults())}}};function de(){let r=x.settings(),e=P.loadFromFile(r),t=C.getInstance().getActiveMode(),s=new Set(t.observation_types.map(o=>o.id)),n=new Set(t.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:s,observationConcepts:n,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 _={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"},ke=4,_e=1;function ue(r){let e=(r.title?.length||0)+(r.subtitle?.length||0)+(r.narrative?.length||0)+JSON.stringify(r.facts||[]).length;return Math.ceil(e/ke)}function ce(r){let e=r.length,t=r.reduce((i,a)=>i+ue(a),0),s=r.reduce((i,a)=>i+(a.discovery_tokens||0),0),n=s-t,o=s>0?Math.round(n/s*100):0;return{totalObservations:e,totalReadTokens:t,totalDiscoveryTokens:s,savings:n,savingsPercent:o}}function ts(r){return C.getInstance().getWorkEmoji(r)}function $(r,e){let t=ue(r),s=r.discovery_tokens||0,n=ts(r.type),o=s>0?`${n} ${s.toLocaleString()}`:"-";return{readTokens:t,discoveryTokens:s,discoveryDisplay:o,workEmoji:n}}function Y(r){return r.showReadTokens||r.showWorkTokens||r.showSavingsAmount||r.showSavingsPercent}var Pe=U(require("path"),1),K=require("fs");var ss=["private","claude-mem-context","system_instruction","system-instruction","persisted-output","system-reminder"],ir=new RegExp(`<(${ss.join("|")})\\b[^>]*>[\\s\\S]*?</\\1>`,"g"),Fe=/<system-reminder>[\s\S]*?<\/system-reminder>/g;var rs=["task-notification"],ar=new RegExp(`^\\s*<(${rs.join("|")})\\b[^>]*>(?:(?!<\\1\\b|</\\1\\b)[\\s\\S])*</\\1>\\s*$`),dr=256*1024;function le(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(",");return r.db.prepare(`
696
696
  SELECT
697
697
  o.id,
698
698
  o.memory_session_id,
@@ -735,7 +735,7 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
735
735
  WHERE (ss.project = ? OR ss.merged_into_project = ?)
736
736
  ORDER BY ss.created_at_epoch DESC
737
737
  LIMIT ?
738
- `).all(e,e,t.sessionCount+_e)}function Pe(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(","),a=e.map(()=>"?").join(",");return r.db.prepare(`
738
+ `).all(e,e,t.sessionCount+_e)}function $e(r,e,t){let s=Array.from(t.observationTypes),n=s.map(()=>"?").join(","),o=Array.from(t.observationConcepts),i=o.map(()=>"?").join(","),a=e.map(()=>"?").join(",");return r.db.prepare(`
739
739
  SELECT
740
740
  o.id,
741
741
  o.memory_session_id,
@@ -782,14 +782,14 @@ ${o.stack}`:` ${o.message}`;else if(this.getLevel()===0&&typeof o=="object")try{
782
782
  OR ss.merged_into_project IN (${s}))
783
783
  ORDER BY ss.created_at_epoch DESC
784
784
  LIMIT ?
785
- `).all(...e,...e,t.sessionCount+_e)}function Ge(r){return r.replace(/[/.]/g,"-")}function rs(r){if(!r.includes('"type":"assistant"'))return null;let e=JSON.parse(r);if(e.type==="assistant"&&e.message?.content&&Array.isArray(e.message.content)){let t="";for(let s of e.message.content)s.type==="text"&&(t+=s.text);if(t=t.replace(Fe,"").trim(),t)return t}return null}function ns(r){for(let e=r.length-1;e>=0;e--)try{let t=rs(r[e]);if(t)return t}catch(t){t instanceof Error?u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e},t):u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e,error:String(t)});continue}return""}function os(r){try{if(!(0,K.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,K.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(`
786
- `).filter(n=>n.trim());return{userMessage:"",assistantMessage:ns(t)}}catch(e){return e instanceof Error?u.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e):u.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r,error:String(e)}),{userMessage:"",assistantMessage:""}}}function pe(r,e,t,s){if(!e.showLastMessage||r.length===0)return{userMessage:"",assistantMessage:""};let n=r.find(d=>d.memory_session_id!==t);if(!n)return{userMessage:"",assistantMessage:""};let o=n.memory_session_id,i=Ge(s),a=$e.default.join(v,"projects",i,`${o}.jsonl`);return os(a)}function je(r,e){let t=e[0]?.id;return r.map((s,n)=>{let o=n===0?null:e[n+1];return{...s,displayEpoch:o?o.created_at_epoch:s.created_at_epoch,displayTime:o?o.created_at:s.created_at,shouldShowLink:s.id!==t}})}function Ee(r,e){let t=[...r.map(s=>({type:"observation",data:s})),...e.map(s=>({type:"summary",data:s}))];return t.sort((s,n)=>{let o=s.type==="observation"?s.data.created_at_epoch:s.data.displayEpoch,i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch;return o-i}),t}function Xe(r,e){return new Set(r.slice(0,e).map(t=>t.id))}function Be(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function We(r){return[`# [${r}] recent context, ${Be()}`,""]}function Ve(){return[`Legend: \u{1F3AF}session ${C.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji}${t.id}`).join(" ")}`,"Format: ID TIME TYPE TITLE","Fetch details: get_observations([IDs]) | Search: mem-search skill",""]}function qe(){return[]}function Ye(){return[]}function Ke(r,e){let t=[],s=[`${r.totalObservations} obs (${r.totalReadTokens.toLocaleString()}t read)`,`${r.totalDiscoveryTokens.toLocaleString()}t work`];return r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?s.push(`${r.savingsPercent}% savings`):e.showSavingsAmount&&s.push(`${r.savings.toLocaleString()}t saved`)),t.push(`Stats: ${s.join(" | ")}`),t.push(""),t}function Je(r){return[`### ${r}`]}function Qe(r){return r.toLowerCase().replace(" am","a").replace(" pm","p")}function ze(r,e,t){let s=r.title||"Untitled",n=C.getInstance().getTypeIcon(r.type),o=e?Qe(e):'"';return`${r.id} ${o} ${n} ${s}`}function Ze(r,e,t,s){let n=[],o=r.title||"Untitled",i=C.getInstance().getTypeIcon(r.type),a=e?Qe(e):'"',{readTokens:d,discoveryDisplay:l}=$(r,s);n.push(`**${r.id}** ${a} ${i} **${o}**`),t&&n.push(t);let c=[];return s.showReadTokens&&c.push(`~${d}t`),s.showWorkTokens&&c.push(l),c.length>0&&n.push(c.join(" ")),n.push(""),n}function et(r,e){return[`S${r.id} ${r.request||"Session started"} (${e})`]}function P(r,e){return e?[`**${r}**: ${e}`,""]:[]}function tt(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function st(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}function rt(r){return`# [${r}] recent context, ${Be()}
785
+ `).all(...e,...e,t.sessionCount+_e)}function Ge(r){return r.replace(/[/.]/g,"-")}function ns(r){if(!r.includes('"type":"assistant"'))return null;let e=JSON.parse(r);if(e.type==="assistant"&&e.message?.content&&Array.isArray(e.message.content)){let t="";for(let s of e.message.content)s.type==="text"&&(t+=s.text);if(t=t.replace(Fe,"").trim(),t)return t}return null}function os(r){for(let e=r.length-1;e>=0;e--)try{let t=ns(r[e]);if(t)return t}catch(t){t instanceof Error?u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e},t):u.debug("WORKER","Skipping malformed transcript line",{lineIndex:e,error:String(t)});continue}return""}function is(r){try{if(!(0,K.existsSync)(r))return{userMessage:"",assistantMessage:""};let e=(0,K.readFileSync)(r,"utf-8").trim();if(!e)return{userMessage:"",assistantMessage:""};let t=e.split(`
786
+ `).filter(n=>n.trim());return{userMessage:"",assistantMessage:os(t)}}catch(e){return e instanceof Error?u.failure("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r},e):u.warn("WORKER","Failed to extract prior messages from transcript",{transcriptPath:r,error:String(e)}),{userMessage:"",assistantMessage:""}}}function pe(r,e,t,s){if(!e.showLastMessage||r.length===0)return{userMessage:"",assistantMessage:""};let n=r.find(d=>d.memory_session_id!==t);if(!n)return{userMessage:"",assistantMessage:""};let o=n.memory_session_id,i=Ge(s),a=Pe.default.join(v,"projects",i,`${o}.jsonl`);return is(a)}function je(r,e){let t=e[0]?.id;return r.map((s,n)=>{let o=n===0?null:e[n+1];return{...s,displayEpoch:o?o.created_at_epoch:s.created_at_epoch,displayTime:o?o.created_at:s.created_at,shouldShowLink:s.id!==t}})}function Ee(r,e){let t=[...r.map(s=>({type:"observation",data:s})),...e.map(s=>({type:"summary",data:s}))];return t.sort((s,n)=>{let o=s.type==="observation"?s.data.created_at_epoch:s.data.displayEpoch,i=n.type==="observation"?n.data.created_at_epoch:n.data.displayEpoch;return o-i}),t}function Xe(r,e){return new Set(r.slice(0,e).map(t=>t.id))}function Be(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function We(r){return[`# [${r}] recent context, ${Be()}`,""]}function Ve(){return[`Legend: \u{1F3AF}session ${C.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji}${t.id}`).join(" ")}`,"Format: ID TIME TYPE TITLE","Fetch details: get_observations([IDs]) | Search: mem-search skill",""]}function qe(){return[]}function Ye(){return[]}function Ke(r,e){let t=[],s=[`${r.totalObservations} obs (${r.totalReadTokens.toLocaleString()}t read)`,`${r.totalDiscoveryTokens.toLocaleString()}t work`];return r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)&&(e.showSavingsPercent?s.push(`${r.savingsPercent}% savings`):e.showSavingsAmount&&s.push(`${r.savings.toLocaleString()}t saved`)),t.push(`Stats: ${s.join(" | ")}`),t.push(""),t}function Je(r){return[`### ${r}`]}function Qe(r){return r.toLowerCase().replace(" am","a").replace(" pm","p")}function ze(r,e,t){let s=r.title||"Untitled",n=C.getInstance().getTypeIcon(r.type),o=e?Qe(e):'"';return`${r.id} ${o} ${n} ${s}`}function Ze(r,e,t,s){let n=[],o=r.title||"Untitled",i=C.getInstance().getTypeIcon(r.type),a=e?Qe(e):'"',{readTokens:d,discoveryDisplay:l}=$(r,s);n.push(`**${r.id}** ${a} ${i} **${o}**`),t&&n.push(t);let c=[];return s.showReadTokens&&c.push(`~${d}t`),s.showWorkTokens&&c.push(l),c.length>0&&n.push(c.join(" ")),n.push(""),n}function et(r,e){return[`S${r.id} ${r.request||"Session started"} (${e})`]}function H(r,e){return e?[`**${r}**: ${e}`,""]:[]}function tt(r){return r.assistantMessage?["","---","","**Previously**","",`A: ${r.assistantMessage}`,""]:[]}function st(r,e){return["",`Access ${Math.round(r/1e3)}k tokens of past work via get_observations([IDs]) or mem-search skill.`]}function rt(r){return`# [${r}] recent context, ${Be()}
787
787
 
788
- No previous sessions found.`}function nt(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function ot(r){return["",`${_.bright}${_.cyan}[${r}] recent context, ${nt()}${_.reset}`,`${_.gray}${"\u2500".repeat(60)}${_.reset}`,""]}function it(){let e=C.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${_.dim}Legend: session-request | ${e}${_.reset}`,""]}function at(){return[`${_.bright}Column Key${_.reset}`,`${_.dim} Read: Tokens to read this observation (cost to learn it now)${_.reset}`,`${_.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${_.reset}`,""]}function dt(){return[`${_.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${_.reset}`,"",`${_.dim}When you need implementation details, rationale, or debugging context:${_.reset}`,`${_.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${_.reset}`,`${_.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${_.reset}`,`${_.dim} - Trust this index over re-reading code for past decisions and learnings${_.reset}`,""]}function _t(r,e){let t=[];if(t.push(`${_.bright}${_.cyan}Context Economics${_.reset}`),t.push(`${_.dim} Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)${_.reset}`),t.push(`${_.dim} Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${_.reset}`),r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let s=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?s+=`${r.savings.toLocaleString()} tokens (${r.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?s+=`${r.savings.toLocaleString()} tokens`:s+=`${r.savingsPercent}% reduction from reuse`,t.push(`${_.green}${s}${_.reset}`)}return t.push(""),t}function ut(r){return[`${_.bright}${_.cyan}${r}${_.reset}`,""]}function ct(r){return[`${_.dim}${r}${_.reset}`]}function lt(r,e,t,s){let n=r.title||"Untitled",o=C.getInstance().getTypeIcon(r.type),{readTokens:i,discoveryTokens:a,workEmoji:d}=$(r,s),l=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),c=s.showReadTokens&&i>0?`${_.dim}(~${i}t)${_.reset}`:"",T=s.showWorkTokens&&a>0?`${_.dim}(${d} ${a.toLocaleString()}t)${_.reset}`:"";return` ${_.dim}#${r.id}${_.reset} ${l} ${o} ${n} ${c} ${T}`}function mt(r,e,t,s,n){let o=[],i=r.title||"Untitled",a=C.getInstance().getTypeIcon(r.type),{readTokens:d,discoveryTokens:l,workEmoji:c}=$(r,n),T=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),p=n.showReadTokens&&d>0?`${_.dim}(~${d}t)${_.reset}`:"",E=n.showWorkTokens&&l>0?`${_.dim}(${c} ${l.toLocaleString()}t)${_.reset}`:"";return o.push(` ${_.dim}#${r.id}${_.reset} ${T} ${a} ${_.bright}${i}${_.reset}`),s&&o.push(` ${_.dim}${s}${_.reset}`),(p||E)&&o.push(` ${p} ${E}`),o.push(""),o}function pt(r,e){let t=`${r.request||"Session started"} (${e})`;return[`${_.yellow}#S${r.id}${_.reset} ${t}`,""]}function H(r,e,t){return e?[`${t}${r}:${_.reset} ${e}`,""]:[]}function Et(r){return r.assistantMessage?["","---","",`${_.bright}${_.magenta}Previously${_.reset}`,"",`${_.dim}A: ${r.assistantMessage}${_.reset}`,""]:[]}function gt(r,e){let t=Math.round(r/1e3);return["",`${_.dim}Access ${t}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${_.reset}`]}function Tt(r){return`
788
+ No previous sessions found.`}function nt(){let r=new Date,e=r.toLocaleDateString("en-CA"),t=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}).toLowerCase().replace(" ",""),s=r.toLocaleTimeString("en-US",{timeZoneName:"short"}).split(" ").pop();return`${e} ${t} ${s}`}function ot(r){return["",`${_.bright}${_.cyan}[${r}] recent context, ${nt()}${_.reset}`,`${_.gray}${"\u2500".repeat(60)}${_.reset}`,""]}function it(){let e=C.getInstance().getActiveMode().observation_types.map(t=>`${t.emoji} ${t.id}`).join(" | ");return[`${_.dim}Legend: session-request | ${e}${_.reset}`,""]}function at(){return[`${_.bright}Column Key${_.reset}`,`${_.dim} Read: Tokens to read this observation (cost to learn it now)${_.reset}`,`${_.dim} Work: Tokens spent on work that produced this record ( research, building, deciding)${_.reset}`,""]}function dt(){return[`${_.dim}Context Index: This semantic index (titles, types, files, tokens) is usually sufficient to understand past work.${_.reset}`,"",`${_.dim}When you need implementation details, rationale, or debugging context:${_.reset}`,`${_.dim} - Fetch by ID: get_observations([IDs]) for observations visible in this index${_.reset}`,`${_.dim} - Search history: Use the mem-search skill for past decisions, bugs, and deeper research${_.reset}`,`${_.dim} - Trust this index over re-reading code for past decisions and learnings${_.reset}`,""]}function _t(r,e){let t=[];if(t.push(`${_.bright}${_.cyan}Context Economics${_.reset}`),t.push(`${_.dim} Loading: ${r.totalObservations} observations (${r.totalReadTokens.toLocaleString()} tokens to read)${_.reset}`),t.push(`${_.dim} Work investment: ${r.totalDiscoveryTokens.toLocaleString()} tokens spent on research, building, and decisions${_.reset}`),r.totalDiscoveryTokens>0&&(e.showSavingsAmount||e.showSavingsPercent)){let s=" Your savings: ";e.showSavingsAmount&&e.showSavingsPercent?s+=`${r.savings.toLocaleString()} tokens (${r.savingsPercent}% reduction from reuse)`:e.showSavingsAmount?s+=`${r.savings.toLocaleString()} tokens`:s+=`${r.savingsPercent}% reduction from reuse`,t.push(`${_.green}${s}${_.reset}`)}return t.push(""),t}function ut(r){return[`${_.bright}${_.cyan}${r}${_.reset}`,""]}function ct(r){return[`${_.dim}${r}${_.reset}`]}function lt(r,e,t,s){let n=r.title||"Untitled",o=C.getInstance().getTypeIcon(r.type),{readTokens:i,discoveryTokens:a,workEmoji:d}=$(r,s),l=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),c=s.showReadTokens&&i>0?`${_.dim}(~${i}t)${_.reset}`:"",T=s.showWorkTokens&&a>0?`${_.dim}(${d} ${a.toLocaleString()}t)${_.reset}`:"";return` ${_.dim}#${r.id}${_.reset} ${l} ${o} ${n} ${c} ${T}`}function mt(r,e,t,s,n){let o=[],i=r.title||"Untitled",a=C.getInstance().getTypeIcon(r.type),{readTokens:d,discoveryTokens:l,workEmoji:c}=$(r,n),T=t?`${_.dim}${e}${_.reset}`:" ".repeat(e.length),p=n.showReadTokens&&d>0?`${_.dim}(~${d}t)${_.reset}`:"",E=n.showWorkTokens&&l>0?`${_.dim}(${c} ${l.toLocaleString()}t)${_.reset}`:"";return o.push(` ${_.dim}#${r.id}${_.reset} ${T} ${a} ${_.bright}${i}${_.reset}`),s&&o.push(` ${_.dim}${s}${_.reset}`),(p||E)&&o.push(` ${p} ${E}`),o.push(""),o}function pt(r,e){let t=`${r.request||"Session started"} (${e})`;return[`${_.yellow}#S${r.id}${_.reset} ${t}`,""]}function G(r,e,t){return e?[`${t}${r}:${_.reset} ${e}`,""]:[]}function Et(r){return r.assistantMessage?["","---","",`${_.bright}${_.magenta}Previously${_.reset}`,"",`${_.dim}A: ${r.assistantMessage}${_.reset}`,""]:[]}function gt(r,e){let t=Math.round(r/1e3);return["",`${_.dim}Access ${t}k tokens of past research & decisions for just ${e.toLocaleString()}t. Use the claude-mem skill to access memories by ID.${_.reset}`]}function Tt(r){return`
789
789
  ${_.bright}${_.cyan}[${r}] recent context, ${nt()}${_.reset}
790
790
  ${_.gray}${"\u2500".repeat(60)}${_.reset}
791
791
 
792
792
  ${_.dim}No previous sessions found for this project yet.${_.reset}
793
- `}function ft(r,e,t,s){let n=[];return s?n.push(...ot(r)):n.push(...We(r)),s?n.push(...it()):n.push(...Ve()),s?n.push(...at()):n.push(...qe()),s?n.push(...dt()):n.push(...Ye()),Y(t)&&(s?n.push(..._t(e,t)):n.push(...Ke(e,t))),n}var ge=U(require("path"),1);function z(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return u.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function Te(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function fe(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function bt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function St(r,e){return ge.default.isAbsolute(r)?ge.default.relative(e,r):r}function ht(r,e,t){let s=z(r);if(s.length>0)return St(s[0],e);if(t){let n=z(t);if(n.length>0)return St(n[0],e)}return"General"}function is(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=bt(n);e.has(o)||e.set(o,[]),e.get(o).push(s)}let t=Array.from(e.entries()).sort((s,n)=>{let o=new Date(s[0]).getTime(),i=new Date(n[0]).getTime();return o-i});return new Map(t)}function Ot(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?z(r.facts).join(`
794
- `):null}function as(r,e,t,s){let n=[];n.push(...Je(r));let o="";for(let i of e)if(i.type==="summary"){let a=i.data,d=Te(a.displayTime);n.push(...et(a,d))}else{let a=i.data,d=fe(a.created_at),c=d!==o?d:"";if(o=d,t.has(a.id)){let p=Ot(a,s);n.push(...Ze(a,c,p,s))}else n.push(ze(a,c,s))}return n}function ds(r,e,t,s,n){let o=[];o.push(...ut(r));let i=null,a="";for(let d of e)if(d.type==="summary"){i=null,a="";let l=d.data,c=Te(l.displayTime);o.push(...pt(l,c))}else{let l=d.data,c=ht(l.files_modified,n,l.files_read),T=fe(l.created_at),p=T!==a;a=T;let E=t.has(l.id);if(c!==i&&(o.push(...ct(c)),i=c),E){let f=Ot(l,s);o.push(...mt(l,T,p,f,s))}else o.push(lt(l,T,p,s))}return o.push(""),o}function _s(r,e,t,s,n,o){return o?ds(r,e,t,s,n):as(r,e,t,s)}function Rt(r,e,t,s,n){let o=[],i=is(r);for(let[a,d]of i)o.push(..._s(a,d,e,t,s,n));return o}function At(r,e,t){return!(!r.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||t&&e.created_at_epoch<=t.created_at_epoch)}function Nt(r,e){let t=[];return e?(t.push(...H("Investigated",r.investigated,_.blue)),t.push(...H("Learned",r.learned,_.yellow)),t.push(...H("Completed",r.completed,_.green)),t.push(...H("Next Steps",r.next_steps,_.magenta))):(t.push(...P("Investigated",r.investigated)),t.push(...P("Learned",r.learned)),t.push(...P("Completed",r.completed)),t.push(...P("Next Steps",r.next_steps))),t}function Ct(r,e){return e?Et(r):tt(r)}function It(r,e,t){return!Y(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?gt(r.totalDiscoveryTokens,r.totalReadTokens):st(r.totalDiscoveryTokens,r.totalReadTokens)}var us=Lt.default.join((0,Mt.homedir)(),".claude","plugins","marketplaces","bjlee2024","plugin",".install-version");function cs(){try{return new W}catch(r){if(r instanceof Error&&r.code==="ERR_DLOPEN_FAILED"){try{(0,Dt.unlinkSync)(us)}catch(e){e instanceof Error?u.debug("WORKER","Marker file cleanup failed (may not exist)",{},e):u.debug("WORKER","Marker file cleanup failed (may not exist)",{error:String(e)})}return u.error("WORKER","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function ls(r,e){return e?Tt(r):rt(r)}function ms(r,e,t,s,n,o,i){let a=[],d=ce(e);a.push(...ft(r,d,s,i));let l=t.slice(0,s.sessionCount),c=je(l,t),T=Ee(e,c),p=Xe(e,s.fullObservationCount);a.push(...Rt(T,p,s,n,i));let E=t[0],f=e[0];At(s,E,f)&&a.push(...Nt(E,i));let b=pe(e,s,o,n);return a.push(...Ct(b,i)),a.push(...It(d,s,i)),a.join(`
795
- `).trimEnd()}async function Se(r,e=!1){let t=de(),s=r?.cwd??process.cwd(),n=ne(s),o=r?.projects?.length?r.projects:n.allProjects,i=o[o.length-1]??n.primary;r?.full&&(t.totalObservationCount=999999,t.sessionCount=999999);let a=cs();if(!a)return"";try{let d=o.length>1?Pe(a,o,t):le(a,i,t),l=o.length>1?He(a,o,t):me(a,i,t);return d.length===0&&l.length===0?ls(i,e):ms(i,d,l,t,s,r?.session_id,e)}finally{a.close()}}0&&(module.exports={generateContext});
793
+ `}function ft(r,e,t,s){let n=[];return s?n.push(...ot(r)):n.push(...We(r)),s?n.push(...it()):n.push(...Ve()),s?n.push(...at()):n.push(...qe()),s?n.push(...dt()):n.push(...Ye()),Y(t)&&(s?n.push(..._t(e,t)):n.push(...Ke(e,t))),n}var ge=U(require("path"),1);function z(r){if(!r)return[];try{let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch(e){return u.debug("PARSER","Failed to parse JSON array, using empty fallback",{preview:r?.substring(0,50)},e instanceof Error?e:new Error(String(e))),[]}}function Te(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})}function fe(r){return new Date(r).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})}function bt(r){return new Date(r).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})}function St(r,e){return ge.default.isAbsolute(r)?ge.default.relative(e,r):r}function ht(r,e,t){let s=z(r);if(s.length>0)return St(s[0],e);if(t){let n=z(t);if(n.length>0)return St(n[0],e)}return"General"}function as(r){let e=new Map;for(let s of r){let n=s.type==="observation"?s.data.created_at:s.data.displayTime,o=bt(n);e.has(o)||e.set(o,[]),e.get(o).push(s)}let t=Array.from(e.entries()).sort((s,n)=>{let o=new Date(s[0]).getTime(),i=new Date(n[0]).getTime();return o-i});return new Map(t)}function Ot(r,e){return e.fullObservationField==="narrative"?r.narrative:r.facts?z(r.facts).join(`
794
+ `):null}function ds(r,e,t,s){let n=[];n.push(...Je(r));let o="";for(let i of e)if(i.type==="summary"){let a=i.data,d=Te(a.displayTime);n.push(...et(a,d))}else{let a=i.data,d=fe(a.created_at),c=d!==o?d:"";if(o=d,t.has(a.id)){let p=Ot(a,s);n.push(...Ze(a,c,p,s))}else n.push(ze(a,c,s))}return n}function _s(r,e,t,s,n){let o=[];o.push(...ut(r));let i=null,a="";for(let d of e)if(d.type==="summary"){i=null,a="";let l=d.data,c=Te(l.displayTime);o.push(...pt(l,c))}else{let l=d.data,c=ht(l.files_modified,n,l.files_read),T=fe(l.created_at),p=T!==a;a=T;let E=t.has(l.id);if(c!==i&&(o.push(...ct(c)),i=c),E){let f=Ot(l,s);o.push(...mt(l,T,p,f,s))}else o.push(lt(l,T,p,s))}return o.push(""),o}function us(r,e,t,s,n,o){return o?_s(r,e,t,s,n):ds(r,e,t,s)}function Rt(r,e,t,s,n){let o=[],i=as(r);for(let[a,d]of i)o.push(...us(a,d,e,t,s,n));return o}function At(r,e,t){return!(!r.showLastSummary||!e||!!!(e.investigated||e.learned||e.completed||e.next_steps)||t&&e.created_at_epoch<=t.created_at_epoch)}function Nt(r,e){let t=[];return e?(t.push(...G("Investigated",r.investigated,_.blue)),t.push(...G("Learned",r.learned,_.yellow)),t.push(...G("Completed",r.completed,_.green)),t.push(...G("Next Steps",r.next_steps,_.magenta))):(t.push(...H("Investigated",r.investigated)),t.push(...H("Learned",r.learned)),t.push(...H("Completed",r.completed)),t.push(...H("Next Steps",r.next_steps))),t}function Ct(r,e){return e?Et(r):tt(r)}function It(r,e,t){return!Y(e)||r.totalDiscoveryTokens<=0||r.savings<=0?[]:t?gt(r.totalDiscoveryTokens,r.totalReadTokens):st(r.totalDiscoveryTokens,r.totalReadTokens)}var cs=Lt.default.join((0,Mt.homedir)(),".claude","plugins","marketplaces","bjlee2024","plugin",".install-version");function ls(){try{return new V}catch(r){if(r instanceof Error&&r.code==="ERR_DLOPEN_FAILED"){try{(0,Dt.unlinkSync)(cs)}catch(e){e instanceof Error?u.debug("WORKER","Marker file cleanup failed (may not exist)",{},e):u.debug("WORKER","Marker file cleanup failed (may not exist)",{error:String(e)})}return u.error("WORKER","Native module rebuild needed - restart Claude Code to auto-fix"),null}throw r}}function ms(r,e){return e?Tt(r):rt(r)}function ps(r,e,t,s,n,o,i){let a=[],d=ce(e);a.push(...ft(r,d,s,i));let l=t.slice(0,s.sessionCount),c=je(l,t),T=Ee(e,c),p=Xe(e,s.fullObservationCount);a.push(...Rt(T,p,s,n,i));let E=t[0],f=e[0];At(s,E,f)&&a.push(...Nt(E,i));let b=pe(e,s,o,n);return a.push(...Ct(b,i)),a.push(...It(d,s,i)),a.join(`
795
+ `).trimEnd()}async function Se(r,e=!1){let t=de(),s=r?.cwd??process.cwd(),n=ne(s),o=r?.projects?.length?r.projects:n.allProjects,i=o[o.length-1]??n.primary;r?.full&&(t.totalObservationCount=999999,t.sessionCount=999999);let a=ls();if(!a)return"";try{let d=o.length>1?$e(a,o,t):le(a,i,t),l=o.length>1?He(a,o,t):me(a,i,t);return d.length===0&&l.length===0?ms(i,e):ps(i,d,l,t,s,r?.session_id,e)}finally{a.close()}}0&&(module.exports={generateContext});
@@ -212,7 +212,7 @@ ${f}`}let a=s.lineStart;for(let u=s.lineStart-1;u>=0;u--){let l=i[u].trim();if(l
212
212
  ${c}`}var $_=new Set([".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".pyw",".go",".rs",".rb",".java",".cs",".cpp",".cc",".cxx",".c",".h",".hpp",".hh",".swift",".kt",".kts",".php",".vue",".svelte",".ex",".exs",".lua",".scala",".sc",".sh",".bash",".zsh",".hs",".zig",".css",".scss",".toml",".yml",".yaml",".sql",".md",".mdx"]),yP=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),SP=512*1024;async function*P_(t,e,r=20,n){if(r<=0)return;let o;try{o=await(0,Nr.readdir)(t,{withFileTypes:!0})}catch(s){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,s instanceof Error?s:void 0);return}for(let s of o){if(s.name.startsWith(".")&&s.name!=="."||yP.has(s.name))continue;let i=(0,ro.join)(t,s.name);if(s.isDirectory())yield*P_(i,e,r-1,n);else if(s.isFile()){let a=s.name.slice(s.name.lastIndexOf("."));($_.has(a)||n&&n.has(a))&&(yield i)}}}async function vP(t){try{let e=await(0,Nr.stat)(t);if(e.size>SP||e.size===0)return null;let r=await(0,Nr.readFile)(t,"utf-8");return r.slice(0,1e3).includes("\0")?null:r}catch(e){return y.debug("WORKER",`safeReadFile: failed to read ${t}`,void 0,e instanceof Error?e:void 0),null}}async function T_(t,e,r={}){let n=r.maxResults||20,o=e.toLowerCase(),s=o.split(/[\s_\-./]+/).filter(E=>E.length>0),i=r.projectRoot||t,a=to(i),c=new Set;for(let E of Object.values(a.grammars))for(let v of E.extensions)$_.has(v)||c.add(v);let u=[];for await(let E of P_(t,t,20,c.size>0?c:void 0)){if(r.filePattern&&!(0,ro.relative)(t,E).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let v=await vP(E);v&&u.push({absolutePath:E,relativePath:(0,ro.relative)(t,E),content:v})}let l=w_(u,i),d=[],p=[],f=0;for(let[E,v]of l){f+=bP(v);let x=Ls(E.toLowerCase(),s)>0,ye=[],we=(Lt,tr)=>{for(let ae of Lt){let vt=0,Be="",Fr=Ls(ae.name.toLowerCase(),s);Fr>0&&(vt+=Fr*3,Be="name match"),ae.signature.toLowerCase().includes(o)&&(vt+=2,Be=Be?`${Be} + signature`:"signature match"),ae.jsdoc&&ae.jsdoc.toLowerCase().includes(o)&&(vt+=1,Be=Be?`${Be} + jsdoc`:"jsdoc match"),vt>0&&(x=!0,ye.push({filePath:E,symbolName:tr?`${tr}.${ae.name}`:ae.name,kind:ae.kind,signature:ae.signature,jsdoc:ae.jsdoc,lineStart:ae.lineStart,lineEnd:ae.lineEnd,matchReason:Be})),ae.children&&we(ae.children,ae.name)}};we(v.symbols),x&&(d.push(v),p.push(...ye))}p.sort((E,v)=>{let $=Ls(E.symbolName.toLowerCase(),s);return Ls(v.symbolName.toLowerCase(),s)-$});let m=p.slice(0,n),_=new Set(m.map(E=>E.filePath)),S=d.filter(E=>_.has(E.filePath)).slice(0,n),b=S.reduce((E,v)=>E+v.foldedTokenEstimate,0);return{foldedFiles:S,matchingSymbols:m,totalFilesScanned:u.length,totalSymbolsFound:f,tokenEstimate:b}}function Ls(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let o=0,s=0;for(let i of n){let a=t.indexOf(i,o);a!==-1&&(s++,o=a+1)}s===n.length&&(r+=1)}return r}function bP(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function z_(t,e){let r=[];if(r.push(`\u{1F50D} Smart Search: "${e}"`),r.push(` Scanned ${t.totalFilesScanned} files, found ${t.totalSymbolsFound} symbols`),r.push(` ${t.matchingSymbols.length} matches across ${t.foldedFiles.length} files (~${t.tokenEstimate} tokens for folded view)`),r.push(""),t.matchingSymbols.length===0)return r.push(" No matching symbols found."),r.join(`
213
213
  `);r.push("\u2500\u2500 Matching Symbols \u2500\u2500"),r.push("");for(let n of t.matchingSymbols){if(r.push(` ${n.kind} ${n.symbolName} (${n.filePath}:${n.lineStart+1})`),r.push(` ${n.signature}`),n.jsdoc){let o=n.jsdoc.split(`
214
214
  `).find(s=>s.replace(/^[\s*/]+/,"").trim().length>0);o&&r.push(` \u{1F4AC} ${o.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Cr(n)),r.push("");return r.push("\u2500\u2500 Actions \u2500\u2500"),r.push(" To see full implementation: use smart_unfold with file path and symbol name"),r.join(`
215
- `)}var Eu=require("node:fs/promises"),qs=require("node:fs"),tt=require("node:path"),D_=require("node:os"),j_=require("node:url");var EP=Ir(le.API_REQUEST),Ve=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerBetaClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},no=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=wP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??EP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ve("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async resolveProject(e){return(await this.request("POST","/v1/projects/resolve",{name:e})).id}async getJobStatus(e){if(!e)throw new Ve("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.sourceEventId!==void 0?{sourceEventId:e.sourceEventId}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ve("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await uu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ve(l?"timeout":"transport",`Server beta ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ve("http_error",`Server beta ${e} ${r} returned ${i.status}: ${kP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Ve("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:c})}}};function vu(t){return t instanceof Ve}function wP(t){return t.replace(/\/+$/,"")}function kP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var Us=require("node:path"),jt=require("node:fs"),Dr=class t{client;mapPath;cache;constructor(e){this.client=e.client,this.mapPath=e.mapPath,this.cache=this.load()}static projectName(e){return(0,Us.basename)(e)}async resolve(e){let r=t.projectName(e),n=this.cache[r];if(n)return n;let o=await this.client.resolveProject(r);return this.cache[r]=o,this.persist(),o}load(){try{return(0,jt.existsSync)(this.mapPath)?JSON.parse((0,jt.readFileSync)(this.mapPath,"utf8")):{}}catch{return{}}}persist(){try{(0,jt.mkdirSync)((0,Us.dirname)(this.mapPath),{recursive:!0}),(0,jt.writeFileSync)(this.mapPath,JSON.stringify(this.cache,null,2),{mode:384})}catch{}}};function xP(t){let e=(t??"worker").trim().toLowerCase();return e==="server-beta"?"server-beta":e==="client"?"client":"worker"}function jr(){return xP(Gn().CLAUDE_MEM_RUNTIME)}function R_(){let t=Gn(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return y.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!n)return y.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let o={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new no(o),projectId:n,serverBaseUrl:e}}function I_(){let t=Gn(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim();if(!e)return y.warn("HOOK","[client-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[client-fallback] reason=missing_api_key"),null;let n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim()||null;return{runtime:"client",client:new no({serverBaseUrl:e,apiKey:r}),projectId:n,serverBaseUrl:e}}var L_=require("node:path"),UP={},$P="13.4.6";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var U_=!1,q_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,tt.dirname)((0,j_.fileURLToPath)(UP.url))}catch{return U_=!0,process.cwd()}})(),wu=(0,tt.resolve)(q_,"worker-service.cjs");function PP(){U_&&((0,qs.existsSync)(wu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:wu,mcpServerDir:q_}))}var O_={search:"/api/search",timeline:"/api/timeline"};async function bu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Ns(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function TP(t,e){let r=await Ns(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function Lr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await TP(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function zP(){try{return(await Ns("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function RP(){let t=jr();if(t==="server-beta"){let e=R_();return e?{...e,available:!0}:{runtime:"server-beta",available:!1,reason:"server-beta is selected but configuration is incomplete (missing url, api key, or project id)"}}if(t==="client"){let e=I_();return e?{...e,available:!0}:{runtime:"client",available:!1,reason:"client runtime selected but CLAUDE_MEM_SERVER_BETA_URL or CLAUDE_MEM_SERVER_BETA_API_KEY is missing"}}return null}function Ur(t){return vu(t)?{content:[{type:"text",text:`Server beta error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function qr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Zr(t){let e=RP();if(!e)throw new Ve("transport",`${t} requires CLAUDE_MEM_RUNTIME=server-beta or CLAUDE_MEM_RUNTIME=client. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ve("missing_api_key",`${t}: ${e.reason}`);return e}async function so(t,e){let r=e?.trim();return r||(t.projectId?t.projectId:new Dr({client:t.client,mapPath:(0,L_.join)(B,"project-map.json")}).resolve(process.cwd()))}async function A_(t){try{let e=Zr("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:await so(e,t.projectId),content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return qr(o)}catch(e){return Ur(e)}}async function IP(t){try{let e=Zr("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:await so(e,t.projectId),sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return qr(o)}catch(e){return Ur(e)}}async function M_(t){try{let e=Zr("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:await so(e,t.projectId),query:t.query,...t.limit!==void 0?{limit:t.limit}:{}},o=await e.client.searchObservations(n);return qr(o)}catch(e){return Ur(e)}}async function C_(t){try{let e=Zr("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:await so(e,t.projectId),query:t.query,...t.limit!==void 0?{limit:t.limit}:{}},o=await e.client.contextObservations(n);return qr(o)}catch(e){return Ur(e)}}async function OP(t){try{let e=Zr("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return qr(n)}catch(e){return Ur(e)}}async function AP(){if(await zP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),PP();try{let t=lu(),e=await d_(t,wu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var Z_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
215
+ `)}var Eu=require("node:fs/promises"),qs=require("node:fs"),tt=require("node:path"),D_=require("node:os"),j_=require("node:url");var EP=Ir(le.API_REQUEST),Ve=class extends Error{kind;status;cause;constructor(e,r,n={}){super(r),this.name="ServerBetaClientError",this.kind=e,this.status=n.status??null,this.cause=n.cause}isFallbackEligible(){return this.kind==="transport"||this.kind==="timeout"||this.kind==="missing_api_key"||this.kind==="http_error"&&(this.status!==null&&this.status>=500||this.status===429)}},no=class{baseUrl;apiKey;timeoutMs;constructor(e){this.baseUrl=wP(e.serverBaseUrl),this.apiKey=e.apiKey,this.timeoutMs=e.timeoutMs??EP}async startSession(e){let r=this.buildStartSessionPayload(e);return this.request("POST","/v1/sessions/start",r)}async recordEvent(e){let r=this.buildEventPayload(e),n=e.generate===!1?"/v1/events?generate=false":"/v1/events";return this.request("POST",n,r)}async endSession(e){if(!e.sessionId)throw new Ve("invalid_response","sessionId is required for endSession");return this.request("POST",`/v1/sessions/${encodeURIComponent(e.sessionId)}/end`,{})}async addObservation(e){return this.request("POST","/v1/memories",this.buildAddObservationPayload(e))}async searchObservations(e){return this.request("POST","/v1/search",this.buildSearchPayload(e))}async contextObservations(e){return this.request("POST","/v1/context",this.buildSearchPayload(e))}async resolveProject(e){return(await this.request("POST","/v1/projects/resolve",{name:e})).id}async getJobStatus(e){if(!e)throw new Ve("invalid_response","jobId is required for getJobStatus");return this.request("GET",`/v1/jobs/${encodeURIComponent(e)}`)}buildAddObservationPayload(e){let r=e.content,n=e.kind??"manual",o=typeof e.metadata?.title=="string"?e.metadata.title:void 0;return{projectId:e.projectId,kind:n,type:n,narrative:r,...o?{title:o}:{},...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildSearchPayload(e){return{projectId:e.projectId,query:e.query,...e.limit!==void 0?{limit:e.limit}:{}}}buildStartSessionPayload(e){return{projectId:e.projectId,...e.externalSessionId!==void 0?{externalSessionId:e.externalSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.agentId!==void 0?{agentId:e.agentId}:{},...e.agentType!==void 0?{agentType:e.agentType}:{},...e.platformSource!==void 0?{platformSource:e.platformSource}:{},...e.metadata!==void 0?{metadata:e.metadata}:{}}}buildEventPayload(e){return{projectId:e.projectId,sourceType:e.sourceType,eventType:e.eventType,occurredAtEpoch:e.occurredAtEpoch,...e.serverSessionId!==void 0?{serverSessionId:e.serverSessionId}:{},...e.contentSessionId!==void 0?{contentSessionId:e.contentSessionId}:{},...e.memorySessionId!==void 0?{memorySessionId:e.memorySessionId}:{},...e.payload!==void 0?{payload:e.payload}:{},...e.sourceEventId!==void 0?{sourceEventId:e.sourceEventId}:{}}}async request(e,r,n){if(!this.apiKey||!this.apiKey.trim())throw new Ve("missing_api_key","Server beta API key is not configured (CLAUDE_MEM_SERVER_BETA_API_KEY).");let o=`${this.baseUrl}${r}`,s={method:e,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};n!==void 0&&(s.body=JSON.stringify(n));let i;try{i=await uu(o,s,this.timeoutMs)}catch(c){let u=c instanceof Error?c.message:String(c),l=/timed out|timeout/i.test(u);throw new Ve(l?"timeout":"transport",`Server beta ${e} ${r} failed: ${u}`,{cause:c})}if(!i.ok){let c=await i.text().catch(()=>"");throw new Ve("http_error",`Server beta ${e} ${r} returned ${i.status}: ${kP(c,200)}`,{status:i.status})}let a=await i.text();if(!a||a.length===0)return{};try{return JSON.parse(a)}catch(c){throw new Ve("invalid_response",`Server beta ${e} ${r} returned non-JSON response`,{cause:c})}}};function vu(t){return t instanceof Ve}function wP(t){return t.replace(/\/+$/,"")}function kP(t,e){return t.length<=e?t:`${t.slice(0,e)}\u2026`}var Us=require("node:path"),jt=require("node:fs"),Dr=class t{client;mapPath;cache;constructor(e){this.client=e.client,this.mapPath=e.mapPath,this.cache=this.load()}static projectName(e){return(0,Us.basename)(e)}async resolve(e){let r=t.projectName(e),n=this.cache[r];if(n)return n;let o=await this.client.resolveProject(r);return this.cache[r]=o,this.persist(),o}load(){try{return(0,jt.existsSync)(this.mapPath)?JSON.parse((0,jt.readFileSync)(this.mapPath,"utf8")):{}}catch{return{}}}persist(){try{(0,jt.mkdirSync)((0,Us.dirname)(this.mapPath),{recursive:!0}),(0,jt.writeFileSync)(this.mapPath,JSON.stringify(this.cache,null,2),{mode:384})}catch{}}};function xP(t){let e=(t??"worker").trim().toLowerCase();return e==="server-beta"?"server-beta":e==="client"?"client":"worker"}function jr(){return xP(Gn().CLAUDE_MEM_RUNTIME)}function R_(){let t=Gn(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim(),n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim();if(!e)return y.warn("HOOK","[server-beta-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[server-beta-fallback] reason=missing_api_key"),null;if(!n)return y.warn("HOOK","[server-beta-fallback] reason=missing_project_id"),null;let o={serverBaseUrl:e,apiKey:r};return{runtime:"server-beta",client:new no(o),projectId:n,serverBaseUrl:e}}function I_(){let t=Gn(),e=(t.CLAUDE_MEM_SERVER_BETA_URL??"").trim(),r=(t.CLAUDE_MEM_SERVER_BETA_API_KEY??"").trim();if(!e)return y.warn("HOOK","[client-fallback] reason=missing_base_url"),null;if(!r)return y.warn("HOOK","[client-fallback] reason=missing_api_key"),null;let n=(t.CLAUDE_MEM_SERVER_BETA_PROJECT_ID??"").trim()||null;return{runtime:"client",client:new no({serverBaseUrl:e,apiKey:r}),projectId:n,serverBaseUrl:e}}var L_=require("node:path"),UP={},$P="13.4.9";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var U_=!1,q_=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,tt.dirname)((0,j_.fileURLToPath)(UP.url))}catch{return U_=!0,process.cwd()}})(),wu=(0,tt.resolve)(q_,"worker-service.cjs");function PP(){U_&&((0,qs.existsSync)(wu)||y.error("SYSTEM","mcp-server: dirname resolution failed (both __dirname and import.meta.url are unavailable). Fell back to process.cwd() and the resolved WORKER_SCRIPT_PATH does not exist. This is the actual problem \u2014 the worker bundle is fine, but mcp-server cannot locate it. Worker auto-start will fail until the dirname-resolution path is fixed.",{workerScriptPath:wu,mcpServerDir:q_}))}var O_={search:"/api/search",timeline:"/api/timeline"};async function bu(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[o,s]of Object.entries(e))s!=null&&r.append(o,String(s));let n=`${t}?${r}`;try{let o=await Ns(n);if(!o.ok){let i=await o.text();throw new Error(`Worker API error (${o.status}): ${i}`)}let s=await o.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),s}catch(o){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},o instanceof Error?o:new Error(String(o))),{content:[{type:"text",text:`Error calling Worker API: ${o instanceof Error?o.message:String(o)}`}],isError:!0}}}async function TP(t,e){let r=await Ns(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let o=await r.text();throw new Error(`Worker API error (${r.status}): ${o}`)}let n=await r.json();return y.debug("HTTP","Worker API success (POST)",void 0,{endpoint:t}),{content:[{type:"text",text:JSON.stringify(n,null,2)}]}}async function Lr(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await TP(t,e)}catch(r){return y.error("HTTP","Worker API error (POST)",{endpoint:t},r instanceof Error?r:new Error(String(r))),{content:[{type:"text",text:`Error calling Worker API: ${r instanceof Error?r.message:String(r)}`}],isError:!0}}}async function zP(){try{return(await Ns("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}function RP(){let t=jr();if(t==="server-beta"){let e=R_();return e?{...e,available:!0}:{runtime:"server-beta",available:!1,reason:"server-beta is selected but configuration is incomplete (missing url, api key, or project id)"}}if(t==="client"){let e=I_();return e?{...e,available:!0}:{runtime:"client",available:!1,reason:"client runtime selected but CLAUDE_MEM_SERVER_BETA_URL or CLAUDE_MEM_SERVER_BETA_API_KEY is missing"}}return null}function Ur(t){return vu(t)?{content:[{type:"text",text:`Server beta error (${t.kind}${t.status?` ${t.status}`:""}): ${t.message}`}],isError:!0}:{content:[{type:"text",text:`Tool error: ${t instanceof Error?t.message:String(t)}`}],isError:!0}}function qr(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function Zr(t){let e=RP();if(!e)throw new Ve("transport",`${t} requires CLAUDE_MEM_RUNTIME=server-beta or CLAUDE_MEM_RUNTIME=client. Current runtime is "worker"; use the existing search/timeline/get_observations tools for worker-mode memory access.`);if(!e.available)throw new Ve("missing_api_key",`${t}: ${e.reason}`);return e}async function so(t,e){let r=e?.trim();return r||(t.projectId?t.projectId:new Dr({client:t.client,mapPath:(0,L_.join)(B,"project-map.json")}).resolve(process.cwd()))}async function A_(t){try{let e=Zr("observation_add");if(typeof t?.content!="string"||t.content.trim().length===0)throw new Error('observation_add: "content" is required');let n={projectId:await so(e,t.projectId),content:t.content,...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.kind!==void 0?{kind:t.kind}:{},...t.metadata!==void 0?{metadata:t.metadata}:{}},o=await e.client.addObservation(n);return qr(o)}catch(e){return Ur(e)}}async function IP(t){try{let e=Zr("observation_record_event");if(typeof t?.eventType!="string"||t.eventType.trim().length===0)throw new Error('observation_record_event: "eventType" is required');let n={projectId:await so(e,t.projectId),sourceType:t.sourceType??"api",eventType:t.eventType,occurredAtEpoch:typeof t.occurredAtEpoch=="number"?t.occurredAtEpoch:Date.now(),...t.serverSessionId!==void 0?{serverSessionId:t.serverSessionId}:{},...t.contentSessionId!==void 0?{contentSessionId:t.contentSessionId}:{},...t.memorySessionId!==void 0?{memorySessionId:t.memorySessionId}:{},...t.payload!==void 0?{payload:t.payload}:{},...t.generate!==void 0?{generate:t.generate}:{}},o=await e.client.recordEvent(n);return qr(o)}catch(e){return Ur(e)}}async function M_(t){try{let e=Zr("observation_search");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_search: "query" is required');let n={projectId:await so(e,t.projectId),query:t.query,...t.limit!==void 0?{limit:t.limit}:{}},o=await e.client.searchObservations(n);return qr(o)}catch(e){return Ur(e)}}async function C_(t){try{let e=Zr("observation_context");if(typeof t?.query!="string"||t.query.trim().length===0)throw new Error('observation_context: "query" is required');let n={projectId:await so(e,t.projectId),query:t.query,...t.limit!==void 0?{limit:t.limit}:{}},o=await e.client.contextObservations(n);return qr(o)}catch(e){return Ur(e)}}async function OP(t){try{let e=Zr("observation_generation_status"),r=(t?.jobId??t?.job_id??"").trim();if(!r)throw new Error('observation_generation_status: "jobId" is required');let n=await e.client.getJobStatus(r);return qr(n)}catch(e){return Ur(e)}}async function AP(){if(await zP())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),PP();try{let t=lu(),e=await d_(t,wu);return e==="dead"&&y.error("SYSTEM","Worker auto-start failed \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running. Check earlier log lines for the specific failure reason (Bun not found, missing worker bundle, port conflict, etc.)."),e!=="dead"}catch(t){return y.error("SYSTEM","Worker auto-start threw \u2014 MCP tools that require the worker (search, timeline, get_observations) will fail until the worker is running.",void 0,t instanceof Error?t:new Error(String(t))),!1}}var Z_=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
216
216
  1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
217
217
  2. timeline(anchor=ID) \u2192 Get context around interesting results
218
218
  3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs
@@ -59,7 +59,7 @@ ${s.stack}`:` ${s.message}`;else if(this.getLevel()===0&&typeof s=="object")try{
59
59
  `,"utf8")}catch(f){Ay(`[LOGGER] Failed to write to log file: ${f instanceof Error?f.message:String(f)}
60
60
  `)}else Ay(p+`
61
61
  `)}debug(e,t,n,i){this.log(0,e,t,n,i)}info(e,t,n,i){this.log(1,e,t,n,i)}warn(e,t,n,i){this.log(2,e,t,n,i)}error(e,t,n,i){this.log(3,e,t,n,i)}dataIn(e,t,n,i){this.info(e,`\u2192 ${t}`,n,i)}dataOut(e,t,n,i){this.info(e,`\u2190 ${t}`,n,i)}success(e,t,n,i){this.info(e,`\u2713 ${t}`,n,i)}failure(e,t,n,i){this.error(e,`\u2717 ${t}`,n,i)}timing(e,t,n,i){this.info(e,`\u23F1 ${t}`,i,{duration:`${n}ms`})}happyPathError(e,t,n,i,s=""){let l=((new Error().stack||"").split(`
62
- `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Oy});var pT=h((mde,dT)=>{"use strict";var uT=Object.getOwnPropertySymbols,T$=Object.prototype.hasOwnProperty,A$=Object.prototype.propertyIsEnumerable;function K$(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function O$(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}dT.exports=O$()?Object.assign:function(r,e){for(var t,n=K$(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)T$.call(t,a)&&(n[a]=t[a]);if(uT){i=uT(t);for(var o=0;o<i.length;o++)A$.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var mT=h((hde,fT)=>{(function(){"use strict";var r=pT(),e=xy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function a(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function o(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(o(m)),E.push(a(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(o(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(k,L){if(k)I(k);else{var J=r({},t,L),ne=null;J.origin&&typeof J.origin=="function"?ne=J.origin:J.origin&&(ne=function(Re,ae){ae(null,J.origin)}),ne?ne(g.headers.origin,function(Re,ae){Re||!ae?I(Re):(J.origin=ae,p(J,g,E,I))}):I()}})}}fT.exports=f})()});function jy(r,e={}){let t=[];e.includeCors!==!1&&t.push(Fl()),t.push(Ry.default.json({limit:"5mb"})),t.push((s,a,o)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return o();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=a.send.bind(a);a.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${a.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},o()});let n=Pi(),i=yT.default.join(n,"plugin","ui");return t.push(Ry.default.static(i)),t}function Fl(){return(0,hT.default)({origin:(r,e)=>{!r||r.startsWith("http://localhost:")||r.startsWith("http://127.0.0.1:")?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function ho(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Cy(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Ry,hT,yT,bT=D(()=>{"use strict";Ry=ct(Nl(),1),hT=ct(mT(),1),yT=ct(require("path"),1);Ur();me()});var gT=D(()=>{"use strict";bT()});function vT(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function xT(r,e){e.status(404).json(vT("NotFound",`Cannot ${r.method} ${r.path}`))}var Ls,ET,ST=D(()=>{"use strict";me();Ls=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};ET=(r,e,t,n)=>{let i=r instanceof Ls?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Ls?r.code:void 0},r);let s=vT(r.name||"Error",r.message,r instanceof Ls?r.code:void 0,r instanceof Ls?r.details:void 0);t.status(i).json(s)}});var wT=D(()=>{"use strict"});function yo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(j$.has(t)){e[t]=n;continue}Py.has(t)||R$.has(t)||Dy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var Dy,Py,R$,j$,Jl=D(()=>{"use strict";Dy=["CLAUDECODE_","CLAUDE_CODE_"],Py=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),R$=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),j$=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function or(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}function L$(r){let e=IT.get(r);if(e&&Date.now()-e.capturedAtMs<M$)return e.token;let t=null;try{let n=(0,Fy.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...yo(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return IT.set(r,{token:t,capturedAtMs:Date.now()}),t}function Jy(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Gr.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return L$(r);try{let e=(0,Fy.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...yo(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Fn(r){if(!r||!or(r.pid))return!1;if(!r.startToken)return!0;let e=Jy(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Ul(){return My||(My=new qy),My}function Ly(){let r=N$.shift();r&&r()}var Fy,Gr,Ny,C$,D$,P$,M$,IT,qy,My,N$,Ns=D(()=>{"use strict";Fy=require("child_process");wT();Gr=require("fs"),Ny=ct(require("path"),1);me();Jl();Ur();C$=5e3,D$=1e3,P$=$e.supervisorRegistry();M$=5e3,IT=new Map;qy=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=P$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Gr.mkdirSync)(Ny.default.dirname(this.registryPath),{recursive:!0}),!(0,Gr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Gr.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&Ly()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)or(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)Ly();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(o=>o.pid)});let i=t.filter(o=>or(o.pid));for(let o of i)try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}let s=Date.now()+C$;for(;Date.now()<s&&i.filter(c=>or(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let a=i.filter(o=>or(o.pid));for(let o of a){_.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}}if(a.length>0){let o=Date.now()+D$;for(;Date.now()<o&&a.filter(l=>or(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of t)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of t)o.type==="sdk"&&Ly();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Gr.mkdirSync)(Ny.default.dirname(this.registryPath),{recursive:!0}),(0,Gr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},My=null;N$=[]});var _T,kT=D(()=>{"use strict";_T={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function jT(r){let e=r.currentPid??process.pid,t=r.pidFilePath??F$,n=r.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!or(a.pid)){r.registry.unregister(a.id);continue}try{await AT(a,"SIGTERM")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await TT(i,5e3);let s=i.filter(a=>or(a.pid));for(let a of s)try{await AT(a,"SIGKILL")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await TT(s,1e3);for(let a of i)r.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))r.registry.unregister(a.id);try{(0,OT.rmSync)(t,{force:!0})}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},a):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(a)})}r.registry.pruneDeadEntries()}async function TT(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>or(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function AT(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}try{process.kill(t,e)}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(a){if(a instanceof Error&&a.code==="ESRCH")return;throw a}return}let i=await J$();if(i){await new Promise((a,o)=>{i(t,e,c=>{if(!c){a();return}if(c.code==="ESRCH"){a();return}o(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await q$("taskkill",s,{timeout:_T.POWERSHELL_COMMAND,windowsHide:!0})}async function J$(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var KT,OT,RT,q$,F$,CT=D(()=>{"use strict";KT=require("child_process"),OT=require("fs"),RT=require("util");me();kT();Ns();Ur();q$=(0,RT.promisify)(KT.execFile),F$=$e.workerPid()});function U$(){let e=Ul().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function PT(){qs===null&&(qs=setInterval(U$,DT),qs.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:DT}))}function MT(){qs!==null&&(clearInterval(qs),qs=null,_.debug("SYSTEM","Health checker stopped"))}var DT,qs,LT=D(()=>{"use strict";me();Ns();DT=3e4,qs=null});function NT(){return B$}function $$(r={}){let e=r.pidFilePath??G$;if(!(0,Mi.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Mi.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Mi.rmSync)(e,{force:!0}),"invalid"}return Fn(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Mi.rmSync)(e,{force:!0}),"stale")}var Mi,G$,Uy,B$,qT=D(()=>{"use strict";Mi=require("fs");me();Ns();CT();LT();Ur();G$=$e.workerPid(),Uy=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),$$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,PT()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}MT(),this.stopPromise=jT({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},B$=new Uy(Ul())});function Gy(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var FT=D(()=>{"use strict"});function By(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var JT=D(()=>{"use strict"});var $y,UT,Zde,GT=D(()=>{"use strict";$y=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}clear(){this.entries.clear()}},UT=new $y,Zde=900*1e3});function z$(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var VT,HT,Hy,bo,zT,V$,Vy,BT,H$,$T,Gl,YT=D(()=>{"use strict";VT=ct(Nl(),1),HT=ct(require("http"),1),Hy=ct(require("fs"),1),bo=ct(require("path"),1);sT();me();gT();ST();qT();Ns();Jl();FT();JT();GT();zT=bo.default.resolve(__dirname,"../skills/mem-search"),V$=bo.default.join(zT,"operations"),Vy=bo.default.join(zT,"SKILL.md"),BT=(()=>{try{let r=Hy.readFileSync(Vy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:Vy,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:Vy,message:r instanceof Error?r.message:String(r)}),null}})(),H$=(()=>{let r=new Map;for(let e of _y){let t=bo.default.join(V$,`${e}.md`);try{r.set(e,Hy.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),$T="13.4.6";Gl=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,VT.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=HT.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(xT),this.app.use(ET)}setupMiddleware(){jy(Cy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{z$(t),n()})}setupCors(){this.app.use(Fl())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:$T,workerPath:this.options.workerPath,uptime:By(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),rateLimits:UT.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:$T})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!iT.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!_y.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let a=H$.get(i);return a===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:a}]})}if(BT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(BT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",ho,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):Gy(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",ho,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):Gy(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",ho,(e,t)=>{let a=NT().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:or(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Py.has(f)||Dy.some(m=>f.startsWith(m))),l=By(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c}})})}extractInstructionSection(e,t){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[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Dt,Y$,W$,zy,WT=D(()=>{"use strict";Dt=require("zod"),Y$=Dt.z.enum(["hook","worker","provider","server","api"]),W$=Dt.z.object({id:Dt.z.string().min(1),projectId:Dt.z.string().min(1),serverSessionId:Dt.z.string().min(1).nullable().default(null),sourceType:Y$,eventType:Dt.z.string().min(1),platformSource:Dt.z.string().min(1).nullable().default(null),sourceEventId:Dt.z.string().min(1).nullable().default(null),payload:Dt.z.unknown().default({}),contentSessionId:Dt.z.string().min(1).nullable().default(null),memorySessionId:Dt.z.string().min(1).nullable().default(null),occurredAtEpoch:Dt.z.number().int().nonnegative(),createdAtEpoch:Dt.z.number().int().nonnegative()}),zy=W$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,sourceEventId:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,Bl.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function QT(r){return Array.isArray(r)?r:[]}function ve(r){return typeof r=="number"?r:new Date(r).getTime()}function cr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function W(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function _r(r,e,t){if(!await W(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function mn(r,e,t,n){if(!await W(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function go(r){return JSON.stringify(Yy(r))}function kr(r){return(0,Bl.createHash)("sha256").update(go(r)).digest("hex")}function Yy(r){if(Array.isArray(r))return r.map(Yy);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Yy(e[n]),t),{})}return r}var Bl,Br=D(()=>{"use strict";Bl=require("crypto")});function XT(r){return r.sourceEventId?`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),go(r.payload??{})])}`}function Wy(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:ze(r.metadata),occurredAtEpoch:ve(r.occurred_at),receivedAtEpoch:ve(r.received_at),createdAtEpoch:ve(r.created_at)}}var lr,Fs=D(()=>{"use strict";Br();lr=class{constructor(e){this.client=e}client;async create(e){await _r(this.client,e.projectId,e.teamId),e.serverSessionId&&await mn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=XT(e),n=await W(this.client,`
62
+ `)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),u=l?`${l[1].split("/").pop()}:${l[2]}`:"unknown",d={...n,location:u};return this.warn(e,`[HAPPY-PATH] ${t}`,d,i),s}},_=new Oy});var pT=h((mde,dT)=>{"use strict";var uT=Object.getOwnPropertySymbols,T$=Object.prototype.hasOwnProperty,A$=Object.prototype.propertyIsEnumerable;function K$(r){if(r==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(r)}function O$(){try{if(!Object.assign)return!1;var r=new String("abc");if(r[5]="de",Object.getOwnPropertyNames(r)[0]==="5")return!1;for(var e={},t=0;t<10;t++)e["_"+String.fromCharCode(t)]=t;var n=Object.getOwnPropertyNames(e).map(function(s){return e[s]});if(n.join("")!=="0123456789")return!1;var i={};return"abcdefghijklmnopqrst".split("").forEach(function(s){i[s]=s}),Object.keys(Object.assign({},i)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}dT.exports=O$()?Object.assign:function(r,e){for(var t,n=K$(r),i,s=1;s<arguments.length;s++){t=Object(arguments[s]);for(var a in t)T$.call(t,a)&&(n[a]=t[a]);if(uT){i=uT(t);for(var o=0;o<i.length;o++)A$.call(t,i[o])&&(n[i[o]]=t[i[o]])}}return n}});var mT=h((hde,fT)=>{(function(){"use strict";var r=pT(),e=xy(),t={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function n(m){return typeof m=="string"||m instanceof String}function i(m,y){if(Array.isArray(y)){for(var b=0;b<y.length;++b)if(i(m,y[b]))return!0;return!1}else return n(y)?m===y:y instanceof RegExp?y.test(m):!!y}function s(m,y){var b=y.headers.origin,g=[],E;return!m.origin||m.origin==="*"?g.push([{key:"Access-Control-Allow-Origin",value:"*"}]):n(m.origin)?(g.push([{key:"Access-Control-Allow-Origin",value:m.origin}]),g.push([{key:"Vary",value:"Origin"}])):(E=i(b,m.origin),g.push([{key:"Access-Control-Allow-Origin",value:E?b:!1}]),g.push([{key:"Vary",value:"Origin"}])),g}function a(m){var y=m.methods;return y.join&&(y=m.methods.join(",")),{key:"Access-Control-Allow-Methods",value:y}}function o(m){return m.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}function c(m,y){var b=m.allowedHeaders||m.headers,g=[];return b?b.join&&(b=b.join(",")):(b=y.headers["access-control-request-headers"],g.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),b&&b.length&&g.push([{key:"Access-Control-Allow-Headers",value:b}]),g}function l(m){var y=m.exposedHeaders;if(y)y.join&&(y=y.join(","));else return null;return y&&y.length?{key:"Access-Control-Expose-Headers",value:y}:null}function u(m){var y=(typeof m.maxAge=="number"||m.maxAge)&&m.maxAge.toString();return y&&y.length?{key:"Access-Control-Max-Age",value:y}:null}function d(m,y){for(var b=0,g=m.length;b<g;b++){var E=m[b];E&&(Array.isArray(E)?d(E,y):E.key==="Vary"&&E.value?e(y,E.value):E.value&&y.setHeader(E.key,E.value))}}function p(m,y,b,g){var E=[],I=y.method&&y.method.toUpperCase&&y.method.toUpperCase();I==="OPTIONS"?(E.push(s(m,y)),E.push(o(m)),E.push(a(m)),E.push(c(m,y)),E.push(u(m)),E.push(l(m)),d(E,b),m.preflightContinue?g():(b.statusCode=m.optionsSuccessStatus,b.setHeader("Content-Length","0"),b.end())):(E.push(s(m,y)),E.push(o(m)),E.push(l(m)),d(E,b),g())}function f(m){var y=null;return typeof m=="function"?y=m:y=function(b,g){g(null,m)},function(g,E,I){y(g,function(k,L){if(k)I(k);else{var J=r({},t,L),ne=null;J.origin&&typeof J.origin=="function"?ne=J.origin:J.origin&&(ne=function(Re,ae){ae(null,J.origin)}),ne?ne(g.headers.origin,function(Re,ae){Re||!ae?I(Re):(J.origin=ae,p(J,g,E,I))}):I()}})}}fT.exports=f})()});function jy(r,e={}){let t=[];e.includeCors!==!1&&t.push(Fl()),t.push(Ry.default.json({limit:"5mb"})),t.push((s,a,o)=>{let l=[".html",".js",".css",".svg",".png",".jpg",".jpeg",".webp",".woff",".woff2",".ttf",".eot"].some(y=>s.path.endsWith(y)),u=s.path==="/api/logs";if(s.path.startsWith("/health")||s.path==="/"||l||u)return o();let d=Date.now(),p=`${s.method}-${Date.now()}`,f=r(s.method,s.path,s.body);_.debug("HTTP",`\u2192 ${s.method} ${s.path}`,{requestId:p},f);let m=a.send.bind(a);a.send=function(y){let b=Date.now()-d;return _.debug("HTTP",`\u2190 ${a.statusCode} ${s.path}`,{requestId:p,duration:`${b}ms`}),m(y)},o()});let n=Pi(),i=yT.default.join(n,"plugin","ui");return t.push(Ry.default.static(i)),t}function Fl(){return(0,hT.default)({origin:(r,e)=>{!r||r.startsWith("http://localhost:")||r.startsWith("http://127.0.0.1:")?e(null,!0):e(new Error("CORS not allowed"))},methods:["GET","HEAD","POST","PUT","PATCH","DELETE"],allowedHeaders:["Content-Type","Authorization","X-Requested-With"],credentials:!1})}function ho(r,e,t){let n=r.ip||r.connection.remoteAddress||"";if(!(n==="127.0.0.1"||n==="::1"||n==="::ffff:127.0.0.1"||n==="localhost")){_.warn("SECURITY","Admin endpoint access denied - not localhost",{endpoint:r.path,clientIp:n,method:r.method}),e.status(403).json({error:"Forbidden",message:"Admin endpoints are only accessible from localhost"});return}t()}function Cy(r,e,t){if(!t||Object.keys(t).length===0||e.includes("/init"))return"";if(e.includes("/observations")){let n=t.tool_name||"?",i=t.tool_input;return`tool=${_.formatTool(n,i)}`}return e.includes("/summarize")?"requesting summary":""}var Ry,hT,yT,bT=D(()=>{"use strict";Ry=ct(Nl(),1),hT=ct(mT(),1),yT=ct(require("path"),1);Ur();me()});var gT=D(()=>{"use strict";bT()});function vT(r,e,t,n){let i={error:r,message:e};return t&&(i.code=t),n&&(i.details=n),i}function xT(r,e){e.status(404).json(vT("NotFound",`Cannot ${r.method} ${r.path}`))}var Ls,ET,ST=D(()=>{"use strict";me();Ls=class extends Error{constructor(t,n=500,i,s){super(t);this.statusCode=n;this.code=i;this.details=s;this.name="AppError"}statusCode;code;details};ET=(r,e,t,n)=>{let i=r instanceof Ls?r.statusCode:500;_.error("HTTP",`Error handling ${e.method} ${e.path}`,{statusCode:i,error:r.message,code:r instanceof Ls?r.code:void 0},r);let s=vT(r.name||"Error",r.message,r instanceof Ls?r.code:void 0,r instanceof Ls?r.details:void 0);t.status(i).json(s)}});var wT=D(()=>{"use strict"});function yo(r=process.env){let e={};for(let[t,n]of Object.entries(r))if(n!==void 0){if(j$.has(t)){e[t]=n;continue}Py.has(t)||R$.has(t)||Dy.some(i=>t.startsWith(i))||(e[t]=n)}return e}var Dy,Py,R$,j$,Jl=D(()=>{"use strict";Dy=["CLAUDECODE_","CLAUDE_CODE_"],Py=new Set(["CLAUDECODE","CLAUDE_CODE_SESSION","CLAUDE_CODE_ENTRYPOINT","MCP_SESSION_ID"]),R$=new Set(["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","http_proxy","https_proxy","all_proxy","no_proxy","npm_config_proxy","npm_config_https_proxy"]),j$=new Set(["CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_GIT_BASH_PATH","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX","ANTHROPIC_BEDROCK_BASE_URL","AWS_REGION","AWS_PROFILE","AWS_ACCESS_KEY_ID","AWS_SECRET_ACCESS_KEY","AWS_SESSION_TOKEN","ANTHROPIC_VERTEX_PROJECT_ID","CLOUD_ML_REGION","GOOGLE_APPLICATION_CREDENTIALS"])});function or(r){if(!Number.isInteger(r)||r<0||r===0)return!1;try{return process.kill(r,0),!0}catch(e){if(e instanceof Error){let t=e.code;return t==="EPERM"?!0:(_.debug("SYSTEM","PID check failed",{pid:r,code:t}),!1)}return _.warn("SYSTEM","PID check threw non-Error",{pid:r,error:String(e)}),!1}}function L$(r){let e=IT.get(r);if(e&&Date.now()-e.capturedAtMs<M$)return e.token;let t=null;try{let n=(0,Fy.spawnSync)("powershell.exe",["-NoProfile","-NonInteractive","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${r}").CreationDate.ToString('yyyyMMddHHmmss.ffffff')`],{encoding:"utf-8",timeout:5e3,windowsHide:!0,env:{...yo(process.env),LC_ALL:"C",LANG:"C"}});if(n.status===0){let i=n.stdout.trim();t=i.length>0?i:null}}catch(n){_.debug("SYSTEM","captureProcessStartToken: powershell CIM lookup failed",{pid:r,error:n instanceof Error?n.message:String(n)}),t=null}return IT.set(r,{token:t,capturedAtMs:Date.now()}),t}function Jy(r){if(!Number.isInteger(r)||r<=0)return null;if(process.platform==="linux")try{let e=(0,Gr.readFileSync)(`/proc/${r}/stat`,"utf-8"),t=e.lastIndexOf(") ");if(t<0)return null;let i=e.slice(t+2).split(" ")[19];return i&&/^\d+$/.test(i)?i:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: /proc read failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}if(process.platform==="win32")return L$(r);try{let e=(0,Fy.spawnSync)("ps",["-p",String(r),"-o","lstart="],{encoding:"utf-8",timeout:2e3,env:{...yo(process.env),LC_ALL:"C",LANG:"C"}});if(e.status!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}catch(e){return _.debug("SYSTEM","captureProcessStartToken: ps exec failed",{pid:r,error:e instanceof Error?e.message:String(e)}),null}}function Fn(r){if(!r||!or(r.pid))return!1;if(!r.startToken)return!0;let e=Jy(r.pid);if(e===null)return!0;let t=e===r.startToken;return t||_.debug("SYSTEM","verifyPidFileOwnership: start-token mismatch (PID reused)",{pid:r.pid,stored:r.startToken,current:e}),t}function Ul(){return My||(My=new qy),My}function Ly(){let r=N$.shift();r&&r()}var Fy,Gr,Ny,C$,D$,P$,M$,IT,qy,My,N$,Ns=D(()=>{"use strict";Fy=require("child_process");wT();Gr=require("fs"),Ny=ct(require("path"),1);me();Jl();Ur();C$=5e3,D$=1e3,P$=$e.supervisorRegistry();M$=5e3,IT=new Map;qy=class{registryPath;entries=new Map;runtimeProcesses=new Map;initialized=!1;constructor(e=P$){this.registryPath=e}initialize(){if(this.initialized)return;if(this.initialized=!0,(0,Gr.mkdirSync)(Ny.default.dirname(this.registryPath),{recursive:!0}),!(0,Gr.existsSync)(this.registryPath)){this.persist();return}try{let n=JSON.parse((0,Gr.readFileSync)(this.registryPath,"utf-8")).processes??{};for(let[i,s]of Object.entries(n))this.entries.set(i,s)}catch(t){t instanceof Error?_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath},t):_.warn("SYSTEM","Failed to parse supervisor registry, rebuilding",{path:this.registryPath,error:String(t)}),this.entries.clear()}let e=this.pruneDeadEntries();e>0&&_.info("SYSTEM","Removed dead processes from supervisor registry",{removed:e}),this.persist()}register(e,t,n){this.initialize(),this.entries.set(e,t),n&&this.runtimeProcesses.set(e,n),this.persist()}unregister(e){this.initialize();let t=this.entries.get(e);this.entries.delete(e),this.runtimeProcesses.delete(e),this.persist(),t?.type==="sdk"&&Ly()}clear(){this.entries.clear(),this.runtimeProcesses.clear(),this.persist()}getAll(){return this.initialize(),Array.from(this.entries.entries()).map(([e,t])=>({id:e,...t})).sort((e,t)=>{let n=Date.parse(e.startedAt),i=Date.parse(t.startedAt);return(Number.isNaN(n)?0:n)-(Number.isNaN(i)?0:i)})}getBySession(e){let t=String(e);return this.getAll().filter(n=>n.sessionId!==void 0&&String(n.sessionId)===t)}getRuntimeProcess(e){return this.runtimeProcesses.get(e)}getByPid(e){return this.getAll().filter(t=>t.pid===e)}pruneDeadEntries(){this.initialize();let e=0,t=0;for(let[n,i]of this.entries)or(i.pid)||(this.entries.delete(n),this.runtimeProcesses.delete(n),e+=1,i.type==="sdk"&&(t+=1));e>0&&this.persist();for(let n=0;n<t;n+=1)Ly();return e}async reapSession(e){this.initialize();let t=this.getBySession(e);if(t.length===0)return 0;let n=typeof e=="number"?e:Number(e)||void 0;_.info("SYSTEM",`Reaping ${t.length} process(es) for session ${e}`,{sessionId:n,pids:t.map(o=>o.pid)});let i=t.filter(o=>or(o.pid));for(let o of i)try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGTERM"):process.kill(o.pid,"SIGTERM")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGTERM session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGTERM session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}let s=Date.now()+C$;for(;Date.now()<s&&i.filter(c=>or(c.pid)).length!==0;)await new Promise(c=>setTimeout(c,100));let a=i.filter(o=>or(o.pid));for(let o of a){_.warn("SYSTEM",`Session process PID ${o.pid} did not exit after SIGTERM, sending SIGKILL`,{pid:o.pid,pgid:o.pgid,sessionId:n});try{typeof o.pgid=="number"&&process.platform!=="win32"?process.kill(-o.pgid,"SIGKILL"):process.kill(o.pid,"SIGKILL")}catch(c){c instanceof Error?c.code!=="ESRCH"&&_.debug("SYSTEM",`Failed to SIGKILL session process PID ${o.pid}`,{pid:o.pid,pgid:o.pgid},c):_.warn("SYSTEM",`Failed to SIGKILL session process PID ${o.pid} (non-Error)`,{pid:o.pid,pgid:o.pgid,error:String(c)})}}if(a.length>0){let o=Date.now()+D$;for(;Date.now()<o&&a.filter(l=>or(l.pid)).length!==0;)await new Promise(l=>setTimeout(l,100))}for(let o of t)this.entries.delete(o.id),this.runtimeProcesses.delete(o.id);this.persist();for(let o of t)o.type==="sdk"&&Ly();return _.info("SYSTEM",`Reaped ${t.length} process(es) for session ${e}`,{sessionId:n,reaped:t.length}),t.length}persist(){let e={processes:Object.fromEntries(this.entries.entries())};(0,Gr.mkdirSync)(Ny.default.dirname(this.registryPath),{recursive:!0}),(0,Gr.writeFileSync)(this.registryPath,JSON.stringify(e,null,2))}},My=null;N$=[]});var _T,kT=D(()=>{"use strict";_T={DEFAULT:3e5,HEALTH_CHECK:3e3,API_REQUEST:3e4,HOOK_READINESS_WAIT:1e4,POST_SPAWN_WAIT:15e3,READINESS_WAIT:3e4,PORT_IN_USE_WAIT:3e3,WORKER_STARTUP_WAIT:1e3,PRE_RESTART_SETTLE_DELAY:2e3,POWERSHELL_COMMAND:1e4,WINDOWS_MULTIPLIER:1.5}});async function jT(r){let e=r.currentPid??process.pid,t=r.pidFilePath??F$,n=r.registry.getAll(),i=[...n].filter(a=>a.pid!==e).sort((a,o)=>Date.parse(o.startedAt)-Date.parse(a.startedAt));for(let a of i){if(!or(a.pid)){r.registry.unregister(a.id);continue}try{await AT(a,"SIGTERM")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to send SIGTERM to child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to send SIGTERM to child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}}await TT(i,5e3);let s=i.filter(a=>or(a.pid));for(let a of s)try{await AT(a,"SIGKILL")}catch(o){o instanceof Error?_.debug("SYSTEM","Failed to force kill child process",{pid:a.pid,pgid:a.pgid,type:a.type},o):_.warn("SYSTEM","Failed to force kill child process (non-Error)",{pid:a.pid,pgid:a.pgid,type:a.type,error:String(o)})}await TT(s,1e3);for(let a of i)r.registry.unregister(a.id);for(let a of n.filter(o=>o.pid===e))r.registry.unregister(a.id);try{(0,OT.rmSync)(t,{force:!0})}catch(a){a instanceof Error?_.debug("SYSTEM","Failed to remove PID file during shutdown",{pidFilePath:t},a):_.warn("SYSTEM","Failed to remove PID file during shutdown (non-Error)",{pidFilePath:t,error:String(a)})}r.registry.pruneDeadEntries()}async function TT(r,e){let t=Date.now()+e;for(;Date.now()<t;){if(r.filter(i=>or(i.pid)).length===0)return;await new Promise(i=>setTimeout(i,100))}}async function AT(r,e){let{pid:t,pgid:n}=r;if(process.platform!=="win32"){if(typeof n=="number")try{process.kill(-n,e);return}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}try{process.kill(t,e)}catch(a){if((a instanceof Error?a.code:void 0)!=="ESRCH")throw a}return}if(e==="SIGTERM"){try{process.kill(t,e)}catch(a){if(a instanceof Error&&a.code==="ESRCH")return;throw a}return}let i=await J$();if(i){await new Promise((a,o)=>{i(t,e,c=>{if(!c){a();return}if(c.code==="ESRCH"){a();return}o(c)})});return}let s=["/PID",String(t),"/T"];e==="SIGKILL"&&s.push("/F"),await q$("taskkill",s,{timeout:_T.POWERSHELL_COMMAND,windowsHide:!0})}async function J$(){let r="tree-kill";try{let e=await import(r);return e.default??e}catch(e){return _.debug("SYSTEM","tree-kill module not available, using fallback",{},e instanceof Error?e:void 0),null}}var KT,OT,RT,q$,F$,CT=D(()=>{"use strict";KT=require("child_process"),OT=require("fs"),RT=require("util");me();kT();Ns();Ur();q$=(0,RT.promisify)(KT.execFile),F$=$e.workerPid()});function U$(){let e=Ul().pruneDeadEntries();e>0&&_.info("SYSTEM",`Health check: pruned ${e} dead process(es) from registry`)}function PT(){qs===null&&(qs=setInterval(U$,DT),qs.unref(),_.debug("SYSTEM","Health checker started",{intervalMs:DT}))}function MT(){qs!==null&&(clearInterval(qs),qs=null,_.debug("SYSTEM","Health checker stopped"))}var DT,qs,LT=D(()=>{"use strict";me();Ns();DT=3e4,qs=null});function NT(){return B$}function $$(r={}){let e=r.pidFilePath??G$;if(!(0,Mi.existsSync)(e))return"missing";let t=null;try{t=JSON.parse((0,Mi.readFileSync)(e,"utf-8"))}catch(i){return i instanceof Error?_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e},i):_.warn("SYSTEM","Failed to parse worker PID file, removing it",{path:e,error:String(i)}),(0,Mi.rmSync)(e,{force:!0}),"invalid"}return Fn(t)&&t?((r.logAlive??!0)&&_.info("SYSTEM","Worker already running (PID alive)",{existingPid:t.pid,existingPort:t.port,startedAt:t.startedAt}),"alive"):(_.info("SYSTEM","Removing stale PID file (worker process is dead or PID has been reused)",{pid:t?.pid,port:t?.port,startedAt:t?.startedAt}),(0,Mi.rmSync)(e,{force:!0}),"stale")}var Mi,G$,Uy,B$,qT=D(()=>{"use strict";Mi=require("fs");me();Ns();CT();LT();Ur();G$=$e.workerPid(),Uy=class{registry;started=!1;stopPromise=null;signalHandlersRegistered=!1;shutdownInitiated=!1;shutdownHandler=null;constructor(e){this.registry=e}async start(){if(this.started)return;if(this.registry.initialize(),$$({logAlive:!1})==="alive")throw new Error("Worker already running");this.started=!0,PT()}configureSignalHandlers(e){if(this.shutdownHandler=e,this.signalHandlersRegistered)return;this.signalHandlersRegistered=!0;let t=async n=>{if(this.shutdownInitiated){_.warn("SYSTEM",`Received ${n} but shutdown already in progress`);return}this.shutdownInitiated=!0,_.info("SYSTEM",`Received ${n}, shutting down...`);try{this.shutdownHandler?await this.shutdownHandler():await this.stop()}catch(i){i instanceof Error?_.error("SYSTEM","Error during shutdown",{},i):_.error("SYSTEM","Error during shutdown (non-Error)",{error:String(i)});try{await this.stop()}catch(s){s instanceof Error?_.debug("SYSTEM","Supervisor shutdown fallback failed",{},s):_.debug("SYSTEM","Supervisor shutdown fallback failed",{error:String(s)})}}process.exit(0)};process.on("SIGTERM",()=>{t("SIGTERM")}),process.on("SIGINT",()=>{t("SIGINT")}),process.platform!=="win32"&&(process.argv.includes("--daemon")?process.on("SIGHUP",()=>{_.debug("SYSTEM","Ignoring SIGHUP in daemon mode")}):process.on("SIGHUP",()=>{t("SIGHUP")}))}async stop(){if(this.stopPromise){await this.stopPromise;return}MT(),this.stopPromise=jT({registry:this.registry,currentPid:process.pid}).finally(()=>{this.started=!1,this.stopPromise=null}),await this.stopPromise}assertCanSpawn(e){if(this.stopPromise!==null)throw new Error(`Supervisor is shutting down, refusing to spawn ${e}`)}registerProcess(e,t,n){this.registry.register(e,t,n)}unregisterProcess(e){this.registry.unregister(e)}getRegistry(){return this.registry}},B$=new Uy(Ul())});function Gy(r,e,t){r.on("finish",async()=>{try{await t()}finally{process.exit(0)}}),r.json(e)}var FT=D(()=>{"use strict"});function By(r,e=Date.now){return Math.max(0,Math.floor((e()-r)/1e3))}var JT=D(()=>{"use strict"});var $y,UT,Zde,GT=D(()=>{"use strict";$y=class{entries=new Map;set(e){if(!e||typeof e!="object")return;let t=e.rateLimitType??"default";this.entries.set(t,{...e,observedAt:Date.now()})}get(e){return e?this.entries.get(e):this.entries.get("default")}getAll(){return Array.from(this.entries.values()).sort((e,t)=>t.observedAt-e.observedAt)}getMostRecentByWindow(){return{five_hour:this.entries.get("five_hour"),seven_day:this.entries.get("seven_day"),seven_day_opus:this.entries.get("seven_day_opus"),seven_day_sonnet:this.entries.get("seven_day_sonnet"),overage:this.entries.get("overage")}}get size(){return this.entries.size}clear(){this.entries.clear()}},UT=new $y,Zde=900*1e3});function z$(r){r.setHeader("X-Content-Type-Options","nosniff"),r.setHeader("X-Frame-Options","DENY"),r.setHeader("X-DNS-Prefetch-Control","off"),r.setHeader("Referrer-Policy","no-referrer"),r.setHeader("Cross-Origin-Opener-Policy","same-origin"),r.setHeader("Cross-Origin-Resource-Policy","same-origin"),r.setHeader("Origin-Agent-Cluster","?1"),r.removeHeader("X-Powered-By")}var VT,HT,Hy,bo,zT,V$,Vy,BT,H$,$T,Gl,YT=D(()=>{"use strict";VT=ct(Nl(),1),HT=ct(require("http"),1),Hy=ct(require("fs"),1),bo=ct(require("path"),1);sT();me();gT();ST();qT();Ns();Jl();FT();JT();GT();zT=bo.default.resolve(__dirname,"../skills/mem-search"),V$=bo.default.join(zT,"operations"),Vy=bo.default.join(zT,"SKILL.md"),BT=(()=>{try{let r=Hy.readFileSync(Vy,"utf-8");return _.info("SYSTEM","Cached SKILL.md at boot",{path:Vy,bytes:Buffer.byteLength(r,"utf-8")}),r}catch(r){return _.debug("SYSTEM","SKILL.md not present at boot, /api/instructions will 404 for topic queries",{path:Vy,message:r instanceof Error?r.message:String(r)}),null}})(),H$=(()=>{let r=new Map;for(let e of _y){let t=bo.default.join(V$,`${e}.md`);try{r.set(e,Hy.readFileSync(t,"utf-8"))}catch(n){_.debug("SYSTEM","Operation instruction file not present at boot",{path:t,message:n instanceof Error?n.message:String(n)})}}return r.size>0&&_.info("SYSTEM","Cached operation instruction files at boot",{count:r.size,operations:Array.from(r.keys())}),r})(),$T="13.4.9";Gl=class{app;server=null;options;startTime=Date.now();constructor(e){this.options=e,this.app=(0,VT.default)(),this.app.disable("x-powered-by"),this.setupSecurityHeaders(),this.setupCors(),this.setupPreBodyParserRoutes(),this.setupMiddleware(),this.setupCoreRoutes()}getHttpServer(){return this.server}async listen(e,t){return new Promise((n,i)=>{let s=HT.default.createServer(this.app);this.server=s;let a=c=>{s.off("listening",o),i(c)},o=()=>{s.off("error",a),_.info("SYSTEM","HTTP server started",{host:t,port:e,pid:process.pid}),n()};s.once("error",a),s.once("listening",o),s.listen(e,t)})}async close(){this.server&&(this.server.closeAllConnections(),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),await new Promise((e,t)=>{this.server.close(n=>n?t(n):e())}),process.platform==="win32"&&await new Promise(e=>setTimeout(e,500)),this.server=null,_.info("SYSTEM","HTTP server closed"))}registerRoutes(e){e.setupRoutes(this.app)}finalizeRoutes(){this.app.use(xT),this.app.use(ET)}setupMiddleware(){jy(Cy,{includeCors:!1}).forEach(t=>this.app.use(t))}setupSecurityHeaders(){this.options.securityHeaders&&this.app.use((e,t,n)=>{z$(t),n()})}setupCors(){this.app.use(Fl())}setupPreBodyParserRoutes(){this.options.preBodyParserRoutes?.forEach(e=>e.setupRoutes(this.app))}setupCoreRoutes(){this.app.get("/api/health",async(e,t)=>{let n=this.options.getQueueHealth?await this.options.getQueueHealth():null,i=n?.engine==="bullmq"&&n.redis.status==="error";t.status(i?503:200).json({status:i?"degraded":"ok",...this.options.runtime?{runtime:this.options.runtime}:{},version:$T,workerPath:this.options.workerPath,uptime:By(this.startTime),managed:process.env.CLAUDE_MEM_MANAGED==="true",hasIpc:typeof process.send=="function",platform:process.platform,pid:process.pid,initialized:this.options.getInitializationComplete(),mcpReady:this.options.getMcpReady(),ai:this.options.getAiStatus(),rateLimits:UT.getMostRecentByWindow(),...n?{queue:n}:{}})}),this.app.get("/api/readiness",(e,t)=>{this.options.getInitializationComplete()?t.status(200).json({status:"ready",mcpReady:this.options.getMcpReady()}):t.status(503).json({status:"initializing",message:"Worker is still initializing, please retry"})}),this.app.get("/api/version",(e,t)=>{t.status(200).json({version:$T})}),this.app.get("/api/instructions",(e,t)=>{let n=e.query.topic||"all",i=e.query.operation;if(n&&!iT.includes(n))return t.status(400).json({error:"Invalid topic"});if(i&&!_y.includes(i))return t.status(400).json({error:"Invalid operation"});if(i){let a=H$.get(i);return a===void 0?(_.debug("HTTP","Instruction file not cached at boot",{operation:i}),t.status(404).json({error:"Instruction not found"})):t.json({content:[{type:"text",text:a}]})}if(BT===null)return _.debug("HTTP","SKILL.md not cached at boot",{topic:n}),t.status(404).json({error:"Instruction not found"});let s=this.extractInstructionSection(BT,n);t.json({content:[{type:"text",text:s}]})}),this.app.post("/api/admin/restart",ho,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"restarting"}),_.info("SYSTEM","Sending restart request to wrapper"),process.send({type:"restart"})):Gy(t,{status:"restarting"},()=>this.options.onRestart())}),this.app.post("/api/admin/shutdown",ho,async(e,t)=>{process.platform==="win32"&&process.env.CLAUDE_MEM_MANAGED==="true"&&process.send?(t.json({status:"shutting_down"}),_.info("SYSTEM","Sending shutdown request to wrapper"),process.send({type:"shutdown"})):Gy(t,{status:"shutting_down"},()=>this.options.onShutdown())}),this.app.get("/api/admin/doctor",ho,(e,t)=>{let a=NT().getRegistry().getAll().map(f=>({id:f.id,pid:f.pid,type:f.type,status:or(f.pid)?"alive":"dead",startedAt:f.startedAt})),o=a.filter(f=>f.status==="dead").map(f=>f.pid),c=!Object.keys(process.env).some(f=>Py.has(f)||Dy.some(m=>f.startsWith(m))),l=By(this.startTime),u=Math.floor(l/3600),d=Math.floor(l%3600/60),p=u>0?`${u}h ${d}m`:`${d}m`;t.json({supervisor:{running:!0,pid:process.pid,uptime:p},processes:a,health:{deadProcessPids:o,envClean:c}})})}extractInstructionSection(e,t){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[t]||n.all}extractBetween(e,t,n){let i=e.indexOf(t),s=e.indexOf(n);return i===-1?e:s===-1?e.substring(i):e.substring(i,s).trim()}}});var Dt,Y$,W$,zy,WT=D(()=>{"use strict";Dt=require("zod"),Y$=Dt.z.enum(["hook","worker","provider","server","api"]),W$=Dt.z.object({id:Dt.z.string().min(1),projectId:Dt.z.string().min(1),serverSessionId:Dt.z.string().min(1).nullable().default(null),sourceType:Y$,eventType:Dt.z.string().min(1),platformSource:Dt.z.string().min(1).nullable().default(null),sourceEventId:Dt.z.string().min(1).nullable().default(null),payload:Dt.z.unknown().default({}),contentSessionId:Dt.z.string().min(1).nullable().default(null),memorySessionId:Dt.z.string().min(1).nullable().default(null),occurredAtEpoch:Dt.z.number().int().nonnegative(),createdAtEpoch:Dt.z.number().int().nonnegative()}),zy=W$.omit({id:!0,createdAtEpoch:!0}).partial({serverSessionId:!0,platformSource:!0,sourceEventId:!0,payload:!0,contentSessionId:!0,memorySessionId:!0})});function qe(){return(0,Bl.randomUUID)()}function ze(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}function QT(r){return Array.isArray(r)?r:[]}function ve(r){return typeof r=="number"?r:new Date(r).getTime()}function cr(r){return r==null?null:r instanceof Date?r:new Date(r)}async function W(r,e,t=[]){return(await r.query(e,t)).rows[0]??null}async function _r(r,e,t){if(!await W(r,"SELECT id FROM projects WHERE id = $1 AND team_id = $2",[e,t]))throw new Error("project_id must belong to team_id")}async function mn(r,e,t,n){if(!await W(r,"SELECT id FROM server_sessions WHERE id = $1 AND project_id = $2 AND team_id = $3",[e,t,n]))throw new Error("server_session_id must belong to project_id and team_id")}function go(r){return JSON.stringify(Yy(r))}function kr(r){return(0,Bl.createHash)("sha256").update(go(r)).digest("hex")}function Yy(r){if(Array.isArray(r))return r.map(Yy);if(r&&typeof r=="object"){let e=r;return Object.keys(e).sort().reduce((t,n)=>(t[n]=Yy(e[n]),t),{})}return r}var Bl,Br=D(()=>{"use strict";Bl=require("crypto")});function XT(r){return r.sourceEventId?`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.sourceEventId])}`:`agent_event:v1:${kr([r.teamId,r.projectId,r.sourceAdapter,r.serverSessionId??null,r.eventType,new Date(r.occurredAt).toISOString(),go(r.payload??{})])}`}function Wy(r){return{id:r.id,projectId:r.project_id,teamId:r.team_id,serverSessionId:r.server_session_id,sourceAdapter:r.source_adapter,sourceEventId:r.source_event_id,idempotencyKey:r.idempotency_key,eventType:r.event_type,platformSource:r.platform_source,payload:r.payload,metadata:ze(r.metadata),occurredAtEpoch:ve(r.occurred_at),receivedAtEpoch:ve(r.received_at),createdAtEpoch:ve(r.created_at)}}var lr,Fs=D(()=>{"use strict";Br();lr=class{constructor(e){this.client=e}client;async create(e){await _r(this.client,e.projectId,e.teamId),e.serverSessionId&&await mn(this.client,e.serverSessionId,e.projectId,e.teamId);let t=XT(e),n=await W(this.client,`
63
63
  INSERT INTO agent_events (
64
64
  id, project_id, team_id, server_session_id, source_adapter,
65
65
  source_event_id, idempotency_key, event_type, platform_source, payload, metadata, occurred_at