@promptbook/cli 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.
Files changed (30) hide show
  1. package/esm/index.es.js +583 -2
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/scripts/run-codex-prompts/runners/claude-code/ClaudeCodeRunner.d.ts +15 -0
  4. package/esm/scripts/run-codex-prompts/runners/claude-code/parseClaudeCodeOutputEvents.d.ts +3 -0
  5. package/esm/scripts/run-codex-prompts/runners/claude-code/parseClaudeCodeSubscriptionUsage.d.ts +11 -0
  6. package/esm/scripts/run-codex-prompts/runners/openai-codex/OpenAiCodexRunner.d.ts +8 -0
  7. package/esm/scripts/run-codex-prompts/runners/openai-codex/getCodexSubscriptionUsage.d.ts +19 -0
  8. package/esm/scripts/run-codex-prompts/runners/types/HarnessSubscriptionUsage.d.ts +43 -0
  9. package/esm/scripts/run-codex-prompts/ui/CoderRunUiState.d.ts +6 -0
  10. package/esm/scripts/run-codex-prompts/ui/buildCoderRunUiFrame.d.ts +2 -0
  11. package/esm/scripts/run-codex-prompts/ui/buildSubscriptionUsageSessionRows.d.ts +11 -0
  12. package/esm/scripts/run-codex-prompts/ui/refreshCoderRunUiSubscriptionUsage.d.ts +14 -0
  13. package/esm/src/version.d.ts +1 -1
  14. package/package.json +1 -1
  15. package/src/other/templates/getTemplatesPipelineCollection.ts +720 -957
  16. package/src/version.ts +2 -2
  17. package/src/versions.txt +1 -0
  18. package/umd/index.umd.js +582 -1
  19. package/umd/index.umd.js.map +1 -1
  20. package/umd/scripts/run-codex-prompts/runners/claude-code/ClaudeCodeRunner.d.ts +15 -0
  21. package/umd/scripts/run-codex-prompts/runners/claude-code/parseClaudeCodeOutputEvents.d.ts +3 -0
  22. package/umd/scripts/run-codex-prompts/runners/claude-code/parseClaudeCodeSubscriptionUsage.d.ts +11 -0
  23. package/umd/scripts/run-codex-prompts/runners/openai-codex/OpenAiCodexRunner.d.ts +8 -0
  24. package/umd/scripts/run-codex-prompts/runners/openai-codex/getCodexSubscriptionUsage.d.ts +19 -0
  25. package/umd/scripts/run-codex-prompts/runners/types/HarnessSubscriptionUsage.d.ts +43 -0
  26. package/umd/scripts/run-codex-prompts/ui/CoderRunUiState.d.ts +6 -0
  27. package/umd/scripts/run-codex-prompts/ui/buildCoderRunUiFrame.d.ts +2 -0
  28. package/umd/scripts/run-codex-prompts/ui/buildSubscriptionUsageSessionRows.d.ts +11 -0
  29. package/umd/scripts/run-codex-prompts/ui/refreshCoderRunUiSubscriptionUsage.d.ts +14 -0
  30. package/umd/src/version.d.ts +1 -1
package/umd/index.umd.js CHANGED
@@ -58,7 +58,7 @@
58
58
  * @generated
59
59
  * @see https://github.com/webgptorg/promptbook
60
60
  */
61
- const PROMPTBOOK_ENGINE_VERSION = '0.114.0-21';
61
+ const PROMPTBOOK_ENGINE_VERSION = '0.114.0-22';
62
62
  /**
63
63
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
64
64
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -25557,6 +25557,29 @@
25557
25557
  }
25558
25558
  }
25559
25559
 
25560
+ /**
25561
+ * Merges a newly reported subset of subscription windows into the latest complete snapshot.
25562
+ *
25563
+ * Some harnesses emit an update only for the limit whose state changed. Keeping the previous windows means a
25564
+ * five-hour update cannot make a still-valid weekly limit disappear from the dashboard. Existing order is preserved
25565
+ * and newly discovered windows are appended, which keeps the terminal presentation stable between refreshes.
25566
+ *
25567
+ * @private internal utility of `ptbk coder`
25568
+ */
25569
+ function mergeHarnessSubscriptionUsage(previousSubscriptionUsage, latestSubscriptionUsage) {
25570
+ if (previousSubscriptionUsage === undefined) {
25571
+ return latestSubscriptionUsage;
25572
+ }
25573
+ const latestLimitsByLabel = new Map(latestSubscriptionUsage.limits.map((latestLimit) => [latestLimit.label, latestLimit]));
25574
+ const previousLimitLabels = new Set(previousSubscriptionUsage.limits.map((previousLimit) => previousLimit.label));
25575
+ return {
25576
+ limits: [
25577
+ ...previousSubscriptionUsage.limits.map((previousLimit) => { var _a; return (_a = latestLimitsByLabel.get(previousLimit.label)) !== null && _a !== void 0 ? _a : previousLimit; }),
25578
+ ...latestSubscriptionUsage.limits.filter((latestLimit) => !previousLimitLabels.has(latestLimit.label)),
25579
+ ],
25580
+ };
25581
+ }
25582
+
25560
25583
  /**
25561
25584
  * Base delimiter used for passing large prompts through stdin.
25562
25585
  */
