context-mode 2.0.0-next.37 → 2.0.0-next.39

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/hook.mjs CHANGED
@@ -24,7 +24,7 @@ Run the command on the line above with Bash instead. It runs the same command in
24
24
  `,Nd=`
25
25
  `;function Gt(e){let t=e.length>0&&e.charCodeAt(0)===65279?e.slice(1):e;return t.indexOf(cc)<0?t:t.split(cc).join(Nd)}import{basename as z_,dirname as J_,join as ac,posix as $_,resolve as Q_,win32 as Z_}from"node:path";var yd=Object.freeze({NODE_TOO_OLD:"Node <v> is below 24.15.0. Fix: install Node 24.15.0 or later.",NO_SQLITE:"node:sqlite failed to load. Fix: run ctx_doctor.",DB_GONE:"context.db is gone and its WAL file is still in place. Fix: run ctx_doctor once; it keeps the WAL file in a dated folder and starts a new index.",NO_PROJECT:"Project source <kind> is missing. Fix: run ctx_doctor.",UNKNOWN_FIELD:'Unknown field "<f>". Fix: use "queries".',TIMEOUT:"Timed out after <ms> ms. Fix: pass background: true.",NO_GIT_BASH:"Git Bash not found. Fix: install Git for Windows.",NO_RUNTIME:"No <lang> runtime on PATH. Fix: install it or pick another language.",FETCH_FAILED:"Fetch failed: <code>. Fix: check the URL or proxy.",SSRF:"Blocked private address <host>. Fix: use a public URL.",OUTSIDE_ROOT:"Path <p> is outside the project. Fix: use a path inside <root>.",INVALID_ARGS:"Invalid argument <field>. Fix: <action>.",ONE_OF_INPUT:"Pass exactly one of <names>. Fix: drop the extra field.",SPAWN_FAILED:"Failed to start the process: <detail>. Fix: check the command and PATH.",DB_CORRUPT:"context.db failed integrity_check. Fix: run ctx_doctor.",SCHEMA_STALE:"context.db schema is version <found>, expected <want>. Fix: run ctx_doctor.",NO_GIT_DIR:"No git repository at <path>. Fix: run context-mode inside a git repository.",NO_HOME:"Env var <name> is not set. Fix: set <name> to your home directory.",PLUGIN_ROOT_MISSING:"Plugin root for <agent> not found at <path>. Fix: run ctx_upgrade.",BUNDLE_HASH_MISMATCH:"Fetched bundle hash does not match SHA256SUMS. Fix: run ctx_upgrade again.",CONFIG_PARSE_FAILED:"<agent> config at <path> did not parse as <format>. Fix: fix the syntax error and re-run ctx_upgrade."});function Id(e,t){let n=yd[e],o="",r=0;for(;r<n.length;){if(n[r]!=="<"){o+=n[r],r+=1;continue}let s=r+1;for(;s<n.length&&n[s]!=="<"&&n[s]!==">";)s+=1;if(s>=n.length){o+=n.slice(r);break}if(n[s]==="<"){o+="<",r+=1;continue}let i=n.slice(r+1,s),c=t[i];if(c===void 0)throw new Error("formatError: missing var "+i+" for "+e);o+=String(c),r=s+1}return o}var T=class extends Error{code;vars;constructor(t,n){super(Id(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{mkdirSync:Cd,realpathSync:kd}=process.getBuiltinModule("node:fs");function me(e,t=process.platform){let n=o=>o!==void 0&&o!=="";return t==="win32"?n(e.USERPROFILE)?e.USERPROFILE:n(e.HOMEDRIVE)&&n(e.HOMEPATH)?e.HOMEDRIVE+e.HOMEPATH:n(e.HOME)?e.HOME:null:n(e.HOME)?e.HOME:n(e.USERPROFILE)?e.USERPROFILE:null}function Be(e,t){let n=e[ht];return n!==void 0&&n!==""?n:ac(t,...Os["claude-code"])}function Dd(e,t=process.platform){let n=me(e,t);if(n!==null)return n;throw new T("NO_HOME",{name:t==="win32"?"USERPROFILE":"HOME"})}function lc(e){let t=ac(Dd(e),ct.slice(1));return Cd(t,{recursive:!0}),kd.native(t)}var{readFileSync:xc}=process.getBuiltinModule("node:fs");function he(e){return e.agentId!==void 0&&e.agentId!==""}function go(e,t){if(t===null)return"C";let n=re(e.agent),o=new Set(t);for(let r of ot)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function mo(e,t){if(!he(e))return null;let n=re(e.agent);if(t.manifestTools!==void 0)return fc(t.manifestTools.map(c=>_o(n,c)));let o=e.agentType??"",r=Ld(o,t);if(r===null)return null;let s=(r.tools??Hd(n)).map(c=>_o(n,c)),i=r.disallowed.map(c=>_o(n,c));return fc(s.filter(c=>!i.some(a=>vd(a,c))))}function Ld(e,t){if(!wd(e))return null;let n=Pd(t.env);if(e.indexOf(de)>=0){if(n!==null){let s=Md(Be(t.env,n),e);if(s!==null)return s}}else{let s=Eo(Bt(t.projectDir,Tr,at,e+lt));if(s!==null)return s;if(n!==null){let i=Eo(Bt(Be(t.env,n),at,e+lt));if(i!==null)return i}}let r=t.cliAgents;if(r!==void 0&&Object.prototype.hasOwnProperty.call(r,e)){let s=r[e];return{tools:Array.isArray(s.tools)?s.tools:null,disallowed:Array.isArray(s.disallowedTools)?s.disallowedTools:[]}}return null}function wd(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(de))if(t===""||t==="."||t==="..")return!1;return!0}function Pd(e){return me(e)}function Md(e,t){let n=t.indexOf(de),o=t.slice(0,n),r=t.slice(n+de.length);if(r.indexOf(de)>=0)return null;let s;try{s=JSON.parse(Gt(xc(Bt(e,hn,Rr),"utf8")))}catch{return null}let i=s?.plugins;if(i===null||typeof i!="object")return null;for(let c of Object.keys(i)){let a=c.indexOf(Ar);if((a<0?c:c.slice(0,a))!==o)continue;let l=i[c];if(Array.isArray(l))for(let u of l){let d=u?.installPath;if(typeof d!="string"||d==="")continue;let f=Eo(Bt(d,at,r+lt));if(f!==null)return f}}return null}function Eo(e){let t;try{t=xc(e,"utf8")}catch{return null}return Ud(t)}function Ud(e){let t=e.split(`
