@cortexkit/pi-openai-auth 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,7 +11,7 @@ This package is part of the CortexKit OpenAI Auth monorepo, which supports both
11
11
  Install with Pi's package manager:
12
12
 
13
13
  ```bash
14
- pi install npm:@cortexkit/pi-openai-auth@0.11.0
14
+ pi install npm:@cortexkit/pi-openai-auth@0.11.1
15
15
  ```
16
16
 
17
17
  For an unpinned install:
package/dist/index.js CHANGED
@@ -207,7 +207,7 @@ Code: \`${J}\`
207
207
 
208
208
  ${G[J]??"The server returned a no-op result. No reset was confirmed."}`)}async function E6($,Z){let z=[Z.resolveResetTarget?void 0:"resolveResetTarget",Z.fetchImpl?void 0:"fetchImpl",Z.now?void 0:"now",Z.randomUUID?void 0:"randomUUID",Z.refreshResetTargetQuota?void 0:"refreshResetTargetQuota"].filter((Q)=>Q!==void 0);if(z.length>0)return _.warn("reset command dependencies unwired",{missingDeps:z}),{command:y0,text:`## Reset credit
209
209
 
210
- Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let X=Z,J=$.trim().split(/\s+/).filter(Boolean),G=J[0];if(!G||G==="refresh"){let Y=["main",...((await Z.loadAccounts(m(Z)))?.accounts??[]).filter((B)=>B.enabled!==!1&&B.type==="oauth").map((B)=>B.id)];_.debug("reset accounts stage requested",{accountKeys:Y});let W=await Promise.all(Y.map((B)=>b$(B,X)));return _.debug("reset accounts stage built",{rows:W.map((B)=>({accountKey:B.accountKey,eligible:B.eligible,reason:B.reason,usedPercent:B.usedPercent,availableCount:B.availableCount,applicableAvailableCount:B.applicableAvailableCount}))}),{command:y0,text:w6(W),knobs:{stage:"accounts",accounts:W}}}if(G==="select"){let Q=Z1(J[1]);if(!Q||!i(Q)||J.length!==2)return g("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let Y=await b$(Q,X);if(!Y.eligible)return g(Q,"not_eligible",S$(Y));return{command:y0,text:S$(Y),knobs:{stage:"confirm",preview:Y}}}if(G==="confirm"||G==="retry"){let Q=Z1(J[1]),Y=Z1(J[2]);if(!Q||!i(Q)||!Y||J.length!==3)return g(Q??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);_.info("reset redemption decision",{accountKey:Q,action:G}),_.debug("reset redemption identity binding",{accountKey:Q,expectedChatgptAccountId:Y});try{let W=await I$({configPath:Z.accountStoragePath,statePath:Z.accountStatePath,mutateAccountsFn:G0,loadAccountsFn:Z.loadAccounts,now:X.now,randomUUID:X.randomUUID,fetchImpl:X.fetchImpl,resolveTarget:X.resolveResetTarget,fetchUsage:(B)=>d8({accessToken:B.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:Q,expectedChatgptAccountId:Y,retry:G==="retry"});return _.info("reset redemption outcome",{accountKey:Q,code:W.outcome.kind}),w$(W,X,Y)}catch(W){let B=f6(Q,W,Y);return _.info("reset redemption outcome",{accountKey:Q,code:B.knobs.code}),B}}return g("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var y6=new Set(["access","refresh","apikey","authheader","password","secret"]);function v6($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(y6.has(Z))return!0;return Z.endsWith("token")}function Z8($,Z,z){if(Array.isArray($))return $.map((J,G)=>Z8(J,`${Z}[${G}]`,z));if(!R$($))return $;let X={};for(let[J,G]of Object.entries($)){if(v6(J)){z.push(`${Z}.${J}`);continue}X[J]=Z8(G,`${Z}.${J}`,z)}return X}async function z1($,Z,z,X={}){let J=await h6($,Z,z,X),G=[],Q=Z8(J.knobs,"knobs",G);if(G.length>0)return _.warn("credential-shaped knob stripped before RPC",{command:$,fields:G}),{...J,knobs:Q};return J}async function h6($,Z,z,X){switch($){case"openai-quota":return T6(z);case"openai-account":return C6(Z,z);case"openai-routing":return b6(Z,z);case"openai-reset":return E6(Z,z);default:{let J=X[$];if(!J)throw Error(`unhandled command: ${$}`);return J(Z,z)}}}import{readdirSync as x9,statSync as F9}from"node:fs";import{tmpdir as I9,userInfo as R9}from"node:os";import{join as p0}from"node:path";import{debuglog as t6}from"node:util";import{createHmac as l6,randomBytes as d6,timingSafeEqual as i6}from"node:crypto";import u6 from"node:net";var p=2,G8=21,Q8=5,X1=67108864,H;(function($){$[$.Request=0]="Request",$[$.Response=1]="Response",$[$.Push=2]="Push",$[$.StreamData=3]="StreamData",$[$.StreamEnd=4]="StreamEnd",$[$.Error=5]="Error",$[$.Cancel=6]="Cancel",$[$.Ping=7]="Ping",$[$.Pong=8]="Pong",$[$.Hello=9]="Hello",$[$.HelloAck=10]="HelloAck",$[$.Goodbye=11]="Goodbye"})(H||(H={}));var f$=H.Goodbye;function E$($){return $===H.Cancel||$===H.Ping||$===H.Pong||$===H.Goodbye}var C;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(C||(C={}));var w;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(w||(w={}));var m6=1,y$=6,J1=1,g6=8,v$=48,G1=4,h$=192;function v($,Z,z,X=w.Normal){let J=0;if($)J|=m6;if(J|=Z<<J1,z)J|=g6;return J|=X<<G1,J}function m$($){let Z=new Uint8Array(21),z=new DataView(Z.buffer);return z.setUint32(0,$.len,!0),Z[4]=$.ver,Z[5]=$.ty,Z[6]=$.flags,z.setUint16(7,$.channel,!0),z.setUint32(9,$.epoch,!0),z.setBigUint64(13,$.corr,!0),Z}class x extends Error{code;constructor($,Z){super($);this.code=Z,this.name="DecodeError"}}function p6($){let Z=$.len>>>0,z=$.ver>>>0&255,X=$.ty>>>0&255,J=$.flags>>>0&255,G=$.channel>>>0&65535,Q=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),z!==2)throw new x(`unsupported envelope version ${z}`,"unsupported_version");if(X>f$)throw new x(`unknown frame type byte ${X}`,"unknown_frame_type");let Y=X;if((J&h$)!==0)throw new x(`reserved flag bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((J&y$)>>J1===3)throw new x(`reserved priority bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(J&v$)>>G1;if(W===3)throw new x(`reserved admission class set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===w.Sheddable&&Y!==H.Push&&Y!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[Y]} in flags 0b${J.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(G===0&&Q!==0)throw new x(`control channel carried nonzero epoch ${Q}`,"nonzero_epoch_on_control_channel");if(E$(Y)&&Z!==0)throw new x(`pure-header frame ${H[Y]} declared non-zero body length ${Z}`,"pure_header_frame_with_body")}function Q1($){if($.length<5)throw new x(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let Z=$[4];if(Z!==2)throw new x(`unsupported envelope version ${Z}`,"unsupported_version");if($.length<21)throw new x(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let z=new DataView($.buffer,$.byteOffset,$.byteLength),X=z.getUint32(0,!0),J=$[5];if(J>f$)throw new x(`unknown frame type byte ${J}`,"unknown_frame_type");let G=J,Q=$[6];if((Q&h$)!==0)throw new x(`reserved flag bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((Q&y$)>>J1===3)throw new x(`reserved priority bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Y=(Q&v$)>>G1;if(Y===3)throw new x(`reserved admission class set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Y===w.Sheddable&&G!==H.Push&&G!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[G]} in flags 0b${Q.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let W=z.getUint16(7,!0),B=z.getUint32(9,!0);if(W===0&&B!==0)throw new x(`control channel carried nonzero epoch ${B}`,"nonzero_epoch_on_control_channel");if(E$(G)&&X!==0)throw new x(`pure-header frame ${H[G]} declared non-zero body length ${X}`,"pure_header_frame_with_body");return{len:X,ver:Z,ty:G,flags:Q,channel:W,epoch:B,corr:z.getBigUint64(13,!0)}}function E($,Z,z,X,J,G){return a(2,$,Z,z,X,J,G)}function a($,Z,z,X,J,G,Q){if(Q.length>67108864)throw new x(`frame body ${Q.length} exceeds max 67108864`,"frame_body_too_large");let Y={len:Q.length,ver:$,ty:Z,flags:z,channel:X,epoch:J,corr:G};return p6(Y),{header:Y,body:Q}}function t($){if($.header.len!==$.body.length)throw new x(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let Z=m$($.header),z=new Uint8Array(Z.length+$.body.length);return z.set(Z,0),z.set($.body,Z.length),z}class Z0 extends Error{}class s extends Error{}class o extends Error{cause;constructor($,Z){super($);this.cause=Z}}class Q0 extends Error{cause;constructor($,Z){super($);this.cause=Z}}function g$($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var p$=Symbol("subc.socket.writeBorrowed"),u$=Symbol("subc.socket.writeTrackedBorrowed");function r($,Z,z){let X=$[p$];return X?X.call($,Z,z):$.write(Z,z)}function Y1($,Z,z){let X=$[u$];return X?X.call($,Z,z):$.writeTracked(Z,z)}class H0{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor($){this.sock=$,$.on("data",(z)=>{this.chunks.push(z),this.buffered+=z.length,this.tryServe()});let Z=(z)=>{if(!this.closedErr)this.closedErr=z;this.tryServe()};$.on("error",(z)=>Z(z instanceof Error?z:Error(String(z)))),$.on("end",()=>Z(new Z0("subc closed the connection"))),$.on("close",()=>Z(new Z0("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,Z,z){return new Promise((X,J)=>{let G=u6.connect({host:$,port:Z});G.setNoDelay(!0);let Q=setTimeout(()=>{G.destroy(),J(new s(`timed out connecting to ${$}:${Z}`))},Math.max(0,z-Date.now()));G.once("connect",()=>{clearTimeout(Q),X(new H0(G))}),G.once("error",(Y)=>{clearTimeout(Q),J(Y)})})}async readFrame($,Z,z){let X=await this.readExact(Q8,$),J=X[4];if(J!==p)throw new x(`unsupported envelope version ${J}`,"unsupported_version");let G=await this.readExact(G8-Q8,$),Q=new Uint8Array(G8);Q.set(X),Q.set(G,Q8);let Y=Q1(Q);if(Y.len>X1)throw new x(`frame body ${Y.len} exceeds max ${X1}`,"frame_body_too_large");z?.();let W=typeof Z==="number"?Z:Date.now()+Z.afterHeaderMs,B=Y.len===0?new Uint8Array(0):await this.readExact(Y.len,W);return{header:Y,body:B}}readExact($,Z){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((z,X)=>{let J=null;if(Number.isFinite(Z)){let G=Z-Date.now();if(G<=0){X(new s(`timed out waiting for ${$} bytes`));return}J=setTimeout(()=>{this.waiter=null,X(new s(`timed out waiting for ${$} bytes`))},G)}this.waiter={need:$,resolve:z,reject:X,timer:J},this.tryServe()})}async write($,Z){await this.writeBuffer(Buffer.from($),Z)}writeTracked($,Z){return this.writeTrackedBuffer(Buffer.from($),Z)}async[p$]($,Z){await this.writeBuffer(g$($),Z)}[u$]($,Z){return this.writeTrackedBuffer(g$($),Z)}async writeBuffer($,Z){try{await this.writeTrackedBuffer($,Z).completed}catch(z){if(z instanceof o||z instanceof Q0)throw z.cause??z;throw z}}writeTrackedBuffer($,Z){if(this.closedErr)return{queued:!1,completed:Promise.reject(new o("subc socket was closed before bytes could be queued",this.closedErr))};let z=!1,X=!1,J=null,G=new Promise((Q,Y)=>{let W=(V)=>{if(X)return;if(X=!0,J)clearTimeout(J);V()},B=Z-Date.now();if(B<=0){W(()=>Y(new o("timed out before bytes could be queued to subc",new s("timed out writing to subc"))));return}J=setTimeout(()=>{let V=new s("timed out writing to subc");W(()=>Y(z?new Q0("timed out after bytes were handed to the subc socket",V):new o("timed out before bytes could be queued to subc",V)))},B);try{this.sock.write($,(V)=>{W(()=>{if(V)Y(new Q0("subc socket reported a write error after bytes were handed to the socket",V instanceof Error?V:Error(String(V))));else Q()})}),z=!0}catch(V){W(()=>Y(new o("subc socket write threw before bytes could be queued",V instanceof Error?V:Error(String(V)))))}});return{queued:z,completed:G}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let Z=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(Z);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let Z=Buffer.allocUnsafe($),z=0;while(z<$){let X=this.chunks[0],J=$-z;if(X.length<=J)X.copy(Z,z),z+=X.length,this.chunks.shift();else X.copy(Z,z,0,J),this.chunks[0]=X.subarray(J),z+=J}return this.buffered-=$,Z}}var i$=32;var Y8=4096,c$="subc-server-v1",s$="subc-client-v1",c6="client";class y extends Error{}function B1($,Z,z,X,J){let G=l6("sha256",Buffer.from($));return G.update(Buffer.from(Z,"utf8")),G.update(Buffer.from(z)),G.update(Buffer.from(X)),G.update(Buffer.from(J)),new Uint8Array(G.digest())}function l$($,Z){if($.length!==Z.length)return!1;return i6(Buffer.from($),Buffer.from(Z))}async function d$($,Z,z){let X=Buffer.from(JSON.stringify(Z),"utf8");if(X.length>Y8)throw new y(`auth message too large: ${X.length} > ${Y8}`);let J=new Uint8Array(4);new DataView(J.buffer).setUint32(0,X.length,!0),await r($,J,z),await r($,X,z)}async function s6($,Z){let z=await $.readExact(4,Z),X=new DataView(z.buffer,z.byteOffset,4).getUint32(0,!0);if(X>Y8)throw new y(`auth message too large: ${X} > ${Y8}`);let J=X===0?new Uint8Array(0):await $.readExact(X,Z);try{return JSON.parse(Buffer.from(J).toString("utf8"))}catch(G){throw new y(`auth message JSON decode failed: ${String(G)}`)}}function W1($,Z){if(!Array.isArray($))throw new y(`auth field '${Z}' must be a byte array`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new y(`auth field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}async function v0($,Z,z){let X=new Uint8Array(d6(i$));await d$($,{client_nonce:Array.from(X),role:c6},z);let J=await s6($,z),G=W1(J.server_nonce,"server_nonce"),Q=W1(J.daemon_id,"daemon_id"),Y=W1(J.server_proof,"server_proof"),W=B1(Z.key,c$,X,G,Q);if(!l$(W,Y))throw new y("server proof mismatch — wrong key or impostor daemon");if(!l$(Q,Z.daemonId))throw new y("daemon id mismatch — connection file points at a different daemon");let B=B1(Z.key,s$,X,G,Q);await d$($,{client_auth:Array.from(B)},z)}import{promises as V1}from"node:fs";var n$=1,a$=32,t$=16;class b extends Error{}function o$($,Z){if(!Array.isArray($))throw new b(`connection file field '${Z}' must be a JSON array of bytes`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new b(`connection file field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}function n6($){if($.schema!==n$)throw new b(`unsupported connection file schema ${$.schema}; expected ${n$}`);if($.endpoints.length===0)throw new b("connection file must include at least one endpoint");if($.key.length<a$)throw new b(`connection file key is too short: ${$.key.length} bytes, need at least ${a$}`);if($.daemonId.length!==t$)throw new b(`connection file daemon_id must be ${t$} bytes, got ${$.daemonId.length}`)}async function a6($){if(process.platform==="win32")return;let z=(await V1.stat($)).mode&511;if((z&63)!==0)throw new b(`connection file ${$} has insecure permissions 0o${z.toString(8)}; expected owner-only 0600`)}async function P0($){await a6($);let Z=await V1.readFile($,"utf8"),z;try{z=JSON.parse(Z)}catch(Y){throw new b(`connection file JSON read failed for ${$}: ${String(Y)}`)}let X=z.wire_version;if(X!==void 0&&X!==p)throw new b(`connection file wire_version ${String(X)} but this client speaks ${p}; the client library must be upgraded`);let J=z.endpoints;if(!Array.isArray(J))throw new b("connection file 'endpoints' must be an array");let G=J.map((Y)=>{let W=Y;if(typeof W.host!=="string"||typeof W.port!=="number")throw new b("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),Q={schema:z.schema,endpoints:G,key:o$(z.key,"key"),daemonId:o$(z.daemon_id,"daemon_id"),pid:z.pid,daemonVer:z.daemon_ver??""};return n6(Q),Q}var r$=new WeakMap;class W8{channel;epoch;constructor($,Z,z){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(Z)||Z<=0||Z>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${Z}`);this.channel=$,this.epoch=Z,r$.set(this,z),Object.freeze(this)}static create($,Z,z){return new W8($,Z,z)}}function B8($,Z,z){return W8.create($,Z,z)}class z0 extends Error{handle;code="stale_route_handle";constructor($){super(`route handle (${$.channel}, ${$.epoch}) is not live on the current connection`);this.handle=$,this.name="StaleRouteHandleError"}}function O0(){return Object.freeze({})}function h0($,Z){return r$.get($)===Z}function V8($,Z){return $===Z}var o6=t6("subc-client"),r6=1e4,m0=30000,e6=50,$9=2000,e$="request_deadline",j1="deadline_exceeded_no_drop_observed",Z9=30000,z9=30000,$3=new Uint8Array(0),X9="management_surface",z3="SUBC_MODULE_ID",X3="SUBC_LAUNCH_NONCE",L8={baseMs:100,capMs:2000,maxAttempts:6};class S extends Error{kind;code;cause;constructor($,Z,z,X){super(Z);this.kind=$,this.code=z,this.cause=X,this.name="SubcCallError"}}class F extends Error{code;constructor($,Z){super($);this.code=Z}}class K0{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=O0();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,Z,z){this.sock=$,this.currentConn=Z,this.opts=z,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let Z=G9($),z=await K0.openConnection(Z);return new K0(z.sock,z.conn,Z)}async catalogList($){let Z=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),z=await this.controlRpc(Z);return this.parseJson(z).modules??[]}async routeOpen($,Z,z={}){let X=q1(z),J=z.consumerCapabilities,G=this.encode({op:"route.open",target:$,identity:Z,...X?{consumer_identity:X}:{},...J!==void 0?{consumer_capabilities:J}:{}}),Q=null,Y=(B)=>{if(B.header.ty!==H.Response)return!0;let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")throw new F(`route.open returned no route handle: ${JSON.stringify(V)}`);return Q=this.installRoute(V.route_channel,V.route_epoch),!0},W=(B)=>{if(B.header.ty!==H.Response)return;try{let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")return;let j=this.installRoute(V.route_channel,V.route_epoch);this.failHandle(j,new F("late route.open was closed","route_closed")),this.liveRoutes.delete(j.channel),this.sendRouteGoodbye(j,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(G,Y,W),!Q)throw new F("route.open response was not installed");return Q}async request($,Z,z={}){this.assertLiveHandle($);let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??w.Normal,Q=await this.send($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}async call($,Z,z,X={}){let J=z===void 0?{method:Z}:{method:Z,params:z},G=!1;for(;;){let Q=await this.cachedRouteHandle($,X);try{return await this.managedRequest(Q,J,X)}catch(Y){if(!(Y instanceof S))throw this.terminalCallError("managed call failed",Y);let W=Y.code==="unknown_channel"||Y.code==="stale_route_epoch";if(W&&!G&&!this.closeStarted){G=!0,this.evictRouteHandle(Q);continue}if(W&&G)this.evictRouteHandle(Q);if(Y.kind==="not_sent"){try{await this.reconnectAfterDrop(Y)}catch(B){throw this.notSentRecoveryError("managed call was not sent",B)}continue}if(Y.kind==="outcome_unknown"&&Y.code!==j1)this.scheduleReconnectAfterDrop(Y);else if(Y.kind==="outcome_unknown"&&Y.code===j1)this.probeLivenessAfterDeadline();throw Y}}}subscribe($,Z,z,X={}){this.assertLiveHandle($);let J=Z instanceof Uint8Array?Z:this.encode(Z),G=X.priority??C.Interactive,Q=X.admissionClass??w.Normal,Y=this.allocateCorr(),W=q8($,Y),B=null,V=null,j=new Promise((L,U)=>{if(this.closedErr){U(this.closedErr);return}V=L,B={handle:$,resolve:()=>L(),reject:U,onProgress:z,timer:null,subscription:!0},this.pending.set(W,B);let D=E(H.Request,v(!1,G,!1,Q),$.channel,$.epoch,Y,J);r(this.sock,t(D),Date.now()+m0).catch((P)=>{let A=this.pending.get(W);if(A)this.rejectPending(W,A,P instanceof Error?P:new F(String(P)))})}),q=!1;return{unsubscribe:()=>{if(q)return;if(q=!0,B&&V)this.settle(W,B,V);if(this.isLiveHandle($))this.cancel($,Y,G)},closed:j}}cancel($,Z,z=C.Interactive){this.assertLiveHandle($);let X=E(H.Cancel,v(!1,z,!1),$.channel,$.epoch,Z,$3);r(this.sock,t(X),Date.now()+m0).catch(()=>{return})}async routePoll($,Z){this.assertLiveHandle($);let z=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:Z}),X=await this.controlRpc(z,(J)=>{if(J.header.ty!==H.Response)return!0;let G=this.parseJson(J);return G.route_channel===$.channel&&G.route_epoch===$.epoch});return this.parseJson(X)}async closeRoute($,Z={}){this.assertLiveHandle($);for(let[z,X]of this.routes)if(X.handle&&V8(X.handle,$))X.closed=!0,X.handle=null,this.routes.delete(z);if(Z.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new F("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,Z,z={}){let X=Z3($,Z,q1(z)),J=this.routes.get(X);if(!J)return;J.closed=!0,this.routes.delete(X);let G=J.handle;if(J.handle=null,G)await this.closeRoute(G,z)}async closeRouteChannel($,Z={}){await this.closeRoute($,Z)}close(){this.closeStarted=!0,this.fail(new F("client closed")),this.sock.close()}drainUnaryOnHandle($){let Z=[];for(let z of this.pending.values())if(z.handle===$&&!z.subscription)Z.push(new Promise((X)=>{let J=z.onSettle;z.onSettle=()=>{J?.(),X()}}));return Promise.all(Z).then(()=>{return})}sendRouteGoodbye($,Z=!1){if(this.assertLiveConnection($),this.closedErr){if(Z)this.closeConnectionAfterCleanupFailure();return}let z=E(H.Goodbye,v(!1,C.Interactive,!1),$.channel,$.epoch,0n,$3),X=Y1(this.sock,t(z),Date.now()+m0);if(!X.queued&&Z)this.closeConnectionAfterCleanupFailure();X.completed.catch(()=>{if(Z&&!X.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let Z=await P0($.connectionFile),z=Date.now()+($.handshakeTimeoutMs??r6),X=Z.endpoints[0],J=await H0.connect(X.host,X.port,z);try{await v0(J,Z,z)}catch(G){throw J.close(),G}return{sock:J,conn:Z}}async controlRpc($,Z,z){return this.send(null,$,C.Interactive,w.Normal,void 0,void 0,Z,z)}send($,Z,z,X,J,G,Q,Y){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let W;try{W=this.allocateCorr()}catch(K){return Promise.reject(K)}let B=q8($,W),V=$?.channel??0,j=$?.epoch??0,q=E(H.Request,v(!1,z,!1,X),V,j,W,Z);return new Promise((K,L)=>{let U=J??m0,D={handle:$,resolve:K,reject:L,onProgress:G,timer:null,acceptFrame:Q,onLateResponse:Y};D.timer=setTimeout(()=>this.arbitrateTimeout(B,D,V,W,U),U),this.pending.set(B,D),r(this.sock,t(q),Date.now()+U).catch((P)=>{let A=this.pending.get(B);if(A)this.rejectPending(B,A,P instanceof Error?P:new F(String(P)))})})}arbitrateTimeout($,Z,z,X,J){let G=()=>{if(Z.onLateResponse)this.lateResponses.set($,Z.onLateResponse);this.rejectPending($,Z,new F(this.timeoutMessage(z,X,J),e$))},Q=Date.now()+this.opts.timeoutArbitrationGraceMs,Y=()=>{if(this.pending.get($)!==Z)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<Q){setImmediate(Y);return}G()};setImmediate(Y)}async managedRequest($,Z,z){let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??w.Normal;try{let Q=await this.sendManaged($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}catch(Q){if(Q instanceof S)throw Q;throw this.terminalCallError("managed call failed",Q)}}sendManaged($,Z,z,X,J,G){try{this.assertLiveHandle($)}catch(j){return Promise.reject(this.notSentCallError("request used a stale route handle",j))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let Q;try{Q=this.allocateCorr()}catch(j){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",j))}let Y=q8($,Q),W=E(H.Request,v(!1,z,!1,X),$.channel,$.epoch,Q,Z),B=!1,V=(j)=>{if(!B)return this.notSentCallError("request bytes were not queued to the subc socket",j);if(j instanceof F&&j.code===e$)return new S("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${j8(j)}`,j1,j);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",j)};return new Promise((j,q)=>{let K=J??m0,L={handle:$,resolve:j,reject:q,onProgress:G,timer:null,classifyFailure:V};L.timer=setTimeout(()=>this.arbitrateTimeout(Y,L,$.channel,Q,K),K),this.pending.set(Y,L);let U=Y1(this.sock,t(W),Date.now()+K);B=U.queued,U.completed.catch((D)=>{let P=this.pending.get(Y);if(P)this.rejectPending(Y,P,D instanceof Error?D:new F(String(D)))})})}async cachedRouteHandle($,Z){let z=Z.identity??this.opts.identity;if(!z)throw new S("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let X={kind:Z.targetKind??this.opts.targetKind,module_id:$},J=q1(Z),G=Z3(X,z,J),Q=this.routes.get(G);if(!Q)Q={key:G,moduleId:$,target:X,identity:z,consumerIdentity:J,handle:null,opening:null},this.routes.set(G,Q);if(Q.handle&&this.isLiveHandle(Q.handle))return Q.handle;if(!Q.opening)Q.opening=this.openCachedRoute(Q).finally(()=>{Q.opening=null});return Q.opening}async openCachedRoute($){let Z=Date.now()+Z9,z=this.opts.reconnectBackoff.baseMs,X=0;for(;;){if($.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(J){throw this.notSentRecoveryError("route.open could not run because reconnect failed",J)}if($.handle&&this.isLiveHandle($.handle))return $.handle;try{let J=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed)throw this.liveRoutes.delete(J.channel),this.sendRouteGoodbye(J),this.routeClosedDuringOpen();return $.handle=J,J}catch(J){if(J instanceof S&&J.code==="route_closed")throw J;if(!this.closeStarted&&H8(J)){try{await this.reconnectAfterDrop(J)}catch(G){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",G)}continue}if(!this.closeStarted&&J instanceof F&&J9(J.code)){if(X+=1,X<this.opts.reconnectBackoff.maxAttempts&&Date.now()<Z){await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${$.moduleId}: ${J.code} (retry budget exhausted)`,J)}throw this.terminalCallError(`route.open failed for module ${$.moduleId}`,J)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let $ of this.pending.values())if($.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let $=this.sock,Z=this.generation,z;try{z=this.allocateCorr()}catch{return}let X=Date.now(),J=E(H.Ping,v(!1,C.Interactive,!1,w.Normal),0,0,z,new Uint8Array),G=(async()=>{if(await r($,t(J),X+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==Z||this.closeStarted)return;if(this.lastInboundAtMs>=X)return;if(this.hasControlPending())return;this.fail(new Z0(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`)),$.close()})().finally(()=>{this.livenessProbe=null});this.livenessProbe=G}async ensureConnectedForManaged(){if(this.closeStarted)throw new F("client closed");if(this.reconnecting)await this.reconnecting;if(this.closedErr)await this.reconnectAfterDrop(this.closedErr)}scheduleReconnectAfterDrop($){if(this.closeStarted||this.reconnecting)return;this.reconnectAfterDrop($).catch(()=>{})}reconnectAfterDrop($){if(this.closeStarted)return Promise.reject(new F("client closed"));if(this.reconnecting)return this.reconnecting;let Z=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===Z)this.reconnecting=null});return this.reconnecting=Z,Z}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new F("client closed");Z+=1;try{let X=await K0.openConnection(this.opts);if(this.closeStarted)throw X.sock.close(),new F("client closed");this.replaceConnection(X),await this.reopenCachedRoutes();return}catch(X){if(!H8(X)||Z>=this.opts.reconnectBackoff.maxAttempts){if(X instanceof y&&Z>1)throw new y(`reconnect gave up after ${Z} attempts: ${X.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw X}await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection($){this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.closedErr=null,this.generation+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop($.sock,this.generation)}async reopenCachedRoutes(){for(let $ of this.routes.values())$.handle=null;for(let $ of this.routes.values()){if($.closed)continue;let Z=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed){this.liveRoutes.delete(Z.channel),this.sendRouteGoodbye(Z);continue}$.handle=Z}}timeoutMessage($,Z,z){let X=this.sock.localPort();return`request on ${X===null?"channel":`local_port=${X} channel`} ${$} corr ${Z} timed out after ${z}ms`}routeClosedDuringOpen(){return new S("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,Z){try{for(;;){this.readerActive=!1;let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:z9},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===Z)this.dispatch(z)}finally{this.readerActive=!1}}}catch(z){if(this.sock===$&&this.generation===Z)this.fail(z instanceof Error?z:new F(String(z)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===H.Push){let G=this.opts.onControlPush;if(G){let Q=null;try{let Y=this.parseJson($);if(Y&&typeof Y.op==="string")Q={op:Y.op,body:Y}}catch{}if(Q)try{G(Q)}catch{}}return}let Z=null;if($.header.channel!==0){if(Z=this.liveRoutes.get($.header.channel)??null,!Z||Z.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}let z=q8(Z,$.header.corr),X=this.pending.get(z);if(X){if(X.acceptFrame&&!X.acceptFrame($))return;switch($.header.ty){case H.Push:case H.StreamData:try{X.onProgress?.($.body)}catch{}return;case H.Response:case H.StreamEnd:this.settle(z,X,()=>X.resolve($));return;case H.Error:this.settle(z,X,()=>X.reject(this.errorFromFrame($)));return;default:return}}let J=this.lateResponses.get(z);if(J&&($.header.ty===H.Response||$.header.ty===H.Error)){this.lateResponses.delete(z),J($);return}if($.header.ty===H.Goodbye&&Z){if(this.failHandle(Z,new F("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(Z.channel)===Z)this.liveRoutes.delete(Z.channel);this.evictRouteHandle(Z);return}if($.header.ty===H.Response||$.header.ty===H.Error||$.header.ty===H.StreamEnd)o6("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",$.header.ty,$.header.channel,$.header.epoch,$.header.corr,this.sock.localPort()??"?")}settle($,Z,z){if(this.pending.get($)!==Z)return!1;if(this.pending.delete($),Z.timer)clearTimeout(Z.timer);return z(),Z.onSettle?.(),!0}rejectPending($,Z,z){this.settle($,Z,()=>Z.reject(Z.classifyFailure?.(z)??z))}errorFromFrame($){try{let Z=JSON.parse(Buffer.from($.body).toString("utf8"));return new F(Z.message??"subc error",Z.code)}catch{return new F(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let Z of this.routes.values())if(Z.handle&&V8(Z.handle,$))Z.handle=null}failHandle($,Z){for(let[z,X]of this.pending)if(X.handle&&V8(X.handle,$))this.rejectPending(z,X,Z)}fail($){if(!this.closedErr)this.closedErr=$;for(let[Z,z]of this.pending)this.rejectPending(Z,z,$)}notSentCallError($,Z){return new S("not_sent",`${$}${j8(Z)}`,K8(Z),Z)}outcomeUnknownCallError($,Z){return new S("outcome_unknown",`${$}${j8(Z)}`,K8(Z),Z)}terminalCallError($,Z){if(Z instanceof S)return Z;return new S("terminal",`${$}${j8(Z)}`,K8(Z),Z)}notSentRecoveryError($,Z){if(Z instanceof S)return Z;if(H8(Z))return this.notSentCallError($,Z);return this.terminalCallError($,Z)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,Z){let z=B8($,Z,this.connectionToken);return this.liveRoutes.set($,z),z}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!h0($,this.connectionToken))throw new z0($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new F("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(z),this.sock.close(),this.scheduleReconnectAfterDrop(z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}closeConnectionAfterCleanupFailure(){let $=new F("late route cleanup could not be queued","late_route_cleanup_failed");this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($)}encode($){return Buffer.from(JSON.stringify($),"utf8")}parseJson($){let Z=$.body;return JSON.parse(Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength).toString("utf8"))}}function H8($){if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof S)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof y)return!0;if($ instanceof F||$ instanceof b)return!1;let Z=K8($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function J9($){return $==="unknown_module"||$==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}function G9($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??X9,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??e6,livenessProbeWindowMs:$.livenessProbeWindowMs??$9,onControlPush:$.onControlPush}}function Z3($,Z,z){let X=z?`${z.module_id}\x00${z.launch_nonce}`:"";return`${$.kind}\x00${$.module_id}\x00${Z.project_root}\x00${Z.harness}\x00${Z.session}\x00${X}`}function q1($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let Z=process.env[z3],z=process.env[X3];if(!Z||!z)return;return{module_id:Z,launch_nonce:z}}function K8($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}function j8($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function q8($,Z){return $?`${$.channel}:${$.epoch}:${Z}`:`0:0:${Z}`}import{Buffer as N1}from"node:buffer";var Q9=1e4,Y9=30000,G3=30000,W9=250,H1=64,L1="health.check",Q3=1n;class U8{available;waiters=[];constructor($){if(!Number.isInteger($)||$<=0)throw new I("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=$}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise(($)=>{this.waiters.push($)}),this.releaseOnce()}releaseOnce(){let $=!1;return()=>{if($)return;$=!0;let Z=this.waiters.shift();if(Z)Z();else this.available+=1}}}class I extends Error{code;kind;constructor($,Z,z="terminal"){super($);this.code=Z,this.kind=z}}class g0{sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=O0();nextCorr=1n;ingressEpochDropCount=0;requestGate=new U8(H1);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;constructor($,Z,z,X){this.sock=$,this.currentConn=Z,this.opts=z,this.storage=X,this.closed=new Promise((J)=>{this.resolveClosed=J}),this.readLoop($,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request($,Z,z={}){this.assertLiveHandle($);let X=this.allocateCorr(),J=N8($,X),G=z.timeoutMs??G3,Q=E(H.Request,v(!1,z.priority??C.Interactive,!1,z.admissionClass??w.Normal),$.channel,$.epoch,X,Z);return await new Promise((Y,W)=>{let B=setTimeout(()=>{if(this.pending.delete(J))W(new I("reverse request timed out","request_timeout"))},G);this.pending.set(J,{resolve:(V)=>Y(V.body),reject:W,timer:B}),this.sendOn(this.sock,this.generation,Q).catch((V)=>{let j=this.pending.get(J);if(!j)return;this.pending.delete(J),clearTimeout(j.timer),W(V instanceof Error?V:new I(String(V)))})})}async push($,Z,z={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,E(H.Push,v(!1,z.priority??C.Interactive,!1,z.admissionClass??w.Normal),$.channel,$.epoch,0n,Z))}cancel($,Z){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,E(H.Cancel,e(),$.channel,$.epoch,Z,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,E(H.Goodbye,e(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==p)throw new I(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${p}`,"invalid_manifest");let Z=q9($),z=await g0.openConnection(Z);return new g0(z.sock,z.conn,Z,z.ack.storage)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await K1($,E(H.Goodbye,e(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,Z){let z=await P0($.connectionFile),X=Date.now()+($.handshakeTimeoutMs??Q9),J=z.endpoints[0],G=await H0.connect(J.host,J.port,X);try{Z?.(G),await v0(G,z,X),await K1(G,K9($));let Q=await D9(G,X);return{sock:G,conn:z,ack:Q}}catch(Q){throw G.close(),Q}}async readLoop($,Z){try{for(;;){let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:Y9});if(!await this.dispatch(z,$,Z)){if(this.sock===$&&this.generation===Z)this.closeStarted=!0;break}}}catch(z){if(this.sock===$&&this.generation===Z&&!this.closeStarted){this.handleUnexpectedDrop($,Z,z instanceof Error?z:new I(String(z)));return}}finally{if(this.sock===$&&this.generation===Z){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,Z,z){let X=null;if($.header.channel!==0){if(X=this.liveRoutes.get($.header.channel)??null,!X||X.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(X){let J=N8(X,$.header.corr),G=this.pending.get(J);if(G){if($.header.ty===H.Push||$.header.ty===H.StreamData)return!0;if($.header.ty===H.Response||$.header.ty===H.StreamEnd)return this.pending.delete(J),clearTimeout(G.timer),G.resolve($),!0;if($.header.ty===H.Error)return this.pending.delete(J),clearTimeout(G.timer),G.reject(B9($)),!0}}switch($.header.ty){case H.Ping:if($.header.channel===0)await this.sendOn(Z,z,a($.header.ver,H.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case H.Goodbye:if(!X)return!1;return this.liveRoutes.delete(X.channel),this.abortHandle(X),await this.opts.onRouteGone?.(X),!0;case H.Cancel:if(X)this.inflight.get(N8(X,$.header.corr))?.abort();return!0;case H.Request:if($.header.channel===0)await this.handleControlRequest($,Z,z);else if(X)this.handleDataRequest($,X,Z,z).catch((J)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider handler failed after its request was dispatched",J)});return!0;default:return!0}}abortHandle($){let Z=`${$.channel}:${$.epoch}:`;for(let[z,X]of this.inflight)if(z.startsWith(Z))X.abort();for(let[z,X]of this.pending){if(!z.startsWith(Z))continue;this.pending.delete(z),clearTimeout(X.timer),X.reject(new z0($))}}abortGeneration($){this.abortAllInflight();for(let[Z,z]of this.pending)this.pending.delete(Z),clearTimeout(z.timer),z.reject(new I("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,Z,z){let X=P8($.body);if(X.op===L1){this.handleHealthRequest($,Z,z).catch((j)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider health handler failed after its request was dispatched",j)});return}if(X.op!=="route.bind")throw new I(`unsupported module control request ${X.op??"<missing op>"}`);let J=J3(X.route_channel,"route_channel"),G=J3(X.epoch,"epoch"),Q=this.liveRoutes.get(J);if(Q){if(G<=Q.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${G} does not supersede installed epoch ${Q.epoch} on channel ${J}`,e(),Z,z);return}this.liveRoutes.delete(Q.channel),this.abortHandle(Q),await this.opts.onRouteGone?.(Q)}let Y=B8(J,G,this.connectionToken),W={handle:Y,target:X.target,identity:X.identity,principal:X.principal,consumer_capabilities:X.consumer_capabilities},B;try{B=await this.opts.onBind?.(W)}catch(j){try{await this.sendError($,"route_rejected",j instanceof Error?j.message:String(j),e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}let V=P9(B);if(V){try{await this.sendError($,V.code,V.message,e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}try{await this.sendOn(Z,z,a($.header.ver,H.Response,e(),0,0,$.header.corr,D8({op:"route.bind"})))}catch(j){throw await this.opts.onRouteGone?.(Y),j}if(this.sock!==Z||this.generation!==z||this.closeStarted||this.closedErr){await this.opts.onRouteGone?.(Y);return}this.liveRoutes.set(Y.channel,Y),await this.opts.onBound?.(Y)}async handleDataRequest($,Z,z,X){let{corr:J,ver:G}=$.header,Q=N8(Z,J),Y=new AbortController;this.inflight.set(Q,Y);let W={handle:Z,signal:Y.signal,currentEpoch:()=>this.connectionEpoch,emit:async(j,q={})=>{if(this.assertLiveHandle(Z),Y.signal.aborted)return;await this.sendOn(z,X,a(G,H.StreamData,v(!1,q.priority??C.Interactive,!1,q.admissionClass??w.Normal),Z.channel,Z.epoch,J,j))}},B=await(this.requestGate??new U8(H1)).acquire(),V=v(!1,C.Interactive,!1);try{if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}let j=await this.opts.handler(Z,$.body,W);if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}if(this.assertLiveHandle(Z),j===void 0)await this.sendOn(z,X,a(G,H.StreamEnd,V,Z.channel,Z.epoch,J,new Uint8Array(0)));else if(j instanceof Uint8Array)await this.sendOn(z,X,a(G,H.Response,V,Z.channel,Z.epoch,J,j));else throw new I("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(j){if(j instanceof z0)return;if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}await this.sendError($,j instanceof I&&j.code?j.code:"handler_error",j instanceof Error?j.message:String(j),V,z,X)}finally{if(B(),this.inflight.get(Q)===Y)this.inflight.delete(Q)}}async handleHealthRequest($,Z,z){let{corr:X,ver:J}=$.header,G=`control:${z}:${X}`,Q=new AbortController;this.inflight.set(G,Q);let Y=await(this.requestGate??new U8(H1)).acquire();try{if(Q.signal.aborted)return;let W=await this.opts.health();await this.sendOn(Z,z,a(J,H.Response,e(),0,0,X,D8({op:L1,status:W.status,...W.detail===void 0?{}:{detail:W.detail},...W.metrics===void 0?{}:{metrics:W.metrics}})))}catch(W){await this.sendError($,W instanceof I&&W.code?W.code:"health_error",W instanceof Error?W.message:String(W),e(),Z,z)}finally{if(Y(),this.inflight.get(G)===Q)this.inflight.delete(G)}}async sendError($,Z,z,X,J,G){if($.header.channel!==0){let Q=this.liveRoutes.get($.header.channel);if(!Q||Q.epoch!==$.header.epoch||!this.isLiveHandle(Q))return}await this.sendOn(J,G,a($.header.ver,H.Error,X,$.header.channel,$.header.epoch,$.header.corr,D8({code:Z,message:z})))}async sendOn($,Z,z){if(this.sock!==$||this.generation!==Z||this.closeStarted||this.closedErr)return;await K1($,z)}handleUnexpectedDrop($,Z,z){if(this.closeStarted||this.sock!==$||this.generation!==Z)return;this.cancelRestoredDebounce(),this.abortGeneration(Z),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(z,this.generation,$)}scheduleReconnectAfterDrop($,Z,z){if(this.closeStarted)return;let X=this.reconnecting;if(X){if(!this.shouldSupersedeReconnect(X,Z,z))return;X.superseded=!0,X.socket?.close()}let J={generation:Z,socket:null,socketDied:!1,superseded:!1};this.reconnecting=J,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(J).catch((G)=>{if(this.isCurrentReconnect(J)&&!this.closeStarted)this.failFatal(G instanceof Error?G:new I(String(G)))}).finally(()=>{if(this.isCurrentReconnect(J))this.reconnecting=null})}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new I("provider closed");$.socket=null,$.socketDied=!1,Z+=1,this.enqueueReconnectState($,Z);try{let X=await g0.openConnection(this.opts,(G)=>{if(!this.isCurrentReconnect($)){G.close();return}$.socket=G});if(!this.isCurrentReconnect($)||this.closeStarted){if(X.sock.close(),this.closeStarted)throw new I("provider closed");return}let J=this.replaceConnection(X,$.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new I("reconnect state must clear before restored","reconnect_state");this.scheduleRestored($.generation,J);return}catch(X){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw X;if(!L9(X))throw X;await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,Z,z){return $.generation<Z||$.socketDied||$.socket===z}enqueueReconnectState($,Z){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:Z},$.generation,$)}replaceConnection($,Z){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,Z),this.connectionEpoch}scheduleRestored($,Z){if(!this.opts.onConnectionState)return;let z=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if(z===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===$&&this.connectionEpoch===Z)this.enqueueConnectionState({state:"restored",epoch:Z},$)}).catch((X)=>{if(z===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",X)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,Z,z){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:Z,reconnect:z}),!this.drainingStateQueue)this.drainConnectionStateQueue()}async drainConnectionStateQueue(){if(this.drainingStateQueue)return;this.drainingStateQueue=!0;try{while(this.stateQueue.length>0){let $=this.stateQueue[0];if(this.closeStarted||$.generation!==void 0&&$.generation!==this.generation||$.reconnect?.superseded){this.stateQueue.shift();continue}let{event:Z}=$;try{await this.opts.onConnectionState?.(Z),this.stateQueue.shift()}catch(z){if(Z.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",z),await U9();continue}console.warn("SubcProvider connection-state callback failed",z),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new I("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function N8($,Z){return`${$.channel}:${$.epoch}:${Z}`}function B9($){try{let Z=P8($.body);return new I(Z.message??"subc error",Z.code,Z.code==="stale_route_epoch"||Z.code==="unknown_channel"?"not_sent":"terminal")}catch{return new I(N1.from($.body).toString("utf8")||"subc error")}}function V9($){let Z=$.launchNonce??process.env[j9];return Z&&Z.length>0?Z:void 0}var j9="SUBC_LAUNCH_NONCE";function q9($){return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),restoredDebounceMs:$.restoredDebounceMs??W9,onConnectionState:$.onConnectionState,launchNonce:$.launchNonce}}function H9($){if($===null)return null;let Z=new Set($??[]);return Z.add(L1),[...Z]}function K9($){let Z=V9($);return E(H.Hello,e(),0,0,Q3,D8({manifest:O9($.manifest),protocol_ver:p,control_ops:H9($.controlOps),...Z?{launch_nonce:Z}:{}}))}function L9($){if($ instanceof I)return $.code==="duplicate_module_id";if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof y)return!0;if($ instanceof b)return!1;let Z=N9($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function N9($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}async function U9(){await new Promise(($)=>setTimeout($,0))}function e(){return v(!1,C.Passive,!1)}async function K1($,Z){await r($,t(Z),Date.now()+G3)}async function D9($,Z){let z=await $.readFrame(Z,Z);switch(z.header.ty){case H.HelloAck:{let X=P8(z.body);if(X.negotiated_ver!==p)throw new I(`subc negotiated protocol ${X.negotiated_ver}; expected exactly ${p}`,"unsupported_version");return X}case H.Error:{let X=P8(z.body);throw new I(`subc rejected HELLO: ${X.code??"unknown"} — ${X.message??"subc error"}`,X.code)}default:throw new I(`unexpected frame ${H[z.header.ty]} awaiting HELLO_ACK`)}}function D8($){return new Uint8Array(N1.from(JSON.stringify($),"utf8"))}function P8($){return JSON.parse(N1.from($).toString("utf8"))}function J3($,Z){if(typeof $!=="number"||!Number.isInteger($))throw new I(`route.bind ${Z} must be an integer`);return $}function P9($){if($===void 0||$===!0)return null;if($===!1)return{code:"route_rejected",message:"route.bind rejected by provider"};if($.accept)return null;return{code:$.code??"route_rejected",message:$.message??"route.bind rejected by provider"}}function O9($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(M9),consumes:$.consumes.map(_9),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((Z)=>({secret:Z.secret,reason:Z.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function M9($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((Z)=>({name:Z.name,...Z.description===void 0?{}:{description:Z.description},execution_mode:Z.execution_mode,schema:Z.schema})),identity_scope:[...$.identity_scope],concurrency:$.concurrency,emits_push:$.emits_push,sub_supervises:$.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:$.stage,applies_to:{provider:$.applies_to.provider,model:$.applies_to.model},interface:$.interface,declares_frozen_floor:$.declares_frozen_floor,needs_signals:[...$.needs_signals],conformance_class:$.conformance_class};case"management_surface":return{role:"management_surface",operations:$.operations.map((Z)=>({name:Z.name,kind:Z.kind})),config_schema:$.config_schema,observability:$.observability.map((Z)=>({name:Z.name,kind:Z.kind})),identity_scope:[...$.identity_scope],concurrency:$.concurrency};case"internal_service":return{role:"internal_service",service_id:$.service_id,transport:$.transport,agent_facing:$.agent_facing,operations:[...$.operations]}}}function _9($){switch($.role){case"tool_client":return{role:"tool_client",of:[...$.of]};case"llm_client":return{role:"llm_client",via:$.via,auth:$.auth};case"service_client":return{role:"service_client",of:[...$.of]}}}var O8="subc-connection.json",A9="subc-",T9=".connection.json";function Y3(){let $=process.env.HOME;return $?p0($,".local","share","cortexkit","run",O8):void 0}function C9(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($)return p0($,O8);let Z=Y3();if(Z)return Z;return p0(R9().homedir,".local","share","cortexkit","run",O8)}function b9(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($){let X=p0($,O8);if(U1(X))return X}let Z=Y3();if(Z&&U1(Z))return Z;let z=S9(I9());return z.length===1?z[0]:void 0}function D1(){return b9()??C9()}function P1($){return $?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||D1()}function U1($){try{return F9($).isFile()}catch{return!1}}function S9($){let Z;try{Z=x9($)}catch{return[]}let z=[];for(let X of Z){if(typeof X!=="string")continue;if(!X.startsWith(A9)||!X.endsWith(T9))continue;let J=p0($,X);if(U1(J))z.push(J)}return z.sort(),z}import{createHash as k9}from"node:crypto";import{existsSync as w9,realpathSync as W3}from"node:fs";import{dirname as f9,relative as E9,resolve as y9}from"node:path";function B3($){let Z=$,z;try{z=W3(Z)}catch(X){if(X.code!=="ENOENT")throw X;let J=Z;while(!w9(J)){let G=f9(J);if(G===J)break;J=G}z=y9(W3(J),E9(J,Z))}return k9("sha256").update(z).digest("hex")}function O1($,Z){return{project_root:$,harness:"opencode",session:`store-${B3(Z)}`}}var V3=["transient","permanent","auth_required","context_overflow"];class _0 extends Error{code;action;["class"];constructor($,Z,z){super(`Claustrum credential request failed: ${$}`);this.code=$,this.action=z,this.name="ClaustrumCredentialError",this.class=Z}}function M0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j3($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function M($,Z="invalid_response",z=(X)=>console.warn(X)){let X=M0($)&&M0($.result)?$.result:void 0,J=X&&M0(X.error)?X.error:void 0,G=J?.class,Q=J?.code,Y=typeof G==="string"&&V3.includes(G),W=typeof Q==="string",V=Y&&W?G:"transient";if(typeof G!=="string")z("unknown");else if(!Y)z(G);return new _0(W?Q:Z,V,j3(V))}function L0($){return M0($)&&M0($.result)&&M0($.result.error)}var q3="claustrum",m9=60000;function u($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0?$:void 0}function X0($){return $===void 0||typeof $==="string"}function H3($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.payload;if(!Array.isArray(X)||X.length===0||!X.every((q)=>typeof q==="number"&&Number.isInteger(q)&&q>=0&&q<=255))throw M($,"invalid_response",Z);let J=_1(z?.record_version);if(J===void 0)throw M($,"invalid_record_version",Z);let G=z?.expires_at_ms,Q=G===void 0||G===null?null:typeof G==="number"&&Number.isFinite(G)?G:void 0;if(Q===void 0)throw M($,"invalid_expiry",Z);let Y=z?.credential_id,W=z?.project_id,B=z?.account_id,V=z?.email,j=z?.org_name;if(!X0(Y)||!X0(W)||!X0(B)||!X0(V)||!X0(j))throw M($,"invalid_response",Z);return{material:new TextDecoder().decode(Uint8Array.from(X)),recordVersion:J,expiresAtMs:Q,credentialId:Y,projectId:W,accountId:B,email:V,orgName:j}}function g9($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=_1(z?.record_version);if(typeof z?.ready!=="boolean"||z?.last_error_code!==void 0&&z?.last_error_code!==null&&typeof z?.last_error_code!=="string"||typeof z?.lease_held!=="boolean"||X===void 0||z?.stale_pending!==void 0&&typeof z.stale_pending!=="boolean")throw M($,"invalid_status",Z);return{ready:z.ready,lastErrorCode:z.last_error_code??null,leaseHeld:z.lease_held,recordVersion:X,...z.stale_pending===void 0?{}:{stalePending:z.stale_pending}}}class M8{#z;#J;#B;#Y;#G;#$;#X=null;#Q=0;#W=!1;constructor($,Z,z,X,J,G){this.#z=$,this.#J=Z,this.#B=z,this.#Y=X,this.#G=J,this.#$=G}static async connect($={}){let Z=P1($.connectionFile),z=$.connector??((G)=>K0.connect(G)),X=$.identity??O1($.projectRoot??process.cwd(),$.storagePath??process.cwd()),J=await z({connectionFile:Z,handshakeTimeoutMs:$.handshakeTimeoutMs});return new M8(J,z,Z,$.handshakeTimeoutMs,X,$.logger??((G)=>console.warn(G)))}async getCredential($,Z){let z=await this.#Z("credential.get",{handle:$,min_ttl_ms:Z,force_refresh:!1});return H3(z,this.#$)}async statusCredential($){let Z=await this.#Z("credential.status",{handle:$});return g9(Z,this.#$)}async reportAuthFailure($){let Z=await this.#Z("credential.report_auth_failure",{handle:$.handle,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async listScoped($){let Z=await this.#Z("credential.list_scoped",$===void 0?{}:{enrollment_token:$});return p9(Z,this.#$)}async getScoped($){let Z=await this.#Z("credential.get_scoped",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,min_ttl_ms:$.minTtlMs});return H3(Z,this.#$)}async reportAuthFailureScoped($){let Z=await this.#Z("credential.report_auth_failure",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async enrollPropose($){let Z=await this.#Z("auth.enroll_propose",{proposed_name:$.name,request_secret_hash:$.requestSecretHash}),X=M1(Z,this.#$).request_id;if(typeof X!=="string"||X.length===0)throw M(Z,"invalid_response",this.#$);return{requestId:X}}async enrollPoll($){let Z=await this.#Z("auth.enroll_poll",{request_id:$.requestId,request_secret:$.requestSecret});return u9(Z,this.#$)}async enrollRotate($){let Z=await this.#Z("auth.enroll_rotate",{token:$.token,expected_token_generation:$.expectedTokenGeneration}),z=M1(Z,this.#$),X=z.token,J=z.token_generation;if(typeof X!=="string"||X.length===0||typeof J!=="number")throw M(Z,"invalid_response",this.#$);return{token:X,tokenGeneration:J}}close(){this.#W=!0,this.#z.close()}async#Z($,Z){try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(z){if(this.#j(z)){try{await this.#q()}catch(X){throw this.#V(X)}try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(X){throw this.#V(X)}}throw this.#V(z)}}#V($){if($ instanceof _0)return $;let Z=$ instanceof S&&$.code?$.code:"transport_error";return new _0(Z,"transient","retry")}#j($){return!this.#W&&$ instanceof S&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"}async#q(){if(this.#W)throw Error("Claustrum client is closed");if(this.#X){await this.#X;return}let $=Date.now();if($<this.#Q)throw Error("Claustrum client reconnect is backed off");this.#Q=$+m9,this.#X=this.#J({connectionFile:this.#B,handshakeTimeoutMs:this.#Y}).then((Z)=>{if(this.#W)throw Z.close(),Error("Claustrum client is closed");let z=this.#z;this.#z=Z,z.close()}).finally(()=>{this.#X=null}),await this.#X}}function p9($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.credentials;if(!Array.isArray(X))throw M($,"invalid_response",Z);let J=z?.view;if(typeof J!=="string"||J.length===0)throw M($,"invalid_response",Z);return{rows:X.map((Q)=>{if(!u(Q))throw M($,"invalid_response",Z);let Y=_1(Q.record_version);if(Y===void 0)throw M($,"invalid_record_version",Z);let W=(V)=>{if(!Array.isArray(V)||!V.every((j)=>typeof j==="string"))throw M($,"invalid_response",Z);return V};if(typeof Q.id!=="string"||typeof Q.type!=="string"||typeof Q.state!=="string")throw M($,"invalid_response",Z);let B=Q.created_at_ms===void 0||Q.created_at_ms===null?null:typeof Q.created_at_ms==="number"&&Number.isFinite(Q.created_at_ms)?Q.created_at_ms:void 0;if(B===void 0)throw M($,"invalid_response",Z);if(!X0(Q.refresh_adapter))throw M($,"invalid_response",Z);if(!X0(Q.account_id)||!X0(Q.email)||!X0(Q.org_name))throw M($,"invalid_response",Z);return{id:Q.id,categories:W(Q.categories),credentialType:Q.type,serves:W(Q.serves),state:Q.state,refreshAdapter:Q.refresh_adapter,recordVersion:Y,operations:W(Q.operations),createdAtMs:B,accountId:Q.account_id,email:Q.email,orgName:Q.org_name}}),view:J}}function M1($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0;if(z===void 0)throw M($,"invalid_response",Z);return z}function u9($,Z){let z=M1($,Z),X=z.status;if(X==="pending")return{status:"pending"};if(X==="denied")return{status:"denied"};if(X!=="approved")throw M($,"invalid_response",Z);let{name:J,token:G,token_generation:Q}=z;if(typeof J!=="string"||typeof G!=="string"||G.length===0||typeof Q!=="number"||!Number.isInteger(Q))throw M($,"invalid_response",Z);return{status:"approved",name:J,token:G,tokenGeneration:Q}}l8();var VZ=d("quota");var K3={name:"@cortexkit/pi-openai-auth",version:"0.11.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/openai-auth-core":"workspace:*"},peerDependencies:{"@earendil-works/pi-ai":">=0.80.10","@earendil-works/pi-coding-agent":">=0.80.10","@earendil-works/pi-tui":">=0.80.10"}};import{homedir as i9}from"node:os";import{join as L3}from"node:path";function c9(){return process.env.PI_AGENT_DIR?.trim()||L3(i9(),".pi","agent")}function N3(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||L3(c9(),n0)}function s9($=N3()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||g8($)}function U3($=N3()){return{configPath:$,statePath:s9($)}}var D3=new Map;function P3($){return D3.get($)}function O3($){return D3.delete($)}var n9={auth:{set:async()=>{}}};async function a9($,Z){let z=(Z.accountPaths??U3)(),X=Z.loadAccounts??B$,J=await X(z),G=new n({storage:null,configPath:z.configPath,fetchImpl:Z.fetchImpl,now:Z.now});return G.seedFallbacksFromAccounts((J?.accounts??[]).filter(m8)),{accountStoragePath:z.configPath,accountStatePath:z.statePath,packageVersion:Z.packageVersion??K3.version,quotaManager:G,loadAccounts:X,client:n9,sessionId:$.sessionManager.getSessionId(),notify:(Q)=>$.ui.notify(Q.text),clearStickyRouting:async(Q)=>O3(Q),getStickyRouting:async(Q)=>P3(Q),fetchImpl:Z.fetchImpl,now:Z.now,randomUUID:Z.randomUUID,beginAccountLogin:Z.beginAccountLogin}}async function t9($,Z,z,X={}){return z1($,Z,await a9(z,X))}async function x1($,Z,z,X){let J=await t9($,Z,z,X);z.ui.notify(J.text)}function M3($,Z={}){$.registerCommand(X8,{description:"List, add, remove, or reorder OpenAI fallback accounts",handler:(z,X)=>x1(X8,z,X,Z)}),$.registerCommand(z8,{description:"Show persisted OpenAI quota for fallback accounts",handler:(z,X)=>x1(z8,z,X,Z)}),$.registerCommand(J8,{description:"Show or change OpenAI account routing mode",handler:(z,X)=>x1(J8,z,X,Z)})}import{connect as o9}from"node:net";import{connect as r9}from"node:tls";var e9="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",_3=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class F1{url;readyState=0;socket;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor($,Z){this.url=$,this.connect($,Z)}addEventListener($,Z,z){this.listeners[$]?.add(Z)}removeEventListener($,Z){this.listeners[$]?.delete(Z)}emit($,Z){for(let z of[...this.listeners[$]??[]])try{z(Z)}catch{}}async connect($,Z){let z=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),X=z.hostname,J=z.port?Number(z.port):z.protocol==="https:"?443:80,G=`${z.pathname}${z.search}`,Q=crypto.getRandomValues(new Uint8Array(16)),Y=Buffer.from(Q).toString("base64"),W=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(Y+e9));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let B={};for(let[q,K]of Object.entries(Z))B[q.toLowerCase()]=K;let V=[`GET ${G} HTTP/1.1`,`Host: ${X}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${Y}`];for(let q of _3)if(B[q]!==void 0)V.push(`${$2(q)}: ${B[q]}`);for(let[q,K]of Object.entries(Z))if(!_3.includes(q.toLowerCase())&&q.toLowerCase()!=="content-length")V.push(`${q}: ${K}`);let j=`${V.join(`\r
210
+ Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let X=Z,J=$.trim().split(/\s+/).filter(Boolean),G=J[0];if(!G||G==="refresh"){let Y=["main",...((await Z.loadAccounts(m(Z)))?.accounts??[]).filter((B)=>B.enabled!==!1&&B.type==="oauth").map((B)=>B.id)];_.debug("reset accounts stage requested",{accountKeys:Y});let W=await Promise.all(Y.map((B)=>b$(B,X)));return _.debug("reset accounts stage built",{rows:W.map((B)=>({accountKey:B.accountKey,eligible:B.eligible,reason:B.reason,usedPercent:B.usedPercent,availableCount:B.availableCount,applicableAvailableCount:B.applicableAvailableCount}))}),{command:y0,text:w6(W),knobs:{stage:"accounts",accounts:W}}}if(G==="select"){let Q=Z1(J[1]);if(!Q||!i(Q)||J.length!==2)return g("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let Y=await b$(Q,X);if(!Y.eligible)return g(Q,"not_eligible",S$(Y));return{command:y0,text:S$(Y),knobs:{stage:"confirm",preview:Y}}}if(G==="confirm"||G==="retry"){let Q=Z1(J[1]),Y=Z1(J[2]);if(!Q||!i(Q)||!Y||J.length!==3)return g(Q??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);_.info("reset redemption decision",{accountKey:Q,action:G}),_.debug("reset redemption identity binding",{accountKey:Q,expectedChatgptAccountId:Y});try{let W=await I$({configPath:Z.accountStoragePath,statePath:Z.accountStatePath,mutateAccountsFn:G0,loadAccountsFn:Z.loadAccounts,now:X.now,randomUUID:X.randomUUID,fetchImpl:X.fetchImpl,resolveTarget:X.resolveResetTarget,fetchUsage:(B)=>d8({accessToken:B.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:Q,expectedChatgptAccountId:Y,retry:G==="retry"});return _.info("reset redemption outcome",{accountKey:Q,code:W.outcome.kind}),w$(W,X,Y)}catch(W){let B=f6(Q,W,Y);return _.info("reset redemption outcome",{accountKey:Q,code:B.knobs.code}),B}}return g("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var y6=new Set(["access","refresh","apikey","authheader","password","secret"]);function v6($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(y6.has(Z))return!0;return Z.endsWith("token")}function Z8($,Z,z){if(Array.isArray($))return $.map((J,G)=>Z8(J,`${Z}[${G}]`,z));if(!R$($))return $;let X={};for(let[J,G]of Object.entries($)){if(v6(J)){z.push(`${Z}.${J}`);continue}X[J]=Z8(G,`${Z}.${J}`,z)}return X}async function z1($,Z,z,X={}){let J=await h6($,Z,z,X),G=[],Q=Z8(J.knobs,"knobs",G);if(G.length>0)return _.warn("credential-shaped knob stripped before RPC",{command:$,fields:G}),{...J,knobs:Q};return J}async function h6($,Z,z,X){switch($){case"openai-quota":return T6(z);case"openai-account":return C6(Z,z);case"openai-routing":return b6(Z,z);case"openai-reset":return E6(Z,z);default:{let J=X[$];if(!J)throw Error(`unhandled command: ${$}`);return J(Z,z)}}}import{readdirSync as x9,statSync as F9}from"node:fs";import{tmpdir as I9,userInfo as R9}from"node:os";import{join as p0}from"node:path";import{debuglog as t6}from"node:util";import{createHmac as l6,randomBytes as d6,timingSafeEqual as i6}from"node:crypto";import u6 from"node:net";var p=2,G8=21,Q8=5,X1=67108864,H;(function($){$[$.Request=0]="Request",$[$.Response=1]="Response",$[$.Push=2]="Push",$[$.StreamData=3]="StreamData",$[$.StreamEnd=4]="StreamEnd",$[$.Error=5]="Error",$[$.Cancel=6]="Cancel",$[$.Ping=7]="Ping",$[$.Pong=8]="Pong",$[$.Hello=9]="Hello",$[$.HelloAck=10]="HelloAck",$[$.Goodbye=11]="Goodbye"})(H||(H={}));var f$=H.Goodbye;function E$($){return $===H.Cancel||$===H.Ping||$===H.Pong||$===H.Goodbye}var C;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(C||(C={}));var w;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(w||(w={}));var m6=1,y$=6,J1=1,g6=8,v$=48,G1=4,h$=192;function v($,Z,z,X=w.Normal){let J=0;if($)J|=m6;if(J|=Z<<J1,z)J|=g6;return J|=X<<G1,J}function m$($){let Z=new Uint8Array(21),z=new DataView(Z.buffer);return z.setUint32(0,$.len,!0),Z[4]=$.ver,Z[5]=$.ty,Z[6]=$.flags,z.setUint16(7,$.channel,!0),z.setUint32(9,$.epoch,!0),z.setBigUint64(13,$.corr,!0),Z}class x extends Error{code;constructor($,Z){super($);this.code=Z,this.name="DecodeError"}}function p6($){let Z=$.len>>>0,z=$.ver>>>0&255,X=$.ty>>>0&255,J=$.flags>>>0&255,G=$.channel>>>0&65535,Q=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),z!==2)throw new x(`unsupported envelope version ${z}`,"unsupported_version");if(X>f$)throw new x(`unknown frame type byte ${X}`,"unknown_frame_type");let Y=X;if((J&h$)!==0)throw new x(`reserved flag bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((J&y$)>>J1===3)throw new x(`reserved priority bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(J&v$)>>G1;if(W===3)throw new x(`reserved admission class set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===w.Sheddable&&Y!==H.Push&&Y!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[Y]} in flags 0b${J.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(G===0&&Q!==0)throw new x(`control channel carried nonzero epoch ${Q}`,"nonzero_epoch_on_control_channel");if(E$(Y)&&Z!==0)throw new x(`pure-header frame ${H[Y]} declared non-zero body length ${Z}`,"pure_header_frame_with_body")}function Q1($){if($.length<5)throw new x(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let Z=$[4];if(Z!==2)throw new x(`unsupported envelope version ${Z}`,"unsupported_version");if($.length<21)throw new x(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let z=new DataView($.buffer,$.byteOffset,$.byteLength),X=z.getUint32(0,!0),J=$[5];if(J>f$)throw new x(`unknown frame type byte ${J}`,"unknown_frame_type");let G=J,Q=$[6];if((Q&h$)!==0)throw new x(`reserved flag bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((Q&y$)>>J1===3)throw new x(`reserved priority bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Y=(Q&v$)>>G1;if(Y===3)throw new x(`reserved admission class set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Y===w.Sheddable&&G!==H.Push&&G!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[G]} in flags 0b${Q.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let W=z.getUint16(7,!0),B=z.getUint32(9,!0);if(W===0&&B!==0)throw new x(`control channel carried nonzero epoch ${B}`,"nonzero_epoch_on_control_channel");if(E$(G)&&X!==0)throw new x(`pure-header frame ${H[G]} declared non-zero body length ${X}`,"pure_header_frame_with_body");return{len:X,ver:Z,ty:G,flags:Q,channel:W,epoch:B,corr:z.getBigUint64(13,!0)}}function E($,Z,z,X,J,G){return a(2,$,Z,z,X,J,G)}function a($,Z,z,X,J,G,Q){if(Q.length>67108864)throw new x(`frame body ${Q.length} exceeds max 67108864`,"frame_body_too_large");let Y={len:Q.length,ver:$,ty:Z,flags:z,channel:X,epoch:J,corr:G};return p6(Y),{header:Y,body:Q}}function t($){if($.header.len!==$.body.length)throw new x(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let Z=m$($.header),z=new Uint8Array(Z.length+$.body.length);return z.set(Z,0),z.set($.body,Z.length),z}class Z0 extends Error{}class s extends Error{}class o extends Error{cause;constructor($,Z){super($);this.cause=Z}}class Q0 extends Error{cause;constructor($,Z){super($);this.cause=Z}}function g$($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var p$=Symbol("subc.socket.writeBorrowed"),u$=Symbol("subc.socket.writeTrackedBorrowed");function r($,Z,z){let X=$[p$];return X?X.call($,Z,z):$.write(Z,z)}function Y1($,Z,z){let X=$[u$];return X?X.call($,Z,z):$.writeTracked(Z,z)}class H0{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor($){this.sock=$,$.on("data",(z)=>{this.chunks.push(z),this.buffered+=z.length,this.tryServe()});let Z=(z)=>{if(!this.closedErr)this.closedErr=z;this.tryServe()};$.on("error",(z)=>Z(z instanceof Error?z:Error(String(z)))),$.on("end",()=>Z(new Z0("subc closed the connection"))),$.on("close",()=>Z(new Z0("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,Z,z){return new Promise((X,J)=>{let G=u6.connect({host:$,port:Z});G.setNoDelay(!0);let Q=setTimeout(()=>{G.destroy(),J(new s(`timed out connecting to ${$}:${Z}`))},Math.max(0,z-Date.now()));G.once("connect",()=>{clearTimeout(Q),X(new H0(G))}),G.once("error",(Y)=>{clearTimeout(Q),J(Y)})})}async readFrame($,Z,z){let X=await this.readExact(Q8,$),J=X[4];if(J!==p)throw new x(`unsupported envelope version ${J}`,"unsupported_version");let G=await this.readExact(G8-Q8,$),Q=new Uint8Array(G8);Q.set(X),Q.set(G,Q8);let Y=Q1(Q);if(Y.len>X1)throw new x(`frame body ${Y.len} exceeds max ${X1}`,"frame_body_too_large");z?.();let W=typeof Z==="number"?Z:Date.now()+Z.afterHeaderMs,B=Y.len===0?new Uint8Array(0):await this.readExact(Y.len,W);return{header:Y,body:B}}readExact($,Z){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((z,X)=>{let J=null;if(Number.isFinite(Z)){let G=Z-Date.now();if(G<=0){X(new s(`timed out waiting for ${$} bytes`));return}J=setTimeout(()=>{this.waiter=null,X(new s(`timed out waiting for ${$} bytes`))},G)}this.waiter={need:$,resolve:z,reject:X,timer:J},this.tryServe()})}async write($,Z){await this.writeBuffer(Buffer.from($),Z)}writeTracked($,Z){return this.writeTrackedBuffer(Buffer.from($),Z)}async[p$]($,Z){await this.writeBuffer(g$($),Z)}[u$]($,Z){return this.writeTrackedBuffer(g$($),Z)}async writeBuffer($,Z){try{await this.writeTrackedBuffer($,Z).completed}catch(z){if(z instanceof o||z instanceof Q0)throw z.cause??z;throw z}}writeTrackedBuffer($,Z){if(this.closedErr)return{queued:!1,completed:Promise.reject(new o("subc socket was closed before bytes could be queued",this.closedErr))};let z=!1,X=!1,J=null,G=new Promise((Q,Y)=>{let W=(V)=>{if(X)return;if(X=!0,J)clearTimeout(J);V()},B=Z-Date.now();if(B<=0){W(()=>Y(new o("timed out before bytes could be queued to subc",new s("timed out writing to subc"))));return}J=setTimeout(()=>{let V=new s("timed out writing to subc");W(()=>Y(z?new Q0("timed out after bytes were handed to the subc socket",V):new o("timed out before bytes could be queued to subc",V)))},B);try{this.sock.write($,(V)=>{W(()=>{if(V)Y(new Q0("subc socket reported a write error after bytes were handed to the socket",V instanceof Error?V:Error(String(V))));else Q()})}),z=!0}catch(V){W(()=>Y(new o("subc socket write threw before bytes could be queued",V instanceof Error?V:Error(String(V)))))}});return{queued:z,completed:G}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let Z=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(Z);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let Z=Buffer.allocUnsafe($),z=0;while(z<$){let X=this.chunks[0],J=$-z;if(X.length<=J)X.copy(Z,z),z+=X.length,this.chunks.shift();else X.copy(Z,z,0,J),this.chunks[0]=X.subarray(J),z+=J}return this.buffered-=$,Z}}var i$=32;var Y8=4096,c$="subc-server-v1",s$="subc-client-v1",c6="client";class y extends Error{}function B1($,Z,z,X,J){let G=l6("sha256",Buffer.from($));return G.update(Buffer.from(Z,"utf8")),G.update(Buffer.from(z)),G.update(Buffer.from(X)),G.update(Buffer.from(J)),new Uint8Array(G.digest())}function l$($,Z){if($.length!==Z.length)return!1;return i6(Buffer.from($),Buffer.from(Z))}async function d$($,Z,z){let X=Buffer.from(JSON.stringify(Z),"utf8");if(X.length>Y8)throw new y(`auth message too large: ${X.length} > ${Y8}`);let J=new Uint8Array(4);new DataView(J.buffer).setUint32(0,X.length,!0),await r($,J,z),await r($,X,z)}async function s6($,Z){let z=await $.readExact(4,Z),X=new DataView(z.buffer,z.byteOffset,4).getUint32(0,!0);if(X>Y8)throw new y(`auth message too large: ${X} > ${Y8}`);let J=X===0?new Uint8Array(0):await $.readExact(X,Z);try{return JSON.parse(Buffer.from(J).toString("utf8"))}catch(G){throw new y(`auth message JSON decode failed: ${String(G)}`)}}function W1($,Z){if(!Array.isArray($))throw new y(`auth field '${Z}' must be a byte array`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new y(`auth field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}async function v0($,Z,z){let X=new Uint8Array(d6(i$));await d$($,{client_nonce:Array.from(X),role:c6},z);let J=await s6($,z),G=W1(J.server_nonce,"server_nonce"),Q=W1(J.daemon_id,"daemon_id"),Y=W1(J.server_proof,"server_proof"),W=B1(Z.key,c$,X,G,Q);if(!l$(W,Y))throw new y("server proof mismatch — wrong key or impostor daemon");if(!l$(Q,Z.daemonId))throw new y("daemon id mismatch — connection file points at a different daemon");let B=B1(Z.key,s$,X,G,Q);await d$($,{client_auth:Array.from(B)},z)}import{promises as V1}from"node:fs";var n$=1,a$=32,t$=16;class b extends Error{}function o$($,Z){if(!Array.isArray($))throw new b(`connection file field '${Z}' must be a JSON array of bytes`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new b(`connection file field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}function n6($){if($.schema!==n$)throw new b(`unsupported connection file schema ${$.schema}; expected ${n$}`);if($.endpoints.length===0)throw new b("connection file must include at least one endpoint");if($.key.length<a$)throw new b(`connection file key is too short: ${$.key.length} bytes, need at least ${a$}`);if($.daemonId.length!==t$)throw new b(`connection file daemon_id must be ${t$} bytes, got ${$.daemonId.length}`)}async function a6($){if(process.platform==="win32")return;let z=(await V1.stat($)).mode&511;if((z&63)!==0)throw new b(`connection file ${$} has insecure permissions 0o${z.toString(8)}; expected owner-only 0600`)}async function P0($){await a6($);let Z=await V1.readFile($,"utf8"),z;try{z=JSON.parse(Z)}catch(Y){throw new b(`connection file JSON read failed for ${$}: ${String(Y)}`)}let X=z.wire_version;if(X!==void 0&&X!==p)throw new b(`connection file wire_version ${String(X)} but this client speaks ${p}; the client library must be upgraded`);let J=z.endpoints;if(!Array.isArray(J))throw new b("connection file 'endpoints' must be an array");let G=J.map((Y)=>{let W=Y;if(typeof W.host!=="string"||typeof W.port!=="number")throw new b("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),Q={schema:z.schema,endpoints:G,key:o$(z.key,"key"),daemonId:o$(z.daemon_id,"daemon_id"),pid:z.pid,daemonVer:z.daemon_ver??""};return n6(Q),Q}var r$=new WeakMap;class W8{channel;epoch;constructor($,Z,z){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(Z)||Z<=0||Z>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${Z}`);this.channel=$,this.epoch=Z,r$.set(this,z),Object.freeze(this)}static create($,Z,z){return new W8($,Z,z)}}function B8($,Z,z){return W8.create($,Z,z)}class z0 extends Error{handle;code="stale_route_handle";constructor($){super(`route handle (${$.channel}, ${$.epoch}) is not live on the current connection`);this.handle=$,this.name="StaleRouteHandleError"}}function O0(){return Object.freeze({})}function h0($,Z){return r$.get($)===Z}function V8($,Z){return $===Z}var o6=t6("subc-client"),r6=1e4,m0=30000,e6=50,$9=2000,e$="request_deadline",j1="deadline_exceeded_no_drop_observed",Z9=30000,z9=30000,$3=new Uint8Array(0),X9="management_surface",z3="SUBC_MODULE_ID",X3="SUBC_LAUNCH_NONCE",L8={baseMs:100,capMs:2000,maxAttempts:6};class S extends Error{kind;code;cause;constructor($,Z,z,X){super(Z);this.kind=$,this.code=z,this.cause=X,this.name="SubcCallError"}}class F extends Error{code;constructor($,Z){super($);this.code=Z}}class K0{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=O0();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,Z,z){this.sock=$,this.currentConn=Z,this.opts=z,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let Z=G9($),z=await K0.openConnection(Z);return new K0(z.sock,z.conn,Z)}async catalogList($){let Z=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),z=await this.controlRpc(Z);return this.parseJson(z).modules??[]}async routeOpen($,Z,z={}){let X=q1(z),J=z.consumerCapabilities,G=this.encode({op:"route.open",target:$,identity:Z,...X?{consumer_identity:X}:{},...J!==void 0?{consumer_capabilities:J}:{}}),Q=null,Y=(B)=>{if(B.header.ty!==H.Response)return!0;let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")throw new F(`route.open returned no route handle: ${JSON.stringify(V)}`);return Q=this.installRoute(V.route_channel,V.route_epoch),!0},W=(B)=>{if(B.header.ty!==H.Response)return;try{let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")return;let j=this.installRoute(V.route_channel,V.route_epoch);this.failHandle(j,new F("late route.open was closed","route_closed")),this.liveRoutes.delete(j.channel),this.sendRouteGoodbye(j,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(G,Y,W),!Q)throw new F("route.open response was not installed");return Q}async request($,Z,z={}){this.assertLiveHandle($);let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??w.Normal,Q=await this.send($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}async call($,Z,z,X={}){let J=z===void 0?{method:Z}:{method:Z,params:z},G=!1;for(;;){let Q=await this.cachedRouteHandle($,X);try{return await this.managedRequest(Q,J,X)}catch(Y){if(!(Y instanceof S))throw this.terminalCallError("managed call failed",Y);let W=Y.code==="unknown_channel"||Y.code==="stale_route_epoch";if(W&&!G&&!this.closeStarted){G=!0,this.evictRouteHandle(Q);continue}if(W&&G)this.evictRouteHandle(Q);if(Y.kind==="not_sent"){try{await this.reconnectAfterDrop(Y)}catch(B){throw this.notSentRecoveryError("managed call was not sent",B)}continue}if(Y.kind==="outcome_unknown"&&Y.code!==j1)this.scheduleReconnectAfterDrop(Y);else if(Y.kind==="outcome_unknown"&&Y.code===j1)this.probeLivenessAfterDeadline();throw Y}}}subscribe($,Z,z,X={}){this.assertLiveHandle($);let J=Z instanceof Uint8Array?Z:this.encode(Z),G=X.priority??C.Interactive,Q=X.admissionClass??w.Normal,Y=this.allocateCorr(),W=q8($,Y),B=null,V=null,j=new Promise((L,U)=>{if(this.closedErr){U(this.closedErr);return}V=L,B={handle:$,resolve:()=>L(),reject:U,onProgress:z,timer:null,subscription:!0},this.pending.set(W,B);let D=E(H.Request,v(!1,G,!1,Q),$.channel,$.epoch,Y,J);r(this.sock,t(D),Date.now()+m0).catch((P)=>{let A=this.pending.get(W);if(A)this.rejectPending(W,A,P instanceof Error?P:new F(String(P)))})}),q=!1;return{unsubscribe:()=>{if(q)return;if(q=!0,B&&V)this.settle(W,B,V);if(this.isLiveHandle($))this.cancel($,Y,G)},closed:j}}cancel($,Z,z=C.Interactive){this.assertLiveHandle($);let X=E(H.Cancel,v(!1,z,!1),$.channel,$.epoch,Z,$3);r(this.sock,t(X),Date.now()+m0).catch(()=>{return})}async routePoll($,Z){this.assertLiveHandle($);let z=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:Z}),X=await this.controlRpc(z,(J)=>{if(J.header.ty!==H.Response)return!0;let G=this.parseJson(J);return G.route_channel===$.channel&&G.route_epoch===$.epoch});return this.parseJson(X)}async closeRoute($,Z={}){this.assertLiveHandle($);for(let[z,X]of this.routes)if(X.handle&&V8(X.handle,$))X.closed=!0,X.handle=null,this.routes.delete(z);if(Z.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new F("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,Z,z={}){let X=Z3($,Z,q1(z)),J=this.routes.get(X);if(!J)return;J.closed=!0,this.routes.delete(X);let G=J.handle;if(J.handle=null,G)await this.closeRoute(G,z)}async closeRouteChannel($,Z={}){await this.closeRoute($,Z)}close(){this.closeStarted=!0,this.fail(new F("client closed")),this.sock.close()}drainUnaryOnHandle($){let Z=[];for(let z of this.pending.values())if(z.handle===$&&!z.subscription)Z.push(new Promise((X)=>{let J=z.onSettle;z.onSettle=()=>{J?.(),X()}}));return Promise.all(Z).then(()=>{return})}sendRouteGoodbye($,Z=!1){if(this.assertLiveConnection($),this.closedErr){if(Z)this.closeConnectionAfterCleanupFailure();return}let z=E(H.Goodbye,v(!1,C.Interactive,!1),$.channel,$.epoch,0n,$3),X=Y1(this.sock,t(z),Date.now()+m0);if(!X.queued&&Z)this.closeConnectionAfterCleanupFailure();X.completed.catch(()=>{if(Z&&!X.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let Z=await P0($.connectionFile),z=Date.now()+($.handshakeTimeoutMs??r6),X=Z.endpoints[0],J=await H0.connect(X.host,X.port,z);try{await v0(J,Z,z)}catch(G){throw J.close(),G}return{sock:J,conn:Z}}async controlRpc($,Z,z){return this.send(null,$,C.Interactive,w.Normal,void 0,void 0,Z,z)}send($,Z,z,X,J,G,Q,Y){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let W;try{W=this.allocateCorr()}catch(K){return Promise.reject(K)}let B=q8($,W),V=$?.channel??0,j=$?.epoch??0,q=E(H.Request,v(!1,z,!1,X),V,j,W,Z);return new Promise((K,L)=>{let U=J??m0,D={handle:$,resolve:K,reject:L,onProgress:G,timer:null,acceptFrame:Q,onLateResponse:Y};D.timer=setTimeout(()=>this.arbitrateTimeout(B,D,V,W,U),U),this.pending.set(B,D),r(this.sock,t(q),Date.now()+U).catch((P)=>{let A=this.pending.get(B);if(A)this.rejectPending(B,A,P instanceof Error?P:new F(String(P)))})})}arbitrateTimeout($,Z,z,X,J){let G=()=>{if(Z.onLateResponse)this.lateResponses.set($,Z.onLateResponse);this.rejectPending($,Z,new F(this.timeoutMessage(z,X,J),e$))},Q=Date.now()+this.opts.timeoutArbitrationGraceMs,Y=()=>{if(this.pending.get($)!==Z)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<Q){setImmediate(Y);return}G()};setImmediate(Y)}async managedRequest($,Z,z){let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??w.Normal;try{let Q=await this.sendManaged($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}catch(Q){if(Q instanceof S)throw Q;throw this.terminalCallError("managed call failed",Q)}}sendManaged($,Z,z,X,J,G){try{this.assertLiveHandle($)}catch(j){return Promise.reject(this.notSentCallError("request used a stale route handle",j))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let Q;try{Q=this.allocateCorr()}catch(j){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",j))}let Y=q8($,Q),W=E(H.Request,v(!1,z,!1,X),$.channel,$.epoch,Q,Z),B=!1,V=(j)=>{if(!B)return this.notSentCallError("request bytes were not queued to the subc socket",j);if(j instanceof F&&j.code===e$)return new S("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${j8(j)}`,j1,j);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",j)};return new Promise((j,q)=>{let K=J??m0,L={handle:$,resolve:j,reject:q,onProgress:G,timer:null,classifyFailure:V};L.timer=setTimeout(()=>this.arbitrateTimeout(Y,L,$.channel,Q,K),K),this.pending.set(Y,L);let U=Y1(this.sock,t(W),Date.now()+K);B=U.queued,U.completed.catch((D)=>{let P=this.pending.get(Y);if(P)this.rejectPending(Y,P,D instanceof Error?D:new F(String(D)))})})}async cachedRouteHandle($,Z){let z=Z.identity??this.opts.identity;if(!z)throw new S("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let X={kind:Z.targetKind??this.opts.targetKind,module_id:$},J=q1(Z),G=Z3(X,z,J),Q=this.routes.get(G);if(!Q)Q={key:G,moduleId:$,target:X,identity:z,consumerIdentity:J,handle:null,opening:null},this.routes.set(G,Q);if(Q.handle&&this.isLiveHandle(Q.handle))return Q.handle;if(!Q.opening)Q.opening=this.openCachedRoute(Q).finally(()=>{Q.opening=null});return Q.opening}async openCachedRoute($){let Z=Date.now()+Z9,z=this.opts.reconnectBackoff.baseMs,X=0;for(;;){if($.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(J){throw this.notSentRecoveryError("route.open could not run because reconnect failed",J)}if($.handle&&this.isLiveHandle($.handle))return $.handle;try{let J=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed)throw this.liveRoutes.delete(J.channel),this.sendRouteGoodbye(J),this.routeClosedDuringOpen();return $.handle=J,J}catch(J){if(J instanceof S&&J.code==="route_closed")throw J;if(!this.closeStarted&&H8(J)){try{await this.reconnectAfterDrop(J)}catch(G){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",G)}continue}if(!this.closeStarted&&J instanceof F&&J9(J.code)){if(X+=1,X<this.opts.reconnectBackoff.maxAttempts&&Date.now()<Z){await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${$.moduleId}: ${J.code} (retry budget exhausted)`,J)}throw this.terminalCallError(`route.open failed for module ${$.moduleId}`,J)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let $ of this.pending.values())if($.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let $=this.sock,Z=this.generation,z;try{z=this.allocateCorr()}catch{return}let X=Date.now(),J=E(H.Ping,v(!1,C.Interactive,!1,w.Normal),0,0,z,new Uint8Array),G=(async()=>{if(await r($,t(J),X+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==Z||this.closeStarted)return;if(this.lastInboundAtMs>=X)return;if(this.hasControlPending())return;this.fail(new Z0(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`)),$.close()})().finally(()=>{this.livenessProbe=null});this.livenessProbe=G}async ensureConnectedForManaged(){if(this.closeStarted)throw new F("client closed");if(this.reconnecting)await this.reconnecting;if(this.closedErr)await this.reconnectAfterDrop(this.closedErr)}scheduleReconnectAfterDrop($){if(this.closeStarted||this.reconnecting)return;this.reconnectAfterDrop($).catch(()=>{})}reconnectAfterDrop($){if(this.closeStarted)return Promise.reject(new F("client closed"));if(this.reconnecting)return this.reconnecting;let Z=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===Z)this.reconnecting=null});return this.reconnecting=Z,Z}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new F("client closed");Z+=1;try{let X=await K0.openConnection(this.opts);if(this.closeStarted)throw X.sock.close(),new F("client closed");this.replaceConnection(X),await this.reopenCachedRoutes();return}catch(X){if(!H8(X)||Z>=this.opts.reconnectBackoff.maxAttempts){if(X instanceof y&&Z>1)throw new y(`reconnect gave up after ${Z} attempts: ${X.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw X}await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection($){this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.closedErr=null,this.generation+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop($.sock,this.generation)}async reopenCachedRoutes(){for(let $ of this.routes.values())$.handle=null;for(let $ of this.routes.values()){if($.closed)continue;let Z=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed){this.liveRoutes.delete(Z.channel),this.sendRouteGoodbye(Z);continue}$.handle=Z}}timeoutMessage($,Z,z){let X=this.sock.localPort();return`request on ${X===null?"channel":`local_port=${X} channel`} ${$} corr ${Z} timed out after ${z}ms`}routeClosedDuringOpen(){return new S("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,Z){try{for(;;){this.readerActive=!1;let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:z9},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===Z)this.dispatch(z)}finally{this.readerActive=!1}}}catch(z){if(this.sock===$&&this.generation===Z)this.fail(z instanceof Error?z:new F(String(z)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===H.Push){let G=this.opts.onControlPush;if(G){let Q=null;try{let Y=this.parseJson($);if(Y&&typeof Y.op==="string")Q={op:Y.op,body:Y}}catch{}if(Q)try{G(Q)}catch{}}return}let Z=null;if($.header.channel!==0){if(Z=this.liveRoutes.get($.header.channel)??null,!Z||Z.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}let z=q8(Z,$.header.corr),X=this.pending.get(z);if(X){if(X.acceptFrame&&!X.acceptFrame($))return;switch($.header.ty){case H.Push:case H.StreamData:try{X.onProgress?.($.body)}catch{}return;case H.Response:case H.StreamEnd:this.settle(z,X,()=>X.resolve($));return;case H.Error:this.settle(z,X,()=>X.reject(this.errorFromFrame($)));return;default:return}}let J=this.lateResponses.get(z);if(J&&($.header.ty===H.Response||$.header.ty===H.Error)){this.lateResponses.delete(z),J($);return}if($.header.ty===H.Goodbye&&Z){if(this.failHandle(Z,new F("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(Z.channel)===Z)this.liveRoutes.delete(Z.channel);this.evictRouteHandle(Z);return}if($.header.ty===H.Response||$.header.ty===H.Error||$.header.ty===H.StreamEnd)o6("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",$.header.ty,$.header.channel,$.header.epoch,$.header.corr,this.sock.localPort()??"?")}settle($,Z,z){if(this.pending.get($)!==Z)return!1;if(this.pending.delete($),Z.timer)clearTimeout(Z.timer);return z(),Z.onSettle?.(),!0}rejectPending($,Z,z){this.settle($,Z,()=>Z.reject(Z.classifyFailure?.(z)??z))}errorFromFrame($){try{let Z=JSON.parse(Buffer.from($.body).toString("utf8"));return new F(Z.message??"subc error",Z.code)}catch{return new F(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let Z of this.routes.values())if(Z.handle&&V8(Z.handle,$))Z.handle=null}failHandle($,Z){for(let[z,X]of this.pending)if(X.handle&&V8(X.handle,$))this.rejectPending(z,X,Z)}fail($){if(!this.closedErr)this.closedErr=$;for(let[Z,z]of this.pending)this.rejectPending(Z,z,$)}notSentCallError($,Z){return new S("not_sent",`${$}${j8(Z)}`,K8(Z),Z)}outcomeUnknownCallError($,Z){return new S("outcome_unknown",`${$}${j8(Z)}`,K8(Z),Z)}terminalCallError($,Z){if(Z instanceof S)return Z;return new S("terminal",`${$}${j8(Z)}`,K8(Z),Z)}notSentRecoveryError($,Z){if(Z instanceof S)return Z;if(H8(Z))return this.notSentCallError($,Z);return this.terminalCallError($,Z)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,Z){let z=B8($,Z,this.connectionToken);return this.liveRoutes.set($,z),z}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!h0($,this.connectionToken))throw new z0($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new F("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(z),this.sock.close(),this.scheduleReconnectAfterDrop(z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}closeConnectionAfterCleanupFailure(){let $=new F("late route cleanup could not be queued","late_route_cleanup_failed");this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($)}encode($){return Buffer.from(JSON.stringify($),"utf8")}parseJson($){let Z=$.body;return JSON.parse(Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength).toString("utf8"))}}function H8($){if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof S)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof y)return!0;if($ instanceof F||$ instanceof b)return!1;let Z=K8($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function J9($){return $==="unknown_module"||$==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}function G9($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??X9,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??e6,livenessProbeWindowMs:$.livenessProbeWindowMs??$9,onControlPush:$.onControlPush}}function Z3($,Z,z){let X=z?`${z.module_id}\x00${z.launch_nonce}`:"";return`${$.kind}\x00${$.module_id}\x00${Z.project_root}\x00${Z.harness}\x00${Z.session}\x00${X}`}function q1($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let Z=process.env[z3],z=process.env[X3];if(!Z||!z)return;return{module_id:Z,launch_nonce:z}}function K8($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}function j8($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function q8($,Z){return $?`${$.channel}:${$.epoch}:${Z}`:`0:0:${Z}`}import{Buffer as N1}from"node:buffer";var Q9=1e4,Y9=30000,G3=30000,W9=250,H1=64,L1="health.check",Q3=1n;class U8{available;waiters=[];constructor($){if(!Number.isInteger($)||$<=0)throw new I("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=$}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise(($)=>{this.waiters.push($)}),this.releaseOnce()}releaseOnce(){let $=!1;return()=>{if($)return;$=!0;let Z=this.waiters.shift();if(Z)Z();else this.available+=1}}}class I extends Error{code;kind;constructor($,Z,z="terminal"){super($);this.code=Z,this.kind=z}}class g0{sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=O0();nextCorr=1n;ingressEpochDropCount=0;requestGate=new U8(H1);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;constructor($,Z,z,X){this.sock=$,this.currentConn=Z,this.opts=z,this.storage=X,this.closed=new Promise((J)=>{this.resolveClosed=J}),this.readLoop($,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request($,Z,z={}){this.assertLiveHandle($);let X=this.allocateCorr(),J=N8($,X),G=z.timeoutMs??G3,Q=E(H.Request,v(!1,z.priority??C.Interactive,!1,z.admissionClass??w.Normal),$.channel,$.epoch,X,Z);return await new Promise((Y,W)=>{let B=setTimeout(()=>{if(this.pending.delete(J))W(new I("reverse request timed out","request_timeout"))},G);this.pending.set(J,{resolve:(V)=>Y(V.body),reject:W,timer:B}),this.sendOn(this.sock,this.generation,Q).catch((V)=>{let j=this.pending.get(J);if(!j)return;this.pending.delete(J),clearTimeout(j.timer),W(V instanceof Error?V:new I(String(V)))})})}async push($,Z,z={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,E(H.Push,v(!1,z.priority??C.Interactive,!1,z.admissionClass??w.Normal),$.channel,$.epoch,0n,Z))}cancel($,Z){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,E(H.Cancel,e(),$.channel,$.epoch,Z,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,E(H.Goodbye,e(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==p)throw new I(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${p}`,"invalid_manifest");let Z=q9($),z=await g0.openConnection(Z);return new g0(z.sock,z.conn,Z,z.ack.storage)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await K1($,E(H.Goodbye,e(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,Z){let z=await P0($.connectionFile),X=Date.now()+($.handshakeTimeoutMs??Q9),J=z.endpoints[0],G=await H0.connect(J.host,J.port,X);try{Z?.(G),await v0(G,z,X),await K1(G,K9($));let Q=await D9(G,X);return{sock:G,conn:z,ack:Q}}catch(Q){throw G.close(),Q}}async readLoop($,Z){try{for(;;){let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:Y9});if(!await this.dispatch(z,$,Z)){if(this.sock===$&&this.generation===Z)this.closeStarted=!0;break}}}catch(z){if(this.sock===$&&this.generation===Z&&!this.closeStarted){this.handleUnexpectedDrop($,Z,z instanceof Error?z:new I(String(z)));return}}finally{if(this.sock===$&&this.generation===Z){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,Z,z){let X=null;if($.header.channel!==0){if(X=this.liveRoutes.get($.header.channel)??null,!X||X.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(X){let J=N8(X,$.header.corr),G=this.pending.get(J);if(G){if($.header.ty===H.Push||$.header.ty===H.StreamData)return!0;if($.header.ty===H.Response||$.header.ty===H.StreamEnd)return this.pending.delete(J),clearTimeout(G.timer),G.resolve($),!0;if($.header.ty===H.Error)return this.pending.delete(J),clearTimeout(G.timer),G.reject(B9($)),!0}}switch($.header.ty){case H.Ping:if($.header.channel===0)await this.sendOn(Z,z,a($.header.ver,H.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case H.Goodbye:if(!X)return!1;return this.liveRoutes.delete(X.channel),this.abortHandle(X),await this.opts.onRouteGone?.(X),!0;case H.Cancel:if(X)this.inflight.get(N8(X,$.header.corr))?.abort();return!0;case H.Request:if($.header.channel===0)await this.handleControlRequest($,Z,z);else if(X)this.handleDataRequest($,X,Z,z).catch((J)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider handler failed after its request was dispatched",J)});return!0;default:return!0}}abortHandle($){let Z=`${$.channel}:${$.epoch}:`;for(let[z,X]of this.inflight)if(z.startsWith(Z))X.abort();for(let[z,X]of this.pending){if(!z.startsWith(Z))continue;this.pending.delete(z),clearTimeout(X.timer),X.reject(new z0($))}}abortGeneration($){this.abortAllInflight();for(let[Z,z]of this.pending)this.pending.delete(Z),clearTimeout(z.timer),z.reject(new I("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,Z,z){let X=P8($.body);if(X.op===L1){this.handleHealthRequest($,Z,z).catch((j)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider health handler failed after its request was dispatched",j)});return}if(X.op!=="route.bind")throw new I(`unsupported module control request ${X.op??"<missing op>"}`);let J=J3(X.route_channel,"route_channel"),G=J3(X.epoch,"epoch"),Q=this.liveRoutes.get(J);if(Q){if(G<=Q.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${G} does not supersede installed epoch ${Q.epoch} on channel ${J}`,e(),Z,z);return}this.liveRoutes.delete(Q.channel),this.abortHandle(Q),await this.opts.onRouteGone?.(Q)}let Y=B8(J,G,this.connectionToken),W={handle:Y,target:X.target,identity:X.identity,principal:X.principal,consumer_capabilities:X.consumer_capabilities},B;try{B=await this.opts.onBind?.(W)}catch(j){try{await this.sendError($,"route_rejected",j instanceof Error?j.message:String(j),e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}let V=P9(B);if(V){try{await this.sendError($,V.code,V.message,e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}try{await this.sendOn(Z,z,a($.header.ver,H.Response,e(),0,0,$.header.corr,D8({op:"route.bind"})))}catch(j){throw await this.opts.onRouteGone?.(Y),j}if(this.sock!==Z||this.generation!==z||this.closeStarted||this.closedErr){await this.opts.onRouteGone?.(Y);return}this.liveRoutes.set(Y.channel,Y),await this.opts.onBound?.(Y)}async handleDataRequest($,Z,z,X){let{corr:J,ver:G}=$.header,Q=N8(Z,J),Y=new AbortController;this.inflight.set(Q,Y);let W={handle:Z,signal:Y.signal,currentEpoch:()=>this.connectionEpoch,emit:async(j,q={})=>{if(this.assertLiveHandle(Z),Y.signal.aborted)return;await this.sendOn(z,X,a(G,H.StreamData,v(!1,q.priority??C.Interactive,!1,q.admissionClass??w.Normal),Z.channel,Z.epoch,J,j))}},B=await(this.requestGate??new U8(H1)).acquire(),V=v(!1,C.Interactive,!1);try{if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}let j=await this.opts.handler(Z,$.body,W);if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}if(this.assertLiveHandle(Z),j===void 0)await this.sendOn(z,X,a(G,H.StreamEnd,V,Z.channel,Z.epoch,J,new Uint8Array(0)));else if(j instanceof Uint8Array)await this.sendOn(z,X,a(G,H.Response,V,Z.channel,Z.epoch,J,j));else throw new I("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(j){if(j instanceof z0)return;if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}await this.sendError($,j instanceof I&&j.code?j.code:"handler_error",j instanceof Error?j.message:String(j),V,z,X)}finally{if(B(),this.inflight.get(Q)===Y)this.inflight.delete(Q)}}async handleHealthRequest($,Z,z){let{corr:X,ver:J}=$.header,G=`control:${z}:${X}`,Q=new AbortController;this.inflight.set(G,Q);let Y=await(this.requestGate??new U8(H1)).acquire();try{if(Q.signal.aborted)return;let W=await this.opts.health();await this.sendOn(Z,z,a(J,H.Response,e(),0,0,X,D8({op:L1,status:W.status,...W.detail===void 0?{}:{detail:W.detail},...W.metrics===void 0?{}:{metrics:W.metrics}})))}catch(W){await this.sendError($,W instanceof I&&W.code?W.code:"health_error",W instanceof Error?W.message:String(W),e(),Z,z)}finally{if(Y(),this.inflight.get(G)===Q)this.inflight.delete(G)}}async sendError($,Z,z,X,J,G){if($.header.channel!==0){let Q=this.liveRoutes.get($.header.channel);if(!Q||Q.epoch!==$.header.epoch||!this.isLiveHandle(Q))return}await this.sendOn(J,G,a($.header.ver,H.Error,X,$.header.channel,$.header.epoch,$.header.corr,D8({code:Z,message:z})))}async sendOn($,Z,z){if(this.sock!==$||this.generation!==Z||this.closeStarted||this.closedErr)return;await K1($,z)}handleUnexpectedDrop($,Z,z){if(this.closeStarted||this.sock!==$||this.generation!==Z)return;this.cancelRestoredDebounce(),this.abortGeneration(Z),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(z,this.generation,$)}scheduleReconnectAfterDrop($,Z,z){if(this.closeStarted)return;let X=this.reconnecting;if(X){if(!this.shouldSupersedeReconnect(X,Z,z))return;X.superseded=!0,X.socket?.close()}let J={generation:Z,socket:null,socketDied:!1,superseded:!1};this.reconnecting=J,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(J).catch((G)=>{if(this.isCurrentReconnect(J)&&!this.closeStarted)this.failFatal(G instanceof Error?G:new I(String(G)))}).finally(()=>{if(this.isCurrentReconnect(J))this.reconnecting=null})}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new I("provider closed");$.socket=null,$.socketDied=!1,Z+=1,this.enqueueReconnectState($,Z);try{let X=await g0.openConnection(this.opts,(G)=>{if(!this.isCurrentReconnect($)){G.close();return}$.socket=G});if(!this.isCurrentReconnect($)||this.closeStarted){if(X.sock.close(),this.closeStarted)throw new I("provider closed");return}let J=this.replaceConnection(X,$.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new I("reconnect state must clear before restored","reconnect_state");this.scheduleRestored($.generation,J);return}catch(X){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw X;if(!L9(X))throw X;await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,Z,z){return $.generation<Z||$.socketDied||$.socket===z}enqueueReconnectState($,Z){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:Z},$.generation,$)}replaceConnection($,Z){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,Z),this.connectionEpoch}scheduleRestored($,Z){if(!this.opts.onConnectionState)return;let z=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if(z===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===$&&this.connectionEpoch===Z)this.enqueueConnectionState({state:"restored",epoch:Z},$)}).catch((X)=>{if(z===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",X)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,Z,z){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:Z,reconnect:z}),!this.drainingStateQueue)this.drainConnectionStateQueue()}async drainConnectionStateQueue(){if(this.drainingStateQueue)return;this.drainingStateQueue=!0;try{while(this.stateQueue.length>0){let $=this.stateQueue[0];if(this.closeStarted||$.generation!==void 0&&$.generation!==this.generation||$.reconnect?.superseded){this.stateQueue.shift();continue}let{event:Z}=$;try{await this.opts.onConnectionState?.(Z),this.stateQueue.shift()}catch(z){if(Z.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",z),await U9();continue}console.warn("SubcProvider connection-state callback failed",z),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new I("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function N8($,Z){return`${$.channel}:${$.epoch}:${Z}`}function B9($){try{let Z=P8($.body);return new I(Z.message??"subc error",Z.code,Z.code==="stale_route_epoch"||Z.code==="unknown_channel"?"not_sent":"terminal")}catch{return new I(N1.from($.body).toString("utf8")||"subc error")}}function V9($){let Z=$.launchNonce??process.env[j9];return Z&&Z.length>0?Z:void 0}var j9="SUBC_LAUNCH_NONCE";function q9($){return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),restoredDebounceMs:$.restoredDebounceMs??W9,onConnectionState:$.onConnectionState,launchNonce:$.launchNonce}}function H9($){if($===null)return null;let Z=new Set($??[]);return Z.add(L1),[...Z]}function K9($){let Z=V9($);return E(H.Hello,e(),0,0,Q3,D8({manifest:O9($.manifest),protocol_ver:p,control_ops:H9($.controlOps),...Z?{launch_nonce:Z}:{}}))}function L9($){if($ instanceof I)return $.code==="duplicate_module_id";if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof y)return!0;if($ instanceof b)return!1;let Z=N9($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function N9($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}async function U9(){await new Promise(($)=>setTimeout($,0))}function e(){return v(!1,C.Passive,!1)}async function K1($,Z){await r($,t(Z),Date.now()+G3)}async function D9($,Z){let z=await $.readFrame(Z,Z);switch(z.header.ty){case H.HelloAck:{let X=P8(z.body);if(X.negotiated_ver!==p)throw new I(`subc negotiated protocol ${X.negotiated_ver}; expected exactly ${p}`,"unsupported_version");return X}case H.Error:{let X=P8(z.body);throw new I(`subc rejected HELLO: ${X.code??"unknown"} — ${X.message??"subc error"}`,X.code)}default:throw new I(`unexpected frame ${H[z.header.ty]} awaiting HELLO_ACK`)}}function D8($){return new Uint8Array(N1.from(JSON.stringify($),"utf8"))}function P8($){return JSON.parse(N1.from($).toString("utf8"))}function J3($,Z){if(typeof $!=="number"||!Number.isInteger($))throw new I(`route.bind ${Z} must be an integer`);return $}function P9($){if($===void 0||$===!0)return null;if($===!1)return{code:"route_rejected",message:"route.bind rejected by provider"};if($.accept)return null;return{code:$.code??"route_rejected",message:$.message??"route.bind rejected by provider"}}function O9($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(M9),consumes:$.consumes.map(_9),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((Z)=>({secret:Z.secret,reason:Z.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function M9($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((Z)=>({name:Z.name,...Z.description===void 0?{}:{description:Z.description},execution_mode:Z.execution_mode,schema:Z.schema})),identity_scope:[...$.identity_scope],concurrency:$.concurrency,emits_push:$.emits_push,sub_supervises:$.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:$.stage,applies_to:{provider:$.applies_to.provider,model:$.applies_to.model},interface:$.interface,declares_frozen_floor:$.declares_frozen_floor,needs_signals:[...$.needs_signals],conformance_class:$.conformance_class};case"management_surface":return{role:"management_surface",operations:$.operations.map((Z)=>({name:Z.name,kind:Z.kind})),config_schema:$.config_schema,observability:$.observability.map((Z)=>({name:Z.name,kind:Z.kind})),identity_scope:[...$.identity_scope],concurrency:$.concurrency};case"internal_service":return{role:"internal_service",service_id:$.service_id,transport:$.transport,agent_facing:$.agent_facing,operations:[...$.operations]}}}function _9($){switch($.role){case"tool_client":return{role:"tool_client",of:[...$.of]};case"llm_client":return{role:"llm_client",via:$.via,auth:$.auth};case"service_client":return{role:"service_client",of:[...$.of]}}}var O8="subc-connection.json",A9="subc-",T9=".connection.json";function Y3(){let $=process.env.HOME;return $?p0($,".local","share","cortexkit","run",O8):void 0}function C9(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($)return p0($,O8);let Z=Y3();if(Z)return Z;return p0(R9().homedir,".local","share","cortexkit","run",O8)}function b9(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($){let X=p0($,O8);if(U1(X))return X}let Z=Y3();if(Z&&U1(Z))return Z;let z=S9(I9());return z.length===1?z[0]:void 0}function D1(){return b9()??C9()}function P1($){return $?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||D1()}function U1($){try{return F9($).isFile()}catch{return!1}}function S9($){let Z;try{Z=x9($)}catch{return[]}let z=[];for(let X of Z){if(typeof X!=="string")continue;if(!X.startsWith(A9)||!X.endsWith(T9))continue;let J=p0($,X);if(U1(J))z.push(J)}return z.sort(),z}import{createHash as k9}from"node:crypto";import{existsSync as w9,realpathSync as W3}from"node:fs";import{dirname as f9,relative as E9,resolve as y9}from"node:path";function B3($){let Z=$,z;try{z=W3(Z)}catch(X){if(X.code!=="ENOENT")throw X;let J=Z;while(!w9(J)){let G=f9(J);if(G===J)break;J=G}z=y9(W3(J),E9(J,Z))}return k9("sha256").update(z).digest("hex")}function O1($,Z){return{project_root:$,harness:"opencode",session:`store-${B3(Z)}`}}var V3=["transient","permanent","auth_required","context_overflow"];class _0 extends Error{code;action;["class"];constructor($,Z,z){super(`Claustrum credential request failed: ${$}`);this.code=$,this.action=z,this.name="ClaustrumCredentialError",this.class=Z}}function M0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j3($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function M($,Z="invalid_response",z=(X)=>console.warn(X)){let X=M0($)&&M0($.result)?$.result:void 0,J=X&&M0(X.error)?X.error:void 0,G=J?.class,Q=J?.code,Y=typeof G==="string"&&V3.includes(G),W=typeof Q==="string",V=Y&&W?G:"transient";if(typeof G!=="string")z("unknown");else if(!Y)z(G);return new _0(W?Q:Z,V,j3(V))}function L0($){return M0($)&&M0($.result)&&M0($.result.error)}var q3="claustrum",m9=60000;function u($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _1($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0?$:void 0}function X0($){return $===void 0||typeof $==="string"}function H3($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.payload;if(!Array.isArray(X)||X.length===0||!X.every((q)=>typeof q==="number"&&Number.isInteger(q)&&q>=0&&q<=255))throw M($,"invalid_response",Z);let J=_1(z?.record_version);if(J===void 0)throw M($,"invalid_record_version",Z);let G=z?.expires_at_ms,Q=G===void 0||G===null?null:typeof G==="number"&&Number.isFinite(G)?G:void 0;if(Q===void 0)throw M($,"invalid_expiry",Z);let Y=z?.credential_id,W=z?.project_id,B=z?.account_id,V=z?.email,j=z?.org_name;if(!X0(Y)||!X0(W)||!X0(B)||!X0(V)||!X0(j))throw M($,"invalid_response",Z);return{material:new TextDecoder().decode(Uint8Array.from(X)),recordVersion:J,expiresAtMs:Q,credentialId:Y,projectId:W,accountId:B,email:V,orgName:j}}function g9($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=_1(z?.record_version);if(typeof z?.ready!=="boolean"||z?.last_error_code!==void 0&&z?.last_error_code!==null&&typeof z?.last_error_code!=="string"||typeof z?.lease_held!=="boolean"||X===void 0||z?.stale_pending!==void 0&&typeof z.stale_pending!=="boolean")throw M($,"invalid_status",Z);return{ready:z.ready,lastErrorCode:z.last_error_code??null,leaseHeld:z.lease_held,recordVersion:X,...z.stale_pending===void 0?{}:{stalePending:z.stale_pending}}}class M8{#z;#J;#B;#Y;#G;#$;#X=null;#Q=0;#W=!1;constructor($,Z,z,X,J,G){this.#z=$,this.#J=Z,this.#B=z,this.#Y=X,this.#G=J,this.#$=G}static async connect($={}){let Z=P1($.connectionFile),z=$.connector??((G)=>K0.connect(G)),X=$.identity??O1($.projectRoot??process.cwd(),$.storagePath??process.cwd()),J=await z({connectionFile:Z,handshakeTimeoutMs:$.handshakeTimeoutMs});return new M8(J,z,Z,$.handshakeTimeoutMs,X,$.logger??((G)=>console.warn(G)))}async getCredential($,Z){let z=await this.#Z("credential.get",{handle:$,min_ttl_ms:Z,force_refresh:!1});return H3(z,this.#$)}async statusCredential($){let Z=await this.#Z("credential.status",{handle:$});return g9(Z,this.#$)}async reportAuthFailure($){let Z=await this.#Z("credential.report_auth_failure",{handle:$.handle,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async listScoped($){let Z=await this.#Z("credential.list_scoped",$===void 0?{}:{enrollment_token:$});return p9(Z,this.#$)}async getScoped($){let Z=await this.#Z("credential.get_scoped",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,min_ttl_ms:$.minTtlMs});return H3(Z,this.#$)}async reportAuthFailureScoped($){let Z=await this.#Z("credential.report_auth_failure",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async enrollPropose($){let Z=await this.#Z("auth.enroll_propose",{proposed_name:$.name,request_secret_hash:$.requestSecretHash}),X=M1(Z,this.#$).request_id;if(typeof X!=="string"||X.length===0)throw M(Z,"invalid_response",this.#$);return{requestId:X}}async enrollPoll($){let Z=await this.#Z("auth.enroll_poll",{request_id:$.requestId,request_secret:$.requestSecret});return u9(Z,this.#$)}async enrollRotate($){let Z=await this.#Z("auth.enroll_rotate",{token:$.token,expected_token_generation:$.expectedTokenGeneration}),z=M1(Z,this.#$),X=z.token,J=z.token_generation;if(typeof X!=="string"||X.length===0||typeof J!=="number")throw M(Z,"invalid_response",this.#$);return{token:X,tokenGeneration:J}}close(){this.#W=!0,this.#z.close()}async#Z($,Z){try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(z){if(this.#j(z)){try{await this.#q()}catch(X){throw this.#V(X)}try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(X){throw this.#V(X)}}throw this.#V(z)}}#V($){if($ instanceof _0)return $;let Z=$ instanceof S&&$.code?$.code:"transport_error";return new _0(Z,"transient","retry")}#j($){return!this.#W&&$ instanceof S&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"}async#q(){if(this.#W)throw Error("Claustrum client is closed");if(this.#X){await this.#X;return}let $=Date.now();if($<this.#Q)throw Error("Claustrum client reconnect is backed off");this.#Q=$+m9,this.#X=this.#J({connectionFile:this.#B,handshakeTimeoutMs:this.#Y}).then((Z)=>{if(this.#W)throw Z.close(),Error("Claustrum client is closed");let z=this.#z;this.#z=Z,z.close()}).finally(()=>{this.#X=null}),await this.#X}}function p9($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.credentials;if(!Array.isArray(X))throw M($,"invalid_response",Z);let J=z?.view;if(typeof J!=="string"||J.length===0)throw M($,"invalid_response",Z);return{rows:X.map((Q)=>{if(!u(Q))throw M($,"invalid_response",Z);let Y=_1(Q.record_version);if(Y===void 0)throw M($,"invalid_record_version",Z);let W=(V)=>{if(!Array.isArray(V)||!V.every((j)=>typeof j==="string"))throw M($,"invalid_response",Z);return V};if(typeof Q.id!=="string"||typeof Q.type!=="string"||typeof Q.state!=="string")throw M($,"invalid_response",Z);let B=Q.created_at_ms===void 0||Q.created_at_ms===null?null:typeof Q.created_at_ms==="number"&&Number.isFinite(Q.created_at_ms)?Q.created_at_ms:void 0;if(B===void 0)throw M($,"invalid_response",Z);if(!X0(Q.refresh_adapter))throw M($,"invalid_response",Z);if(!X0(Q.account_id)||!X0(Q.email)||!X0(Q.org_name))throw M($,"invalid_response",Z);return{id:Q.id,categories:W(Q.categories),credentialType:Q.type,serves:W(Q.serves),state:Q.state,refreshAdapter:Q.refresh_adapter,recordVersion:Y,operations:W(Q.operations),createdAtMs:B,accountId:Q.account_id,email:Q.email,orgName:Q.org_name}}),view:J}}function M1($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0;if(z===void 0)throw M($,"invalid_response",Z);return z}function u9($,Z){let z=M1($,Z),X=z.status;if(X==="pending")return{status:"pending"};if(X==="denied")return{status:"denied"};if(X!=="approved")throw M($,"invalid_response",Z);let{name:J,token:G,token_generation:Q}=z;if(typeof J!=="string"||typeof G!=="string"||G.length===0||typeof Q!=="number"||!Number.isInteger(Q))throw M($,"invalid_response",Z);return{status:"approved",name:J,token:G,tokenGeneration:Q}}l8();var VZ=d("quota");var K3={name:"@cortexkit/pi-openai-auth",version:"0.11.1",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/openai-auth-core":"workspace:*"},peerDependencies:{"@earendil-works/pi-ai":">=0.80.10","@earendil-works/pi-coding-agent":">=0.80.10","@earendil-works/pi-tui":">=0.80.10"}};import{homedir as i9}from"node:os";import{join as L3}from"node:path";function c9(){return process.env.PI_AGENT_DIR?.trim()||L3(i9(),".pi","agent")}function N3(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||L3(c9(),n0)}function s9($=N3()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||g8($)}function U3($=N3()){return{configPath:$,statePath:s9($)}}var D3=new Map;function P3($){return D3.get($)}function O3($){return D3.delete($)}var n9={auth:{set:async()=>{}}};async function a9($,Z){let z=(Z.accountPaths??U3)(),X=Z.loadAccounts??B$,J=await X(z),G=new n({storage:null,configPath:z.configPath,fetchImpl:Z.fetchImpl,now:Z.now});return G.seedFallbacksFromAccounts((J?.accounts??[]).filter(m8)),{accountStoragePath:z.configPath,accountStatePath:z.statePath,packageVersion:Z.packageVersion??K3.version,quotaManager:G,loadAccounts:X,client:n9,sessionId:$.sessionManager.getSessionId(),notify:(Q)=>$.ui.notify(Q.text),clearStickyRouting:async(Q)=>O3(Q),getStickyRouting:async(Q)=>P3(Q),fetchImpl:Z.fetchImpl,now:Z.now,randomUUID:Z.randomUUID,beginAccountLogin:Z.beginAccountLogin}}async function t9($,Z,z,X={}){return z1($,Z,await a9(z,X))}async function x1($,Z,z,X){let J=await t9($,Z,z,X);z.ui.notify(J.text)}function M3($,Z={}){$.registerCommand(X8,{description:"List, add, remove, or reorder OpenAI fallback accounts",handler:(z,X)=>x1(X8,z,X,Z)}),$.registerCommand(z8,{description:"Show persisted OpenAI quota for fallback accounts",handler:(z,X)=>x1(z8,z,X,Z)}),$.registerCommand(J8,{description:"Show or change OpenAI account routing mode",handler:(z,X)=>x1(J8,z,X,Z)})}import{connect as o9}from"node:net";import{connect as r9}from"node:tls";var e9="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",_3=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class F1{url;readyState=0;socket;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor($,Z){this.url=$,this.connect($,Z)}addEventListener($,Z,z){this.listeners[$]?.add(Z)}removeEventListener($,Z){this.listeners[$]?.delete(Z)}emit($,Z){for(let z of[...this.listeners[$]??[]])try{z(Z)}catch{}}async connect($,Z){let z=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),X=z.hostname,J=z.port?Number(z.port):z.protocol==="https:"?443:80,G=`${z.pathname}${z.search}`,Q=crypto.getRandomValues(new Uint8Array(16)),Y=Buffer.from(Q).toString("base64"),W=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(Y+e9));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let B={};for(let[q,K]of Object.entries(Z))B[q.toLowerCase()]=K;let V=[`GET ${G} HTTP/1.1`,`Host: ${X}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${Y}`];for(let q of _3)if(B[q]!==void 0)V.push(`${$2(q)}: ${B[q]}`);for(let[q,K]of Object.entries(Z))if(!_3.includes(q.toLowerCase())&&q.toLowerCase()!=="content-length")V.push(`${q}: ${K}`);let j=`${V.join(`\r
211
211
  `)}\r
212
212
  \r
213
213
  `;try{this.log("connect_start",{host:X,port:J,tls:z.protocol==="https:"});let q=()=>{this.socket?.write(j)},K=z.protocol==="https:"?r9({host:X,port:J,servername:X},q):o9({host:X,port:J},q);this.socket=K,K.on("data",(L)=>{this.onData(typeof L==="string"?Buffer.from(L,"binary"):L)}),K.on("error",(L)=>{this.readyState=3;let U=L instanceof Error?L.message:String(L);this.log("socket_error",{message:U}),this.emit("error",{message:U})}),K.on("close",(L)=>{this.readyState=3,this.log("socket_close",{hadError:L}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(q){this.readyState=3,this.log("connect_exception",{message:q instanceof Error?q.message:String(q)}),this.emit("error",{message:q instanceof Error?q.message:String(q)})}}onData($){if(this.rxBuffer=Z2(this.rxBuffer,$),!this.handshakeDone){let Z=Buffer.from(this.rxBuffer).toString("latin1"),z=Z.indexOf(`\r
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/pi-openai-auth",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {