sidekick-agent-hub 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,6 +8,11 @@ Sidekick CLI reads from `~/.config/sidekick/` — the same data files the [VS Co
8
8
 
9
9
  ## What's New
10
10
 
11
+ - **Usage reports from session logs** — `sidekick daily`, `weekly`, `monthly`, and `sessions` compute tokens and cost for every provider straight from session logs (local calendar days, `--breakdown`, `--by-project`, `--csv`, `--json`), so CLI-only users no longer need the extension's history store; `sidekick import` backfills that store when you want `stats` and `today` to see older sessions.
12
+ - **`sidekick blocks`** — five-hour billing blocks with cache-inclusive totals, cost provenance, burn rate, and end-of-block projections, with the official status-line sample beside the local estimate.
13
+ - **Official quota through the status line** — `sidekick statusline` reads the JSON Claude Code pipes on stdin, appends context %, session cost, and cache hit rate, and persists the official limits; `quota`, `quota --all`, and `mcp get_quota_status` share one resolution order and print a `Source` row naming where the numbers came from.
14
+ - **`state.json`** — a public, versioned snapshot (account, quota with freshness, context, session cost, active billing block) written by `statusline` and the dashboard for tmux status bars and scripts.
15
+ - **Scripting flags** — global `--offline` and `--output-file`, `--csv` on `stats`, `dump --list`, and `quota history`, `quota history --window 5h|7d|max`, and `--json` on the quick-capture commands and `report`; every token total is cache-inclusive and every cost carries its provenance.
11
16
  - **`sidekick history`** — list your most recent Codex prompts across every workspace, newest first; `--path <id-or-prefix>` resolves a session to its transcript file for `less`/`jq`, and `--json` emits full ids and timestamps. `sidekick dump --list` and the session picker now read a cheap preview index with a `--limit` bound (default 50), so huge session histories list quickly.
12
17
  - **`sidekick statusline`, `today` & `doctor`** — a cache-only one-line account/quota/burn footer, a cache-only daily brief, and cross-provider health diagnostics.
13
18
  - **Quick capture** — `sidekick tasks add`, `tasks done`, `note add`, and `decision add` write straight to the shared project stores with atomic merges.
@@ -50,20 +55,22 @@ If `sqlite3` is missing or not executable in the current shell environment, Side
50
55
 
51
56
  ```bash
52
57
  sidekick dashboard [options]
53
- sidekick tasks|decisions|notes|stats|quota|status|account|handoff|search|context|extract [options]
58
+ sidekick tasks|decisions|notes|stats|import|blocks|daily|weekly|monthly|sessions|quota|status|account|handoff|search|context|extract [options]
54
59
  sidekick today|doctor|statusline|mcp [options]
55
60
  sidekick tasks add|tasks done|note add|decision add [args]
56
61
  ```
57
62
 
58
63
  The standalone commands open the dashboard directly to a specific panel or run a one-shot query. All accept `--project` and `--provider` flags.
59
64
 
60
- | Flag | Description |
61
- | ------------------ | ------------------------------------------------------------------------- |
62
- | `--project <path>` | Override project path (default: current working directory) |
63
- | `--provider <id>` | Session provider: `claude-code`, `opencode`, `codex`, or `auto` (default) |
64
- | `--no-color` | Disable colored output (also honors `NO_COLOR`) |
65
- | `--session <id>` | Follow a specific session by ID |
66
- | `--replay` | Replay existing events from the beginning before streaming live |
65
+ | Flag | Description |
66
+ | ---------------------- | ------------------------------------------------------------------------- |
67
+ | `--project <path>` | Override project path (default: current working directory) |
68
+ | `--provider <id>` | Session provider: `claude-code`, `opencode`, `codex`, or `auto` (default) |
69
+ | `--no-color` | Disable colored output (also honors `NO_COLOR`) |
70
+ | `--offline` | Price from the cached catalog only (also `SIDEKICK_OFFLINE=1`) |
71
+ | `--output-file <path>` | Write a command's stdout to a file, without colour codes |
72
+ | `--session <id>` | Follow a specific session by ID |
73
+ | `--replay` | Replay existing events from the beginning before streaming live |
67
74
 
68
75
  ## Daily Brief & Statusline
69
76
 
@@ -72,7 +79,7 @@ sidekick today
72
79
  sidekick statusline
73
80
  ```
74
81
 
75
- `sidekick today` prints a cache-only daily brief: yesterday's sessions/tokens/cost, open tasks, the newest decision, the latest handoff, a quota summary, and the scheduled peak-hours window. `sidekick statusline` renders the same account/quota/burn summary as a single line, entirely from cached snapshots — no account bootstrap, pricing hydration, or quota network access — so it is fast enough to run on every agent prompt (the VS Code extension can wire it into Claude Code's `statusLine` setting). Global flags `--project`, `--provider`, and `--json` apply to `today`; `statusline` takes no flags.
82
+ `sidekick today` prints a cache-only daily brief: yesterday's sessions/tokens/cost, open tasks, the newest decision, the latest handoff, a quota summary, and the scheduled peak-hours window. `sidekick statusline` renders the same account/quota/burn summary as a single line with no account bootstrap, pricing hydration, or quota network access, so it is fast enough to run on every agent prompt (the VS Code extension can wire it into Claude Code's `statusLine` setting). When Claude Code runs it as the status line it pipes a JSON document on stdin: Sidekick appends context usage, session cost, and prompt-cache hit rate, and persists the official five-hour and seven-day limits so every other command sees authoritative quota without a network call. Cached quota older than five minutes shows its age. Global flags `--project`, `--provider`, and `--json` apply to `today`; `statusline` takes no flags (`SIDEKICK_STATUSLINE_STDIN=0` ignores stdin).
76
83
 
77
84
  ## Doctor
78
85
 
@@ -82,6 +89,30 @@ sidekick doctor
82
89
 
83
90
  Diagnose project identity, sessions, accounts, providers, and dependencies in one typed health report — the same diagnostics behind the VS Code `Sidekick: Run Doctor` command. Global flags `--project` and `--json` also apply.
84
91
 
92
+ ## Billing Blocks
93
+
94
+ ```bash
95
+ sidekick blocks [--active | --recent | --since <time>] [--csv]
96
+ ```
97
+
98
+ Five-hour billing blocks computed from session logs (ccusage-style: a block opens at the first usage event, aligned to the UTC hour, lasts five hours, and a longer gap opens a new one). Each block shows its cache-inclusive token total, cost with provenance, burn rate, and — for the open block — projected end-of-block tokens and cost plus the time remaining. Sessions are read once and cached by size and mtime under the Sidekick config directory. When the status line has persisted an official Claude Code rate-limit sample, it is shown beneath the local estimate for comparison. `--since` accepts an ISO date, `YYYY-MM-DD`, or a relative window such as `7d`; `--json` prints the full report and `--csv` one row per block.
99
+
100
+ ## Import History
101
+
102
+ ```bash
103
+ sidekick import [--since <time>]
104
+ ```
105
+
106
+ Fold finished sessions from every provider into the history store that `sidekick stats`, `sidekick today`, and the VS Code History tab read — the same importer and store mutation the extension runs on first activation, so both hosts credit sessions identically. Idempotent: already-imported files, sessions the live monitor persisted, and files modified in the last minute are skipped. `--since` limits the scan; `--json` prints the result.
107
+
108
+ ## Usage Reports
109
+
110
+ ```bash
111
+ sidekick daily|weekly|monthly|sessions [--since <time>] [--until <time>] [--breakdown] [--by-project] [--utc] [--csv]
112
+ ```
113
+
114
+ Usage computed straight from session logs — no VS Code extension or history store required — for every provider with session data side by side (`--provider` narrows to one). Rows are bucketed by the time of each usage event on the local calendar (`--utc` for UTC), so a session that crosses midnight is split across both days; weeks start on Monday. `--breakdown` adds per-model sub-rows, `--by-project` groups by project, `sessions` prints one row per session, and `--json` / `--csv` feed scripts. Defaults: 30 days, 12 weeks, 12 calendar months, 30 days.
115
+
85
116
  ## Quick Capture
86
117
 
87
118
  ```bash
@@ -230,7 +261,7 @@ sidekick quota
230
261
  Provider-aware quota and rate-limit display. The command auto-detects the active provider:
231
262
 
232
263
  - **Claude Code**: Shows Claude Max subscription quota — 5-hour and 7-day windows with color-coded progress bars, projections, and reset countdowns. Includes a peak-hours summary line.
233
- - **Codex**: Shows rate limits from Codex `token_count.rate_limits` events — primary and secondary windows with progress bars, projected end-of-window utilization, and reset countdowns. The default path is local-only: current workspace rollout, recent account-level rollouts, then the active account's cached snapshot. Add `--refresh` to explicitly refresh from Codex's usage API before falling back to local data. When refreshed from the API, the output also lists any available **reset credits** — a `Reset Credits: N available` line plus each credit's expiration.
264
+ - **Codex**: Shows rate limits from Codex `token_count.rate_limits` events — primary and secondary windows with progress bars, projected end-of-window utilization, and reset countdowns. Rollouts (current workspace, then recent account-level) are the session-derived step of the shared precedence below. When quota comes from the API, the output also lists any available **reset credits** — a `Reset Credits: N available` line plus each credit's expiration.
234
265
  - **OpenCode / z.ai**: OpenCode has no native rate-limit data, but when z.ai Coding Plan credentials are available, `sidekick quota --provider opencode` can auto-route to authoritative z.ai quota (5-Hour / Weekly, with projected end-of-window utilization). Use `--provider zai` to request it explicitly. z.ai quota is read from z.ai's quota API using OpenCode's stored token, with fallback support for `ANTHROPIC_BASE_URL` and `ANTHROPIC_AUTH_TOKEN`.
235
266
 
236
267
  Every provider renders in the same aligned table — a `now` column (current utilization), a `projected` column (estimated end-of-window utilization, or `—` when it can't be computed), and a `resets` countdown:
@@ -245,11 +276,11 @@ Subscription Quota now projected resets
245
276
 
246
277
  When quota data is unavailable, `sidekick quota` shows structured auth, rate-limit, network, server, or unexpected-failure messaging instead of a generic raw error. The dashboard Sessions panel also keeps a compact inline quota/rate-limit state visible instead of hiding the section entirely.
247
278
 
248
- Use `--json` for machine-readable output. Use `--provider codex` to explicitly check Codex rate limits, and `--refresh` to opt in to a Codex usage API refresh for that single-provider check (the combined `--all` view is API-first for Codex — see below). Claude Code requires active credentials (read from the system Keychain on macOS, or `~/.claude/.credentials.json` on Linux/Windows). JSON output includes `failureKind`, `httpStatus`, and `retryAfterMs` on unavailable responses.
279
+ Every provider (and `--all`, `sidekick mcp`'s `get_quota_status`, and both dashboards) resolves quota through one shared path: a persisted sample younger than five minutes (the status-line sample, a session-log sample, or an earlier API answer) is returned without a network call; otherwise session logs are checked; otherwise the provider API is called and its answer persisted; otherwise the most recent older sample is shown with its age. The `Source` row says which step produced the numbers. Add `--refresh` to ask the API first. Use `--json` for machine-readable output; it includes `resolution`, `source`, `capturedSource`, `freshness`, and `ageMs`, plus `failureKind`, `httpStatus`, and `retryAfterMs` on unavailable responses. Claude Code requires active credentials (read from the system Keychain on macOS, or `~/.claude/.credentials.json` on Linux/Windows).
249
280
 
250
281
  When multi-account is enabled, `sidekick quota` shows the currently logged-in account email above the quota bars — resolved live from the provider's auth, so it stays correct even after a native `claude login` / `codex login`.
251
282
 
252
- Use `sidekick quota --all` to show Claude and Codex quota together in a single run, plus z.ai when API quota is available or z.ai traffic is active. Each provider degrades independently — if one provider's quota can't be fetched, its error is shown inline and the others still render (the command never aborts on a single provider's failure). Codex is fetched **API-first** under `--all` (falling back to local rollouts and the cached snapshot), matching the live Claude and z.ai legs, so the combined view reflects the authoritative aggregate plan quota. `--all --json` emits a provider-keyed payload for dashboards and automation.
283
+ Use `sidekick quota --all` to show Claude and Codex quota together in a single run, plus z.ai when API quota is available or z.ai traffic is active. Each provider degrades independently — if one provider's quota can't be fetched, its error is shown inline and the others still render (the command never aborts on a single provider's failure). The combined view uses the same precedence as the single-provider view, so the two never disagree. `--all --json` emits a provider-keyed payload for dashboards and automation.
253
284
 
254
285
  ### Quota History
255
286
 
@@ -267,7 +298,7 @@ Mon ··▒▒▓█▒░· ·░░·· ·▒▓
267
298
  Peak 92% · Avg 38% · Samples 612
268
299
  ```
269
300
 
270
- Flags: `--weeks <n>` (1-26, default 13), `--provider claude|codex|zai` (default all available, stacked), `--workspace <path>` (default `cwd`). `--json` emits a `{ workspaceId, weeks, providers, generatedAt }` payload — the same shape consumed by the VS Code dashboard's Quota History panel.
301
+ Flags: `--weeks <n>` (1-26, default 13), `--provider claude|codex|zai` (default all available, stacked), `--workspace <path>` (default `cwd`), `--window 5h|7d|max` (default `5h`), `--csv`. `--json` emits a `{ workspaceId, weeks, window, providers, generatedAt }` payload — the same shape consumed by the VS Code dashboard's Quota History panel. Cells are local calendar days.
271
302
 
272
303
  History is stored at `~/.config/sidekick/quota-history/<workspaceId>/<provider>.jsonl` (mode `0600`, 60-second debounce, 91-day retention). The workspace id is `sha256(realpath)[0..16]`, so the same folder yields the same store whether sampled from the CLI or VS Code.
273
304
 
@@ -1,8 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __createRequire } from "module";
3
3
  const require = __createRequire(import.meta.url);
4
- var qn=Object.create;var st=Object.defineProperty;var Wn=Object.getOwnPropertyDescriptor;var Bn=Object.getOwnPropertyNames;var zn=Object.getPrototypeOf,Un=Object.prototype.hasOwnProperty;var f=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var w=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}};var Kn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Bn(t))!Un.call(e,i)&&i!==n&&st(e,i,{get:()=>t[i],enumerable:!(r=Wn(t,i))||r.enumerable});return e};var kn=(e,t,n)=>(n=e!=null?qn(zn(e)):{},Kn(t||!e||!e.__esModule?st(n,"default",{value:e,enumerable:!0}):n,e));var be=w(p=>{"use strict";var Jn=p&&p.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Vn=p&&p.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Oe=p&&p.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Jn(n,t,r[i]);return Vn(n,t),n}})();Object.defineProperty(p,"__esModule",{value:!0});p.CONFIG_DIR_ENV_VAR=void 0;p.getDefaultConfigDir=lt;p.setConfigDir=Gn;p.getConfigDirOverride=Yn;p.getConfigDir=je;p.getProjectDataPath=Xn;p.getGlobalDataPath=Zn;p.encodeWorkspacePath=Ce;p.getProjectSlug=er;p.resolveProjectIdentity=Ie;p.getProjectSlugRaw=tr;var Qn=Oe(f("fs")),W=Oe(f("path")),dt=Oe(f("os"));p.CONFIG_DIR_ENV_VAR="SIDEKICK_CONFIG_DIR";var ce=null;function lt(){return process.platform==="win32"?W.join(process.env.APPDATA||dt.homedir(),"sidekick"):W.join(dt.homedir(),".config","sidekick")}function Gn(e){let t=e?.trim();ce=t?W.resolve(t):null}function Yn(){return ce}function je(){if(ce)return ce;let e=process.env[p.CONFIG_DIR_ENV_VAR]?.trim();return e?W.resolve(e):lt()}function Xn(e,t){return W.join(je(),t,`${e}.json`)}function Zn(e){return W.join(je(),e)}function Ce(e){return e.replace(/\\/g,"/").replace(/[:/_]/g,"-")}function er(e){return Ie(e).canonicalSlug}function Ie(e){let t=W.resolve(e||process.cwd()),n;try{n=Qn.realpathSync(t)}catch{n=t}let r=Ce(n),i=Ce(t);return{cwd:t,resolvedCwd:n,canonicalSlug:r,legacySlug:i,candidates:r===i?[r]:[r,i],hasLegacyMismatch:r!==i}}function tr(e){return Ie(e).legacySlug}});var Z=w(I=>{"use strict";var nr=I&&I.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),rr=I&&I.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),De=I&&I.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&nr(n,t,r[i]);return rr(n,t),n}})();Object.defineProperty(I,"__esModule",{value:!0});I.atomicWriteJson=yt;I.atomicWriteJsonSync=pt;I.atomicWriteFileSync=mt;I.updateJsonStoreAtomic=sr;I.withFileLockSync=gt;I.updateJsonStoreAtomicSync=yr;var J=De(f("crypto")),a=De(f("fs")),k=De(f("path")),Pe=1e4,K=3e3,ir=12e4,ft=15e3,cr=15,or=new Int32Array(new SharedArrayBuffer(4));async function ar(e){let t;try{t=await a.promises.open(e,"r"),await t.sync()}catch(n){let r=n.code;if(!["EISDIR","EINVAL","ENOSYS","EPERM","EACCES"].includes(r??""))throw n}finally{await t?.close().catch(()=>{})}}function ur(e){let t;try{t=a.openSync(e,"r"),a.fsyncSync(t)}catch(n){let r=n.code;if(!["EISDIR","EINVAL","ENOSYS","EPERM","EACCES"].includes(r??""))throw n}finally{t!==void 0&&a.closeSync(t)}}async function yt(e,t){await a.promises.mkdir(k.dirname(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${J.randomBytes(8).toString("hex")}.tmp`,r;try{r=await a.promises.open(n,"wx",384),await r.writeFile(JSON.stringify(t,null,2),"utf8"),await r.sync(),await r.close(),r=void 0,await a.promises.rename(n,e),await ar(k.dirname(e))}catch(i){throw await r?.close().catch(()=>{}),await a.promises.rm(n,{force:!0}).catch(()=>{}),i}}function pt(e,t){mt(e,JSON.stringify(t,null,2))}function mt(e,t,n=384){a.mkdirSync(k.dirname(e),{recursive:!0,mode:448});let r=`${e}.${process.pid}.${J.randomBytes(8).toString("hex")}.tmp`,i;try{i=a.openSync(r,"wx",n),a.writeFileSync(i,t,{encoding:"utf8"}),a.fsyncSync(i),a.closeSync(i),i=void 0,a.renameSync(r,e),ur(k.dirname(e))}catch(c){throw i!==void 0&&a.closeSync(i),a.rmSync(r,{force:!0}),c}}async function sr(e,t,n){await a.promises.mkdir(k.dirname(e),{recursive:!0,mode:448});let r=`${e}.lock`,i=await dr(r);try{let c=t(),o;try{o=await a.promises.readFile(e,"utf8")}catch(s){if(s.code!=="ENOENT")throw s}if(o!==void 0)try{c=JSON.parse(o)}catch{let s=`${e}.corrupt-${Date.now()}-${J.randomBytes(4).toString("hex")}`;await a.promises.rename(e,s)}let d=await n(c);return await yt(e,d),d}finally{await lr(r,i)}}async function dr(e){let t=Date.now()+K,n=null;for(;;)try{let r=await a.promises.open(e,"wx",384),i=`${process.pid}:${J.randomBytes(16).toString("hex")}`;await r.writeFile(i,"utf8"),await r.sync();let c=setInterval(()=>{a.promises.utimes(e,new Date,new Date).catch(()=>{})},Math.floor(Pe/3));return c.unref(),{handle:r,token:i,heartbeat:c}}catch(r){if(r.code!=="EEXIST")throw r;let i=await a.promises.readFile(e,"utf8").catch(()=>null);i!==null&&i!==n&&(n=i,t=Date.now()+K);try{let c=await a.promises.stat(e),o=Date.now()-c.mtimeMs;o>Pe&&!ht(i,o)&&await a.promises.rm(e,{force:!0})}catch{}if(Date.now()>=t)throw new Error(`Timed out waiting for store lock: ${e} (no progress for ${K}ms)`);await new Promise(c=>setTimeout(c,15))}}async function lr(e,t){clearInterval(t.heartbeat),await t.handle.close().catch(()=>{});try{await a.promises.readFile(e,"utf8")===t.token&&await a.promises.rm(e,{force:!0})}catch{}}function ht(e,t){if(t>ir)return!1;let n=Number.parseInt((e??"").split(":",1)[0],10);if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(r){return r.code==="EPERM"}}function gt(e,t){let n=fr(e);try{return t()}finally{try{a.readFileSync(e,"utf8")===n&&a.rmSync(e,{force:!0})}catch{}}}function fr(e){let t=Date.now(),n=t+K,r=null;for(;;)try{let i=a.openSync(e,"wx",384),c=`${process.pid}:${J.randomBytes(16).toString("hex")}`;return a.writeFileSync(i,c,"utf8"),a.fsyncSync(i),a.closeSync(i),c}catch(i){if(i.code!=="EEXIST")throw i;let c=null;try{c=a.readFileSync(e,"utf8")}catch{}c!==null&&c!==r&&(r=c,n=Date.now()+K);try{let d=a.statSync(e),s=Date.now()-d.mtimeMs;s>Pe&&!ht(c,s)&&a.rmSync(e,{force:!0})}catch{}let o=Date.now();if(o>=n)throw new Error(`Timed out waiting for store lock: ${e} (no progress for ${K}ms)`);if(o-t>=ft)throw new Error(`Timed out waiting for store lock: ${e} (blocked synchronously for ${ft}ms)`);Atomics.wait(or,0,0,cr)}}function yr(e,t,n){return a.mkdirSync(k.dirname(e),{recursive:!0,mode:448}),gt(`${e}.lock`,()=>{let r=t(),i;try{i=a.readFileSync(e,"utf8")}catch(o){if(o.code!=="ENOENT")throw o}if(i!==void 0)try{r=JSON.parse(i)}catch{let o=`${e}.corrupt-${Date.now()}-${J.randomBytes(4).toString("hex")}`;a.renameSync(e,o)}let c=n(r);return pt(e,c),c})}});var vt=w(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe._onRawAccountsChanged=pr;oe._emitAccountsChanged=mr;var xe=new Set;function pr(e){return xe.add(e),()=>xe.delete(e)}function mr(e){for(let t of xe)try{t(e)}catch{}}});var Me=w(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.MODEL_PROVIDER_IDS=D.RUNTIME_QUOTA_PROVIDER_IDS=D.QUOTA_PROVIDER_IDS=D.ACCOUNT_PROVIDER_IDS=D.SESSION_PROVIDER_IDS=void 0;D.SESSION_PROVIDER_IDS=["claude-code","opencode","codex"];D.ACCOUNT_PROVIDER_IDS=["claude-code","codex"];D.QUOTA_PROVIDER_IDS=["claude-code","codex","zai"];D.RUNTIME_QUOTA_PROVIDER_IDS=["claude","codex","zai"];D.MODEL_PROVIDER_IDS=["anthropic","openai","google","unknown"]});var ue=w(v=>{"use strict";var hr=v&&v.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),gr=v&&v.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),At=v&&v.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&hr(n,t,r[i]);return gr(n,t),n}})();Object.defineProperty(v,"__esModule",{value:!0});v.ACCOUNT_PROVIDER_IDS=void 0;v.getAccountsDir=Ee;v.readSavedAccountRegistry=ee;v.writeSavedAccountRegistry=wr;v.listSavedAccountProfiles=Cr;v.getActiveSavedAccount=Or;v.upsertSavedAccountProfile=jr;v.setActiveSavedAccount=Ir;v.replaceSavedAccountProfiles=br;v.removeSavedAccountProfile=Pr;var St=At(f("fs")),_t=At(f("path")),vr=be(),ae=Z(),Ar=vt(),Sr=Me();Object.defineProperty(v,"ACCOUNT_PROVIDER_IDS",{enumerable:!0,get:function(){return Sr.ACCOUNT_PROVIDER_IDS}});function Ee(){return _t.join((0,vr.getConfigDir)(),"accounts")}function Re(){return _t.join(Ee(),"accounts.json")}function Ne(){return Re()+".lock"}function Fe(){St.mkdirSync(Ee(),{recursive:!0,mode:448})}function Te(e){(0,ae.atomicWriteJsonSync)(Re(),Ct(e)),(0,Ar._emitAccountsChanged)("local")}function Le(e){return Fe(),(0,ae.withFileLockSync)(Ne(),()=>{let t=e(ee()??wt());return Te(t),t})}function wt(){return{version:2,activeByProvider:{"claude-code":null,codex:null},accounts:[]}}function Ct(e){let t=wt();return t.activeByProvider["claude-code"]=e.activeByProvider?.["claude-code"]??null,t.activeByProvider.codex=e.activeByProvider?.codex??null,t.accounts=Array.isArray(e.accounts)?e.accounts.filter(n=>!!n&&(n.providerId==="claude-code"||n.providerId==="codex")&&typeof n.id=="string"&&typeof n.addedAt=="string").map(n=>({...n,label:n.label||void 0,email:n.email||void 0,providerAccountId:n.providerAccountId||void 0,metadata:n.metadata?{email:n.metadata.email||void 0,workspaceId:n.metadata.workspaceId||void 0,planType:n.metadata.planType||void 0,authMode:n.metadata.authMode||void 0}:void 0})):[],t}function _r(e){return{version:2,activeByProvider:{"claude-code":e.activeAccountUuid,codex:null},accounts:e.accounts.map(t=>({id:t.uuid,providerId:"claude-code",providerAccountId:t.uuid,email:t.email,label:t.label,addedAt:t.addedAt,metadata:{email:t.email}}))}}function ee(){try{let e=St.readFileSync(Re(),"utf8"),t=JSON.parse(e);return t?.version===2?Ct(t):t?.version===1&&Array.isArray(t.accounts)?_r(t):null}catch{return null}}function wr(e){Fe(),(0,ae.withFileLockSync)(Ne(),()=>Te(e))}function Cr(e){let t=ee();return t?e?t.accounts.filter(n=>n.providerId===e):t.accounts:[]}function Or(e){let t=ee();if(!t)return null;let n=t.activeByProvider[e];return n?t.accounts.find(r=>r.providerId===e&&r.id===n)??null:null}function jr(e){return Le(t=>{let n=t.accounts.findIndex(r=>r.providerId===e.providerId&&r.id===e.id);return n>=0?t.accounts[n]=e:t.accounts.push(e),t})}function Ir(e,t){return Le(n=>(n.activeByProvider[e]=t,n))}function br(e,t,n){return Le(r=>(r.accounts=r.accounts.filter(i=>i.providerId!==e).concat(t),r.activeByProvider[e]=n,r))}function Pr(e,t){return Fe(),(0,ae.withFileLockSync)(Ne(),()=>{let n=ee();if(!n)return null;let r=n.accounts.findIndex(c=>c.providerId===e&&c.id===t);if(r===-1)return null;let[i]=n.accounts.splice(r,1);return n.activeByProvider[e]===t&&(n.activeByProvider[e]=n.accounts.find(c=>c.providerId===e)?.id??null),Te(n),i})}});var He=w(C=>{"use strict";var Dr=C&&C.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),xr=C&&C.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),jt=C&&C.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Dr(n,t,r[i]);return xr(n,t),n}})();Object.defineProperty(C,"__esModule",{value:!0});C.getClaudeProfilesDir=It;C.getClaudeProfileHome=bt;C.ensureClaudeProfileDirs=Nr;C.claudeKeychainSuffix=Pt;C.claudeKeychainService=Dt;C.readClaudeProfileIdentity=xt;C.keychainServiceExists=Mt;C.isClaudeProfileAuthenticated=Fr;var Mr=f("child_process"),Er=f("crypto"),$e=jt(f("fs")),se=jt(f("path")),Rr=ue(),Ot="Claude Code-credentials";function It(){return se.join((0,Rr.getAccountsDir)(),"claude","profiles")}function bt(e){return se.join(It(),e,"home")}function Nr(e){$e.mkdirSync(bt(e),{recursive:!0,mode:448})}function Pt(e){return(0,Er.createHash)("sha256").update(e).digest("hex").slice(0,8)}function Dt(e){return e?`${Ot}-${Pt(e)}`:Ot}function xt(e){try{let t=JSON.parse($e.readFileSync(se.join(e,".claude.json"),"utf8")),n=t?.oauthAccount?.emailAddress,r=t?.oauthAccount?.accountUuid;return typeof n=="string"&&typeof r=="string"?{email:n,uuid:r}:null}catch{return null}}function Mt(e){try{return(0,Mr.execFileSync)("security",["find-generic-password","-s",e],{stdio:["ignore","ignore","ignore"],timeout:4e3,killSignal:"SIGKILL"}),!0}catch{return!1}}function Fr(e){return(process.platform==="darwin"?Mt(Dt(e)):$e.existsSync(se.join(e,".credentials.json")))&&xt(e)!==null}});var Tt=w(x=>{"use strict";var Tr=x&&x.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Lr=x&&x.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Be=x&&x.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Tr(n,t,r[i]);return Lr(n,t),n}})();Object.defineProperty(x,"__esModule",{value:!0});x.KEYCHAIN_SERVICE=void 0;x.readActiveCredentials=Hr;x.writeActiveCredentials=qr;var We=Be(f("fs")),Et=Be(f("path")),$r=Be(f("os")),Rt=f("child_process"),Nt=He();x.KEYCHAIN_SERVICE="Claude Code-credentials";function qe(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function Ft(e){return Et.join(e??Et.join($r.homedir(),".claude"),".credentials.json")}function Hr(e){if(process.platform==="darwin")try{let t=(0,Rt.execFileSync)("security",["find-generic-password","-s",(0,Nt.claudeKeychainService)(e),"-w"],{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:4e3,killSignal:"SIGKILL"});return JSON.parse(t.trim())}catch{return null}try{return JSON.parse(We.readFileSync(Ft(e),"utf8"))}catch{return null}}function qr(e,t){let n=JSON.stringify(e);if(JSON.parse(n),process.platform==="darwin"){let c=(0,Nt.claudeKeychainService)(t),o=process.env.USER||"user",d=["add-generic-password","-U","-s",qe(c),"-a",qe(o),"-w",qe(n)].join(" ");(0,Rt.execFileSync)("security",["-i"],{input:d+`
5
- `,stdio:["pipe","pipe","pipe"],timeout:4e3,killSignal:"SIGKILL"});return}let r=Ft(t),i=r+".tmp";We.writeFileSync(i,n,{encoding:"utf8",mode:384}),We.renameSync(i,r)}});var Vt=w(h=>{"use strict";var Wr=h&&h.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Br=h&&h.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ze=h&&h.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Wr(n,t,r[i]);return Br(n,t),n}})();Object.defineProperty(h,"__esModule",{value:!0});h.readAccountRegistry=fe;h.writeAccountRegistry=le;h.readActiveClaudeAccount=ye;h.addCurrentAccount=Qr;h.switchToAccount=Gr;h.resolveActiveClaudeHome=Xr;h.applyActiveClaudeToLiveHome=Zr;h.reconcileClaudeAuthState=ei;h.removeAccount=ti;h.listAccounts=ni;h.getActiveAccount=Jt;h.resolveActiveClaudeAccount=ri;h.isMultiAccountEnabled=ii;var O=ze(f("fs")),m=ze(f("path")),Lt=ze(f("os")),E=Tt(),T=Z(),A=ue(),G=He();function $t(){return m.join(Lt.homedir(),".claude")}function L(){let e=m.join($t(),".claude.json");try{if(JSON.parse(O.readFileSync(e,"utf8"))?.oauthAccount)return e}catch{}return m.join(Lt.homedir(),".claude.json")}function V(){return m.join((0,A.getAccountsDir)(),"credentials")}function Q(){return m.join((0,A.getAccountsDir)(),"configs")}function zr(){return m.join((0,A.getAccountsDir)(),"claude",".profiles-migrated-v1")}function Ur(){for(let e of[(0,A.getAccountsDir)(),V(),Q()])O.mkdirSync(e,{recursive:!0,mode:448})}function Ue(e){try{return JSON.parse(O.readFileSync(e,"utf8"))}catch{return null}}function Ht(e){return Ue(e)?.oauthAccount??null}function qt(e,t){(0,T.atomicWriteJsonSync)(m.join((0,G.getClaudeProfileHome)(e),".claude.json"),{oauthAccount:t})}function Wt(e,t){(0,E.writeActiveCredentials)(t,(0,G.getClaudeProfileHome)(e))}function de(e,t,n){qt(e,n),Wt(e,t)}function Bt(e){return Ue(m.join(V(),`${e}.credentials.json`))}function zt(e){return Ue(m.join(Q(),`${e}.config.json`))}function Ut(e){return Ht(m.join((0,G.getClaudeProfileHome)(e),".claude.json"))}function Kr(e){let t=(0,E.readActiveCredentials)((0,G.getClaudeProfileHome)(e)),n=Ut(e);if(t&&n)return{credentials:t,oauthAccount:n};let r=Bt(e),i=zt(e);if(r&&i){try{de(e,r,i)}catch{}return{credentials:r,oauthAccount:i}}return null}function kr(){return Ht(L())}function Jr(){let e=ye();if(!e)return;let t=(0,E.readActiveCredentials)(),n=kr();if(t)try{(0,T.atomicWriteJsonSync)(m.join(V(),`${e.uuid}.credentials.json`),t),Wt(e.uuid,t)}catch{}if(n)try{(0,T.atomicWriteJsonSync)(m.join(Q(),`${e.uuid}.config.json`),n),qt(e.uuid,n)}catch{}}function Vr(e){let t={};try{t=JSON.parse(O.readFileSync(L(),"utf8"))}catch{}t.oauthAccount=e,(0,T.atomicWriteJsonSync)(L(),t)}function fe(){let e=(0,A.readSavedAccountRegistry)();if(!e)return null;let t=e.accounts.filter(n=>n.providerId==="claude-code").map(n=>({uuid:n.providerAccountId??n.id,email:n.email??n.metadata?.email??"unknown",label:n.label,addedAt:n.addedAt}));return{version:1,activeAccountUuid:e.activeByProvider["claude-code"],accounts:t}}function le(e){let t=e.accounts.map(n=>({id:n.uuid,providerId:"claude-code",providerAccountId:n.uuid,email:n.email,label:n.label,addedAt:n.addedAt,metadata:{email:n.email}}));(0,A.replaceSavedAccountProfiles)("claude-code",t,e.activeAccountUuid)}function ye(){try{let e=O.readFileSync(L(),"utf8"),t=JSON.parse(e),n=t?.oauthAccount?.emailAddress,r=t?.oauthAccount?.accountUuid;return!n||!r?null:{email:n,uuid:r}}catch{return null}}function Qr(e){let t=ye();if(!t)return{success:!1,error:"No active Claude account found. Sign in with `claude` first."};let n=(0,E.readActiveCredentials)();if(!n)return{success:!1,error:"Could not read Claude credentials."};let r;try{r=JSON.parse(O.readFileSync(L(),"utf8")).oauthAccount}catch{return{success:!1,error:"Could not read Claude config file."}}Ur();let i=fe()??{version:1,activeAccountUuid:null,accounts:[]},c=i.accounts.find(o=>o.uuid===t.uuid);if(c){e!==void 0&&(c.label=e),(0,T.atomicWriteJsonSync)(m.join(V(),`${t.uuid}.credentials.json`),n),(0,T.atomicWriteJsonSync)(m.join(Q(),`${t.uuid}.config.json`),r);try{de(t.uuid,n,r)}catch{}return i.activeAccountUuid=t.uuid,le(i),{success:!0}}(0,T.atomicWriteJsonSync)(m.join(V(),`${t.uuid}.credentials.json`),n),(0,T.atomicWriteJsonSync)(m.join(Q(),`${t.uuid}.config.json`),r);try{de(t.uuid,n,r)}catch{}return i.accounts.push({uuid:t.uuid,email:t.email,label:e,addedAt:new Date().toISOString()}),i.activeAccountUuid=t.uuid,le(i),{success:!0}}function Kt(e){let t=m.join((0,A.getAccountsDir)(),"claude");return O.mkdirSync(t,{recursive:!0,mode:448}),(0,T.withFileLockSync)(m.join(t,"auth-swap.lock"),e)}function Gr(e){try{return Kt(()=>Yr(e))}catch(t){return{success:!1,error:`Could not acquire the account-switch lock: ${t}`}}}function Yr(e){let t=fe();if(!t)return{success:!1,error:"No account registry found. Save an account first."};if(!t.accounts.find(o=>o.uuid===e))return{success:!1,error:`Account ${e} not found in registry.`};let r=null,i=null;r=(0,E.readActiveCredentials)();try{i=O.readFileSync(L(),"utf8")}catch{}try{Jr()}catch{}try{(0,A.setActiveSavedAccount)("claude-code",e)}catch(o){return{success:!1,error:`Failed to update account registry: ${o}`}}let c=kt();if(!c.success){try{(0,A.setActiveSavedAccount)("claude-code",t.activeAccountUuid)}catch{}if(r)try{(0,E.writeActiveCredentials)(r)}catch{}if(i)try{O.writeFileSync(L(),i)}catch{}return c}return c}function Xr(){let e=(0,A.getActiveSavedAccount)("claude-code");return e?(0,G.getClaudeProfileHome)(e.providerAccountId??e.id):$t()}function Zr(){try{return Kt(kt)}catch(e){return{success:!1,error:`Could not acquire the account-switch lock: ${e}`}}}function kt(){let e=(0,A.getActiveSavedAccount)("claude-code");if(!e)return{success:!1,error:"No active Claude account found."};let t=e.providerAccountId??e.id,n=Kr(t);if(!n)return{success:!1,error:`Stored credentials for ${e.email??t} not found.`};let r=(0,E.readActiveCredentials)(),i=null;try{i=O.readFileSync(L(),"utf8")}catch{}try{(0,E.writeActiveCredentials)(n.credentials)}catch(c){if(r)try{(0,E.writeActiveCredentials)(r)}catch{}return{success:!1,error:`Failed to write credentials: ${c}`}}try{Vr(n.oauthAccount)}catch(c){if(r)try{(0,E.writeActiveCredentials)(r)}catch{}if(i)try{O.writeFileSync(L(),i)}catch{}return{success:!1,error:`Failed to write config: ${c}`}}return{success:!0}}function ei(){try{let e=zr();if(O.existsSync(e))return;let t=(0,A.readSavedAccountRegistry)();if(t)for(let n of t.accounts.filter(r=>r.providerId==="claude-code"))try{let r=n.providerAccountId??n.id;if((0,E.readActiveCredentials)((0,G.getClaudeProfileHome)(r))&&Ut(r))continue;let i=Bt(r),c=zt(r);if(!i||!c)continue;de(r,i,c)}catch{}O.mkdirSync(m.dirname(e),{recursive:!0,mode:448}),O.writeFileSync(e,new Date().toISOString()+`
6
- `,{encoding:"utf8",mode:384})}catch{}}function ti(e){let t=fe();if(!t)return{success:!1,error:"No account registry found."};let n=t.accounts.findIndex(r=>r.uuid===e);if(n===-1)return{success:!1,error:`Account ${e} not found.`};try{O.unlinkSync(m.join(V(),`${e}.credentials.json`))}catch{}try{O.unlinkSync(m.join(Q(),`${e}.config.json`))}catch{}return t.accounts.splice(n,1),t.activeAccountUuid===e&&(t.activeAccountUuid=t.accounts[0]?.uuid??null),le(t),{success:!0}}function ni(){return(0,A.listSavedAccountProfiles)("claude-code").map(e=>({uuid:e.providerAccountId??e.id,email:e.email??e.metadata?.email??"unknown",label:e.label,addedAt:e.addedAt}))}function Jt(){let e=(0,A.getActiveSavedAccount)("claude-code");return e?{uuid:e.providerAccountId??e.id,email:e.email??e.metadata?.email??"unknown",label:e.label,addedAt:e.addedAt}:null}function ri(){let e=ye();if(e){let n=(0,A.listSavedAccountProfiles)("claude-code"),r=n.find(i=>(i.providerAccountId??i.id)===e.uuid)??n.find(i=>(i.email??i.metadata?.email)===e.email);if(r){let i=(0,A.getActiveSavedAccount)("claude-code");if(!i||i.id!==r.id)try{(0,A.setActiveSavedAccount)("claude-code",r.id)}catch{}}return{email:e.email,label:r?.label,providerAccountId:e.uuid,registryAccountId:r?.id,source:"live"}}let t=Jt();return t?{email:t.email,label:t.label,providerAccountId:t.uuid,registryAccountId:t.uuid,source:"registry"}:{source:"none"}}function ii(){return(0,A.listSavedAccountProfiles)("claude-code").length>=1}});var vn=w(l=>{"use strict";var ci=l&&l.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),oi=l&&l.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Je=l&&l.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&ci(n,t,r[i]);return oi(n,t),n}})();Object.defineProperty(l,"__esModule",{value:!0});l.getSystemCodexHome=N;l.getCodexMonitoringHomes=li;l.getCodexProfilesDir=Xt;l.getCodexProfileHome=R;l.readCodexAccountMetadata=rn;l.readCodexAccountMetadataAsync=cn;l.isCodexProfileAuthenticated=on;l.isCodexProfileAuthenticatedAsync=an;l.listCodexAccounts=Y;l.getActiveCodexAccount=Ae;l.resolveSidekickCodexHome=Ye;l.resolveActiveCodexAccount=_i;l.getCodexExecutionEnv=wi;l.prepareCodexAccount=Ci;l.prepareCodexAccountAsync=Oi;l.finalizeCodexAccount=dn;l.finalizeCodexAccountAsync=ln;l.switchToCodexAccount=Pi;l.switchToCodexAccountAsync=Di;l.reconcileCodexAuthState=xi;l.reconcileCodexAuthStateAsync=Mi;l.removeCodexAccount=Ei;var g=Je(f("fs")),ai=Je(f("os")),u=Je(f("path")),pe=f("child_process"),ui=f("crypto"),_=ue(),S=Z(),si=11520*60*1e3;function Gt(){return u.join(ai.homedir(),".codex")}function Yt(){let e=process.env.CODEX_HOME?.trim();return e||null}function di(e){let t=new Set,n=[];for(let r of e){let i=u.resolve(r);t.has(i)||(t.add(i),n.push(r))}return n}function N(){return Yt()??Gt()}function li(){let e=Yt();if(e)return[e];let t=[Gt()];for(let n of Y()){let r=R(n.id);g.existsSync(u.join(r,"sessions"))&&t.push(r)}return di(t)}function Xt(){return u.join((0,_.getAccountsDir)(),"codex","profiles")}function Ve(e){return u.join(Xt(),e)}function R(e){return u.join(Ve(e),"codex-home")}function Zt(e){return u.join(Ve(e),"profile.json")}function en(e){g.mkdirSync(R(e),{recursive:!0,mode:448})}function H(e){try{return g.readFileSync(e,"utf8")}catch{return null}}function Qe(e){try{return JSON.parse(g.readFileSync(Zt(e),"utf8"))}catch{return null}}function fi(e,t){en(e),(0,S.atomicWriteJsonSync)(Zt(e),t)}function Ke(e,t){return g.existsSync(e)?(g.mkdirSync(u.dirname(t),{recursive:!0,mode:448}),g.copyFileSync(e,t),!0):!1}function yi(e,t){Ke(u.join(e,"config.toml"),u.join(t,"config.toml"))}function pi(e,t){let n=Ke(u.join(e,"auth.json"),u.join(t,"auth.json")),r=Ke(u.join(e,".credentials.json"),u.join(t,".credentials.json"));return n||r}function mi(e){let t=e.split(".");if(t.length<2)return null;try{let n=Buffer.from(t[1],"base64url").toString("utf8");return JSON.parse(n)}catch{return null}}function Ge(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function B(e){let t=Ge(e);if(!t)return null;let n=t.tokens?.id_token,r=n?mi(n):null,i=r?.["https://api.openai.com/profile"],c=r?.["https://api.openai.com/auth"],o=typeof r?.email=="string"?r.email:typeof i?.email=="string"?i.email:void 0,d=typeof c?.chatgpt_account_id=="string"?c.chatgpt_account_id:t.tokens?.account_id,s=typeof c?.chatgpt_plan_type=="string"?c.chatgpt_plan_type:void 0,y=t.OPENAI_API_KEY||t.auth_mode==="api_key"?"api-key":"chatgpt";return{email:o,workspaceId:d,planType:s,authMode:y}}function ke(e,t){let n=Ge(e);if(n?.last_refresh){let r=Date.parse(n.last_refresh);if(!Number.isNaN(r))return r}if(t)try{return g.statSync(t).mtimeMs}catch{}return null}function hi(e){let t=B(H(u.join(e,"auth.json")));return t?{email:t.email,workspaceId:t.workspaceId,planType:t.planType,authMode:t.authMode}:{}}function gi(e){let t=u.join(e,".credentials.json");if(!g.existsSync(t))return{};try{let n=JSON.parse(g.readFileSync(t,"utf8"));if(typeof n.OPENAI_API_KEY=="string"||typeof n.CODEX_API_KEY=="string")return{authMode:"api-key"}}catch{}return{}}var me=4e3;function tn(e,t){let n=t.trim();return e===0&&/^Logged in/i.test(n)?/API key/i.test(n)?{loggedIn:!0,authMode:"api-key"}:/ChatGPT/i.test(n)?{loggedIn:!0,authMode:"chatgpt"}:{loggedIn:!0}:{loggedIn:!1}}function he(e){try{let t={...process.env,CODEX_HOME:e},n=(0,pe.spawnSync)("codex",["login","status"],{encoding:"utf8",env:t,timeout:me,killSignal:"SIGKILL"});return tn(n.status,String(n.stdout??""))}catch{}return{loggedIn:!1}}function ge(e){return new Promise(t=>{try{let n={...process.env,CODEX_HOME:e};(0,pe.execFile)("codex",["login","status"],{encoding:"utf8",env:n,timeout:me,killSignal:"SIGKILL"},(r,i)=>{t(r?{loggedIn:!1}:tn(0,String(i??"")))})}catch{t({loggedIn:!1})}})}function vi(){if(process.platform==="win32")return!1;try{return(0,pe.spawnSync)("pgrep",["-x","codex"],{encoding:"utf8",timeout:me,killSignal:"SIGKILL"}).status===0}catch{return!1}}function Ai(){return process.platform==="win32"?Promise.resolve(!1):new Promise(e=>{try{(0,pe.execFile)("pgrep",["-x","codex"],{encoding:"utf8",timeout:me,killSignal:"SIGKILL"},t=>e(!t))}catch{e(!1)}})}function ve(e){let t=hi(e);if(t.email||t.workspaceId||t.planType||t.authMode)return t;let n=gi(e);return n.authMode?n:null}function nn(e){return e.loggedIn?{authMode:e.authMode??"unknown"}:{}}function rn(e){return ve(e)??nn(he(e))}async function cn(e){return ve(e)??nn(await ge(e))}function te(e){return g.existsSync(u.join(e,"auth.json"))||g.existsSync(u.join(e,".credentials.json"))}function on(e){return te(e)||he(e).loggedIn}async function an(e){return te(e)||(await ge(e)).loggedIn}function Si(e,t){let n=e.trim().toLowerCase();return Y().find(i=>i.id!==t&&(i.label??"").trim().toLowerCase()===n)?`A Codex account named "${e}" already exists.`:null}function Y(){return(0,_.listSavedAccountProfiles)("codex")}function Ae(){return(0,_.getActiveSavedAccount)("codex")}function Ye(){return N()}function _i(){let e=B(H(u.join(Ye(),"auth.json")));if(e&&(e.email||e.workspaceId)){let n=Xe(e);if(n){let r=(0,_.getActiveSavedAccount)("codex");if(!r||r.id!==n.id)try{(0,_.setActiveSavedAccount)("codex",n.id)}catch{}}return{email:e.email??n?.email??n?.metadata?.email,label:n?.label,providerAccountId:n?.providerAccountId??e.workspaceId,registryAccountId:n?.id,source:"live"}}let t=Ae();return t?{email:t.email??t.metadata?.email,label:t.label,providerAccountId:t.providerAccountId,registryAccountId:t.id,source:"registry"}:{source:"none"}}function wi(e=process.env){return{...e,CODEX_HOME:Ye()}}function un(e){let t=e.trim();if(!t)return{result:{success:!1,error:"Codex accounts require a non-empty label."}};let n=Si(t);if(n)return{result:{success:!1,error:n}};let r=(0,ui.randomUUID)(),i=R(r);en(r),fi(r,{label:t,addedAt:new Date().toISOString()});let c=N();return yi(c,i),pi(c,i)?{finalize:{profileId:r,codexHome:i}}:{result:{success:!0,profileId:r,codexHome:i,needsLogin:!0}}}function Ci(e){let t=un(e);return"finalize"in t?{...dn(t.finalize.profileId),...t.finalize,needsLogin:!1}:t.result}async function Oi(e){let t=un(e);return"finalize"in t?{...await ln(t.finalize.profileId),...t.finalize,needsLogin:!1}:t.result}function sn(e,t,n){let r=Qe(e);if(!r)return{result:{success:!1,error:`Codex profile ${e} was not prepared.`}};let i=R(e);if(!n.authenticated)return{result:{success:!1,error:"Codex profile is not authenticated yet."}};let c={id:e,providerId:"codex",label:r.label,email:n.metadata.email,addedAt:r.addedAt,metadata:n.metadata};return(0,_.upsertSavedAccountProfile)(c),t.activate===!1?{result:{success:!0}}:te(i)?{swap:c}:((0,_.setActiveSavedAccount)("codex",e),{result:{success:!0,warning:"Codex stores credentials in the OS keyring; sidekick cannot swap them per account, so `codex` keeps using the keyring credentials."}})}function dn(e,t={}){if(!Qe(e))return{success:!1,error:`Codex profile ${e} was not prepared.`};let n=R(e),r=on(n),i=sn(e,t,{authenticated:r,metadata:r?rn(n):{}});return"swap"in i?yn(i.swap):i.result}async function ln(e,t={}){if(!Qe(e))return{success:!1,error:`Codex profile ${e} was not prepared.`};let n=R(e),r=await an(n),i=sn(e,t,{authenticated:r,metadata:r?await cn(n):{}});return"swap"in i?pn(i.swap):i.result}function Qt(){return u.join((0,_.getAccountsDir)(),"codex","stash")}function fn(e,t){try{let n=new Date().toISOString().replace(/[:.]/g,"-"),r=null;if(e&&(r=u.join(Qt(),`auth-${n}.json`),(0,S.atomicWriteFileSync)(r,e)),t){let i=u.join(Qt(),`credentials-${n}.json`);(0,S.atomicWriteFileSync)(i,t),r=r??i}return r}catch{return null}}function Xe(e){let t=Y();if(e?.workspaceId){let n=t.find(r=>r.metadata?.workspaceId===e.workspaceId);if(n)return n}if(e?.email){let n=t.find(r=>(r.email??r.metadata?.email)===e.email);if(n)return n}return!e?.workspaceId&&!e?.email?Ae():null}function ji(e,t){if(!e&&!t)return{};try{let n=B(e),r=Xe(n);if(!r){let c=fn(e,t);return{stashPath:c??void 0,warning:c?`Live Codex credentials did not match any saved account; stashed at ${c}.`:"Live Codex credentials did not match any saved account and could not be stashed."}}let i=R(r.id);e&&(0,S.atomicWriteFileSync)(u.join(i,"auth.json"),e),t&&(0,S.atomicWriteFileSync)(u.join(i,".credentials.json"),t);try{let c=ve(i)??{};(0,_.upsertSavedAccountProfile)({...r,email:c.email??r.email,metadata:{...r.metadata,...c}})}catch{}return{syncedProfileId:r.id}}catch(n){return{warning:`Could not back up live Codex credentials: ${n}`}}}function Se(e){let t=u.join((0,_.getAccountsDir)(),"codex");return g.mkdirSync(t,{recursive:!0,mode:448}),(0,S.withFileLockSync)(u.join(t,"auth-swap.lock"),e)}function Ii(){let e=N();return{codexRunning:vi(),systemKeyringLoggedIn:te(e)?!1:he(e).loggedIn}}async function bi(){let e=N();return{codexRunning:await Ai(),systemKeyringLoggedIn:te(e)?!1:(await ge(e)).loggedIn}}function yn(e){let t=Ii();try{return Se(()=>mn(e,t))}catch(n){return{success:!1,error:`Could not acquire the account-switch lock: ${n}`}}}async function pn(e){let t=await bi();try{return Se(()=>mn(e,t))}catch(n){return{success:!1,error:`Could not acquire the account-switch lock: ${n}`}}}function mn(e,t){let n=N(),r=u.join(n,"auth.json"),i=u.join(n,".credentials.json"),c=H(r),o=H(i);if(!c&&!o&&t.systemKeyringLoggedIn)return{success:!1,error:'Codex stores credentials in the OS keyring; file-based account switching is not supported. Set `cli_auth_credentials_store = "file"` in ~/.codex/config.toml and run `codex login` again.'};let d=R(e.id),s=u.join(d,"auth.json"),y=H(s),M=H(u.join(d,".credentials.json")),q=e.label??e.email??e.id;if(!y&&!M)return{success:!1,error:`No stored credentials for "${q}". Remove and re-add this account.`};if(y&&!Ge(y))return{success:!1,error:`Stored credentials for "${q}" are corrupted. Remove and re-add this account.`};let $=[];t.codexRunning&&$.push("A codex process appears to be running; restart codex sessions so they pick up the switched account.");let P=B(c),X=B(y),it=e.metadata?.workspaceId??X?.workspaceId,ct=e.email??e.metadata?.email??X?.email;if(!!(P?.workspaceId&&it&&P.workspaceId===it||P?.email&&ct&&P.email===ct||c!==null&&c===y||!c&&!y&&o!==null&&o===M)){try{c&&(0,S.atomicWriteFileSync)(s,c),o&&(0,S.atomicWriteFileSync)(u.join(d,".credentials.json"),o);let U=ve(d)??{};(0,_.upsertSavedAccountProfile)({...e,email:U.email??e.email,metadata:{...e.metadata,...U}})}catch{}return(0,_.setActiveSavedAccount)("codex",e.id),{success:!0,warning:$.length?$.join(" "):void 0}}let ot=ke(y,s);ot!==null&&Date.now()-ot>si&&$.push(`Stored credentials for "${q}" have not been refreshed in over 8 days; codex may ask you to log in again.`);let at=ji(c,o);at.warning&&$.push(at.warning);let ut=()=>{try{c?(0,S.atomicWriteFileSync)(r,c):g.rmSync(r,{force:!0}),o?(0,S.atomicWriteFileSync)(i,o):g.rmSync(i,{force:!0})}catch{}};try{y?((0,S.atomicWriteFileSync)(r,y),M?(0,S.atomicWriteFileSync)(i,M):o&&g.rmSync(i,{force:!0})):((0,S.atomicWriteFileSync)(i,M),c&&g.rmSync(r,{force:!0}))}catch(U){return ut(),{success:!1,error:`Failed to write Codex credentials: ${U}`}}try{(0,_.setActiveSavedAccount)("codex",e.id)}catch(U){return ut(),{success:!1,error:`Failed to update account registry: ${U}`}}return{success:!0,warning:$.length?$.join(" "):void 0}}function Pi(e){let t=Y().find(n=>n.id===e);return t?yn(t):{success:!1,error:`Codex account ${e} not found.`}}async function Di(e){let t=Y().find(n=>n.id===e);return t?pn(t):{success:!1,error:`Codex account ${e} not found.`}}function hn(){let e=u.join((0,_.getAccountsDir)(),"codex",".live-auth-migrated-v1");return g.existsSync(e)?!1:!g.existsSync(u.join(N(),"auth.json"))}function xi(){try{let e=hn()?he(N()).loggedIn:!1;Se(()=>gn({systemKeyringLoggedIn:e}))}catch{}}async function Mi(){try{let e=hn()?(await ge(N())).loggedIn:!1;Se(()=>gn({systemKeyringLoggedIn:e}))}catch{}}function gn(e){try{let t=u.join((0,_.getAccountsDir)(),"codex",".live-auth-migrated-v1");if(g.existsSync(t))return;let n=()=>(0,S.atomicWriteFileSync)(t,new Date().toISOString()+`
7
- `),r=Ae();if(!r){n();return}let i=R(r.id),c=u.join(i,"auth.json"),o=H(c);if(!o){n();return}let d=N(),s=u.join(d,"auth.json"),y=H(s);if(!y){e.systemKeyringLoggedIn||(0,S.atomicWriteFileSync)(s,o),n();return}let M=B(y),q=B(o);if(!!(M?.workspaceId&&q?.workspaceId&&M.workspaceId===q.workspaceId||M?.email&&M.email===q?.email)){let P=ke(y,s),X=ke(o,c);X!==null&&(P===null||X>P)?(fn(y,null),(0,S.atomicWriteFileSync)(s,o)):(0,S.atomicWriteFileSync)(c,y)}else{let P=Xe(M);P&&P.id!==r.id&&((0,S.atomicWriteFileSync)(u.join(R(P.id),"auth.json"),y),(0,_.setActiveSavedAccount)("codex",P.id))}n()}catch{}}function Ei(e){return(0,_.removeSavedAccountProfile)("codex",e)?(g.rmSync(Ve(e),{recursive:!0,force:!0}),{success:!0}):{success:!1,error:`Codex account ${e} not found.`}}});var An=w(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getActiveAccountStatus=Ti;var Ri=Vt(),Ni=vn();function Fi(e){return e instanceof Error?e.message:String(e)}function Ti(e){try{let t=(0,Ri.resolveActiveClaudeAccount)(),n=(0,Ni.resolveActiveCodexAccount)(),r=t.source!=="none"?{present:!0,...t.registryAccountId?{accountId:t.registryAccountId}:{},email:t.email,label:t.label??t.email}:{present:!1},i=n.source!=="none"?{present:!0,...n.registryAccountId?{accountId:n.registryAccountId}:{},email:n.email,label:n.label??n.email??n.providerAccountId}:{present:!1};return{ok:r.present||i.present,claude:r,codex:i,error:e}}catch(t){return{ok:!1,claude:{present:!1},codex:{present:!1},error:e??Fi(t)}}}});var Sn=w(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.isAggregateCodexLimit=Li;function Li(e){return!e||e==="codex"}});var Dn=w(F=>{"use strict";var $i=F&&F.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Hi=F&&F.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Cn=F&&F.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&$i(n,t,r[i]);return Hi(n,t),n}})();Object.defineProperty(F,"__esModule",{value:!0});F.writeQuotaSnapshot=Ui;F.readQuotaSnapshot=Ki;var On=Cn(f("fs")),qi=Cn(f("path")),jn=be(),In=Z(),_n=Sn();function tt(){return qi.join((0,jn.getConfigDir)(),"quota-snapshots.json")}function bn(){On.mkdirSync((0,jn.getConfigDir)(),{recursive:!0,mode:448})}function Pn(){try{let e=JSON.parse(On.readFileSync(tt(),"utf8"));if(e?.version===1&&Array.isArray(e.snapshots))return e}catch{}return{version:1,snapshots:[]}}function Wi(e){bn(),(0,In.atomicWriteJsonSync)(tt(),e)}function Bi(e){return bn(),(0,In.withFileLockSync)(`${tt()}.lock`,e)}function wn(e){let t=e.capturedAt?Date.parse(e.capturedAt):NaN;return Number.isFinite(t)?t:0}function _e(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function zi(e,t){let n=(0,_n.isAggregateCodexLimit)(e.limitId),r=(0,_n.isAggregateCodexLimit)(t.limitId);if(n!==r)return n;let i=_e(e.fiveHour.resetsAt),c=_e(t.fiveHour.resetsAt);if(i!==c)return i>c;let o=_e(e.sevenDay.resetsAt),d=_e(t.sevenDay.resetsAt);if(o!==d)return o>d;let s=e.fiveHour.utilization+e.sevenDay.utilization,y=t.fiveHour.utilization+t.sevenDay.utilization;return s!==y?s>y:wn(e)>wn(t)}function Ui(e,t,n){Bi(()=>{let r=Pn(),i=r.snapshots.findIndex(s=>s.providerId===e&&s.accountId===t),c=i>=0?r.snapshots[i].quota:void 0,o={...n,providerId:e,capturedAt:n.capturedAt??new Date().toISOString(),source:n.source??"session",stale:!1,resetCredits:n.resetCredits??(e==="codex"?c?.resetCredits:void 0)};if(i>=0&&zi(r.snapshots[i].quota,o))return;let d={providerId:e,accountId:t,quota:o};i>=0?r.snapshots[i]=d:r.snapshots.push(d),Wi(r)})}function Ki(e,t){let r=Pn().snapshots.find(i=>i.providerId===e&&i.accountId===t);return r?{...r.quota,providerId:e,source:"cache",stale:!0}:null}});var rt=w(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.BurnRateCalculator=void 0;ne.estimateTimeToQuota=xn;var nt=class{events=[];windowMs;constructor(t=5){this.windowMs=t*6e4}addEvent(t,n=new Date){this.events.push({tokens:t,timestamp:n}),this.pruneOldEvents(n)}calculateBurnRate(t=new Date){if(this.pruneOldEvents(t),this.events.length===0)return 0;let n=this.events.reduce((i,c)=>i+c.tokens,0),r=Math.max((t.getTime()-this.events[0].timestamp.getTime())/6e4,1);return n/r}estimateTimeToQuota(t,n,r=new Date){return xn(t,n,this.calculateBurnRate(r))}getEventCount(){return this.events.length}reset(){this.events=[]}pruneOldEvents(t){let n=t.getTime()-this.windowMs;this.events=this.events.filter(r=>r.timestamp.getTime()>=n)}};ne.BurnRateCalculator=nt;function xn(e,t,n){if(n<=0)return null;let r=t-e;return r<=0?0:r/n}});var Mn=w(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.SEVEN_DAY_WINDOW_MS=j.FIVE_HOUR_WINDOW_MS=j.QUOTA_PROVIDER_IDS=void 0;j.projectQuotaWindow=ie;j.withQuotaProjections=Gi;j.fetchQuota=Xi;var ki=Me();Object.defineProperty(j,"QUOTA_PROVIDER_IDS",{enumerable:!0,get:function(){return ki.QUOTA_PROVIDER_IDS}});var Ji="https://api.anthropic.com/api/oauth/usage",Vi="oauth-2025-04-20",Qi=1e4;j.FIVE_HOUR_WINDOW_MS=5*36e5;j.SEVEN_DAY_WINDOW_MS=7*864e5;function ie(e){let{utilization:t,resetsAt:n,windowMs:r,capturedAt:i}=e;if(!n||t<=0||!Number.isFinite(t)||r<=0)return;let c=new Date(n).getTime();if(!Number.isFinite(c))return;let o=i?Date.parse(i):NaN,d=Number.isFinite(o)?o:Date.now(),s=r-(c-d);if(!(s<=0))return Math.min(Math.round(t*(r/s)),200)}function Gi(e,t={}){if(!e.available)return e;let n={...e},r=t.capturedAt??e.capturedAt;if(n.projectedFiveHour==null){let i=ie({utilization:n.fiveHour.utilization,resetsAt:n.fiveHour.resetsAt,windowMs:t.fiveHourWindowMs??j.FIVE_HOUR_WINDOW_MS,capturedAt:r});i!==void 0&&(n.projectedFiveHour=i)}if(n.projectedSevenDay==null){let i=ie({utilization:n.sevenDay.utilization,resetsAt:n.sevenDay.resetsAt,windowMs:t.sevenDayWindowMs??j.SEVEN_DAY_WINDOW_MS,capturedAt:r});i!==void 0&&(n.projectedSevenDay=i)}return n}function re(e,t={}){return{fiveHour:{utilization:0,resetsAt:""},sevenDay:{utilization:0,resetsAt:""},available:!1,error:e,...t}}function Yi(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.round(t*1e3);let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(n-Date.now(),0)}async function Xi(e){let t=new AbortController,n=setTimeout(()=>t.abort(),Qi);n.unref();try{let r=await fetch(Ji,{method:"GET",signal:t.signal,headers:{Authorization:`Bearer ${e}`,"anthropic-beta":Vi,"Content-Type":"application/json"}});if(!r.ok)return r.status===401?re("Sign in to Claude Code to view quota",{failureKind:"auth",httpStatus:r.status}):r.status===429?re(`API error: ${r.status}`,{failureKind:"rate_limit",httpStatus:r.status,retryAfterMs:Yi(r.headers.get("retry-after"))}):r.status>=500&&r.status<=599?re(`API error: ${r.status}`,{failureKind:"server",httpStatus:r.status}):re(`API error: ${r.status}`,{failureKind:"unknown",httpStatus:r.status});let i=await r.json(),c=i.five_hour?.utilization??0,o=i.seven_day?.utilization??0,d=i.five_hour?.resets_at??"",s=i.seven_day?.resets_at??"";return{fiveHour:{utilization:c,resetsAt:d},sevenDay:{utilization:o,resetsAt:s},available:!0,projectedFiveHour:ie({utilization:c,resetsAt:d,windowMs:j.FIVE_HOUR_WINDOW_MS}),projectedSevenDay:ie({utilization:o,resetsAt:s,windowMs:j.SEVEN_DAY_WINDOW_MS})}}catch{return re("Network error",{failureKind:"network"})}finally{clearTimeout(n)}}});var Rn=w(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.selectStatuslineAccount=En;we.formatStatusline=tc;var Zi=Mn(),ec=rt();function En(e){return e.accounts.claude.present?{providerId:"claude-code",accountId:e.accounts.claude.accountId,accountLabel:e.accounts.claude.label??e.accounts.claude.email??"claude",quota:e.claudeQuota??null}:e.accounts.codex.present?{providerId:"codex",accountId:e.accounts.codex.accountId,accountLabel:e.accounts.codex.label??e.accounts.codex.email??"codex",quota:e.codexQuota??null}:null}function tc(e){let t=En(e);if(!t)return"acct:none \xB7 quota unavailable";let n=rc(t.accountLabel),r=t.quota;if(!r?.available)return`acct:${n} \xB7 quota unavailable`;let i=e.now??new Date,c=ic(r.fiveHour.utilization),o=cc(r.fiveHour.resetsAt,i),d=nc(r,i),s=d==null?"":` \xB7 ~${oc(d)} left`;return`acct:${n} \xB7 5h ${Math.round(c)}% resets ${o}${s}`}function nc(e,t){let n=Date.parse(e.fiveHour.resetsAt);if(!Number.isFinite(n))return null;let r=t.getTime();if(n<=r)return null;let i=e.capturedAt?Date.parse(e.capturedAt):t.getTime(),c=Number.isFinite(i)?i:t.getTime();if(c>=n)return null;let o=(c-(n-Zi.FIVE_HOUR_WINDOW_MS))/6e4;if(o<=0||e.fiveHour.utilization<=0)return null;let d=e.fiveHour.utilization/o,s=(0,ec.estimateTimeToQuota)(e.fiveHour.utilization,100,d),y=(n-r)/6e4;return s!==null&&s<y?s:null}function rc(e){let t=e.trim();return(t.includes("@")?t.split("@")[0]:t).replace(/\s+/g,"-").slice(0,24)||"unknown"}function ic(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}function cc(e,t){let n=new Date(e),r=Number.isNaN(n.getTime())?t:n;return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}).format(r)}function oc(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}min`;let n=Math.floor(t/60),r=t%60;return r?`${n}h${r}m`:`${n}h`}});var Tn=w(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.selectStatuslineAccount=b.formatStatusline=b.estimateTimeToQuota=b.BurnRateCalculator=b.readQuotaSnapshot=b.getActiveAccountStatus=void 0;var ac=An();Object.defineProperty(b,"getActiveAccountStatus",{enumerable:!0,get:function(){return ac.getActiveAccountStatus}});var uc=Dn();Object.defineProperty(b,"readQuotaSnapshot",{enumerable:!0,get:function(){return uc.readQuotaSnapshot}});var Nn=rt();Object.defineProperty(b,"BurnRateCalculator",{enumerable:!0,get:function(){return Nn.BurnRateCalculator}});Object.defineProperty(b,"estimateTimeToQuota",{enumerable:!0,get:function(){return Nn.estimateTimeToQuota}});var Fn=Rn();Object.defineProperty(b,"formatStatusline",{enumerable:!0,get:function(){return Fn.formatStatusline}});Object.defineProperty(b,"selectStatuslineAccount",{enumerable:!0,get:function(){return Fn.selectStatuslineAccount}})});var z=kn(Tn(),1);function Ln(){let e=(0,z.getActiveAccountStatus)(),t=e.claude.accountId?(0,z.readQuotaSnapshot)("claude-code",e.claude.accountId):null,n=e.codex.accountId?(0,z.readQuotaSnapshot)("codex",e.codex.accountId):null;process.stdout.write(`${(0,z.formatStatusline)({accounts:e,claudeQuota:t,codexQuota:n})}
8
- `)}var $n=["--project","--provider"],sc=["--json","--no-color"];function dc(e){for(let t=0;t<e.length;t++){let n=e[t];if(!sc.includes(n)){if($n.includes(n)){t++;continue}if(!$n.some(r=>n.startsWith(`${r}=`)))return n}}}function Hn(e){return dc(e)==="statusline"}Hn(process.argv.slice(2))?Ln():await import("./sidekick-main.mjs");
4
+ var $r=Object.create;var Ht=Object.defineProperty;var zr=Object.getOwnPropertyDescriptor;var qr=Object.getOwnPropertyNames;var kr=Object.getPrototypeOf,Wr=Object.prototype.hasOwnProperty;var y=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var C=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}};var Ur=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of qr(t))!Wr.call(e,i)&&i!==n&&Ht(e,i,{get:()=>t[i],enumerable:!(r=zr(t,i))||r.enumerable});return e};var Qr=(e,t,n)=>(n=e!=null?$r(kr(e)):{},Ur(t||!e||!e.__esModule?Ht(n,"default",{value:e,enumerable:!0}):n,e));var pe=C(S=>{"use strict";var Br=S&&S.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Kr=S&&S.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Qe=S&&S.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Br(n,t,r[i]);return Kr(n,t),n}})();Object.defineProperty(S,"__esModule",{value:!0});S.CONFIG_DIR_ENV_VAR=void 0;S.getDefaultConfigDir=zt;S.setConfigDir=Vr;S.getConfigDirOverride=Gr;S.getConfigDir=Be;S.getProjectDataPath=Yr;S.getGlobalDataPath=Xr;S.encodeWorkspacePath=Ue;S.getProjectSlug=Zr;S.resolveProjectIdentity=Ke;S.getProjectSlugRaw=ei;var Jr=Qe(y("fs")),G=Qe(y("path")),$t=Qe(y("os"));S.CONFIG_DIR_ENV_VAR="SIDEKICK_CONFIG_DIR";var _e=null;function zt(){return process.platform==="win32"?G.join(process.env.APPDATA||$t.homedir(),"sidekick"):G.join($t.homedir(),".config","sidekick")}function Vr(e){let t=e?.trim();_e=t?G.resolve(t):null}function Gr(){return _e}function Be(){if(_e)return _e;let e=process.env[S.CONFIG_DIR_ENV_VAR]?.trim();return e?G.resolve(e):zt()}function Yr(e,t){return G.join(Be(),t,`${e}.json`)}function Xr(e){return G.join(Be(),e)}function Ue(e){return e.replace(/\\/g,"/").replace(/[:/_]/g,"-")}function Zr(e){return Ke(e).canonicalSlug}function Ke(e){let t=G.resolve(e||process.cwd()),n;try{n=Jr.realpathSync(t)}catch{n=t}let r=Ue(n),i=Ue(t);return{cwd:t,resolvedCwd:n,canonicalSlug:r,legacySlug:i,candidates:r===i?[r]:[r,i],hasLegacyMismatch:r!==i}}function ei(e){return Ke(e).legacySlug}});var Y=C(x=>{"use strict";var ti=x&&x.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),ni=x&&x.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Ve=x&&x.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&ti(n,t,r[i]);return ni(n,t),n}})();Object.defineProperty(x,"__esModule",{value:!0});x.atomicWriteJson=kt;x.atomicWriteJsonSync=Wt;x.atomicWriteFileSync=Ut;x.updateJsonStoreAtomic=ui;x.withFileLockSync=Bt;x.updateJsonStoreAtomicSync=fi;var oe=Ve(y("crypto")),d=Ve(y("fs")),ie=Ve(y("path")),Je=1e4,re=3e3,ri=12e4,qt=15e3,ii=15,oi=new Int32Array(new SharedArrayBuffer(4));async function ci(e){let t;try{t=await d.promises.open(e,"r"),await t.sync()}catch(n){let r=n.code;if(!["EISDIR","EINVAL","ENOSYS","EPERM","EACCES"].includes(r??""))throw n}finally{await t?.close().catch(()=>{})}}function ai(e){let t;try{t=d.openSync(e,"r"),d.fsyncSync(t)}catch(n){let r=n.code;if(!["EISDIR","EINVAL","ENOSYS","EPERM","EACCES"].includes(r??""))throw n}finally{t!==void 0&&d.closeSync(t)}}async function kt(e,t){await d.promises.mkdir(ie.dirname(e),{recursive:!0,mode:448});let n=`${e}.${process.pid}.${oe.randomBytes(8).toString("hex")}.tmp`,r;try{r=await d.promises.open(n,"wx",384),await r.writeFile(JSON.stringify(t,null,2),"utf8"),await r.sync(),await r.close(),r=void 0,await d.promises.rename(n,e),await ci(ie.dirname(e))}catch(i){throw await r?.close().catch(()=>{}),await d.promises.rm(n,{force:!0}).catch(()=>{}),i}}function Wt(e,t){Ut(e,JSON.stringify(t,null,2))}function Ut(e,t,n=384){d.mkdirSync(ie.dirname(e),{recursive:!0,mode:448});let r=`${e}.${process.pid}.${oe.randomBytes(8).toString("hex")}.tmp`,i;try{i=d.openSync(r,"wx",n),d.writeFileSync(i,t,{encoding:"utf8"}),d.fsyncSync(i),d.closeSync(i),i=void 0,d.renameSync(r,e),ai(ie.dirname(e))}catch(o){throw i!==void 0&&d.closeSync(i),d.rmSync(r,{force:!0}),o}}async function ui(e,t,n){await d.promises.mkdir(ie.dirname(e),{recursive:!0,mode:448});let r=`${e}.lock`,i=await si(r);try{let o=t(),c;try{c=await d.promises.readFile(e,"utf8")}catch(u){if(u.code!=="ENOENT")throw u}if(c!==void 0)try{o=JSON.parse(c)}catch{let u=`${e}.corrupt-${Date.now()}-${oe.randomBytes(4).toString("hex")}`;await d.promises.rename(e,u)}let a=await n(o);return await kt(e,a),a}finally{await li(r,i)}}async function si(e){let t=Date.now()+re,n=null;for(;;)try{let r=await d.promises.open(e,"wx",384),i=`${process.pid}:${oe.randomBytes(16).toString("hex")}`;await r.writeFile(i,"utf8"),await r.sync();let o=setInterval(()=>{d.promises.utimes(e,new Date,new Date).catch(()=>{})},Math.floor(Je/3));return o.unref(),{handle:r,token:i,heartbeat:o}}catch(r){if(r.code!=="EEXIST")throw r;let i=await d.promises.readFile(e,"utf8").catch(()=>null);i!==null&&i!==n&&(n=i,t=Date.now()+re);try{let o=await d.promises.stat(e),c=Date.now()-o.mtimeMs;c>Je&&!Qt(i,c)&&await d.promises.rm(e,{force:!0})}catch{}if(Date.now()>=t)throw new Error(`Timed out waiting for store lock: ${e} (no progress for ${re}ms)`);await new Promise(o=>setTimeout(o,15))}}async function li(e,t){clearInterval(t.heartbeat),await t.handle.close().catch(()=>{});try{await d.promises.readFile(e,"utf8")===t.token&&await d.promises.rm(e,{force:!0})}catch{}}function Qt(e,t){if(t>ri)return!1;let n=Number.parseInt((e??"").split(":",1)[0],10);if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(r){return r.code==="EPERM"}}function Bt(e,t){let n=di(e);try{return t()}finally{try{d.readFileSync(e,"utf8")===n&&d.rmSync(e,{force:!0})}catch{}}}function di(e){let t=Date.now(),n=t+re,r=null;for(;;)try{let i=d.openSync(e,"wx",384),o=`${process.pid}:${oe.randomBytes(16).toString("hex")}`;return d.writeFileSync(i,o,"utf8"),d.fsyncSync(i),d.closeSync(i),o}catch(i){if(i.code!=="EEXIST")throw i;let o=null;try{o=d.readFileSync(e,"utf8")}catch{}o!==null&&o!==r&&(r=o,n=Date.now()+re);try{let a=d.statSync(e),u=Date.now()-a.mtimeMs;u>Je&&!Qt(o,u)&&d.rmSync(e,{force:!0})}catch{}let c=Date.now();if(c>=n)throw new Error(`Timed out waiting for store lock: ${e} (no progress for ${re}ms)`);if(c-t>=qt)throw new Error(`Timed out waiting for store lock: ${e} (blocked synchronously for ${qt}ms)`);Atomics.wait(oi,0,0,ii)}}function fi(e,t,n){return d.mkdirSync(ie.dirname(e),{recursive:!0,mode:448}),Bt(`${e}.lock`,()=>{let r=t(),i;try{i=d.readFileSync(e,"utf8")}catch(c){if(c.code!=="ENOENT")throw c}if(i!==void 0)try{r=JSON.parse(i)}catch{let c=`${e}.corrupt-${Date.now()}-${oe.randomBytes(4).toString("hex")}`;d.renameSync(e,c)}let o=n(r);return Wt(e,o),o})}});var Kt=C(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we._onRawAccountsChanged=pi;we._emitAccountsChanged=yi;var Ge=new Set;function pi(e){return Ge.add(e),()=>Ge.delete(e)}function yi(e){for(let t of Ge)try{t(e)}catch{}}});var Ye=C(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.MODEL_PROVIDER_IDS=L.RUNTIME_QUOTA_PROVIDER_IDS=L.QUOTA_PROVIDER_IDS=L.ACCOUNT_PROVIDER_IDS=L.SESSION_PROVIDER_IDS=void 0;L.SESSION_PROVIDER_IDS=["claude-code","opencode","codex"];L.ACCOUNT_PROVIDER_IDS=["claude-code","codex"];L.QUOTA_PROVIDER_IDS=["claude-code","codex","zai"];L.RUNTIME_QUOTA_PROVIDER_IDS=["claude","codex","zai"];L.MODEL_PROVIDER_IDS=["anthropic","openai","google","unknown"]});var Ce=C(v=>{"use strict";var mi=v&&v.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),hi=v&&v.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Jt=v&&v.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&mi(n,t,r[i]);return hi(n,t),n}})();Object.defineProperty(v,"__esModule",{value:!0});v.ACCOUNT_PROVIDER_IDS=void 0;v.getAccountsDir=Xe;v.withSavedAccountRegistryLock=Yt;v.readSavedAccountRegistry=ye;v.writeSavedAccountRegistry=_i;v.listSavedAccountProfiles=wi;v.getActiveSavedAccount=bi;v.upsertSavedAccountProfile=Ci;v.setActiveSavedAccount=Oi;v.replaceSavedAccountProfiles=Ii;v.replaceSavedAccountProfilesUnlocked=Di;v.removeSavedAccountProfile=Pi;var Vt=Jt(y("fs")),Gt=Jt(y("path")),gi=pe(),be=Y(),Si=Kt(),vi=Ye();Object.defineProperty(v,"ACCOUNT_PROVIDER_IDS",{enumerable:!0,get:function(){return vi.ACCOUNT_PROVIDER_IDS}});function Xe(){return Gt.join((0,gi.getConfigDir)(),"accounts")}function Ze(){return Gt.join(Xe(),"accounts.json")}function et(){return Ze()+".lock"}function tt(){Vt.mkdirSync(Xe(),{recursive:!0,mode:448})}function nt(e,t={}){(0,be.atomicWriteJsonSync)(Ze(),en(e)),t.silent||(0,Si._emitAccountsChanged)("local")}function Yt(e){return tt(),(0,be.withFileLockSync)(et(),e)}function rt(e,t={}){return Yt(()=>Xt(e,t))}function Xt(e,t={}){let n=e(ye()??Zt());return nt(n,t),n}function Zt(){return{version:2,activeByProvider:{"claude-code":null,codex:null},accounts:[]}}function en(e){let t=Zt();return t.activeByProvider["claude-code"]=e.activeByProvider?.["claude-code"]??null,t.activeByProvider.codex=e.activeByProvider?.codex??null,t.accounts=Array.isArray(e.accounts)?e.accounts.filter(n=>!!n&&(n.providerId==="claude-code"||n.providerId==="codex")&&typeof n.id=="string"&&typeof n.addedAt=="string").map(n=>({...n,label:n.label||void 0,email:n.email||void 0,providerAccountId:n.providerAccountId||void 0,metadata:n.metadata?{email:n.metadata.email||void 0,workspaceId:n.metadata.workspaceId||void 0,planType:n.metadata.planType||void 0,authMode:n.metadata.authMode||void 0}:void 0})):[],t}function Ai(e){return{version:2,activeByProvider:{"claude-code":e.activeAccountUuid,codex:null},accounts:e.accounts.map(t=>({id:t.uuid,providerId:"claude-code",providerAccountId:t.uuid,email:t.email,label:t.label,addedAt:t.addedAt,metadata:{email:t.email}}))}}function ye(){try{let e=Vt.readFileSync(Ze(),"utf8"),t=JSON.parse(e);return t?.version===2?en(t):t?.version===1&&Array.isArray(t.accounts)?Ai(t):null}catch{return null}}function _i(e){tt(),(0,be.withFileLockSync)(et(),()=>nt(e))}function wi(e){let t=ye();return t?e?t.accounts.filter(n=>n.providerId===e):t.accounts:[]}function bi(e){let t=ye();if(!t)return null;let n=t.activeByProvider[e];return n?t.accounts.find(r=>r.providerId===e&&r.id===n)??null:null}function Ci(e){return rt(t=>{let n=t.accounts.findIndex(r=>r.providerId===e.providerId&&r.id===e.id);return n>=0?t.accounts[n]=e:t.accounts.push(e),t})}function Oi(e,t,n={}){return rt(r=>(r.activeByProvider[e]=t,r),n)}function tn(e,t,n){return r=>(r.accounts=r.accounts.filter(i=>i.providerId!==e).concat(t),r.activeByProvider[e]=n,r)}function Ii(e,t,n){return rt(tn(e,t,n))}function Di(e,t,n){return Xt(tn(e,t,n))}function Pi(e,t){return tt(),(0,be.withFileLockSync)(et(),()=>{let n=ye();if(!n)return null;let r=n.accounts.findIndex(o=>o.providerId===e&&o.id===t);if(r===-1)return null;let[i]=n.accounts.splice(r,1);return n.activeByProvider[e]===t&&(n.activeByProvider[e]=n.accounts.find(o=>o.providerId===e)?.id??null),nt(n),i})}});var ot=C(F=>{"use strict";var ji=F&&F.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Mi=F&&F.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),rn=F&&F.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&ji(n,t,r[i]);return Mi(n,t),n}})();Object.defineProperty(F,"__esModule",{value:!0});F.getClaudeProfilesDir=on;F.getClaudeProfileHome=cn;F.ensureClaudeProfileDirs=Ni;F.claudeKeychainSuffix=an;F.claudeKeychainService=un;F.readClaudeProfileIdentity=sn;F.keychainServiceExists=ln;F.isClaudeProfileAuthenticated=Ti;var Fi=y("child_process"),Ei=y("crypto"),it=rn(y("fs")),Oe=rn(y("path")),xi=Ce(),nn="Claude Code-credentials";function on(){return Oe.join((0,xi.getAccountsDir)(),"claude","profiles")}function cn(e){return Oe.join(on(),e,"home")}function Ni(e){it.mkdirSync(cn(e),{recursive:!0,mode:448})}function an(e){return(0,Ei.createHash)("sha256").update(e).digest("hex").slice(0,8)}function un(e){return e?`${nn}-${an(e)}`:nn}function sn(e){try{let t=JSON.parse(it.readFileSync(Oe.join(e,".claude.json"),"utf8")),n=t?.oauthAccount?.emailAddress,r=t?.oauthAccount?.accountUuid;return typeof n=="string"&&typeof r=="string"?{email:n,uuid:r}:null}catch{return null}}function ln(e){try{return(0,Fi.execFileSync)("security",["find-generic-password","-s",e],{stdio:["ignore","ignore","ignore"],timeout:4e3,killSignal:"SIGKILL"}),!0}catch{return!1}}function Ti(e){return(process.platform==="darwin"?ln(un(e)):it.existsSync(Oe.join(e,".credentials.json")))&&sn(e)!==null}});var mn=C(H=>{"use strict";var Ri=H&&H.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Li=H&&H.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ut=H&&H.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Ri(n,t,r[i]);return Li(n,t),n}})();Object.defineProperty(H,"__esModule",{value:!0});H.KEYCHAIN_SERVICE=void 0;H.readActiveCredentials=$i;H.writeActiveCredentials=zi;var at=ut(y("fs")),dn=ut(y("path")),Hi=ut(y("os")),fn=y("child_process"),pn=ot();H.KEYCHAIN_SERVICE="Claude Code-credentials";function ct(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function yn(e){return dn.join(e??dn.join(Hi.homedir(),".claude"),".credentials.json")}function $i(e){if(process.platform==="darwin")try{let t=(0,fn.execFileSync)("security",["find-generic-password","-s",(0,pn.claudeKeychainService)(e),"-w"],{encoding:"utf8",stdio:["pipe","pipe","pipe"],timeout:4e3,killSignal:"SIGKILL"});return JSON.parse(t.trim())}catch{return null}try{return JSON.parse(at.readFileSync(yn(e),"utf8"))}catch{return null}}function zi(e,t){let n=JSON.stringify(e);if(JSON.parse(n),process.platform==="darwin"){let o=(0,pn.claudeKeychainService)(t),c=process.env.USER||"user",a=["add-generic-password","-U","-s",ct(o),"-a",ct(c),"-w",ct(n)].join(" ");(0,fn.execFileSync)("security",["-i"],{input:a+`
5
+ `,stdio:["pipe","pipe","pipe"],timeout:4e3,killSignal:"SIGKILL"});return}let r=yn(t),i=r+".tmp";at.writeFileSync(i,n,{encoding:"utf8",mode:384}),at.renameSync(i,r)}});var Pn=C(w=>{"use strict";var qi=w&&w.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),ki=w&&w.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),lt=w&&w.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&qi(n,t,r[i]);return ki(n,t),n}})();Object.defineProperty(w,"__esModule",{value:!0});w.readAccountRegistry=De;w.writeAccountRegistry=Vi;w.readActiveClaudeAccount=Pe;w.addCurrentAccount=Gi;w.switchToAccount=Yi;w.resolveActiveClaudeHome=Zi;w.applyActiveClaudeToLiveHome=eo;w.reconcileClaudeAuthState=to;w.removeAccount=no;w.listAccounts=ro;w.getActiveAccount=Dn;w.resolveActiveClaudeAccount=io;w.isMultiAccountEnabled=oo;var E=lt(y("fs")),A=lt(y("path")),hn=lt(y("os")),$=mn(),U=Y(),_=Ce(),ue=ot();function gn(){return A.join(hn.homedir(),".claude")}function Q(){let e=A.join(gn(),".claude.json");try{if(JSON.parse(E.readFileSync(e,"utf8"))?.oauthAccount)return e}catch{}return A.join(hn.homedir(),".claude.json")}function ce(){return A.join((0,_.getAccountsDir)(),"credentials")}function ae(){return A.join((0,_.getAccountsDir)(),"configs")}function Wi(){return A.join((0,_.getAccountsDir)(),"claude",".profiles-migrated-v1")}function Ui(){for(let e of[(0,_.getAccountsDir)(),ce(),ae()])E.mkdirSync(e,{recursive:!0,mode:448})}function dt(e){try{return JSON.parse(E.readFileSync(e,"utf8"))}catch{return null}}function Sn(e){return dt(e)?.oauthAccount??null}function vn(e,t){(0,U.atomicWriteJsonSync)(A.join((0,ue.getClaudeProfileHome)(e),".claude.json"),{oauthAccount:t})}function An(e,t){(0,$.writeActiveCredentials)(t,(0,ue.getClaudeProfileHome)(e))}function Ie(e,t,n){vn(e,n),An(e,t)}function _n(e){return dt(A.join(ce(),`${e}.credentials.json`))}function wn(e){return dt(A.join(ae(),`${e}.config.json`))}function bn(e){return Sn(A.join((0,ue.getClaudeProfileHome)(e),".claude.json"))}function Qi(e){let t=(0,$.readActiveCredentials)((0,ue.getClaudeProfileHome)(e)),n=bn(e);if(t&&n)return{credentials:t,oauthAccount:n};let r=_n(e),i=wn(e);if(r&&i){try{Ie(e,r,i)}catch{}return{credentials:r,oauthAccount:i}}return null}function Bi(){return Sn(Q())}function Ki(){let e=Pe();if(!e)return;let t=(0,$.readActiveCredentials)(),n=Bi();if(t)try{(0,U.atomicWriteJsonSync)(A.join(ce(),`${e.uuid}.credentials.json`),t),An(e.uuid,t)}catch{}if(n)try{(0,U.atomicWriteJsonSync)(A.join(ae(),`${e.uuid}.config.json`),n),vn(e.uuid,n)}catch{}}function Ji(e){let t={};try{t=JSON.parse(E.readFileSync(Q(),"utf8"))}catch{}t.oauthAccount=e,(0,U.atomicWriteJsonSync)(Q(),t)}function De(){let e=(0,_.readSavedAccountRegistry)();if(!e)return null;let t=e.accounts.filter(n=>n.providerId==="claude-code").map(n=>({uuid:n.providerAccountId??n.id,email:n.email??n.metadata?.email??"unknown",label:n.label,addedAt:n.addedAt}));return{version:1,activeAccountUuid:e.activeByProvider["claude-code"],accounts:t}}function Vi(e){(0,_.replaceSavedAccountProfiles)("claude-code",Cn(e),e.activeAccountUuid)}function st(e){(0,_.replaceSavedAccountProfilesUnlocked)("claude-code",Cn(e),e.activeAccountUuid)}function Cn(e){return e.accounts.map(t=>({id:t.uuid,providerId:"claude-code",providerAccountId:t.uuid,email:t.email,label:t.label,addedAt:t.addedAt,metadata:{email:t.email}}))}function Pe(){try{let e=E.readFileSync(Q(),"utf8"),t=JSON.parse(e),n=t?.oauthAccount?.emailAddress,r=t?.oauthAccount?.accountUuid;return!n||!r?null:{email:n,uuid:r}}catch{return null}}function Gi(e){let t=Pe();if(!t)return{success:!1,error:"No active Claude account found. Sign in with `claude` first."};let n=(0,$.readActiveCredentials)();if(!n)return{success:!1,error:"Could not read Claude credentials."};let r;try{r=JSON.parse(E.readFileSync(Q(),"utf8")).oauthAccount}catch{return{success:!1,error:"Could not read Claude config file."}}return Ui(),(0,_.withSavedAccountRegistryLock)(()=>{let i=De()??{version:1,activeAccountUuid:null,accounts:[]},o=i.accounts.find(c=>c.uuid===t.uuid);if(o){e!==void 0&&(o.label=e),(0,U.atomicWriteJsonSync)(A.join(ce(),`${t.uuid}.credentials.json`),n),(0,U.atomicWriteJsonSync)(A.join(ae(),`${t.uuid}.config.json`),r);try{Ie(t.uuid,n,r)}catch{}return i.activeAccountUuid=t.uuid,st(i),{success:!0}}(0,U.atomicWriteJsonSync)(A.join(ce(),`${t.uuid}.credentials.json`),n),(0,U.atomicWriteJsonSync)(A.join(ae(),`${t.uuid}.config.json`),r);try{Ie(t.uuid,n,r)}catch{}return i.accounts.push({uuid:t.uuid,email:t.email,label:e,addedAt:new Date().toISOString()}),i.activeAccountUuid=t.uuid,st(i),{success:!0}})}function On(e){let t=A.join((0,_.getAccountsDir)(),"claude");return E.mkdirSync(t,{recursive:!0,mode:448}),(0,U.withFileLockSync)(A.join(t,"auth-swap.lock"),e)}function Yi(e){try{return On(()=>Xi(e))}catch(t){return{success:!1,error:`Could not acquire the account-switch lock: ${t}`}}}function Xi(e){let t=De();if(!t)return{success:!1,error:"No account registry found. Save an account first."};if(!t.accounts.find(c=>c.uuid===e))return{success:!1,error:`Account ${e} not found in registry.`};let r=null,i=null;r=(0,$.readActiveCredentials)();try{i=E.readFileSync(Q(),"utf8")}catch{}try{Ki()}catch{}try{(0,_.setActiveSavedAccount)("claude-code",e)}catch(c){return{success:!1,error:`Failed to update account registry: ${c}`}}let o=In();if(!o.success){try{(0,_.setActiveSavedAccount)("claude-code",t.activeAccountUuid)}catch{}if(r)try{(0,$.writeActiveCredentials)(r)}catch{}if(i)try{E.writeFileSync(Q(),i)}catch{}return o}return o}function Zi(){let e=(0,_.getActiveSavedAccount)("claude-code");return e?(0,ue.getClaudeProfileHome)(e.providerAccountId??e.id):gn()}function eo(){try{return On(In)}catch(e){return{success:!1,error:`Could not acquire the account-switch lock: ${e}`}}}function In(){let e=(0,_.getActiveSavedAccount)("claude-code");if(!e)return{success:!1,error:"No active Claude account found."};let t=e.providerAccountId??e.id,n=Qi(t);if(!n)return{success:!1,error:`Stored credentials for ${e.email??t} not found.`};let r=(0,$.readActiveCredentials)(),i=null;try{i=E.readFileSync(Q(),"utf8")}catch{}try{(0,$.writeActiveCredentials)(n.credentials)}catch(o){if(r)try{(0,$.writeActiveCredentials)(r)}catch{}return{success:!1,error:`Failed to write credentials: ${o}`}}try{Ji(n.oauthAccount)}catch(o){if(r)try{(0,$.writeActiveCredentials)(r)}catch{}if(i)try{E.writeFileSync(Q(),i)}catch{}return{success:!1,error:`Failed to write config: ${o}`}}return{success:!0}}function to(){try{let e=Wi();if(E.existsSync(e))return;let t=(0,_.readSavedAccountRegistry)();if(t)for(let n of t.accounts.filter(r=>r.providerId==="claude-code"))try{let r=n.providerAccountId??n.id;if((0,$.readActiveCredentials)((0,ue.getClaudeProfileHome)(r))&&bn(r))continue;let i=_n(r),o=wn(r);if(!i||!o)continue;Ie(r,i,o)}catch{}E.mkdirSync(A.dirname(e),{recursive:!0,mode:448}),E.writeFileSync(e,new Date().toISOString()+`
6
+ `,{encoding:"utf8",mode:384})}catch{}}function no(e){return(0,_.withSavedAccountRegistryLock)(()=>{let t=De();if(!t)return{success:!1,error:"No account registry found."};let n=t.accounts.findIndex(r=>r.uuid===e);if(n===-1)return{success:!1,error:`Account ${e} not found.`};try{E.unlinkSync(A.join(ce(),`${e}.credentials.json`))}catch{}try{E.unlinkSync(A.join(ae(),`${e}.config.json`))}catch{}return t.accounts.splice(n,1),t.activeAccountUuid===e&&(t.activeAccountUuid=t.accounts[0]?.uuid??null),st(t),{success:!0}})}function ro(){return(0,_.listSavedAccountProfiles)("claude-code").map(e=>({uuid:e.providerAccountId??e.id,email:e.email??e.metadata?.email??"unknown",label:e.label,addedAt:e.addedAt}))}function Dn(){let e=(0,_.getActiveSavedAccount)("claude-code");return e?{uuid:e.providerAccountId??e.id,email:e.email??e.metadata?.email??"unknown",label:e.label,addedAt:e.addedAt}:null}function io(e={}){let t=e.selfHeal??!0,n=Pe();if(n){let i=(0,_.listSavedAccountProfiles)("claude-code"),o=i.find(c=>(c.providerAccountId??c.id)===n.uuid)??i.find(c=>(c.email??c.metadata?.email)===n.email);if(o){let c=(0,_.getActiveSavedAccount)("claude-code");if(t&&(!c||c.id!==o.id))try{(0,_.setActiveSavedAccount)("claude-code",o.id,{silent:!0})}catch{}}return{email:n.email,label:o?.label,providerAccountId:n.uuid,registryAccountId:o?.id,source:"live"}}let r=Dn();return r?{email:r.email,label:r.label,providerAccountId:r.uuid,registryAccountId:r.uuid,source:"registry"}:{source:"none"}}function oo(){return(0,_.listSavedAccountProfiles)("claude-code").length>=1}});var Yn=C(m=>{"use strict";var co=m&&m.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),ao=m&&m.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),yt=m&&m.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&co(n,t,r[i]);return ao(n,t),n}})();Object.defineProperty(m,"__esModule",{value:!0});m.getSystemCodexHome=k;m.getCodexMonitoringHomes=po;m.getCodexProfilesDir=En;m.getCodexProfileHome=z;m.readCodexAccountMetadata=Ln;m.readCodexAccountMetadataAsync=Hn;m.isCodexProfileAuthenticated=$n;m.isCodexProfileAuthenticatedAsync=zn;m.listCodexAccounts=se;m.getActiveCodexAccount=Ne;m.resolveSidekickCodexHome=St;m.resolveActiveCodexAccount=bo;m.getCodexExecutionEnv=Co;m.prepareCodexAccount=Oo;m.prepareCodexAccountAsync=Io;m.finalizeCodexAccount=Wn;m.finalizeCodexAccountAsync=Un;m.switchToCodexAccount=Mo;m.switchToCodexAccountAsync=Fo;m.reconcileCodexAuthState=Eo;m.reconcileCodexAuthStateAsync=xo;m.removeCodexAccount=No;var b=yt(y("fs")),uo=yt(y("os")),p=yt(y("path")),je=y("child_process"),so=y("crypto"),M=Ce(),j=Y(),lo=11520*60*1e3;function Mn(){return p.join(uo.homedir(),".codex")}function Fn(){let e=process.env.CODEX_HOME?.trim();return e||null}function fo(e){let t=new Set,n=[];for(let r of e){let i=p.resolve(r);t.has(i)||(t.add(i),n.push(r))}return n}function k(){return Fn()??Mn()}function po(){let e=Fn();if(e)return[e];let t=[Mn()];for(let n of se()){let r=z(n.id);b.existsSync(p.join(r,"sessions"))&&t.push(r)}return fo(t)}function En(){return p.join((0,M.getAccountsDir)(),"codex","profiles")}function mt(e){return p.join(En(),e)}function z(e){return p.join(mt(e),"codex-home")}function xn(e){return p.join(mt(e),"profile.json")}function Nn(e){b.mkdirSync(z(e),{recursive:!0,mode:448})}function K(e){try{return b.readFileSync(e,"utf8")}catch{return null}}function ht(e){try{return JSON.parse(b.readFileSync(xn(e),"utf8"))}catch{return null}}function yo(e,t){Nn(e),(0,j.atomicWriteJsonSync)(xn(e),t)}function ft(e,t){return b.existsSync(e)?(b.mkdirSync(p.dirname(t),{recursive:!0,mode:448}),b.copyFileSync(e,t),!0):!1}function mo(e,t){ft(p.join(e,"config.toml"),p.join(t,"config.toml"))}function ho(e,t){let n=ft(p.join(e,"auth.json"),p.join(t,"auth.json")),r=ft(p.join(e,".credentials.json"),p.join(t,".credentials.json"));return n||r}function go(e){let t=e.split(".");if(t.length<2)return null;try{let n=Buffer.from(t[1],"base64url").toString("utf8");return JSON.parse(n)}catch{return null}}function gt(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function X(e){let t=gt(e);if(!t)return null;let n=t.tokens?.id_token,r=n?go(n):null,i=r?.["https://api.openai.com/profile"],o=r?.["https://api.openai.com/auth"],c=typeof r?.email=="string"?r.email:typeof i?.email=="string"?i.email:void 0,a=typeof o?.chatgpt_account_id=="string"?o.chatgpt_account_id:t.tokens?.account_id,u=typeof o?.chatgpt_plan_type=="string"?o.chatgpt_plan_type:void 0,s=t.OPENAI_API_KEY||t.auth_mode==="api_key"?"api-key":"chatgpt";return{email:c,workspaceId:a,planType:u,authMode:s}}function pt(e,t){let n=gt(e);if(n?.last_refresh){let r=Date.parse(n.last_refresh);if(!Number.isNaN(r))return r}if(t)try{return b.statSync(t).mtimeMs}catch{}return null}function So(e){let t=X(K(p.join(e,"auth.json")));return t?{email:t.email,workspaceId:t.workspaceId,planType:t.planType,authMode:t.authMode}:{}}function vo(e){let t=p.join(e,".credentials.json");if(!b.existsSync(t))return{};try{let n=JSON.parse(b.readFileSync(t,"utf8"));if(typeof n.OPENAI_API_KEY=="string"||typeof n.CODEX_API_KEY=="string")return{authMode:"api-key"}}catch{}return{}}var Me=4e3;function Tn(e,t){let n=t.trim();return e===0&&/^Logged in/i.test(n)?/API key/i.test(n)?{loggedIn:!0,authMode:"api-key"}:/ChatGPT/i.test(n)?{loggedIn:!0,authMode:"chatgpt"}:{loggedIn:!0}:{loggedIn:!1}}function Fe(e){try{let t={...process.env,CODEX_HOME:e},n=(0,je.spawnSync)("codex",["login","status"],{encoding:"utf8",env:t,timeout:Me,killSignal:"SIGKILL"});return Tn(n.status,String(n.stdout??""))}catch{}return{loggedIn:!1}}function Ee(e){return new Promise(t=>{try{let n={...process.env,CODEX_HOME:e};(0,je.execFile)("codex",["login","status"],{encoding:"utf8",env:n,timeout:Me,killSignal:"SIGKILL"},(r,i)=>{t(r?{loggedIn:!1}:Tn(0,String(i??"")))})}catch{t({loggedIn:!1})}})}function Ao(){if(process.platform==="win32")return!1;try{return(0,je.spawnSync)("pgrep",["-x","codex"],{encoding:"utf8",timeout:Me,killSignal:"SIGKILL"}).status===0}catch{return!1}}function _o(){return process.platform==="win32"?Promise.resolve(!1):new Promise(e=>{try{(0,je.execFile)("pgrep",["-x","codex"],{encoding:"utf8",timeout:Me,killSignal:"SIGKILL"},t=>e(!t))}catch{e(!1)}})}function xe(e){let t=So(e);if(t.email||t.workspaceId||t.planType||t.authMode)return t;let n=vo(e);return n.authMode?n:null}function Rn(e){return e.loggedIn?{authMode:e.authMode??"unknown"}:{}}function Ln(e){return xe(e)??Rn(Fe(e))}async function Hn(e){return xe(e)??Rn(await Ee(e))}function me(e){return b.existsSync(p.join(e,"auth.json"))||b.existsSync(p.join(e,".credentials.json"))}function $n(e){return me(e)||Fe(e).loggedIn}async function zn(e){return me(e)||(await Ee(e)).loggedIn}function wo(e,t){let n=e.trim().toLowerCase();return se().find(i=>i.id!==t&&(i.label??"").trim().toLowerCase()===n)?`A Codex account named "${e}" already exists.`:null}function se(){return(0,M.listSavedAccountProfiles)("codex")}function Ne(){return(0,M.getActiveSavedAccount)("codex")}function St(){return k()}function bo(e={}){let t=e.selfHeal??!0,n=X(K(p.join(St(),"auth.json")));if(n&&(n.email||n.workspaceId)){let i=vt(n);if(i){let o=(0,M.getActiveSavedAccount)("codex");if(t&&(!o||o.id!==i.id))try{(0,M.setActiveSavedAccount)("codex",i.id)}catch{}}return{email:n.email??i?.email??i?.metadata?.email,label:i?.label,providerAccountId:i?.providerAccountId??n.workspaceId,registryAccountId:i?.id,source:"live"}}let r=Ne();return r?{email:r.email??r.metadata?.email,label:r.label,providerAccountId:r.providerAccountId,registryAccountId:r.id,source:"registry"}:{source:"none"}}function Co(e=process.env){return{...e,CODEX_HOME:St()}}function qn(e){let t=e.trim();if(!t)return{result:{success:!1,error:"Codex accounts require a non-empty label."}};let n=wo(t);if(n)return{result:{success:!1,error:n}};let r=(0,so.randomUUID)(),i=z(r);Nn(r),yo(r,{label:t,addedAt:new Date().toISOString()});let o=k();return mo(o,i),ho(o,i)?{finalize:{profileId:r,codexHome:i}}:{result:{success:!0,profileId:r,codexHome:i,needsLogin:!0}}}function Oo(e){let t=qn(e);return"finalize"in t?{...Wn(t.finalize.profileId),...t.finalize,needsLogin:!1}:t.result}async function Io(e){let t=qn(e);return"finalize"in t?{...await Un(t.finalize.profileId),...t.finalize,needsLogin:!1}:t.result}function kn(e,t,n){let r=ht(e);if(!r)return{result:{success:!1,error:`Codex profile ${e} was not prepared.`}};let i=z(e);if(!n.authenticated)return{result:{success:!1,error:"Codex profile is not authenticated yet."}};let o={id:e,providerId:"codex",label:r.label,email:n.metadata.email,addedAt:r.addedAt,metadata:n.metadata};return(0,M.upsertSavedAccountProfile)(o),t.activate===!1?{result:{success:!0}}:me(i)?{swap:o}:((0,M.setActiveSavedAccount)("codex",e),{result:{success:!0,warning:"Codex stores credentials in the OS keyring; sidekick cannot swap them per account, so `codex` keeps using the keyring credentials."}})}function Wn(e,t={}){if(!ht(e))return{success:!1,error:`Codex profile ${e} was not prepared.`};let n=z(e),r=$n(n),i=kn(e,t,{authenticated:r,metadata:r?Ln(n):{}});return"swap"in i?Bn(i.swap):i.result}async function Un(e,t={}){if(!ht(e))return{success:!1,error:`Codex profile ${e} was not prepared.`};let n=z(e),r=await zn(n),i=kn(e,t,{authenticated:r,metadata:r?await Hn(n):{}});return"swap"in i?Kn(i.swap):i.result}function jn(){return p.join((0,M.getAccountsDir)(),"codex","stash")}function Qn(e,t){try{let n=new Date().toISOString().replace(/[:.]/g,"-"),r=null;if(e&&(r=p.join(jn(),`auth-${n}.json`),(0,j.atomicWriteFileSync)(r,e)),t){let i=p.join(jn(),`credentials-${n}.json`);(0,j.atomicWriteFileSync)(i,t),r=r??i}return r}catch{return null}}function vt(e){let t=se();if(e?.workspaceId){let n=t.find(r=>r.metadata?.workspaceId===e.workspaceId);if(n)return n}if(e?.email){let n=t.find(r=>(r.email??r.metadata?.email)===e.email);if(n)return n}return!e?.workspaceId&&!e?.email?Ne():null}function Do(e,t){if(!e&&!t)return{};try{let n=X(e),r=vt(n);if(!r){let o=Qn(e,t);return{stashPath:o??void 0,warning:o?`Live Codex credentials did not match any saved account; stashed at ${o}.`:"Live Codex credentials did not match any saved account and could not be stashed."}}let i=z(r.id);e&&(0,j.atomicWriteFileSync)(p.join(i,"auth.json"),e),t&&(0,j.atomicWriteFileSync)(p.join(i,".credentials.json"),t);try{let o=xe(i)??{};(0,M.upsertSavedAccountProfile)({...r,email:o.email??r.email,metadata:{...r.metadata,...o}})}catch{}return{syncedProfileId:r.id}}catch(n){return{warning:`Could not back up live Codex credentials: ${n}`}}}function Te(e){let t=p.join((0,M.getAccountsDir)(),"codex");return b.mkdirSync(t,{recursive:!0,mode:448}),(0,j.withFileLockSync)(p.join(t,"auth-swap.lock"),e)}function Po(){let e=k();return{codexRunning:Ao(),systemKeyringLoggedIn:me(e)?!1:Fe(e).loggedIn}}async function jo(){let e=k();return{codexRunning:await _o(),systemKeyringLoggedIn:me(e)?!1:(await Ee(e)).loggedIn}}function Bn(e){let t=Po();try{return Te(()=>Jn(e,t))}catch(n){return{success:!1,error:`Could not acquire the account-switch lock: ${n}`}}}async function Kn(e){let t=await jo();try{return Te(()=>Jn(e,t))}catch(n){return{success:!1,error:`Could not acquire the account-switch lock: ${n}`}}}function Jn(e,t){let n=k(),r=p.join(n,"auth.json"),i=p.join(n,".credentials.json"),o=K(r),c=K(i);if(!o&&!c&&t.systemKeyringLoggedIn)return{success:!1,error:'Codex stores credentials in the OS keyring; file-based account switching is not supported. Set `cli_auth_credentials_store = "file"` in ~/.codex/config.toml and run `codex login` again.'};let a=z(e.id),u=p.join(a,"auth.json"),s=K(u),f=K(p.join(a,".credentials.json")),I=e.label??e.email??e.id;if(!s&&!f)return{success:!1,error:`No stored credentials for "${I}". Remove and re-add this account.`};if(s&&!gt(s))return{success:!1,error:`Stored credentials for "${I}" are corrupted. Remove and re-add this account.`};let D=[];t.codexRunning&&D.push("A codex process appears to be running; restart codex sessions so they pick up the switched account.");let P=X(o),R=X(s),de=e.metadata?.workspaceId??R?.workspaceId,fe=e.email??e.metadata?.email??R?.email;if(!!(P?.workspaceId&&de&&P.workspaceId===de||P?.email&&fe&&P.email===fe||o!==null&&o===s||!o&&!s&&c!==null&&c===f)){try{o&&(0,j.atomicWriteFileSync)(u,o),c&&(0,j.atomicWriteFileSync)(p.join(a,".credentials.json"),c);let ne=xe(a)??{};(0,M.upsertSavedAccountProfile)({...e,email:ne.email??e.email,metadata:{...e.metadata,...ne}})}catch{}return(0,M.setActiveSavedAccount)("codex",e.id),{success:!0,warning:D.length?D.join(" "):void 0}}let te=pt(s,u);te!==null&&Date.now()-te>lo&&D.push(`Stored credentials for "${I}" have not been refreshed in over 8 days; codex may ask you to log in again.`);let B=Do(o,c);B.warning&&D.push(B.warning);let Lt=()=>{try{o?(0,j.atomicWriteFileSync)(r,o):b.rmSync(r,{force:!0}),c?(0,j.atomicWriteFileSync)(i,c):b.rmSync(i,{force:!0})}catch{}};try{s?((0,j.atomicWriteFileSync)(r,s),f?(0,j.atomicWriteFileSync)(i,f):c&&b.rmSync(i,{force:!0})):((0,j.atomicWriteFileSync)(i,f),o&&b.rmSync(r,{force:!0}))}catch(ne){return Lt(),{success:!1,error:`Failed to write Codex credentials: ${ne}`}}try{(0,M.setActiveSavedAccount)("codex",e.id)}catch(ne){return Lt(),{success:!1,error:`Failed to update account registry: ${ne}`}}return{success:!0,warning:D.length?D.join(" "):void 0}}function Mo(e){let t=se().find(n=>n.id===e);return t?Bn(t):{success:!1,error:`Codex account ${e} not found.`}}async function Fo(e){let t=se().find(n=>n.id===e);return t?Kn(t):{success:!1,error:`Codex account ${e} not found.`}}function Vn(){let e=p.join((0,M.getAccountsDir)(),"codex",".live-auth-migrated-v1");return b.existsSync(e)?!1:!b.existsSync(p.join(k(),"auth.json"))}function Eo(){try{let e=Vn()?Fe(k()).loggedIn:!1;Te(()=>Gn({systemKeyringLoggedIn:e}))}catch{}}async function xo(){try{let e=Vn()?(await Ee(k())).loggedIn:!1;Te(()=>Gn({systemKeyringLoggedIn:e}))}catch{}}function Gn(e){try{let t=p.join((0,M.getAccountsDir)(),"codex",".live-auth-migrated-v1");if(b.existsSync(t))return;let n=()=>(0,j.atomicWriteFileSync)(t,new Date().toISOString()+`
7
+ `),r=Ne();if(!r){n();return}let i=z(r.id),o=p.join(i,"auth.json"),c=K(o);if(!c){n();return}let a=k(),u=p.join(a,"auth.json"),s=K(u);if(!s){e.systemKeyringLoggedIn||(0,j.atomicWriteFileSync)(u,c),n();return}let f=X(s),I=X(c);if(!!(f?.workspaceId&&I?.workspaceId&&f.workspaceId===I.workspaceId||f?.email&&f.email===I?.email)){let P=pt(s,u),R=pt(c,o);R!==null&&(P===null||R>P)?(Qn(s,null),(0,j.atomicWriteFileSync)(u,c)):(0,j.atomicWriteFileSync)(o,s)}else{let P=vt(f);P&&P.id!==r.id&&((0,j.atomicWriteFileSync)(p.join(z(P.id),"auth.json"),s),(0,M.setActiveSavedAccount)("codex",P.id))}n()}catch{}}function No(e){return(0,M.removeSavedAccountProfile)("codex",e)?(b.rmSync(mt(e),{recursive:!0,force:!0}),{success:!0}):{success:!1,error:`Codex account ${e} not found.`}}});var Xn=C(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.getActiveAccountStatus=Ho;var To=Pn(),Ro=Yn();function Lo(e){return e instanceof Error?e.message:String(e)}function Ho(e,t={}){try{let n=(0,To.resolveActiveClaudeAccount)(t),r=(0,Ro.resolveActiveCodexAccount)(t),i=n.source!=="none"?{present:!0,...n.registryAccountId?{accountId:n.registryAccountId}:{},email:n.email,label:n.label??n.email}:{present:!1},o=r.source!=="none"?{present:!0,...r.registryAccountId?{accountId:r.registryAccountId}:{},email:r.email,label:r.label??r.email??r.providerAccountId}:{present:!1};return{ok:i.present||o.present,claude:i,codex:o,error:e}}catch(n){return{ok:!1,claude:{present:!1},codex:{present:!1},error:e??Lo(n)}}}});var Se=C(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.QUOTA_AGING_MAX_AGE_MS=h.QUOTA_FRESH_MAX_AGE_MS=h.SEVEN_DAY_WINDOW_MS=h.FIVE_HOUR_WINDOW_MS=h.QUOTA_PROVIDER_IDS=void 0;h.classifyQuotaFreshness=Wo;h.formatQuotaAge=Uo;h.projectQuotaWindow=ge;h.withQuotaProjections=Qo;h.fetchQuota=Ko;var $o=Ye();Object.defineProperty(h,"QUOTA_PROVIDER_IDS",{enumerable:!0,get:function(){return $o.QUOTA_PROVIDER_IDS}});var zo="https://api.anthropic.com/api/oauth/usage",qo="oauth-2025-04-20",ko=1e4;h.FIVE_HOUR_WINDOW_MS=5*36e5;h.SEVEN_DAY_WINDOW_MS=7*864e5;h.QUOTA_FRESH_MAX_AGE_MS=5*6e4;h.QUOTA_AGING_MAX_AGE_MS=60*6e4;function Wo(e){return typeof e!="number"||!Number.isFinite(e)||e<0?"stale":e<h.QUOTA_FRESH_MAX_AGE_MS?"fresh":e<h.QUOTA_AGING_MAX_AGE_MS?"aging":"stale"}function Uo(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return"age unknown";let t=Math.floor(e/6e4);if(t<1)return"just now";if(t<60)return`${t}m ago`;let n=Math.floor(t/60);return n<48?`${n}h ago`:`${Math.floor(n/24)}d ago`}function ge(e){let{utilization:t,resetsAt:n,windowMs:r,capturedAt:i}=e;if(!n||t<=0||!Number.isFinite(t)||r<=0)return;let o=new Date(n).getTime();if(!Number.isFinite(o))return;let c=i?Date.parse(i):NaN,a=Number.isFinite(c)?c:Date.now(),u=r-(o-a);if(!(u<=0))return Math.min(Math.round(t*(r/u)),200)}function Qo(e,t={}){if(!e.available)return e;let n={...e},r=t.capturedAt??e.capturedAt;if(n.projectedFiveHour==null){let i=ge({utilization:n.fiveHour.utilization,resetsAt:n.fiveHour.resetsAt,windowMs:t.fiveHourWindowMs??h.FIVE_HOUR_WINDOW_MS,capturedAt:r});i!==void 0&&(n.projectedFiveHour=i)}if(n.projectedSevenDay==null){let i=ge({utilization:n.sevenDay.utilization,resetsAt:n.sevenDay.resetsAt,windowMs:t.sevenDayWindowMs??h.SEVEN_DAY_WINDOW_MS,capturedAt:r});i!==void 0&&(n.projectedSevenDay=i)}return n}function he(e,t={}){return{fiveHour:{utilization:0,resetsAt:""},sevenDay:{utilization:0,resetsAt:""},available:!1,error:e,...t}}function Bo(e){if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return Math.round(t*1e3);let n=Date.parse(e);if(!Number.isNaN(n))return Math.max(n-Date.now(),0)}async function Ko(e,t={}){let n=new AbortController,r=setTimeout(()=>n.abort(),ko);r.unref();try{let o=await(t.fetchImpl??fetch)(zo,{method:"GET",signal:n.signal,headers:{Authorization:`Bearer ${e}`,"anthropic-beta":qo,"Content-Type":"application/json"}});if(!o.ok)return o.status===401?he("Sign in to Claude Code to view quota",{failureKind:"auth",httpStatus:o.status}):o.status===429?he(`API error: ${o.status}`,{failureKind:"rate_limit",httpStatus:o.status,retryAfterMs:Bo(o.headers.get("retry-after"))}):o.status>=500&&o.status<=599?he(`API error: ${o.status}`,{failureKind:"server",httpStatus:o.status}):he(`API error: ${o.status}`,{failureKind:"unknown",httpStatus:o.status});let c=await o.json(),a=c.five_hour?.utilization??0,u=c.seven_day?.utilization??0,s=c.five_hour?.resets_at??"",f=c.seven_day?.resets_at??"";return{fiveHour:{utilization:a,resetsAt:s},sevenDay:{utilization:u,resetsAt:f},available:!0,projectedFiveHour:ge({utilization:a,resetsAt:s,windowMs:h.FIVE_HOUR_WINDOW_MS}),projectedSevenDay:ge({utilization:u,resetsAt:f,windowMs:h.SEVEN_DAY_WINDOW_MS})}}catch{return he("Network error",{failureKind:"network"})}finally{clearTimeout(r)}}});var Zn=C(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.isAggregateCodexLimit=Jo;function Jo(e){return!e||e==="codex"}});var Ct=C(W=>{"use strict";var Vo=W&&W.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Go=W&&W.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),tr=W&&W.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Vo(n,t,r[i]);return Go(n,t),n}})();Object.defineProperty(W,"__esModule",{value:!0});W.writeQuotaSnapshot=nc;W.readQuotaSnapshot=rc;var nr=tr(y("fs")),Yo=tr(y("path")),rr=pe(),ir=Y(),Xo=Se(),er=Zn();function bt(){return Yo.join((0,rr.getConfigDir)(),"quota-snapshots.json")}function or(){nr.mkdirSync((0,rr.getConfigDir)(),{recursive:!0,mode:448})}function cr(){try{let e=JSON.parse(nr.readFileSync(bt(),"utf8"));if(e?.version===1&&Array.isArray(e.snapshots))return e}catch{}return{version:1,snapshots:[]}}function Zo(e){or(),(0,ir.atomicWriteJsonSync)(bt(),e)}function ec(e){return or(),(0,ir.withFileLockSync)(`${bt()}.lock`,e)}function wt(e){let t=e.capturedAt?Date.parse(e.capturedAt):NaN;return Number.isFinite(t)?t:0}function Re(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function tc(e,t){let n=(0,er.isAggregateCodexLimit)(e.limitId),r=(0,er.isAggregateCodexLimit)(t.limitId);if(n!==r)return n;let i=Re(e.fiveHour.resetsAt),o=Re(t.fiveHour.resetsAt);if(i!==o)return i>o;let c=Re(e.sevenDay.resetsAt),a=Re(t.sevenDay.resetsAt);if(c!==a)return c>a;let u=e.fiveHour.utilization+e.sevenDay.utilization,s=t.fiveHour.utilization+t.sevenDay.utilization;return u!==s?u>s:wt(e)>wt(t)}function nc(e,t,n){ec(()=>{let r=cr(),i=r.snapshots.findIndex(f=>f.providerId===e&&f.accountId===t),o=i>=0?r.snapshots[i].quota:void 0,{capturedSource:c,...a}=n;delete a.ageMs,delete a.freshness;let u={...a,providerId:e,capturedAt:n.capturedAt??new Date().toISOString(),source:a.source&&a.source!=="cache"?a.source:c??"session",stale:!1,resetCredits:n.resetCredits??(e==="codex"?o?.resetCredits:void 0)};if(i>=0&&tc(r.snapshots[i].quota,u))return;let s={providerId:e,accountId:t,quota:u};i>=0?r.snapshots[i]=s:r.snapshots.push(s),Zo(r)})}function rc(e,t,n=new Date){let i=cr().snapshots.find(s=>s.providerId===e&&s.accountId===t);if(!i)return null;let o=wt(i.quota),c=o>0?Math.max(0,n.getTime()-o):void 0,a=i.quota.capturedSource??i.quota.source,u=a&&a!=="cache"?a:void 0;return{...i.quota,providerId:e,source:"cache",...u?{capturedSource:u}:{},stale:!0,...c!==void 0?{ageMs:c}:{},freshness:(0,Xo.classifyQuotaFreshness)(c)}}});var sr=C(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.formatTokenCount=ic;Z.formatDurationMs=oc;Z.formatLocalDateKey=ar;Z.parseLocalDateKey=ur;Z.addLocalDays=cc;function ic(e,t={}){if(!Number.isFinite(e))return"0";let n=Math.trunc(e),r=n<0?"-":"",i=Math.abs(n),o=t.suffixCase==="upper"?"K":"k";return i>=1e6?`${r}${(i/1e6).toFixed(1)}M`:i>=1e3?`${r}${(i/1e3).toFixed(1)}${o}`:`${n}`}function oc(e,t={}){let n=t.invalid??"N/A";if(!Number.isFinite(e)||e<0)return n;let i=(t.style??"spaced")==="compact"?"":" ",o=t.secondsFractionDigits??0;if(e<1e3)return t.includeMilliseconds?`${Math.round(e)}ms`:`${(e/1e3).toFixed(Math.max(1,o))}s`;let c=e/1e3;if(c<60)return o>0?`${c.toFixed(o)}s`:`${Math.floor(c)}s`;let a=Math.floor(c),u=Math.floor(a/3600),s=Math.floor(a%3600/60),f=a%60;return u>0?`${u}h${i}${s}m${i}${f}s`:`${s}m${i}${f}s`}function ar(e=new Date){let t=typeof e=="number"?new Date(e):e;if(Number.isNaN(t.getTime()))return"";let n=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${n}-${r}-${i}`}function ur(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let n=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(n.getTime())?null:n}function cc(e,t){let n=ur(e);return n?ar(new Date(n.getFullYear(),n.getMonth(),n.getDate()+t)):e}});var Sr=C(N=>{"use strict";var ac=N&&N.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),uc=N&&N.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),It=N&&N.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&ac(n,t,r[i]);return uc(n,t),n}})();Object.defineProperty(N,"__esModule",{value:!0});N.getWorkspaceIdFromPath=pc;N.appendQuotaHistorySample=Ac;N.readQuotaHistoryRange=gr;N.readQuotaHistoryDailyBuckets=_c;N.pruneQuotaHistory=wc;N._resetQuotaHistoryInMemoryStateForTests=bc;var sc=It(y("crypto")),q=It(y("fs")),Dt=It(y("path")),lr=sr(),dr=pe(),lc=Ct(),fr=Y(),dc=6e4,Pt=91,fc=16*1024,pr=864e5,ve=new Map,Le=new Map;function pc(e){let t;try{t=q.realpathSync(e)}catch{t=Dt.resolve(e)}return sc.createHash("sha256").update(t).digest("hex").slice(0,16)}function jt(e,t){return Dt.join((0,dr.getConfigDir)(),"quota-history",e,`${t}.jsonl`)}function yc(e){q.mkdirSync(Dt.join((0,dr.getConfigDir)(),"quota-history",e),{recursive:!0,mode:448})}function He(e){let t=e.trim();if(!t)return null;try{let n=JSON.parse(t);return n&&typeof n=="object"&&typeof n.timestamp=="string"&&n.fiveHour&&n.sevenDay?n:null}catch{return null}}function mc(e){let t;try{t=q.openSync(e,"r");let n=q.fstatSync(t);if(n.size===0)return null;let r=4096,i=n.size,o=Buffer.alloc(0);for(;i>0;){let c=Math.min(r,i),a=Buffer.alloc(c);q.readSync(t,a,0,c,i-c),o=Buffer.concat([a,o]),i-=c;let s=o.toString("utf8").replace(/\n+$/,""),f=s.lastIndexOf(`
8
+ `);if(f>=0){let I=s.slice(f+1),D=He(I);return D&&Date.parse(D.timestamp)||null}if(i===0){let I=He(s);return I&&Date.parse(I.timestamp)||null}}return null}catch(n){return n?.code==="ENOENT",null}finally{if(t!==void 0)try{q.closeSync(t)}catch{}}}function hc(e,t){return(0,fr.withFileLockSync)(`${e}.lock`,t)}function gc(e,t){(0,fr.atomicWriteFileSync)(e,t,384)}function yr(e,t){let n;try{n=q.statSync(e)}catch{return{kept:0,pruned:0}}if(n.size===0)return{kept:0,pruned:0};let r=Date.now()-t*pr,o=q.readFileSync(e,"utf8").split(`
9
+ `),c=[],a=0;for(let u of o){if(!u.trim())continue;let s=He(u);if(!s){a+=1;continue}let f=Date.parse(s.timestamp);Number.isFinite(f)&&f>=r?c.push(u):a+=1}return a>0&&gc(e,c.length>0?c.join(`
10
+ `)+`
11
+ `:""),{kept:c.length,pruned:a}}function Sc(e){let t=mr(e.runtimeProvider);return{fiveHour:{utilization:e.fiveHour.utilization,resetsAt:e.fiveHour.resetsAt},sevenDay:{utilization:e.sevenDay.utilization,resetsAt:e.sevenDay.resetsAt},available:e.available,error:e.error,providerId:t,source:e.source??"session",capturedAt:e.timestamp,stale:e.stale}}function mr(e){return e==="claude"?"claude-code":e==="zai"?"zai":"codex"}async function vc(e,t,n){let r=Le.get(t);if(r===void 0){let c=mc(t);c!==null&&(r=c,Le.set(t,c))}let i=Date.parse(e.timestamp);if(r!==void 0&&Number.isFinite(i)&&i-r<n.minIntervalMs)return;yc(e.workspaceId);let o=JSON.stringify(e)+`
12
+ `;hc(t,()=>{q.appendFileSync(t,o,{encoding:"utf8",mode:384});try{q.statSync(t).size>=fc&&yr(t,n.retentionDays)}catch{}}),Le.set(t,Number.isFinite(i)?i:Date.now());try{let c=mr(e.runtimeProvider);(0,lc.writeQuotaSnapshot)(c,e.providerId,Sc(e))}catch{}}async function Ac(e,t={}){let n={minIntervalMs:t.minIntervalMs??dc,retentionDays:t.retentionDays??Pt},r=jt(e.workspaceId,e.runtimeProvider),o=(ve.get(r)??Promise.resolve()).then(()=>vc(e,r,n)).catch(()=>{});ve.set(r,o);try{await o}finally{ve.get(r)===o&&ve.delete(r)}}function hr(){let e=Date.now();return{fromMs:e-Pt*pr,toMs:e}}async function gr(e){let t=jt(e.workspaceId,e.provider),n;try{n=await q.promises.readFile(t,"utf8")}catch(u){if(u?.code==="ENOENT")return[];throw u}let{fromMs:r,toMs:i}=hr(),o=e.from?Date.parse(e.from):r,c=e.to?Date.parse(e.to):i,a=[];for(let u of n.split(`
13
+ `)){let s=He(u);if(!s)continue;let f=Date.parse(s.timestamp);Number.isFinite(f)&&(f<o||f>c||a.push(s))}return a.sort((u,s)=>Date.parse(u.timestamp)-Date.parse(s.timestamp)),a}function Ot(e){return(0,lr.formatLocalDateKey)(e)}async function _c(e){let t=await gr(e),{fromMs:n,toMs:r}=hr(),i=e.from?Date.parse(e.from):n,o=e.to?Date.parse(e.to):r,c=Ot(i),a=Ot(o),u=new Map;for(let I of t){let D=Date.parse(I.timestamp);if(!Number.isFinite(D))continue;let P=Ot(D),R=u.get(P);R?R.push(I):u.set(P,[I])}let s=[],f=c;for(let I=0;I<=366&&f<=a;I+=1){let D=u.get(f);if(!D||D.length===0)s.push({date:f,samples:0,maxUtilizationFiveHour:0,maxUtilizationSevenDay:0,avgUtilizationFiveHour:0,avgUtilizationSevenDay:0,anyUnavailable:!1});else{let P=0,R=0,de=0,fe=0,We=!1;for(let B of D)P=Math.max(P,B.fiveHour.utilization),R=Math.max(R,B.sevenDay.utilization),de+=B.fiveHour.utilization,fe+=B.sevenDay.utilization,B.available||(We=!0);let te=D.length;s.push({date:f,samples:te,maxUtilizationFiveHour:P,maxUtilizationSevenDay:R,avgUtilizationFiveHour:Math.round(de/te*100)/100,avgUtilizationSevenDay:Math.round(fe/te*100)/100,anyUnavailable:We})}f=(0,lr.addLocalDays)(f,1)}return s}async function wc(e,t,n=Pt){let r=jt(e,t);return yr(r,n)}function bc(){ve.clear(),Le.clear()}});var Ft=C(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.BurnRateCalculator=void 0;Ae.estimateTimeToQuota=vr;var Mt=class{events=[];windowMs;constructor(t=5){this.windowMs=t*6e4}addEvent(t,n=new Date){this.events.push({tokens:t,timestamp:n}),this.pruneOldEvents(n)}calculateBurnRate(t=new Date){if(this.pruneOldEvents(t),this.events.length===0)return 0;let n=this.events.reduce((i,o)=>i+o.tokens,0),r=Math.max((t.getTime()-this.events[0].timestamp.getTime())/6e4,1);return n/r}estimateTimeToQuota(t,n,r=new Date){return vr(t,n,this.calculateBurnRate(r))}getEventCount(){return this.events.length}reset(){this.events=[]}pruneOldEvents(t){let n=t.getTime()-this.windowMs;this.events=this.events.filter(r=>r.timestamp.getTime()>=n)}};Ae.BurnRateCalculator=Mt;function vr(e,t,n){if(n<=0)return null;let r=t-e;return r<=0?0:r/n}});var wr=C(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.selectStatuslineAccount=_r;ze.formatStatusline=Oc;var Ar=Se(),Cc=Ft();function _r(e){return e.accounts.claude.present?{providerId:"claude-code",accountId:e.accounts.claude.accountId,accountLabel:e.accounts.claude.label??e.accounts.claude.email??"claude",quota:e.claudeQuota??null}:e.accounts.codex.present?{providerId:"codex",accountId:e.accounts.codex.accountId,accountLabel:e.accounts.codex.label??e.accounts.codex.email??"codex",quota:e.codexQuota??null}:null}function Oc(e){let t=_r(e),n=e.now??new Date,r=Ic(e.live);if(!t)return Et(["acct:none","quota unavailable",...r]);let i=jc(t.accountLabel),o=t.quota;if(!o?.available)return Et([`acct:${i}`,"quota unavailable",...r]);let c=$e(o.fiveHour.utilization),a=Mc(o.fiveHour.resetsAt,n),u=Pc(o,n),s=[`acct:${i}`,`5h ${Math.round(c)}% resets ${a}`];return u!=null&&s.push(`~${Fc(u)} left`),o.sevenDay.resetsAt&&o.sevenDay.utilization>0&&s.push(`7d ${Math.round($e(o.sevenDay.utilization))}%`),o.freshness&&o.freshness!=="fresh"&&s.push(`(${(0,Ar.formatQuotaAge)(o.ageMs)})`),Et([...s,...r])}function Ic(e){if(!e)return[];let t=[],n=e.contextWindow?.usedPercentage;typeof n=="number"&&t.push(`ctx ${Math.round($e(n))}%`);let r=e.cost?.totalCostUsd;typeof r=="number"&&r>0&&t.push(`$${Dc(r)}`);let i=e.promptCache?.hitRatio;return typeof i=="number"&&t.push(`cache ${Math.round($e(i*100))}%`),t}function Et(e){return e.join(" \xB7 ")}function Dc(e){return e>=100?e.toFixed(0):e>=10?e.toFixed(1):e.toFixed(2)}function Pc(e,t){let n=Date.parse(e.fiveHour.resetsAt);if(!Number.isFinite(n))return null;let r=t.getTime();if(n<=r)return null;let i=e.capturedAt?Date.parse(e.capturedAt):t.getTime(),o=Number.isFinite(i)?i:t.getTime();if(o>=n)return null;let c=(o-(n-Ar.FIVE_HOUR_WINDOW_MS))/6e4;if(c<=0||e.fiveHour.utilization<=0)return null;let a=e.fiveHour.utilization/c,u=(0,Cc.estimateTimeToQuota)(e.fiveHour.utilization,100,a),s=(n-r)/6e4;return u!==null&&u<s?u:null}function jc(e){let t=e.trim();return(t.includes("@")?t.split("@")[0]:t).replace(/\s+/g,"-").slice(0,24)||"unknown"}function $e(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}function Mc(e,t){let n=new Date(e),r=Number.isNaN(n.getTime())?t:n;return new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1}).format(r)}function Fc(e){let t=Math.max(0,Math.round(e));if(t<60)return`${t}min`;let n=Math.floor(t/60),r=t%60;return r?`${n}h${r}m`:`${n}h`}});var Or=C(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.parseClaudeStatuslinePayload=Ec;qe.quotaFromStatuslinePayload=xc;function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function xt(e){return e===null?null:T(e)}function J(e){return typeof e=="string"&&e.length>0?e:void 0}function br(e){return typeof e=="boolean"?e:void 0}function Nt(e){if(!V(e))return;let t=T(e.used_percentage),n=T(e.resets_at);if(!(t===void 0||n===void 0))return{usedPercentage:t,resetsAt:n}}function le(e){return Object.values(e).some(t=>t!==void 0)?e:void 0}function Ec(e){if(typeof e!="string"||!e.trim())return null;let t;try{t=JSON.parse(e)}catch{return null}if(!V(t))return null;let n=V(t.model)?t.model:void 0,r=V(t.workspace)?t.workspace:void 0,i=V(t.context_window)?t.context_window:void 0,o=V(t.cost)?t.cost:void 0,c=V(t.rate_limits)?t.rate_limits:void 0,a=V(t.prompt_cache)?t.prompt_cache:void 0;return{sessionId:J(t.session_id),transcriptPath:J(t.transcript_path),cwd:J(t.cwd),model:n?le({id:J(n.id),displayName:J(n.display_name)}):void 0,workspace:r?le({currentDir:J(r.current_dir),projectDir:J(r.project_dir),gitWorktree:J(r.git_worktree)}):void 0,contextWindow:i?le({usedPercentage:xt(i.used_percentage),remainingPercentage:xt(i.remaining_percentage),contextWindowSize:T(i.context_window_size),totalInputTokens:T(i.total_input_tokens),totalOutputTokens:T(i.total_output_tokens)}):void 0,cost:o?le({totalCostUsd:T(o.total_cost_usd),totalDurationMs:T(o.total_duration_ms),totalApiDurationMs:T(o.total_api_duration_ms),totalLinesAdded:T(o.total_lines_added),totalLinesRemoved:T(o.total_lines_removed)}):void 0,rateLimits:c?le({fiveHour:Nt(c.five_hour),sevenDay:Nt(c.seven_day),spendLimit:Nt(c.spend_limit)}):void 0,promptCache:a?le({warm:br(a.warm),cachingObserved:br(a.caching_observed),hitRatio:xt(a.hit_ratio),requests:T(a.requests),misses:T(a.misses),expectedRebuilds:T(a.expected_rebuilds)}):void 0,raw:t}}function Cr(e,t){return e?{utilization:Math.max(0,e.usedPercentage),resetsAt:new Date(e.resetsAt*1e3).toISOString()}:t??{utilization:0,resetsAt:""}}function xc(e,t={}){let n=e.rateLimits;if(!n?.fiveHour&&!n?.sevenDay)return null;let r=t.now??new Date,i=t.fallback??void 0;return{fiveHour:Cr(n.fiveHour,i?.fiveHour),sevenDay:Cr(n.sevenDay,i?.sevenDay),available:!0,providerId:"claude-code",source:"statusline",capturedAt:r.toISOString(),stale:!1}}});var Pr=C(O=>{"use strict";var Nc=O&&O.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Tc=O&&O.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Rc=O&&O.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&Nc(n,t,r[i]);return Tc(n,t),n}})();Object.defineProperty(O,"__esModule",{value:!0});O.STATE_FILE_NAME=O.STATE_FILE_SCHEMA_VERSION=void 0;O.getStateFilePath=Rt;O.readStateFile=Dr;O.writeStateFile=qc;O.quotaToStateFile=kc;O.billingBlockToStateFile=Wc;var Lc=Rc(y("fs")),Hc=pe(),$c=Se(),zc=Y();O.STATE_FILE_SCHEMA_VERSION=1;O.STATE_FILE_NAME="state.json";function Rt(){return(0,Hc.getGlobalDataPath)(O.STATE_FILE_NAME)}function Dr(e=Rt()){try{let t=JSON.parse(Lc.readFileSync(e,"utf8"));return t&&t.schemaVersion===O.STATE_FILE_SCHEMA_VERSION?t:null}catch{return null}}function Tt(e){if(Array.isArray(e))return`[${e.map(Tt).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().filter(r=>t[r]!==void 0).map(r=>`${JSON.stringify(r)}:${Tt(t[r])}`).join(",")}}`}return JSON.stringify(e)??"null"}function Ir(e){return Tt({...e,schemaVersion:void 0,writtenAt:void 0})}function qc(e,t={}){let n=t.filePath??Rt();try{let r=Dr(n);if(r&&Ir(r)===Ir(e))return!1;let i={schemaVersion:O.STATE_FILE_SCHEMA_VERSION,writtenAt:(t.now??new Date).toISOString(),...e};return(0,zc.atomicWriteJsonSync)(n,i),!0}catch{return!1}}function kc(e,t=Date.now()){if(!e||!e.available)return null;let n=typeof e.ageMs=="number"?e.ageMs:null,r=e.freshness??null;if(n===null&&e.capturedAt){let i=Date.parse(e.capturedAt);Number.isFinite(i)&&(n=Math.max(0,t-i),r??=(0,$c.classifyQuotaFreshness)(n))}return{fiveHour:{utilization:e.fiveHour.utilization,resetsAt:e.fiveHour.resetsAt},sevenDay:{utilization:e.sevenDay.utilization,resetsAt:e.sevenDay.resetsAt},source:e.source??null,capturedSource:e.capturedSource??null,capturedAt:e.capturedAt??null,ageMs:n,freshness:r}}function Wc(e){return e?{start:e.start,end:e.end,isActive:e.isActive,tokens:e.tokens.total,costUsd:e.costUsd,costProvenance:e.costProvenance,burnRatePerMinute:e.burnRatePerMinute,projectedTokens:e.projectedTokens,projectedCostUsd:e.projectedCostUsd,remainingMs:e.remainingMs}:null}});var Tr=C(l=>{"use strict";Object.defineProperty(l,"__esModule",{value:!0});l.writeStateFile=l.readStateFile=l.quotaToStateFile=l.getStateFilePath=l.billingBlockToStateFile=l.STATE_FILE_SCHEMA_VERSION=l.STATE_FILE_NAME=l.quotaFromStatuslinePayload=l.parseClaudeStatuslinePayload=l.selectStatuslineAccount=l.formatStatusline=l.estimateTimeToQuota=l.BurnRateCalculator=l.formatQuotaAge=l.classifyQuotaFreshness=l.getWorkspaceIdFromPath=l.appendQuotaHistorySample=l.writeQuotaSnapshot=l.readQuotaSnapshot=l.getActiveAccountStatus=void 0;var Uc=Xn();Object.defineProperty(l,"getActiveAccountStatus",{enumerable:!0,get:function(){return Uc.getActiveAccountStatus}});var jr=Ct();Object.defineProperty(l,"readQuotaSnapshot",{enumerable:!0,get:function(){return jr.readQuotaSnapshot}});Object.defineProperty(l,"writeQuotaSnapshot",{enumerable:!0,get:function(){return jr.writeQuotaSnapshot}});var Mr=Sr();Object.defineProperty(l,"appendQuotaHistorySample",{enumerable:!0,get:function(){return Mr.appendQuotaHistorySample}});Object.defineProperty(l,"getWorkspaceIdFromPath",{enumerable:!0,get:function(){return Mr.getWorkspaceIdFromPath}});var Fr=Se();Object.defineProperty(l,"classifyQuotaFreshness",{enumerable:!0,get:function(){return Fr.classifyQuotaFreshness}});Object.defineProperty(l,"formatQuotaAge",{enumerable:!0,get:function(){return Fr.formatQuotaAge}});var Er=Ft();Object.defineProperty(l,"BurnRateCalculator",{enumerable:!0,get:function(){return Er.BurnRateCalculator}});Object.defineProperty(l,"estimateTimeToQuota",{enumerable:!0,get:function(){return Er.estimateTimeToQuota}});var xr=wr();Object.defineProperty(l,"formatStatusline",{enumerable:!0,get:function(){return xr.formatStatusline}});Object.defineProperty(l,"selectStatuslineAccount",{enumerable:!0,get:function(){return xr.selectStatuslineAccount}});var Nr=Or();Object.defineProperty(l,"parseClaudeStatuslinePayload",{enumerable:!0,get:function(){return Nr.parseClaudeStatuslinePayload}});Object.defineProperty(l,"quotaFromStatuslinePayload",{enumerable:!0,get:function(){return Nr.quotaFromStatuslinePayload}});var ee=Pr();Object.defineProperty(l,"STATE_FILE_NAME",{enumerable:!0,get:function(){return ee.STATE_FILE_NAME}});Object.defineProperty(l,"STATE_FILE_SCHEMA_VERSION",{enumerable:!0,get:function(){return ee.STATE_FILE_SCHEMA_VERSION}});Object.defineProperty(l,"billingBlockToStateFile",{enumerable:!0,get:function(){return ee.billingBlockToStateFile}});Object.defineProperty(l,"getStateFilePath",{enumerable:!0,get:function(){return ee.getStateFilePath}});Object.defineProperty(l,"quotaToStateFile",{enumerable:!0,get:function(){return ee.quotaToStateFile}});Object.defineProperty(l,"readStateFile",{enumerable:!0,get:function(){return ee.readStateFile}});Object.defineProperty(l,"writeStateFile",{enumerable:!0,get:function(){return ee.writeStateFile}})});var g=Qr(Tr(),1);import*as ke from"fs";function Qc(e=process.env){if(e.SIDEKICK_STATUSLINE_STDIN==="0")return null;try{if(process.stdin.isTTY)return null;let t=ke.fstatSync(0);return t.isFIFO()||t.isFile()||t.isSocket()?(0,g.parseClaudeStatuslinePayload)(ke.readFileSync(0,"utf8")):null}catch{return null}}function Bc(e,t){return e?e.fiveHour.utilization===t.fiveHour.utilization&&e.fiveHour.resetsAt===t.fiveHour.resetsAt&&e.sevenDay.utilization===t.sevenDay.utilization&&e.sevenDay.resetsAt===t.sevenDay.resetsAt:!1}async function Kc(e,t,n,r){if(!Bc(n,t)){try{(0,g.writeQuotaSnapshot)("claude-code",e,t)}catch{}try{let i=r.workspace?.currentDir??r.cwd??process.cwd();await(0,g.appendQuotaHistorySample)({timestamp:t.capturedAt??new Date().toISOString(),runtimeProvider:"claude",providerId:e,workspaceId:(0,g.getWorkspaceIdFromPath)(i),fiveHour:t.fiveHour,sevenDay:t.sevenDay,available:!0,source:"statusline",stale:!1})}catch{}}}function Jc(e,t,n,r){let i=e.claude.present?{providerId:"claude-code",id:e.claude.accountId??null,label:e.claude.label??null}:e.codex.present?{providerId:"codex",id:e.codex.accountId??null,label:e.codex.label??null}:null,o=r?.contextWindow?{usedPercentage:r.contextWindow.usedPercentage??null,contextWindowSize:r.contextWindow.contextWindowSize??null,totalInputTokens:r.contextWindow.totalInputTokens??null,totalOutputTokens:r.contextWindow.totalOutputTokens??null}:null,c=r?{sessionId:r.sessionId??null,cwd:r.workspace?.currentDir??r.cwd??null,model:r.model?.id??null,costUsd:r.cost?.totalCostUsd??null,durationMs:r.cost?.totalDurationMs??null,linesAdded:r.cost?.totalLinesAdded??null,linesRemoved:r.cost?.totalLinesRemoved??null,promptCacheHitRatio:r.promptCache?.hitRatio??null}:null;return{writer:"statusline",account:i,quota:{claude:(0,g.quotaToStateFile)(t),codex:(0,g.quotaToStateFile)(n)},context:o,session:c,billingBlock:null}}async function Rr(){let e=Qc(),t=(0,g.getActiveAccountStatus)(void 0,{selfHeal:!1}),n=t.claude.accountId,r=n?(0,g.readQuotaSnapshot)("claude-code",n):null,i=r,o=t.codex.accountId?(0,g.readQuotaSnapshot)("codex",t.codex.accountId):null,c=null;if(e){let a=(0,g.quotaFromStatuslinePayload)(e,{fallback:r});a&&(i=a,n&&(c=Kc(n,a,r,e)))}process.stdout.write(`${(0,g.formatStatusline)({accounts:t,claudeQuota:i,codexQuota:o,live:e})}
14
+ `),(0,g.writeStateFile)(Jc(t,i,o,e)),c&&await c}var Lr=["--project","--provider","--output-file"],Vc=["--json","--no-color","--offline"];function Gc(e){for(let t=0;t<e.length;t++){let n=e[t];if(!Vc.includes(n)){if(Lr.includes(n)){t++;continue}if(!Lr.some(r=>n.startsWith(`${r}=`)))return n}}}function Hr(e){return Gc(e)==="statusline"}Hr(process.argv.slice(2))?Rr():await import("./sidekick-main.mjs");