oc-flight-deck 0.22.1 → 0.23.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/CHANGELOG.md +5 -1
- package/dist/tui/index.js +334 -10
- package/docs/GUIDE.md +29 -0
- package/flight-deck.example.jsonc +1 -0
- package/flight-deck.schema.json +2 -2
- package/package.json +2 -2
- package/src/tui/codex-quota.ts +152 -0
- package/src/tui/index.tsx +6 -1
- package/src/tui/owned-process.ts +126 -0
- package/src/tui/rows.ts +16 -9
- package/src/tui/stat-fields.ts +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,7 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
-
## [0.
|
|
10
|
+
## [0.23.0] - 2026-11-14
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- 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
15
|
|
|
12
16
|
## [0.22.0] - 2026-11-10
|
|
13
17
|
|
package/dist/tui/index.js
CHANGED
|
@@ -731,6 +731,7 @@ var STAT_FIELDS = [
|
|
|
731
731
|
"turns",
|
|
732
732
|
"guard",
|
|
733
733
|
"go",
|
|
734
|
+
"dex",
|
|
734
735
|
"ses"
|
|
735
736
|
];
|
|
736
737
|
var ANIMATED_FIELDS = ["caution", "status", "elapsed", "tps"];
|
|
@@ -775,6 +776,8 @@ function skeletonValue(field, layout) {
|
|
|
775
776
|
return "0";
|
|
776
777
|
case "go":
|
|
777
778
|
return "\u25CB 0 \u25CB 0 \u25CB 0";
|
|
779
|
+
case "dex":
|
|
780
|
+
return "unavailable";
|
|
778
781
|
case "status":
|
|
779
782
|
return "\u25CB idle";
|
|
780
783
|
case "agent":
|
|
@@ -851,11 +854,15 @@ function asGoWindows(value) {
|
|
|
851
854
|
windows.sort((a, b) => GO_ORDER.indexOf(a.id) - GO_ORDER.indexOf(b.id));
|
|
852
855
|
return windows;
|
|
853
856
|
}
|
|
854
|
-
function goValueSegments(source, layout) {
|
|
855
|
-
|
|
857
|
+
function goValueSegments(source, layout, name = "go") {
|
|
858
|
+
let windows = asGoWindows(source[name]);
|
|
859
|
+
const nowMs = layout.nowMs ?? Date.now();
|
|
860
|
+
if (name === "dex")
|
|
861
|
+
windows = windows.filter((w) => w.id !== "1m" && w.resetAtMs !== undefined && w.resetAtMs > nowMs);
|
|
856
862
|
if (windows.length === 0)
|
|
857
863
|
return;
|
|
858
|
-
|
|
864
|
+
if (name === "dex")
|
|
865
|
+
windows = ["5h", "1w"].map((id) => windows.find((w) => w.id === id) ?? { id });
|
|
859
866
|
let flagged = -1;
|
|
860
867
|
let flaggedRatio = Number.NEGATIVE_INFINITY;
|
|
861
868
|
for (const [index, window] of windows.entries()) {
|
|
@@ -869,6 +876,10 @@ function goValueSegments(source, layout) {
|
|
|
869
876
|
}
|
|
870
877
|
const chunks = [];
|
|
871
878
|
for (const [index, window] of windows.entries()) {
|
|
879
|
+
if (window.ratio === undefined) {
|
|
880
|
+
chunks.push([{ text: "\u2014" }]);
|
|
881
|
+
continue;
|
|
882
|
+
}
|
|
872
883
|
const percent = Math.round((window.ratio ?? 0) * 100);
|
|
873
884
|
const tone = goTone(window) === "error" ? "error" : undefined;
|
|
874
885
|
const chunk = [{ text: `${dialGlyph(percent)} ${percent}`, tone }];
|
|
@@ -1096,9 +1107,13 @@ function statLine(field, source, layout = {}) {
|
|
|
1096
1107
|
const budget = Math.max(8, SES_PREVIEW_WIDTH - Math.max(0, labelPrefix(fieldLabel("ses", layout.labels), labelWidth).length - labelPrefix("ses", labelWidth).length));
|
|
1097
1108
|
return id === undefined ? undefined : row("ses", clip(id, budget));
|
|
1098
1109
|
}
|
|
1099
|
-
case "go":
|
|
1100
|
-
|
|
1101
|
-
|
|
1110
|
+
case "go":
|
|
1111
|
+
case "dex": {
|
|
1112
|
+
const name = canonicalField(field);
|
|
1113
|
+
const value = goValueSegments(source, layout, name);
|
|
1114
|
+
if (name === "dex" && value === undefined)
|
|
1115
|
+
return row("dex", "unavailable");
|
|
1116
|
+
return value === undefined ? undefined : row(name, value.map((segment) => segment.text).join(""));
|
|
1102
1117
|
}
|
|
1103
1118
|
default:
|
|
1104
1119
|
return;
|
|
@@ -1115,12 +1130,12 @@ function statSegments(field, source, layout = {}) {
|
|
|
1115
1130
|
...value
|
|
1116
1131
|
];
|
|
1117
1132
|
}
|
|
1118
|
-
if (name !== "go")
|
|
1133
|
+
if (name !== "go" && name !== "dex")
|
|
1119
1134
|
return;
|
|
1120
|
-
const value = goValueSegments(source, layout);
|
|
1135
|
+
const value = goValueSegments(source, layout, name);
|
|
1121
1136
|
if (value === undefined)
|
|
1122
1137
|
return;
|
|
1123
|
-
return [{ text: labelPrefix(fieldLabel(
|
|
1138
|
+
return [{ text: labelPrefix(fieldLabel(name, layout.labels), layout.labelWidth ?? DEFAULT_LABEL_WIDTH) }, ...value];
|
|
1124
1139
|
}
|
|
1125
1140
|
function statRows(fields, source, layout = {}) {
|
|
1126
1141
|
const hint = { ...layout, hasTotalRow: fields.includes("total") };
|
|
@@ -3520,6 +3535,311 @@ function startGoBridge(host, deps, intervalMs = GO_POLL_MS) {
|
|
|
3520
3535
|
};
|
|
3521
3536
|
}
|
|
3522
3537
|
|
|
3538
|
+
// src/tui/codex-quota.ts
|
|
3539
|
+
import { spawn } from "child_process";
|
|
3540
|
+
import { existsSync as existsSync4, readFileSync as readFileSync3 } from "fs";
|
|
3541
|
+
import { isAbsolute as isAbsolute2, join as join5 } from "path";
|
|
3542
|
+
import { createInterface } from "readline";
|
|
3543
|
+
|
|
3544
|
+
// src/tui/owned-process.ts
|
|
3545
|
+
import { join as join4 } from "path";
|
|
3546
|
+
var supervisor = String.raw`
|
|
3547
|
+
using System;
|
|
3548
|
+
using System.ComponentModel;
|
|
3549
|
+
using System.Runtime.InteropServices;
|
|
3550
|
+
using System.Text;
|
|
3551
|
+
|
|
3552
|
+
public static class FlightDeckOwned {
|
|
3553
|
+
[StructLayout(LayoutKind.Sequential)] struct BasicLimits {
|
|
3554
|
+
public long ProcessTime, JobTime; public uint Flags;
|
|
3555
|
+
public UIntPtr MinWorking, MaxWorking; public uint Active;
|
|
3556
|
+
public UIntPtr Affinity; public uint Priority, Scheduling;
|
|
3557
|
+
}
|
|
3558
|
+
[StructLayout(LayoutKind.Sequential)] struct IoCounters {
|
|
3559
|
+
public ulong ReadOps, WriteOps, OtherOps, ReadBytes, WriteBytes, OtherBytes;
|
|
3560
|
+
}
|
|
3561
|
+
[StructLayout(LayoutKind.Sequential)] struct Limits {
|
|
3562
|
+
public BasicLimits Basic; public IoCounters Io;
|
|
3563
|
+
public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
|
|
3564
|
+
}
|
|
3565
|
+
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct Startup {
|
|
3566
|
+
public uint Size; public string Reserved, Desktop, Title;
|
|
3567
|
+
public uint X, Y, Width, Height, XChars, YChars, Fill, Flags;
|
|
3568
|
+
public ushort Show, ReservedSize; public IntPtr ReservedBytes, Input, Output, Error;
|
|
3569
|
+
}
|
|
3570
|
+
[StructLayout(LayoutKind.Sequential)] struct ProcessInfo {
|
|
3571
|
+
public IntPtr Process, Thread; public uint Pid, Tid;
|
|
3572
|
+
}
|
|
3573
|
+
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
|
|
3574
|
+
static extern IntPtr CreateJobObjectW(IntPtr security, string name);
|
|
3575
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
3576
|
+
static extern bool SetInformationJobObject(IntPtr job, int kind, ref Limits limits, uint size);
|
|
3577
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
3578
|
+
static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
|
3579
|
+
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
|
|
3580
|
+
static extern bool CreateProcessW(string app, StringBuilder command, IntPtr ps, IntPtr ts,
|
|
3581
|
+
bool inherit, uint flags, IntPtr environment, string directory, ref Startup startup, out ProcessInfo info);
|
|
3582
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
|
|
3583
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateProcess(IntPtr process, uint code);
|
|
3584
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateJobObject(IntPtr job, uint code);
|
|
3585
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
|
|
3586
|
+
[DllImport("kernel32.dll")] static extern IntPtr GetCurrentProcess();
|
|
3587
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
3588
|
+
static extern bool GetProcessTimes(IntPtr process, out long created, out long exited, out long kernel, out long user);
|
|
3589
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
3590
|
+
static extern uint WaitForMultipleObjects(uint count, IntPtr[] handles, bool all, uint timeout);
|
|
3591
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle, uint timeout);
|
|
3592
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
|
|
3593
|
+
[DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(int id);
|
|
3594
|
+
[DllImport("kernel32.dll", SetLastError=true)] static extern bool SetHandleInformation(IntPtr handle, uint mask, uint flags);
|
|
3595
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
|
|
3596
|
+
static void Require(bool ok) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); }
|
|
3597
|
+
static string Quote(string value) {
|
|
3598
|
+
var text = new StringBuilder("\""); int slashes = 0;
|
|
3599
|
+
foreach (char c in value) {
|
|
3600
|
+
if (c == '\\') { slashes++; continue; }
|
|
3601
|
+
if (c == '"') { text.Append('\\', slashes * 2 + 1); text.Append(c); }
|
|
3602
|
+
else { text.Append('\\', slashes); text.Append(c); }
|
|
3603
|
+
slashes = 0;
|
|
3604
|
+
}
|
|
3605
|
+
text.Append('\\', slashes * 2); return text.Append('"').ToString();
|
|
3606
|
+
}
|
|
3607
|
+
public static int Run(string executable, string[] args, uint ownerPid) {
|
|
3608
|
+
IntPtr owner = IntPtr.Zero, job = IntPtr.Zero;
|
|
3609
|
+
ProcessInfo child = new ProcessInfo();
|
|
3610
|
+
try {
|
|
3611
|
+
owner = OpenProcess(0x00101000, false, ownerPid);
|
|
3612
|
+
Require(owner != IntPtr.Zero);
|
|
3613
|
+
long ownerCreated, ownCreated, ignored1, ignored2, ignored3;
|
|
3614
|
+
Require(GetProcessTimes(owner, out ownerCreated, out ignored1, out ignored2, out ignored3));
|
|
3615
|
+
Require(GetProcessTimes(GetCurrentProcess(), out ownCreated, out ignored1, out ignored2, out ignored3));
|
|
3616
|
+
// Refuse a recycled owner PID, and hold its identity handle thereafter.
|
|
3617
|
+
if (ownerCreated > ownCreated || WaitForSingleObject(owner, 0) != 258) return 1;
|
|
3618
|
+
job = CreateJobObjectW(IntPtr.Zero, null);
|
|
3619
|
+
Require(job != IntPtr.Zero);
|
|
3620
|
+
var limits = new Limits(); limits.Basic.Flags = 0x2000; // KILL_ON_JOB_CLOSE, no breakaway.
|
|
3621
|
+
Require(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(Limits))));
|
|
3622
|
+
var startup = new Startup(); startup.Size = (uint)Marshal.SizeOf(typeof(Startup));
|
|
3623
|
+
startup.Flags = 0x100; // STARTF_USESTDHANDLES.
|
|
3624
|
+
startup.Input = GetStdHandle(-10); startup.Output = GetStdHandle(-11); startup.Error = GetStdHandle(-12);
|
|
3625
|
+
foreach (IntPtr handle in new [] { startup.Input, startup.Output, startup.Error })
|
|
3626
|
+
Require(SetHandleInformation(handle, 1, 1));
|
|
3627
|
+
var command = new StringBuilder(Quote(executable));
|
|
3628
|
+
foreach (string arg in args) command.Append(" ").Append(Quote(arg));
|
|
3629
|
+
Require(CreateProcessW(executable, command, IntPtr.Zero, IntPtr.Zero, true,
|
|
3630
|
+
0x08000004, IntPtr.Zero, null, ref startup, out child)); // NO_WINDOW | SUSPENDED.
|
|
3631
|
+
if (!AssignProcessToJobObject(job, child.Process)) {
|
|
3632
|
+
// The uncontained child is still suspended. Terminate its exact handle.
|
|
3633
|
+
TerminateProcess(child.Process, 1); WaitForSingleObject(child.Process, 5000);
|
|
3634
|
+
throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
3635
|
+
}
|
|
3636
|
+
Require(ResumeThread(child.Thread) != UInt32.MaxValue);
|
|
3637
|
+
uint ready = WaitForMultipleObjects(2, new [] { child.Process, owner }, false, UInt32.MaxValue);
|
|
3638
|
+
if (ready != 0) {
|
|
3639
|
+
TerminateJobObject(job, 1); WaitForSingleObject(child.Process, 5000); return 1;
|
|
3640
|
+
}
|
|
3641
|
+
uint code; Require(GetExitCodeProcess(child.Process, out code));
|
|
3642
|
+
return (int)code;
|
|
3643
|
+
} finally {
|
|
3644
|
+
// Closing our non-inherited handle kills every remaining descendant,
|
|
3645
|
+
// including detached children, on normal exit, timeout or helper crash.
|
|
3646
|
+
if (job != IntPtr.Zero) CloseHandle(job);
|
|
3647
|
+
if (child.Thread != IntPtr.Zero) CloseHandle(child.Thread);
|
|
3648
|
+
if (child.Process != IntPtr.Zero) CloseHandle(child.Process);
|
|
3649
|
+
if (owner != IntPtr.Zero) CloseHandle(owner);
|
|
3650
|
+
}
|
|
3651
|
+
}
|
|
3652
|
+
}
|
|
3653
|
+
`;
|
|
3654
|
+
function ownedProcess(command, args, ownerPid = process.pid) {
|
|
3655
|
+
const encoded = (value) => Buffer.from(value).toString("base64");
|
|
3656
|
+
const decode = (value) => `[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded(value)}'))`;
|
|
3657
|
+
const script = `$ErrorActionPreference='Stop'
|
|
3658
|
+
Add-Type -TypeDefinition @'
|
|
3659
|
+
${supervisor}
|
|
3660
|
+
'@
|
|
3661
|
+
` + `$command=${decode(command)}
|
|
3662
|
+
$argsList=${decode(JSON.stringify(args))}|ConvertFrom-Json
|
|
3663
|
+
` + `exit [FlightDeckOwned]::Run($command,[string[]]$argsList,${ownerPid})`;
|
|
3664
|
+
return {
|
|
3665
|
+
command: join4(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
|
|
3666
|
+
args: ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")]
|
|
3667
|
+
};
|
|
3668
|
+
}
|
|
3669
|
+
|
|
3670
|
+
// src/tui/codex-quota.ts
|
|
3671
|
+
var record = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
3672
|
+
function quota(limits, account) {
|
|
3673
|
+
if (record(account).type !== "chatgpt")
|
|
3674
|
+
return;
|
|
3675
|
+
const bucket = record(record(record(limits).rateLimitsByLimitId).codex);
|
|
3676
|
+
if (bucket.limitId !== "codex")
|
|
3677
|
+
return;
|
|
3678
|
+
const source = [record(bucket.primary), record(bucket.secondary)];
|
|
3679
|
+
const windows = [];
|
|
3680
|
+
for (const [minutes, id] of [[300, "5h"], [10080, "1w"]]) {
|
|
3681
|
+
const matches = source.filter((w) => w.windowDurationMins === minutes);
|
|
3682
|
+
if (matches.length !== 1)
|
|
3683
|
+
continue;
|
|
3684
|
+
const { usedPercent: used, resetsAt: reset } = matches[0];
|
|
3685
|
+
if (typeof used !== "number" || !Number.isFinite(used) || used < 0 || used > 100)
|
|
3686
|
+
continue;
|
|
3687
|
+
if (typeof reset !== "number" || !Number.isFinite(reset) || reset * 1000 <= Date.now())
|
|
3688
|
+
continue;
|
|
3689
|
+
windows.push({ id, ratio: used / 100, resetAtMs: reset * 1000 });
|
|
3690
|
+
}
|
|
3691
|
+
return windows.length ? { windows } : undefined;
|
|
3692
|
+
}
|
|
3693
|
+
function executable(pathValue = process.env.PATH ?? "") {
|
|
3694
|
+
for (const directory of pathValue.split(process.platform === "win32" ? ";" : ":")) {
|
|
3695
|
+
if (!isAbsolute2(directory))
|
|
3696
|
+
continue;
|
|
3697
|
+
const path = join5(directory, process.platform === "win32" ? "codex.exe" : "codex");
|
|
3698
|
+
if (!existsSync4(path))
|
|
3699
|
+
continue;
|
|
3700
|
+
if (process.platform === "win32") {
|
|
3701
|
+
const shim = path.replace(/\.exe$/i, ".shim");
|
|
3702
|
+
if (existsSync4(shim)) {
|
|
3703
|
+
try {
|
|
3704
|
+
const target = /^path\s*=\s*"([^"\r\n]+)"\s*$/m.exec(readFileSync3(shim, "utf8"))?.[1];
|
|
3705
|
+
if (target && isAbsolute2(target) && /[\\/]codex\.exe$/i.test(target) && existsSync4(target))
|
|
3706
|
+
return target;
|
|
3707
|
+
} catch {}
|
|
3708
|
+
return;
|
|
3709
|
+
}
|
|
3710
|
+
}
|
|
3711
|
+
return path;
|
|
3712
|
+
}
|
|
3713
|
+
}
|
|
3714
|
+
function readCodex(signal, options = {}) {
|
|
3715
|
+
if (signal?.aborted)
|
|
3716
|
+
return Promise.resolve(undefined);
|
|
3717
|
+
const command = options.command ?? executable();
|
|
3718
|
+
if (!command)
|
|
3719
|
+
return Promise.resolve(undefined);
|
|
3720
|
+
const launch = options.command ? { command, args: options.args ?? ["app-server", "proxy"] } : process.platform === "win32" ? ownedProcess(command, ["app-server", "--stdio"]) : { command, args: ["app-server", "proxy"] };
|
|
3721
|
+
return new Promise((resolve) => {
|
|
3722
|
+
const child = spawn(launch.command, launch.args, {
|
|
3723
|
+
windowsHide: true,
|
|
3724
|
+
stdio: ["pipe", "pipe", "ignore"]
|
|
3725
|
+
});
|
|
3726
|
+
let finishing = false, bytes = 0, limits, account;
|
|
3727
|
+
let result;
|
|
3728
|
+
let killTimer;
|
|
3729
|
+
const finish = (value) => {
|
|
3730
|
+
if (finishing)
|
|
3731
|
+
return;
|
|
3732
|
+
finishing = true;
|
|
3733
|
+
result = value;
|
|
3734
|
+
clearTimeout(timer);
|
|
3735
|
+
signal?.removeEventListener("abort", abort);
|
|
3736
|
+
child.stdin.end();
|
|
3737
|
+
killTimer = setTimeout(() => {
|
|
3738
|
+
result = undefined;
|
|
3739
|
+
child.kill("SIGKILL");
|
|
3740
|
+
}, 500);
|
|
3741
|
+
};
|
|
3742
|
+
const abort = () => finish();
|
|
3743
|
+
const timer = setTimeout(() => finish(), options.timeoutMs ?? 15000);
|
|
3744
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
3745
|
+
child.on("error", () => finish());
|
|
3746
|
+
child.stdin.on("error", () => finish());
|
|
3747
|
+
child.on("close", (code) => {
|
|
3748
|
+
clearTimeout(timer);
|
|
3749
|
+
if (killTimer)
|
|
3750
|
+
clearTimeout(killTimer);
|
|
3751
|
+
signal?.removeEventListener("abort", abort);
|
|
3752
|
+
resolve(code === 0 ? result : undefined);
|
|
3753
|
+
});
|
|
3754
|
+
child.stdout.on("data", (chunk) => {
|
|
3755
|
+
bytes += chunk.length;
|
|
3756
|
+
if (bytes > 262144)
|
|
3757
|
+
finish();
|
|
3758
|
+
});
|
|
3759
|
+
const send = (message) => {
|
|
3760
|
+
if (!finishing)
|
|
3761
|
+
child.stdin.write(JSON.stringify(message) + `
|
|
3762
|
+
`);
|
|
3763
|
+
};
|
|
3764
|
+
createInterface({ input: child.stdout }).on("line", (line) => {
|
|
3765
|
+
if (finishing)
|
|
3766
|
+
return;
|
|
3767
|
+
try {
|
|
3768
|
+
const message = record(JSON.parse(line));
|
|
3769
|
+
if (message.error)
|
|
3770
|
+
return finish();
|
|
3771
|
+
if (message.id === 0 && message.result) {
|
|
3772
|
+
send({ method: "initialized", params: {} });
|
|
3773
|
+
send({ id: 1, method: "account/rateLimits/read" });
|
|
3774
|
+
send({ id: 2, method: "account/read", params: { refreshToken: false } });
|
|
3775
|
+
}
|
|
3776
|
+
if (message.id === 1)
|
|
3777
|
+
limits = message.result;
|
|
3778
|
+
if (message.id === 2)
|
|
3779
|
+
account = record(message.result).account;
|
|
3780
|
+
if (limits && account)
|
|
3781
|
+
finish({ limits, account });
|
|
3782
|
+
} catch {
|
|
3783
|
+
finish();
|
|
3784
|
+
}
|
|
3785
|
+
});
|
|
3786
|
+
if (signal?.aborted)
|
|
3787
|
+
finish();
|
|
3788
|
+
else
|
|
3789
|
+
send({ id: 0, method: "initialize", params: {
|
|
3790
|
+
clientInfo: { name: "flight_deck", version: "1.0.0" }
|
|
3791
|
+
} });
|
|
3792
|
+
});
|
|
3793
|
+
}
|
|
3794
|
+
function startCodexQuota(host, deps = {}) {
|
|
3795
|
+
const opened = host.storage?.memory?.("flight-deck.codex-quota", { initial: { value: null, at: 0 } });
|
|
3796
|
+
if (!Array.isArray(opened) || typeof opened[1] !== "function")
|
|
3797
|
+
return;
|
|
3798
|
+
const [state, update] = opened;
|
|
3799
|
+
let disposed = false, running = false, controller;
|
|
3800
|
+
const clear = () => update((draft) => {
|
|
3801
|
+
draft.value = null;
|
|
3802
|
+
draft.at = 0;
|
|
3803
|
+
});
|
|
3804
|
+
clear();
|
|
3805
|
+
const poll = async () => {
|
|
3806
|
+
if (disposed || running)
|
|
3807
|
+
return;
|
|
3808
|
+
running = true;
|
|
3809
|
+
controller = new AbortController;
|
|
3810
|
+
try {
|
|
3811
|
+
const result = await (deps.read ?? readCodex)(controller.signal);
|
|
3812
|
+
if (disposed)
|
|
3813
|
+
return;
|
|
3814
|
+
const value = result ? quota(result.limits, result.account) : undefined;
|
|
3815
|
+
update((draft) => {
|
|
3816
|
+
draft.value = value ?? null;
|
|
3817
|
+
draft.at = value ? Date.now() : 0;
|
|
3818
|
+
});
|
|
3819
|
+
} catch {
|
|
3820
|
+
if (!disposed)
|
|
3821
|
+
clear();
|
|
3822
|
+
} finally {
|
|
3823
|
+
running = false;
|
|
3824
|
+
}
|
|
3825
|
+
};
|
|
3826
|
+
poll();
|
|
3827
|
+
const timer = setInterval(() => {
|
|
3828
|
+
poll();
|
|
3829
|
+
}, deps.intervalMs ?? 60000);
|
|
3830
|
+
return {
|
|
3831
|
+
get value() {
|
|
3832
|
+
return !disposed && Date.now() - state.at <= 90000 ? state.value ?? undefined : undefined;
|
|
3833
|
+
},
|
|
3834
|
+
dispose() {
|
|
3835
|
+
disposed = true;
|
|
3836
|
+
controller?.abort();
|
|
3837
|
+
clearInterval(timer);
|
|
3838
|
+
clear();
|
|
3839
|
+
}
|
|
3840
|
+
};
|
|
3841
|
+
}
|
|
3842
|
+
|
|
3523
3843
|
// src/tui/ticker.ts
|
|
3524
3844
|
var TICKER_KEY = "flight-deck.frame";
|
|
3525
3845
|
var IDLE_REFRESH_MS = 1000;
|
|
@@ -4354,13 +4674,15 @@ var tui_default = Plugin.define({
|
|
|
4354
4674
|
};
|
|
4355
4675
|
const goOption = config.sidebar.footer.go;
|
|
4356
4676
|
const goPanelEnabled = goOption === true || typeof goOption === "object" && goOption !== null;
|
|
4357
|
-
const
|
|
4677
|
+
const dexEnabled = wants("dex");
|
|
4678
|
+
const animated = config.sidebar.enabled && (goPanelEnabled || dexEnabled || config.sidebar.rows.some((name) => ANIMATED_FIELDS.some((field) => field === name)));
|
|
4358
4679
|
let spinnerNeeded = false;
|
|
4359
4680
|
const ticker = startTicker(context, animated ? config.refresh : 0, () => spinnerNeeded);
|
|
4360
4681
|
const wantGuard = config.sidebar.enabled && config.sidebar.rows.includes("guard");
|
|
4361
4682
|
const bridge = wantGuard ? startGuardBridge(context) : undefined;
|
|
4362
4683
|
const wantGo = config.sidebar.enabled && (config.sidebar.rows.includes("go") || goPanelEnabled);
|
|
4363
4684
|
const goBridge = wantGo ? startGoBridge(context) : undefined;
|
|
4685
|
+
const dexBridge = dexEnabled ? startCodexQuota(context) : undefined;
|
|
4364
4686
|
const goPanelLayout = goOption === true ? undefined : typeof goOption === "object" && goOption !== null ? goOption : undefined;
|
|
4365
4687
|
const goLook = createGoLookReader({ hostOptions: context.options, initial: goPanelLayout });
|
|
4366
4688
|
const announce = (sessionID) => {
|
|
@@ -4405,6 +4727,7 @@ var tui_default = Plugin.define({
|
|
|
4405
4727
|
turns,
|
|
4406
4728
|
guard: bridge?.status,
|
|
4407
4729
|
go: goBridge?.usage,
|
|
4730
|
+
dex: dexBridge?.value,
|
|
4408
4731
|
sessionId: wants("ses") ? sessionID : undefined,
|
|
4409
4732
|
frame: ticker?.frame ?? 0
|
|
4410
4733
|
};
|
|
@@ -4490,6 +4813,7 @@ var tui_default = Plugin.define({
|
|
|
4490
4813
|
ticker?.dispose();
|
|
4491
4814
|
bridge?.dispose();
|
|
4492
4815
|
goBridge?.dispose();
|
|
4816
|
+
dexBridge?.dispose();
|
|
4493
4817
|
for (const release of releases)
|
|
4494
4818
|
release();
|
|
4495
4819
|
};
|
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
|
package/flight-deck.schema.json
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "0.23.0",
|
|
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
|
+
}
|
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
|
-
|
|
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
|
-
|
|
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(
|
|
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.
|
package/src/tui/stat-fields.ts
CHANGED
|
@@ -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
|
-
|