@cortexkit/opencode-openai-auth 1.0.5 → 1.1.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 (102) hide show
  1. package/dist/bin.js +9 -8
  2. package/dist/{pool-lifecycle-C_6YRmsh.d.ts → codex-request-BXDXToyt.d.ts} +158 -27
  3. package/dist/index-0yh85bwb.js +69 -0
  4. package/dist/{index-826s1yxa.js → index-4c8yw54k.js} +2 -2
  5. package/dist/{index-y4gxyxqd.js → index-7c6sxtd6.js} +2 -2
  6. package/dist/index-7eb3dw37.js +90 -0
  7. package/dist/index-8re8rprk.js +2 -0
  8. package/dist/{index-66asrje2.js → index-csky2xpg.js} +1 -1
  9. package/dist/index-edbdscy7.js +65 -0
  10. package/dist/{index-pg305s90.js → index-f2fmb596.js} +1 -1
  11. package/dist/{index-fsxbncpw.js → index-j8v2xwq6.js} +1 -1
  12. package/dist/{index-fsky1rsh.js → index-k6cydkgt.js} +2 -2
  13. package/dist/{index-116q849r.js → index-m5qmvr6c.js} +2 -2
  14. package/dist/index-msx2m78k.js +8 -0
  15. package/dist/{index-nx2qh047.js → index-zpm95mt5.js} +1 -1
  16. package/dist/index.d.ts +15 -7
  17. package/dist/index.js +1 -1
  18. package/dist/{map-m6f5a_IA.d.ts → map-Buq-GW7l.d.ts} +1 -1
  19. package/dist/{protocol-DctqemRI.d.ts → model-YRg7Uowo.d.ts} +67 -25
  20. package/dist/{port-file-ZPlxXB4G.d.ts → port-file-CxEpgSHY.d.ts} +1 -1
  21. package/dist/protocol-CDV1Pc6h.d.ts +29 -0
  22. package/dist/rpc/port-file.d.ts +1 -1
  23. package/dist/rpc/port-file.js +1 -1
  24. package/dist/rpc/protocol.d.ts +1 -1
  25. package/dist/rpc/protocol.js +1 -1
  26. package/dist/rpc/rpc-client.d.ts +3 -3
  27. package/dist/rpc/rpc-client.js +1 -1
  28. package/dist/rpc/rpc-dir.js +1 -1
  29. package/dist/{sidebar-state-z_M7Trnd.d.ts → sidebar-state-DjTWUbmf.d.ts} +15 -9
  30. package/dist/sidebar-state.d.ts +1 -1
  31. package/dist/sidebar-state.js +1 -1
  32. package/dist/{token-bzhkgc29.js → token-rz4t3ay6.js} +1 -1
  33. package/dist/token-util-tpy2c7h6.js +1 -0
  34. package/dist/tui-preferences.js +1 -1
  35. package/dist/tui.d.ts +20 -2
  36. package/dist/v2/server.d.ts +73 -1
  37. package/dist/v2/server.js +3 -3
  38. package/package.json +2 -2
  39. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +13 -8
  40. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +354 -0
  41. package/src/tui-compiled/raw/shared/134b008900698fe0-backoff.js +92 -0
  42. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +393 -0
  43. package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
  44. package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +473 -0
  45. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +566 -0
  46. package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
  47. package/src/tui-compiled/raw/shared/4593a4d71edf69fd-tombstone.js +25 -0
  48. package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +500 -0
  49. package/src/tui-compiled/raw/shared/6371b24a0573d79e-any-signal.js +42 -0
  50. package/src/tui-compiled/raw/shared/7c140680fc81be92-interlock.js +29 -0
  51. package/src/tui-compiled/raw/shared/85512cc5263ba259-provider.js +87 -0
  52. package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +192 -0
  53. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +806 -0
  54. package/src/tui-compiled/raw/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
  55. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +0 -1
  56. package/src/tui-compiled/raw/shared/ca0fccaba1d87af4-errors.js +8 -0
  57. package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +152 -0
  58. package/src/tui-compiled/raw/shared/d9d2892a4c371301-host-slot.js +72 -0
  59. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +1470 -0
  60. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
  61. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +24 -0
  62. package/src/tui-compiled/raw/sidebar-state.js +41 -14
  63. package/src/tui-compiled/raw/tui/command-dialogs.tsx +3 -34
  64. package/src/tui-compiled/raw/tui/section-text.js +21 -0
  65. package/src/tui-compiled/raw/tui/v2-dialog.js +137 -0
  66. package/src/tui-compiled/raw/tui/v2.tsx +133 -0
  67. package/src/tui-compiled/raw/tui.tsx +146 -40
  68. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +13 -8
  69. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +354 -0
  70. package/src/tui-compiled/runtime/shared/134b008900698fe0-backoff.js +92 -0
  71. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +393 -0
  72. package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
  73. package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +473 -0
  74. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +566 -0
  75. package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
  76. package/src/tui-compiled/runtime/shared/4593a4d71edf69fd-tombstone.js +25 -0
  77. package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +500 -0
  78. package/src/tui-compiled/runtime/shared/6371b24a0573d79e-any-signal.js +42 -0
  79. package/src/tui-compiled/runtime/shared/7c140680fc81be92-interlock.js +29 -0
  80. package/src/tui-compiled/runtime/shared/85512cc5263ba259-provider.js +87 -0
  81. package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +192 -0
  82. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +806 -0
  83. package/src/tui-compiled/runtime/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
  84. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +0 -1
  85. package/src/tui-compiled/runtime/shared/ca0fccaba1d87af4-errors.js +8 -0
  86. package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +152 -0
  87. package/src/tui-compiled/runtime/shared/d9d2892a4c371301-host-slot.js +72 -0
  88. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +1470 -0
  89. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
  90. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +24 -0
  91. package/src/tui-compiled/runtime/sidebar-state.js +41 -14
  92. package/src/tui-compiled/runtime/tui/command-dialogs.js +3 -15
  93. package/src/tui-compiled/runtime/tui/section-text.js +21 -0
  94. package/src/tui-compiled/runtime/tui/v2-dialog.js +137 -0
  95. package/src/tui-compiled/runtime/tui/v2.js +95 -0
  96. package/src/tui-compiled/runtime/tui.js +255 -163
  97. package/dist/index-4fnghj9e.js +0 -65
  98. package/dist/index-a69gr76b.js +0 -2
  99. package/dist/index-h263aftt.js +0 -157
  100. package/dist/index-ssj7m2rd.js +0 -8
  101. package/dist/index-ydz3hbhc.js +0 -2
  102. package/dist/token-util-4a2xxnpg.js +0 -1
