context-mode 1.0.78 → 1.0.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/.openclaw-plugin/openclaw.plugin.json +1 -1
- package/.openclaw-plugin/package.json +1 -1
- package/build/db-base.js +9 -0
- package/build/store.d.ts +1 -0
- package/build/store.js +42 -11
- package/cli.bundle.mjs +6 -6
- package/hooks/session-db.bundle.mjs +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
- package/server.bundle.mjs +6 -6
|
@@ -6,14 +6,14 @@
|
|
|
6
6
|
},
|
|
7
7
|
"metadata": {
|
|
8
8
|
"description": "Claude Code plugins by Mert Koseoğlu",
|
|
9
|
-
"version": "1.0.
|
|
9
|
+
"version": "1.0.79"
|
|
10
10
|
},
|
|
11
11
|
"plugins": [
|
|
12
12
|
{
|
|
13
13
|
"name": "context-mode",
|
|
14
14
|
"source": "./",
|
|
15
15
|
"description": "Claude Code MCP plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.",
|
|
16
|
-
"version": "1.0.
|
|
16
|
+
"version": "1.0.79",
|
|
17
17
|
"author": {
|
|
18
18
|
"name": "Mert Koseoğlu"
|
|
19
19
|
},
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "context-mode",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.79",
|
|
4
4
|
"description": "MCP server that saves 98% of your context window with session continuity. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and automatic state restore across compactions.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Mert Koseoğlu",
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "Context Mode",
|
|
4
4
|
"kind": "tool",
|
|
5
5
|
"description": "OpenClaw plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.",
|
|
6
|
-
"version": "1.0.
|
|
6
|
+
"version": "1.0.79",
|
|
7
7
|
"sandbox": {
|
|
8
8
|
"mode": "permissive",
|
|
9
9
|
"filesystem_access": "full",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "context-mode",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.79",
|
|
4
4
|
"description": "OpenClaw plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Mert Koseoğlu",
|
package/build/db-base.js
CHANGED
|
@@ -222,6 +222,15 @@ export function loadDatabase() {
|
|
|
222
222
|
export function applyWALPragmas(db) {
|
|
223
223
|
db.pragma("journal_mode = WAL");
|
|
224
224
|
db.pragma("synchronous = NORMAL");
|
|
225
|
+
// Memory-map the DB file for read-heavy FTS5 search workloads.
|
|
226
|
+
// Eliminates read() syscalls — the kernel serves pages directly from
|
|
227
|
+
// the page cache. 256MB is a safe upper bound (SQLite only maps up to
|
|
228
|
+
// the actual file size). Falls back gracefully on platforms where mmap
|
|
229
|
+
// is unavailable or restricted.
|
|
230
|
+
try {
|
|
231
|
+
db.pragma("mmap_size = 268435456");
|
|
232
|
+
}
|
|
233
|
+
catch { /* unsupported runtime */ }
|
|
225
234
|
}
|
|
226
235
|
// ─────────────────────────────────────────────────────────
|
|
227
236
|
// DB file helpers
|
package/build/store.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ export declare function cleanupStaleDBs(): number;
|
|
|
23
23
|
export declare function cleanupStaleContentDBs(contentDir: string, maxAgeDays: number): number;
|
|
24
24
|
export declare class ContentStore {
|
|
25
25
|
#private;
|
|
26
|
+
static readonly OPTIMIZE_EVERY = 50;
|
|
26
27
|
constructor(dbPath?: string);
|
|
27
28
|
/** Delete this session's DB files. Call on process exit. */
|
|
28
29
|
cleanup(): void;
|
package/build/store.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* Use for documentation, API references, and any content where
|
|
8
8
|
* you need EXACT text later — not summaries.
|
|
9
9
|
*/
|
|
10
|
+
var _a;
|
|
10
11
|
import { loadDatabase, applyWALPragmas, closeDB, cleanOrphanedWALFiles, withRetry, deleteDBFiles, isSQLiteCorruptionError } from "./db-base.js";
|
|
11
12
|
import { readFileSync, readdirSync, unlinkSync, existsSync, statSync } from "node:fs";
|
|
12
13
|
import { tmpdir } from "node:os";
|
|
@@ -263,6 +264,11 @@ export class ContentStore {
|
|
|
263
264
|
#stmtChunkContent;
|
|
264
265
|
#stmtStats;
|
|
265
266
|
#stmtSourceMeta;
|
|
267
|
+
// FTS5 optimization: track inserts and optimize periodically to defragment
|
|
268
|
+
// the index. FTS5 b-trees fragment over many insert/delete cycles, degrading
|
|
269
|
+
// search performance. SQLite's built-in 'optimize' merges b-tree segments.
|
|
270
|
+
#insertCount = 0;
|
|
271
|
+
static OPTIMIZE_EVERY = 50;
|
|
266
272
|
constructor(dbPath) {
|
|
267
273
|
const Database = loadDatabase();
|
|
268
274
|
this.#dbPath =
|
|
@@ -623,6 +629,14 @@ export class ContentStore {
|
|
|
623
629
|
const sourceId = transaction();
|
|
624
630
|
if (text)
|
|
625
631
|
this.#extractAndStoreVocabulary(text);
|
|
632
|
+
// Periodically optimize FTS5 indexes to merge b-tree segments.
|
|
633
|
+
// Fragmentation accumulates over insert/delete cycles (dedup re-indexes
|
|
634
|
+
// every source on update). The 'optimize' command merges segments into
|
|
635
|
+
// a single b-tree, improving search latency for long-running sessions.
|
|
636
|
+
this.#insertCount++;
|
|
637
|
+
if (this.#insertCount % _a.OPTIMIZE_EVERY === 0) {
|
|
638
|
+
this.#optimizeFTS();
|
|
639
|
+
}
|
|
626
640
|
return {
|
|
627
641
|
sourceId,
|
|
628
642
|
label,
|
|
@@ -758,20 +772,27 @@ export class ContentStore {
|
|
|
758
772
|
.toLowerCase()
|
|
759
773
|
.split(/\s+/)
|
|
760
774
|
.filter((w) => w.length >= 2);
|
|
761
|
-
// Single-term queries: no reranking needed
|
|
762
|
-
if (terms.length < 2)
|
|
763
|
-
return results;
|
|
764
775
|
return results
|
|
765
776
|
.map((r) => {
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
//
|
|
769
|
-
|
|
770
|
-
|
|
777
|
+
// Title-match boost: query terms found in the chunk title get a boost.
|
|
778
|
+
// Code chunks get a stronger title boost (function/class names are high
|
|
779
|
+
// signal) while prose chunks get a moderate one (headings are useful but
|
|
780
|
+
// body carries more weight).
|
|
781
|
+
const titleLower = r.title.toLowerCase();
|
|
782
|
+
const titleHits = terms.filter((t) => titleLower.includes(t)).length;
|
|
783
|
+
const titleWeight = r.contentType === "code" ? 0.6 : 0.3;
|
|
784
|
+
const titleBoost = titleHits > 0 ? titleWeight * (titleHits / terms.length) : 0;
|
|
785
|
+
// Proximity boost for multi-term queries
|
|
786
|
+
let proximityBoost = 0;
|
|
787
|
+
if (terms.length >= 2) {
|
|
788
|
+
const content = r.content.toLowerCase();
|
|
789
|
+
const positions = terms.map((t) => findAllPositions(content, t));
|
|
790
|
+
if (!positions.some((p) => p.length === 0)) {
|
|
791
|
+
const minSpan = findMinSpan(positions);
|
|
792
|
+
proximityBoost = 1 / (1 + minSpan / Math.max(content.length, 1));
|
|
793
|
+
}
|
|
771
794
|
}
|
|
772
|
-
|
|
773
|
-
const boost = 1 / (1 + minSpan / Math.max(content.length, 1));
|
|
774
|
-
return { result: r, boost };
|
|
795
|
+
return { result: r, boost: titleBoost + proximityBoost };
|
|
775
796
|
})
|
|
776
797
|
.sort((a, b) => b.boost - a.boost || a.result.rank - b.result.rank)
|
|
777
798
|
.map(({ result }) => result);
|
|
@@ -897,7 +918,16 @@ export class ContentStore {
|
|
|
897
918
|
return 0;
|
|
898
919
|
}
|
|
899
920
|
}
|
|
921
|
+
/** Merge FTS5 b-tree segments for both porter and trigram indexes. */
|
|
922
|
+
#optimizeFTS() {
|
|
923
|
+
try {
|
|
924
|
+
this.#db.exec("INSERT INTO chunks(chunks) VALUES('optimize')");
|
|
925
|
+
this.#db.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')");
|
|
926
|
+
}
|
|
927
|
+
catch { /* best effort — don't block indexing */ }
|
|
928
|
+
}
|
|
900
929
|
close() {
|
|
930
|
+
this.#optimizeFTS(); // defragment before close
|
|
901
931
|
closeDB(this.#db); // WAL checkpoint before close — important for persistent DBs
|
|
902
932
|
}
|
|
903
933
|
// ── Vocabulary Extraction ──
|
|
@@ -1163,3 +1193,4 @@ export class ContentStore {
|
|
|
1163
1193
|
return headingStack.map((h) => h.text).join(" > ");
|
|
1164
1194
|
}
|
|
1165
1195
|
}
|
|
1196
|
+
_a = ContentStore;
|
package/cli.bundle.mjs
CHANGED
|
@@ -125,7 +125,7 @@ FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
|
|
|
125
125
|
${n}`;case"elixir":return`file_content_path = ${o}
|
|
126
126
|
file_path = file_content_path
|
|
127
127
|
file_content = File.read!(file_content_path)
|
|
128
|
-
${n}`}}}});var ik={};De(ik,{BunSQLiteAdapter:()=>Ac,NodeSQLiteAdapter:()=>zc,SQLiteBase:()=>Nc,applyWALPragmas:()=>Mo,cleanOrphanedWALFiles:()=>Do,closeDB:()=>Lo,defaultDBPath:()=>ok,deleteDBFiles:()=>jc,isSQLiteCorruptionError:()=>Mc,loadDatabase:()=>zn,renameCorruptDB:()=>sk,withRetry:()=>qr});import{createRequire as jN}from"node:module";import{existsSync as MN,unlinkSync as nk,renameSync as DN}from"node:fs";import{tmpdir as LN}from"node:os";import{join as FN}from"node:path";function zn(){if(!jo){let t=jN(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;jo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new Ac(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(process.platform==="linux")try{let{DatabaseSync:e}=t(["node","sqlite"].join(":"));jo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1});return new zc(s)}}catch{jo=t("better-sqlite3")}else jo=t("better-sqlite3")}return jo}function Mo(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL")}function Do(t){if(!MN(t))for(let e of["-wal","-shm"])try{nk(t+e)}catch{}}function jc(t){for(let e of["","-wal","-shm"])try{nk(t+e)}catch{}}function Lo(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function ok(t="context-mode"){return FN(LN(),`${t}-${process.pid}.db`)}function qr(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function Mc(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function sk(t){let e=Date.now();for(let r of["","-wal","-shm"])try{DN(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var Ac,zc,jo,ci,_h,Nc,ui=b(()=>{"use strict";Ac=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},zc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},jo=null;ci=Symbol.for("__context_mode_live_dbs__"),_h=(()=>{let t=globalThis;return t[ci]||(t[ci]=new Set,process.on("exit",()=>{for(let e of t[ci])Lo(e);t[ci].clear()})),t[ci]})(),Nc=class{#e;#t;constructor(e){let r=zn();this.#e=e,Do(e);let n;try{n=new r(e,{timeout:3e4}),Mo(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Mc(s)){sk(e),Do(e);try{n=new r(e,{timeout:3e4}),Mo(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,_h.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){_h.delete(this.#t),Lo(this.#t)}withRetry(e){return qr(e)}cleanup(){_h.delete(this.#t),Lo(this.#t),jc(this.#e)}}});import{readFileSync as ZN,readdirSync as lk,unlinkSync as vh,existsSync as ak,statSync as yh}from"node:fs";import{tmpdir as dk}from"node:os";import{join as xh}from"node:path";function UN(t,e="AND"){let r=t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(n=>n.length>0&&!["AND","OR","NOT","NEAR"].includes(n.toUpperCase()));return r.length===0?'""':r.map(n=>`"${n}"`).join(e==="OR"?" OR ":" ")}function HN(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=r.split(/\s+/).filter(o=>o.length>=3);return n.length===0?"":n.map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function qN(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function BN(t){return t<=4?1:t<=12?2:3}function bh(){let t=dk(),e=0;try{let r=lk(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=xh(t,n);for(let a of["","-wal","-shm"])try{vh(i+a)}catch{}e++}}}catch{}return e}function Sh(t,e){let r=0;try{if(!ak(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=lk(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=xh(t,s),c=yh(i).mtimeMs<n;if(!c){let u=i+"-wal";if(ak(u))try{let l=yh(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{vh(i+u)}catch{}r++}}catch{}}catch{}return r}function VN(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function WN(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(o=>[...o].sort((s,i)=>s-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var ck,uk,Dc,pk=b(()=>{"use strict";ui();ck=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);uk=4096;Dc=class{#e;#t;#r;#n;#s;#i;#o;#a;#c;#d;#p;#m;#f;#h;#g;#_;#y;#v;#x;#b;#S;#k;#w;#$;#E;#T;#P;#R;#O;constructor(e){let r=zn();this.#t=e??xh(dk(),`context-mode-${process.pid}.db`),Do(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),Mo(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Mc(s)){jc(this.#t),Do(this.#t);try{n=new r(this.#t,{timeout:3e4}),Mo(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#
|
|
128
|
+
${n}`}}}});var ik={};De(ik,{BunSQLiteAdapter:()=>Ac,NodeSQLiteAdapter:()=>zc,SQLiteBase:()=>Nc,applyWALPragmas:()=>Mo,cleanOrphanedWALFiles:()=>Do,closeDB:()=>Lo,defaultDBPath:()=>ok,deleteDBFiles:()=>jc,isSQLiteCorruptionError:()=>Mc,loadDatabase:()=>zn,renameCorruptDB:()=>sk,withRetry:()=>qr});import{createRequire as jN}from"node:module";import{existsSync as MN,unlinkSync as nk,renameSync as DN}from"node:fs";import{tmpdir as LN}from"node:os";import{join as FN}from"node:path";function zn(){if(!jo){let t=jN(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;jo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new Ac(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(process.platform==="linux")try{let{DatabaseSync:e}=t(["node","sqlite"].join(":"));jo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1});return new zc(s)}}catch{jo=t("better-sqlite3")}else jo=t("better-sqlite3")}return jo}function Mo(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function Do(t){if(!MN(t))for(let e of["-wal","-shm"])try{nk(t+e)}catch{}}function jc(t){for(let e of["","-wal","-shm"])try{nk(t+e)}catch{}}function Lo(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function ok(t="context-mode"){return FN(LN(),`${t}-${process.pid}.db`)}function qr(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function Mc(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function sk(t){let e=Date.now();for(let r of["","-wal","-shm"])try{DN(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var Ac,zc,jo,ci,_h,Nc,ui=b(()=>{"use strict";Ac=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},zc=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},jo=null;ci=Symbol.for("__context_mode_live_dbs__"),_h=(()=>{let t=globalThis;return t[ci]||(t[ci]=new Set,process.on("exit",()=>{for(let e of t[ci])Lo(e);t[ci].clear()})),t[ci]})(),Nc=class{#e;#t;constructor(e){let r=zn();this.#e=e,Do(e);let n;try{n=new r(e,{timeout:3e4}),Mo(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Mc(s)){sk(e),Do(e);try{n=new r(e,{timeout:3e4}),Mo(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,_h.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){_h.delete(this.#t),Lo(this.#t)}withRetry(e){return qr(e)}cleanup(){_h.delete(this.#t),Lo(this.#t),jc(this.#e)}}});import{readFileSync as ZN,readdirSync as lk,unlinkSync as vh,existsSync as ak,statSync as yh}from"node:fs";import{tmpdir as dk}from"node:os";import{join as xh}from"node:path";function UN(t,e="AND"){let r=t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(n=>n.length>0&&!["AND","OR","NOT","NEAR"].includes(n.toUpperCase()));return r.length===0?'""':r.map(n=>`"${n}"`).join(e==="OR"?" OR ":" ")}function HN(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=r.split(/\s+/).filter(o=>o.length>=3);return n.length===0?"":n.map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function qN(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function BN(t){return t<=4?1:t<=12?2:3}function bh(){let t=dk(),e=0;try{let r=lk(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=xh(t,n);for(let a of["","-wal","-shm"])try{vh(i+a)}catch{}e++}}}catch{}return e}function Sh(t,e){let r=0;try{if(!ak(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=lk(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=xh(t,s),c=yh(i).mtimeMs<n;if(!c){let u=i+"-wal";if(ak(u))try{let l=yh(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{vh(i+u)}catch{}r++}}catch{}}catch{}return r}function VN(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function WN(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(o=>[...o].sort((s,i)=>s-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var ck,uk,Dc,pk=b(()=>{"use strict";ui();ck=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);uk=4096;Dc=class t{#e;#t;#r;#n;#s;#i;#o;#a;#c;#d;#p;#m;#f;#h;#g;#_;#y;#v;#x;#b;#S;#k;#w;#$;#E;#T;#P;#R;#O;#C=0;static OPTIMIZE_EVERY=50;constructor(e){let r=zn();this.#t=e??xh(dk(),`context-mode-${process.pid}.db`),Do(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),Mo(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(Mc(s)){jc(this.#t),Do(this.#t);try{n=new r(this.#t,{timeout:3e4}),Mo(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#M(),this.#D()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{vh(this.#t+e)}catch{}}#M(){this.#e.exec(`
|
|
129
129
|
CREATE TABLE IF NOT EXISTS sources (
|
|
130
130
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
131
131
|
label TEXT NOT NULL,
|
|
@@ -155,7 +155,7 @@ ${n}`}}}});var ik={};De(ik,{BunSQLiteAdapter:()=>Ac,NodeSQLiteAdapter:()=>zc,SQL
|
|
|
155
155
|
);
|
|
156
156
|
|
|
157
157
|
CREATE INDEX IF NOT EXISTS idx_sources_label ON sources(label);
|
|
158
|
-
`)}#
|
|
158
|
+
`)}#D(){this.#r=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count) VALUES (?, 0, 0)"),this.#n=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count) VALUES (?, ?, ?)"),this.#s=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type) VALUES (?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type) VALUES (?, ?, ?, ?)"),this.#o=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#a=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#c=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#d=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#p=this.#e.prepare(`
|
|
159
159
|
SELECT
|
|
160
160
|
chunks.title,
|
|
161
161
|
chunks.content,
|
|
@@ -320,16 +320,16 @@ ${n}`}}}});var ik={};De(ik,{BunSQLiteAdapter:()=>Ac,NodeSQLiteAdapter:()=>zc,SQL
|
|
|
320
320
|
(SELECT COUNT(*) FROM sources) AS sources,
|
|
321
321
|
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
322
322
|
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
|
|
323
|
-
`)}index(e){let{content:r,path:n,source:o}=e;if(!r&&!n)throw new Error("Either content or path must be provided");let s=r??ZN(n,"utf-8"),i=o??n??"untitled",a=this.#
|
|
323
|
+
`)}index(e){let{content:r,path:n,source:o}=e;if(!r&&!n)throw new Error("Either content or path must be provided");let s=r??ZN(n,"utf-8"),i=o??n??"untitled",a=this.#F(s);return qr(()=>this.#u(a,i,s))}indexPlainText(e,r,n=20){if(!e||e.trim().length===0)return this.#u([],r,"");let o=this.#Z(e,n);return qr(()=>this.#u(o.map(s=>({...s,hasCode:!1})),r,e))}indexJSON(e,r,n=uk){if(!e||e.trim().length===0)return this.indexPlainText("",r);let o;try{o=JSON.parse(e)}catch{return this.indexPlainText(e,r)}let s=[];return this.#j(o,[],s,n),s.length===0?this.indexPlainText(e,r):qr(()=>this.#u(s,r,e))}#u(e,r,n){let o=e.filter(a=>a.hasCode).length,i=this.#e.transaction(()=>{if(this.#a.run(r),this.#c.run(r),this.#d.run(r),e.length===0){let u=this.#r.run(r);return Number(u.lastInsertRowid)}let a=this.#n.run(r,e.length,o),c=Number(a.lastInsertRowid);for(let u of e){let l=u.hasCode?"code":"prose";this.#s.run(u.title,u.content,c,l),this.#i.run(u.title,u.content,c,l)}return c})();return n&&this.#L(n),this.#C++,this.#C%t.OPTIMIZE_EVERY===0&&this.#N(),{sourceId:i,label:r,totalChunks:e.length,codeChunks:o}}#I(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted}))}#l(e,r){return r==="exact"?e:`%${e}%`}search(e,r=3,n,o="AND",s,i="like"){let a=UN(e,o),c,u;return n&&s?(c=i==="exact"?this.#b:this.#x,u=[a,this.#l(n,i),s,r]):n?(c=i==="exact"?this.#f:this.#m,u=[a,this.#l(n,i),r]):s?(c=this.#v,u=[a,s,r]):(c=this.#p,u=[a,r]),qr(()=>this.#I(c.all(...u)))}searchTrigram(e,r=3,n,o="AND",s,i="like"){let a=HN(e,o);if(!a)return[];let c,u;return n&&s?(c=i==="exact"?this.#w:this.#k,u=[a,this.#l(n,i),s,r]):n?(c=i==="exact"?this.#_:this.#g,u=[a,this.#l(n,i),r]):s?(c=this.#S,u=[a,s,r]):(c=this.#h,u=[a,r]),qr(()=>this.#I(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;let n=BN(r.length),o=this.#y.all(r.length-n,r.length+n),s=null,i=n+1;for(let{word:a}of o){if(a===r)return null;let c=qN(r,a);c<i&&(i=c,s=a)}return i<=n?s:null}#A(e,r,n,o,s="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",o,s),u=this.searchTrigram(e,a,n,"OR",o,s),l=new Map,d=m=>`${m.source}::${m.title}`;for(let[m,f]of c.entries()){let p=d(f),h=l.get(p);h?h.score+=1/(60+m+1):l.set(p,{result:f,score:1/(60+m+1)})}for(let[m,f]of u.entries()){let p=d(f),h=l.get(p);h?h.score+=1/(60+m+1):l.set(p,{result:f,score:1/(60+m+1)})}return Array.from(l.values()).sort((m,f)=>f.score-m.score).slice(0,r).map(({result:m,score:f})=>({...m,rank:-f}))}#z(e,r){let n=r.toLowerCase().split(/\s+/).filter(o=>o.length>=2);return e.map(o=>{let s=o.title.toLowerCase(),i=n.filter(l=>s.includes(l)).length,a=o.contentType==="code"?.6:.3,c=i>0?a*(i/n.length):0,u=0;if(n.length>=2){let l=o.content.toLowerCase(),d=n.map(m=>VN(l,m));d.some(m=>m.length===0)||(u=1/(1+WN(d)/Math.max(l.length,1)))}return{result:o,boost:c+u}}).sort((o,s)=>s.boost-o.boost||o.result.rank-s.result.rank).map(({result:o})=>o)}searchWithFallback(e,r=3,n,o,s="like"){let i=this.#A(e,r,n,o,s);if(i.length>0)return this.#z(i,e).map(m=>({...m,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(d=>d.length>=3),c=a.join(" "),l=a.map(d=>this.fuzzyCorrect(d)??d).join(" ");if(l!==c){let d=this.#A(l,r,n,o,s);if(d.length>0)return this.#z(d,l).map(f=>({...f,matchLayer:"rrf-fuzzy"}))}return[]}getSourceMeta(e){let r=this.#O.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at}:null}listSources(){return this.#$.all()}getChunksBySource(e){return this.#E.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#T.get(e);if(!n||n.chunk_count<3)return[];let o=n.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#P.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(m=>m.length>=3&&!ck.has(m)));for(let m of d)a.set(m,(a.get(m)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let m=Math.log(o/d),f=Math.min(l.length/20,.5),p=/[_]/.test(l),h=l.length>=12,g=p?1.5:h?.8:0;return{word:l,score:m+f+g}}).sort((l,d)=>d.score-l.score).slice(0,r).map(l=>l.word)}getStats(){let e=this.#R.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){let r=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),n=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),o=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')");return this.#e.transaction(a=>(r.run(a),n.run(a),o.run(a)))(e).changes}getDBSizeBytes(){try{return yh(this.#t).size}catch{return 0}}#N(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#N(),Lo(this.#e)}#L(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(o=>o.length>=3&&!ck.has(o)),n=[...new Set(r)];this.#e.transaction(()=>{for(let o of n)this.#o.run(o)})()}#F(e,r=uk){let n=[],o=e.split(`
|
|
324
324
|
`),s=[],i=[],a="",c=()=>{let l=i.join(`
|
|
325
|
-
`).trim();if(l.length===0)return;let d=this.#
|
|
325
|
+
`).trim();if(l.length===0)return;let d=this.#B(s,a),m=i.some(_=>/^`{3,}/.test(_));if(Buffer.byteLength(l)<=r){n.push({title:d,content:l,hasCode:m}),i=[];return}let f=l.split(/\n\n+/),p=[],h=1,g=()=>{if(p.length===0)return;let _=p.join(`
|
|
326
326
|
|
|
327
327
|
`).trim();if(_.length===0)return;let y=f.length>1?`${d} (${h})`:d;h++,n.push({title:y,content:_,hasCode:_.includes("```")}),p=[]};for(let _ of f){p.push(_);let y=p.join(`
|
|
328
328
|
|
|
329
|
-
`);Buffer.byteLength(y)>r&&p.length>1&&(p.pop(),g(),p=[_])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let f=d[1].length,p=d[2].trim();for(;s.length>0&&s[s.length-1].level>=f;)s.pop();s.push({level:f,text:p}),a=p,i.push(l),u++;continue}let m=l.match(/^(`{3,})(.*)?$/);if(m){let f=m[1],p=[l];for(u++;u<o.length;){if(p.push(o[u]),o[u].startsWith(f)&&o[u].trim()===f){u++;break}u++}i.push(...p);continue}i.push(l),u++}return c(),n}#
|
|
329
|
+
`);Buffer.byteLength(y)>r&&p.length>1&&(p.pop(),g(),p=[_])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let f=d[1].length,p=d[2].trim();for(;s.length>0&&s[s.length-1].level>=f;)s.pop();s.push({level:f,text:p}),a=p,i.push(l),u++;continue}let m=l.match(/^(`{3,})(.*)?$/);if(m){let f=m[1],p=[l];for(u++;u<o.length;){if(p.push(o[u]),o[u].startsWith(f)&&o[u].trim()===f){u++;break}u++}i.push(...p);continue}i.push(l),u++}return c(),n}#Z(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let l=c.trim();return{title:l.split(`
|
|
330
330
|
`)[0].slice(0,80)||`Section ${u+1}`,content:l}}).filter(c=>c.content.length>0);let o=e.split(`
|
|
331
331
|
`);if(o.length<=r)return[{title:"Output",content:e}];let s=[],a=Math.max(r-2,1);for(let c=0;c<o.length;c+=a){let u=o.slice(c,c+r);if(u.length===0)break;let l=c+1,d=Math.min(c+u.length,o.length),m=u[0]?.trim().slice(0,80);s.push({title:m||`Lines ${l}-${d}`,content:u.join(`
|
|
332
|
-
`)})}return s}#
|
|
332
|
+
`)})}return s}#j(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#j(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#q(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#U(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#H(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#q(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#U(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#H(s,c,l,a,i);n.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#B(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});import{readFileSync as fk}from"node:fs";import{resolve as Fo}from"node:path";import{homedir as hk}from"node:os";function gk(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function GN(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function KN(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function mk(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function JN(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let o=t.slice(0,n),s=t.slice(n+1),i=KN(o),a=mk(s);r=`^${i}(\\s${a})?$`}else r=`^${mk(t)}$`;return new RegExp(r,e?"i":"")}function YN(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function XN(t,e,r=!1){for(let n of e){let o=gk(n);if(o&&JN(o,r).test(t))return n}return null}function QN(t){let e=[],r="",n=!1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!o&&!s&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!s&&c!=="\\"?(o=!o,r+=a):a==="`"&&!n&&!o&&c!=="\\"?(s=!s,r+=a):!n&&!o&&!s?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function kh(t){let e;try{e=fk(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&gk(i)!==null):[];return{allow:o(n.allow),deny:o(n.deny),ask:o(n.ask)}}function wh(t,e){let r=[];if(t){let s=Fo(t,".claude","settings.local.json"),i=kh(s);i&&r.push(i);let a=Fo(t,".claude","settings.json"),c=kh(a);c&&r.push(c)}let n=e??Fo(hk(),".claude","settings.json"),o=kh(n);return o&&r.push(o),r}function _k(t,e,r){let n=[],o=a=>{let c;try{c=fk(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.deny;if(!Array.isArray(l))return[];let d=[];for(let m of l){if(typeof m!="string")continue;let f=GN(m);f&&f.tool===t&&d.push(f.glob)}return d};if(e){let a=o(Fo(e,".claude","settings.local.json"));a!==null&&n.push(a);let c=o(Fo(e,".claude","settings.json"));c!==null&&n.push(c)}let s=r??Fo(hk(),".claude","settings.json"),i=o(s);return i!==null&&n.push(i),n}function $h(t,e,r=process.platform==="win32"){let n=QN(t);for(let o of n)for(let s of e){let i=XN(o,s.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function yk(t,e,r=process.platform==="win32"){let n=t.replace(/\\/g,"/");for(let o of e)for(let s of o)if(YN(s,r).test(n))return{denied:!0,matchedPattern:s};return{denied:!1}}function tj(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let s=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function vk(t,e){let r=ej[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let o of r){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&n.push(i)}}return e==="python"&&n.push(...tj(t)),n}var ej,xk=b(()=>{"use strict";ej={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]}});function Eh(t){let{language:e,exitCode:r,stdout:n,stderr:o}=t,s=e==="shell"&&r===1&&n.trim().length>0;return{isError:!s,output:s?n:`Exit code: ${r}
|
|
333
333
|
|
|
334
334
|
stdout:
|
|
335
335
|
${n}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire as R}from"node:module";import{existsSync as v,unlinkSync as T,renameSync as L}from"node:fs";import{tmpdir as N}from"node:os";import{join as w}from"node:path";var l=class{#t;constructor(t){this.#t=t}pragma(t){let e=this.#t.prepare(`PRAGMA ${t}`).all();if(!e||e.length===0)return;if(e.length>1)return e;let r=Object.values(e[0]);return r.length===1?r[0]:e[0]}exec(t){let s="",e=null;for(let o=0;o<t.length;o++){let a=t[o];if(e)s+=a,a===e&&(e=null);else if(a==="'"||a==='"')s+=a,e=a;else if(a===";"){let u=s.trim();u&&this.#t.prepare(u).run(),s=""}else s+=a}let r=s.trim();return r&&this.#t.prepare(r).run(),this}prepare(t){let s=this.#t.prepare(t);return{run:(...e)=>s.run(...e),get:(...e)=>{let r=s.get(...e);return r===null?void 0:r},all:(...e)=>s.all(...e),iterate:(...e)=>s.iterate(...e)}}transaction(t){return this.#t.transaction(t)}close(){this.#t.close()}},p=class{#t;constructor(t){this.#t=t}pragma(t){let e=this.#t.prepare(`PRAGMA ${t}`).all();if(!e||e.length===0)return;if(e.length>1)return e;let r=Object.values(e[0]);return r.length===1?r[0]:e[0]}exec(t){return this.#t.exec(t),this}prepare(t){let s=this.#t.prepare(t);return{run:(...e)=>s.run(...e),get:(...e)=>s.get(...e),all:(...e)=>s.all(...e),iterate:(...e)=>typeof s.iterate=="function"?s.iterate(...e):s.all(...e)[Symbol.iterator]()}}transaction(t){return(...s)=>{this.#t.exec("BEGIN");try{let e=t(...s);return this.#t.exec("COMMIT"),e}catch(e){throw this.#t.exec("ROLLBACK"),e}}}close(){this.#t.close()}},c=null;function O(){if(!c){let n=R(import.meta.url);if(globalThis.Bun){let t=n(["bun","sqlite"].join(":")).Database;c=function(e,r){let o=new t(e,{readonly:r?.readonly,create:!0}),a=new l(o);return r?.timeout&&a.pragma(`busy_timeout = ${r.timeout}`),a}}else if(process.platform==="linux")try{let{DatabaseSync:t}=n(["node","sqlite"].join(":"));c=function(e,r){let o=new t(e,{readOnly:r?.readonly??!1});return new p(o)}}catch{c=n("better-sqlite3")}else c=n("better-sqlite3")}return c}function g(n){n.pragma("journal_mode = WAL"),n.pragma("synchronous = NORMAL")}function h(n){if(!v(n))for(let t of["-wal","-shm"])try{T(n+t)}catch{}}function D(n){for(let t of["","-wal","-shm"])try{T(n+t)}catch{}}function _(n){try{n.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{n.close()}catch{}}function y(n="context-mode"){return w(N(),`${n}-${process.pid}.db`)}function b(n,t=[100,500,2e3]){let s;for(let e=0;e<=t.length;e++)try{return n()}catch(r){let o=r instanceof Error?r.message:String(r);if(!o.includes("SQLITE_BUSY")&&!o.includes("database is locked"))throw r;if(s=r instanceof Error?r:new Error(o),e<t.length){let a=t[e],u=Date.now();for(;Date.now()-u<a;);}}throw new Error(`SQLITE_BUSY: database is locked after ${t.length} retries. Original error: ${s?.message}`)}function I(n){return n.includes("SQLITE_CORRUPT")||n.includes("SQLITE_NOTADB")||n.includes("database disk image is malformed")||n.includes("file is not a database")}function C(n){let t=Date.now();for(let s of["","-wal","-shm"])try{L(n+s,`${n}${s}.corrupt-${t}`)}catch{}}var d=Symbol.for("__context_mode_live_dbs__"),m=(()=>{let n=globalThis;return n[d]||(n[d]=new Set,process.on("exit",()=>{for(let t of n[d])_(t);n[d].clear()})),n[d]})(),E=class{#t;#e;constructor(t){let s=O();this.#t=t,h(t);let e;try{e=new s(t,{timeout:3e4}),g(e)}catch(r){let o=r instanceof Error?r.message:String(r);if(I(o)){C(t),h(t);try{e=new s(t,{timeout:3e4}),g(e)}catch(a){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${a instanceof Error?a.message:String(a)}`)}}else throw r}this.#e=e,m.add(this.#e),this.initSchema(),this.prepareStatements()}get db(){return this.#e}get dbPath(){return this.#t}close(){m.delete(this.#e),_(this.#e)}withRetry(t){return b(t)}cleanup(){m.delete(this.#e),_(this.#e),D(this.#t)}};import{createHash as S}from"node:crypto";import{execFileSync as A}from"node:child_process";function Y(){let n=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(n!==void 0)return n?`__${n}`:"";try{let t=process.cwd(),s=A("git",["worktree","list","--porcelain"],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).split(/\r?\n/).find(e=>e.startsWith("worktree "))?.replace("worktree ","")?.trim();if(s&&t!==s)return`__${S("sha256").update(t).digest("hex").slice(0,8)}`}catch{}return""}var x=1e3,M=5,i={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions"},f=class extends E{constructor(t){super(t?.dbPath??y("session"))}stmt(t){return this.stmts.get(t)}initSchema(){try{let s=this.db.pragma("table_xinfo(session_events)").find(e=>e.name==="data_hash");s&&s.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
|
|
1
|
+
import{createRequire as R}from"node:module";import{existsSync as v,unlinkSync as T,renameSync as L}from"node:fs";import{tmpdir as N}from"node:os";import{join as w}from"node:path";var l=class{#t;constructor(t){this.#t=t}pragma(t){let e=this.#t.prepare(`PRAGMA ${t}`).all();if(!e||e.length===0)return;if(e.length>1)return e;let r=Object.values(e[0]);return r.length===1?r[0]:e[0]}exec(t){let s="",e=null;for(let o=0;o<t.length;o++){let a=t[o];if(e)s+=a,a===e&&(e=null);else if(a==="'"||a==='"')s+=a,e=a;else if(a===";"){let u=s.trim();u&&this.#t.prepare(u).run(),s=""}else s+=a}let r=s.trim();return r&&this.#t.prepare(r).run(),this}prepare(t){let s=this.#t.prepare(t);return{run:(...e)=>s.run(...e),get:(...e)=>{let r=s.get(...e);return r===null?void 0:r},all:(...e)=>s.all(...e),iterate:(...e)=>s.iterate(...e)}}transaction(t){return this.#t.transaction(t)}close(){this.#t.close()}},p=class{#t;constructor(t){this.#t=t}pragma(t){let e=this.#t.prepare(`PRAGMA ${t}`).all();if(!e||e.length===0)return;if(e.length>1)return e;let r=Object.values(e[0]);return r.length===1?r[0]:e[0]}exec(t){return this.#t.exec(t),this}prepare(t){let s=this.#t.prepare(t);return{run:(...e)=>s.run(...e),get:(...e)=>s.get(...e),all:(...e)=>s.all(...e),iterate:(...e)=>typeof s.iterate=="function"?s.iterate(...e):s.all(...e)[Symbol.iterator]()}}transaction(t){return(...s)=>{this.#t.exec("BEGIN");try{let e=t(...s);return this.#t.exec("COMMIT"),e}catch(e){throw this.#t.exec("ROLLBACK"),e}}}close(){this.#t.close()}},c=null;function O(){if(!c){let n=R(import.meta.url);if(globalThis.Bun){let t=n(["bun","sqlite"].join(":")).Database;c=function(e,r){let o=new t(e,{readonly:r?.readonly,create:!0}),a=new l(o);return r?.timeout&&a.pragma(`busy_timeout = ${r.timeout}`),a}}else if(process.platform==="linux")try{let{DatabaseSync:t}=n(["node","sqlite"].join(":"));c=function(e,r){let o=new t(e,{readOnly:r?.readonly??!1});return new p(o)}}catch{c=n("better-sqlite3")}else c=n("better-sqlite3")}return c}function g(n){n.pragma("journal_mode = WAL"),n.pragma("synchronous = NORMAL");try{n.pragma("mmap_size = 268435456")}catch{}}function h(n){if(!v(n))for(let t of["-wal","-shm"])try{T(n+t)}catch{}}function D(n){for(let t of["","-wal","-shm"])try{T(n+t)}catch{}}function _(n){try{n.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{n.close()}catch{}}function y(n="context-mode"){return w(N(),`${n}-${process.pid}.db`)}function b(n,t=[100,500,2e3]){let s;for(let e=0;e<=t.length;e++)try{return n()}catch(r){let o=r instanceof Error?r.message:String(r);if(!o.includes("SQLITE_BUSY")&&!o.includes("database is locked"))throw r;if(s=r instanceof Error?r:new Error(o),e<t.length){let a=t[e],u=Date.now();for(;Date.now()-u<a;);}}throw new Error(`SQLITE_BUSY: database is locked after ${t.length} retries. Original error: ${s?.message}`)}function I(n){return n.includes("SQLITE_CORRUPT")||n.includes("SQLITE_NOTADB")||n.includes("database disk image is malformed")||n.includes("file is not a database")}function C(n){let t=Date.now();for(let s of["","-wal","-shm"])try{L(n+s,`${n}${s}.corrupt-${t}`)}catch{}}var d=Symbol.for("__context_mode_live_dbs__"),m=(()=>{let n=globalThis;return n[d]||(n[d]=new Set,process.on("exit",()=>{for(let t of n[d])_(t);n[d].clear()})),n[d]})(),E=class{#t;#e;constructor(t){let s=O();this.#t=t,h(t);let e;try{e=new s(t,{timeout:3e4}),g(e)}catch(r){let o=r instanceof Error?r.message:String(r);if(I(o)){C(t),h(t);try{e=new s(t,{timeout:3e4}),g(e)}catch(a){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${a instanceof Error?a.message:String(a)}`)}}else throw r}this.#e=e,m.add(this.#e),this.initSchema(),this.prepareStatements()}get db(){return this.#e}get dbPath(){return this.#t}close(){m.delete(this.#e),_(this.#e)}withRetry(t){return b(t)}cleanup(){m.delete(this.#e),_(this.#e),D(this.#t)}};import{createHash as S}from"node:crypto";import{execFileSync as A}from"node:child_process";function Y(){let n=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(n!==void 0)return n?`__${n}`:"";try{let t=process.cwd(),s=A("git",["worktree","list","--porcelain"],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).split(/\r?\n/).find(e=>e.startsWith("worktree "))?.replace("worktree ","")?.trim();if(s&&t!==s)return`__${S("sha256").update(t).digest("hex").slice(0,8)}`}catch{}return""}var x=1e3,M=5,i={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions"},f=class extends E{constructor(t){super(t?.dbPath??y("session"))}stmt(t){return this.stmts.get(t)}initSchema(){try{let s=this.db.pragma("table_xinfo(session_events)").find(e=>e.name==="data_hash");s&&s.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
|
|
2
2
|
CREATE TABLE IF NOT EXISTS session_events (
|
|
3
3
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
4
4
|
session_id TEXT NOT NULL,
|
package/openclaw.plugin.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "Context Mode",
|
|
4
4
|
"kind": "tool",
|
|
5
5
|
"description": "OpenClaw plugin that saves 98% of your context window. Sandboxed code execution in 11 languages, FTS5 knowledge base with BM25 ranking, and intent-driven search.",
|
|
6
|
-
"version": "1.0.
|
|
6
|
+
"version": "1.0.79",
|
|
7
7
|
"sandbox": {
|
|
8
8
|
"mode": "permissive",
|
|
9
9
|
"filesystem_access": "full",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "context-mode",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.79",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "MCP plugin that saves 98% of your context window. Works with Claude Code, Gemini CLI, VS Code Copilot, OpenCode, and Codex CLI. Sandboxed code execution, FTS5 knowledge base, and intent-driven search.",
|
|
6
6
|
"author": "Mert Koseoğlu",
|
package/server.bundle.mjs
CHANGED
|
@@ -125,7 +125,7 @@ FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
|
|
|
125
125
|
${n}`;case"elixir":return`file_content_path = ${o}
|
|
126
126
|
file_path = file_content_path
|
|
127
127
|
file_content = File.read!(file_content_path)
|
|
128
|
-
${n}`}}};import{createRequire as SC}from"node:module";import{existsSync as kC,unlinkSync as Ex,renameSync as bL}from"node:fs";var hp=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},gp=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},Qn=null;function _s(){if(!Qn){let t=SC(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Qn=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new hp(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(process.platform==="linux")try{let{DatabaseSync:e}=t(["node","sqlite"].join(":"));Qn=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1});return new gp(s)}}catch{Qn=t("better-sqlite3")}else Qn=t("better-sqlite3")}return Qn}function _p(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL")}function yp(t){if(!kC(t))for(let e of["-wal","-shm"])try{Ex(t+e)}catch{}}function Tx(t){for(let e of["","-wal","-shm"])try{Ex(t+e)}catch{}}function xp(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function eo(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function $x(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}var gs=Symbol.for("__context_mode_live_dbs__"),wL=(()=>{let t=globalThis;return t[gs]||(t[gs]=new Set,process.on("exit",()=>{for(let e of t[gs])xp(e);t[gs].clear()})),t[gs]})();import{readFileSync as bC,readdirSync as Cx,unlinkSync as Sp,existsSync as Px,statSync as vp}from"node:fs";import{tmpdir as Ix}from"node:os";import{join as kp}from"node:path";var Rx=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);function wC(t,e="AND"){let r=t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(n=>n.length>0&&!["AND","OR","NOT","NEAR"].includes(n.toUpperCase()));return r.length===0?'""':r.map(n=>`"${n}"`).join(e==="OR"?" OR ":" ")}function EC(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=r.split(/\s+/).filter(o=>o.length>=3);return n.length===0?"":n.map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function TC(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function $C(t){return t<=4?1:t<=12?2:3}var Ox=4096;function bp(){let t=Ix(),e=0;try{let r=Cx(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=kp(t,n);for(let a of["","-wal","-shm"])try{Sp(i+a)}catch{}e++}}}catch{}return e}function wp(t,e){let r=0;try{if(!Px(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=Cx(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=kp(t,s),c=vp(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Px(u))try{let l=vp(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Sp(i+u)}catch{}r++}}catch{}}catch{}return r}function PC(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function RC(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(o=>[...o].sort((s,i)=>s-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var ya=class{#e;#t;#r;#n;#s;#i;#o;#a;#c;#d;#p;#f;#m;#h;#g;#_;#y;#x;#v;#S;#k;#b;#w;#E;#T;#$;#P;#R;#O;constructor(e){let r=_s();this.#t=e??kp(Ix(),`context-mode-${process.pid}.db`),yp(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),_p(n)}catch(o){let s=o instanceof Error?o.message:String(o);if($x(s)){Tx(this.#t),yp(this.#t);try{n=new r(this.#t,{timeout:3e4}),_p(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#
|
|
128
|
+
${n}`}}};import{createRequire as SC}from"node:module";import{existsSync as kC,unlinkSync as Ex,renameSync as bL}from"node:fs";var hp=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},gp=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},Qn=null;function _s(){if(!Qn){let t=SC(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Qn=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new hp(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(process.platform==="linux")try{let{DatabaseSync:e}=t(["node","sqlite"].join(":"));Qn=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1});return new gp(s)}}catch{Qn=t("better-sqlite3")}else Qn=t("better-sqlite3")}return Qn}function _p(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function yp(t){if(!kC(t))for(let e of["-wal","-shm"])try{Ex(t+e)}catch{}}function Tx(t){for(let e of["","-wal","-shm"])try{Ex(t+e)}catch{}}function xp(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function eo(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function $x(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}var gs=Symbol.for("__context_mode_live_dbs__"),wL=(()=>{let t=globalThis;return t[gs]||(t[gs]=new Set,process.on("exit",()=>{for(let e of t[gs])xp(e);t[gs].clear()})),t[gs]})();import{readFileSync as bC,readdirSync as Cx,unlinkSync as Sp,existsSync as Px,statSync as vp}from"node:fs";import{tmpdir as Ix}from"node:os";import{join as kp}from"node:path";var Rx=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);function wC(t,e="AND"){let r=t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(n=>n.length>0&&!["AND","OR","NOT","NEAR"].includes(n.toUpperCase()));return r.length===0?'""':r.map(n=>`"${n}"`).join(e==="OR"?" OR ":" ")}function EC(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=r.split(/\s+/).filter(o=>o.length>=3);return n.length===0?"":n.map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function TC(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function $C(t){return t<=4?1:t<=12?2:3}var Ox=4096;function bp(){let t=Ix(),e=0;try{let r=Cx(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=kp(t,n);for(let a of["","-wal","-shm"])try{Sp(i+a)}catch{}e++}}}catch{}return e}function wp(t,e){let r=0;try{if(!Px(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=Cx(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=kp(t,s),c=vp(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Px(u))try{let l=vp(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Sp(i+u)}catch{}r++}}catch{}}catch{}return r}function PC(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function RC(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(o=>[...o].sort((s,i)=>s-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var ya=class t{#e;#t;#r;#n;#s;#i;#o;#a;#c;#d;#p;#f;#m;#h;#g;#_;#y;#x;#v;#S;#k;#b;#w;#E;#T;#$;#P;#R;#O;#C=0;static OPTIMIZE_EVERY=50;constructor(e){let r=_s();this.#t=e??kp(Ix(),`context-mode-${process.pid}.db`),yp(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),_p(n)}catch(o){let s=o instanceof Error?o.message:String(o);if($x(s)){Tx(this.#t),yp(this.#t);try{n=new r(this.#t,{timeout:3e4}),_p(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#M(),this.#D()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Sp(this.#t+e)}catch{}}#M(){this.#e.exec(`
|
|
129
129
|
CREATE TABLE IF NOT EXISTS sources (
|
|
130
130
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
131
131
|
label TEXT NOT NULL,
|
|
@@ -155,7 +155,7 @@ ${n}`}}};import{createRequire as SC}from"node:module";import{existsSync as kC,un
|
|
|
155
155
|
);
|
|
156
156
|
|
|
157
157
|
CREATE INDEX IF NOT EXISTS idx_sources_label ON sources(label);
|
|
158
|
-
`)}#
|
|
158
|
+
`)}#D(){this.#r=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count) VALUES (?, 0, 0)"),this.#n=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count) VALUES (?, ?, ?)"),this.#s=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type) VALUES (?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type) VALUES (?, ?, ?, ?)"),this.#o=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#a=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#c=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#d=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#p=this.#e.prepare(`
|
|
159
159
|
SELECT
|
|
160
160
|
chunks.title,
|
|
161
161
|
chunks.content,
|
|
@@ -320,16 +320,16 @@ ${n}`}}};import{createRequire as SC}from"node:module";import{existsSync as kC,un
|
|
|
320
320
|
(SELECT COUNT(*) FROM sources) AS sources,
|
|
321
321
|
(SELECT COUNT(*) FROM chunks) AS chunks,
|
|
322
322
|
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
|
|
323
|
-
`)}index(e){let{content:r,path:n,source:o}=e;if(!r&&!n)throw new Error("Either content or path must be provided");let s=r??bC(n,"utf-8"),i=o??n??"untitled",a=this.#
|
|
323
|
+
`)}index(e){let{content:r,path:n,source:o}=e;if(!r&&!n)throw new Error("Either content or path must be provided");let s=r??bC(n,"utf-8"),i=o??n??"untitled",a=this.#Z(s);return eo(()=>this.#u(a,i,s))}indexPlainText(e,r,n=20){if(!e||e.trim().length===0)return this.#u([],r,"");let o=this.#U(e,n);return eo(()=>this.#u(o.map(s=>({...s,hasCode:!1})),r,e))}indexJSON(e,r,n=Ox){if(!e||e.trim().length===0)return this.indexPlainText("",r);let o;try{o=JSON.parse(e)}catch{return this.indexPlainText(e,r)}let s=[];return this.#j(o,[],s,n),s.length===0?this.indexPlainText(e,r):eo(()=>this.#u(s,r,e))}#u(e,r,n){let o=e.filter(a=>a.hasCode).length,i=this.#e.transaction(()=>{if(this.#a.run(r),this.#c.run(r),this.#d.run(r),e.length===0){let u=this.#r.run(r);return Number(u.lastInsertRowid)}let a=this.#n.run(r,e.length,o),c=Number(a.lastInsertRowid);for(let u of e){let l=u.hasCode?"code":"prose";this.#s.run(u.title,u.content,c,l),this.#i.run(u.title,u.content,c,l)}return c})();return n&&this.#L(n),this.#C++,this.#C%t.OPTIMIZE_EVERY===0&&this.#A(),{sourceId:i,label:r,totalChunks:e.length,codeChunks:o}}#I(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted}))}#l(e,r){return r==="exact"?e:`%${e}%`}search(e,r=3,n,o="AND",s,i="like"){let a=wC(e,o),c,u;return n&&s?(c=i==="exact"?this.#S:this.#v,u=[a,this.#l(n,i),s,r]):n?(c=i==="exact"?this.#m:this.#f,u=[a,this.#l(n,i),r]):s?(c=this.#x,u=[a,s,r]):(c=this.#p,u=[a,r]),eo(()=>this.#I(c.all(...u)))}searchTrigram(e,r=3,n,o="AND",s,i="like"){let a=EC(e,o);if(!a)return[];let c,u;return n&&s?(c=i==="exact"?this.#w:this.#b,u=[a,this.#l(n,i),s,r]):n?(c=i==="exact"?this.#_:this.#g,u=[a,this.#l(n,i),r]):s?(c=this.#k,u=[a,s,r]):(c=this.#h,u=[a,r]),eo(()=>this.#I(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;let n=$C(r.length),o=this.#y.all(r.length-n,r.length+n),s=null,i=n+1;for(let{word:a}of o){if(a===r)return null;let c=TC(r,a);c<i&&(i=c,s=a)}return i<=n?s:null}#z(e,r,n,o,s="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",o,s),u=this.searchTrigram(e,a,n,"OR",o,s),l=new Map,d=f=>`${f.source}::${f.title}`;for(let[f,m]of c.entries()){let p=d(m),h=l.get(p);h?h.score+=1/(60+f+1):l.set(p,{result:m,score:1/(60+f+1)})}for(let[f,m]of u.entries()){let p=d(m),h=l.get(p);h?h.score+=1/(60+f+1):l.set(p,{result:m,score:1/(60+f+1)})}return Array.from(l.values()).sort((f,m)=>m.score-f.score).slice(0,r).map(({result:f,score:m})=>({...f,rank:-m}))}#N(e,r){let n=r.toLowerCase().split(/\s+/).filter(o=>o.length>=2);return e.map(o=>{let s=o.title.toLowerCase(),i=n.filter(l=>s.includes(l)).length,a=o.contentType==="code"?.6:.3,c=i>0?a*(i/n.length):0,u=0;if(n.length>=2){let l=o.content.toLowerCase(),d=n.map(f=>PC(l,f));d.some(f=>f.length===0)||(u=1/(1+RC(d)/Math.max(l.length,1)))}return{result:o,boost:c+u}}).sort((o,s)=>s.boost-o.boost||o.result.rank-s.result.rank).map(({result:o})=>o)}searchWithFallback(e,r=3,n,o,s="like"){let i=this.#z(e,r,n,o,s);if(i.length>0)return this.#N(i,e).map(f=>({...f,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(d=>d.length>=3),c=a.join(" "),l=a.map(d=>this.fuzzyCorrect(d)??d).join(" ");if(l!==c){let d=this.#z(l,r,n,o,s);if(d.length>0)return this.#N(d,l).map(m=>({...m,matchLayer:"rrf-fuzzy"}))}return[]}getSourceMeta(e){let r=this.#O.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at}:null}listSources(){return this.#E.all()}getChunksBySource(e){return this.#T.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#$.get(e);if(!n||n.chunk_count<3)return[];let o=n.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#P.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(f=>f.length>=3&&!Rx.has(f)));for(let f of d)a.set(f,(a.get(f)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let f=Math.log(o/d),m=Math.min(l.length/20,.5),p=/[_]/.test(l),h=l.length>=12,g=p?1.5:h?.8:0;return{word:l,score:f+m+g}}).sort((l,d)=>d.score-l.score).slice(0,r).map(l=>l.word)}getStats(){let e=this.#R.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){let r=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),n=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),o=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')");return this.#e.transaction(a=>(r.run(a),n.run(a),o.run(a)))(e).changes}getDBSizeBytes(){try{return vp(this.#t).size}catch{return 0}}#A(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#A(),xp(this.#e)}#L(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(o=>o.length>=3&&!Rx.has(o)),n=[...new Set(r)];this.#e.transaction(()=>{for(let o of n)this.#o.run(o)})()}#Z(e,r=Ox){let n=[],o=e.split(`
|
|
324
324
|
`),s=[],i=[],a="",c=()=>{let l=i.join(`
|
|
325
|
-
`).trim();if(l.length===0)return;let d=this.#
|
|
325
|
+
`).trim();if(l.length===0)return;let d=this.#B(s,a),f=i.some(_=>/^`{3,}/.test(_));if(Buffer.byteLength(l)<=r){n.push({title:d,content:l,hasCode:f}),i=[];return}let m=l.split(/\n\n+/),p=[],h=1,g=()=>{if(p.length===0)return;let _=p.join(`
|
|
326
326
|
|
|
327
327
|
`).trim();if(_.length===0)return;let v=m.length>1?`${d} (${h})`:d;h++,n.push({title:v,content:_,hasCode:_.includes("```")}),p=[]};for(let _ of m){p.push(_);let v=p.join(`
|
|
328
328
|
|
|
329
|
-
`);Buffer.byteLength(v)>r&&p.length>1&&(p.pop(),g(),p=[_])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let m=d[1].length,p=d[2].trim();for(;s.length>0&&s[s.length-1].level>=m;)s.pop();s.push({level:m,text:p}),a=p,i.push(l),u++;continue}let f=l.match(/^(`{3,})(.*)?$/);if(f){let m=f[1],p=[l];for(u++;u<o.length;){if(p.push(o[u]),o[u].startsWith(m)&&o[u].trim()===m){u++;break}u++}i.push(...p);continue}i.push(l),u++}return c(),n}#
|
|
329
|
+
`);Buffer.byteLength(v)>r&&p.length>1&&(p.pop(),g(),p=[_])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let m=d[1].length,p=d[2].trim();for(;s.length>0&&s[s.length-1].level>=m;)s.pop();s.push({level:m,text:p}),a=p,i.push(l),u++;continue}let f=l.match(/^(`{3,})(.*)?$/);if(f){let m=f[1],p=[l];for(u++;u<o.length;){if(p.push(o[u]),o[u].startsWith(m)&&o[u].trim()===m){u++;break}u++}i.push(...p);continue}i.push(l),u++}return c(),n}#U(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let l=c.trim();return{title:l.split(`
|
|
330
330
|
`)[0].slice(0,80)||`Section ${u+1}`,content:l}}).filter(c=>c.content.length>0);let o=e.split(`
|
|
331
331
|
`);if(o.length<=r)return[{title:"Output",content:e}];let s=[],a=Math.max(r-2,1);for(let c=0;c<o.length;c+=a){let u=o.slice(c,c+r);if(u.length===0)break;let l=c+1,d=Math.min(c+u.length,o.length),f=u[0]?.trim().slice(0,80);s.push({title:f||`Lines ${l}-${d}`,content:u.join(`
|
|
332
|
-
`)})}return s}#
|
|
332
|
+
`)})}return s}#j(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#j(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#q(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#H(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#F(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#q(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#H(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#F(s,c,l,a,i);n.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#B(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}};import{readFileSync as Nx}from"node:fs";import{resolve as to}from"node:path";import{homedir as Ax}from"node:os";function jx(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function OC(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function CC(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function zx(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function IC(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let o=t.slice(0,n),s=t.slice(n+1),i=CC(o),a=zx(s);r=`^${i}(\\s${a})?$`}else r=`^${zx(t)}$`;return new RegExp(r,e?"i":"")}function zC(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function NC(t,e,r=!1){for(let n of e){let o=jx(n);if(o&&IC(o,r).test(t))return n}return null}function AC(t){let e=[],r="",n=!1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!o&&!s&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!s&&c!=="\\"?(o=!o,r+=a):a==="`"&&!n&&!o&&c!=="\\"?(s=!s,r+=a):!n&&!o&&!s?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function Ep(t){let e;try{e=Nx(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&jx(i)!==null):[];return{allow:o(n.allow),deny:o(n.deny),ask:o(n.ask)}}function Tp(t,e){let r=[];if(t){let s=to(t,".claude","settings.local.json"),i=Ep(s);i&&r.push(i);let a=to(t,".claude","settings.json"),c=Ep(a);c&&r.push(c)}let n=e??to(Ax(),".claude","settings.json"),o=Ep(n);return o&&r.push(o),r}function Mx(t,e,r){let n=[],o=a=>{let c;try{c=Nx(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.deny;if(!Array.isArray(l))return[];let d=[];for(let f of l){if(typeof f!="string")continue;let m=OC(f);m&&m.tool===t&&d.push(m.glob)}return d};if(e){let a=o(to(e,".claude","settings.local.json"));a!==null&&n.push(a);let c=o(to(e,".claude","settings.json"));c!==null&&n.push(c)}let s=r??to(Ax(),".claude","settings.json"),i=o(s);return i!==null&&n.push(i),n}function $p(t,e,r=process.platform==="win32"){let n=AC(t);for(let o of n)for(let s of e){let i=NC(o,s.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Dx(t,e,r=process.platform==="win32"){let n=t.replace(/\\/g,"/");for(let o of e)for(let s of o)if(zC(s,r).test(n))return{denied:!0,matchedPattern:s};return{denied:!1}}var jC={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]};function MC(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let s=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function Lx(t,e){let r=jC[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let o of r){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&n.push(i)}}return e==="python"&&n.push(...MC(t)),n}function Pp(t){let{language:e,exitCode:r,stdout:n,stderr:o}=t,s=e==="shell"&&r===1&&n.trim().length>0;return{isError:!s,output:s?n:`Exit code: ${r}
|
|
333
333
|
|
|
334
334
|
stdout:
|
|
335
335
|
${n}
|