claude-mem 12.6.1 → 12.6.3

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,7 @@
1
+ /**
2
+ * Claude-Mem - TypeScript Declarations
3
+ *
4
+ * Re-exports SDK utilities for convenience.
5
+ */
6
+
7
+ export * from './sdk/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Claude-Mem - Main Package Entry Point
3
+ *
4
+ * This re-exports the SDK utilities for convenience.
5
+ * For full SDK access, use: import { ... } from 'claude-mem/sdk'
6
+ */
7
+
8
+ export * from './sdk/index.js';
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Claude-Mem SDK - TypeScript Declarations
3
+ *
4
+ * Standalone module for external consumers to parse claude-mem observation XML
5
+ * and build prompts for the memory worker.
6
+ */
7
+
8
+ export interface ParsedObservation {
9
+ type: string;
10
+ title: string | null;
11
+ subtitle: string | null;
12
+ facts: string[];
13
+ narrative: string | null;
14
+ concepts: string[];
15
+ files_read: string[];
16
+ files_modified: string[];
17
+ }
18
+
19
+ export interface ParsedSummary {
20
+ request: string | null;
21
+ investigated: string | null;
22
+ learned: string | null;
23
+ completed: string | null;
24
+ next_steps: string | null;
25
+ notes: string | null;
26
+ }
27
+
28
+ export interface Observation {
29
+ id: number;
30
+ tool_name: string;
31
+ tool_input: string;
32
+ tool_output: string;
33
+ created_at_epoch: number;
34
+ cwd?: string;
35
+ }
36
+
37
+ export interface ParseObservationsOptions {
38
+ /** Array of valid observation types. If provided, validates types against this list. */
39
+ validTypes?: string[];
40
+ /** Type to use if type is missing or invalid. Defaults to 'observation'. */
41
+ fallbackType?: string;
42
+ }
43
+
44
+ /**
45
+ * Parse observation XML blocks from text
46
+ * Returns all observations found in the text
47
+ *
48
+ * @param text - The text containing observation XML blocks
49
+ * @param options - Optional configuration for type validation
50
+ * @returns Array of parsed observations
51
+ *
52
+ * @example
53
+ * ```typescript
54
+ * const text = `<observation>
55
+ * <type>code_change</type>
56
+ * <title>Added login feature</title>
57
+ * <facts><fact>New auth module</fact></facts>
58
+ * </observation>`;
59
+ *
60
+ * const observations = parseObservations(text);
61
+ * // => [{ type: 'code_change', title: 'Added login feature', ... }]
62
+ * ```
63
+ */
64
+ export function parseObservations(
65
+ text: string,
66
+ options?: ParseObservationsOptions
67
+ ): ParsedObservation[];
68
+
69
+ /**
70
+ * Parse summary XML block from text
71
+ * Returns null if no valid summary found or if summary was skipped
72
+ *
73
+ * @param text - The text containing summary XML block
74
+ * @returns Parsed summary or null
75
+ *
76
+ * @example
77
+ * ```typescript
78
+ * const text = `<summary>
79
+ * <request>Implement auth</request>
80
+ * <completed>Added JWT tokens</completed>
81
+ * </summary>`;
82
+ *
83
+ * const summary = parseSummary(text);
84
+ * // => { request: 'Implement auth', completed: 'Added JWT tokens', ... }
85
+ * ```
86
+ */
87
+ export function parseSummary(text: string): ParsedSummary | null;
88
+
89
+ /**
90
+ * Build prompt to send tool observation to SDK agent
91
+ *
92
+ * @param obs - The observation object containing tool data
93
+ * @returns Formatted XML prompt string
94
+ *
95
+ * @example
96
+ * ```typescript
97
+ * const obs = {
98
+ * id: 1,
99
+ * tool_name: 'Read',
100
+ * tool_input: '{"file_path": "/src/index.ts"}',
101
+ * tool_output: '{"content": "..."}',
102
+ * created_at_epoch: Date.now()
103
+ * };
104
+ *
105
+ * const prompt = buildObservationPrompt(obs);
106
+ * // => '<observed_from_primary_session>...'
107
+ * ```
108
+ */
109
+ export function buildObservationPrompt(obs: Observation): string;
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Claude-Mem SDK - Standalone module for external consumers
3
+ *
4
+ * This is a self-contained module that exports parsing and prompt utilities
5
+ * without internal dependencies on the main claude-mem codebase.
6
+ *
7
+ * Usage:
8
+ * import { parseObservations, buildObservationPrompt } from 'claude-mem/sdk';
9
+ */
10
+
11
+ // ============================================================================
12
+ // Parser Functions
13
+ // ============================================================================
14
+
15
+ /**
16
+ * Parse observation XML blocks from text
17
+ * Returns all observations found in the text
18
+ *
19
+ * @param {string} text - The text containing observation XML blocks
20
+ * @param {Object} [options] - Optional configuration
21
+ * @param {string[]} [options.validTypes] - Array of valid observation types. If provided, validates types.
22
+ * @param {string} [options.fallbackType='observation'] - Type to use if type is missing or invalid
23
+ * @returns {ParsedObservation[]} Array of parsed observations
24
+ */
25
+ export function parseObservations(text, options = {}) {
26
+ const observations = [];
27
+ const { validTypes, fallbackType = 'observation' } = options;
28
+
29
+ // Match <observation>...</observation> blocks (non-greedy)
30
+ const observationRegex = /<observation>([\s\S]*?)<\/observation>/g;
31
+
32
+ let match;
33
+ while ((match = observationRegex.exec(text)) !== null) {
34
+ const obsContent = match[1];
35
+
36
+ // Extract all fields
37
+ const type = extractField(obsContent, 'type');
38
+ const title = extractField(obsContent, 'title');
39
+ const subtitle = extractField(obsContent, 'subtitle');
40
+ const narrative = extractField(obsContent, 'narrative');
41
+ const facts = extractArrayElements(obsContent, 'facts', 'fact');
42
+ const concepts = extractArrayElements(obsContent, 'concepts', 'concept');
43
+ const files_read = extractArrayElements(obsContent, 'files_read', 'file');
44
+ const files_modified = extractArrayElements(obsContent, 'files_modified', 'file');
45
+
46
+ // Determine final type
47
+ let finalType = fallbackType;
48
+ if (type) {
49
+ const trimmedType = type.trim();
50
+ if (validTypes) {
51
+ finalType = validTypes.includes(trimmedType) ? trimmedType : fallbackType;
52
+ } else {
53
+ finalType = trimmedType;
54
+ }
55
+ }
56
+
57
+ // Filter out type from concepts array (types and concepts are separate dimensions)
58
+ const cleanedConcepts = concepts.filter(c => c !== finalType);
59
+
60
+ observations.push({
61
+ type: finalType,
62
+ title,
63
+ subtitle,
64
+ facts,
65
+ narrative,
66
+ concepts: cleanedConcepts,
67
+ files_read,
68
+ files_modified
69
+ });
70
+ }
71
+
72
+ return observations;
73
+ }
74
+
75
+ /**
76
+ * Parse summary XML block from text
77
+ * Returns null if no valid summary found or if summary was skipped
78
+ *
79
+ * @param {string} text - The text containing summary XML block
80
+ * @returns {ParsedSummary|null} Parsed summary or null
81
+ */
82
+ export function parseSummary(text) {
83
+ // Check for skip_summary first
84
+ const skipRegex = /<skip_summary\s+reason="([^"]+)"\s*\/>/;
85
+ const skipMatch = skipRegex.exec(text);
86
+
87
+ if (skipMatch) {
88
+ return null;
89
+ }
90
+
91
+ // Match <summary>...</summary> block (non-greedy)
92
+ const summaryRegex = /<summary>([\s\S]*?)<\/summary>/;
93
+ const summaryMatch = summaryRegex.exec(text);
94
+
95
+ if (!summaryMatch) {
96
+ return null;
97
+ }
98
+
99
+ const summaryContent = summaryMatch[1];
100
+
101
+ return {
102
+ request: extractField(summaryContent, 'request'),
103
+ investigated: extractField(summaryContent, 'investigated'),
104
+ learned: extractField(summaryContent, 'learned'),
105
+ completed: extractField(summaryContent, 'completed'),
106
+ next_steps: extractField(summaryContent, 'next_steps'),
107
+ notes: extractField(summaryContent, 'notes')
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Extract a simple field value from XML content
113
+ * Returns null for missing or empty/whitespace-only fields
114
+ */
115
+ function extractField(content, fieldName) {
116
+ const regex = new RegExp(`<${fieldName}>([^<]*)</${fieldName}>`);
117
+ const match = regex.exec(content);
118
+ if (!match) return null;
119
+
120
+ const trimmed = match[1].trim();
121
+ return trimmed === '' ? null : trimmed;
122
+ }
123
+
124
+ /**
125
+ * Extract array of elements from XML content
126
+ */
127
+ function extractArrayElements(content, arrayName, elementName) {
128
+ const elements = [];
129
+
130
+ // Match the array block
131
+ const arrayRegex = new RegExp(`<${arrayName}>(.*?)</${arrayName}>`, 's');
132
+ const arrayMatch = arrayRegex.exec(content);
133
+
134
+ if (!arrayMatch) {
135
+ return elements;
136
+ }
137
+
138
+ const arrayContent = arrayMatch[1];
139
+
140
+ // Extract individual elements
141
+ const elementRegex = new RegExp(`<${elementName}>([^<]+)</${elementName}>`, 'g');
142
+ let elementMatch;
143
+ while ((elementMatch = elementRegex.exec(arrayContent)) !== null) {
144
+ elements.push(elementMatch[1].trim());
145
+ }
146
+
147
+ return elements;
148
+ }
149
+
150
+ // ============================================================================
151
+ // Prompt Building Functions
152
+ // ============================================================================
153
+
154
+ /**
155
+ * Build prompt to send tool observation to SDK agent
156
+ *
157
+ * @param {Observation} obs - The observation object containing tool data
158
+ * @returns {string} Formatted XML prompt string
159
+ */
160
+ export function buildObservationPrompt(obs) {
161
+ // Safely parse tool_input and tool_output - they may be JSON strings
162
+ let toolInput;
163
+ let toolOutput;
164
+
165
+ try {
166
+ toolInput = typeof obs.tool_input === 'string' ? JSON.parse(obs.tool_input) : obs.tool_input;
167
+ } catch {
168
+ toolInput = obs.tool_input;
169
+ }
170
+
171
+ try {
172
+ toolOutput = typeof obs.tool_output === 'string' ? JSON.parse(obs.tool_output) : obs.tool_output;
173
+ } catch {
174
+ toolOutput = obs.tool_output;
175
+ }
176
+
177
+ return `<observed_from_primary_session>
178
+ <what_happened>${obs.tool_name}</what_happened>
179
+ <occurred_at>${new Date(obs.created_at_epoch).toISOString()}</occurred_at>${obs.cwd ? `\n <working_directory>${obs.cwd}</working_directory>` : ''}
180
+ <parameters>${JSON.stringify(toolInput, null, 2)}</parameters>
181
+ <outcome>${JSON.stringify(toolOutput, null, 2)}</outcome>
182
+ </observed_from_primary_session>`;
183
+ }
@@ -3,7 +3,7 @@
3
3
  "name": "Claude-Mem (Persistent Memory)",
4
4
  "description": "Official OpenClaw plugin for Claude-Mem. Records observations from embedded runner sessions and streams them to messaging channels.",
5
5
  "kind": "memory",
6
- "version": "12.6.1",
6
+ "version": "12.6.2",
7
7
  "author": "thedotmack",
8
8
  "homepage": "https://claude-mem.com",
9
9
  "skills": ["skills/make-plan", "skills/do"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "12.6.1",
3
+ "version": "12.6.3",
4
4
  "description": "Memory compression system for Claude Code - persist context across sessions",
5
5
  "keywords": [
6
6
  "claude",
@@ -118,13 +118,7 @@
118
118
  "dependencies": {
119
119
  "@anthropic-ai/claude-agent-sdk": "^0.2.119",
120
120
  "@clack/prompts": "^1.2.0",
121
- "@derekstride/tree-sitter-sql": "^0.3.11",
122
121
  "@modelcontextprotocol/sdk": "^1.29.0",
123
- "@tree-sitter-grammars/tree-sitter-lua": "^0.4.1",
124
- "@tree-sitter-grammars/tree-sitter-markdown": "^0.3.2",
125
- "@tree-sitter-grammars/tree-sitter-toml": "^0.7.0",
126
- "@tree-sitter-grammars/tree-sitter-yaml": "^0.7.1",
127
- "@tree-sitter-grammars/tree-sitter-zig": "^1.1.2",
128
122
  "ansi-to-html": "^0.7.2",
129
123
  "dompurify": "^3.4.1",
130
124
  "express": "^5.2.1",
@@ -133,30 +127,17 @@
133
127
  "picocolors": "^1.1.1",
134
128
  "react": "^19.2.5",
135
129
  "react-dom": "^19.2.5",
136
- "tree-sitter-bash": "^0.25.1",
137
- "tree-sitter-c": "^0.24.1",
138
- "tree-sitter-cli": "^0.26.8",
139
- "tree-sitter-cpp": "^0.23.4",
140
- "tree-sitter-css": "^0.25.0",
141
- "tree-sitter-elixir": "^0.3.5",
142
- "tree-sitter-go": "^0.25.0",
143
- "tree-sitter-haskell": "^0.23.1",
144
- "tree-sitter-java": "^0.23.5",
145
- "tree-sitter-javascript": "^0.25.0",
146
- "tree-sitter-kotlin": "^0.3.8",
147
- "tree-sitter-php": "^0.24.2",
148
- "tree-sitter-python": "^0.25.0",
149
- "tree-sitter-ruby": "^0.23.1",
150
- "tree-sitter-rust": "^0.24.0",
151
- "tree-sitter-scala": "^0.24.0",
152
- "tree-sitter-scss": "^1.0.0",
153
- "tree-sitter-swift": "^0.7.1",
154
- "tree-sitter-typescript": "^0.23.2",
155
130
  "yaml": "^2.8.3",
156
131
  "zod": "^4.3.6",
157
132
  "zod-to-json-schema": "^3.25.2"
158
133
  },
159
134
  "devDependencies": {
135
+ "@derekstride/tree-sitter-sql": "^0.3.11",
136
+ "@tree-sitter-grammars/tree-sitter-lua": "^0.4.1",
137
+ "@tree-sitter-grammars/tree-sitter-markdown": "^0.3.2",
138
+ "@tree-sitter-grammars/tree-sitter-toml": "^0.7.0",
139
+ "@tree-sitter-grammars/tree-sitter-yaml": "^0.7.1",
140
+ "@tree-sitter-grammars/tree-sitter-zig": "^1.1.2",
160
141
  "@types/bun": "^1.3.13",
161
142
  "@types/cors": "^2.8.19",
162
143
  "@types/dompurify": "^3.2.0",
@@ -171,6 +152,25 @@
171
152
  "postcss": "^8.5.13",
172
153
  "remark-mdx": "^3.1.1",
173
154
  "remark-parse": "^11.0.0",
155
+ "tree-sitter-bash": "^0.25.1",
156
+ "tree-sitter-c": "^0.24.1",
157
+ "tree-sitter-cli": "^0.26.8",
158
+ "tree-sitter-cpp": "^0.23.4",
159
+ "tree-sitter-css": "^0.25.0",
160
+ "tree-sitter-elixir": "^0.3.5",
161
+ "tree-sitter-go": "^0.25.0",
162
+ "tree-sitter-haskell": "^0.23.1",
163
+ "tree-sitter-java": "^0.23.5",
164
+ "tree-sitter-javascript": "^0.25.0",
165
+ "tree-sitter-kotlin": "^0.3.8",
166
+ "tree-sitter-php": "^0.24.2",
167
+ "tree-sitter-python": "^0.25.0",
168
+ "tree-sitter-ruby": "^0.23.1",
169
+ "tree-sitter-rust": "^0.24.0",
170
+ "tree-sitter-scala": "^0.24.0",
171
+ "tree-sitter-scss": "^1.0.0",
172
+ "tree-sitter-swift": "^0.7.1",
173
+ "tree-sitter-typescript": "^0.23.2",
174
174
  "ts-prune": "^0.10.3",
175
175
  "tsx": "^4.21.0",
176
176
  "typescript": "^6.0.3",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem",
3
- "version": "12.6.1",
3
+ "version": "12.6.2",
4
4
  "description": "Persistent memory system for Claude Code - seamlessly preserve 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": "12.6.1",
3
+ "version": "12.6.3",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for claude-mem bundled hooks",
6
6
  "type": "module",
@@ -149,7 +149,7 @@ ${m}`}let c=o.lineStart;for(let u=o.lineStart-1;u>=0;u--){let d=i[u].trim();if(d
149
149
  ${l}`}var Gu=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"]),KS=new Set(["node_modules",".git","dist","build",".next","__pycache__",".venv","venv","env",".env","target","vendor",".cache",".turbo","coverage",".nyc_output",".claude",".smart-file-read"]),YS=512*1024;async function*Ku(t,e,r=20,n){if(r<=0)return;let s;try{s=await(0,Wt.readdir)(t,{withFileTypes:!0})}catch(o){y.debug("WORKER",`walkDir: failed to read directory ${t}`,void 0,o instanceof Error?o:void 0);return}for(let o of s){if(o.name.startsWith(".")&&o.name!=="."||KS.has(o.name))continue;let i=(0,Fr.join)(t,o.name);if(o.isDirectory())yield*Ku(i,e,r-1,n);else if(o.isFile()){let c=o.name.slice(o.name.lastIndexOf("."));(Gu.has(c)||n&&n.has(c))&&(yield i)}}}async function BS(t){try{let e=await(0,Wt.stat)(t);if(e.size>YS||e.size===0)return null;let r=await(0,Wt.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 Yu(t,e,r={}){let n=r.maxResults||20,s=e.toLowerCase(),o=s.split(/[\s_\-./]+/).filter(S=>S.length>0),i=r.projectRoot||t,c=Ur(i),l=new Set;for(let S of Object.values(c.grammars))for(let w of S.extensions)Gu.has(w)||l.add(w);let u=[];for await(let S of Ku(t,t,20,l.size>0?l:void 0)){if(r.filePattern&&!(0,Fr.relative)(t,S).toLowerCase().includes(r.filePattern.toLowerCase()))continue;let w=await BS(S);w&&u.push({absolutePath:S,relativePath:(0,Fr.relative)(t,S),content:w})}let d=Hu(u,i),f=[],p=[],m=0;for(let[S,w]of d){m+=JS(w);let k=ns(S.toLowerCase(),o)>0,le=[],fe=(Gt,yt)=>{for(let W of Gt){let Ge=0,be="",Kt=ns(W.name.toLowerCase(),o);Kt>0&&(Ge+=Kt*3,be="name match"),W.signature.toLowerCase().includes(s)&&(Ge+=2,be=be?`${be} + signature`:"signature match"),W.jsdoc&&W.jsdoc.toLowerCase().includes(s)&&(Ge+=1,be=be?`${be} + jsdoc`:"jsdoc match"),Ge>0&&(k=!0,le.push({filePath:S,symbolName:yt?`${yt}.${W.name}`:W.name,kind:W.kind,signature:W.signature,jsdoc:W.jsdoc,lineStart:W.lineStart,lineEnd:W.lineEnd,matchReason:be})),W.children&&fe(W.children,W.name)}};fe(w.symbols),k&&(f.push(w),p.push(...le))}p.sort((S,w)=>{let C=ns(S.symbolName.toLowerCase(),o);return ns(w.symbolName.toLowerCase(),o)-C});let h=p.slice(0,n),g=new Set(h.map(S=>S.filePath)),_=f.filter(S=>g.has(S.filePath)).slice(0,n),E=_.reduce((S,w)=>S+w.foldedTokenEstimate,0);return{foldedFiles:_,matchingSymbols:h,totalFilesScanned:u.length,totalSymbolsFound:m,tokenEstimate:E}}function ns(t,e){let r=0;for(let n of e)if(t===n)r+=10;else if(t.includes(n))r+=5;else{let s=0,o=0;for(let i of n){let c=t.indexOf(i,s);c!==-1&&(o++,s=c+1)}o===n.length&&(r+=1)}return r}function JS(t){let e=t.symbols.length;for(let r of t.symbols)r.children&&(e+=r.children.length);return e}function Bu(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(`
150
150
  `);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 s=n.jsdoc.split(`
151
151
  `).find(o=>o.replace(/^[\s*/]+/,"").trim().length>0);s&&r.push(` \u{1F4AC} ${s.replace(/^[\s*/]+/,"").trim()}`)}r.push("")}r.push("\u2500\u2500 Folded File Views \u2500\u2500"),r.push("");for(let n of t.foldedFiles)r.push(Ht(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(`
152
- `)}var Hi=require("node:fs/promises"),ss=require("node:fs"),Re=require("node:path"),Xu=require("node:os"),Qu=require("node:url"),cE={},ZS="12.6.1";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var ed=!1,td=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Re.dirname)((0,Qu.fileURLToPath)(cE.url))}catch{return ed=!0,process.cwd()}})(),Wi=(0,Re.resolve)(td,"worker-service.cjs");function XS(){ed&&((0,ss.existsSync)(Wi)||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:Wi,mcpServerDir:td}))}var Ju={search:"/api/search",timeline:"/api/timeline"};async function Fi(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[s,o]of Object.entries(e))o!=null&&r.append(s,String(o));let n=`${t}?${r}`;try{let s=await es(n);if(!s.ok){let i=await s.text();throw new Error(`Worker API error (${s.status}): ${i}`)}let o=await s.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),o}catch(s){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},s instanceof Error?s:new Error(String(s))),{content:[{type:"text",text:`Error calling Worker API: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}async function QS(t,e){let r=await es(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let s=await r.text();throw new Error(`Worker API error (${r.status}): ${s}`)}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 Vt(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await QS(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 eE(){try{return(await es("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}async function tE(){if(await eE())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),XS();try{let t=Oi(),e=await Au(t,Wi);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 rd=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
152
+ `)}var Hi=require("node:fs/promises"),ss=require("node:fs"),Re=require("node:path"),Xu=require("node:os"),Qu=require("node:url"),cE={},ZS="12.6.3";console.log=(...t)=>{y.error("CONSOLE","Intercepted console output (MCP protocol protection)",void 0,{args:t})};var ed=!1,td=(()=>{if(typeof __dirname<"u")return __dirname;try{return(0,Re.dirname)((0,Qu.fileURLToPath)(cE.url))}catch{return ed=!0,process.cwd()}})(),Wi=(0,Re.resolve)(td,"worker-service.cjs");function XS(){ed&&((0,ss.existsSync)(Wi)||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:Wi,mcpServerDir:td}))}var Ju={search:"/api/search",timeline:"/api/timeline"};async function Fi(t,e){y.debug("SYSTEM","\u2192 Worker API",void 0,{endpoint:t,params:e});let r=new URLSearchParams;for(let[s,o]of Object.entries(e))o!=null&&r.append(s,String(o));let n=`${t}?${r}`;try{let s=await es(n);if(!s.ok){let i=await s.text();throw new Error(`Worker API error (${s.status}): ${i}`)}let o=await s.json();return y.debug("SYSTEM","\u2190 Worker API success",void 0,{endpoint:t}),o}catch(s){return y.error("SYSTEM","\u2190 Worker API error",{endpoint:t},s instanceof Error?s:new Error(String(s))),{content:[{type:"text",text:`Error calling Worker API: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}async function QS(t,e){let r=await es(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!r.ok){let s=await r.text();throw new Error(`Worker API error (${r.status}): ${s}`)}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 Vt(t,e){y.debug("HTTP","Worker API request (POST)",void 0,{endpoint:t});try{return await QS(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 eE(){try{return(await es("/api/health")).ok}catch(t){return y.debug("SYSTEM","Worker health check failed",{},t instanceof Error?t:new Error(String(t))),!1}}async function tE(){if(await eE())return!0;y.warn("SYSTEM","Worker not available, attempting auto-start for MCP client"),XS();try{let t=Oi(),e=await Au(t,Wi);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 rd=[{name:"__IMPORTANT",description:`3-LAYER WORKFLOW (ALWAYS FOLLOW):
153
153
  1. search(query) \u2192 Get index with IDs (~50-100 tokens/result)
154
154
  2. timeline(anchor=ID) \u2192 Get context around interesting results
155
155
  3. get_observations([IDs]) \u2192 Fetch full details ONLY for filtered IDs