@promptbook/node 0.114.0-21 → 0.114.0-22

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/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('path'), require('fs/promises'), require('spacetrim'), require('colors'), require('child_process'), require('url'), require('crypto-js'), require('crypto-js/enc-hex'), require('waitasecond'), require('dotenv'), require('crypto-js/sha256'), require('rxjs'), require('crypto'), require('mime-types'), require('papaparse'), require('bottleneck')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'path', 'fs/promises', 'spacetrim', 'colors', 'child_process', 'url', 'crypto-js', 'crypto-js/enc-hex', 'waitasecond', 'dotenv', 'crypto-js/sha256', 'rxjs', 'crypto', 'mime-types', 'papaparse', 'bottleneck'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.path, global.promises, global._spaceTrim, global.colors, global.child_process, global.url, global.CryptoJS, global.hexEncoder, global.waitasecond, global.dotenv, global.sha256, global.rxjs, null, global.mimeTypes, global.papaparse, global.Bottleneck));
5
- })(this, (function (exports, path, promises, _spaceTrim, colors, child_process, url, CryptoJS, hexEncoder, waitasecond, dotenv, sha256, rxjs, crypto, mimeTypes, papaparse, Bottleneck) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('path'), require('fs/promises'), require('spacetrim'), require('colors'), require('child_process'), require('readline'), require('url'), require('crypto-js'), require('crypto-js/enc-hex'), require('waitasecond'), require('dotenv'), require('crypto-js/sha256'), require('rxjs'), require('crypto'), require('mime-types'), require('papaparse'), require('bottleneck')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'path', 'fs/promises', 'spacetrim', 'colors', 'child_process', 'readline', 'url', 'crypto-js', 'crypto-js/enc-hex', 'waitasecond', 'dotenv', 'crypto-js/sha256', 'rxjs', 'crypto', 'mime-types', 'papaparse', 'bottleneck'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.path, global.promises, global._spaceTrim, global.colors, global.child_process, global.readline, global.url, global.CryptoJS, global.hexEncoder, global.waitasecond, global.dotenv, global.sha256, global.rxjs, null, global.mimeTypes, global.papaparse, global.Bottleneck));
5
+ })(this, (function (exports, path, promises, _spaceTrim, colors, child_process, readline, url, CryptoJS, hexEncoder, waitasecond, dotenv, sha256, rxjs, crypto, mimeTypes, papaparse, Bottleneck) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -47,7 +47,7 @@
47
47
  * @generated
48
48
  * @see https://github.com/webgptorg/promptbook
49
49
  */
50
- const PROMPTBOOK_ENGINE_VERSION = '0.114.0-21';
50
+ const PROMPTBOOK_ENGINE_VERSION = '0.114.0-22';
51
51
  /**
52
52
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
53
53
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -3425,6 +3425,29 @@
3425
3425
  }
3426
3426
  }
3427
3427
 
3428
+ /**
3429
+ * Merges a newly reported subset of subscription windows into the latest complete snapshot.
3430
+ *
3431
+ * Some harnesses emit an update only for the limit whose state changed. Keeping the previous windows means a
3432
+ * five-hour update cannot make a still-valid weekly limit disappear from the dashboard. Existing order is preserved
3433
+ * and newly discovered windows are appended, which keeps the terminal presentation stable between refreshes.
3434
+ *
3435
+ * @private internal utility of `ptbk coder`
3436
+ */
3437
+ function mergeHarnessSubscriptionUsage(previousSubscriptionUsage, latestSubscriptionUsage) {
3438
+ if (previousSubscriptionUsage === undefined) {
3439
+ return latestSubscriptionUsage;
3440
+ }
3441
+ const latestLimitsByLabel = new Map(latestSubscriptionUsage.limits.map((latestLimit) => [latestLimit.label, latestLimit]));
3442
+ const previousLimitLabels = new Set(previousSubscriptionUsage.limits.map((previousLimit) => previousLimit.label));
3443
+ return {
3444
+ limits: [
3445
+ ...previousSubscriptionUsage.limits.map((previousLimit) => { var _a; return (_a = latestLimitsByLabel.get(previousLimit.label)) !== null && _a !== void 0 ? _a : previousLimit; }),
3446
+ ...latestSubscriptionUsage.limits.filter((latestLimit) => !previousLimitLabels.has(latestLimit.label)),
3447
+ ],
3448
+ };
3449
+ }
3450
+
3428
3451
  /**
3429
3452
  * Base delimiter used for passing large prompts through stdin.
3430
3453
  */
@@ -3758,6 +3781,122 @@
3758
3781
  }
3759
3782
  }