26
26
  `).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==Sn)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===Sn){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=uc(o,Nr),s=uc(o,yr);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function uc(e,t){for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(t+":"))continue;let r=o.slice(t.length+1).trim();if(r===""){let s=[];for(let i=n+1;i<e.length;i++){let c=e[i].trim();if(!c.startsWith("-"))break;s.push(dc(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>dc(s.trim())).filter(s=>s!=="")}return null}function dc(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function Hd(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...ot.map(n=>e.toolNamePrefix+n)]}function _o(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(Ir)?Fd(o):o}function Fd(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||Cr.indexOf(n)>=0;t+=o?n:"_"}return t}function vd(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith(bn)){let n=e.slice(bn.length);if(n!==""&&n.indexOf(On)<0)return t.startsWith(e+On)}return!1}function fc(e){return[...new Set(e.filter(t=>t!==""))]}var ce="",pc=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:ce},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:ce},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:ce},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:ce},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:ce},command:{valueShorts:ce,valueLongs:[],assignments:!1,duration:!1,refuseShorts:"vV"},xargs:{valueShorts:"aEdILnPs",valueLongs:["--arg-file","--delimiter","--max-args","--max-procs","--max-chars"],assignments:!1,duration:!1,refuseShorts:ce}}),jd=["bash","sh","zsh"],Gd="c",Bd=" -c",Wd=["-o","+o","-O","+O"],Wt="-",Xd="+",ho="--",Kd="smhd",qd=".",_c=e=>e!==""&&e>="0"&&e<="9";function Yd(e){if(e===""||!_c(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(_c(n)||n===qd))return t===e.length-1&&Kd.includes(n)}return!0}function Vd(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===ho){n++;break}if(e.assignments&&Pt(o)){n++;continue}if(o.startsWith(ho)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(Wt)&&o.length>Wt.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=Wt.length;r<o.length;r++)if(e.valueShorts.includes(o.charAt(r))){r===o.length-1&&n++;break}continue}break}if(e.duration){if(n>=t.length||!Yd(t[n]))return null;n++}return n<t.length?t.slice(n):null}function zd(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(ho)){if(o.startsWith(Wt)||o.startsWith(Xd)){o.includes(Gd)&&(t=!0),Wd.includes(o)&&n++;continue}return t?o:null}}return null}function Ec(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function So(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let a=s.toLowerCase();if(jd.includes(a)){let d=zd(i),f=d!==null&&n<H?ve(d):null;if(f===null||!f.ok)break;for(let x of f.commands){let p=Ec(x,e);p.redirectsToFile=x.redirectsToFile||c,p.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,So(p,[...r,a+Bd],n+1,o)}return}let l=Object.hasOwn(pc,a)?pc[a]:void 0,u=l===void 0?null:Vd(l,i);if(u===null)break;r.push(a),s=so(u[0]),i=u.slice(1),c=c||io(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=H))for(let a of wt(e.raw)){let l=ve(a.body);if(l.ok)for(let u of l.commands)So(Ec(u,e),[...t,a.wrapper],n+1,o)}}function gc(e){let t=[];for(let n of e)So(n,[],0,t);return t}import{isAbsolute as $d,join as bo,relative as Qd,sep as Oo}from"node:path";var{readFileSync:Jd}=process.getBuiltinModule("node:fs"),mc=".claude",Zd="settings.local.json",hc="settings.json",ef="Bash",tf="Read",Sc=":*",bc="//",Oc="~/",Tc="./",Rc="..",nf=`
27
- \r`,of=Object.freeze({tool:ef});function rf(e,t){if(t!=="claude-code")return[];let n=me(process.env),o=process.env[ht],r=o!==void 0&&o!==""?o:n===null?null:Be(process.env,n),s=[bo(e,mc,Zd),bo(e,mc,hc)];return r===null?s:[...s,bo(r,hc)]}function Ac(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sf(e){let t;try{t=Gt(Jd(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Ac(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Ac(o))return{kind:"bad"};let r=o.deny;return r===void 0?{kind:"ok",deny:[]}:!Array.isArray(r)||!r.every(s=>typeof s=="string")?{kind:"bad"}:{kind:"ok",deny:r}}function Nc(e,t){let n=[];for(let o of rf(e,t)){let r=sf(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function cf(e,t){let n=[],o=0;for(;o<e.length;){let r=e[o];if(r==="*"&&t&&e[o+1]==="*"){let s=e[o+2]==="/";n.push({t:s?"globstarDir":"globstar"}),o+=s?3:2;continue}r==="*"?(n.length===0||n[n.length-1].t!=="star")&&n.push({t:"star"}):r==="?"?n.push({t:"any1"}):n.push({t:"lit",c:r}),o++}return n}function Y(e,t,n){let o=cf(e,n),r=t.length,s=new Uint8Array(r+1);s[r]=1;for(let i=o.length-1;i>=0;i--){let c=o[i],a=new Uint8Array(r+1),l=0;for(let u=r;u>=0;u--){let d=u<r,f=d?t[u]:"";switch(c.t){case"lit":a[u]=d&&f===c.c?s[u+1]:0;break;case"any1":a[u]=d&&!(n&&f==="/")?s[u+1]:0;break;case"star":a[u]=s[u]||(d&&!(n&&f==="/")?a[u+1]:0);break;case"globstar":a[u]=s[u]||(d?a[u+1]:0);break;case"globstarDir":d&&f==="/"&&s[u+1]&&(l=1),a[u]=s[u]||l;break}}s=a}return s[0]===1}function af(e){let t=e.indexOf("(");if(t<1||!e.endsWith(")"))return null;let n=e.slice(t+1,e.length-1);return n===""?null:{tool:e.slice(0,t),glob:n}}function lf(e,t){if(!e.endsWith(Sc))return Y(e,t,!1);let n=e.slice(0,e.length-Sc.length);if(Y(n,t,!1))return!0;for(let o=0;o<t.length;o++)if(nf.includes(t[o])&&Y(n,t.slice(0,o),!1))return!0;return!1}var uf=/^[A-Za-z]:(?=\/)/;function We(e){return Oo==="/"?e:e.split(Oo).join("/")}function df(e,t,n){if(e.startsWith(Tc)){if(n===void 0)return!1;let r=Qd(n,t);return r===""||r===Rc||r.startsWith(Rc+Oo)||$d(r)?!1:Y(e.slice(Tc.length),We(r),!0)}let o=We(t);if(e.startsWith(bc)){let r=We(e.slice(bc.length-1));return Y(r,o,!0)||Y(r,o.replace(uf,""),!0)}if(e.startsWith(Oc)){let r=me(process.env);return r!==null&&Y(We(r)+e.slice(Oc.length-1),o,!0)}return Y(We(e),o,!0)}function V(e,t,n=of){for(let o of t){let r=af(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===tf?df(r.glob,e,n.projectDir):lf(r.glob,e))return o}return null}var mE=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),yc='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var ff="{size}",xf="{path}";function Xt(e,t,n=""){return k(yc,n).split(ff).join(String(t)).split(xf).join(e)}var{statSync:pf}=process.getBuiltinModule("node:fs"),Dc="Bash",Ro="Read",_f="WebFetch",Ef="ctx_execute",gf="ctx_batch",Lc="shell",mf="1",z="-",Ao="--",hf="=",Sf=".",Ic=",",To="p",bf=["-e","--expression"],Of=";&|(`\n\r",le=Object.freeze({kind:"allow"}),G=e=>({kind:"deny",reason:e}),ae=e=>typeof e=="string"?e:void 0,Cc=e=>e!=null,J=(e,t)=>e.includes(t);function wc(e,t,n){let o=e.tool;if(o===void 0)return le;let r=o.canonicalName,s=o.input,i;if(n===null){if(process.env[Or]===mf)return G(k(ut,t.toolNamePrefix));process.stderr.write(Yr+`
27
+ \r`,of=Object.freeze({tool:ef});function rf(e,t){if(t!=="claude-code")return[];let n=me(process.env),o=process.env[ht],r=o!==void 0&&o!==""?o:n===null?null:Be(process.env,n),s=[bo(e,mc,Zd),bo(e,mc,hc)];return r===null?s:[...s,bo(r,hc)]}function Ac(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sf(e){let t;try{t=Gt(Jd(e,"utf8"))}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Ac(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Ac(o))return{kind:"bad"};let r=o.deny;return r===void 0?{kind:"ok",deny:[]}:!Array.isArray(r)||!r.every(s=>typeof s=="string")?{kind:"bad"}:{kind:"ok",deny:r}}function Nc(e,t){let n=[];for(let o of rf(e,t)){let r=sf(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function cf(e,t){let n=[],o=0;for(;o<e.length;){let r=e[o];if(r==="*"&&t&&e[o+1]==="*"){let s=e[o+2]==="/";n.push({t:s?"globstarDir":"globstar"}),o+=s?3:2;continue}r==="*"?(n.length===0||n[n.length-1].t!=="star")&&n.push({t:"star"}):r==="?"?n.push({t:"any1"}):n.push({t:"lit",c:r}),o++}return n}function Y(e,t,n){let o=cf(e,n),r=t.length,s=new Uint8Array(r+1);s[r]=1;for(let i=o.length-1;i>=0;i--){let c=o[i],a=new Uint8Array(r+1),l=0;for(let u=r;u>=0;u--){let d=u<r,f=d?t[u]:"";switch(c.t){case"lit":a[u]=d&&f===c.c?s[u+1]:0;break;case"any1":a[u]=d&&!(n&&f==="/")?s[u+1]:0;break;case"star":a[u]=s[u]||(d&&!(n&&f==="/")?a[u+1]:0);break;case"globstar":a[u]=s[u]||(d?a[u+1]:0);break;case"globstarDir":d&&f==="/"&&s[u+1]&&(l=1),a[u]=s[u]||l;break}}s=a}return s[0]===1}function af(e){let t=e.indexOf("(");if(t<1||!e.endsWith(")"))return null;let n=e.slice(t+1,e.length-1);return n===""?null:{tool:e.slice(0,t),glob:n}}function lf(e,t){if(!e.endsWith(Sc))return Y(e,t,!1);let n=e.slice(0,e.length-Sc.length);if(Y(n,t,!1))return!0;for(let o=0;o<t.length;o++)if(nf.includes(t[o])&&Y(n,t.slice(0,o),!1))return!0;return!1}var uf=/^[A-Za-z]:(?=\/)/;function We(e){return Oo==="/"?e:e.split(Oo).join("/")}function df(e,t,n){if(e.startsWith(Tc)){if(n===void 0)return!1;let r=Qd(n,t);return r===""||r===Rc||r.startsWith(Rc+Oo)||$d(r)?!1:Y(e.slice(Tc.length),We(r),!0)}let o=We(t);if(e.startsWith(bc)){let r=We(e.slice(bc.length-1));return Y(r,o,!0)||Y(r,o.replace(uf,""),!0)}if(e.startsWith(Oc)){let r=me(process.env);return r!==null&&Y(We(r)+e.slice(Oc.length-1),o,!0)}return Y(We(e),o,!0)}function V(e,t,n=of){for(let o of t){let r=af(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===tf?df(r.glob,e,n.projectDir):lf(r.glob,e))return o}return null}var mE=Object.freeze({ctx_execute:'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',ctx_batch:'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',ctx_index:'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',ctx_search:'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',ctx_resume:"Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",ctx_stats:"Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",ctx_doctor:"Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",ctx_upgrade:"Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",ctx_purge:'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'}),yc='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var ff="{size}",xf="{path}";function Xt(e,t,n=""){return k(yc,n).split(ff).join(String(t)).split(xf).join(e)}var{statSync:pf}=process.getBuiltinModule("node:fs"),Dc="Bash",Ro="Read",_f="WebFetch",Ef="ctx_execute",gf="ctx_batch",Lc="shell",mf="1",z="-",Ao="--",hf="=",Sf=".",Ic=",",To="p",bf=["-e","--expression"],Of=";&|(`\n\r",le=Object.freeze({kind:"allow"}),G=e=>({kind:"deny",reason:e}),ae=e=>typeof e=="string"?e:void 0,Cc=e=>e!=null,J=(e,t)=>e.includes(t);function wc(e,t,n){let o=e.tool;if(o===void 0)return le;let r=o.canonicalName,s=o.input,i;if(n===null){if(process.env[Or]===mf)return G(k(ut,t.toolNamePrefix));process.stderr.write(Yr+`
28
28
  `),i=[]}else i=n;let c=Tf(r,s,e.cwd,i);return c!==null?G(Ne+c):r===_f?yf(s,t):r===Dc?If(e,t,s,i):r===Ro?Pf(e,t,s):le}function Pc(e,t,n,o){let r=e==="webfetch",s=r?Ur.map(c=>n.toolNamePrefix+c).join(qr):n.toolNamePrefix+Mr,i=JSON.stringify(r?{url:t}:{language:Lc,code:t,intent:o??Pr});return[Tn+kr[e]+Dr,Lr,wr+s,i].join(`