@@ -25890,6 +25913,122 @@
25890
25913
  }
25891
25914
  }
25892
25915
 
25916
+ /**
25917
+ * Human-readable labels for known Claude Code rolling subscription-limit windows.
25918
+ */
25919
+ const CLAUDE_CODE_RATE_LIMIT_LABELS = {
25920
+ five_hour: '5h',
25921
+ seven_day: '7d',
25922
+ seven_day_opus: '7d Opus',
25923
+ seven_day_sonnet: '7d Sonnet',
25924
+ overage: 'Overage',
25925
+ };
25926
+ /**
25927
+ * Fallback label used when a newer Claude Code release adds a rate-limit window unknown to Promptbook.
25928
+ */
25929
+ const UNKNOWN_CLAUDE_CODE_RATE_LIMIT_LABEL = 'Limit';
25930
+ /**
25931
+ * Converts Claude Code stream-json rate-limit events into the shared subscription-usage snapshot.
25932
+ *
25933
+ * Claude Code can emit one event for each applicable limit, so the parser preserves every distinct window instead of
25934
+ * assuming the familiar 5-hour and seven-day pair. This lets a new vendor-side limit appear in the dashboard without
25935
+ * changing its renderer.
25936
+ *
25937
+ * @private internal utility of the Claude Code runner
25938
+ */
25939
+ function parseClaudeCodeSubscriptionUsage(output) {
25940
+ const limitsByType = new Map();
25941
+ for (const event of parseClaudeCodeOutputEvents(output)) {
25942
+ const limit = parseClaudeCodeSubscriptionUsageLimit(event);
25943
+ if (limit) {
25944
+ limitsByType.set(resolveClaudeCodeRateLimitType(event), limit);
25945
+ }
25946
+ }
25947
+ const limits = [...limitsByType.values()];
25948
+ return limits.length === 0 ? undefined : { limits };
25949
+ }
25950
+ /**
25951
+ * Parses one Claude Code stream event when it contains a usable subscription-limit update.
25952
+ *
25953
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
25954
+ */
25955
+ function parseClaudeCodeSubscriptionUsageLimit(event) {
25956
+ if (event.type !== 'rate_limit_event' || !event.rate_limit_info) {
25957
+ return undefined;
25958
+ }
25959
+ const rateLimitType = resolveClaudeCodeRateLimitType(event);
25960
+ const usedPercentage = resolveClaudeCodeUsedPercentage(event.rate_limit_info);
25961
+ if (usedPercentage === undefined) {
25962
+ return undefined;
25963
+ }
25964
+ const resetsAt = resolveClaudeCodeResetTimestamp(event.rate_limit_info);
25965
+ return {
25966
+ label: formatClaudeCodeRateLimitTypeLabel(rateLimitType),
25967
+ usedPercentage,
25968
+ ...(resetsAt !== undefined && { resetsAt }),
25969
+ };
25970
+ }
25971
+ /**
25972
+ * Formats known and newly introduced Claude Code rate-limit types for a stable terminal label.
25973
+ *
25974
+ * A newer limit type remains distinct in the dashboard instead of making several unrelated windows all appear as
25975
+ * a generic `Limit` row.
25976
+ *
25977
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
25978
+ */
25979
+ function formatClaudeCodeRateLimitTypeLabel(rateLimitType) {
25980
+ const knownLabel = CLAUDE_CODE_RATE_LIMIT_LABELS[rateLimitType];
25981
+ if (knownLabel) {
25982
+ return knownLabel;
25983
+ }
25984
+ const words = rateLimitType.split(/[\s_-]+/u).filter(Boolean);
25985
+ if (words.length === 0) {
25986
+ return UNKNOWN_CLAUDE_CODE_RATE_LIMIT_LABEL;
25987
+ }
25988
+ return words.map((word) => `${word.slice(0, 1).toUpperCase()}${word.slice(1)}`).join(' ');
25989
+ }
25990
+ /**
25991
+ * Resolves the stable rate-limit type key emitted by Claude Code across camel- and snake-case payload versions.
25992
+ *
25993
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
25994
+ */
25995
+ function resolveClaudeCodeRateLimitType(event) {
25996
+ var _a;
25997
+ const rateLimitInfo = event.rate_limit_info;
25998
+ 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;
25999
+ return typeof rateLimitType === 'string' && rateLimitType.trim() !== ''
26000
+ ? rateLimitType.trim()
26001
+ : UNKNOWN_CLAUDE_CODE_RATE_LIMIT_LABEL;
26002
+ }
26003
+ /**
26004
+ * Converts Claude's fractional utilization value to a displayed percentage.
26005
+ *
26006
+ * A rejected limit event may omit utilization, but it still conveys a precise zero-remaining state and is therefore
26007
+ * rendered as 100 percent consumed.
26008
+ *
26009
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
26010
+ */
26011
+ function resolveClaudeCodeUsedPercentage(rateLimitInfo) {
26012
+ const utilization = rateLimitInfo.utilization;
26013
+ if (typeof utilization === 'number' && Number.isFinite(utilization)) {
26014
+ const usedPercentage = utilization <= 1 ? utilization * 100 : utilization;
26015
+ if (usedPercentage >= 0 && usedPercentage <= 100) {
26016
+ return usedPercentage;
26017
+ }
26018
+ }
26019
+ return rateLimitInfo.status === 'rejected' ? 100 : undefined;
26020
+ }
26021
+ /**
26022
+ * Reads Claude's optional Unix reset timestamp from either current or earlier stream payload naming.
26023
+ *
26024
+ * @private helper of `parseClaudeCodeSubscriptionUsage`
26025
+ */
26026
+ function resolveClaudeCodeResetTimestamp(rateLimitInfo) {
26027
+ var _a;
26028
+ const resetsAt = (_a = rateLimitInfo.resetsAt) !== null && _a !== void 0 ? _a : rateLimitInfo.resets_at;
26029
+ return typeof resetsAt === 'number' && Number.isFinite(resetsAt) && resetsAt > 0 ? resetsAt : undefined;
26030
+ }
26031
+
25893
26032
  /**
25894
26033
  * Polling interval used while waiting for Claude Code session limits to reset.
25895
26034
  */
