sidekick-agent-hub 0.24.5 → 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,12 @@ 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.
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.
11
17
  - **`sidekick statusline`, `today` & `doctor`** — a cache-only one-line account/quota/burn footer, a cache-only daily brief, and cross-provider health diagnostics.
12
18
  - **Quick capture** — `sidekick tasks add`, `tasks done`, `note add`, and `decision add` write straight to the shared project stores with atomic merges.
13
19
  - **`sidekick mcp`** — a read-only stdio MCP facts server so Claude Code or Codex can inspect quota, burn rate, context pressure, and project stores mid-session.
@@ -49,20 +55,22 @@ If `sqlite3` is missing or not executable in the current shell environment, Side
49
55
 
50
56
  ```bash
51
57
  sidekick dashboard [options]
52
- 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]
53
59
  sidekick today|doctor|statusline|mcp [options]
54
60
  sidekick tasks add|tasks done|note add|decision add [args]
55
61
  ```
56
62
 
57
63
  The standalone commands open the dashboard directly to a specific panel or run a one-shot query. All accept `--project` and `--provider` flags.
58
64
 
59
- | Flag | Description |
60
- | ------------------ | ------------------------------------------------------------------------- |
61
- | `--project <path>` | Override project path (default: current working directory) |
62
- | `--provider <id>` | Session provider: `claude-code`, `opencode`, `codex`, or `auto` (default) |
63
- | `--no-color` | Disable colored output (also honors `NO_COLOR`) |
64
- | `--session <id>` | Follow a specific session by ID |
65
- | `--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 |
66
74
 
67
75
  ## Daily Brief & Statusline
68
76
 
@@ -71,7 +79,7 @@ sidekick today
71
79
  sidekick statusline
72
80
  ```
73
81
 
74
- `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).
75
83
 
76
84
  ## Doctor
77
85
 
@@ -81,6 +89,30 @@ sidekick doctor
81
89
 
82
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.
83
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
+
84
116
  ## Quick Capture
85
117
 
86
118
  ```bash
@@ -229,7 +261,7 @@ sidekick quota
229
261
  Provider-aware quota and rate-limit display. The command auto-detects the active provider:
230
262
 
231
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.
232
- - **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.
233
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`.
234
266
 
235
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:
@@ -244,11 +276,11 @@ Subscription Quota now projected resets
244
276
 
245
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.
246
278
 
247
- 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).
248
280
 
249
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`.
250
282
 
251
- 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.
252
284
 
253
285
  ### Quota History
254
286
 
@@ -266,7 +298,7 @@ Mon ··▒▒▓█▒░· ·░░·· ·▒▓
266
298
  Peak 92% · Avg 38% · Samples 612
