#!/usr/bin/env node
import"./suppress-stderr.mjs";import{readFileSync as N,writeFileSync as $,existsSync as Q,rmSync as c,mkdirSync as F,copyFileSync as k,readdirSync as u}from"node:fs";import{resolve as q,dirname as H,basename as R}from"node:path";import{fileURLToPath as x}from"node:url";import{homedir as M,tmpdir as v}from"node:os";import{readStdin as g}from"./core/stdin.mjs";import{routePreToolUse as D,initSecurity as P}from"./core/routing.mjs";import{formatDecision as S}from"./core/formatters.mjs";function T(W,z){F(z,{recursive:!0});for(let X of u(W,{withFileTypes:!0})){let A=q(W,X.name),Y=q(z,X.name);if(X.isDirectory())T(A,Y);else k(A,Y)}}try{let W=H(x(import.meta.url)),z=q(W,".."),A=JSON.parse(N(q(z,"package.json"),"utf-8")).version??"unknown",Y=R(z),f=H(z),I=q(v(),`context-mode-healed-${A}`),j=z.includes("/plugins/cache/")||z.includes("\\plugins\\cache\\");if(A!=="unknown"&&j&&!Q(I)){let J=q(f,A);if(Y!==A&&!Q(J)){T(z,J);let B=q(J,"start.mjs");if(!Q(B))$(B,["#!/usr/bin/env node",'import { existsSync } from "node:fs";','import { dirname, resolve } from "node:path";','import { fileURLToPath } from "node:url";',"const __dirname = dirname(fileURLToPath(import.meta.url));","process.chdir(__dirname);","if (!process.env.PUKU_PROJECT_DIR) process.env.PUKU_PROJECT_DIR = process.cwd();",'if (existsSync(resolve(__dirname, "server.bundle.mjs"))) {','  await import("./server.bundle.mjs");','} else if (existsSync(resolve(__dirname, "build", "server.js"))) {','  await import("./build/server.js");',"}"].join(`
`),"utf-8")}let b=Q(J)?J:z,C=q(M(),".claude","plugins","installed_plugins.json");if(Q(C)){let B=JSON.parse(N(C,"utf-8"));for(let[Z,K]of Object.entries(B.plugins||{})){if(!Z.toLowerCase().includes("context-mode"))continue;for(let E of K)E.installPath=b,E.version=A,E.lastUpdated=new Date().toISOString()}$(C,JSON.stringify(B,null,2)+`
`,"utf-8")}let L=q(M(),".claude","settings.json");try{let B=JSON.parse(N(L,"utf-8")),Z=B.hooks||{},K=!1;for(let E of Object.keys(Z)){let _=Z[E];if(!Array.isArray(_))continue;for(let O of _){if(E==="PreToolUse"&&O.matcher?.includes("Task")&&!O.matcher.includes("Agent"))O.matcher=O.matcher.replace("Task","Agent|Task"),K=!0;for(let G of O.hooks||[])if(G.command&&G.command.includes(".mjs")&&G.command.includes("context-mode")&&!G.command.includes(b)){let U=G.command.match(/([a-z]+\.mjs)\s*"?\s*$/);if(U)G.command="node "+q(b,"hooks",U[1]),K=!0}}}if(K)$(L,JSON.stringify(B,null,2)+`
`,"utf-8")}catch{}$(I,Date.now().toString(),"utf-8")}}catch{}var p=H(x(import.meta.url));await P(q(p,"..","build"));var l=await g(),V=JSON.parse(l),d=V.tool_name??"",h=V.tool_input??{},m=D(d,h,process.env.PUKU_PROJECT_DIR),w=S(m);if(w!==null)process.stdout.write(JSON.stringify(w)+`
`);