@@ -25905,6 +26044,14 @@
25905
26044
  this.options = options;
25906
26045
  this.name = 'claude-code';
25907
26046
  }
26047
+ /**
26048
+ * Returns the latest subscription-limit snapshot emitted by this Claude Code session.
26049
+ *
26050
+ * Claude exposes these values in the normal stream after a response, so no separate quota-only model call is made.
26051
+ */
26052
+ async getSubscriptionUsage() {
26053
+ return this.subscriptionUsage;
26054
+ }
25908
26055
  /**
25909
26056
  * Runs the prompt using Claude Code and parses usage output.
25910
26057
  */
@@ -25918,6 +26065,7 @@
25918
26065
  prompt,
25919
26066
  resumeSessionId,
25920
26067
  }).catch(async (error) => {
26068
+ this.updateSubscriptionUsage(error instanceof Error ? error.message : String(error));
25921
26069
  const sessionLimit = extractClaudeCodeSessionLimitFromError(error);
25922
26070
  if (!sessionLimit) {
25923
26071
  throw error;
@@ -25932,6 +26080,7 @@
25932
26080
  continue;
25933
26081
  }
25934
26082
  const sessionLimit = extractClaudeCodeSessionLimitFromOutput(output);
26083
+ this.updateSubscriptionUsage(output);
25935
26084
  if (sessionLimit) {
25936
26085
  resurrectionCount++;
25937
26086
  await waitForClaudeCodeSessionLimitReset(sessionLimit, resurrectionCount, options);
@@ -25961,6 +26110,18 @@
25961
26110
  preserveArtifactsOnSuccess: options.preserveArtifactsOnSuccess,
25962
26111
  });
25963
26112
  }
26113
+ /**
26114
+ * Keeps the newest usable Claude subscription-limit values reported by the stream.
26115
+ *
26116
+ * A stream can omit these values for API-key users or unsupported plan types; retaining the prior snapshot avoids
26117
+ * a temporary omission erasing a still-valid dashboard value while a long queue is running.
26118
+ */
26119
+ updateSubscriptionUsage(output) {
26120
+ const subscriptionUsage = parseClaudeCodeSubscriptionUsage(output);
26121
+ if (subscriptionUsage) {
26122
+ this.subscriptionUsage = mergeHarnessSubscriptionUsage(this.subscriptionUsage, subscriptionUsage);
26123
+ }
26124
+ }
25964
26125
  }
