import{q as j,r as v}from"./cli-0.5.3-j3f3sebz.mjs";import{Uf as C}from"./cli-0.5.3-5bnpvchp.mjs";import{VP as S,WP as b}from"./cli-0.5.3-me9jkw92.mjs";import{hY as R,jY as E}from"./cli-0.5.3-g0svn6bx.mjs";import{D5 as k,V5 as h}from"./cli-0.5.3-vpcrbd8n.mjs";import{Eca as Z,Gca as U,Hca as w,Ica as z}from"./cli-0.5.3-kavpx97n.mjs";import{Hda as L,Uda as I}from"./cli-0.5.3-1rg2r7n7.mjs";import{Nfa as M,Qfa as l,qfa as D,rfa as T,vfa as u}from"./cli-0.5.3-n3cxyxpg.mjs";import{Ega as f,Lga as p}from"./cli-0.5.3-c8bcrqa4.mjs";U();I();z();E();C();var F={init_retry_max_attempts:3,init_retry_base_delay_ms:500,init_retry_jitter_fraction:0.25,init_retry_max_delay_ms:4000,http_timeout_ms:1e4,uuid_dedup_buffer_size:2000,heartbeat_interval_ms:20000,heartbeat_jitter_fraction:0.1,token_refresh_buffer_ms:300000,teardown_archive_timeout_ms:1500,connect_timeout_ms:15000,min_version:"0.0.0",should_show_app_upgrade_message:!1},m=w(()=>Z.object({init_retry_max_attempts:Z.number().int().min(1).max(10).default(3),init_retry_base_delay_ms:Z.number().int().min(100).default(500),init_retry_jitter_fraction:Z.number().min(0).max(1).default(0.25),init_retry_max_delay_ms:Z.number().int().min(500).default(4000),http_timeout_ms:Z.number().int().min(2000).default(1e4),uuid_dedup_buffer_size:Z.number().int().min(100).max(50000).default(2000),heartbeat_interval_ms:Z.number().int().min(5000).max(30000).default(20000),heartbeat_jitter_fraction:Z.number().min(0).max(0.5).default(0.1),token_refresh_buffer_ms:Z.number().int().min(30000).max(1800000).default(300000),teardown_archive_timeout_ms:Z.number().int().min(500).max(2000).default(1500),connect_timeout_ms:Z.number().int().min(5000).max(60000).default(15000),min_version:Z.string().refine((J)=>{try{return R(J,"0.0.0"),!0}catch{return!1}}).default("0.0.0"),should_show_app_upgrade_message:Z.boolean().default(!1)}));async function y(){let J=await L("tengu_bridge_repl_v2_config",F),K=m().safeParse(J);return K.success?K.data:F}async function o(){let J=await y();if(J.min_version&&R("99.0.0",J.min_version))return`Your version of Claudio (99.0.0) is too old for Remote Control.
Version ${J.min_version} or higher is required. Run \`claudio update\` to update.`;return null}h();u();function JJ(J){let K=Buffer.from(J,"base64url").toString("utf-8"),X=T(K);if(!X||typeof X!=="object"||!("version"in X)||X.version!==1)throw Error(`Unsupported work secret version: ${X&&typeof X==="object"&&"version"in X?X.version:"unknown"}`);let Y=X;if(typeof Y.session_ingress_token!=="string"||Y.session_ingress_token.length===0)throw Error("Invalid work secret: missing or empty session_ingress_token");if(typeof Y.api_base_url!=="string")throw Error("Invalid work secret: missing api_base_url");return X}function KJ(J,K){let X=new URL(J).hostname,Y=X==="localhost"||X==="127.0.0.1",x=Y?"ws":"wss",H=Y?"v2":"v1",P=J.replace(/^https?:\/\//,"").replace(/\/+$/,"");return`${x}://${P}/${H}/session_ingress/ws/${K}`}function QJ(J,K){if(J===K)return!0;let X=J.slice(J.lastIndexOf("_")+1),Y=K.slice(K.lastIndexOf("_")+1);return X.length>=4&&X===Y}function XJ(J,K){return`${J.replace(/\/+$/,"")}/v1/code/sessions/${K}`}async function B(J,K){let X=await k.post(`${J}/worker/register`,{},{headers:{Authorization:`Bearer ${K}`,"Content-Type":"application/json","anthropic-version":"2023-06-01"},timeout:1e4}),Y=X.data?.worker_epoch,x=typeof Y==="string"?Number(Y):Y;if(typeof x!=="number"||!Number.isFinite(x)||!Number.isSafeInteger(x))throw Error(`registerWorker: invalid worker_epoch in response: ${D(X.data)}`);return x}l();p();b();function WJ(J){return{write:(K)=>J.write(K),writeBatch:(K)=>J.writeBatch(K),close:()=>J.close(),isConnectedStatus:()=>J.isConnectedStatus(),getStateLabel:()=>J.getStateLabel(),setOnData:(K)=>J.setOnData(K),setOnClose:(K)=>J.setOnClose(K),setOnConnect:(K)=>J.setOnConnect(K),connect:()=>void J.connect(),getLastSequenceNum:()=>0,get droppedBatchCount(){return J.droppedBatchCount},reportState:()=>{},reportMetadata:()=>{},reportDelivery:()=>{},flush:()=>Promise.resolve()}}async function HJ(J){let{sessionUrl:K,ingressToken:X,sessionId:Y,initialSequenceNum:x,getAuthToken:H}=J,P;if(H)P=()=>{let Q=H();if(!Q)return{};return{Authorization:`Bearer ${Q}`}};else S(X);let O=J.epoch??await B(K,X);M(`[bridge:repl] CCR v2: worker sessionId=${Y} epoch=${O}${J.epoch!==void 0?" (from /bridge)":" (via registerWorker)"}`);let V=new URL(K);V.pathname=V.pathname.replace(/\/$/,"")+"/worker/events/stream";let q=new v(V,{},Y,void 0,x,P),G,$=new j(q,new URL(K),{getAuthHeaders:P,heartbeatIntervalMs:J.heartbeatIntervalMs,heartbeatJitterFraction:J.heartbeatJitterFraction,onEpochMismatch:()=>{M("[bridge:repl] CCR v2: epoch superseded (409) — closing for poll-loop recovery");try{$.close(),q.close(),G?.(4090)}catch(Q){M(`[bridge:repl] CCR v2: error during epoch-mismatch cleanup: ${f(Q)}`,{level:"error"})}throw Error("epoch superseded")}});q.setOnEvent((Q)=>{$.reportDelivery(Q.event_id,"received"),$.reportDelivery(Q.event_id,"processed")});let _,N=!1,A=!1;return{write(Q){return $.writeEvent(Q)},async writeBatch(Q){for(let W of Q){if(A)break;await $.writeEvent(W)}},close(){A=!0,$.close(),q.close()},isConnectedStatus(){return N},getStateLabel(){if(q.isClosedStatus())return"closed";if(q.isConnectedStatus())return N?"connected":"init";return"connecting"},setOnData(Q){q.setOnData(Q)},setOnClose(Q){G=Q,q.setOnClose((W)=>{$.close(),Q(W??4092)})},setOnConnect(Q){_=Q},getLastSequenceNum(){return q.getLastSequenceNum()},droppedBatchCount:0,reportState(Q){$.reportState(Q)},reportMetadata(Q){$.reportMetadata(Q)},reportDelivery(Q,W){$.reportDelivery(Q,W)},flush(){return $.flush()},connect(){if(!J.outboundOnly)q.connect();$.initialize(O).then(()=>{N=!0,M(`[bridge:repl] v2 transport ready for writes (epoch=${O}, sse=${q.isConnectedStatus()?"open":"opening"})`),_?.()},(Q)=>{M(`[bridge:repl] CCR v2 initialize failed: ${f(Q)}`,{level:"error"}),$.close(),q.close(),G?.(4091)})}}}class g{_active=!1;_pending=[];get active(){return this._active}get pendingCount(){return this._pending.length}start(){this._active=!0}end(){return this._active=!1,this._pending.splice(0)}enqueue(...J){if(!this._active)return!1;return this._pending.push(...J),!0}drop(){this._active=!1;let J=this._pending.length;return this._pending.length=0,J}deactivate(){this._active=!1}}
export{y as e,o as f,JJ as g,KJ as h,QJ as i,XJ as j,WJ as k,HJ as l,g as m};
