@cortexkit/opencode-openai-auth 1.0.3 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -60
- package/dist/bin.js +13 -0
- package/dist/index-2hch7e8n.js +8 -0
- package/dist/{index-766sfrh5.js → index-45qgkb0m.js} +1 -1
- package/dist/index-5dg931q0.js +65 -0
- package/dist/index-99esnzg0.js +157 -0
- package/dist/index-9reyazwh.js +2 -0
- package/dist/index-bgq9d21h.js +2 -0
- package/dist/index-dryydk6b.js +2 -0
- package/dist/index-egrty6tz.js +12 -0
- package/dist/index-envpbt0k.js +3 -0
- package/dist/index-jye6vccc.js +2 -0
- package/dist/index-k4eacw7x.js +2 -0
- package/dist/{index-hy9030jh.js → index-yeyp8t0k.js} +1 -1
- package/dist/index-yf6arn5w.js +2 -0
- package/dist/index.d.ts +2 -56
- package/dist/index.js +1 -1
- package/dist/map-CCbSZIhT.d.ts +56 -0
- package/dist/{pool-lifecycle-YLz2B8A5.d.ts → pool-lifecycle-DqKq8Eej.d.ts} +99 -789
- package/dist/{port-file-Do3lQIEk.d.ts → port-file-CZ9MIdy2.d.ts} +1 -1
- package/dist/{protocol-BOBdkqqm.d.ts → protocol-CSIDDBDf.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-D6cUKgkm.d.ts → sidebar-state-BCxFpH68.d.ts} +5 -3
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-gmn5yaqc.js +1 -0
- package/dist/{token-ypk61xj0.js → token-vykm9bxh.js} +1 -1
- package/dist/tui-preferences.d.ts +2 -1
- package/dist/tui-preferences.js +3 -3
- package/dist/tui.d.ts +2 -2
- package/dist/v2/server.d.ts +1 -1
- package/dist/v2/server.js +3 -4
- package/package.json +13 -8
- package/src/tui-compiled/raw/logger.js +10 -2
- package/src/tui-compiled/raw/shared/053cc17b5419261e-codec.js +2 -1
- package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +26 -10
- package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +302 -0
- package/src/tui-compiled/raw/shared/39c3cb05738fcf6d-projection.js +3 -1
- package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +5 -0
- package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +2 -2
- package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +4 -0
- package/src/tui-compiled/raw/shared/4f36d333d081d040-merge.js +21 -5
- package/src/tui-compiled/raw/shared/7211cfec06a298bc-atomic-write.js +21 -0
- package/src/tui-compiled/raw/shared/905bffc0220f43d0-map.js +36 -1
- package/src/tui-compiled/raw/shared/a09b6a533c11858f-tui-preferences.js +6 -4
- package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +30 -8
- package/src/tui-compiled/raw/shared/c64d7afbc14ca125-sidebar-file.js +17 -8
- package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +3 -0
- package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +3 -2
- package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +1 -1
- package/src/tui-compiled/raw/shared/d7dcba96fea1685c-engine.js +126 -11
- package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +254 -37
- package/src/tui-compiled/raw/shared/ec971142548df90e-index.js +1 -0
- package/src/tui-compiled/raw/shared/fbcdcd0f925e74c0-rpc-client.js +15 -1
- package/src/tui-compiled/runtime/logger.js +10 -2
- package/src/tui-compiled/runtime/shared/053cc17b5419261e-codec.js +2 -1
- package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +26 -10
- package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +302 -0
- package/src/tui-compiled/runtime/shared/39c3cb05738fcf6d-projection.js +3 -1
- package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +5 -0
- package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +2 -2
- package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +4 -0
- package/src/tui-compiled/runtime/shared/4f36d333d081d040-merge.js +21 -5
- package/src/tui-compiled/runtime/shared/7211cfec06a298bc-atomic-write.js +21 -0
- package/src/tui-compiled/runtime/shared/905bffc0220f43d0-map.js +36 -1
- package/src/tui-compiled/runtime/shared/a09b6a533c11858f-tui-preferences.js +6 -4
- package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +30 -8
- package/src/tui-compiled/runtime/shared/c64d7afbc14ca125-sidebar-file.js +17 -8
- package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +3 -0
- package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +3 -2
- package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +1 -1
- package/src/tui-compiled/runtime/shared/d7dcba96fea1685c-engine.js +126 -11
- package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +254 -37
- package/src/tui-compiled/runtime/shared/ec971142548df90e-index.js +1 -0
- package/src/tui-compiled/runtime/shared/fbcdcd0f925e74c0-rpc-client.js +15 -1
- package/dist/index-8kj7sa1p.js +0 -12
- package/dist/index-b3q3j39x.js +0 -2
- package/dist/index-bmd7x5aq.js +0 -2
- package/dist/index-ff1jy44a.js +0 -222
- package/dist/index-jyr8y8k4.js +0 -7
- package/dist/index-rv08jmd4.js +0 -2
- package/dist/index-sjx8t1nr.js +0 -2
- package/dist/token-util-wdza526f.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/rpc/port-file.d.ts
|
|
2
2
|
interface PortFileEntry {
|
|
3
3
|
port: number;
|
|
4
4
|
token: string;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/commands/model.d.ts
|
|
2
2
|
/** The section slots, in the one order every renderer shows them. */
|
|
3
3
|
declare const SECTION_SLOTS: readonly ['accounts', 'quota', 'routing', 'limits', 'cache', 'diagnostics', 'extra'];
|
|
4
4
|
type SectionSlot = (typeof SECTION_SLOTS)[number];
|
package/dist/rpc/port-file.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as discoverPortFile, r as writePortFile, t as PortFileEntry } from "../port-file-
|
|
1
|
+
import { n as discoverPortFile, r as writePortFile, t as PortFileEntry } from "../port-file-CZ9MIdy2.js";
|
|
2
2
|
//#region src/rpc/port-file.d.ts
|
|
3
3
|
export declare const isOpenaiRpcStateDir: (name: string) => boolean;
|
|
4
4
|
//#endregion
|
package/dist/rpc/port-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ld as c}from"../index-jye6vccc.js";import{Nd as a,Pd as b}from"../index-egrty6tz.js";import"../index-dryydk6b.js";import"../index-45qgkb0m.js";import"../index-bgq9d21h.js";export{a as writePortFile,c as isOpenaiRpcStateDir,b as discoverPortFile};
|
package/dist/rpc/protocol.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as RpcNotification, i as OpenDialogPayload, n as ApplyResult, o as isNotifyPayload, r as NotifyPayload, t as ApplyRequest } from "../protocol-
|
|
1
|
+
import { a as RpcNotification, i as OpenDialogPayload, n as ApplyResult, o as isNotifyPayload, r as NotifyPayload, t as ApplyRequest } from "../protocol-CSIDDBDf.js";
|
|
2
2
|
export { type ApplyRequest, type ApplyResult, type NotifyPayload, type OpenDialogPayload, type RpcNotification, isNotifyPayload };
|
package/dist/rpc/protocol.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{$d as b}from"../index-k4eacw7x.js";import"../index-dryydk6b.js";import"../index-bgq9d21h.js";export{b as isNotifyPayload};
|
package/dist/rpc/rpc-client.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { a as RpcNotification, n as ApplyResult, t as ApplyRequest } from "../protocol-
|
|
2
|
-
import { t as PortFileEntry } from "../port-file-
|
|
3
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
1
|
+
import { a as RpcNotification, n as ApplyResult, t as ApplyRequest } from "../protocol-CSIDDBDf.js";
|
|
2
|
+
import { t as PortFileEntry } from "../port-file-CZ9MIdy2.js";
|
|
3
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/rpc/rpc-client.d.ts
|
|
4
4
|
export declare const DEFAULT_RPC_TIMEOUT_MS = 2000;
|
|
5
5
|
//#endregion
|
|
6
6
|
//#region src/rpc/rpc-client.d.ts
|
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Qd as F,Rd as f}from"../index-egrty6tz.js";import"../index-dryydk6b.js";import"../index-bgq9d21h.js";function y(r,s,v){return f(r,s,v)}export{y as createRpcClient,F as DEFAULT_RPC_TIMEOUT_MS};
|
package/dist/rpc/rpc-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{me as a,ne as b,oe as c,pe as d}from"../index-45qgkb0m.js";import"../index-bgq9d21h.js";export{a as tmpdir,d as resolveRpcDir,c as getRpcDir,b as RPC_DIRECTORY_PREFIX};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import { t as QuotaCounter } from "./map-CCbSZIhT.js";
|
|
2
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/logger/engine.d.ts
|
|
2
3
|
interface ChannelLogger {
|
|
3
4
|
error(message: string, data?: unknown): void;
|
|
4
5
|
warn(message: string, data?: unknown): void;
|
|
@@ -8,7 +9,7 @@ interface ChannelLogger {
|
|
|
8
9
|
}
|
|
9
10
|
declare function createLogger(channel: string): ChannelLogger;
|
|
10
11
|
//#endregion
|
|
11
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
12
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/quota/projection.d.ts
|
|
12
13
|
interface ProjectedLimit {
|
|
13
14
|
scope: string;
|
|
14
15
|
label: string;
|
|
@@ -40,9 +41,10 @@ interface ProjectedQuota {
|
|
|
40
41
|
checkedAt?: number;
|
|
41
42
|
/** Present only when the stored budget is a reading, not cleared. */
|
|
42
43
|
budget?: ProjectedBudget;
|
|
44
|
+
counters?: Record<string, QuotaCounter>;
|
|
43
45
|
}
|
|
44
46
|
//#endregion
|
|
45
|
-
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.
|
|
47
|
+
//#region ../../node_modules/.bun/@cortexkit+common-auth@0.17.0+0d2d5e37d881ac14/node_modules/@cortexkit/common-auth/dist/sidebar-file/sidebar-file.d.ts
|
|
46
48
|
interface SidebarFileHooks {
|
|
47
49
|
/** Runs on the first merge attempt, before checking for older, unlocked writers. */
|
|
48
50
|
beforeRecheck?: () => void | Promise<void>;
|
package/dist/sidebar-state.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as resolveSessionSidebarRouting, A as clearSidebarStickyAssignment, B as getSidebarStateFile, C as StickyAssignment, D as StickyPinOverlay, E as StickyAssignmentPlan, F as exhaustedQuotaResetAt, G as persistSidebarStickyAssignment, H as isQuotaExhausted, I as formatWindowLabel, J as pruneActiveRouting, K as planSidebarStickyAssignment, L as getCollapsedQuotaSummary, M as createSidebarBookkeepingQueue, N as createSidebarStateCache, O as StickyPinOverlayEntry, P as drainSidebarWrites, Q as resolveActiveAccount, R as getPresentQuotaWindows, S as SpendControlReading, T as StickyAssignmentMap, U as isUsableRoutingEntry, V as hashSidebarSessionId, W as normalizeSidebarState, X as rememberStickyPin, Y as pruneStickyAssignments, Z as removeSidebarActiveRouting, _ as SidebarMachineState, a as ActiveRoutingMap, at as setSidebarState, b as SidebarState, c as PresentQuotaWindow, ct as spendControlExhaustedResetAt, d as QuotaWindowKey, et as resolveSessionStickyAccount, f as ResolveStickyAssignmentInput, g as SidebarBookkeepingQueue, h as SidebarAccountState, i as ActiveRoutingEntry, it as setSidebarMachineState, j as computeQuotaPacing, k as applyStickyPinOverlay, l as QuotaPacing, lt as upsertSidebarActiveRouting, m as STICKY_ASSIGNMENT_MAX_ENTRIES, n as ACTIVE_ROUTING_MAX_ENTRIES, nt as setLegacySidebarStateFileForTest, o as DEFAULT_SIDEBAR_STATE, ot as settleWithinBudget, p as STICKY_ASSIGNMENT_MAX_AGE_MS, q as planSidebarStickyAssignmentFromSnapshot, r as AccountQuota, rt as setSidebarLegacyRouting, s as HOT_PATH_READ_BUDGET_MS, st as sidebarQuotaProjection, t as ACTIVE_ROUTING_MAX_AGE_MS, tt as resolveSidebarStickyAssignment, u as QuotaWindow, v as SidebarRoutingAccount, w as StickyAssignmentChoice, x as SidebarStateCache, y as SidebarSnapshot, z as getSidebarState } from "./sidebar-state-
|
|
1
|
+
import { $ as resolveSessionSidebarRouting, A as clearSidebarStickyAssignment, B as getSidebarStateFile, C as StickyAssignment, D as StickyPinOverlay, E as StickyAssignmentPlan, F as exhaustedQuotaResetAt, G as persistSidebarStickyAssignment, H as isQuotaExhausted, I as formatWindowLabel, J as pruneActiveRouting, K as planSidebarStickyAssignment, L as getCollapsedQuotaSummary, M as createSidebarBookkeepingQueue, N as createSidebarStateCache, O as StickyPinOverlayEntry, P as drainSidebarWrites, Q as resolveActiveAccount, R as getPresentQuotaWindows, S as SpendControlReading, T as StickyAssignmentMap, U as isUsableRoutingEntry, V as hashSidebarSessionId, W as normalizeSidebarState, X as rememberStickyPin, Y as pruneStickyAssignments, Z as removeSidebarActiveRouting, _ as SidebarMachineState, a as ActiveRoutingMap, at as setSidebarState, b as SidebarState, c as PresentQuotaWindow, ct as spendControlExhaustedResetAt, d as QuotaWindowKey, et as resolveSessionStickyAccount, f as ResolveStickyAssignmentInput, g as SidebarBookkeepingQueue, h as SidebarAccountState, i as ActiveRoutingEntry, it as setSidebarMachineState, j as computeQuotaPacing, k as applyStickyPinOverlay, l as QuotaPacing, lt as upsertSidebarActiveRouting, m as STICKY_ASSIGNMENT_MAX_ENTRIES, n as ACTIVE_ROUTING_MAX_ENTRIES, nt as setLegacySidebarStateFileForTest, o as DEFAULT_SIDEBAR_STATE, ot as settleWithinBudget, p as STICKY_ASSIGNMENT_MAX_AGE_MS, q as planSidebarStickyAssignmentFromSnapshot, r as AccountQuota, rt as setSidebarLegacyRouting, s as HOT_PATH_READ_BUDGET_MS, st as sidebarQuotaProjection, t as ACTIVE_ROUTING_MAX_AGE_MS, tt as resolveSidebarStickyAssignment, u as QuotaWindow, v as SidebarRoutingAccount, w as StickyAssignmentChoice, x as SidebarStateCache, y as SidebarSnapshot, z as getSidebarState } from "./sidebar-state-BCxFpH68.js";
|
|
2
2
|
export { ACTIVE_ROUTING_MAX_AGE_MS, ACTIVE_ROUTING_MAX_ENTRIES, AccountQuota, ActiveRoutingEntry, ActiveRoutingMap, DEFAULT_SIDEBAR_STATE, HOT_PATH_READ_BUDGET_MS, PresentQuotaWindow, QuotaPacing, QuotaWindow, QuotaWindowKey, ResolveStickyAssignmentInput, STICKY_ASSIGNMENT_MAX_AGE_MS, STICKY_ASSIGNMENT_MAX_ENTRIES, SidebarAccountState, SidebarBookkeepingQueue, SidebarMachineState, SidebarRoutingAccount, SidebarSnapshot, SidebarState, SidebarStateCache, SpendControlReading, StickyAssignment, StickyAssignmentChoice, StickyAssignmentMap, StickyAssignmentPlan, StickyPinOverlay, StickyPinOverlayEntry, applyStickyPinOverlay, clearSidebarStickyAssignment, computeQuotaPacing, createSidebarBookkeepingQueue, createSidebarStateCache, drainSidebarWrites, exhaustedQuotaResetAt, formatWindowLabel, getCollapsedQuotaSummary, getPresentQuotaWindows, getSidebarState, getSidebarStateFile, hashSidebarSessionId, isQuotaExhausted, isUsableRoutingEntry, normalizeSidebarState, persistSidebarStickyAssignment, planSidebarStickyAssignment, planSidebarStickyAssignmentFromSnapshot, pruneActiveRouting, pruneStickyAssignments, rememberStickyPin, removeSidebarActiveRouting, resolveActiveAccount, resolveSessionSidebarRouting, resolveSessionStickyAccount, resolveSidebarStickyAssignment, setLegacySidebarStateFileForTest, setSidebarLegacyRouting, setSidebarMachineState, setSidebarState, settleWithinBudget, sidebarQuotaProjection, spendControlExhaustedResetAt, upsertSidebarActiveRouting };
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$
|
|
1
|
+
import{$c as E,Ac as d,Bc as e,Cc as f,Dc as g,Ec as h,Fc as i,Gc as j,Hc as k,Ic as l,Jc as m,Kc as n,Lc as o,Mc as p,Nc as q,Oc as r,Pc as s,Qc as t,Rc as u,Sc as v,Tc as w,Uc as x,Vc as y,Wc as z,Xc as A,Yc as B,Zc as C,_c as D,ad as F,bd as G,cd as H,dd as I,ed as J,fd as K,gd as L,hd as M,id as N,jd as O,xc as a,yc as b,zc as c}from"./index-9reyazwh.js";import"./index-yf6arn5w.js";import"./index-2hch7e8n.js";import"./index-k4eacw7x.js";import"./index-dryydk6b.js";import"./index-bgq9d21h.js";export{w as upsertSidebarActiveRouting,n as spendControlExhaustedResetAt,M as sidebarQuotaProjection,G as settleWithinBudget,u as setSidebarState,v as setSidebarMachineState,x as setSidebarLegacyRouting,c as setLegacySidebarStateFileForTest,A as resolveSidebarStickyAssignment,q as resolveSessionStickyAccount,r as resolveSessionSidebarRouting,L as resolveActiveAccount,y as removeSidebarActiveRouting,I as rememberStickyPin,t as pruneStickyAssignments,s as pruneActiveRouting,B as planSidebarStickyAssignmentFromSnapshot,z as planSidebarStickyAssignment,C as persistSidebarStickyAssignment,i as normalizeSidebarState,m as isUsableRoutingEntry,p as isQuotaExhausted,f as hashSidebarSessionId,g as getSidebarStateFile,j as getSidebarState,b as getPresentQuotaWindows,N as getCollapsedQuotaSummary,a as formatWindowLabel,o as exhaustedQuotaResetAt,E as drainSidebarWrites,H as createSidebarStateCache,K as createSidebarBookkeepingQueue,O as computeQuotaPacing,D as clearSidebarStickyAssignment,J as applyStickyPinOverlay,e as STICKY_ASSIGNMENT_MAX_ENTRIES,d as STICKY_ASSIGNMENT_MAX_AGE_MS,F as HOT_PATH_READ_BUDGET_MS,h as DEFAULT_SIDEBAR_STATE,l as ACTIVE_ROUTING_MAX_ENTRIES,k as ACTIVE_ROUTING_MAX_AGE_MS};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as a}from"./index-yeyp8t0k.js";import"./index-bgq9d21h.js";export default a();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as U,b as V}from"./index-
|
|
1
|
+
import{a as U,b as V}from"./index-yeyp8t0k.js";import{qe as R}from"./index-bgq9d21h.js";var E=R((M,Q)=>{var{defineProperty:H,getOwnPropertyDescriptor:W,getOwnPropertyNames:X}=Object,Y=Object.prototype.hasOwnProperty,Z=(z,q)=>{for(var B in q)H(z,B,{get:q[B],enumerable:!0})},$=(z,q,B,F)=>{if(q&&typeof q==="object"||typeof q==="function"){for(let v of X(q))if(!Y.call(z,v)&&v!==B)H(z,v,{get:()=>q[v],enumerable:!(F=W(q,v))||F.enumerable})}return z},A=(z)=>$(H({},"__esModule",{value:!0}),z),L={};Z(L,{refreshToken:()=>D});Q.exports=A(L);var K=U(),G=V();async function D(z){let q=z?.project,B=z?.team;if(!q&&!B){let v=(0,G.findProjectInfo)();q=v.projectId,B=v.teamId}else if(!q||!B){let v=(0,G.findProjectInfo)();q=q??v.projectId,B=B??v.teamId}if(!q)throw new K.VercelOidcTokenError("Failed to refresh OIDC token: No project specified. Try re-linking your project with `vc link`");let F=(0,G.loadToken)(q);if(!F||(0,G.isExpired)((0,G.getTokenPayload)(F.token),z?.expirationBufferMs)){let v=await(0,G.getVercelToken)({expirationBufferMs:z?.expirationBufferMs});if(F=await(0,G.getVercelOidcToken)(v,q,B),!F)throw new K.VercelOidcTokenError("Failed to refresh OIDC token");(0,G.saveToken)(F,q)}process.env.VERCEL_OIDC_TOKEN=F.token;return}});export default E();
|
|
@@ -38,4 +38,5 @@ export declare function computeEffectiveOrder(root: Record<string, unknown>, plu
|
|
|
38
38
|
type JsonValue = string | number | boolean | null;
|
|
39
39
|
export declare function queueTuiPreferenceUpdate(pluginKey: string, path: string[], value: JsonValue): Promise<void>;
|
|
40
40
|
export declare function watchTuiPreferences(onChange: () => void): () => void;
|
|
41
|
-
//#endregion
|
|
41
|
+
//#endregion
|
|
42
|
+
export {};
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ed as u,Fd as P,yd as h}from"./index-2hch7e8n.js";import{be as M,ce as R,he as S}from"./index-dryydk6b.js";import"./index-bgq9d21h.js";import{mkdir as Yq,writeFile as Vq}from"node:fs/promises";import{homedir as Wq}from"node:os";import{dirname as Dq,join as b}from"node:path";import{applyEdits as t,modify as r,parse as e}from"jsonc-parser";function qq(z){return z!==null&&typeof z==="object"&&!Array.isArray(z)}async function k(z){try{let q=[],H=e(await S(z,M),q,{allowTrailingComma:!0});return q.length===0&&qq(H)?H:{}}catch(q){if(q instanceof R&&q.code!=="ENOENT")throw q;return{}}}var zq=`// Shared preferences for TUI plugins.
|
|
2
2
|
// Plugins update individual keys in place and preserve comments.
|
|
3
3
|
{}
|
|
4
|
-
`;function
|
|
4
|
+
`;function g(z){let{file:q,pluginKey:H,beforeCommit:Q}=z,$={...P.preferences,timeoutMs:z.timeoutMs??P.preferences.timeoutMs},Z=Promise.resolve();async function X(U,j){await u(q,$,async(K)=>{let J;try{J=await S(q,M)}catch(G){if(G.code!=="ENOENT")throw G;J=""}if(J.trim()==="")J=zq;let B=t(J,r(J,[H,...U],j,{formattingOptions:{insertSpaces:!0,tabSize:2}}));await h(q,B,{serialize:(G)=>String(G),beforeRename:async()=>{await Q?.(),await K.assertOwned()}})})}return{queueTuiPreferenceUpdate(U,j){let K=[...U],J=structuredClone(j),B=Z.then(()=>X(K,J));return Z=B.catch(()=>{}),B}}}import{readFileSync as Hq,realpathSync as Qq,statSync as Xq,watch as Zq}from"node:fs";import{readFile as $q,stat as Bq}from"node:fs/promises";import{basename as p,dirname as s,join as Gq,resolve as Jq}from"node:path";import{clearTimeout as w,setTimeout as c}from"node:timers";function n(z){let q=Jq(z);if(M)return q;try{return Qq(q)}catch{let H=s(q);return H===q?q:Gq(n(H),p(q))}}function d(z){return z&&`${z.dev}:${z.ino}:${z.mtimeMs}:${z.size}`}function T(z,q,H={}){let Q=globalThis,$=Symbol.for("cortexkit.common-auth.tui-prefs.watchers.v1"),Z=Q[$]??new Map;Q[$]=Z;let X=n(z),U=Z.get(X);if(U)return U.subscribe(q);let j=p(X),K=M?(Y)=>S(Y):H.fs?.readFile??((Y)=>$q(Y,"utf8")),J=H.fs?.stat??Bq,B=null,G=null,x=null,C=null;if(!M)try{let Y=d((H.fs?.statSync??Xq)(X));C=(H.fs?.readFileSync??((V)=>Hq(V,"utf8")))(X),x=Y}catch{}let N=!1,L=new Set,E=Promise.resolve(),v=(Y)=>{return E=E.then(async()=>{if(N)return;let V=d(await J(X).catch(()=>null));if(!Y&&V===x)return;if(V===null){x=null;return}let I=await K(X).catch((W)=>{if(W instanceof R&&W.code!=="ENOENT")if(H.onError)H.onError(W);else process.emitWarning(W.message,W.name);return null});if(N)return;if(I===null)return;if(x=V,I===C)return;C=I;for(let W of[...L]){if(!L.has(W))continue;try{W.notify()}catch{}}}),E},i=()=>{if(N)return;if(B)w(B);B=c(()=>{B=null,v(!0)},150)},O=null;try{O=(H.watchDirectory??Zq)(s(X),(Y,V)=>{let I=V?.toString(),W=I===j||I?.startsWith(`${j}.`)&&I.endsWith(".tmp");if(I!=null&&!W)return;i()}),O.on("error",()=>{O?.close(),O=null})}catch{}let f=()=>{if(N||G)return;G=c(()=>{if(G=null,N)return;v(!1).finally(f)},1000),G.unref()},F={subscribe:(Y)=>{let V={notify:Y};return L.add(V),()=>{if(!L.delete(V)||L.size>0)return;if(N=!0,B)w(B);if(G)w(G);if(O?.close(),Z.get(X)===F)Z.delete(X)}}};return Z.set(X,F),f(),F.subscribe(q)}var Uq="OPENCODE_TUI_PREFERENCES_FILE",Iq="tui-preferences.jsonc";function m(){let z=process.env[Uq];if(z)return z;let q=process.env.OPENCODE_CONFIG_DIR||b(process.env.XDG_CONFIG_HOME||b(Wq(),".config"),"opencode");return b(q,Iq)}function _(z){return typeof z==="object"&&z!==null&&!Array.isArray(z)}function dq(){return k(m())}var Mq="openai-auth",Aq=160,l={forceToTop:!1,order:Aq,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"OPENAI",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function D(z,q){return typeof z==="boolean"?z:q}function A(z,q,H,Q){if(typeof z!=="number"||!Number.isFinite(z))return q;return Math.min(Math.max(Math.round(z),H),Q)}function jq(z,q,H){if(typeof z!=="string"||z.length===0)return q;return z.slice(0,H)}function o(z,q){if(typeof z!=="string")return q;return[...z][0]??q}function pq(z){let q=z[Mq];if(!_(q))return structuredClone(l);let H=l,Q=_(q.header)?q.header:{},$=_(q.sections)?q.sections:{},Z=_(q.appearance)?q.appearance:{},X=A(Z.warnThreshold,H.appearance.warnThreshold,0,99),U=Math.max(A(Z.errorThreshold,H.appearance.errorThreshold,0,100),Math.min(X+1,100));return{forceToTop:D(q.forceToTop,H.forceToTop),order:A(q.order,H.order,-1e4,1e4),startCollapsed:D(q.startCollapsed,H.startCollapsed),rememberCollapsed:D(q.rememberCollapsed,H.rememberCollapsed),collapsed:typeof q.collapsed==="boolean"?q.collapsed:null,pollMs:A(q.pollMs,H.pollMs,500,30000),refreshDebounceMs:A(q.refreshDebounceMs,H.refreshDebounceMs,50,5000),header:{label:jq(Q.label,H.header.label,20),showVersion:D(Q.showVersion,H.header.showVersion)},sections:{quota:D($.quota,H.sections.quota),fallbackAccounts:D($.fallbackAccounts,H.sections.fallbackAccounts),routing:D($.routing,H.sections.routing),health:D($.health,H.sections.health),pacing:D($.pacing,H.sections.pacing)},appearance:{barWidth:A(Z.barWidth,H.appearance.barWidth,4,40),barFilledChar:o(Z.barFilledChar,H.appearance.barFilledChar),barEmptyChar:o(Z.barEmptyChar,H.appearance.barEmptyChar),warnThreshold:X,errorThreshold:U}}}var Nq=-1e5;function sq(z,q,H){let Q=z[q];if(!_(Q))return H;if(Q.forceToTop===!0)return Nq+Object.keys(z).indexOf(q);return A(Q.order,H,-1e4,1e4)}var Kq=`// Shared preferences for opencode TUI plugins.
|
|
5
5
|
// One top-level key per plugin (short name). See each plugin's README for
|
|
6
6
|
// its supported settings. This file is safe to hand-edit; plugins update
|
|
7
7
|
// individual keys in place and preserve comments.
|
|
8
8
|
{}
|
|
9
|
-
`,
|
|
9
|
+
`,a=new Map;function Lq(z,q){let H=JSON.stringify([z,q]),Q=a.get(H);if(!Q)Q=g({file:z,pluginKey:q}),a.set(H,Q);return Q}async function Oq(z){await Yq(Dq(z),{recursive:!0}),await Vq(z,Kq,{encoding:"utf8",flag:"wx"}).catch(()=>{})}var y=Promise.resolve();function nq(z,q,H){let Q=m(),$=Lq(Q,z);return y=y.then(()=>Oq(Q)).then(()=>$.queueTuiPreferenceUpdate(q,H)).catch(()=>{}),y}function lq(z){return T(m(),z)}export{lq as watchTuiPreferences,pq as resolveOpenaiAuthPrefs,dq as readTuiPreferencesFile,nq as queueTuiPreferenceUpdate,m as getTuiPreferencesFile,sq as computeEffectiveOrder,Uq as TUI_PREFS_FILE_ENV,Mq as PLUGIN_KEY,Aq as DEFAULT_SLOT_ORDER,l as DEFAULT_PREFS};
|
package/dist/tui.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as ApplyRequest } from "./protocol-
|
|
2
|
-
import { S as SpendControlReading, b as SidebarState, l as QuotaPacing, r as AccountQuota, u as QuotaWindow } from "./sidebar-state-
|
|
1
|
+
import { t as ApplyRequest } from "./protocol-CSIDDBDf.js";
|
|
2
|
+
import { S as SpendControlReading, b as SidebarState, l as QuotaPacing, r as AccountQuota, u as QuotaWindow } from "./sidebar-state-BCxFpH68.js";
|
|
3
3
|
import { TuiPluginModule } from "@opencode-ai/plugin/tui";
|
|
4
4
|
//#region src/tui.d.ts
|
|
5
5
|
/** One drawer action as the RPC apply request carries it, with its session. */
|
package/dist/v2/server.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as BeginAccountLoginOptions, h as AccountPaths, l as BeginAccountLoginResult, n as HostSlotAdapter, s as OpenAiVaultOptions, t as PoolLifecycleDeps } from "../pool-lifecycle-DqKq8Eej.js";
|
|
2
2
|
import { Plugin } from "@opencode/plugin";
|
|
3
3
|
import "@opencode/plugin/promise/session";
|
|
4
4
|
import "@opencode/plugin/promise/integration";
|
package/dist/v2/server.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}:{event:
|
|
3
|
-
`)}}function L2($,Z){let X=new TextDecoder,z="",j=(q)=>{let F=F$(q);if(!F)return;try{$(F)}catch(O){Z(O)}},B=()=>{for(;;){let q=/\r?\n\r?\n/.exec(z);if(!q)return;let F=z.slice(0,q.index);z=z.slice(q.index+q[0].length),j(F)}};return new TransformStream({transform(q,F){F.enqueue(q),z+=X.decode(q,{stream:!0}),B()},flush(){if(z+=X.decode(),B(),z.trim()!=="")j(z);z=""}})}var s2=512,Y2="x-common-auth-attempt",e=($,Z)=>JSON.stringify([$,Z]),o=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function P$($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function T$($,Z){let X=$.getReader();return new ReadableStream({async pull(z){let j;try{j=await X.read()}catch(B){Z({reason:"failed",message:B instanceof Error?B.message:String(B)}),z.error(B);return}if(j.done)Z(),z.close();else z.enqueue(j.value)},async cancel(z){Z({reason:"cancelled",...z===void 0?{}:{message:String(z)}}),await X.cancel(z)}})}function _2($,Z){for(let[X,z]of Object.entries(Z)){let j=X.toLowerCase();for(let B of Object.keys($))if(B.toLowerCase()===j)delete $[B];if(z!==null)$[X]=z}}function M$($,Z){for(let[X,z]of Object.entries(Z))if(z===null)$.delete(X);else $.set(X,z)}async function q2($,Z,X={}){let{providerID:z}=Z,j=X.gateOnPlaceholder,B=(Y)=>j===void 0||j.credential(Y)===a(z),q=X.logger,F=Math.max(1,X.maxRecords??s2),O=[...X.hostCredentials??[a(z)],...j?[a(z)]:[]].filter((Y)=>Y!==""),H=new Map,W=new WeakMap,k=new Map,b=new Set,S=new Map,v=!1,m=!1,d=new Map,I=0,u=!1,g=new Map,h=(Y,K)=>{try{q?.warn(Y,K)}catch{}},J=(Y)=>Y instanceof Error?Y.message:String(Y),V=async(Y,K)=>{let G=d.get(Y);if(!G||G.size===0)return;await Promise.all([...G].map(async(Q)=>{try{await Q(K)}catch(M){h("opencode2 auth listener threw; the request is unaffected",{event:Y,error:J(M)})}}))},P=async(Y,K)=>{try{await Z.onAttemptEnd?.(Y,K)}catch(G){h("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:Y.attemptId,error:J(G)})}},C=(Y,K)=>{if(Y.ended||!Y.attempt)return;let G={...Y.status===void 0?{}:{status:Y.status},outputStarted:Y.outputStarted,...Y.limit?{limit:Y.limit.signal}:{},...K?{error:K}:{}};if(K)Y.endError=K;Y.ended=P(Y.attempt,G)},A=(Y,K)=>C(Y,{reason:"abandoned",message:K}),T=(Y)=>[...H.values()].filter((K)=>K.key===Y),D=(Y)=>T(Y).at(-1),y=(Y)=>{if(H.delete(Y.id),!T(Y.key).length)k.delete(Y.key)},x=(Y)=>{H.set(Y.id,Y);while(H.size>F){let K=H.values().next().value;if(K===void 0)break;A(K,"dropped to keep the record bound"),y(K)}},f=(Y)=>Y.accountId===void 0?void 0:{...Y.scope,accountId:Y.accountId},i=(Y,K)=>new c({kind:"no-account",providerID:z,sessionID:Y.sessionID,requestKind:Y.kind,...K===void 0?{}:{message:K}}),p=(Y)=>{g.get(Y)?.clear(),g.delete(Y)},l=async(Y,K)=>{let G=()=>i(Y,`${z} ${Y.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(u)throw G();let Q=g.get(Y.sessionID);if(!Q)Q=new Set,g.set(Y.sessionID,Q);let M={};Q.add(M);let E=()=>{if(!Q.has(M))throw G()};try{return await K(E)}finally{if(Q.delete(M),Q.size===0&&g.get(Y.sessionID)===Q)g.delete(Y.sessionID)}},U=(Y,K)=>{for(let[G,Q]of K)if(O.some((M)=>Q.includes(M)))throw new c({kind:"host-credential-on-wire",providerID:z,sessionID:Y.sessionID,requestKind:Y.kind,message:`${z} ${Y.kind} request still carries the host's placeholder credential in ${G}; the adapter's account headers must replace it`})},L=(Y)=>{for(let K of T(Y))if(K.ended||!K.attempt)y(K);else if(K.transport==="ws"||K.judged)A(K,"a newer attempt of its session and kind began"),y(K)},R=async(Y,K,G,Q)=>{let M=e(Y.sessionID,Y.kind),E=k.get(M);k.delete(M);let N=E?.accountId??D(M)?.accountId;L(M);let _={...Y,...N===void 0?{}:{previousAccountId:N},...E?.rerouteFrom===void 0?{}:{rerouteFrom:E.rerouteFrom}},w=await Z.chooseAccount(_);G();let s={},c2;if(w!==void 0){let Q2=await Z.accountHeaders({...Y,accountId:w});if(G(),P$(Q2))s=Q2.headers,c2=Q2.attempt;else s=Q2}let d2=`attempt-${++I}`,z2={id:d2,key:M,scope:Y,accountId:w,headers:s,attempt:w===void 0?void 0:{...Y,accountId:w,attemptId:d2,transport:Q,data:c2},...Q===void 0?{}:{transport:Q},outputStarted:!1};if(x(z2),z2.attempt)V("select",{...Y,accountId:z2.attempt.accountId,hook:K,..._.previousAccountId===void 0?{}:{previousAccountId:_.previousAccountId},..._.rerouteFrom===void 0?{}:{rerouteFrom:_.rerouteFrom},handle:z2.attempt});return z2},K2=async(Y,K,G,Q,M)=>{let E=e(Y.sessionID,Y.kind),N=Q===void 0?void 0:H.get(Q);if(N?.key!==E)N=void 0;if(!N){if(N=D(E),T(E).filter((w)=>w.transport===void 0&&!w.ended).length>1&&!m)m=!0,h("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:Y.sessionID,kind:Y.kind})}if(!N||N.transport!==void 0||N.ended)N=await R(Y,K,M,G);else if(N.transport=G,N.attempt)N.attempt.transport=G;if(G==="ws"){for(let _ of T(E))if(_!==N&&_.transport==="ws")A(_,"a newer attempt of its session and kind went out over WebSocket")}return N},$2=async(Y,K)=>{try{return await K()}catch(G){throw C(Y,{reason:"failed",message:J(G)}),G}},f2=(Y,K)=>{let G=T(e(Y,K)).filter((Q)=>Q.transport==="ws").at(-1);return G?.attempt!==void 0&&!G.ended?G:void 0},P2=(Y,K,G)=>{let Q=f(Y);if(!Q||!Y.attempt||Y.limit)return;Y.limit={signal:K,delivered:V("limit",{...Q,via:G,limit:K,outputStarted:Y.outputStarted,handle:Y.attempt})}},m2=(Y,K,G,Q)=>{let M=f(Y);if(!M||!Y.attempt)return;V("quota",{...M,transport:K,...Q===void 0?{}:{status:Q},quota:G,handle:Y.attempt})},g2=(Y,K,G,Q)=>{let M=Y.attempt;if(!M)return;let E=Z.inspectEvent?.(Q===void 0?{transport:K,data:G,attempt:M}:{transport:K,data:G,event:Q,attempt:M});if(!E)return;if(E.quota!==void 0)m2(Y,K,E.quota);if(E.outputStarted)Y.outputStarted=!0;if(E.limit)P2(Y,E.limit,K);if(E.error!==void 0)C(Y,{reason:"failed",message:E.error});else if(E.done)C(Y)},U$=(Y,K)=>{let G=Y.attempt;if(!G||K.accountId===Y.accountId)return;if(G.reboundFrom??=G.accountId,G.accountId=K.accountId,"data"in K)G.data=K.data;Y.accountId=K.accountId},C$=(Y)=>!Y.attempt||Y.endError!==void 0||Y.status!==void 0&&Y.status>=400,N$=(Y)=>{let K=[...H.values()].filter((_)=>_.scope.sessionID===Y),G=K.filter((_)=>_.limit&&!_.rerouted).at(-1);if(G)return G;let Q=K.filter((_)=>_.scope.kind==="primary"),M=Q.length>0?Q:K;if(M.length<=1)return M[0];let E=M.filter((_)=>!_.judged&&C$(_)).at(-1);if(E)return E;let N=M.filter((_)=>_.attempt&&!_.ended);if(N.length>1)return"ambiguous";return N[0]??M.at(-1)},t={providerID:z},r=[];r.push(await $.session.hook("model.request",(Y)=>{if(j)return;return l(o(Y),async(K)=>{let G=await R(o(Y),"model.request",K);if(K(),G.accountId===void 0)throw i(G.scope);_2(Y.headers,{...G.headers,[Y2]:G.id})})},t)),r.push(await $.session.hook("http.request",(Y)=>{if(j){let K=B(Y.request.headers);if(S.set(Y.sessionID,K),!K)return}return l(o(Y),async(K)=>{let G=Y.request.headers.get(Y2)??void 0,Q=j?await R(o(Y),"http.request",K,"http"):await K2(o(Y),"http.request","http",G,K);K();let M=f(Q),E=Q.attempt;if(!M||!E)throw i(Q.scope);await $2(Q,async()=>{let N=Y.request;if(Z.rewriteRequest){if(G!==void 0){let s=new Headers(N.headers);s.delete(Y2),N=new Request(N,{headers:s})}N=await Z.rewriteRequest({...M,request:N,attempt:E})??N,K()}let _=new Headers(N.headers);_.delete(Y2),M$(_,Q.headers),U(Q.scope,_.entries());let w=new Request(N,{headers:_});W.set(w,Q),Y.request=w})})},t)),r.push(await $.session.hook("http.response",async(Y)=>{let K=W.get(Y.request);if(!K){if(j)return;if(!v)v=!0,h("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:Y.sessionID,kind:Y.kind});return}let G=Y.response;if(Z.answeredBy&&K.attempt){let _=K.attempt,w=await $2(K,async()=>Z.answeredBy?.({request:Y.request,response:G,attempt:_}));if(w)U$(K,w)}let Q=f(K),M=K.attempt;if(!Q||!M)return;K.status=G.status;let E=Z.quotaFromHeaders?.(G.headers,G.status,M);if(E!==void 0)m2(K,"http",E,G.status);if(!G.ok&&Z.limitFromResponse){let _=await Z.limitFromResponse({status:G.status,headers:G.headers,body:()=>G.clone().text(),attempt:M});if(_)P2(K,_,"http")}if(!G.ok||!G.body)C(K);let N=G;if(G.body&&(Z.inspectEvent||Z.onAttemptEnd)){let _=G.body;if(Z.inspectEvent)_=_.pipeThrough(L2((w)=>g2(K,"http",w.data,w.event),(w)=>h("opencode2 auth event inspection threw",{error:J(w)})));N=new Response(T$(_,(w)=>C(K,w)),{status:G.status,statusText:G.statusText,headers:G.headers})}if(Z.rewriteResponse)N=await Z.rewriteResponse({...Q,request:Y.request,response:N,attempt:M})??N;if(N!==G)Y.response=N},t)),r.push(await $.session.hook("experimental.ws.handshake",(Y)=>{if(j){let K=B(new Headers(Y.headers)),G=e(Y.sessionID,Y.kind);if(S.set(Y.sessionID,K),b.delete(G),!K)return}return l(o(Y),async(K)=>{let G;for(let N of Object.keys(Y.headers)){if(N.toLowerCase()!==Y2)continue;G??=Y.headers[N],delete Y.headers[N]}let Q=j?await R(o(Y),"experimental.ws.handshake",K,"ws"):await K2(o(Y),"experimental.ws.handshake","ws",G,K);K();let M=f(Q),E=Q.attempt;if(!M||!E)throw i(Q.scope);await $2(Q,async()=>{_2(Y.headers,Q.headers);let N=Z.rewriteHandshakeURL?.({...M,url:Y.url,attempt:E});if(N!==void 0)Y.url=N;if(U(Q.scope,Object.entries(Y.headers)),j)b.add(Q.key)})})},t));let u2=Z.rewriteWebSocketFrame?.bind(Z);if(u2)r.push(await $.session.hook("experimental.ws.send",async(Y)=>{let K=o(Y);if(j&&!b.has(e(K.sessionID,K.kind)))return;let G=f2(K.sessionID,K.kind),Q=await u2({...K,attempt:G?.attempt,frame:Y.frame});if(Q!==void 0)Y.frame=Q},t));r.push(await $.session.hook("experimental.ws.receive",(Y)=>{if(j&&!b.has(e(Y.sessionID,Y.kind)))return;let K=f2(Y.sessionID,Y.kind);if(!K)return;try{g2(K,"ws",Y.frame)}catch(G){h("opencode2 auth frame inspection threw",{error:J(G)})}},t)),r.push(await $.session.hook("retry",async(Y)=>{if(j&&S.get(Y.sessionID)!==!0)return;let K=N$(Y.sessionID);if(!K)return;let G=Y.decision;if(K==="ambiguous"){await V("retry",{sessionID:Y.sessionID,attempt:Y.attempt,reason:"host-decides",hostDecision:G,decision:G});return}let Q=K;await l(Q.scope,async(M)=>{Q.judged=!0;let E=G,N,_,w=Q.attempt;if(Q.accountId===void 0||!w)E={retry:!1},N="no-account";else if(Q.outputStarted)E={retry:!1},N="output-started";else{if(!Q.limit){let s=Z.limitFromError?.(Y.error,w);if(s)P2(Q,s,"error")}if(Q.ended)await Q.ended,M();if(Q.limit)await Q.limit.delivered,M(),Q.rerouted=!0,_={accountId:Q.accountId,limit:Q.limit.signal},E={retry:!0,delay:0},N="reroute";else N="host-decides"}if(Y.decision=E,E.retry&&Q.accountId!==void 0)k.set(Q.key,{sessionID:Q.scope.sessionID,accountId:Q.accountId,..._===void 0?{}:{rerouteFrom:_}});await V("retry",{sessionID:Y.sessionID,...Q.accountId===void 0?{}:{accountId:Q.accountId},kind:Q.scope.kind,attempt:Y.attempt,reason:N,hostDecision:G,decision:E,...w===void 0?{}:{handle:w}})})},t));let l2=(Y)=>{p(Y),S.delete(Y);for(let K of b)if(JSON.parse(K)[0]===Y)b.delete(K);for(let K of[...H.values()]){if(K.scope.sessionID!==Y)continue;A(K,"its session was forgotten"),H.delete(K.id)}for(let[K,G]of k)if(G.sessionID===Y)k.delete(K)},T2=new AbortController,p2=$.event;if(p2)(async()=>{try{for await(let Y of p2.subscribe({signal:T2.signal}))if(Y.type==="session.deleted")l2(Y.data.sessionID)}catch(Y){if(!T2.signal.aborted)h("opencode2 auth stopped listening for session deletion",{error:J(Y)})}})();return{on(Y,K){let G=d.get(Y);if(!G)G=new Set,d.set(Y,G);let Q=K;return G.add(Q),()=>{G.delete(Q)}},accountFor(Y,K){return D(e(Y,K))?.accountId},forgetSession:l2,get size(){return H.size},async dispose(){if(u)return;u=!0;for(let Y of g.keys())p(Y);T2.abort();for(let Y of H.values())A(Y,"the installation was disposed");H.clear(),k.clear(),b.clear(),S.clear(),d.clear(),await Promise.all(r.map(async(Y)=>{try{await Y.dispose()}catch(K){h("opencode2 auth hook did not dispose cleanly",{error:J(K)})}}))}}}var x2={version:o2,"user-agent":r2,originator:"codex_exec"},L$="x-openai-internal-codex-responses-lite",_$=1024,q$=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,B2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),x$=($)=>B2($)&&($.type==="message"||("role"in $))&&$.role==="user",E$=($)=>B2($)&&$.type==="configuration_update";class E2{#$=new Map;apply($,Z,X){if(Z.kind!=="primary")return!1;let z=typeof $.model==="string"?$.model:"";if(!t2.has(z))return!1;if(q$.test(z))return!1;let j=B2($.reasoning)?$.reasoning:void 0,B=typeof j?.effort==="string"?j.effort:void 0;if(!B)return!1;let q=this.#$.get(Z.sessionID);if(q===void 0)return this.#Y(Z.sessionID,B),!1;if(B===q)return!1;let F=Array.isArray($.input)?$.input:void 0;if(!F||F.length===0)return!1;let O=F.findLastIndex(x$);if(O<0){if(X==="http")return!1;return $.reasoning={...j,effort:q},!0}if($.reasoning={...j,effort:q},!E$(F[O-1]))F.splice(O,0,{type:"configuration_update",reasoning:{effort:B}});return!0}forget($){this.#$.delete($)}#Y($,Z){this.#$.set($,Z);while(this.#$.size>_$){let X=this.#$.keys().next().value;if(X===void 0)break;this.#$.delete(X)}}}function S$($){if(typeof $.model!=="string"||!a2.has($.model))return!1;return e2($),!0}function $1($){try{let Z=JSON.parse($);return B2(Z)?Z:void 0}catch{return}}async function Y1($,Z,X,z){if($.method.toUpperCase()!=="POST"||$.body===null)return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let j=$1(await $.clone().text());if(!j)return;let B="max_output_tokens"in j;delete j.max_output_tokens;let q=X.apply(j,Z,"http"),F=z&&S$(j);if(!B&&!q&&!F)return;let O=new Headers($.headers);if(O.delete("content-length"),F)O.set(L$,"true");return new Request($,{headers:O,body:JSON.stringify(j)})}function Z1($,Z,X){let z=$1($);if(z?.type!=="response.create")return;let j="max_output_tokens"in z;delete z.max_output_tokens;let B=X.apply(z,Z,"ws");return j||B?JSON.stringify(z):void 0}function R$($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function S2($,Z){let X=new URL($);if(X.origin!=="https://api.openai.com"&&X.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(X.pathname))return $;let z=new URL(`${R$(Z)}/responses`);if(z.search=X.search,X.protocol==="ws:"||X.protocol==="wss:")z.protocol=z.protocol==="https:"?"wss:":"ws:";return z.href}var n="openai",A$=60000,K1=1,D$="request refused: no account with a usable credential",O$=1024,Z2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function A2($){try{return JSON.parse($)}catch{return}}function z1($){let Z=H2($);return Z?U2(Z):void 0}var b$=new Set(["usage_limit_reached","rate_limit_exceeded"]);function D2($,Z,X){return{reason:$.window,...X!==void 0?{status:X}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-Z)}:{}}}function k$($,Z){let X=W2($);if(X){let B=typeof $.status==="number"?$.status:void 0;return D2(X,Z,B)}if($.type!=="response.failed"||!Z2($.response))return;let z=$.response.failed;if(Z2(z)&&typeof z.rate_limit_reached_type==="string")return{reason:z.rate_limit_reached_type};let j=$.response.error;if(Z2(j)){let B=typeof j.code==="string"?j.code:typeof j.type==="string"?j.type:void 0;if(B&&b$.has(B))return{reason:B}}return}function y$($,Z){let X=A2($);if(!Z2(X))return;let z=typeof X.type==="string"?X.type:void 0;if(z==="codex.rate_limits")return{quota:{snapshot:G1(X),complete:!0}};let j=k$(X,Z);if(j)return{limit:j};if(z===void 0||z==="error")return;return q1(z)?void 0:{outputStarted:!0}}function w$($){let Z=!1;for(let X of $.keys())if(X.toLowerCase().startsWith("x-codex-")){Z=!0;break}if(!Z)return;return{snapshot:J1($),complete:j1($)}}function I$($){let Z=$.get("retry-after");if(Z===null)return;let X=Number(Z);return Number.isFinite(X)&&X>=0?X*1000:void 0}function x1($){let{source:Z,pins:X}=$,z=$.now??Date.now,j=$.log,B=$.vault,q=new E2,F=new Map,O=(J)=>`${J.sessionID}\x00${J.kind}\x00${J.accountId}`,H=new Map,W=new Map,k=(J,V)=>{W.delete(J),W.set(J,V);while(W.size>O$){let P=W.keys().next().value;if(P===void 0)break;W.delete(P)}},b=(J,V,P)=>{let C=P?[]:_1(Z.peek().rows,J,V,B?.identities()??new Set),A=(B?.routes()??[]).filter((T)=>T.kind==="oauth"&&B1(V2(T.quota),J,V));return[...C.map((T)=>({id:T.id,...T.identity!==void 0?{identity:T.identity}:{},quota:T.quota,row:T})),...A.map((T)=>({id:T.id,...T.identity!==void 0?{identity:T.identity}:{},quota:T.quota}))]},S=(J,V,P)=>{let C=new Map;if(V1(V))for(let x of J)C.set(x.id,H1(V2(x.quota),V,x.id===R2?void 0:x.id,P));let A=J.map((x)=>({id:x.id,kind:"oauth",...X1(x.quota)?{quota:x.quota}:{}})),T=J.flatMap((x)=>x.row?[x.row]:[]),D=new Set(J.filter((x)=>!x.row).map((x)=>x.id)),y=Z.rateLimitMarks(T);for(let x of D){let f=H.get(x);if(f===void 0)continue;if(f<=P)H.delete(x);else y.set(x,f)}return{rows:A,now:P,rateLimitMarks:y,refreshBackoff:Z.refreshBackoffFor(T),killswitch:C,requestPull:(x)=>D.has(x)?B?.requestReading(x):Z.requestReading(x)}},v=(J,V,P,C)=>{let A=P1({...J,placement:N1(V)});if(A.kind==="block"){j?.debug("pool admission refused the request",{reason:A.block.reason});return}let T=A.order.filter((D)=>!P.has(D));if(C!==void 0&&T.includes(C))return C;return T[0]},m=(J,V,P,C,A,T)=>{let D={requestBytes:K1,reservePercent:(U)=>W1(P,U===R2?void 0:U),resetCredits:()=>{return}},y=T1(J),x=(U,L)=>X.place({sessionId:C,requestBytes:K1,validPinnedAccountIds:J.rows.map((R)=>R.id).filter((R)=>!y.excluded.has(R)),excludeAccountIds:U,quotaCheckedAtByAccount:Object.fromEntries(J.rows.map((R)=>[R.id,y.projections.get(R.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(V.map((R)=>[R.id,R.identity])),select:(R)=>M1(J,D,new Set(U),R),persist:L}),f=[...A],i=x(f,T);if(!i)return;let p=i.accountId,l=L1(J,D,p);if(l.kind==="none")return;if(l.kind==="move"){let U=x([...f,p],T);if(U)return U.accountId;return l.reason==="killswitch"?void 0:p}if(l.kind==="detour")return x([...f,p],!1)?.accountId;return p},u={providerID:n,chooseAccount:async(J)=>{let V=await B?.authority(),P=await $.storage(),C=V!==void 0&&V!=="local",A=()=>{throw new c({kind:"no-account",providerID:n,sessionID:J.sessionID,requestKind:J.kind,message:C2})};if(C)await $.awaitVaultRoster?.();else{if(!(await Z.current()).active){if(await $.slotPlaceholderWithoutMain?.())A();j?.warn("the account pool does not serve requests yet; refusing the request",{kind:J.kind});return}await Z.prepareTokens(Z.peek().rows,P)}let T=z(),D=b(P,T,C),y=F1(S(D.filter((R)=>R.id!==J.rerouteFrom?.accountId),P,T));if(y)await y,T=z(),D=b(P,T,C);let x=new Map(D.map((R)=>[R.id,R])),f=S(D,P,T),i=new Set(J.rerouteFrom?[J.rerouteFrom.accountId]:[]),p=P?.routing?.mode??"main-first",l=J.kind==="primary",U=new Set,L;for(;;){let R=new Set([...i,...U]);if(L=void 0,p==="sticky-balanced")L=m(f,D,P,J.sessionID,R,l&&U.size===0);if(L??=v(f,p,R,l?void 0:W.get(J.sessionID)),L===void 0||U.has(L)){L=void 0;break}let K2=x.get(L)?.row;if(K2){if(Z.usableToken(K2)!==void 0)break;j?.debug("pool row holds no usable token; choosing again",{accountId:L})}else{if(!B)break;let $2=await B.authorize(L);if($2){F.set(O({...J,accountId:L}),$2);break}j?.debug("the vault refused to serve an account; choosing again",{accountId:L})}U.add(L)}if(L===void 0&&!C&&D.length===0&&await $.slotPlaceholderWithoutMain?.())A();if(L===void 0&&C&&B&&(D.length===0||U.size>0)){let R=U.size>0?"vault-refused":C1(B);throw j?.warn("vault mode: no vault account can serve; refusing the request",{cause:R}),new c({kind:"no-account",providerID:n,sessionID:J.sessionID,requestKind:J.kind,message:U1[R]})}if(L!==void 0&&l)k(J.sessionID,L);return j?.debug("pool account chosen",{kind:J.kind,accountId:L,mode:p,...J.rerouteFrom?{rerouteFrom:J.rerouteFrom.accountId}:{}}),L},accountHeaders:async(J)=>{let{accountId:V}=J,P=()=>new c({kind:"no-account",providerID:n,sessionID:J.sessionID,requestKind:J.kind,message:D$}),C=B&&await B.authority()!=="local"?void 0:Z.peek().rows.find((D)=>D.id===V);if(!C&&B){let D=O(J),y=F.get(D)??await B.authorize(V);if(F.delete(D),!y)throw j?.warn("the vault refused to serve an account; refusing the request",{accountId:V}),P();return{headers:{...x2,"session-id":J.sessionID,authorization:`Bearer ${y.accessToken}`,"chatgpt-account-id":y.accountIdentity??z1(y.accessToken)??null},attempt:{kind:"vault",routeId:V,receipt:y}}}let A=C?Z.usableToken(C):void 0;if(!C||!A)throw j?.warn("pool row holds no usable token; refusing the request",{accountId:V}),P();let T=C.identity??z1(A);return{headers:{...x2,"session-id":J.sessionID,authorization:`Bearer ${A}`,"chatgpt-account-id":T??null},attempt:{kind:"pool",token:A,credentialEpoch:C.credentialEpoch}}},async rewriteRequest({request:J,sessionID:V,kind:P}){let C=$.codexEndpoint?S2(J.url,$.codexEndpoint()):J.url,A=C===J.url?J:new Request(C,J);return await Y1(A,{sessionID:V,kind:P},q,$.responsesLite?.()??!1)??A},rewriteHandshakeURL:({url:J})=>$.codexEndpoint?S2(J,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:J,sessionID:V,kind:P})=>Z1(J,{sessionID:V,kind:P},q),quotaFromHeaders:(J)=>w$(J),async limitFromResponse({status:J,headers:V,body:P}){if(J<400)return;let C=A2(await P().catch(()=>"")),A=W2({...Z2(C)?C:{},status:J});if(!A)return;let T=z(),D=D2(A,T,J);if(D.retryAfterMs!==void 0)return D;let y=I$(V);return y===void 0?D:{...D,retryAfterMs:y}},inspectEvent:({data:J})=>y$(J,z()),limitFromError(J){let V=A2(J.message),P=W2({...Z2(V)?V:{},...J.status!==void 0?{status:J.status}:{}})??(J.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return P?D2(P,z(),J.status):void 0},async onAttemptEnd(J,V){let P=J.data;if(P?.kind!=="vault"||V.status!==401)return;j?.warn("a vault account answered 401; reporting it to the vault",{accountId:J.accountId}),await B?.reportFailure(P.receipt,401)}},g=(J,V,P)=>{let C=P.data;if(C?.kind==="vault"){B?.recordSnapshot(J,V.snapshot,V.complete,C.receipt);return}if(C?.kind!=="pool")return;if(Z.peek().rows.find((T)=>T.id===J)?.credentialEpoch!==C.credentialEpoch){j?.debug("quota reading dropped: the row holds another credential",{accountId:J});return}Z.recordSnapshot(J,V.snapshot,C.token,V.complete)},h=(J,V,P)=>{let C=z(),A=P.data?.kind==="vault",T=A?B?.routes().find((x)=>x.id===J)?.quota:Z.peek().rows.find((x)=>x.id===J)?.quota,D=Q1(V2(T),V.reason,C,A$,V.retryAfterMs!==void 0?C+V.retryAfterMs:void 0);if(!A){Z.markRateLimited(J,D);return}let y=H.get(J);if(y===void 0||y<D)H.set(J,D)};return{adapter:u,attach(J){J.on("quota",(V)=>g(V.accountId,V.quota,V.handle)),J.on("limit",(V)=>{h(V.accountId,V.limit,V.handle),j?.debug("pool row refused the request",{accountId:V.accountId,via:V.via,reason:V.limit.reason,outputStarted:V.outputStarted})})},forgetSession(J){X.forget(J),W.delete(J),q.forget(J)}}}import{randomUUID as h$}from"node:crypto";import{chmod as v$,mkdir as f$,readFile as m$,rename as g$,rm as u$,stat as l$,writeFile as p$}from"node:fs/promises";import{dirname as c$,resolve as d$}from"node:path";var i$="(no OpenCode 1 logins on this machine)";function n$($=process.env){return E1($)}async function O2($){let Z;try{Z=await m$($,"utf8")}catch(z){if(z.code==="ENOENT")return;throw z}let X=JSON.parse(Z);if(!X||typeof X!=="object"||Array.isArray(X))throw Error(`${$} does not hold a JSON object`);return X}function b2($){return $===void 0?void 0:JSON.stringify($)}async function s$($){try{return(await l$($)).mode&511}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function S1($=n$()){let Z=new Map;return{path:d$($),async get(X){let z=(await O2($))?.[X.path.id];return Z.set(X.path.id,b2(z)),z},async set(X){let z=X.path.id,j=await s$($),B=await O2($)??{};if(!Z.has(z)||Z.get(z)!==b2(B[z]))throw new k2;B[z]=X.body,await f$(c$($),{recursive:!0});let q=`${$}.${h$()}.tmp`;try{await p$(q,`${JSON.stringify(B,null,2)}
|
|
4
|
-
`,{mode:j??384}),await v$(q,j??384),await g$(q,$)}catch(F){throw await u$(q,{force:!0}).catch(()=>{}),F}return Z.set(z,b2(X.body)),!0},async all(){let X=await O2($);if(!X||Object.keys(X).length===0)return{[i$]:!0};return X}}}var a$="openai-auth-pool-browser",o$="openai-auth-pool-headless",r$="openai-auth-vault",t$="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Connect to the vault or disconnect this host before trying again.";async function J2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function k1($){return{method:{id:r$,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await R1($.paths,$.name)!=="vault")throw Error(t$)}}}function y1($){let Z=(X,z,j)=>({method:{id:X,type:"oauth",label:z},async authorize(){if($.vault)await J2($.vault);let B=await $.beginLogin({version:$.version,headless:j});return{url:B.url,instructions:B.instructions,mode:"auto",callback:B.completion}}});return[Z(a$,"ChatGPT (openai-auth pool, browser)",!1),Z(o$,"ChatGPT (openai-auth pool, headless)",!0)]}function y2($){let Z=(X)=>typeof X==="string"?X:"";return X2({type:"oauth",access:Z($.access),refresh:Z($.refresh)})||$.refresh===O1||A1($)}function e$($){if($.accountId)return $.accountId;let Z=$.access?H2($.access):void 0;return Z?U2(Z):void 0}async function w1($,Z,X,z={}){if(z.vault)await J2(z.vault);if(y2(X))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let j=D1($,{rowLocks:(S)=>b1(Z,S)}),B=await j.read();if(B.status!=="ready")throw Error(`the account pool cannot be read (${B.status}); the login was not stored`);let q={type:"oauth",refresh:X.refresh,...X.access!==void 0?{access:X.access}:{},...X.expires!==void 0?{expires:X.expires}:{}},F=e$(X);if(z.vault)await J2(z.vault);let O=F!==void 0?{identity:F}:{};if(z.origin==="import"){let S=B.rows.find((v)=>F!==void 0&&v.identity===F||v.credential?.type==="oauth"&&v.credential.refresh===X.refresh);if(S)return{id:S.id,operation:"kept"}}let H=B.rows.filter((S)=>S.type==="oauth"&&!S.invalid),W=F?H.find((S)=>S.identity===F):void 0,k=B.rows.find((S)=>S.id===N2);if(W)return{id:(await j.replace(W.id,q,O)).id,operation:"replaced"};if(!k){let S=await j.add({id:N2,credential:q,...O,...X.label!==void 0?{label:X.label}:{}});return{id:S.id,operation:S.outcome==="added-disabled"?"added-disabled":"added"}}if(!k.invalid&&!k.credential)return{id:(await j.replace(N2,q,O)).id,operation:"replaced"};let b=await j.add({id:X.id,credential:q,...O,...X.label!==void 0?{label:X.label}:{}});return{id:b.id,operation:b.outcome==="added-disabled"?"added-disabled":b.outcome==="rotated"?"replaced":"added"}}function $Y($){if(!I1($.modelID??$.id)){$.enabled=!1;return}let Z=h1($.id);if(Z)$.limit={...Z}}function v1($){return $.model.transform((Z)=>{for(let X of Z.list(n))Z.update(n,String(X.id),(z)=>$Y(z))})}var YY=1024;class w2{pins=new Map;limit;constructor($=YY){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.pins.delete($)}get size(){return this.pins.size}set($,Z){this.pins.delete($),this.pins.set($,Z);while(this.pins.size>this.limit){let X=this.pins.keys().next().value;if(X===void 0)break;this.pins.delete(X)}}place($){return f1(this.pins,$,(Z,X)=>this.set(Z,X))}}var F2="cortexkit-openai-auth",ZY=5000;async function m1($,Z,X){let z=new Map,j=new Map,B=(H)=>{j.delete(H);for(let W of z.keys())if(W.startsWith(`${H}:`))z.delete(W)},F=await q2({session:{hook:(H,W,k)=>$.session.hook(H,async(b)=>{let S=H==="http.request"?b:void 0,v=H==="experimental.ws.handshake"?b:void 0,d=(S?S.request.headers:v?new Headers(v.headers):void 0)?.get("authorization")===`Bearer ${a(Z.providerID)}`;try{await W(b)}catch(I){if(d&&!(I instanceof c))throw o1(I);throw I}if(S||v){let I=S??v;if(!I)return;let g=(S?S.request.headers:new Headers(I.headers)).get("authorization")?.replace(/^Bearer /,"");if(d&&g)j.set(I.sessionID,g);else j.delete(I.sessionID);if(v){let h=`${v.sessionID}:${v.kind}`;if(d&&g)z.set(h,g);else z.delete(h)}if(j.size>512){let h=j.keys().next().value;if(h)j.delete(h)}if(z.size>512){let h=z.keys().next().value;if(h)z.delete(h)}}else if(H==="experimental.ws.receive"){let I=b,u=z.get(`${I.sessionID}:${I.kind}`);if(u)I.frame=r1(I.frame,u)}else if(H==="retry"){let I=b,u=j.get(I.sessionID);if(u)Object.assign(I.error,{message:a1(I.error.message,u)})}},k)},event:{subscribe:(H)=>async function*(){for await(let W of $.event.subscribe(H)){if(W.type==="session.deleted")B(W.data.sessionID);yield W}}()}},{...Z,rewriteResponse:async(H)=>{let W=await Z.rewriteResponse?.(H)??H.response;return t1(W,H.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(H)=>{let W=H.get("authorization");return W?.startsWith("Bearer ")?W.slice(7):void 0}},logger:{warn:(H,W)=>X.warn(H,{data:W})}}),O=F.dispose;return{...F,dispose:async()=>{j.clear(),z.clear(),await O()}}}function v2($={}){return{id:F2,setup:(Z)=>KY(Z,$)}}async function KY($,Z={}){let f=[];try{let X=j2("opencode2");let z=j2("quota");let j=Z.paths??(()=>$$(e1()));let B=Z.fetch??fetch;let q=Z.version??X$;let F=Z.poolMigration??W$;if(!F&&!G2(j().configPath)){X.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let U=(R)=>{throw new c({kind:"no-account",providerID:n,sessionID:R.sessionID,requestKind:R.kind,message:C2})},L=await m1($,{providerID:n,chooseAccount:U,accountHeaders:U},X);return()=>L.dispose()}let O=Z.vault?.firstRosterWaitMs??j$;let H=V$({host:"opencode",stateDir:Z.vault?.stateDir??s1(j().statePath),reservedRouteIds:()=>m.peek().rows.map((U)=>U.id),...Z.vault?.connectionFile?{connectionFile:Z.vault.connectionFile}:{},...Z.vault?.connectScoped?{connectScoped:Z.vault.connectScoped}:{},...Z.vault?.connectEnrollment?{connectEnrollment:Z.vault.connectEnrollment}:{},...Z.vault?.pollIntervalMs!==void 0?{pollIntervalMs:Z.vault.pollIntervalMs}:{},fetchImpl:()=>B},j());let W=H.vault;let k=!1;let b=!1;const S=g1(f,{[Symbol.dispose](){if(!k)H.release()}},0);await W.authority();let v=H.firstRoster;let m=new G$({paths:j,refreshProvider:async(U)=>{let L=await c1({refreshToken:U.refresh,fetchImpl:B,now:Date.now}),R=l1({id_token:"",access_token:L.access,refresh_token:L.refresh});return{...L,...R?{identity:R}:{}}},pullQuota:async(U)=>{let L=U.credential;if(L.type!=="oauth"||!L.access)throw Error("the row holds no access token to poll with");let R=await d1({accessToken:L.access,fetchImpl:B,now:Date.now,...U.identity?{accountId:U.identity}:{},accountKey:U.id,logger:z});return n1(R,Date.now(),!0)},vaultIdentities:()=>W.identities(),vaultMode:()=>W.enrolled(),vaultAuthority:()=>W.authority(),vaultFirstRoster:v,vaultFirstRosterBackgroundWaitMs:O,log:j2("pool")});await m.load();let d=Z.heartbeat===!1?void 0:await B$({version:q,logger:j2("heartbeat")});let I=Z.fence??(()=>z$({currentVersion:q}));let u=Z.slot??S1();let g=async()=>Y$(j(),await u.get({path:{id:"openai"}}));let h=!1;let J=F?Q$({paths:j,slot:u,version:q,fence:I,runDeps:{vaultServes:()=>W.serves()},paused:async()=>await W.authority()!=="local",migrate:async(U)=>{let L=await Z$(U);if(h=L.status==="refused",!b)await m.load();return L},adopt:async(U)=>{if(b)return{status:"retry",reason:"unsettled"};if(!await h2(v,O))return{status:"retry",reason:"vault-roster-pending"};if(b)return{status:"retry",reason:"unsettled"};let L=await K$(U);if(!b)await m.load();return L}}):void 0;J?.start();H.start();let V=new w2;let P=x1({source:m,slotPlaceholderWithoutMain:g,storage:()=>i1(j()),pins:V,vault:W,awaitVaultRoster:async()=>{await h2(v,J$)},responsesLite:()=>I2().responsesLite,codexEndpoint:()=>I2().codexApiEndpoint,log:X});let C=await m1($,P.adapter,X);P.attach(C);let A=async(U)=>{if(await J2(W),G2(j().configPath))return;if(await J?.idle(),G2(j().configPath))return;if(h&&!y2(U)&&(await I()).open){await m.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let T=async(U)=>{await A(U);let L=await w1(m.poolStore(),j(),U,{vault:W});if(!G2(j().configPath))await J?.requestAdoption();await m.load(),X.info("ChatGPT login stored in the account pool",L)};let D=await M2($,{integrationID:n,methods:y1({beginLogin:Z.beginLogin??p1,version:q,vault:W}),onLogin:(U)=>T(U),label:"ChatGPT (openai-auth account pool)",vault:k1(W)});let y=await v1($);let x=new AbortController;(async()=>{try{for await(let U of $.event.subscribe({signal:x.signal}))if(U.type==="session.deleted")P.forgetSession(U.data.sessionID)}catch(U){if(!x.signal.aborted)X.warn("stopped listening for session deletion",{error:U instanceof Error?U.message:String(U)})}})();k=!0;return async()=>{b=!0,x.abort(),J?.dispose(),m.dispose(),await Promise.allSettled([C.dispose(),D.dispose(),y.dispose()]);let U;try{await Promise.race([Promise.all([J?.idle(),m.settled()]),new Promise((L)=>{U=setTimeout(L,ZY),U.unref?.()})])}finally{clearTimeout(U),H.release(),await d?.release()}}}catch(i){var p=i,l=1}finally{u1(f,p,l)}}var zY=v2(),_Z={id:F2,setup:zY.setup,server:H$.server};export{_Z as default,v2 as createOpenAIAuthPlugin,F2 as OPENAI_AUTH_PLUGIN_ID};
|
|
1
|
+
import{c as H$}from"../index-envpbt0k.js";import{C as b1,D as y1,F as n2,G as a2,H as s2,S as W$,Y as o2,Z as r2,aa as U$,d as e1,e as k2,f as G2,g as C2,h as z$,i as J$,j as X$,k as j$,l as w2,m as G$,n as Q$,o as R2,p as U1,q as C1,r as N1,s as F1,t as P1,u as T1,v as M1,w as B$,x as V$,y as W2,z as L1}from"../index-5dg931q0.js";import{$a as V1,$b as r1,Ba as l1,Ca as z1,Da as J1,Ea as X1,Ia as q1,Ib as E1,Ka as x1,Ma as c1,Na as d1,Oa as j1,Pb as w1,Ta as i1,Xa as G1,Ya as Q1,Zb as s1,_a as B1,_b as o1,ac as t1,cc as $$,dc as S1,eb as N2,kb as n1,lb as V2,mc as Y$,nc as K$,ob as a1,oc as Z$,pb as W1,pc as R1,qb as H1,sa as H2,ta as U2,ua as p1}from"../index-99esnzg0.js";import"../index-9reyazwh.js";import{nd as Z1}from"../index-yf6arn5w.js";import"../index-2hch7e8n.js";import"../index-jye6vccc.js";import"../index-egrty6tz.js";import{Vd as j2}from"../index-k4eacw7x.js";import"../index-dryydk6b.js";import"../index-45qgkb0m.js";import{te as g1,ue as u1}from"../index-bgq9d21h.js";class c extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function s($){return`common-auth-placeholder.${$}`}function c2($){let K=s($.integrationID);return{type:"oauth",methodID:$.methodID,access:K,refresh:K,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function J2($,K){if($?.type!=="oauth")return!1;let J=K===void 0?void 0:s(K),X=(j)=>J===void 0?j.startsWith("common-auth-placeholder."):j===J;return X($.access)&&X($.refresh)}var d2="No browser sign-in: this connects the plugin to the accounts in its vault.";async function M2($,K){let J=K.now??Date.now,{integrationID:X}=K,j=(T)=>c2({integrationID:X,methodID:T,now:J()}),B=async(T,O)=>{return await K.onLogin(T,{integrationID:X,methodID:O}),j(O)},R=(T)=>async(O)=>{let H=T.method.id,W=await T.authorize(O),y={url:W.url,instructions:W.instructions,...W.expiresAt===void 0?{}:{expiresAt:W.expiresAt}};if(W.mode==="auto")return{...y,mode:"auto",callback:W.callback.then((E)=>B(E,H))};let b=W.callback;return{...y,mode:"code",callback:async(E)=>B(await b(E),H)}};return $.integration.transform((T)=>{let O=K.label===void 0?{}:{label:()=>K.label};for(let y of K.methods)T.method.update({integrationID:X,method:y.method,authorize:R(y),refresh:async(b)=>{if(!J2(b,X))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return j(b.methodID)},...O});let H=K.vault;if(H===void 0)return;let W=H.method.id;T.method.update({integrationID:X,method:H.method,authorize:async()=>({url:"",instructions:H.instructions??d2,mode:"auto",callback:Promise.resolve().then(()=>H.activate({integrationID:X,methodID:W})).then(()=>j(W))}),refresh:async(y)=>{if(!J2(y,X)||y.methodID!==W)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return j(W)},...O})})}function P$($){let K=[],J;for(let X of $.split(/\r?\n/))if(X.startsWith("data:"))K.push(X.slice(5).replace(/^ /,""));else if(X.startsWith("event:"))J=X.slice(6).trim();if(K.length===0)return;return J===void 0?{data:K.join(`
|
|
2
|
+
`)}:{event:J,data:K.join(`
|
|
3
|
+
`)}}function L2($,K){let J=new TextDecoder,X="",j=(R)=>{let T=P$(R);if(!T)return;try{$(T)}catch(O){K(O)}},B=()=>{for(;;){let R=/\r?\n\r?\n/.exec(X);if(!R)return;let T=X.slice(0,R.index);X=X.slice(R.index+R[0].length),j(T)}};return new TransformStream({transform(R,T){T.enqueue(R),X+=J.decode(R,{stream:!0}),B()},flush(){if(X+=J.decode(),B(),X.trim()!=="")j(X);X=""}})}var i2=512,Y2="x-common-auth-attempt",e=($,K)=>JSON.stringify([$,K]),o=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function T$($){let K=$.headers;return typeof K==="object"&&K!==null}function M$($,K){let J=$.getReader();return new ReadableStream({async pull(X){let j;try{j=await J.read()}catch(B){K({reason:"failed",message:B instanceof Error?B.message:String(B)}),X.error(B);return}if(j.done)K(),X.close();else X.enqueue(j.value)},async cancel(X){K({reason:"cancelled",...X===void 0?{}:{message:String(X)}}),await J.cancel(X)}})}function _2($,K){for(let[J,X]of Object.entries(K)){let j=J.toLowerCase();for(let B of Object.keys($))if(B.toLowerCase()===j)delete $[B];if(X!==null)$[J]=X}}function L$($,K){for(let[J,X]of Object.entries(K))if(X===null)$.delete(J);else $.set(J,X)}async function q2($,K,J={}){let{providerID:X}=K,j=J.gateOnPlaceholder,B=(Y)=>j===void 0||j.credential(Y)===s(X),R=J.logger,T=Math.max(1,J.maxRecords??i2),O=[...J.hostCredentials??[s(X)],...j?[s(X)]:[]].filter((Y)=>Y!==""),H=new Map,W=new WeakMap,y=new Map,b=new Set,E=new Map,v=!1,f=!1,d=new Map,I=0,u=!1,g=new Map,h=(Y,Z)=>{try{R?.warn(Y,Z)}catch{}},z=(Y)=>Y instanceof Error?Y.message:String(Y),V=async(Y,Z)=>{let G=d.get(Y);if(!G||G.size===0)return;await Promise.all([...G].map(async(Q)=>{try{await Q(Z)}catch(M){h("opencode2 auth listener threw; the request is unaffected",{event:Y,error:z(M)})}}))},F=async(Y,Z)=>{try{await K.onAttemptEnd?.(Y,Z)}catch(G){h("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:Y.attemptId,error:z(G)})}},C=(Y,Z)=>{if(Y.ended||!Y.attempt)return;let G={...Y.status===void 0?{}:{status:Y.status},outputStarted:Y.outputStarted,...Y.limit?{limit:Y.limit.signal}:{},...Z?{error:Z}:{}};if(Z)Y.endError=Z;Y.ended=F(Y.attempt,G)},A=(Y,Z)=>C(Y,{reason:"abandoned",message:Z}),P=(Y)=>[...H.values()].filter((Z)=>Z.key===Y),D=(Y)=>P(Y).at(-1),k=(Y)=>{if(H.delete(Y.id),!P(Y.key).length)y.delete(Y.key)},q=(Y)=>{H.set(Y.id,Y);while(H.size>T){let Z=H.values().next().value;if(Z===void 0)break;A(Z,"dropped to keep the record bound"),k(Z)}},m=(Y)=>Y.accountId===void 0?void 0:{...Y.scope,accountId:Y.accountId},i=(Y,Z)=>new c({kind:"no-account",providerID:X,sessionID:Y.sessionID,requestKind:Y.kind,...Z===void 0?{}:{message:Z}}),l=(Y)=>{g.get(Y)?.clear(),g.delete(Y)},p=async(Y,Z)=>{let G=()=>i(Y,`${X} ${Y.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(u)throw G();let Q=g.get(Y.sessionID);if(!Q)Q=new Set,g.set(Y.sessionID,Q);let M={};Q.add(M);let x=()=>{if(!Q.has(M))throw G()};try{return await Z(x)}finally{if(Q.delete(M),Q.size===0&&g.get(Y.sessionID)===Q)g.delete(Y.sessionID)}},U=(Y,Z)=>{for(let[G,Q]of Z)if(O.some((M)=>Q.includes(M)))throw new c({kind:"host-credential-on-wire",providerID:X,sessionID:Y.sessionID,requestKind:Y.kind,message:`${X} ${Y.kind} request still carries the host's placeholder credential in ${G}; the adapter's account headers must replace it`})},L=(Y)=>{for(let Z of P(Y))if(Z.ended||!Z.attempt)k(Z);else if(Z.transport==="ws"||Z.judged)A(Z,"a newer attempt of its session and kind began"),k(Z)},S=async(Y,Z,G,Q)=>{let M=e(Y.sessionID,Y.kind),x=y.get(M);y.delete(M);let N=x?.accountId??D(M)?.accountId;L(M);let _={...Y,...N===void 0?{}:{previousAccountId:N},...x?.rerouteFrom===void 0?{}:{rerouteFrom:x.rerouteFrom}},w=await K.chooseAccount(_);G();let a={},p2;if(w!==void 0){let Q2=await K.accountHeaders({...Y,accountId:w});if(G(),T$(Q2))a=Q2.headers,p2=Q2.attempt;else a=Q2}let l2=`attempt-${++I}`,z2={id:l2,key:M,scope:Y,accountId:w,headers:a,attempt:w===void 0?void 0:{...Y,accountId:w,attemptId:l2,transport:Q,data:p2},...Q===void 0?{}:{transport:Q},outputStarted:!1};if(q(z2),z2.attempt)V("select",{...Y,accountId:z2.attempt.accountId,hook:Z,..._.previousAccountId===void 0?{}:{previousAccountId:_.previousAccountId},..._.rerouteFrom===void 0?{}:{rerouteFrom:_.rerouteFrom},handle:z2.attempt});return z2},Z2=async(Y,Z,G,Q,M)=>{let x=e(Y.sessionID,Y.kind),N=Q===void 0?void 0:H.get(Q);if(N?.key!==x)N=void 0;if(!N){if(N=D(x),P(x).filter((w)=>w.transport===void 0&&!w.ended).length>1&&!f)f=!0,h("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:Y.sessionID,kind:Y.kind})}if(!N||N.transport!==void 0||N.ended)N=await S(Y,Z,M,G);else if(N.transport=G,N.attempt)N.attempt.transport=G;if(G==="ws"){for(let _ of P(x))if(_!==N&&_.transport==="ws")A(_,"a newer attempt of its session and kind went out over WebSocket")}return N},$2=async(Y,Z)=>{try{return await Z()}catch(G){throw C(Y,{reason:"failed",message:z(G)}),G}},h2=(Y,Z)=>{let G=P(e(Y,Z)).filter((Q)=>Q.transport==="ws").at(-1);return G?.attempt!==void 0&&!G.ended?G:void 0},P2=(Y,Z,G)=>{let Q=m(Y);if(!Q||!Y.attempt||Y.limit)return;Y.limit={signal:Z,delivered:V("limit",{...Q,via:G,limit:Z,outputStarted:Y.outputStarted,handle:Y.attempt})}},v2=(Y,Z,G,Q)=>{let M=m(Y);if(!M||!Y.attempt)return;V("quota",{...M,transport:Z,...Q===void 0?{}:{status:Q},quota:G,handle:Y.attempt})},m2=(Y,Z,G,Q)=>{let M=Y.attempt;if(!M)return;let x=K.inspectEvent?.(Q===void 0?{transport:Z,data:G,attempt:M}:{transport:Z,data:G,event:Q,attempt:M});if(!x)return;if(x.quota!==void 0)v2(Y,Z,x.quota);if(x.outputStarted)Y.outputStarted=!0;if(x.limit)P2(Y,x.limit,Z);if(x.error!==void 0)C(Y,{reason:"failed",message:x.error});else if(x.done)C(Y)},C$=(Y,Z)=>{let G=Y.attempt;if(!G||Z.accountId===Y.accountId)return;if(G.reboundFrom??=G.accountId,G.accountId=Z.accountId,"data"in Z)G.data=Z.data;Y.accountId=Z.accountId},N$=(Y)=>!Y.attempt||Y.endError!==void 0||Y.status!==void 0&&Y.status>=400,F$=(Y)=>{let Z=[...H.values()].filter((_)=>_.scope.sessionID===Y),G=Z.filter((_)=>_.limit&&!_.rerouted).at(-1);if(G)return G;let Q=Z.filter((_)=>_.scope.kind==="primary"),M=Q.length>0?Q:Z;if(M.length<=1)return M[0];let x=M.filter((_)=>!_.judged&&N$(_)).at(-1);if(x)return x;let N=M.filter((_)=>_.attempt&&!_.ended);if(N.length>1)return"ambiguous";return N[0]??M.at(-1)},t={providerID:X},r=[];r.push(await $.session.hook("model.request",(Y)=>{if(j)return;return p(o(Y),async(Z)=>{let G=await S(o(Y),"model.request",Z);if(Z(),G.accountId===void 0)throw i(G.scope);_2(Y.headers,{...G.headers,[Y2]:G.id})})},t)),r.push(await $.session.hook("http.request",(Y)=>{if(j){let Z=B(Y.request.headers);if(E.set(Y.sessionID,Z),!Z)return}return p(o(Y),async(Z)=>{let G=Y.request.headers.get(Y2)??void 0,Q=j?await S(o(Y),"http.request",Z,"http"):await Z2(o(Y),"http.request","http",G,Z);Z();let M=m(Q),x=Q.attempt;if(!M||!x)throw i(Q.scope);await $2(Q,async()=>{let N=Y.request;if(K.rewriteRequest){if(G!==void 0){let a=new Headers(N.headers);a.delete(Y2),N=new Request(N,{headers:a})}N=await K.rewriteRequest({...M,request:N,attempt:x})??N,Z()}let _=new Headers(N.headers);_.delete(Y2),L$(_,Q.headers),U(Q.scope,_.entries());let w=new Request(N,{headers:_});W.set(w,Q),Y.request=w})})},t)),r.push(await $.session.hook("http.response",async(Y)=>{let Z=W.get(Y.request);if(!Z){if(j)return;if(!v)v=!0,h("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:Y.sessionID,kind:Y.kind});return}let G=Y.response;if(K.answeredBy&&Z.attempt){let _=Z.attempt,w=await $2(Z,async()=>K.answeredBy?.({request:Y.request,response:G,attempt:_}));if(w)C$(Z,w)}let Q=m(Z),M=Z.attempt;if(!Q||!M)return;Z.status=G.status;let x=K.quotaFromHeaders?.(G.headers,G.status,M);if(x!==void 0)v2(Z,"http",x,G.status);if(!G.ok&&K.limitFromResponse){let _=await K.limitFromResponse({status:G.status,headers:G.headers,body:()=>G.clone().text(),attempt:M});if(_)P2(Z,_,"http")}if(!G.ok||!G.body)C(Z);let N=G;if(G.body&&(K.inspectEvent||K.onAttemptEnd)){let _=G.body;if(K.inspectEvent)_=_.pipeThrough(L2((w)=>m2(Z,"http",w.data,w.event),(w)=>h("opencode2 auth event inspection threw",{error:z(w)})));N=new Response(M$(_,(w)=>C(Z,w)),{status:G.status,statusText:G.statusText,headers:G.headers})}if(K.rewriteResponse)N=await K.rewriteResponse({...Q,request:Y.request,response:N,attempt:M})??N;if(N!==G)Y.response=N},t)),r.push(await $.session.hook("experimental.ws.handshake",(Y)=>{if(j){let Z=B(new Headers(Y.headers)),G=e(Y.sessionID,Y.kind);if(E.set(Y.sessionID,Z),b.delete(G),!Z)return}return p(o(Y),async(Z)=>{let G;for(let N of Object.keys(Y.headers)){if(N.toLowerCase()!==Y2)continue;G??=Y.headers[N],delete Y.headers[N]}let Q=j?await S(o(Y),"experimental.ws.handshake",Z,"ws"):await Z2(o(Y),"experimental.ws.handshake","ws",G,Z);Z();let M=m(Q),x=Q.attempt;if(!M||!x)throw i(Q.scope);await $2(Q,async()=>{_2(Y.headers,Q.headers);let N=K.rewriteHandshakeURL?.({...M,url:Y.url,attempt:x});if(N!==void 0)Y.url=N;if(U(Q.scope,Object.entries(Y.headers)),j)b.add(Q.key)})})},t));let f2=K.rewriteWebSocketFrame?.bind(K);if(f2)r.push(await $.session.hook("experimental.ws.send",async(Y)=>{let Z=o(Y);if(j&&!b.has(e(Z.sessionID,Z.kind)))return;let G=h2(Z.sessionID,Z.kind),Q=await f2({...Z,attempt:G?.attempt,frame:Y.frame});if(Q!==void 0)Y.frame=Q},t));r.push(await $.session.hook("experimental.ws.receive",(Y)=>{if(j&&!b.has(e(Y.sessionID,Y.kind)))return;let Z=h2(Y.sessionID,Y.kind);if(!Z)return;try{m2(Z,"ws",Y.frame)}catch(G){h("opencode2 auth frame inspection threw",{error:z(G)})}},t)),r.push(await $.session.hook("retry",async(Y)=>{if(j&&E.get(Y.sessionID)!==!0)return;let Z=F$(Y.sessionID);if(!Z)return;let G=Y.decision;if(Z==="ambiguous"){await V("retry",{sessionID:Y.sessionID,attempt:Y.attempt,reason:"host-decides",hostDecision:G,decision:G});return}let Q=Z;await p(Q.scope,async(M)=>{Q.judged=!0;let x=G,N,_,w=Q.attempt;if(Q.accountId===void 0||!w)x={retry:!1},N="no-account";else if(Q.outputStarted)x={retry:!1},N="output-started";else{if(!Q.limit){let a=K.limitFromError?.(Y.error,w);if(a)P2(Q,a,"error")}if(Q.ended)await Q.ended,M();if(Q.limit)await Q.limit.delivered,M(),Q.rerouted=!0,_={accountId:Q.accountId,limit:Q.limit.signal},x={retry:!0,delay:0},N="reroute";else N="host-decides"}if(Y.decision=x,x.retry&&Q.accountId!==void 0)y.set(Q.key,{sessionID:Q.scope.sessionID,accountId:Q.accountId,..._===void 0?{}:{rerouteFrom:_}});await V("retry",{sessionID:Y.sessionID,...Q.accountId===void 0?{}:{accountId:Q.accountId},kind:Q.scope.kind,attempt:Y.attempt,reason:N,hostDecision:G,decision:x,...w===void 0?{}:{handle:w}})})},t));let g2=(Y)=>{l(Y),E.delete(Y);for(let Z of b)if(JSON.parse(Z)[0]===Y)b.delete(Z);for(let Z of[...H.values()]){if(Z.scope.sessionID!==Y)continue;A(Z,"its session was forgotten"),H.delete(Z.id)}for(let[Z,G]of y)if(G.sessionID===Y)y.delete(Z)},T2=new AbortController,u2=$.event;if(u2)(async()=>{try{for await(let Y of u2.subscribe({signal:T2.signal}))if(Y.type==="session.deleted")g2(Y.data.sessionID)}catch(Y){if(!T2.signal.aborted)h("opencode2 auth stopped listening for session deletion",{error:z(Y)})}})();return{on(Y,Z){let G=d.get(Y);if(!G)G=new Set,d.set(Y,G);let Q=Z;return G.add(Q),()=>{G.delete(Q)}},accountFor(Y,Z){return D(e(Y,Z))?.accountId},forgetSession:g2,get size(){return H.size},async dispose(){if(u)return;u=!0;for(let Y of g.keys())l(Y);T2.abort();for(let Y of H.values())A(Y,"the installation was disposed");H.clear(),y.clear(),b.clear(),E.clear(),d.clear(),await Promise.all(r.map(async(Y)=>{try{await Y.dispose()}catch(Z){h("opencode2 auth hook did not dispose cleanly",{error:z(Z)})}}))}}}var x2={version:a2,"user-agent":s2,originator:"codex_exec"},_$="x-openai-internal-codex-responses-lite",q$=1024,x$=/(?:^|\/)gpt-6-(?:astra|sol|luna)$/i,B2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($),E$=($)=>B2($)&&($.type==="message"||("role"in $))&&$.role==="user",S$=($)=>B2($)&&$.type==="configuration_update";class E2{#$=new Map;apply($,K,J){if(K.kind!=="primary")return!1;let X=typeof $.model==="string"?$.model:"";if(!o2.has(X))return!1;if(x$.test(X))return!1;let j=B2($.reasoning)?$.reasoning:void 0,B=typeof j?.effort==="string"?j.effort:void 0;if(!B)return!1;let R=this.#$.get(K.sessionID);if(R===void 0)return this.#Y(K.sessionID,B),!1;if(B===R)return!1;let T=Array.isArray($.input)?$.input:void 0;if(!T||T.length===0)return!1;let O=T.findLastIndex(E$);if(O<0){if(J==="http")return!1;return $.reasoning={...j,effort:R},!0}if($.reasoning={...j,effort:R},!S$(T[O-1]))T.splice(O,0,{type:"configuration_update",reasoning:{effort:B}});return!0}forget($){this.#$.delete($)}#Y($,K){this.#$.set($,K);while(this.#$.size>q$){let J=this.#$.keys().next().value;if(J===void 0)break;this.#$.delete(J)}}}function R$($){if(typeof $.model!=="string"||!n2.has($.model))return!1;return r2($),!0}function t2($){try{let K=JSON.parse($);return B2(K)?K:void 0}catch{return}}async function e2($,K,J,X){if($.method.toUpperCase()!=="POST"||$.body===null)return;if(!/\/responses\/?$/.test(new URL($.url).pathname))return;let j=t2(await $.clone().text());if(!j)return;let B="max_output_tokens"in j;delete j.max_output_tokens;let R=J.apply(j,K,"http"),T=X&&R$(j);if(!B&&!R&&!T)return;let O=new Headers($.headers);if(O.delete("content-length"),T)O.set(_$,"true");return new Request($,{headers:O,body:JSON.stringify(j)})}function $1($,K,J){let X=t2($);if(X?.type!=="response.create")return;let j="max_output_tokens"in X;delete X.max_output_tokens;let B=J.apply(X,K,"ws");return j||B?JSON.stringify(X):void 0}function A$($){return $.replace(/\/responses\/?$/,"").replace(/\/$/,"")}function S2($,K){let J=new URL($);if(J.origin!=="https://api.openai.com"&&J.origin!=="wss://api.openai.com"||!/\/responses\/?$/.test(J.pathname))return $;let X=new URL(`${A$(K)}/responses`);if(X.search=J.search,J.protocol==="ws:"||J.protocol==="wss:")X.protocol=X.protocol==="https:"?"wss:":"ws:";return X.href}var n="openai",D$=60000,Y1=1,O$="request refused: no account with a usable credential",b$=1024,K2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function A2($){try{return JSON.parse($)}catch{return}}function K1($){let K=H2($);return K?U2(K):void 0}var y$=new Set(["usage_limit_reached","rate_limit_exceeded"]);function D2($,K,J){return{reason:$.window,...J!==void 0?{status:J}:{},...$.resetAt!==void 0?{retryAfterMs:Math.max(0,$.resetAt-K)}:{}}}function k$($,K){let J=W2($);if(J){let B=typeof $.status==="number"?$.status:void 0;return D2(J,K,B)}if($.type!=="response.failed"||!K2($.response))return;let X=$.response.failed;if(K2(X)&&typeof X.rate_limit_reached_type==="string")return{reason:X.rate_limit_reached_type};let j=$.response.error;if(K2(j)){let B=typeof j.code==="string"?j.code:typeof j.type==="string"?j.type:void 0;if(B&&y$.has(B))return{reason:B}}return}function w$($,K){let J=A2($);if(!K2(J))return;let X=typeof J.type==="string"?J.type:void 0;if(X==="codex.rate_limits")return{quota:{snapshot:X1(J),complete:!0}};let j=k$(J,K);if(j)return{limit:j};if(X===void 0||X==="error")return;return L1(X)?void 0:{outputStarted:!0}}function I$($){let K=!1;for(let J of $.keys())if(J.toLowerCase().startsWith("x-codex-")){K=!0;break}if(!K)return;return{snapshot:z1($),complete:J1($)}}function h$($){let K=$.get("retry-after");if(K===null)return;let J=Number(K);return Number.isFinite(J)&&J>=0?J*1000:void 0}function _1($){let{source:K,pins:J}=$,X=$.now??Date.now,j=$.log,B=$.vault,R=new E2,T=new Map,O=(z)=>`${z.sessionID}\x00${z.kind}\x00${z.accountId}`,H=new Map,W=new Map,y=(z,V)=>{W.delete(z),W.set(z,V);while(W.size>b$){let F=W.keys().next().value;if(F===void 0)break;W.delete(F)}},b=(z,V,F)=>{let C=F?[]:M1(K.peek().rows,z,V,B?.identities()??new Set),A=(B?.routes()??[]).filter((P)=>P.kind==="oauth"&&G1(V2(P.quota),z,V));return[...C.map((P)=>({id:P.id,...P.identity!==void 0?{identity:P.identity}:{},quota:P.quota,row:P})),...A.map((P)=>({id:P.id,...P.identity!==void 0?{identity:P.identity}:{},quota:P.quota}))]},E=(z,V,F)=>{let C=new Map;if(Q1(V))for(let q of z)C.set(q.id,V1(V2(q.quota),V,q.id===R2?void 0:q.id,F));let A=z.map((q)=>({id:q.id,kind:"oauth",...Z1(q.quota)?{quota:q.quota}:{}})),P=z.flatMap((q)=>q.row?[q.row]:[]),D=new Set(z.filter((q)=>!q.row).map((q)=>q.id)),k=K.rateLimitMarks(P);for(let q of D){let m=H.get(q);if(m===void 0)continue;if(m<=F)H.delete(q);else k.set(q,m)}return{rows:A,now:F,rateLimitMarks:k,refreshBackoff:K.refreshBackoffFor(P),killswitch:C,requestPull:(q)=>D.has(q)?B?.requestReading(q):K.requestReading(q)}},v=(z,V,F,C)=>{let A=N1({...z,placement:U1(V)});if(A.kind==="block"){j?.debug("pool admission refused the request",{reason:A.block.reason});return}let P=A.order.filter((D)=>!F.has(D));if(C!==void 0&&P.includes(C))return C;return P[0]},f=(z,V,F,C,A,P)=>{let D={requestBytes:Y1,reservePercent:(U)=>B1(F,U===R2?void 0:U),resetCredits:()=>{return}},k=F1(z),q=(U,L)=>J.place({sessionId:C,requestBytes:Y1,validPinnedAccountIds:z.rows.map((S)=>S.id).filter((S)=>!k.excluded.has(S)),excludeAccountIds:U,quotaCheckedAtByAccount:Object.fromEntries(z.rows.map((S)=>[S.id,k.projections.get(S.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(V.map((S)=>[S.id,S.identity])),select:(S)=>P1(z,D,new Set(U),S),persist:L}),m=[...A],i=q(m,P);if(!i)return;let l=i.accountId,p=T1(z,D,l);if(p.kind==="none")return;if(p.kind==="move"){let U=q([...m,l],P);if(U)return U.accountId;return p.reason==="killswitch"?void 0:l}if(p.kind==="detour")return q([...m,l],!1)?.accountId;return l},u={providerID:n,chooseAccount:async(z)=>{let V=await B?.authority(),F=await $.storage(),C=V!==void 0&&V!=="local",A=()=>{throw new c({kind:"no-account",providerID:n,sessionID:z.sessionID,requestKind:z.kind,message:C2})};if(C)await $.awaitVaultRoster?.();else{if(!(await K.current()).active){if(await $.slotPlaceholderWithoutMain?.())A();j?.warn("the account pool does not serve requests yet; refusing the request",{kind:z.kind});return}await K.prepareTokens(K.peek().rows,F)}let P=X(),D=b(F,P,C),k=C1(E(D.filter((S)=>S.id!==z.rerouteFrom?.accountId),F,P));if(k)await k,P=X(),D=b(F,P,C);let q=new Map(D.map((S)=>[S.id,S])),m=E(D,F,P),i=new Set(z.rerouteFrom?[z.rerouteFrom.accountId]:[]),l=F?.routing?.mode??"main-first",p=z.kind==="primary",U=new Set,L;for(;;){let S=new Set([...i,...U]);if(L=void 0,l==="sticky-balanced")L=f(m,D,F,z.sessionID,S,p&&U.size===0);if(L??=v(m,l,S,p?void 0:W.get(z.sessionID)),L===void 0||U.has(L)){L=void 0;break}let Z2=q.get(L)?.row;if(Z2){if(K.usableToken(Z2)!==void 0)break;j?.debug("pool row holds no usable token; choosing again",{accountId:L})}else{if(!B)break;let $2=await B.authorize(L);if($2){T.set(O({...z,accountId:L}),$2);break}j?.debug("the vault refused to serve an account; choosing again",{accountId:L})}U.add(L)}if(L===void 0&&!C&&D.length===0&&await $.slotPlaceholderWithoutMain?.())A();if(L===void 0&&C&&B&&(D.length===0||U.size>0)){let S=U.size>0?"vault-refused":H1(B);throw j?.warn("vault mode: no vault account can serve; refusing the request",{cause:S}),new c({kind:"no-account",providerID:n,sessionID:z.sessionID,requestKind:z.kind,message:W1[S]})}if(L!==void 0&&p)y(z.sessionID,L);return j?.debug("pool account chosen",{kind:z.kind,accountId:L,mode:l,...z.rerouteFrom?{rerouteFrom:z.rerouteFrom.accountId}:{}}),L},accountHeaders:async(z)=>{let{accountId:V}=z,F=()=>new c({kind:"no-account",providerID:n,sessionID:z.sessionID,requestKind:z.kind,message:O$}),C=B&&await B.authority()!=="local"?void 0:K.peek().rows.find((D)=>D.id===V);if(!C&&B){let D=O(z),k=T.get(D)??await B.authorize(V);if(T.delete(D),!k)throw j?.warn("the vault refused to serve an account; refusing the request",{accountId:V}),F();return{headers:{...x2,"session-id":z.sessionID,authorization:`Bearer ${k.accessToken}`,"chatgpt-account-id":k.accountIdentity??K1(k.accessToken)??null},attempt:{kind:"vault",routeId:V,receipt:k}}}let A=C?K.usableToken(C):void 0;if(!C||!A)throw j?.warn("pool row holds no usable token; refusing the request",{accountId:V}),F();let P=C.identity??K1(A);return{headers:{...x2,"session-id":z.sessionID,authorization:`Bearer ${A}`,"chatgpt-account-id":P??null},attempt:{kind:"pool",token:A,credentialEpoch:C.credentialEpoch}}},async rewriteRequest({request:z,sessionID:V,kind:F}){let C=$.codexEndpoint?S2(z.url,$.codexEndpoint()):z.url,A=C===z.url?z:new Request(C,z);return await e2(A,{sessionID:V,kind:F},R,$.responsesLite?.()??!1)??A},rewriteHandshakeURL:({url:z})=>$.codexEndpoint?S2(z,$.codexEndpoint()):void 0,rewriteWebSocketFrame:({frame:z,sessionID:V,kind:F})=>$1(z,{sessionID:V,kind:F},R),quotaFromHeaders:(z)=>I$(z),async limitFromResponse({status:z,headers:V,body:F}){if(z<400)return;let C=A2(await F().catch(()=>"")),A=W2({...K2(C)?C:{},status:z});if(!A)return;let P=X(),D=D2(A,P,z);if(D.retryAfterMs!==void 0)return D;let k=h$(V);return k===void 0?D:{...D,retryAfterMs:k}},inspectEvent:({data:z})=>w$(z,X()),limitFromError(z){let V=A2(z.message),F=W2({...K2(V)?V:{},...z.status!==void 0?{status:z.status}:{}})??(z.message.includes("usage_limit_reached")?{window:"usage_limit_reached"}:void 0);return F?D2(F,X(),z.status):void 0},async onAttemptEnd(z,V){let F=z.data;if(F?.kind!=="vault"||V.status!==401)return;j?.warn("a vault account answered 401; reporting it to the vault",{accountId:z.accountId}),await B?.reportFailure(F.receipt,401)}},g=(z,V,F)=>{let C=F.data;if(C?.kind==="vault"){B?.recordSnapshot(z,V.snapshot,V.complete,C.receipt);return}if(C?.kind!=="pool")return;if(K.peek().rows.find((P)=>P.id===z)?.credentialEpoch!==C.credentialEpoch){j?.debug("quota reading dropped: the row holds another credential",{accountId:z});return}K.recordSnapshot(z,V.snapshot,C.token,V.complete)},h=(z,V,F)=>{let C=X(),A=F.data?.kind==="vault",P=A?B?.routes().find((q)=>q.id===z)?.quota:K.peek().rows.find((q)=>q.id===z)?.quota,D=j1(V2(P),V.reason,C,D$,V.retryAfterMs!==void 0?C+V.retryAfterMs:void 0);if(!A){K.markRateLimited(z,D);return}let k=H.get(z);if(k===void 0||k<D)H.set(z,D)};return{adapter:u,attach(z){z.on("quota",(V)=>g(V.accountId,V.quota,V.handle)),z.on("limit",(V)=>{h(V.accountId,V.limit,V.handle),j?.debug("pool row refused the request",{accountId:V.accountId,via:V.via,reason:V.limit.reason,outputStarted:V.outputStarted})})},forgetSession(z){J.forget(z),W.delete(z),R.forget(z)}}}var v$="openai-auth-pool-browser",m$="openai-auth-pool-headless",f$="openai-auth-vault",g$="Vault login requires this OpenCode host to be enrolled in the Claustrum vault. Connect to the vault or disconnect this host before trying again.";async function X2($){if(await $.authority()!=="local")throw Error("This host is connected to the credential vault or its enrollment is unreadable; the login was not stored. Disconnect this host from the vault to add a local login.")}function A1($){return{method:{id:f$,type:"oauth",label:"ChatGPT accounts in the vault"},async activate(){if(await q1($.paths,$.name)!=="vault")throw Error(g$)}}}function D1($){let K=(J,X,j)=>({method:{id:J,type:"oauth",label:X},async authorize(){if($.vault)await X2($.vault);let B=await $.beginLogin({version:$.version,headless:j});return{url:B.url,instructions:B.instructions,mode:"auto",callback:B.completion}}});return[K(v$,"ChatGPT (openai-auth pool, browser)",!1),K(m$,"ChatGPT (openai-auth pool, headless)",!0)]}function O2($){let K=(J)=>typeof J==="string"?J:"";return J2({type:"oauth",access:K($.access),refresh:K($.refresh)})||$.refresh===S1||x1($)}function u$($){if($.accountId)return $.accountId;let K=$.access?H2($.access):void 0;return K?U2(K):void 0}async function O1($,K,J,X={}){if(X.vault)await X2(X.vault);if(O2(J))throw Error("the credential is not a ChatGPT login (a placeholder or a tombstone); it was not stored");let j=E1($,{rowLocks:(E)=>R1(K,E)}),B=await j.read();if(B.status!=="ready")throw Error(`the account pool cannot be read (${B.status}); the login was not stored`);let R={type:"oauth",refresh:J.refresh,...J.access!==void 0?{access:J.access}:{},...J.expires!==void 0?{expires:J.expires}:{}},T=u$(J);if(X.vault)await X2(X.vault);let O=T!==void 0?{identity:T}:{};if(X.origin==="import"){let E=B.rows.find((v)=>T!==void 0&&v.identity===T||v.credential?.type==="oauth"&&v.credential.refresh===J.refresh);if(E)return{id:E.id,operation:"kept"}}let H=B.rows.filter((E)=>E.type==="oauth"&&!E.invalid),W=T?H.find((E)=>E.identity===T):void 0,y=B.rows.find((E)=>E.id===N2);if(W)return{id:(await j.replace(W.id,R,O)).id,operation:"replaced"};if(!y){let E=await j.add({id:N2,credential:R,...O,...J.label!==void 0?{label:J.label}:{}});return{id:E.id,operation:E.outcome==="added-disabled"?"added-disabled":"added"}}if(!y.invalid&&!y.credential)return{id:(await j.replace(N2,R,O)).id,operation:"replaced"};let b=await j.add({id:J.id,credential:R,...O,...J.label!==void 0?{label:J.label}:{}});return{id:b.id,operation:b.outcome==="added-disabled"?"added-disabled":b.outcome==="rotated"?"replaced":"added"}}function p$($){if(!b1($.modelID??$.id)){$.enabled=!1;return}let K=y1($.id);if(K)$.limit={...K}}function k1($){return $.model.transform((K)=>{for(let J of K.list(n))K.update(n,String(J.id),(X)=>p$(X))})}import{resolve as I1}from"node:path";var l$=1024;class b2{pins=new Map;limit;constructor($=l$){this.limit=Math.max(1,$)}get($){return this.pins.get($)?.accountId}forget($){this.pins.delete($)}get size(){return this.pins.size}set($,K){this.pins.delete($),this.pins.set($,K);while(this.pins.size>this.limit){let J=this.pins.keys().next().value;if(J===void 0)break;this.pins.delete(J)}}place($){return w1(this.pins,$,(K,J)=>this.set(K,J))}}var h1=Symbol.for("@cortexkit/openai-auth/opencode2-pins"),v1=globalThis,y2=v1[h1]??new Map;v1[h1]=y2;function m1($){let K=JSON.stringify([I1($.configPath),I1($.statePath)]),J=y2.get(K);if(!J)J=new b2,y2.set(K,J);return J}var F2="cortexkit-openai-auth",c$=5000;async function f1($,K,J){let X=new Map,j=new Map,B=(H)=>{j.delete(H);for(let W of X.keys())if(W.startsWith(`${H}:`))X.delete(W)},T=await q2({session:{hook:(H,W,y)=>$.session.hook(H,async(b)=>{let E=H==="http.request"?b:void 0,v=H==="experimental.ws.handshake"?b:void 0,d=(E?E.request.headers:v?new Headers(v.headers):void 0)?.get("authorization")===`Bearer ${s(K.providerID)}`;try{await W(b)}catch(I){if(d&&!(I instanceof c))throw o1(I);throw I}if(E||v){let I=E??v;if(!I)return;let g=(E?E.request.headers:new Headers(I.headers)).get("authorization")?.replace(/^Bearer /,"");if(d&&g)j.set(I.sessionID,g);else j.delete(I.sessionID);if(v){let h=`${v.sessionID}:${v.kind}`;if(d&&g)X.set(h,g);else X.delete(h)}if(j.size>512){let h=j.keys().next().value;if(h)j.delete(h)}if(X.size>512){let h=X.keys().next().value;if(h)X.delete(h)}}else if(H==="experimental.ws.receive"){let I=b,u=X.get(`${I.sessionID}:${I.kind}`);if(u)I.frame=r1(I.frame,u)}else if(H==="retry"){let I=b,u=j.get(I.sessionID);if(u)Object.assign(I.error,{message:s1(I.error.message,u)})}},y)},event:{subscribe:(H)=>async function*(){for await(let W of $.event.subscribe(H)){if(W.type==="session.deleted")B(W.data.sessionID);yield W}}()}},{...K,rewriteResponse:async(H)=>{let W=await K.rewriteResponse?.(H)??H.response;return t1(W,H.request.headers.get("authorization")?.replace(/^Bearer /,""),"event-stream")}},{gateOnPlaceholder:{credential:(H)=>{let W=H.get("authorization");return W?.startsWith("Bearer ")?W.slice(7):void 0}},logger:{warn:(H,W)=>J.warn(H,{data:W})}}),O=T.dispose;return{...T,dispose:async()=>{j.clear(),X.clear(),await O()}}}function I2($={}){return{id:F2,setup:(K)=>d$(K,$)}}async function d$($,K={}){let m=[];try{let J=j2("opencode2");let X=j2("quota");let j=K.paths??(()=>$$(e1()));let B=K.fetch??fetch;let R=K.version??J$;let T=K.poolMigration??W$;if(!T&&!G2(j().configPath)){J.info("openai-auth stands aside on OpenCode 2: this install has not moved into the account pool and the migration is switched off, so OpenCode 2 serves its own ChatGPT login");let U=(S)=>{throw new c({kind:"no-account",providerID:n,sessionID:S.sessionID,requestKind:S.kind,message:C2})},L=await f1($,{providerID:n,chooseAccount:U,accountHeaders:U},J);return()=>L.dispose()}let O=K.vault?.firstRosterWaitMs??j$;let H=V$({host:"opencode",stateDir:K.vault?.stateDir??a1(j().statePath),reservedRouteIds:()=>f.peek().rows.map((U)=>U.id),...K.vault?.connectionFile?{connectionFile:K.vault.connectionFile}:{},...K.vault?.connectScoped?{connectScoped:K.vault.connectScoped}:{},...K.vault?.connectEnrollment?{connectEnrollment:K.vault.connectEnrollment}:{},...K.vault?.pollIntervalMs!==void 0?{pollIntervalMs:K.vault.pollIntervalMs}:{},fetchImpl:()=>B},j());let W=H.vault;let y=!1;let b=!1;const E=g1(m,{[Symbol.dispose](){if(!y)H.release()}},0);await W.authority();let v=H.firstRoster;let f=new G$({paths:j,refreshProvider:async(U)=>{let L=await c1({refreshToken:U.refresh,fetchImpl:B,now:Date.now}),S=p1({id_token:"",access_token:L.access,refresh_token:L.refresh});return{...L,...S?{identity:S}:{}}},pullQuota:async(U)=>{let L=U.credential;if(L.type!=="oauth"||!L.access)throw Error("the row holds no access token to poll with");let S=await d1({accessToken:L.access,fetchImpl:B,now:Date.now,...U.identity?{accountId:U.identity}:{},accountKey:U.id,logger:X});return n1(S,Date.now(),!0)},vaultIdentities:()=>W.identities(),vaultMode:()=>W.enrolled(),vaultAuthority:()=>W.authority(),vaultFirstRoster:v,vaultFirstRosterBackgroundWaitMs:O,log:j2("pool")});await f.load();let d=K.heartbeat===!1?void 0:await B$({version:R,logger:j2("heartbeat")});let I=K.fence??(()=>z$({currentVersion:R}));let u=K.slot??H$();let g=async()=>Y$(j(),await u.get({path:{id:"openai"}}));let h=!1;let z=T?Q$({paths:j,slot:u,version:R,fence:I,runDeps:{vaultServes:()=>W.serves()},paused:async()=>await W.authority()!=="local",migrate:async(U)=>{let L=await K$(U);if(h=L.status==="refused",!b)await f.load();return L},adopt:async(U)=>{if(b)return{status:"retry",reason:"unsettled"};if(!await w2(v,O))return{status:"retry",reason:"vault-roster-pending"};if(b)return{status:"retry",reason:"unsettled"};let L=await Z$(U);if(!b)await f.load();return L}}):void 0;z?.start();H.start();let V=m1(j());let F=_1({source:f,slotPlaceholderWithoutMain:g,storage:()=>i1(j()),pins:V,vault:W,awaitVaultRoster:async()=>{await w2(W.awaitRequestRoster(),X$)},responsesLite:()=>k2().responsesLite,codexEndpoint:()=>k2().codexApiEndpoint,log:J});let C=await f1($,F.adapter,J);F.attach(C);let A=async(U)=>{if(await X2(W),G2(j().configPath))return;if(await z?.idle(),G2(j().configPath))return;if(h&&!O2(U)&&(await I()).open){await f.poolStore().initialize();return}throw Error("OpenAI accounts move to the shared account pool once every OpenCode process on this machine runs this version of openai-auth; the login was not stored. Update or close the older processes and sign in again.")};let P=async(U)=>{await A(U);let L=await O1(f.poolStore(),j(),U,{vault:W});if(!G2(j().configPath))await z?.requestAdoption();await f.load(),J.info("ChatGPT login stored in the account pool",L)};let D=await M2($,{integrationID:n,methods:D1({beginLogin:K.beginLogin??l1,version:R,vault:W}),onLogin:(U)=>P(U),label:"ChatGPT (openai-auth account pool)",vault:A1(W)});let k=await k1($);let q=new AbortController;(async()=>{try{for await(let U of $.event.subscribe({signal:q.signal}))if(U.type==="session.deleted")F.forgetSession(U.data.sessionID)}catch(U){if(!q.signal.aborted)J.warn("stopped listening for session deletion",{error:U instanceof Error?U.message:String(U)})}})();y=!0;return async()=>{b=!0,q.abort(),z?.dispose(),f.dispose(),await Promise.allSettled([C.dispose(),D.dispose(),k.dispose()]);let U;try{await Promise.race([Promise.all([z?.idle(),f.settled()]),new Promise((L)=>{U=setTimeout(L,c$),U.unref?.()})])}finally{clearTimeout(U),H.release(),await d?.release()}}}catch(i){var l=i,p=1}finally{u1(m,l,p)}}var i$=I2(),jK={id:F2,setup:i$.setup,server:U$.server};export{jK as default,I2 as createOpenAIAuthPlugin,F2 as OPENAI_AUTH_PLUGIN_ID};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-openai-auth",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.4",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
},
|
|
11
11
|
"main": "./dist/index.js",
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
|
+
"bin": {
|
|
14
|
+
"opencode-openai-auth": "./dist/bin.js"
|
|
15
|
+
},
|
|
13
16
|
"exports": {
|
|
14
17
|
".": {
|
|
15
18
|
"import": "./dist/index.js",
|
|
@@ -43,7 +46,7 @@
|
|
|
43
46
|
"LICENSE"
|
|
44
47
|
],
|
|
45
48
|
"scripts": {
|
|
46
|
-
"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 --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --minify && bun run build:types && bun run build:tui",
|
|
49
|
+
"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",
|
|
47
50
|
"build:tui": "bun scripts/build-tui.ts",
|
|
48
51
|
"build:types": "cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native",
|
|
49
52
|
"build:dev": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
@@ -63,15 +66,17 @@
|
|
|
63
66
|
},
|
|
64
67
|
"devDependencies": {
|
|
65
68
|
"@ai-sdk/openai": "3.0.88",
|
|
66
|
-
"@cortexkit/
|
|
67
|
-
"@cortexkit/common-auth": "^0.14.2",
|
|
69
|
+
"@cortexkit/common-auth": "^0.17.0",
|
|
68
70
|
"@cortexkit/openai-auth-core": "workspace:*",
|
|
69
|
-
"@opencode/plugin": "2.0.
|
|
71
|
+
"@opencode/plugin": "2.0.27"
|
|
70
72
|
},
|
|
71
73
|
"dependencies": {
|
|
72
|
-
"@
|
|
73
|
-
"@
|
|
74
|
-
"
|
|
74
|
+
"@cortexkit/claustrum-client": "^0.9.0",
|
|
75
|
+
"@cortexkit/private-files": "^0.2.1",
|
|
76
|
+
"@cortexkit/subc-client": "^0.16.0",
|
|
77
|
+
"@opentui/core": ">=0.6.1",
|
|
78
|
+
"@opentui/solid": ">=0.6.1",
|
|
79
|
+
"ai": "^7.0.137",
|
|
75
80
|
"jsonc-parser": "^3.3.1",
|
|
76
81
|
"solid-js": "1.9.12"
|
|
77
82
|
}
|
|
@@ -14,11 +14,19 @@ export {
|
|
|
14
14
|
} from "./shared/3c2d4169d00f907e-tui-support.js";
|
|
15
15
|
const LEVELS = ["error", "warn", "info", "debug", "trace"];
|
|
16
16
|
export function getLogFile() {
|
|
17
|
-
return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE ?? join(tmpdir(), "opencode-openai-auth.log");
|
|
17
|
+
return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE ?? (process.platform === "win32" ? join(tmpdir(), "opencode-openai-auth", "opencode-openai-auth.log") : join(tmpdir(), "opencode-openai-auth.log"));
|
|
18
18
|
}
|
|
19
19
|
export function getEnvLogLevel() {
|
|
20
20
|
const env = process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;
|
|
21
21
|
return env && LEVELS.includes(env) ? env : void 0;
|
|
22
22
|
}
|
|
23
23
|
initLogger({ file: getLogFile, level: getEnvLogLevel });
|
|
24
|
-
process.
|
|
24
|
+
process.once("beforeExit", async () => {
|
|
25
|
+
try {
|
|
26
|
+
await flushLogs();
|
|
27
|
+
} catch {
|
|
28
|
+
process.emitWarning("OpenAI auth could not flush its log file at shutdown");
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
if (process.platform !== "win32")
|
|
32
|
+
process.on("exit", () => flushLogs());
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isQuotaMap } from "./905bffc0220f43d0-map.js";
|
|
1
|
+
import { decodeQuotaMap, isQuotaMap } from "./905bffc0220f43d0-map.js";
|
|
2
2
|
import { mergeQuotaObservation } from "./4f36d333d081d040-merge.js";
|
|
3
3
|
/**
|
|
4
4
|
* The quota codec the account-pool store (the `/store` subpath) takes when it
|
|
@@ -8,5 +8,6 @@ import { mergeQuotaObservation } from "./4f36d333d081d040-merge.js";
|
|
|
8
8
|
*/
|
|
9
9
|
export const quotaCodec = Object.freeze({
|
|
10
10
|
validate: isQuotaMap,
|
|
11
|
+
decode: decodeQuotaMap,
|
|
11
12
|
merge: mergeQuotaObservation,
|
|
12
13
|
});
|
|
@@ -2,8 +2,13 @@ import { readFileSync, realpathSync, statSync, watch, } from "node:fs";
|
|
|
2
2
|
import { readFile, stat } from "node:fs/promises";
|
|
3
3
|
import { basename, dirname, join, resolve } from "node:path";
|
|
4
4
|
import { clearTimeout, setTimeout } from "node:timers";
|
|
5
|
+
import { PrivateFileError, readPrivateText, windowsPrivateFiles, } from "./375d9cca2def037d-private-files.js";
|
|
5
6
|
function canonicalPath(file) {
|
|
6
7
|
const path = resolve(file);
|
|
8
|
+
// Leave reparse points in the path for private-files' ancestor walk to reject;
|
|
9
|
+
// realpath would follow them before the security backend saw the original path.
|
|
10
|
+
if (windowsPrivateFiles)
|
|
11
|
+
return path;
|
|
7
12
|
try {
|
|
8
13
|
return realpathSync(path);
|
|
9
14
|
}
|
|
@@ -34,7 +39,9 @@ export function watchTuiPreferences(file, onChange, options = {}) {
|
|
|
34
39
|
if (shared)
|
|
35
40
|
return shared.subscribe(onChange);
|
|
36
41
|
const name = basename(path);
|
|
37
|
-
const read =
|
|
42
|
+
const read = windowsPrivateFiles
|
|
43
|
+
? (file) => readPrivateText(file)
|
|
44
|
+
: (options.fs?.readFile ?? ((file) => readFile(file, 'utf8')));
|
|
38
45
|
const probe = options.fs?.stat ?? stat;
|
|
39
46
|
let timer = null;
|
|
40
47
|
let pollTimer = null;
|
|
@@ -43,14 +50,15 @@ export function watchTuiPreferences(file, onChange, options = {}) {
|
|
|
43
50
|
// Seed synchronously so an immediate write cannot be absorbed as the baseline.
|
|
44
51
|
// The metadata is recorded only together with contents that were read, as in
|
|
45
52
|
// the probe below: if the first read fails, the probe keeps trying.
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
53
|
+
if (!windowsPrivateFiles)
|
|
54
|
+
try {
|
|
55
|
+
const metadata = identity((options.fs?.statSync ?? statSync)(path));
|
|
56
|
+
lastSeen = (options.fs?.readFileSync ?? ((file) => readFileSync(file, 'utf8')))(path);
|
|
57
|
+
lastMetadata = metadata;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
// Missing or unreadable files are picked up by the probe later.
|
|
61
|
+
}
|
|
54
62
|
let disposed = false;
|
|
55
63
|
const subscribers = new Set();
|
|
56
64
|
let checking = Promise.resolve();
|
|
@@ -68,7 +76,15 @@ export function watchTuiPreferences(file, onChange, options = {}) {
|
|
|
68
76
|
lastMetadata = null;
|
|
69
77
|
return;
|
|
70
78
|
}
|
|
71
|
-
const text = await read(path).catch(() =>
|
|
79
|
+
const text = await read(path).catch((error) => {
|
|
80
|
+
if (error instanceof PrivateFileError && error.code !== 'ENOENT') {
|
|
81
|
+
if (options.onError)
|
|
82
|
+
options.onError(error);
|
|
83
|
+
else
|
|
84
|
+
process.emitWarning(error.message, error.name);
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
});
|
|
72
88
|
if (disposed)
|
|
73
89
|
return;
|
|
74
90
|
// Record the metadata only once its contents were read. A failed read
|