25965
26126
  /**
25966
26127
  * Waits until the Claude Code session can be resumed, keeping terminal status clear.
@@ -26868,6 +27029,292 @@
26868
27029
  return (_c = OPENAI_MODELS.find((model) => model.modelName === CODEX_FALLBACK_PRICING_MODEL)) === null || _c === void 0 ? void 0 : _c.pricing;
26869
27030
  }
26870
27031
 
27032
+ /**
27033
+ * Arguments which start the Codex app server over JSON-RPC stdio.
27034
+ */
27035
+ const CODEX_APP_SERVER_ARGUMENTS = ['app-server', '--stdio'];
27036
+ /**
27037
+ * Maximum time spent waiting for the optional Codex account-rate-limit snapshot.
27038
+ */
27039
+ const CODEX_SUBSCRIPTION_USAGE_REQUEST_TIMEOUT_MS = 10 * 1000;
27040
+ /**
27041
+ * JSON-RPC request id used for the required app-server initialization handshake.
27042
+ */
27043
+ const INITIALIZE_REQUEST_ID = 1;
27044
+ /**
27045
+ * JSON-RPC request id used for the Codex account rate-limit snapshot.
27046
+ */
27047
+ const RATE_LIMITS_REQUEST_ID = 2;
27048
+ /**
27049
+ * Client name sent to the Codex app server while Promptbook reads subscription limits.
27050
+ */
27051
+ const PROMPTBOOK_CODEX_APP_SERVER_CLIENT_NAME = 'ptbk-coder';
27052
+ /**
27053
+ * Client version sent to the Codex app server while Promptbook reads subscription limits.
27054
+ *
27055
+ * The app-server protocol only requires a non-empty version string, and the CLI's own version is intentionally not
27056
+ * coupled to Promptbook's package version.
27057
+ */
27058
+ const PROMPTBOOK_CODEX_APP_SERVER_CLIENT_VERSION = '1';
27059
+ /**
27060
+ * Reads the current Codex subscription limit windows through its local app-server protocol.
27061
+ *
27062
+ * Codex versions without this optional protocol, API-key sessions, and transient account failures simply provide no
27063
+ * snapshot. Subscription usage is contextual UI information, so it must never make a coding prompt fail.
27064
+ *
27065
+ * @private internal utility of the OpenAI Codex runner
27066
+ */
27067
+ async function getCodexSubscriptionUsage(codexCommand) {
27068
+ try {
27069
+ return await requestCodexSubscriptionUsage(codexCommand);
27070
+ }
27071
+ catch (_a) {
27072
+ return undefined;
27073
+ }
27074
+ }
27075
+ /**
27076
+ * Performs the small Codex app-server JSON-RPC exchange which reads rate limits.
27077
+ *
27078
+ * The app server requires a completed `initialize` handshake before it accepts account methods. Closing standard input
27079
+ * after the response lets the short-lived helper exit without sharing the lifecycle of the coding process itself.
27080
+ *
27081
+ * @private helper of `getCodexSubscriptionUsage`
27082
+ */
27083
+ function requestCodexSubscriptionUsage(codexCommand) {
27084
+ return new Promise((resolve) => {
27085
+ const codexAppServerProcess = child_process.spawn(codexCommand, CODEX_APP_SERVER_ARGUMENTS, {
27086
+ shell: process.platform === 'win32',
27087
+ stdio: 'pipe',
27088
+ });
27089
+ const outputReader = readline.createInterface({ input: codexAppServerProcess.stdout });
27090
+ let requestTimeout;
27091
+ let isSettled = false;
27092
+ // Draining stderr prevents a protocol diagnostic from blocking the short-lived child process. The response is
27093
+ // deliberately not surfaced because missing usage must not distract from an otherwise healthy coding run.
27094
+ codexAppServerProcess.stderr.resume();
27095
+ codexAppServerProcess.stdin.on('error', () => undefined);
27096
+ /**
27097
+ * Stops the helper process and settles this optional request exactly once.
27098
+ */
27099
+ const settle = (subscriptionUsage) => {
27100
+ if (isSettled) {
27101
+ return;
27102
+ }
27103
+ isSettled = true;
27104
+ if (requestTimeout) {
27105
+ clearTimeout(requestTimeout);
27106
+ }
27107
+ outputReader.close();
27108
+ codexAppServerProcess.stdin.end();
27109
+ if (codexAppServerProcess.exitCode === null && !codexAppServerProcess.killed) {
27110
+ codexAppServerProcess.kill();
27111
+ }
27112
+ resolve(subscriptionUsage);
27113
+ };
27114
+ /**
27115
+ * Sends one JSON-RPC message to the Codex app server.
27116
+ */
27117
+ const sendJsonRpcMessage = (message) => {
27118
+ try {
27119
+ codexAppServerProcess.stdin.write(`${JSON.stringify(message)}\n`);
27120
+ }
27121
+ catch (_a) {
27122
+ settle(undefined);
27123
+ }
27124
+ };
27125
+ requestTimeout = setTimeout(() => settle(undefined), CODEX_SUBSCRIPTION_USAGE_REQUEST_TIMEOUT_MS);
27126
+ codexAppServerProcess.on('error', () => settle(undefined));
27127
+ codexAppServerProcess.on('close', () => settle(undefined));
27128
+ outputReader.on('line', (line) => {
27129
+ const response = parseJsonRecord(line);
27130
+ if (!response) {
27131
+ return;
27132
+ }
27133
+ if (response.id === INITIALIZE_REQUEST_ID) {
27134
+ if (!isJsonRecord(response.result)) {
27135
+ settle(undefined);
27136
+ return;
27137
+ }
27138
+ sendJsonRpcMessage({ jsonrpc: '2.0', method: 'initialized' });
27139
+ sendJsonRpcMessage({
27140
+ jsonrpc: '2.0',
27141
+ id: RATE_LIMITS_REQUEST_ID,
27142
+ method: 'account/rateLimits/read',
27143
+ });
27144
+ return;
27145
+ }
27146
+ if (response.id === RATE_LIMITS_REQUEST_ID) {
27147
+ settle(buildCodexSubscriptionUsage(response.result));
27148
+ }
27149
+ });
27150
+ sendJsonRpcMessage({
27151
+ jsonrpc: '2.0',
27152
+ id: INITIALIZE_REQUEST_ID,
27153
+ method: 'initialize',
27154
+ params: {
27155
+ clientInfo: {
27156
+ name: PROMPTBOOK_CODEX_APP_SERVER_CLIENT_NAME,
27157
+ version: PROMPTBOOK_CODEX_APP_SERVER_CLIENT_VERSION,
27158
+ },
27159
+ capabilities: {
27160
+ experimentalApi: true,
27161
+ },
27162
+ },
27163
+ });
27164
+ });
27165
+ }
27166
+ /**
27167
+ * Converts the raw Codex app-server rate-limit response into Promptbook's harness-neutral subscription snapshot.
27168
+ *
27169
+ * Modern Codex versions can report several metered buckets, while older versions expose a single compatibility
27170
+ * bucket. In both cases every primary and secondary rolling window is preserved for the terminal dashboard.
27171
+ *
27172
+ * @private internal utility of the OpenAI Codex runner
27173
+ */
27174
+ function buildCodexSubscriptionUsage(response) {
27175
+ if (!isJsonRecord(response)) {
27176
+ return undefined;
27177
+ }
27178
+ const snapshots = resolveCodexRateLimitSnapshots(response);
27179
+ const hasMultipleSnapshots = snapshots.length > 1;
27180
+ const limits = snapshots.flatMap(({ identifier, value }) => buildCodexSubscriptionUsageLimits({
27181
+ snapshot: value,
27182
+ identifier,
27183
+ hasMultipleSnapshots,
27184
+ }));
27185
+ return limits.length === 0 ? undefined : { limits };
27186
+ }
27187
+ /**
27188
+ * Resolves either Codex's multi-bucket rate-limit response or its compatible single-bucket fallback.
27189
+ *
27190
+ * @private helper of `buildCodexSubscriptionUsage`
27191
+ */
27192
+ function resolveCodexRateLimitSnapshots(response) {
27193
+ const rateLimitsByLimitId = response.rateLimitsByLimitId;
27194
+ if (isJsonRecord(rateLimitsByLimitId)) {
27195
+ const snapshots = Object.entries(rateLimitsByLimitId)
27196
+ .filter(([, value]) => isJsonRecord(value))
27197
+ .map(([identifier, value]) => ({ identifier, value: value }));
27198
+ if (snapshots.length > 0) {
27199
+ return snapshots;
27200
+ }
27201
+ }
27202
+ return isJsonRecord(response.rateLimits) ? [{ value: response.rateLimits }] : [];
27203
+ }
27204
+ /**
27205
+ * Creates every displayed rolling window from one Codex rate-limit bucket.
27206
+ *
27207
+ * @private helper of `buildCodexSubscriptionUsage`
27208
+ */
27209
+ function buildCodexSubscriptionUsageLimits(options) {
27210
+ var _a;
27211
+ const { snapshot, identifier, hasMultipleSnapshots } = options;
27212
+ const bucketLabel = hasMultipleSnapshots ? (_a = readString(snapshot.limitName)) !== null && _a !== void 0 ? _a : identifier : undefined;
27213
+ return [
27214
+ buildCodexSubscriptionUsageLimit(snapshot.primary, bucketLabel, 'Primary'),
27215
+ buildCodexSubscriptionUsageLimit(snapshot.secondary, bucketLabel, 'Secondary'),
27216
+ ].filter((limit) => limit !== undefined);
27217
+ }
27218
+ /**
27219
+ * Converts one raw Codex rate-limit window to a displayable subscription usage limit.
27220
+ *
27221
+ * @private helper of `buildCodexSubscriptionUsage`
27222
+ */
27223
+ function buildCodexSubscriptionUsageLimit(rawWindow, bucketLabel, fallbackWindowLabel) {
27224
+ var _a;
27225
+ if (!isJsonRecord(rawWindow)) {
27226
+ return undefined;
27227
+ }
27228
+ const usedPercentage = readPercentage(rawWindow.usedPercent);
27229
+ if (usedPercentage === undefined) {
27230
+ return undefined;
27231
+ }
27232
+ const windowLabel = (_a = formatCodexRateLimitWindowDuration(rawWindow.windowDurationMins)) !== null && _a !== void 0 ? _a : fallbackWindowLabel;
27233
+ const label = bucketLabel ? `${bucketLabel} ${windowLabel}` : windowLabel;
27234
+ const resetsAt = readUnixTimestamp(rawWindow.resetsAt);
27235
+ return {
27236
+ label,
27237
+ usedPercentage,
27238
+ ...(resetsAt !== undefined && { resetsAt }),
27239
+ };
27240
+ }
27241
+ /**
27242
+ * Formats the duration of one Codex rolling rate-limit window for compact terminal display.
27243
+ *
27244
+ * @private helper of `buildCodexSubscriptionUsage`
27245
+ */
27246
+ function formatCodexRateLimitWindowDuration(value) {
27247
+ const durationMinutes = readNonNegativeFiniteNumber(value);
27248
+ if (durationMinutes === undefined || durationMinutes === 0) {
27249
+ return undefined;
27250
+ }
27251
+ const MINUTES_PER_HOUR = 60;
27252
+ const MINUTES_PER_DAY = 24 * MINUTES_PER_HOUR;
27253
+ if (durationMinutes % MINUTES_PER_DAY === 0) {
27254
+ return `${durationMinutes / MINUTES_PER_DAY}d`;
27255
+ }
27256
+ if (durationMinutes % MINUTES_PER_HOUR === 0) {
27257
+ return `${durationMinutes / MINUTES_PER_HOUR}h`;
27258
+ }
27259
+ return `${durationMinutes}m`;
27260
+ }
27261
+ /**
27262
+ * Parses one JSON-RPC line when it is an object.
27263
+ *
27264
+ * @private helper of `getCodexSubscriptionUsage`
27265
+ */
27266
+ function parseJsonRecord(line) {
27267
+ try {
27268
+ const value = JSON.parse(line);
27269
+ return isJsonRecord(value) ? value : undefined;
27270
+ }
27271
+ catch (_a) {
27272
+ return undefined;
27273
+ }
27274
+ }
27275
+ /**
27276
+ * Checks whether a value is a JSON object.
27277
+ *
27278
+ * @private helper of `getCodexSubscriptionUsage`
27279
+ */
27280
+ function isJsonRecord(value) {
27281
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
27282
+ }
27283
+ /**
27284
+ * Reads one non-empty string from an untrusted JSON object.
27285
+ *
27286
+ * @private helper of `buildCodexSubscriptionUsage`
27287
+ */
27288
+ function readString(value) {
27289
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
27290
+ }
27291
+ /**
27292
+ * Reads a finite number which cannot be negative.
27293
+ *
27294
+ * @private helper of `buildCodexSubscriptionUsage`
27295
+ */
27296
+ function readNonNegativeFiniteNumber(value) {
27297
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
27298
+ }
27299
+ /**
27300
+ * Reads a valid percentage from the Codex app-server response.
27301
+ *
27302
+ * @private helper of `buildCodexSubscriptionUsage`
27303
+ */
27304
+ function readPercentage(value) {
27305
+ const percentage = readNonNegativeFiniteNumber(value);
27306
+ return percentage !== undefined && percentage <= 100 ? percentage : undefined;
27307
+ }
27308
+ /**
27309
+ * Reads a Unix timestamp in seconds from the Codex app-server response.
27310
+ *
27311
+ * @private helper of `buildCodexSubscriptionUsage`
27312
+ */
27313
+ function readUnixTimestamp(value) {
27314
+ const timestamp = readNonNegativeFiniteNumber(value);
27315
+ return timestamp !== undefined && timestamp > 0 ? timestamp : undefined;
27316
+ }
27317
+
26871
27318
  /**
26872
27319
  * Detects which login method Codex used from the captured CLI output.
26873
27320
  *
@@ -27055,6 +27502,15 @@
27055
27502
  jitterRatio: RATE_LIMIT_BACKOFF_JITTER_RATIO,
27056
27503
  });
27057
27504
  }
27505
+ /**
27506
+ * Reads the current ChatGPT subscription quota snapshot through Codex's local app server.
27507
+ *
27508
+ * API-key sessions and unsupported Codex versions simply return no snapshot, which keeps this optional dashboard
27509
+ * information from affecting the actual prompt execution.
27510
+ */
27511
+ async getSubscriptionUsage() {
27512
+ return await getCodexSubscriptionUsage(this.options.codexCommand);
27513
+ }
27058
27514
  /**
27059
27515
  * Runs the Codex prompt in a temporary script and waits for completion output.
27060
27516
  */
