MCPcopy Index your code
hub / github.com/ChinaSiro/claude-code-sourcemap / constructor

Method constructor

package/cli.js:7965–7965  ·  view source on GitHub ↗
(q,K,_)

Source from the content-addressed store, hash-verified

7963`),eK(1);return}return Promise.resolve().then(() => (VUK(),kUK)).then((_)=>_.showInvalidConfigDialog({error:K}))}else throw K}})});function EUK(q){let K=z6(3),{getFpsMetrics:_,children:z}=q,Y;if(K[0]!==z||K[1]!==_)Y=aS6.default.createElement(yUK.Provider,{value:_},z),K[0]=z,K[1]=_,K[2]=Y;else Y=K[2];return Y}function LUK(){return aS6.useContext(yUK)}var aS6,yUK;var _z7=y(()=>{q8();aS6=O6(D6(),1),yUK=aS6.createContext(void 0)});function zz7(q,K){let _=K/100*(q.length-1),z=Math.floor(_),Y=Math.ceil(_);if(z===Y)return q[z];return q[z]+(q[Y]-q[z])*(_-z)}function Yz7(){let q=new Map,K=new Map,_=new Map;return{increment(z,Y=1){q.set(z,(q.get(z)??0)+Y)},set(z,Y){q.set(z,Y)},observe(z,Y){let $=K.get(z);if(!$)$={reservoir:[],count:0,sum:0,min:Y,max:Y},K.set(z,$);if($.count++,$.sum+=Y,Y<$.min)$.min=Y;if(Y>$.max)$.max=Y;if($.reservoir.length<RUK)$.reservoir.push(Y);else{let A=Math.floor(Math.random()*$.count);if(A<RUK)$.reservoir[A]=Y}},add(z,Y){let $=_.get(z);if(!$)$=new Set,_.set(z,$);$.add(Y)},getAll(){let z=Object.fromEntries(q);for(let[Y,$]of K){if($.count===0)continue;z[`${Y}_count`]=$.count,z[`${Y}_min`]=$.min,z[`${Y}_max`]=$.max,z[`${Y}_avg`]=$.sum/$.count;let A=[...$.reservoir].sort((O,w)=>O-w);z[`${Y}_p50`]=zz7(A,50),z[`${Y}_p95`]=zz7(A,95),z[`${Y}_p99`]=zz7(A,99)}for(let[Y,$]of _)z[Y]=$.size;return z}}}function hUK(q){let K=z6(7),{store:_,children:z}=q,Y;if(K[0]===Symbol.for("react.memo_cache_sentinel"))Y=Yz7(),K[0]=Y;else Y=K[0];let A=_??Y,O,w;if(K[1]!==A)O=()=>{let H=()=>{let J=A.getAll();if(Object.keys(J).length>0)jw((M)=>({...M,lastSessionMetrics:J}))};return process.on("exit",H),()=>{process.off("exit",H)}},w=[A],K[1]=A,K[2]=O,K[3]=w;else O=K[2],w=K[3];LJ6.useEffect(O,w);let j;if(K[4]!==z||K[5]!==A)j=LJ6.default.createElement(uxY.Provider,{value:A},z),K[4]=z,K[5]=A,K[6]=j;else j=K[6];return j}var LJ6,RUK=1024,uxY;var $z7=y(()=>{q8();V1();LJ6=O6(D6(),1);uxY=LJ6.createContext(null)});function bUK(q){SUK=q}function xUK(q){K48=q}function IUK(q){CUK=q}function mUK(){return uUK}function sS6(q,K){if(uUK=q,SUK?.(q,K),q==="requires_action"&&K)Az7=!0,K48?.({pending_action:K});else if(Az7)Az7=!1,K48?.({pending_action:null});if(q==="idle")K48?.({task_summary:null});if(i6(process.env.CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS))ur({type:"system",subtype:"session_state_changed",state:q})}function _48(q){K48?.(q)}function pUK(q){CUK?.(q)}var SUK=null,K48=null,CUK=null,Az7=!1,uUK="idle";var z48=y(()=>{m8();pC()});function BUK(q){return(K)=>({...K,...typeof q.permission_mode==="string"?{toolPermissionContext:{...K.toolPermissionContext,mode:vE(q.permission_mode)}}:{},...typeof q.is_ultraplan_mode==="boolean"?{isUltraplanMode:q.is_ultraplan_mode}:{}})}function Ss({newState:q,oldState:K}){let _=K.toolPermissionContext.mode,z=q.toolPermissionContext.mode;if(_!==z){let Y=KI(_),$=KI(z);if(Y!==$){let A=$==="plan"&&q.isUltraplanMode&&!K.isUltraplanMode?!0:null;_48({permission_mode:$,is_ultraplan_mode:A})}pUK(z)}if(q.mainLoopModel!==K.mainLoopModel&&q.mainLoopModel===null)W7("userSettings",{model:void 0}),YP(null);if(q.mainLoopModel!==K.mainLoopModel&&q.mainLoopModel!==null)W7("userSettings",{model:q.mainLoopModel}),YP(q.mainLoopModel);if(q.expandedView!==K.expandedView){let Y=q.expandedView==="tasks",$=q.expandedView==="teammates";if(j8().showExpandedTodos!==Y||j8().showSpinnerTree!==$)b8((A)=>({...A,showExpandedTodos:Y,showSpinnerTree:$}))}if(q.verbose!==K.verbose&&j8().verbose!==q.verbose){let Y=q.verbose;b8(($)=>({...$,verbose:Y}))}if(q.settings!==K.settings)try{if(id6(),rd6(),od6(),q.settings.env!==K.settings.env)xd()}catch(Y){H6(x1(Y))}}var tS6=y(()=>{v8();G7();V1();y8();E8();q48();yW();z48();U1()});var Oz7={};T8(Oz7,{App:()=>mxY});function mxY(q){let K=z6(9),{getFpsMetrics:_,stats:z,initialState:Y,children:$}=q,A;if(K[0]!==$||K[1]!==Y)A=aQ8.default.createElement(LJ,{initialState:Y,onChangeAppState:Ss},$),K[0]=$,K[1]=Y,K[2]=A;else A=K[2];let O;if(K[3]!==z||K[4]!==A)O=aQ8.default.createElement(hUK,{store:z},A),K[3]=z,K[4]=A,K[5]=O;else O=K[5];let w;if(K[6]!==_||K[7]!==O)w=aQ8.default.createElement(EUK,{getFpsMetrics:_},O),K[6]=_,K[7]=O,K[8]=w;else w=K[8];return w}var aQ8;var wz7=y(()=>{q8();_z7();$z7();C7();tS6();aQ8=O6(D6(),1)});function gUK(){sQ8.useContext(Zi);let q=VA.get(process.stdout);return sQ8.useMemo(()=>{if(!q)return{setQuery:()=>{},scanElement:()=>[],setPositions:()=>{}};return{setQuery:(K)=>q.setSearchHighlight(K),scanElement:(K)=>q.scanElementSubtree(K),setPositions:(K)=>q.setSearchPositions(K)}},[q])}var sQ8;var FUK=y(()=>{pc6();QV();sQ8=O6(D6(),1)});function UUK(q){let K=z6(7),{onDone:_}=q,z;if(K[0]===Symbol.for("react.memo_cache_sentinel"))z=eS6.default.createElement(u,{flexDirection:"column"},eS6.default.createElement(k,null,"Learn more about how to monitor your spending:"),eS6.default.createElement(hq,{url:"https://code.claude.com/docs/en/costs"})),K[0]=z;else z=K[0];let Y;if(K[1]===Symbol.for("react.memo_cache_sentinel"))Y=[{value:"ok",label:"Got it, thanks!"}],K[1]=Y;else Y=K[1];let $;if(K[2]!==_)$=eS6.default.createElement(H1,{options:Y,onChange:_}),K[2]=_,K[3]=$;else $=K[3];let A;if(K[4]!==_||K[5]!==$)A=eS6.default.createElement(R1,{title:"You've spent $5 on the Anthropic API this session.",onCancel:_},z,$),K[4]=_,K[5]=$,K[6]=A;else A=K[6];return A}var eS6;var QUK=y(()=>{q8();s6();d_();e4();eS6=O6(D6(),1)});function dUK(q){let K=z6(16),{idleMinutes:_,totalInputTokens:z,onDone:Y}=q,$;if(K[0]!==_)$=pxY(_),K[0]=_,K[1]=$;else $=K[1];let A=$,O;if(K[2]!==z)O=_Y(z),K[2]=z,K[3]=O;else O=K[3];let j=`You've been away ${A} and this conversation is ${O} tokens.`,H;if(K[4]!==Y)H=()=>Y("dismiss"),K[4]=Y,K[5]=H;else H=K[5];let J;if(K[6]===Symbol.for("react.memo_cache_sentinel"))J=Y48.default.createElement(u,{flexDirection:"column"},Y48.default.createElement(k,null,"If this is a new task, clearing context will save usage and be faster.")),K[6]=J;else J=K[6];let M;if(K[7]===Symbol.for("react.memo_cache_sentinel"))M={value:"continue",label:"Continue this conversation"},K[7]=M;else M=K[7];let X;if(K[8]===Symbol.for("react.memo_cache_sentinel"))X={value:"clear",label:"Send message as a new conversation"},K[8]=X;else X=K[8];let P;if(K[9]===Symbol.for("react.memo_cache_sentinel"))P=[M,X,{value:"never",label:"Don't ask me again"}],K[9]=P;else P=K[9];let W;if(K[10]!==Y)W=Y48.default.createElement(H1,{options:P,onChange:(f)=>Y(f)}),K[10]=Y,K[11]=W;else W=K[11];let D;if(K[12]!==j||K[13]!==H||K[14]!==W)D=Y48.default.createElement(R1,{title:j,onCancel:H},J,W),K[12]=j,K[13]=H,K[14]=W,K[15]=D;else D=K[15];return D}function pxY(q){if(q<1)return"< 1m";if(q<60)return`${Math.floor(q)}m`;let K=Math.floor(q/60),_=Math.floor(q%60);if(_===0)return`${K}h`;return`${K}h ${_}m`}var Y48;var cUK=y(()=>{q8();s6();U7();d_();e4();Y48=O6(D6(),1)});import{spawn as BxY}from"child_process";function nUK(){if(RJ6++,RJ6===1)oUK(),QxY()}function iUK(){if(RJ6>0)RJ6--;if(RJ6===0)rUK(),jz7()}function UxY(){RJ6=0,rUK(),jz7()}function QxY(){if(process.platform!=="darwin")return;if(qC6!==null)return;qC6=setInterval(()=>{if(RJ6>0)N("Restarting caffeinate to maintain sleep prevention"),jz7(),oUK()},FxY),qC6.unref()}function rUK(){if(qC6!==null)clearInterval(qC6),qC6=null}function oUK(){if(process.platform!=="darwin")return;if(ky!==null)return;if(!lUK)lUK=!0,pq(async()=>{UxY()});try{ky=BxY("caffeinate",["-i","-t",String(gxY)],{stdio:"ignore"}),ky.unref();let q=ky;ky.on("error",(K)=>{if(N(`caffeinate spawn error: ${K.message}`),ky===q)ky=null}),ky.on("exit",()=>{if(ky===q)ky=null}),N("Started caffeinate to prevent sleep")}catch{ky=null}}function jz7(){if(ky!==null){let q=ky;ky=null;try{q.kill("SIGKILL"),N("Stopped caffeinate, allowing sleep")}catch{}}}var gxY=300,FxY=240000,ky=null,qC6=null,RJ6=0,lUK=!1;var aUK=y(()=>{c9();_8()});class Hz7{_status="idle";_generation=0;_changed=Dz();reserve(){if(this._status!=="idle")return!1;return this._status="dispatching",this._notify(),!0}cancelReservation(){if(this._status!=="dispatching")return;this._status="idle",this._notify()}tryStart(){if(this._status==="running")return null;return this._status="running",++this._generation,this._notify(),this._generation}end(q){if(this._generation!==q)return!1;if(this._status!=="running")return!1;return this._status="idle",this._notify(),!0}forceEnd(){if(this._status==="idle")return;this._status="idle",++this._generation,this._notify()}get isActive(){return this._status!=="idle"}get generation(){return this._generation}subscribe=this._changed.subscribe;getSnapshot=()=>{return this._status!=="idle"};_notify(){this._changed.emit()}}var sUK=()=>{};function tUK(q){let K=z6(7),{name:_,color:z}=q,Y;if(K[0]!==z)Y=R0(z),K[0]=z,K[1]=Y;else Y=K[1];let $=Y,A;if(K[2]!==_)A=hJ6.createElement(k,{bold:!0},"@",_),K[2]=_,K[3]=A;else A=K[3];let O;if(K[4]!==$||K[5]!==A)O=hJ6.createElement(u,{flexDirection:"row",gap:1},hJ6.createElement(k,{color:$},A_," ",A)),K[4]=$,K[5]=A,K[6]=O;else O=K[6];return O}var hJ6;var eUK=y(()=>{q8();zz();s6();Fo();hJ6=O6(D6(),1)});function Jz7(q){let K=z6(15),{toolName:_,description:z}=q,Y;if(K[0]===Symbol.for("react.memo_cache_sentinel"))Y=$9(),K[0]=Y;else Y=K[0];let $=Y,A;if(K[1]===Symbol.for("react.memo_cache_sentinel"))A=M_(),K[1]=A;else A=K[1];let O=A,w;if(K[2]===Symbol.for("react.memo_cache_sentinel"))w=vj(),K[2]=w;else w=K[2];let j=w,H,J;if(K[3]===Symbol.for("react.memo_cache_sentinel"))H=WO.createElement(u,{marginBottom:1},WO.createElement(IK,null),WO.createElement(k,{color:"warning",bold:!0}," ","Waiting for team lead approval")),J=O&&j&&WO.createElement(u,{marginBottom:1},WO.createElement(tUK,{name:O,color:j})),K[3]=H,K[4]=J;else H=K[3],J=K[4];let M;if(K[5]===Symbol.for("react.memo_cache_sentinel"))M=WO.createElement(k,{dimColor:!0},"Tool: "),K[5]=M;else M=K[5];let X;if(K[6]!==_)X=WO.createElement(u,null,M,WO.createElement(k,null,_)),K[6]=_,K[7]=X;else X=K[7];let P;if(K[8]===Symbol.for("react.memo_cache_sentinel"))P=WO.createElement(k,{dimColor:!0},"Action: "),K[8]=P;else P=K[8];let W;if(K[9]!==z)W=WO.createElement(u,null,P,WO.createElement(k,null,z)),K[9]=z,K[10]=W;else W=K[10];let D;if(K[11]===Symbol.for("react.memo_cache_sentinel"))D=$&&WO.createElement(u,{marginTop:1},WO.createElement(k,{dimColor:!0},"Permission request sent to team ",'"',$,'"'," leader")),K[11]=D;else D=K[11];let f;if(K[12]!==X||K[13]!==W)f=WO.createElement(u,{flexDirection:"column",borderStyle:"round",borderColor:"warning",paddingX:1},H,J,X,W,D),K[12]=X,K[13]=W,K[14]=f;else f=K[14];return f}var WO;var qQK=y(()=>{q8();s6();AY();Q2();eUK();WO=O6(D6(),1)});function KQK(q,K=!1){let _=P8((O)=>O.teamContext),z=SJ6.useRef(0),Y=SJ6.useRef(void 0),$=SJ6.useRef(void 0),A=SJ6.useRef(0);SJ6.useEffect(()=>{if(K)return;let O=q[0]?.uuid,w=z.current,j=$.current===void 0,H=O!==void 0&&!j&&O===$.current&&w<=q.length,J=O!==void 0&&!j&&O===$.current&&w>q.length,M=H?w:0;if(M===q.length)return;let X=M===0?q:q.slice(M),P=H?Y.current:void 0,W=++A.current;if(fN(X,nq()?{teamName:_?.teamName,agentName:_?.selfAgentName}:{},P,q).then((D)=>{if(W!==A.current)return;if(D&&!H)Y.current=D}),H||j||J){let D=Bq8(X,q).findLast(FS6);if(D)Y.current=D.uuid}z.current=q.length,$.current=O},[q,K,_?.teamName,_?.selfAgentName])}var SJ6;var _QK=y(()=>{C7();i$();_K();SJ6=O6(D6(),1)});function zQK(q){if(!q||typeof q!=="object")return!1;return"behavior"in q&&(q.behavior==="allow"||q.behavior==="deny")}var YQK=()=>{};function tQ8(q){if(q.type!=="user")return;let K=q.message?.content;if(!K)return;if(Array.isArray(K)&&K.length===0)return;let _="uuid"in q&&typeof q.uuid==="string"?q.uuid:void 0;return{content:Array.isArray(K)?dxY(K):K,uuid:_}}function dxY(q){if(!q.some($QK))return q;return q.map((K)=>{if(!$QK(K))return K;let _=K.source,z=typeof _.mediaType==="string"&&_.mediaType?_.mediaType:Cr6(K.source.data);return{...K,source:{type:"base64",media_type:z,data:K.source.data}}})}function $QK(q){if(q.type!=="image"||q.source?.type!=="base64")return!1;return!q.source.media_type}var Mz7=y(()=>{RL()});import{randomUUID as cxY}from"crypto";function Xz7(q){return q===v4?CB:q}function eQ8(q){let _=Z7()?.outputStyle??iv,z={type:"system",subtype:"init",cwd:Z8(),session_id:N8(),tools:q.tools.map((Y)=>Xz7(Y.name)),mcp_servers:q.mcpClients.map((Y)=>({name:Y.name,status:Y.type})),model:q.model,permissionMode:q.permissionMode,slash_commands:q.commands.filter((Y)=>Y.userInvocable!==!1).map((Y)=>Y.name),apiKeySource:Ow().source,betas:QM(),claude_code_version:{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,output_style:_,agents:q.agents.map((Y)=>Y.agentType),skills:q.skills.filter((Y)=>Y.userInvocable!==!1).map((Y)=>Y.name),plugins:q.plugins.map((Y)=>({name:Y.name,path:Y.path,source:Y.source})),uuid:cxY()};return z.fast_mode_state=II(q.model,q.fastMode),z}var Pz7=y(()=>{v8();TU();Z$();G7();I7();xf();U1()});function qd8(q){if(q===null||typeof q!=="object")return q;let K=q;if("requestId"in K&&!("request_id"in K))K.request_id=K.requestId,delete K.requestId;if("response"in K&&K.response!==null&&typeof K.response==="object"){let _=K.response;if("requestId"in _&&!("request_id"in _))_.request_id=_.requestId,delete _.requestId}return q}import{randomUUID as lxY}from"crypto";function nxY(q){return q!==null&&typeof q==="object"&&"type"in q&&typeof q.type==="string"}function ixY(q){return q!==null&&typeof q==="object"&&"type"in q&&q.type==="control_response"&&"response"in q}function rxY(q){return q!==null&&typeof q==="object"&&"type"in q&&q.type==="control_request"&&"request_id"in q&&"request"in q}function KC6(q){if((q.type==="user"||q.type==="assistant")&&q.isVirtual)return!1;return q.type==="user"||q.type==="assistant"||q.type==="system"&&q.subtype==="local_command"}function Kd8(q){if(q.type!=="user"||q.isMeta||q.toolUseResult||q.isCompactSummary)return;if(q.origin&&q.origin.kind!=="human")return;let K=q.message.content,_;if(typeof K==="string")_=K;else for(let Y of K)if(Y.type==="text"){_=Y.text;break}if(!_)return;return CW6(_)||void 0}function _d8(q,K,_,z,Y,$){try{let A=qd8(r8(q));if(ixY(A)){N("[bridge:repl] Ingress message type=control_response"),Y?.(A);return}if(rxY(A)){N(`[bridge:repl] Inbound control_request subtype=${A.request.subtype}`),$?.(A);return}if(!nxY(A))return;let O="uuid"in A&&typeof A.uuid==="string"?A.uuid:void 0;if(O&&K.has(O)){N(`[bridge:repl] Ignoring echo: type=${A.type} uuid=${O}`);return}if(O&&_.has(O)){N(`[bridge:repl] Ignoring re-delivered inbound: type=${A.type} uuid=${O}`);return}if(N(`[bridge:repl] Ingress message type=${A.type}${O?` uuid=${O}`:""}`),A.type==="user"){if(O)_.add(O);d("tengu_bridge_message_received",{is_repl:!0}),z?.(A)}else N(`[bridge:repl] Ignoring non-user inbound message: type=${A.type}`)}catch(A){N(`[bridge:repl] Failed to parse ingress message: ${d6(A)}`)}}function zd8(q,K){let{transport:_,sessionId:z,outboundOnly:Y,onInterrupt:$,onSetModel:A,onSetMaxThinkingTokens:O,onSetPermissionMode:w}=K;if(!_){N("[bridge:repl] Cannot respond to control_request: transport not configured");return}let j;if(Y&&q.request.subtype!=="initialize"){j={type:"control_response",response:{subtype:"error",request_id:q.request_id,error:oxY}};let J={...j,session_id:z};_.write(J),N(`[bridge:repl] Rejected ${q.request.subtype} (outbound-only) request_id=${q.request_id}`);return}switch(q.request.subtype){case"initialize":j={type:"control_response",response:{subtype:"success",request_id:q.request_id,response:{commands:[],output_style:"normal",available_output_styles:["normal"],models:[],account:{},pid:process.pid}}};break;case"set_model":A?.(q.request.model),j={type:"control_response",response:{subtype:"success",request_id:q.request_id}};break;case"set_max_thinking_tokens":O?.(q.request.max_thinking_tokens),j={type:"control_response",response:{subtype:"success",request_id:q.request_id}};break;case"set_permission_mode":{let J=w?.(q.request.mode)??{ok:!1,error:"set_permission_mode is not supported in this context (onSetPermissionMode callback not registered)"};if(J.ok)j={type:"control_response",response:{subtype:"success",request_id:q.request_id}};else j={type:"control_response",response:{subtype:"error",request_id:q.request_id,error:J.error}};break}case"interrupt":$?.(),j={type:"control_response",response:{subtype:"success",request_id:q.request_id}};break;default:j={type:"control_response",response:{subtype:"error",request_id:q.request_id,error:`REPL bridge does not handle control_request subtype: ${q.request.subtype}`}}}let H={...j,session_id:z};_.write(H),N(`[bridge:repl] Sent control_response for ${q.request.subtype} request_id=${q.request_id} result=${j.response.subtype}`)}function _C6(q){return{type:"result",subtype:"success",duration_ms:0,duration_api_ms:0,is_error:!1,num_turns:0,result:"",stop_reason:null,total_cost_usd:0,usage:{...n0},modelUsage:{},permission_denials:[],session_id:q,uuid:lxY()}}class Cs{capacity;ring;set=new Set;writeIdx=0;constructor(q){this.capacity=q,this.ring=Array(q)}add(q){if(this.set.has(q))return;let K=this.ring[this.writeIdx];if(K!==void 0)this.set.delete(K);this.ring[this.writeIdx]=q,this.set.add(q),this.writeIdx=(this.writeIdx+1)%this.capacity}has(q){return this.set.has(q)}clear(){this.set.clear(),this.ring.fill(void 0),this.writeIdx=0}}var oxY="This session is outbound-only. Enable Remote Control locally to allow inbound control.";var Yd8=y(()=>{k8();E87();_8();bW6();y8();l8()});class CJ6{pending=[];pendingAtClose=0;draining=!1;closed=!1;backpressureResolvers=[];sleepResolve=null;flushResolvers=[];droppedBatches=0;config;constructor(q){this.config=q}get droppedBatchCount(){return this.droppedBatches}get pendingCount(){return this.closed?this.pendingAtClose:this.pending.length}async enqueue(q){if(this.closed)return;let K=Array.isArray(q)?q:[q];if(K.length===0)return;while(this.pending.length+K.length>this.config.maxQueueSize&&!this.closed)await new Promise((_)=>{this.backpressureResolvers.push(_)});if(this.closed)return;this.pending.push(...K),this.drain()}flush(){if(this.pending.length===0&&!this.draining)return Promise.resolve();return this.drain(),new Promise((q)=>{this.flushResolvers.push(q)})}close(){if(this.closed)return;this.closed=!0,this.pendingAtClose=this.pending.length,this.pending=[],this.sleepResolve?.(),this.sleepResolve=null;for(let q of this.backpressureResolvers)q();this.backpressureResolvers=[];for(let q of this.flushResolvers)q();this.flushResolvers=[]}async drain(){if(this.draining||this.closed)return;this.draining=!0;let q=0;try{while(this.pending.length>0&&!this.closed){let K=this.takeBatch();if(K.length===0)continue;try{await this.config.send(K),q=0}catch(_){if(q++,this.config.maxConsecutiveFailures!==void 0&&q>=this.config.maxConsecutiveFailures){this.droppedBatches++,this.config.onBatchDropped?.(K.length,q),q=0,this.releaseBackpressure();continue}this.pending=K.concat(this.pending);let z=_ instanceof zC6?_.retryAfterMs:void 0;await this.sleep(this.retryDelay(q,z));continue}this.releaseBackpressure()}}finally{if(this.draining=!1,this.pending.length===0){for(let K of this.flushResolvers)K();this.flushResolvers=[]}}}takeBatch(){let{maxBatchSize:q,maxBatchBytes:K}=this.config;if(K===void 0)return this.pending.splice(0,q);let _=0,z=0;while(z<this.pending.length&&z<q){let Y;try{Y=Buffer.byteLength(g6(this.pending[z]))}catch{this.pending.splice(z,1);continue}if(z>0&&_+Y>K)break;_+=Y,z++}return this.pending.splice(0,z)}retryDelay(q,K){let _=Math.random()*this.config.jitterMs;if(K!==void 0)return Math.max(this.config.baseDelayMs,Math.min(K,this.config.maxDelayMs))+_;return Math.min(this.config.baseDelayMs*2**(q-1),this.config.maxDelayMs)+_}releaseBackpressure(){let q=this.backpressureResolvers;this.backpressureResolvers=[];for(let K of q)K()}sleep(q){return new Promise((K)=>{this.sleepResolve=K,setTimeout((_,z)=>{_.sleepResolve=null,z()},q,this,K)})}}var zC6;var Wz7=y(()=>{l8();zC6=class zC6 extends Error{retryAfterMs;constructor(q,K){super(q);this.retryAfterMs=K}}});class $48{ws=null;lastSentId=null;url;state="idle";onData;onCloseCallback;onConnectCallback;headers;sessionId;autoReconnect;isBridge;reconnectAttempts=0;reconnectStartTime=null;reconnectTimer=null;lastReconnectAttemptTime=null;lastActivityTime=0;pingInterval=null;pongReceived=!0;keepAliveInterval=null;messageBuffer;isBunWs=!1;connectStartTime=0;refreshHeaders;constructor(q,K={},_,z,Y){this.url=q,this.headers=K,this.sessionId=_,this.refreshHeaders=z,this.autoReconnect=Y?.autoReconnect??!0,this.isBridge=Y?.isBridge??!1,this.messageBuffer=new I68(sxY)}async connect(){if(this.state!=="idle"&&this.state!=="reconnecting"){N(`WebSocketTransport: Cannot connect, current state is ${this.state}`,{level:"error"}),c8("error","cli_websocket_connect_failed");return}this.state="reconnecting",this.connectStartTime=Date.now(),N(`WebSocketTransport: Opening ${this.url.href}`),c8("info","cli_websocket_connect_opening");let q={...this.headers};if(this.lastSentId)q["X-Last-Request-Id"]=this.lastSentId,N(`WebSocketTransport: Adding X-Last-Request-Id header: ${this.lastSentId}`);if(typeof Bun<"u"){let K=new globalThis.WebSocket(this.url.href,{headers:q,proxy:NI(this.url.href),tls:YV()||void 0});this.ws=K,this.isBunWs=!0,K.addEventListener("open",this.onBunOpen),K.addEventListener("message",this.onBunMessage),K.addEventListener("error",this.onBunError),K.addEventListener("close",this.onBunClose),K.addEventListener("pong",this.onPong)}else{let{default:K}=await Promise.resolve().then(() => (W96(),MI6)),_=new K(this.url.href,{headers:q,agent:VI(this.url.href),...YV()});this.ws=_,this.isBunWs=!1,_.on("open",this.onNodeOpen),_.on("message",this.onNodeMessage),_.on("error",this.onNodeError),_.on("close",this.onNodeClose),_.on("pong",this.onPong)}}onBunOpen=()=>{if(this.handleOpenEvent(),this.lastSentId)this.replayBufferedMessages("")};onBunMessage=(q)=>{let K=typeof q.data==="string"?q.data:String(q.data);if(this.lastActivityTime=Date.now(),c8("info","cli_websocket_message_received",{length:K.length}),this.onData)this.onData(K)};onBunError=()=>{N("WebSocketTransport: Error",{level:"error"}),c8("error","cli_websocket_connect_error")};onBunClose=(q)=>{let K=q.code===1000||q.code===1001;N(`WebSocketTransport: Closed: ${q.code}`,K?void 0:{level:"error"}),c8("error","cli_websocket_connect_closed"),this.handleConnectionError(q.code)};onNodeOpen=()=>{let q=this.ws;if(this.handleOpenEvent(),!q)return;let _=q.upgradeReq;if(_?.headers?.["x-last-request-id"]){let z=_.headers["x-last-request-id"];this.replayBufferedMessages(z)}};onNodeMessage=(q)=>{let K=q.toString();if(this.lastActivityTime=Date.now(),c8("info","cli_websocket_message_received",{length:K.length}),this.onData)this.onData(K)};onNodeError=(q)=>{N(`WebSocketTransport: Error: ${q.message}`,{level:"error"}),c8("error","cli_websocket_connect_error")};onNodeClose=(q,K)=>{let _=q===1000||q===1001;N(`WebSocketTransport: Closed: ${q}`,_?void 0:{level:"error"}),c8("error","cli_websocket_connect_closed"),this.handleConnectionError(q)};onPong=()=>{this.pongReceived=!0};handleOpenEvent(){let q=Date.now()-this.connectStartTime;if(N("WebSocketTransport: Connected"),c8("info","cli_websocket_connect_connected",{duration_ms:q}),this.isBridge&&this.reconnectStartTime!==null)d("tengu_ws_transport_reconnected",{attempts:this.reconnectAttempts,downtimeMs:Date.now()-this.reconnectStartTime});this.reconnectAttempts=0,this.reconnectStartTime=null,this.lastReconnectAttemptTime=null,this.lastActivityTime=Date.now(),this.state="connected",this.onConnectCallback?.(),this.startPingInterval(),this.startKeepaliveInterval(),Yp8(()=>{this.write({type:"keep_alive"})})}sendLine(q){if(!this.ws||this.state!=="connected")return N("WebSocketTransport: Not connected"),c8("info","cli_websocket_send_not_connected"),!1;try{return this.ws.send(q),this.lastActivityTime=Date.now(),!0}catch(K){return N(`WebSocketTransport: Failed to send: ${K}`,{level:"error"}),c8("error","cli_websocket_send_error"),this.handleConnectionError(),!1}}removeWsListeners(q){if(this.isBunWs){let K=q;K.removeEventListener("open",this.onBunOpen),K.removeEventListener("message",this.onBunMessage),K.removeEventListener("error",this.onBunError),K.removeEventListener("close",this.onBunClose),K.removeEventListener("pong",this.onPong)}else{let K=q;K.off("open",this.onNodeOpen),K.off("message",this.onNodeMessage),K.off("error",this.onNodeError),K.off("close",this.onNodeClose),K.off("pong",this.onPong)}}doDisconnect(){if(this.stopPingInterval(),this.stopKeepaliveInterval(),z18(),this.ws)this.removeWsListeners(this.ws),this.ws.close(),this.ws=null}handleConnectionError(q){if(N(`WebSocketTransport: Disconnected from ${this.url.href}`+(q!=null?` (code ${q})`:"")),c8("info","cli_websocket_disconnected"),this.isBridge)d("tengu_ws_transport_closed",{closeCode:q,msSinceLastActivity:this.lastActivityTime>0?Date.now()-this.lastActivityTime:-1,wasConnected:this.state==="connected",reconnectAttempts:this.reconnectAttempts});if(this.doDisconnect(),this.state==="closing"||this.state==="closed")return;let K=!1;if(q===4003&&this.refreshHeaders){let Y=this.refreshHeaders();if(Y.Authorization!==this.headers.Authorization)Object.assign(this.headers,Y),K=!0,N("WebSocketTransport: 4003 received but headers refreshed, scheduling reconnect"),c8("info","cli_websocket_4003_token_refreshed")}if(q!=null&&_IY.has(q)&&!K){N(`WebSocketTransport: Permanent close code ${q}, not reconnecting`,{level:"error"}),c8("error","cli_websocket_permanent_close",{closeCode:q}),this.state="closed",this.onCloseCallback?.(q);return}if(!this.autoReconnect){this.state="closed",this.onCloseCallback?.(q);return}let _=Date.now();if(!this.reconnectStartTime)this.reconnectStartTime=_;if(this.lastReconnectAttemptTime!==null&&_-this.lastReconnectAttemptTime>AQK)N(`WebSocketTransport: Detected system sleep (${Math.round((_-this.lastReconnectAttemptTime)/1000)}s gap), resetting reconnection budget`),c8("info","cli_websocket_sleep_detected",{gapMs:_-this.lastReconnectAttemptTime}),this.reconnectStartTime=_,this.reconnectAttempts=0;this.lastReconnectAttemptTime=_;let z=_-this.reconnectStartTime;if(z<exY){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(!K&&this.refreshHeaders){let A=this.refreshHeaders();Object.assign(this.headers,A),N("WebSocketTransport: Refreshed headers for reconnect")}this.state="reconnecting",this.reconnectAttempts++;let Y=Math.min(txY*Math.pow(2,this.reconnectAttempts-1),OQK),$=Math.max(0,Y+Y*0.25*(2*Math.random()-1));if(N(`WebSocketTransport: Reconnecting in ${Math.round($)}ms (attempt ${this.reconnectAttempts}, ${Math.round(z/1000)}s elapsed)`),c8("error","cli_websocket_reconnect_attempt",{reconnectAttempts:this.reconnectAttempts}),this.isBridge)d("tengu_ws_transport_reconnecting",{attempt:this.reconnectAttempts,elapsedMs:z,delayMs:Math.round($)});this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},$)}else if(N(`WebSocketTransport: Reconnection time budget exhausted after ${Math.round(z/1000)}s for ${this.url.href}`,{level:"error"}),c8("error","cli_websocket_reconnect_exhausted",{reconnectAttempts:this.reconnectAttempts,elapsedMs:z}),this.state="closed",this.onCloseCallback)this.onCloseCallback(q)}close(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;this.stopPingInterval(),this.stopKeepaliveInterval(),z18(),this.state="closing",this.doDisconnect()}replayBufferedMessages(q){let K=this.messageBuffer.toArray();if(K.length===0)return;let _=0;if(q){let Y=K.findIndex(($)=>("uuid"in $)&&$.uuid===q);if(Y>=0){_=Y+1;let $=K.slice(_);if(this.messageBuffer.clear(),this.messageBuffer.addAll($),$.length===0)this.lastSentId=null;N(`WebSocketTransport: Evicted ${_} confirmed messages, ${$.length} remaining`),c8("info","cli_websocket_evicted_confirmed_messages",{evicted:_,remaining:$.length})}}let z=K.slice(_);if(z.length===0){N("WebSocketTransport: No new messages to replay"),c8("info","cli_websocket_no_messages_to_replay");return}N(`WebSocketTransport: Replaying ${z.length} buffered messages`),c8("info","cli_websocket_messages_to_replay",{count:z.length});for(let Y of z){let $=g6(Y)+`
7964`;if(!this.sendLine($)){this.handleConnectionError();break}}}isConnectedStatus(){return this.state==="connected"}isClosedStatus(){return this.state==="closed"}setOnData(q){this.onData=q}setOnConnect(q){this.onConnectCallback=q}setOnClose(q){this.onCloseCallback=q}getStateLabel(){return this.state}async write(q){if("uuid"in q&&typeof q.uuid==="string")this.messageBuffer.add(q),this.lastSentId=q.uuid;let K=g6(q)+`
7965`;if(this.state!=="connected")return;let _=this.sessionId?` session=${this.sessionId}`:"",z=this.getControlMessageDetailLabel(q);N(`WebSocketTransport: Sending message type=${q.type}${_}${z}`),this.sendLine(K)}getControlMessageDetailLabel(q){if(q.type==="control_request"){let{request_id:K,request:_}=q,z=_.subtype==="can_use_tool"?_.tool_name:"";return` subtype=${_.subtype} request_id=${K}${z?` tool=${z}`:""}`}if(q.type==="control_response"){let{subtype:K,request_id:_}=q.response;return` subtype=${K} request_id=${_}`}return""}startPingInterval(){this.stopPingInterval(),this.pongReceived=!0;let q=Date.now();this.pingInterval=setInterval(()=>{if(this.state==="connected"&&this.ws){let K=Date.now(),_=K-q;if(q=K,_>AQK){N(`WebSocketTransport: ${Math.round(_/1000)}s tick gap detected — process was suspended, forcing reconnect`),c8("info","cli_websocket_sleep_detected_on_ping",{gapMs:_}),this.handleConnectionError();return}if(!this.pongReceived){N("WebSocketTransport: No pong received, connection appears dead",{level:"error"}),c8("error","cli_websocket_pong_timeout"),this.handleConnectionError();return}this.pongReceived=!1;try{this.ws.ping?.()}catch(z){N(`WebSocketTransport: Ping failed: ${z}`,{level:"error"}),c8("error","cli_websocket_ping_failed")}}},qIY)}stopPingInterval(){if(this.pingInterval)clearInterval(this.pingInterval),this.pingInterval=null}startKeepaliveInterval(){if(this.stopKeepaliveInterval(),i6(process.env.CLAUDE_CODE_REMOTE))return;this.keepAliveInterval=setInterval(()=>{if(this.state==="connected"&&this.ws)try{this.ws.send(axY),this.lastActivityTime=Date.now(),N("WebSocketTransport: Sent periodic keep_alive data frame")}catch(q){N(`WebSocketTransport: Periodic keep_alive failed: ${q}`,{level:"error"}),c8("error","cli_websocket_keepalive_failed")}},KIY)}stopKeepaliveInterval(){if(this.keepAliveInterval)clearInterval(this.keepAliveInterval),this.keepAliveInterval=null}}var axY=`{"type":"keep_alive"}
7966`,sxY=1000,txY=1000,OQK=30000,exY=600000,qIY=1e4,KIY=300000,AQK,_IY;var Dz7=y(()=>{k8();_8();oY();m8();PI();qv();rR6();l8();AQK=OQK*2,_IY=new Set([1002,4001,4003])});function AIY(q){let K=q.protocol==="wss:"?"https:":"http:",_=q.pathname;if(_=_.replace("/ws/","/session/"),!_.endsWith("/events"))_=_.endsWith("/")?_+"events":_+"/events";return`${K}//${q.host}${_}${q.search}`}var zIY=100,YIY=15000,$IY=3000,A48;var fz7=y(()=>{CK();_8();oY();nC();Wz7();Dz7();A48=class A48 extends $48{postUrl;uploader;streamEventBuffer=[];streamEventTimer=null;constructor(q,K={},_,z,Y){super(q,K,_,z,Y);let{maxConsecutiveFailures:$,onBatchDropped:A}=Y??{};this.postUrl=AIY(q),this.uploader=new CJ6({maxBatchSize:500,maxQueueSize:1e5,baseDelayMs:500,maxDelayMs:8000,jitterMs:1000,maxConsecutiveFailures:$,onBatchDropped:(O,w)=>{c8("error","cli_hybrid_batch_dropped_max_failures",{batchSize:O,failures:w}),A?.(O,w)},send:(O)=>this.postOnce(O)}),N(`HybridTransport: POST URL = ${this.postUrl}`),c8("info","cli_hybrid_transport_initialized")}async write(q){if(q.type==="stream_event"){if(this.streamEventBuffer.push(q),!this.streamEventTimer)this.streamEventTimer=setTimeout(()=>this.flushStreamEvents(),zIY);return}return await this.uploader.enqueue([...this.takeStreamEvents(),q]),this.uploader.flush()}async writeBatch(q){return await this.uploader.enqueue([...this.takeStreamEvents(),...q]),this.uploader.flush()}get droppedBatchCount(){return this.uploader.droppedBatchCount}flush(){return this.uploader.enqueue(this.takeStreamEvents()),this.uploader.flush()}takeStreamEvents(){if(this.streamEventTimer)clearTimeout(this.streamEventTimer),this.streamEventTimer=null;let q=this.streamEventBuffer;return this.streamEventBuffer=[],q}flushStreamEvents(){this.streamEventTimer=null,this.uploader.enqueue(this.takeStreamEvents())}close(){if(this.streamEventTimer)clearTimeout(this.streamEventTimer),this.streamEventTimer=null;this.streamEventBuffer=[];let q=this.uploader,K;Promise.race([q.flush(),new Promise((_)=>{K=setTimeout(_,$IY)})]).finally(()=>{clearTimeout(K),q.close()}),super.close()}async postOnce(q){let K=WD();if(!K){N("HybridTransport: No session token available for POST"),c8("warn","cli_hybrid_post_no_token");return}let _={Authorization:`Bearer ${K}`,"Content-Type":"application/json"},z;try{z=await $1.post(this.postUrl,{events:q},{headers:_,validateStatus:()=>!0,timeout:YIY})}catch(Y){throw N(`HybridTransport: POST error: ${Y.message}`),c8("warn","cli_hybrid_post_network_error"),Y}if(z.status>=200&&z.status<300){N(`HybridTransport: POST success count=${q.length}`);return}if(z.status>=400&&z.status<500&&z.status!==429){N(`HybridTransport: POST returned ${z.status} (permanent), dropping`),c8("warn","cli_hybrid_post_client_error",{status:z.status});return}throw N(`HybridTransport: POST returned ${z.status} (retryable)`),c8("warn","cli_hybrid_post_retryable_error",{status:z.status}),Error(`POST failed with ${z.status}`)}}});class Zz7{inflight=null;pending=null;closed=!1;config;constructor(q){this.config=q}enqueue(q){if(this.closed)return;this.pending=this.pending?wQK(this.pending,q):q,this.drain()}close(){this.closed=!0,this.pending=null}async drain(){if(this.inflight||this.closed)return;if(!this.pending)return;let q=this.pending;this.pending=null,this.inflight=this.sendWithRetry(q).then(()=>{if(this.inflight=null,this.pending&&!this.closed)this.drain()})}async sendWithRetry(q){let K=q,_=0;while(!this.closed){if(await this.config.send(K))return;if(_++,await R7(this.retryDelay(_)),this.pending&&!this.closed)K=wQK(K,this.pending),this.pending=null}}retryDelay(q){let K=Math.min(this.config.baseDelayMs*2**(q-1),this.config.maxDelayMs),_=Math.random()*this.config.jitterMs;return K+_}}function wQK(q,K){let _={...q};for(let[z,Y]of Object.entries(K))if((z==="external_metadata"||z==="internal_metadata")&&_[z]&&typeof _[z]==="object"&&typeof Y==="object"&&Y!==null)_[z]={..._[z],...Y};else _[z]=Y;return _}var jQK=()=>{};import{randomUUID as HQK}from"crypto";function JQK(){return!0}function HIY(){return{byMessage:new Map,scopeToMessage:new Map}}function $d8(q){return`${q.session_id}:${q.parent_tool_use_id??""}`}function JIY(q,K){let _=[],z=new Map;for(let Y of q)switch(Y.event.type){case"message_start":{let $=Y.event.message.id,A=K.scopeToMessage.get($d8(Y));if(A)K.byMessage.delete(A);K.scopeToMessage.set($d8(Y),$),K.byMessage.set($,[]),_.push(Y);break}case"content_block_delta":{if(Y.event.delta.type!=="text_delta"){_.push(Y);break}let $=K.scopeToMessage.get($d8(Y)),A=$?K.byMessage.get($):void 0;if(!A){_.push(Y);break}let O=A[Y.event.index]??=[];O.push(Y.event.delta.text);let w=z.get(O);if(w){w.event.delta.text=O.join("");break}let j={type:"stream_event",uuid:Y.uuid,session_id:Y.session_id,parent_tool_use_id:Y.parent_tool_use_id,event:{type:"content_block_delta",index:Y.event.index,delta:{type:"text_delta",text:O.join("")}}};z.set(O,j),_.push(j);break}default:_.push(Y)}return _}function MIY(q,K){q.byMessage.delete(K.message.id);let _=$d8(K);if(q.scopeToMessage.get(_)===K.message.id)q.scopeToMessage.delete(_)}class O48{workerEpoch=0;heartbeatIntervalMs;heartbeatJitterFraction;heartbeatTimer=null;heartbeatInFlight=!1;closed=!1;consecutiveAuthFailures=0;currentState=null;sessionBaseUrl;sessionId;http=c1q({keepAlive:!0});streamEventBuffer=[];streamEventTimer=null;streamTextAccumulator=HIY();workerState;eventUploader;internalEventUploader;deliveryUploader;onEpochMismatch;getAuthHeaders;constructor(q,K,_){if(this.onEpochMismatch=_?.onEpochMismatch??(()=>{process.exit(1)}),this.heartbeatIntervalMs=_?.heartbeatIntervalMs??OIY,this.heartbeatJitterFraction=_?.heartbeatJitterFraction??0,this.getAuthHeaders=_?.getAuthHeaders??SE8,K.protocol!=="http:"&&K.protocol!=="https:")throw Error(`CCRClient: Expected http(s) URL, got ${K.protocol}`);let z=K.pathname.replace(/\/$/,"");this.sessionBaseUrl=`${K.protocol}//${K.host}${z}`,this.sessionId=z.split("/").pop()||"",this.workerState=new Zz7({send:(Y)=>this.request("put","/worker",{worker_epoch:this.workerEpoch,...Y},"PUT worker").then(($)=>$.ok),baseDelayMs:500,maxDelayMs:30000,jitterMs:500}),this.eventUploader=new CJ6({maxBatchSize:100,maxBatchBytes:10485760,maxQueueSize:1e5,send:async(Y)=>{let $=await this.request("post","/worker/events",{worker_epoch:this.workerEpoch,events:Y},"client events");if(!$.ok)throw new zC6("client event POST failed",$.retryAfterMs)},baseDelayMs:500,maxDelayMs:30000,jitterMs:500}),this.internalEventUploader=new CJ6({maxBatchSize:100,maxBatchBytes:10485760,maxQueueSize:200,send:async(Y)=>{let $=await this.request("post","/worker/internal-events",{worker_epoch:this.workerEpoch,events:Y},"internal events");if(!$.ok)throw new zC6("internal event POST failed",$.retryAfterMs)},baseDelayMs:500,maxDelayMs:30000,jitterMs:500}),this.deliveryUploader=new CJ6({maxBatchSize:64,maxQueueSize:64,send:async(Y)=>{let $=await this.request("post","/worker/events/delivery",{worker_epoch:this.workerEpoch,updates:Y.map((A)=>({event_id:A.eventId,status:A.status}))},"delivery batch");if(!$.ok)throw new zC6("delivery POST failed",$.retryAfterMs)},baseDelayMs:500,maxDelayMs:30000,jitterMs:500}),q.setOnEvent((Y)=>{this.reportDelivery(Y.event_id,"received")})}async initialize(q){let K=Date.now();if(Object.keys(this.getAuthHeaders()).length===0)throw new YC6("no_auth_headers");if(q===void 0){let A=process.env.CLAUDE_CODE_WORKER_EPOCH;q=A?parseInt(A,10):NaN}if(isNaN(q))throw new YC6("missing_epoch");this.workerEpoch=q;let _=this.getWorkerState();if(!(await this.request("put","/worker",{worker_status:"idle",worker_epoch:this.workerEpoch,external_metadata:{pending_action:null,task_summary:null}},"PUT worker (init)")).ok)throw new YC6("worker_register_failed");this.currentState="idle",this.startHeartbeat(),Yp8(()=>{this.writeEvent({type:"keep_alive"})}),N(`CCRClient: initialized, epoch=${this.workerEpoch}`),c8("info","cli_worker_lifecycle_initialized",{epoch:this.workerEpoch,duration_ms:Date.now()-K});let{metadata:Y,durationMs:$}=await _;if(!this.closed)c8("info","cli_worker_state_restored",{duration_ms:$,had_state:Y!==null});return Y}async getWorkerState(){let q=Date.now(),K=this.getAuthHeaders();if(Object.keys(K).length===0)return{metadata:null,durationMs:0};return{metadata:(await this.getWithRetry(`${this.sessionBaseUrl}/worker`,K,"worker_state"))?.worker?.external_metadata??null,durationMs:Date.now()-q}}async request(q,K,_,z,{timeout:Y=1e4}={}){let $=this.getAuthHeaders();if(Object.keys($).length===0)return{ok:!1};try{let A=await this.http[q](`${this.sessionBaseUrl}${K}`,_,{headers:{...$,"Content-Type":"application/json","anthropic-version":"2023-06-01","User-Agent":n$()},validateStatus:JQK,timeout:Y});if(A.status>=200&&A.status<300)return this.consecutiveAuthFailures=0,{ok:!0};if(A.status===409)this.handleEpochMismatch();if(A.status===401||A.status===403){let O=WD(),w=O?h_7(O):null;if(w!==null&&w*1000<Date.now())N(`CCRClient: session_token expired (exp=${new Date(w*1000).toISOString()}) — no refresh was delivered, exiting`,{level:"error"}),c8("error","cli_worker_token_expired_no_refresh"),this.onEpochMismatch();if(this.consecutiveAuthFailures++,this.consecutiveAuthFailures>=jIY)N(`CCRClient: ${this.consecutiveAuthFailures} consecutive auth failures with a valid-looking token — server-side auth unrecoverable, exiting`,{level:"error"}),c8("error","cli_worker_auth_failures_exhausted"),this.onEpochMismatch()}if(N(`CCRClient: ${z} returned ${A.status}`,{level:"warn"}),c8("warn","cli_worker_request_failed",{method:q,path:K,status:A.status}),A.status===429){let O=A.headers?.["retry-after"],w=typeof O==="string"?parseInt(O,10):NaN;if(!isNaN(w)&&w>=0)return{ok:!1,retryAfterMs:w*1000}}return{ok:!1}}catch(A){return N(`CCRClient: ${z} failed: ${d6(A)}`,{level:"warn"}),c8("warn","cli_worker_request_error",{method:q,path:K,error_code:s1(A)}),{ok:!1}}}reportState(q,K){if(q===this.currentState&&!K)return;this.currentState=q,this.workerState.enqueue({worker_status:q,requires_action_details:K?{tool_name:K.tool_name,action_description:K.action_description,request_id:K.request_id}:null})}reportMetadata(q){this.workerState.enqueue({external_metadata:q})}handleEpochMismatch(){N("CCRClient: Epoch mismatch (409), shutting down",{level:"error"}),c8("error","cli_worker_epoch_mismatch"),this.onEpochMismatch()}startHeartbeat(){this.stopHeartbeat();let q=()=>{let _=this.heartbeatIntervalMs*this.heartbeatJitterFraction*(2*Math.random()-1);this.heartbeatTimer=setTimeout(K,this.heartbeatIntervalMs+_)},K=()=>{if(this.sendHeartbeat(),this.heartbeatTimer===null)return;q()};q()}stopHeartbeat(){if(this.heartbeatTimer)clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null}async sendHeartbeat(){if(this.heartbeatInFlight)return;this.heartbeatInFlight=!0;try{if((await this.request("post","/worker/heartbeat",{session_id:this.sessionId,worker_epoch:this.workerEpoch},"Heartbeat",{timeout:5000})).ok)N("CCRClient: Heartbeat sent")}finally{this.heartbeatInFlight=!1}}async writeEvent(q){if(q.type==="stream_event"){if(this.streamEventBuffer.push(q),!this.streamEventTimer)this.streamEventTimer=setTimeout(()=>void this.flushStreamEventBuffer(),wIY);return}if(await this.flushStreamEventBuffer(),q.type==="assistant")MIY(this.streamTextAccumulator,q);await this.eventUploader.enqueue(this.toClientEvent(q))}toClientEvent(q){let K=q;return{payload:{...K,uuid:typeof K.uuid==="string"?K.uuid:HQK()}}}async flushStreamEventBuffer(){if(this.streamEventTimer)clearTimeout(this.streamEventTimer),this.streamEventTimer=null;if(this.streamEventBuffer.length===0)return;let q=this.streamEventBuffer;this.streamEventBuffer=[];let K=JIY(q,this.streamTextAccumulator);await this.eventUploader.enqueue(K.map((_)=>({payload:_,ephemeral:!0})))}async writeInternalEvent(q,K,{isCompaction:_=!1,agentId:z}={}){let Y={payload:{type:q,...K,uuid:typeof K.uuid==="string"?K.uuid:HQK()},..._&&{is_compaction:!0},...z&&{agent_id:z}};await this.internalEventUploader.enqueue(Y)}flushInternalEvents(){return this.internalEventUploader.flush()}async flush(){return await this.flushStreamEventBuffer(),this.eventUploader.flush()}async readInternalEvents(){return this.paginatedGet("/worker/internal-events",{},"internal_events")}async readSubagentInternalEvents(){return this.paginatedGet("/worker/internal-events",{subagents:"true"},"subagent_events")}async paginatedGet(q,K,_){let z=this.getAuthHeaders();if(Object.keys(z).length===0)return null;let Y=[],$;do{let A=new URL(`${this.sessionBaseUrl}${q}`);for(let[w,j]of Object.entries(K))A.searchParams.set(w,j);if($)A.searchParams.set("cursor",$);let O=await this.getWithRetry(A.toString(),z,_);if(!O)return null;Y.push(...O.data??[]),$=O.next_cursor}while($);return N(`CCRClient: Read ${Y.length} internal events from ${q}${K.subagents?" (subagents)":""}`),Y}async getWithRetry(q,K,_){for(let z=1;z<=10;z++){let Y;try{Y=await this.http.get(q,{headers:{...K,"anthropic-version":"2023-06-01","User-Agent":n$()},validateStatus:JQK,timeout:30000})}catch($){if(N(`CCRClient: GET ${q} failed (attempt ${z}/10): ${d6($)}`,{level:"warn"}),z<10){let A=Math.min(500*2**(z-1),30000)+Math.random()*500;await R7(A)}continue}if(Y.status>=200&&Y.status<300)return Y.data;if(Y.status===409)this.handleEpochMismatch();if(N(`CCRClient: GET ${q} returned ${Y.status} (attempt ${z}/10)`,{level:"warn"}),z<10){let $=Math.min(500*2**(z-1),30000)+Math.random()*500;await R7($)}}return N("CCRClient: GET retries exhausted",{level:"error"}),c8("error","cli_worker_get_retries_exhausted",{context:_}),null}reportDelivery(q,K){this.deliveryUploader.enqueue({eventId:q,status:K})}getWorkerEpoch(){return this.workerEpoch}get internalEventsPending(){return this.internalEventUploader.pendingCount}close(){if(this.closed=!0,this.stopHeartbeat(),z18(),this.streamEventTimer)clearTimeout(this.streamEventTimer),this.streamEventTimer=null;this.streamEventBuffer=[],this.streamTextAccumulator.byMessage.clear(),this.streamTextAccumulator.scopeToMessage.clear(),this.workerState.close(),this.eventUploader.close(),this.internalEventUploader.close(),this.deliveryUploader.close()}}var OIY=20000,wIY=100,YC6,jIY=10;var Gz7=y(()=>{BQ8();_8();oY();y8();qv();rR6();nC();Wz7();jQK();YC6=class YC6 extends Error{reason;constructor(q){super(`CCRClient init failed: ${q}`);this.reason=q}}});function vIY(){return!0}function kIY(q){let K=[],_=0,z;while((z=q.indexOf(`
7967
7968`,_))!==-1){let Y=q.slice(_,z);if(_=z+2,!Y.trim())continue;let $={},A=!1;for(let O of Y.split(`

Callers

nothing calls this directly

Calls 6

requestMethod · 0.95
reportDeliveryMethod · 0.95
replaceMethod · 0.45
popMethod · 0.45
thenMethod · 0.45
setOnEventMethod · 0.45

Tested by

no test coverage detected