29
29
  `)}function Mc(e){for(let t of xt){let n=ae(e[t]);if(n!==void 0&&n!=="")return n}}function Tf(e,t,n,o){if(o.length===0)return null;let r=s=>V(qt(n,s),o,{tool:Ro,projectDir:n});if(e===Dc){let s=ae(t.command);return s===void 0?null:V(s,o)}if(e===Ro){let s=Mc(t);return s===void 0?null:r(s)}if(e===Ef){let s=ae(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=ae(t.code);return t.language===Lc&&c!==void 0?V(c,o):null}if(e===gf&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?V(s,o):null;if(i!==null)return i}return null}function Rf(e,t){return t.length===0?null:V([e.argv0,...e.args].join(" "),t)??V(e.raw,t)}function Af(e,t){if(t.length===0)return!1;for(let n=0;n<=e.length;n++)if(!(n>0&&!Of.includes(e.charAt(n-1)))&&V(e.slice(n).trimStart(),t)!==null)return!0;return!1}function Nf(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return Vr.some(n=>t===n||t.endsWith(Sf+n))}function yf(e,t){let n=ae(e.url)??"";return Nf(n)?le:G(Pc("webfetch",n,t))}function If(e,t,n,o){let r=ae(n.command)??"",s=ve(r);if(!s.ok)return Af(r,o)?G(k(dt,t.toolNamePrefix)):kc(r,e.cwd,t)??le;let i=gc(s.commands);for(let c of i){let a=Rf(c,o);if(a!==null)return G(Ne+a)}if(!Le(t)||he(e))for(let c of i){let a=Cf(c);if(a!==null)return G(Pc(a,r,t,ae(n.description)))}return Mf(i,e.cwd,t)??kc(r,e.cwd,t)??le}function Cf(e){let t=e.argv0.toLowerCase();return J(zr,t)&&kf(t,e)?"curl":Lf(e.raw)?"http":J(Zr,t)?"build":null}function kf(e,t){return t.redirectsToFile?!Df(e,t.args):!t.endsInBoundedSink}function Df(e,t){let n=Jr[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===Ao)break;if(J($r,s)||s===Qr&&t[r+1]===z)return!1;(s===n.long||s.startsWith(z)&&!s.startsWith(Ao)&&s.includes(n.short,z.length))&&(o=!0)}return o}function Lf(e){let t=e.toLowerCase();for(let n of ns)if(t.includes(n))return!0;for(let n=t.indexOf(Ie);n>=0;n=t.indexOf(Ie,n+1)){let o=t.charAt(n+Ie.length);if(o!==""&&es.includes(o)&&t.startsWith(ts,n+Ie.length+o.length))return!0}return!1}var wf="cd";function No(e){try{let t=pf(e);return t.isFile()?t.size:-1}catch{return-1}}function Pf(e,t,n){if(!Cc(n.offset)&&!Cc(n.limit)){let o=Mc(n);if(o!==void 0){let r=qt(e.cwd,o),s=No(r);if(s>K)return G(Xt(r,s,t.toolNamePrefix))}}return le}function Mf(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&Vn(n))return null;let o=t,r=null;for(let s of e){let i=s.argv0.toLowerCase();if(i===wf&&s.args.length===1&&s.insideConstruct===void 0&&(o=qt(o,s.args[0])),s.redirectsToFile||s.endsInBoundedSink||s.pipesOut===!0||s.insideConstruct!==void 0||!J(os,i))continue;let c=Ff(i,s.args);if(c===null)continue;if(c.bounded){r=le;continue}let a=qt(o,c.file),l=No(a);if(l>K)return G(Xt(a,l,n.toolNamePrefix))}return r}function kc(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&Vn(n))return null;for(let o of ic(e,t)){let r=No(o);if(r>K)return G(Xt(o,r,n.toolNamePrefix))}return null}var Kt=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function Uf(e){if(J(An,e))return 1;for(let t of An)if(t.startsWith(Ao)?e.startsWith(t+hf):e.startsWith(t))return 0;return e.startsWith(z)&&Kt(e.slice(z.length))?0:-1}function Hf(e){if(e===To)return"all";if(!e.endsWith(To))return null;let t=e.slice(0,e.length-To.length),n=t.indexOf(Ic);return(n<0?Kt(t):Kt(t.slice(0,n))&&Kt(t.slice(n+Ic.length)))?"range":null}function Ff(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(J(rs,e)){let a=Uf(c);if(a>=0){o=!0,i+=a;continue}}if(e===ft&&J(ss,c)){r=!0;continue}if(e===ft&&J(bf,c)){s=t[i+1],i++;continue}c.startsWith(z)&&c!==z||n.push(c)}if(e===ft){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:Hf(s);if(i===null)return null;o=i==="range"}return e===is&&n.shift()!==D.identity?null:n.length===1&&n[0]!==z?{file:n[0],bounded:o}:null}import{basename as Yf,dirname as Vt,join as Ke,resolve as jc}from"node:path";import{dirname as Uc,sep as jf}from"node:path";var{realpathSync:vf}=process.getBuiltinModule("node:fs");function Gf(e){try{return vf.native(e)}catch{return}}function Yt(e){return e.split(jf).filter(t=>t!=="")}function Hc(e){let t=e.map(Gf).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=Yt(n).length;for(let s of t){let i=Yt(s),c=Yt(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;Yt(r).length>o&&Uc(r)!==r;)r=Uc(r);return r}var Bf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Wf=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],w=(e,t)=>e>>>t|e<<32-t;function Fc(e){let t=Buffer.from(e,"utf8"),n=t.length*8,o=Math.ceil((t.length+9)/64)*64,r=Buffer.alloc(o);t.copy(r),r[t.length]=128,r.writeUInt32BE(Math.floor(n/4294967296),o-8),r.writeUInt32BE(n>>>0,o-4);let s=Wf.slice(),i=new Uint32Array(64);for(let c=0;c<o;c+=64){for(let E=0;E<16;E++)i[E]=r.readUInt32BE(c+E*4);for(let E=16;E<64;E++){let h=w(i[E-15],7)^w(i[E-15],18)^i[E-15]>>>3,S=w(i[E-2],17)^w(i[E-2],19)^i[E-2]>>>10;i[E]=i[E-16]+h+i[E-7]+S>>>0}let[a,l,u,d,f,x,p,g]=s;for(let E=0;E<64;E++){let h=g+(w(f,6)^w(f,11)^w(f,25))+(f&x^~f&p)+Bf[E]+i[E]>>>0,S=(w(a,2)^w(a,13)^w(a,22))+(a&l^a&u^l&u)>>>0;g=p,p=x,x=f,f=d+h>>>0,d=u,u=l,l=a,a=h+S>>>0}s[0]=s[0]+a>>>0,s[1]=s[1]+l>>>0,s[2]=s[2]+u>>>0,s[3]=s[3]+d>>>0,s[4]=s[4]+f>>>0,s[5]=s[5]+x>>>0,s[6]=s[6]+p>>>0,s[7]=s[7]+g>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:Xf,readFileSync:Kf,realpathSync:vc,statSync:qf}=process.getBuiltinModule("node:fs");function Vf(e){switch(e){case"claude-code":return"env:CLAUDE_PROJECT_DIR";case"codex":case"copilot-cli":case"kiro":return"arg:--agent+cwd";case"vscode":return"arg:workspaceFolder";case"gemini":case"qwen":case"zcode":case"opencode":return"spawn-cwd";case"pi":return"pi:ctx.cwd"}}function Xe(e){return e===void 0||e===""?void 0:e}function zf(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return Xe(t.env.CLAUDE_PROJECT_DIR)??Xe(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return Xe(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(it);return n<0?void 0:Xe(t.argv[n+1])}case"pi:ctx.cwd":return Xe(t.piCwd)}}function Jf(e){let t;try{t=vc.native(e)}catch{throw new T("NO_GIT_DIR",{path:e})}let n=t;for(;;){let o=$f(Ke(t,En));if(o!==null){let s=Gc(Ke(o,hr));return{commonDir:vc.native(s===null?o:jc(o,s)),worktree:t,start:n}}let r=Vt(t);if(r===t)return{commonDir:null,start:n};t=r}}function $f(e){let t;try{if(qf(e).isDirectory())t=e;else{let n=Gc(e);if(n===null||!n.startsWith(mn))return null;t=jc(Vt(e),n.slice(mn.length))}}catch{return null}return Xf(Ke(t,Sr))?t:null}function Gc(e){let t;try{t=Kf(e,"utf8")}catch{return null}let n=t.indexOf(`