@@ -27634,6 +28090,90 @@
27634
28090
  }
27635
28091
  // Note: [🟡] Code for priority filtering [priorityFilter](scripts/run-codex-prompts/prompts/priorityFilter.ts) should never be published outside of `@promptbook/cli`
27636
28092
 
28093
+ /**
28094
+ * Label shown on the first subscription-usage row in the terminal Session box.
28095
+ */
28096
+ const SUBSCRIPTION_USAGE_SESSION_LABEL = 'Usage';
28097
+ /**
28098
+ * Number of milliseconds in one calendar-free day used for compact reset countdowns.
28099
+ */
28100
+ const ONE_DAY_MS = 24 * 60 * 60 * 1000;
28101
+ /**
28102
+ * Builds every available subscription-limit row for the terminal Session box.
28103
+ *
28104
+ * The first row carries the `Usage` label and subsequent rows stay aligned beneath it, allowing a harness to report
28105
+ * any number of windows instead of making the dashboard assume a fixed 5-hour/weekly pair.
28106
+ *
28107
+ * @private internal utility of coder run UI
28108
+ */
28109
+ function buildSubscriptionUsageSessionRows(subscriptionUsage, currentTimeMs = Date.now()) {
28110
+ if (!subscriptionUsage || subscriptionUsage.limits.length === 0) {
28111
+ return [];
28112
+ }
28113
+ return subscriptionUsage.limits.map((limit, index) => ({
28114
+ label: index === 0 ? SUBSCRIPTION_USAGE_SESSION_LABEL : '',
28115
+ value: formatSubscriptionUsageLimit(limit, currentTimeMs),
28116
+ }));
28117
+ }
28118
+ /**
28119
+ * Formats one remaining subscription limit and its optional reset time for the terminal dashboard.
28120
+ *
28121
+ * @private helper of `buildSubscriptionUsageSessionRows`
28122
+ */
28123
+ function formatSubscriptionUsageLimit(limit, currentTimeMs) {
28124
+ const remainingPercentage = Math.round(Math.max(0, Math.min(100, 100 - limit.usedPercentage)));
28125
+ const remainingPercentageColor = resolveRemainingPercentageColor(remainingPercentage);
28126
+ const resetText = formatSubscriptionUsageReset(limit.resetsAt, currentTimeMs);
28127
+ const label = limit.label.trim() || SUBSCRIPTION_USAGE_SESSION_LABEL;
28128
+ return [
28129
+ colors__default["default"].bold(label),
28130
+ remainingPercentageColor(`${remainingPercentage}% remaining`),
28131
+ ...(resetText ? [colors__default["default"].gray(resetText)] : []),
28132
+ ].join(' · ');
28133
+ }
28134
+ /**
28135
+ * Chooses an attention color for the remaining subscription percentage.
28136
+ *
28137
+ * @private helper of `buildSubscriptionUsageSessionRows`
28138
+ */
28139
+ function resolveRemainingPercentageColor(remainingPercentage) {
28140
+ if (remainingPercentage === 0) {
28141
+ return colors__default["default"].red;
28142
+ }
28143
+ if (remainingPercentage <= 20) {
28144
+ return colors__default["default"].yellow;
28145
+ }
28146
+ return colors__default["default"].green;
28147
+ }
28148
+ /**
28149
+ * Formats the optional future reset timestamp of one subscription limit.
28150
+ *
28151
+ * @private helper of `buildSubscriptionUsageSessionRows`
28152
+ */
28153
+ function formatSubscriptionUsageReset(resetsAt, currentTimeMs) {
28154
+ if (resetsAt === undefined) {
28155
+ return undefined;
28156
+ }
28157
+ const remainingDurationMs = resetsAt * 1000 - currentTimeMs;
28158
+ if (remainingDurationMs <= 0) {
28159
+ return 'resets now';
28160
+ }
28161
+ return `resets in ${formatSubscriptionUsageDuration(remainingDurationMs)}`;
28162
+ }
28163
+ /**
28164
+ * Formats a reset countdown with days when a weekly-style limit is still several days away.
28165
+ *
28166
+ * @private helper of `buildSubscriptionUsageSessionRows`
28167
+ */
28168
+ function formatSubscriptionUsageDuration(durationMs) {
28169
+ const dayCount = Math.floor(durationMs / ONE_DAY_MS);
28170
+ if (dayCount === 0) {
28171
+ return formatDurationMs(durationMs);
28172
+ }
28173
+ const remainingDurationMs = durationMs - dayCount * ONE_DAY_MS;
28174
+ return remainingDurationMs === 0 ? `${dayCount}d` : `${dayCount}d ${formatDurationMs(remainingDurationMs)}`;
28175
+ }
28176
+
27637
28177
  /**
27638
28178
  * Minimum width used for the rich coder-run frame.
27639
28179
  */
