oc-flight-deck 0.22.1 → 0.23.1

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/CHANGELOG.md CHANGED
@@ -7,7 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
- ## [0.22.1] - 2026-11-10
10
+ ## [0.23.1] - 2026-11-15
11
+
12
+ ### Fixed
13
+
14
+ - The compact Go row shows reset countdowns with the same two-unit precision as the Go panel instead of rounding hours or days up to a single unit.
15
+
16
+ ### Added
17
+
18
+ - Opt-in `dex` sidebar row: compact 5h and 1w Codex account dials match the Go row. Windows uses a private authenticated stdio server enclosed in an owned Job Object; no shared daemon, OAuth credential-file access or process-tree kills.
11
19
 
12
20
  ## [0.22.0] - 2026-11-10
13
21
 
package/dist/tui/index.js CHANGED
@@ -645,10 +645,16 @@ function formatRemaining(ms) {
645
645
  const minutes = Math.ceil(ms / 60000);
646
646
  if (minutes < 60)
647
647
  return `${minutes}m`;
648
- const hours = Math.ceil(ms / 3600000);
649
- if (hours < 24)
650
- return `${hours}h`;
651
- return `${Math.ceil(ms / 86400000)}d`;
648
+ const hours = Math.floor(ms / 3600000);
649
+ if (hours < 24) {
650
+ if (hours === 0)
651
+ return `${minutes}m`;
652
+ const rest = Math.floor((ms - hours * 3600000) / 60000);
653
+ return rest > 0 ? `${hours}h${rest}m` : `${hours}h`;
654
+ }
655
+ const days = Math.floor(ms / 86400000);
656
+ const rest = Math.floor((ms - days * 86400000) / 3600000);
657
+ return rest > 0 ? `${days}d${rest}h` : `${days}d`;
652
658
  }