30
30
  `),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function Qf(e,t){let{spawnSync:n}=process.getBuiltinModule("node:child_process"),o=n("git",t,{cwd:e,shell:!1,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});if(o.error!==void 0||o.status!==0)throw new T("NO_GIT_DIR",{path:e});return o.stdout.split(`
@@ -135,7 +135,7 @@ INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VAL
135
135
  AND (:source IS NULL OR s.label = :source)
136
136
  AND (:ids IS NULL OR s.id IN (SELECT value FROM json_each(:ids)))
137
137
  ${ta}`,oa=`
138
- ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,Eg=`
138
+ ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,gg=`
139
139
  WITH m AS (${na}
140
140
  ), r AS (
141
141
  SELECT *,
@@ -144,11 +144,11 @@ WITH m AS (${na}
144
144
  FROM m
145
145
  )
146
146
  SELECT rid, source_id, session_id, worktree, ord, full, 1.0 / (:k + rank_a) + 1.0 / (:k + rank_b) AS score
147
- FROM r${oa}`,gg=`
147
+ FROM r${oa}`,mg=`
148
148
  WITH m AS (${na}
149
149
  )
150
150
  SELECT rid, source_id, session_id, worktree, ord, full, -bm AS score
151
- FROM m${oa}`;var mg=`
151
+ FROM m${oa}`;var hg=`
152
152
  SELECT t.rowid AS rid, c.source_id AS source_id, c.session_id AS session_id, c.worktree AS worktree, c.ord AS ord
153
153
  FROM chunks_tri t JOIN chunks c ON c.rowid = t.rowid JOIN sources s ON s.id = c.source_id
154
154
  WHERE chunks_tri MATCH :match
@@ -159,7 +159,7 @@ WHERE chunks_tri MATCH :match
159
159
  ${ta}
160
160
  ORDER BY bm25(chunks_tri, 1.0, ${ea}) ASC, c.source_id DESC, c.ord ASC`;var R0="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",A0="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function ra(e,t,n){let o=Do(e,t,n);return ia(e,o,t,n),o}function Do(e,t,n){let o=0;for(let r of n)o+=r.bytes;return P(e,r=>{let s=r.raw.prepare(O0).get({session_id:t.sessionId,worktree:t.worktree,agent:t.agent,kind:t.kind,label:t.label,bytes_total:o,chunk_count:n.length,created_ts:t.createdAt,created_at:new Date(t.createdAt).toISOString()});return Number(s.id)})}function sa(e,t,n,o,r){try{ia(e,t,n,o),wo(e,t,n.sessionId,r)}catch(s){throw P(e,i=>{N0(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function ia(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>un&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)P(e,a=>{let l=a.raw.prepare(T0),u=a.raw.prepare(R0);for(let d of c){let f=d.title??"",x=l.run(t,n.sessionId,n.worktree,n.agent,d.ord,d.text,f).lastInsertRowid;u.run(x,d.text,f)}})}function N0(e,t){if(t==="all")return e.exec("INSERT INTO chunks_tri(chunks_tri) VALUES ('delete-all')"),e.exec("DELETE FROM line_units"),Number(e.prepare("DELETE FROM chunks").run().changes);let[n,o]="sourceId"in t?["source_id = ?",t.sourceId]:["source_id IN (SELECT id FROM sources WHERE label = ?)",t.label];return e.prepare(A0+" WHERE "+n).run(o),e.prepare("DELETE FROM line_units WHERE "+n).run(o),Number(e.prepare("DELETE FROM chunks WHERE "+n).run(o).changes)}function Lo(e){let t=[],n="";for(let o of e)o.trim()===""||o==="\0"?(n!==""&&t.push(n),n=""):n+=o==='"'?'""':o;return n!==""&&t.push(n),t.map(o=>`"${o}"*`).join(" ")}function y0(e){return[...new Set(Lo(e).split(" ").filter(n=>n!==""))].join(" OR ")}var I0=new Set(["a","an","the","and","or","of","to","in","on","at","by","is","be","it","as","do","i","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","who","did","get","got","let","she","too","will","with","this","that","from","they","been","have","some","them","than","each","into","your","could","would","about","which","their","there","other","should","also","very","when","what","then","these","those","being","does","both","while","where","here","were","much","any","my","me","we"]);function C0(e){let t=[...new Set(Lo(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!I0.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var Zt=`
161
161
  AND (:scope <> 'session' OR session_id = :session_id)
162
- AND (:scope <> 'worktree' OR worktree = :worktree)`,hg=`
162
+ AND (:scope <> 'worktree' OR worktree = :worktree)`,Sg=`
163
163
  WITH e AS (
164
164
  SELECT seq, kind, key, path, body, created_at FROM events
165
165
  WHERE created_at > :after${Zt}
@@ -167,7 +167,7 @@ WITH e AS (
167
167
  )
168
168
  SELECT seq, kind, key, path, body, created_at FROM e
169
169
  WHERE created_at <= IFNULL((SELECT created_at FROM e ORDER BY created_at, seq LIMIT 1 OFFSET :off), created_at)
170
- ORDER BY created_at ASC, seq ASC`,Sg=`
170
+ ORDER BY created_at ASC, seq ASC`,bg=`
171
171
  WITH s AS (
172
172
  SELECT id, label, created_ts FROM sources
173
173
  WHERE created_ts > :after${Zt}
@@ -176,7 +176,7 @@ WITH s AS (
176
176
  )
177
177
  SELECT id, label, created_ts FROM s
178
178
  WHERE created_ts <= IFNULL((SELECT created_ts FROM s ORDER BY created_ts, id LIMIT 1 OFFSET :off), created_ts)
179
- ORDER BY created_ts ASC, id ASC`;var bg=`
179
+ ORDER BY created_ts ASC, id ASC`;var Og=`
180
180
  SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${Zt} AND (:source IS NULL OR kind = :source))
181
181
  OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${Zt} AND (:source IS NULL OR label = :source)
182
182
  AND label <> :reserved) AS more`;var k0=`CREATE VIRTUAL TABLE r USING fts5(body, ${Jt}, content='')`,D0="INSERT INTO r(rowid, body) VALUES (?, ?)",L0="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function W(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?y0(t):Lo(t);if(r===""||e.length===0)return o;let s=process.getBuiltinModule("node:sqlite");if(s===void 0)throw new T("NO_SQLITE");let i=new s.DatabaseSync(":memory:");try{i.exec(k0);let c=i.prepare(D0);i.exec("BEGIN");for(let a=0;a<e.length;a++)c.run(a+1,e[a]);i.exec("COMMIT");for(let a of i.prepare(L0).all(r))o[Number(a.id)-1]=-a.bm;return o}finally{i.close()}}var w0="s";function ca(e){return w0+e.toString(36)}function wo(e,t,n,o){let r=0;for(;r<o.length;){let s=r,i=0;for(;s<o.length&&(s===r||i+o[s].body.length<=un);)i+=o[s].body.length,s++;let c=r;P(e,a=>{let l=a.raw.prepare("INSERT INTO line_units(body, source_id, session_id, ord) VALUES (?, ?, ?, ?)");for(let u=c;u<s;u++){let d=o[u];l.run(d.body,t,n,d.ord)}}),r=s}}function aa(e,t){return t===e?e:e+" "+t}function la(e,t,n,o){let r=C0(n).join(" OR ");return r===""||t===""?[]:e.raw.prepare("SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? ORDER BY bm25(line_units) LIMIT ?").all(r,t,o).map(i=>({sourceId:Number(i.source_id),ord:Number(i.ord),label:i.label,body:i.body,score:i.score}))}function P0(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function Po(e){let t=e.split(`
@@ -34,6 +34,7 @@ function REPLACE_HANDLE_LINE(intent, handle, bytes5, prefix = "", asked = "") {
34
34
  var HANDLE_PROMPT_WORDS = 3;
35
35
  var MAX_CHUNK_BYTES = 4096;
36
36
  var SEARCH_PAGE_SIZE = 20;
37
+ var MEMORY_LABEL_PREFIX = "memory ";
37
38
  var SEARCH_REPLY_HITS = 5;
38
39
  var SNIPPET_MAX_BYTES = 800;
39
40
  var SNIPPET_CODE_MAX_BYTES = 2048;
@@ -425,7 +426,7 @@ var DECISION_OPTION_KEY = "option";
425
426
  var DECISION_LABEL_JOIN = " | ";
426
427
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
427
428
  var RELEASE_BRANCH = "release";
428
- var BUNDLE_SHA = true ? "2ed67370714045804b7620af1f3af2c9eabc1713" : void 0;
429
+ var BUNDLE_SHA = true ? "1fdd9889d173fa80227ade07d30705291f097df5" : void 0;
429
430
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
430
431
  var DOCTOR_LABEL = Object.freeze({
431
432
  D1: "version",
@@ -3747,7 +3748,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
3747
3748
  ctx_execute: 'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',
3748
3749
  ctx_batch: 'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',
3749
3750
  ctx_index: 'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',
3750
- ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',
3751
+ ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',
3751
3752
  ctx_resume: "Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",
3752
3753
  ctx_stats: "Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",
3753
3754
  ctx_doctor: "Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",
@@ -7076,7 +7077,7 @@ function ftsQueryTimeline(db, scope, ctx, sessionId, limit, after, source, memor
7076
7077
  }
7077
7078
  }
7078
7079
  for (const m of memory) {
7079
- if (m.ts > from && (source === void 0 || m.label === source)) merged.push(m);
7080
+ if (m.ts > from && (source === void 0 || m.label === source || MEMORY_LABEL_PREFIX + m.label === source)) merged.push(m);
7080
7081
  }
7081
7082
  merged.sort(timelineOrder);
7082
7083
  let end = Math.min(limit, merged.length);
@@ -20222,17 +20223,29 @@ function runProcess(argv, o) {
20222
20223
  }
20223
20224
 
20224
20225
  // src/core/index/auto-memory.ts
20225
- import { readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
20226
+ import { readdirSync, readFileSync as readFileSync5, statSync as statSync4 } from "node:fs";
20226
20227
  import { join as join7 } from "node:path";
20227
- var CLAUDE_CODE_MEMORY_FILES = Object.freeze([
20228
+ var MEMORY_FILES = Object.freeze([
20228
20229
  Object.freeze(["CLAUDE.md"]),
20229
20230
  Object.freeze(["CLAUDE.local.md"]),
20230
- Object.freeze([".claude", "CLAUDE.md"])
20231
+ Object.freeze([".claude", "CLAUDE.md"]),
20232
+ Object.freeze(["AGENTS.md"]),
20233
+ Object.freeze(["GEMINI.md"]),
20234
+ Object.freeze(["QWEN.md"]),
20235
+ Object.freeze([".github", "copilot-instructions.md"])
20231
20236
  ]);
20237
+ var KIRO_STEERING = Object.freeze([".kiro", "steering"]);
20238
+ var MD = ".md";
20239
+ function steeringFiles(worktree) {
20240
+ try {
20241
+ return readdirSync(join7(worktree, ...KIRO_STEERING)).filter((n) => n.endsWith(MD)).sort().map((n) => [...KIRO_STEERING, n]);
20242
+ } catch {
20243
+ return [];
20244
+ }
20245
+ }
20232
20246
  function readAutoMemory(project) {
20233
- if (project.agent !== "claude-code") return [];
20234
20247
  const rows = [];
20235
- for (const segs of CLAUDE_CODE_MEMORY_FILES) {
20248
+ for (const segs of [...MEMORY_FILES, ...steeringFiles(project.worktree)]) {
20236
20249
  const path7 = join7(project.worktree, ...segs);
20237
20250
  if (!isInside(project.worktree, path7)) continue;
20238
20251
  try {
@@ -20252,6 +20265,24 @@ function readAutoMemory(project) {
20252
20265
  }
20253
20266
  return rows;
20254
20267
  }
20268
+ function memoryFileNamed(rows, value) {
20269
+ const v = value.split("\\").join("/");
20270
+ return rows.find((r) => r.label === v || MEMORY_LABEL_PREFIX + r.label === v) ?? null;
20271
+ }
20272
+ function memoryChunks(rows) {
20273
+ const out = [];
20274
+ rows.forEach((r, i) => {
20275
+ for (const c of chunkText(r.text, "md")) out.push({ fileNo: i + 1, label: r.label, ord: c.ord, text: c.text });
20276
+ });
20277
+ return out;
20278
+ }
20279
+ function memoryHits(chunks, q, limit) {
20280
+ if (chunks.length === 0) return [];
20281
+ const texts = chunks.map((c) => c.text);
20282
+ const any2 = rankTexts(texts, q, "any");
20283
+ const all = rankTexts(texts, q, "all");
20284
+ return chunks.map((c, i) => ({ c, s: any2[i], full: all[i] > 0 })).filter((e) => e.s > 0).sort((a, b) => Number(b.full) - Number(a.full) || b.s - a.s || a.c.fileNo - b.c.fileNo || a.c.ord - b.c.ord).slice(0, limit).map((e) => ({ sourceId: -e.c.fileNo, label: MEMORY_LABEL_PREFIX + e.c.label, ord: e.c.ord, snippet: highlight(e.c.text, q, SNIPPET_MAX_BYTES), score: e.s, full: e.full }));
20285
+ }
20255
20286
 
20256
20287
  // src/core/tools/search.ts
20257
20288
  function unknownField(issue2) {
@@ -20288,8 +20319,8 @@ function sourceCount(db, scope, ctx, source) {
20288
20319
  });
20289
20320
  return Number(row5.n);
20290
20321
  }
20291
- function zeroHits(db, scope, ctx, source, offset = 0) {
20292
- const n = sourceCount(db, scope, ctx, source);
20322
+ function zeroHits(db, scope, ctx, source, mem, offset = 0) {
20323
+ const n = sourceCount(db, scope, ctx, source) + mem.rows.length;
20293
20324
  if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
20294
20325
  return reply('No hits in scope "' + scope + '" across ' + n + " source(s).", false);
20295
20326
  }
@@ -20312,7 +20343,7 @@ function sourceCard(db, id2, input, scope, arg) {
20312
20343
  }
20313
20344
  function callText(queries, scope, source, cursor) {
20314
20345
  const src = source === void 0 ? "" : ", source:" + JSON.stringify(source);
20315
- return "ctx_search({queries:" + JSON.stringify(queries) + ", scope:" + JSON.stringify(scope) + src + ", " + cursor + "})";
20346
+ return "ctx_search({queries:" + JSON.stringify(queries) + ", scope:" + JSON.stringify(scope) + src + (cursor === "" ? "" : ", " + cursor) + "})";
20316
20347
  }
20317
20348
  function decisionQueries(input) {
20318
20349
  return input.source === DECISION_SOURCE && input.queries.length === 0 ? [""] : input.queries;
@@ -20389,14 +20420,46 @@ function replyHits(hits, size) {
20389
20420
  while (n < size && n < hits.length && hits[n].full === true) n++;
20390
20421
  return n;
20391
20422
  }
20392
- function relevance(db, given, scope, ctx, nm) {
20423
+ var MEMORY_HITS = 2;
20424
+ function mergeMemory(content, memory) {
20425
+ const out = [];
20426
+ let c = 0;
20427
+ let m = 0;
20428
+ let lastMem = true;
20429
+ while (c < content.length || m < memory.length) {
20430
+ const rank = (h) => h === void 0 ? -1 : h.full === true ? 1 : 0;
20431
+ const rc = rank(content[c]);
20432
+ const rm = rank(memory[m]);
20433
+ const mem = rc < 0 || rm > rc || rm === rc && !lastMem;
20434
+ if (mem) {
20435
+ out.push(memory[m++]);
20436
+ lastMem = true;
20437
+ } else {
20438
+ out.push(content[c++]);
20439
+ lastMem = false;
20440
+ }
20441
+ }
20442
+ return out;
20443
+ }
20444
+ var contentIn = (hits, n) => hits.slice(0, n).filter((h) => h.sourceId > 0).length;
20445
+ function relevance(db, given, scope, ctx, nm, ms, indexed) {
20393
20446
  const input = { ...given, queries: decisionQueries(given) };
20394
20447
  const offset = input.offset ?? 0;
20395
20448
  const size = pageSize(input);
20396
- const fetched = input.queries.map((q) => page(db, q, input, scope, ctx, offset, 1));
20449
+ const mem = ms.named || offset === 0 ? memoryChunks(ms.rows) : [];
20450
+ const count2 = (hits, n) => ms.named ? Math.min(n, hits.length) : contentIn(hits, n);
20451
+ const fetched = input.queries.map((q) => {
20452
+ if (ms.named) {
20453
+ const want = offset + size + 1;
20454
+ const content2 = indexed ? ftsQuery(db, q, scope, ctx.project, ctx.sessionId, want, 0, input.source) : [];
20455
+ return mergeMemory(content2, memoryHits(mem, q, want)).slice(offset, want);
20456
+ }
20457
+ const content = page(db, q, input, scope, ctx, offset, 1);
20458
+ return mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, q, MEMORY_HITS));
20459
+ });
20397
20460
  const take = fetched.map((h) => replyHits(h, size));
20398
20461
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
20399
- if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, offset);
20462
+ if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, offset);
20400
20463
  const moreLine3 = (q, pos) => "More: " + callText([q], scope, nm.arg, "offset:" + pos);
20401
20464
  let reserve = 0;
20402
20465
  for (const q of input.queries) reserve += bytes2(moreLine3(q, offset + size)) + 1;
@@ -20429,13 +20492,13 @@ function relevance(db, given, scope, ctx, nm) {
20429
20492
  }
20430
20493
  const line = shownLabel(hit.label, hit.sourceId) + " #" + hit.ord + ": " + hit.snippet;
20431
20494
  if (used + bytes2(line) + 1 + reserve > OUTPUT_CAP) {
20432
- cut = offset + i;
20495
+ cut = offset + count2(hits, i);
20433
20496
  stopped = true;
20434
20497
  break;
20435
20498
  }
20436
20499
  const room = total.get(hit.sourceId);
20437
20500
  if (room !== void 0 && mine.has(hit.sourceId) && (spent.get(hit.sourceId) ?? 0) + bytes2(line) + 1 > room * SMALL_SOURCE_SHARE * (qi + 1) / input.queries.length) {
20438
- cut = offset + i;
20501
+ cut = offset + count2(hits, i);
20439
20502
  break;
20440
20503
  }
20441
20504
  lines.push(line);
@@ -20450,7 +20513,7 @@ function relevance(db, given, scope, ctx, nm) {
20450
20513
  used += bytes2(line) + 1;
20451
20514
  }
20452
20515
  if (cut >= 0) more.push({ q, pos: cut });
20453
- else if (fetched[qi].length > take[qi]) more.push({ q, pos: offset + take[qi] });
20516
+ else if (count2(fetched[qi], fetched[qi].length) > count2(fetched[qi], take[qi])) more.push({ q, pos: offset + count2(fetched[qi], take[qi]) });
20454
20517
  });
20455
20518
  const moreLines = [];
20456
20519
  const byPos = /* @__PURE__ */ new Map();
@@ -20464,10 +20527,9 @@ function timelineLine(r) {
20464
20527
  const seq = r.seq === null ? "" : " #" + r.seq;
20465
20528
  return "[" + new Date(r.ts).toISOString() + "] " + shownLabel(r.label, r.sourceId) + seq + " " + first;
20466
20529
  }
20467
- function timeline(db, input, scope, ctx, nm) {
20468
- const memory = scope === "session" ? [] : readAutoMemory(ctx.project);
20469
- const page2 = ftsQueryTimeline(db, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, input.after ?? null, input.source, memory);
20470
- if (page2.rows.length === 0) return zeroHits(db, scope, ctx, input.source);
20530
+ function timeline(db, input, scope, ctx, nm, ms) {
20531
+ const page2 = ftsQueryTimeline(db, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, input.after ?? null, input.source, ms.rows);
20532
+ if (page2.rows.length === 0) return zeroHits(db, scope, ctx, input.source, ms);
20471
20533
  const moreLine3 = (ts) => "more: " + callText(input.queries, scope, nm.arg, 'sort:"timeline", after:' + ts);
20472
20534
  const reserve = bytes2(moreLine3(page2.rows[page2.rows.length - 1].ts)) + 1;
20473
20535
  const lines = nm.note === null ? [] : [nm.note];
@@ -20496,6 +20558,15 @@ function timeline(db, input, scope, ctx, nm) {
20496
20558
  if (more && lastTs !== null) lines.push(moreLine3(lastTs));
20497
20559
  return reply(lines.join("\n"), false);
20498
20560
  }
20561
+ function answer(db, input, scope, ctx, nm, ms, indexed, sort, pick2) {
20562
+ if (sort === "timeline") return timeline(db, input, scope, ctx, nm, ms);
20563
+ if (pick2 !== null && pick2.id !== null && input.queries.length === 0) {
20564
+ const card = sourceCard(db, pick2.id, input, scope, nm.arg);
20565
+ if (card !== null) return card;
20566
+ }
20567
+ const rows = ms.named ? null : jsonRowsReply(db, input, scope, ctx, nm);
20568
+ return rows ?? relevance(db, input, scope, ctx, nm, ms, indexed);
20569
+ }
20499
20570
  async function handler(input, ctx) {
20500
20571
  const sort = input.sort ?? "relevance";
20501
20572
  if (sort === "timeline" && input.offset !== void 0) {
@@ -20511,12 +20582,18 @@ async function handler(input, ctx) {
20511
20582
  const pick2 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given) : null;
20512
20583
  if (pick2 !== null) input = { ...input, source: pick2.label };
20513
20584
  const nm = named(given, pick2);
20514
- if (sort === "timeline") return timeline(db, input, scope, ctx, nm);
20515
- if (pick2 !== null && pick2.id !== null && input.queries.length === 0) {
20516
- const card = sourceCard(db, pick2.id, input, scope, nm.arg);
20517
- if (card !== null) return card;
20518
- }
20519
- return jsonRowsReply(db, input, scope, ctx, nm) ?? relevance(db, input, scope, ctx, nm);
20585
+ const indexed = pick2 !== null && pick2.id !== null;
20586
+ const files = scope !== "session" || given !== void 0 ? readAutoMemory(ctx.project) : [];
20587
+ const file2 = given === void 0 || given === DECISION_SOURCE ? null : memoryFileNamed(files, given);
20588
+ const ms = { rows: scope === "session" ? [] : file2 !== null ? [file2] : given === void 0 ? files : [], named: file2 !== null };
20589
+ if (file2 !== null && indexed && scope !== "session") {
20590
+ const both = "Source " + JSON.stringify(given) + ": searched the indexed source " + shownLabel(pick2.label, pick2.id) + " and the memory file " + file2.label + ".";
20591
+ nm.note = nm.note === null ? both : nm.note + "\n" + both;
20592
+ }
20593
+ const out = answer(db, input, scope, ctx, nm, ms, indexed, sort, pick2);
20594
+ if (file2 === null || scope !== "session") return out;
20595
+ const call = callText(input.queries, "worktree", nm.arg, sort === "timeline" ? 'sort:"timeline"' : "");
20596
+ return reply(out.text + "\nMemory file " + file2.label + ' is in scope "worktree": ' + call + " searches it.", out.isError);
20520
20597
  } finally {
20521
20598
  closeDb(db);
20522
20599
  }
@@ -20652,7 +20729,7 @@ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20652
20729
  function bytes3(s) {
20653
20730
  return Buffer.byteLength(s, "utf8");
20654
20731
  }
20655
- function answer(db, ctx, ownIds, queries, share, own2) {
20732
+ function answer2(db, ctx, ownIds, queries, share, own2) {
20656
20733
  const seen = /* @__PURE__ */ new Set();
20657
20734
  const lines = [];
20658
20735
  for (const [qi, q] of queries.entries()) {
@@ -20715,7 +20792,7 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20715
20792
  notice = cut === null ? stop : cause === null ? cut : cause + " " + cut;
20716
20793
  const fixed = (exitLine === null ? 0 : bytes3(exitLine) + 1) + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
20717
20794
  const share = Math.floor((OUTPUT_CAP - fixed) / queries.length);
20718
- const answered = answer(db, ctx, idx.ids, queries, share, idx.bodies);
20795
+ const answered = answer2(db, ctx, idx.ids, queries, share, idx.bodies);
20719
20796
  sections = answered.lines;
20720
20797
  const unseen = [...idx.bodies].filter(([k, text]) => text !== "" && !answered.seen.has(k)).map(([k]) => idx.raw.get(k));
20721
20798
  const unseenBytes = unseen.reduce((n, t) => n + bytes3(t) + 1, 0);
@@ -20751,15 +20828,15 @@ var ctxBatch = Object.freeze({
20751
20828
  });
20752
20829
 
20753
20830
  // src/core/tools/doctor.ts
20754
- import { readdirSync as readdirSync5, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20831
+ import { readdirSync as readdirSync6, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
20755
20832
  import { basename as basename5, dirname as dirname8, join as join16 } from "node:path";
20756
20833
 
20757
20834
  // src/core/ops/doctor-config.ts
20758
- import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
20835
+ import { existsSync as existsSync6, readdirSync as readdirSync4 } from "node:fs";
20759
20836
  import { join as join11 } from "node:path";
20760
20837
 
20761
20838
  // src/core/ops/detect-v1.ts
20762
- import { existsSync as existsSync4, opendirSync, readdirSync, readFileSync as readFileSync7 } from "node:fs";
20839
+ import { existsSync as existsSync4, opendirSync, readdirSync as readdirSync2, readFileSync as readFileSync7 } from "node:fs";
20763
20840
  import { tmpdir } from "node:os";
20764
20841
  import { join as join9 } from "node:path";
20765
20842
 
@@ -23479,7 +23556,7 @@ function scanVscode(agentHome, project, out) {
23479
23556
  }
23480
23557
  function jsonFiles(dir) {
23481
23558
  try {
23482
- return readdirSync(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
23559
+ return readdirSync2(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
23483
23560
  } catch {
23484
23561
  return [];
23485
23562
  }
@@ -23605,7 +23682,7 @@ function detectV1(agent, home, scope = {}) {
23605
23682
  }
23606
23683
 
23607
23684
  // src/core/ops/plugin-root.ts
23608
- import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23685
+ import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23609
23686
  import { dirname as dirname6, isAbsolute as isAbsolute2, join as join10, sep as sep3 } from "node:path";
23610
23687
  import { fileURLToPath } from "node:url";
23611
23688
  function missing(agent, path7) {
@@ -23705,7 +23782,7 @@ function marketplaceRoot(adapter, env, worktree) {
23705
23782
  if (ownReal !== null && cacheReal !== null && ownReal.startsWith(cacheReal + sep3) && existsSync5(join10(ownReal, SERVER_ENTRY_FILE))) return ownReal;
23706
23783
  const pattern = join10(cache, "*", PLUGIN_NAME);
23707
23784
  if (!existsSync5(cache)) throw missing(adapter.id, pattern);
23708
- const found = readdirSync2(cache).sort().map((marketplace) => join10(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync5(dir));
23785
+ const found = readdirSync3(cache).sort().map((marketplace) => join10(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync5(dir));
23709
23786
  if (found.length !== 1) throw missing(adapter.id, found.length === 0 ? pattern : found.join(", "));
23710
23787
  return found[0];
23711
23788
  }
@@ -23848,10 +23925,10 @@ function codexNativeDir(env, home) {
23848
23925
  const cache = join11(codexDir, "plugins", PLUGIN_CACHE_DIR_NAME);
23849
23926
  if (!existsSync6(cache)) return null;
23850
23927
  const found = [];
23851
- for (const market of readdirSync3(cache)) {
23928
+ for (const market of readdirSync4(cache)) {
23852
23929
  const plugin = join11(cache, market, SERVER_KEY);
23853
23930
  if (!existsSync6(plugin)) continue;
23854
- for (const version2 of readdirSync3(plugin).sort()) {
23931
+ for (const version2 of readdirSync4(plugin).sort()) {
23855
23932
  const dir = join11(plugin, version2, CODEX_PLUGIN_SUBDIR);
23856
23933
  if (existsSync6(join11(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
23857
23934
  }
@@ -24626,7 +24703,7 @@ import { existsSync as existsSync11, mkdirSync as mkdirSync5, rmSync as rmSync3
24626
24703
  import { basename as basename4, dirname as dirname7, join as join14 } from "node:path";
24627
24704
 
24628
24705
  // src/core/store/owners.ts
24629
- import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24706
+ import { mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24630
24707
  import { basename as basename3, join as join13 } from "node:path";
24631
24708
  function ownersDir(configDir, projectKey) {
24632
24709
  return join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
@@ -24649,7 +24726,7 @@ function listLiveOwners(configDir, projectKey) {
24649
24726
  const dir = ownersDir(configDir, projectKey);
24650
24727
  let names;
24651
24728
  try {
24652
- names = readdirSync4(dir);
24729
+ names = readdirSync5(dir);
24653
24730
  } catch (err) {
24654
24731
  if (errCode2(err) === "ENOENT") return [];
24655
24732
  throw err;
@@ -25047,7 +25124,7 @@ async function hookRow(ctx, adapter, host) {
25047
25124
  function ownServerId(configDir, projectKey) {
25048
25125
  const dir = join16(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
25049
25126
  if (!existsSync13(dir)) return "";
25050
- for (const name of readdirSync5(dir)) {
25127
+ for (const name of readdirSync6(dir)) {
25051
25128
  if (!name.endsWith(OWNER_PID_EXT)) continue;
25052
25129
  if (readFileSync13(join16(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
25053
25130
  }
@@ -25351,7 +25428,7 @@ import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as
25351
25428
  import { dirname as dirname10, extname, join as join19, relative as relative3, resolve as resolve7 } from "node:path";
25352
25429
 
25353
25430
  // src/core/index/walk.ts
25354
- import { readdirSync as readdirSync6, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync7 } from "node:fs";
25431
+ import { readdirSync as readdirSync7, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync7 } from "node:fs";
25355
25432
  import { join as join18 } from "node:path";
25356
25433
  var GITIGNORE = ".gitignore";
25357
25434
  var GIT_DIR = ".git";
@@ -25366,7 +25443,7 @@ function walkDir(root, containmentRoot) {
25366
25443
  function visit(abs, rel, parent, contain, seen, found) {
25367
25444
  let entries;
25368
25445
  try {
25369
- entries = readdirSync6(abs, { withFileTypes: true });
25446
+ entries = readdirSync7(abs, { withFileTypes: true });
25370
25447
  } catch {
25371
25448
  return;
25372
25449
  }
@@ -30125,7 +30202,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
30125
30202
  }
30126
30203
 
30127
30204
  // src/core/ops/plugin-swap.ts
30128
- import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
30205
+ import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync8, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
30129
30206
  import { basename as basename6, join as join21, win32 as win322 } from "node:path";
30130
30207
  function linkTarget(path7, win) {
30131
30208
  if (!isLink(path7)) return null;
@@ -30136,7 +30213,7 @@ function isLink(path7) {
30136
30213
  return lstatSync(path7, { throwIfNoEntry: false })?.isSymbolicLink() === true;
30137
30214
  }
30138
30215
  function generations(agentDir) {
30139
- return readdirSync7(agentDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).filter((name) => !name.startsWith(UPGRADE_FETCH_DIR_PREFIX) && !name.endsWith(UPGRADE_TRASH_SUFFIX)).sort();
30216
+ return readdirSync8(agentDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).filter((name) => !name.startsWith(UPGRADE_FETCH_DIR_PREFIX) && !name.endsWith(UPGRADE_TRASH_SUFFIX)).sort();
30140
30217
  }
30141
30218
  function settleLinks(link, tmp, old, opts) {
30142
30219
  if (isLink(tmp)) unlinkSync2(tmp);
@@ -30205,7 +30282,7 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
30205
30282
  }
30206
30283
 
30207
30284
  // src/core/ops/uninstall.ts
30208
- import { existsSync as existsSync19, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
30285
+ import { existsSync as existsSync19, readdirSync as readdirSync9, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
30209
30286
  import { join as join23 } from "node:path";
30210
30287
  function row2(area, before, after) {
30211
30288
  return { area, before, after };
@@ -30321,7 +30398,7 @@ function removeProjectData(configDir, projectKey) {
30321
30398
  const dir = join23(projects, projectKey);
30322
30399
  if (!existsSync19(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
30323
30400
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
30324
- for (const name of readdirSync8(dir)) {
30401
+ for (const name of readdirSync9(dir)) {
30325
30402
  if (name !== OWNERS_DIR_NAME) rmSync7(join23(dir, name), { recursive: true, force: true });
30326
30403
  }
30327
30404
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
@@ -30466,7 +30543,7 @@ function removeV1(agent, findings) {
30466
30543
 
30467
30544
  // src/core/ops/verify-sums.ts
30468
30545
  import { createHash as createHash2 } from "node:crypto";
30469
- import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "node:fs";
30546
+ import { lstatSync as lstatSync2, readdirSync as readdirSync10, readFileSync as readFileSync17 } from "node:fs";
30470
30547
  import { join as join24 } from "node:path";
30471
30548
  function mismatch() {
30472
30549
  return new CtxError("BUNDLE_HASH_MISMATCH");
@@ -30485,7 +30562,7 @@ function parseSums(text) {
30485
30562
  return sums;
30486
30563
  }
30487
30564
  function walk3(dir, prefix, out) {
30488
- for (const entry of readdirSync9(dir, { withFileTypes: true })) {
30565
+ for (const entry of readdirSync10(dir, { withFileTypes: true })) {
30489
30566
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
30490
30567
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
30491
30568
  const abs = join24(dir, entry.name);
package/package.json CHANGED
@@ -69,5 +69,5 @@
69
69
  "url": "git+https://github.com/mksglu/context-mode.git"
70
70
  },
71
71
  "type": "module",
72
- "version": "2.0.0-next.37"
72
+ "version": "2.0.0-next.39"
73
73
  }