@@ -27739,6 +28279,7 @@
27739
28279
  value: runnerParts.join(' · '),
27740
28280
  },
27741
28281
  ...configurationRows,
28282
+ ...buildSubscriptionUsageSessionRows(options.subscriptionUsage),
27742
28283
  ...buildScriptPathSessionRows(options.currentScriptPaths || [], bodyWidth),
27743
28284
  {
27744
28285
  label: 'This run',
@@ -28284,6 +28825,13 @@
28284
28825
  this.agentStatusTableRows = [...agentStatusTableRows];
28285
28826
  this.emitChange();
28286
28827
  }
28828
+ /**
28829
+ * Replaces the optional harness subscription usage shown in the Session box.
28830
+ */
28831
+ setSubscriptionUsage(subscriptionUsage) {
28832
+ this.subscriptionUsage = subscriptionUsage;
28833
+ this.emitChange();
28834
+ }
28287
28835
  /**
28288
28836
  * Sets or clears the Enter-key action label shown in the controls panel.
28289
28837
  */
@@ -29275,6 +29823,7 @@
29275
29823
  pauseTargetLabel: getPauseTargetLabel(),
29276
29824
  isEndAfterCurrentPromptRequested: getEndAfterCurrentPromptState(),
29277
29825
  config: state.config,
