@cortexkit/opencode-openai-auth 1.0.4 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +7 -7
- package/dist/{index-dryydk6b.js → index-116q849r.js} +2 -2
- package/dist/{index-5dg931q0.js → index-4fnghj9e.js} +1 -1
- package/dist/{index-bgq9d21h.js → index-66asrje2.js} +1 -1
- package/dist/{index-jye6vccc.js → index-826s1yxa.js} +2 -2
- package/dist/index-a69gr76b.js +2 -0
- package/dist/{index-egrty6tz.js → index-fsky1rsh.js} +2 -2
- package/dist/{index-envpbt0k.js → index-fsxbncpw.js} +1 -1
- package/dist/{index-99esnzg0.js → index-h263aftt.js} +8 -8
- package/dist/{index-yeyp8t0k.js → index-nx2qh047.js} +1 -1
- package/dist/{index-45qgkb0m.js → index-pg305s90.js} +1 -1
- package/dist/{index-2hch7e8n.js → index-ssj7m2rd.js} +2 -2
- package/dist/{index-k4eacw7x.js → index-y4gxyxqd.js} +2 -2
- package/dist/{index-9reyazwh.js → index-ydz3hbhc.js} +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{map-CCbSZIhT.d.ts → map-m6f5a_IA.d.ts} +1 -1
- package/dist/{pool-lifecycle-DqKq8Eej.d.ts → pool-lifecycle-C_6YRmsh.d.ts} +21 -21
- package/dist/{port-file-CZ9MIdy2.d.ts → port-file-ZPlxXB4G.d.ts} +1 -1
- package/dist/{protocol-CSIDDBDf.d.ts → protocol-DctqemRI.d.ts} +1 -1
- package/dist/rpc/port-file.d.ts +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +3 -3
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{sidebar-state-BCxFpH68.d.ts → sidebar-state-z_M7Trnd.d.ts} +4 -4
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-vykm9bxh.js → token-bzhkgc29.js} +1 -1
- package/dist/token-util-4a2xxnpg.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +2 -2
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +1 -1
- package/package.json +2 -2
- package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +65 -34
- package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +1 -1
- package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +65 -34
- package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +1 -1
- package/dist/index-yf6arn5w.js +0 -2
- package/dist/token-util-gmn5yaqc.js +0 -1
package/dist/bin.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as
|
|
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
3
|
${G.map((D)=>` - PID ${D.pid}: ${D.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=
|
|
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
|
|
7
7
|
`)?`\r
|
|
8
8
|
`:`
|
|
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)=>
|
|
10
|
-
`,U=
|
|
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
|
|
12
|
-
ck auth grant --principal enrolled:${
|
|
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(
|
|
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}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{S as
|
|
1
|
+
import{re as O}from"./index-66asrje2.js";import{randomUUID as w}from"node:crypto";import{lstat as N,readFile as B,rename as b,unlink as U}from"node:fs/promises";import{dirname as V,resolve as L}from"node:path";var S=process.platform==="win32",W=new Set;function I(j){if(j?.reason==="io-error"){if(j.win32Code===2||j.win32Code===3)return"ENOENT";if(j.win32Code===80||j.win32Code===183)return"EEXIST"}return j?.code??"ERR_PRIVATE_FILE"}var C;function q(){return C??=import("@cortexkit/private-files"),C}class R extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor(j,G,A){let z=A;super(`Private file refused at ${G}: ${j} (${z?.reason??z?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:A});this.path=j,this.stage=G,this.name="PrivateFileError",this.code=I(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function x(j,G,A){try{return await A()}catch(z){if(z instanceof R)throw z;throw new R(j,G,z)}}var E;async function _(j,G){j=L(j),G??=E,await x(j,"safe-parent",async()=>{let A=await(await q()).verifySafeParent(j,G);if(A.ok===!1){if(A.reason==="io-error"||A.reason==="wrong-kind")await N(j);throw new R(A.level??A.path,"safe-parent",{...A,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function T(j,G,A=!1){if(j=L(j),G==="directory")return _(j);await x(j,"verify",async()=>{let z=await q(),K=await z.verifyOwnerOnly(j),H=!1;if(!K.ok){let{reason:M}=K.refusal;if(M==="io-error")await z.verifyPrivatePath(j,G);if(A&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(M))await _(V(j)),await z.securePrivatePath(j,G),H=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:M,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath(j,G),H&&!W.has(j))W.add(j),process.emitWarning(`Private permissions tightened: ${j}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function D(j,G=!1,A){j=L(j),await x(j,"directory",async()=>{let z=await q();try{return await N(j),await _(j,A)}catch(H){if(I(H)!=="ENOENT")throw H}let K=V(j);if(K===j)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await D(K,!1,A);try{await z.createOwnerOnly(j,{kind:"dir"})}catch(H){if(I(H)!=="EEXIST")throw H}await _(j,A)})}async function m(j,G=!1){if(!S)return B(j,"utf8");return(await k(j,G)).toString("utf8")}async function k(j,G=!1){if(!S)return B(j);if(j=L(j),G)await _(V(j)),await T(j,"file",!0);return x(j,"read",async()=>(await q()).readOwnerOnly(j))}async function F(j,G){await _(V(L(j))),await x(j,"create",async()=>{await(await q()).createPrivateFile(L(j),G)})}async function c(j){await _(V(L(j))),await x(j,"directory-create",async()=>{await(await q()).createOwnerOnly(L(j),{kind:"dir"})})}async function g(j,G,A={}){j=L(j),G=L(G);let z=A.now??(()=>performance.now()),K=z(),H=Math.min(K+500,A.deadline??1/0),M=[0,10,20,40,80,100],Y,$=0;for(let Q of M){if(z()>=H)break;if(Q)await(A.sleep??((X)=>new Promise((Z)=>setTimeout(Z,X))))(Math.min(Q,Math.max(0,H-z())));if(z()>=H)break;if(await A.beforeRename?.(),z()>=H)break;$++;try{return await(A.rename??b)(j,G),{attempts:$,elapsedMs:z()-K}}catch(X){Y??=X;let Z=X;if(!(Z.win32Code!==void 0?Z.win32Code===32||Z.win32Code===33:["EBUSY","EPERM","EACCES"].includes(Z.code??"")&&!Z.reason))break}}let J=new R(G,"rename",Y??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw J.attempts=$,J.elapsedMs=z()-K,J}async function v(j,G,A={}){j=L(j),await D(V(j));try{await T(j,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J}let z=L(A.stagePath??`${j}.${w()}.tmp`);if(V(z)!==V(j))throw new R(j,"stage-directory",{code:"EXDEV"});let K=!1,H=!1,M={attempts:0,elapsedMs:0},Y="stage-create",$=(J)=>{try{A.onOutcome?.({path:j,stage:J?.stage??"published",published:H,fileDurable:H,durabilityConfirmed:!1,attempts:J?.attempts??M.attempts,elapsedMs:J?.elapsedMs??M.elapsedMs,...J&&{code:J.code,win32Code:J.win32Code}})}catch{}};try{if(await F(z,G),K=!0,Y="before-rename",M=await g(z,j,A),K=!1,H=!0,Y="published-callback",A.onRenamed?.(),Y="published-verify",await T(j,"file"),A.durable&&A.durability!=="file-only-on-windows")throw new R(j,"directory-sync-unsupported",{code:"ENOTSUP"});$()}catch(J){let Q=J instanceof R?J:new R(j,Y,J);if(Q.published=H,Q.fileDurable=H,H)Object.assign(Q,M);if(K){try{await U(z)}catch{Q.orphanPath=z}K=!1}throw $(Q),Q}finally{if(K)await U(z).catch(()=>{})}}
|
|
2
|
+
export{S as ae,R as be,x as ce,_ as de,T as ee,D as fe,m as ge,F as he,c as ie,g as je,v as ke};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$a as J6,Aa as rX,Ba as d9,Bb as YJ,Ca as a8,Cb as XJ,Da as f6,Db as JJ,Ea as MG,Eb as QJ,Fa as TJ,Fb as M6,Gb as l9,Hb as k8,Ia as sX,Ib as a1,Jb as n8,Ka as c0,Kb as t1,La as z$,Lb as e1,Ma as R9,Mb as YY,Na as t6,Nb as XY,Oa as K$,Ob as JY,Pa as U$,Qa as a0,Qb as jY,Ra as H$,Rb as FY,Sa as xX,Sb as C6,Ta as A0,Tb as xJ,Ua as i9,Ub as vJ,Va as W3,Vb as hJ,Wa as C9,Wb as yJ,Xa as TY,Xb as gJ,Ya as X6,Yb as R6,Za as s9,_a as Q9,_b as h8,ab as Z$,ac as t8,ba as G1,bb as V$,bc as j$,ca as lJ,cb as kJ,cc as U0,da as dJ,db as z3,ea as $3,eb as M8,ec as $J,fa as iJ,fb as s0,fc as vX,ga as nJ,gb as o8,gc as hX,ha as D6,hb as GY,hc as WJ,ia as jJ,ib as B$,ic as F$,ja as Q$,jb as s,jc as i4,ka as kX,kb as A6,kc as D$,la as J9,lb as Q8,lc as s6,ma as $$,mc as v1,na as T8,nc as J1,oa as d4,ob as L$,oc as Q1,pa as W$,pb as RY,pc as O6,qa as uX,qb as N$,qc as fJ,ra as pX,rb as j3,rc as a6,sa as N8,sb as aX,sc as n4,ta as j8,tb as WY,tc as zJ,ua as s8,ub as tX,va as lX,vb as eX,wa as dX,wc as O$,xa as iX,ya as nX,za as oX}from"./index-99esnzg0.js";import{Ac as RJ,Cc as L8,Dc as P$,Gc as q$,Kc as E3,Lc as E$,Mc as M$,Nc as A$,Sc as h1,Tc as y1,Uc as T$,Vc as R$,Yc as C$,Zc as w$,_c as S$,ad as Y1,bd as X1,cd as I$,dd as b$,ed as V6,fd as k$,yc as IY}from"./index-9reyazwh.js";import{nd as e8,pd as F6,td as Y6}from"./index-yf6arn5w.js";import{Bd as a9}from"./index-2hch7e8n.js";import{Gd as UJ,Hd as HJ,Id as ZJ,Jd as r3,Kd as G$,Ld as u9}from"./index-jye6vccc.js";import{Sd as v3,Td as r9,Vd as B0,_d as y6,ae as GJ}from"./index-k4eacw7x.js";import{be as F8,ce as z9,fe as I3,ge as b3,he as yY,ie as k3,le as x3}from"./index-dryydk6b.js";import{ne as VJ,pe as _$}from"./index-45qgkb0m.js";import{re as dY}from"./index-bgq9d21h.js";import{createHash as UB,randomUUID as HB}from"node:crypto";import{mkdirSync as ZB,readFileSync as VB,renameSync as BB,statSync as LB,writeFileSync as NB}from"node:fs";import c4 from"node:os";import{join as jB}from"node:path";import{readFile as FW}from"node:fs/promises";import{readFileSync as o$}from"node:fs";import{homedir as r$,tmpdir as s$}from"node:os";import{join as g9}from"node:path";var a$="https://chatgpt.com/backend-api/codex/responses",t$="openai-auth.json",x8={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function f9(){let Y=process.env[x8.configDir]?.trim();if(Y)return Y;return g9(process.env.XDG_CONFIG_HOME||g9(r$(),".config"),"opencode")}function Y0(){return process.env[x8.configFile]?.trim()||g9(f9(),t$)}function e$(){try{let Y=JSON.parse(o$(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function YW(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function h9(Y,X,J){let Q=YW(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function XW(){let Y=e$(),X;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")X=Y.dump.enabled;else if(typeof Y.dump==="boolean")X=Y.dump}return{webSockets:h9(x8.webSockets,Y.webSockets,!1),rawWebSocket:h9(x8.rawWebSocket,Y.rawWebSocket,!1),responsesLite:h9(x8.responsesLite,Y.responsesLite,!1),dump:h9(x8.dump,X,!1),dumpDir:process.env[x8.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():g9(s$(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[x8.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():a$)}}var y9;function r0(){if(!y9)y9=XW();return y9}function CX(){return y9=void 0,r0()}import{readFileSync as JW}from"node:fs";var QW="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function GW(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function _6(Y,X={}){return D6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:F6,...X})}function QY(Y){try{let X=JSON.parse(JW(Y,"utf8"));if(!X||typeof X!=="object"||Array.isArray(X))return!1;return s6(X).migratedAt!==void 0}catch{return!1}}async function m9(Y,X){if(!QY(Y.configPath))return;let J=await X.read();return J.status==="ready"?J.rows:void 0}function c9(Y,X){if(Y===M8)return QW;if(s6(X.config).pending?.rowId===Y)return GW(Y);return}function $W(Y,X){return O6(Y,M8,X.legacyLocks).filter((J)=>J.name===a6)}function A8(Y,X={}){return $W(Y,X)}var P6="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class r8 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function wX(Y){let X=Y.storage,J=o8(X);if(!X||!J||c0(J))return;let Q=J,G=Y.now(),$=(X.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!T8(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,X)}catch(U){Y.warn?.("pool main row refresh failed",{error:U instanceof Error?U.message:String(U)})}let K=Q.access?.trim();if(!K)return;if(typeof Q.expires!=="number"||Q.expires<=Y.now())return;return{account:Q,token:K}}import{readdir as WW,readFile as zW}from"node:fs/promises";import{homedir as KW}from"node:os";import{join as q6}from"node:path";function IX(){return process.env.XDG_STATE_HOME||q6(KW(),".local","state")}function UW(Y=IX()){return q6(Y,"cortexkit","openai-auth","processes")}function HW(Y=IX()){return q6(Y,"cortexkit","openai-auth","rpc")}function ZW(Y){try{return process.kill(Y,0),!0}catch(X){return X.code==="EPERM"}}function SX(Y){let X=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(Y.trim());if(!X)return;return{core:[Number(X[1]),Number(X[2]),Number(X[3])],pre:X[4]?X[4].split("."):[]}}function VW(Y,X){let J=SX(Y),Q=SX(X);if(!J||!Q)return;for(let G=0;G<3;G++){let $=J.core[G]-Q.core[G];if($!==0)return Math.sign($)}if(J.pre.length===0||Q.pre.length===0)return Math.sign(Q.pre.length-J.pre.length);for(let G=0;G<Math.max(J.pre.length,Q.pre.length);G++){let $=J.pre[G],W=Q.pre[G];if($===void 0)return-1;if(W===void 0)return 1;let K=/^\d+$/.test($),U=/^\d+$/.test(W);if(K&&U){let Z=Number($)-Number(W);if(Z!==0)return Math.sign(Z)}else if(K!==U)return K?-1:1;else if($!==W)return $<W?-1:1}return 0}async function $Y(Y){try{return{ok:!0,names:await WW(Y)}}catch(X){let J=X.code;if(J==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:J,error:`${Y}: ${String(X)}`}}}async function BW(Y,X){let J;try{J=await zW(Y,"utf8")}catch(Q){if(Q.code==="ENOENT")return{kind:"gone"};return{kind:"unreadable"}}try{let Q=JSON.parse(J);if(Q!==null&&typeof Q==="object"&&Q.pid===X&&typeof Q.version==="string")return{kind:"ok",version:Q.version}}catch{}return{kind:"unreadable"}}async function E6(Y){let X=Y.isAlive??ZW,J=Y.selfPid??process.pid,Q=new Map,G=(V)=>{let D=V.pid==="unknown"?`dir:${V.detail}`:V.pid;if(!Q.has(D))Q.set(D,V)},$=(V)=>{try{return X(V)}catch{return!0}},W=(V,D)=>{let E=D.exec(V),P=E?Number(E[1]):Number.NaN;return Number.isSafeInteger(P)&&P>=1?P:void 0},K=UW(Y.stateHome),U=new Set,Z=await $Y(K);if(!Z.ok)G({pid:"unknown",version:"unknown",detail:Z.error});for(let V of Z.ok?Z.names:[]){let D=W(V,/^(\d+)\.json$/);if(D===void 0||D===J)continue;let E=q6(K,V),P=await BW(E,D);if(P.kind==="gone")continue;if(U.add(D),!$(D))continue;if(P.kind==="unreadable"){G({pid:D,version:"unknown",detail:E});continue}let T=VW(P.version,Y.currentVersion);if(T===void 0||T<0)G({pid:D,version:P.version,detail:E})}let B=Y.rpcDir??HW(Y.stateHome),O=await $Y(B);if(!O.ok)G({pid:"unknown",version:"unknown",detail:O.error});for(let V of O.ok?O.names:[]){if(!u9(V))continue;let D=q6(B,V),E=await $Y(D);if(!E.ok){if(E.code==="ENOTDIR")continue;G({pid:"unknown",version:"unknown",detail:E.error});continue}for(let P of E.names){let T=W(P,/^port-(\d+)\.json$/);if(T===void 0||T===J||U.has(T))continue;if($(T))G({pid:T,version:"unknown",detail:q6(D,P)})}}let N=(V)=>V.pid==="unknown"?Number.POSITIVE_INFINITY:V.pid;return Q.size===0?{open:!0}:{open:!1,blockers:[...Q.values()].sort((V,D)=>N(V)-N(D))}}var v8="1.0.4";import{readFile as yX}from"node:fs/promises";function p9(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function gX(Y){let X=await xX(Y.configPath),J=[];try{let G=JSON.parse(await yX(Y.statePath,"utf8"));if(p9(G)){let $=G.accounts;if(p9($))J=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:X?[...X]:[],stateIds:J,orphanStateIds:X?J.filter((G)=>!X.has(G)):[]}}async function LW(Y){try{let X=JSON.parse(await yX(Y.configPath,"utf8"));return p9(X)&&p9(X.claustrum)&&X.claustrum.mode==="claustrum"}catch{return!1}}var bX="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function fX(Y){if(!Y)return;let X=Y.accounts.find((J)=>J.id==="main"&&a0(J));if(X)return X;if(!Y.mainAccountId)return;return Y.accounts.find((J)=>a0(J)&&J.accountId===Y.mainAccountId)}function NW(Y,X){let J=Y.lastRefreshError;return T8(J,Y.refresh,X)&&J!==void 0&&J.nextRetryAt!==void 0&&J.nextRetryAt-J.checkedAt>=kX}function jW(Y){let X=[],J=[],Q=Y.now??Date.now(),G=fX(Y.storage),$=!1;if(c0(Y.auth))X.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${bX}`});else if(s0(Y.auth)){if(!o8(Y.storage))X.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)X.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),$=!0;else if(Y.auth.type!=="oauth")X.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.refresh!==Y.auth.refresh))X.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),$=!0;if($&&G){let U={type:"restore-main-credential"};J.push(U);let Z=X.find((B)=>B.code==="auth-slot-missing"||B.code==="auth-slot-not-oauth"||B.code==="main-refresh-not-in-store");if(Z)Z.repair=U}let W=Y.storage?.accounts??[];if(W.length===0)X.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((U)=>U.enabled!==!1))X.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let U of W){if(!a0(U)||!c0(U))continue;X.push({code:"tombstoned-account",accountId:U.id,message:`Account ${U.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${bX}`})}if(Y.retiredCustodyMode)X.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let U of W){if(!a0(U))continue;if(!NW(U,Q))continue;let Z={type:"clear-refresh-backoff",accountId:U.id};J.push(Z),X.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:Z})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let U={type:"prune-orphan-state-ids",ids:K};J.push(U),X.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:U})}return{findings:X,repairs:J}}function mX(Y){let X=(J)=>{if(J.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(s0(await Y.readAuth()))return;let Q=fX(await Y.loadAccounts(Y.paths));if(!Q)return;await Y.setMainAuth({refresh:Q.refresh,access:Q.access??"",expires:Q.expires??0})}};if(Y.migrated)return;if(J.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${J.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${J.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===J.accountId&&a0($));if(G)G.lastRefreshError=void 0;return Q},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[J,Q,G,$]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),LW(Y.paths)]),W=jW({auth:G.type==="missing"?void 0:G,storage:J,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),K=await D6({provider:"openai",quota:F6,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(K.status==="ready")for(let U of K.rows){if(U.disabledReason!==vX)continue;W.findings.push({code:"slot-transfer-origin-unknown",accountId:U.id,message:`Account ${U.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${hX}`})}return W.findings.map((U)=>{let Z=U.repair?X(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...Z?{repair:Z}:{}}})}}]}var DW=GJ,cX="OpenAI accounts",OW="ChatGPT accounts in the vault",_W="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function PW(){let{redirectUri:Y}=await iX(),X=await pX(),J=uX(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=lX(Y,X,J),G=nX(X,J);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:s8($)}}finally{dX(J)}}}}async function qW(Y){let{deviceData:X,url:J,instructions:Q}=await oX(Y);return{url:J,instructions:Q,method:"auto",async callback(){try{let G=await rX(X,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:s8(G)}}catch{return{type:"failed"}}}}}function KJ({client:Y,getAuth:X,getPaths:J=()=>U0(Y0()),fetchImpl:Q=fetch,packageVersion:G=v8,dependencies:$,onMainSlotWritten:W,vault:K}){let U={authorizeBrowser:$?.authorizeBrowser??PW,authorizeHeadless:$?.authorizeHeadless??(()=>qW(G)),beginAccountLogin:$?.beginAccountLogin??d9,loadAccounts:$?.loadAccounts??A0,mutateAccounts:$?.mutateAccounts??i9,readStoreIds:$?.readStoreIds??gX,openBrowser:$?.openBrowser??DW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??_6,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await E6({currentVersion:G});return j.open?[]:j.blockers.map((S)=>({pid:S.pid,version:S.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},Z=async()=>await X?.().catch(()=>{return})??{type:"missing"},B=async()=>{if(K&&await K.authority()!=="local")return!0;if((await Z()).type!=="missing")return!0;let j=J(),S=U.openAccountPool(j);if((await S.read()).status==="ready")return XJ(S);return((await U.loadAccounts(j))?.accounts.length??0)>0},O=async(j)=>{if(await WJ(J().configPath,async()=>{if(K&&await K.authority()!=="local")return!1;if(s0(await Z()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},N=(j)=>({begin:async({headless:S,signal:h})=>{if(K&&await K.authority()!=="local")throw Error(M6);let M=await U.beginAccountLogin({version:G,headless:S,...h?{signal:h}:{}});return{url:M.url,instructions:M.instructions,completion:M.completion.then(async(y)=>{if(K&&await K.authority()!=="local")throw Error(M6);let n=await j.read(),o=n.status==="ready"?n.rows.find((u)=>u.id===M8)?.identity:void 0;if(y.accountId&&o&&y.accountId===o)throw Error("that account is already the OpenCode main credential");return{id:y.id,credential:{type:"oauth",refresh:y.refresh,...y.access!==void 0?{access:y.access}:{},...y.expires!==void 0?{expires:y.expires}:{}},...y.accountId!==void 0?{identity:y.accountId}:{},...y.label!==void 0?{label:y.label}:{}}})}},openBrowser:(S)=>U.openBrowser(S)}),V=async(j)=>{if(K&&await K.authority()!=="local")throw Error(M6);let S=j.credential;if(S?.type!=="oauth"||!S.access)throw Error("no usable access token for a quota check");let h=await t6({accessToken:S.access,fetchImpl:Q,now:U.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return A6(h,U.now(),!0)},D=(j)=>mX({paths:J(),migrated:j,readAuth:Z,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:O,now:U.now}),E=(j,S)=>({title:cX,store:a1(S,{rowLocks:(h)=>O6(j,h)}),...U.terminal?{terminal:U.terminal}:{},login:N(S),protect:(h,M)=>c9(h,M),extraLocks:A8(j),pollQuota:V,doctor:D(!0),status:async()=>{let h=await K?.status();if(K&&await K.authority()!=="local"&&h)return[WY(K.host,K.name,h.enrollment)];return[`Routing: ${(await U.loadAccounts(j))?.routing?.mode??"main-first"}`,...K?[WY(K.host,K.name,(await K.status()).enrollment)]:[]]},...K?{extraActions:[P(K)]}:{}}),P=(j)=>{let S=j.enrolled();return{id:S?"vault-disconnect":"vault-connect",label:S?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(h)=>{let M=await j.authority();if(S){if(M!=="local")await j.disconnect();h.print("Disconnected from the Claustrum vault.");return}if(M!=="local"){h.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}h.print(`Asking the Claustrum vault to enroll ${j.name}…`);let y,n=await j.waitForApproval({...U.vaultWait,onPending:(o)=>{let V0=o.state==="pending"?o.requestId??o.retryCode??"":o.state;if(V0===y)return;y=V0;for(let u of aX(j.name,o))h.print(u);h.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});h.print(tX(j,n).text)}}},T=async()=>{let j=await U.migrationBlockers();return YJ({title:cX,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...j.length>0?["These processes still hold the move back:",...j.map((S)=>` ${S.pid==="unknown"?"processes that could not be read":`pid ${S.pid}`}: version ${S.version}`)]:[]],actions:[eX({checks:D(!1)})],...U.terminal?{terminal:U.terminal}:{}})},w=async(j)=>{let S=J(),h=U.openAccountPool(S);if(K&&await K.authority()!=="local")return l9(E(S,h),K);if(await m9(S,h)===void 0)return T();let M=E(S,h);return K?l9(M,K):JJ(M)},x=(j)=>async()=>{if(K&&await K.authority()!=="local")throw Error(M6);let S=await j();if(S.method!=="auto")return S;return{...S,callback:async()=>{let h=await S.callback();if(K&&await K.authority()!=="local")return{type:"failed"};return h}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:QJ({hasCredential:B,openMenu:w,login:x(()=>U.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:x(()=>U.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...K?.enrolled()?[{label:OW,type:"oauth",authorize:async()=>({url:"",instructions:_W,method:"auto",callback:async()=>{if(await sX(K.paths,K.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await FW(zJ(),"utf8"));if(!j||typeof j!=="object"||Array.isArray(j)||Object.hasOwn(j,"openai"))return{type:"failed"}}catch(j){if(j.code!=="ENOENT")return{type:"failed"}}return{...$J,type:"success"}}})}]:[]]}var zY={rpcRoot:"openai-auth",directoryPrefix:VJ,registrationSessionId:"process"};function n9(Y,X){UJ(zY,Y,X)}function BJ(Y=0,X){return HJ(zY,Y,X)}function LJ(Y){return ZJ(zY,Y)}var o9=B0("commands");function T6(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function KY(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function EW(Y){let X=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!X)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let J=Number(X[1]),Q=Number(X[2]);if(J>23||Q>23||J===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:J,endHour:Q}}var MW="Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.\n\nBefore enabling sustain with Magic Context, set a non-expiring `cache_ttl` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.";function AW(Y){let X=(J)=>n8(Y.store(),A8(T6(Y)),(Q)=>{let G={...Q.cacheKeep??{}};J(G),Q.cacheKeep=G});return{title:"Cache",build:async()=>{let J=Y.cacheKeepManager;if(!J)return{lines:["Keep-warm unavailable"]};let Q=s9(await Y.loadAccounts(T6(Y))),G=Q?.enabled===!0,$=Q?.subagents===!0,W=J.status(),K=W.window?KY(W.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${W.tracked===0?"no sessions":`${W.tracked} session${W.tracked===1?"":"s"}`}`,`Timer ${W.running?"armed":"idle"} · subagents ${$?"on":"off"} · sustain ${W.sustain?"on":"off"}`,`Window ${K}`,`TTL ${Math.round(W.ttlMs/1000)}s · lead ${Math.round(W.leadMs/1000)}s · idle cap ${Math.round(W.maxIdleWarmMs/60000)}min (subagents ${Math.round(W.maxSubagentIdleMs/60000)}min)`],items:W.targets.map((U)=>({id:U.sessionKey,label:U.sessionKey,group:"Sessions",detail:[U.accountId??"main",`expires in ${Math.ceil((U.cacheExpiresAt-W.generatedAt)/1000)}s`,...U.lastWarmedAt?[`last warm ${Math.ceil((W.generatedAt-U.lastWarmedAt)/1000)}s ago`]:[],...U.backoffUntil&&U.backoffUntil>W.generatedAt?[`backoff ${Math.ceil((U.backoffUntil-W.generatedAt)/1000)}s`]:[]].join(" · ")})),actions:[{id:"enabled",label:G?"Turn keep-warm off":"Turn keep-warm on",knobs:[{kind:"toggle",id:"enabled",label:"Keep-warm",value:!G}],run:async({values:U})=>{let Z=U.enabled===!0;if(await X((B)=>{B.enabled=Z}),Y.setCacheKeepEnabled?.(Z),Z)J.start();else J.stop();return o9.info(Z?"cachekeep enabled":"cachekeep disabled"),Z?`Keep-warm is on. TTL ${Math.round(W.ttlMs/1000)}s, idle cap ${Math.round(W.maxIdleWarmMs/60000)}min.`:"Keep-warm is off."}},{id:"subagents",label:$?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!$}],run:async({values:U})=>{let Z=U.subagents===!0;return await X((B)=>{B.subagents=Z}),Y.setCacheKeepSubagents?.(Z),`Subagent warming is ${Z?"on":"off"}.`}},{id:"sustain",label:W.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!W.sustain}],run:async({values:U})=>{let Z=U.sustain===!0;return await X((B)=>{B.sustain=Z}),Y.setCacheKeepSustain?.(Z),Z?MW:"Main-agent sessions again stop warming at the configured idle cap."}},{id:"window",label:"Set the warm window",description:"Warm only between these local hours, e.g. 9-18 or 22-6. Leave it empty to warm at any hour.",knobs:[{kind:"text",id:"window",label:"Window (HH-HH)",placeholder:"9-18",...W.window?{value:KY(W.window)}:{}}],run:async({values:U})=>{let Z=U.window;if(typeof Z!=="string"||Z.trim()==="")return await X((V)=>{delete V.startHour,delete V.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let B=EW(Z);if(!B.ok)return{ok:!1,text:`Invalid window: ${B.reason}`};let{startHour:O,endHour:N}=B;return await X((V)=>{V.startHour=O,V.endHour=N}),Y.setCacheKeepWindow?.({startHour:O,endHour:N}),`Warming limited to ${KY(B)} local hours.`}}]}}}}var NJ=["error","warn","info","debug","trace"];function TW(Y){return{title:"Diagnostics",build:async()=>{let X=r0(),Q=(await Y.loadAccounts(T6(Y)))?.logging?.level??"info";return{lines:[`Dumps ${X.dump?"on":"off"}`,`Dump directory: ${X.dumpDir}`,`Log level: ${Q}`],actions:[{id:"dump",label:X.dump?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!X.dump}],run:async({values:G})=>{let $=G.enabled===!0;await n8(Y.store(),A8(T6(Y)),(K)=>{K.dump={...K.dump??{},enabled:$}});let W=CX();return o9.info($?"request dump enabled":"request dump disabled"),$?`Request dumps are on, written to ${W.dumpDir}.
|
|
1
|
+
import{$a as J6,$b as t8,Aa as rX,Ab as YJ,Ba as d9,Bb as XJ,Ca as a8,Cb as JJ,Da as f6,Db as QJ,Ea as MG,Eb as M6,Fa as TJ,Fb as l9,Gb as k8,Hb as a1,Ia as sX,Ib as n8,Jb as t1,Ka as c0,Kb as e1,La as z$,Lb as YY,Ma as R9,Mb as XY,Na as t6,Nb as JY,Oa as K$,Pa as U$,Pb as jY,Qa as a0,Qb as FY,Ra as H$,Rb as C6,Sa as xX,Sb as xJ,Ta as A0,Tb as vJ,Ua as i9,Ub as hJ,Va as W3,Vb as yJ,Wa as C9,Wb as gJ,Xa as TY,Xb as R6,Ya as X6,Za as s9,Zb as h8,_a as Q9,ab as Z$,ac as j$,ba as G1,bb as V$,bc as U0,ca as lJ,cb as kJ,da as dJ,db as z3,dc as $J,ea as $3,eb as M8,ec as vX,fa as iJ,fb as s0,fc as hX,ga as nJ,gb as o8,gc as WJ,ha as D6,hb as GY,hc as F$,ia as jJ,ib as B$,ic as i4,ja as Q$,jb as s,jc as D$,ka as kX,kb as A6,kc as s6,la as J9,lb as Q8,lc as v1,ma as $$,mc as J1,na as T8,nc as Q1,oa as d4,ob as L$,oc as O6,pa as W$,pb as RY,pc as fJ,qa as uX,qb as N$,qc as a6,ra as pX,rb as j3,rc as n4,sa as N8,sb as aX,sc as zJ,ta as j8,tb as WY,ua as s8,ub as tX,va as lX,vb as eX,vc as O$,wa as dX,xa as iX,ya as nX,za as oX}from"./index-h263aftt.js";import{$c as Y1,Bc as L8,Cc as P$,Fc as q$,Jc as E3,Kc as E$,Lc as M$,Mc as A$,Rc as h1,Sc as y1,Tc as T$,Uc as R$,Xc as C$,Yc as w$,Zc as S$,ad as X1,bd as I$,cd as b$,dd as V6,ed as k$,xc as IY,zc as RJ}from"./index-ydz3hbhc.js";import{md as e8,od as F6,sd as Y6}from"./index-a69gr76b.js";import{Ad as a9}from"./index-ssj7m2rd.js";import{Fd as UJ,Gd as HJ,Hd as ZJ,Id as r3,Jd as G$,Kd as u9}from"./index-826s1yxa.js";import{$d as GJ,Rd as v3,Sd as r9,Ud as B0,Zd as y6}from"./index-y4gxyxqd.js";import{ae as F8,be as z9,ee as I3,fe as b3,ge as yY,he as k3,ke as x3}from"./index-116q849r.js";import{me as VJ,oe as _$}from"./index-pg305s90.js";import{qe as dY}from"./index-66asrje2.js";import{createHash as UB,randomUUID as HB}from"node:crypto";import{mkdirSync as ZB,readFileSync as VB,renameSync as BB,statSync as LB,writeFileSync as NB}from"node:fs";import c4 from"node:os";import{join as jB}from"node:path";import{readFile as FW}from"node:fs/promises";import{readFileSync as o$}from"node:fs";import{homedir as r$,tmpdir as s$}from"node:os";import{join as g9}from"node:path";var a$="https://chatgpt.com/backend-api/codex/responses",t$="openai-auth.json",x8={webSockets:"CORTEXKIT_OPENAI_AUTH_WEBSOCKETS",rawWebSocket:"CORTEXKIT_OPENAI_AUTH_RAW_WS",responsesLite:"CORTEXKIT_OPENAI_AUTH_RESPONSES_LITE",dump:"CORTEXKIT_OPENAI_AUTH_DUMP",dumpDir:"OPENCODE_OPENAI_AUTH_DUMP_DIR",codexApiEndpoint:"CORTEXKIT_OPENAI_AUTH_CODEX_ENDPOINT",configFile:"OPENCODE_OPENAI_AUTH_FILE",stateFile:"OPENCODE_OPENAI_AUTH_STATE_FILE",configDir:"OPENCODE_CONFIG_DIR"};function f9(){let Y=process.env[x8.configDir]?.trim();if(Y)return Y;return g9(process.env.XDG_CONFIG_HOME||g9(r$(),".config"),"opencode")}function Y0(){return process.env[x8.configFile]?.trim()||g9(f9(),t$)}function e$(){try{let Y=JSON.parse(o$(Y0(),"utf8"));return Y!=null&&typeof Y==="object"&&!Array.isArray(Y)?Y:{}}catch{return{}}}function YW(Y){let X=process.env[Y];if(X===void 0)return;let J=X.trim().toLowerCase();if(J==="1"||J==="true"||J==="yes"||J==="on")return!0;if(J===""||J==="0"||J==="false"||J==="no"||J==="off")return!1;return}function h9(Y,X,J){let Q=YW(Y);if(Q!==void 0)return Q;if(typeof X==="boolean")return X;return J}function XW(){let Y=e$(),X;if(Y.dump!==void 0&&Y.dump!==null){if(typeof Y.dump==="object")X=Y.dump.enabled;else if(typeof Y.dump==="boolean")X=Y.dump}return{webSockets:h9(x8.webSockets,Y.webSockets,!1),rawWebSocket:h9(x8.rawWebSocket,Y.rawWebSocket,!1),responsesLite:h9(x8.responsesLite,Y.responsesLite,!1),dump:h9(x8.dump,X,!1),dumpDir:process.env[x8.dumpDir]?.trim()||(typeof Y.dumpDir==="string"&&Y.dumpDir.trim()?Y.dumpDir.trim():g9(s$(),"opencode-openai-auth-dumps")),codexApiEndpoint:process.env[x8.codexApiEndpoint]?.trim()||(typeof Y.codexApiEndpoint==="string"&&Y.codexApiEndpoint.trim()?Y.codexApiEndpoint.trim():a$)}}var y9;function r0(){if(!y9)y9=XW();return y9}function CX(){return y9=void 0,r0()}import{readFileSync as JW}from"node:fs";var QW="The `main` account holds the login OpenCode signs in with (its login slot only points at it), so it cannot be removed. Sign in with another account through `opencode auth login` to replace it.";function GW(Y){return`The account-pool migration is moving OpenCode's login into \`${Y}\` right now, so it cannot be removed yet. Try again once the migration has finished.`}function _6(Y,X={}){return D6({provider:"openai",configPath:Y.configPath,statePath:Y.statePath,quota:F6,...X})}function QY(Y){try{let X=JSON.parse(JW(Y,"utf8"));if(!X||typeof X!=="object"||Array.isArray(X))return!1;return s6(X).migratedAt!==void 0}catch{return!1}}async function m9(Y,X){if(!QY(Y.configPath))return;let J=await X.read();return J.status==="ready"?J.rows:void 0}function c9(Y,X){if(Y===M8)return QW;if(s6(X.config).pending?.rowId===Y)return GW(Y);return}function $W(Y,X){return O6(Y,M8,X.legacyLocks).filter((J)=>J.name===a6)}function A8(Y,X={}){return $W(Y,X)}var P6="This setup has no OpenAI login in its account store. Sign in for this setup with opencode auth login, or point OPENCODE_OPENAI_AUTH_FILE and OPENCODE_OPENAI_AUTH_STATE_FILE at the store that holds the login.";class r8 extends Error{constructor(){super("The main OpenAI account lives in the account pool");this.name="MainAccountInPoolError"}}async function wX(Y){let X=Y.storage,J=o8(X);if(!X||!J||c0(J))return;let Q=J,G=Y.now(),$=(X.refresh?.refreshBeforeExpiryMinutes??240)*60000;if((!Q.access||!Q.expires||Q.expires-G<=$)&&!T8(Q.lastRefreshError,Q.refresh,G))try{Q=await Y.refreshAccount(Q,X)}catch(U){Y.warn?.("pool main row refresh failed",{error:U instanceof Error?U.message:String(U)})}let K=Q.access?.trim();if(!K)return;if(typeof Q.expires!=="number"||Q.expires<=Y.now())return;return{account:Q,token:K}}import{readdir as WW,readFile as zW}from"node:fs/promises";import{homedir as KW}from"node:os";import{join as q6}from"node:path";function IX(){return process.env.XDG_STATE_HOME||q6(KW(),".local","state")}function UW(Y=IX()){return q6(Y,"cortexkit","openai-auth","processes")}function HW(Y=IX()){return q6(Y,"cortexkit","openai-auth","rpc")}function ZW(Y){try{return process.kill(Y,0),!0}catch(X){return X.code==="EPERM"}}function SX(Y){let X=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(Y.trim());if(!X)return;return{core:[Number(X[1]),Number(X[2]),Number(X[3])],pre:X[4]?X[4].split("."):[]}}function VW(Y,X){let J=SX(Y),Q=SX(X);if(!J||!Q)return;for(let G=0;G<3;G++){let $=J.core[G]-Q.core[G];if($!==0)return Math.sign($)}if(J.pre.length===0||Q.pre.length===0)return Math.sign(Q.pre.length-J.pre.length);for(let G=0;G<Math.max(J.pre.length,Q.pre.length);G++){let $=J.pre[G],W=Q.pre[G];if($===void 0)return-1;if(W===void 0)return 1;let K=/^\d+$/.test($),U=/^\d+$/.test(W);if(K&&U){let Z=Number($)-Number(W);if(Z!==0)return Math.sign(Z)}else if(K!==U)return K?-1:1;else if($!==W)return $<W?-1:1}return 0}async function $Y(Y){try{return{ok:!0,names:await WW(Y)}}catch(X){let J=X.code;if(J==="ENOENT")return{ok:!0,names:[]};return{ok:!1,code:J,error:`${Y}: ${String(X)}`}}}async function BW(Y,X){let J;try{J=await zW(Y,"utf8")}catch(Q){if(Q.code==="ENOENT")return{kind:"gone"};return{kind:"unreadable"}}try{let Q=JSON.parse(J);if(Q!==null&&typeof Q==="object"&&Q.pid===X&&typeof Q.version==="string")return{kind:"ok",version:Q.version}}catch{}return{kind:"unreadable"}}async function E6(Y){let X=Y.isAlive??ZW,J=Y.selfPid??process.pid,Q=new Map,G=(V)=>{let D=V.pid==="unknown"?`dir:${V.detail}`:V.pid;if(!Q.has(D))Q.set(D,V)},$=(V)=>{try{return X(V)}catch{return!0}},W=(V,D)=>{let E=D.exec(V),P=E?Number(E[1]):Number.NaN;return Number.isSafeInteger(P)&&P>=1?P:void 0},K=UW(Y.stateHome),U=new Set,Z=await $Y(K);if(!Z.ok)G({pid:"unknown",version:"unknown",detail:Z.error});for(let V of Z.ok?Z.names:[]){let D=W(V,/^(\d+)\.json$/);if(D===void 0||D===J)continue;let E=q6(K,V),P=await BW(E,D);if(P.kind==="gone")continue;if(U.add(D),!$(D))continue;if(P.kind==="unreadable"){G({pid:D,version:"unknown",detail:E});continue}let T=VW(P.version,Y.currentVersion);if(T===void 0||T<0)G({pid:D,version:P.version,detail:E})}let B=Y.rpcDir??HW(Y.stateHome),O=await $Y(B);if(!O.ok)G({pid:"unknown",version:"unknown",detail:O.error});for(let V of O.ok?O.names:[]){if(!u9(V))continue;let D=q6(B,V),E=await $Y(D);if(!E.ok){if(E.code==="ENOTDIR")continue;G({pid:"unknown",version:"unknown",detail:E.error});continue}for(let P of E.names){let T=W(P,/^port-(\d+)\.json$/);if(T===void 0||T===J||U.has(T))continue;if($(T))G({pid:T,version:"unknown",detail:q6(D,P)})}}let N=(V)=>V.pid==="unknown"?Number.POSITIVE_INFINITY:V.pid;return Q.size===0?{open:!0}:{open:!1,blockers:[...Q.values()].sort((V,D)=>N(V)-N(D))}}var v8="1.0.5";import{readFile as yX}from"node:fs/promises";function p9(Y){return typeof Y==="object"&&Y!==null&&!Array.isArray(Y)}async function gX(Y){let X=await xX(Y.configPath),J=[];try{let G=JSON.parse(await yX(Y.statePath,"utf8"));if(p9(G)){let $=G.accounts;if(p9($))J=Object.keys($)}}catch(G){if(G.code!=="ENOENT")throw G}return{rosterIds:X?[...X]:[],stateIds:J,orphanStateIds:X?J.filter((G)=>!X.has(G)):[]}}async function LW(Y){try{let X=JSON.parse(await yX(Y.configPath,"utf8"));return p9(X)&&p9(X.claustrum)&&X.claustrum.mode==="claustrum"}catch{return!1}}var bX="Connect this host to the Claustrum vault (`opencode auth login` > Connect to the Claustrum vault, or the Vault section of `/openai`) if the vault holds the account, or sign in to the account again.";function fX(Y){if(!Y)return;let X=Y.accounts.find((J)=>J.id==="main"&&a0(J));if(X)return X;if(!Y.mainAccountId)return;return Y.accounts.find((J)=>a0(J)&&J.accountId===Y.mainAccountId)}function NW(Y,X){let J=Y.lastRefreshError;return T8(J,Y.refresh,X)&&J!==void 0&&J.nextRetryAt!==void 0&&J.nextRetryAt-J.checkedAt>=kX}function jW(Y){let X=[],J=[],Q=Y.now??Date.now(),G=fX(Y.storage),$=!1;if(c0(Y.auth))X.push({code:"tombstoned-host-slot",message:`OpenCode's OpenAI slot holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${bX}`});else if(s0(Y.auth)){if(!o8(Y.storage))X.push({code:"main-pool-row-missing",message:"The main account was moved into the account pool, but the pool has no usable `main` row."})}else if(!Y.auth)X.push({code:"auth-slot-missing",message:"OpenCode's OpenAI auth slot is missing."}),$=!0;else if(Y.auth.type!=="oauth")X.push({code:"auth-slot-not-oauth",message:"OpenCode's OpenAI auth slot is not OAuth."}),$=!0;else if(G&&(!Y.auth.refresh||G.refresh!==Y.auth.refresh))X.push({code:"main-refresh-not-in-store",message:"OpenCode's main credential does not match the copy in the account store."}),$=!0;if($&&G){let U={type:"restore-main-credential"};J.push(U);let Z=X.find((B)=>B.code==="auth-slot-missing"||B.code==="auth-slot-not-oauth"||B.code==="main-refresh-not-in-store");if(Z)Z.repair=U}let W=Y.storage?.accounts??[];if(W.length===0)X.push({code:"no-accounts",message:"The account store has no accounts."});else if(!W.some((U)=>U.enabled!==!1))X.push({code:"no-enabled-accounts",message:"The account store has no enabled accounts."});for(let U of W){if(!a0(U)||!c0(U))continue;X.push({code:"tombstoned-account",accountId:U.id,message:`Account ${U.id} holds a tombstone left by the vault custody of an older version, not a credential; it is never sent. ${bX}`})}if(Y.retiredCustodyMode)X.push({code:"retired-custody-mode",message:"The config still selects the vault custody mode of an older version (`claustrum.mode`). It is ignored, and dropped at the next settings write; vault accounts are served once this host is connected to the Claustrum vault."});for(let U of W){if(!a0(U))continue;if(!NW(U,Q))continue;let Z={type:"clear-refresh-backoff",accountId:U.id};J.push(Z),X.push({code:"armed-non-transient-refresh-backoff",accountId:U.id,message:`Account ${U.id} has an armed non-transient refresh backoff.`,repair:Z})}let K=[...Y.orphanStateIds??[]];if(K.length>0){let U={type:"prune-orphan-state-ids",ids:K};J.push(U),X.push({code:"orphan-state-ids",message:`State contains ids absent from the config roster: ${K.join(", ")}.`,repair:U})}return{findings:X,repairs:J}}function mX(Y){let X=(J)=>{if(J.type==="restore-main-credential")return{label:"Copy the stored main credential back into OpenCode's slot",apply:async()=>{if(s0(await Y.readAuth()))return;let Q=fX(await Y.loadAccounts(Y.paths));if(!Q)return;await Y.setMainAuth({refresh:Q.refresh,access:Q.access??"",expires:Q.expires??0})}};if(Y.migrated)return;if(J.type==="prune-orphan-state-ids")return{label:`Drop the state entries of ${J.ids.join(", ")}`,apply:async()=>{await Y.mutateAccounts((Q)=>Q,Y.paths)}};return{label:`Clear the refresh backoff of ${J.accountId}`,apply:async()=>{await Y.mutateAccounts((Q)=>{let G=Q.accounts.find(($)=>$.id===J.accountId&&a0($));if(G)G.lastRefreshError=void 0;return Q},Y.paths)}}};return[{id:"openai-auth",run:async()=>{let[J,Q,G,$]=await Promise.all([Y.loadAccounts(Y.paths),Y.readStoreIds(Y.paths),Y.readAuth(),LW(Y.paths)]),W=jW({auth:G.type==="missing"?void 0:G,storage:J,orphanStateIds:Q.orphanStateIds,retiredCustodyMode:$,now:Y.now()}),K=await D6({provider:"openai",quota:F6,configPath:Y.paths.configPath,statePath:Y.paths.statePath}).read();if(K.status==="ready")for(let U of K.rows){if(U.disabledReason!==vX)continue;W.findings.push({code:"slot-transfer-origin-unknown",accountId:U.id,message:`Account ${U.id} was preserved disabled after an interrupted transfer with an untagged placeholder; sole ownership could not be established. ${hX}`})}return W.findings.map((U)=>{let Z=U.repair?X(U.repair):void 0;return{code:U.code,message:U.message,...U.accountId!==void 0?{accountId:U.accountId}:{},...Z?{repair:Z}:{}}})}}]}var DW=GJ,cX="OpenAI accounts",OW="ChatGPT accounts in the vault",_W="Uses the ChatGPT accounts in the Claustrum vault, with no sign-in. This works only while this host is connected to the vault and OpenCode has no OpenAI login stored; otherwise it fails and changes nothing.";async function PW(){let{redirectUri:Y}=await iX(),X=await pX(),J=uX(crypto.getRandomValues(new Uint8Array(32)).buffer),Q=lX(Y,X,J),G=nX(X,J);return{url:Q,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{try{let $=await G;return{type:"success",refresh:$.refresh_token,access:$.access_token,expires:Date.now()+($.expires_in??3600)*1000,accountId:s8($)}}finally{dX(J)}}}}async function qW(Y){let{deviceData:X,url:J,instructions:Q}=await oX(Y);return{url:J,instructions:Q,method:"auto",async callback(){try{let G=await rX(X,Y);return{type:"success",refresh:G.refresh_token,access:G.access_token,expires:Date.now()+(G.expires_in??3600)*1000,accountId:s8(G)}}catch{return{type:"failed"}}}}}function KJ({client:Y,getAuth:X,getPaths:J=()=>U0(Y0()),fetchImpl:Q=fetch,packageVersion:G=v8,dependencies:$,onMainSlotWritten:W,vault:K}){let U={authorizeBrowser:$?.authorizeBrowser??PW,authorizeHeadless:$?.authorizeHeadless??(()=>qW(G)),beginAccountLogin:$?.beginAccountLogin??d9,loadAccounts:$?.loadAccounts??A0,mutateAccounts:$?.mutateAccounts??i9,readStoreIds:$?.readStoreIds??gX,openBrowser:$?.openBrowser??DW,now:$?.now??Date.now,openAccountPool:$?.openAccountPool??_6,migrationBlockers:$?.migrationBlockers??(async()=>{let j=await E6({currentVersion:G});return j.open?[]:j.blockers.map((S)=>({pid:S.pid,version:S.version}))}),...$?.terminal?{terminal:$.terminal}:{},...$?.vaultWait?{vaultWait:$.vaultWait}:{}},Z=async()=>await X?.().catch(()=>{return})??{type:"missing"},B=async()=>{if(K&&await K.authority()!=="local")return!0;if((await Z()).type!=="missing")return!0;let j=J(),S=U.openAccountPool(j);if((await S.read()).status==="ready")return XJ(S);return((await U.loadAccounts(j))?.accounts.length??0)>0},O=async(j)=>{if(await WJ(J().configPath,async()=>{if(K&&await K.authority()!=="local")return!1;if(s0(await Z()))return!1;return await Y.auth.set({path:{id:"openai"},body:{type:"oauth",...j}}),!0}))await W?.().catch(()=>{})},N=(j)=>({begin:async({headless:S,signal:h})=>{if(K&&await K.authority()!=="local")throw Error(M6);let M=await U.beginAccountLogin({version:G,headless:S,...h?{signal:h}:{}});return{url:M.url,instructions:M.instructions,completion:M.completion.then(async(y)=>{if(K&&await K.authority()!=="local")throw Error(M6);let n=await j.read(),o=n.status==="ready"?n.rows.find((u)=>u.id===M8)?.identity:void 0;if(y.accountId&&o&&y.accountId===o)throw Error("that account is already the OpenCode main credential");return{id:y.id,credential:{type:"oauth",refresh:y.refresh,...y.access!==void 0?{access:y.access}:{},...y.expires!==void 0?{expires:y.expires}:{}},...y.accountId!==void 0?{identity:y.accountId}:{},...y.label!==void 0?{label:y.label}:{}}})}},openBrowser:(S)=>U.openBrowser(S)}),V=async(j)=>{if(K&&await K.authority()!=="local")throw Error(M6);let S=j.credential;if(S?.type!=="oauth"||!S.access)throw Error("no usable access token for a quota check");let h=await t6({accessToken:S.access,fetchImpl:Q,now:U.now,...j.identity?{accountId:j.identity}:{},accountKey:j.id});return A6(h,U.now(),!0)},D=(j)=>mX({paths:J(),migrated:j,readAuth:Z,loadAccounts:U.loadAccounts,readStoreIds:U.readStoreIds,mutateAccounts:U.mutateAccounts,setMainAuth:O,now:U.now}),E=(j,S)=>({title:cX,store:a1(S,{rowLocks:(h)=>O6(j,h)}),...U.terminal?{terminal:U.terminal}:{},login:N(S),protect:(h,M)=>c9(h,M),extraLocks:A8(j),pollQuota:V,doctor:D(!0),status:async()=>{let h=await K?.status();if(K&&await K.authority()!=="local"&&h)return[WY(K.host,K.name,h.enrollment)];return[`Routing: ${(await U.loadAccounts(j))?.routing?.mode??"main-first"}`,...K?[WY(K.host,K.name,(await K.status()).enrollment)]:[]]},...K?{extraActions:[P(K)]}:{}}),P=(j)=>{let S=j.enrolled();return{id:S?"vault-disconnect":"vault-connect",label:S?"Disconnect from the Claustrum vault":"Connect to the Claustrum vault",hint:"serve OpenAI accounts held in the vault",run:async(h)=>{let M=await j.authority();if(S){if(M!=="local")await j.disconnect();h.print("Disconnected from the Claustrum vault.");return}if(M!=="local"){h.print("Nothing was changed: this host is already connected or its enrollment is unreadable. Reopen the menu to disconnect.");return}h.print(`Asking the Claustrum vault to enroll ${j.name}…`);let y,n=await j.waitForApproval({...U.vaultWait,onPending:(o)=>{let V0=o.state==="pending"?o.requestId??o.retryCode??"":o.state;if(V0===y)return;y=V0;for(let u of aX(j.name,o))h.print(u);h.print("Waiting for the approval… (stop with Ctrl-C; Connect picks the request up again)")}});h.print(tX(j,n).text)}}},T=async()=>{let j=await U.migrationBlockers();return YJ({title:cX,status:["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. Account management opens after the move.",...j.length>0?["These processes still hold the move back:",...j.map((S)=>` ${S.pid==="unknown"?"processes that could not be read":`pid ${S.pid}`}: version ${S.version}`)]:[]],actions:[eX({checks:D(!1)})],...U.terminal?{terminal:U.terminal}:{}})},w=async(j)=>{let S=J(),h=U.openAccountPool(S);if(K&&await K.authority()!=="local")return l9(E(S,h),K);if(await m9(S,h)===void 0)return T();let M=E(S,h);return K?l9(M,K):JJ(M)},x=(j)=>async()=>{if(K&&await K.authority()!=="local")throw Error(M6);let S=await j();if(S.method!=="auto")return S;return{...S,callback:async()=>{let h=await S.callback();if(K&&await K.authority()!=="local")return{type:"failed"};return h}}};return[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:QJ({hasCredential:B,openMenu:w,login:x(()=>U.authorizeBrowser())})},{label:"ChatGPT Pro/Plus (headless)",type:"oauth",authorize:x(()=>U.authorizeHeadless())},{label:"Manually enter API Key",type:"api"},...K?.enrolled()?[{label:OW,type:"oauth",authorize:async()=>({url:"",instructions:_W,method:"auto",callback:async()=>{if(await sX(K.paths,K.name)!=="vault")return{type:"failed"};try{let j=JSON.parse(await FW(zJ(),"utf8"));if(!j||typeof j!=="object"||Array.isArray(j)||Object.hasOwn(j,"openai"))return{type:"failed"}}catch(j){if(j.code!=="ENOENT")return{type:"failed"}}return{...$J,type:"success"}}})}]:[]]}var zY={rpcRoot:"openai-auth",directoryPrefix:VJ,registrationSessionId:"process"};function n9(Y,X){UJ(zY,Y,X)}function BJ(Y=0,X){return HJ(zY,Y,X)}function LJ(Y){return ZJ(zY,Y)}var o9=B0("commands");function T6(Y){return{configPath:Y.accountStoragePath,statePath:Y.accountStatePath}}function KY(Y){return`${String(Y.startHour).padStart(2,"0")}-${String(Y.endHour).padStart(2,"0")}`}function EW(Y){let X=/^(\d{1,2})-(\d{1,2})$/.exec(Y.trim());if(!X)return{ok:!1,reason:"expected HH-HH, e.g. 9-18 or 22-6"};let J=Number(X[1]),Q=Number(X[2]);if(J>23||Q>23||J===Q)return{ok:!1,reason:"hours must be integers 0-23 and start ≠ end"};return{ok:!0,startHour:J,endHour:Q}}var MW="Sustain keeps main-agent sessions warming past the idle cap for this process. Clock windows still apply.\n\nBefore enabling sustain with Magic Context, set a non-expiring `cache_ttl` for models used by main sessions; elapsed-time cold-cache assumptions are no longer valid.";function AW(Y){let X=(J)=>n8(Y.store(),A8(T6(Y)),(Q)=>{let G={...Q.cacheKeep??{}};J(G),Q.cacheKeep=G});return{title:"Cache",build:async()=>{let J=Y.cacheKeepManager;if(!J)return{lines:["Keep-warm unavailable"]};let Q=s9(await Y.loadAccounts(T6(Y))),G=Q?.enabled===!0,$=Q?.subagents===!0,W=J.status(),K=W.window?KY(W.window):"always (no window)";return{lines:[`Keep-warm ${G?"on":"off"} · ${W.tracked===0?"no sessions":`${W.tracked} session${W.tracked===1?"":"s"}`}`,`Timer ${W.running?"armed":"idle"} · subagents ${$?"on":"off"} · sustain ${W.sustain?"on":"off"}`,`Window ${K}`,`TTL ${Math.round(W.ttlMs/1000)}s · lead ${Math.round(W.leadMs/1000)}s · idle cap ${Math.round(W.maxIdleWarmMs/60000)}min (subagents ${Math.round(W.maxSubagentIdleMs/60000)}min)`],items:W.targets.map((U)=>({id:U.sessionKey,label:U.sessionKey,group:"Sessions",detail:[U.accountId??"main",`expires in ${Math.ceil((U.cacheExpiresAt-W.generatedAt)/1000)}s`,...U.lastWarmedAt?[`last warm ${Math.ceil((W.generatedAt-U.lastWarmedAt)/1000)}s ago`]:[],...U.backoffUntil&&U.backoffUntil>W.generatedAt?[`backoff ${Math.ceil((U.backoffUntil-W.generatedAt)/1000)}s`]:[]].join(" · ")})),actions:[{id:"enabled",label:G?"Turn keep-warm off":"Turn keep-warm on",knobs:[{kind:"toggle",id:"enabled",label:"Keep-warm",value:!G}],run:async({values:U})=>{let Z=U.enabled===!0;if(await X((B)=>{B.enabled=Z}),Y.setCacheKeepEnabled?.(Z),Z)J.start();else J.stop();return o9.info(Z?"cachekeep enabled":"cachekeep disabled"),Z?`Keep-warm is on. TTL ${Math.round(W.ttlMs/1000)}s, idle cap ${Math.round(W.maxIdleWarmMs/60000)}min.`:"Keep-warm is off."}},{id:"subagents",label:$?"Stop warming subagent sessions":"Warm subagent sessions too",knobs:[{kind:"toggle",id:"subagents",label:"Subagent warming",value:!$}],run:async({values:U})=>{let Z=U.subagents===!0;return await X((B)=>{B.subagents=Z}),Y.setCacheKeepSubagents?.(Z),`Subagent warming is ${Z?"on":"off"}.`}},{id:"sustain",label:W.sustain?"Stop sustaining main sessions":"Sustain main sessions past the idle cap",knobs:[{kind:"toggle",id:"sustain",label:"Sustain",value:!W.sustain}],run:async({values:U})=>{let Z=U.sustain===!0;return await X((B)=>{B.sustain=Z}),Y.setCacheKeepSustain?.(Z),Z?MW:"Main-agent sessions again stop warming at the configured idle cap."}},{id:"window",label:"Set the warm window",description:"Warm only between these local hours, e.g. 9-18 or 22-6. Leave it empty to warm at any hour.",knobs:[{kind:"text",id:"window",label:"Window (HH-HH)",placeholder:"9-18",...W.window?{value:KY(W.window)}:{}}],run:async({values:U})=>{let Z=U.window;if(typeof Z!=="string"||Z.trim()==="")return await X((V)=>{delete V.startHour,delete V.endHour}),Y.setCacheKeepWindow?.(void 0),"Warm window cleared: keep-warm warms at any hour (within idle caps).";let B=EW(Z);if(!B.ok)return{ok:!1,text:`Invalid window: ${B.reason}`};let{startHour:O,endHour:N}=B;return await X((V)=>{V.startHour=O,V.endHour=N}),Y.setCacheKeepWindow?.({startHour:O,endHour:N}),`Warming limited to ${KY(B)} local hours.`}}]}}}}var NJ=["error","warn","info","debug","trace"];function TW(Y){return{title:"Diagnostics",build:async()=>{let X=r0(),Q=(await Y.loadAccounts(T6(Y)))?.logging?.level??"info";return{lines:[`Dumps ${X.dump?"on":"off"}`,`Dump directory: ${X.dumpDir}`,`Log level: ${Q}`],actions:[{id:"dump",label:X.dump?"Turn request dumps off":"Turn request dumps on",knobs:[{kind:"toggle",id:"enabled",label:"Request dumps",value:!X.dump}],run:async({values:G})=>{let $=G.enabled===!0;await n8(Y.store(),A8(T6(Y)),(K)=>{K.dump={...K.dump??{},enabled:$}});let W=CX();return o9.info($?"request dump enabled":"request dump disabled"),$?`Request dumps are on, written to ${W.dumpDir}.
|
|
2
2
|
|
|
3
3
|
Body dumps may contain prompt and session content. Turn this off after debugging.`:"Request dumps are off."}},{id:"logging",label:"Set the log level",knobs:[{kind:"choice",id:"level",label:"Level",choices:NJ.map((G)=>({value:G,label:G})),value:NJ.includes(Q)?Q:"info"}],run:async({values:G})=>{let $=String(G.level);return await n8(Y.store(),A8(T6(Y)),(W)=>{W.logging={...W.logging??{},level:$}}),r9($),o9.info("log level changed",{level:$}),`Log level set to ${$}.`}}]}}}}async function RW(Y){let X=await Y.store().read(),J=X.status==="ready"?X.rows:[];return[...new Set(["main",...J.filter((Q)=>Q.enabled&&Q.type==="oauth").map((Q)=>Q.id)])]}function FJ(Y){let X=T6(Y),J=A8(X),Q=Y.resolveResetTarget&&Y.refreshResetTargetQuota&&Y.fetchImpl&&Y.now&&Y.randomUUID?XY({configPath:X.configPath,statePath:X.statePath,quotaManager:Y.quotaManager,loadAccounts:Y.loadAccounts,mutateAccounts:t1(Y.store(),J),resolveResetTarget:Y.resolveResetTarget,refreshResetTargetQuota:Y.refreshResetTargetQuota,fetchImpl:Y.fetchImpl,now:Y.now,randomUUID:Y.randomUUID,accountKeys:()=>RW(Y)}):void 0,G=Y.beginAccountLogin;return JY({store:Y.store(),...Y.vault?{vault:Y.vault}:{},...Y.now?{now:Y.now}:{},extraLocks:J,rowLocks:($)=>O6(X,$),migration:Y.migration,...G?{login:{begin:($)=>G({...$,version:Y.packageVersion}),mainIdentity:async()=>{let $=await Y.store().read();if($.status!=="ready")return;return $.rows.find((W)=>W.id==="main")?.identity}}}:{},protect:($,W)=>c9($,W),...Y.refreshAllQuota?{quotaCheck:async($)=>{if($.length===1){let U=Y.store();for(let Z of $)await U.requestReading(Z);await U.pullsSettled();return}let K=(await Y.refreshAllQuota?.()??[]).filter((U)=>!U.ok);if(K.length>0)throw new jJ("quota-check-failed",K.map((U)=>U.permanent?`${U.account}: sign-in no longer accepted — remove and add this account again`:`${U.account}: fetch failed — check again to retry`).join(`
|
|
4
4
|
`))}}:{},cache:AW(Y),diagnostics:TW(Y),extras:[...Q?[Q]:[],e1({...Y.getStickyRouting?{getPin:Y.getStickyRouting}:{},...Y.clearStickyRouting?{clearPin:Y.clearStickyRouting}:{}}),...Y.vault?[YY({vault:Y.vault,changed:Y.afterWrite})]:[]],afterApply:async()=>{await Y.afterWrite?.(),await Y.refreshSidebar?.().catch(()=>{})}})}function DJ(Y){return(X,J="info")=>{o9.info("menu notification",{sessionId:Y,kind:J}),n9({command:k8,notify:{message:X,kind:J}},Y)}}function OJ(Y,X){return FJ(Y).open({...X!==void 0?{sessionId:X}:{},notify:DJ(X)})}function _J(Y,X){return FJ(Y).apply(X,{...X.sessionId!==void 0?{sessionId:X.sessionId}:{},notify:DJ(X.sessionId)})}function PJ(Y){let X=[`## ${Y.title}`];for(let J of Y.sections){X.push("",`### ${J.title}`);for(let Q of J.lines)X.push(Q);for(let Q of J.items){let G=Q.detail??Q.status;X.push(`- ${Q.label}${G?`: ${G}`:""}`)}}return X.push("","Open the OpenCode TUI to change these settings."),X.join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{createRequire as n}from"node:module";var k=Object.defineProperty;var q=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports);var l=(b)=>b;function m(b,a){this[b]=l.bind(null,a)}var r=(b,a)=>{for(var c in a)k(b,c,{get:a[c],enumerable:!0,configurable:!0,set:m.bind(a,c)})};var t=n(import.meta.url),o=Symbol.dispose||Symbol.for("Symbol.dispose"),p=Symbol.asyncDispose||Symbol.for("Symbol.asyncDispose"),u=(b,a,c)=>{if(a!=null){if(typeof a!=="object"&&typeof a!=="function")throw TypeError('Object expected to be assigned to "using" declaration');var e;if(c)e=a[p];if(e===void 0)e=a[o];if(typeof e!=="function")throw TypeError("Object not disposable");b.push([c,e,a])}else if(c)b.push([c]);return a},v=(b,a,c)=>{var e=typeof SuppressedError==="function"?SuppressedError:function(d,i,f,g){return g=Error(f),g.name="SuppressedError",g.error=d,g.suppressed=i,g},j=(d)=>a=c?new e(d,a,"An error was suppressed during disposal"):(c=!0,d),h=(d)=>{while(d=b.pop())try{var i=d[1]&&d[1].call(d[2]);if(d[0])return Promise.resolve(i).then(h,(f)=>(j(f),h()))}catch(f){j(f)}if(c)throw a};return h()};
|
|
2
|
-
export{q as
|
|
2
|
+
export{q as pe,r as qe,t as re,u as se,v as te};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
export{d as
|
|
1
|
+
import{Ld as k,Md as _,Nd as R}from"./index-fsky1rsh.js";import{be as h,ge as D}from"./index-116q849r.js";import{me as w}from"./index-pg305s90.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
|
+
export{d as Fd,i as Gd,n as Hd,Bf as Id,Hf as Jd,bf as Kd};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{Td as P,Wd as e}from"./index-y4gxyxqd.js";var V="all",zz=Object.freeze(["primary"]);function y(z){return z.kind==="retired"?z.retiredAt:z.checkedAt}function M(z,H){return JSON.stringify([z,H])}function T(z){return typeof z==="object"&&z!==null&&!Array.isArray(z)}function W(z){return typeof z==="number"&&Number.isFinite(z)}function b(z){return typeof z==="string"&&z.length>0}function I(z,H,J){return z[H]===void 0||J(z[H])}function Hz(z){return W(z)&&z>0}function F(z){return typeof z==="string"}function Jz(z){if(!T(z)||!b(z.scope)||!b(z.label))return!1;switch(z.kind){case"reading":return W(z.checkedAt)&&W(z.usedPercent)&&I(z,"resetsAt",F)&&I(z,"windowMinutes",Hz);case"retired":return W(z.retiredAt);case"absent":return W(z.checkedAt);default:return!1}}function Uz(z){if(!T(z)||!W(z.checkedAt))return!1;if(z.kind==="cleared")return!0;return z.kind==="reading"&&typeof z.reached==="boolean"&&I(z,"remainingPercent",W)&&I(z,"usedPercent",W)&&I(z,"resetsAt",F)&&I(z,"limit",W)&&I(z,"used",W)&&I(z,"remaining",W)&&I(z,"unit",F)}function p(z){return T(z)&&W(z.value)&&Number.isInteger(z.value)&&z.value>=0&&W(z.checkedAt)}function N(z){return T(z)&&Object.values(z).every(p)}function A(z){if(!T(z))return;let H=Object.entries(z).filter(([,J])=>p(J));return H.length===0?void 0:Object.fromEntries(H)}function R(z){if(Q(z))return z;if(!T(z))return;let{counters:H,...J}=z;if(!Q(J))return;let U=A(H);return{...J,...U===void 0?{}:{counters:U}}}function Q(z){if(!T(z)||!Array.isArray(z.limits))return!1;let H=new Set;for(let J of z.limits){if(!Jz(J))return!1;let U=M(J.scope,J.label);if(H.has(U))return!1;H.add(U)}return I(z,"budget",Uz)&&I(z,"counters",N)}var m=900000,d="no quota reading yet",v="no limits reported";function s(z){let H=Math.max(1,Math.round(z/60000));if(H<60)return`${H}m`;let J=Math.round(H/60);if(J<24)return`${J}h`;return`${Math.max(1,Math.round(H/1440))}d`}function Xz(z){if(z%1440===0)return`${z/1440}d`;if(z%60===0)return`${z/60}h`;return`${z}m`}function o(z){if(z.scope!==V||z.windowMinutes===void 0)return z.label;return Xz(z.windowMinutes)}function L(z){return Math.min(100,Math.max(0,z))}function c(z){return`${Math.round(L(z))}% left`}function g(z,H,J){let U=z===void 0?Number.NaN:Date.parse(z);return{...Number.isFinite(U)&&U>J?{resetIn:s(U-J)}:{},resetSinceReading:Number.isFinite(U)&&U>H&&U<=J}}function Yz(z,H){let J=z.windowMinutes,U=H.windowMinutes;if(J!==void 0&&U!==void 0&&J!==U)return J-U;if(J===void 0!==(U===void 0))return J===void 0?1:-1;if(z.scope!==H.scope){if(z.scope===V)return-1;if(H.scope===V)return 1;return z.scope<H.scope?-1:1}return z.label<H.label?-1:z.label>H.label?1:0}function u(z,H){if(!z)return{windows:[]};let{now:J}=H,Z=z.limits.filter((Y)=>Y.kind==="reading"&&Y.remainingPercent!==void 0).sort(Yz).map((Y)=>{let D=L(Y.remainingPercent??0);return{kind:"window",name:o(Y),figure:c(Y.remainingPercent??0),remainingPercent:D,checkedAt:Y.checkedAt,...g(Y.resetsAt,Y.checkedAt,J)}}),X=z.budget;if(X){let Y=X.remainingPercent,D=X.reached?"credits spent":Y!==void 0?`credits ${c(Y)}`:"credits available";Z.push({kind:"budget",name:"credits",figure:D,...Y===void 0?{}:{remainingPercent:L(Y)},checkedAt:X.checkedAt,...g(X.resetsAt,X.checkedAt,J)})}if(Z.length>0){let Y=J-Math.min(...Z.map((D)=>D.checkedAt));if(Y>(H.staleAfterMs??m))return{windows:Z,age:`checked ${s(Y)} ago`}}return{windows:Z}}function n(z,H){let J=u(z,H),U=(H.form??"full")==="full",Z=J.windows.map((X)=>{let Y=U&&X.resetIn?`, resets ${X.resetIn}`:"";return`${X.kind==="budget"?"":`${X.name} `}${X.figure}${Y}`});return J.age===void 0?Z:[...Z,J.age]}function Zz(z,H){let J=n(z,H);if(J.length>0)return J.join(" · ");return z&&z.limits.length>0?v:d}function $z(z){if(z.kind==="retired")return{scope:z.scope,label:z.label,kind:"retired",checkedAt:z.retiredAt};if(z.kind==="absent")return{scope:z.scope,label:z.label,kind:"absent",checkedAt:z.checkedAt};return{scope:z.scope,label:z.label,kind:"reading",checkedAt:z.checkedAt,usedPercent:z.usedPercent,remainingPercent:100-z.usedPercent,...z.windowMinutes===void 0?{}:{windowMinutes:z.windowMinutes},...z.resetsAt===void 0?{}:{resetsAt:z.resetsAt}}}function Gz(z,H){let J=z.windowMinutes!==void 0,U=H.windowMinutes!==void 0;if(J!==U)return J?-1:1;if(J&&U&&z.windowMinutes!==H.windowMinutes)return(H.windowMinutes??0)-(z.windowMinutes??0);if(z.label!==H.label)return z.label<H.label?-1:1;return 0}function Vz(z){return{checkedAt:z.checkedAt,reached:z.reached,...z.remainingPercent===void 0?{}:{remainingPercent:z.remainingPercent},...z.resetsAt===void 0?{}:{resetsAt:z.resetsAt}}}function Wz(z,H=V){let J=new Map;for(let G of z?.limits??[]){if(G.scope!==H&&G.scope!==V)continue;let K=J.get(G.label);if(K===void 0){J.set(G.label,G);continue}let j=G.scope===V?K:G,E=G.scope===V?G:K;J.set(G.label,j.kind==="reading"?j:E)}let U=[...J.values()].map($z).sort(Gz),Z=U.filter((G)=>G.kind==="reading"),X=Z.length>0?Z:U,Y=X.length>0?Math.min(...X.map((G)=>G.checkedAt)):void 0,D=z?.budget?.kind==="reading"?Vz(z.budget):void 0,S=A(z?.counters);return{scope:H,limits:U,...Y===void 0?{}:{checkedAt:Y},...D===void 0?{}:{budget:D},...S===void 0?{}:{counters:S}}}function Dz(z,H){let J=z?.budget;if(J?.reached!==!0||typeof J.resetsAt!=="string")return;let U=Date.parse(J.resetsAt);if(!Number.isFinite(U)||U<=H)return;return{resetsAt:J.resetsAt,resetAtMs:U}}function Iz(z){return z.kind==="reading"&&typeof z.usedPercent==="number"&&Number.isFinite(z.usedPercent)&&z.usedPercent>=100}function xz(z,H){if(typeof z.resetsAt!=="string")return;let J=Date.parse(z.resetsAt);return Number.isFinite(J)&&J>H?J:void 0}class O extends TypeError{constructor(z){super(z);this.name="QuotaCodecError"}}function C(z){return typeof z==="object"&&z!==null&&!Array.isArray(z)}function q(z){return typeof z==="number"&&Number.isFinite(z)}function l(z){return z===void 0||typeof z==="string"&&z!==""}function r(z){return typeof z==="string"&&z!==""}function _(z,H){return z[H]===void 0||q(z[H])}function k(z,H){return z[H]===void 0||typeof z[H]==="string"}function Bz(z){return C(z)&&l(z.scope)&&r(z.label)&&q(z.usedPercent)&&k(z,"resetsAt")&&(z.windowMinutes===void 0||q(z.windowMinutes)&&z.windowMinutes>0)}function Tz(z){return C(z)&&l(z.scope)&&r(z.label)}function Mz(z){if(!C(z))return!1;if(z.kind==="cleared")return!0;return z.kind==="reading"&&typeof z.reached==="boolean"&&_(z,"remainingPercent")&&_(z,"usedPercent")&&k(z,"resetsAt")&&_(z,"limit")&&_(z,"used")&&_(z,"remaining")&&k(z,"unit")}function a(z){if(!C(z)||!q(z.checkedAt))return!1;let H=z.readings??[],J=z.coverage??[];if(!Array.isArray(H)||!Array.isArray(J))return!1;let U=new Set;for(let Z of H){if(!Bz(Z))return!1;let X=M(Z.scope??V,Z.label);if(U.has(X))return!1;U.add(X)}if(!J.every(Tz))return!1;return(z.budget===void 0||Mz(z.budget))&&(z.counters===void 0||N(z.counters))}function Qz(z,H){if(z.scope!==H.scope)return z.scope<H.scope?-1:1;if(z.label!==H.label)return z.label<H.label?-1:1;return 0}function Rz(z,H,J){if(H===void 0)return z;if(z!==void 0&&J<z.checkedAt)return z;return{...H,checkedAt:J}}function _z(z,H){let J=new Map(Object.entries(z??{}));for(let[U,Z]of Object.entries(H??{})){let X=J.get(U);if(X===void 0||Z.checkedAt>=X.checkedAt)J.set(U,Z)}return J.size===0?void 0:Object.fromEntries(J)}function f(z,H){let J=z===void 0?void 0:R(z);if(z!==void 0&&J===void 0)throw new O("stored quota map is malformed");if(!a(H))throw new O("quota observation is malformed");let U=J??{limits:[]},Z=H.checkedAt,X=new Map;for(let $ of U.limits)X.set(M($.scope,$.label),$);let Y=($)=>{let x=X.get($);return x===void 0||Z>=y(x)},D=new Set;for(let $ of H.readings??[]){let x=$.scope??V,B=M(x,$.label);if(D.add(B),!Y(B))continue;X.set(B,{scope:x,label:$.label,kind:"reading",checkedAt:Z,usedPercent:$.usedPercent,...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt},...$.windowMinutes===void 0?{}:{windowMinutes:$.windowMinutes}})}for(let $ of H.coverage??[]){let x=$.scope??V,B=M(x,$.label);if(D.has(B)||!Y(B))continue;let h=X.get(B);X.set(B,h===void 0||h.kind==="absent"?{scope:x,label:$.label,kind:"absent",checkedAt:Z}:{scope:x,label:$.label,kind:"retired",retiredAt:Z})}let{limits:S,budget:G,counters:K,...j}=U,E=Rz(U.budget,H.budget,Z),w=_z(U.counters,H.counters);return{...j,limits:[...X.values()].sort(Qz),...E===void 0?{}:{budget:E},...w===void 0?{}:{counters:w}}}var Kz=Object.freeze({validate:Q,decode:R,merge:f});import{tmpdir as i}from"node:os";import{join as t}from"node:path";var jz=["error","warn","info","debug","trace"];function Ez(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?t(i(),"opencode-openai-auth","opencode-openai-auth.log"):t(i(),"opencode-openai-auth.log"))}function Oz(){let z=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return z&&jz.includes(z)?z:void 0}e({file:Ez,level:Oz});if(process.once("beforeExit",async()=>{try{await P()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>P());
|
|
2
|
+
export{V as jd,zz as kd,R as ld,Q as md,f as nd,Kz as od,o as pd,n as qd,Zz as rd,Wz as sd,Dz as td,Iz as ud,xz as vd};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ae as O,be as U,ee as b,fe as m,ge as L,ke as y}from"./index-116q849r.js";import{createHash as Zz,randomUUID as v}from"node:crypto";import{chmod as t,mkdir as r,open as e,readdir as j,rename as zz,rmdir as Gz,stat as Jz,unlink as S}from"node:fs/promises";import{join as R,resolve as D}from"node:path";function l(z){return typeof z==="number"&&Number.isSafeInteger(z)&&z>0}function F(z){if(!l(z))return!1;try{return process.kill(z,0),!0}catch(J){return J.code==="EPERM"}}function Cz(z){return(J)=>Kz(J,z)}function Kz(z,J){if(/^[0-9a-f]{16}$/.test(z))return!0;return z.startsWith(J)&&/^[0-9a-f]{16}$/.test(z.slice(J.length))}function Nz(z){let J=/^port-(\d+)\.json$/.exec(z);return J?Number(J[1]):void 0}function p(z,J){if(z===null||typeof z!=="object"||Array.isArray(z))return!1;let{pid:V,port:Q,token:K}=z;return l(V)&&Nz(J)===V&&typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=65535&&typeof K==="string"&&K.length>0}async function h(z,J){J?.debug("rpc corrupt port file",{pid:process.pid,portFile:z}),await S(z).catch(()=>{})}async function Az(z,J,V={}){let Q=async()=>{let K=R(z,`port-${J.pid}.json`);if(O)return await m(z,V.secureDir??!1),await V.beforeWrite?.(),await y(K,JSON.stringify({...J,startedAt:Date.now()}),{stagePath:`${K}.${(V.stageName??v)()}.tmp`}),K;if(await r(z,{recursive:!0,mode:V.secureDir?448:void 0}),V.secureDir)await t(z,448);await V.beforeWrite?.();let W={...J,startedAt:Date.now()},Y=`${K}.${(V.stageName??v)()}.tmp`,N,G=!1;try{N=await e(Y,"wx",384),G=!0,await N.writeFile(JSON.stringify(W),"utf8"),await N.chmod(384),await N.close(),N=void 0,await zz(Y,K),G=!1}finally{if(await N?.close().catch(()=>{}),G)await S(Y).catch(()=>{})}return K};try{return await Q()}catch(K){if(K.code==="ENOENT")return await Q();throw K}}async function Oz(z,J,V,Q){let K;try{K=await j(z,{withFileTypes:!0})}catch(Y){if(Y.code==="ENOENT")return;throw Y}let W=D(J);for(let Y of K){if(!Y.isDirectory()||!V(Y.name))continue;let N=R(z,Y.name),G;try{G=await j(N)}catch(X){if(X.code==="ENOENT")continue;throw X}for(let X of G){if(!X.startsWith("port-")||!X.endsWith(".json"))continue;let $=R(N,X),Z;try{Z=await L($)}catch(H){if(H instanceof U&&H.code!=="ENOENT")throw H;continue}if(Z===void 0)continue;let q;try{q=JSON.parse(Z)}catch{await h($,Q);continue}if(!p(q,X)){await h($,Q);continue}if(!F(q.pid))await S($).catch(()=>{})}if(D(N)!==W)await Gz(N).catch(()=>{})}}async function c(z,J){if(!F(J.pid))return null;let V=R(D(z),`port-${J.pid}.json`);try{if(O)await b(V,"file");let Q=await Jz(V);return`${V}:${Q.dev}:${Q.ino}:${Q.mtimeMs}:${Q.size}`}catch(Q){if(Q instanceof U&&Q.code!=="ENOENT")throw Q;return null}}async function a(z,J,V={}){let Q;try{if(O)await b(z,"directory");Q=await j(z)}catch(G){if(G instanceof U&&G.code!=="ENOENT")throw G;return null}let K=[];for(let G of Q){if(!G.startsWith("port-")||!G.endsWith(".json"))continue;try{let X=JSON.parse(await L(R(z,G)));if(p(X,G))if(F(X.pid))K.push(X);else await S(R(z,G)).catch(()=>{})}catch(X){if(X instanceof U&&X.code!=="ENOENT")throw X}}if(K.length===0)return null;let W=J!==void 0&&J>=1?K.filter((G)=>G.pid===J):[];if(V.exactPid===!0&&W.length===0)return null;let Y=W.length>0?W:K,N=(G)=>typeof G.startedAt==="number"&&Number.isFinite(G.startedAt)?G.startedAt:-1/0;return Y.sort((G,X)=>N(X)-N(G))[0]??null}import{open as Qz}from"node:fs/promises";import{connect as Vz}from"node:net";import{join as Wz,resolve as o}from"node:path";var i=2000,A=new Map,T=new Map;async function Xz(z,J){let V=Wz(o(z),`port-${J.pid}.json`);if(O){let K=JSON.parse(await L(V));if(K.pid!==J.pid||K.port!==J.port||K.token!==J.token)return null;return null}let Q;try{Q=await Qz(V,"r");let K=await Q.stat(),W=JSON.parse(await Q.readFile("utf8"));if(W.pid!==J.pid||W.port!==J.port||W.token!==J.token)return null;return`${V}:${K.dev}:${K.ino}:${K.mtimeMs}:${K.size}`}catch{return null}finally{await Q?.close().catch(()=>{})}}async function s(z,J,V,Q){let K=A.get(z);if(!O&&K&&await c(J,K.entry)===K.identity)return K;A.delete(z);let W=T.get(z);if(W)return W;let Y=(async()=>{let N=await(Q.discover??a)(J,V,Q);if(!N)return null;let G=await Xz(J,N);if(!G)return{entry:N,identity:""};let X={entry:N,identity:G};return A.set(z,X),X})();T.set(z,Y);try{return await Y}finally{if(T.get(z)===Y)T.delete(z)}}async function d(z,J,V,Q=i){return new Promise((K)=>{let W,Y=!1,N=!1,G=($,Z=!1)=>{if(Y)return;Y=!0,clearTimeout(X),W?.destroy(),K({value:$,stale:Z})},X=setTimeout(()=>G(null),Q);try{let $=JSON.stringify(V);W=Vz({host:"127.0.0.1",port:z.port}),W.on("connect",()=>{N=!0,W?.write(`POST /rpc/${J} HTTP/1.0\r
|
|
2
2
|
Host: 127.0.0.1:${z.port}\r
|
|
3
3
|
Connection: close\r
|
|
4
4
|
Content-Type: application/json\r
|
|
@@ -9,4 +9,4 @@ Authorization: Bearer ${z.token}\r
|
|
|
9
9
|
\r
|
|
10
10
|
`);if(B>=0)C=B+4;if((C??_.length)>16384)return G(null);if(C!==void 0){let x=_.subarray(0,B).toString("latin1").split(`\r
|
|
11
11
|
`),f=/^HTTP\/1\.[01] (\d{3})(?: |$)/.exec(x[0]??"");if(!f)return G(null);let w=Number(f[1]);if(w<200||w>=300)return G(null,[401,403,404,410].includes(w));for(let M of x.slice(1)){let k=M.indexOf(":"),u=M.slice(0,k).toLowerCase(),P=M.slice(k+1).trim();if(u==="transfer-encoding")return G(null);if(u==="content-length"){if(H!==void 0||!/^\d+$/.test(P))return G(null);if(H=Number(P),!Number.isSafeInteger(H)||H>8388608)return G(null)}}_=Buffer.alloc(0)}}let I=q-(C??q);if(I>8388608)return G(null);if(H!==void 0){if(I>H)return G(null);if(I===H)g()}}),W.on("end",()=>{if(H!==void 0&&q-(C??0)!==H)return G(null);g()}),W.on("error",()=>G(null,!N)),W.on("close",()=>G(null))}catch{G(null,!N)}})}async function n(z,J,V,Q,K,W,Y=i){let N=JSON.stringify([o(z),J??null,V.exactPid===!0]),G=await s(N,z,J,V);if(Q(G?.entry??null),!G)return null;let X=Date.now()+Y,$=await d(G.entry,K,W,Y);if(!$.stale)return $.value;if(A.get(N)===G)A.delete(N);let Z=await s(N,z,J,V);if(!Z||Date.now()>=X)return null;if(Z.entry.port===G.entry.port&&Z.entry.pid===G.entry.pid&&Z.entry.token===G.entry.token){if(A.get(N)===Z)A.delete(N);return null}let q=await d(Z.entry,K,W,X-Date.now());if(q.stale&&A.get(N)===Z)A.delete(N);return q.value}function Tz(z,J,V,Q={}){let K={exactPid:Q.exactPid,discover:Q.discover},W=!1,Y=(N)=>{if(W)return;V?.(N),W=!0};return{async pending(N,G,X){return(await n(z,J,K,Y,"pending-notifications",{lastReceivedId:N,sessionId:G},X))?.messages??[]},async apply(N,G){return await n(z,J,K,Y,"apply",{...N},G)??{text:"apply failed",knobs:{}}}}}
|
|
12
|
-
export{Cz as
|
|
12
|
+
export{Cz as Ld,Az as Md,Oz as Nd,a as Od,i as Pd,Tz as Qd};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{sc as X,uc as V}from"./index-h263aftt.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
|
|
2
2
|
`,{mode:W??384}),await $(B,W??384),await L(B,b)}catch(Y){throw await T(B,{force:!0}).catch(()=>{}),Y}return z.set(q,R(j.body)),!0},async all(){let j=await Q(b);if(!j||Object.keys(j).length===0)return{[x]:!0};return j}}}
|
|
3
3
|
export{_ as c};
|