@cortexkit/opencode-openai-auth 1.2.0 → 1.3.0

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.
Files changed (49) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{codex-request-CjXETpTA.d.ts → codex-request-B9D0e97Q.d.ts} +145 -28
  3. package/dist/{index-ehjj89rx.js → index-1mbgsxsr.js} +1 -1
  4. package/dist/{index-htvcmtcx.js → index-2pgkrebq.js} +1 -1
  5. package/dist/{index-rwbrhkse.js → index-4v2fs42x.js} +1 -1
  6. package/dist/index-8x1aj7q3.js +2 -0
  7. package/dist/{index-6n4pnfkg.js → index-ex6nx3mq.js} +1 -1
  8. package/dist/{index-qxbchh2d.js → index-gn2b097f.js} +1 -1
  9. package/dist/{index-qp5hdpw8.js → index-m3ctrabv.js} +1 -1
  10. package/dist/{index-03em8hv1.js → index-psjyexj3.js} +15 -15
  11. package/dist/{index-ffg0sgg5.js → index-tddr876f.js} +1 -1
  12. package/dist/index-tn8x5tz8.js +90 -0
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +1 -1
  15. package/dist/{model-CQcw10oW.d.ts → model-BdITTmeb.d.ts} +1 -1
  16. package/dist/{port-file-BDJnzgHH.d.ts → port-file-DbHIVC9a.d.ts} +1 -1
  17. package/dist/{protocol-C-kagE6O.d.ts → protocol-MysYPAho.d.ts} +1 -1
  18. package/dist/rpc/port-file.d.ts +1 -1
  19. package/dist/rpc/port-file.js +1 -1
  20. package/dist/rpc/protocol.d.ts +1 -1
  21. package/dist/rpc/protocol.js +1 -1
  22. package/dist/rpc/rpc-client.d.ts +3 -3
  23. package/dist/rpc/rpc-client.js +1 -1
  24. package/dist/{sidebar-state-BfQ4mpZO.d.ts → sidebar-state-CVSok7zv.d.ts} +20 -4
  25. package/dist/sidebar-state.d.ts +1 -1
  26. package/dist/sidebar-state.js +1 -1
  27. package/dist/tui-preferences.js +1 -1
  28. package/dist/tui.d.ts +2 -2
  29. package/dist/v2/server.d.ts +2 -2
  30. package/dist/v2/server.js +1 -1
  31. package/package.json +4 -4
  32. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +69 -1
  33. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +225 -16
  34. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +130 -5
  35. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +10 -2
  36. package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +106 -0
  37. package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +286 -21
  38. package/src/tui-compiled/raw/shared/dc9290c2a7552ba6-watch.js +253 -0
  39. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +4 -1
  40. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +69 -1
  41. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +225 -16
  42. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +130 -5
  43. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +10 -2
  44. package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +106 -0
  45. package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +286 -21
  46. package/src/tui-compiled/runtime/shared/dc9290c2a7552ba6-watch.js +253 -0
  47. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +4 -1
  48. package/dist/index-f21addzm.js +0 -90
  49. package/dist/index-r2s51ac1.js +0 -2
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{c as _0}from"./index-qp5hdpw8.js";import{Cb as I0,Fa as j0,Ga as E,Ha as O,Ia as v,kb as A0,ta as k0,ua as f,va as o}from"./index-03em8hv1.js";import{$c as R0,gd as m,hd as P,jd as c,kd as q0}from"./index-f21addzm.js";import"./index-qxbchh2d.js";import{Ee as e,Ke as Y0,Le as C0,Oe as w0}from"./index-ehjj89rx.js";import"./index-r2s51ac1.js";import"./index-xwvze96g.js";import{spawn as L0}from"node:child_process";var M=4096,S0=1048576;class t{buffer=Buffer.alloc(M);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=M){if(G.length>M||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-M),this.start=0,this.length=M;return}let b=Math.max(0,this.length+G.length-M);if(b>0)this.truncated=!0;this.start=(this.start+b)%M,this.length-=b;let z=(this.start+this.length)%M,J=Math.min(G.length,M-z);if(G.copy(this.buffer,z,0,J),J<G.length)G.copy(this.buffer,0,J);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),b=Math.min(this.length,M-this.start);if(this.buffer.copy(G,0,this.start,this.start+b),b<this.length)this.buffer.copy(G,b,0,this.length-b);let z=0;while(z<G.length){let J=G[z];if(J===void 0||(J&192)!==128)break;z++}return G.subarray(z).toString("utf8")}}var A={run(G,b,z={}){return new Promise((J)=>{let K=performance.now(),Q=z.timeoutMs??15000,$=new t,W=[],q=0,Z=!1,x=!1,D=!1,U;try{U=L0(G,[...b],{env:z.env??process.env,windowsHide:!0,windowsVerbatimArguments:z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{J({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let j=Q>0?setTimeout(()=>{D=!0,U.kill("SIGTERM")},Q):void 0;U.stdout?.on("data",(X)=>{let R=S0-q,F=Math.min(R,X.length);if(F>0)W.push(X.subarray(0,F)),q+=F;if(X.length>R)Z=!0,U.kill("SIGTERM")}),U.stderr?.on("data",(X)=>$.push(X));let V=!1,B=(X,R)=>{if(V)return;if(V=!0,j)clearTimeout(j);J({exitCode:x?1:Z?1:X??1,stdout:Buffer.concat(W,q).toString("utf8"),stderr:$.toString(),stderrTruncated:$.didTruncate,...x?{spawnError:!0}:{},signal:R??null,timedOut:D,durationMs:performance.now()-K})};U.once("error",()=>{if(x=!0,U.pid===void 0)B(null,null)}),U.once("close",(X,R)=>B(X,R))})}};function g(G,b,z,J,K,Q=15000){if(b==="win32"&&/\.(cmd|bat)$/i.test(z)){if(/["%!\r\n]/.test(z)||J.some(($)=>!/^[a-zA-Z0-9@:/._+-]+$/.test($)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${z}" ${J.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return G.run(z,J,{env:K,timeoutMs:Q})}var y0="Pi install failed; run pi install after checking your npm connection.";function v0(G){let b=Buffer.from(G,"utf8");if(b.length<=M)return G;let z=b.length-M;while(z<b.length){let J=b[z];if(J===void 0||(J&192)!==128)break;z++}return b.subarray(z).toString("utf8")}function E0(G){let b=G.indexOf(`
2
+ import{c as _0}from"./index-m3ctrabv.js";import{Cb as I0,Fa as j0,Ga as E,Ha as O,Ia as v,kb as A0,ta as k0,ua as f,va as o}from"./index-psjyexj3.js";import{$c as R0,gd as m,hd as P,jd as c,kd as q0}from"./index-tn8x5tz8.js";import"./index-gn2b097f.js";import{Ee as e,Ke as Y0,Le as C0,Oe as w0}from"./index-1mbgsxsr.js";import"./index-8x1aj7q3.js";import"./index-xwvze96g.js";import{spawn as L0}from"node:child_process";var M=4096,S0=1048576;class t{buffer=Buffer.alloc(M);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=M){if(G.length>M||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-M),this.start=0,this.length=M;return}let b=Math.max(0,this.length+G.length-M);if(b>0)this.truncated=!0;this.start=(this.start+b)%M,this.length-=b;let z=(this.start+this.length)%M,J=Math.min(G.length,M-z);if(G.copy(this.buffer,z,0,J),J<G.length)G.copy(this.buffer,0,J);this.length+=G.length}toString(){let G=Buffer.alloc(this.length),b=Math.min(this.length,M-this.start);if(this.buffer.copy(G,0,this.start,this.start+b),b<this.length)this.buffer.copy(G,b,0,this.length-b);let z=0;while(z<G.length){let J=G[z];if(J===void 0||(J&192)!==128)break;z++}return G.subarray(z).toString("utf8")}}var A={run(G,b,z={}){return new Promise((J)=>{let K=performance.now(),Q=z.timeoutMs??15000,$=new t,W=[],q=0,Z=!1,x=!1,D=!1,U;try{U=L0(G,[...b],{env:z.env??process.env,windowsHide:!0,windowsVerbatimArguments:z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{J({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let j=Q>0?setTimeout(()=>{D=!0,U.kill("SIGTERM")},Q):void 0;U.stdout?.on("data",(X)=>{let R=S0-q,F=Math.min(R,X.length);if(F>0)W.push(X.subarray(0,F)),q+=F;if(X.length>R)Z=!0,U.kill("SIGTERM")}),U.stderr?.on("data",(X)=>$.push(X));let V=!1,B=(X,R)=>{if(V)return;if(V=!0,j)clearTimeout(j);J({exitCode:x?1:Z?1:X??1,stdout:Buffer.concat(W,q).toString("utf8"),stderr:$.toString(),stderrTruncated:$.didTruncate,...x?{spawnError:!0}:{},signal:R??null,timedOut:D,durationMs:performance.now()-K})};U.once("error",()=>{if(x=!0,U.pid===void 0)B(null,null)}),U.once("close",(X,R)=>B(X,R))})}};function g(G,b,z,J,K,Q=15000){if(b==="win32"&&/\.(cmd|bat)$/i.test(z)){if(/["%!\r\n]/.test(z)||J.some(($)=>!/^[a-zA-Z0-9@:/._+-]+$/.test($)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${z}" ${J.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return G.run(z,J,{env:K,timeoutMs:Q})}var y0="Pi install failed; run pi install after checking your npm connection.";function v0(G){let b=Buffer.from(G,"utf8");if(b.length<=M)return G;let z=b.length-M;while(z<b.length){let J=b[z];if(J===void 0||(J&192)!==128)break;z++}return b.subarray(z).toString("utf8")}function E0(G){let b=G.indexOf(`
3
3
  `);return b<0?"":G.slice(b+1)}class d extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(y0);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let b=G.stderrTruncated?E0(G.stderrTail):G.stderrTail,z=e(b);this.stderrTail=v0(typeof z==="string"?z:"")}}var f0={opencode:"OpenCode",pi:"Pi"},g0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function G0({host:G,outcome:b}){return`${f0[G]}: ${g0[b]}`}var d0=new WeakMap;function b0(G,b){if(typeof G!=="object"&&typeof G!=="function"||!G)return;d0.set(G,Object.freeze(b.map((z)=>Object.freeze({...z}))))}import{accessSync as p0,constants as l0,existsSync as a0,readFileSync as i0,realpathSync as s0,statSync as r0}from"node:fs";import{mkdtemp as n0,rm as o0}from"node:fs/promises";import{tmpdir as t0}from"node:os";import{join as e0}from"node:path";import{parse as G1}from"jsonc-parser";import{homedir as m0}from"node:os";import{posix as c0,win32 as h0}from"node:path";import{fileURLToPath as u0}from"node:url";function N(G={}){let b=G.env??process.env,z=G.platform??process.platform,J=z==="win32"?h0:c0,K=G.home??(z==="win32"?b.USERPROFILE:b.HOME)??m0(),Q=G.cwd??process.cwd(),$=(x)=>J.resolve(Q,x),W=b.OPENCODE_CONFIG_DIR?.trim(),q=b.XDG_CONFIG_HOME?.trim(),Z=b.PI_CODING_AGENT_DIR?.trim()||J.join(K,".pi","agent");if(Z==="~")Z=K;else if(/^~[/\\]/.test(Z))Z=J.join(K,Z.slice(2));if(Z.startsWith("file://"))Z=u0(Z);return{env:b,platform:z,path:J,home:K,cwd:Q,opencode:W?$(W):q?J.join($(q),"opencode"):J.join(K,".config","opencode"),pi:$(Z)}}function h(G,b){try{return r0(G)[b]()}catch{return!1}}var _={exists:a0,isFile:(G)=>h(G,"isFile"),isDirectory:(G)=>h(G,"isDirectory"),isExecutable(G){try{return p0(G,l0.X_OK),h(G,"isFile")}catch{return!1}},readText:(G)=>i0(G,"utf8"),realpath:s0};function k(G,b={}){let{env:z,platform:J,path:K,cwd:Q}=N(b),$=b.fs??_,W=Object.entries(z).find(([Z])=>J==="win32"?Z.toUpperCase()==="PATH":Z==="PATH")?.[1]??"",q=J==="win32"?[".exe",".cmd",".bat",""]:[""];for(let Z of W.split(J==="win32"?";":":")){let x=Z.trim().replace(/^"|"$/g,"");if(!x)continue;for(let D of q){let U=K.resolve(Q,x,G+D);if(J==="win32"?$.isFile(U):$.isExecutable(U))return U}}return null}function z0(G={}){let{platform:b,home:z,env:J,path:K}=N(G);if(b==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",K.join(z,"Applications","OpenCode.app"),K.join(z,"Applications","OpenCode Beta.app")];if(b==="win32"){let Q=J.LOCALAPPDATA||K.join(z,"AppData","Local");return[K.join(Q,"Programs","opencode"),K.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",K.join(z,".local","share","applications","opencode.desktop")]}function u(G,b){let z=b.fs??_,{path:J}=N(b);try{let K=z.readText(G);if(K.length>65536)return G;let Q=[...K.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...K.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let $=Q.at(-1)?.[1];if($){let W=J.join(J.dirname(G),...$.split(/[/\\]+/));if(z.isFile(W))return z.realpath(W)}return z.realpath(G)}catch{return G}}function b1(G,b){let z=b.fs??_,{path:J}=N(b),K=J.dirname(u(G,b));for(;;){try{let $=JSON.parse(z.readText(J.join(K,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes($.name))return"2";if($.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test($.version??"")?"2":"1"}catch{}let Q=J.dirname(K);if(Q===K)return null;K=Q}}function J0(G={}){let b=k("opencode",G),z=k("opencode2",G),J=b&&z&&u(b,G)===u(z,G),K=G.fs??_,{path:Q,opencode:$}=N(G),W="1";for(let Z of["jsonc","json"]){let x=Q.join($,`opencode.${Z}`);if(!K.exists(x))continue;try{if(Object.hasOwn(G1(K.readText(x))??{},"plugins"))W="2"}catch{}break}let q=b?b1(b,G)??(J?"2":W):null;if(z&&q==="1"&&!J)return"ambiguous";return z||J?"2":q??W}async function p(G,b={}){let z=b.fs??_,{env:J,platform:K,opencode:Q,pi:$}=N(b),W=b.runner??A,q=k("opencode",b)??k("opencode2",b),Z=k("pi",b),x=k("ck",b),D=async(B)=>{if(!B)return null;let X;try{X=await n0(e0(t0(),"common-auth-setup-version-"));let R={...J,HOME:X,USERPROFILE:X,XDG_CONFIG_HOME:X,XDG_DATA_HOME:X,XDG_STATE_HOME:X,XDG_CACHE_HOME:X,OPENCODE_CONFIG_DIR:X,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:X},F=await g(W,K,B,["--version"],R,2000);return F.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(F.stdout)?.[0]??null:null}catch{return null}finally{if(X)await o0(X,{recursive:!0,force:!0}).catch(()=>{})}},U=!1;if(x&&z.exists(G.vault.connectionFile))try{(await(b.connect??m)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),U=!0}catch{U=!1}let[j,V]=await Promise.all([D(q),D(Z)]);return{opencode:{installed:z.isDirectory(Q)||z0(b).some((B)=>z.exists(B))||q!==null,executable:q,version:j,directory:Q,generation:J0(b)},pi:{installed:Z!==null||z.isDirectory($),executable:Z,version:V,directory:$},claustrum:{available:U,executable:x}}}import{setTimeout as U1}from"node:timers/promises";import{writeEnrollmentTokenFile as W1}from"@cortexkit/claustrum-client";var z1=45000,K0=new Set(["opencode","litecode","opencode2","pi"]),J1=new Set(["node","bun"]),K1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function Q1(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((b)=>b[1]??b[2]??"")}function Q0(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var Z1=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--title","--input-type","--preload","--cwd","-c","--config","--tsconfig-override","-d","--define","-l","--main-fields"]),$1=new Set(["-e","--eval","-p","--print"]);function q1(G,b){for(let z=0;z<b.length;z++){let J=b[z]??"";if(J==="--")return b[z+1];if($1.has(J))return;if(J.startsWith("-")){if(!J.includes("=")&&Z1.has(J))z++;continue}if(G==="bun"&&J==="run")continue;return J}return}function Z0(G){let[b,...z]=Q1(G);if(b===void 0)return null;let J=Q0(b);if(K0.has(J))return J;if(!J1.has(J))return null;let K=q1(J,z);if(K===void 0)return null;let Q=Q0(K);if(K0.has(Q))return Q;return K1.test(K)?"pi":null}class Y extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(G){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=G.step,this.exitCode=G.exitCode,this.signal=G.signal,this.timedOut=G.timedOut,this.durationMs=G.durationMs}get refusalText(){let G=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${G} after ${Math.round(this.durationMs)} ms.`}}class T extends Error{activeHosts;constructor(G){let b=G.map((z)=>({pid:z.pid,command:Z0(z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
4
4
  ${b.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
5
5
  `)}
@@ -9,6 +9,6 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);thi
9
9
  `:`
10
10
  `}},W=G,q=Q[b];if(q!==void 0&&!Array.isArray(q))throw Error(`OpenCode ${b} must be an array.`);let Z=Array.isArray(q)?[...q]:[],x=Z.flatMap((j,V)=>F0(j)===z?[V]:[]),D=`${z}@${J}`;if(!x.length)W=a(W,D0(W,q===void 0?[b]:[b,Z.length],q===void 0?[D]:D,$));else{let j=x[0],V=Z[j],B=Array.isArray(V)?[D,...V.slice(1)]:V&&typeof V==="object"?{...V,package:D}:D;if(JSON.stringify(V)!==JSON.stringify(B))W=a(W,D0(W,[b,j],B,$));for(let X of x.slice(1).reverse())W=V0(W,b,X)}let U=b==="plugin"?"plugins":"plugin";if(Array.isArray(Q[U])){let j=Q[U];for(let V=j.length-1;V>=0;V--)if(F0(j[V])===z)W=V0(W,U,V)}return W}function i(G,b,z={}){let J=z.fs??_,{path:K,opencode:Q}=N(z),$=b==="2"?"plugins":"plugin";return(b==="2"?["opencode"]:["opencode","tui"]).map((q)=>{let Z=K.join(Q,`${q}.jsonc`),x=K.join(Q,`${q}.json`),D=J.exists(Z)?Z:J.exists(x)?x:Z,U=J.exists(D),j=U?J.readText(D):`${JSON.stringify({$schema:`https://opencode.ai/${q==="tui"?"tui":"config"}.json`},null,2)}
11
11
  `,V=X0(j,$,G.packages.opencode,G.version);return{path:D,content:V,changed:!U||V!==j}})}async function s(G,b){for(let z of G){if(!z.changed)continue;await b?.(),await x0(z.path,z.content,{beforeRename:b})}}async function r(G,b,z={}){let{platform:J,env:K}=N(z),Q=await g(z.runner??A,J,b,["install",`npm:${G.packages.pi}@${G.version}`],K);if(Q.exitCode!==0||Q.timedOut)throw new d({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var O0="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function k1(G){let b={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,opencode:void 0};for(let z of G)if(z==="--yes")b.yes=!0;else if(z==="--dry-run")b.dryRun=!0;else if(z==="--claustrum")b.claustrum=!0;else if(z==="--no-claustrum")b.noClaustrum=!0;else if(z==="--login")b.login=!0;else if(/^--opencode=(1|2|both)$/.test(z))b.opencode=z.slice(11);else throw Error(`Unknown setup argument: ${z}`);if(b.claustrum&&b.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(b.login&&b.claustrum)throw Error("--login and --claustrum cannot be used together.");return b}function w1(G){for(let b of Object.values(G.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(b))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(G.version))throw Error("Setup requires a concrete package version.");for(let b of Object.values(G.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(b.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function A1(G,b,z){let J=[];for(let K of b){let Q=z.get(K)??"not-enrolled";if(Q==="unknown"){let{name:$,paths:W}=G.vault.hosts[K],q=await c(P(W),$).catch(()=>"unreadable");if(q==="vault")Q="enrolled";else if(q==="local")Q="not-enrolled"}J.push({host:K,outcome:Q})}return J}async function n(G,b=[],z={}){let J=k1(b);w1(G);let K=z.terminal??j0(),Q=await p(G,z);O(K,`${G.displayName} setup`);for(let[F,H]of[["OpenCode",Q.opencode],["Pi",Q.pi]])O(K,`${F}: ${H.installed?`found (version ${H.version??"unknown"})`:"not found"} — ${H.directory}`);O(K,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let $=Q.pi.installed&&!Q.pi.executable;if($)O(K,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let W=["opencode","pi"].filter((F)=>Q[F].installed&&!(F==="pi"&&$)),q=J.yes||J.dryRun&&!E(K);if(!q&&!E(K))throw Error("Setup requires a TTY or --yes.");let Z=q?W:await W0(K,W)??[],x=J.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(Z.includes("opencode")&&!J.opencode&&Q.opencode.generation==="ambiguous"){if(q||!E(K))throw Error(O0);let F=await v(K,[{value:"1",label:"OpenCode 1"},{value:"2",label:"OpenCode 2"},{value:"both",label:"Both (one compatible registration)"}],{message:"Which OpenCode generation should be registered?"});if(F===null)return{hosts:[],dryRun:J.dryRun,mode:"local",detection:Q};x=F}if(!Z.length)return O(K,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:Z,dryRun:J.dryRun,mode:"local",detection:Q};let{env:D,platform:U}=N(z),j=z.fence??S(z.runner??A,{platform:U}),V=async()=>{try{await y(j,D)}catch(F){if(F instanceof Y)O(K,F.refusalText);throw F}};if(O(K,"Checking that OpenCode and Pi are not running…"),J.dryRun)try{let F=j.previewRunningHosts?await j.previewRunningHosts(D):{hosts:await j.listRunningHosts(D),uncheckedRuntimes:0},H=F.hosts;if(F.uncheckedRuntimes>0)O(K,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let C=new Set(new T(H).activeHosts.map((w)=>w.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let w of C)O(K,`${w} is running; setup will ask you to quit it.`)}catch(F){if(O(K,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),F instanceof Y)O(K,F.refusalText)}else await V();if(J.claustrum&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck or use --no-claustrum for local sign-in.");let B=Boolean(J.claustrum);if(!B&&!J.login&&!J.noClaustrum&&!q&&Q.claustrum.available&&E(K)){let F=await v(K,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(F===null)return O(K,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:J.dryRun,mode:"local",detection:Q};B=F===!0}let X=B?"claustrum":"local",R=Z.includes("opencode")?i(G,x,z):[];if(J.dryRun){O(K,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let F of Z){if(G.beforeSignIn)O(K,`Would run beforeSignIn(${F}, ${X}).`);if(B){let H=P(G.vault.hosts[F].paths);O(K,`Would Connect ${F}: write ${H.statePath} and ${H.tokenPath}; wait for ck auth enroll approve.`)}else O(K,`Would sign in locally for ${F}.`);if(G.beforeRegister)O(K,`Would run beforeRegister(${F}, ${X}).`)}for(let F of R)O(K,`${F.changed?"Would write":"Unchanged"} ${F.path}:
12
- ${F.content}`);if(Z.includes("pi"))O(K,`Would run ${Q.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let F of Z)O(K,`Would migrate ${F} using the plugin callback (provider-specific writes).`)}else{let F={opencodeGeneration:x,mode:X,hosts:Object.freeze([...Z]),piAgentDir:Q.pi.directory},H=new Map;try{for(let C of Z){if(await V(),await G.beforeSignIn?.(C,F),await V(),B){H.set(C,"unknown");try{await U0(G,C,z,K,V)}catch(w){if(w instanceof I)H.set(C,"not-enrolled");throw w}H.set(C,"enrolled")}else await G.signInLocal(C,F);if(await V(),await G.beforeRegister?.(C,X,F),await V(),C==="opencode")await s(R,V);else await r(G,Q.pi.executable,z);await V(),await G.migrate(C,F)}}catch(C){if(H.size===0)throw C;try{let w=await A1(G,Z,H);b0(C,w);for(let P0 of w)O(K,G0(P0))}catch{}throw C}}return O(K,`${J.dryRun?"Planned":"Configured"} ${G.displayName} for ${Z.join(", ")} (${X}).`),O(K,`Next: ${Z.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`),{hosts:Z,dryRun:J.dryRun,mode:X,detection:Q}}import{basename as S1}from"node:path";import{resolveClaustrumConnectionPath as y1}from"@cortexkit/claustrum-client";var B0={name:"@cortexkit/pi-openai-auth",version:"1.2.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/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.19.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.10.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.16.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{homedir as _1}from"node:os";import{join as H0}from"node:path";function T1(){return process.env.PI_AGENT_DIR?.trim()||H0(_1(),".pi","agent")}function M0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||H0(T1(),Y0)}function P1(G=M0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||C0(G)}function N0(G=M0()){return{configPath:G,statePath:P1(G)}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.2.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.19.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.27"},dependencies:{"@cortexkit/claustrum-client":"^0.10.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.16.0","@opentui/core":">=0.6.1","@opentui/solid":">=0.6.1",ai:"^7.0.137","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};function T0(G={}){let b=G.print??console.log,z=G.fence??S(),J={opencode:{stateDir:o(A0().statePath),host:"opencode"},pi:{stateDir:o(N0().statePath),host:"pi"}},K=async(Q)=>{if(await c(P(J[Q]),f(Q))!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:L.name,pi:B0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:y1(),hosts:{opencode:{name:f("opencode"),paths:J.opencode},pi:{name:f("pi"),paths:J.pi}}},async beforeRegister(Q,$){if($==="claustrum"){if(b(`Allow this host to read OpenAI accounts with:
12
+ ${F.content}`);if(Z.includes("pi"))O(K,`Would run ${Q.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let F of Z)O(K,`Would migrate ${F} using the plugin callback (provider-specific writes).`)}else{let F={opencodeGeneration:x,mode:X,hosts:Object.freeze([...Z]),piAgentDir:Q.pi.directory},H=new Map;try{for(let C of Z){if(await V(),await G.beforeSignIn?.(C,F),await V(),B){H.set(C,"unknown");try{await U0(G,C,z,K,V)}catch(w){if(w instanceof I)H.set(C,"not-enrolled");throw w}H.set(C,"enrolled")}else await G.signInLocal(C,F);if(await V(),await G.beforeRegister?.(C,X,F),await V(),C==="opencode")await s(R,V);else await r(G,Q.pi.executable,z);await V(),await G.migrate(C,F)}}catch(C){if(H.size===0)throw C;try{let w=await A1(G,Z,H);b0(C,w);for(let P0 of w)O(K,G0(P0))}catch{}throw C}}return O(K,`${J.dryRun?"Planned":"Configured"} ${G.displayName} for ${Z.join(", ")} (${X}).`),O(K,`Next: ${Z.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`),{hosts:Z,dryRun:J.dryRun,mode:X,detection:Q}}import{basename as S1}from"node:path";import{resolveClaustrumConnectionPath as y1}from"@cortexkit/claustrum-client";var B0={name:"@cortexkit/pi-openai-auth",version:"1.3.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/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.21.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.12.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{homedir as _1}from"node:os";import{join as H0}from"node:path";function T1(){return process.env.PI_AGENT_DIR?.trim()||H0(_1(),".pi","agent")}function M0(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||H0(T1(),Y0)}function P1(G=M0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||C0(G)}function N0(G=M0()){return{configPath:G,statePath:P1(G)}}var L={name:"@cortexkit/opencode-openai-auth",version:"1.3.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.21.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.27"},dependencies:{"@cortexkit/claustrum-client":"^0.12.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0","@opentui/core":">=0.6.1","@opentui/solid":">=0.6.1",ai:"^7.0.137","jsonc-parser":"^3.3.1","solid-js":"1.9.12"}};function T0(G={}){let b=G.print??console.log,z=G.fence??S(),J={opencode:{stateDir:o(A0().statePath),host:"opencode"},pi:{stateDir:o(N0().statePath),host:"pi"}},K=async(Q)=>{if(await c(P(J[Q]),f(Q))!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:L.name,pi:B0.name},version:L.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:y1(),hosts:{opencode:{name:f("opencode"),paths:J.opencode},pi:{name:f("pi"),paths:J.pi}}},async beforeRegister(Q,$){if($==="claustrum"){if(b(`Allow this host to read OpenAI accounts with:
13
13
  ck auth grant --principal enrolled:${f(Q)} --selector-kind category --selector ${k0.category} --operation read`),Q==="opencode")b("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,$){if(await K(Q),Q==="pi"){b("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if($.opencodeGeneration!=="1"){let X=S1(k("opencode2",G.io)??k("opencode",G.io)??"opencode");b(`In OpenCode 2, run ${X} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if($.opencodeGeneration==="2")return;if(I0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let W=_0(),q={path:{id:"openai"}};if(await W.get(q)!==void 0){b("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let Z=G.beginLogin??R0,x=new AbortController,D=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),U={version:L.version,signal:x.signal},j,V=!D;try{j=await Z({...U,headless:D})}catch(X){if(D)throw X;V=!1,b("Browser callback unavailable; using device-code sign-in."),j=await Z({version:L.version,headless:!0})}if(V){if(!(G.openBrowser??w0)(j.url))x.abort(),await j.completion.catch(()=>{}),b("Browser unavailable; using device-code sign-in."),j=await Z({version:L.version,headless:!0})}b(`${j.url}
14
14
  ${j.instructions}`);let B=await j.completion;await y(z),await K(Q),await W.set({...q,body:{type:"oauth",access:B.access,refresh:B.refresh,expires:B.expires,...B.accountId?{accountId:B.accountId}:{}}}),b("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){b(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await n(T0(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}
@@ -1,8 +1,8 @@
1
- import { a as KnobValues, c as PluginExtraSection, i as CommandInvocation, l as PluginSection, o as MenuKnob, t as CommandApplyRequest } from "./model-CQcw10oW.js";
2
- import { mt as QuotaMap } from "./sidebar-state-BfQ4mpZO.js";
1
+ import { a as KnobValues, c as PluginExtraSection, i as CommandInvocation, l as PluginSection, o as MenuKnob, t as CommandApplyRequest } from "./model-BdITTmeb.js";
2
+ import { mt as QuotaMap } from "./sidebar-state-CVSok7zv.js";
3
3
  import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
4
4
  import "@cortexkit/private-files";
5
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/schema.d.ts
5
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/schema.d.ts
6
6
  type OAuthCredential = {
7
7
  type: 'oauth';
8
8
  access?: string;
@@ -191,7 +191,7 @@ interface PoolRow {
191
191
  unbound?: true;
192
192
  }
193
193
  //#endregion
194
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/errors.d.ts
194
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/errors.d.ts
195
195
  /** Every library operation that can fail, as named in the failure value. */
196
196
  type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
197
197
  /**
@@ -238,12 +238,12 @@ declare class PoolOperationError extends Error {
238
238
  });
239
239
  }
240
240
  //#endregion
241
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/hooks.d.ts
241
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/hooks.d.ts
242
242
  interface PoolLogger {
243
243
  warn(message: string, data?: unknown): void;
244
244
  }
245
245
  //#endregion
246
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.d.ts
246
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.d.ts
247
247
  interface LockLoss {
248
248
  readonly reason: 'taken-over' | 'expired' | 'unreadable' | 'renewal-failed' | 'marker-lost';
249
249
  readonly expectedOwnerId: string;
@@ -278,7 +278,7 @@ type RefreshFileLockOptions = {
278
278
  /** Filesystem leases share wall time across all callers and processes. */
279
279
  declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
280
280
  //#endregion
281
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.d.ts
281
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.d.ts
282
282
  type LockStep = NonNullable<Parameters<typeof acquireRefreshFileLock>[0]['onStep']> extends ((step: infer S) => unknown) ? S : never;
283
283
  /** Tuning shared by every lock the store takes; each field is overridable. */
284
284
  interface PoolLockOptions {
@@ -310,7 +310,7 @@ interface LockEnvironment {
310
310
  }, event: 'scheduled' | 'cancelled') => void;
311
311
  }
312
312
  //#endregion
313
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/mutate.d.ts
313
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/mutate.d.ts
314
314
  /** Named points on the write path, for crash and ownership injection. */
315
315
  type WriteStep = 'before-config-write' | 'after-config-write' | 'before-state-write' | 'after-state-write';
316
316
  /** Awaitable pause points on the pull and refresh paths. */
@@ -345,11 +345,11 @@ interface StoreContext {
345
345
  /** What `initializePool` did. */
346
346
  type InitializeOutcome = 'initialized' | 'already-ready';
347
347
  //#endregion
348
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/runtime.d.ts
348
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/runtime.d.ts
349
349
  /** Where a pull was fired from; `load` fires at most once per process per row. */
350
350
  type PullReason = 'load' | 'add' | 'replace' | 'admission';
351
351
  //#endregion
352
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/attribution.d.ts
352
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/attribution.d.ts
353
353
  /**
354
354
  * What a pull or refresh captured about its row (named by id alongside) when
355
355
  * it was issued. A result applies only while the row with that id still has
@@ -372,7 +372,7 @@ interface Attribution {
372
372
  identity?: string;
373
373
  }
374
374
  //#endregion
375
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/rows.d.ts
375
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/rows.d.ts
376
376
  type FailureHook = (rowId: string, error: PoolOperationError) => void | Promise<void>;
377
377
  interface RowOperationOptions {
378
378
  /** Called once, awaited, on every non-success path, before locks release. */
@@ -588,7 +588,7 @@ interface RowTransitionResult {
588
588
  providerState?: unknown;
589
589
  }
590
590
  //#endregion
591
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/provider-state.d.ts
591
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/provider-state.d.ts
592
592
  /**
593
593
  * Receives a private copy of the row's provider state (undefined when the row
594
594
  * shows none) and the row as loaded under the locks, and returns the next
@@ -624,7 +624,7 @@ declare const DECLINE_TRANSITION: unique symbol;
624
624
  */
625
625
  type RowTransitionMutator = (current: unknown | undefined, row: PoolRow) => unknown | typeof DECLINE_TRANSITION | Promise<unknown | typeof DECLINE_TRANSITION>;
626
626
  //#endregion
627
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/publication.d.ts
627
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/publication.d.ts
628
628
  interface PublishPlan {
629
629
  operationId: string;
630
630
  remove: Array<{
@@ -667,7 +667,7 @@ interface PublishResult {
667
667
  receipt: PublicationReceipt;
668
668
  }
669
669
  //#endregion
670
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/pull.d.ts
670
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/pull.d.ts
671
671
  /** What a pull is issued with: the credential and its attribution tuple. */
672
672
  interface PullRequest {
673
673
  id: string;
@@ -678,7 +678,7 @@ interface PullRequest {
678
678
  }
679
679
  type PullHook = (request: PullRequest) => Promise<unknown>;
680
680
  //#endregion
681
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/refresh.d.ts
681
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/refresh.d.ts
682
682
  /** What the injected provider refresh function returns. */
683
683
  interface ProviderRefreshResult {
684
684
  access: string;
@@ -741,7 +741,7 @@ type RefreshOutcome = {
741
741
  reason: string;
742
742
  };
743
743
  //#endregion
744
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/settings.d.ts
744
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/settings.d.ts
745
745
  /** The plugin's settings: every top-level config key except the pool-owned ones. */
746
746
  type PoolSettings = Record<string, unknown>;
747
747
  type SettingsRead = {
@@ -785,7 +785,7 @@ type UpdateSettingsResult = {
785
785
  outcome: 'updated' | 'unchanged';
786
786
  };
787
787
  //#endregion
788
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/store/pool.d.ts
788
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/store/pool.d.ts
789
789
  interface OpenPoolStoreOptions {
790
790
  /** The provider every row of this pool belongs to; keys the provider-wide lock. */
791
791
  provider: string;
@@ -971,13 +971,13 @@ interface PoolStore {
971
971
  pullsSettled(): Promise<void>;
972
972
  }
973
973
  //#endregion
974
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/commands/seam.d.ts
974
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/commands/seam.d.ts
975
975
  /** Where a dropped field is reported. Names only, never values. */
976
976
  interface SeamLogger {
977
977
  warn(message: string, data?: unknown): void;
978
978
  }
979
979
  //#endregion
980
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/commands/builtins.d.ts
980
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/commands/builtins.d.ts
981
981
  /**
982
982
  * What a plugin's login hands back. `ready` adds the account now. `pending`
983
983
  * means the user must finish somewhere else (a browser, a device code):
@@ -1097,17 +1097,92 @@ interface BeginAccountLoginResult {
1097
1097
  */
1098
1098
  declare function beginAccountLogin(opts: BeginAccountLoginOptions): Promise<BeginAccountLoginResult>;
1099
1099
  //#endregion
1100
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/claustrum/insula.d.ts
1100
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/claustrum/watch.d.ts
1101
+ /**
1102
+ * How a host currently learns about changes, for logs and status displays.
1103
+ * `watching`: a watch was accepted and is open, so polling is reduced to a
1104
+ * slow safety read. `polling`: no watch is open yet (not started, opening, or
1105
+ * re-subscribing after a close), so the host polls at its usual interval.
1106
+ * `fallback`: the watch is unavailable (an older module or client, a refusal,
1107
+ * the watch limit, or repeated failures), so the host polls at its usual
1108
+ * interval and may try a watch again later. Never carries secrets.
1109
+ */
1110
+ type WatchMode = 'watching' | 'polling' | 'fallback';
1111
+ /**
1112
+ * The fields every change notice carries, from the vault's watchScoped and
1113
+ * insula's usage.watch alike.
1114
+ */
1115
+ interface ChangeNotice {
1116
+ readonly kind: string;
1117
+ readonly epoch: string;
1118
+ readonly seq: number;
1119
+ }
1120
+ /** A vault watch notice: `view` is the same digest `list_scoped` returns. */
1121
+ interface ScopedWatchNoticeShape extends ChangeNotice {
1122
+ readonly view: string;
1123
+ }
1124
+ /**
1125
+ * How a vault watch ended, as claustrum-client 0.12.0 reports it. `refused`
1126
+ * and `not_accepting` both mean the watch closed before its first notice; the
1127
+ * client then made one `list_scoped` read to learn why, and `refused` carries
1128
+ * that read's refusal.
1129
+ */
1130
+ type ScopedWatchEnd = {
1131
+ readonly kind: 'refused';
1132
+ readonly error: unknown;
1133
+ } | {
1134
+ readonly kind: 'transport_lost';
1135
+ readonly error: unknown;
1136
+ } | {
1137
+ readonly kind: 'ended' | 'not_accepting' | 'unsupported' | 'stopped';
1138
+ };
1139
+ interface ScopedWatchHandle {
1140
+ stop(): void;
1141
+ readonly closed: Promise<ScopedWatchEnd>;
1142
+ }
1143
+ /**
1144
+ * The part of a vault client that can watch. claustrum-client added
1145
+ * `watchScoped` in 0.12.0; the peer range still admits 0.6.2, so it is
1146
+ * optional and detected at run time.
1147
+ */
1148
+ interface ScopedWatchSource {
1149
+ watchScoped?(onNotice: (notice: ScopedWatchNoticeShape) => void, options?: {
1150
+ enrollmentToken?: string;
1151
+ }): ScopedWatchHandle;
1152
+ }
1153
+ //#endregion
1154
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/claustrum/insula.d.ts
1155
+ /**
1156
+ * A held-open `usage.watch` stream. `closed` resolves when insula ends the
1157
+ * stream (STREAM_END at shutdown, or a reply that ends it) or after `stop()`,
1158
+ * and rejects with insula's refusal (an error with a `code`, such as
1159
+ * `unknown_method` from an insula that predates the method, or
1160
+ * `usage_watch_limit` when 64 watches are already open) or with the
1161
+ * transport failure.
1162
+ */
1163
+ interface InsulaUsageWatch {
1164
+ stop(): void;
1165
+ readonly closed: Promise<void>;
1166
+ }
1101
1167
  /** Optional transport for custom scoped clients; getUsage must not retry refusals. */
1102
1168
  interface InsulaUsageTransport {
1103
1169
  connectionFile: string;
1104
1170
  getUsage(): Promise<unknown>;
1171
+ /**
1172
+ * Open a `usage.watch` stream, passing each notice's raw JSON body to
1173
+ * `onNotice`. Optional: a transport without it is polled as before.
1174
+ */
1175
+ watchUsage?(onNotice: (body: Uint8Array) => void): InsulaUsageWatch;
1105
1176
  }
1106
1177
  //#endregion
1107
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/claustrum/custody.d.ts
1178
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/claustrum/custody.d.ts
1179
+ /**
1180
+ * `watchScoped` is present from claustrum-client 0.12.0. Hosts detect it at
1181
+ * run time and keep polling without it.
1182
+ */
1108
1183
  type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
1109
1184
  insula?: InsulaUsageTransport;
1110
- };
1185
+ } & ScopedWatchSource;
1111
1186
  /** The two credential types a plugin's family can hold; routing differs by type. */
1112
1187
  type VaultCredentialType = 'oauth' | 'api_key';
1113
1188
  /**
@@ -1192,9 +1267,20 @@ interface ClaustrumScopedAttempt {
1192
1267
  readonly accessToken: string;
1193
1268
  readonly recordVersion: number;
1194
1269
  readonly expiresAtMs: number | null;
1270
+ /**
1271
+ * True when this receipt was not freshly served but is the last token kept
1272
+ * from an earlier read, used because the vault could not be reached. A 401
1273
+ * with such a receipt must not be retried and is not reported to the vault,
1274
+ * which is unreachable.
1275
+ */
1276
+ readonly fromKeptReceipt?: true;
1277
+ }
1278
+ interface KeptReceiptState {
1279
+ readonly active: boolean;
1280
+ readonly since: number | null;
1195
1281
  }
1196
1282
  //#endregion
1197
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.d.ts
1283
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.d.ts
1198
1284
  /**
1199
1285
  * The declined-account interlock: the user's "do not use this vault account",
1200
1286
  * kept on the consumer side because the vault has no notion of it.
@@ -1213,7 +1299,7 @@ interface DeclinedAccount {
1213
1299
  readonly accountIdentity?: string;
1214
1300
  }
1215
1301
  //#endregion
1216
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/claustrum/roster.d.ts
1302
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/claustrum/roster.d.ts
1217
1303
  /**
1218
1304
  * One vault account as the pool sees it. It carries no bearer material: the
1219
1305
  * access token is fetched from the vault for every send. Several vault
@@ -1268,7 +1354,18 @@ interface VaultRosterFile {
1268
1354
  */
1269
1355
  type QuotaReceipt = Pick<ClaustrumScopedAttempt, 'credentialId' | 'accountIdentity' | 'accountIdentitySource' | 'expectedAccountIdentity'>;
1270
1356
  //#endregion
1271
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.19.0+eac60b769bf9196b/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.d.ts
1357
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/claustrum/consumer.d.ts
1358
+ /**
1359
+ * How a started consumer learns about changes, for logs and status displays.
1360
+ * `insula` is present when the consumer was given an insula source. Never
1361
+ * carries secrets.
1362
+ */
1363
+ interface ClaustrumWatchState {
1364
+ readonly vault: WatchMode;
1365
+ readonly insula?: WatchMode;
1366
+ }
1367
+ //#endregion
1368
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.21.0+ceea0b545671e3e4/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.d.ts
1272
1369
  interface ClaustrumEnrollmentClient {
1273
1370
  enrollPropose(input: {
1274
1371
  name: string;
@@ -1369,6 +1466,12 @@ interface OpenAiVaultOptions {
1369
1466
  pollIntervalMs?: number;
1370
1467
  fetchImpl?: () => typeof fetch;
1371
1468
  now?: () => number;
1469
+ /**
1470
+ * Replace the timers behind the background poll, the vault and insula
1471
+ * watches' retries and the outage probe (tests).
1472
+ */
1473
+ setTimeoutImpl?: typeof setTimeout;
1474
+ clearTimeoutImpl?: typeof clearTimeout;
1372
1475
  }
1373
1476
  /** One host's view of its OpenAI accounts in the vault. */
1374
1477
  declare class OpenAiVault {
@@ -1387,9 +1490,13 @@ declare class OpenAiVault {
1387
1490
  */
1388
1491
  enrolled(): boolean;
1389
1492
  /**
1390
- * Polls enrollment files and the vault's accounts. With local authority the
1391
- * consumer sends no vault request. A new enrollment completed by another
1392
- * process is detected on the next poll.
1493
+ * Starts the consumer's background poll and its vault and insula watches.
1494
+ * With local authority the consumer sends no vault request. A new
1495
+ * enrollment completed by another process is detected on the next poll.
1496
+ * While the vault watch is open the poll lists the vault only every five
1497
+ * minutes, and a notice that the visible accounts changed starts a
1498
+ * discovery at once; without a watch (an older vault or client, or a
1499
+ * refusal) every poll lists the vault as before.
1393
1500
  */
1394
1501
  start(): void;
1395
1502
  /**
@@ -1414,6 +1521,16 @@ declare class OpenAiVault {
1414
1521
  */
1415
1522
  refresh(): Promise<VaultRosterFile | undefined>;
1416
1523
  snapshot(): VaultRosterFile | undefined;
1524
+ /**
1525
+ * Whether the consumer learns about vault and insula changes from a watch
1526
+ * or by polling, without any I/O.
1527
+ */
1528
+ watchState(): ClaustrumWatchState;
1529
+ /**
1530
+ * Whether any account is being served the last token the vault gave it
1531
+ * because the vault cannot be reached, without any I/O.
1532
+ */
1533
+ keptReceiptState(): KeptReceiptState;
1417
1534
  /**
1418
1535
  * What the vault says this host is granted, from the latest list, without
1419
1536
  * any I/O. Undefined is unknown (a vault that does not report grants, or
@@ -1,2 +1,2 @@
1
- import{Pe as q,Re as O,Te as A,Ue as y,We as p,Ye as k}from"./index-r2s51ac1.js";import{appendFileSync as QJ,chmodSync as UJ,existsSync as W,renameSync as g,statSync as ZJ}from"node:fs";import{open as $J}from"node:fs/promises";import{dirname as VJ,resolve as IJ}from"node:path";var i=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,e=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function JJ(J){return J instanceof Error||Object.prototype.toString.call(J)==="[object Error]"}function T(J={}){let H=[e,...J.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function Z(G){let U=G.toLowerCase().replace(/[-_]/g,"");return i.test(G)||U.includes("apikey")||U.endsWith("secret")||U.endsWith("password")||U.endsWith("token")&&!U.endsWith("tokens")||!!J.extraSecretKeys?.(U)}function I(G){let U=G,$=[["name",G.name],["message",G.message],["stack",G.stack]];for(let j of["code","status","cause"])if(U[j]!==void 0)$.push([j,U[j]]);let Y=new Set($.map(([j])=>j));for(let j of Object.entries(G))if(!Y.has(j[0]))$.push(j);return $}function B(G,U,$,Y=0){if(typeof G==="string")return H.reduce((j,C)=>j.replace(C,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if($.has(G))return"[Circular]";$.add(G);try{if(Array.isArray(G))return G.map((N)=>B(N,U,$,Y));let j=JJ(G);if(j&&Y>=8)return"[Truncated]";let C=j?Y+1:Y;return Object.fromEntries((j?I(G):Object.entries(G)).map(([N,z])=>[N,U&&Z(N)?"***REDACTED***":B(z,U,$,C)]))}finally{$.delete(G)}}return{redact:(G)=>B(G,!0,new WeakSet),redactStrings:(G)=>B(G,!1,new WeakSet)}}var F=T(),GJ=F.redact,HJ=F.redactStrings;var D={error:0,warn:1,info:2,debug:3,trace:4},h=5242880,m=3;function b(J){try{UJ(J,384)}catch{}}function jJ(J){try{if(!(W(J)&&ZJ(J).size>=h))return;for(let Z=m-1;Z>=1;Z--)if(W(`${J}.${Z}`)){let I=`${J}.${Z+1}`;g(`${J}.${Z}`,I),b(I)}let H=`${J}.1`;g(J,H),b(H)}catch{}}async function M(J){let{file:H,handle:Z}=J;if(J.file=void 0,J.handle=void 0,H&&Z)await O(H,"log-close",()=>Z.close())}async function w(J,H){await y(VJ(H));try{await A(H,"file",!0)}catch(Z){if(Z.code!=="ENOENT")throw Z;try{await p(H,"")}catch(I){if(I.code!=="EEXIST")throw I;await A(H,"file",!0)}}return J.handle=await O(H,"log-open",()=>$J(H,"a")),J.file=H,J.handle}async function XJ(J,H,Z){H=IJ(H);try{if(J.file!==H)await M(J);let I=J.handle??await w(J,H);if((await O(H,"log-stat",()=>I.stat())).size>=h){await M(J);for(let G=m-1;G>=0;G--){let U=G===0?H:`${H}.${G}`,$=`${H}.${G+1}`;try{await A(U,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await A($,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await k(U,$),await A($,"file")}I=await w(J,H)}await O(H,"log-append",()=>I.appendFile(Z,"utf8"))}catch(I){throw await M(J).catch(()=>{}),I}}function YJ(J){try{return` ${JSON.stringify(J)}`}catch{return" [unserializable]"}}function BJ(J){let H,Z,I,B=T(),G,U=[],$,Y=Promise.resolve(),j,C={};function N(Q){let V=Y.then(Q);return Y=V.catch((X)=>{j=X}),V}function z(Q){if(q&&Q.file!==H)N(()=>M(C)).catch(()=>{});H=Q.file,Z=Q.level,B=T(Q),G=Q.captureSink}function s(Q){if(Q===void 0||Q in D)I=Q}function o(){if(H===void 0)return;return(typeof H==="function"?H():H)||void 0}function t(){if(I)return I;let Q=typeof Z==="function"?Z():Z;if(Q&&Q in D)return Q;return"info"}function R(Q=!0){if($)clearTimeout($),$=void 0;if(!U.length){if(q)return N(async()=>{if(Q)await M(C);if(j)throw j});return}let V;try{V=o()}catch{if(U=[],q&&Q)return N(()=>M(C));return}let X=U.join("");if(U=[],!V){if(q&&Q)return N(()=>M(C));return}if(q)return N(async()=>{try{await XJ(C,V,X)}finally{if(Q)await M(C)}});try{if(jJ(V),W(V))b(V);QJ(V,X,{encoding:"utf8",mode:384})}catch{}}function a(){if(!$)$=setTimeout(()=>{$=void 0;let Q=R(!1);if(Q instanceof Promise)Q.catch(()=>{})},500)}function _(Q,V,X,P){if(H===void 0&&G===void 0)return;try{if(D[V]>D[t()])return;let S=B.redactStrings(X),K;try{K=B.redact(P)}catch{K="[unserializable]"}let r=`[${new Date().toISOString()}] ${V.toUpperCase()} [${Q}] ${S}`+(P===void 0?"":YJ(K))+`
1
+ import{Pe as q,Re as O,Te as A,Ue as y,We as p,Ye as k}from"./index-8x1aj7q3.js";import{appendFileSync as QJ,chmodSync as UJ,existsSync as W,renameSync as g,statSync as ZJ}from"node:fs";import{open as $J}from"node:fs/promises";import{dirname as VJ,resolve as IJ}from"node:path";var i=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,e=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function JJ(J){return J instanceof Error||Object.prototype.toString.call(J)==="[object Error]"}function T(J={}){let H=[e,...J.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function Z(G){let U=G.toLowerCase().replace(/[-_]/g,"");return i.test(G)||U.includes("apikey")||U.endsWith("secret")||U.endsWith("password")||U.endsWith("token")&&!U.endsWith("tokens")||!!J.extraSecretKeys?.(U)}function I(G){let U=G,$=[["name",G.name],["message",G.message],["stack",G.stack]];for(let j of["code","status","cause"])if(U[j]!==void 0)$.push([j,U[j]]);let Y=new Set($.map(([j])=>j));for(let j of Object.entries(G))if(!Y.has(j[0]))$.push(j);return $}function B(G,U,$,Y=0){if(typeof G==="string")return H.reduce((j,C)=>j.replace(C,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if($.has(G))return"[Circular]";$.add(G);try{if(Array.isArray(G))return G.map((N)=>B(N,U,$,Y));let j=JJ(G);if(j&&Y>=8)return"[Truncated]";let C=j?Y+1:Y;return Object.fromEntries((j?I(G):Object.entries(G)).map(([N,z])=>[N,U&&Z(N)?"***REDACTED***":B(z,U,$,C)]))}finally{$.delete(G)}}return{redact:(G)=>B(G,!0,new WeakSet),redactStrings:(G)=>B(G,!1,new WeakSet)}}var F=T(),GJ=F.redact,HJ=F.redactStrings;var D={error:0,warn:1,info:2,debug:3,trace:4},h=5242880,m=3;function b(J){try{UJ(J,384)}catch{}}function jJ(J){try{if(!(W(J)&&ZJ(J).size>=h))return;for(let Z=m-1;Z>=1;Z--)if(W(`${J}.${Z}`)){let I=`${J}.${Z+1}`;g(`${J}.${Z}`,I),b(I)}let H=`${J}.1`;g(J,H),b(H)}catch{}}async function M(J){let{file:H,handle:Z}=J;if(J.file=void 0,J.handle=void 0,H&&Z)await O(H,"log-close",()=>Z.close())}async function w(J,H){await y(VJ(H));try{await A(H,"file",!0)}catch(Z){if(Z.code!=="ENOENT")throw Z;try{await p(H,"")}catch(I){if(I.code!=="EEXIST")throw I;await A(H,"file",!0)}}return J.handle=await O(H,"log-open",()=>$J(H,"a")),J.file=H,J.handle}async function XJ(J,H,Z){H=IJ(H);try{if(J.file!==H)await M(J);let I=J.handle??await w(J,H);if((await O(H,"log-stat",()=>I.stat())).size>=h){await M(J);for(let G=m-1;G>=0;G--){let U=G===0?H:`${H}.${G}`,$=`${H}.${G+1}`;try{await A(U,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await A($,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await k(U,$),await A($,"file")}I=await w(J,H)}await O(H,"log-append",()=>I.appendFile(Z,"utf8"))}catch(I){throw await M(J).catch(()=>{}),I}}function YJ(J){try{return` ${JSON.stringify(J)}`}catch{return" [unserializable]"}}function BJ(J){let H,Z,I,B=T(),G,U=[],$,Y=Promise.resolve(),j,C={};function N(Q){let V=Y.then(Q);return Y=V.catch((X)=>{j=X}),V}function z(Q){if(q&&Q.file!==H)N(()=>M(C)).catch(()=>{});H=Q.file,Z=Q.level,B=T(Q),G=Q.captureSink}function s(Q){if(Q===void 0||Q in D)I=Q}function o(){if(H===void 0)return;return(typeof H==="function"?H():H)||void 0}function t(){if(I)return I;let Q=typeof Z==="function"?Z():Z;if(Q&&Q in D)return Q;return"info"}function R(Q=!0){if($)clearTimeout($),$=void 0;if(!U.length){if(q)return N(async()=>{if(Q)await M(C);if(j)throw j});return}let V;try{V=o()}catch{if(U=[],q&&Q)return N(()=>M(C));return}let X=U.join("");if(U=[],!V){if(q&&Q)return N(()=>M(C));return}if(q)return N(async()=>{try{await XJ(C,V,X)}finally{if(Q)await M(C)}});try{if(jJ(V),W(V))b(V);QJ(V,X,{encoding:"utf8",mode:384})}catch{}}function a(){if(!$)$=setTimeout(()=>{$=void 0;let Q=R(!1);if(Q instanceof Promise)Q.catch(()=>{})},500)}function _(Q,V,X,P){if(H===void 0&&G===void 0)return;try{if(D[V]>D[t()])return;let S=B.redactStrings(X),K;try{K=B.redact(P)}catch{K="[unserializable]"}let r=`[${new Date().toISOString()}] ${V.toUpperCase()} [${Q}] ${S}`+(P===void 0?"":YJ(K))+`
2
2
  `;try{G?.({channel:Q,level:V,message:S,data:K})}catch{}if(H===void 0)return;if(U.push(r),U.length>=50){let E=R(!1);if(E instanceof Promise)E.catch(()=>{})}else a()}catch{}}function n(Q){return{error:(V,X)=>_(Q,"error",V,X),warn:(V,X)=>_(Q,"warn",V,X),info:(V,X)=>_(Q,"info",V,X),debug:(V,X)=>_(Q,"debug",V,X),trace:(V,X)=>_(Q,"trace",V,X)}}function l(){if(q)N(()=>M(C)).catch(()=>{});if(j=void 0,U=[],$)clearTimeout($),$=void 0;H=void 0,Z=void 0,I=void 0,B=T(),G=void 0}if(J)z(J);return{configure:z,createLogger:n,setLogLevel:s,flushLogs:R,reset:l}}var x=BJ();function L(J){x.configure(J);let{configure:H,createLogger:Z,setLogLevel:I,flushLogs:B}=x;return{configure:H,createLogger:Z,setLogLevel:I,flushLogs:B}}function v(J){x.setLogLevel(J)}function u(){return x.flushLogs()}function c(J){return x.createLogger(J)}function f(J){return J==="chatgptaccountid"||J==="email"||J==="orgname"||J==="organizationname"}var d=T({extraSecretKeys:f}),kJ=d.redact,hJ=d.redactStrings;function mJ(J){L({...J,extraSecretKeys:f})}function cJ(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;try{return JSON.stringify(J)}catch{return String(J)}}function dJ(J){return"notify"in J}import{basename as MJ,dirname as TJ,join as qJ}from"node:path";var AJ="openai-auth.json",_J="openai-auth-state.json";function tJ(J){return MJ(J)===AJ?qJ(TJ(J),_J):`${J}.state.json`}import{execFileSync as OJ,spawn as xJ}from"node:child_process";function lJ(J,H=process.platform,Z=OJ,I=xJ){try{if(H==="win32"){let B=`Start-Process '${J.replaceAll("'","''")}'`,G=Buffer.from(B,"utf16le").toString("base64"),U=I("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",G],{stdio:"ignore",windowsHide:!0});return U.on("error",()=>{}),U.unref(),U.pid!==void 0}return Z(H==="darwin"?"open":"xdg-open",[J],{stdio:"ignore",timeout:3000}),!0}catch{return!1}}export{T as De,GJ as Ee,v as Fe,u as Ge,c as He,hJ as Ie,mJ as Je,AJ as Ke,tJ as Le,cJ as Me,dJ as Ne,lJ as Oe};
@@ -1,2 +1,2 @@
1
- import{xe as k,ye as _,ze as R}from"./index-ffg0sgg5.js";import{Qe as h,Ve as D}from"./index-r2s51ac1.js";import{$e as w}from"./index-bc89akak.js";class T extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function F(f){return typeof f==="string"&&f.length>0}var S=new Map;function W(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=S.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},S.set(x,z);return z}var U=100,j=3000;function d(f,x,z){if(f.requireSession===!0&&!F(z))throw new T("push");let J=W(f);if(J.queue.push({id:J.nextId++,type:"open-dialog",payload:x,sessionId:z}),J.queue.length>U)J.queue=J.queue.slice(-U)}function i(f,x=0,z){if(f.requireSession===!0&&!F(z))throw new T("drain");let J=W(f),Y=Date.now();if(J.lastDrainAtAny=Y,z!==void 0)J.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",V=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)J.queue=J.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return J.queue.filter((B)=>B.id>x&&V(B))}function n(f,x){let z=Date.now(),J=W(f),Y=x!==void 0?J.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?J.lastDrainAtAny:0;return Y>0&&z-Y<j}import{randomBytes as t,timingSafeEqual as q}from"node:crypto";import{unlink as v}from"node:fs/promises";import{createServer as u}from"node:http";import{join as I}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class g extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function l(f){return new Promise((x,z)=>{let J=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new g(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){J(!0);return}let Z=[],V=0;f.on("data",(B)=>{if(V+=B.length,V>E){J();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class m extends Error{}async function p(f,x){let z,J=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new m("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,J])}finally{clearTimeout(z)}}function c(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),J=Buffer.from(x);return z.length===J.length&&q(z,J)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=t(32).toString("hex"),J=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,V=new Set,B=u((G,K)=>{G.setTimeout(J,()=>{G.socket.destroy()}),M(G,K)});B.on("connection",(G)=>{V.add(G),G.once("close",()=>V.delete(G))}),B.requestTimeout=Y,B.headersTimeout=Y;async function M(G,K){let H=(X,Q,C={})=>{if(K.headersSent||K.writableEnded||K.destroyed)return;K.writeHead(X,{"content-type":"application/json",...C}),K.end(JSON.stringify(Q))};try{let X=new URL(G.url??"/","http://127.0.0.1").pathname;if(G.method==="GET"&&X==="/health")return H(200,{ok:!0});if(G.method!=="POST"||!X.startsWith("/rpc/"))return H(404,{error:"not found"});if(!c(G.headers.authorization,z))return H(401,{error:"unauthorized"});let Q=X.slice(5),C;try{C=await l(G)}catch($){if(!($ instanceof g))throw $;if($.declaredOversize){let y=G.socket;K.once("finish",()=>{y.end();let A=setTimeout(()=>y.destroy(),2000);if(A.unref(),G.once("end",()=>y.destroy()),y.once("close",()=>clearTimeout(A)),G.complete)y.destroy()})}return H(413,{error:"body too large"},{connection:"close"})}let b;try{b=JSON.parse(C||"{}")}catch{return H(400,{error:"invalid json"})}if(Q==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(b);else{if(!b||typeof b!=="object"||Array.isArray(b))throw Error("invalid params");let L=b;if(f.requireSession===!0&&!F(L.sessionId))return H(400,{error:"session required"});if("lastReceivedId"in L&&(typeof L.lastReceivedId!=="number"||!Number.isSafeInteger(L.lastReceivedId)||L.lastReceivedId<0)||"sessionId"in L&&typeof L.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(L.lastReceivedId??0),sessionId:typeof L.sessionId==="string"?L.sessionId:void 0}}}catch(L){if(L instanceof N)throw L;return H(400,{error:"invalid params"})}let{lastReceivedId:y,sessionId:A}=$;if(f.requireSession===!0&&!F(A))return H(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let O;if(f.drainAsync)try{O=await f.drainAsync(y,A)}catch(L){return x.warn("rpc notification drain failed",{pid:process.pid,error:L instanceof Error?L.message:String(L)}),H(500,{error:"drain failed"})}else O=f.drain?.(y,A);return H(200,{messages:O})}if(Q==="apply"){let $=Promise.resolve(f.apply(b)),y=f.applyDeadlineMs===void 0?await $:await p($,f.applyDeadlineMs);return H(200,y)}return H(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),H(X.status,{error:X.message});if(X instanceof m)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),H(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),H(500,{error:"internal error"})}}let P=await new Promise((G,K)=>{B.on("error",K),B.listen(0,"127.0.0.1",()=>{let H=B.address();if(H&&typeof H==="object")G(H.port);else K(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await R(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(G){x.warn("rpc state sweep failed",{pid:process.pid,error:G instanceof Error?G.message:String(G)})}try{await _(f.dir,{port:P,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:P})}catch(G){throw await new Promise((K)=>B.close(()=>K())),G}return{port:P,token:z,async stop(){await new Promise((H)=>{B.closeAllConnections?.(),B.close(()=>H());for(let X of V)X.destroy()});let G=I(f.dir,`port-${process.pid}.json`),K=await D(G).then((H)=>JSON.parse(H)).catch((H)=>{if(H instanceof h&&H.code!=="ENOENT")throw H;return});if(K?.port===P&&K.token===z)await v(G).catch(()=>{})}}}async function Hf(f,x,z){let J=globalThis,Y=Symbol.for(f),Z=J[Y]??{servers:new Map,pending:new Map};J[Y]=Z;let{servers:V,pending:B}=Z,M=B.get(x)??Promise.resolve(),P,G=M.catch(()=>{}).then(async()=>{let H=V.get(x);if(H){if(await H.stop(),V.get(x)===H)V.delete(x)}P=await z(),V.set(x,P)});B.set(x,G);try{await G}finally{if(B.get(x)===G)B.delete(x)}let K=P;if(!K)throw Error("RPC server failed to start");return{server:K,release:async()=>{if(V.get(x)!==K)return;if(await K.stop(),V.get(x)===K)V.delete(x)}}}var bf=k(w);
1
+ import{xe as k,ye as _,ze as R}from"./index-tddr876f.js";import{Qe as h,Ve as D}from"./index-8x1aj7q3.js";import{$e as w}from"./index-bc89akak.js";class T extends Error{operation;constructor(f){super(`a ${f} on a strict notification scope needs a session id`);this.name="RpcSessionRequiredError",this.operation=f}}function F(f){return typeof f==="string"&&f.length>0}var S=new Map;function W(f){let x=JSON.stringify([f.rpcRoot,f.directoryPrefix,f.registrationSessionId,...f.requireSession===!0?["strict"]:[]]),z=S.get(x);if(!z)z={queue:[],nextId:1,lastDrainAtBySession:new Map,lastDrainAtAny:0},S.set(x,z);return z}var U=100,j=3000;function d(f,x,z){if(f.requireSession===!0&&!F(z))throw new T("push");let J=W(f);if(J.queue.push({id:J.nextId++,type:"open-dialog",payload:x,sessionId:z}),J.queue.length>U)J.queue=J.queue.slice(-U)}function i(f,x=0,z){if(f.requireSession===!0&&!F(z))throw new T("drain");let J=W(f),Y=Date.now();if(J.lastDrainAtAny=Y,z!==void 0)J.lastDrainAtBySession.set(z,Y);let Z=f.sessionlessDrain==="broadcast-only",V=(B)=>z===void 0?!Z||B.sessionId===void 0:B.sessionId===void 0||B.sessionId===z;if(x>0)J.queue=J.queue.filter((B)=>{if(B.id>x)return!0;if(z===void 0)return!Z||B.sessionId!==void 0;return B.sessionId!==z});return J.queue.filter((B)=>B.id>x&&V(B))}function n(f,x){let z=Date.now(),J=W(f),Y=x!==void 0?J.lastDrainAtBySession.get(x)??0:f.sessionlessDrain==="broadcast-only"?J.lastDrainAtAny:0;return Y>0&&z-Y<j}import{randomBytes as t,timingSafeEqual as q}from"node:crypto";import{unlink as v}from"node:fs/promises";import{createServer as u}from"node:http";import{join as I}from"node:path";class N extends Error{status;constructor(f,x){if(!Number.isInteger(f)||f<400||f>499)throw RangeError(`RpcRequestError status must be 4xx, got ${f}`);super(x);this.name="RpcRequestError",this.status=f}}var E=1e6;class g extends Error{declaredOversize;constructor(f){super("body too large");this.declaredOversize=f}}function l(f){return new Promise((x,z)=>{let J=(B=!1)=>{f.removeAllListeners("data"),f.on("data",()=>{}),f.resume(),z(new g(B))},Y=Number(f.headers["content-length"]);if(Number.isFinite(Y)&&Y>E){J(!0);return}let Z=[],V=0;f.on("data",(B)=>{if(V+=B.length,V>E){J();return}Z.push(B)}),f.on("end",()=>x(Buffer.concat(Z).toString("utf8"))),f.on("error",z)})}class m extends Error{}async function p(f,x){let z,J=new Promise((Y,Z)=>{z=setTimeout(()=>Z(new m("apply deadline exceeded")),x),z.unref?.()});f.catch(()=>{});try{return await Promise.race([f,J])}finally{clearTimeout(z)}}function c(f,x){if(!f?.startsWith("Bearer "))return!1;let z=Buffer.from(f.slice(7)),J=Buffer.from(x);return z.length===J.length&&q(z,J)}async function Bf(f){if(typeof f.drain==="function"===(typeof f.drainAsync==="function"))throw TypeError("exactly one of drain or drainAsync must be provided");let x=f.log??{warn(){},debug(){}},z=t(32).toString("hex"),J=f.timeoutMs??90000,Y=f.receiptTimeoutMs??2000,Z=!1,V=new Set,B=u((G,K)=>{G.setTimeout(J,()=>{G.socket.destroy()}),M(G,K)});B.on("connection",(G)=>{V.add(G),G.once("close",()=>V.delete(G))}),B.requestTimeout=Y,B.headersTimeout=Y;async function M(G,K){let H=(X,Q,C={})=>{if(K.headersSent||K.writableEnded||K.destroyed)return;K.writeHead(X,{"content-type":"application/json",...C}),K.end(JSON.stringify(Q))};try{let X=new URL(G.url??"/","http://127.0.0.1").pathname;if(G.method==="GET"&&X==="/health")return H(200,{ok:!0});if(G.method!=="POST"||!X.startsWith("/rpc/"))return H(404,{error:"not found"});if(!c(G.headers.authorization,z))return H(401,{error:"unauthorized"});let Q=X.slice(5),C;try{C=await l(G)}catch($){if(!($ instanceof g))throw $;if($.declaredOversize){let y=G.socket;K.once("finish",()=>{y.end();let A=setTimeout(()=>y.destroy(),2000);if(A.unref(),G.once("end",()=>y.destroy()),y.once("close",()=>clearTimeout(A)),G.complete)y.destroy()})}return H(413,{error:"body too large"},{connection:"close"})}let b;try{b=JSON.parse(C||"{}")}catch{return H(400,{error:"invalid json"})}if(Q==="pending-notifications"){let $;try{if(f.parsePending)$=f.parsePending(b);else{if(!b||typeof b!=="object"||Array.isArray(b))throw Error("invalid params");let L=b;if(f.requireSession===!0&&!F(L.sessionId))return H(400,{error:"session required"});if("lastReceivedId"in L&&(typeof L.lastReceivedId!=="number"||!Number.isSafeInteger(L.lastReceivedId)||L.lastReceivedId<0)||"sessionId"in L&&typeof L.sessionId!=="string")throw Error("invalid params");$={lastReceivedId:Number(L.lastReceivedId??0),sessionId:typeof L.sessionId==="string"?L.sessionId:void 0}}}catch(L){if(L instanceof N)throw L;return H(400,{error:"invalid params"})}let{lastReceivedId:y,sessionId:A}=$;if(f.requireSession===!0&&!F(A))return H(400,{error:"session required"});if(A===void 0&&!Z)Z=!0,x.warn("rpc notification drain missing session id",{pid:process.pid});let O;if(f.drainAsync)try{O=await f.drainAsync(y,A)}catch(L){return x.warn("rpc notification drain failed",{pid:process.pid,error:L instanceof Error?L.message:String(L)}),H(500,{error:"drain failed"})}else O=f.drain?.(y,A);return H(200,{messages:O})}if(Q==="apply"){let $=Promise.resolve(f.apply(b)),y=f.applyDeadlineMs===void 0?await $:await p($,f.applyDeadlineMs);return H(200,y)}return H(404,{error:"unknown method"})}catch(X){if(X instanceof N)return x.debug("rpc request refused",{pid:process.pid,status:X.status}),H(X.status,{error:X.message});if(X instanceof m)return x.warn("rpc apply deadline exceeded",{pid:process.pid,deadlineMs:f.applyDeadlineMs}),H(504,{error:"handler deadline exceeded"});x.warn("rpc request failed",{pid:process.pid,error:X instanceof Error?X.message:String(X)}),H(500,{error:"internal error"})}}let P=await new Promise((G,K)=>{B.on("error",K),B.listen(0,"127.0.0.1",()=>{let H=B.address();if(H&&typeof H==="object")G(H.port);else K(Error("no port"))})});if(B.unref(),f.sweepRoot)try{await R(f.sweepRoot,f.dir,f.isManagedDir,x)}catch(G){x.warn("rpc state sweep failed",{pid:process.pid,error:G instanceof Error?G.message:String(G)})}try{await _(f.dir,{port:P,token:z,pid:process.pid},{secureDir:f.secureDir}),x.debug("rpc server pid",{pid:process.pid,rpcPort:P})}catch(G){throw await new Promise((K)=>B.close(()=>K())),G}return{port:P,token:z,async stop(){await new Promise((H)=>{B.closeAllConnections?.(),B.close(()=>H());for(let X of V)X.destroy()});let G=I(f.dir,`port-${process.pid}.json`),K=await D(G).then((H)=>JSON.parse(H)).catch((H)=>{if(H instanceof h&&H.code!=="ENOENT")throw H;return});if(K?.port===P&&K.token===z)await v(G).catch(()=>{})}}}async function Hf(f,x,z){let J=globalThis,Y=Symbol.for(f),Z=J[Y]??{servers:new Map,pending:new Map};J[Y]=Z;let{servers:V,pending:B}=Z,M=B.get(x)??Promise.resolve(),P,G=M.catch(()=>{}).then(async()=>{let H=V.get(x);if(H){if(await H.stop(),V.get(x)===H)V.delete(x)}P=await z(),V.set(x,P)});B.set(x,G);try{await G}finally{if(B.get(x)===G)B.delete(x)}let K=P;if(!K)throw Error("RPC server failed to start");return{server:K,release:async()=>{if(V.get(x)!==K)return;if(await K.stop(),V.get(x)===K)V.delete(x)}}}var bf=k(w);
2
2
  export{d as re,i as se,n as te,Bf as ue,Hf as ve,bf as we};