29826
+ subscriptionUsage: state.subscriptionUsage,
29278
29827
  agentVisual: state.agentVisual,
29279
29828
  phase: state.phase,
29280
29829
  currentPromptLabel: state.currentPromptLabel,
@@ -76420,6 +76969,30 @@
76420
76969
  await promises.writeFile(file.path, content, 'utf-8');
76421
76970
  }
76422
76971
 
76972
+ /**
76973
+ * Refreshes optional harness subscription usage in the shared coder-run UI state.
76974
+ *
76975
+ * Subscription visibility is an enhancement, not a prerequisite for running prompts. A harness which cannot expose a
76976
+ * snapshot, or whose account endpoint is temporarily unavailable, therefore leaves the existing dashboard unchanged.
76977
+ *
76978
+ * @private internal utility of coder run UI
76979
+ */
76980
+ async function refreshCoderRunUiSubscriptionUsage(options) {
76981
+ const { runner, uiState } = options;
76982
+ if (!uiState || !runner.getSubscriptionUsage) {
76983
+ return;
76984
+ }
76985
+ try {
76986
+ const subscriptionUsage = await runner.getSubscriptionUsage();
76987
+ if (subscriptionUsage) {
76988
+ uiState.setSubscriptionUsage(subscriptionUsage);
76989
+ }
76990
+ }
76991
+ catch (_a) {
76992
+ // A current subscription snapshot must never interrupt the coding queue.
76993
+ }
76994
+ }
76995
+
76423
76996
  /**
76424
76997
  * Maximum number of retry attempts performed after a prompt round throws an error.
76425
76998
  * After this many retries the round is finalized as failed.
@@ -76497,6 +77070,10 @@
76497
77070
  }),
76498
77071
  waitForPauseCheckpoint: waitForRequestedPause,
76499
77072
  });
77073
+ await refreshCoderRunUiSubscriptionUsage({
77074
+ runner,
77075
+ uiState: uiHandle === null || uiHandle === void 0 ? void 0 : uiHandle.state,
77076
+ });
76500
77077
  await finalizeSuccessfulPromptRound({
76501
77078
  options,
76502
77079
  nextPrompt,
@@ -77737,6 +78314,10 @@
77737
78314
  console.info(colors__default["default"].green(`Running prompts with ${runner.name}`));
77738
78315
  initializeRunUi(uiHandle, runner.name, actualRunnerModel, options);
77739
78316
  await initializeRunUiAgentVisual(uiHandle, resolvedCoderAgent === null || resolvedCoderAgent === void 0 ? void 0 : resolvedCoderAgent.agentSource);
78317
+ await refreshCoderRunUiSubscriptionUsage({
78318
+ runner,
78319
+ uiState: uiHandle === null || uiHandle === void 0 ? void 0 : uiHandle.state,
78320
+ });
77740
78321
  await seedCachedAveragePromptDuration({
77741
78322
  options,
77742
78323
  actualRunnerModel,