package/dist/bin.js CHANGED
@@ -1,13 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import{c as M1}from"./index-fsxbncpw.js";import{Ba as U1,Ga as P,Ha as N,Ia as Y1,Ja as t,bc as x1,mb as R1,nb as E,ob as a,tc as j1,wb as K1,xb as S,yb as R,zb as L}from"./index-h263aftt.js";import"./index-a69gr76b.js";import"./index-ssj7m2rd.js";import{$d as W1,Xd as $1,Yd as q1}from"./index-y4gxyxqd.js";import"./index-116q849r.js";import"./index-66asrje2.js";import{execFile as F1}from"node:child_process";var F={run(b,G,D={}){return new Promise((X)=>{let z=performance.now(),J=D.timeoutMs??15000;F1(b,[...G],{env:D.env??process.env,timeout:J,windowsHide:!0,windowsVerbatimArguments:D.windowsVerbatimArguments,maxBuffer:1048576},(Q,q,Z)=>{let K=performance.now()-z;X({exitCode:Q?typeof Q.code==="number"?Q.code:1:0,stdout:String(q??""),stderr:String(Z??""),signal:Q?.signal??null,timedOut:Q?.killed===!0&&typeof Q.code!=="string"&&Q.signal==="SIGTERM"&&K>=J&&J>0,durationMs:K})})})}};function y(b,G,D,X,z,J=15000){if(G==="win32"&&/\.(cmd|bat)$/i.test(D)){if(/["%!\r\n]/.test(D)||X.some((Q)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(Q)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return b.run("cmd.exe",["/d","/s","/c",`""${D}" ${X.join(" ")}"`],{env:z,timeoutMs:J,windowsVerbatimArguments:!0})}return b.run(D,X,{env:z,timeoutMs:J})}import{accessSync as C1,constants as w1,existsSync as L1,readFileSync as S1,realpathSync as E1,statSync as I1}from"node:fs";import{mkdtemp as y1,rm as P1}from"node:fs/promises";import{tmpdir as v1}from"node:os";import{join as f1}from"node:path";import{parse as g1}from"jsonc-parser";import{homedir as V1}from"node:os";import{posix as k1,win32 as N1}from"node:path";import{fileURLToPath as A1}from"node:url";function T(b={}){let G=b.env??process.env,D=b.platform??process.platform,X=D==="win32"?N1:k1,z=b.home??(D==="win32"?G.USERPROFILE:G.HOME)??V1(),J=b.cwd??process.cwd(),Q=(O)=>X.resolve(J,O),q=G.OPENCODE_CONFIG_DIR?.trim(),Z=G.XDG_CONFIG_HOME?.trim(),K=G.PI_CODING_AGENT_DIR?.trim()||X.join(z,".pi","agent");if(K==="~")K=z;else if(/^~[/\\]/.test(K))K=X.join(z,K.slice(2));if(K.startsWith("file://"))K=A1(K);return{env:G,platform:D,path:X,home:z,cwd:J,opencode:q?Q(q):Z?X.join(Q(Z),"opencode"):X.join(z,".config","opencode"),pi:Q(K)}}function f(b,G){try{return I1(b)[G]()}catch{return!1}}var V={exists:L1,isFile:(b)=>f(b,"isFile"),isDirectory:(b)=>f(b,"isDirectory"),isExecutable(b){try{return C1(b,w1.X_OK),f(b,"isFile")}catch{return!1}},readText:(b)=>S1(b,"utf8"),realpath:E1};function H(b,G={}){let{env:D,platform:X,path:z,cwd:J}=T(G),Q=G.fs??V,q=Object.entries(D).find(([K])=>X==="win32"?K.toUpperCase()==="PATH":K==="PATH")?.[1]??"",Z=X==="win32"?[".exe",".cmd",".bat",""]:[""];for(let K of q.split(X==="win32"?";":":")){let O=K.trim().replace(/^"|"$/g,"");if(!O)continue;for(let B of Z){let $=z.resolve(J,O,b+B);if(X==="win32"?Q.isFile($):Q.isExecutable($))return $}}return null}function s(b={}){let{platform:G,home:D,env:X,path:z}=T(b);if(G==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",z.join(D,"Applications","OpenCode.app"),z.join(D,"Applications","OpenCode Beta.app")];if(G==="win32"){let J=X.LOCALAPPDATA||z.join(D,"AppData","Local");return[z.join(J,"Programs","opencode"),z.join(J,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",z.join(D,".local","share","applications","opencode.desktop")]}function g(b,G){let D=G.fs??V,{path:X}=T(G);try{let z=D.readText(b);if(z.length>65536)return b;let J=[...z.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!J.length)J.push(...z.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let Q=J.at(-1)?.[1];if(Q){let q=X.join(X.dirname(b),...Q.split(/[/\\]+/));if(D.isFile(q))return D.realpath(q)}return D.realpath(b)}catch{return b}}function d1(b,G){let D=G.fs??V,{path:X}=T(G),z=X.dirname(g(b,G));for(;;){try{let Q=JSON.parse(D.readText(X.join(z,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(Q.name))return"2";if(Q.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(Q.version??"")?"2":"1"}catch{}let J=X.dirname(z);if(J===z)return null;z=J}}function i(b={}){let G=H("opencode",b),D=H("opencode2",b),X=G&&D&&g(G,b)===g(D,b),z=b.fs??V,{path:J,opencode:Q}=T(b),q="1";for(let K of["jsonc","json"]){let O=J.join(Q,`opencode.${K}`);if(!z.exists(O))continue;try{if(Object.hasOwn(g1(z.readText(O))??{},"plugins"))q="2"}catch{}break}let Z=G?d1(G,b)??(X?"2":q):null;if(D&&Z==="1"&&!X)return"ambiguous";return D||X?"2":Z??q}async function d(b,G={}){let D=G.fs??V,{env:X,platform:z,opencode:J,pi:Q}=T(G),q=G.runner??F,Z=H("opencode",G)??H("opencode2",G),K=H("pi",G),O=H("ck",G),B=async(x)=>{if(!x)return null;let W;try{W=await y1(f1(v1(),"common-auth-setup-version-"));let I={...X,HOME:W,USERPROFILE:W,XDG_CONFIG_HOME:W,XDG_DATA_HOME:W,XDG_STATE_HOME:W,XDG_CACHE_HOME:W,OPENCODE_CONFIG_DIR:W,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:W},_=await y(q,z,x,["--version"],I,2000);return _.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(_.stdout)?.[0]??null:null}catch{return null}finally{if(W)await P1(W,{recursive:!0,force:!0}).catch(()=>{})}},$=!1;if(O&&D.exists(b.vault.connectionFile))try{(await(G.connect??P)({connectionFile:b.vault.connectionFile,handshakeTimeoutMs:2000})).close(),$=!0}catch{$=!1}let[Y,U]=await Promise.all([B(Z),B(K)]);return{opencode:{installed:D.isDirectory(J)||s(G).some((x)=>D.exists(x))||Z!==null,executable:Z,version:Y,directory:J,generation:i(G)},pi:{installed:K!==null||D.isDirectory(Q),executable:K,version:U,directory:Q},claustrum:{available:$,executable:O}}}import{setTimeout as s1}from"node:timers/promises";import{writeEnrollmentTokenFile as i1}from"@cortexkit/claustrum-client";var c1=45000,r=new Set(["opencode","litecode","opencode2","pi"]),h1=new Set(["node","bun"]),u1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function m1(b){return[...b.matchAll(/"([^"]*)"|(\S+)/g)].map((G)=>G[1]??G[2]??"")}function n(b){return(b.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var p1=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"]),l1=new Set(["-e","--eval","-p","--print"]);function a1(b,G){for(let D=0;D<G.length;D++){let X=G[D]??"";if(X==="--")return G[D+1];if(l1.has(X))return;if(X.startsWith("-")){if(!X.includes("=")&&p1.has(X))D++;continue}if(b==="bun"&&X==="run")continue;return X}return}function o(b){let[G,...D]=m1(b);if(G===void 0)return null;let X=n(G);if(r.has(X))return X;if(!h1.has(X))return null;let z=a1(X,D);if(z===void 0)return null;let J=n(z);if(r.has(J))return J;return u1.test(z)?"pi":null}class j extends Error{code="process-inspection-failed";step;exitCode;signal;timedOut;durationMs;constructor(b){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=b.step,this.exitCode=b.exitCode,this.signal=b.signal,this.timedOut=b.timedOut,this.durationMs=b.durationMs}get refusalText(){let b=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}: ${b} after ${Math.round(this.durationMs)} ms.`}}class k extends Error{activeHosts;constructor(b){let G=b.map((D)=>({pid:D.pid,command:o(D.command)??"host"}));super(`OpenCode or Pi processes are currently running:
3
- ${G.map((D)=>` - PID ${D.pid}: ${D.command}`).join(`
2
+ import{c as R1}from"./index-j8v2xwq6.js";import{Aa as S,Ba as X,Ca as P,eb as C1,pa as B1,qa as E,ra as i,wb as M1,za as O1}from"./index-0yh85bwb.js";import{$c as N1,Rc as V1,Yc as v,Zc as A,ad as b1}from"./index-7eb3dw37.js";import"./index-msx2m78k.js";import{Ae as D1,Be as H1,Ee as Y1,ue as Q1}from"./index-7c6sxtd6.js";import"./index-m5qmvr6c.js";import"./index-csky2xpg.js";import{spawn as _1}from"node:child_process";var Y=4096,A1=1048576;class s{buffer=Buffer.alloc(Y);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(G){if(G.length>=Y){if(G.length>Y||this.length>0)this.truncated=!0;G.copy(this.buffer,0,G.length-Y),this.start=0,this.length=Y;return}let b=Math.max(0,this.length+G.length-Y);if(b>0)this.truncated=!0;this.start=(this.start+b)%Y,this.length-=b;let z=(this.start+this.length)%Y,J=Math.min(G.length,Y-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,Y-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 w={run(G,b,z={}){return new Promise((J)=>{let Q=performance.now(),Z=z.timeoutMs??15000,K=new s,O=[],U=0,$=!1,W=!1,x=!1,q;try{q=_1(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()-Q});return}let F=Z>0?setTimeout(()=>{x=!0,q.kill("SIGTERM")},Z):void 0;q.stdout?.on("data",(j)=>{let M=A1-U,D=Math.min(M,j.length);if(D>0)O.push(j.subarray(0,D)),U+=D;if(j.length>M)$=!0,q.kill("SIGTERM")}),q.stderr?.on("data",(j)=>K.push(j));let H=!1,V=(j,M)=>{if(H)return;if(H=!0,F)clearTimeout(F);J({exitCode:W?1:$?1:j??1,stdout:Buffer.concat(O,U).toString("utf8"),stderr:K.toString(),stderrTruncated:K.didTruncate,...W?{spawnError:!0}:{},signal:M??null,timedOut:x,durationMs:performance.now()-Q})};q.once("error",()=>{if(W=!0,q.pid===void 0)V(null,null)}),q.once("close",(j,M)=>V(j,M))})}};function y(G,b,z,J,Q,Z=15000){if(b==="win32"&&/\.(cmd|bat)$/i.test(z)){if(/["%!\r\n]/.test(z)||J.some((K)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(K)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return G.run("cmd.exe",["/d","/s","/c",`""${z}" ${J.join(" ")}"`],{env:Q,timeoutMs:Z,windowsVerbatimArguments:!0})}return G.run(z,J,{env:Q,timeoutMs:Z})}import{accessSync as S1,constants as E1,existsSync as y1,readFileSync as v1,realpathSync as f1,statSync as g1}from"node:fs";import{mkdtemp as d1,rm as m1}from"node:fs/promises";import{tmpdir as c1}from"node:os";import{join as h1}from"node:path";import{parse as u1}from"jsonc-parser";import{homedir as I1}from"node:os";import{posix as T1,win32 as L1}from"node:path";import{fileURLToPath as P1}from"node:url";function C(G={}){let b=G.env??process.env,z=G.platform??process.platform,J=z==="win32"?L1:T1,Q=G.home??(z==="win32"?b.USERPROFILE:b.HOME)??I1(),Z=G.cwd??process.cwd(),K=(W)=>J.resolve(Z,W),O=b.OPENCODE_CONFIG_DIR?.trim(),U=b.XDG_CONFIG_HOME?.trim(),$=b.PI_CODING_AGENT_DIR?.trim()||J.join(Q,".pi","agent");if($==="~")$=Q;else if(/^~[/\\]/.test($))$=J.join(Q,$.slice(2));if($.startsWith("file://"))$=P1($);return{env:b,platform:z,path:J,home:Q,cwd:Z,opencode:O?K(O):U?J.join(K(U),"opencode"):J.join(Q,".config","opencode"),pi:K($)}}function d(G,b){try{return g1(G)[b]()}catch{return!1}}var k={exists:y1,isFile:(G)=>d(G,"isFile"),isDirectory:(G)=>d(G,"isDirectory"),isExecutable(G){try{return S1(G,E1.X_OK),d(G,"isFile")}catch{return!1}},readText:(G)=>v1(G,"utf8"),realpath:f1};function R(G,b={}){let{env:z,platform:J,path:Q,cwd:Z}=C(b),K=b.fs??k,O=Object.entries(z).find(([$])=>J==="win32"?$.toUpperCase()==="PATH":$==="PATH")?.[1]??"",U=J==="win32"?[".exe",".cmd",".bat",""]:[""];for(let $ of O.split(J==="win32"?";":":")){let W=$.trim().replace(/^"|"$/g,"");if(!W)continue;for(let x of U){let q=Q.resolve(Z,W,G+x);if(J==="win32"?K.isFile(q):K.isExecutable(q))return q}}return null}function o(G={}){let{platform:b,home:z,env:J,path:Q}=C(G);if(b==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",Q.join(z,"Applications","OpenCode.app"),Q.join(z,"Applications","OpenCode Beta.app")];if(b==="win32"){let Z=J.LOCALAPPDATA||Q.join(z,"AppData","Local");return[Q.join(Z,"Programs","opencode"),Q.join(Z,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",Q.join(z,".local","share","applications","opencode.desktop")]}function m(G,b){let z=b.fs??k,{path:J}=C(b);try{let Q=z.readText(G);if(Q.length>65536)return G;let Z=[...Q.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Z.length)Z.push(...Q.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let K=Z.at(-1)?.[1];if(K){let O=J.join(J.dirname(G),...K.split(/[/\\]+/));if(z.isFile(O))return z.realpath(O)}return z.realpath(G)}catch{return G}}function p1(G,b){let z=b.fs??k,{path:J}=C(b),Q=J.dirname(m(G,b));for(;;){try{let K=JSON.parse(z.readText(J.join(Q,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(K.name))return"2";if(K.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(K.version??"")?"2":"1"}catch{}let Z=J.dirname(Q);if(Z===Q)return null;Q=Z}}function n(G={}){let b=R("opencode",G),z=R("opencode2",G),J=b&&z&&m(b,G)===m(z,G),Q=G.fs??k,{path:Z,opencode:K}=C(G),O="1";for(let $ of["jsonc","json"]){let W=Z.join(K,`opencode.${$}`);if(!Q.exists(W))continue;try{if(Object.hasOwn(u1(Q.readText(W))??{},"plugins"))O="2"}catch{}break}let U=b?p1(b,G)??(J?"2":O):null;if(z&&U==="1"&&!J)return"ambiguous";return z||J?"2":U??O}async function c(G,b={}){let z=b.fs??k,{env:J,platform:Q,opencode:Z,pi:K}=C(b),O=b.runner??w,U=R("opencode",b)??R("opencode2",b),$=R("pi",b),W=R("ck",b),x=async(V)=>{if(!V)return null;let j;try{j=await d1(h1(c1(),"common-auth-setup-version-"));let M={...J,HOME:j,USERPROFILE:j,XDG_CONFIG_HOME:j,XDG_DATA_HOME:j,XDG_STATE_HOME:j,XDG_CACHE_HOME:j,OPENCODE_CONFIG_DIR:j,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:j},D=await y(O,Q,V,["--version"],M,2000);return D.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(D.stdout)?.[0]??null:null}catch{return null}finally{if(j)await m1(j,{recursive:!0,force:!0}).catch(()=>{})}},q=!1;if(W&&z.exists(G.vault.connectionFile))try{(await(b.connect??v)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000})).close(),q=!0}catch{q=!1}let[F,H]=await Promise.all([x(U),x($)]);return{opencode:{installed:z.isDirectory(Z)||o(b).some((V)=>z.exists(V))||U!==null,executable:U,version:F,directory:Z,generation:n(b)},pi:{installed:$!==null||z.isDirectory(K),executable:$,version:H,directory:K},claustrum:{available:q,executable:W}}}import{setTimeout as t1}from"node:timers/promises";import{writeEnrollmentTokenFile as e1}from"@cortexkit/claustrum-client";var l1=45000,t=new Set(["opencode","litecode","opencode2","pi"]),a1=new Set(["node","bun"]),r1=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function i1(G){return[...G.matchAll(/"([^"]*)"|(\S+)/g)].map((b)=>b[1]??b[2]??"")}function e(G){return(G.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var s1=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"]),o1=new Set(["-e","--eval","-p","--print"]);function n1(G,b){for(let z=0;z<b.length;z++){let J=b[z]??"";if(J==="--")return b[z+1];if(o1.has(J))return;if(J.startsWith("-")){if(!J.includes("=")&&s1.has(J))z++;continue}if(G==="bun"&&J==="run")continue;return J}return}function G1(G){let[b,...z]=i1(G);if(b===void 0)return null;let J=e(b);if(t.has(J))return J;if(!a1.has(J))return null;let Q=n1(J,z);if(Q===void 0)return null;let Z=e(Q);if(t.has(Z))return Z;return r1.test(Q)?"pi":null}class N 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 _ extends Error{activeHosts;constructor(G){let b=G.map((z)=>({pid:z.pid,command:G1(z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
3
+ ${b.map((z)=>` - PID ${z.pid}: ${z.command}`).join(`
4
4
  `)}
5
5
 
6
- Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=G,this.name="ProcessFenceViolationError"}}async function c(b=F,G={}){let D=(G.platform??process.platform)==="win32",X={step:D?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},z=async(J,Q,q,Z)=>{let K=performance.now();X={step:J,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let O=await b.run(Q,q,{env:G.env,timeoutMs:Z});return X={step:J,exitCode:O.exitCode,signal:O.signal??null,timedOut:O.timedOut??!1,durationMs:O.durationMs??performance.now()-K},O}finally{if(X.exitCode===null)X.durationMs=performance.now()-K;G.onStep?.({...X})}};try{let J=await z(D?"tasklist":"ps",D?"tasklist.exe":"ps",D?["/fo","csv","/nh"]:["-eo","pid,command"]);if(J.exitCode!==0)throw new j(X);let Q=[];for(let Z of J.stdout.split(/\r?\n/)){let K=Z.trim();if(!K)continue;let O,B;if(D){let $=/^"([^"]+)","(\d+)"(?:,|$)/.exec(K);if(!$)throw new j(X);B=$[1]??"",O=Number($[2])}else{let $=/^(\d+)\s+(.+)$/.exec(K);if(!$){if(/^PID\s+COMMAND$/i.test(K))continue;throw new j(X)}O=Number($[1]),B=$[2]??""}if(!Number.isSafeInteger(O)||O<0)throw new j(X);Q.push({pid:O,command:B})}if(!Q.length)throw new j(X);let q=Q.filter((Z)=>Z.pid!==process.pid&&/^(?:node|bun)\.exe$/i.test(Z.command));if(D&&q.length&&G.inspectRuntimes!==!1){let Z=await z("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],c1);if(Z.exitCode!==0)throw new j(X);let K=JSON.parse(Z.stdout||"null"),O=K===null?[]:Array.isArray(K)?K:[K],B=new Map;for(let $ of O){if(!$||typeof $!=="object"||!("ProcessId"in $)||!("CommandLine"in $)||!Number.isSafeInteger($.ProcessId))throw new j(X);if(typeof $.CommandLine==="string")B.set(Number($.ProcessId),$.CommandLine);else if(q.some((Y)=>Y.pid===$.ProcessId))throw new j(X)}for(let $ of q)$.command=B.get($.pid)??""}return Q}catch(J){if(J instanceof j)throw J;throw new j(X)}}function C(b=F,G={}){let D=(X)=>X.pid!==process.pid&&o(X.command)!==null;return{async listRunningHosts(X){return(await c(b,{...G,env:X})).filter(D)},async previewRunningHosts(X){let z=await c(b,{...G,env:X,inspectRuntimes:!1}),J=(G.platform??process.platform)==="win32";return{hosts:z.filter(D),uncheckedRuntimes:J?z.filter((Q)=>Q.pid!==process.pid&&/^(?:node|bun)\.exe$/i.test(Q.command)).length:0}}}}async function w(b,G){let D=await b.listRunningHosts(G);if(D.length)throw new k(D)}async function e(b,G,D,X,z){let{name:J,paths:Q}=b.vault.hosts[G],q=N(Q);await z();let Z=await(D.connect??P)({connectionFile:b.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw Error("Claustrum connection failed; start ck and rerun setup.")});try{let K=new t({proposedName:J,paths:q,client:{enrollPropose:async(B)=>{return await z(),Z.enrollPropose(B)},enrollPoll:async(B)=>{return await z(),Z.enrollPoll(B)}},writeTokenFile:async(B,$)=>{await z(),await i1(B,$)}}),O;for(let B=0;B<300;B++){await z();let $=await K.reconcile();if($.state==="approved"){R(X,`Connected ${G} to Claustrum.`);return}if($.state!=="pending"&&$.state!=="busy")throw Error("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");if($.state==="pending"&&$.requestId&&$.requestId!==O){if(!/^[a-zA-Z0-9_-]+$/.test($.requestId))throw Error("Invalid enrollment request id.");O=$.requestId,R(X,"Waiting for approval. In another terminal, run:"),R(X,` ck auth enroll approve --request-id ${$.requestId} --name ${J}`),R(X,`Enrollment files: ${q.statePath}, ${q.tokenPath}`)}await(D.wait??s1)(1000)}throw Error("Claustrum approval is still pending; approve with ck and rerun setup.")}catch(K){if(K instanceof k||K instanceof j)throw K;throw Error("Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.")}finally{Z.close()}}async function b1(b,G){let D=new Set(G);for(;;){let X=await L(b,[...["opencode","pi"].map((z)=>({value:z,label:`[${D.has(z)?"x":" "}] ${z==="opencode"?"OpenCode":"Pi"}`,hint:G.includes(z)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if(X===null)return null;if(X==="done")return[...D];if(D.has(X))D.delete(X);else D.add(X)}}import{applyEdits as h,createScanner as J0,findNodeAtLocation as K0,modify as D1,parse as Q0,parseTree as Z0}from"jsonc-parser";import{randomUUID as r1}from"node:crypto";import{mkdir as n1,open as o1,rename as t1,stat as e1,unlink as b0}from"node:fs/promises";import{basename as G0,dirname as D0,join as X0}from"node:path";import{setTimeout as z0}from"node:timers/promises";async function G1(b,G,D={}){let X=(D.platform??process.platform)==="win32",z=D0(b);await n1(z,{recursive:!0});let J;if(!X)try{J=(await e1(b)).mode&4095}catch(Z){if(Z.code!=="ENOENT")throw Z}let Q=X0(z,`.${G0(b)}.${(D.stageName??r1)()}.tmp`),q=!1;try{let Z=await o1(Q,"wx",J??438);q=!0;try{if(await Z.writeFile(G,"utf8"),J!==void 0)await Z.chmod(J)}finally{await Z.close()}let K=D.now??(()=>performance.now()),O=K();for(let B=0;;B++){await D.beforeRename?.();try{await(D.rename??t1)(Q,b),q=!1;return}catch($){let Y=$.code,U=2000-(K()-O);if(!X||!["EPERM","EBUSY","EACCES"].includes(Y??"")||U<=0||B>=40)throw Error(`Unable to replace host config ${b}. Close editors or other programs using the file, then rerun setup.`);await(D.wait??z0)(Math.min(U,25*2**Math.min(B,2)))}}}finally{if(q)await b0(Q).catch(()=>{})}}function X1(b){let G=typeof b==="string"?b:Array.isArray(b)?b[0]:b&&typeof b==="object"&&("package"in b)?b.package:null;if(typeof G!=="string")return null;let D=G.indexOf("@",G.startsWith("@")?1:0);return D<0?G:G.slice(0,D)}function z1(b,G,D){let X=Z0(b),z=X&&K0(X,[G]),J=z?.children??[],Q=J[D];if(!Q||!z)throw Error("Invalid plugin array edit.");let q=[{offset:Q.offset,length:Q.length,content:""}],Z=(K,O)=>{let B=J0(b.slice(K,O),!0);if(B.scan(),b[K+B.getTokenOffset()]===",")q.push({offset:K+B.getTokenOffset(),length:1,content:""})};if(D===J.length-1){let K=J[D-1];if(K)Z(K.offset+K.length,Q.offset);Z(Q.offset+Q.length,z.offset+z.length-1)}else Z(Q.offset+Q.length,J[D+1]?.offset??Q.offset+Q.length);return h(b,q)}function J1(b,G,D,X){let z=[],J=Q0(b,z,{allowTrailingComma:!0});if(z.length||!J||typeof J!=="object"||Array.isArray(J))throw Error("Invalid OpenCode config; refusing to overwrite it.");let Q={formattingOptions:{insertSpaces:!/^\t+/m.test(b),tabSize:/^([ ]+)"/m.exec(b)?.[1]?.length??2,eol:b.includes(`\r
6
+ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=b,this.name="ProcessFenceViolationError"}}async function h(G=w,b={}){let z=(b.platform??process.platform)==="win32",J={step:z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},Q=async(Z,K,O,U)=>{let $=performance.now();J={step:Z,exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let W=await G.run(K,O,{env:b.env,timeoutMs:U});return J={step:Z,exitCode:W.exitCode,signal:W.signal??null,timedOut:W.timedOut??!1,durationMs:W.durationMs??performance.now()-$},W}finally{if(J.exitCode===null)J.durationMs=performance.now()-$;b.onStep?.({...J})}};try{let Z=await Q(z?"tasklist":"ps",z?"tasklist.exe":"ps",z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(Z.exitCode!==0)throw new N(J);let K=[];for(let U of Z.stdout.split(/\r?\n/)){let $=U.trim();if(!$)continue;let W,x;if(z){let q=/^"([^"]+)","(\d+)"(?:,|$)/.exec($);if(!q)throw new N(J);x=q[1]??"",W=Number(q[2])}else{let q=/^(\d+)\s+(.+)$/.exec($);if(!q){if(/^PID\s+COMMAND$/i.test($))continue;throw new N(J)}W=Number(q[1]),x=q[2]??""}if(!Number.isSafeInteger(W)||W<0)throw new N(J);K.push({pid:W,command:x})}if(!K.length)throw new N(J);let O=K.filter((U)=>U.pid!==process.pid&&/^(?:node|bun)\.exe$/i.test(U.command));if(z&&O.length&&b.inspectRuntimes!==!1){let U=await Q("CIM","powershell.exe",["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`],l1);if(U.exitCode!==0)throw new N(J);let $=JSON.parse(U.stdout||"null"),W=$===null?[]:Array.isArray($)?$:[$],x=new Map;for(let q of W){if(!q||typeof q!=="object"||!("ProcessId"in q)||!("CommandLine"in q)||!Number.isSafeInteger(q.ProcessId))throw new N(J);if(typeof q.CommandLine==="string")x.set(Number(q.ProcessId),q.CommandLine);else if(O.some((F)=>F.pid===q.ProcessId))throw new N(J)}for(let q of O)q.command=x.get(q.pid)??""}return K}catch(Z){if(Z instanceof N)throw Z;throw new N(J)}}function T(G=w,b={}){let z=(J)=>J.pid!==process.pid&&G1(J.command)!==null;return{async listRunningHosts(J){return(await h(G,{...b,env:J})).filter(z)},async previewRunningHosts(J){let Q=await h(G,{...b,env:J,inspectRuntimes:!1}),Z=(b.platform??process.platform)==="win32";return{hosts:Q.filter(z),uncheckedRuntimes:Z?Q.filter((K)=>K.pid!==process.pid&&/^(?:node|bun)\.exe$/i.test(K.command)).length:0}}}}async function L(G,b){let z=await G.listRunningHosts(b);if(z.length)throw new _(z)}async function z1(G,b,z,J,Q){let{name:Z,paths:K}=G.vault.hosts[b],O=A(K);await Q();let U=await(z.connect??v)({connectionFile:G.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw Error("Claustrum connection failed; start ck and rerun setup.")});try{let $=new b1({proposedName:Z,paths:O,client:{enrollPropose:async(x)=>{return await Q(),U.enrollPropose(x)},enrollPoll:async(x)=>{return await Q(),U.enrollPoll(x)}},writeTokenFile:async(x,q)=>{await Q(),await e1(x,q)}}),W;for(let x=0;x<300;x++){await Q();let q=await $.reconcile();if(q.state==="approved"){X(J,`Connected ${b} to Claustrum.`);return}if(q.state!=="pending"&&q.state!=="busy")throw Error("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");if(q.state==="pending"&&q.requestId&&q.requestId!==W){if(!/^[a-zA-Z0-9_-]+$/.test(q.requestId))throw Error("Invalid enrollment request id.");W=q.requestId,X(J,"Waiting for approval. In another terminal, run:"),X(J,` ck auth enroll approve --request-id ${q.requestId} --name ${Z}`),X(J,`Enrollment files: ${O.statePath}, ${O.tokenPath}`)}await(z.wait??t1)(1000)}throw Error("Claustrum approval is still pending; approve with ck and rerun setup.")}catch($){if($ instanceof _||$ instanceof N)throw $;throw Error("Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.")}finally{U.close()}}async function J1(G,b){let z=new Set(b);for(;;){let J=await P(G,[...["opencode","pi"].map((Q)=>({value:Q,label:`[${z.has(Q)?"x":" "}] ${Q==="opencode"?"OpenCode":"Pi"}`,hint:b.includes(Q)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if(J===null)return null;if(J==="done")return[...z];if(z.has(J))z.delete(J);else z.add(J)}}import{applyEdits as u,createScanner as D0,findNodeAtLocation as H0,modify as $1,parse as j0,parseTree as F0}from"jsonc-parser";var G0="Pi install failed; run pi install after checking your npm connection.";function b0(G){let b=Buffer.from(G,"utf8");if(b.length<=Y)return G;let z=b.length-Y;while(z<b.length){let J=b[z];if(J===void 0||(J&192)!==128)break;z++}return b.subarray(z).toString("utf8")}function z0(G){let b=G.indexOf(`
7
+ `);return b<0?"":G.slice(b+1)}class f extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(G){super(G0);this.name="SetupCommandError",this.exitCode=G.exitCode,this.signal=G.signal;let b=G.stderrTruncated?z0(G.stderrTail):G.stderrTail,z=Q1(b);this.stderrTail=b0(typeof z==="string"?z:"")}}import{randomUUID as J0}from"node:crypto";import{mkdir as Q0,open as Z0,rename as $0,stat as K0,unlink as q0}from"node:fs/promises";import{basename as U0,dirname as O0,join as W0}from"node:path";import{setTimeout as x0}from"node:timers/promises";async function Z1(G,b,z={}){let J=(z.platform??process.platform)==="win32",Q=O0(G);await Q0(Q,{recursive:!0});let Z;if(!J)try{Z=(await K0(G)).mode&4095}catch(U){if(U.code!=="ENOENT")throw U}let K=W0(Q,`.${U0(G)}.${(z.stageName??J0)()}.tmp`),O=!1;try{let U=await Z0(K,"wx",Z??438);O=!0;try{if(await U.writeFile(b,"utf8"),Z!==void 0)await U.chmod(Z)}finally{await U.close()}let $=z.now??(()=>performance.now()),W=$();for(let x=0;;x++){await z.beforeRename?.();try{await(z.rename??$0)(K,G),O=!1;return}catch(q){let F=q.code,H=2000-($()-W);if(!J||!["EPERM","EBUSY","EACCES"].includes(F??"")||H<=0||x>=40)throw Error(`Unable to replace host config ${G}. Close editors or other programs using the file, then rerun setup.`);await(z.wait??x0)(Math.min(H,25*2**Math.min(x,2)))}}}finally{if(O)await q0(K).catch(()=>{})}}function K1(G){let b=typeof G==="string"?G:Array.isArray(G)?G[0]:G&&typeof G==="object"&&("package"in G)?G.package:null;if(typeof b!=="string")return null;let z=b.indexOf("@",b.startsWith("@")?1:0);return z<0?b:b.slice(0,z)}function q1(G,b,z){let J=F0(G),Q=J&&H0(J,[b]),Z=Q?.children??[],K=Z[z];if(!K||!Q)throw Error("Invalid plugin array edit.");let O=[{offset:K.offset,length:K.length,content:""}],U=($,W)=>{let x=D0(G.slice($,W),!0);if(x.scan(),G[$+x.getTokenOffset()]===",")O.push({offset:$+x.getTokenOffset(),length:1,content:""})};if(z===Z.length-1){let $=Z[z-1];if($)U($.offset+$.length,K.offset);U(K.offset+K.length,Q.offset+Q.length-1)}else U(K.offset+K.length,Z[z+1]?.offset??K.offset+K.length);return u(G,O)}function U1(G,b,z,J){let Q=[],Z=j0(G,Q,{allowTrailingComma:!0});if(Q.length||!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid OpenCode config; refusing to overwrite it.");let K={formattingOptions:{insertSpaces:!/^\t+/m.test(G),tabSize:/^([ ]+)"/m.exec(G)?.[1]?.length??2,eol:G.includes(`\r
7
8
  `)?`\r
8
9
  `:`
9
- `}},q=b,Z=J[G];if(Z!==void 0&&!Array.isArray(Z))throw Error(`OpenCode ${G} must be an array.`);let K=Array.isArray(Z)?[...Z]:[],O=K.flatMap((Y,U)=>X1(Y)===D?[U]:[]),B=`${D}@${X}`;if(!O.length)q=h(q,D1(q,Z===void 0?[G]:[G,K.length],Z===void 0?[B]:B,Q));else{let Y=O[0],U=K[Y],x=Array.isArray(U)?[B,...U.slice(1)]:U&&typeof U==="object"?{...U,package:B}:B;if(JSON.stringify(U)!==JSON.stringify(x))q=h(q,D1(q,[G,Y],x,Q));for(let W of O.slice(1).reverse())q=z1(q,G,W)}let $=G==="plugin"?"plugins":"plugin";if(Array.isArray(J[$])){let Y=J[$];for(let U=Y.length-1;U>=0;U--)if(X1(Y[U])===D)q=z1(q,$,U)}return q}function u(b,G,D={}){let X=D.fs??V,{path:z,opencode:J}=T(D),Q=G==="2"?"plugins":"plugin";return(G==="2"?["opencode"]:["opencode","tui"]).map((Z)=>{let K=z.join(J,`${Z}.jsonc`),O=z.join(J,`${Z}.json`),B=X.exists(K)?K:X.exists(O)?O:K,$=X.exists(B),Y=$?X.readText(B):`${JSON.stringify({$schema:`https://opencode.ai/${Z==="tui"?"tui":"config"}.json`},null,2)}
10
- `,U=J1(Y,Q,b.packages.opencode,b.version);return{path:B,content:U,changed:!$||U!==Y}})}async function m(b,G){for(let D of b){if(!D.changed)continue;await G?.(),await G1(D.path,D.content,{beforeRename:G})}}async function p(b,G,D={}){let{platform:X,env:z}=T(D);if((await y(D.runner??F,X,G,["install",`npm:${b.packages.pi}@${b.version}`],z)).exitCode!==0)throw Error("Pi install failed; run pi install after checking your npm connection.")}var Q1="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function $0(b){let G={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,opencode:void 0};for(let D of b)if(D==="--yes")G.yes=!0;else if(D==="--dry-run")G.dryRun=!0;else if(D==="--claustrum")G.claustrum=!0;else if(D==="--no-claustrum")G.noClaustrum=!0;else if(D==="--login")G.login=!0;else if(/^--opencode=(1|2|both)$/.test(D))G.opencode=D.slice(11);else throw Error(`Unknown setup argument: ${D}`);if(G.claustrum&&G.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(G.login&&G.claustrum)throw Error("--login and --claustrum cannot be used together.");return G}function q0(b){for(let G of Object.values(b.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(G))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(b.version))throw Error("Setup requires a concrete package version.");for(let G of Object.values(b.vault.hosts))if(!/^[a-z0-9][a-z0-9-]*$/.test(G.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.")}async function l(b,G=[],D={}){let X=$0(G);q0(b);let z=D.terminal??K1(),J=await d(b,D);R(z,`${b.displayName} setup`);for(let[_,M]of[["OpenCode",J.opencode],["Pi",J.pi]])R(z,`${_}: ${M.installed?`found (version ${M.version??"unknown"})`:"not found"} — ${M.directory}`);R(z,`Claustrum: ${J.claustrum.available?"available":"not available"}`);let Q=J.pi.installed&&!J.pi.executable;if(Q)R(z,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let q=["opencode","pi"].filter((_)=>J[_].installed&&!(_==="pi"&&Q)),Z=X.yes||X.dryRun&&!S(z);if(!Z&&!S(z))throw Error("Setup requires a TTY or --yes.");let K=Z?q:await b1(z,q)??[],O=X.opencode??(J.opencode.generation==="ambiguous"?"1":J.opencode.generation);if(K.includes("opencode")&&!X.opencode&&J.opencode.generation==="ambiguous"){if(Z||!S(z))throw Error(Q1);let _=await L(z,[{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(_===null)return{hosts:[],dryRun:X.dryRun,mode:"local",detection:J};O=_}if(!K.length)return R(z,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:K,dryRun:X.dryRun,mode:"local",detection:J};let{env:B,platform:$}=T(D),Y=D.fence??C(D.runner??F,{platform:$}),U=async()=>{try{await w(Y,B)}catch(_){if(_ instanceof j)R(z,_.refusalText);throw _}};if(R(z,"Checking that OpenCode and Pi are not running…"),X.dryRun)try{let _=Y.previewRunningHosts?await Y.previewRunningHosts(B):{hosts:await Y.listRunningHosts(B),uncheckedRuntimes:0},M=_.hosts;if(_.uncheckedRuntimes>0)R(z,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let H1=new Set(new k(M).activeHosts.map((v)=>v.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let v of H1)R(z,`${v} is running; setup will ask you to quit it.`)}catch(_){if(R(z,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),_ instanceof j)R(z,_.refusalText)}else await U();if(X.claustrum&&!J.claustrum.available)throw Error("Claustrum is not available. Start ck or use --no-claustrum for local sign-in.");let x=Boolean(X.claustrum);if(!x&&!X.login&&!X.noClaustrum&&!Z&&J.claustrum.available&&S(z)){let _=await L(z,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(_===null)return R(z,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:X.dryRun,mode:"local",detection:J};x=_===!0}let W=x?"claustrum":"local",I=K.includes("opencode")?u(b,O,D):[];if(X.dryRun){R(z,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let _ of K){if(b.beforeSignIn)R(z,`Would run beforeSignIn(${_}, ${W}).`);if(x){let M=N(b.vault.hosts[_].paths);R(z,`Would Connect ${_}: write ${M.statePath} and ${M.tokenPath}; wait for ck auth enroll approve.`)}else R(z,`Would sign in locally for ${_}.`);if(b.beforeRegister)R(z,`Would run beforeRegister(${_}, ${W}).`)}for(let _ of I)R(z,`${_.changed?"Would write":"Unchanged"} ${_.path}:
11
- ${_.content}`);if(K.includes("pi"))R(z,`Would run ${J.pi.executable} install npm:${b.packages.pi}@${b.version}`);for(let _ of K)R(z,`Would migrate ${_} using the plugin callback (provider-specific writes).`)}else{let _={opencodeGeneration:O,mode:W,hosts:Object.freeze([...K]),piAgentDir:J.pi.directory};for(let M of K){if(await U(),await b.beforeSignIn?.(M,_),await U(),x)await e(b,M,D,z,U);else await b.signInLocal(M,_);if(await U(),await b.beforeRegister?.(M,W,_),await U(),M==="opencode")await m(I,U);else await p(b,J.pi.executable,D);await U(),await b.migrate(M,_)}}return R(z,`${X.dryRun?"Planned":"Configured"} ${b.displayName} for ${K.join(", ")} (${W}).`),R(z,`Next: ${K.includes("opencode")?"start OpenCode":"start Pi"} and run ${b.slashCommand}.`),{hosts:K,dryRun:X.dryRun,mode:W,detection:J}}import{basename as R0}from"node:path";import{resolveClaustrumConnectionPath as W0}from"@cortexkit/claustrum-client";var Z1={name:"@cortexkit/pi-openai-auth",version:"1.0.5",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.17.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.9.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 O0}from"node:os";import{join as B1}from"node:path";function _0(){return process.env.PI_AGENT_DIR?.trim()||B1(O0(),".pi","agent")}function O1(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||B1(_0(),$1)}function U0(b=O1()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||q1(b)}function _1(b=O1()){return{configPath:b,statePath:U0(b)}}var A={name:"@cortexkit/opencode-openai-auth",version:"1.0.5",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.17.1","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.27"},dependencies:{"@cortexkit/claustrum-client":"^0.9.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 T1(b={}){let G=b.print??console.log,D=b.fence??C(),X={opencode:{stateDir:a(x1().statePath),host:"opencode"},pi:{stateDir:a(_1().statePath),host:"pi"}},z=async(J)=>{if(await Y1(N(X[J]),E(J))!=="local")throw Error(`${J} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:A.name,pi:Z1.name},version:A.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:W0(),hosts:{opencode:{name:E("opencode"),paths:X.opencode},pi:{name:E("pi"),paths:X.pi}}},async beforeRegister(J,Q){if(Q==="claustrum"){if(G(`Allow this host to read OpenAI accounts with:
12
- ck auth grant --principal enrolled:${E(J)} --selector-kind category --selector ${R1.category} --operation read`),J==="opencode")G("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await z(J)},async signInLocal(J,Q){if(await z(J),J==="pi"){G("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(Q.opencodeGeneration!=="1"){let W=R0(H("opencode2",b.io)??H("opencode",b.io)??"opencode");G(`In OpenCode 2, run ${W} 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(Q.opencodeGeneration==="2")return;if(j1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let q=M1(),Z={path:{id:"openai"}};if(await q.get(Z)!==void 0){G("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let K=b.beginLogin??U1,O=new AbortController,B=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),$={version:A.version,signal:O.signal},Y,U=!B;try{Y=await K({...$,headless:B})}catch(W){if(B)throw W;U=!1,G("Browser callback unavailable; using device-code sign-in."),Y=await K({version:A.version,headless:!0})}if(U){if(!(b.openBrowser??W1)(Y.url))O.abort(),await Y.completion.catch(()=>{}),G("Browser unavailable; using device-code sign-in."),Y=await K({version:A.version,headless:!0})}G(`${Y.url}
13
- ${Y.instructions}`);let x=await Y.completion;await w(D),await z(J),await q.set({...Z,body:{type:"oauth",access:x.access,refresh:x.refresh,expires:x.expires,...x.accountId?{accountId:x.accountId}:{}}}),G("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(J){G(`${J}: 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 l(T1(),process.argv.slice(3))}catch(b){console.error(b instanceof Error?b.message:String(b)),process.exitCode=1}
10
+ `}},O=G,U=Z[b];if(U!==void 0&&!Array.isArray(U))throw Error(`OpenCode ${b} must be an array.`);let $=Array.isArray(U)?[...U]:[],W=$.flatMap((F,H)=>K1(F)===z?[H]:[]),x=`${z}@${J}`;if(!W.length)O=u(O,$1(O,U===void 0?[b]:[b,$.length],U===void 0?[x]:x,K));else{let F=W[0],H=$[F],V=Array.isArray(H)?[x,...H.slice(1)]:H&&typeof H==="object"?{...H,package:x}:x;if(JSON.stringify(H)!==JSON.stringify(V))O=u(O,$1(O,[b,F],V,K));for(let j of W.slice(1).reverse())O=q1(O,b,j)}let q=b==="plugin"?"plugins":"plugin";if(Array.isArray(Z[q])){let F=Z[q];for(let H=F.length-1;H>=0;H--)if(K1(F[H])===z)O=q1(O,q,H)}return O}function p(G,b,z={}){let J=z.fs??k,{path:Q,opencode:Z}=C(z),K=b==="2"?"plugins":"plugin";return(b==="2"?["opencode"]:["opencode","tui"]).map((U)=>{let $=Q.join(Z,`${U}.jsonc`),W=Q.join(Z,`${U}.json`),x=J.exists($)?$:J.exists(W)?W:$,q=J.exists(x),F=q?J.readText(x):`${JSON.stringify({$schema:`https://opencode.ai/${U==="tui"?"tui":"config"}.json`},null,2)}
11
+ `,H=U1(F,K,G.packages.opencode,G.version);return{path:x,content:H,changed:!q||H!==F}})}async function l(G,b){for(let z of G){if(!z.changed)continue;await b?.(),await Z1(z.path,z.content,{beforeRename:b})}}async function a(G,b,z={}){let{platform:J,env:Q}=C(z),Z=await y(z.runner??w,J,b,["install",`npm:${G.packages.pi}@${G.version}`],Q);if(Z.exitCode!==0||Z.timedOut)throw new f({exitCode:Z.spawnError?null:Z.exitCode,signal:Z.signal??null,stderrTail:Z.stderr,stderrTruncated:Z.stderrTruncated??!1})}var W1="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function X0(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 V0(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 r(G,b=[],z={}){let J=X0(b);V0(G);let Q=z.terminal??O1(),Z=await c(G,z);X(Q,`${G.displayName} setup`);for(let[D,B]of[["OpenCode",Z.opencode],["Pi",Z.pi]])X(Q,`${D}: ${B.installed?`found (version ${B.version??"unknown"})`:"not found"} — ${B.directory}`);X(Q,`Claustrum: ${Z.claustrum.available?"available":"not available"}`);let K=Z.pi.installed&&!Z.pi.executable;if(K)X(Q,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let O=["opencode","pi"].filter((D)=>Z[D].installed&&!(D==="pi"&&K)),U=J.yes||J.dryRun&&!S(Q);if(!U&&!S(Q))throw Error("Setup requires a TTY or --yes.");let $=U?O:await J1(Q,O)??[],W=J.opencode??(Z.opencode.generation==="ambiguous"?"1":Z.opencode.generation);if($.includes("opencode")&&!J.opencode&&Z.opencode.generation==="ambiguous"){if(U||!S(Q))throw Error(W1);let D=await P(Q,[{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(D===null)return{hosts:[],dryRun:J.dryRun,mode:"local",detection:Z};W=D}if(!$.length)return X(Q,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:$,dryRun:J.dryRun,mode:"local",detection:Z};let{env:x,platform:q}=C(z),F=z.fence??T(z.runner??w,{platform:q}),H=async()=>{try{await L(F,x)}catch(D){if(D instanceof N)X(Q,D.refusalText);throw D}};if(X(Q,"Checking that OpenCode and Pi are not running…"),J.dryRun)try{let D=F.previewRunningHosts?await F.previewRunningHosts(x):{hosts:await F.listRunningHosts(x),uncheckedRuntimes:0},B=D.hosts;if(D.uncheckedRuntimes>0)X(Q,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let k1=new Set(new _(B).activeHosts.map((g)=>g.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let g of k1)X(Q,`${g} is running; setup will ask you to quit it.`)}catch(D){if(X(Q,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),D instanceof N)X(Q,D.refusalText)}else await H();if(J.claustrum&&!Z.claustrum.available)throw Error("Claustrum is not available. Start ck or use --no-claustrum for local sign-in.");let V=Boolean(J.claustrum);if(!V&&!J.login&&!J.noClaustrum&&!U&&Z.claustrum.available&&S(Q)){let D=await P(Q,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"});if(D===null)return X(Q,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:J.dryRun,mode:"local",detection:Z};V=D===!0}let j=V?"claustrum":"local",M=$.includes("opencode")?p(G,W,z):[];if(J.dryRun){X(Q,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let D of $){if(G.beforeSignIn)X(Q,`Would run beforeSignIn(${D}, ${j}).`);if(V){let B=A(G.vault.hosts[D].paths);X(Q,`Would Connect ${D}: write ${B.statePath} and ${B.tokenPath}; wait for ck auth enroll approve.`)}else X(Q,`Would sign in locally for ${D}.`);if(G.beforeRegister)X(Q,`Would run beforeRegister(${D}, ${j}).`)}for(let D of M)X(Q,`${D.changed?"Would write":"Unchanged"} ${D.path}:
12
+ ${D.content}`);if($.includes("pi"))X(Q,`Would run ${Z.pi.executable} install npm:${G.packages.pi}@${G.version}`);for(let D of $)X(Q,`Would migrate ${D} using the plugin callback (provider-specific writes).`)}else{let D={opencodeGeneration:W,mode:j,hosts:Object.freeze([...$]),piAgentDir:Z.pi.directory};for(let B of $){if(await H(),await G.beforeSignIn?.(B,D),await H(),V)await z1(G,B,z,Q,H);else await G.signInLocal(B,D);if(await H(),await G.beforeRegister?.(B,j,D),await H(),B==="opencode")await l(M,H);else await a(G,Z.pi.executable,z);await H(),await G.migrate(B,D)}}return X(Q,`${J.dryRun?"Planned":"Configured"} ${G.displayName} for ${$.join(", ")} (${j}).`),X(Q,`Next: ${$.includes("opencode")?"start OpenCode":"start Pi"} and run ${G.slashCommand}.`),{hosts:$,dryRun:J.dryRun,mode:j,detection:Z}}import{basename as R0}from"node:path";import{resolveClaustrumConnectionPath as w0}from"@cortexkit/claustrum-client";var x1={name:"@cortexkit/pi-openai-auth",version:"1.1.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.18.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.9.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 B0}from"node:os";import{join as j1}from"node:path";function Y0(){return process.env.PI_AGENT_DIR?.trim()||j1(B0(),".pi","agent")}function F1(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||j1(Y0(),D1)}function C0(G=F1()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||H1(G)}function X1(G=F1()){return{configPath:G,statePath:C0(G)}}var I={name:"@cortexkit/opencode-openai-auth",version:"1.1.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.18.0","@cortexkit/openai-auth-core":"workspace:*","@opencode/plugin":"2.0.27"},dependencies:{"@cortexkit/claustrum-client":"^0.9.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 w1(G={}){let b=G.print??console.log,z=G.fence??T(),J={opencode:{stateDir:i(C1().statePath),host:"opencode"},pi:{stateDir:i(X1().statePath),host:"pi"}},Q=async(Z)=>{if(await N1(A(J[Z]),E(Z))!=="local")throw Error(`${Z} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:I.name,pi:x1.name},version:I.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:w0(),hosts:{opencode:{name:E("opencode"),paths:J.opencode},pi:{name:E("pi"),paths:J.pi}}},async beforeRegister(Z,K){if(K==="claustrum"){if(b(`Allow this host to read OpenAI accounts with:
13
+ ck auth grant --principal enrolled:${E(Z)} --selector-kind category --selector ${B1.category} --operation read`),Z==="opencode")b("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await Q(Z)},async signInLocal(Z,K){if(await Q(Z),Z==="pi"){b("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(K.opencodeGeneration!=="1"){let j=R0(R("opencode2",G.io)??R("opencode",G.io)??"opencode");b(`In OpenCode 2, run ${j} 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(K.opencodeGeneration==="2")return;if(M1(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let O=R1(),U={path:{id:"openai"}};if(await O.get(U)!==void 0){b("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let $=G.beginLogin??V1,W=new AbortController,x=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),q={version:I.version,signal:W.signal},F,H=!x;try{F=await $({...q,headless:x})}catch(j){if(x)throw j;H=!1,b("Browser callback unavailable; using device-code sign-in."),F=await $({version:I.version,headless:!0})}if(H){if(!(G.openBrowser??Y1)(F.url))W.abort(),await F.completion.catch(()=>{}),b("Browser unavailable; using device-code sign-in."),F=await $({version:I.version,headless:!0})}b(`${F.url}
14
+ ${F.instructions}`);let V=await F.completion;await L(z),await Q(Z),await O.set({...U,body:{type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires,...V.accountId?{accountId:V.accountId}:{}}}),b("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Z){b(`${Z}: 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 r(w1(),process.argv.slice(3))}catch(G){console.error(G instanceof Error?G.message:String(G)),process.exitCode=1}
@@ -1,7 +1,8 @@
1
- import { n as QuotaMap } from "./map-m6f5a_IA.js";
1
+ import { a as KnobValues, c as PluginExtraSection, i as CommandInvocation, l as PluginSection, o as MenuKnob, t as CommandApplyRequest } from "./model-YRg7Uowo.js";
2
+ import { n as QuotaMap } from "./map-Buq-GW7l.js";
2
3
  import { ClaustrumClient, EnrollmentPollOutcome } from "@cortexkit/claustrum-client";
3
4
  import "@cortexkit/private-files";
4
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/schema.d.ts
5
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/schema.d.ts
5
6
  type OAuthCredential = {
6
7
  type: 'oauth';
7
8
  access?: string;
@@ -190,7 +191,7 @@ interface PoolRow {
190
191
  unbound?: true;
191
192
  }
192
193
  //#endregion
193
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/errors.d.ts
194
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/errors.d.ts
194
195
  /** Every library operation that can fail, as named in the failure value. */
195
196
  type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
196
197
  /**
@@ -237,12 +238,12 @@ declare class PoolOperationError extends Error {
237
238
  });
238
239
  }
239
240
  //#endregion
240
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/hooks.d.ts
241
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/hooks.d.ts
241
242
  interface PoolLogger {
242
243
  warn(message: string, data?: unknown): void;
243
244
  }
244
245
  //#endregion
245
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.d.ts
246
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.d.ts
246
247
  interface LockLoss {
247
248
  readonly reason: 'taken-over' | 'expired' | 'unreadable' | 'renewal-failed' | 'marker-lost';
248
249
  readonly expectedOwnerId: string;
@@ -257,7 +258,7 @@ interface RefreshFileLock {
257
258
  whenLost(): Promise<LockLoss>;
258
259
  hasLost(): boolean;
259
260
  }
260
- declare function acquireRefreshFileLock(options: {
261
+ type RefreshFileLockOptions = {
261
262
  name: string;
262
263
  ttlMs: number;
263
264
  /**
@@ -266,7 +267,6 @@ declare function acquireRefreshFileLock(options: {
266
267
  * be one host's path.
267
268
  */
268
269
  path: string;
269
- now?: () => number;
270
270
  renew?: boolean;
271
271
  renewIntervalMs?: number;
272
272
  /** Notifies a live-owner refusal without awaiting; observer failures are ignored. */
@@ -274,9 +274,11 @@ declare function acquireRefreshFileLock(options: {
274
274
  /** Synchronous, never awaited; throws and returned promise/thenable rejections are isolated. */
275
275
  onRenewalTimer?: (event: 'scheduled' | 'cancelled') => void;
276
276
  onStep?: (step: 'stale-marker-stat' | 'stale-marker-claimed' | 'stale-lock-observed' | 'lock-read-ready' | 'lock-missing' | 'stale-lock-confirmed' | 'stale-lock-removed' | 'stale-lock-recreated' | 'eviction-marker-acquired' | 'renewal-owner-confirmed' | 'renewal-marker-unavailable' | 'renewal-write-fenced' | 'renewal-write-ready' | 'renewal-write-finished' | 'relinquish-read' | 'renewal-finished' | 'release-owner-confirmed') => void | Promise<void>;
277
- }): Promise<RefreshFileLock | null>;
277
+ };
278
+ /** Filesystem leases share wall time across all callers and processes. */
279
+ declare function acquireRefreshFileLock(options: RefreshFileLockOptions): Promise<RefreshFileLock | null>;
278
280
  //#endregion
279
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.d.ts
281
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/refresh-lock.d.ts
280
282
  type LockStep = NonNullable<Parameters<typeof acquireRefreshFileLock>[0]['onStep']> extends ((step: infer S) => unknown) ? S : never;
281
283
  /** Tuning shared by every lock the store takes; each field is overridable. */
282
284
  interface PoolLockOptions {
@@ -297,7 +299,6 @@ type LockEvent = {
297
299
  path: string;
298
300
  };
299
301
  interface LockEnvironment {
300
- now: () => number;
301
302
  onLockEvent?: (event: LockEvent) => void;
302
303
  onLockStep?: (lock: {
303
304
  name: string;
@@ -309,7 +310,7 @@ interface LockEnvironment {
309
310
  }, event: 'scheduled' | 'cancelled') => void;
310
311
  }
311
312
  //#endregion
312
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/mutate.d.ts
313
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/mutate.d.ts
313
314
  /** Named points on the write path, for crash and ownership injection. */
314
315
  type WriteStep = 'before-config-write' | 'after-config-write' | 'before-state-write' | 'after-state-write';
315
316
  /** Awaitable pause points on the pull and refresh paths. */
@@ -344,11 +345,11 @@ interface StoreContext {
344
345
  /** What `initializePool` did. */
345
346
  type InitializeOutcome = 'initialized' | 'already-ready';
346
347
  //#endregion
347
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/runtime.d.ts
348
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/runtime.d.ts
348
349
  /** Where a pull was fired from; `load` fires at most once per process per row. */
349
350
  type PullReason = 'load' | 'add' | 'replace' | 'admission';
350
351
  //#endregion
351
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/attribution.d.ts
352
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/attribution.d.ts
352
353
  /**
353
354
  * What a pull or refresh captured about its row (named by id alongside) when
354
355
  * it was issued. A result applies only while the row with that id still has
@@ -371,7 +372,7 @@ interface Attribution {
371
372
  identity?: string;
372
373
  }
373
374
  //#endregion
374
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/rows.d.ts
375
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/rows.d.ts
375
376
  type FailureHook = (rowId: string, error: PoolOperationError) => void | Promise<void>;
376
377
  interface RowOperationOptions {
377
378
  /** Called once, awaited, on every non-success path, before locks release. */
@@ -587,7 +588,7 @@ interface RowTransitionResult {
587
588
  providerState?: unknown;
588
589
  }
589
590
  //#endregion
590
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/provider-state.d.ts
591
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/provider-state.d.ts
591
592
  /**
592
593
  * Receives a private copy of the row's provider state (undefined when the row
593
594
  * shows none) and the row as loaded under the locks, and returns the next
@@ -623,7 +624,7 @@ declare const DECLINE_TRANSITION: unique symbol;
623
624
  */
624
625
  type RowTransitionMutator = (current: unknown | undefined, row: PoolRow) => unknown | typeof DECLINE_TRANSITION | Promise<unknown | typeof DECLINE_TRANSITION>;
625
626
  //#endregion
626
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/publication.d.ts
627
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/publication.d.ts
627
628
  interface PublishPlan {
628
629
  operationId: string;
629
630
  remove: Array<{
@@ -666,7 +667,7 @@ interface PublishResult {
666
667
  receipt: PublicationReceipt;
667
668
  }
668
669
  //#endregion
669
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/pull.d.ts
670
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/pull.d.ts
670
671
  /** What a pull is issued with: the credential and its attribution tuple. */
671
672
  interface PullRequest {
672
673
  id: string;
@@ -677,7 +678,7 @@ interface PullRequest {
677
678
  }
678
679
  type PullHook = (request: PullRequest) => Promise<unknown>;
679
680
  //#endregion
680
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/refresh.d.ts
681
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/refresh.d.ts
681
682
  /** What the injected provider refresh function returns. */
682
683
  interface ProviderRefreshResult {
683
684
  access: string;
@@ -740,7 +741,7 @@ type RefreshOutcome = {
740
741
  reason: string;
741
742
  };
742
743
  //#endregion
743
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/settings.d.ts
744
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/settings.d.ts
744
745
  /** The plugin's settings: every top-level config key except the pool-owned ones. */
745
746
  type PoolSettings = Record<string, unknown>;
746
747
  type SettingsRead = {
@@ -784,7 +785,7 @@ type UpdateSettingsResult = {
784
785
  outcome: 'updated' | 'unchanged';
785
786
  };
786
787
  //#endregion
787
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/pool.d.ts
788
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/store/pool.d.ts
788
789
  interface OpenPoolStoreOptions {
789
790
  /** The provider every row of this pool belongs to; keys the provider-wide lock. */
790
791
  provider: string;
@@ -817,7 +818,7 @@ interface OpenPoolStoreOptions {
817
818
  requireCredentialStamps?: boolean;
818
819
  /** Require an exact secret fingerprint for every roster-publication removal. */
819
820
  requireRemovedFingerprint?: boolean;
820
- /** Injected clock for leases, refresh stamps and `addedAt`. */
821
+ /** Logical clock for refresh stamps and `addedAt`; filesystem leases always use wall time. */
821
822
  now?: () => number;
822
823
  /**
823
824
  * Ordered store-lock list held across every read-modify-write. Defaults to
@@ -970,6 +971,44 @@ interface PoolStore {
970
971
  pullsSettled(): Promise<void>;
971
972
  }
972
973
  //#endregion
974
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/commands/seam.d.ts
975
+ /** Where a dropped field is reported. Names only, never values. */
976
+ interface SeamLogger {
977
+ warn(message: string, data?: unknown): void;
978
+ }
979
+ //#endregion
980
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/commands/builtins.d.ts
981
+ /**
982
+ * What a plugin's login hands back. `ready` adds the account now. `pending`
983
+ * means the user must finish somewhere else (a browser, a device code):
984
+ * `message` tells them how, and the account is added when `completion`
985
+ * settles, with the result sent to the invocation that started it.
986
+ */
987
+ type LoginOutcome = {
988
+ status: 'ready';
989
+ account: AddInput;
990
+ } | {
991
+ status: 'pending';
992
+ message: string;
993
+ /** Resolves with the account to add, or undefined when the user gave up. */
994
+ completion: Promise<AddInput | undefined>;
995
+ } | {
996
+ status: 'cancelled';
997
+ message?: string;
998
+ };
999
+ interface AccountsSectionOptions {
1000
+ /** What to show as an account's identity; defaults to its recorded identity. */
1001
+ describeIdentity?(row: PoolRow): string | undefined;
1002
+ /** The plugin's login; without it the section offers no add action. */
1003
+ login?: {
1004
+ label?: string;
1005
+ knobs?: MenuKnob[];
1006
+ run(values: KnobValues, invocation: CommandInvocation): Promise<LoginOutcome>;
1007
+ };
1008
+ /** Passed to `store.remove`: a reason refuses removing that id. */
1009
+ protect?: RemoveOptions['protect'];
1010
+ }
1011
+ //#endregion
973
1012
  //#region ../core/dist/paths.d.ts
974
1013
  /**
975
1014
  * The config file and the runtime-state file a store operation reads and writes.
@@ -1058,14 +1097,14 @@ interface BeginAccountLoginResult {
1058
1097
  */
1059
1098
  declare function beginAccountLogin(opts: BeginAccountLoginOptions): Promise<BeginAccountLoginResult>;
1060
1099
  //#endregion
1061
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/insula.d.ts
1100
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/insula.d.ts
1062
1101
  /** Optional transport for custom scoped clients; getUsage must not retry refusals. */
1063
1102
  interface InsulaUsageTransport {
1064
1103
  connectionFile: string;
1065
1104
  getUsage(): Promise<unknown>;
1066
1105
  }
1067
1106
  //#endregion
1068
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/custody.d.ts
1107
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/custody.d.ts
1069
1108
  type ClaustrumScopedClient = Pick<ClaustrumClient, 'listScoped' | 'getScoped' | 'reportAuthFailureScoped' | 'close'> & {
1070
1109
  insula?: InsulaUsageTransport;
1071
1110
  };
@@ -1131,7 +1170,7 @@ interface ClaustrumScopedAttempt {
1131
1170
  readonly expiresAtMs: number | null;
1132
1171
  }
1133
1172
  //#endregion
1134
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.d.ts
1173
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/interlock.d.ts
1135
1174
  /**
1136
1175
  * The declined-account interlock: the user's "do not use this vault account",
1137
1176
  * kept on the consumer side because the vault has no notion of it.
@@ -1150,7 +1189,7 @@ interface DeclinedAccount {
1150
1189
  readonly accountIdentity?: string;
1151
1190
  }
1152
1191
  //#endregion
1153
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/roster.d.ts
1192
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/roster.d.ts
1154
1193
  /**
1155
1194
  * One vault account as the pool sees it. It carries no bearer material: the
1156
1195
  * access token is fetched from the vault for every send. Several vault
@@ -1205,7 +1244,7 @@ interface VaultRosterFile {
1205
1244
  */
1206
1245
  type QuotaReceipt = Pick<ClaustrumScopedAttempt, 'credentialId' | 'accountIdentity' | 'accountIdentitySource' | 'expectedAccountIdentity'>;
1207
1246
  //#endregion
1208
- //#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.1+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.d.ts
1247
+ //#region ../../node_modules/.bun/@cortexkit+common-auth@0.18.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.d.ts
1209
1248
  interface ClaustrumEnrollmentClient {
1210
1249
  enrollPropose(input: {
1211
1250
  name: string;
@@ -1265,6 +1304,8 @@ interface VaultPaths extends ClaustrumEnrollmentPaths {
1265
1304
  /** One vault account as routing sees it. */
1266
1305
  interface VaultRoute {
1267
1306
  id: string;
1307
+ /** The vault credential name, distinct from its stable routing id. */
1308
+ credentialId?: string;
1268
1309
  kind: 'oauth' | 'api-key';
1269
1310
  /** The ChatGPT account it signs in as, when the vault knows it. */
1270
1311
  identity?: string;
@@ -1455,6 +1496,9 @@ declare class OpenAiVault {
1455
1496
  close(): void;
1456
1497
  }
1457
1498
  //#endregion
1499
+ //#region ../core/dist/vault-account-menu.d.ts
1500
+ type MenuVault = Pick<OpenAiVault, 'authority' | 'refresh' | 'status' | 'identities' | 'routes' | 'pollQuota' | 'snapshot'>;
1501
+ //#endregion
1458
1502
  //#region ../core/dist/commands.d.ts
1459
1503
  /**
1460
1504
  * The prompt-cache manager, as the Cache section uses it.
@@ -1496,6 +1540,15 @@ interface ResetTargetIdentity {
1496
1540
  chatgptAccountId?: string;
1497
1541
  onAuthFailure?: (status: number) => Promise<void>;
1498
1542
  }
1543
+ interface AccountRules {
1544
+ /**
1545
+ * The legacy locks a write of row `id` holds besides the store's own: the
1546
+ * locks an older openai-auth process holds while it refreshes that row.
1547
+ * Taken by remove, enable, disable and replace (and by the replace a
1548
+ * re-login becomes).
1549
+ */
1550
+ rowLocks?(id: string): readonly PoolLockSpec[];
1551
+ }
1499
1552
  /** One live process, on an older version, that keeps the accounts from moving to the account pool. */
1500
1553
  interface MigrationBlocker {
1501
1554
  /** `'unknown'` when the directory of process heartbeats could not be read. */
@@ -1508,6 +1561,53 @@ type MenuMigrationState = {
1508
1561
  migrated: false;
1509
1562
  blockers: readonly MigrationBlocker[];
1510
1563
  };
1564
+ /** A started OAuth login, as `beginAccountLogin` returns it. */
1565
+ interface MenuLoginFlow {
1566
+ url: string;
1567
+ instructions: string;
1568
+ completion: Promise<IngestAccount>;
1569
+ }
1570
+ interface MenuLoginDeps {
1571
+ /** Starts a browser login, or a device-code login when `headless`. */
1572
+ begin(options: {
1573
+ label?: string;
1574
+ headless: boolean;
1575
+ }): Promise<MenuLoginFlow>;
1576
+ /** The main account's ChatGPT identity; a login of that account is refused. */
1577
+ mainIdentity?(): Promise<string | undefined>;
1578
+ }
1579
+ interface OpenAiMenuOptions {
1580
+ store: PoolStore;
1581
+ vault?: MenuVault;
1582
+ /** Display the normal actions, but refuse all applies before running one. */
1583
+ readOnly?: boolean;
1584
+ /** A host capability fence, checked before the shared engine runs an action. */
1585
+ allowAction?: (request: CommandApplyRequest) => boolean;
1586
+ /** Keep unsupported host sections in their normal positions without actions. */
1587
+ unavailableSections?: readonly ('cache' | 'diagnostics' | 'reset')[];
1588
+ /**
1589
+ * The legacy locks the menu's writes that name no single row take (the
1590
+ * roster order, settings, a new account).
1591
+ */
1592
+ extraLocks?: readonly PoolLockSpec[];
1593
+ /** The legacy locks a write of one row takes; see `AccountRules`. */
1594
+ rowLocks?: AccountRules['rowLocks'];
1595
+ /** Whether the install is migrated; absent means it always is (Pi). */
1596
+ migration?(): Promise<MenuMigrationState>;
1597
+ login?: MenuLoginDeps;
1598
+ /** Passed to every removal: refuses row `main` and a pending transfer's row. */
1599
+ protect?: RemoveOptions['protect'];
1600
+ describeIdentity?: AccountsSectionOptions['describeIdentity'];
1601
+ /** The plugin's "check quota now"; without it the store pulls each row. */
1602
+ quotaCheck?(ids: readonly string[], invocation: CommandInvocation): Promise<void>;
1603
+ cache?: PluginSection;
1604
+ diagnostics?: PluginSection;
1605
+ extras?: readonly PluginExtraSection[];
1606
+ /** Runs after every successful apply (the host re-reads its rows). */
1607
+ afterApply?(): unknown;
1608
+ logger?: SeamLogger;
1609
+ now?: () => number;
1610
+ }
1511
1611
  //#endregion
1512
1612
  //#region src/core/version-fence.d.ts
1513
1613
  /** One live process that keeps the fence shut. */
@@ -1741,4 +1841,35 @@ interface PoolLifecycleDeps {
1741
1841
  paused?: () => boolean | Promise<boolean>;
1742
1842
  }
1743
1843
  //#endregion
1744
- export { ResetTargetIdentity as a, BeginAccountLoginOptions as c, TokenResponse as d, beginAccountLogin as f, PoolStore as g, AccountPaths as h, MenuMigrationState as i, BeginAccountLoginResult as l, parseJwtClaims as m, HostSlotAdapter as n, OpenAiVault as o, extractAccountIdFromClaims as p, CacheKeepManager as r, OpenAiVaultOptions as s, PoolLifecycleDeps as t, IdTokenClaims as u };
1844
+ //#region src/util/canonical-input.d.ts
1845
+ interface CanonicalInput {
1846
+ texts: string[];
1847
+ snapshots: unknown[];
1848
+ retainable: boolean;
1849
+ }
1850
+ //#endregion
1851
+ //#region src/codex-request.d.ts
1852
+ declare const RESPONSES_LITE_MODELS: ReadonlySet<string>;
1853
+ declare const CODEX_VERSION = "0.159.0";
1854
+ declare const CODEX_USER_AGENT = "codex_exec/0.159.0 (Debian 12.0.0; aarch64) unknown (codex_exec; 0.159.0)";
1855
+ interface CodexSessionMetadata {
1856
+ threadID: string;
1857
+ turnID: string;
1858
+ windowID: string;
1859
+ turnStartedAt?: number;
1860
+ input?: unknown[];
1861
+ canonicalInput?: CanonicalInput;
1862
+ /** Keep the opening effort fixed while later changes travel as input items. */
1863
+ pinnedEffort?: string;
1864
+ effortUpdates?: Array<{
1865
+ anchor: number;
1866
+ fingerprint: string;
1867
+ effort: string;
1868
+ }>;
1869
+ }
1870
+ interface CodexRequestRuntime {
1871
+ now: () => number;
1872
+ uuid: () => string;
1873
+ }
1874
+ //#endregion
1875
+ export { PoolStore as S, TokenResponse as _, RESPONSES_LITE_MODELS as a, parseJwtClaims as b, CacheKeepManager as c, ResetTargetIdentity as d, OpenAiVault as f, IdTokenClaims as g, BeginAccountLoginResult as h, CodexSessionMetadata as i, MenuMigrationState as l, BeginAccountLoginOptions as m, CODEX_VERSION as n, PoolLifecycleDeps as o, OpenAiVaultOptions as p, CodexRequestRuntime as r, HostSlotAdapter as s, CODEX_USER_AGENT as t, OpenAiMenuOptions as u, beginAccountLogin as v, AccountPaths as x, extractAccountIdFromClaims as y };