653
659
  function goResetSuffix(window, nowMs) {
654
660
  if (goTone(window) !== "error")
@@ -731,6 +737,7 @@ var STAT_FIELDS = [
731
737
  "turns",
732
738
  "guard",
733
739
  "go",
740
+ "dex",
734
741
  "ses"
735
742
  ];
736
743
  var ANIMATED_FIELDS = ["caution", "status", "elapsed", "tps"];
@@ -775,6 +782,8 @@ function skeletonValue(field, layout) {
775
782
  return "0";
776
783
  case "go":
777
784
  return "\u25CB 0 \u25CB 0 \u25CB 0";
785
+ case "dex":
786
+ return "unavailable";
778
787
  case "status":
779
788
  return "\u25CB idle";
780
789
  case "agent":
@@ -851,11 +860,15 @@ function asGoWindows(value) {
851
860
  windows.sort((a, b) => GO_ORDER.indexOf(a.id) - GO_ORDER.indexOf(b.id));
852
861
  return windows;
853
862
  }
854
- function goValueSegments(source, layout) {
855
- const windows = asGoWindows(source.go);
863
+ function goValueSegments(source, layout, name = "go") {
864
+ let windows = asGoWindows(source[name]);
865
+ const nowMs = layout.nowMs ?? Date.now();
866
+ if (name === "dex")
867
+ windows = windows.filter((w) => w.id !== "1m" && w.resetAtMs !== undefined && w.resetAtMs > nowMs);
856
868
  if (windows.length === 0)
857
869
  return;
858
- const nowMs = layout.nowMs ?? Date.now();
870
+ if (name === "dex")
871
+ windows = ["5h", "1w"].map((id) => windows.find((w) => w.id === id) ?? { id });
859
872
  let flagged = -1;
860
873
  let flaggedRatio = Number.NEGATIVE_INFINITY;
861
874
  for (const [index, window] of windows.entries()) {
@@ -869,6 +882,10 @@ function goValueSegments(source, layout) {
869
882
  }
870
883
  const chunks = [];
871
884
  for (const [index, window] of windows.entries()) {
885
+ if (window.ratio === undefined) {
886
+ chunks.push([{ text: "\u2014" }]);
887
+ continue;
888
+ }
872
889
  const percent = Math.round((window.ratio ?? 0) * 100);
873
890
  const tone = goTone(window) === "error" ? "error" : undefined;
874
891
  const chunk = [{ text: `${dialGlyph(percent)} ${percent}`, tone }];
@@ -1096,9 +1113,13 @@ function statLine(field, source, layout = {}) {
1096
1113
  const budget = Math.max(8, SES_PREVIEW_WIDTH - Math.max(0, labelPrefix(fieldLabel("ses", layout.labels), labelWidth).length - labelPrefix("ses", labelWidth).length));
1097
1114
  return id === undefined ? undefined : row("ses", clip(id, budget));
1098
1115
  }
1099
- case "go": {
1100
- const value = goValueSegments(source, layout);
1101
- return value === undefined ? undefined : row("go", value.map((segment) => segment.text).join(""));
1116
+ case "go":
1117
+ case "dex": {
1118
+ const name = canonicalField(field);
1119
+ const value = goValueSegments(source, layout, name);
1120
+ if (name === "dex" && value === undefined)
1121
+ return row("dex", "unavailable");
1122
+ return value === undefined ? undefined : row(name, value.map((segment) => segment.text).join(""));
1102
1123
  }
1103
1124
  default:
1104
1125
  return;
@@ -1115,12 +1136,12 @@ function statSegments(field, source, layout = {}) {
1115
1136
  ...value
1116
1137
  ];
1117
1138
  }
1118
- if (name !== "go")
1139
+ if (name !== "go" && name !== "dex")
1119
1140
  return;
1120
- const value = goValueSegments(source, layout);
1141
+ const value = goValueSegments(source, layout, name);
1121
1142
  if (value === undefined)
1122
1143
  return;
1123
- return [{ text: labelPrefix(fieldLabel("go", layout.labels), layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
1144
+ return [{ text: labelPrefix(fieldLabel(name, layout.labels), layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
1124
1145
  }
1125
1146
  function statRows(fields, source, layout = {}) {
1126
1147
  const hint = { ...layout, hasTotalRow: fields.includes("total") };
@@ -2474,7 +2495,6 @@ function railLineSpans(line, style) {
2474
2495
  function footerLine(config) {
2475
2496
  return config.footer.enabled ? config.footer.text : undefined;
2476
2497
  }
2477
-
2478
2498
  // src/tui/go-panel.ts
2479
2499
  var PANEL_WINDOWS = ["5h", "1w", "1m"];
2480
2500
  var PANEL_DEFAULT_LABELS = {
@@ -2613,24 +2633,6 @@ function windowById(usage) {
2613
2633
  }
2614
2634
  return byId;
2615
2635
  }
2616
- function formatCompactRemaining(ms) {
2617
- const totalSeconds = Math.ceil(ms / 1000);
2618
- if (totalSeconds < 60)
2619
- return `${totalSeconds}s`;
2620
- const totalMinutes = Math.ceil(ms / 60000);
2621
- if (totalMinutes < 60)
2622
- return `${totalMinutes}m`;
2623
- const totalHours = Math.floor(ms / 3600000);
2624
- if (totalHours < 24) {
2625
- if (totalHours === 0)
2626
- return `${totalMinutes}m`;
2627
- const minutes = Math.floor((ms - totalHours * 3600000) / 60000);
2628
- return minutes > 0 ? `${totalHours}h${minutes}m` : `${totalHours}h`;
2629
- }
2630
- const totalDays = Math.floor(ms / 86400000);
2631
- const hours = Math.floor((ms - totalDays * 86400000) / 3600000);
2632
- return hours > 0 ? `${totalDays}d${hours}h` : `${totalDays}d`;
2633
- }
2634
2636
  function resetCountdown(window, nowMs) {
2635
2637
  const resetAtMs = window.resetAtMs;
2636
2638
  if (resetAtMs === undefined || !Number.isFinite(resetAtMs) || !Number.isFinite(nowMs))
@@ -2638,7 +2640,7 @@ function resetCountdown(window, nowMs) {
2638
2640
  const remaining = resetAtMs - nowMs;
2639
2641
  if (remaining <= 0)
2640
2642
  return;
2641
- return formatCompactRemaining(remaining);
2643
+ return formatRemaining(remaining);
2642
2644
  }
2643
2645
  function panelTone(window) {
2644
2646
  if (goTone(window) === "error")
@@ -3520,6 +3522,311 @@ function startGoBridge(host, deps, intervalMs = GO_POLL_MS) {
3520
3522
  };
3521
3523
  }
3522
3524
 
3525
+ // src/tui/codex-quota.ts
3526
+ import { spawn } from "child_process";
3527
+ import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
3528
+ import { isAbsolute as isAbsolute2, join as join5 } from "path";
3529
+ import { createInterface } from "readline";
3530
+
3531
+ // src/tui/owned-process.ts
3532
+ import { join as join4 } from "path";
3533
+ var supervisor = String.raw`
3534
+ using System;
3535
+ using System.ComponentModel;
3536
+ using System.Runtime.InteropServices;
3537
+ using System.Text;
3538
+
3539
+ public static class FlightDeckOwned {
3540
+ [StructLayout(LayoutKind.Sequential)] struct BasicLimits {
3541
+ public long ProcessTime, JobTime; public uint Flags;
3542
+ public UIntPtr MinWorking, MaxWorking; public uint Active;
3543
+ public UIntPtr Affinity; public uint Priority, Scheduling;
3544
+ }
3545
+ [StructLayout(LayoutKind.Sequential)] struct IoCounters {
3546
+ public ulong ReadOps, WriteOps, OtherOps, ReadBytes, WriteBytes, OtherBytes;
3547
+ }
3548
+ [StructLayout(LayoutKind.Sequential)] struct Limits {
3549
+ public BasicLimits Basic; public IoCounters Io;
3550
+ public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
3551
+ }
3552
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct Startup {
3553
+ public uint Size; public string Reserved, Desktop, Title;
3554
+ public uint X, Y, Width, Height, XChars, YChars, Fill, Flags;
3555
+ public ushort Show, ReservedSize; public IntPtr ReservedBytes, Input, Output, Error;
3556
+ }
3557
+ [StructLayout(LayoutKind.Sequential)] struct ProcessInfo {
3558
+ public IntPtr Process, Thread; public uint Pid, Tid;
3559
+ }
3560
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
3561
+ static extern IntPtr CreateJobObjectW(IntPtr security, string name);
3562
+ [DllImport("kernel32.dll", SetLastError=true)]
3563
+ static extern bool SetInformationJobObject(IntPtr job, int kind, ref Limits limits, uint size);
3564
+ [DllImport("kernel32.dll", SetLastError=true)]
3565
+ static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
3566
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
3567
+ static extern bool CreateProcessW(string app, StringBuilder command, IntPtr ps, IntPtr ts,
3568
+ bool inherit, uint flags, IntPtr environment, string directory, ref Startup startup, out ProcessInfo info);
3569
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
3570
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateProcess(IntPtr process, uint code);
3571
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateJobObject(IntPtr job, uint code);
3572
+ [DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
3573
+ [DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();
3574
+ [DllImport("kernel32.dll", SetLastError=true)]
3575
+ static extern bool GetProcessTimes(IntPtr process, out long created, out long exited, out long kernel, out long user);
3576
+ [DllImport("kernel32.dll", SetLastError=true)]
3577
+ static extern uint WaitForMultipleObjects(uint count, IntPtr[] handles, bool all, uint timeout);
3578
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle, uint timeout);
3579
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
3580
+ [DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(int id);
3581
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetHandleInformation(IntPtr handle, uint mask, uint flags);
3582
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
3583
+ static void Require(bool ok) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); }
3584
+ static string Quote(string value) {
3585
+ var text = new StringBuilder("\""); int slashes = 0;
3586
+ foreach (char c in value) {
3587
+ if (c == '\\') { slashes++; continue; }
3588
+ if (c == '"') { text.Append('\\', slashes * 2 + 1); text.Append(c); }
3589
+ else { text.Append('\\', slashes); text.Append(c); }
3590
+ slashes = 0;
3591
+ }
3592
+ text.Append('\\', slashes * 2); return text.Append('"').ToString();
3593
+ }
3594
+ public static int Run(string executable, string[] args, uint ownerPid) {
3595
+ IntPtr owner = IntPtr.Zero, job = IntPtr.Zero;
3596
+ ProcessInfo child = new ProcessInfo();
3597
+ try {
3598
+ owner = OpenProcess(0x00101000, false, ownerPid);
3599
+ Require(owner != IntPtr.Zero);
3600
+ long ownerCreated, ownCreated, ignored1, ignored2, ignored3;
3601
+ Require(GetProcessTimes(owner, out ownerCreated, out ignored1, out ignored2, out ignored3));
3602
+ Require(GetProcessTimes(GetCurrentProcess(), out ownCreated, out ignored1, out ignored2, out ignored3));
3603
+ // Refuse a recycled owner PID, and hold its identity handle thereafter.
3604
+ if (ownerCreated > ownCreated || WaitForSingleObject(owner, 0) != 258) return 1;
3605
+ job = CreateJobObjectW(IntPtr.Zero, null);
3606
+ Require(job != IntPtr.Zero);
3607
+ var limits = new Limits(); limits.Basic.Flags = 0x2000; // KILL_ON_JOB_CLOSE, no breakaway.
3608
+ Require(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(Limits))));
3609
+ var startup = new Startup(); startup.Size = (uint)Marshal.SizeOf(typeof(Startup));
3610
+ startup.Flags = 0x100; // STARTF_USESTDHANDLES.
3611
+ startup.Input = GetStdHandle(-10); startup.Output = GetStdHandle(-11); startup.Error = GetStdHandle(-12);
3612
+ foreach (IntPtr handle in new [] { startup.Input, startup.Output, startup.Error })
3613
+ Require(SetHandleInformation(handle, 1, 1));
3614
+ var command = new StringBuilder(Quote(executable));
3615
+ foreach (string arg in args) command.Append(" ").Append(Quote(arg));
3616
+ Require(CreateProcessW(executable, command, IntPtr.Zero, IntPtr.Zero, true,
3617
+ 0x08000004, IntPtr.Zero, null, ref startup, out child)); // NO_WINDOW | SUSPENDED.
3618
+ if (!AssignProcessToJobObject(job, child.Process)) {
3619
+ // The uncontained child is still suspended. Terminate its exact handle.
3620
+ TerminateProcess(child.Process, 1); WaitForSingleObject(child.Process, 5000);
3621
+ throw new Win32Exception(Marshal.GetLastWin32Error());
3622
+ }
3623
+ Require(ResumeThread(child.Thread) != UInt32.MaxValue);
3624
+ uint ready = WaitForMultipleObjects(2, new [] { child.Process, owner }, false, UInt32.MaxValue);
3625
+ if (ready != 0) {
3626
+ TerminateJobObject(job, 1); WaitForSingleObject(child.Process, 5000); return 1;
3627
+ }
3628
+ uint code; Require(GetExitCodeProcess(child.Process, out code));
3629
+ return (int)code;
3630
+ } finally {
3631
+ // Closing our non-inherited handle kills every remaining descendant,
3632
+ // including detached children, on normal exit, timeout or helper crash.
3633
+ if (job != IntPtr.Zero) CloseHandle(job);
3634
+ if (child.Thread != IntPtr.Zero) CloseHandle(child.Thread);
3635
+ if (child.Process != IntPtr.Zero) CloseHandle(child.Process);
3636
+ if (owner != IntPtr.Zero) CloseHandle(owner);
3637
+ }
3638
+ }
3639
+ }
3640
+ `;
3641
+ function ownedProcess(command, args, ownerPid = process.pid) {
3642
+ const encoded = (value) => Buffer.from(value).toString("base64");
3643
+ const decode = (value) => `[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded(value)}'))`;
3644
+ const script = `$ErrorActionPreference='Stop'
3645
+ Add-Type -TypeDefinition @'
3646
+ ${supervisor}
3647
+ '@
3648
+ ` + `$command=${decode(command)}
3649
+ $argsList=${decode(JSON.stringify(args))}|ConvertFrom-Json
3650
+ ` + `exit [FlightDeckOwned]::Run($command,[string[]]$argsList,${ownerPid})`;
3651
+ return {
3652
+ command: join4(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
3653
+ args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")]
3654
+ };
3655
+ }
3656
+
3657
+ // src/tui/codex-quota.ts
3658
+ var record = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
3659
+ function quota(limits, account) {
3660
+ if (record(account).type !== "chatgpt")
3661
+ return;
3662
+ const bucket = record(record(record(limits).rateLimitsByLimitId).codex);
3663
+ if (bucket.limitId !== "codex")
3664
+ return;
3665
+ const source = [record(bucket.primary), record(bucket.secondary)];
3666
+ const windows = [];
3667
+ for (const [minutes, id] of [[300, "5h"], [10080, "1w"]]) {
3668
+ const matches = source.filter((w) => w.windowDurationMins === minutes);
3669
+ if (matches.length !== 1)
3670
+ continue;
3671
+ const { usedPercent: used, resetsAt: reset } = matches[0];
3672
+ if (typeof used !== "number" || !Number.isFinite(used) || used < 0 || used > 100)
3673
+ continue;
3674
+ if (typeof reset !== "number" || !Number.isFinite(reset) || reset * 1000 <= Date.now())
3675
+ continue;
3676
+ windows.push({ id, ratio: used / 100, resetAtMs: reset * 1000 });
3677
+ }
3678
+ return windows.length ? { windows } : undefined;
3679
+ }
3680
+ function executable(pathValue = process.env.PATH ?? "") {
3681
+ for (const directory of pathValue.split(process.platform === "win32" ? ";" : ":")) {
3682
+ if (!isAbsolute2(directory))
3683
+ continue;
3684
+ const path = join5(directory, process.platform === "win32" ? "codex.exe" : "codex");
3685
+ if (!existsSync4(path))
3686
+ continue;
3687
+ if (process.platform === "win32") {
3688
+ const shim = path.replace(/\.exe$/i, ".shim");
3689
+ if (existsSync4(shim)) {
3690
+ try {
3691
+ const target = /^path\s*=\s*"([^"\r\n]+)"\s*$/m.exec(readFileSync3(shim, "utf8"))?.[1];
3692
+ if (target && isAbsolute2(target) && /[\\/]codex\.exe$/i.test(target) && existsSync4(target))
3693
+ return target;
3694
+ } catch {}
3695
+ return;
3696
+ }
3697
+ }
3698
+ return path;
3699
+ }
3700
+ }
3701
+ function readCodex(signal, options = {}) {
3702
+ if (signal?.aborted)
3703
+ return Promise.resolve(undefined);
3704
+ const command = options.command ?? executable();
3705
+ if (!command)
3706
+ return Promise.resolve(undefined);
3707
+ const launch = options.command ? { command, args: options.args ?? ["app-server", "proxy"] } : process.platform === "win32" ? ownedProcess(command, ["app-server", "--stdio"]) : { command, args: ["app-server", "proxy"] };
3708
+ return new Promise((resolve) => {
3709
+ const child = spawn(launch.command, launch.args, {
3710
+ windowsHide: true,
3711
+ stdio: ["pipe", "pipe", "ignore"]
3712
+ });
3713
+ let finishing = false, bytes = 0, limits, account;
3714
+ let result;
3715
+ let killTimer;
3716
+ const finish = (value) => {
3717
+ if (finishing)
3718
+ return;
3719
+ finishing = true;
3720
+ result = value;
3721
+ clearTimeout(timer);
3722
+ signal?.removeEventListener("abort", abort);
3723
+ child.stdin.end();
3724
+ killTimer = setTimeout(() => {
3725
+ result = undefined;
3726
+ child.kill("SIGKILL");
3727
+ }, 500);
3728
+ };
3729
+ const abort = () => finish();
3730
+ const timer = setTimeout(() => finish(), options.timeoutMs ?? 15000);
3731
+ signal?.addEventListener("abort", abort, { once: true });
3732
+ child.on("error", () => finish());
3733
+ child.stdin.on("error", () => finish());
3734
+ child.on("close", (code) => {
3735
+ clearTimeout(timer);
3736
+ if (killTimer)
3737
+ clearTimeout(killTimer);
3738
+ signal?.removeEventListener("abort", abort);
3739
+ resolve(code === 0 ? result : undefined);
3740
+ });
3741
+ child.stdout.on("data", (chunk) => {
3742
+ bytes += chunk.length;
3743
+ if (bytes > 262144)
3744
+ finish();
3745
+ });
3746
+ const send = (message) => {
3747
+ if (!finishing)
3748
+ child.stdin.write(JSON.stringify(message) + `
3749
+ `);
3750
+ };
3751
+ createInterface({ input: child.stdout }).on("line", (line) => {
3752
+ if (finishing)
3753
+ return;
3754
+ try {
3755
+ const message = record(JSON.parse(line));
3756
+ if (message.error)
3757
+ return finish();
3758
+ if (message.id === 0 && message.result) {
3759
+ send({ method: "initialized", params: {} });
3760
+ send({ id: 1, method: "account/rateLimits/read" });
3761
+ send({ id: 2, method: "account/read", params: { refreshToken: false } });
3762
+ }
3763
+ if (message.id === 1)
3764
+ limits = message.result;
3765
+ if (message.id === 2)
3766
+ account = record(message.result).account;
3767
+ if (limits && account)
3768
+ finish({ limits, account });
3769
+ } catch {
3770
+ finish();
3771
+ }
3772
+ });
3773
+ if (signal?.aborted)
3774
+ finish();
3775
+ else
3776
+ send({ id: 0, method: "initialize", params: {
3777
+ clientInfo: { name: "flight_deck", version: "1.0.0" }
3778
+ } });
3779
+ });
3780
+ }
3781
+ function startCodexQuota(host, deps = {}) {
3782
+ const opened = host.storage?.memory?.("flight-deck.codex-quota", { initial: { value: null, at: 0 } });
3783
+ if (!Array.isArray(opened) || typeof opened[1] !== "function")
3784
+ return;
3785
+ const [state, update] = opened;
3786
+ let disposed = false, running = false, controller;
3787
+ const clear = () => update((draft) => {
3788
+ draft.value = null;
3789
+ draft.at = 0;
3790
+ });
3791
+ clear();
3792
+ const poll = async () => {
3793
+ if (disposed || running)
3794
+ return;
3795
+ running = true;
3796
+ controller = new AbortController;
3797
+ try {
3798
+ const result = await (deps.read ?? readCodex)(controller.signal);
3799
+ if (disposed)
3800
+ return;
3801
+ const value = result ? quota(result.limits, result.account) : undefined;
3802
+ update((draft) => {
3803
+ draft.value = value ?? null;
3804
+ draft.at = value ? Date.now() : 0;
3805
+ });
3806
+ } catch {
3807
+ if (!disposed)
3808
+ clear();
3809
+ } finally {
3810
+ running = false;
3811
+ }
3812
+ };
3813
+ poll();
3814
+ const timer = setInterval(() => {
3815
+ poll();
3816
+ }, deps.intervalMs ?? 60000);
3817
+ return {
3818
+ get value() {
3819
+ return !disposed && Date.now() - state.at <= 90000 ? state.value ?? undefined : undefined;
3820
+ },
3821
+ dispose() {
3822
+ disposed = true;
3823
+ controller?.abort();
3824
+ clearInterval(timer);
3825
+ clear();
3826
+ }
3827
+ };
3828
+ }
3829
+
3523
3830
  // src/tui/ticker.ts
3524
3831
  var TICKER_KEY = "flight-deck.frame";
3525
3832
  var IDLE_REFRESH_MS = 1000;
@@ -4354,13 +4661,15 @@ var tui_default = Plugin.define({
4354
4661
  };
4355
4662
  const goOption = config.sidebar.footer.go;
4356
4663
  const goPanelEnabled = goOption === true || typeof goOption === "object" && goOption !== null;
4357
- const animated = config.sidebar.enabled && (goPanelEnabled || config.sidebar.rows.some((name) => ANIMATED_FIELDS.some((field) => field === name)));
4664
+ const dexEnabled = wants("dex");
4665
+ const animated = config.sidebar.enabled && (goPanelEnabled || dexEnabled || config.sidebar.rows.some((name) => ANIMATED_FIELDS.some((field) => field === name)));
4358
4666
  let spinnerNeeded = false;
4359
4667
  const ticker = startTicker(context, animated ? config.refresh : 0, () => spinnerNeeded);
4360
4668
  const wantGuard = config.sidebar.enabled && config.sidebar.rows.includes("guard");
4361
4669
  const bridge = wantGuard ? startGuardBridge(context) : undefined;
4362
4670
  const wantGo = config.sidebar.enabled && (config.sidebar.rows.includes("go") || goPanelEnabled);
4363
4671
  const goBridge = wantGo ? startGoBridge(context) : undefined;
4672
+ const dexBridge = dexEnabled ? startCodexQuota(context) : undefined;
4364
4673
  const goPanelLayout = goOption === true ? undefined : typeof goOption === "object" && goOption !== null ? goOption : undefined;
4365
4674
  const goLook = createGoLookReader({ hostOptions: context.options, initial: goPanelLayout });
4366
4675
  const announce = (sessionID) => {
@@ -4405,6 +4714,7 @@ var tui_default = Plugin.define({
4405
4714
  turns,
4406
4715
  guard: bridge?.status,
4407
4716
  go: goBridge?.usage,
4717
+ dex: dexBridge?.value,
4408
4718
  sessionId: wants("ses") ? sessionID : undefined,
4409
4719
  frame: ticker?.frame ?? 0
4410
4720
  };
@@ -4490,6 +4800,7 @@ var tui_default = Plugin.define({
4490
4800
  ticker?.dispose();
4491
4801
  bridge?.dispose();
4492
4802
  goBridge?.dispose();
4803
+ dexBridge?.dispose();
4493
4804
  for (const release of releases)
4494
4805
  release();
4495
4806
  };
package/docs/GUIDE.md CHANGED
@@ -17,6 +17,34 @@ The plugin registers one sidebar rail and one ticker. On every tick it reads wha
17
17
 
18
18
  ## Panels
19
19
 
20
+ ### Codex account limits
21
+
22
+ Add `"dex"` to `sidebar.rows` in `flight-deck.jsonc` to show the Codex CLI
23
+ account's 5h and 1w usage, in that order. It uses the Go row's compact dials,
24
+ spacing and error/reset indicators, under its own `dex` label.
25
+ These are Codex/ChatGPT plan limits, not OpenCode Go usage or the selected
26
+ OpenCode model's allowance. The account is the one authenticated in Codex.
27
+
28
+ Requires an authenticated native Codex CLI. On Windows, Flight Deck starts a
29
+ private `codex app-server --stdio` inside an owned Job Object. It does not
30
+ start a shared daemon or change privileges. On other platforms, a running
31
+ authenticated daemon with `app-server proxy` support is required; start it
32
+ separately with `codex app-server daemon start`. Flight Deck never starts or
33
+ stops that shared daemon.
34
+ No new account, paid service or API key is required beyond your existing
35
+ Codex/ChatGPT plan. Codex manages its own authentication.
36
+
37
+ The plugin polls once per minute through a short-lived private connection. It reads
38
+ only account metadata and rate limits, never OAuth files or thread history.
39
+ On Windows, the native server is created suspended, assigned to a kill-on-close
40
+ job, then resumed. A hidden built-in PowerShell helper holds the job and the
41
+ owner's process identity handle. Success closes stdin; timeout or cancellation
42
+ terminates only that helper. Helper exit/crash or owner death closes the job
43
+ and reaps all server descendants, including detached children. Scoop shims are
44
+ bypassed so the native server, not a launcher, is contained before it can run.
45
+ Missing daemon, API-key authentication, invalid windows, expired resets and
46
+ data older than 90 seconds show unavailable rather than fabricated zero usage.
47
+
20
48
  One rail, in the order you list the rows, dimmed under any fixed lines. A session with subagents, defaults, a 200k window:
21
49
 
22
50
  ```text
@@ -162,6 +190,7 @@ Every name `sidebar.rows` accepts, what its number means, and whether it draws b
162
190
  | `turns` | Prompts sent this session. | opt-in |
163
191
  | `guard` | Harness status when a guard bridge supplies it (breaches, orphans, findings, or ok). Without the bridge the row has no data. | opt-in |
164
192
  | `go` | Zen Go usage: three dials (`○ ◔ ◑ ◕ ●`) plus percent for 5h, 1w, 1m, read from OpenCode's own active opencode-go credential store; no env var. A window at 90% or more, or non-ok, turns red; only the worst flagged window carries a reset countdown. | opt-in |
193
+ | `dex` | Codex CLI account usage: the same compact dials for 5h then 1w. Uses a private Job-owned stdio server on Windows, or an existing Codex daemon elsewhere. Missing or stale data says unavailable, never zero; a missing individual window shows a dash in its original position. | opt-in |
165
194
  | `ses` | Clipped 18-cell preview of the session id (less when the label column is narrow, floored at 8), labelled `session`. Click copies the full id. A verified copy is silent: the host write reports `written`, or an exact clipboard read-back confirms an OSC52 dispatch. An unconfirmed dispatch is an advisory warning (paste to verify). Gate the failure toast with `notifications.copy`. | opt-in |
166
195
  | `session` | Alias for `ses`; accepted in `sidebar.rows` and folded to it. | opt-in |
167
196
 
@@ -201,6 +201,7 @@
201
201
  "elapsed",
202
202
  "tps"
203
203
  // ,"go" Zen Go account usage (needs the active opencode-go credential)
204
+ // ,"dex" Codex CLI account's 5h/1w dials (private Job-owned server on Windows)
204
205
  // ,"caution" — the annunciator
205
206
  // ,"branch" — current git branch
206
207
  // ,"updated" — absolute timestamp of the newest recorded action
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "rows": {
147
147
  "type": "array",
148
- "items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "updated", "tps", "spark", "reasoning", "turns", "guard", "go", "ses", "session"] },
148
+ "items": { "enum": ["caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "updated", "tps", "spark", "reasoning", "turns", "guard", "go", "dex", "ses", "session"] },
149
149
  "default": ["status", "agent", "model", "cost", "project", "tokens", "cache", "context", "perms", "elapsed", "tps"],
150
150
  "maxItems": 24,
151
151
  "description": "Which live fields to draw, top to bottom. Any subset, any order - this is the single most useful thing to change. With `sidebar.persist` (the default) every named row always renders, drawing its zero skeleton until the host has data (the opt-in `updated` row has no skeleton and draws `sidebar.placeholder` instead, because there is no honest zero timestamp); with `persist: false` rows with no data are omitted entirely. Counted together with `sidebar.lines` against a 24-line cap on the whole rail. The opt-in `ses` row shows a clipped preview of the session id under the `session` label - budget 18 cells, reduced by however much the label overflows `layout.labelWidth`, floored at 8 - and a mouse click on that row copies the full id to the OS clipboard: a host write reporting `written` or an exact clipboard read-back after the OSC52 dispatch verifies it, only a verified copy counts as success, a verified copy stays silent, and an unverified or failed outcome surfaces a toast gated by `notifications.copy`. `session` is accepted as an alias for `ses` and is normalized to it."
@@ -450,7 +450,7 @@
450
450
  }
451
451
  },
452
452
  "propertyNames": {
453
- "enum": ["*", "caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "updated", "tps", "spark", "reasoning", "turns", "guard", "go", "ses", "session"]
453
+ "enum": ["*", "caution", "status", "agent", "model", "branch", "cost", "total", "project", "tokens", "cache", "context", "perms", "elapsed", "updated", "tps", "spark", "reasoning", "turns", "guard", "go", "dex", "ses", "session"]
454
454
  },
455
455
  "default": { "*": { "color": "subdued", "attributes": [] } },
456
456
  "description": "Style all live rows under `*`, then optionally override any known row name such as `cost`. A row can change one field and inherit the other from `*`; unknown row names are reported and ignored. `session` is accepted as an alias for `ses` and is normalized to it."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oc-flight-deck",
3
- "version": "0.22.1",
3
+ "version": "0.23.1",
4
4
  "description": "Live OpenCode V2 session telemetry — agent, model, branch, cost, tokens, cache hit rate and context usage in your sidebar.",
5
5
  "keywords": [
6
6
  "opencode",
@@ -54,7 +54,7 @@
54
54
  "compile": "bun scripts/build.ts",
55
55
  "check": "bun run typecheck && bun test",
56
56
  "check:dist": "bun run compile && git diff --exit-code -- dist",
57
- "prepublishOnly": "bun run check && bun run compile"
57
+ "prepublishOnly": "node ../../scripts/check-version-cell.mjs . && bun run check && bun run compile"
58
58
  },
59
59
  "publishConfig": {
60
60
  "access": "public"
@@ -0,0 +1,152 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { createInterface } from "node:readline";
5
+ import type { GoUsage, GoWindow } from "./go-usage.js";
6
+ import { ownedProcess } from "./owned-process.js";
7
+
8
+ const record = (v: unknown): Record<string, unknown> =>
9
+ v !== null && typeof v === "object" && !Array.isArray(v) ? v as Record<string, unknown> : {};
10
+
11
+ /** Codex's authenticated account, not the OpenCode Go provider's allowance. */
12
+ export function quota(limits: unknown, account: unknown): GoUsage | undefined {
13
+ if (record(account).type !== "chatgpt") return;
14
+ const bucket = record(record(record(limits).rateLimitsByLimitId).codex);
15
+ if (bucket.limitId !== "codex") return;
16
+ const source = [record(bucket.primary), record(bucket.secondary)];
17
+ const windows: GoWindow[] = [];
18
+ for (const [minutes, id] of [[300, "5h"], [10080, "1w"]] as const) {
19
+ const matches = source.filter(w => w.windowDurationMins === minutes);
20
+ if (matches.length !== 1) continue;
21
+ const { usedPercent: used, resetsAt: reset } = matches[0]!;
22
+ if (typeof used !== "number" || !Number.isFinite(used) || used < 0 || used > 100) continue;
23
+ if (typeof reset !== "number" || !Number.isFinite(reset) || reset * 1000 <= Date.now()) continue;
24
+ windows.push({ id, ratio: used / 100, resetAtMs: reset * 1000 });
25
+ }
26
+ return windows.length ? { windows } : undefined;
27
+ }
28
+
29
+ /** Bypass Scoop's launcher: ownership must refer to the native proxy itself. */
30
+ export function executable(pathValue = process.env.PATH ?? ""): string | undefined {
31
+ for (const directory of pathValue.split(process.platform === "win32" ? ";" : ":")) {
32
+ if (!isAbsolute(directory)) continue;
33
+ const path = join(directory, process.platform === "win32" ? "codex.exe" : "codex");
34
+ if (!existsSync(path)) continue;
35
+ if (process.platform === "win32") {
36
+ const shim = path.replace(/\.exe$/i, ".shim");
37
+ if (existsSync(shim)) {
38
+ try {
39
+ const target = /^path\s*=\s*"([^"\r\n]+)"\s*$/m.exec(readFileSync(shim, "utf8"))?.[1];
40
+ if (target && isAbsolute(target) && /[\\/]codex\.exe$/i.test(target) && existsSync(target)) return target;
41
+ } catch { /* not a supported native installation */ }
42
+ return;
43
+ }
44
+ }
45
+ return path;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Windows uses a private stdio server enclosed in an owned Job Object.
51
+ * Other platforms connect to the existing daemon. Never read OAuth files,
52
+ * create threads, or kill a PID tree. Resolve only after the owned process closes.
53
+ */
54
+ export function readCodex(signal?: AbortSignal, options: {
55
+ command?: string; args?: string[]; timeoutMs?: number;
56
+ } = {}): Promise<{ limits: unknown; account: unknown } | undefined> {
57
+ if (signal?.aborted) return Promise.resolve(undefined);
58
+ const command = options.command ?? executable();
59
+ if (!command) return Promise.resolve(undefined);
60
+ const launch = options.command
61
+ ? { command, args: options.args ?? ["app-server", "proxy"] }
62
+ : process.platform === "win32"
63
+ ? ownedProcess(command, ["app-server", "--stdio"])
64
+ : { command, args: ["app-server", "proxy"] };
65
+ return new Promise(resolve => {
66
+ const child = spawn(launch.command, launch.args, {
67
+ windowsHide: true, stdio: ["pipe", "pipe", "ignore"],
68
+ });
69
+ let finishing = false, bytes = 0, limits: unknown, account: unknown;
70
+ let result: { limits: unknown; account: unknown } | undefined;
71
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
72
+ const finish = (value?: typeof result) => {
73
+ if (finishing) return;
74
+ finishing = true;
75
+ result = value;
76
+ clearTimeout(timer);
77
+ signal?.removeEventListener("abort", abort);
78
+ child.stdin.end();
79
+ // A hung proxy is the exact child handle, never a launcher or PID tree.
80
+ killTimer = setTimeout(() => { result = undefined; child.kill("SIGKILL"); }, 500);
81
+ };
82
+ const abort = () => finish();
83
+ const timer = setTimeout(() => finish(), options.timeoutMs ?? 15000);
84
+ signal?.addEventListener("abort", abort, { once: true });
85
+ child.on("error", () => finish());
86
+ child.stdin.on("error", () => finish());
87
+ child.on("close", code => {
88
+ clearTimeout(timer);
89
+ if (killTimer) clearTimeout(killTimer);
90
+ signal?.removeEventListener("abort", abort);
91
+ resolve(code === 0 ? result : undefined);
92
+ });
93
+ child.stdout.on("data", (chunk: Buffer) => {
94
+ bytes += chunk.length;
95
+ if (bytes > 262144) finish();
96
+ });
97
+ const send = (message: unknown) => {
98
+ if (!finishing) child.stdin.write(JSON.stringify(message) + "\n");
99
+ };
100
+ createInterface({ input: child.stdout }).on("line", line => {
101
+ if (finishing) return;
102
+ try {
103
+ const message = record(JSON.parse(line));
104
+ if (message.error) return finish();
105
+ if (message.id === 0 && message.result) {
106
+ send({ method: "initialized", params: {} });
107
+ send({ id: 1, method: "account/rateLimits/read" });
108
+ send({ id: 2, method: "account/read", params: { refreshToken: false } });
109
+ }
110
+ if (message.id === 1) limits = message.result;
111
+ if (message.id === 2) account = record(message.result).account;
112
+ if (limits && account) finish({ limits, account });
113
+ } catch { finish(); }
114
+ });
115
+ if (signal?.aborted) finish();
116
+ else send({ id: 0, method: "initialize", params: {
117
+ clientInfo: { name: "flight_deck", version: "1.0.0" },
118
+ } });
119
+ });
120
+ }
121
+
122
+ interface State { value: GoUsage | null; at: number }
123
+ interface Host { storage: { memory(key: string, options: { initial: State }): unknown } }
124
+
125
+ export function startCodexQuota(host: Host, deps: {
126
+ read?: (signal: AbortSignal) => ReturnType<typeof readCodex>; intervalMs?: number;
127
+ } = {}) {
128
+ const opened = host.storage?.memory?.("flight-deck.codex-quota", { initial: { value: null, at: 0 } });
129
+ if (!Array.isArray(opened) || typeof opened[1] !== "function") return;
130
+ const [state, update] = opened as [State, (fn: (draft: State) => void) => void];
131
+ let disposed = false, running = false, controller: AbortController | undefined;
132
+ const clear = () => update(draft => { draft.value = null; draft.at = 0; });
133
+ clear();
134
+ const poll = async () => {
135
+ if (disposed || running) return;
136
+ running = true;
137
+ controller = new AbortController();
138
+ try {
139
+ const result = await (deps.read ?? readCodex)(controller.signal);
140
+ if (disposed) return;
141
+ const value = result ? quota(result.limits, result.account) : undefined;
142
+ update(draft => { draft.value = value ?? null; draft.at = value ? Date.now() : 0; });
143
+ } catch { if (!disposed) clear(); }
144
+ finally { running = false; }
145
+ };
146
+ void poll();
147
+ const timer = setInterval(() => { void poll(); }, deps.intervalMs ?? 60000);
148
+ return {
149
+ get value() { return !disposed && Date.now() - state.at <= 90000 ? state.value ?? undefined : undefined; },
150
+ dispose() { disposed = true; controller?.abort(); clearInterval(timer); clear(); },
151
+ };
152
+ }
@@ -26,7 +26,8 @@
26
26
  // can never overflow or wrap.
27
27
 
28
28
  import { asCount, asRecord } from "./coerce.js";
29
- import { goTone, type GoUsage, type GoWindow } from "./go-usage.js";
29
+ import { formatRemaining as formatCompactRemaining, goTone, type GoUsage, type GoWindow } from "./go-usage.js";
30
+ export { formatRemaining as formatCompactRemaining } from "./go-usage.js";
30
31
  import type { RailLine } from "./presentation.js";
31
32
  import type { StatSegment } from "./rows.js";
32
33
  import { DEFAULT_PLACEHOLDER } from "./stat-fields.js";
@@ -333,38 +334,6 @@ function windowById(usage: GoUsage | undefined): Map<GoWindow["id"], GoWindow> {
333
334
  return byId;
334
335
  }
335
336
 
336
- /**
337
- * A duration as one or two compact units: `45s`, `12m`, `2h`, `4h44m`, `1d6h`,
338
- * `30d23h`.
339
- *
340
- * Deliberately not ./go-usage.js's `formatRemaining`: that one is the one-line
341
- * `go` row's hint and stays single-unit. The panel has the columns for the
342
- * next unit down, and the next unit is what turns "4h" into something an agent
343
- * can plan against. Seconds are dropped once hours are on the clock - two
344
- * units is the whole budget - and a unit is omitted when it is zero, so an
345
- * exact `2h` reads `2h` rather than `2h0m`.
346
- *
347
- * The sub-hour branches round up (as the row's hint does), so a countdown
348
- * never understates the wait: 90s reads `2m`, not `1m30s`.
349
- */
350
- export function formatCompactRemaining(ms: number): string {
351
- const totalSeconds = Math.ceil(ms / 1_000);
352
- if (totalSeconds < 60) return `${totalSeconds}s`;
353
- const totalMinutes = Math.ceil(ms / 60_000);
354
- if (totalMinutes < 60) return `${totalMinutes}m`;
355
- const totalHours = Math.floor(ms / 3_600_000);
356
- if (totalHours < 24) {
357
- // Just under the hour: `totalMinutes` is 60 and the hours place is empty,
358
- // so name the minutes rather than print a hollow `0h59m`.
359
- if (totalHours === 0) return `${totalMinutes}m`;
360
- const minutes = Math.floor((ms - totalHours * 3_600_000) / 60_000);
361
- return minutes > 0 ? `${totalHours}h${minutes}m` : `${totalHours}h`;
362
- }
363
- const totalDays = Math.floor(ms / 86_400_000);
364
- const hours = Math.floor((ms - totalDays * 86_400_000) / 3_600_000);
365
- return hours > 0 ? `${totalDays}d${hours}h` : `${totalDays}d`;
366
- }
367
-
368
337
  /**
369
338
  * The reset countdown for one window, or `undefined` when the reset is unknown
370
339
  * or already past.
@@ -289,20 +289,27 @@ export function goTone(window: GoWindow): "error" | "normal" {
289
289
  }
290
290
 
291
291
  /**
292
- * A duration as one short unit: `45s`, `12m`, `2h`, `5d`.
292
+ * A duration as one or two compact units: `45s`, `12m`, `4h44m`, `26d20h`.
293
293
  *
294
294
  * Exported because the footer's Go panel (./go-panel.ts) draws a countdown for
295
295
  * every known future reset, while {@link goResetSuffix} draws one only under the
296
- * error tone. Both must read the same way, so both read this.
296
+ * error tone. Sub-hour waits round up; longer waits truncate smaller units,
297
+ * matching the panel's compact display.
297
298
  */
298
299
  export function formatRemaining(ms: number): string {
299
300
  const seconds = Math.ceil(ms / 1000);
300
301
  if (seconds < 60) return `${seconds}s`;
301
302
  const minutes = Math.ceil(ms / 60_000);
302
303
  if (minutes < 60) return `${minutes}m`;
303
- const hours = Math.ceil(ms / 3_600_000);
304
- if (hours < 24) return `${hours}h`;
305
- return `${Math.ceil(ms / 86_400_000)}d`;
304
+ const hours = Math.floor(ms / 3_600_000);
305
+ if (hours < 24) {
306
+ if (hours === 0) return `${minutes}m`;
307
+ const rest = Math.floor((ms - hours * 3_600_000) / 60_000);
308
+ return rest > 0 ? `${hours}h${rest}m` : `${hours}h`;
309
+ }
310
+ const days = Math.floor(ms / 86_400_000);
311
+ const rest = Math.floor((ms - days * 86_400_000) / 3_600_000);
312
+ return rest > 0 ? `${days}d${rest}h` : `${days}d`;
306
313
  }
307
314
 
308
315
  /**
package/src/tui/index.tsx CHANGED
@@ -19,6 +19,7 @@ import { ANIMATED_FIELDS, type StatSource } from "./stats.js";
19
19
  import { attributeMask, themeColor } from "./style.js";
20
20
  import { startGuardBridge } from "./guard.js";
21
21
  import { startGoBridge } from "./go.js";
22
+ import { startCodexQuota } from "./codex-quota.js";
22
23
  import { startTicker } from "./ticker.js";
23
24
  import { asCount, asRecord, type SessionLike } from "./coerce.js";
24
25
  import { createProjectTotals } from "./project-totals.js";
@@ -220,9 +221,10 @@ export default Plugin.define({
220
221
  // frame only when the look opts in; by default the bar is static).
221
222
  const goOption = config.sidebar.footer.go;
222
223
  const goPanelEnabled = goOption === true || (typeof goOption === "object" && goOption !== null);
224
+ const dexEnabled = wants("dex");
223
225
  const animated =
224
226
  config.sidebar.enabled &&
225
- (goPanelEnabled ||
227
+ (goPanelEnabled || dexEnabled ||
226
228
  config.sidebar.rows.some((name) => ANIMATED_FIELDS.some((field) => field === name)));
227
229
  let spinnerNeeded = false;
228
230
  const ticker = startTicker(context, animated ? config.refresh : 0, () => spinnerNeeded);
@@ -243,6 +245,7 @@ export default Plugin.define({
243
245
  const wantGo =
244
246
  config.sidebar.enabled && (config.sidebar.rows.includes("go") || goPanelEnabled);
245
247
  const goBridge = wantGo ? startGoBridge(context) : undefined;
248
+ const dexBridge = dexEnabled ? startCodexQuota(context) : undefined;
246
249
 
247
250
  // The footer panel's look, re-resolved live from the config file: the
248
251
  // reader cheap-stats the file each render (mtime + size) and re-reads +
@@ -336,6 +339,7 @@ export default Plugin.define({
336
339
  // Read the go store inside the render too, so a poll re-runs the rail
337
340
  // exactly as the guard read does.
338
341
  go: goBridge?.usage,
342
+ dex: dexBridge?.value,
339
343
  // The id comes from the slot render props, read fresh on every render
340
344
  // rather than cached: the sidebar is not remounted on a session switch,
341
345
  // so a signal or module variable here would copy a stale session.
@@ -492,6 +496,7 @@ export default Plugin.define({
492
496
  ticker?.dispose();
493
497
  bridge?.dispose();
494
498
  goBridge?.dispose();
499
+ dexBridge?.dispose();
495
500
  for (const release of releases) release();
496
501
  };
497
502
  },
@@ -0,0 +1,126 @@
1
+ import { join } from "node:path";
2
+
3
+ // Windows has no Node Job Object API. This in-process PowerShell helper uses
4
+ // only process/job handles; it never opens credentials or alternate tokens.
5
+ // The server is born suspended and cannot run before assignment to our job.
6
+ const supervisor = String.raw`
7
+ using System;
8
+ using System.ComponentModel;
9
+ using System.Runtime.InteropServices;
10
+ using System.Text;
11
+
12
+ public static class FlightDeckOwned {
13
+ [StructLayout(LayoutKind.Sequential)] struct BasicLimits {
14
+ public long ProcessTime, JobTime; public uint Flags;
15
+ public UIntPtr MinWorking, MaxWorking; public uint Active;
16
+ public UIntPtr Affinity; public uint Priority, Scheduling;
17
+ }
18
+ [StructLayout(LayoutKind.Sequential)] struct IoCounters {
19
+ public ulong ReadOps, WriteOps, OtherOps, ReadBytes, WriteBytes, OtherBytes;
20
+ }
21
+ [StructLayout(LayoutKind.Sequential)] struct Limits {
22
+ public BasicLimits Basic; public IoCounters Io;
23
+ public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
24
+ }
25
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct Startup {
26
+ public uint Size; public string Reserved, Desktop, Title;
27
+ public uint X, Y, Width, Height, XChars, YChars, Fill, Flags;
28
+ public ushort Show, ReservedSize; public IntPtr ReservedBytes, Input, Output, Error;
29
+ }
30
+ [StructLayout(LayoutKind.Sequential)] struct ProcessInfo {
31
+ public IntPtr Process, Thread; public uint Pid, Tid;
32
+ }
33
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
34
+ static extern IntPtr CreateJobObjectW(IntPtr security, string name);
35
+ [DllImport("kernel32.dll", SetLastError=true)]
36
+ static extern bool SetInformationJobObject(IntPtr job, int kind, ref Limits limits, uint size);
37
+ [DllImport("kernel32.dll", SetLastError=true)]
38
+ static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
39
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
40
+ static extern bool CreateProcessW(string app, StringBuilder command, IntPtr ps, IntPtr ts,
41
+ bool inherit, uint flags, IntPtr environment, string directory, ref Startup startup, out ProcessInfo info);
42
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
43
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateProcess(IntPtr process, uint code);
44
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateJobObject(IntPtr job, uint code);
45
+ [DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
46
+ [DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();
47
+ [DllImport("kernel32.dll", SetLastError=true)]
48
+ static extern bool GetProcessTimes(IntPtr process, out long created, out long exited, out long kernel, out long user);
49
+ [DllImport("kernel32.dll", SetLastError=true)]
50
+ static extern uint WaitForMultipleObjects(uint count, IntPtr[] handles, bool all, uint timeout);
51
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle, uint timeout);
52
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
53
+ [DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(int id);
54
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetHandleInformation(IntPtr handle, uint mask, uint flags);
55
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
56
+ static void Require(bool ok) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); }
57
+ static string Quote(string value) {
58
+ var text = new StringBuilder("\""); int slashes = 0;
59
+ foreach (char c in value) {
60
+ if (c == '\\') { slashes++; continue; }
61
+ if (c == '"') { text.Append('\\', slashes * 2 + 1); text.Append(c); }
62
+ else { text.Append('\\', slashes); text.Append(c); }
63
+ slashes = 0;
64
+ }
65
+ text.Append('\\', slashes * 2); return text.Append('"').ToString();
66
+ }
67
+ public static int Run(string executable, string[] args, uint ownerPid) {
68
+ IntPtr owner = IntPtr.Zero, job = IntPtr.Zero;
69
+ ProcessInfo child = new ProcessInfo();
70
+ try {
71
+ owner = OpenProcess(0x00101000, false, ownerPid);
72
+ Require(owner != IntPtr.Zero);
73
+ long ownerCreated, ownCreated, ignored1, ignored2, ignored3;
74
+ Require(GetProcessTimes(owner, out ownerCreated, out ignored1, out ignored2, out ignored3));
75
+ Require(GetProcessTimes(GetCurrentProcess(), out ownCreated, out ignored1, out ignored2, out ignored3));
76
+ // Refuse a recycled owner PID, and hold its identity handle thereafter.
77
+ if (ownerCreated > ownCreated || WaitForSingleObject(owner, 0) != 258) return 1;
78
+ job = CreateJobObjectW(IntPtr.Zero, null);
79
+ Require(job != IntPtr.Zero);
80
+ var limits = new Limits(); limits.Basic.Flags = 0x2000; // KILL_ON_JOB_CLOSE, no breakaway.
81
+ Require(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(Limits))));
82
+ var startup = new Startup(); startup.Size = (uint)Marshal.SizeOf(typeof(Startup));
83
+ startup.Flags = 0x100; // STARTF_USESTDHANDLES.
84
+ startup.Input = GetStdHandle(-10); startup.Output = GetStdHandle(-11); startup.Error = GetStdHandle(-12);
85
+ foreach (IntPtr handle in new [] { startup.Input, startup.Output, startup.Error })
86
+ Require(SetHandleInformation(handle, 1, 1));
87
+ var command = new StringBuilder(Quote(executable));
88
+ foreach (string arg in args) command.Append(" ").Append(Quote(arg));
89
+ Require(CreateProcessW(executable, command, IntPtr.Zero, IntPtr.Zero, true,
90
+ 0x08000004, IntPtr.Zero, null, ref startup, out child)); // NO_WINDOW | SUSPENDED.
91
+ if (!AssignProcessToJobObject(job, child.Process)) {
92
+ // The uncontained child is still suspended. Terminate its exact handle.
93
+ TerminateProcess(child.Process, 1); WaitForSingleObject(child.Process, 5000);
94
+ throw new Win32Exception(Marshal.GetLastWin32Error());
95
+ }
96
+ Require(ResumeThread(child.Thread) != UInt32.MaxValue);
97
+ uint ready = WaitForMultipleObjects(2, new [] { child.Process, owner }, false, UInt32.MaxValue);
98
+ if (ready != 0) {
99
+ TerminateJobObject(job, 1); WaitForSingleObject(child.Process, 5000); return 1;
100
+ }
101
+ uint code; Require(GetExitCodeProcess(child.Process, out code));
102
+ return (int)code;
103
+ } finally {
104
+ // Closing our non-inherited handle kills every remaining descendant,
105
+ // including detached children, on normal exit, timeout or helper crash.
106
+ if (job != IntPtr.Zero) CloseHandle(job);
107
+ if (child.Thread != IntPtr.Zero) CloseHandle(child.Thread);
108
+ if (child.Process != IntPtr.Zero) CloseHandle(child.Process);
109
+ if (owner != IntPtr.Zero) CloseHandle(owner);
110
+ }
111
+ }
112
+ }
113
+ `;
114
+
115
+ /** Start a private native process enclosed in an owned Windows job. */
116
+ export function ownedProcess(command: string, args: string[], ownerPid = process.pid): { command: string; args: string[] } {
117
+ const encoded = (value: string) => Buffer.from(value).toString("base64");
118
+ const decode = (value: string) => `[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded(value)}'))`;
119
+ const script = `$ErrorActionPreference='Stop'\nAdd-Type -TypeDefinition @'\n${supervisor}\n'@\n` +
120
+ `$command=${decode(command)}\n$argsList=${decode(JSON.stringify(args))}|ConvertFrom-Json\n` +
121
+ `exit [FlightDeckOwned]::Run($command,[string[]]$argsList,${ownerPid})`;
122
+ return {
123
+ command: join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
124
+ args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")],
125
+ };
126
+ }
package/src/tui/rows.ts CHANGED
@@ -172,11 +172,14 @@ function asGoWindows(value: unknown): readonly GoWindow[] {
172
172
  * makes the row read as one panel with a problem rather than as a different
173
173
  * kind of line.
174
174
  */
175
- function goValueSegments(source: StatSource, layout: LayoutHint): StatSegment[] | undefined {
176
- const windows = asGoWindows(source.go);
175
+ function goValueSegments(source: StatSource, layout: LayoutHint, name: "go" | "dex" = "go"): StatSegment[] | undefined {
176
+ let windows = asGoWindows(source[name]);
177
+ const nowMs = layout.nowMs ?? Date.now();
178
+ if (name === "dex") windows = windows.filter(w => w.id !== "1m" && w.resetAtMs !== undefined && w.resetAtMs > nowMs);
177
179
  if (windows.length === 0) return undefined;
180
+ // Preserve the 5h/1w positions even when one window is unavailable.
181
+ if (name === "dex") windows = (["5h", "1w"] as const).map(id => windows.find(w => w.id === id) ?? { id });
178
182
 
179
- const nowMs = layout.nowMs ?? Date.now();
180
183
  // Only the worst flagged window carries a reset hint. With every window red,
181
184
  // three hints overflow the rail (the 38-column budget) for information that is
182
185
  // redundant three times over; the fullest window is the one actually in
@@ -196,6 +199,7 @@ function goValueSegments(source: StatSource, layout: LayoutHint): StatSegment[]
196
199
  }
197
200
  const chunks: StatSegment[][] = [];
198
201
  for (const [index, window] of windows.entries()) {
202
+ if (window.ratio === undefined) { chunks.push([{ text: "\u2014" }]); continue; }
199
203
  const percent = Math.round((window.ratio ?? 0) * 100);
200
204
  const tone: StyleColor | undefined = goTone(window) === "error" ? "error" : undefined;
201
205
  const chunk: StatSegment[] = [{ text: `${dialGlyph(percent)} ${percent}`, tone }];
@@ -574,12 +578,15 @@ export function statLine(
574
578
  );
575
579
  return id === undefined ? undefined : row("ses", clip(id, budget));
576
580
  }
577
- case "go": {
581
+ case "go":
582
+ case "dex": {
583
+ const name = canonicalField(field) as "go" | "dex";
578
584
  // The plain string is the exact join of the coloured segments, so the
579
585
  // string view (tests, `sidebarTextLines`) and the JSX view agree
580
586
  // character-for-character.
581
- const value = goValueSegments(source, layout);
582
- return value === undefined ? undefined : row("go", value.map((segment) => segment.text).join(""));
587
+ const value = goValueSegments(source, layout, name);
588
+ if (name === "dex" && value === undefined) return row("dex", "unavailable");
589
+ return value === undefined ? undefined : row(name, value.map((segment) => segment.text).join(""));
583
590
  }
584
591
  default:
585
592
  return undefined;
@@ -611,10 +618,10 @@ export function statSegments(
611
618
  ...value,
612
619
  ];
613
620
  }
614
- if (name !== "go") return undefined;
615
- const value = goValueSegments(source, layout);
621
+ if (name !== "go" && name !== "dex") return undefined;
622
+ const value = goValueSegments(source, layout, name);
616
623
  if (value === undefined) return undefined;
617
- return [{ text: labelPrefix(fieldLabel("go", layout.labels), layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
624
+ return [{ text: labelPrefix(fieldLabel(name, layout.labels), layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
618
625
  }
619
626
 
620
627
  /** Render every named field, in the given order.
@@ -79,6 +79,8 @@ export interface StatSource {
79
79
  * type across the module boundary.
80
80
  */
81
81
  readonly go?: unknown;
82
+ /** Authenticated Codex CLI account limits: 5h and 1w, never Go usage. */
83
+ readonly dex?: unknown;
82
84
  }
83
85
 
84
86
  /** Fields a user may name in `sidebar.rows`, in the order they are documented. */
@@ -103,6 +105,7 @@ export const STAT_FIELDS = [
103
105
  "turns",
104
106
  "guard",
105
107
  "go",
108
+ "dex",
106
109
  "ses",
107
110
  ] as const;
108
111
 
@@ -280,6 +283,8 @@ export function skeletonValue(field: string, layout: LayoutHint): string | undef
280
283
  return "0";
281
284
  case "go":
282
285
  return "○ 0 ○ 0 ○ 0";
286
+ case "dex":
287
+ return "unavailable";
283
288
  case "status":
284
289
  return "○ idle";
285
290
  case "agent":
@@ -294,4 +299,3 @@ export function skeletonValue(field: string, layout: LayoutHint): string | undef
294
299
  return undefined;
295
300
  }
296
301
  }
297
-