267
299
  ```
268
300
 
269
- 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.
270
302
 
271
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.
272
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 Ln=Object.create;var ct=Object.defineProperty;var $n=Object.getOwnPropertyDescriptor;var Tn=Object.getOwnPropertyNames;var Rn=Object.getPrototypeOf,Hn=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 j=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}};var Wn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Tn(t))!Hn.call(e,i)&&i!==n&&ct(e,i,{get:()=>t[i],enumerable:!(r=$n(t,i))||r.enumerable});return e};var qn=(e,t,n)=>(n=e!=null?Ln(Rn(e)):{},Wn(t||!e||!e.__esModule?ct(n,"default",{value:e,enumerable:!0}):n,e));var be=j(p=>{"use strict";var Bn=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]})),zn=p&&p.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),_e=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"&&Bn(n,t,r[i]);return zn(n,t),n}})();Object.defineProperty(p,"__esModule",{value:!0});p.CONFIG_DIR_ENV_VAR=void 0;p.getDefaultConfigDir=at;p.setConfigDir=kn;p.getConfigDirOverride=Jn;p.getConfigDir=Ce;p.getProjectDataPath=Un;p.getGlobalDataPath=Qn;p.encodeWorkspacePath=we;p.getProjectSlug=Vn;p.resolveProjectIdentity=je;p.getProjectSlugRaw=Gn;var Kn=_e(f("fs")),W=_e(f("path")),ot=_e(f("os"));p.CONFIG_DIR_ENV_VAR="SIDEKICK_CONFIG_DIR";var ie=null;function at(){return process.platform==="win32"?W.join(process.env.APPDATA||ot.homedir(),"sidekick"):W.join(ot.homedir(),".config","sidekick")}function kn(e){let t=e?.trim();ie=t?W.resolve(t):null}function Jn(){return ie}function Ce(){if(ie)return ie;let e=process.env[p.CONFIG_DIR_ENV_VAR]?.trim();return e?W.resolve(e):at()}function Un(e,t){return W.join(Ce(),t,`${e}.json`)}function Qn(e){return W.join(Ce(),e)}function we(e){return e.replace(/\\/g,"/").replace(/[:/_]/g,"-")}function Vn(e){return je(e).canonicalSlug}function je(e){let t=W.resolve(e||process.cwd()),n;try{n=Kn.realpathSync(t)}catch{n=t}let r=we(n),i=we(t);return{cwd:t,resolvedCwd:n,canonicalSlug:r,legacySlug:i,candidates:r===i?[r]:[r,i],hasLegacyMismatch:r!==i}}function Gn(e){return je(e).legacySlug}});var X=j(b=>{"use strict";var Yn=b&&b.__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]})),Xn=b&&b.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Ie=b&&b.__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"&&Yn(n,t,r[i]);return Xn(n,t),n}})();Object.defineProperty(b,"__esModule",{value:!0});b.atomicWriteJson=st;b.atomicWriteJsonSync=dt;b.atomicWriteFileSync=lt;b.updateJsonStoreAtomic=ir;b.withFileLockSync=yt;b.updateJsonStoreAtomicSync=ur;var J=Ie(f("crypto")),a=Ie(f("fs")),k=Ie(f("path")),Oe=1e4,K=3e3,Zn=12e4,ut=15e3,er=15,tr=new Int32Array(new SharedArrayBuffer(4));async function nr(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 rr(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 st(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 nr(k.dirname(e))}catch(i){throw await r?.close().catch(()=>{}),await a.promises.rm(n,{force:!0}).catch(()=>{}),i}}function dt(e,t){lt(e,JSON.stringify(t,null,2))}function lt(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),rr(k.dirname(e))}catch(c){throw i!==void 0&&a.closeSync(i),a.rmSync(r,{force:!0}),c}}async function ir(e,t,n){await a.promises.mkdir(k.dirname(e),{recursive:!0,mode:448});let r=`${e}.lock`,i=await cr(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 st(e,d),d}finally{await or(r,i)}}async function cr(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(Oe/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>Oe&&!ft(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 or(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 ft(e,t){if(t>Zn)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 yt(e,t){let n=ar(e);try{return t()}finally{try{a.readFileSync(e,"utf8")===n&&a.rmSync(e,{force:!0})}catch{}}}function ar(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>Oe&&!ft(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>=ut)throw new Error(`Timed out waiting for store lock: ${e} (blocked synchronously for ${ut}ms)`);Atomics.wait(tr,0,0,er)}}function ur(e,t,n){return a.mkdirSync(k.dirname(e),{recursive:!0,mode:448}),yt(`${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 dt(e,c),c})}});var oe=j(S=>{"use strict";var sr=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]})),dr=S&&S.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),pt=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"&&sr(n,t,r[i]);return dr(n,t),n}})();Object.defineProperty(S,"__esModule",{value:!0});S.getAccountsDir=Pe;S.readSavedAccountRegistry=Z;S.writeSavedAccountRegistry=yr;S.listSavedAccountProfiles=pr;S.getActiveSavedAccount=mr;S.upsertSavedAccountProfile=hr;S.setActiveSavedAccount=gr;S.replaceSavedAccountProfiles=vr;S.removeSavedAccountProfile=Ar;var mt=pt(f("fs")),ht=pt(f("path")),lr=be(),ce=X();function Pe(){return ht.join((0,lr.getConfigDir)(),"accounts")}function xe(){return ht.join(Pe(),"accounts.json")}function De(){return xe()+".lock"}function Me(){mt.mkdirSync(Pe(),{recursive:!0,mode:448})}function Ee(e){(0,ce.atomicWriteJsonSync)(xe(),vt(e))}function Fe(e){return Me(),(0,ce.withFileLockSync)(De(),()=>{let t=e(Z()??gt());return Ee(t),t})}function gt(){return{version:2,activeByProvider:{"claude-code":null,codex:null},accounts:[]}}function vt(e){let t=gt();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 fr(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 Z(){try{let e=mt.readFileSync(xe(),"utf8"),t=JSON.parse(e);return t?.version===2?vt(t):t?.version===1&&Array.isArray(t.accounts)?fr(t):null}catch{return null}}function yr(e){Me(),(0,ce.withFileLockSync)(De(),()=>Ee(e))}function pr(e){let t=Z();return t?e?t.accounts.filter(n=>n.providerId===e):t.accounts:[]}function mr(e){let t=Z();if(!t)return null;let n=t.activeByProvider[e];return n?t.accounts.find(r=>r.providerId===e&&r.id===n)??null:null}function hr(e){return Fe(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 gr(e,t){return Fe(n=>(n.activeByProvider[e]=t,n))}function vr(e,t,n){return Fe(r=>(r.accounts=r.accounts.filter(i=>i.providerId!==e).concat(t),r.activeByProvider[e]=n,r))}function Ar(e,t){return Me(),(0,ce.withFileLockSync)(De(),()=>{let n=Z();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),Ee(n),i})}});var Le=j(_=>{"use strict";var Sr=_&&_.__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]})),wr=_&&_.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),St=_&&_.__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"&&Sr(n,t,r[i]);return wr(n,t),n}})();Object.defineProperty(_,"__esModule",{value:!0});_.getClaudeProfilesDir=wt;_.getClaudeProfileHome=_t;_.ensureClaudeProfileDirs=br;_.claudeKeychainSuffix=Ct;_.claudeKeychainService=jt;_.readClaudeProfileIdentity=bt;_.keychainServiceExists=Ot;_.isClaudeProfileAuthenticated=Or;var _r=f("child_process"),Cr=f("crypto"),Ne=St(f("fs")),ae=St(f("path")),jr=oe(),At="Claude Code-credentials";function wt(){return ae.join((0,jr.getAccountsDir)(),"claude","profiles")}function _t(e){return ae.join(wt(),e,"home")}function br(e){Ne.mkdirSync(_t(e),{recursive:!0,mode:448})}function Ct(e){return(0,Cr.createHash)("sha256").update(e).digest("hex").slice(0,8)}function jt(e){return e?`${At}-${Ct(e)}`:At}function bt(e){try{let t=JSON.parse(Ne.readFileSync(ae.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 Ot(e){try{return(0,_r.execFileSync)("security",["find-generic-password","-s",e],{stdio:["ignore","ignore","ignore"],timeout:4e3,killSignal:"SIGKILL"}),!0}catch{return!1}}function Or(e){return(process.platform==="darwin"?Ot(jt(e)):Ne.existsSync(ae.join(e,".credentials.json")))&&bt(e)!==null}});var Mt=j(x=>{"use strict";var Ir=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]})),Pr=x&&x.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Re=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"&&Ir(n,t,r[i]);return Pr(n,t),n}})();Object.defineProperty(x,"__esModule",{value:!0});x.KEYCHAIN_SERVICE=void 0;x.readActiveCredentials=Dr;x.writeActiveCredentials=Mr;var Te=Re(f("fs")),It=Re(f("path")),xr=Re(f("os")),Pt=f("child_process"),xt=Le();x.KEYCHAIN_SERVICE="Claude Code-credentials";function $e(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function Dt(e){return It.join(e??It.join(xr.homedir(),".claude"),".credentials.json")}function Dr(e){if(process.platform==="darwin")try{let t=(0,Pt.execFileSync)("security",["find-generic-password","-s",(0,xt.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(Te.readFileSync(Dt(e),"utf8"))}catch{return null}}function Mr(e,t){let n=JSON.stringify(e);if(JSON.parse(n),process.platform==="darwin"){let c=(0,xt.claudeKeychainService)(t),o=process.env.USER||"user",d=["add-generic-password","-U","-s",$e(c),"-a",$e(o),"-w",$e(n)].join(" ");(0,Pt.execFileSync)("security",["-i"],{input:d+`
5
- `,stdio:["pipe","pipe","pipe"],timeout:4e3,killSignal:"SIGKILL"});return}let r=Dt(t),i=r+".tmp";Te.writeFileSync(i,n,{encoding:"utf8",mode:384}),Te.renameSync(i,r)}});var zt=j(h=>{"use strict";var Er=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]})),Fr=h&&h.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),He=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"&&Er(n,t,r[i]);return Fr(n,t),n}})();Object.defineProperty(h,"__esModule",{value:!0});h.readAccountRegistry=de;h.writeAccountRegistry=se;h.readActiveClaudeAccount=le;h.addCurrentAccount=Wr;h.switchToAccount=qr;h.resolveActiveClaudeHome=zr;h.applyActiveClaudeToLiveHome=Kr;h.reconcileClaudeAuthState=kr;h.removeAccount=Jr;h.listAccounts=Ur;h.getActiveAccount=Bt;h.resolveActiveClaudeAccount=Qr;h.isMultiAccountEnabled=Vr;var C=He(f("fs")),m=He(f("path")),Et=He(f("os")),M=Mt(),L=X(),v=oe(),V=Le();function Ft(){return m.join(Et.homedir(),".claude")}function $(){let e=m.join(Ft(),".claude.json");try{if(JSON.parse(C.readFileSync(e,"utf8"))?.oauthAccount)return e}catch{}return m.join(Et.homedir(),".claude.json")}function U(){return m.join((0,v.getAccountsDir)(),"credentials")}function Q(){return m.join((0,v.getAccountsDir)(),"configs")}function Nr(){return m.join((0,v.getAccountsDir)(),"claude",".profiles-migrated-v1")}function Lr(){for(let e of[(0,v.getAccountsDir)(),U(),Q()])C.mkdirSync(e,{recursive:!0,mode:448})}function We(e){try{return JSON.parse(C.readFileSync(e,"utf8"))}catch{return null}}function Nt(e){return We(e)?.oauthAccount??null}function Lt(e,t){(0,L.atomicWriteJsonSync)(m.join((0,V.getClaudeProfileHome)(e),".claude.json"),{oauthAccount:t})}function $t(e,t){(0,M.writeActiveCredentials)(t,(0,V.getClaudeProfileHome)(e))}function ue(e,t,n){Lt(e,n),$t(e,t)}function Tt(e){return We(m.join(U(),`${e}.credentials.json`))}function Rt(e){return We(m.join(Q(),`${e}.config.json`))}function Ht(e){return Nt(m.join((0,V.getClaudeProfileHome)(e),".claude.json"))}function $r(e){let t=(0,M.readActiveCredentials)((0,V.getClaudeProfileHome)(e)),n=Ht(e);if(t&&n)return{credentials:t,oauthAccount:n};let r=Tt(e),i=Rt(e);if(r&&i){try{ue(e,r,i)}catch{}return{credentials:r,oauthAccount:i}}return null}function Tr(){return Nt($())}function Rr(){let e=le();if(!e)return;let t=(0,M.readActiveCredentials)(),n=Tr();if(t)try{(0,L.atomicWriteJsonSync)(m.join(U(),`${e.uuid}.credentials.json`),t),$t(e.uuid,t)}catch{}if(n)try{(0,L.atomicWriteJsonSync)(m.join(Q(),`${e.uuid}.config.json`),n),Lt(e.uuid,n)}catch{}}function Hr(e){let t={};try{t=JSON.parse(C.readFileSync($(),"utf8"))}catch{}t.oauthAccount=e,(0,L.atomicWriteJsonSync)($(),t)}function de(){let e=(0,v.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 se(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,v.replaceSavedAccountProfiles)("claude-code",t,e.activeAccountUuid)}function le(){try{let e=C.readFileSync($(),"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 Wr(e){let t=le();if(!t)return{success:!1,error:"No active Claude account found. Sign in with `claude` first."};let n=(0,M.readActiveCredentials)();if(!n)return{success:!1,error:"Could not read Claude credentials."};let r;try{r=JSON.parse(C.readFileSync($(),"utf8")).oauthAccount}catch{return{success:!1,error:"Could not read Claude config file."}}Lr();let i=de()??{version:1,activeAccountUuid:null,accounts:[]},c=i.accounts.find(o=>o.uuid===t.uuid);if(c){e!==void 0&&(c.label=e),(0,L.atomicWriteJsonSync)(m.join(U(),`${t.uuid}.credentials.json`),n),(0,L.atomicWriteJsonSync)(m.join(Q(),`${t.uuid}.config.json`),r);try{ue(t.uuid,n,r)}catch{}return i.activeAccountUuid=t.uuid,se(i),{success:!0}}(0,L.atomicWriteJsonSync)(m.join(U(),`${t.uuid}.credentials.json`),n),(0,L.atomicWriteJsonSync)(m.join(Q(),`${t.uuid}.config.json`),r);try{ue(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,se(i),{success:!0}}function Wt(e){let t=m.join((0,v.getAccountsDir)(),"claude");return C.mkdirSync(t,{recursive:!0,mode:448}),(0,L.withFileLockSync)(m.join(t,"auth-swap.lock"),e)}function qr(e){try{return Wt(()=>Br(e))}catch(t){return{success:!1,error:`Could not acquire the account-switch lock: ${t}`}}}function Br(e){let t=de();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,M.readActiveCredentials)();try{i=C.readFileSync($(),"utf8")}catch{}try{Rr()}catch{}try{(0,v.setActiveSavedAccount)("claude-code",e)}catch(o){return{success:!1,error:`Failed to update account registry: ${o}`}}let c=qt();if(!c.success){try{(0,v.setActiveSavedAccount)("claude-code",t.activeAccountUuid)}catch{}if(r)try{(0,M.writeActiveCredentials)(r)}catch{}if(i)try{C.writeFileSync($(),i)}catch{}return c}return c}function zr(){let e=(0,v.getActiveSavedAccount)("claude-code");return e?(0,V.getClaudeProfileHome)(e.providerAccountId??e.id):Ft()}function Kr(){try{return Wt(qt)}catch(e){return{success:!1,error:`Could not acquire the account-switch lock: ${e}`}}}function qt(){let e=(0,v.getActiveSavedAccount)("claude-code");if(!e)return{success:!1,error:"No active Claude account found."};let t=e.providerAccountId??e.id,n=$r(t);if(!n)return{success:!1,error:`Stored credentials for ${e.email??t} not found.`};let r=(0,M.readActiveCredentials)(),i=null;try{i=C.readFileSync($(),"utf8")}catch{}try{(0,M.writeActiveCredentials)(n.credentials)}catch(c){if(r)try{(0,M.writeActiveCredentials)(r)}catch{}return{success:!1,error:`Failed to write credentials: ${c}`}}try{Hr(n.oauthAccount)}catch(c){if(r)try{(0,M.writeActiveCredentials)(r)}catch{}if(i)try{C.writeFileSync($(),i)}catch{}return{success:!1,error:`Failed to write config: ${c}`}}return{success:!0}}function kr(){try{let e=Nr();if(C.existsSync(e))return;let t=(0,v.readSavedAccountRegistry)();if(t)for(let n of t.accounts.filter(r=>r.providerId==="claude-code"))try{let r=n.providerAccountId??n.id;if((0,M.readActiveCredentials)((0,V.getClaudeProfileHome)(r))&&Ht(r))continue;let i=Tt(r),c=Rt(r);if(!i||!c)continue;ue(r,i,c)}catch{}C.mkdirSync(m.dirname(e),{recursive:!0,mode:448}),C.writeFileSync(e,new Date().toISOString()+`
6
- `,{encoding:"utf8",mode:384})}catch{}}function Jr(e){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{C.unlinkSync(m.join(U(),`${e}.credentials.json`))}catch{}try{C.unlinkSync(m.join(Q(),`${e}.config.json`))}catch{}return t.accounts.splice(n,1),t.activeAccountUuid===e&&(t.activeAccountUuid=t.accounts[0]?.uuid??null),se(t),{success:!0}}function Ur(){return(0,v.listSavedAccountProfiles)("claude-code").map(e=>({uuid:e.providerAccountId??e.id,email:e.email??e.metadata?.email??"unknown",label:e.label,addedAt:e.addedAt}))}function Bt(){let e=(0,v.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 Qr(){let e=le();if(e){let n=(0,v.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,v.getActiveSavedAccount)("claude-code");if(!i||i.id!==r.id)try{(0,v.setActiveSavedAccount)("claude-code",r.id)}catch{}}return{email:e.email,label:r?.label,providerAccountId:e.uuid,registryAccountId:r?.id,source:"live"}}let t=Bt();return t?{email:t.email,label:t.label,providerAccountId:t.uuid,registryAccountId:t.uuid,source:"registry"}:{source:"none"}}function Vr(){return(0,v.listSavedAccountProfiles)("claude-code").length>=1}});var yn=j(l=>{"use strict";var Gr=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]})),Yr=l&&l.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),ze=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"&&Gr(n,t,r[i]);return Yr(n,t),n}})();Object.defineProperty(l,"__esModule",{value:!0});l.getSystemCodexHome=F;l.getCodexMonitoringHomes=ni;l.getCodexProfilesDir=Ut;l.getCodexProfileHome=E;l.readCodexAccountMetadata=Xt;l.readCodexAccountMetadataAsync=Zt;l.isCodexProfileAuthenticated=en;l.isCodexProfileAuthenticatedAsync=tn;l.listCodexAccounts=G;l.getActiveCodexAccount=ge;l.resolveSidekickCodexHome=Ue;l.resolveActiveCodexAccount=fi;l.getCodexExecutionEnv=yi;l.prepareCodexAccount=pi;l.prepareCodexAccountAsync=mi;l.finalizeCodexAccount=cn;l.finalizeCodexAccountAsync=on;l.switchToCodexAccount=Ai;l.switchToCodexAccountAsync=Si;l.reconcileCodexAuthState=wi;l.reconcileCodexAuthStateAsync=_i;l.removeCodexAccount=Ci;var g=ze(f("fs")),Xr=ze(f("os")),u=ze(f("path")),fe=f("child_process"),Zr=f("crypto"),w=oe(),A=X(),ei=11520*60*1e3;function kt(){return u.join(Xr.homedir(),".codex")}function Jt(){let e=process.env.CODEX_HOME?.trim();return e||null}function ti(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 F(){return Jt()??kt()}function ni(){let e=Jt();if(e)return[e];let t=[kt()];for(let n of G()){let r=E(n.id);g.existsSync(u.join(r,"sessions"))&&t.push(r)}return ti(t)}function Ut(){return u.join((0,w.getAccountsDir)(),"codex","profiles")}function Ke(e){return u.join(Ut(),e)}function E(e){return u.join(Ke(e),"codex-home")}function Qt(e){return u.join(Ke(e),"profile.json")}function Vt(e){g.mkdirSync(E(e),{recursive:!0,mode:448})}function R(e){try{return g.readFileSync(e,"utf8")}catch{return null}}function ke(e){try{return JSON.parse(g.readFileSync(Qt(e),"utf8"))}catch{return null}}function ri(e,t){Vt(e),(0,A.atomicWriteJsonSync)(Qt(e),t)}function qe(e,t){return g.existsSync(e)?(g.mkdirSync(u.dirname(t),{recursive:!0,mode:448}),g.copyFileSync(e,t),!0):!1}function ii(e,t){qe(u.join(e,"config.toml"),u.join(t,"config.toml"))}function ci(e,t){let n=qe(u.join(e,"auth.json"),u.join(t,"auth.json")),r=qe(u.join(e,".credentials.json"),u.join(t,".credentials.json"));return n||r}function oi(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 Je(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function q(e){let t=Je(e);if(!t)return null;let n=t.tokens?.id_token,r=n?oi(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 Be(e,t){let n=Je(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 ai(e){let t=q(R(u.join(e,"auth.json")));return t?{email:t.email,workspaceId:t.workspaceId,planType:t.planType,authMode:t.authMode}:{}}function ui(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 ye=4e3;function Gt(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 pe(e){try{let t={...process.env,CODEX_HOME:e},n=(0,fe.spawnSync)("codex",["login","status"],{encoding:"utf8",env:t,timeout:ye,killSignal:"SIGKILL"});return Gt(n.status,String(n.stdout??""))}catch{}return{loggedIn:!1}}function me(e){return new Promise(t=>{try{let n={...process.env,CODEX_HOME:e};(0,fe.execFile)("codex",["login","status"],{encoding:"utf8",env:n,timeout:ye,killSignal:"SIGKILL"},(r,i)=>{t(r?{loggedIn:!1}:Gt(0,String(i??"")))})}catch{t({loggedIn:!1})}})}function si(){if(process.platform==="win32")return!1;try{return(0,fe.spawnSync)("pgrep",["-x","codex"],{encoding:"utf8",timeout:ye,killSignal:"SIGKILL"}).status===0}catch{return!1}}function di(){return process.platform==="win32"?Promise.resolve(!1):new Promise(e=>{try{(0,fe.execFile)("pgrep",["-x","codex"],{encoding:"utf8",timeout:ye,killSignal:"SIGKILL"},t=>e(!t))}catch{e(!1)}})}function he(e){let t=ai(e);if(t.email||t.workspaceId||t.planType||t.authMode)return t;let n=ui(e);return n.authMode?n:null}function Yt(e){return e.loggedIn?{authMode:e.authMode??"unknown"}:{}}function Xt(e){return he(e)??Yt(pe(e))}async function Zt(e){return he(e)??Yt(await me(e))}function ee(e){return g.existsSync(u.join(e,"auth.json"))||g.existsSync(u.join(e,".credentials.json"))}function en(e){return ee(e)||pe(e).loggedIn}async function tn(e){return ee(e)||(await me(e)).loggedIn}function li(e,t){let n=e.trim().toLowerCase();return G().find(i=>i.id!==t&&(i.label??"").trim().toLowerCase()===n)?`A Codex account named "${e}" already exists.`:null}function G(){return(0,w.listSavedAccountProfiles)("codex")}function ge(){return(0,w.getActiveSavedAccount)("codex")}function Ue(){return F()}function fi(){let e=q(R(u.join(Ue(),"auth.json")));if(e&&(e.email||e.workspaceId)){let n=Qe(e);if(n){let r=(0,w.getActiveSavedAccount)("codex");if(!r||r.id!==n.id)try{(0,w.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=ge();return t?{email:t.email??t.metadata?.email,label:t.label,providerAccountId:t.providerAccountId,registryAccountId:t.id,source:"registry"}:{source:"none"}}function yi(e=process.env){return{...e,CODEX_HOME:Ue()}}function nn(e){let t=e.trim();if(!t)return{result:{success:!1,error:"Codex accounts require a non-empty label."}};let n=li(t);if(n)return{result:{success:!1,error:n}};let r=(0,Zr.randomUUID)(),i=E(r);Vt(r),ri(r,{label:t,addedAt:new Date().toISOString()});let c=F();return ii(c,i),ci(c,i)?{finalize:{profileId:r,codexHome:i}}:{result:{success:!0,profileId:r,codexHome:i,needsLogin:!0}}}function pi(e){let t=nn(e);return"finalize"in t?{...cn(t.finalize.profileId),...t.finalize,needsLogin:!1}:t.result}async function mi(e){let t=nn(e);return"finalize"in t?{...await on(t.finalize.profileId),...t.finalize,needsLogin:!1}:t.result}function rn(e,t,n){let r=ke(e);if(!r)return{result:{success:!1,error:`Codex profile ${e} was not prepared.`}};let i=E(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,w.upsertSavedAccountProfile)(c),t.activate===!1?{result:{success:!0}}:ee(i)?{swap:c}:((0,w.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 cn(e,t={}){if(!ke(e))return{success:!1,error:`Codex profile ${e} was not prepared.`};let n=E(e),r=en(n),i=rn(e,t,{authenticated:r,metadata:r?Xt(n):{}});return"swap"in i?un(i.swap):i.result}async function on(e,t={}){if(!ke(e))return{success:!1,error:`Codex profile ${e} was not prepared.`};let n=E(e),r=await tn(n),i=rn(e,t,{authenticated:r,metadata:r?await Zt(n):{}});return"swap"in i?sn(i.swap):i.result}function Kt(){return u.join((0,w.getAccountsDir)(),"codex","stash")}function an(e,t){try{let n=new Date().toISOString().replace(/[:.]/g,"-"),r=null;if(e&&(r=u.join(Kt(),`auth-${n}.json`),(0,A.atomicWriteFileSync)(r,e)),t){let i=u.join(Kt(),`credentials-${n}.json`);(0,A.atomicWriteFileSync)(i,t),r=r??i}return r}catch{return null}}function Qe(e){let t=G();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?ge():null}function hi(e,t){if(!e&&!t)return{};try{let n=q(e),r=Qe(n);if(!r){let c=an(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=E(r.id);e&&(0,A.atomicWriteFileSync)(u.join(i,"auth.json"),e),t&&(0,A.atomicWriteFileSync)(u.join(i,".credentials.json"),t);try{let c=he(i)??{};(0,w.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 ve(e){let t=u.join((0,w.getAccountsDir)(),"codex");return g.mkdirSync(t,{recursive:!0,mode:448}),(0,A.withFileLockSync)(u.join(t,"auth-swap.lock"),e)}function gi(){let e=F();return{codexRunning:si(),systemKeyringLoggedIn:ee(e)?!1:pe(e).loggedIn}}async function vi(){let e=F();return{codexRunning:await di(),systemKeyringLoggedIn:ee(e)?!1:(await me(e)).loggedIn}}function un(e){let t=gi();try{return ve(()=>dn(e,t))}catch(n){return{success:!1,error:`Could not acquire the account-switch lock: ${n}`}}}async function sn(e){let t=await vi();try{return ve(()=>dn(e,t))}catch(n){return{success:!1,error:`Could not acquire the account-switch lock: ${n}`}}}function dn(e,t){let n=F(),r=u.join(n,"auth.json"),i=u.join(n,".credentials.json"),c=R(r),o=R(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=E(e.id),s=u.join(d,"auth.json"),y=R(s),D=R(u.join(d,".credentials.json")),H=e.label??e.email??e.id;if(!y&&!D)return{success:!1,error:`No stored credentials for "${H}". Remove and re-add this account.`};if(y&&!Je(y))return{success:!1,error:`Stored credentials for "${H}" are corrupted. Remove and re-add this account.`};let T=[];t.codexRunning&&T.push("A codex process appears to be running; restart codex sessions so they pick up the switched account.");let P=q(c),Y=q(y),et=e.metadata?.workspaceId??Y?.workspaceId,tt=e.email??e.metadata?.email??Y?.email;if(!!(P?.workspaceId&&et&&P.workspaceId===et||P?.email&&tt&&P.email===tt||c!==null&&c===y||!c&&!y&&o!==null&&o===D)){try{c&&(0,A.atomicWriteFileSync)(s,c),o&&(0,A.atomicWriteFileSync)(u.join(d,".credentials.json"),o);let z=he(d)??{};(0,w.upsertSavedAccountProfile)({...e,email:z.email??e.email,metadata:{...e.metadata,...z}})}catch{}return(0,w.setActiveSavedAccount)("codex",e.id),{success:!0,warning:T.length?T.join(" "):void 0}}let nt=Be(y,s);nt!==null&&Date.now()-nt>ei&&T.push(`Stored credentials for "${H}" have not been refreshed in over 8 days; codex may ask you to log in again.`);let rt=hi(c,o);rt.warning&&T.push(rt.warning);let it=()=>{try{c?(0,A.atomicWriteFileSync)(r,c):g.rmSync(r,{force:!0}),o?(0,A.atomicWriteFileSync)(i,o):g.rmSync(i,{force:!0})}catch{}};try{y?((0,A.atomicWriteFileSync)(r,y),D?(0,A.atomicWriteFileSync)(i,D):o&&g.rmSync(i,{force:!0})):((0,A.atomicWriteFileSync)(i,D),c&&g.rmSync(r,{force:!0}))}catch(z){return it(),{success:!1,error:`Failed to write Codex credentials: ${z}`}}try{(0,w.setActiveSavedAccount)("codex",e.id)}catch(z){return it(),{success:!1,error:`Failed to update account registry: ${z}`}}return{success:!0,warning:T.length?T.join(" "):void 0}}function Ai(e){let t=G().find(n=>n.id===e);return t?un(t):{success:!1,error:`Codex account ${e} not found.`}}async function Si(e){let t=G().find(n=>n.id===e);return t?sn(t):{success:!1,error:`Codex account ${e} not found.`}}function ln(){let e=u.join((0,w.getAccountsDir)(),"codex",".live-auth-migrated-v1");return g.existsSync(e)?!1:!g.existsSync(u.join(F(),"auth.json"))}function wi(){try{let e=ln()?pe(F()).loggedIn:!1;ve(()=>fn({systemKeyringLoggedIn:e}))}catch{}}async function _i(){try{let e=ln()?(await me(F())).loggedIn:!1;ve(()=>fn({systemKeyringLoggedIn:e}))}catch{}}function fn(e){try{let t=u.join((0,w.getAccountsDir)(),"codex",".live-auth-migrated-v1");if(g.existsSync(t))return;let n=()=>(0,A.atomicWriteFileSync)(t,new Date().toISOString()+`
7
- `),r=ge();if(!r){n();return}let i=E(r.id),c=u.join(i,"auth.json"),o=R(c);if(!o){n();return}let d=F(),s=u.join(d,"auth.json"),y=R(s);if(!y){e.systemKeyringLoggedIn||(0,A.atomicWriteFileSync)(s,o),n();return}let D=q(y),H=q(o);if(!!(D?.workspaceId&&H?.workspaceId&&D.workspaceId===H.workspaceId||D?.email&&D.email===H?.email)){let P=Be(y,s),Y=Be(o,c);Y!==null&&(P===null||Y>P)?(an(y,null),(0,A.atomicWriteFileSync)(s,o)):(0,A.atomicWriteFileSync)(c,y)}else{let P=Qe(D);P&&P.id!==r.id&&((0,A.atomicWriteFileSync)(u.join(E(P.id),"auth.json"),y),(0,w.setActiveSavedAccount)("codex",P.id))}n()}catch{}}function Ci(e){return(0,w.removeSavedAccountProfile)("codex",e)?(g.rmSync(Ke(e),{recursive:!0,force:!0}),{success:!0}):{success:!1,error:`Codex account ${e} not found.`}}});var pn=j(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.getActiveAccountStatus=Ii;var ji=zt(),bi=yn();function Oi(e){return e instanceof Error?e.message:String(e)}function Ii(e){try{let t=(0,ji.resolveActiveClaudeAccount)(),n=(0,bi.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??Oi(t)}}}});var mn=j(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.isAggregateCodexLimit=Pi;function Pi(e){return!e||e==="codex"}});var jn=j(N=>{"use strict";var xi=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]})),Di=N&&N.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),vn=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"&&xi(n,t,r[i]);return Di(n,t),n}})();Object.defineProperty(N,"__esModule",{value:!0});N.writeQuotaSnapshot=Li;N.readQuotaSnapshot=$i;var An=vn(f("fs")),Mi=vn(f("path")),Sn=be(),wn=X(),hn=mn();function Ye(){return Mi.join((0,Sn.getConfigDir)(),"quota-snapshots.json")}function _n(){An.mkdirSync((0,Sn.getConfigDir)(),{recursive:!0,mode:448})}function Cn(){try{let e=JSON.parse(An.readFileSync(Ye(),"utf8"));if(e?.version===1&&Array.isArray(e.snapshots))return e}catch{}return{version:1,snapshots:[]}}function Ei(e){_n(),(0,wn.atomicWriteJsonSync)(Ye(),e)}function Fi(e){return _n(),(0,wn.withFileLockSync)(`${Ye()}.lock`,e)}function gn(e){let t=e.capturedAt?Date.parse(e.capturedAt):NaN;return Number.isFinite(t)?t:0}function Ae(e){let t=Date.parse(e);return Number.isFinite(t)?t:0}function Ni(e,t){let n=(0,hn.isAggregateCodexLimit)(e.limitId),r=(0,hn.isAggregateCodexLimit)(t.limitId);if(n!==r)return n;let i=Ae(e.fiveHour.resetsAt),c=Ae(t.fiveHour.resetsAt);if(i!==c)return i>c;let o=Ae(e.sevenDay.resetsAt),d=Ae(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:gn(e)>gn(t)}function Li(e,t,n){Fi(()=>{let r=Cn(),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&&Ni(r.snapshots[i].quota,o))return;let d={providerId:e,accountId:t,quota:o};i>=0?r.snapshots[i]=d:r.snapshots.push(d),Ei(r)})}function $i(e,t){let r=Cn().snapshots.find(i=>i.providerId===e&&i.accountId===t);return r?{...r.quota,providerId:e,source:"cache",stale:!0}:null}});var Ze=j(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.BurnRateCalculator=void 0;te.estimateTimeToQuota=bn;var Xe=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 bn(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)}};te.BurnRateCalculator=Xe;function bn(e,t,n){if(n<=0)return null;let r=t-e;return r<=0?0:r/n}});var On=j(I=>{"use strict";Object.defineProperty(I,"__esModule",{value:!0});I.SEVEN_DAY_WINDOW_MS=I.FIVE_HOUR_WINDOW_MS=void 0;I.projectQuotaWindow=re;I.withQuotaProjections=Wi;I.fetchQuota=Bi;var Ti="https://api.anthropic.com/api/oauth/usage",Ri="oauth-2025-04-20",Hi=1e4;I.FIVE_HOUR_WINDOW_MS=5*36e5;I.SEVEN_DAY_WINDOW_MS=7*864e5;function re(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 Wi(e,t={}){if(!e.available)return e;let n={...e},r=t.capturedAt??e.capturedAt;if(n.projectedFiveHour==null){let i=re({utilization:n.fiveHour.utilization,resetsAt:n.fiveHour.resetsAt,windowMs:t.fiveHourWindowMs??I.FIVE_HOUR_WINDOW_MS,capturedAt:r});i!==void 0&&(n.projectedFiveHour=i)}if(n.projectedSevenDay==null){let i=re({utilization:n.sevenDay.utilization,resetsAt:n.sevenDay.resetsAt,windowMs:t.sevenDayWindowMs??I.SEVEN_DAY_WINDOW_MS,capturedAt:r});i!==void 0&&(n.projectedSevenDay=i)}return n}function ne(e,t={}){return{fiveHour:{utilization:0,resetsAt:""},sevenDay:{utilization:0,resetsAt:""},available:!1,error:e,...t}}function qi(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 Bi(e){let t=new AbortController,n=setTimeout(()=>t.abort(),Hi);n.unref();try{let r=await fetch(Ti,{method:"GET",signal:t.signal,headers:{Authorization:`Bearer ${e}`,"anthropic-beta":Ri,"Content-Type":"application/json"}});if(!r.ok)return r.status===401?ne("Sign in to Claude Code to view quota",{failureKind:"auth",httpStatus:r.status}):r.status===429?ne(`API error: ${r.status}`,{failureKind:"rate_limit",httpStatus:r.status,retryAfterMs:qi(r.headers.get("retry-after"))}):r.status>=500&&r.status<=599?ne(`API error: ${r.status}`,{failureKind:"server",httpStatus:r.status}):ne(`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:re({utilization:c,resetsAt:d,windowMs:I.FIVE_HOUR_WINDOW_MS}),projectedSevenDay:re({utilization:o,resetsAt:s,windowMs:I.SEVEN_DAY_WINDOW_MS})}}catch{return ne("Network error",{failureKind:"network"})}finally{clearTimeout(n)}}});var Pn=j(Se=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.selectStatuslineAccount=In;Se.formatStatusline=ki;var zi=On(),Ki=Ze();function In(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 ki(e){let t=In(e);if(!t)return"acct:none \xB7 quota unavailable";let n=Ui(t.accountLabel),r=t.quota;if(!r?.available)return`acct:${n} \xB7 quota unavailable`;let i=e.now??new Date,c=Qi(r.fiveHour.utilization),o=Vi(r.fiveHour.resetsAt,i),d=Ji(r,i),s=d==null?"":` \xB7 ~${Gi(d)} left`;return`acct:${n} \xB7 5h ${Math.round(c)}% resets ${o}${s}`}function Ji(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,Ki.estimateTimeToQuota)(e.fiveHour.utilization,100,d),y=(n-r)/6e4;return s!==null&&s<y?s:null}function Ui(e){let t=e.trim();return(t.includes("@")?t.split("@")[0]:t).replace(/\s+/g,"-").slice(0,24)||"unknown"}function Qi(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}function Vi(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 Gi(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 Mn=j(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.selectStatuslineAccount=O.formatStatusline=O.estimateTimeToQuota=O.BurnRateCalculator=O.readQuotaSnapshot=O.getActiveAccountStatus=void 0;var Yi=pn();Object.defineProperty(O,"getActiveAccountStatus",{enumerable:!0,get:function(){return Yi.getActiveAccountStatus}});var Xi=jn();Object.defineProperty(O,"readQuotaSnapshot",{enumerable:!0,get:function(){return Xi.readQuotaSnapshot}});var xn=Ze();Object.defineProperty(O,"BurnRateCalculator",{enumerable:!0,get:function(){return xn.BurnRateCalculator}});Object.defineProperty(O,"estimateTimeToQuota",{enumerable:!0,get:function(){return xn.estimateTimeToQuota}});var Dn=Pn();Object.defineProperty(O,"formatStatusline",{enumerable:!0,get:function(){return Dn.formatStatusline}});Object.defineProperty(O,"selectStatuslineAccount",{enumerable:!0,get:function(){return Dn.selectStatuslineAccount}})});var B=qn(Mn(),1);function En(){let e=(0,B.getActiveAccountStatus)(),t=e.claude.accountId?(0,B.readQuotaSnapshot)("claude-code",e.claude.accountId):null,n=e.codex.accountId?(0,B.readQuotaSnapshot)("codex",e.codex.accountId):null;process.stdout.write(`${(0,B.formatStatusline)({accounts:e,claudeQuota:t,codexQuota:n})}
8
- `)}var Fn=["--project","--provider"],Zi=["--json","--no-color"];function ec(e){for(let t=0;t<e.length;t++){let n=e[t];if(!Zi.includes(n)){if(Fn.includes(n)){t++;continue}if(!Fn.some(r=>n.startsWith(`${r}=`)))return n}}}function Nn(e){return ec(e)==="statusline"}Nn(process.argv.slice(2))?En():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");