()
| 169 | Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return Jn(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return tA(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(fs(e,"utf-8"))}}catch(n){let r=n instanceof Error?n.message:String(n);return(typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:n instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:r}:{ok:!1,reason:"read_error",error:r}}}writeHooksConfig(e){let n=this.getHooksPath();wp(Ep(n),{recursive:!0}),Jx(n,JSON.stringify(e,null,2)+` |
| 170 | `,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return QI(Jn(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&Xx(n),s=Ac(e),i=this.hasCodexPluginHookManifest(s),a=o?this.probeCodexContextModePluginRoot():null,c=a?this.hasCodexPluginHookManifest(a):!1,u=a?!this.samePath(s,a):!1;return{enabled:o,configuredRoot:s,configuredManifestAvailable:i,runtimeRoot:a,runtimeManifestAvailable:c,rootMismatch:u,hooksAvailable:o&&(c||!a&&i),ownsHooksForUpgrade:o&&a!==null&&c&&!u}}probeCodexContextModePluginRoot(){try{let e=process.platform==="win32"?this.codexPluginListRunner("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):this.codexPluginListRunner("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});return Nc(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(Ac(e))===this.normalizeCommand(Ac(n))}pruneStaleUserHookTrustState(e,n){let r=this.normalizeCommand(this.getHooksPath()),o={post_compact:"PostCompact",post_tool_use:"PostToolUse",pre_compact:"PreCompact",pre_tool_use:"PreToolUse",session_start:"SessionStart",stop:"Stop",user_prompt_submit:"UserPromptSubmit"};return Qx(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=cA(s.slice(i.length));if(a===null)return!1;let u=this.normalizeCommand(a).split(":"),l=Number(u.pop()),d=Number(u.pop()),p=o[u.pop()??""];if(u.join(":")!==r||!p||!Number.isInteger(d)||!Number.isInteger(l))return!1;let m=n[p]?.[d];return!m||!Array.isArray(m.hooks)||!m.hooks[l]})}isExpectedHookEntry(e,n,r){return!n||typeof n!="object"||e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}isManagedContextModeEntry(e,n){return!n||typeof n!="object"?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(Array.isArray(n.hooks)?n.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(no[e]??""),s=sA[e]??[];return r.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as oS,writeFileSync as uA,mkdirSync as lA,accessSync as dA,chmodSync as pA,constants as mA}from"node:fs";import{resolve as Dc,join as fA}from"node:path";var wr,jc=x(()=>{"use strict";it();wr=class extends ve{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return Dc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule;return{[n.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_TOOL_USE,e)}]}],[n.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.POST_TOOL_USE,e)}]}],[n.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_COMPACT,e)}]}],[n.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:r(n.SESSION_START,e)}]}]}}readSettings(){try{let e=oS(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=oS(Dc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();lA(Dc(".github","hooks"),{recursive:!0}),uA(n,JSON.stringify(e,null,2)+` |
| 171 | `,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=fA(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Dc(r,o);try{dA(s,mA.R_OK),pA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function sS(t,e){if(!Pp[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Yt,Pp,HW,UW,iS=x(()=>{"use strict";Yt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Pp={[Yt.PRE_TOOL_USE]:"pretooluse.mjs",[Yt.POST_TOOL_USE]:"posttooluse.mjs",[Yt.PRE_COMPACT]:"precompact.mjs",[Yt.SESSION_START]:"sessionstart.mjs"},HW=[Yt.PRE_TOOL_USE,Yt.SESSION_START],UW=[Yt.POST_TOOL_USE,Yt.PRE_COMPACT]});var cS={};_e(cS,{VSCodeCopilotAdapter:()=>Op});import{readFileSync as Rp,mkdirSync as aS,accessSync as hA,existsSync as gA,constants as yA}from"node:fs";import{resolve as hs,join as Di}from"node:path";import{homedir as Cp}from"node:os";var Op,uS=x(()=>{"use strict";jc();it();iS();Op=class extends wr{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Yt,HOOK_SCRIPTS:Pp,buildHookCommand:sS};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=ht();if(e){let s=Di(e,"context-mode","sessions");return aS(s,{recursive:!0}),s}let n=hs(".github","context-mode","sessions"),r=Di(Cp(),".vscode","context-mode","sessions"),o=gA(hs(".github"))?n:r;return aS(o,{recursive:!0}),o}getConfigDir(e){return hs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=hs(".github","hooks");try{hA(r,yA.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=hs(r,"context-mode.json");try{let s=Rp(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Yt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Yt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=hs(".vscode","mcp.json"),n=Rp(e,"utf-8"),o=JSON.parse(n).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Di(Cp(),".vscode","extensions"),Di(Cp(),".vscode-insiders","extensions")];for(let n of e)try{let r=Rp(Di(n,"extensions.json"),"utf-8"),s=JSON.parse(r).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function lS(t,e){if(!Ip[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Qt,Ip,GW,JW,dS=x(()=>{"use strict";Qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Ip={[Qt.PRE_TOOL_USE]:"pretooluse.mjs",[Qt.POST_TOOL_USE]:"posttooluse.mjs",[Qt.PRE_COMPACT]:"precompact.mjs",[Qt.SESSION_START]:"sessionstart.mjs"},GW=[Qt.PRE_TOOL_USE,Qt.SESSION_START],JW=[Qt.POST_TOOL_USE,Qt.PRE_COMPACT]});var pS={};_e(pS,{JetBrainsCopilotAdapter:()=>Ap});import{readFileSync as _A}from"node:fs";import{resolve as bA}from"node:path";var Ap,mS=x(()=>{"use strict";jc();dS();Ap=class extends wr{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Qt,HOOK_SCRIPTS:Ip,buildHookCommand:lS};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return bA(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=_A(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[Qt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Qt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function fS(t,e){let n=Np[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var St,Np,r3,o3,hS=x(()=>{"use strict";St={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Np={[St.PRE_TOOL_USE]:"pretooluse.mjs",[St.POST_TOOL_USE]:"posttooluse.mjs",[St.PRE_COMPACT]:"precompact.mjs",[St.SESSION_START]:"sessionstart.mjs",[St.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[St.STOP]:"stop.mjs"},r3=[St.PRE_TOOL_USE,St.SESSION_START],o3=[St.POST_TOOL_USE,St.PRE_COMPACT,St.USER_PROMPT_SUBMIT,St.STOP]});var SS={};_e(SS,{CopilotCliAdapter:()=>Dp,copilotCliHome:()=>zc,copilotCliMcpConfigPath:()=>Lc});import{existsSync as gS,mkdirSync as yS,readFileSync as Mp,writeFileSync as xA}from"node:fs";import{homedir as _S}from"node:os";import{dirname as SA,join as gs,resolve as xS}from"node:path";function bS(){return process.env[vA]==="1"}function kA(t){return xS(t,"configs","copilot-cli","hooks.json")}function wA(t){return Wn(Mp(t,"utf-8"))??{}}function EA(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function zc(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?gs(_S(),t.replace(/^~[/\\]?/,"")):xS(t):gs(_S(),".copilot")}function Lc(){return gs(zc(),"mcp-config.json")}var vA,Dp,vS=x(()=>{"use strict";jc();it();Mi();hS();vA="CONTEXT_MODE_COPILOT_PLUGIN";Dp=class extends wr{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:St,HOOK_SCRIPTS:Np,buildHookCommand:fS};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return gs(zc(),"hooks","context-mode.json")}getConfigDir(e){return zc()}getSessionDir(){let e=ht(),n=e?gs(e,"context-mode","sessions"):gs(this.getConfigDir(),"context-mode","sessions");return yS(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();yS(SA(n),{recursive:!0}),xA(n,JSON.stringify(e,null,2)+` |
| 172 | `,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=Mp(this.getSettingsPath(),"utf-8");return Wn(e)??null}catch{return null}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="ask")return{permissionDecision:"ask",permissionDecisionReason:e.reason??"Action requires user confirmation"};if(e.decision==="modify"&&e.updatedInput)return{modifiedArgs:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext}}formatPostToolUseResponse(e){if(e.updatedOutput)return{modifiedResult:{resultType:"success",textResultForLlm:e.updatedOutput}};if(e.additionalContext)return{additionalContext:e.additionalContext}}formatPreCompactResponse(e){}formatSessionStartResponse(e){return e.context?{additionalContext:e.context}:void 0}validateHooks(e){let n=[],r=bS(),o=r?kA(e):this.getSettingsPath(),s=r?`Copilot CLI plugin bundle hooks.json (${o})`:o,i=r?"copilot plugin install mksglu/context-mode:configs/copilot-cli":"context-mode upgrade";try{let a=wA(o),c=a.hooks;n.push({check:"Hooks schema version",status:a.version===1?"pass":"fail",message:a.version===1?`${s} declares the required "version": 1`:`${s} is missing top-level "version": 1`,...a.version===1?{}:{fix:i}});for(let u of Object.values(St)){let l=EA(c,u);n.push({check:`${u} hook`,status:l?"pass":"fail",message:l?`${u} hook configured in ${s}`:`${u} not found in ${s}`,...l?{}:{fix:i}})}}catch{n.push({check:"Hook configuration",status:"fail",message:`Could not read ${s}`,fix:i})}return n}checkPluginRegistration(){if(bS())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=Mp(Lc(),"utf-8");return"context-mode"in((Wn(e)??{})?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in Copilot CLI mcp-config.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in Copilot CLI mcpServers",fix:"copilot mcp add context-mode -- context-mode"}}catch{return{check:"MCP registration",status:"fail",message:`Could not read ${Lc()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return gS(Lc())||gS(this.getSettingsPath())?"standalone":"not installed"}}});function ji(t,e){let n=jp[e],r=en(e);if("command"in t){let s=t.command??"";return n!=null&&s.includes(n)||s.includes(r)}return t.hooks?.some(s=>{let i=s.command??"";return n!=null&&i.includes(n)||i.includes(r)})??!1}function en(t){return`context-mode hook cursor ${t.toLowerCase()}`}var ke,jp,TA,$A,Lp,kS,wS,ES=x(()=>{"use strict";ke={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},jp={[ke.PRE_TOOL_USE]:"pretooluse.mjs",[ke.POST_TOOL_USE]:"posttooluse.mjs",[ke.SESSION_START]:"sessionstart.mjs",[ke.STOP]:"stop.mjs",[ke.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},TA="MCP:(?!ctx_)",$A=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",TA],Lp=$A.join("|"),kS=[ke.PRE_TOOL_USE],wS=[ke.POST_TOOL_USE]});var CS={};_e(CS,{CursorAdapter:()=>zp});import{readFileSync as Hc,writeFileSync as PA,mkdirSync as RA,accessSync as TS,chmodSync as CA,constants as $S,existsSync as PS,readdirSync as OA}from"node:fs";import{execSync as IA}from"node:child_process";import{resolve as ro,join as oo}from"node:path";import{homedir as Uc}from"node:os";var RS,zp,OS=x(()=>{"use strict";it();Sr();ES();RS="/Library/Application Support/Cursor/hooks.json",zp=class extends ve{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output??n.error_message,isError:!!n.error_message,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??n.trigger??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let n=e;return{sessionId:n.conversation_id??`pid-${process.ppid}`,status:n.status??"completed",loopCount:n.loop_count??0,generationId:n.generation_id,transcriptPath:n.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return ro(".cursor","hooks.json")}getConfigDir(e){return ro(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[ke.PRE_TOOL_USE]:[{type:"command",command:en(ke.PRE_TOOL_USE),matcher:Lp,loop_limit:null,failClosed:!1}],[ke.POST_TOOL_USE]:[{type:"command",command:en(ke.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[ke.SESSION_START]:[{type:"command",command:en(ke.SESSION_START),loop_limit:null,failClosed:!1}],[ke.STOP]:[{type:"command",command:en(ke.STOP),loop_limit:null,failClosed:!1}],[ke.AFTER_AGENT_RESPONSE]:[{type:"command",command:en(ke.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=Hc(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();RA(ro(".cursor"),{recursive:!0}),PA(n,JSON.stringify(e,null,2)+` |
| 173 | `,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of kS){let a=s[i],c=Array.isArray(a)&&a.some(u=>ji(u,i));n.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${r.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of wS){let a=s[i],c=Array.isArray(a)&&a.some(u=>ji(u,i));n.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}PS(RS)&&n.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&n.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((r?Object.entries(r.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>ji(c,i))):!1)&&r?n.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${r.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):n.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),n}detectPluginInstalls(){let e=[oo(Uc(),".cursor","plugins","local"),oo(Uc(),".cursor","plugins","cache")],n=[];for(let r of e){try{TS(r,$S.F_OK)}catch{continue}let o=[];try{o=OA(r)}catch{continue}for(let s of o){let i=oo(r,s,".cursor-plugin","plugin.json");try{let a=Hc(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[ro(".cursor","mcp.json"),oo(Uc(),".cursor","mcp.json")];for(let r of e)try{let o=Hc(r,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${r}`}}catch{continue}let n=this.detectPluginInstalls();return n.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${n[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return IA("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=this.readSettings()??{version:1,hooks:{}},r=n.hooks??{},o=[];return this.upsertHookEntry(r,ke.PRE_TOOL_USE,{type:"command",command:en(ke.PRE_TOOL_USE),matcher:Lp,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.POST_TOOL_USE,{type:"command",command:en(ke.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.SESSION_START,{type:"command",command:en(ke.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.STOP,{type:"command",command:en(ke.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ke.AFTER_AGENT_RESPONSE,{type:"command",command:en(ke.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),n.version=1,n.hooks=r,this.writeSettings(n),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let n=[],r=oo(e,"hooks","cursor");for(let o of Object.values(jp)){let s=ro(r,o);try{TS(s,$S.R_OK),CA(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),oo(Uc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(RS),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let n=Hc(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[ro(".claude","settings.json"),ro(".claude","settings.local.json"),oo(Ze(),"settings.json")].some(n=>PS(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>ji(c,n));a>=0?(i[a]=r,o.push(`Updated existing ${n} hook entry`)):(i.push(r),o.push(`Added ${n} hook entry`)),e[n]=i}}});var AS={};_e(AS,{AntigravityAdapter:()=>Li});import{readFileSync as Fc,writeFileSync as AA,mkdirSync as NA}from"node:fs";import{resolve as Zc,dirname as IS}from"node:path";import{fileURLToPath as MA}from"node:url";import{homedir as Hp}from"node:os";var Li,Up=x(()=>{"use strict";it();Li=class extends ve{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Zc(Hp(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Zc(Hp(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Fc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();NA(IS(n),{recursive:!0}),AA(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Fc(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.gemini/antigravity/mcp_config.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.gemini/antigravity/mcp_config.json"}}}getInstalledVersion(){try{let e=Zc(Hp(),".gemini","extensions","context-mode","package.json");return JSON.parse(Fc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Zc(IS(MA(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Fc(e,"utf-8")}catch{return`# context-mode |
| 174 |
no test coverage detected