3760
3783
 
3784
+ /**
3785
+ * Human-readable labels for known Claude Code rolling subscription-limit windows.
3786
+ */
3787
+ const CLAUDE_CODE_RATE_LIMIT_LABELS = {
3788
+ five_hour: '5h',
3789
+ seven_day: '7d',
3790
+ seven_day_opus: '7d Opus',
3791
+ seven_day_sonnet: '7d Sonnet',
3792
+ overage: 'Overage',
3793
+ };
3794
+ /**
3795
+ * Fallback label used when a newer Claude Code release adds a rate-limit window unknown to Promptbook.
3796
+ */
3797
+ const UNKNOWN_CLAUDE_CODE_RATE_LIMIT_LABEL = 'Limit';
3798
+ /**
3799
+ * Converts Claude Code stream-json rate-limit events into the shared subscription-usage snapshot.
3800
+ *
3801
+ * Claude Code can emit one event for each applicable limit, so the parser preserves every distinct window instead of
3802
+ * assuming the familiar 5-hour and seven-day pair. This lets a new vendor-side limit appear in the dashboard without
3803
+ * changing its renderer.
3804
+ *
3805
+ * @private internal utility of the Claude Code runner
3806
+ */
3807
+ function parseClaudeCodeSubscriptionUsage(output) {
3808
+ const limitsByType = new Map();
3809
+ for (const event of parseClaudeCodeOutputEvents(output)) {
3810
+ const limit = parseClaudeCodeSubscriptionUsageLimit(event);
3811
+ if (limit) {
3812
+ limitsByType.set(resolveClaudeCodeRateLimitType(event), limit);
3813
+ }
3814
+ }
3815
+ const limits = [...limitsByType.values()];
3816
+ return limits.length === 0 ? undefined : { limits };
3817
+ }
3818
+ /**
3819
+ * Parses one Claude Code stream event when it contains a usable subscription-limit update.
3820
+ *
3821
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
3822
+ */
3823
+ function parseClaudeCodeSubscriptionUsageLimit(event) {
3824
+ if (event.type !== 'rate_limit_event' || !event.rate_limit_info) {
3825
+ return undefined;
3826
+ }
3827
+ const rateLimitType = resolveClaudeCodeRateLimitType(event);
3828
+ const usedPercentage = resolveClaudeCodeUsedPercentage(event.rate_limit_info);
3829
+ if (usedPercentage === undefined) {
3830
+ return undefined;
3831
+ }
3832
+ const resetsAt = resolveClaudeCodeResetTimestamp(event.rate_limit_info);
3833
+ return {
3834
+ label: formatClaudeCodeRateLimitTypeLabel(rateLimitType),
3835
+ usedPercentage,
3836
+ ...(resetsAt !== undefined && { resetsAt }),
3837
+ };
3838
+ }
3839
+ /**
3840
+ * Formats known and newly introduced Claude Code rate-limit types for a stable terminal label.
3841
+ *
3842
+ * A newer limit type remains distinct in the dashboard instead of making several unrelated windows all appear as
3843
+ * a generic `Limit` row.
3844
+ *
3845
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
3846
+ */
3847
+ function formatClaudeCodeRateLimitTypeLabel(rateLimitType) {
3848
+ const knownLabel = CLAUDE_CODE_RATE_LIMIT_LABELS[rateLimitType];
3849
+ if (knownLabel) {
3850
+ return knownLabel;
3851
+ }
3852
+ const words = rateLimitType.split(/[\s_-]+/u).filter(Boolean);
3853
+ if (words.length === 0) {
3854
+ return UNKNOWN_CLAUDE_CODE_RATE_LIMIT_LABEL;
3855
+ }
3856
+ return words.map((word) => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`).join(' ');
3857
+ }
3858
+ /**
3859
+ * Resolves the stable rate-limit type key emitted by Claude Code across camel- and snake-case payload versions.
3860
+ *
3861
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
3862
+ */
3863
+ function resolveClaudeCodeRateLimitType(event) {
3864
+ var _a;
3865
+ const rateLimitInfo = event.rate_limit_info;
3866
+ const rateLimitType = (_a = rateLimitInfo === null || rateLimitInfo === void 0 ? void 0 : rateLimitInfo.rateLimitType) !== null && _a !== void 0 ? _a : rateLimitInfo === null || rateLimitInfo === void 0 ? void 0 : rateLimitInfo.rate_limit_type;
3867
+ return typeof rateLimitType === 'string' && rateLimitType.trim() !== ''
3868
+ ? rateLimitType.trim()
3869
+ : UNKNOWN_CLAUDE_CODE_RATE_LIMIT_LABEL;
3870
+ }
3871
+ /**
3872
+ * Converts Claude's fractional utilization value to a displayed percentage.
3873
+ *
3874
+ * A rejected limit event may omit utilization, but it still conveys a precise zero-remaining state and is therefore
3875
+ * rendered as 100 percent consumed.
3876
+ *
3877
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
3878
+ */
3879
+ function resolveClaudeCodeUsedPercentage(rateLimitInfo) {
3880
+ const utilization = rateLimitInfo.utilization;
3881
+ if (typeof utilization === 'number' && Number.isFinite(utilization)) {
3882
+ const usedPercentage = utilization <= 1 ? utilization * 100 : utilization;
3883
+ if (usedPercentage >= 0 && usedPercentage <= 100) {
3884
+ return usedPercentage;
3885
+ }
3886
+ }
3887
+ return rateLimitInfo.status === 'rejected' ? 100 : undefined;
3888
+ }
3889
+ /**
3890
+ * Reads Claude's optional Unix reset timestamp from either current or earlier stream payload naming.
3891
+ *
3892
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
3893
+ */
3894
+ function resolveClaudeCodeResetTimestamp(rateLimitInfo) {
3895
+ var _a;
3896
+ const resetsAt = (_a = rateLimitInfo.resetsAt) !== null && _a !== void 0 ? _a : rateLimitInfo.resets_at;
3897
+ return typeof resetsAt === 'number' && Number.isFinite(resetsAt) && resetsAt > 0 ? resetsAt : undefined;
3898
+ }
3899
+
3761
3900
  /**
3762
3901
  * Polling interval used while waiting for Claude Code session limits to reset.
3763
3902
  */
@@ -3773,6 +3912,14 @@
3773
3912
  this.options = options;
3774
3913
  this.name = 'claude-code';
3775
3914
  }
3915
+ /**
3916
+ * Returns the latest subscription-limit snapshot emitted by this Claude Code session.
3917
+ *
3918
+ * Claude exposes these values in the normal stream after a response, so no separate quota-only model call is made.
3919
+ */
3920
+ async getSubscriptionUsage() {
3921
+ return this.subscriptionUsage;
3922
+ }
3776
3923
  /**
3777
3924
  * Runs the prompt using Claude Code and parses usage output.
3778
3925
  */
@@ -3786,6 +3933,7 @@
3786
3933
  prompt,
3787
3934
  resumeSessionId,
3788
3935
  }).catch(async (error) => {
3936
+ this.updateSubscriptionUsage(error instanceof Error ? error.message : String(error));
3789
3937
  const sessionLimit = extractClaudeCodeSessionLimitFromError(error);
3790
3938
  if (!sessionLimit) {
3791
3939
  throw error;
@@ -3800,6 +3948,7 @@
3800
3948
  continue;
3801
3949
  }
3802
3950
  const sessionLimit = extractClaudeCodeSessionLimitFromOutput(output);
3951
+ this.updateSubscriptionUsage(output);
3803
3952
  if (sessionLimit) {
3804
3953
  resurrectionCount++;
3805
3954
  await waitForClaudeCodeSessionLimitReset(sessionLimit, resurrectionCount, options);
@@ -3829,6 +3978,18 @@
3829
3978
  preserveArtifactsOnSuccess: options.preserveArtifactsOnSuccess,
3830
3979
  });
3831
3980
  }
3981
+ /**
3982
+ * Keeps the newest usable Claude subscription-limit values reported by the stream.
3983
+ *
3984
+ * A stream can omit these values for API-key users or unsupported plan types; retaining the prior snapshot avoids
3985
+ * a temporary omission erasing a still-valid dashboard value while a long queue is running.
3986
+ */
3987
+ updateSubscriptionUsage(output) {
3988
+ const subscriptionUsage = parseClaudeCodeSubscriptionUsage(output);
3989
+ if (subscriptionUsage) {
3990
+ this.subscriptionUsage = mergeHarnessSubscriptionUsage(this.subscriptionUsage, subscriptionUsage);
3991
+ }
3992
+ }
3832
3993
  }
3833
3994
  /**
3834
3995
  * Waits until the Claude Code session can be resumed, keeping terminal status clear.
@@ -4795,6 +4956,292 @@
4795
4956
  return (_c = OPENAI_MODELS.find((model) => model.modelName === CODEX_FALLBACK_PRICING_MODEL)) === null || _c === void 0 ? void 0 : _c.pricing;
4796
4957
  }
4797
4958
 
4959
+ /**
4960
+ * Arguments which start the Codex app server over JSON-RPC stdio.
4961
+ */
4962
+ const CODEX_APP_SERVER_ARGUMENTS = ['app-server', '--stdio'];
4963
+ /**
4964
+ * Maximum time spent waiting for the optional Codex account-rate-limit snapshot.
4965
+ */
4966
+ const CODEX_SUBSCRIPTION_USAGE_REQUEST_TIMEOUT_MS = 10 * 1000;
4967
+ /**
4968
+ * JSON-RPC request id used for the required app-server initialization handshake.
4969
+ */
4970
+ const INITIALIZE_REQUEST_ID = 1;
4971
+ /**
4972
+ * JSON-RPC request id used for the Codex account rate-limit snapshot.
4973
+ */
4974
+ const RATE_LIMITS_REQUEST_ID = 2;
4975
+ /**
4976
+ * Client name sent to the Codex app server while Promptbook reads subscription limits.
4977
+ */
4978
+ const PROMPTBOOK_CODEX_APP_SERVER_CLIENT_NAME = 'ptbk-coder';
4979
+ /**
4980
+ * Client version sent to the Codex app server while Promptbook reads subscription limits.
4981
+ *
4982
+ * The app-server protocol only requires a non-empty version string, and the CLI's own version is intentionally not
4983
+ * coupled to Promptbook's package version.
4984
+ */
4985
+ const PROMPTBOOK_CODEX_APP_SERVER_CLIENT_VERSION = '1';
4986
+ /**
4987
+ * Reads the current Codex subscription limit windows through its local app-server protocol.
4988
+ *
4989
+ * Codex versions without this optional protocol, API-key sessions, and transient account failures simply provide no
4990
+ * snapshot. Subscription usage is contextual UI information, so it must never make a coding prompt fail.
4991
+ *
4992
+ * @private internal utility of the OpenAI Codex runner
4993
+ */
4994
+ async function getCodexSubscriptionUsage(codexCommand) {
4995
+ try {
4996
+ return await requestCodexSubscriptionUsage(codexCommand);
4997
+ }
4998
+ catch (_a) {
4999
+ return undefined;
5000
+ }
5001
+ }
5002
+ /**
5003
+ * Performs the small Codex app-server JSON-RPC exchange which reads rate limits.
5004
+ *
5005
+ * The app server requires a completed `initialize` handshake before it accepts account methods. Closing standard input
5006
+ * after the response lets the short-lived helper exit without sharing the lifecycle of the coding process itself.
5007
+ *
5008
+ * @private helper of `getCodexSubscriptionUsage`
5009
+ */
5010
+ function requestCodexSubscriptionUsage(codexCommand) {
5011
+ return new Promise((resolve) => {
5012
+ const codexAppServerProcess = child_process.spawn(codexCommand, CODEX_APP_SERVER_ARGUMENTS, {
5013
+ shell: process.platform === 'win32',
5014
+ stdio: 'pipe',
5015
+ });
5016
+ const outputReader = readline.createInterface({ input: codexAppServerProcess.stdout });
5017
+ let requestTimeout;
5018
+ let isSettled = false;
5019
+ // Draining stderr prevents a protocol diagnostic from blocking the short-lived child process. The response is
5020
+ // deliberately not surfaced because missing usage must not distract from an otherwise healthy coding run.
5021
+ codexAppServerProcess.stderr.resume();
5022
+ codexAppServerProcess.stdin.on('error', () => undefined);
5023
+ /**
5024
+ * Stops the helper process and settles this optional request exactly once.
5025
+ */
5026
+ const settle = (subscriptionUsage) => {
5027
+ if (isSettled) {
5028
+ return;
5029
+ }
5030
+ isSettled = true;
5031
+ if (requestTimeout) {
5032
+ clearTimeout(requestTimeout);
5033
+ }
5034
+ outputReader.close();
5035
+ codexAppServerProcess.stdin.end();
5036
+ if (codexAppServerProcess.exitCode === null && !codexAppServerProcess.killed) {
5037
+ codexAppServerProcess.kill();
5038
+ }
5039
+ resolve(subscriptionUsage);
5040
+ };
5041
+ /**
5042
+ * Sends one JSON-RPC message to the Codex app server.
5043
+ */
5044
+ const sendJsonRpcMessage = (message) => {
5045
+ try {
5046
+ codexAppServerProcess.stdin.write(`${JSON.stringify(message)}\n`);
5047
+ }
5048
+ catch (_a) {
5049
+ settle(undefined);
5050
+ }
5051
+ };
5052
+ requestTimeout = setTimeout(() => settle(undefined), CODEX_SUBSCRIPTION_USAGE_REQUEST_TIMEOUT_MS);
5053
+ codexAppServerProcess.on('error', () => settle(undefined));
5054
+ codexAppServerProcess.on('close', () => settle(undefined));
5055
+ outputReader.on('line', (line) => {
5056
+ const response = parseJsonRecord(line);
5057
+ if (!response) {
5058
+ return;
5059
+ }
5060
+ if (response.id === INITIALIZE_REQUEST_ID) {
5061
+ if (!isJsonRecord(response.result)) {
5062
+ settle(undefined);
5063
+ return;
5064
+ }
5065
+ sendJsonRpcMessage({ jsonrpc: '2.0', method: 'initialized' });
5066
+ sendJsonRpcMessage({
5067
+ jsonrpc: '2.0',
5068
+ id: RATE_LIMITS_REQUEST_ID,
5069
+ method: 'account/rateLimits/read',
5070
+ });
5071
+ return;
5072
+ }
5073
+ if (response.id === RATE_LIMITS_REQUEST_ID) {
5074
+ settle(buildCodexSubscriptionUsage(response.result));
5075
+ }
5076
+ });
5077
+ sendJsonRpcMessage({
5078
+ jsonrpc: '2.0',
5079
+ id: INITIALIZE_REQUEST_ID,
5080
+ method: 'initialize',
5081
+ params: {
5082
+ clientInfo: {
5083
+ name: PROMPTBOOK_CODEX_APP_SERVER_CLIENT_NAME,
5084
+ version: PROMPTBOOK_CODEX_APP_SERVER_CLIENT_VERSION,
5085
+ },
5086
+ capabilities: {
5087
+ experimentalApi: true,
5088
+ },
5089
+ },
5090
+ });
5091
+ });
5092
+ }
5093
+ /**
5094
+ * Converts the raw Codex app-server rate-limit response into Promptbook's harness-neutral subscription snapshot.
5095
+ *
5096
+ * Modern Codex versions can report several metered buckets, while older versions expose a single compatibility
5097
+ * bucket. In both cases every primary and secondary rolling window is preserved for the terminal dashboard.
5098
+ *
5099
+ * @private internal utility of the OpenAI Codex runner
5100
+ */
5101
+ function buildCodexSubscriptionUsage(response) {
5102
+ if (!isJsonRecord(response)) {
5103
+ return undefined;
5104
+ }
5105
+ const snapshots = resolveCodexRateLimitSnapshots(response);
5106
+ const hasMultipleSnapshots = snapshots.length > 1;
5107
+ const limits = snapshots.flatMap(({ identifier, value }) => buildCodexSubscriptionUsageLimits({
5108
+ snapshot: value,
5109
+ identifier,
5110
+ hasMultipleSnapshots,
5111
+ }));
5112
+ return limits.length === 0 ? undefined : { limits };
5113
+ }
5114
+ /**
5115
+ * Resolves either Codex's multi-bucket rate-limit response or its compatible single-bucket fallback.
5116
+ *
5117
+ * @private helper of `buildCodexSubscriptionUsage`
5118
+ */
5119
+ function resolveCodexRateLimitSnapshots(response) {
5120
+ const rateLimitsByLimitId = response.rateLimitsByLimitId;
5121
+ if (isJsonRecord(rateLimitsByLimitId)) {
5122
+ const snapshots = Object.entries(rateLimitsByLimitId)
5123
+ .filter(([, value]) => isJsonRecord(value))
5124
+ .map(([identifier, value]) => ({ identifier, value: value }));
5125
+ if (snapshots.length > 0) {
5126
+ return snapshots;
5127
+ }
5128
+ }
5129
+ return isJsonRecord(response.rateLimits) ? [{ value: response.rateLimits }] : [];
5130
+ }
5131
+ /**
5132
+ * Creates every displayed rolling window from one Codex rate-limit bucket.
5133
+ *
5134
+ * @private helper of `buildCodexSubscriptionUsage`
5135
+ */
5136
+ function buildCodexSubscriptionUsageLimits(options) {
5137
+ var _a;
5138
+ const { snapshot, identifier, hasMultipleSnapshots } = options;
5139
+ const bucketLabel = hasMultipleSnapshots ? (_a = readString(snapshot.limitName)) !== null && _a !== void 0 ? _a : identifier : undefined;
5140
+ return [
5141
+ buildCodexSubscriptionUsageLimit(snapshot.primary, bucketLabel, 'Primary'),
5142
+ buildCodexSubscriptionUsageLimit(snapshot.secondary, bucketLabel, 'Secondary'),
5143
+ ].filter((limit) => limit !== undefined);
5144
+ }
5145
+ /**
5146
+ * Converts one raw Codex rate-limit window to a displayable subscription usage limit.
5147
+ *
5148
+ * @private helper of `buildCodexSubscriptionUsage`
5149
+ */
5150
+ function buildCodexSubscriptionUsageLimit(rawWindow, bucketLabel, fallbackWindowLabel) {
5151
+ var _a;
5152
+ if (!isJsonRecord(rawWindow)) {
5153
+ return undefined;
5154
+ }
5155
+ const usedPercentage = readPercentage(rawWindow.usedPercent);
5156
+ if (usedPercentage === undefined) {
5157
+ return undefined;
5158
+ }
5159
+ const windowLabel = (_a = formatCodexRateLimitWindowDuration(rawWindow.windowDurationMins)) !== null && _a !== void 0 ? _a : fallbackWindowLabel;
5160
+ const label = bucketLabel ? `${bucketLabel} ${windowLabel}` : windowLabel;
5161
+ const resetsAt = readUnixTimestamp(rawWindow.resetsAt);
5162
+ return {
5163
+ label,
5164
+ usedPercentage,
5165
+ ...(resetsAt !== undefined && { resetsAt }),
5166
+ };
5167
+ }
5168
+ /**
5169
+ * Formats the duration of one Codex rolling rate-limit window for compact terminal display.
5170
+ *
5171
+ * @private helper of `buildCodexSubscriptionUsage`
5172
+ */
5173
+ function formatCodexRateLimitWindowDuration(value) {
5174
+ const durationMinutes = readNonNegativeFiniteNumber(value);
5175
+ if (durationMinutes === undefined || durationMinutes === 0) {
5176
+ return undefined;
5177
+ }
5178
+ const MINUTES_PER_HOUR = 60;
5179
+ const MINUTES_PER_DAY = 24 * MINUTES_PER_HOUR;
5180
+ if (durationMinutes % MINUTES_PER_DAY === 0) {
5181
+ return `${durationMinutes / MINUTES_PER_DAY}d`;
5182
+ }
5183
+ if (durationMinutes % MINUTES_PER_HOUR === 0) {
5184
+ return `${durationMinutes / MINUTES_PER_HOUR}h`;
5185
+ }
5186
+ return `${durationMinutes}m`;
5187
+ }
5188
+ /**
5189
+ * Parses one JSON-RPC line when it is an object.
5190
+ *
5191
+ * @private helper of `getCodexSubscriptionUsage`
5192
+ */
5193
+ function parseJsonRecord(line) {
5194
+ try {
5195
+ const value = JSON.parse(line);
5196
+ return isJsonRecord(value) ? value : undefined;
5197
+ }
5198
+ catch (_a) {
5199
+ return undefined;
5200
+ }
5201
+ }
5202
+ /**
5203
+ * Checks whether a value is a JSON object.
5204
+ *
5205
+ * @private helper of `getCodexSubscriptionUsage`
5206
+ */
5207
+ function isJsonRecord(value) {
5208
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
5209
+ }
5210
+ /**
5211
+ * Reads one non-empty string from an untrusted JSON object.
5212
+ *
5213
+ * @private helper of `buildCodexSubscriptionUsage`
5214
+ */
5215
+ function readString(value) {
5216
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
5217
+ }
5218
+ /**
5219
+ * Reads a finite number which cannot be negative.
5220
+ *
5221
+ * @private helper of `buildCodexSubscriptionUsage`
5222
+ */
5223
+ function readNonNegativeFiniteNumber(value) {
5224
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
5225
+ }
5226
+ /**
5227
+ * Reads a valid percentage from the Codex app-server response.
5228
+ *
5229
+ * @private helper of `buildCodexSubscriptionUsage`
5230
+ */
5231
+ function readPercentage(value) {
5232
+ const percentage = readNonNegativeFiniteNumber(value);
5233
+ return percentage !== undefined && percentage <= 100 ? percentage : undefined;
5234
+ }
5235
+ /**
5236
+ * Reads a Unix timestamp in seconds from the Codex app-server response.
5237
+ *
5238
+ * @private helper of `buildCodexSubscriptionUsage`
5239
+ */
5240
+ function readUnixTimestamp(value) {
5241
+ const timestamp = readNonNegativeFiniteNumber(value);
5242
+ return timestamp !== undefined && timestamp > 0 ? timestamp : undefined;
5243
+ }
5244
+
4798
5245
  /**
4799
5246
  * Detects which login method Codex used from the captured CLI output.
4800
5247
  *
@@ -4982,6 +5429,15 @@
4982
5429
  jitterRatio: RATE_LIMIT_BACKOFF_JITTER_RATIO,
4983
5430
  });
4984
5431
  }
5432
+ /**
5433
+ * Reads the current ChatGPT subscription quota snapshot through Codex's local app server.
5434
+ *
5435
+ * API-key sessions and unsupported Codex versions simply return no snapshot, which keeps this optional dashboard
5436
+ * information from affecting the actual prompt execution.
5437
+ */
5438
+ async getSubscriptionUsage() {
5439
+ return await getCodexSubscriptionUsage(this.options.codexCommand);
5440
+ }
4985
5441
  /**
4986
5442
  * Runs the Codex prompt in a temporary script and waits for completion output.
4987
5443
  */