| 751 | `).map((W)=>W.replace(/\r$/,"")).filter(Boolean));return}if(A.code===1){z([]);return}if(["ENOENT","EACCES","EPERM"].includes(A.code)){Y(A);return}if(!j&&nh_(w)){N("rg EAGAIN error detected, retrying with single-threaded mode (-j 1)"),d("tengu_ripgrep_eagain_retry",{}),e44(q,K,_,(W,D,f)=>{$(W,D,f,!0)},!0);return}let J=O&&O.trim().length>0,M=A.signal==="SIGTERM"||A.signal==="SIGKILL"||A.code==="ABORT_ERR",X=A.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER",P=[];if(J){if(P=O.trim().split(` |
| 752 | `).map((W)=>W.replace(/\r$/,"")).filter(Boolean),P.length>0&&(M||X))P=P.slice(0,-1)}if(N(`rg error (signal=${A.signal}, code=${A.code}, stderr: ${w}), ${P.length} results`),A.code!==2&&A.code!=="ABORT_ERR")H6(A);if(M&&P.length===0){Y(new _K4(`Ripgrep search timed out after ${Z1()==="wsl"?60:20} seconds. The search may have matched files but did not complete in time. Try searching a more specific path or pattern.`,P));return}z(P)};e44(q,K,_,(A,O,w)=>{$(A,O,w,!1)})})}function zK4(){let q=gG8();return{mode:q.mode,path:q.command,working:BG8?.working??null}}async function YK4(){if(process.platform!=="darwin"||qK4)return;qK4=!0;let q=gG8();if(q.mode!=="builtin")return;let K=q.command;if(!(await a8("codesign",["-vv","-d",K],{preserveOutputOnError:!1})).stdout.split(` |
| 753 | `).find((Y)=>Y.includes("linker-signed")))return;try{let Y=await a8("codesign",["--sign","-","--force","--preserve-metadata=entitlements,requirements,flags,runtime",K]);if(Y.code!==0)H6(Error(`Failed to sign ripgrep: ${Y.stdout} ${Y.stderr}`));let $=await a8("xattr",["-d","com.apple.quarantine",K]);if($.code!==0)H6(Error(`Failed to remove quarantine: ${$.stdout} ${$.stderr}`))}catch(Y){H6(Y)}}var ch_,lh_,gG8,Zn6=20000000,_K4,FG8,BG8=null,rh_,qK4=!1;var KC=y(()=>{F4();k8();_8();m8();XK();i41();E8();vK();ch_=dh_(import.meta.url),lh_=_76.join(ch_,"../"),gG8=_1(()=>{if(k_(process.env.USE_BUILTIN_RIPGREP)){let{cmd:z}=wA8("rg",[]);if(z!=="rg")return{mode:"system",command:"rg",args:[]}}if(jj())return{mode:"embedded",command:process.execPath,args:["--no-config"],argv0:"rg"};let K=_76.resolve(lh_,"vendor","ripgrep");return{mode:"builtin",command:process.platform==="win32"?_76.resolve(K,`${process.arch}-win32`,"rg.exe"):_76.resolve(K,`${process.arch}-${process.platform}`,"rg"),args:[]}});_K4=class _K4 extends Error{partialResults;constructor(q,K){super(q);this.partialResults=K;this.name="RipgrepTimeoutError"}};FG8=_1(async(q,K,_=[])=>{if(_76.resolve(q)===_76.resolve(Qh_()))return;try{let z=["--files","--hidden"];_.forEach((O)=>{z.push("--glob",`!${O}`)});let Y=await ih_(z,q,K);if(Y===0)return 0;let $=Math.floor(Math.log10(Y)),A=Math.pow(10,$);return Math.round(Y/A)*A}catch(z){if(z?.name!=="AbortError")H6(z)}},(q,K,_=[])=>`${q}|${_.join(",")}`);rh_=_1(async()=>{if(BG8!==null)return;let q=gG8();try{let K;if(q.argv0){let z=Bun.spawn([q.command,"--version"],{argv0:q.argv0,stderr:"ignore",stdout:"pipe"}),[Y,$]=await Promise.all([z.stdout.text(),z.exited]);K={code:$,stdout:Y}}else K=await a8(q.command,[...q.args,"--version"],{timeout:5000});let _=K.code===0&&!!K.stdout&&K.stdout.startsWith("ripgrep ");BG8={working:_,lastTested:Date.now(),config:q},N(`Ripgrep first use test: ${_?"PASSED":"FAILED"} (mode=${q.mode}, path=${q.command})`),d("tengu_ripgrep_availability",{working:_?1:0,using_system:q.mode==="system"?1:0})}catch(K){BG8={working:!1,lastTested:Date.now(),config:q},H6(K)}})});function fG(q){let K=v1("policySettings")?.strictPluginOnlyCustomization;if(K===!0)return!0;if(Array.isArray(K))return K.includes(q);return!1}function Gn6(q){return q!==void 0&&oh_.has(q)}var oh_;var IA6=y(()=>{U1();oh_=new Set(["plugin","policySettings","built-in","builtin","bundled"])});import{statSync as ah_}from"fs";import{lstat as sh_,readdir as th_,readFile as eh_,realpath as qS_,stat as $K4}from"fs/promises";import{homedir as KS_}from"os";import{dirname as _S_,join as Wv6,resolve as AK4,sep as zS_}from"path";function z76(q,K="Custom item"){let _=q.split(` |
| 754 | `);for(let z of _){let Y=z.trim();if(Y){let A=Y.match(/^#+\s+(.+)$/)?.[1]??Y;return A.length>100?A.substring(0,97)+"...":A}}return K}function wK4(q){if(q===void 0||q===null)return null;if(!q)return[];let K=[];if(typeof q==="string")K=[q];else if(Array.isArray(q))K=q.filter((z)=>typeof z==="string");if(K.length===0)return[];let _=_C(K);if(_.includes("*"))return["*"];return _}function Y76(q){let K=wK4(q);if(K===null)return q===void 0?void 0:[];if(K.includes("*"))return;return K}function RF(q){let K=wK4(q);if(K===null)return[];return K}async function YS_(q){try{let K=await sh_(q,{bigint:!0});if(K.dev===0n&&K.ino===0n)return null;return`${K.dev}:${K.ino}`}catch{return null}}function $S_(q){let K=hY(q),_=hY(Fz());if(!K||!_)return K;let z=jH(q);if(z&&zJ(z)===zJ(_))return K;let Y=zJ(K),$=zJ(_);if(Y!==$&&Y.startsWith($+zS_))return _;return K}function kh1(q,K){let _=AK4(KS_()).normalize("NFC"),z=$S_(K),Y=AK4(K),$=[];while(!0){if(zJ(Y)===zJ(_))break;let A=Wv6(Y,".claude",q);try{ah_(A),$.push(A)}catch(w){if(!e3(w))throw w}if(z&&zJ(Y)===zJ(z))break;let O=_S_(Y);if(O===Y)break;Y=O}return $}async function AS_(q,K){let _=[],z=new Set;async function Y($){if(K.aborted)return;try{let A=await $K4($,{bigint:!0});if(A.isDirectory()){let O=A.dev!==void 0&&A.ino!==void 0?`${A.dev}:${A.ino}`:await qS_($);if(z.has(O)){N(`Skipping already visited directory (circular symlink): ${$}`);return}z.add(O)}}catch(A){let O=A instanceof Error?A.message:String(A);N(`Failed to stat directory ${$}: ${O}`);return}try{let A=await th_($,{withFileTypes:!0});for(let O of A){if(K.aborted)break;let w=Wv6($,O.name);try{if(O.isSymbolicLink())try{let j=await $K4(w);if(j.isDirectory())await Y(w);else if(j.isFile()&&O.name.endsWith(".md"))_.push(w)}catch(j){let H=j instanceof Error?j.message:String(j);N(`Failed to follow symlink ${w}: ${H}`)}else if(O.isDirectory())await Y(w);else if(O.isFile()&&O.name.endsWith(".md"))_.push(w)}catch(j){let H=j instanceof Error?j.message:String(j);N(`Failed to access ${w}: ${H}`)}}}catch(A){let O=A instanceof Error?A.message:String(A);N(`Failed to read directory ${$}: ${O}`)}}return await Y(q),_}async function vh1(q){let K=i6(process.env.CLAUDE_CODE_USE_NATIVE_FILE_SEARCH),_=AbortSignal.timeout(3000),z;try{z=K?await AS_(q,_):await LF(["--files","--hidden","--follow","--no-ignore","--glob","*.md"],q,_)}catch($){if(e3($))return[];throw $}return(await Promise.all(z.map(async($)=>{try{let A=await eh_($,{encoding:"utf-8"}),{frontmatter:O,content:w}=kH(A,$);return{filePath:$,frontmatter:O,content:w}}catch(A){let O=A instanceof Error?A.message:String(A);return N(`Failed to read/parse markdown file: ${$}: ${O}`),null}}))).filter(($)=>$!==null)}var OK4,ii;var ri=y(()=>{F4();k8();v8();_8();m8();y8();bK();rV();E5();fX();KC();kO();qI();IA6();OK4=["commands","agents","output-styles","skills","workflows",...[]];ii=_1(async function(q,K){let _=Date.now(),z=Wv6(c1(),q),Y=Wv6(MP(),".claude",q),$=kh1(q,K),A=hY(K),O=jH(K);if(A&&O&&O!==A){let f=zJ(Wv6(A,".claude",q));if(!$.some((Z)=>zJ(Z)===f)){let Z=Wv6(O,".claude",q);if(!$.includes(Z))$.push(Z)}}let[w,j,H]=await Promise.all([vh1(Y).then((f)=>f.map((G)=>({...G,baseDir:Y,source:"policySettings"}))),$J("userSettings")&&!(q==="agents"&&fG("agents"))?vh1(z).then((f)=>f.map((G)=>({...G,baseDir:z,source:"userSettings"}))):Promise.resolve([]),$J("projectSettings")&&!(q==="agents"&&fG("agents"))?Promise.all($.map((f)=>vh1(f).then((G)=>G.map((Z)=>({...Z,baseDir:f,source:"projectSettings"}))))):Promise.resolve([])]),J=H.flat(),M=[...w,...j,...J],X=await Promise.all(M.map((f)=>YS_(f.filePath))),P=new Map,W=[];for(let[f,G]of M.entries()){let Z=X[f]??null;if(Z===null){W.push(G);continue}let T=P.get(Z);if(T!==void 0){N(`Skipping duplicate file '${G.filePath}' from ${G.source} (same inode already loaded from ${T})`);continue}P.set(Z,G.source),W.push(G)}let D=M.length-W.length;if(D>0)N(`Deduplicated ${D} files in ${q} (same inode via symlinks or hard links)`);return d("tengu_dir_search",{durationMs:Date.now()-_,managedFilesFound:w.length,userFilesFound:j.length,projectFilesFound:J.length,projectDirsSearched:$.length,subdir:q}),W},(q,K)=>`${q}:${K}`)});function $M(q){switch(q.type){case"generic-error":return q.error;case"path-not-found":return`Path not found: ${q.path} (${q.component})`;case"git-auth-failed":return`Git authentication failed (${q.authType}): ${q.gitUrl}`;case"git-timeout":return`Git ${q.operation} timeout: ${q.gitUrl}`;case"network-error":return`Network error: ${q.url}${q.details?` - ${q.details}`:""}`;case"manifest-parse-error":return`Manifest parse error: ${q.parseError}`;case"manifest-validation-error":return`Manifest validation failed: ${q.validationErrors.join(", ")}`;case"plugin-not-found":return`Plugin ${q.pluginId} not found in marketplace ${q.marketplace}`;case"marketplace-not-found":return`Marketplace ${q.marketplace} not found`;case"marketplace-load-failed":return`Marketplace ${q.marketplace} failed to load: ${q.reason}`;case"mcp-config-invalid":return`MCP server ${q.serverName} invalid: ${q.validationError}`;case"mcp-server-suppressed-duplicate":{let K=q.duplicateOf.startsWith("plugin:")?`server provided by plugin "${q.duplicateOf.split(":")[1]??"?"}"`:`already-configured "${q.duplicateOf}"`;return`MCP server "${q.serverName}" skipped — same command/URL as ${K}`}case"hook-load-failed":return`Hook load failed: ${q.reason}`;case"component-load-failed":return`${q.component} load failed from ${q.path}: ${q.reason}`;case"mcpb-download-failed":return`Failed to download MCPB from ${q.url}: ${q.reason}`;case"mcpb-extract-failed":return`Failed to extract MCPB ${q.mcpbPath}: ${q.reason}`;case"mcpb-invalid-manifest":return`MCPB manifest invalid at ${q.mcpbPath}: ${q.validationError}`;case"lsp-config-invalid":return`Plugin "${q.plugin}" has invalid LSP server config for "${q.serverName}": ${q.validationError}`;case"lsp-server-start-failed":return`Plugin "${q.plugin}" failed to start LSP server "${q.serverName}": ${q.reason}`;case"lsp-server-crashed":if(q.signal)return`Plugin "${q.plugin}" LSP server "${q.serverName}" crashed with signal ${q.signal}`;return`Plugin "${q.plugin}" LSP server "${q.serverName}" crashed with exit code ${q.exitCode??"unknown"}`;case"lsp-request-timeout":return`Plugin "${q.plugin}" LSP server "${q.serverName}" timed out on ${q.method} request after ${q.timeoutMs}ms`;case"lsp-request-failed":return`Plugin "${q.plugin}" LSP server "${q.serverName}" ${q.method} request failed: ${q.error}`;case"marketplace-blocked-by-policy":if(q.blockedByBlocklist)return`Marketplace '${q.marketplace}' is blocked by enterprise policy`;return`Marketplace '${q.marketplace}' is not in the allowed marketplace list`;case"dependency-unsatisfied":{let K=q.reason==="not-enabled"?"disabled — enable it or remove the dependency":"not found in any configured marketplace";return`Dependency "${q.dependency}" is ${K}`}case"plugin-cache-miss":return`Plugin "${q.plugin}" not cached at ${q.installPath} — run /plugins to refresh`}}function jK4(q){return q.endsWith(`@${Tn6}`)}function HK4(q){return Vh1.get(q)}function Nh1(){let q=Z7(),K=[],_=[];for(let[z,Y]of Vh1){if(Y.isAvailable&&!Y.isAvailable())continue;let $=`${z}@${Tn6}`,A=q?.enabledPlugins?.[$],O=A!==void 0?A===!0:Y.defaultEnabled??!0,w={name:z,manifest:{name:z,description:Y.description,version:Y.version},path:Tn6,source:$,repository:$,enabled:O,isBuiltin:!0,hooksConfig:Y.hooks,mcpServers:Y.mcpServers};if(O)K.push(w);else _.push(w)}return{enabled:K,disabled:_}}function JK4(){let{enabled:q}=Nh1(),K=[];for(let _ of q){let z=Vh1.get(_.name);if(!z?.skills)continue;for(let Y of z.skills)K.push(OS_(Y))}return K}function OS_(q){return{type:"prompt",name:q.name,description:q.description,hasUserSpecifiedDescription:!0,allowedTools:q.allowedTools??[],argumentHint:q.argumentHint,whenToUse:q.whenToUse,model:q.model,disableModelInvocation:q.disableModelInvocation??!1,userInvocable:q.userInvocable??!0,contentLength:0,source:"bundled",loadedFrom:"bundled",hooks:q.hooks,context:q.context,agent:q.agent,isEnabled:q.isEnabled??(()=>!0),isHidden:!(q.userInvocable??!0),progressMessage:"running",getPromptForCommand:q.getPromptForCommand}}var Vh1,Tn6="builtin";var vn6=y(()=>{U1();Vh1=new Map});import{join as MK4}from"path";function uA6(){let q={};for(let K of NZ())for(let _ of XK4){let{settings:z}=le(MK4(K,".claude",_));if(!z?.enabledPlugins)continue;Object.assign(q,z.enabledPlugins)}return q}function PK4(){let q={};for(let K of NZ())for(let _ of XK4){let{settings:z}=le(MK4(K,".claude",_));if(!z?.extraKnownMarketplaces)continue;Object.assign(q,z.extraKnownMarketplaces)}return q}var XK4;var UG8=y(()=>{v8();U1();XK4=["settings.json","settings.local.json"]});function Z4(q){if(q.includes("@")){let K=q.split("@");return{name:K[0]||"",marketplace:K[1]}}return{name:q}}function Ru(q){return q!==void 0&&_I.has(q.toLowerCase())}function hF(q){if(q==="managed")throw Error("Cannot install plugins to managed scope");return wS_[q]}function WK4(q){return yh1[q]}var yh1,wS_;var hP=y(()=>{BZ();yh1={policySettings:"managed",userSettings:"user",projectSettings:"project",localSettings:"local",flagSettings:"flag"};wS_={user:"userSettings",project:"projectSettings",local:"localSettings"}});function Eh1(q,K){if(Z4(q).marketplace)return q;let _=Z4(K).marketplace;if(!_||_===jS_)return q;return`${q}@${_}`}async function DK4(q,K,_,z=new Set){let Y=Z4(q).marketplace,$=[],A=new Set,O=[];async function w(H,J){if(H!==q&&_.has(H))return null;let M=Z4(H).marketplace;if(M!==Y&&!(M&&z.has(M)))return{ok:!1,reason:"cross-marketplace",dependency:H,requiredBy:J};if(O.includes(H))return{ok:!1,reason:"cycle",chain:[...O,H]};if(A.has(H))return null;A.add(H);let X=await K(H);if(!X)return{ok:!1,reason:"not-found",missing:H,requiredBy:J};O.push(H);for(let P of X.dependencies??[]){let W=Eh1(P,H),D=await w(W,H);if(D)return D}return O.pop(),$.push(H),null}let j=await w(q,q);if(j)return j;return{ok:!0,closure:$}}function fK4(q){let K=new Set(q.map((w)=>w.source)),_=new Set(q.filter((w)=>w.enabled).map((w)=>w.source)),z=new Set(q.map((w)=>Z4(w.source).name)),Y=new Map;for(let w of _){let j=Z4(w).name;Y.set(j,(Y.get(j)??0)+1)}let $=[],A=!0;while(A){A=!1;for(let w of q){if(!_.has(w.source))continue;for(let j of w.manifest.dependencies??[]){let H=Eh1(j,w.source),J=!Z4(H).marketplace;if(!(J?(Y.get(H)??0)>0:_.has(H))){_.delete(w.source);let X=Y.get(w.name)??0;if(X<=1)Y.delete(w.name);else Y.set(w.name,X-1);$.push({type:"dependency-unsatisfied",source:w.source,plugin:w.name,dependency:H,reason:(J?z.has(H):K.has(H))?"not-enabled":"not-found"}),A=!0;break}}}}return{demoted:new Set(q.filter((w)=>w.enabled&&!_.has(w.source)).map((w)=>w.source)),errors:$}}function Lh1(q,K){let{name:_}=Z4(q);return K.filter((z)=>z.enabled&&z.source!==q&&(z.manifest.dependencies??[]).some((Y)=>{let $=Eh1(Y,z.source);return Z4($).marketplace?$===q:$===_})).map((z)=>z.name)}function ZK4(q){return new Set(Object.entries(v1(q)?.enabledPlugins??{}).filter(([,K])=>K===!0||Array.isArray(K)).map(([K])=>K))}function GK4(q){if(q.length===0)return"";let K=q.length;return` (+ ${K} ${K===1?"dependency":"dependencies"})`}function Rh1(q){if(!q||q.length===0)return"";return` — warning: required by ${q.join(", ")}`}var jS_="inline";var QG8=y(()=>{U1();hP()});var Dv6,C2="claude-plugins-official";var oi=y(()=>{Dv6={source:"github",repo:"anthropics/claude-plugins-official"}});function JS_(q){let K,_=/^[^@/]+@([^:/]+):/.exec(q);if(_)K=_[1];else try{K=new URL(q).hostname}catch{return"unknown"}let z=K.toLowerCase();return HS_.has(z)?z:"other"}function MS_(q){return q.includes(`anthropics/${C2}`)}function KD(q,K,_,z,Y){d("tengu_plugin_remote_fetch",{source:q,host:K?JS_(K):"unknown",is_official:K?MS_(K):!1,outcome:_,duration_ms:Math.round(z),...Y&&{error_kind:Y}})}function zC(q){let K=String(q?.message??q);if(/ENOTFOUND|ECONNREFUSED|EAI_AGAIN|Could not resolve host|Connection refused/i.test(K))return"dns_or_refused";if(/ETIMEDOUT|timed out|timeout/i.test(K))return"timeout";if(/ECONNRESET|socket hang up|Connection reset by peer|remote end hung up/i.test(K))return"conn_reset";if(/403|401|authentication|permission denied/i.test(K))return"auth";if(/404|not found|repository not found/i.test(K))return"not_found";if(/certificate|SSL|TLS|unable to get local issuer/i.test(K))return"tls";if(/Invalid response format|Invalid marketplace schema/i.test(K))return"invalid_schema";return"other"}var HS_;var kn6=y(()=>{k8();oi();HS_=new Set(["github.com","raw.githubusercontent.com","objects.githubusercontent.com","gist.githubusercontent.com","gitlab.com","bitbucket.org","codeberg.org","dev.azure.com","ssh.dev.azure.com","storage.googleapis.com"])});async function XS_(q){try{return!!await TO(q)}catch{return!1}}function TK4(){mA6.cache?.set?.(void 0,Promise.resolve(!1))}var mA6;var dG8=y(()=>{F4();rk();mA6=_1(async()=>{return XS_("git")})});function O7(q,K){if(!process.env.SRT_DEBUG)return;let _=K?.level||"info",z="[SandboxDebug]";switch(_){case"error":console.error(`${z} ${q}`);break;case"warn":console.warn(`${z} ${q}`);break;default:console.error(`${z} ${q}`)}}import{Agent as PS_,createServer as WS_}from"node:http";import{request as vK4}from"node:http";import{request as DS_}from"node:https";import{connect as kK4}from"node:net";import{URL as fS_}from"node:url";function VK4(q){let K=WS_();return K.on("connect",async(_,z)=>{z.on("error",(Y)=>{O7(`Client socket error: ${Y.message}`,{level:"error"})});try{let[Y,$]=_.url.split(":"),A=$===void 0?void 0:parseInt($,10);if(!Y||!A){O7(`Invalid CONNECT request: ${_.url}`,{level:"error"}),z.end(`HTTP/1.1 400 Bad Request\r |
| 755 | \r |
| 756 | `);return}if(!await q.filter(A,Y,z)){O7(`Connection blocked to ${Y}:${A}`,{level:"error"}),z.end(`HTTP/1.1 403 Forbidden\r |
| 757 | Content-Type: text/plain\r |
| 758 | X-Proxy-Error: blocked-by-allowlist\r |
| 759 | \r |
| 760 | Connection blocked by network allowlist`);return}let w=q.getMitmSocketPath?.(Y);if(w){O7(`Routing CONNECT ${Y}:${A} through MITM proxy at ${w}`);let j=kK4({path:w},()=>{j.write(`CONNECT ${Y}:${A} HTTP/1.1\r |
| 761 | Host: ${Y}:${A}\r |
| 762 | \r |
| 763 | `)}),H="",J=(M)=>{H+=M.toString();let X=H.indexOf(`\r |
| 764 | \r |
| 765 | `);if(X!==-1){j.removeListener("data",J);let P=H.substring(0,H.indexOf(`\r |
| 766 | `));if(P.includes(" 200 ")){z.write(`HTTP/1.1 200 Connection Established\r |
| 767 | \r |
| 768 | `);let W=H.substring(X+4);if(W.length>0)z.write(W);j.pipe(z),z.pipe(j)}else O7(`MITM proxy rejected CONNECT: ${P}`,{level:"error"}),z.end(`HTTP/1.1 502 Bad Gateway\r |
| 769 | \r |
| 770 | `),j.destroy()}};j.on("data",J),j.on("error",(M)=>{O7(`MITM proxy connection failed: ${M.message}`,{level:"error"}),z.end(`HTTP/1.1 502 Bad Gateway\r |
| 771 | \r |
| 772 | `)}),z.on("error",(M)=>{O7(`Client socket error: ${M.message}`,{level:"error"}),j.destroy()}),z.on("end",()=>j.end()),j.on("end",()=>z.end())}else{let j=kK4(A,Y,()=>{z.write(`HTTP/1.1 200 Connection Established\r |
| 773 | \r |
| 774 | `),j.pipe(z),z.pipe(j)});j.on("error",(H)=>{O7(`CONNECT tunnel failed: ${H.message}`,{level:"error"}),z.end(`HTTP/1.1 502 Bad Gateway\r |
| 775 | \r |
| 776 | `)}),z.on("error",(H)=>{O7(`Client socket error: ${H.message}`,{level:"error"}),j.destroy()}),z.on("end",()=>j.end()),j.on("end",()=>z.end())}}catch(Y){O7(`Error handling CONNECT: ${Y}`,{level:"error"}),z.end(`HTTP/1.1 500 Internal Server Error\r |
| 777 | \r |
| 778 | `)}}),K.on("request",async(_,z)=>{try{let Y=new fS_(_.url),$=Y.hostname,A=Y.port?parseInt(Y.port,10):Y.protocol==="https:"?443:80;if(!await q.filter(A,$,_.socket)){O7(`HTTP request blocked to ${$}:${A}`,{level:"error"}),z.writeHead(403,{"Content-Type":"text/plain","X-Proxy-Error":"blocked-by-allowlist"}),z.end("Connection blocked by network allowlist");return}let w=q.getMitmSocketPath?.($);if(w){O7(`Routing HTTP ${_.method} ${$}:${A} through MITM proxy at ${w}`);let j=new PS_({socketPath:w}),H=vK4({agent:j,path:_.url,method:_.method,headers:{..._.headers,host:Y.host}},(J)=>{z.writeHead(J.statusCode,J.headers),J.pipe(z)});H.on("error",(J)=>{if(O7(`MITM proxy request failed: ${J.message}`,{level:"error"}),!z.headersSent)z.writeHead(502,{"Content-Type":"text/plain"}),z.end("Bad Gateway")}),_.pipe(H)}else{let H=(Y.protocol==="https:"?DS_:vK4)({hostname:$,port:A,path:Y.pathname+Y.search,method:_.method,headers:{..._.headers,host:Y.host}},(J)=>{z.writeHead(J.statusCode,J.headers),J.pipe(z)});H.on("error",(J)=>{if(O7(`Proxy request failed: ${J.message}`,{level:"error"}),!z.headersSent)z.writeHead(502,{"Content-Type":"text/plain"}),z.end("Bad Gateway")}),_.pipe(H)}}catch(Y){O7(`Error handling HTTP request: ${Y}`,{level:"error"}),z.writeHead(500,{"Content-Type":"text/plain"}),z.end("Internal Server Error")}}),K}var NK4=()=>{};var CK4=m((MgA,SK4)=>{var{create:ZS_,defineProperty:cG8,getOwnPropertyDescriptor:GS_,getOwnPropertyNames:TS_,getPrototypeOf:vS_}=Object,kS_=Object.prototype.hasOwnProperty,VS_=(q,K)=>{for(var _ in K)cG8(q,_,{get:K[_],enumerable:!0})},yK4=(q,K,_,z)=>{if(K&&typeof K==="object"||typeof K==="function"){for(let Y of TS_(K))if(!kS_.call(q,Y)&&Y!==_)cG8(q,Y,{get:()=>K[Y],enumerable:!(z=GS_(K,Y))||z.enumerable})}return q},EK4=(q,K,_)=>(_=q!=null?ZS_(vS_(q)):{},yK4(K||!q||!q.__esModule?cG8(_,"default",{value:q,enumerable:!0}):_,q)),NS_=(q)=>yK4(cG8({},"__esModule",{value:!0}),q),LK4={};VS_(LK4,{Socks5Server:()=>hK4,createServer:()=>RS_,defaultConnectionHandler:()=>Sh1});SK4.exports=NS_(LK4);var yS_=EK4(U6("net")),RK4=((q)=>{return q[q.connect=1]="connect",q[q.bind=2]="bind",q[q.udp=3]="udp",q})(RK4||{}),hh1=((q)=>{return q[q.REQUEST_GRANTED=0]="REQUEST_GRANTED",q[q.GENERAL_FAILURE=1]="GENERAL_FAILURE",q[q.CONNECTION_NOT_ALLOWED=2]="CONNECTION_NOT_ALLOWED",q[q.NETWORK_UNREACHABLE=3]="NETWORK_UNREACHABLE",q[q.HOST_UNREACHABLE=4]="HOST_UNREACHABLE",q[q.CONNECTION_REFUSED=5]="CONNECTION_REFUSED",q[q.TTL_EXPIRED=6]="TTL_EXPIRED",q[q.COMMAND_NOT_SUPPORTED=7]="COMMAND_NOT_SUPPORTED",q[q.ADDRESS_TYPE_NOT_SUPPORTED=8]="ADDRESS_TYPE_NOT_SUPPORTED",q})(hh1||{}),ES_=class{constructor(q,K){this.errorHandler=()=>{},this.metadata={},this.socket=K,this.server=q,K.on("error",this.errorHandler),K.pause(),this.handleGreeting()}readBytes(q){return new Promise((K)=>{let _=Buffer.allocUnsafe(q),z=0,Y=($)=>{let A=Math.min($.length,q-z);if($.copy(_,z,0,A),z+=A,z<q)return;this.socket.removeListener("data",Y),this.socket.push($.subarray(A)),K(_),this.socket.pause()};this.socket.on("data",Y),this.socket.resume()})}async handleGreeting(){if((await this.readBytes(1)).readUInt8()!==5)return this.socket.destroy();let K=(await this.readBytes(1)).readUInt8();if(K>128||K===0)return this.socket.destroy();let _=await this.readBytes(K),z=this.server.authHandler?2:0;if(!_.includes(z))return this.socket.write(Buffer.from([5,255])),this.socket.destroy();if(this.socket.write(Buffer.from([5,z])),this.server.authHandler)this.handleUserPassword();else this.handleConnectionRequest()}async handleUserPassword(){await this.readBytes(1);let q=(await this.readBytes(1)).readUint8(),K=(await this.readBytes(q)).toString(),_=(await this.readBytes(1)).readUint8(),z=(await this.readBytes(_)).toString();this.username=K,this.password=z;let Y=!1,$=()=>{if(Y)return;Y=!0,this.socket.write(Buffer.from([1,0])),this.handleConnectionRequest()},A=()=>{if(Y)return;Y=!0,this.socket.write(Buffer.from([1,1])),this.socket.destroy()},O=await this.server.authHandler(this,$,A);if(O===!0)$();else if(O===!1)A()}async handleConnectionRequest(){await this.readBytes(1);let q=(await this.readBytes(1))[0],K=RK4[q];if(!K)return this.socket.destroy();this.command=K,await this.readBytes(1);let _=(await this.readBytes(1)).readUInt8(),z="";switch(_){case 1:z=(await this.readBytes(4)).join(".");break;case 3:let j=(await this.readBytes(1)).readUInt8();z=(await this.readBytes(j)).toString();break;case 4:let H=await this.readBytes(16);for(let J=0;J<16;J++){if(J%2===0&&J>0)z+=":";z+=`${H[J]<16?"0":""}${H[J].toString(16)}`}break;default:this.socket.destroy();return}let Y=(await this.readBytes(2)).readUInt16BE();if(!this.server.supportedCommands.has(K))return this.socket.write(Buffer.from([5,7])),this.socket.destroy();this.destAddress=z,this.destPort=Y;let $=!1,A=()=>{if($)return;$=!0,this.connect()};if(!this.server.rulesetValidator)return A();let O=()=>{if($)return;$=!0,this.socket.write(Buffer.from([5,2,0,1,0,0,0,0,0,0])),this.socket.destroy()},w=await this.server.rulesetValidator(this,A,O);if(w===!0)A();else if(w===!1)O()}connect(){this.socket.removeListener("error",this.errorHandler),this.server.connectionHandler(this,(q)=>{if(hh1[q]===void 0)throw Error(`"${q}" is not a valid status.`);if(this.socket.write(Buffer.from([5,hh1[q],0,1,0,0,0,0,0,0])),q!=="REQUEST_GRANTED")this.socket.destroy()}),this.socket.resume()}},LS_=EK4(U6("net"));function Sh1(q,K){if(q.command!=="connect")return K("COMMAND_NOT_SUPPORTED");q.socket.on("error",()=>{});let _=LS_.default.createConnection({host:q.destAddress,port:q.destPort});_.setNoDelay();let z=!1;return _.on("error",(Y)=>{if(!z)switch(Y.code){case"EINVAL":case"ENOENT":case"ENOTFOUND":case"ETIMEDOUT":case"EADDRNOTAVAIL":case"EHOSTUNREACH":K("HOST_UNREACHABLE");break;case"ENETUNREACH":K("NETWORK_UNREACHABLE");break;case"ECONNREFUSED":K("CONNECTION_REFUSED");break;default:K("GENERAL_FAILURE")}}),_.on("ready",()=>{z=!0,K("REQUEST_GRANTED"),q.socket.pipe(_).pipe(q.socket)}),q.socket.on("close",()=>_.destroy()),_}var hK4=class{constructor(){this.supportedCommands=new Set(["connect"]),this.connectionHandler=Sh1,this.server=yS_.default.createServer((q)=>{q.setNoDelay(),this._handleConnection(q)})}listen(...q){return this.server.listen(...q),this}close(q){return this.server.close(q),this}setAuthHandler(q){return this.authHandler=q,this}disableAuthHandler(){return this.authHandler=void 0,this}setRulesetValidator(q){return this.rulesetValidator=q,this}disableRulesetValidator(){return this.rulesetValidator=void 0,this}setConnectionHandler(q){return this.connectionHandler=q,this}useDefaultConnectionHandler(){return this.connectionHandler=Sh1,this}_handleConnection(q){return new ES_(this,q),this}};function RS_(q){let K=new hK4;if(q?.auth)K.setAuthHandler((_)=>{return _.username===q.auth.username&&_.password===q.auth.password});if(q?.port)K.listen(q.port,q.hostname);return K}});function xK4(q){let K=bK4.createServer();return K.setRulesetValidator(async(_)=>{try{let{destAddress:z,destPort:Y}=_;if(O7(`Connection request to ${z}:${Y}`),!await q.filter(Y,z))return O7(`Connection blocked to ${z}:${Y}`,{level:"error"}),!1;return O7(`Connection allowed to ${z}:${Y}`),!0}catch(z){return O7(`Error validating connection: ${z}`,{level:"error"}),!1}}),{server:K,getPort(){try{let _=K?.server;if(_&&typeof _?.address==="function"){let z=_.address();if(z&&typeof z==="object"&&"port"in z)return z.port}}catch(_){O7(`Error getting port: ${_}`,{level:"error"})}return},listen(_,z){return new Promise((Y,$)=>{let A=()=>{let O=this.getPort();if(O)O7(`SOCKS proxy listening on ${z}:${O}`),Y(O);else $(Error("Failed to get SOCKS proxy server port"))};K.listen(_,z,A)})},async close(){return new Promise((_,z)=>{K.close((Y)=>{if(Y){let $=Y.message?.toLowerCase()||"";if(!($.includes("not running")||$.includes("already closed")||$.includes("not listening"))){z(Y);return}}_()})})},unref(){try{let _=K?.server;if(_&&typeof _?.unref==="function")_.unref()}catch(_){O7(`Error calling unref: ${_}`,{level:"error"})}}}}var bK4;var IK4=y(()=>{bK4=O6(CK4(),1)});import{spawnSync as hS_}from"node:child_process";function ai(q){if(typeof globalThis.Bun<"u")return globalThis.Bun.which(q);let K=hS_("which",[q],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1000});if(K.status===0&&K.stdout)return K.stdout.trim();return null}var Vn6=()=>{};import*as uK4 from"fs";function Ch1(){if(process.platform!=="linux")return;try{let q=uK4.readFileSync("/proc/version",{encoding:"utf8"}),K=q.match(/WSL(\d+)/i);if(K&&K[1])return K[1];if(q.toLowerCase().includes("microsoft"))return"1";return}catch{return}}function ZG(){switch(process.platform){case"darwin":return"macos";case"linux":return"linux";case"win32":return"windows";default:return"unknown"}}var lG8=()=>{};var pK4=m((TgA,mK4)=>{mK4.exports=function(K){return K.map(function(_){if(_==="")return"''";if(_&&typeof _==="object")return _.op.replace(/(.)/g,"\\$1");if(/["\s\\]/.test(_)&&!/'/.test(_))return"'"+_.replace(/(['])/g,"\\$1")+"'";if(/["'\s]/.test(_))return'"'+_.replace(/(["\\$`!])/g,"\\$1")+'"';return String(_).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")}});var cK4=m((vgA,dK4)=>{var QK4="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",BK4=new RegExp("^"+QK4+"$"),gK4="|&;()<> \\t",SS_='"((\\\\"|[^"])*?)"',CS_="'((\\\\'|[^'])*?)'",bS_=/^#$/,FK4="'",UK4='"',bh1="$",pA6="",xS_=4294967296;for(nG8=0;nG8<4;nG8++)pA6+=(xS_*Math.random()).toString(16);var nG8,IS_=new RegExp("^"+pA6);function uS_(q,K){var _=K.lastIndex,z=[],Y;while(Y=K.exec(q))if(z.push(Y),K.lastIndex===Y.index)K.lastIndex+=1;return K.lastIndex=_,z}function mS_(q,K,_){var z=typeof q==="function"?q(_):q[_];if(typeof z>"u"&&_!="")z="";else if(typeof z>"u")z="$";if(typeof z==="object")return K+pA6+JSON.stringify(z)+pA6;return K+z}function pS_(q,K,_){if(!_)_={};var z=_.escape||"\\",Y="(\\"+z+`['"`+gK4+`]|[^\\s'"`+gK4+"])+",$=new RegExp(["("+QK4+")","("+Y+"|"+SS_+"|"+CS_+")+"].join("|"),"g"),A=uS_(q,$);if(A.length===0)return[];if(!K)K={};var O=!1;return A.map(function(w){var j=w[0];if(!j||O)return;if(BK4.test(j))return{op:j};var H=!1,J=!1,M="",X=!1,P;function W(){P+=1;var G,Z,T=j.charAt(P);if(T==="{"){if(P+=1,j.charAt(P)==="}")throw Error("Bad substitution: "+j.slice(P-2,P+1));if(G=j.indexOf("}",P),G<0)throw Error("Bad substitution: "+j.slice(P));Z=j.slice(P,G),P=G}else if(/[*@#?$!_-]/.test(T))Z=T,P+=1;else{var v=j.slice(P);if(G=v.match(/[^\w\d_]/),!G)Z=v,P=j.length;else Z=v.slice(0,G.index),P+=G.index-1}return mS_(K,"",Z)}for(P=0;P<j.length;P++){var D=j.charAt(P);if(X=X||!H&&(D==="*"||D==="?"),J)M+=D,J=!1;else if(H)if(D===H)H=!1;else if(H==FK4)M+=D;else if(D===z)if(P+=1,D=j.charAt(P),D===UK4||D===z||D===bh1)M+=D;else M+=z+D;else if(D===bh1)M+=W();else M+=D;else if(D===UK4||D===FK4)H=D;else if(BK4.test(D))return{op:j};else if(bS_.test(D)){O=!0;var f={comment:q.slice(w.index+P+1)};if(M.length)return[M,f];return[f]}else if(D===z)J=!0;else if(D===bh1)M+=W();else M+=D}if(X)return{op:"glob",pattern:M};return M}).reduce(function(w,j){return typeof j>"u"?w:w.concat(j)},[])}dK4.exports=function(K,_,z){var Y=pS_(K,_,z);if(typeof _!=="function")return Y;return Y.reduce(function($,A){if(typeof A==="object")return $.concat(A);var O=A.split(RegExp("("+pA6+".*?"+pA6+")","g"));if(O.length===1)return $.concat(O[0]);return $.concat(O.filter(Boolean).map(function(w){if(IS_.test(w))return JSON.parse(w.split(pA6)[1]);return w}))},[])}});var iG8=m((BS_)=>{BS_.quote=pK4();BS_.parse=cK4()});import{spawn as US_}from"child_process";import{text as lK4}from"node:stream/consumers";async function nK4(q,K,_,z={command:"rg"}){let{command:Y,args:$=[],argv0:A}=z,O=US_(Y,[...$,...q,K],{argv0:A,signal:_,timeout:1e4,windowsHide:!0}),[w,j,H]=await Promise.all([lK4(O.stdout),lK4(O.stderr),new Promise((J,M)=>{O.on("close",J),O.on("error",M)})]);if(H===0)return w.trim().split(` |
| 779 | `).filter(Boolean);if(H===1)return[];throw Error(`ripgrep failed with exit code ${H}: ${j}`)}var iK4=y(()=>{Vn6()});import{homedir as xh1}from"os";import*as Lv from"path";import*as BA6 from"fs";function oG8(){return[...QS_.filter((q)=>q!==".git"),".claude/commands",".claude/agents"]}function Ih1(q){return q.toLowerCase()}function GG(q){return q.includes("*")||q.includes("?")||q.includes("[")||q.includes("]")}function si(q){return q.replace(/\/\*\*$/,"")||"/"}function rG8(q,K){let _=Lv.normalize(q),z=Lv.normalize(K);if(z===_)return!1;if(_.startsWith("/tmp/")&&z==="/private"+_)return!1;if(_.startsWith("/var/")&&z==="/private"+_)return!1;if(_.startsWith("/private/tmp/")&&z===_)return!1;if(_.startsWith("/private/var/")&&z===_)return!1;if(z==="/")return!0;if(z.split("/").filter(Boolean).length<=1)return!0;if(_.startsWith(z+"/"))return!0;let $=_;if(_.startsWith("/tmp/"))$="/private"+_;else if(_.startsWith("/var/"))$="/private"+_;if($!==_&&$.startsWith(z+"/"))return!0;let A=z.startsWith(_+"/"),O=$!==_&&z.startsWith($+"/");if(z!==_&&!($!==_&&z===$)&&!A&&!O)return!0;return!1}function oV(q){let K=process.cwd(),_=q;if(q==="~")_=xh1();else if(q.startsWith("~/"))_=xh1()+q.slice(1);else if(q.startsWith("./")||q.startsWith("../"))_=Lv.resolve(K,q);else if(!Lv.isAbsolute(q))_=Lv.resolve(K,q);if(GG(_)){let z=_.split(/[*?[\]]/)[0];if(z&&z!=="/"){let Y=z.endsWith("/")?z.slice(0,-1):Lv.dirname(z);try{let $=BA6.realpathSync(Y);if(!rG8(Y,$)){let A=_.slice(Y.length);return $+A}}catch{}}return _}try{let z=BA6.realpathSync(_);if(rG8(_,z));else _=z}catch{}return _}function yn6(){let q=xh1();return["/dev/stdout","/dev/stderr","/dev/null","/dev/tty","/dev/dtracehelper","/dev/autofs_nowait","/tmp/claude","/private/tmp/claude",Lv.join(q,".npm/_logs"),Lv.join(q,".claude/debug")]}function aG8(q,K){let z=["SANDBOX_RUNTIME=1",`TMPDIR=${process.env.CLAUDE_TMPDIR||"/tmp/claude"}`];if(!q&&!K)return z;let Y=["localhost","127.0.0.1","::1","*.local",".local","169.254.0.0/16","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16"].join(",");if(z.push(`NO_PROXY=${Y}`),z.push(`no_proxy=${Y}`),q)z.push(`HTTP_PROXY=http://localhost:${q}`),z.push(`HTTPS_PROXY=http://localhost:${q}`),z.push(`http_proxy=http://localhost:${q}`),z.push(`https_proxy=http://localhost:${q}`);if(K){z.push(`ALL_PROXY=socks5h://localhost:${K}`),z.push(`all_proxy=socks5h://localhost:${K}`);let $=ZG();if($==="macos")z.push(`GIT_SSH_COMMAND=ssh -o ProxyCommand='nc -X 5 -x localhost:${K} %h %p'`);else if($==="linux"&&q)z.push(`GIT_SSH_COMMAND=ssh -o ProxyCommand='socat - PROXY:localhost:%h:%p,proxyport=${q}'`);if(z.push(`FTP_PROXY=socks5h://localhost:${K}`),z.push(`ftp_proxy=socks5h://localhost:${K}`),z.push(`RSYNC_PROXY=localhost:${K}`),z.push(`DOCKER_HTTP_PROXY=http://localhost:${q||K}`),z.push(`DOCKER_HTTPS_PROXY=http://localhost:${q||K}`),q)z.push("CLOUDSDK_PROXY_TYPE=https"),z.push("CLOUDSDK_PROXY_ADDRESS=localhost"),z.push(`CLOUDSDK_PROXY_PORT=${q}`);z.push(`GRPC_PROXY=socks5h://localhost:${K}`),z.push(`grpc_proxy=socks5h://localhost:${K}`)}return z}function sG8(q){let K=q.slice(0,100);return Buffer.from(K).toString("base64")}function rK4(q){return Buffer.from(q,"base64").toString("utf8")}function gA6(q){return"^"+q.replace(/[.^$+{}()|\\]/g,"\\$&").replace(/\[([^\]]*?)$/g,"\\[$1").replace(/\*\*\//g,"__GLOBSTAR_SLASH__").replace(/\*\*/g,"__GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/\?/g,"[^/]").replace(/__GLOBSTAR_SLASH__/g,"(.*/)?").replace(/__GLOBSTAR__/g,".*")+"$"}function En6(q){let K=oV(q),_=K.split(/[*?[\]]/)[0];if(!_||_==="/")return O7(`[Sandbox] Glob pattern too broad, skipping: ${q}`),[];let z=_.endsWith("/")?_.slice(0,-1):Lv.dirname(_);if(!BA6.existsSync(z))return O7(`[Sandbox] Base directory for glob does not exist: ${z}`),[];let Y=new RegExp(gA6(K)),$=[];try{let A=BA6.readdirSync(z,{recursive:!0,withFileTypes:!0});for(let O of A){let w=O.parentPath??O.path??z,j=Lv.join(w,O.name);if(Y.test(j))$.push(j)}}catch(A){O7(`[Sandbox] Error expanding glob pattern ${q}: ${A}`)}return $}var Nn6,QS_;var fv6=y(()=>{lG8();Nn6=[".gitconfig",".gitmodules",".bashrc",".bash_profile",".zshrc",".zprofile",".profile",".ripgreprc",".mcp.json"],QS_=[".git",".vscode",".idea"]});import{join as YC,dirname as dS_}from"node:path";import{fileURLToPath as cS_}from"node:url";import*as FA6 from"node:fs";import{execSync as lS_}from"node:child_process";import{homedir as nS_}from"node:os";function oK4(){if(ph1)return ph1;let q=[];try{let _=lS_("npm root -g",{encoding:"utf8",timeout:5000,stdio:["pipe","pipe","ignore"]}).trim();if(_)q.push(YC(_,"@anthropic-ai","sandbox-runtime"))}catch{}let K=nS_();return q.push(YC("/usr","lib","node_modules","@anthropic-ai","sandbox-runtime"),YC("/usr","local","lib","node_modules","@anthropic-ai","sandbox-runtime"),YC("/opt","homebrew","lib","node_modules","@anthropic-ai","sandbox-runtime"),YC(K,".npm","lib","node_modules","@anthropic-ai","sandbox-runtime"),YC(K,".npm-global","lib","node_modules","@anthropic-ai","sandbox-runtime")),ph1=q,q}function Bh1(){let q=process.arch;switch(q){case"x64":case"x86_64":return"x64";case"arm64":case"aarch64":return"arm64";case"ia32":case"x86":return O7("[SeccompFilter] 32-bit x86 (ia32) is not currently supported due to missing socketcall() syscall blocking. The current seccomp filter only blocks socket(AF_UNIX, ...), but on 32-bit x86, socketcall() can be used to bypass this.",{level:"error"}),null;default:return O7(`[SeccompFilter] Unsupported architecture: ${q}. Only x64 and arm64 are supported.`),null}}function aK4(q){let K=Bh1();if(!K)return[];let _=dS_(cS_(import.meta.url)),z=YC("vendor","seccomp",K,q);return[YC(_,z),YC(_,"..","..",z),YC(_,"..",z)]}function gh1(q){let K=q??"";if(uh1.has(K))return uh1.get(K);let _=iS_(q);return uh1.set(K,_),_}function iS_(q){if(q){if(FA6.existsSync(q))return O7(`[SeccompFilter] Using BPF filter from explicit path: ${q}`),q;O7(`[SeccompFilter] Explicit path provided but file not found: ${q}`)}let K=Bh1();if(!K)return O7(`[SeccompFilter] Cannot find pre-generated BPF filter: unsupported architecture ${process.arch}`),null;O7(`[SeccompFilter] Detected architecture: ${K}`);for(let _ of aK4("unix-block.bpf"))if(FA6.existsSync(_))return O7(`[SeccompFilter] Found pre-generated BPF filter: ${_} (${K})`),_;for(let _ of oK4()){let z=YC(_,"vendor","seccomp",K,"unix-block.bpf");if(FA6.existsSync(z))return O7(`[SeccompFilter] Found pre-generated BPF filter in global install: ${z} (${K})`),z}return O7(`[SeccompFilter] Pre-generated BPF filter not found in any expected location (${K})`),null}function Ln6(q){let K=q??"";if(mh1.has(K))return mh1.get(K);let _=rS_(q);return mh1.set(K,_),_}function rS_(q){if(q){if(FA6.existsSync(q))return O7(`[SeccompFilter] Using apply-seccomp binary from explicit path: ${q}`),q;O7(`[SeccompFilter] Explicit path provided but file not found: ${q}`)}let K=Bh1();if(!K)return O7(`[SeccompFilter] Cannot find apply-seccomp binary: unsupported architecture ${process.arch}`),null;O7(`[SeccompFilter] Looking for apply-seccomp binary for architecture: ${K}`);for(let _ of aK4("apply-seccomp"))if(FA6.existsSync(_))return O7(`[SeccompFilter] Found apply-seccomp binary: ${_} (${K})`),_;for(let _ of oK4()){let z=YC(_,"vendor","seccomp",K,"apply-seccomp");if(FA6.existsSync(z))return O7(`[SeccompFilter] Found apply-seccomp binary in global install: ${z} (${K})`),z}return O7(`[SeccompFilter] apply-seccomp binary not found in any expected location (${K})`),null}function sK4(q){let K=gh1(q);if(K)return O7("[SeccompFilter] Using pre-generated BPF filter"),K;return O7("[SeccompFilter] Pre-generated BPF filter not available for this architecture. Only x64 and arm64 are supported.",{level:"error"}),null}function Fh1(q){}var uh1,mh1,ph1=null;var tK4=y(()=>{uh1=new Map,mh1=new Map});import{randomBytes as oS_}from"node:crypto";import*as KO from"fs";import{spawn as eK4}from"node:child_process";import{tmpdir as Uh1}from"node:os";import ZX,{join as q54}from"node:path";function aS_(q,K){let _=q.split(ZX.sep),z="";for(let Y of _){if(!Y)continue;let $=z+ZX.sep+Y;try{if(KO.lstatSync($).isSymbolicLink()){if(K.some((w)=>$.startsWith(w+"/")||$===w))return $}}catch{break}z=$}return null}function sS_(q){let K=q.split(ZX.sep),_="";for(let z of K){if(!z)continue;let Y=_+ZX.sep+z;try{let $=KO.statSync(Y);if($.isFile()||$.isSymbolicLink())return!0}catch{break}_=Y}return!1}function tS_(q){let K=q.split(ZX.sep),_="";for(let z of K){if(!z)continue;let Y=_+ZX.sep+z;if(!KO.existsSync(Y))return Y;_=Y}return q}async function eS_(q={command:"rg"},K=ch1,_=!1,z){let Y=process.cwd(),$=new AbortController,A=z??$.signal,O=oG8(),w=[...Nn6.map((X)=>ZX.resolve(Y,X)),...O.map((X)=>ZX.resolve(Y,X))],j=ZX.resolve(Y,".git"),H=!1;try{H=KO.statSync(j).isDirectory()}catch{}if(H){if(w.push(ZX.resolve(Y,".git/hooks")),!_)w.push(ZX.resolve(Y,".git/config"))}let J=[];for(let X of Nn6)J.push("--iglob",X);for(let X of O)J.push("--iglob",`**/${X}/**`);if(J.push("--iglob","**/.git/hooks/**"),!_)J.push("--iglob","**/.git/config");let M=[];try{M=await nK4(["--files","--hidden","--max-depth",String(K),...J,"-g","!**/node_modules/**"],Y,A,q)}catch(X){O7(`[Sandbox] ripgrep scan failed: ${X}`)}for(let X of M){let P=ZX.resolve(Y,X),W=!1;for(let D of[...O,".git"]){let f=Ih1(D),G=P.split(ZX.sep),Z=G.findIndex((T)=>Ih1(T)===f);if(Z!==-1){if(D===".git"){let T=G.slice(0,Z+1).join(ZX.sep);if(X.includes(".git/hooks"))w.push(ZX.join(T,"hooks"));else if(X.includes(".git/config"))w.push(ZX.join(T,"config"))}else w.push(G.slice(0,Z+1).join(ZX.sep));W=!0;break}}if(!W)w.push(P)}return[...new Set(w)]}function dh1(){if(K54)return;process.on("exit",()=>{for(let q of Qh1)try{Fh1(q)}catch{}lh1()}),K54=!0}function lh1(){for(let q of tG8)try{let K=KO.statSync(q);if(K.isFile()&&K.size===0)KO.unlinkSync(q),O7(`[Sandbox Linux] Cleaned up bwrap mount point (file): ${q}`);else if(K.isDirectory()){if(KO.readdirSync(q).length===0)KO.rmdirSync(q),O7(`[Sandbox Linux] Cleaned up bwrap mount point (dir): ${q}`)}}catch{}tG8.clear()}function _54(q){let K=[],_=[];if(ai("bwrap")===null)K.push("bubblewrap (bwrap) not installed");if(ai("socat")===null)K.push("socat not installed");let z=gh1(q?.bpfPath)!==null,Y=Ln6(q?.applyPath)!==null;if(!z||!Y)_.push("seccomp not available - unix socket access not restricted");return{warnings:_,errors:K}}async function z54(q,K){let _=oS_(8).toString("hex"),z=q54(Uh1(),`claude-http-${_}.sock`),Y=q54(Uh1(),`claude-socks-${_}.sock`),$=[`UNIX-LISTEN:${z},fork,reuseaddr`,`TCP:localhost:${q},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];O7(`Starting HTTP bridge: socat ${$.join(" ")}`);let A=eK4("socat",$,{stdio:"ignore"});if(!A.pid)throw Error("Failed to start HTTP bridge process");A.on("error",(H)=>{O7(`HTTP bridge process error: ${H}`,{level:"error"})}),A.on("exit",(H,J)=>{O7(`HTTP bridge process exited with code ${H}, signal ${J}`,{level:H===0?"info":"error"})});let O=[`UNIX-LISTEN:${Y},fork,reuseaddr`,`TCP:localhost:${K},keepalive,keepidle=10,keepintvl=5,keepcnt=3`];O7(`Starting SOCKS bridge: socat ${O.join(" ")}`);let w=eK4("socat",O,{stdio:"ignore"});if(!w.pid){if(A.pid)try{process.kill(A.pid,"SIGTERM")}catch{}throw Error("Failed to start SOCKS bridge process")}w.on("error",(H)=>{O7(`SOCKS bridge process error: ${H}`,{level:"error"})}),w.on("exit",(H,J)=>{O7(`SOCKS bridge process exited with code ${H}, signal ${J}`,{level:H===0?"info":"error"})});let j=5;for(let H=0;H<j;H++){if(!A.pid||A.killed||!w.pid||w.killed)throw Error("Linux bridge process died unexpectedly");try{if(KO.existsSync(z)&&KO.existsSync(Y)){O7(`Linux bridges ready after ${H+1} attempts`);break}}catch(J){O7(`Error checking sockets (attempt ${H+1}): ${J}`,{level:"error"})}if(H===j-1){if(A.pid)try{process.kill(A.pid,"SIGTERM")}catch{}if(w.pid)try{process.kill(w.pid,"SIGTERM")}catch{}throw Error(`Failed to create bridge sockets after ${j} attempts`)}await new Promise((J)=>setTimeout(J,H*100))}return{httpSocketPath:z,socksSocketPath:Y,httpBridgeProcess:A,socksBridgeProcess:w,httpProxyPort:q,socksProxyPort:K}}function qC_(q,K,_,z,Y,$){let A=Y||"bash",O=[`socat TCP-LISTEN:3128,fork,reuseaddr UNIX-CONNECT:${q} >/dev/null 2>&1 &`,`socat TCP-LISTEN:1080,fork,reuseaddr UNIX-CONNECT:${K} >/dev/null 2>&1 &`,'trap "kill %1 %2 2>/dev/null; exit" EXIT'];if(z){let w=Ln6($);if(!w)throw Error("apply-seccomp binary not found. This should have been caught earlier. Ensure vendor/seccomp/{x64,arm64}/apply-seccomp binaries are included in the package.");let j=UA6.default.quote([w,z,A,"-c",_]),H=[...O,j].join(` |
| 780 | `);return`${A} -c ${UA6.default.quote([H])}`}else{let w=[...O,`eval ${UA6.default.quote([_])}`].join(` |