| 7928 | `);let Q6=await new Promise((_6)=>{b6.question("Choose [1/2] (default: 1): ",_6)});b6.close();let Y6=Q6.trim()==="2"?"worktree":"same-dir";i=Y6,d("tengu_bridge_spawn_mode_chosen",{spawn_mode:Y6}),g((_6)=>{if(_6.remoteControlSpawnMode===Y6)return _6;return{..._6,remoteControlSpawnMode:Y6}})}let $6,M6;if(X)M6="single-session",$6="resume";else if(w!==void 0)M6=w,$6="flag";else if(i!==void 0)M6=i,$6="saved";else M6=T?"same-dir":"single-session",$6="gate_default";let j6=M6==="single-session"?1:j??xFK,G6=H??!0;if(!X){let{clearBridgePointer:x6}=await Promise.resolve().then(() => (rq8(),iq8));await x6(D)}if(M6==="worktree"&&!e)console.error("Error: Worktree mode requires a git repository or WorktreeCreate hooks configured. Use --spawn=session for single-session mode."),process.exit(1);let w6=await c(),o=await K6(),s=bFK(),a=nQ8(),{handleOAuth401Error:n}=await Promise.resolve().then(() => (G7(),_L)),l=Tq8({baseUrl:F,getAccessToken:R,runnerVersion:{ISSUES_EXPLAINER:"report the issue at https://github.com/anthropics/claude-code/issues",PACKAGE_URL:"@anthropic-ai/claude-code",README_URL:"https://code.claude.com/docs/en/overview",VERSION:"2.1.88",FEEDBACK_CHANNEL:"https://github.com/anthropics/claude-code/issues",BUILD_TIME:"2026-03-30T21:59:52Z"}.VERSION,onDebug:N,onAuth401:n,getTrustedDeviceToken:q46}),A6,J6={dir:D,machineName:s,branch:w6,gitRepoUrl:o,maxSessions:j6,spawnMode:M6,verbose:_,sandbox:z,bridgeId:a,workerType:"claude_code",environmentId:nQ8(),reuseEnvironmentId:A6,apiBaseUrl:F,sessionIngressUrl:U,debugFile:Y,sessionTimeoutMs:$};N(`[bridge:init] bridgeId=${a}${A6?` reuseEnvironmentId=${A6}`:""} dir=${D} branch=${w6} gitRepoUrl=${o} machine=${s}`),N(`[bridge:init] apiBaseUrl=${F} sessionIngressUrl=${U}`),N(`[bridge:init] sandbox=${z}${Y?` debugFile=${Y}`:""}`);let X6,f6;try{let x6=await l.registerBridgeEnvironment(J6);X6=x6.environment_id,f6=x6.environment_secret}catch(x6){d("tengu_bridge_registration_failed",{status:x6 instanceof PT?x6.status:void 0}),console.error(x6 instanceof PT&&x6.status===404?"Remote Control environments are not available for your account.":`Error: ${d6(x6)}`),process.exit(1)}let N6;N(`[bridge:init] Registered, server environmentId=${X6}`);let Z6=bd();d("tengu_bridge_started",{max_sessions:J6.maxSessions,has_debug_file:!!J6.debugFile,sandbox:J6.sandbox,verbose:J6.verbose,heartbeat_interval_ms:Z6.non_exclusive_heartbeat_interval_ms,spawn_mode:J6.spawnMode,spawn_mode_source:$6,multi_session_gate:T,pre_create_session:G6,worktree_available:e}),c8("info","bridge_started",{max_sessions:J6.maxSessions,sandbox:J6.sandbox,spawn_mode:J6.spawnMode});let V6=C_7({execPath:process.execPath,scriptArgs:uFK(),env:process.env,verbose:_,sandbox:z,debugFile:Y,permissionMode:A,onDebug:N,onActivity:(x6,b6)=>{N(`[bridge:activity] sessionId=${x6} ${b6.type} ${b6.summary}`)},onPermissionRequest:(x6,b6,Q6)=>{N(`[bridge:perm] sessionId=${x6} tool=${b6.request.tool_name} request_id=${b6.request_id} (not auto-approving)`)}}),y6=WFK({verbose:_}),{parseGitHubRepository:T6}=await Promise.resolve().then(() => (mZ(),$p6)),n6=o?T6(o):null,o6=n6?n6.split("/").pop():zbY(D);y6.setRepoInfo(o6,w6);let I6=M6!=="single-session"&&e;if(I6)y6.setSpawnModeDisplay(M6);let C6=(x6)=>{if(x6[0]===3||x6[0]===4){process.emit("SIGINT");return}if(x6[0]===32){y6.toggleQr();return}if(x6[0]===119){if(!I6)return;let b6=J6.spawnMode==="same-dir"?"worktree":"same-dir";J6.spawnMode=b6,d("tengu_bridge_spawn_mode_toggled",{spawn_mode:b6}),y6.logStatus(b6==="worktree"?"Spawn mode: worktree (new sessions get isolated git worktrees)":"Spawn mode: same-dir (new sessions share the current directory)"),y6.setSpawnModeDisplay(b6),y6.refreshDisplay(),g((Q6)=>{if(Q6.remoteControlSpawnMode===b6)return Q6;return{...Q6,remoteControlSpawnMode:b6}});return}};if(process.stdin.isTTY)process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",C6);let l6=new AbortController,S6=()=>{N("[bridge:shutdown] SIGINT received, shutting down"),l6.abort()},E6=()=>{N("[bridge:shutdown] SIGTERM received, shutting down"),l6.abort()};process.on("SIGINT",S6),process.on("SIGTERM",E6);let R6=null;if(G6){let{createBridgeSession:x6}=await Promise.resolve().then(() => (eH6(),DS6));try{if(R6=await x6({environmentId:X6,title:O,events:[],gitRepoUrl:o,branch:w6,signal:l6.signal,baseUrl:F,getAccessToken:R,permissionMode:A}),R6)N(`[bridge:init] Created initial session ${R6}`)}catch(b6){N(`[bridge:init] Session creation failed (non-fatal): ${d6(b6)}`)}}let h6=null;if(R6&&M6==="single-session"){let{writeBridgePointer:x6}=await Promise.resolve().then(() => (rq8(),iq8)),b6={sessionId:R6,environmentId:X6,source:"standalone"};await x6(J6.dir,b6),h6=setInterval(x6,3600000,J6.dir,b6),h6.unref?.()}try{await g_7(J6,X6,f6,l,V6,y6,l6.signal,void 0,R6??void 0,async()=>{return E(),await S(),R()})}finally{if(h6!==null)clearInterval(h6);if(process.off("SIGINT",S6),process.off("SIGTERM",E6),process.stdin.off("data",C6),process.stdin.isTTY)process.stdin.setRawMode(!1);process.stdin.pause()}process.exit(0)}async function ZbY(q,K){let{dir:_,log:z}=q;process.chdir(_);let{setOriginalCwd:Y,setCwdState:$}=await Promise.resolve().then(() => (v8(),D38));Y(_),$(_);let{enableConfigs:A,checkHasTrustDialogAccepted:O}=await Promise.resolve().then(() => (V1(),G16));A();let{initSinks:w}=await Promise.resolve().then(() => (oq8(),lQ8));if(w(),!O())throw new tq8(`Workspace not trusted: ${_}. Run \`claude\` in that directory first to accept the trust dialog.`);if(!q.getAccessToken())throw Error(wU8);let{getBridgeBaseUrl:j}=await Promise.resolve().then(() => (Ea(),Ve1)),H=j();if(H.startsWith("http://")&&!H.includes("localhost")&&!H.includes("127.0.0.1"))throw new tq8("Remote Control base URL uses HTTP. Only HTTPS or localhost HTTP is allowed.");let J=H,{getBranch:M,getRemoteUrl:X,findGitRoot:P}=await Promise.resolve().then(() => (E5(),qA8)),{hasWorktreeCreateHook:W}=await Promise.resolve().then(() => (y$(),FL8));if(q.spawnMode==="worktree"){if(!(W()||P(_)!==null))throw new tq8(`Worktree mode requires a git repository or WorktreeCreate hooks. Directory ${_} has neither.`)}let D=await M(),f=await X(),G=bFK(),Z=nQ8(),T={dir:_,machineName:G,branch:D,gitRepoUrl:f,maxSessions:q.capacity,spawnMode:q.spawnMode,verbose:!1,sandbox:q.sandbox,bridgeId:Z,workerType:"claude_code",environmentId:nQ8(),apiBaseUrl:H,sessionIngressUrl:J,sessionTimeoutMs:q.sessionTimeoutMs},v=Tq8({baseUrl:H,getAccessToken:q.getAccessToken,runnerVersion:{ISSUES_EXPLAINER:"report the issue at https://github.com/anthropics/claude-code/issues",PACKAGE_URL:"@anthropic-ai/claude-code",README_URL:"https://code.claude.com/docs/en/overview",VERSION:"2.1.88",FEEDBACK_CHANNEL:"https://github.com/anthropics/claude-code/issues",BUILD_TIME:"2026-03-30T21:59:52Z"}.VERSION,onDebug:z,onAuth401:q.onAuth401,getTrustedDeviceToken:q46}),V,E;try{let I=await v.registerBridgeEnvironment(T);V=I.environment_id,E=I.environment_secret}catch(I){throw Error(`Bridge registration failed: ${d6(I)}`)}let S=C_7({execPath:process.execPath,scriptArgs:uFK(),env:process.env,verbose:!1,sandbox:q.sandbox,permissionMode:q.permissionMode,onDebug:z}),R=GbY(z);R.printBanner(T,V);let x;if(q.createSessionOnStart){let{createBridgeSession:I}=await Promise.resolve().then(() => (eH6(),DS6));try{let B=await I({environmentId:V,title:q.name,events:[],gitRepoUrl:f,branch:D,signal:K,baseUrl:H,getAccessToken:q.getAccessToken,permissionMode:q.permissionMode});if(B)x=B,z(`created initial session ${B}`)}catch(B){z(`session pre-creation failed (non-fatal): ${d6(B)}`)}}await g_7(T,V,E,v,S,R,K,void 0,x,async()=>q.getAccessToken())}function GbY(q){let K=()=>{};return{printBanner:(_,z)=>q(`registered environmentId=${z} dir=${_.dir} spawnMode=${_.spawnMode} capacity=${_.maxSessions}`),logSessionStart:(_,z)=>q(`session start ${_}`),logSessionComplete:(_,z)=>q(`session complete ${_} (${z}ms)`),logSessionFailed:(_,z)=>q(`session failed ${_}: ${z}`),logStatus:q,logVerbose:q,logError:(_)=>q(`error: ${_}`),logReconnected:(_)=>q(`reconnected after ${_}ms`),addSession:(_,z)=>q(`session attached ${_}`),removeSession:(_)=>q(`session detached ${_}`),updateIdleStatus:K,updateReconnectingStatus:K,updateSessionStatus:K,updateSessionActivity:K,updateSessionCount:K,updateFailedStatus:K,setSpawnModeDisplay:K,setRepoInfo:K,setDebugLogPath:K,setAttached:K,setSessionTitle:K,clearStatus:K,toggleQr:K,refreshDisplay:K}}var $bY,AbY=1000,xFK=32,wbY,HbY,PbY=80,tq8;var U_7=y(()=>{sG6();Hi();o1();k8();_8();oY();m8();y8();U7();E8();d0();kq8();Q46();DFK();Ys();BQ8();gQ8();kFK();rw6();nq8();$bY={connInitialMs:2000,connCapMs:120000,connGiveUpMs:600000,generalInitialMs:500,generalCapMs:30000,generalGiveUpMs:600000};wbY=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","ENETUNREACH","EHOSTUNREACH"]);HbY=["session","same-dir","worktree"];tq8=class tq8 extends Error{constructor(q){super(q);this.name="BridgeHeadlessPermanentError"}}});var eq8=m((TbY)=>{class Q_7 extends Error{constructor(q,K,_){super(_);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=K,this.exitCode=q,this.nestedError=void 0}}class gFK extends Q_7{constructor(q){super(1,"commander.invalidArgument",q);Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}TbY.CommanderError=Q_7;TbY.InvalidArgumentError=gFK});var iQ8=m((ybY)=>{var{InvalidArgumentError:VbY}=eq8();class FFK{constructor(q,K){switch(this.description=K||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,q[0]){case"<":this.required=!0,this._name=q.slice(1,-1);break;case"[":this.required=!1,this._name=q.slice(1,-1);break;default:this.required=!0,this._name=q;break}if(this._name.length>3&&this._name.slice(-3)==="...")this.variadic=!0,this._name=this._name.slice(0,-3)}name(){return this._name}_concatValue(q,K){if(K===this.defaultValue||!Array.isArray(K))return[q];return K.concat(q)}default(q,K){return this.defaultValue=q,this.defaultValueDescription=K,this}argParser(q){return this.parseArg=q,this}choices(q){return this.argChoices=q.slice(),this.parseArg=(K,_)=>{if(!this.argChoices.includes(K))throw new VbY(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(K,_);return K},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}}function NbY(q){let K=q.name()+(q.variadic===!0?"...":"");return q.required?"<"+K+">":"["+K+"]"}ybY.Argument=FFK;ybY.humanReadableArgName=NbY});var d_7=m((hbY)=>{var{humanReadableArgName:RbY}=iQ8();class UFK{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}visibleCommands(q){let K=q.commands.filter((z)=>!z._hidden),_=q._getHelpCommand();if(_&&!_._hidden)K.push(_);if(this.sortSubcommands)K.sort((z,Y)=>{return z.name().localeCompare(Y.name())});return K}compareOptions(q,K){let _=(z)=>{return z.short?z.short.replace(/^-/,""):z.long.replace(/^--/,"")};return _(q).localeCompare(_(K))}visibleOptions(q){let K=q.options.filter((z)=>!z.hidden),_=q._getHelpOption();if(_&&!_.hidden){let z=_.short&&q._findOption(_.short),Y=_.long&&q._findOption(_.long);if(!z&&!Y)K.push(_);else if(_.long&&!Y)K.push(q.createOption(_.long,_.description));else if(_.short&&!z)K.push(q.createOption(_.short,_.description))}if(this.sortOptions)K.sort(this.compareOptions);return K}visibleGlobalOptions(q){if(!this.showGlobalOptions)return[];let K=[];for(let _=q.parent;_;_=_.parent){let z=_.options.filter((Y)=>!Y.hidden);K.push(...z)}if(this.sortOptions)K.sort(this.compareOptions);return K}visibleArguments(q){if(q._argsDescription)q.registeredArguments.forEach((K)=>{K.description=K.description||q._argsDescription[K.name()]||""});if(q.registeredArguments.find((K)=>K.description))return q.registeredArguments;return[]}subcommandTerm(q){let K=q.registeredArguments.map((_)=>RbY(_)).join(" ");return q._name+(q._aliases[0]?"|"+q._aliases[0]:"")+(q.options.length?" [options]":"")+(K?" "+K:"")}optionTerm(q){return q.flags}argumentTerm(q){return q.name()}longestSubcommandTermLength(q,K){return K.visibleCommands(q).reduce((_,z)=>{return Math.max(_,K.subcommandTerm(z).length)},0)}longestOptionTermLength(q,K){return K.visibleOptions(q).reduce((_,z)=>{return Math.max(_,K.optionTerm(z).length)},0)}longestGlobalOptionTermLength(q,K){return K.visibleGlobalOptions(q).reduce((_,z)=>{return Math.max(_,K.optionTerm(z).length)},0)}longestArgumentTermLength(q,K){return K.visibleArguments(q).reduce((_,z)=>{return Math.max(_,K.argumentTerm(z).length)},0)}commandUsage(q){let K=q._name;if(q._aliases[0])K=K+"|"+q._aliases[0];let _="";for(let z=q.parent;z;z=z.parent)_=z.name()+" "+_;return _+K+" "+q.usage()}commandDescription(q){return q.description()}subcommandDescription(q){return q.summary()||q.description()}optionDescription(q){let K=[];if(q.argChoices)K.push(`choices: ${q.argChoices.map((_)=>JSON.stringify(_)).join(", ")}`);if(q.defaultValue!==void 0){if(q.required||q.optional||q.isBoolean()&&typeof q.defaultValue==="boolean")K.push(`default: ${q.defaultValueDescription||JSON.stringify(q.defaultValue)}`)}if(q.presetArg!==void 0&&q.optional)K.push(`preset: ${JSON.stringify(q.presetArg)}`);if(q.envVar!==void 0)K.push(`env: ${q.envVar}`);if(K.length>0)return`${q.description} (${K.join(", ")})`;return q.description}argumentDescription(q){let K=[];if(q.argChoices)K.push(`choices: ${q.argChoices.map((_)=>JSON.stringify(_)).join(", ")}`);if(q.defaultValue!==void 0)K.push(`default: ${q.defaultValueDescription||JSON.stringify(q.defaultValue)}`);if(K.length>0){let _=`(${K.join(", ")})`;if(q.description)return`${q.description} ${_}`;return _}return q.description}formatHelp(q,K){let _=K.padWidth(q,K),z=K.helpWidth||80,Y=2,$=2;function A(X,P){if(P){let W=`${X.padEnd(_+2)}${P}`;return K.wrap(W,z-2,_+2)}return X}function O(X){return X.join(` |