context-mode 2.0.0-next.5 → 2.0.0-next.7
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 +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/hooks.json +50 -0
- package/.codex-plugin/mcp.json +14 -0
- package/.codex-plugin/plugin.json +12 -0
- package/SHA256SUMS +22 -16
- package/cli.mjs +196 -24
- package/codex/skills/ctx-doctor/SKILL.md +6 -0
- package/codex/skills/ctx-stats/SKILL.md +6 -0
- package/codex/skills/ctx-upgrade/SKILL.md +6 -0
- package/copilot/plugin.json +1 -1
- package/gemini-extension.json +1 -1
- package/hook.mjs +81 -81
- package/opencode/plugin.js +122 -30
- package/package.json +4 -1
- package/pi/index.js +122 -30
- package/qwen-extension.json +1 -1
- package/run.mjs +79 -16
- package/search.mjs +79 -16
- package/server.mjs +99 -26
- package/skills/ctx-doctor/SKILL.md +1 -1
- package/skills/ctx-stats/SKILL.md +1 -1
- package/skills/ctx-upgrade/SKILL.md +1 -1
package/hook.mjs
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
var
|
|
2
|
-
Run the command on the line above with Bash instead. It runs the same command in the same folder, indexes the full output and prints only the part that matches your intent, with the same exit code.`,
|
|
3
|
-
`+o}}return typeof e=="object"&&e!==null&&
|
|
4
|
-
`),keep:n}}function
|
|
5
|
-
`+t.reason});case"replace":return n&&e.event==="PostToolUse"?o({updatedToolOutput:
|
|
6
|
-
`+t.reason}),exitCode:0}:
|
|
7
|
-
`+t.reason}),exitCode:0};case"replace":return e.event!=="PostToolUse"?
|
|
8
|
-
`+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var
|
|
9
|
-
`+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function
|
|
10
|
-
`+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var
|
|
11
|
-
`,
|
|
12
|
-
`,
|
|
13
|
-
`,
|
|
14
|
-
\r;&|()<>`,
|
|
15
|
-
\r`,
|
|
16
|
-
`,s),u=l<0?e.n:l,f=e.s.slice(s,u);if(f.endsWith("\r")&&(f=f.slice(0,-1)),s=l<0?e.n:l+1,(i.strip?f.trim():f)===i.tag){a=!0;break}}if(o!==null&&r!==null&&r.push(o.length),v(o,"unhandled",e.s.slice(c,s),c,s),!a)return le(e,"unterminated-heredoc"),e.n}return n.length=0,s}function
|
|
17
|
-
`||d==="\r"){let h=c;c+=i.startsWith(
|
|
18
|
-
`&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(gn,c)||i.startsWith(vs,c)){let h=pt(e,c+gn.length,!0,o+1,null,null);v(r,"unhandled",i.slice(c,h),c,h),c=h,u=null;continue}let E=Qa(i,c);if(E!==null){v(r,"io",i.slice(c,E.end),c,E.end),u=E.op===Xa||E.op===Is?E.op===Is:null,c=E.end;continue}if(i.startsWith(ae,c)&&bn(i.charAt(c+ae.length))){let h=$a(e,c,o);if(h>0){v(r,"unhandled",i.slice(c,h),c,h),c=h,u=null;continue}}if(i.startsWith(Ne,c)){let h=Rn(i,c);if(h>0){v(r,"unhandled",i.slice(c,h),c,h),c=h,u=null;continue}}let m=ja.find(h=>i.startsWith(h,c));if(m!==void 0){if(n&&m==="("&&a++,n&&m===")"){if(a>0)a--;else if(l===0)return c+1}v(r,"op",m,c,c+m.length),c+=m.length,u=null;continue}if(d==="$"&&x==="("||d==="`"){let h=d==="`"?ue(e,c):ke(e,c,o);if(js(i.charAt(h))){v(r,"unhandled",i.slice(c,h),c,h),c=h,u=null;continue}}let _=c;c=Za(e,c,o);let S=i.slice(_,c);v(r,"word",S,_,c),u!==null&&(f.push({tag:de(S),strip:u}),u=null),n&&S===Va&&l++,n&&S===za&&l>0&&l--}return f.length>0&&le(e,"unterminated-heredoc"),e.n}function Bs(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return pt(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function de(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=D;continue}if(r==="'"){let s=e.indexOf("'",n+1),i=s<0?o:s;t+=e.slice(n+1,i),n=i+1;continue}if(r==="$"&&e.charAt(n+1)==="'"){let s=n+Hs.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=D;continue}t+=e.charAt(s),s++}n=s+1;continue}if(r==='"'){let s=n+1;for(;s<o&&e.charAt(s)!=='"';){let i=e.charAt(s+1);if(e.charAt(s)==="\\"&&i!==""&&Ja.includes(i)){t+=i,s+=D;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function Et(e){let t={s:e,n:e.length,end:"complete"},n=[],o=!1,r=0;for(;r<t.n;){let s=e.charAt(r),i=e.charAt(r+1);if(s==="\\"){r+=D;continue}if(!o&&s==="'"){r=xt(t,r);continue}if(!o&&s==="$"&&i==="'"){r=Gs(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Ms.length;continue}let c=e.startsWith(gn,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(vs,r))){let a=r+1;if(s==="$"&&e.startsWith(Ne,a)&&Rn(e,a)>0){r=a+Ne.length;continue}let l=pt(t,a+1,!0,1,null,null),u=l>a+1&&e.charAt(l-1)===")"?l-1:l;n.push({wrapper:s==="$"?"$()":c?"<()":">()",body:e.slice(a+1,u)}),r=l;continue}if(s==="`"){let a=ue(t,r),l=a>r+1&&e.charAt(a-1)==="`"?a-1:a;n.push({wrapper:"`",body:e.slice(r+1,l)}),r=a;continue}r++}return n}function mt(e){let t=e.charAt(0);if(!(Us(t)||t==="_"))return!1;for(let n=1;n<e.length;n++){let o=e.charAt(n);if(o==="="||o==="+"&&e.charAt(n+1)==="=")return!0;if(!(Us(o)||hn(o)||o==="_"))return!1}return!1}var qs=[";","&","&&","||"],Ys=["|","|&"],Ce="(",Ie=")",Js=";;",yn=["(",")"],tl="!",b=Object.freeze({group:"{",groupEnd:"}",if:"if",then:"then",elif:"elif",else:"else",fi:"fi",while:"while",until:"until",for:"for",in:"in",do:"do",done:"done",case:"case",esac:"esac",function:"function",coproc:"coproc",select:"select"}),Vs=[],nl="[[",ol="((",zs=[">",">>",">|","&>","&>>",">&"],rl=[...zs,"<","<>","<<<","<<","<<-"],sl=["","1"],$s=["-","/dev/stdout","/dev/stderr"],gt="-",De="--",we="=",il="/",cl=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),_t=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),On="-c",An="--bytes",al="c",ll="--count",ne=()=>({cmds:[],simple:null}),T=(e,t=0)=>e.toks[e.i+t],W=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,k=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,Nn=e=>e!==""&&e>="0"&&e<="9",ul=e=>Nn(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function kn(e){let t=e.lastIndexOf(il);return t>=0&&t<e.length-1?e.slice(t+1):e}function Cn(e,t){let n=cl[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===De)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+we))s=r.slice(n.long.length+we.length);else if(r.startsWith(gt)&&!r.startsWith(De)){let i=r.indexOf(n.short,gt.length);if(i<0)continue;s=i+n.short.length<r.length?r.slice(i+n.short.length):t[o+1]}else continue;if(s!==void 0&&!$s.includes(s))return!0}return!1}function dl(e){if(e==="")return!1;for(let t of e)if(!Nn(t))return!1;return!0}function fl(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===On||n===An?o=e[t+1]:n.startsWith(An+we)?o=n.slice(An.length+we.length):n.startsWith(On)&&!n.startsWith(De)&&(o=n.slice(On.length)),o!==void 0)return dl(o)&&Number(o)<=he}return!1}function xl(e){for(let t of e){if(t===De)return!1;if(t===ll||t.startsWith(gt)&&!t.startsWith(De)&&t.includes(al))return!0}return!1}function Ws(e){if(!e.startsWith(I.fieldSep))return!1;for(let t of e.slice(I.fieldSep.length).split(I.fieldSep)){if(t==="")return!1;for(let n of t)if(!ul(n))return!1}return!0}function pl(e){let t=e.trim();if(t===I.identity||t===I.length)return!0;let n=t.indexOf(I.pipeLength.charAt(0));if(n<0)return Ws(t);let o=t.slice(0,n).trim(),r=I.pipeLength.slice(1).trim();return(o===I.identity||Ws(o))&&t.slice(n+1).trim()===r}function El(e){let t=e.argv0.toLowerCase();if(t===_t.wc)return!0;if(t===_t.head)return fl(e.args);if(t===_t.grep)return xl(e.args);if(t===_t.jq){let n=e.args.filter(o=>!o.startsWith(gt));return n.length===1&&pl(n[0])}return!1}function In(e){return Et(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function Qs(e,t,n){return n<=t?[]:In(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function Zs(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function ml(e){let t=0;for(;Nn(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function ei(e){let t=ml(e.toks[e.i].text);if(e.i++,!rl.includes(t.op))return!1;let n=T(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,zs.includes(t.op)&&sl.includes(t.fd)&&!$s.includes(de(n.text)))}function ti(e){let t=!1;for(;T(e)?.kind==="io";)t=ei(e)||t;return t}function ni(e){for(;T(e)?.kind==="op"&&qs.includes(T(e)?.text??"");)e.i++}function fe(e,t){if(e.depth++,e.depth>ee)return e.err="nesting-too-deep",ne();let n=t();if(e.depth--,ti(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function oi(e){if(ni(e),!k(T(e),b.do))return[];e.i++;let t=F(e,[b.done]);return k(T(e),b.done)&&e.i++,t}function _l(e){e.i++;let t=F(e,[b.then]);for(;e.err===null;){let n=T(e);if(k(n,b.then)||k(n,b.else)){e.i++,t.push(...F(e,[b.elif,b.else,b.fi]));continue}if(k(n,b.elif)){e.i++,t.push(...F(e,[b.then]));continue}k(n,b.fi)&&e.i++;break}return t}function gl(e){e.i++;let t=F(e,[b.do]);return t.push(...oi(e)),t}function hl(e){e.i++;let t=[],n=T(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,k(T(e),b.in)){e.i++;let o=e.i;for(;(T(e)?.kind==="word"||T(e)?.kind==="unhandled")&&!k(T(e),b.do);)e.i++;t.push(...Qs(e,o,e.i))}return t.push(...oi(e)),t}function bl(e){e.i++;let t=[],n=T(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,t.push(...Qs(e,e.i-1,e.i))),k(T(e),b.in)&&e.i++;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)||o.kind==="op"&&(qs.includes(o.text)||o.text===Js)){e.i++;continue}if(k(o,b.esac)){e.i++;break}for(W(o,Ce)&&e.i++;e.i<e.toks.length&&!W(T(e),Ie);){let s=e.toks[e.i];if(s.kind==="op"&&!Ys.includes(s.text))break;e.i++}if(!W(T(e),Ie))break;e.i++;let r=F(e,[b.esac]);Zs(r,b.case),t.push(...r)}return t}function Xs(e,t){ni(e);let n=ri(e);return Zs(n.cmds,t),{cmds:n.cmds,simple:null}}function Ks(e,t){return yn.every((n,o)=>W(e.toks[t+o],n))}function Sl(e){let t=e.i,n=[],o=!1;for(;e.i<e.toks.length;){let l=e.toks[e.i];if(l.kind==="op")break;if(l.kind==="io"){o=ei(e)||o;continue}if(n.length===0&&l.kind==="word"&&mt(l.text)){e.i++;let u=T(e);if(l.text.endsWith(we)&&u!==void 0&&W(u,Ce)&&u.start===l.end){let f=0;for(;e.i<e.toks.length;){let d=e.toks[e.i];if(e.i++,W(d,Ce)&&f++,W(d,Ie)&&--f===0)break}}continue}n.push(l),e.i++}if(e.i===t)return ne();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:In(r),simple:null};let s=l=>l.kind==="word"?de(l.text):l.text,i=kn(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||Cn(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function ri(e){let t=T(e);if(t===void 0)return ne();if(t.kind==="op")return t.text!==Ce?ne():fe(e,()=>{e.i++;let n=F(e,Vs);return W(T(e),Ie)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(nl)||t.text.startsWith(ol)))return e.i++,ti(e),{cmds:In(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return fe(e,()=>{e.i++;let n=F(e,[b.groupEnd]);return k(T(e),b.groupEnd)&&e.i++,n});case b.if:return fe(e,()=>_l(e));case b.while:case b.until:return fe(e,()=>gl(e));case b.for:return fe(e,()=>hl(e));case b.case:return fe(e,()=>bl(e));case b.coproc:return e.err="coproc",ne();case b.select:return e.err="select",ne();case b.function:{e.i++;let n=T(e),o="";return n?.kind==="word"&&(o=de(n.text),e.i++),Ks(e,e.i)&&(e.i+=yn.length),Xs(e,o)}default:if(Ks(e,e.i+1))return e.i+=yn.length+1,Xs(e,de(t.text))}return Sl(e)}function Tl(e){k(T(e),tl)&&e.i++;let t=[],n=ne();for(;e.err===null;){n=ri(e),t.push(...n.cmds);let o=T(e);if(o!==void 0&&o.kind==="op"&&Ys.includes(o.text)){e.i++;continue}break}if(n.simple!==null&&El(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function F(e,t){let n=[];for(;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)){e.i++;continue}if(o.kind==="op"){if(o.text===Ie||o.text===Js)return n;if(o.text!==Ce){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;n.push(...Tl(e)),e.i===r&&e.err===null&&e.i++}return n}function Le(e){let t=Bs(e);if(t.end==="unterminated-quote")return{ok:!1,construct:"unterminated-quote"};if(t.end==="unterminated-heredoc")return{ok:!1,construct:"unterminated-heredoc"};if(t.end==="too-deep")return{ok:!1,construct:"nesting-too-deep"};let n={toks:t.tokens,src:e,bodies:new Set(t.heredocBodies),i:0,depth:0,err:null},o=[];for(;n.i<n.toks.length&&n.err===null;)o.push(...F(n,Vs)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{join as ht}from"node:path";import{join as Nl}from"node:path";var Rl=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 path vanished. Fix: run ctx_doctor.",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_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 Ol(e,t){let n=Rl[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 R=class extends Error{code;vars;constructor(t,n){super(Ol(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{mkdirSync:Al,realpathSync:yl}=process.getBuiltinModule("node:fs");function xe(e){let t=e.HOME;if(t!==void 0&&t!=="")return t;let n=e.USERPROFILE;return n!==void 0&&n!==""?n:null}function kl(e){let t=xe(e);if(t!==null)return t;throw new R("NO_HOME",{name:process.platform==="win32"?"USERPROFILE":"HOME"})}function si(e){let t=Nl(kl(e),Fo.slice(1));return Al(t,{recursive:!0}),yl.native(t)}var{readFileSync:li}=process.getBuiltinModule("node:fs");function pe(e){return e.agentId!==void 0&&e.agentId!==""}function Ln(e,t){if(t===null)return"C";let n=ye(e.agent),o=new Set(t);for(let r of Xe)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function Pn(e,t){if(!pe(e))return null;let n=ye(e.agent);if(t.manifestTools!==void 0)return ai(t.manifestTools.map(c=>Dn(n,c)));let o=e.agentType??"",r=Cl(o,t);if(r===null)return null;let s=(r.tools??Pl(n)).map(c=>Dn(n,c)),i=r.disallowed.map(c=>Dn(n,c));return ai(s.filter(c=>!i.some(a=>Ml(a,c))))}function Cl(e,t){if(!Il(e))return null;let n=Dl(t.env);if(e.indexOf(ce)>=0){if(n!==null){let s=wl(n,e);if(s!==null)return s}}else{let s=wn(ht(t.projectDir,Je,Ve,e+ze));if(s!==null)return s;if(n!==null){let i=wn(ht(n,Je,Ve,e+ze));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 Il(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(ce))if(t===""||t==="."||t==="..")return!1;return!0}function Dl(e){return xe(e)}function wl(e,t){let n=t.indexOf(ce),o=t.slice(0,n),r=t.slice(n+ce.length);if(r.indexOf(ce)>=0)return null;let s;try{s=JSON.parse(li(ht(e,Je,Go,Bo),"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(Wo);if((a<0?c:c.slice(0,a))!==o)continue;let l=i[c];if(Array.isArray(l))for(let u of l){let f=u?.installPath;if(typeof f!="string"||f==="")continue;let d=wn(ht(f,Ve,r+ze));if(d!==null)return d}}return null}function wn(e){let t;try{t=li(e,"utf8")}catch{return null}return Ll(t)}function Ll(e){let t=e.split(`
|
|
19
|
-
`).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==
|
|
20
|
-
\r`,
|
|
21
|
-
`),i=[]}else i=n;let c=
|
|
22
|
-
`)}function
|
|
23
|
-
`),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function
|
|
24
|
-
`).filter(r=>r!=="")}function
|
|
1
|
+
var ge=["claude-code","codex","gemini","qwen","copilot-cli","vscode","kiro","zcode","pi","opencode"];var Q="context-mode",Ke=Object.freeze(["ctx_execute","ctx_batch","ctx_index","ctx_search","ctx_resume","ctx_stats","ctx_doctor","ctx_upgrade","ctx_purge"]);function U(e,t){if(t==="")return e;let n=e;for(let o of Ke)n=n.split(o).join(t+o);return n}var be=16384,ho=2048;var Kc=4096,bo=640,Ft="</context_mode_state>",jt=1048576,So=65536,To=4096,Ro=96,Oo=256,Ao=48;function yo(e,t,n,o="",r=""){let s=r===""?[e]:[e,r];return o+"ctx_search({queries:["+s.map(i=>JSON.stringify(i)).join(",")+"], source:"+JSON.stringify(t)+"}) searches the whole output ("+n+" B)."}var No=3,Z=4096;var Gt=85,Bt=340,Wt=Object.freeze({toolerr:900,decision:700,prompt:500,edit:400,index:200});var Co=.7,ko=.7,Io=.3,Xt=Object.freeze([1e3,881,780,696,625,565,515,473,438,408,383,361,344,329,316,306,297,289,283,278,273,270,267,264,262,260,258,257,256,255,254,253,253,252,252,252,251,251,251,251,251,251,251,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250,250]),Do='context-mode: earlier work of this session is in ctx_resume (state block) and ctx_search(scope:"session", sort:"timeline").';var qc=6e5;var ie=5e3,qe="-wal",Ye="-shm",wo=".tmp",Lo=255,Po=11,Uo=26;var M=5e3;var Kt=0;var Mo=16,Se=5;var Ho="projects",vo="context.db";var qt=".git",Yt="worktree ",Vt="gitdir: ",Fo="commondir",jo="HEAD",Ve="--workspace-folder",gf=Object.freeze(["shell","powershell","javascript","typescript","python"]);var Go=80;var hf=Object.freeze({NO_COLOR:"1",FORCE_COLOR:"0"});var bf=Object.freeze({"claude-code":"CLAUDE_CODE_SESSION_ID"}),Jt="24.15.0",Bo="~/.context-mode";var Wo="CONTEXT_MODE_REQUIRE_SECURITY",Je=".claude",ze="agents",$e=".md",Xo="plugins",Ko="installed_plugins.json",ce=":",qo="@",zt="---",Yo="tools",Vo="disallowedTools",$t="mcp__",Qt="__",Jo="mcp_",zo="_-.:",go=10;function Yc(e){if(e===void 0||e.trim()==="")return go;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:go}var Sf=Yc(process.env.CTX_MCP_HINT_EVERY);var ee=32;var $o="context-mode: ",Qo=Object.freeze({curl:"This curl/wget call",http:"This inline HTTP call",build:"This build command",webfetch:"WebFetch"}),Zo=" sends its body into the conversation.",er="Run it here instead; the full output is indexed and only the part that matches your intent comes back.",tr="Tool: ",nr="state what you need",or="ctx_execute",rr=Object.freeze(["ctx_index","ctx_search"]),Te="Blocked by security policy: matches deny pattern ",Qe="context-mode: your deny rules could not be read. Fix: run ctx_doctor.",Ze="context-mode: could not parse this command; it may be blocked by your own rules. Run it through ctx_execute instead.",Tf=Object.freeze(["pwd","whoami","uname","id","realpath","ln"]),Rf=Object.freeze(["status"]),Of=Object.freeze(["--version","-v"]),Af=Object.freeze(["cp","mv","rm"]),yf=Object.freeze(["-v","--verbose"]),I=Object.freeze({identity:".",length:"length",pipeLength:"| length",fieldSep:"."}),sr="{prefix}",ir=", then ",cr="context-mode: your deny rules could not be read, so they are not applied. Fix: run ctx_doctor.",ar=Object.freeze(["claude.ai","claude.site","claudeusercontent.com"]),lr=Object.freeze(["curl","wget"]),ur=Object.freeze({curl:{short:"s",long:"--silent"},wget:{short:"q",long:"--quiet"}}),dr=Object.freeze(["-v","--verbose","--trace","--trace-ascii"]),fr="-D",xr=Object.freeze(["gradlew","gradle","mvnw","mvn","sbt"]),Re="fetch(",pr="'\"`",Er="http",mr=Object.freeze(["requests.get(","requests.post(","requests.put(","http.get(","http.request("]),_r=Object.freeze(["cat","head","tail","sed","less","jq","bat","more"]),gr=Object.freeze(["head","tail"]),Zt=Object.freeze(["-n","-c","--lines","--bytes"]),et="sed",hr=Object.freeze(["-n","--quiet","--silent"]),br="jq",Sr=Object.freeze(["file_path","absolute_path","path"]),Tr="ctx_",Rr="Bash",Or=Object.freeze(["Write","Edit"]),Ar=Object.freeze(["file_path","path"]),en="Exit code ",Oe="resume-hint",tn="compact-state",nn="pending-compact",tt="pending_compact:",on="1",rn=2048,sn=5,yr=340,cn="compacted:",Nr="recall_units_seen:",Cr=64,kr="recall_seen:",an="<context_mode_recall>",ln="</context_mode_recall>",Ir="recall",un="This session may have run before. Call {prefix}ctx_resume for a summary of what happened.",Dr="subagent:",wr="run.mjs",Lr="node",Pr=`context-mode: This command sends its body into the conversation.
|
|
2
|
+
Run the command on the line above with Bash instead. It runs the same command in the same folder, indexes the full output and prints only the part that matches your intent, with the same exit code.`,nt="--agent",Ur=1e3;var Nf=Object.freeze(["Scope","Produced","Returned","Saved","Reduction %"]);var Cf=Object.freeze(["session","source","project"]);var ot="decision";var dn="AskUserQuestion",Mr="answers",rt="option",Hr=" | ";var kf=Object.freeze(["D1","D2","D3","D4","D5","D5b","D6","D7","D8","D9","D10"]),If=Object.freeze({D1:"version",D2:"node",D3:"host config",D4:"old entries",D5:"hook round trip",D5b:"double-fire",D6:"MCP",D7:"project and worktree",D8:"context.db",D9:"index",D10:"enforcement mode"});var Df=`(report truncated at ${Kc} B; run ctx_doctor again after the first fix)`;var wf=`install Node ${Jt} or later`;var Lf=Object.freeze(["MCP entry","hook entries","hook timeout"]);var Vc=Object.freeze({"claude-code":[".claude"],codex:[".codex"],gemini:[".gemini"],qwen:[".qwen"],"copilot-cli":[".copilot"],vscode:[".vscode"],kiro:[".kiro"],zcode:[".zcode"],pi:[".pi"],opencode:[".config","opencode"]});var Pf=Object.freeze(["upgrade","uninstall"]);var Uf=Object.freeze(["clone","--depth","1","--branch"]),Mf=Object.freeze(["rev-parse","HEAD"]);var Hf=Object.freeze(["pi","opencode"]);var vf=Object.freeze({GIT_TERMINAL_PROMPT:"0"}),Ff=Object.freeze({GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"core.autocrlf",GIT_CONFIG_VALUE_0:"false"});var jf=Object.freeze(["doctor-env.ts","doctor-config.ts","doctor-hook.ts","doctor-db.ts","doctor-heal.ts","release-fetch.ts","verify-sums.ts","plugin-swap.ts","host-write.ts","v1-remove.ts","uninstall.ts"]);var Gf=Object.freeze({"claude-code":{root:"plugin",file:["hooks","claude-code.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},codex:{root:"home",file:[".codex","hooks.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},gemini:{root:"home",file:[".gemini","settings.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!1},qwen:{root:"home",file:[".qwen","settings.json"],key:["hooks"],shape:"nested",timeoutKey:"timeout",matcher:!0},"copilot-cli":{root:"home",file:[".copilot","hooks","context-mode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeoutSec",matcher:!1},vscode:{root:"project",file:[".github","hooks","context-mode.json"],key:["hooks"],shape:"flat",timeoutKey:"timeout",matcher:!1},kiro:{root:"home",file:[".kiro","hooks","context-mode.json"],key:["hooks"],shape:"kiro",timeoutKey:"timeout",matcher:!1},zcode:{root:"home",file:[".zcode","cli","config.json"],key:["hooks","events"],shape:"zcode",timeoutKey:"timeoutMs",matcher:!0},pi:null,opencode:null}),Bf=Object.freeze(["PreToolUse","PostToolUse"]);var Wf=Object.freeze([["@mcp","mcp"],["shell","shell"]]);var Xf=Object.freeze(["features","hooks"]);var Kf=Object.freeze(["",qe,Ye]);var qf=Object.freeze({"claude-code":"claude plugin marketplace update context-mode && claude plugin update context-mode@context-mode",codex:"rewrite config.toml's [mcp_servers.context-mode*] block to the v2 entry, then restart Codex",gemini:"gemini extensions install https://github.com/mksglu/context-mode --ref release --auto-update",qwen:"qwen extensions install https://github.com/mksglu/context-mode --ref release --auto-update"});var Yf=Object.freeze(["afteragentresponse.mjs","aftermodel.mjs","aftertool.mjs","agentspawn.mjs","beforeagent.mjs","beforetool.mjs","posttooluse.mjs","precompact.mjs","precompress.mjs","pretooluse.mjs","sessionend.mjs","sessionstart.mjs","stop.mjs","userpromptsubmit.mjs"]);var Vf=Object.freeze(["hooks","codex"]);var Jf=Object.freeze([".mjs",".sh"]);var zf=Object.freeze(["agents","default.json"]);var $f=Object.freeze(["steering","KIRO.md"]);var Qf=Object.freeze(["opencode.jsonc","opencode.json"]);var Zf=Object.freeze(["content","platform.json"]);var vr="custom";var ex=Object.freeze(["/","\\"]),he=Object.freeze({hook:"old context-mode hook entry: command contains context-mode and an old script name or context-mode hook",cacheHealHook:"old context-mode cache-heal SessionStart hook entry",cacheHealFile:"old context-mode cache-heal script file",statusLine:"old context-mode statusLine (context-mode statusline): report only, never removed",mcpEntry:"old context-mode MCP entry mcpServers.context-mode",codexHook:"old context-mode Codex hook entry: context-mode hook codex or hooks/codex/*.mjs",codexToml:"old context-mode config.toml [mcp_servers.context-mode*] section",hookFile:"old context-mode hook file context-mode.json (runs context-mode hook)",vscodeMcp:"old context-mode MCP entry servers.context-mode in .vscode/mcp.json: report only, never removed",kiroHook:"old Kiro hook entry: command contains context-mode and an old script name or context-mode hook",kiroAgentFile:"old context-mode Kiro agent file agents/*.json with name context-mode",kiroSteering:"old context-mode Kiro steering doc .kiro/steering/KIRO.md: manual review, report only, never removed",piNpm:"old context-mode Pi package npm:context-mode",opencodePlugin:"old context-mode OpenCode plugin spec context-mode",zcodeHook:"old context-mode ZCode hook entry: command contains context-mode hook",dataDir:"old context-mode data dir <agent home>/context-mode/",dataDirShared:"old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",dataRoot:"old context-mode content under ~/.context-mode/",tmpFile:"old context-mode temp file context-mode-* under the OS temp dir: report only, no action needed"}),tx=Object.freeze([he.statusLine,he.vscodeMcp,he.dataDirShared,he.tmpFile,he.kiroSteering]);var nx=Q+"_";var Jc=Object.freeze(["features","mcp"]),zc="omit_tools_from",$c=Object.freeze(["deferred"]),Qc="default_tools_approval_mode",Zc="approve",ox=Object.freeze({codex:{file:[".codex","config.toml"],key:["mcp_servers",Q],fields:{[zc]:$c,[Qc]:Zc}},vscode:{file:[".vscode","mcp.json"],key:["servers",Q]},kiro:{file:[".kiro","settings","mcp.json"],key:["mcpServers",Q]},zcode:{file:[".zcode","cli","config.json"],key:["mcp","servers",Q],fields:{type:"stdio",enabled:!0,timeoutMs:qc},also:[[Jc,!0]]}});var rx=Object.freeze({NODE_ENV:Object.freeze(["development","production","test"])});import{dirname as F0,join as j0}from"node:path";var fn="mcp__plugin_context-mode_context-mode__",ea=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"],Fr="mcp__",jr="__",ta={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function na(e,t){if(e.startsWith(t))return e.slice(t.length);if(!e.startsWith(Fr))return e;let n=e.slice(Fr.length),o=n.indexOf(jr);return o<0?e:"mcp:"+n.slice(0,o)+":"+n.slice(o+jr.length)}function oa(e){if(e===void 0)return"";if(typeof e=="string")return e;if(Array.isArray(e))return Br(e).text;if(typeof e=="object"&&e!==null){let t=e;if(typeof t.stdout=="string"||typeof t.stderr=="string"){let n=typeof t.stdout=="string"?t.stdout:"",o=typeof t.stderr=="string"?t.stderr:"";return o===""?n:n===""?o:n+`
|
|
3
|
+
`+o}}return typeof e=="object"&&e!==null&&Gr(e)?e.content:JSON.stringify(e)}function Gr(e){let t=e;return t.mode==="content"&&typeof t.content=="string"}function Br(e){let t=[],n=!1;for(let o of e){let r=typeof o=="object"&&o!==null?o:{};r.type==="text"&&typeof r.text=="string"?t.push(r.text):n=!0}return{text:t.join(`
|
|
4
|
+
`),keep:n}}function ra(e){let t=oa(e),o={isError:typeof e=="object"&&e!==null&&e.is_error===!0,bytes:Buffer.byteLength(t),text:t};if(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Gr(e)&&(o.shape=e),Array.isArray(e)&&(o.blocks=!0,Br(e).keep&&(o.keep=!0)),typeof e=="object"&&e!==null){let r=e;typeof r.persistedOutputPath=="string"&&r.persistedOutputPath!==""&&typeof r.persistedOutputSize=="number"&&r.persistedOutputSize>o.bytes&&(o.persistedPath=r.persistedOutputPath)}return o}function te(e,t,n,o){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error(t+": hook payload is not a JSON object");let r=e,s=ea.find(c=>c===r.hook_event_name);if(s===void 0)throw new Error(t+": unknown hook event "+String(r.hook_event_name));let i={event:s,agent:t,sessionId:String(r.session_id??""),cwd:String(r.cwd??"")};if(typeof r.agent_id=="string"&&(i.agentId=r.agent_id,typeof r.agent_type=="string"&&(i.agentType=r.agent_type)),s==="SessionStart"&&typeof r.source=="string"&&o[r.source]!==void 0&&(i.source=o[r.source]),s==="UserPromptSubmit"&&typeof r.prompt=="string"&&(i.prompt=r.prompt),s==="PreToolUse"||s==="PostToolUse"){let c=String(r.tool_name??""),a=typeof r.tool_input=="object"&&r.tool_input!==null?r.tool_input:{},l={name:c,canonicalName:na(c,n),input:a};typeof r.tool_use_id=="string"&&r.tool_use_id!==""&&(l.callId=r.tool_use_id),i.tool=l}return s==="PostToolUse"&&(i.result=ra(r.tool_response)),i}function sa(e,t){return e.tool?.canonicalName==="Bash"?{stdout:t,stderr:"",interrupted:!1}:e.result?.shape!==void 0?{...e.result.shape,content:t}:e.result?.blocks===!0?[{type:"text",text:t}]:t}function H(e,t,n){let o=r=>({stdout:JSON.stringify({hookSpecificOutput:{hookEventName:e.event,...r}}),exitCode:0});switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return o({additionalContext:t.text});case"deny":return o({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
5
|
+
`+t.reason});case"replace":return n&&e.event==="PostToolUse"?o({updatedToolOutput:sa(e,t.output)}):{stdout:"",exitCode:0}}}var ia={PreToolUse:["tool_name"],PostToolUse:["tool_name","tool_response"]};function ca(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function aa(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(t.hook_event_name===void 0)throw new Error("claude-code: missing required field hook_event_name");for(let n of ia[t.hook_event_name]??[])if(t[n]===void 0)throw new Error("claude-code: missing required field "+n)}function Wr(e){aa(e);let t=te(e,"claude-code",fn,ta);if(t.cwd===""&&(t.cwd=process.env.CLAUDE_PROJECT_DIR||process.cwd()),t.event==="PostToolUse"&&t.tool!==void 0&&t.tool.callId===void 0){let n=typeof t.tool.input.command=="string"?t.tool.input.command:JSON.stringify(t.tool.input);t.tool.callId="h"+ca(t.tool.name+"\0"+n+"\0"+String(t.turn??0))}return t}function Xr(e,t,n){return H(e,t,!0)}var xn="mcp__context_mode__",ua={startup:"startup",resume:"resume",clear:"clear",compact:"compact",fork:"resume"};function Kr(e){return te(e,"codex",xn,ua)}function qr(e,t,n){return H(e,t,!1)}var it="mcp_context-mode_",Yr={SessionStart:"SessionStart",BeforeAgent:"UserPromptSubmit",BeforeTool:"PreToolUse",AfterTool:"PostToolUse",PreCompress:"PreCompact"},Vr={startup:"startup",resume:"resume",clear:"clear"},fa=["SessionStart","UserPromptSubmit","PostToolUse"],xa=["UserPromptSubmit","PreToolUse"],st={stdout:"",exitCode:0};function N(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var Jr={run_shell_command:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"};function pa(e,t){if(e.startsWith(it))return e.slice(it.length);if(Object.hasOwn(Jr,e))return Jr[e];if(typeof t!="object"||t===null)return e;let n=t,o=N(n,"server_name"),r=N(n,"tool_name");return typeof o!="string"||typeof r!="string"?e:"mcp:"+o+":"+r}function Ea(e){let t=typeof e=="object"&&e!==null?e:void 0,n=t===void 0?void 0:N(t,"llmContent"),o=e===void 0?"":typeof e=="string"?e:typeof n=="string"?n:JSON.stringify(e),r=t===void 0?void 0:N(t,"error");return{isError:r!=null,bytes:Buffer.byteLength(o),text:o}}function zr(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("gemini: hook payload is not a JSON object");let t=e,n=N(t,"hook_event_name"),o=typeof n=="string"&&Object.hasOwn(Yr,n)?Yr[n]:void 0;if(o===void 0)throw new Error("gemini: unknown hook event "+String(n));let r={event:o,agent:"gemini",sessionId:String(N(t,"session_id")??""),cwd:String(N(t,"cwd")??"")},s=N(t,"source");o==="SessionStart"&&typeof s=="string"&&Object.hasOwn(Vr,s)&&(r.source=Vr[s]);let i=N(t,"prompt");if(o==="UserPromptSubmit"&&typeof i=="string"&&(r.prompt=i),o==="PreToolUse"||o==="PostToolUse"){let c=String(N(t,"tool_name")??""),a=N(t,"tool_input");r.tool={name:c,canonicalName:pa(c,N(t,"mcp_context")),input:typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{}}}return o==="PostToolUse"&&(r.result=Ea(N(t,"tool_response"))),r}function $r(e,t,n){switch(t.kind){case"allow":return st;case"hint":return fa.includes(e.event)?{stdout:JSON.stringify({hookSpecificOutput:{additionalContext:t.text}}),exitCode:0}:st;case"deny":return xa.includes(e.event)?{stdout:JSON.stringify({decision:"deny",reason:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
6
|
+
`+t.reason}),exitCode:0}:st;case"replace":return e.event!=="PostToolUse"?st:{stdout:JSON.stringify({decision:"deny",reason:t.output}),exitCode:0}}}var pn="mcp__context-mode__",_a={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Qr={run_shell_command:"Bash",Shell:"Bash",read_file:"Read",grep_search:"Grep",web_fetch:"WebFetch"},ga="PostToolUseFailure";function Zr(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.hook_event_name===ga,n=t?{...e,hook_event_name:"PostToolUse"}:e,o=te(n,"qwen",pn,_a);if(o.tool!==void 0&&Object.hasOwn(Qr,o.tool.name)&&(o.tool.canonicalName=Qr[o.tool.name]),t){let r=e.error,s=typeof r=="string"?r:r===void 0?"":JSON.stringify(r);o.result={isError:!0,bytes:Buffer.byteLength(s),text:s}}return o}function es(e,t,n){return H(e,t,!1)}var at="context-mode-",ba={sessionStart:{event:"SessionStart",casing:"camel",failure:!1},userPromptSubmitted:{event:"UserPromptSubmit",casing:"camel",failure:!1},preToolUse:{event:"PreToolUse",casing:"camel",failure:!1},postToolUse:{event:"PostToolUse",casing:"camel",failure:!1},postToolUseFailure:{event:"PostToolUse",casing:"camel",failure:!0},SessionStart:{event:"SessionStart",casing:"snake",failure:!1},UserPromptSubmit:{event:"UserPromptSubmit",casing:"snake",failure:!1},PreToolUse:{event:"PreToolUse",casing:"snake",failure:!1},PostToolUse:{event:"PostToolUse",casing:"snake",failure:!1},PostToolUseFailure:{event:"PostToolUse",casing:"snake",failure:!0}},ts={startup:"startup",resume:"resume",new:"startup"},Sa={camel:{event:"hookEventName",session:"sessionId",tool:"toolName",args:"toolArgs",result:"toolResult"},snake:{event:"hook_event_name",session:"session_id",tool:"tool_name",args:"tool_input",result:"tool_result"}},os="success";function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ns={bash:"Bash"};function Ta(e){return e.startsWith(at)?e.slice(at.length):Object.hasOwn(ns,e)?ns[e]:e}function Ra(e){if(lt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return lt(t)?t:{}}catch{return{}}}var Oa={camel:{type:"resultType",text:"textResultForLlm"},snake:{type:"result_type",text:"text_result_for_llm"}};function Aa(e,t,n){let o=Oa[t],r=lt(e)?e:{},s=typeof r[o.text]=="string"?r[o.text]:"";return{isError:n||typeof r[o.type]=="string"&&r[o.type]!==os,bytes:Buffer.byteLength(s),text:s}}var ya=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"]];function Na(e){return typeof e.hookEventName=="string"?e.hookEventName:e.hook_event_name!==void 0?e.hook_event_name:ya.find(([t])=>Object.hasOwn(e,t))?.[1]}function rs(e){if(!lt(e))throw new Error("copilot-cli: hook payload is not a JSON object");let t=Na(e),n=typeof t=="string"?ba[t]:void 0;if(n===void 0)throw new Error("copilot-cli: unknown hook event "+String(t));let o=Sa[n.casing],r=n.event,s={event:r,agent:"copilot-cli",sessionId:String(e[o.session]??""),cwd:String(e.cwd??"")};if(r==="SessionStart"&&typeof e.source=="string"&&ts[e.source]!==void 0&&(s.source=ts[e.source]),r==="UserPromptSubmit"&&typeof e.prompt=="string"&&(s.prompt=e.prompt),r==="PreToolUse"||r==="PostToolUse"){let i=String(e[o.tool]??""),c={name:i,canonicalName:Ta(i),input:Ra(e[o.args])};s.tool=c}return r==="PostToolUse"&&(s.result=Aa(e[o.result],n.casing,n.failure)),s}var ct={stdout:"",exitCode:0};function ss(e,t,n){switch(t.kind){case"allow":return ct;case"hint":return e.event==="PostToolUse"?ct:{stdout:JSON.stringify({additionalContext:t.text}),exitCode:0};case"deny":return e.event!=="PreToolUse"?ct:{stdout:JSON.stringify({permissionDecision:"deny",permissionDecisionReason:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
7
|
+
`+t.reason}),exitCode:0};case"replace":return e.event!=="PostToolUse"?ct:{stdout:JSON.stringify({modifiedResult:{resultType:os,textResultForLlm:t.output}}),exitCode:0}}}var ut="mcp_context-mode_",ds=["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse","PreCompact"],is="mcp_",cs="_",ka="new",En="run_in_terminal",as={[En]:"Bash"};function fs(e){if(e.startsWith(ut))return e.slice(ut.length);if(Object.hasOwn(as,e))return as[e];if(!e.startsWith(is))return e;let t=e.slice(is.length),n=t.indexOf(cs);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+cs.length)}function Ia(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:typeof e=="object"&&e!==null&&e.is_error===!0,bytes:Buffer.byteLength(t),text:t}}var Da={sessionStart:"SessionStart",userPromptSubmitted:"UserPromptSubmit",preToolUse:"PreToolUse",postToolUse:"PostToolUse",preCompact:"PreCompact"},wa=[["toolResult","postToolUse"],["toolName","preToolUse"],["prompt","userPromptSubmitted"],["source","sessionStart"],["trigger","preCompact"]],ls={new:"startup",startup:"startup",resume:"resume"},La="success";function dt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Pa(e){if(dt(e))return e;if(typeof e!="string")return{};try{let t=JSON.parse(e);return dt(t)?t:{}}catch{return{}}}function Ua(e){let t=dt(e)?e:{},n=typeof t.textResultForLlm=="string"?t.textResultForLlm:"";return{isError:typeof t.resultType=="string"&&t.resultType!==La,bytes:Buffer.byteLength(n),text:n}}function us(e,t){let n=typeof t=="string"?Da[t]??ds.find(r=>r===t):void 0;if(n===void 0)throw new Error("vscode: unknown hook event "+String(t));let o={event:n,agent:"vscode",sessionId:String(e.sessionId??""),cwd:String(e.cwd??"")};if(n==="SessionStart"&&typeof e.source=="string"&&ls[e.source]!==void 0&&(o.source=ls[e.source]),n==="UserPromptSubmit"&&typeof e.prompt=="string"&&(o.prompt=e.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(e.toolName??"");o.tool={name:r,canonicalName:fs(r),input:Pa(e.toolArgs)}}return n==="PostToolUse"&&(o.result=Ua(e.toolResult)),o}function xs(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("vscode: hook payload is not a JSON object");let t=e;if(t.hookEventName!==void 0)return us(t,t.hookEventName);if(t.hook_event_name===void 0){let r=wa.find(([s])=>Object.hasOwn(t,s))?.[1];if(r===void 0)throw new Error("vscode: missing required field hook_event_name");return us(t,r)}let n=ds.find(r=>r===t.hook_event_name);if(n===void 0)throw new Error("vscode: unknown hook event "+String(t.hook_event_name));let o={event:n,agent:"vscode",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")};if(n==="SessionStart"&&t.source===ka&&(o.source="startup"),n==="UserPromptSubmit"&&typeof t.prompt=="string"&&(o.prompt=t.prompt),n==="PreToolUse"||n==="PostToolUse"){let r=String(t.tool_name??""),s=dt(t.tool_input)?t.tool_input:{};o.tool={name:r,canonicalName:fs(r),input:s}}return n==="PostToolUse"&&(o.result=Ia(t.tool_response)),o}function ps(e,t,n){return H(e,t,!1)}var ft="mcp_context-mode_",Es={SessionStart:"SessionStart",agentSpawn:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PromptSubmit:"UserPromptSubmit",userPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",preToolUse:"PreToolUse",PostToolUse:"PostToolUse",postToolUse:"PostToolUse"},Ha="USER_PROMPT",ms="mcp_",mn=Object.freeze(["execute_bash","execute_pwsh","shell"]),_s=Object.fromEntries(mn.map(e=>[e,"Bash"])),gs="_",hs={startup:"startup",resume:"resume",clear:"clear",compact:"compact"};function va(e){if(e.startsWith(ft))return e.slice(ft.length);if(Object.hasOwn(_s,e))return _s[e];if(!e.startsWith(ms))return e;let t=e.slice(ms.length),n=t.indexOf(gs);return n<=0||n===t.length-1?e:"mcp:"+t.slice(0,n)+":"+t.slice(n+gs.length)}function Fa(e){let t=e===void 0?"":typeof e=="string"?e:JSON.stringify(e);return{isError:!1,bytes:Buffer.byteLength(t),text:t}}function bs(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("kiro: hook payload is not a JSON object");let t=e,n=typeof t.hook_event_name=="string"?t.hook_event_name:"",o=Object.prototype.hasOwnProperty.call(Es,n)?Es[n]:void 0;if(o===void 0)throw new Error("kiro: unknown hook event "+String(t.hook_event_name));let r={event:o,agent:"kiro",sessionId:String(t.session_id??""),cwd:String(t.cwd??"")};if(o==="SessionStart"&&typeof t.source=="string"&&hs[t.source]!==void 0&&(r.source=hs[t.source]),o==="UserPromptSubmit"){let s=process.env[Ha];s!==void 0&&(r.prompt=s)}if(o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool_name??""),i=typeof t.tool_input=="object"&&t.tool_input!==null&&!Array.isArray(t.tool_input)?t.tool_input:{};r.tool={name:s,canonicalName:va(s),input:i}}return o==="PostToolUse"&&(r.result=Fa(t.tool_response)),r}function Ss(e,t,n){if(e.event==="UserPromptSubmit")return{stdout:"",exitCode:0};switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:t.text,exitCode:0};case"deny":return{stdout:"",stderr:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
8
|
+
`+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var _n="mcp__context-mode__",Ga={startup:"startup",resume:"resume",clear:"clear",compact:"compact"},Ba={hook_event_name:"hookEventName",session_id:"sessionId"},Wa="PostToolUseFailure";function Ts(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("zcode: hook payload is not a JSON object");let t={...e};for(let[r,s]of Object.entries(Ba))t[r]===void 0&&(t[r]=t[s]);let n=t.hook_event_name===Wa;n&&(t.hook_event_name="PostToolUse");let o=te(t,"zcode",_n,Ga);if(n){let r=typeof t.error=="string"?t.error:t.error===void 0?"":JSON.stringify(t.error);o.result={isError:!0,bytes:Buffer.byteLength(r),text:r}}return o}function Rs(e,t,n){return H(e,t,!1)}var ys="",Os={session_start:{event:"SessionStart",source:"startup"},session_compact:{event:"SessionStart",source:"compact"},input:{event:"UserPromptSubmit"},tool_call:{event:"PreToolUse"},tool_result:{event:"PostToolUse"}},As={bash:"Bash",read:"Read"};function Ka(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function qa(e){let t=e.content===void 0?"":typeof e.content=="string"?e.content:JSON.stringify(e.content),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function Ns(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("pi: hook payload is not an object");let t=e,n=typeof t.type=="string"?t.type:"",o=Object.prototype.hasOwnProperty.call(Os,n)?Os[n]:void 0;if(o===void 0)throw new Error("pi: unknown hook event "+String(t.type));let r={event:o.event,agent:"pi",sessionId:String(t.sessionId??""),cwd:String(t.cwd??"")};if(o.source!==void 0&&(r.source=o.source),o.event==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o.event==="PreToolUse"||o.event==="PostToolUse"){let s=String(t.toolName??"");r.tool={name:s,canonicalName:Object.hasOwn(As,s)?As[s]:s,input:Ka(t.input)},typeof t.toolCallId=="string"&&(r.tool.callId=t.toolCallId)}return o.event==="PostToolUse"&&(r.result=qa(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Ya(e,t){switch(t?.kind){case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
9
|
+
`+t.reason,exitCode:2};case"replace":return{stdout:e.event==="PostToolUse"?t.output:"",exitCode:0}}return{stdout:"",exitCode:0}}function Cs(e,t,n){let o=Ya(e,t);return t?.kind==="allow"?o:{stdout:o.stdout,exitCode:o.exitCode,role:vr,content:o.stdout,timestamp:Date.now()}}function ks(e){return e.exitCode===2?{block:!0,reason:e.stdout}:void 0}var Ls="",Is=Q+"_",Ds={context:"SessionStart",prompt:"UserPromptSubmit","execute.before":"PreToolUse","execute.after":"PostToolUse",compaction:"PreCompact","step-finish":"Usage"},gn="bash",ws={webfetch:"WebFetch",[gn]:"Bash"};function hn(e){return e.startsWith(Is)?e.slice(Is.length):Object.prototype.hasOwnProperty.call(ws,e)?ws[e]:e}function Ja(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function za(e){let t=e.output===void 0?"":typeof e.output=="string"?e.output:JSON.stringify(e.output),n={isError:e.isError===!0,bytes:Buffer.byteLength(t),text:t};return typeof e.exitCode=="number"&&(n.exitCode=e.exitCode),n}function Ps(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("opencode: hook payload is not an object");let t=e,n=typeof t.type=="string"?t.type:"",o=Object.prototype.hasOwnProperty.call(Ds,n)?Ds[n]:void 0;if(o===void 0)throw new Error("opencode: unknown hook event "+String(t.type));let r={event:o,agent:"opencode",sessionId:String(t.sessionID??""),cwd:String(t.directory??"")};if(o==="UserPromptSubmit"&&typeof t.message=="string"&&(r.prompt=t.message),o==="PreToolUse"||o==="PostToolUse"){let s=String(t.tool??"");r.tool={name:s,canonicalName:hn(s),input:Ja(t.args)},typeof t.callID=="string"&&(r.tool.callId=t.callID)}return o==="PostToolUse"&&(r.result=za(t)),typeof t.turn=="number"&&(r.turn=t.turn),r}function Us(e,t,n){switch(t.kind){case"allow":return{stdout:"",exitCode:0};case"hint":return{stdout:e.event==="SessionStart"?t.text:"",exitCode:0};case"deny":return e.event!=="PreToolUse"?{stdout:"",exitCode:0}:{stdout:t.rewritten===void 0?t.reason:t.rewritten+`
|
|
10
|
+
`+t.reason,exitCode:2};case"replace":return{stdout:"",exitCode:0}}}var Ae={SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},Ms={shell:["Bash"],read:["Read"],grep:["Grep"],webfetch:["WebFetch"],edit:["Write","Edit","NotebookEdit"]},Qa=Object.freeze([{id:"claude-code",installMode:"marketplace",projectSource:"env:CLAUDE_PROJECT_DIR",toolNamePrefix:fn,nativeTools:Ms,execReadOnlyHint:!1,eventMap:Ae,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:M,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/claude-code.json"},skillChannel:{kind:"package",path:"claude-code/skills"},decode:Wr,encode:Xr},{id:"codex",installMode:"config-mcp",projectSource:"arg:--agent+cwd",toolNamePrefix:xn,nativeTools:{shell:["Bash"],edit:["apply_patch"]},execReadOnlyHint:!0,eventMap:Ae,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:M,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".codex/hooks.json"},skillChannel:{kind:"home-dir",path:".codex/skills"},decode:Kr,encode:qr},{id:"gemini",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:it,nativeTools:{shell:["run_shell_command"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:{UserPromptSubmit:"BeforeAgent",PreToolUse:"BeforeTool",PostToolUse:"AfterTool",PreCompact:"PreCompress"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:M,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/hooks.json"},skillChannel:{kind:"package",path:"skills"},decode:zr,encode:$r},{id:"qwen",installMode:"extension",projectSource:"spawn-cwd",toolNamePrefix:pn,nativeTools:{shell:["run_shell_command","Shell"],read:["read_file"],grep:["grep_search"],webfetch:["web_fetch"]},execReadOnlyHint:!1,eventMap:Ae,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:M,denyChannel:"deny-reason",hookChannel:{kind:"package",path:"hooks/qwen.json"},skillChannel:{kind:"package",path:"skills"},decode:Zr,encode:es},{id:"copilot-cli",installMode:"plugin",projectSource:"arg:--agent+cwd",toolNamePrefix:at,nativeTools:{shell:["bash"]},execReadOnlyHint:!1,eventMap:{SessionStart:"sessionStart",UserPromptSubmit:"userPromptSubmitted",PreToolUse:"preToolUse",PostToolUse:"postToolUse"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:M,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".copilot/skills"},decode:rs,encode:ss},{id:"vscode",installMode:"mcp-entry",projectSource:"arg:workspaceFolder",toolNamePrefix:ut,nativeTools:{shell:[En]},execReadOnlyHint:!1,eventMap:{...Ae,PreCompact:"PreCompact"},compactDelivery:"pending-flag",compactSummary:"none",hookTimeoutMs:M,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".copilot/hooks/context-mode-vscode.json"},skillChannel:{kind:"home-dir",path:".agents/skills"},decode:xs,encode:ps},{id:"kiro",installMode:"mcp-entry",projectSource:"arg:--agent+cwd",toolNamePrefix:ft,nativeTools:{shell:[...mn]},execReadOnlyHint:!1,eventMap:{SessionStart:"SessionStart",UserPromptSubmit:"UserPromptSubmit",PreToolUse:"PreToolUse",PostToolUse:"PostToolUse"},compactDelivery:"none",compactSummary:"none",hookTimeoutMs:M,denyChannel:"hint-only",hookChannel:{kind:"home-file",path:".kiro/hooks/context-mode.json"},skillChannel:{kind:"home-dir",path:".kiro/skills"},decode:bs,encode:Ss},{id:"zcode",installMode:"hooks+mcp",projectSource:"spawn-cwd",toolNamePrefix:_n,nativeTools:Ms,execReadOnlyHint:!1,eventMap:Ae,compactDelivery:"sessionstart",compactSummary:"none",hookTimeoutMs:M,denyChannel:"deny-reason",hookChannel:{kind:"home-file",path:".zcode/cli/config.json"},skillChannel:{kind:"home-dir",path:".zcode/skills"},decode:Ts,encode:Rs},{id:"pi",installMode:"in-process",projectSource:"pi:ctx.cwd",toolNamePrefix:ys,nativeTools:{shell:["bash"],read:["read"]},execReadOnlyHint:!1,eventMap:{SessionStart:"session_start",UserPromptSubmit:"input",PreToolUse:"tool_call",PostToolUse:"tool_result"},compactDelivery:"pi-flag",compactSummary:"none",hookTimeoutMs:Kt,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"pi/index.js"},skillChannel:{kind:"package",path:"pi/skills"},decode:Ns,encode:Cs,checkPermission:ks},{id:"opencode",installMode:"in-process",projectSource:"spawn-cwd",toolNamePrefix:Ls,nativeTools:{shell:[gn]},execReadOnlyHint:!1,eventMap:{SessionStart:"context",UserPromptSubmit:"prompt",PreToolUse:"execute.before",PostToolUse:"execute.after",PreCompact:"compaction",Usage:"step-finish"},compactDelivery:"opencode-cache",compactSummary:"none",hookTimeoutMs:Kt,denyChannel:"deny-reason",hookChannel:{kind:"in-process",path:"opencode/plugin.js"},skillChannel:{kind:"home-dir",path:".config/opencode/skills"},decode:Ps,encode:Us,toCanonicalTool:hn}]),Za=new Map(Qa.map(e=>[e.id,e])),el=new Set(["claude-code","gemini","copilot-cli","pi"]);function ye(e){return el.has(e.id)}var tl=new Set(["claude-code","copilot-cli","pi"]);function Hs(e){return tl.has(e.id)&&ye(e)}var nl=new Set(["claude-code","codex","gemini","qwen","copilot-cli","vscode","zcode"]);function xt(e){return nl.has(e.id)}function Ne(e){return Za.get(e)}import{resolve as Kn}from"node:path";var ol=["&&","||",";;","|&",";","|","&","(",")"],rl=["&>>","&>"],sl=[">>",">|",">&",">","<<<","<<-","<<","<&","<>","<"],il="&",cl="<<",vs="<<-",al=";",Fs=`\r
|
|
11
|
+
`,js=`\\
|
|
12
|
+
`,Gs=`\\\r
|
|
13
|
+
`,ll="$(",Xs="${",Ks="$'",Ce="((",Bs="))",ae="[[",pt="]]",bn="<(",qs=">(",D=2,Ys=`
|
|
14
|
+
\r;&|()<>`,ul=`
|
|
15
|
+
\r`,dl='$`"\\\n',fl="case",xl="esac";function le(e,t){e.end==="complete"&&(e.end=t)}function Sn(e){return e!==""&&e>="0"&&e<="9"}function Ws(e){return e!==""&&(e>="a"&&e<="z"||e>="A"&&e<="Z")}function Vs(e){return e===""||Ys.includes(e)}function Tn(e){return e!==""&&ul.includes(e)}function v(e,t,n,o,r){e!==null&&e.push({kind:t,text:n,start:o,end:r})}function Et(e,t){let n=e.s.indexOf("'",t+1);return n<0?(le(e,"unterminated-quote"),e.n):n+1}function Js(e,t){let n=t+Ks.length;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=D;continue}if(o==="'")return n+1;n++}return le(e,"unterminated-quote"),e.n}function Rn(e,t,n){let o=t+1;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(r==="\\"){o+=D;continue}if(r==='"')return o+1;if(r==="$"&&s==="("){o=ke(e,o,n);continue}if(r==="$"&&s==="{"){o=On(e,o,n);continue}if(r==="`"){o=ue(e,o);continue}o++}return le(e,"unterminated-quote"),e.n}function ue(e,t){let n=t+1;for(;n<e.n;){let o=e.s.charAt(n);if(o==="\\"){n+=D;continue}if(o==="`")return n+1;n++}return e.n}function On(e,t,n){let o=t+Xs.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=D;continue}if(s==="'"){o=Et(e,o);continue}if(s==='"'){o=Rn(e,o,n);continue}if(s==="$"&&i==="("){o=ke(e,o,n);continue}if(s==="`"){o=ue(e,o);continue}if(s==="{"&&r++,s==="}"){if(r===0)return o+1;r--}o++}return e.n}function An(e,t){let n=0,o=t+Ce.length;for(;o<e.length;){let r=e.charAt(o);if(r==="("&&n++,r===")"){if(n===0)return e.startsWith(Bs,o)?o+Bs.length:-1;n--}o++}return-1}function ke(e,t,n){let o=t+ll.length-1;if(e.s.startsWith(Ce,o)){let r=An(e.s,o);if(r>0)return r}return mt(e,o+1,!0,n+1,null,null)}function pl(e,t,n){let o=t+ae.length,r=0;for(;o<e.n;){let s=e.s.charAt(o),i=e.s.charAt(o+1);if(s==="\\"){o+=D;continue}if(s==="'"){o=Et(e,o);continue}if(s==='"'){o=Rn(e,o,n);continue}if(s==="$"&&i==="("){o=ke(e,o,n);continue}if(s==="$"&&i==="{"){o=On(e,o,n);continue}if(s==="`"){o=ue(e,o);continue}let c=Tn(e.s.charAt(o-1));if(c&&e.s.startsWith(pt,o)&&Vs(e.s.charAt(o+pt.length))){if(r===0)return o+pt.length;r--,o+=pt.length;continue}if(c&&e.s.startsWith(ae,o)&&Tn(e.s.charAt(o+ae.length))){r++,o+=ae.length;continue}o++}return-1}function El(e,t){let n=t;for(;Sn(e.charAt(n));)n++;if(n===t){for(let o of rl)if(e.startsWith(o,t))return{end:t+o.length,op:o}}for(let o of sl){if(!e.startsWith(o,n))continue;let r=n+o.length;if(o.endsWith(il))if(e.charAt(r)==="-")r++;else for(;Sn(e.charAt(r));)r++;return{end:r,op:o}}return null}function ml(e,t,n){let o=t;for(;o<e.n;){let r=e.s.charAt(o),s=e.s.charAt(o+1);if(Ys.includes(r))break;if(r==="\\"){o+=D;continue}if(r==="'"){o=Et(e,o);continue}if(r==='"'){o=Rn(e,o,n);continue}if(r==="$"&&s==="'"){o=Js(e,o);continue}if(r==="$"&&s==="("){o=ke(e,o,n);continue}if(r==="$"&&s==="{"){o=On(e,o,n);continue}if(r==="`"){o=ue(e,o);continue}o++}return Math.min(o,e.n)}function _l(e,t,n,o,r){let s=t;for(let i of n){let c=s,a=!1;for(;s<e.n;){let l=e.s.indexOf(`
|
|
16
|
+
`,s),u=l<0?e.n:l,f=e.s.slice(s,u);if(f.endsWith("\r")&&(f=f.slice(0,-1)),s=l<0?e.n:l+1,(i.strip?f.trim():f)===i.tag){a=!0;break}}if(o!==null&&r!==null&&r.push(o.length),v(o,"unhandled",e.s.slice(c,s),c,s),!a)return le(e,"unterminated-heredoc"),e.n}return n.length=0,s}function mt(e,t,n,o,r,s){if(o>ee)return le(e,"too-deep"),e.n;let i=e.s,c=t,a=0,l=0,u=null,f=[];for(;c<e.n;){let d=i.charAt(c),x=i.charAt(c+1);if(d===" "||d===" "){c++;continue}if(i.startsWith(js,c)){c+=js.length;continue}if(i.startsWith(Gs,c)){c+=Gs.length;continue}if(d===`
|
|
17
|
+
`||d==="\r"){let h=c;c+=i.startsWith(Fs,c)?Fs.length:1,v(r,"op",al,h,c),u=null,f.length>0&&(c=_l(e,c,f,r,s));continue}if(d==="#"){for(;c<e.n&&i.charAt(c)!==`
|
|
18
|
+
`&&i.charAt(c)!=="\r";)c++;continue}if(i.startsWith(bn,c)||i.startsWith(qs,c)){let h=mt(e,c+bn.length,!0,o+1,null,null);v(r,"unhandled",i.slice(c,h),c,h),c=h,u=null;continue}let E=El(i,c);if(E!==null){v(r,"io",i.slice(c,E.end),c,E.end),u=E.op===cl||E.op===vs?E.op===vs:null,c=E.end;continue}if(i.startsWith(ae,c)&&Tn(i.charAt(c+ae.length))){let h=pl(e,c,o);if(h>0){v(r,"unhandled",i.slice(c,h),c,h),c=h,u=null;continue}}if(i.startsWith(Ce,c)){let h=An(i,c);if(h>0){v(r,"unhandled",i.slice(c,h),c,h),c=h,u=null;continue}}let m=ol.find(h=>i.startsWith(h,c));if(m!==void 0){if(n&&m==="("&&a++,n&&m===")"){if(a>0)a--;else if(l===0)return c+1}v(r,"op",m,c,c+m.length),c+=m.length,u=null;continue}if(d==="$"&&x==="("||d==="`"){let h=d==="`"?ue(e,c):ke(e,c,o);if(Vs(i.charAt(h))){v(r,"unhandled",i.slice(c,h),c,h),c=h,u=null;continue}}let _=c;c=ml(e,c,o);let S=i.slice(_,c);v(r,"word",S,_,c),u!==null&&(f.push({tag:de(S),strip:u}),u=null),n&&S===fl&&l++,n&&S===xl&&l>0&&l--}return f.length>0&&le(e,"unterminated-heredoc"),e.n}function zs(e){let t={s:e,n:e.length,end:"complete"},n=[],o=[];return mt(t,0,!1,0,n,o),{tokens:n,heredocBodies:o,end:t.end}}function de(e){let t="",n=0,o=e.length;for(;n<o;){let r=e.charAt(n);if(r==="\\"){t+=e.charAt(n+1),n+=D;continue}if(r==="'"){let s=e.indexOf("'",n+1),i=s<0?o:s;t+=e.slice(n+1,i),n=i+1;continue}if(r==="$"&&e.charAt(n+1)==="'"){let s=n+Ks.length;for(;s<o&&e.charAt(s)!=="'";){if(e.charAt(s)==="\\"){t+=e.charAt(s+1),s+=D;continue}t+=e.charAt(s),s++}n=s+1;continue}if(r==='"'){let s=n+1;for(;s<o&&e.charAt(s)!=='"';){let i=e.charAt(s+1);if(e.charAt(s)==="\\"&&i!==""&&dl.includes(i)){t+=i,s+=D;continue}t+=e.charAt(s),s++}n=s+1;continue}t+=r,n++}return t}function _t(e){let t={s:e,n:e.length,end:"complete"},n=[],o=!1,r=0;for(;r<t.n;){let s=e.charAt(r),i=e.charAt(r+1);if(s==="\\"){r+=D;continue}if(!o&&s==="'"){r=Et(t,r);continue}if(!o&&s==="$"&&i==="'"){r=Js(t,r);continue}if(s==='"'){o=!o,r++;continue}if(s==="$"&&i==="{"){r+=Xs.length;continue}let c=e.startsWith(bn,r);if(s==="$"&&i==="("||!o&&(c||e.startsWith(qs,r))){let a=r+1;if(s==="$"&&e.startsWith(Ce,a)&&An(e,a)>0){r=a+Ce.length;continue}let l=mt(t,a+1,!0,1,null,null),u=l>a+1&&e.charAt(l-1)===")"?l-1:l;n.push({wrapper:s==="$"?"$()":c?"<()":">()",body:e.slice(a+1,u)}),r=l;continue}if(s==="`"){let a=ue(t,r),l=a>r+1&&e.charAt(a-1)==="`"?a-1:a;n.push({wrapper:"`",body:e.slice(r+1,l)}),r=a;continue}r++}return n}function gt(e){let t=e.charAt(0);if(!(Ws(t)||t==="_"))return!1;for(let n=1;n<e.length;n++){let o=e.charAt(n);if(o==="="||o==="+"&&e.charAt(n+1)==="=")return!0;if(!(Ws(o)||Sn(o)||o==="_"))return!1}return!1}var ei=[";","&","&&","||"],ti=["|","|&"],Ie="(",De=")",ni=";;",Cn=["(",")"],gl="!",b=Object.freeze({group:"{",groupEnd:"}",if:"if",then:"then",elif:"elif",else:"else",fi:"fi",while:"while",until:"until",for:"for",in:"in",do:"do",done:"done",case:"case",esac:"esac",function:"function",coproc:"coproc",select:"select"}),oi=[],hl="[[",bl="((",ri=[">",">>",">|","&>","&>>",">&"],Sl=[...ri,"<","<>","<<<","<<","<<-"],Tl=["","1"],si=["-","/dev/stdout","/dev/stderr"],bt="-",we="--",Le="=",Rl="/",Ol=Object.freeze({curl:{short:"o",long:"--output"},wget:{short:"O",long:"--output-document"}}),ht=Object.freeze({head:"head",wc:"wc",grep:"grep",jq:"jq"}),yn="-c",Nn="--bytes",Al="c",yl="--count",ne=()=>({cmds:[],simple:null}),T=(e,t=0)=>e.toks[e.i+t],W=(e,t)=>e!==void 0&&e.kind==="op"&&e.text===t,C=(e,t)=>e!==void 0&&e.kind==="word"&&e.text===t,kn=e=>e!==""&&e>="0"&&e<="9",Nl=e=>kn(e)||e>="a"&&e<="z"||e>="A"&&e<="Z"||e==="_";function In(e){let t=e.lastIndexOf(Rl);return t>=0&&t<e.length-1?e.slice(t+1):e}function Dn(e,t){let n=Ol[e.toLowerCase()];if(n===void 0)return!1;for(let o=0;o<t.length;o++){let r=t[o];if(r===we)break;let s;if(r===n.long)s=t[o+1];else if(r.startsWith(n.long+Le))s=r.slice(n.long.length+Le.length);else if(r.startsWith(bt)&&!r.startsWith(we)){let i=r.indexOf(n.short,bt.length);if(i<0)continue;s=i+n.short.length<r.length?r.slice(i+n.short.length):t[o+1]}else continue;if(s!==void 0&&!si.includes(s))return!0}return!1}function Cl(e){if(e==="")return!1;for(let t of e)if(!kn(t))return!1;return!0}function kl(e){for(let t=0;t<e.length;t++){let n=e[t],o;if(n===yn||n===Nn?o=e[t+1]:n.startsWith(Nn+Le)?o=n.slice(Nn.length+Le.length):n.startsWith(yn)&&!n.startsWith(we)&&(o=n.slice(yn.length)),o!==void 0)return Cl(o)&&Number(o)<=be}return!1}function Il(e){for(let t of e){if(t===we)return!1;if(t===yl||t.startsWith(bt)&&!t.startsWith(we)&&t.includes(Al))return!0}return!1}function $s(e){if(!e.startsWith(I.fieldSep))return!1;for(let t of e.slice(I.fieldSep.length).split(I.fieldSep)){if(t==="")return!1;for(let n of t)if(!Nl(n))return!1}return!0}function Dl(e){let t=e.trim();if(t===I.identity||t===I.length)return!0;let n=t.indexOf(I.pipeLength.charAt(0));if(n<0)return $s(t);let o=t.slice(0,n).trim(),r=I.pipeLength.slice(1).trim();return(o===I.identity||$s(o))&&t.slice(n+1).trim()===r}function wl(e){let t=e.argv0.toLowerCase();if(t===ht.wc)return!0;if(t===ht.head)return kl(e.args);if(t===ht.grep)return Il(e.args);if(t===ht.jq){let n=e.args.filter(o=>!o.startsWith(bt));return n.length===1&&Dl(n[0])}return!1}function wn(e){return _t(e).length===0?[]:[{argv0:"",args:[],redirectsToFile:!1,endsInBoundedSink:!1,raw:e}]}function ii(e,t,n){return n<=t?[]:wn(e.src.slice(e.toks[t].start,e.toks[n-1].end))}function ci(e,t){for(let n of e)n.insideConstruct===void 0&&(n.insideConstruct=t)}function Ll(e){let t=0;for(;kn(e.charAt(t));)t++;return{fd:e.slice(0,t),op:e.slice(t)}}function ai(e){let t=Ll(e.toks[e.i].text);if(e.i++,!Sl.includes(t.op))return!1;let n=T(e);return n===void 0||n.kind==="op"||n.kind==="io"?!1:(e.i++,ri.includes(t.op)&&Tl.includes(t.fd)&&!si.includes(de(n.text)))}function li(e){let t=!1;for(;T(e)?.kind==="io";)t=ai(e)||t;return t}function ui(e){for(;T(e)?.kind==="op"&&ei.includes(T(e)?.text??"");)e.i++}function fe(e,t){if(e.depth++,e.depth>ee)return e.err="nesting-too-deep",ne();let n=t();if(e.depth--,li(e))for(let o of n)o.redirectsToFile=!0;return{cmds:n,simple:null}}function di(e){if(ui(e),!C(T(e),b.do))return[];e.i++;let t=F(e,[b.done]);return C(T(e),b.done)&&e.i++,t}function Pl(e){e.i++;let t=F(e,[b.then]);for(;e.err===null;){let n=T(e);if(C(n,b.then)||C(n,b.else)){e.i++,t.push(...F(e,[b.elif,b.else,b.fi]));continue}if(C(n,b.elif)){e.i++,t.push(...F(e,[b.then]));continue}C(n,b.fi)&&e.i++;break}return t}function Ul(e){e.i++;let t=F(e,[b.do]);return t.push(...di(e)),t}function Ml(e){e.i++;let t=[],n=T(e);if(n?.kind==="unhandled")e.i++;else if(n?.kind==="word"&&e.i++,C(T(e),b.in)){e.i++;let o=e.i;for(;(T(e)?.kind==="word"||T(e)?.kind==="unhandled")&&!C(T(e),b.do);)e.i++;t.push(...ii(e,o,e.i))}return t.push(...di(e)),t}function Hl(e){e.i++;let t=[],n=T(e);for(n!==void 0&&n.kind!=="op"&&n.kind!=="io"&&(e.i++,t.push(...ii(e,e.i-1,e.i))),C(T(e),b.in)&&e.i++;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)||o.kind==="op"&&(ei.includes(o.text)||o.text===ni)){e.i++;continue}if(C(o,b.esac)){e.i++;break}for(W(o,Ie)&&e.i++;e.i<e.toks.length&&!W(T(e),De);){let s=e.toks[e.i];if(s.kind==="op"&&!ti.includes(s.text))break;e.i++}if(!W(T(e),De))break;e.i++;let r=F(e,[b.esac]);ci(r,b.case),t.push(...r)}return t}function Qs(e,t){ui(e);let n=fi(e);return ci(n.cmds,t),{cmds:n.cmds,simple:null}}function Zs(e,t){return Cn.every((n,o)=>W(e.toks[t+o],n))}function vl(e){let t=e.i,n=[],o=!1;for(;e.i<e.toks.length;){let l=e.toks[e.i];if(l.kind==="op")break;if(l.kind==="io"){o=ai(e)||o;continue}if(n.length===0&&l.kind==="word"&>(l.text)){e.i++;let u=T(e);if(l.text.endsWith(Le)&&u!==void 0&&W(u,Ie)&&u.start===l.end){let f=0;for(;e.i<e.toks.length;){let d=e.toks[e.i];if(e.i++,W(d,Ie)&&f++,W(d,De)&&--f===0)break}}continue}n.push(l),e.i++}if(e.i===t)return ne();let r=e.src.slice(e.toks[t].start,e.toks[e.i-1].end);if(n.length===0)return{cmds:wn(r),simple:null};let s=l=>l.kind==="word"?de(l.text):l.text,i=In(s(n[0])),c=n.slice(1).map(s),a={argv0:i,args:c,redirectsToFile:o||Dn(i,c),endsInBoundedSink:!1,raw:r};return{cmds:[a],simple:a}}function fi(e){let t=T(e);if(t===void 0)return ne();if(t.kind==="op")return t.text!==Ie?ne():fe(e,()=>{e.i++;let n=F(e,oi);return W(T(e),De)&&e.i++,n});if(t.kind==="unhandled"&&(t.text.startsWith(hl)||t.text.startsWith(bl)))return e.i++,li(e),{cmds:wn(t.text),simple:null};if(t.kind==="word")switch(t.text){case b.group:return fe(e,()=>{e.i++;let n=F(e,[b.groupEnd]);return C(T(e),b.groupEnd)&&e.i++,n});case b.if:return fe(e,()=>Pl(e));case b.while:case b.until:return fe(e,()=>Ul(e));case b.for:return fe(e,()=>Ml(e));case b.case:return fe(e,()=>Hl(e));case b.coproc:return e.err="coproc",ne();case b.select:return e.err="select",ne();case b.function:{e.i++;let n=T(e),o="";return n?.kind==="word"&&(o=de(n.text),e.i++),Zs(e,e.i)&&(e.i+=Cn.length),Qs(e,o)}default:if(Zs(e,e.i+1))return e.i+=Cn.length+1,Qs(e,de(t.text))}return vl(e)}function Fl(e){C(T(e),gl)&&e.i++;let t=[],n=ne();for(;e.err===null;){n=fi(e),t.push(...n.cmds);let o=T(e);if(o!==void 0&&o.kind==="op"&&ti.includes(o.text)){e.i++;continue}break}if(n.simple!==null&&wl(n.simple))for(let o of t)o.endsInBoundedSink=!0;return t}function F(e,t){let n=[];for(;e.i<e.toks.length&&e.err===null;){let o=e.toks[e.i];if(e.bodies.has(e.i)){e.i++;continue}if(o.kind==="op"){if(o.text===De||o.text===ni)return n;if(o.text!==Ie){e.i++;continue}}if(o.kind==="word"&&t.includes(o.text))return n;let r=e.i;n.push(...Fl(e)),e.i===r&&e.err===null&&e.i++}return n}function Pe(e){let t=zs(e);if(t.end==="unterminated-quote")return{ok:!1,construct:"unterminated-quote"};if(t.end==="unterminated-heredoc")return{ok:!1,construct:"unterminated-heredoc"};if(t.end==="too-deep")return{ok:!1,construct:"nesting-too-deep"};let n={toks:t.tokens,src:e,bodies:new Set(t.heredocBodies),i:0,depth:0,err:null},o=[];for(;n.i<n.toks.length&&n.err===null;)o.push(...F(n,oi)),n.i<n.toks.length&&n.i++;return n.err!==null?{ok:!1,construct:n.err}:{ok:!0,commands:o}}import{join as St}from"node:path";import{join as Xl}from"node:path";var jl=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 path vanished. Fix: run ctx_doctor.",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_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 Gl(e,t){let n=jl[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 R=class extends Error{code;vars;constructor(t,n){super(Gl(t,n??{})),this.code=t,this.vars=n??{}}toLine(){return this.message}};var{mkdirSync:Bl,realpathSync:Wl}=process.getBuiltinModule("node:fs");function xe(e){let t=e.HOME;if(t!==void 0&&t!=="")return t;let n=e.USERPROFILE;return n!==void 0&&n!==""?n:null}function Kl(e){let t=xe(e);if(t!==null)return t;throw new R("NO_HOME",{name:process.platform==="win32"?"USERPROFILE":"HOME"})}function xi(e){let t=Xl(Kl(e),Bo.slice(1));return Bl(t,{recursive:!0}),Wl.native(t)}var{readFileSync:_i}=process.getBuiltinModule("node:fs");function pe(e){return e.agentId!==void 0&&e.agentId!==""}function Un(e,t){if(t===null)return"C";let n=Ne(e.agent),o=new Set(t);for(let r of Ke)if(o.has(n.toolNamePrefix+r))return"A";for(let r of n.nativeTools.shell)if(o.has(r))return"B";return"C"}function Mn(e,t){if(!pe(e))return null;let n=Ne(e.agent);if(t.manifestTools!==void 0)return mi(t.manifestTools.map(c=>Ln(n,c)));let o=e.agentType??"",r=ql(o,t);if(r===null)return null;let s=(r.tools??$l(n)).map(c=>Ln(n,c)),i=r.disallowed.map(c=>Ln(n,c));return mi(s.filter(c=>!i.some(a=>Zl(a,c))))}function ql(e,t){if(!Yl(e))return null;let n=Vl(t.env);if(e.indexOf(ce)>=0){if(n!==null){let s=Jl(n,e);if(s!==null)return s}}else{let s=Pn(St(t.projectDir,Je,ze,e+$e));if(s!==null)return s;if(n!==null){let i=Pn(St(n,Je,ze,e+$e));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 Yl(e){if(e===""||e==="."||e===".."||e.indexOf("/")>=0||e.indexOf("\\")>=0)return!1;for(let t of e.split(ce))if(t===""||t==="."||t==="..")return!1;return!0}function Vl(e){return xe(e)}function Jl(e,t){let n=t.indexOf(ce),o=t.slice(0,n),r=t.slice(n+ce.length);if(r.indexOf(ce)>=0)return null;let s;try{s=JSON.parse(_i(St(e,Je,Xo,Ko),"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(qo);if((a<0?c:c.slice(0,a))!==o)continue;let l=i[c];if(Array.isArray(l))for(let u of l){let f=u?.installPath;if(typeof f!="string"||f==="")continue;let d=Pn(St(f,ze,r+$e));if(d!==null)return d}}return null}function Pn(e){let t;try{t=_i(e,"utf8")}catch{return null}return zl(t)}function zl(e){let t=e.split(`
|
|
19
|
+
`).map(i=>i.endsWith("\r")?i.slice(0,-1):i);if(t.length===0||t[0].trim()!==zt)return null;let n=-1;for(let i=1;i<t.length;i++)if(t[i].trim()===zt){n=i;break}if(n<0)return null;let o=t.slice(1,n),r=pi(o,Yo),s=pi(o,Vo);return{tools:r!==null&&r.length>0?r:null,disallowed:s??[]}}function pi(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(Ei(c.slice(1).trim()))}return s.filter(i=>i!=="")}return r.startsWith("[")&&r.endsWith("]")&&(r=r.slice(1,-1)),r.split(",").map(s=>Ei(s.trim())).filter(s=>s!=="")}return null}function Ei(e){return e.length>1&&(e[0]==='"'||e[0]==="'")&&e.endsWith(e[0])?e.slice(1,-1):e}function $l(e){let t=e.nativeTools;return[...t.shell,...t.read??[],...t.grep??[],...t.webfetch??[],...t.edit??[],...Ke.map(n=>e.toolNamePrefix+n)]}function Ln(e,t){let n=t.indexOf("("),o=(n>=0?t.slice(0,n):t).trim();return e.id==="gemini"&&o.startsWith(Jo)?Ql(o):o}function Ql(e){let t="";for(let n of e){let o=n>="a"&&n<="z"||n>="A"&&n<="Z"||n>="0"&&n<="9"||zo.indexOf(n)>=0;t+=o?n:"_"}return t}function Zl(e,t){if(e.endsWith("*"))return t.startsWith(e.slice(0,-1));if(e===t)return!0;if(e.startsWith($t)){let n=e.slice($t.length);if(n!==""&&n.indexOf(Qt)<0)return t.startsWith(e+Qt)}return!1}function mi(e){return[...new Set(e.filter(t=>t!==""))]}var oe="",gi=Object.freeze({sudo:{valueShorts:"ugpChDrtUTR",valueLongs:["--user","--group","--prompt","--chdir","--host"],assignments:!0,duration:!1,refuseShorts:oe},env:{valueShorts:"uCS",valueLongs:["--unset","--chdir","--split-string"],assignments:!0,duration:!1,refuseShorts:oe},time:{valueShorts:"fo",valueLongs:["--format","--output"],assignments:!1,duration:!1,refuseShorts:oe},nice:{valueShorts:"n",valueLongs:["--adjustment"],assignments:!1,duration:!1,refuseShorts:oe},timeout:{valueShorts:"sk",valueLongs:["--signal","--kill-after"],assignments:!1,duration:!0,refuseShorts:oe},command:{valueShorts:oe,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:oe}}),eu=["bash","sh"],tu="c",nu=" -c",ou=["-o","+o","-O","+O"],Tt="-",ru="+",Hn="--",su="smhd",iu=".",hi=e=>e!==""&&e>="0"&&e<="9";function cu(e){if(e===""||!hi(e.charAt(0)))return!1;for(let t=0;t<e.length;t++){let n=e.charAt(t);if(!(hi(n)||n===iu))return t===e.length-1&&su.includes(n)}return!0}function au(e,t){let n=0;for(;n<t.length;){let o=t[n];if(o===Hn){n++;break}if(e.assignments&>(o)){n++;continue}if(o.startsWith(Hn)){n++,e.valueLongs.includes(o)&&n++;continue}if(o.startsWith(Tt)&&o.length>Tt.length){n++;for(let r of e.refuseShorts)if(o.includes(r))return null;for(let r=Tt.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||!cu(t[n]))return null;n++}return n<t.length?t.slice(n):null}function lu(e){let t=!1;for(let n=0;n<e.length;n++){let o=e[n];if(!o.startsWith(Hn)){if(o.startsWith(Tt)||o.startsWith(ru)){o.includes(tu)&&(t=!0),ou.includes(o)&&n++;continue}return t?o:null}}return null}function bi(e,t){let n={...e};return n.insideConstruct===void 0&&t.insideConstruct!==void 0&&(n.insideConstruct=t.insideConstruct),n}function vn(e,t,n,o){let r=[...t],s=e.argv0,i=e.args,c=e.redirectsToFile;for(;;){let a=s.toLowerCase();if(eu.includes(a)){let f=lu(i),d=f!==null&&n<ee?Pe(f):null;if(d===null||!d.ok)break;for(let x of d.commands){let E=bi(x,e);E.redirectsToFile=x.redirectsToFile||c,E.endsInBoundedSink=x.endsInBoundedSink||e.endsInBoundedSink,vn(E,[...r,a+nu],n+1,o)}return}let l=Object.hasOwn(gi,a)?gi[a]:void 0,u=l===void 0?null:au(l,i);if(u===null)break;r.push(a),s=In(u[0]),i=u.slice(1),c=c||Dn(s,i)}if(o.push({...e,argv0:s,args:i,redirectsToFile:c,wrappedBy:r}),!(n>=ee))for(let a of _t(e.raw)){let l=Pe(a.body);if(l.ok)for(let u of l.commands)vn(bi(u,e),[...t,a.wrapper],n+1,o)}}function Si(e){let t=[];for(let n of e)vn(n,[],0,t);return t}import{isAbsolute as du,join as Rt,relative as fu,sep as jn}from"node:path";var{readFileSync:uu}=process.getBuiltinModule("node:fs"),Fn=".claude",xu="CLAUDE_CONFIG_DIR",pu="settings.local.json",Ti="settings.json",Eu="Bash",mu="Read",Ri=":*",Oi="//",Ai="~/",yi="./",Ni="..",_u=`
|
|
20
|
+
\r`,gu=Object.freeze({tool:Eu});function hu(e,t){if(t!=="claude-code")return[];let n=process.env[xu],o=xe(process.env),r=n!==void 0&&n!==""?n:o===null?null:Rt(o,Fn),s=[Rt(e,Fn,pu),Rt(e,Fn,Ti)];return r===null?s:[...s,Rt(r,Ti)]}function Ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bu(e){let t;try{t=uu(e,"utf8")}catch(s){return s.code==="ENOENT"?{kind:"absent"}:{kind:"bad"}}let n;try{n=JSON.parse(t)}catch{return{kind:"bad"}}if(!Ci(n))return{kind:"bad"};let o=n.permissions;if(o===void 0)return{kind:"ok",deny:[]};if(!Ci(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 ki(e,t){let n=[];for(let o of hu(e,t)){let r=bu(o);if(r.kind==="bad")return null;r.kind==="ok"&&n.push(...r.deny)}return n}function Su(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 X(e,t,n){let o=Su(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 f=u<r,d=f?t[u]:"";switch(c.t){case"lit":a[u]=f&&d===c.c?s[u+1]:0;break;case"any1":a[u]=f&&!(n&&d==="/")?s[u+1]:0;break;case"star":a[u]=s[u]||(f&&!(n&&d==="/")?a[u+1]:0);break;case"globstar":a[u]=s[u]||(f?a[u+1]:0);break;case"globstarDir":f&&d==="/"&&s[u+1]&&(l=1),a[u]=s[u]||l;break}}s=a}return s[0]===1}function Tu(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 Ru(e,t){if(!e.endsWith(Ri))return X(e,t,!1);let n=e.slice(0,e.length-Ri.length);if(X(n,t,!1))return!0;for(let o=0;o<t.length;o++)if(_u.includes(t[o])&&X(n,t.slice(0,o),!1))return!0;return!1}var Ou=/^[A-Za-z]:(?=\/)/;function Ue(e){return jn==="/"?e:e.split(jn).join("/")}function Au(e,t,n){if(e.startsWith(yi)){if(n===void 0)return!1;let r=fu(n,t);return r===""||r===Ni||r.startsWith(Ni+jn)||du(r)?!1:X(e.slice(yi.length),Ue(r),!0)}let o=Ue(t);if(e.startsWith(Oi)){let r=Ue(e.slice(Oi.length-1));return X(r,o,!0)||X(r,o.replace(Ou,""),!0)}if(e.startsWith(Ai)){let r=xe(process.env);return r!==null&&X(Ue(r)+e.slice(Ai.length-1),o,!0)}return X(Ue(e),o,!0)}function K(e,t,n=gu){for(let o of t){let r=Tu(o);if(r===null||r.tool!==n.tool)continue;if(n.tool===mu?Au(r.glob,e,n.projectDir):Ru(r.glob,e))return o}return null}var Hx=Object.freeze({ctx_execute:"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.\n",ctx_batch:"Runs 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:"Stores 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:"Searches 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:"Returns 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:"Reports how many bytes context-mode kept out of the conversation in this session and in this project, per agent, as a Markdown table. Show the table to the user as it is. Use it when the user asks what context-mode saved.",ctx_doctor:"Checks 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 and the fix in one line. It changes nothing. Use it when the user asks whether context-mode works, or after a context-mode error.",ctx_upgrade:"Updates 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:"Deletes 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."}),Ii='context-mode: {size}-byte file, over the one-read limit. Run ctx_execute(language, code, file="{path}") and print only the answer.';var yu="{size}",Nu="{path}";function Gn(e,t,n=""){return U(Ii,n).split(yu).join(String(t)).split(Nu).join(e)}var{statSync:Cu}=process.getBuiltinModule("node:fs"),Li="Bash",Wn="Read",ku="WebFetch",Iu="ctx_execute",Du="ctx_batch",Pi="shell",wu="1",q="-",Xn="--",Lu="=",Pu=".",Di=",",Bn="p",Uu=["-e","--expression"],Mu=";&|(`\n\r",se=Object.freeze({kind:"allow"}),Y=e=>({kind:"deny",reason:e}),re=e=>typeof e=="string"?e:void 0,wi=e=>e!=null,V=(e,t)=>e.includes(t);function Ui(e,t,n){let o=e.tool;if(o===void 0)return se;let r=o.canonicalName,s=o.input,i;if(n===null){if(process.env[Wo]===wu)return Y(U(Qe,t.toolNamePrefix));process.stderr.write(cr+`
|
|
21
|
+
`),i=[]}else i=n;let c=Hu(r,s,e.cwd,i);return c!==null?Y(Te+c):r===ku?Gu(s,t):r===Li?Bu(e,t,s,i):r===Wn?Yu(e,t,s):se}function Mi(e,t,n,o){let r=e==="webfetch",s=r?rr.map(c=>n.toolNamePrefix+c).join(ir):n.toolNamePrefix+or,i=JSON.stringify(r?{url:t}:{language:Pi,code:t,intent:o??nr});return[$o+Qo[e]+Zo,er,tr+s,i].join(`
|
|
22
|
+
`)}function Hi(e){for(let t of Sr){let n=re(e[t]);if(n!==void 0&&n!=="")return n}}function Hu(e,t,n,o){if(o.length===0)return null;let r=s=>K(Kn(n,s),o,{tool:Wn,projectDir:n});if(e===Li){let s=re(t.command);return s===void 0?null:K(s,o)}if(e===Wn){let s=Hi(t);return s===void 0?null:r(s)}if(e===Iu){let s=re(t.file),i=s===void 0||s===""?null:r(s);if(i!==null)return i;let c=re(t.code);return t.language===Pi&&c!==void 0?K(c,o):null}if(e===Du&&Array.isArray(t.commands))for(let s of t.commands){let i=typeof s=="string"?K(s,o):null;if(i!==null)return i}return null}function vu(e,t){return t.length===0?null:K([e.argv0,...e.args].join(" "),t)??K(e.raw,t)}function Fu(e,t){if(t.length===0)return!1;for(let n=0;n<=e.length;n++)if(!(n>0&&!Mu.includes(e.charAt(n-1)))&&K(e.slice(n).trimStart(),t)!==null)return!0;return!1}function ju(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!1}return ar.some(n=>t===n||t.endsWith(Pu+n))}function Gu(e,t){let n=re(e.url)??"";return ju(n)?se:Y(Mi("webfetch",n,t))}function Bu(e,t,n,o){let r=re(n.command)??"",s=Pe(r);if(!s.ok)return Fu(r,o)?Y(U(Ze,t.toolNamePrefix)):se;let i=Si(s.commands);for(let c of i){let a=vu(c,o);if(a!==null)return Y(Te+a)}if(!ye(t)||pe(e))for(let c of i){let a=Wu(c);if(a!==null)return Y(Mi(a,r,t,re(n.description)))}return Vu(i,e.cwd,t)??se}function Wu(e){let t=e.argv0.toLowerCase();return V(lr,t)&&Xu(t,e)?"curl":qu(e.raw)?"http":V(xr,t)?"build":null}function Xu(e,t){return t.redirectsToFile?!Ku(e,t.args):!t.endsInBoundedSink}function Ku(e,t){let n=ur[e],o=!1;for(let r=0;r<t.length;r++){let s=t[r];if(s===Xn)break;if(V(dr,s)||s===fr&&t[r+1]===q)return!1;(s===n.long||s.startsWith(q)&&!s.startsWith(Xn)&&s.includes(n.short,q.length))&&(o=!0)}return o}function qu(e){let t=e.toLowerCase();for(let n of mr)if(t.includes(n))return!0;for(let n=t.indexOf(Re);n>=0;n=t.indexOf(Re,n+1)){let o=t.charAt(n+Re.length);if(o!==""&&pr.includes(o)&&t.startsWith(Er,n+Re.length+o.length))return!0}return!1}function vi(e){try{let t=Cu(e);return t.isFile()?t.size:-1}catch{return-1}}function Yu(e,t,n){if(!wi(n.offset)&&!wi(n.limit)){let o=Hi(n);if(o!==void 0){let r=Kn(e.cwd,o),s=vi(r);if(s>be)return Y(Gn(r,s,t.toolNamePrefix))}}return se}function Vu(e,t,n){if(n.nativeTools.read!==void 0&&n.nativeTools.read.length>0&&Hs(n)||e.length!==1)return null;let o=e[0];if(o.redirectsToFile||o.endsInBoundedSink)return null;let r=o.argv0.toLowerCase();if(!V(_r,r))return null;let s=$u(r,o.args);if(s===null)return null;if(s.bounded)return se;let i=Kn(t,s.file),c=vi(i);return c>be?Y(Gn(i,c,n.toolNamePrefix)):null}var Ot=e=>e!==""&&[...e].every(t=>t>="0"&&t<="9");function Ju(e){if(V(Zt,e))return 1;for(let t of Zt)if(t.startsWith(Xn)?e.startsWith(t+Lu):e.startsWith(t))return 0;return e.startsWith(q)&&Ot(e.slice(q.length))?0:-1}function zu(e){if(e===Bn)return"all";if(!e.endsWith(Bn))return null;let t=e.slice(0,e.length-Bn.length),n=t.indexOf(Di);return(n<0?Ot(t):Ot(t.slice(0,n))&&Ot(t.slice(n+Di.length)))?"range":null}function $u(e,t){let n=[],o=!1,r=!1,s;for(let i=0;i<t.length;i++){let c=t[i];if(V(gr,e)){let a=Ju(c);if(a>=0){o=!0,i+=a;continue}}if(e===et&&V(hr,c)){r=!0;continue}if(e===et&&V(Uu,c)){s=t[i+1],i++;continue}c.startsWith(q)&&c!==q||n.push(c)}if(e===et){if(!r)return null;s===void 0&&(s=n.shift());let i=s===void 0?null:zu(s);if(i===null)return null;o=i==="range"}return e===br&&n.shift()!==I.identity?null:n.length===1&&n[0]!==q?{file:n[0],bounded:o}:null}import{basename as id,dirname as yt,join as He,resolve as Bi}from"node:path";import{dirname as Fi,sep as Zu}from"node:path";var{realpathSync:Qu}=process.getBuiltinModule("node:fs");function ed(e){try{return Qu.native(e)}catch{return}}function At(e){return e.split(Zu).filter(t=>t!=="")}function ji(e){let t=e.map(ed).filter(s=>s!==void 0);if(t.length===0)throw new RangeError("commonRoot needs at least one existing path");let n=t[0],o=At(n).length;for(let s of t){let i=At(s),c=At(n),a=0;for(;a<o&&a<i.length&&i[a]===c[a];)a+=1;o=a}let r=n;for(;At(r).length>o&&Fi(r)!==r;)r=Fi(r);return r}var td=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]),nd=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],w=(e,t)=>e>>>t|e<<32-t;function Gi(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=nd.slice(),i=new Uint32Array(64);for(let c=0;c<o;c+=64){for(let _=0;_<16;_++)i[_]=r.readUInt32BE(c+_*4);for(let _=16;_<64;_++){let S=w(i[_-15],7)^w(i[_-15],18)^i[_-15]>>>3,h=w(i[_-2],17)^w(i[_-2],19)^i[_-2]>>>10;i[_]=i[_-16]+S+i[_-7]+h>>>0}let[a,l,u,f,d,x,E,m]=s;for(let _=0;_<64;_++){let S=m+(w(d,6)^w(d,11)^w(d,25))+(d&x^~d&E)+td[_]+i[_]>>>0,h=(w(a,2)^w(a,13)^w(a,22))+(a&l^a&u^l&u)>>>0;m=E,E=x,x=d,d=f+S>>>0,f=u,u=l,l=a,a=S+h>>>0}s[0]=s[0]+a>>>0,s[1]=s[1]+l>>>0,s[2]=s[2]+u>>>0,s[3]=s[3]+f>>>0,s[4]=s[4]+d>>>0,s[5]=s[5]+x>>>0,s[6]=s[6]+E>>>0,s[7]=s[7]+m>>>0}return s.map(c=>c.toString(16).padStart(8,"0")).join("")}var{existsSync:od,readFileSync:rd,realpathSync:qn,statSync:sd}=process.getBuiltinModule("node:fs");function cd(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 Me(e){return e===void 0||e===""?void 0:e}function ad(e,t){switch(e){case"env:CLAUDE_PROJECT_DIR":return Me(t.env.CLAUDE_PROJECT_DIR)??Me(t.cwd)??process.cwd();case"arg:--agent+cwd":case"spawn-cwd":return Me(t.cwd);case"arg:workspaceFolder":{let n=t.argv.indexOf(Ve);return n<0?void 0:Me(t.argv[n+1])}case"pi:ctx.cwd":return Me(t.piCwd)}}function ld(e){let t;try{t=qn.native(e)}catch{throw new R("NO_GIT_DIR",{path:e})}for(;;){let n=ud(He(t,qt));if(n!==null){let r=Wi(He(n,Fo));return{commonDir:qn.native(r===null?n:Bi(n,r)),worktree:t}}let o=yt(t);if(o===t)return null;t=o}}function ud(e){let t;try{if(sd(e).isDirectory())t=e;else{let n=Wi(e);if(n===null||!n.startsWith(Vt))return null;t=Bi(yt(e),n.slice(Vt.length))}}catch{return null}return od(He(t,jo))?t:null}function Wi(e){let t;try{t=rd(e,"utf8")}catch{return null}let n=t.indexOf(`
|
|
23
|
+
`),o=(n<0?t:t.slice(0,n)).trim();return o===""?null:o}function dd(e,t){let{spawnSync:n}=process.getBuiltinModule("node:child_process"),o=n("git",t,{cwd:e,shell:!1,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(o.error!==void 0||o.status!==0)throw new R("NO_GIT_DIR",{path:e});return o.stdout.split(`
|
|
24
|
+
`).filter(r=>r!=="")}function fd(e,t){let n=id(t)===qt?yt(t):t,o=dd(e,["worktree","list","--porcelain"]).filter(r=>r.startsWith(Yt)).map(r=>r.slice(Yt.length));return ji([yt(n),...o])}function Xi(e,t){let n=cd(e),o=ad(n,t);if(o===void 0)throw new R("NO_PROJECT",{kind:n});let r=ld(o),s=r===null?qn.native(o):void 0,i=r?.commonDir??s,c=r?.worktree??s,a=Gi(i).slice(0,Mo),l=He(xi(process.env),Ho,a),u;return{projectKey:a,projectDir:l,dbPath:He(l,vo),worktree:c,get containmentRoot(){return u??=s??fd(o,i),u},agent:e,source:n}}var Nt=Se,xd=`
|
|
25
25
|
PRAGMA busy_timeout = ${ie};
|
|
26
26
|
PRAGMA journal_mode = WAL;
|
|
27
|
-
`,
|
|
27
|
+
`,Ct="tokenize = 'porter unicode61 remove_diacritics 2'",pd="tokenize = 'unicode61 remove_diacritics 2'",Ed=`
|
|
28
28
|
CREATE TABLE IF NOT EXISTS events (
|
|
29
29
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
30
30
|
session_id TEXT NOT NULL,
|
|
@@ -69,16 +69,16 @@ CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
|
|
|
69
69
|
agent UNINDEXED,
|
|
70
70
|
ord UNINDEXED,
|
|
71
71
|
body,
|
|
72
|
-
${
|
|
72
|
+
${pd}
|
|
73
73
|
);
|
|
74
74
|
|
|
75
75
|
CREATE TABLE IF NOT EXISTS meta (
|
|
76
76
|
key TEXT PRIMARY KEY,
|
|
77
77
|
value TEXT NOT NULL
|
|
78
78
|
);
|
|
79
|
-
`,
|
|
79
|
+
`,md=`
|
|
80
80
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_events_cost_session_turn ON events(session_id, turn) WHERE kind = 'cost';
|
|
81
|
-
`,
|
|
81
|
+
`,_d=`
|
|
82
82
|
CREATE VIRTUAL TABLE chunks_v3 USING fts5(
|
|
83
83
|
source_id UNINDEXED,
|
|
84
84
|
session_id UNINDEXED,
|
|
@@ -87,13 +87,13 @@ CREATE VIRTUAL TABLE chunks_v3 USING fts5(
|
|
|
87
87
|
ord UNINDEXED,
|
|
88
88
|
body,
|
|
89
89
|
title,
|
|
90
|
-
${
|
|
90
|
+
${Ct}
|
|
91
91
|
);
|
|
92
92
|
INSERT INTO chunks_v3(rowid, source_id, session_id, worktree, agent, ord, body, title)
|
|
93
93
|
SELECT rowid, source_id, session_id, worktree, agent, ord, body, '' FROM chunks;
|
|
94
94
|
DROP TABLE chunks;
|
|
95
95
|
ALTER TABLE chunks_v3 RENAME TO chunks;
|
|
96
|
-
`,
|
|
96
|
+
`,gd=`
|
|
97
97
|
CREATE VIRTUAL TABLE chunks_tri USING fts5(
|
|
98
98
|
body,
|
|
99
99
|
title,
|
|
@@ -102,30 +102,30 @@ CREATE VIRTUAL TABLE chunks_tri USING fts5(
|
|
|
102
102
|
);
|
|
103
103
|
INSERT INTO chunks_tri(rowid, body, title) SELECT rowid, body, title FROM chunks;
|
|
104
104
|
CREATE VIRTUAL TABLE chunks_vocab USING fts5vocab(chunks, 'row');
|
|
105
|
-
`,
|
|
105
|
+
`,hd=`
|
|
106
106
|
CREATE VIRTUAL TABLE line_units USING fts5(
|
|
107
107
|
body,
|
|
108
108
|
source_id UNINDEXED,
|
|
109
109
|
session_id UNINDEXED,
|
|
110
110
|
ord UNINDEXED,
|
|
111
|
-
${
|
|
111
|
+
${Ct}
|
|
112
112
|
);
|
|
113
|
-
`,od=[{version:1,sql:Qu},{version:2,sql:Zu},{version:3,sql:ed},{version:4,sql:td},{version:5,sql:nd}];function Kn(e,t){if(t!==At){if(t>At)throw new R("SCHEMA_STALE",{found:t,want:At});e.exec(zu),e.exec("BEGIN IMMEDIATE");try{for(let n of od)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${At}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}var{existsSync:He,linkSync:rd,mkdirSync:sd,rmSync:id}=process.getBuiltinModule("node:fs");function Hi(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function cd(e,t){let n=Hi(e),o=Hi(t);for(let r=0;r<o.length;r+=1){let s=n[r]??0;if(s!==o[r])return s<o[r]}return!1}function ad(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&Io;return n===Do||n===wo}async function ld(){try{return await import("node:sqlite")}catch{throw new R("NO_SQLITE")}}function qn(e){return e.prepare("PRAGMA user_version").get().user_version}function ud(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+Co;try{let r=new e.DatabaseSync(o,{timeout:ie});try{Kn(r,qn(r))}finally{r.close()}try{rd(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",Ke,qe])id(o+r,{force:!0})}}function vi(e,t){let n=null;try{return He(t)||ud(e,t),n=new e.DatabaseSync(t,{timeout:ie}),Kn(n,qn(n)),n}catch(o){throw n&&n.close(),o}}function dd(e,t){let n=new e.DatabaseSync(t,{timeout:ie,readOnly:!0});try{let o=qn(n);if(o!==be)throw new R("SCHEMA_STALE",{found:o,want:be});return n}catch(o){throw n.close(),o}}async function y(e,t){if(cd(process.version,Yt))throw new R("NODE_TOO_OLD",{v:process.version});let n=await ld();sd(e.projectDir,{recursive:!0});let o=e.dbPath;if((He(o+Ke)||He(o+qe))&&!He(o))throw new R("DB_GONE");try{let s;return t?.readOnly===!0?(He(o)||vi(n,o).close(),s=dd(n,o)):s=vi(n,o),{raw:s,projectKey:e.projectKey,path:o}}catch(s){throw ad(s)?new R("DB_CORRUPT"):s}}function L(e,t){e.raw.exec("BEGIN IMMEDIATE");try{let n=t(e);return e.raw.exec("COMMIT"),n}catch(n){throw e.raw.isTransaction&&e.raw.exec("ROLLBACK"),n}}function Fi(e,t){return e.raw.isTransaction?t(e):L(e,t)}function V(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function j(e,t,n){Fi(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function Nt(e,t){return Fi(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var ji="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",fd="INSERT INTO "+ji,xd="INSERT OR IGNORE INTO "+ji,pd="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function kt(e,t){return L(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?xd:fd).run(t.session_id,t.worktree,t.agent,t.kind,t.tool,t.key,t.path,t.ok,t.exit_code,t.bytes,t.body,t.turn,t.sandbox_bytes,t.returned_bytes,o,o);return s.changes===1?Number(s.lastInsertRowid):n.raw.prepare(pd).get(t.session_id,t.turn).seq})}function Gi(e,t){let n="",o="",r=!1,s=!1;for(let i of t){if(o===""&&!r&&i.trim()===""){s=n!=="";continue}s&&(n+=" ",s=!1),n+=i,r?r=!1:i==="\\"&&o!=="'"?r=!0:o===""&&(i==="'"||i==='"')?o=i:i===o&&(o="")}return e+":"+n}function Yn(e,t,n){return t===""?[]:n===void 0?e.raw.prepare("SELECT * FROM events WHERE session_id = ? ORDER BY seq ASC").all(t):e.raw.prepare("SELECT * FROM events WHERE session_id = ? AND kind = ? ORDER BY seq ASC").all(t,n)}function Bi(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq DESC LIMIT 1").get(t);return n===void 0?"":n.body}function Wi(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq ASC LIMIT 1").get(t);return n===void 0?"":n.body}function Xi(e,t,n,o){return t===""?[]:e.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND (session_id = ? OR worktree = ?) ORDER BY seq DESC LIMIT ?").all(t,n,o)}function Ki(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function qi(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var Jn=Object.freeze([170,170,178,179,181,181,185,186,188,190,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,895,895,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1327,1329,1366,1369,1369,1376,1416,1488,1514,1519,1522,1568,1610,1632,1641,1646,1647,1649,1747,1749,1749,1765,1766,1774,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1984,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2144,2154,2160,2183,2185,2191,2208,2249,2308,2361,2365,2365,2384,2384,2392,2401,2406,2415,2417,2432,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2534,2545,2548,2553,2556,2556,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2662,2671,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2790,2799,2809,2809,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2918,2927,2929,2935,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3046,3058,3077,3084,3086,3088,3090,3112,3114,3129,3133,3133,3160,3162,3164,3165,3168,3169,3174,3183,3192,3198,3200,3200,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3292,3294,3296,3297,3302,3311,3313,3314,3332,3340,3342,3344,3346,3386,3389,3389,3406,3406,3412,3414,3416,3425,3430,3448,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3558,3567,3585,3632,3634,3635,3648,3654,3664,3673,3713,3714,3716,3716,3718,3722,3724,3747,3749,3749,3751,3760,3762,3763,3773,3773,3776,3780,3782,3782,3792,3801,3804,3807,3840,3840,3872,3891,3904,3911,3913,3948,3976,3980,4096,4138,4159,4169,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4240,4249,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4969,4988,4992,5007,5024,5109,5112,5117,5121,5740,5743,5759,5761,5786,5792,5866,5870,5880,5888,5905,5919,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6112,6121,6128,6137,6160,6169,6176,6264,6272,6276,6279,6312,6314,6314,6320,6389,6400,6430,6470,6509,6512,6516,6528,6571,6576,6601,6608,6618,6656,6678,6688,6740,6784,6793,6800,6809,6823,6823,6917,6963,6981,6988,6992,7001,7043,7072,7086,7141,7168,7203,7232,7241,7245,7293,7296,7306,7312,7354,7357,7359,7401,7404,7406,7411,7413,7414,7418,7418,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8304,8305,8308,8313,8319,8329,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8528,8585,9312,9371,9450,9471,10102,10131,11264,11492,11499,11502,11506,11507,11517,11517,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12591,12593,12686,12690,12693,12704,12735,12784,12799,12832,12841,12872,12879,12881,12895,12928,12937,12977,12991,13312,19903,19968,42124,42192,42237,42240,42508,42512,42539,42560,42606,42623,42653,42656,42735,42775,42783,42786,42888,42891,42972,42993,43009,43011,43013,43015,43018,43020,43042,43056,43061,43072,43123,43138,43187,43216,43225,43250,43255,43259,43259,43261,43262,43264,43301,43312,43334,43360,43388,43396,43442,43471,43481,43488,43492,43494,43518,43520,43560,43584,43586,43588,43595,43600,43609,43616,43638,43642,43642,43646,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43824,43866,43868,43881,43888,44002,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65296,65305,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500,65536,65547,65549,65574,65576,65594,65596,65597,65599,65613,65616,65629,65664,65786,65799,65843,65856,65912,65930,65931,66176,66204,66208,66256,66273,66299,66304,66339,66349,66378,66384,66421,66432,66461,66464,66499,66504,66511,66513,66517,66560,66717,66720,66729,66736,66771,66776,66811,66816,66855,66864,66915,66928,66938,66940,66954,66956,66962,66964,66965,66967,66977,66979,66993,66995,67001,67003,67004,67008,67059,67072,67382,67392,67413,67424,67431,67456,67461,67463,67504,67506,67514,67584,67589,67592,67592,67594,67637,67639,67640,67644,67644,67647,67669,67672,67702,67705,67742,67751,67759,67808,67826,67828,67829,67835,67867,67872,67897,67904,67929,67968,68023,68028,68047,68050,68096,68112,68115,68117,68119,68121,68149,68160,68168,68192,68222,68224,68255,68288,68295,68297,68324,68331,68335,68352,68405,68416,68437,68440,68466,68472,68497,68521,68527,68608,68680,68736,68786,68800,68850,68858,68899,68912,68921,68928,68965,68975,68997,69216,69246,69248,69289,69296,69297,69314,69319,69376,69415,69424,69445,69457,69460,69488,69505,69552,69579,69600,69622,69635,69687,69714,69743,69745,69746,69749,69749,69763,69807,69840,69864,69872,69881,69891,69926,69942,69951,69956,69956,69959,69959,69968,70002,70006,70006,70019,70066,70081,70084,70096,70106,70108,70108,70113,70132,70144,70161,70163,70187,70207,70208,70272,70278,70280,70280,70282,70285,70287,70301,70303,70312,70320,70366,70384,70393,70405,70412,70415,70416,70419,70440,70442,70448,70450,70451,70453,70457,70461,70461,70480,70480,70493,70497,70528,70537,70539,70539,70542,70542,70544,70581,70583,70583,70609,70609,70611,70611,70656,70708,70727,70730,70736,70745,70751,70753,70784,70831,70852,70853,70855,70855,70864,70873,71040,71086,71128,71131,71168,71215,71236,71236,71248,71257,71296,71338,71352,71352,71360,71369,71376,71395,71424,71450,71472,71483,71488,71494,71680,71723,71840,71922,71935,71942,71945,71945,71948,71955,71957,71958,71960,71983,71999,71999,72001,72001,72016,72025,72096,72103,72106,72144,72161,72161,72163,72163,72192,72192,72203,72242,72250,72250,72272,72272,72284,72329,72349,72349,72368,72440,72640,72672,72688,72697,72704,72712,72714,72750,72768,72768,72784,72812,72818,72847,72960,72966,72968,72969,72971,73008,73030,73030,73040,73049,73056,73061,73063,73064,73066,73097,73112,73112,73120,73129,73136,73179,73184,73193,73440,73458,73474,73474,73476,73488,73490,73523,73552,73561,73648,73648,73664,73684,73728,74649,74752,74862,74880,75075,77712,77808,77824,78895,78913,78918,78944,82938,82944,83526,90368,90397,90416,90425,92160,92728,92736,92766,92768,92777,92784,92862,92864,92873,92880,92909,92928,92975,92992,92995,93008,93017,93019,93025,93027,93047,93053,93071,93504,93548,93552,93561,93760,93846,93856,93880,93883,93907,93952,94026,94032,94032,94099,94111,94176,94177,94179,94179,94194,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,113664,113770,113776,113788,113792,113800,113808,113817,118e3,118009,119488,119507,119520,119539,119648,119672,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,120782,120831,122624,122654,122661,122666,122928,122989,123136,123180,123191,123197,123200,123209,123214,123214,123536,123565,123584,123627,123632,123641,124112,124139,124144,124153,124368,124397,124400,124410,124608,124638,124640,124642,124644,124645,124647,124653,124656,124660,124670,124671,124896,124902,124904,124907,124909,124910,124912,124926,124928,125124,125127,125135,125184,125251,125259,125259,125264,125273,126065,126123,126125,126127,126129,126132,126209,126253,126255,126269,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,127232,127244,130032,130041,131072,173791,173824,178205,178208,183981,183984,191456,191472,192093,194560,195101,196608,201546,201552,210041]);function Ed(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=Jn.length/2-1;for(;t<=n;){let o=t+n>>1,r=Jn[2*o],s=Jn[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function md(e,t){let n=[],o=-1,r=0;for(let s of e)t(s.codePointAt(0))?o>=0&&(n.push(e.slice(o,r)),o=-1):o<0&&(o=r),r+=s.length;return o>=0&&n.push(e.slice(o)),n}function Yi(e){return md(e,t=>!Ed(t))}var _d=`
|
|
113
|
+
`,bd=[{version:1,sql:Ed},{version:2,sql:md},{version:3,sql:_d},{version:4,sql:gd},{version:5,sql:hd}];function Yn(e,t){if(t!==Nt){if(t>Nt)throw new R("SCHEMA_STALE",{found:t,want:Nt});e.exec(xd),e.exec("BEGIN IMMEDIATE");try{for(let n of bd)n.version>t&&e.exec(n.sql);e.exec(`PRAGMA user_version = ${Nt}`),e.exec("COMMIT")}catch(n){throw e.isTransaction&&e.exec("ROLLBACK"),n}}}var{existsSync:ve,linkSync:Sd,mkdirSync:Td,rmSync:Rd}=process.getBuiltinModule("node:fs");function Ki(e){return(e.startsWith("v")?e.slice(1):e).split(".").map(n=>Number.parseInt(n,10))}function Od(e,t){let n=Ki(e),o=Ki(t);for(let r=0;r<o.length;r+=1){let s=n[r]??0;if(s!==o[r])return s<o[r]}return!1}function Ad(e){if(typeof e!="object"||e===null)return!1;let t=e.errcode;if(typeof t!="number")return!1;let n=t&Lo;return n===Po||n===Uo}async function yd(){try{return await import("node:sqlite")}catch{throw new R("NO_SQLITE")}}function Vn(e){return e.prepare("PRAGMA user_version").get().user_version}function Nd(e,t){let{randomUUID:n}=process.getBuiltinModule("node:crypto"),o=t+"."+n()+wo;try{let r=new e.DatabaseSync(o,{timeout:ie});try{Yn(r,Vn(r))}finally{r.close()}try{Sd(o,t)}catch(s){if(s.code!=="EEXIST")throw s}}finally{for(let r of["",qe,Ye])Rd(o+r,{force:!0})}}function qi(e,t){let n=null;try{return ve(t)||Nd(e,t),n=new e.DatabaseSync(t,{timeout:ie}),Yn(n,Vn(n)),n}catch(o){throw n&&n.close(),o}}function Cd(e,t){let n=new e.DatabaseSync(t,{timeout:ie,readOnly:!0});try{let o=Vn(n);if(o!==Se)throw new R("SCHEMA_STALE",{found:o,want:Se});return n}catch(o){throw n.close(),o}}async function y(e,t){if(Od(process.version,Jt))throw new R("NODE_TOO_OLD",{v:process.version});let n=await yd();Td(e.projectDir,{recursive:!0});let o=e.dbPath;if((ve(o+qe)||ve(o+Ye))&&!ve(o))throw new R("DB_GONE");try{let s;return t?.readOnly===!0?(ve(o)||qi(n,o).close(),s=Cd(n,o)):s=qi(n,o),{raw:s,projectKey:e.projectKey,path:o}}catch(s){throw Ad(s)?new R("DB_CORRUPT"):s}}function L(e,t){e.raw.exec("BEGIN IMMEDIATE");try{let n=t(e);return e.raw.exec("COMMIT"),n}catch(n){throw e.raw.isTransaction&&e.raw.exec("ROLLBACK"),n}}function Yi(e,t){return e.raw.isTransaction?t(e):L(e,t)}function J(e,t){let n=e.raw.prepare("SELECT value FROM meta WHERE key = ?").get(t);return n===void 0?null:n.value}function j(e,t,n){Yi(e,o=>{o.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)})}function kt(e,t){return Yi(e,n=>{let o=n.raw.prepare("DELETE FROM meta WHERE key = ? RETURNING value").get(t);return o===void 0?null:o.value})}var Vi="events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",kd="INSERT INTO "+Vi,Id="INSERT OR IGNORE INTO "+Vi,Dd="SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";function It(e,t){return L(e,n=>{let o=Date.now(),r=t.kind==="cost",s=n.raw.prepare(r?Id:kd).run(t.session_id,t.worktree,t.agent,t.kind,t.tool,t.key,t.path,t.ok,t.exit_code,t.bytes,t.body,t.turn,t.sandbox_bytes,t.returned_bytes,o,o);return s.changes===1?Number(s.lastInsertRowid):n.raw.prepare(Dd).get(t.session_id,t.turn).seq})}function Ji(e,t){let n="",o="",r=!1,s=!1;for(let i of t){if(o===""&&!r&&i.trim()===""){s=n!=="";continue}s&&(n+=" ",s=!1),n+=i,r?r=!1:i==="\\"&&o!=="'"?r=!0:o===""&&(i==="'"||i==='"')?o=i:i===o&&(o="")}return e+":"+n}function Jn(e,t,n){return t===""?[]:n===void 0?e.raw.prepare("SELECT * FROM events WHERE session_id = ? ORDER BY seq ASC").all(t):e.raw.prepare("SELECT * FROM events WHERE session_id = ? AND kind = ? ORDER BY seq ASC").all(t,n)}function zi(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq DESC LIMIT 1").get(t);return n===void 0?"":n.body}function $i(e,t){if(t==="")return"";let n=e.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq ASC LIMIT 1").get(t);return n===void 0?"":n.body}function Qi(e,t,n,o){return t===""?[]:e.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND (session_id = ? OR worktree = ?) ORDER BY seq DESC LIMIT ?").all(t,n,o)}function Zi(e,t,n){return e.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(t,n)!==void 0}function ec(e,t){return e.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(t)!==void 0}var zn=Object.freeze([170,170,178,179,181,181,185,186,188,190,192,214,216,246,248,705,710,721,736,740,748,748,750,750,880,884,886,887,890,893,895,895,902,902,904,906,908,908,910,929,931,1013,1015,1153,1162,1327,1329,1366,1369,1369,1376,1416,1488,1514,1519,1522,1568,1610,1632,1641,1646,1647,1649,1747,1749,1749,1765,1766,1774,1788,1791,1791,1808,1808,1810,1839,1869,1957,1969,1969,1984,2026,2036,2037,2042,2042,2048,2069,2074,2074,2084,2084,2088,2088,2112,2136,2144,2154,2160,2183,2185,2191,2208,2249,2308,2361,2365,2365,2384,2384,2392,2401,2406,2415,2417,2432,2437,2444,2447,2448,2451,2472,2474,2480,2482,2482,2486,2489,2493,2493,2510,2510,2524,2525,2527,2529,2534,2545,2548,2553,2556,2556,2565,2570,2575,2576,2579,2600,2602,2608,2610,2611,2613,2614,2616,2617,2649,2652,2654,2654,2662,2671,2674,2676,2693,2701,2703,2705,2707,2728,2730,2736,2738,2739,2741,2745,2749,2749,2768,2768,2784,2785,2790,2799,2809,2809,2821,2828,2831,2832,2835,2856,2858,2864,2866,2867,2869,2873,2877,2877,2908,2909,2911,2913,2918,2927,2929,2935,2947,2947,2949,2954,2958,2960,2962,2965,2969,2970,2972,2972,2974,2975,2979,2980,2984,2986,2990,3001,3024,3024,3046,3058,3077,3084,3086,3088,3090,3112,3114,3129,3133,3133,3160,3162,3164,3165,3168,3169,3174,3183,3192,3198,3200,3200,3205,3212,3214,3216,3218,3240,3242,3251,3253,3257,3261,3261,3292,3294,3296,3297,3302,3311,3313,3314,3332,3340,3342,3344,3346,3386,3389,3389,3406,3406,3412,3414,3416,3425,3430,3448,3450,3455,3461,3478,3482,3505,3507,3515,3517,3517,3520,3526,3558,3567,3585,3632,3634,3635,3648,3654,3664,3673,3713,3714,3716,3716,3718,3722,3724,3747,3749,3749,3751,3760,3762,3763,3773,3773,3776,3780,3782,3782,3792,3801,3804,3807,3840,3840,3872,3891,3904,3911,3913,3948,3976,3980,4096,4138,4159,4169,4176,4181,4186,4189,4193,4193,4197,4198,4206,4208,4213,4225,4238,4238,4240,4249,4256,4293,4295,4295,4301,4301,4304,4346,4348,4680,4682,4685,4688,4694,4696,4696,4698,4701,4704,4744,4746,4749,4752,4784,4786,4789,4792,4798,4800,4800,4802,4805,4808,4822,4824,4880,4882,4885,4888,4954,4969,4988,4992,5007,5024,5109,5112,5117,5121,5740,5743,5759,5761,5786,5792,5866,5870,5880,5888,5905,5919,5937,5952,5969,5984,5996,5998,6e3,6016,6067,6103,6103,6108,6108,6112,6121,6128,6137,6160,6169,6176,6264,6272,6276,6279,6312,6314,6314,6320,6389,6400,6430,6470,6509,6512,6516,6528,6571,6576,6601,6608,6618,6656,6678,6688,6740,6784,6793,6800,6809,6823,6823,6917,6963,6981,6988,6992,7001,7043,7072,7086,7141,7168,7203,7232,7241,7245,7293,7296,7306,7312,7354,7357,7359,7401,7404,7406,7411,7413,7414,7418,7418,7424,7615,7680,7957,7960,7965,7968,8005,8008,8013,8016,8023,8025,8025,8027,8027,8029,8029,8031,8061,8064,8116,8118,8124,8126,8126,8130,8132,8134,8140,8144,8147,8150,8155,8160,8172,8178,8180,8182,8188,8304,8305,8308,8313,8319,8329,8336,8348,8450,8450,8455,8455,8458,8467,8469,8469,8473,8477,8484,8484,8486,8486,8488,8488,8490,8493,8495,8505,8508,8511,8517,8521,8526,8526,8528,8585,9312,9371,9450,9471,10102,10131,11264,11492,11499,11502,11506,11507,11517,11517,11520,11557,11559,11559,11565,11565,11568,11623,11631,11631,11648,11670,11680,11686,11688,11694,11696,11702,11704,11710,11712,11718,11720,11726,11728,11734,11736,11742,11823,11823,12293,12295,12321,12329,12337,12341,12344,12348,12353,12438,12445,12447,12449,12538,12540,12543,12549,12591,12593,12686,12690,12693,12704,12735,12784,12799,12832,12841,12872,12879,12881,12895,12928,12937,12977,12991,13312,19903,19968,42124,42192,42237,42240,42508,42512,42539,42560,42606,42623,42653,42656,42735,42775,42783,42786,42888,42891,42972,42993,43009,43011,43013,43015,43018,43020,43042,43056,43061,43072,43123,43138,43187,43216,43225,43250,43255,43259,43259,43261,43262,43264,43301,43312,43334,43360,43388,43396,43442,43471,43481,43488,43492,43494,43518,43520,43560,43584,43586,43588,43595,43600,43609,43616,43638,43642,43642,43646,43695,43697,43697,43701,43702,43705,43709,43712,43712,43714,43714,43739,43741,43744,43754,43762,43764,43777,43782,43785,43790,43793,43798,43808,43814,43816,43822,43824,43866,43868,43881,43888,44002,44016,44025,44032,55203,55216,55238,55243,55291,63744,64109,64112,64217,64256,64262,64275,64279,64285,64285,64287,64296,64298,64310,64312,64316,64318,64318,64320,64321,64323,64324,64326,64433,64467,64829,64848,64911,64914,64967,65008,65019,65136,65140,65142,65276,65296,65305,65313,65338,65345,65370,65382,65470,65474,65479,65482,65487,65490,65495,65498,65500,65536,65547,65549,65574,65576,65594,65596,65597,65599,65613,65616,65629,65664,65786,65799,65843,65856,65912,65930,65931,66176,66204,66208,66256,66273,66299,66304,66339,66349,66378,66384,66421,66432,66461,66464,66499,66504,66511,66513,66517,66560,66717,66720,66729,66736,66771,66776,66811,66816,66855,66864,66915,66928,66938,66940,66954,66956,66962,66964,66965,66967,66977,66979,66993,66995,67001,67003,67004,67008,67059,67072,67382,67392,67413,67424,67431,67456,67461,67463,67504,67506,67514,67584,67589,67592,67592,67594,67637,67639,67640,67644,67644,67647,67669,67672,67702,67705,67742,67751,67759,67808,67826,67828,67829,67835,67867,67872,67897,67904,67929,67968,68023,68028,68047,68050,68096,68112,68115,68117,68119,68121,68149,68160,68168,68192,68222,68224,68255,68288,68295,68297,68324,68331,68335,68352,68405,68416,68437,68440,68466,68472,68497,68521,68527,68608,68680,68736,68786,68800,68850,68858,68899,68912,68921,68928,68965,68975,68997,69216,69246,69248,69289,69296,69297,69314,69319,69376,69415,69424,69445,69457,69460,69488,69505,69552,69579,69600,69622,69635,69687,69714,69743,69745,69746,69749,69749,69763,69807,69840,69864,69872,69881,69891,69926,69942,69951,69956,69956,69959,69959,69968,70002,70006,70006,70019,70066,70081,70084,70096,70106,70108,70108,70113,70132,70144,70161,70163,70187,70207,70208,70272,70278,70280,70280,70282,70285,70287,70301,70303,70312,70320,70366,70384,70393,70405,70412,70415,70416,70419,70440,70442,70448,70450,70451,70453,70457,70461,70461,70480,70480,70493,70497,70528,70537,70539,70539,70542,70542,70544,70581,70583,70583,70609,70609,70611,70611,70656,70708,70727,70730,70736,70745,70751,70753,70784,70831,70852,70853,70855,70855,70864,70873,71040,71086,71128,71131,71168,71215,71236,71236,71248,71257,71296,71338,71352,71352,71360,71369,71376,71395,71424,71450,71472,71483,71488,71494,71680,71723,71840,71922,71935,71942,71945,71945,71948,71955,71957,71958,71960,71983,71999,71999,72001,72001,72016,72025,72096,72103,72106,72144,72161,72161,72163,72163,72192,72192,72203,72242,72250,72250,72272,72272,72284,72329,72349,72349,72368,72440,72640,72672,72688,72697,72704,72712,72714,72750,72768,72768,72784,72812,72818,72847,72960,72966,72968,72969,72971,73008,73030,73030,73040,73049,73056,73061,73063,73064,73066,73097,73112,73112,73120,73129,73136,73179,73184,73193,73440,73458,73474,73474,73476,73488,73490,73523,73552,73561,73648,73648,73664,73684,73728,74649,74752,74862,74880,75075,77712,77808,77824,78895,78913,78918,78944,82938,82944,83526,90368,90397,90416,90425,92160,92728,92736,92766,92768,92777,92784,92862,92864,92873,92880,92909,92928,92975,92992,92995,93008,93017,93019,93025,93027,93047,93053,93071,93504,93548,93552,93561,93760,93846,93856,93880,93883,93907,93952,94026,94032,94032,94099,94111,94176,94177,94179,94179,94194,94198,94208,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,113664,113770,113776,113788,113792,113800,113808,113817,118e3,118009,119488,119507,119520,119539,119648,119672,119808,119892,119894,119964,119966,119967,119970,119970,119973,119974,119977,119980,119982,119993,119995,119995,119997,120003,120005,120069,120071,120074,120077,120084,120086,120092,120094,120121,120123,120126,120128,120132,120134,120134,120138,120144,120146,120485,120488,120512,120514,120538,120540,120570,120572,120596,120598,120628,120630,120654,120656,120686,120688,120712,120714,120744,120746,120770,120772,120779,120782,120831,122624,122654,122661,122666,122928,122989,123136,123180,123191,123197,123200,123209,123214,123214,123536,123565,123584,123627,123632,123641,124112,124139,124144,124153,124368,124397,124400,124410,124608,124638,124640,124642,124644,124645,124647,124653,124656,124660,124670,124671,124896,124902,124904,124907,124909,124910,124912,124926,124928,125124,125127,125135,125184,125251,125259,125259,125264,125273,126065,126123,126125,126127,126129,126132,126209,126253,126255,126269,126464,126467,126469,126495,126497,126498,126500,126500,126503,126503,126505,126514,126516,126519,126521,126521,126523,126523,126530,126530,126535,126535,126537,126537,126539,126539,126541,126543,126545,126546,126548,126548,126551,126551,126553,126553,126555,126555,126557,126557,126559,126559,126561,126562,126564,126564,126567,126570,126572,126578,126580,126583,126585,126588,126590,126590,126592,126601,126603,126619,126625,126627,126629,126633,126635,126651,127232,127244,130032,130041,131072,173791,173824,178205,178208,183981,183984,191456,191472,192093,194560,195101,196608,201546,201552,210041]);function wd(e){if(e<128)return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95;let t=0,n=zn.length/2-1;for(;t<=n;){let o=t+n>>1,r=zn[2*o],s=zn[2*o+1];if(e<r)n=o-1;else if(e>s)t=o+1;else return!0}return!1}function Ld(e,t){let n=[],o=-1,r=0;for(let s of e)t(s.codePointAt(0))?o>=0&&(n.push(e.slice(o,r)),o=-1):o<0&&(o=r),r+=s.length;return o>=0&&n.push(e.slice(o)),n}function Ee(e){return Ld(e,t=>!wd(t))}var Pd=`
|
|
114
114
|
INSERT INTO sources(session_id, worktree, agent, kind, label, bytes_total, chunk_count, created_ts, created_at, accessed_ts)
|
|
115
115
|
VALUES (:session_id, :worktree, :agent, :kind, :label, :bytes_total, :chunk_count, :created_ts, :created_at, :created_ts)
|
|
116
|
-
RETURNING id`,
|
|
117
|
-
INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
116
|
+
RETURNING id`,Ud=`
|
|
117
|
+
INSERT INTO chunks(source_id, session_id, worktree, agent, ord, body, title) VALUES (?, ?, ?, ?, ?, ?, ?)`,tc=1,nc=`
|
|
118
118
|
SELECT chunks.rowid AS rid, chunks.source_id AS source_id, chunks.session_id AS session_id,
|
|
119
119
|
chunks.worktree AS worktree, chunks.ord AS ord, s.created_ts AS created_ts,
|
|
120
|
-
bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${
|
|
120
|
+
bm25(chunks, 0, 0, 0, 0, 0, 1.0, ${tc}) AS bm,
|
|
121
121
|
(chunks.rowid IN (SELECT rowid FROM chunks WHERE chunks MATCH :all)) AS full
|
|
122
122
|
FROM chunks JOIN sources s ON s.id = chunks.source_id
|
|
123
123
|
WHERE chunks MATCH :match
|
|
124
124
|
AND (:scope <> 'session' OR chunks.session_id = :session_id)
|
|
125
125
|
AND (:scope <> 'worktree' OR chunks.worktree = :worktree)
|
|
126
|
-
AND (:source IS NULL OR s.label = :source)`,
|
|
127
|
-
ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,
|
|
128
|
-
WITH m AS (${
|
|
126
|
+
AND (:source IS NULL OR s.label = :source)`,oc=`
|
|
127
|
+
ORDER BY (session_id = :session_id) DESC, (worktree = :worktree) DESC, full DESC, score DESC, source_id DESC, ord ASC`,Lp=`
|
|
128
|
+
WITH m AS (${nc}
|
|
129
129
|
), r AS (
|
|
130
130
|
SELECT *,
|
|
131
131
|
ROW_NUMBER() OVER (ORDER BY full DESC, bm ASC, source_id DESC, ord ASC) AS rank_a,
|
|
@@ -133,70 +133,70 @@ WITH m AS (${Vi}
|
|
|
133
133
|
FROM m
|
|
134
134
|
)
|
|
135
135
|
SELECT rid, source_id, session_id, worktree, ord, full, 1.0 / (:k + rank_a) + 1.0 / (:k + rank_b) AS score
|
|
136
|
-
FROM r${
|
|
137
|
-
WITH m AS (${
|
|
136
|
+
FROM r${oc}`,Pp=`
|
|
137
|
+
WITH m AS (${nc}
|
|
138
138
|
)
|
|
139
139
|
SELECT rid, source_id, session_id, worktree, ord, full, -bm AS score
|
|
140
|
-
FROM m${
|
|
140
|
+
FROM m${oc}`;var Up=`
|
|
141
141
|
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
|
|
142
142
|
FROM chunks_tri t JOIN chunks c ON c.rowid = t.rowid JOIN sources s ON s.id = c.source_id
|
|
143
143
|
WHERE chunks_tri MATCH :match
|
|
144
144
|
AND (:scope <> 'session' OR c.session_id = :session_id)
|
|
145
145
|
AND (:scope <> 'worktree' OR c.worktree = :worktree)
|
|
146
146
|
AND (:source IS NULL OR s.label = :source)
|
|
147
|
-
ORDER BY bm25(chunks_tri, 1.0, ${
|
|
147
|
+
ORDER BY bm25(chunks_tri, 1.0, ${tc}) ASC, c.source_id DESC, c.ord ASC`;var Md="INSERT INTO chunks_tri(rowid, body, title) VALUES (?, ?, ?)",Hd="INSERT INTO chunks_tri(chunks_tri, rowid, body, title) SELECT 'delete', rowid, body, title FROM chunks";function rc(e,t,n){let o=$n(e,t,n);return ic(e,o,t,n),o}function $n(e,t,n){let o=0;for(let r of n)o+=r.bytes;return L(e,r=>{let s=r.raw.prepare(Pd).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 sc(e,t,n,o,r){try{ic(e,t,n,o),Zn(e,t,n.sessionId,r)}catch(s){throw L(e,i=>{vd(i.raw,{sourceId:t}),i.raw.prepare("DELETE FROM sources WHERE id = ?").run(t)}),s}}function ic(e,t,n,o){let r=[],s=[],i=0;for(let c of o)s.length>0&&i+c.bytes>jt&&(r.push(s),s=[],i=0),s.push(c),i+=c.bytes;s.length>0&&r.push(s);for(let c of r)L(e,a=>{let l=a.raw.prepare(Ud),u=a.raw.prepare(Md);for(let f of c){let d=f.title??"",x=l.run(t,n.sessionId,n.worktree,n.agent,f.ord,f.text,d).lastInsertRowid;u.run(x,f.text,d)}})}function vd(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(Hd+" 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 Qn(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 Fd(e){return[...new Set(Qn(e).split(" ").filter(n=>n!==""))].join(" OR ")}var jd=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 Gd(e){let t=[...new Set(Qn(e).split(" ").filter(o=>o!==""))],n=t.filter(o=>!jd.has(o.slice(1,-2).toLowerCase()));return n.length>0?n:t}var Dt=`
|
|
148
148
|
AND (:scope <> 'session' OR session_id = :session_id)
|
|
149
|
-
AND (:scope <> 'worktree' OR worktree = :worktree)`,
|
|
149
|
+
AND (:scope <> 'worktree' OR worktree = :worktree)`,Mp=`
|
|
150
150
|
WITH e AS (
|
|
151
151
|
SELECT seq, kind, key, path, body, created_at FROM events
|
|
152
|
-
WHERE created_at > :after${
|
|
152
|
+
WHERE created_at > :after${Dt}
|
|
153
153
|
AND (:source IS NULL OR kind = :source)
|
|
154
154
|
)
|
|
155
155
|
SELECT seq, kind, key, path, body, created_at FROM e
|
|
156
156
|
WHERE created_at <= IFNULL((SELECT created_at FROM e ORDER BY created_at, seq LIMIT 1 OFFSET :off), created_at)
|
|
157
|
-
ORDER BY created_at ASC, seq ASC`,
|
|
157
|
+
ORDER BY created_at ASC, seq ASC`,Hp=`
|
|
158
158
|
WITH s AS (
|
|
159
159
|
SELECT id, label, created_ts FROM sources
|
|
160
|
-
WHERE created_ts > :after${
|
|
160
|
+
WHERE created_ts > :after${Dt}
|
|
161
161
|
AND (:source IS NULL OR label = :source)
|
|
162
162
|
AND label <> :reserved
|
|
163
163
|
)
|
|
164
164
|
SELECT id, label, created_ts FROM s
|
|
165
165
|
WHERE created_ts <= IFNULL((SELECT created_ts FROM s ORDER BY created_ts, id LIMIT 1 OFFSET :off), created_ts)
|
|
166
|
-
ORDER BY created_ts ASC, id ASC`;var
|
|
167
|
-
SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${
|
|
168
|
-
OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${
|
|
169
|
-
AND label <> :reserved) AS more`;var
|
|
170
|
-
`),n=[],o=[];for(let r=0;r<t.length;r++){let s=t[r].endsWith("\r")?t[r].slice(0,-1):t[r],i=
|
|
171
|
-
`)}),n.push({indent:i,line:s})}}return o}function
|
|
172
|
-
`);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function
|
|
173
|
-
`+e.body}function
|
|
174
|
-
`)}function
|
|
175
|
-
`),seqs:l.map(d=>d.seq),...u.length>0?{units:u.map(
|
|
176
|
-
`)}var
|
|
166
|
+
ORDER BY created_ts ASC, id ASC`;var vp=`
|
|
167
|
+
SELECT EXISTS(SELECT 1 FROM events WHERE created_at > :after${Dt} AND (:source IS NULL OR kind = :source))
|
|
168
|
+
OR EXISTS(SELECT 1 FROM sources WHERE created_ts > :after${Dt} AND (:source IS NULL OR label = :source)
|
|
169
|
+
AND label <> :reserved) AS more`;var Bd=`CREATE VIRTUAL TABLE r USING fts5(body, ${Ct}, content='')`,Wd="INSERT INTO r(rowid, body) VALUES (?, ?)",Xd="SELECT rowid AS id, bm25(r) AS bm FROM r WHERE r MATCH ?";function G(e,t,n="all"){let o=e.map(()=>0),r=n==="any"?Fd(t):Qn(t);if(r===""||e.length===0)return o;let s=process.getBuiltinModule("node:sqlite");if(s===void 0)throw new R("NO_SQLITE");let i=new s.DatabaseSync(":memory:");try{i.exec(Bd);let c=i.prepare(Wd);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(Xd).all(r))o[Number(a.id)-1]=-a.bm;return o}finally{i.close()}}var Kd="s";function cc(e){return Kd+e.toString(36)}function Zn(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<=jt);)i+=o[s].body.length,s++;let c=r;L(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 f=o[u];l.run(f.body,t,n,f.ord)}}),r=s}}function ac(e,t){return t===e?e:e+" "+t}function lc(e,t,n,o){let r=Gd(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 qd(e){let t=0;for(;t<e.length&&(e[t]===" "||e[t]===" ");)t++;return t}function eo(e){let t=e.split(`
|
|
170
|
+
`),n=[],o=[];for(let r=0;r<t.length;r++){let s=t[r].endsWith("\r")?t[r].slice(0,-1):t[r],i=qd(s);if(i!==s.length){for(;n.length>0&&n[n.length-1].indent>=i;)n.pop();o.push({ord:r,body:[...n.map(c=>c.line),s].join(`
|
|
171
|
+
`)}),n.push({indent:i,line:s})}}return o}function to(e){let t=e.indexOf(`
|
|
172
|
+
`);return(t<0?e:e.slice(0,t)).replaceAll("\r"," ")}function me(e,t,n,o,r){let s=Buffer.byteLength(n,"utf8");if(s<1)throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");return{section:e,seq:t.seq,turn:t.turn,text:n,bytes:s,repeatCount:o,pinned:e==="last_request",query:r}}function Fe(e){return e.length>Gt?e.slice(e.length-Gt):e}function Yd(){return{lastRequest:null,openErrors:[],changedFiles:[],decisions:[],earlierRequests:[],indexedSources:[]}}function uc(e,t){if(!t)return Yd();let n=e.filter(p=>p.session_id===t).sort((p,g)=>p.seq-g.seq),o=n.filter(p=>p.kind==="prompt"),r=o.length>0?o[o.length-1]:void 0,s=r===void 0?null:me("last_request",r,"now: "+to(r.body),1,null),i=o.slice(0,o.length-1).map(p=>me("earlier_requests",p,"asked #"+p.seq+": "+to(p.body),1,null)),c=new Map,a=new Map;for(let p of n)if(!(p.kind!=="cmd"&&p.kind!=="toolerr"||p.key===null)){if(p.ok===1){a.set(p.key,p.seq);continue}c.set(p.key,{row:p,count:(c.get(p.key)?.count??0)+1})}let l=[];for(let[p,g]of c)(a.get(p)??0)>g.row.seq||l.push(me("open_errors",g.row,"error #"+g.row.seq+" "+(g.row.tool??"")+": "+p,g.count,p));l.sort((p,g)=>p.seq-g.seq);let u=new Map;for(let p of n)p.kind!=="edit"||p.path===null||u.set(p.path,{row:p,count:(u.get(p.path)?.count??0)+1});let f=[];for(let[p,g]of u){let A=me("changed_files",g.row,"edited "+p+" x"+g.count,g.count,p);f.push({...A,editCount:g.count})}f.sort((p,g)=>p.seq-g.seq);let d=new Map;for(let p of n){if(p.kind!=="decision"||p.body==="")continue;let g=p.key??p.body;d.set(g,{row:p,count:(d.get(g)?.count??0)+1})}let x=[];for(let[p,g]of d)x.push(me("decisions",g.row,"decided #"+g.row.seq+": "+to(g.row.body),g.count,p));x.sort((p,g)=>p.seq-g.seq);let E=n.filter(p=>p.kind==="index").map(p=>me("indexed_sources",p,"indexed "+(p.key??""),1,p.key)),m={lastRequest:s,openErrors:Fe(l),changedFiles:Fe(f),decisions:Fe(x),earlierRequests:Fe(i),indexedSources:Fe(E)},_=[...m.openErrors,...m.changedFiles,...m.decisions,...m.earlierRequests,...m.indexedSources],S=_.length+(s===null?0:1);if(S<=Bt)return m;let h=new Set(_.map(p=>p.seq).sort((p,g)=>p-g).slice(0,S-Bt));return{lastRequest:s,openErrors:m.openErrors.filter(p=>!h.has(p.seq)),changedFiles:m.changedFiles.filter(p=>!h.has(p.seq)),decisions:m.decisions.filter(p=>!h.has(p.seq)),earlierRequests:m.earlierRequests.filter(p=>!h.has(p.seq)),indexedSources:m.indexedSources.filter(p=>!h.has(p.seq))}}function Vd(e){if(!Object.hasOwn(Wt,e.section))throw new Error(`compaction: "${String(e.section)}" has no weight; only toolerr, decision, prompt, edit and index rows are scored (ADR-0009 \xA73, DECISIONS-r11).`);let t=Math.max(0,e.currentTurn-e.itemTurn),n=Xt[Math.min(t,Xt.length-1)],o=1;for(let r=Math.max(1,e.repeatCount);r>1;r>>=1)o+=1;return Math.round(Wt[e.section]*n*o/Ur)}function Jd(e){switch(e){case"last_request":case"earlier_requests":return"prompt";case"open_errors":return"toolerr";case"changed_files":return"edit";case"decisions":return"decision";case"indexed_sources":return"index"}}function dc(e,t){return e.map(n=>({...n,score:Vd({section:Jd(n.section),currentTurn:t,itemTurn:n.turn,repeatCount:n.repeatCount})}))}function pc(e){return e.sourceId+":"+e.ord}function Lt(e){return"@"+e.label+" line "+(e.ord+1)+`:
|
|
173
|
+
`+e.body}function zd(e){return new Set(Ee(e.toLowerCase()))}function $d(e,t){let n=0;for(let o of e)t.has(o)&&n++;return e.size+t.size-n===0?0:n/(e.size+t.size-n)}function oo(e,t,n){let o=e.filter(l=>!t.has(pc(l))&&l.score>=sn);if(o.length===0)return[];let r=Math.max(...o.map(l=>l.score)),s=o.map(l=>zd(l.body)),i=[],c=new Set(o.map((l,u)=>u)),a=0;for(;c.size>0;){let l=-1,u=-1/0;for(let d of c){let x=0;for(let m of i)x=Math.max(x,$d(s[d],s[m]));let E=ko*(o[d].score/r)-Io*x;E>u&&(u=E,l=d)}c.delete(l);let f=wt(Lt(o[l]))+1;a+f>n||(a+=f,i.push(l))}return i.map(l=>o[l])}var fc={text:"",seqs:[]};function wt(e){return Buffer.byteLength(e,"utf8")}function no(e){return[e.key??"",e.path??"",e.body].filter(t=>t!=="").join(`
|
|
174
|
+
`)}function xc(e){return"#"+e.seq+" "+e.kind+(e.tool===null?"":" "+e.tool)+": "+no(e)}function Ec(e,t,n,o=[],r=new Set){if(t.trim()==="")return fc;let s=e.filter(d=>!n.has(d.seq)&&d.kind!=="cost"&&!(d.kind==="prompt"&&d.body===t)&&no(d)!==""),i=s.length===0?[]:G(s.map(no),t,"any"),c=s.map((d,x)=>({r:d,score:i[x]})).filter(d=>d.score>=sn).sort((d,x)=>x.score-d.score||x.r.seq-d.r.seq),a=wt(an)+1+wt(ln),l=[];for(let{r:d}of c){let x=wt(xc(d))+1;a+x>rn||(a+=x,l.push(d))}let u=oo(o,r,rn-a);if(l.length===0&&u.length===0)return fc;l.sort((d,x)=>d.seq-x.seq);let f=[...l.map(xc),...u.map(Lt)];return{text:[an,...f,ln].join(`
|
|
175
|
+
`),seqs:l.map(d=>d.seq),...u.length>0?{units:u.map(pc)}:{}}}function z(e){return Buffer.byteLength(e,"utf8")}function ro(e,t){return e.bytes>bo?"#"+e.seq+" ("+e.bytes+" B) "+t+"ctx_resume(seq:"+e.seq+")":e.text}function so(e,t){return"more: "+t+"ctx_search(queries:"+JSON.stringify(e)+', scope:"session")'}function mc(e,t,n,o=""){let r;for(let g of e)(r===void 0||g.seq>r.seq)&&(r=g);let s=r===void 0?"":r.session_id,i=r===void 0||s===""?0:r.seq,c=uc(e,s),a=`<context_mode_state session="${s}" upto="${i}">`,l=z(so([],o)),u=ho-(z(a)+1+l+1+z(Ft)),f=0,d=c.lastRequest===null?null:ro(c.lastRequest,o);d!==null&&(f+=z(d)+1);let x=dc([...c.openErrors,...c.changedFiles,...c.decisions,...c.earlierRequests,...c.indexedSources],t),E=new Map,m=[],_=[];for(;x.length>0;){let g=0,A=-1/0;for(let We=0;We<x.length;We++){let Xe=x[We],vt=Xe.score*Co**(E.get(Xe.section)??0)/Xe.bytes;(vt>A||vt===A&&Xe.seq>x[g].seq)&&(g=We,A=vt)}let k=x.splice(g,1)[0],Be=z(ro(k,o))+1;f+Be<=u?(f+=Be,m.push(k),E.set(k.section,(E.get(k.section)??0)+1)):_.push(k)}let S=[a];d!==null&&S.push(d);for(let g of["open_errors","changed_files","decisions","earlier_requests","indexed_sources"])for(let A of m.filter(k=>k.section===g).sort((k,Be)=>k.seq-Be.seq))S.push(ro(A,o));if(n!==void 0){for(let g of n.sources){let A=z(g)+1;f+A>u||(f+=A,S.push(g))}for(let g of oo(n.units,new Set,u-f)){let A=Lt(g);f+=z(A)+1,S.push(A)}}let h=[],p=new Set;for(let g of _.sort((A,k)=>A.seq-k.seq))if(!(g.query===null||p.has(g.query))){if(z(so([...h,g.query],o))-l>u-f)break;h.push(g.query),p.add(g.query)}return S.push(so(h,o),Ft),S.join(`
|
|
176
|
+
`)}var Qd=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Zd=new Set(["script","style"]),e0=new TextEncoder;function Pt(e,t,n=Z){let o=o0(e);if(o.length===0)return[];let r=Math.max(4,Math.min(Z,Math.floor(n)));if(t==="md")return t0(o,r,r<Z);let s=t==="html"?c0(o):io(o,!1);return co(o,s,t!=="text",r,r<Z)}function t0(e,t,n){let o=[],r=[],s="",i=[],c=(l,u)=>{o.push({ord:o.length,text:l,bytes:u,title:s})},a=()=>{if(i.length!==0){for(let l of co(e,i,!0,t,n))c(l.text,l.bytes);i=[]}};for(let l of io(e,!0)){if(l.heading!==void 0){for(a();r.length>0&&r[r.length-1].level>=l.heading.level;)r.pop();r.push(l.heading),s=r.map(u=>u.text).join(" > ")}if(l.fence!==void 0&&$(e.slice(l.start,l.end))>t){let u=n0(e,l,l.fence,t);if(u!==void 0){a();for(let f of u)c(f,$(f));continue}}i.push(l)}return a(),o}function n0(e,t,n,o){let r=e.slice(t.start,n.openEnd),s=n.closeStart>=0?e.slice(n.closeStart,t.end):n.fence,i=n.closeStart>=0?Math.max(n.openEnd+1,n.closeStart-1):t.end,c=e.slice(Math.min(n.openEnd+1,i),i),a=o-$(r)-$(s)-2;if(!(a<16||c.length===0))return co(c,io(c,!1),!0,a,!0).map(l=>r+`
|
|
177
177
|
`+l.text+`
|
|
178
|
-
`+s)}function
|
|
178
|
+
`+s)}function o0(e){let t=e.split(`\r
|
|
179
179
|
`).join(`
|
|
180
|
-
`);return t.startsWith("\uFEFF")?t.slice(1):t}function
|
|
181
|
-
`,f),x=d<0?e.length:d,E=e.slice(f,x);if(i!=="")u(f,x,!1),
|
|
182
|
-
`||e===" "||e==="\f"||e==="\r"}function
|
|
180
|
+
`);return t.startsWith("\uFEFF")?t.slice(1):t}function io(e,t){let n=[],o=-1,r=-1,s=!1,i="",c,a,l=()=>{if(o>=0){let d={start:o,end:r};c!==void 0&&(d.heading=c),a!==void 0&&(d.fence=a),n.push(d)}o=-1,c=void 0,a=void 0},u=(d,x,E)=>{o<0&&(o=d),r=x,s=E},f=0;for(;f<=e.length;){let d=e.indexOf(`
|
|
181
|
+
`,f),x=d<0?e.length:d,E=e.slice(f,x);if(i!=="")u(f,x,!1),i0(E,i)&&(i="",t&&a!==void 0&&(a.closeStart=f,l()));else if(E.length===0)l();else{let m=t?s0(E):"",_=t&&m===""?r0(E):void 0,S=t&&m===""&&_===void 0&&E.includes("|");t&&o>=0&&(S!==s||m!==""||_!==void 0)&&l(),u(f,x,S),i=m,m!==""&&(a={fence:m,openEnd:x,closeStart:-1}),_!==void 0&&(c=_,l())}f=x+1}return l(),n}function r0(e){let t=0;for(;t<e.length&&t<4&&e[t]===" ";)t+=1;if(t>3)return;let n=0;for(;t+n<e.length&&e[t+n]==="#";)n+=1;if(n<1||n>6)return;let o=e[t+n];if(o!==void 0&&o!==" "&&o!==" ")return;let r=e.slice(t+n).trim(),s=r.length;for(;s>0&&r[s-1]==="#";)s-=1;return s===0?r="":s<r.length&&(r[s-1]===" "||r[s-1]===" ")&&(r=r.slice(0,s).trim()),{level:n,text:r}}function s0(e){let t=e.trimStart();if(!t.startsWith("```")&&!t.startsWith("~~~"))return"";let n=0;for(;n<t.length&&t[n]===t[0];)n+=1;return t.slice(0,n)}function i0(e,t){let n=e.trim();if(n.length<t.length)return!1;for(let o=0;o<n.length;o+=1)if(n[o]!==t[0])return!1;return!0}function c0(e){let t=[],n=new Map,o=0,r=0,s=0,i=c=>{gc(t,e,r,c),r=c};for(;s<e.length;){if(e[s]!=="<"){s+=1;continue}if(e.startsWith("<!--",s)){let a=e.indexOf("-->",s+4);s=a<0?e.length:a+3;continue}let c=a0(e,s);if(c===void 0){s+=1;continue}if(s=c.end,c.close){let a=n.get(c.name)??0;if(a===0)continue;n.set(c.name,a-1),o-=1,o===0&&i(s);continue}if(!(c.selfClose||Qd.has(c.name))){if(Zd.has(c.name)){s=l0(e,s,c.name),o===0&&i(s);continue}n.set(c.name,(n.get(c.name)??0)+1),o+=1}}return gc(t,e,r,e.length),t}function bc(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}function Sc(e){return bc(e)||e>="0"&&e<="9"||e==="-"||e===":"}function a0(e,t){let n=t+1,o=e[n]==="/";if(o&&(n+=1),n>=e.length||!bc(e[n]))return;let r=n;for(;n<e.length&&Sc(e[n]);)n+=1;let s=e.slice(r,n).toLowerCase(),i="";for(;n<e.length;){let c=e[n];if(i!=="")c===i&&(i="");else if(c==='"'||c==="'")i=c;else if(c===">")break;n+=1}if(!(n>=e.length))return{name:s,close:o,selfClose:e[n-1]==="/",end:n+1}}function l0(e,t,n){let o=e.indexOf("</",t);for(;o>=0;){let r=o+2+n.length;if(e.slice(o+2,r).toLowerCase()===n&&(r>=e.length||!Sc(e[r]))){let i=e.indexOf(">",r);return i<0?e.length:i+1}o=e.indexOf("</",o+2)}return e.length}function _c(e){return e===" "||e===`
|
|
182
|
+
`||e===" "||e==="\f"||e==="\r"}function gc(e,t,n,o){let r=n,s=o;for(;r<s&&_c(t[r]);)r+=1;for(;s>r&&_c(t[s-1]);)s-=1;r<s&&e.push({start:r,end:s})}function $(e){return Buffer.byteLength(e,"utf8")}function hc(e,t,n,o){let r=Math.min(n,t+o.length);r<n&&[...e.slice(r-1,r+1)].length===1&&(r-=1);let s=e0.encodeInto(e.slice(t,r),o);return{end:t+s.read,written:s.written}}function co(e,t,n,o,r){let s=[],i=new Uint8Array(o),c,a,l=0,u=(f,d,x)=>{s.push({ord:s.length,text:e.slice(f,d),bytes:x})};for(let f of t){if(a!==void 0&&!n&&(u(a.start,a.end,l),a=void 0),a!==void 0){let E=$(e.slice(a.end,f.end));if(l+E<=o){a.end=f.end,l+=E;continue}u(a.start,a.end,l),a=void 0}let d=f.start,x=$(e.slice(f.start,f.end));for(;x>o;){let E=hc(e,d,f.end,i),m=r?e.lastIndexOf(`
|
|
183
183
|
`,E.end-1):-1;if(m>d){let _=$(e.slice(d,m+1));u(d,m+1,_),d=m+1,x-=_;continue}if(r){let _=e.indexOf(`
|
|
184
|
-
`,d),S=_<0||_>=f.end?f.end:_+1,h=$(e.slice(d,S));if(h<=Z){u(d,S,h),d=S,x-=h;continue}c??=new Uint8Array(Z);let p=
|
|
185
|
-
`,
|
|
186
|
-
`,
|
|
187
|
-
`&&n!=="\r"&&n!==" ")return n}return""}function
|
|
188
|
-
`);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<
|
|
189
|
-
`)}}function
|
|
190
|
-
ref: #`+n}}function
|
|
191
|
-
`),
|
|
192
|
-
`),o.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},O)}let s;try{let c=e==="vscode"?[
|
|
193
|
-
`),o.encode(r,O)}let i;try{i=await
|
|
194
|
-
`),i=O}return o.encode(r,i)}function
|
|
195
|
-
`)})}function
|
|
196
|
-
`)})}async function
|
|
197
|
-
`),n=t<0?e:e.slice(0,t);if(!n.startsWith(
|
|
198
|
-
`+t}function
|
|
199
|
-
`+t)-1-Buffer.byteLength(e))}function
|
|
200
|
-
`);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,
|
|
201
|
-
`)})}function
|
|
202
|
-
`)}async function
|
|
184
|
+
`,d),S=_<0||_>=f.end?f.end:_+1,h=$(e.slice(d,S));if(h<=Z){u(d,S,h),d=S,x-=h;continue}c??=new Uint8Array(Z);let p=hc(e,d,S,c);u(d,p.end,p.written),d=p.end,x-=p.written;continue}u(d,E.end,E.written),d=E.end,x-=E.written}d>=f.end||(a={start:d,end:f.end},l=x)}return a!==void 0&&u(a.start,a.end,l),s}var u0=`
|
|
185
|
+
`,d0=1;function Tc(e,t,n,o,r){return f0(e,t,n,o,r)}function f0(e,t,n,o,r){if(e.length===0)return{text:"",more:null};let s=e.map(d=>d.text),i=r===void 0?G(s,t):G(s,r,"any"),c=e.map((d,x)=>x).sort((d,x)=>i[x]-i[d]||e[x].ord-e[d].ord),a=[],l=0,u=!1;for(let d of c){let x=e[d].bytes+(a.length>0?d0:0);if(l+x>n){u=!0;continue}a.push(e[d]),l+=x}return a.sort((d,x)=>d.ord-x.ord),{text:a.map(d=>d.text).join(u0),more:u?ao(t,o):null}}function ao(e,t){let n=t===void 0?"":", source:"+JSON.stringify(t);return"ctx_search({queries:["+JSON.stringify(e)+"]"+n+"})"}var Rc=20,P=2,Oc=9,Ac=8,x0=.9,p0=.5,E0=64,m0=2,_0=4,lo=`
|
|
186
|
+
`,g0="(absent)",B=e=>Buffer.byteLength(e,"utf8");function yc(e,t,n){let o=S0(e,t)??O0(e,t)??N0(e);if(o===null||t.trim()==="")return null;let r=o.direct===!0?o.units.map(()=>1):G(o.units.map(l=>l.rank),t,"any"),s=o.units.map((l,u)=>u).filter(l=>r[l]>0).sort((l,u)=>r[u]-r[l]||o.units[l].pos-o.units[u].pos),i=[],c=0;for(let l of s){let u=i.length>0?B(lo):0,f=o.units[l].render(n-c-u);f===null||c+u+B(f)>n||(i.push({pos:o.units[l].pos,text:f}),c+=u+B(f))}if(i.length===0)return null;i.sort((l,u)=>l.pos-u.pos);let a=i.map(l=>l.text);return c+B(lo)+B(o.header)<=n&&a.unshift(o.header),a.join(lo)}function h0(e){for(let t=0;t<e.length;t++){let n=e[t];if(n!==" "&&n!==`
|
|
187
|
+
`&&n!=="\r"&&n!==" ")return n}return""}function b0(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nc(e,t,n){if(n.size<2||n.size>Ac)return[];let o=[...n.entries()].sort((i,c)=>c[1]-i[1]);if(n.size<=P+1)return o[0][1]<x0*e||e-o[0][1]>P?[]:o.slice(1).flatMap(([i])=>t.get(i)??[]);let r=o.filter(([,i])=>i>P),s=o.filter(([,i])=>i<=P);return r.length<2||s.length===0?[]:s.flatMap(([i])=>t.get(i)??[])}function Cc(e){if(h0(e)!=="[")return null;let t;try{t=JSON.parse(e)}catch{return null}if(!Array.isArray(t)||t.length<Rc||!t.every(b0))return null;let n=t,o=[],r=new Set;for(let s of n)for(let i of Object.keys(s))r.has(i)||(r.add(i),o.push(i));return{objs:n,keys:o}}var kc=(e,t)=>e+" objects {"+t.join(",")+"}";function S0(e,t){let n=Cc(e);if(n===null)return null;let{objs:o,keys:r}=n,s=new Map;for(let l of r){let u=new Map,f=new Map,d=!0;for(let x=0;x<o.length&&d;x++){let E=l in o[x]?o[x][l]:void 0;if(typeof E=="object"&&E!==null){d=!1;break}let m=E===void 0?g0:JSON.stringify(E);f.set(m,(f.get(m)??0)+1);let _=u.get(m)??[];if(_.length<=P&&_.push(x),u.set(m,_),f.size>Ac)break}if(d)for(let x of Nc(o.length,u,f))s.set(x,[...s.get(x)??[],l])}if(s.size===0||s.size>Oc)return null;let i=G(r,t,"any"),c=new Set(r.filter((l,u)=>i[u]>0)),a=[...s.entries()].map(([l,u])=>({pos:l,rank:JSON.stringify(o[l]),render:f=>Ic(l,o[l],u,c,f)}));return{header:kc(o.length,r)+", "+s.size+" rare:",units:a}}function Ic(e,t,n,o,r){let s="["+e+"] ",i=T0(t,n,o,r-B(s));return i===null?null:s+i}function T0(e,t,n,o){let r=JSON.stringify(e);if(B(r)<=o)return r;let s=Object.keys(e),i=f=>t.includes(f)?0:n.has(f)?1:typeof e[f]!="object"||e[f]===null?2:3,c=[...s].sort((f,d)=>i(f)-i(d)||s.indexOf(f)-s.indexOf(d)),a=f=>JSON.stringify(f)+":"+JSON.stringify(e[f]),l=new Set,u=2;for(let f of c){let d=B(a(f))+(l.size>0?1:0);u+d>o||(l.add(f),u+=d)}return t.every(f=>l.has(f))?"{"+s.filter(f=>l.has(f)).map(a).join(",")+"}":null}function R0(e,t){let n=G(e,t,"any");return new Set(e.filter((o,r)=>n[r]>0))}function O0(e,t){let n=Cc(e);if(n===null)return null;let{objs:o,keys:r}=n,s=R0(r,t),i=new Map,c=0;for(let l of r){if(!s.has(l)||c>=m0||!o.every(d=>typeof d[l]=="number"&&Number.isFinite(d[l])))continue;let u=0,f=0;for(let d=1;d<o.length;d++)o[d][l]>o[u][l]&&(u=d),o[d][l]<o[f][l]&&(f=d);u!==f&&(c++,i.set(u,l),i.set(f,l))}if(i.size===0)return null;let a=[...i.entries()].map(([l,u])=>({pos:l,rank:"",render:f=>Ic(l,o[l],[u],s,f)}));return{header:kc(o.length,r)+", extremes of "+[...new Set(i.values())].join(",")+":",units:a,direct:!0}}function A0(e){for(let t=0;t<e.length;t++)if(e[t]>="0"&&e[t]<="9")return!0;return!1}function y0(e,t){let n=0;for(let o=0;o<e.length;o++)(e[o]===t[o]||e[o]==="<*>"||t[o]==="<*>")&&n++;return n/e.length}function N0(e){let t=e.split(`
|
|
188
|
+
`);if(t.length>0&&t[t.length-1]===""&&t.pop(),t.length<Rc)return null;let n=new Map,o=[];for(let a=0;a<t.length;a++){let l=t[a].split(" ").filter(E=>E!==""),u=l.map(E=>A0(E)?"<*>":E),f=u.length+" "+(u[0]??""),d=n.get(f)??[],x;for(let E of d)if(y0(E.tpl,u)>=p0){x=E;break}if(x===void 0){if(x={tpl:[...u],count:0,lines:[],pos:l.map(()=>({counts:new Map,totals:new Map}))},d.push(x),n.set(f,d),o.push(x),o.length>E0)return null}else for(let E=0;E<x.tpl.length;E++)x.tpl[E]!==u[E]&&(x.tpl[E]="<*>");x.count++,x.lines.length<=P&&x.lines.push(a);for(let E=0;E<x.pos.length;E++){let m=x.pos[E];if(m===null)continue;m.totals.set(l[E],(m.totals.get(l[E])??0)+1);let _=m.counts.get(l[E])??[];_.length<=P&&_.push(a),m.counts.set(l[E],_),m.totals.size>P+1&&(x.pos[E]=null)}}let r=o.filter(a=>a.count>P);if(r.length===0||r.length>_0||r.some(a=>a.tpl.every(l=>l==="<*>")))return null;let s=new Set(o.filter(a=>a.count<=P).flatMap(a=>a.lines));for(let a of r)for(let l of a.pos)if(l!==null)for(let u of Nc(a.count,l.counts,l.totals))s.add(u);if(s.size===0||s.size>Oc)return null;let i=t.length+" lines, "+s.size+" rare:",c=[...s].sort((a,l)=>a-l).map(a=>{let l=a+1+": "+t[a];return{pos:a,rank:t[a],render:u=>B(l)<=u?l:null}});return{header:i,units:c}}function C0(e,t,n,o,r,s,i,c=Pt(s,i)){return{sourceId:rc(e,{projectKey:t.projectKey,sessionId:n,worktree:t.worktree,agent:t.agent,kind:o,label:r,bytes:Buffer.byteLength(s,"utf8"),chunkCount:c.length,createdAt:Date.now()},c),chunks:c.length}}function uo(e,t,n,o,r,s,i){return C0(e,t,n,"content",o,r,s,i)}async function k0(e,t){try{let n=await y(e);It(n,t)}catch(n){let o=n instanceof Error?n.message:String(n);process.stderr.write("hooks: journal write failed: "+o+`
|
|
189
|
+
`)}}function Ut(e,t,n){k0(e,n)}function Dc(e,t,n){let o=new Set(Ee(t.toLowerCase()));for(let i of Ee(e.toLowerCase()))o.delete(i);if(o.size===0)return"";let r=new Map;for(let i of Ee(n.toLowerCase()))o.has(i)&&r.set(i,(r.get(i)??0)+1);return[...r.entries()].sort((i,c)=>i[1]-c[1]||(i[0]<c[0]?-1:i[0]>c[0]?1:0)).slice(0,No).map(i=>i[0]).join(" ")}function je(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function I0(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").join(Hr):""}function D0(e){return Array.isArray(e)?e.filter(je).filter(t=>typeof t.question=="string").map(t=>[t.question,t.label]):je(e)?Object.entries(e):[]}function Lc(e){let t;try{t=JSON.parse(e)}catch{return[]}if(!je(t))return[];let n=[];for(let[o,r]of D0(t[Mr])){let s=I0(r);o===""||s===""||n.push({key:o,body:"Q: "+o+" \u2192 A: "+s})}return n}function Pc(e){let t=e.questions;if(!Array.isArray(t))return[];let n=[];for(let o of t)if(!(!je(o)||!Array.isArray(o.options)))for(let r of o.options)je(r)&&typeof r.label=="string"&&r.label!==""&&n.push(r.label);return n}function wc(e){return e.trim().toLowerCase()}function Uc(e,t,n){let o=wc(e);if(o==="")return null;let r=t.find(s=>wc(s)===o);return r===void 0?null:{key:rt,body:"A: "+r+`
|
|
190
|
+
ref: #`+n}}function w0(e,t){return"hint:"+e+":"+t}function L0(e,t){return J(e,t)!==null?!1:(j(e,t,"1"),!0)}function P0(e,t,n){let o=J(e,t),r=(o===null?0:Number.parseInt(o,10))+1;return j(e,t,String(r)),(r-1)%n===0}function Mt(e,t,n,o){if(t==="")return!1;let r=w0(t,n),s=i=>o===void 0?L0(i,r):P0(i,r,o);return e.raw.isTransaction?s(e):L(e,s)}var{read:U0,writeSync:M0}=process.getBuiltinModule("node:fs"),Mc=65536;function H0(e){let t=Buffer.allocUnsafe(Mc);return new Promise(n=>{let o=()=>{U0(0,t,0,Mc,null,(r,s)=>{if(r)return n(r.code==="EOF");if(s===0)return n(!0);e.push(Buffer.from(t.subarray(0,s))),o()})};o()})}async function fo(){let e=[];if(!await H0(e))for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}function xo(e){let t=Buffer.from(e,"utf8"),n=0;try{for(;n<t.length;)n+=M0(1,t,n,t.length-n)}catch(o){if(o.code!=="EAGAIN")throw o;process.stdout.write(t.subarray(n))}}var{readFileSync:v0}=process.getBuiltinModule("node:fs"),O={kind:"allow"},G0={stdout:"",exitCode:0},B0=48;function W0(e){return ge.includes(e)}function _e(e){return e instanceof Error?e.message:String(e)}function Ge(e){return typeof e=="string"?e:""}async function vc(e,t,n){if(!W0(e))return process.stderr.write("hooks: unknown agent "+JSON.stringify(e)+`
|
|
191
|
+
`),G0;let o=Ne(e),r;try{r=o.decode(t)}catch(c){return process.stderr.write("hooks: decode failed: "+_e(c)+`
|
|
192
|
+
`),o.encode({event:"PreToolUse",agent:e,sessionId:"",cwd:"",turn:0},O)}let s;try{let c=e==="vscode"?[Ve,r.cwd]:process.argv;s=Xi(e,{env:n,argv:c,cwd:r.cwd,piCwd:e==="pi"?r.cwd:void 0})}catch(c){return process.stderr.write("hooks: no project: "+String(c.code??"ERROR")+" "+_e(c)+`
|
|
193
|
+
`),o.encode(r,O)}let i;try{i=await X0(r,o,s,n)}catch(c){process.stderr.write("hooks: "+_e(c)+`
|
|
194
|
+
`),i=O}return o.encode(r,i)}function X0(e,t,n,o){switch(e.event){case"SessionStart":return K0(e,t,n);case"UserPromptSubmit":return q0(e,t,n);case"PreToolUse":return ef(e,t,n,o);case"PostToolUse":return cf(e,t,n,o);case"PreCompact":return xf(e,t,n);case"Usage":return pf(e,n)}return Promise.resolve(O)}function Fc(e,t){return e.split(sr).join(t.toolNamePrefix)}function Eo(e,t,n){return n.compactSummary==="host"?U(Do,n.toolNamePrefix):mc(Jn(e,t.sessionId),t.turn??0,void 0,n.toolNamePrefix)}async function K0(e,t,n){if(e.source==="compact"&&xt(t)&&jc(await y(n),e.sessionId),e.source==="compact"&&t.compactDelivery==="sessionstart"){let r=await y(n);return Mt(r,e.sessionId,tn)?{kind:"hint",text:Eo(r,e,t),onceKey:tn}:O}let o=await y(n);return t.compactDelivery==="opencode-cache"&&kt(o,tt+e.sessionId)!==null?{kind:"hint",text:Eo(o,e,t),onceKey:nn}:Mt(o,e.sessionId,Oe)?{kind:"hint",text:Fc(un,t),onceKey:Oe}:O}async function q0(e,t,n){let o=e.prompt??"",r=await Y0(e,t,n);if(Ut(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:"prompt",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(o),body:o,turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),Q0(e,n,o),t.compactDelivery==="pending-flag"){let s=await y(n);if(kt(s,tt+e.sessionId)!==null)return{kind:"hint",text:Eo(s,e,t),onceKey:nn}}return r!==null?r:z0(e,t,n,o)}async function Y0(e,t,n){if(t.eventMap.SessionStart!==void 0||e.sessionId==="")return null;let o=await y(n);return ec(o,e.sessionId)||!Mt(o,e.sessionId,Oe)||!Zi(o,n.worktree,e.agent)?null:{kind:"hint",text:Fc(un,t),onceKey:Oe}}function jc(e,t){t!==""&&j(e,cn+t,on)}function V0(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="number"):[]}catch{return[]}}function J0(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}async function z0(e,t,n,o){if(!xt(t)||e.sessionId==="")return O;let r=await y(n);if(J(r,cn+e.sessionId)===null)return O;let s=kr+e.sessionId,i=V0(J(r,s)),c=Nr+e.sessionId,a=J0(J(r,c)),l=$i(r,e.sessionId),u=lc(r,e.sessionId,ac(o,l),Cr),f=Ec(Qi(r,e.sessionId,n.worktree,yr),o,new Set(i),u,new Set(a));return f.text===""?O:(f.seqs.length>0&&j(r,s,JSON.stringify([...i,...f.seqs])),f.units!==void 0&&j(r,c,JSON.stringify([...a,...f.units])),{kind:"hint",text:f.text,onceKey:Ir})}function Gc(e){return ot+":"+rt+":"+e}function $0(e){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;let{seq:n,labels:o}=t;return typeof n!="number"||!Array.isArray(o)?null:{seq:n,labels:o.filter(r=>typeof r=="string")}}catch{return null}}function Q0(e,t,n){if(e.sessionId==="")return;let o=Gc(e.sessionId);y(t).then(r=>{if(J(r,o)===null)return;let s=kt(r,o),i=s===null?null:$0(s);if(i===null)return;let c=Uc(n,i.labels,i.seq);c!==null&&Bc(r,e,t,[c])}).catch(r=>{process.stderr.write("hooks: decision write failed: "+_e(r)+`
|
|
195
|
+
`)})}function Bc(e,t,n,o){for(let r of o)It(e,{session_id:t.sessionId,worktree:n.worktree,agent:t.agent,kind:"decision",tool:dn,key:r.key,path:null,ok:1,exit_code:null,bytes:Buffer.byteLength(r.body),body:r.body,turn:t.turn??0,sandbox_bytes:0,returned_bytes:0}),uo(e,n,t.sessionId,ot,r.body,"text")}function Z0(e,t,n,o){let r=Lc(o),s=r.length===0?Pc(n.input):[];r.length===0&&s.length===0||y(t).then(i=>{if(r.length>0)return Bc(i,e,t,r);let c=Jn(i,e.sessionId,"prompt"),a=c[c.length-1];a===void 0||e.sessionId===""||j(i,Gc(e.sessionId),JSON.stringify({seq:a.seq,labels:s}))}).catch(i=>{process.stderr.write("hooks: decision write failed: "+_e(i)+`
|
|
196
|
+
`)})}async function ef(e,t,n,o){let r=ki(n.worktree,e.agent),s=Ui(e,t,r),i=s;return s.kind==="deny"&&pe(e)&&Un(e,Mn(e,{projectDir:n.worktree,env:o}))==="B"&&(i=nf(e,t,s,r)),i}function Wc(e,t){return e.canonicalName===Rr||t.nativeTools.shell.includes(e.name)}function tf(e,t){return e.startsWith(Te)||e===U(Qe,t.toolNamePrefix)||e===U(Ze,t.toolNamePrefix)}function po(e){return Buffer.from(e,"utf8").toString("base64url")}function nf(e,t,n,o){let r=e.tool;if(r===void 0||!Wc(r,t)||tf(n.reason,t))return n;let s=r.input.command;if(typeof s!="string")return n;let i='"'+j0(F0(process.argv[1]??""),wr)+'"',c=[Lr,i,po(s),po(JSON.stringify(o??[])),po(Ge(r.input.description))].join(" ");return{kind:"deny",reason:Pr,rewritten:c}}function of(e,t,n){return n?"toolerr":Or.includes(e.canonicalName)||(t.nativeTools.edit??[]).includes(e.name)?"edit":Wc(e,t)?"cmd":null}function mo(e){if(Array.isArray(e))return"["+e.map(mo).join(",")+"]";if(typeof e=="object"&&e!==null){let t=e;return"{"+Object.keys(t).filter(o=>t[o]!==void 0).sort().map(o=>JSON.stringify(o)+":"+mo(t[o])).join(",")+"}"}return JSON.stringify(e)??"null"}function rf(e){let t=e.indexOf(`
|
|
197
|
+
`),n=t<0?e:e.slice(0,t);if(!n.startsWith(en))return null;let o=0,r=0;for(let s of n.slice(en.length)){let i=s.charCodeAt(0)-B0;if(i<0||i>9)break;o=o*10+i,r++}return r===0?null:o}function sf(e){for(let t of Ar)if(typeof e[t]=="string")return e[t];return null}async function cf(e,t,n,o){let r=e.tool;if(r===void 0||r.canonicalName.startsWith(Tr))return O;let s=e.result??{isError:!1,bytes:0},i=lf(s);s.persistedPath!==void 0&&(s.bytes=Buffer.byteLength(i)),r.canonicalName===dn&&Z0(e,n,r,i);let c=of(r,t,s.isError);if(c!==null){let g=c==="cmd"?Ji(r.canonicalName,Ge(r.input.command)):c==="toolerr"?r.canonicalName+":"+mo(r.input):null;Ut(n,e.sessionId,{session_id:e.sessionId,worktree:n.worktree,agent:e.agent,kind:c,tool:r.canonicalName,key:g,path:sf(r.input),ok:s.isError?0:1,exit_code:rf(i),bytes:s.bytes,body:i,turn:e.turn??0,sandbox_bytes:s.bytes,returned_bytes:s.bytes})}if(s.bytes<=To||s.keep===!0)return O;let a;if(pe(e)){if(Un(e,Mn(e,{projectDir:n.worktree,env:o}))==="A")return O;a=Dr+r.canonicalName+":"+String(e.turn??0)}else{if(!ye(t))return O;a=df(r,e)}let l=[r.input.description,r.input.command,r.input.file_path,r.input.pattern,r.input.url].map(Ge).find(g=>g.trim()!=="")??"",u=Pt(i,"text",Ao),f=await y(n),d;s.bytes<=So?(d=uo(f,n,e.sessionId,a,i,"text",u).sourceId,Zn(f,d,e.sessionId,eo(i))):(d=$n(f,Xc(n,e.sessionId,a),u),ff(n,e.sessionId,d,a,i,u));let x=cc(d),E=await uf(n,e.sessionId),m=E.trim()===""?void 0:l+" "+E,_=yo(l,x,s.bytes,t.toolNamePrefix,Dc(l,E,i)),S=af(_,ao(l,a)),h=yc(i,m??l,Oo);if(h!==null)return{kind:"replace",output:Hc(h,_)};let p=Tc(u,l,S,a,m);return{kind:"replace",output:p.more!==null?Hc(p.text,_):p.text}}function Hc(e,t){return e===""?t:e+`
|
|
198
|
+
`+t}function af(e,t){return Math.max(0,Ro+Buffer.byteLength(`
|
|
199
|
+
`+t)-1-Buffer.byteLength(e))}function lf(e){let t=e.text??"";if(e.persistedPath===void 0)return t;try{return v0(e.persistedPath,"utf8")}catch{return t}}async function uf(e,t){try{return zi(await y(e),t)}catch{return""}}function df(e,t){let n=Ge(e.input.command)??Ge(e.input.file_path)??"",o=n.indexOf(`
|
|
200
|
+
`);return(e.canonicalName+":"+(o<0?n:n.slice(0,o))).slice(0,Go)+"#"+(e.callId??String(t.turn??0))}function ff(e,t,n,o,r,s){y(e).then(i=>{sc(i,n,Xc(e,t,o),s,eo(r))}).catch(i=>{process.stderr.write("hooks: index write failed: "+_e(i)+`
|
|
201
|
+
`)})}function Xc(e,t,n){return{sessionId:t,worktree:e.worktree,agent:e.agent,kind:"content",label:n,createdAt:Date.now()}}async function xf(e,t,n){let o=await y(n);return j(o,tt+e.sessionId,on),xt(t)&&jc(o,e.sessionId),O}function pf(e,t){return Ut(t,e.sessionId,{session_id:e.sessionId,worktree:t.worktree,agent:e.agent,kind:"cost",tool:null,key:null,path:null,ok:1,exit_code:null,bytes:0,body:"",turn:e.turn??0,sandbox_bytes:0,returned_bytes:0}),Promise.resolve(O)}var _o={stdout:"",exitCode:0};function Ef(e){return ge.includes(e)}function Ht(e){process.exitCode=e.exitCode,e.stdout!==""&&xo(e.stdout),e.stderr!==void 0&&e.stderr!==""&&process.stderr.write(e.stderr+`
|
|
202
|
+
`)}async function mf(e,t){let n=e.indexOf(nt),o=n>=0?e[n+1]??"":"";if(!Ef(o))return console.error("hooks: unknown "+nt+" "+JSON.stringify(o)+". Fix: pass "+nt+" with one of "+ge.join(", ")+"."),Ht(_o);let r;try{r=JSON.parse(await fo())}catch(s){return console.error("hooks: "+s.message),Ht(_o)}try{return Ht(await vc(o,r,t))}catch(s){return console.error("hooks: "+s.message),Ht(_o)}}mf(process.argv.slice(2),process.env);export{mf as main};
|