johns-harness 2026.10.21 → 2026.10.23

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 (73) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +3 -0
  3. package/dist/anthropic-auth-runtime.js +62 -0
  4. package/dist/auth-profiles-5CHn7vq1.js +9 -4
  5. package/dist/compact-B247y5Qt.js +41 -74
  6. package/dist/config-koj5M_EO.js +4 -2
  7. package/dist/daemon-cli.js +4 -2
  8. package/dist/model-selection-BGlGpPgM.js +9 -4
  9. package/dist/model-selection-BU6wl1le.js +9 -4
  10. package/dist/model-selection-L7RMwsG-.js +9 -4
  11. package/dist/pi-embedded-C6ITuRXf.js +42 -89
  12. package/dist/pi-embedded-DoQsYfIY.js +42 -89
  13. package/dist/plugin-sdk/bluebubbles.js +2 -1
  14. package/dist/plugin-sdk/config/types.models.d.ts +1 -0
  15. package/dist/plugin-sdk/config/zod-schema.core.d.ts +3 -0
  16. package/dist/plugin-sdk/config/zod-schema.d.ts +1 -0
  17. package/dist/plugin-sdk/config-4Fgm-yEH.js +9 -4
  18. package/dist/plugin-sdk/config-Di-lyCdh.js +9 -4
  19. package/dist/plugin-sdk/discord.js +4 -2
  20. package/dist/plugin-sdk/dispatch-BP0viZiL.js +42 -89
  21. package/dist/plugin-sdk/dispatch-CQsjmw7g.js +42 -89
  22. package/dist/plugin-sdk/dispatch-Cerq29sy.js +42 -89
  23. package/dist/plugin-sdk/dispatch-Cndjtt0g.js +42 -89
  24. package/dist/plugin-sdk/dispatch-UogiJYul.js +42 -89
  25. package/dist/plugin-sdk/feishu.js +2 -1
  26. package/dist/plugin-sdk/googlechat.js +2 -1
  27. package/dist/plugin-sdk/imessage.js +2 -1
  28. package/dist/plugin-sdk/model-auth-CX9cPHdC.js +9 -4
  29. package/dist/plugin-sdk/model-auth-Ciehz0x5.js +9 -4
  30. package/dist/plugin-sdk/model-auth-DVyo6JSX.js +9 -4
  31. package/dist/plugin-sdk/model-auth-kiHYHGrs.js +9 -4
  32. package/dist/plugin-sdk/model-selection-Dbj4jDYM.js +8 -3
  33. package/dist/plugin-sdk/nostr.js +2 -1
  34. package/dist/plugin-sdk/reply-DbZnH8-h.js +42 -89
  35. package/dist/plugin-sdk/signal.js +2 -1
  36. package/dist/plugin-sdk/slack.js +2 -1
  37. package/dist/plugin-sdk/telegram.js +2 -1
  38. package/dist/plugin-sdk/tlon.js +2 -1
  39. package/dist/plugin-sdk/twitch.js +2 -1
  40. package/dist/plugin-sdk/utils/usage-format.d.ts +1 -0
  41. package/dist/plugin-sdk/voice-call.js +2 -1
  42. package/dist/plugin-sdk/zalo.js +2 -1
  43. package/dist/plugin-sdk/zalouser.js +2 -1
  44. package/dist/reply-C5LKjXcC.js +41 -74
  45. package/dist/session-cost-usage-5CCZbVhO.js +4 -19
  46. package/dist/session-cost-usage-CkCo2kVx.js +4 -19
  47. package/dist/usage-billing.js +88 -0
  48. package/dist/usage-format-CNGi1eHQ.js +6 -11
  49. package/dist/usage-format-CvaU1ntA.js +6 -11
  50. package/docs/PATCHES.md +54 -1
  51. package/docs/providers/anthropic.md +23 -2
  52. package/docs/reference/token-use.md +11 -1
  53. package/models/models.json +33 -33
  54. package/node_modules/@mariozechner/pi-ai/dist/models.d.ts +1 -0
  55. package/node_modules/@mariozechner/pi-ai/dist/models.generated.js +32 -32
  56. package/node_modules/@mariozechner/pi-ai/dist/models.js +16 -5
  57. package/node_modules/@mariozechner/pi-ai/dist/providers/anthropic.js +15 -0
  58. package/node_modules/@mariozechner/pi-ai/dist/providers/google-vertex.js +1 -1
  59. package/node_modules/@mariozechner/pi-ai/dist/providers/google.js +1 -1
  60. package/node_modules/@mariozechner/pi-ai/dist/providers/openai-completions.js +5 -5
  61. package/node_modules/@mariozechner/pi-ai/dist/types.d.ts +3 -0
  62. package/node_modules/@mariozechner/pi-coding-agent/dist/core/model-registry.js +3 -0
  63. package/package.json +1 -1
  64. package/scripts/models-sync.mjs +1 -0
  65. package/vendor/patched-deps/@mariozechner/pi-ai/dist/models.d.ts +25 -0
  66. package/vendor/patched-deps/@mariozechner/pi-ai/dist/models.generated.js +32 -32
  67. package/vendor/patched-deps/@mariozechner/pi-ai/dist/models.js +16 -5
  68. package/vendor/patched-deps/@mariozechner/pi-ai/dist/providers/anthropic.js +15 -0
  69. package/vendor/patched-deps/@mariozechner/pi-ai/dist/providers/google-vertex.js +371 -0
  70. package/vendor/patched-deps/@mariozechner/pi-ai/dist/providers/google.js +1 -1
  71. package/vendor/patched-deps/@mariozechner/pi-ai/dist/providers/openai-completions.js +5 -5
  72. package/vendor/patched-deps/@mariozechner/pi-ai/dist/types.d.ts +282 -0
  73. package/vendor/patched-deps/@mariozechner/pi-coding-agent/dist/core/model-registry.js +3 -0
@@ -1,3 +1,5 @@
1
+ import { createSubscriptionAuthTracker, formatAuthProfileFallback } from "./anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { normalizeBillingUsage, readLatestBillingUsage, formatBillingCost } from "./usage-billing.js"; // JOHNNESS_PATCH_USAGE_BILLING_91 dist/pi-embedded-C6ITuRXf.js
1
3
  import { importOptional66 } from "./optional-module.js";
2
4
  const JOHNNESS_PATCH_SLIM_TREE_66 = true;
3
5
  import { createImageGenerateTool } from "./image-generate.js";
@@ -24991,21 +24993,7 @@ function hasNonzeroUsage(usage) {
24991
24993
  ].some((v) => typeof v === "number" && Number.isFinite(v) && v > 0);
24992
24994
  }
24993
24995
  function normalizeUsage(raw) {
24994
- if (!raw) return;
24995
- const rawInput = asFiniteNumber(raw.input ?? raw.inputTokens ?? raw.input_tokens ?? raw.promptTokens ?? raw.prompt_tokens);
24996
- const input = rawInput !== void 0 && rawInput < 0 ? 0 : rawInput;
24997
- const output = asFiniteNumber(raw.output ?? raw.outputTokens ?? raw.output_tokens ?? raw.completionTokens ?? raw.completion_tokens);
24998
- const cacheRead = asFiniteNumber(raw.cacheRead ?? raw.cache_read ?? raw.cache_read_input_tokens ?? raw.cached_tokens ?? raw.prompt_tokens_details?.cached_tokens);
24999
- const cacheWrite = asFiniteNumber(raw.cacheWrite ?? raw.cache_write ?? raw.cache_creation_input_tokens);
25000
- const total = asFiniteNumber(raw.total ?? raw.totalTokens ?? raw.total_tokens);
25001
- if (input === void 0 && output === void 0 && cacheRead === void 0 && cacheWrite === void 0 && total === void 0) return;
25002
- return {
25003
- input,
25004
- output,
25005
- cacheRead,
25006
- cacheWrite,
25007
- total
25008
- };
24996
+ return normalizeBillingUsage(raw);
25009
24997
  }
25010
24998
  function derivePromptTokens(usage) {
25011
24999
  if (!usage) return;
@@ -25393,62 +25381,19 @@ const readUsageFromSessionLog = (sessionId, sessionEntry, agentId, sessionKey, s
25393
25381
  } catch {
25394
25382
  return;
25395
25383
  }
25396
- if (!fs$1.existsSync(logPath)) return;
25397
- try {
25398
- const TAIL_BYTES = 8192;
25399
- const stat = fs$1.statSync(logPath);
25400
- const offset = Math.max(0, stat.size - TAIL_BYTES);
25401
- const buf = Buffer.alloc(Math.min(TAIL_BYTES, stat.size));
25402
- const fd = fs$1.openSync(logPath, "r");
25403
- try {
25404
- fs$1.readSync(fd, buf, 0, buf.length, offset);
25405
- } finally {
25406
- fs$1.closeSync(fd);
25407
- }
25408
- const tail = buf.toString("utf-8");
25409
- const lines = (offset > 0 ? tail.slice(tail.indexOf("\n") + 1) : tail).split(/\n+/);
25410
- let input = 0;
25411
- let output = 0;
25412
- let promptTokens = 0;
25413
- let model;
25414
- let lastUsage;
25415
- for (const line of lines) {
25416
- if (!line.trim()) continue;
25417
- try {
25418
- const parsed = JSON.parse(line);
25419
- const usage = normalizeUsage(parsed.message?.usage ?? parsed.usage);
25420
- if (usage) lastUsage = usage;
25421
- model = parsed.message?.model ?? parsed.model ?? model;
25422
- } catch {}
25423
- }
25424
- if (!lastUsage) return;
25425
- input = lastUsage.input ?? 0;
25426
- output = lastUsage.output ?? 0;
25427
- promptTokens = derivePromptTokens(lastUsage) ?? lastUsage.total ?? input + output;
25428
- const total = lastUsage.total ?? promptTokens + output;
25429
- if (promptTokens === 0 && total === 0) return;
25430
- return {
25431
- input,
25432
- output,
25433
- promptTokens,
25434
- total,
25435
- model
25436
- };
25437
- } catch {
25438
- return;
25439
- }
25384
+ return readLatestBillingUsage(logPath);
25440
25385
  };
25441
- const formatUsagePair = (input, output) => {
25442
- if (input == null && output == null) return null;
25443
- return `🧮 Tokens: ${typeof input === "number" ? formatTokenCount(input) : "?"} in / ${typeof output === "number" ? formatTokenCount(output) : "?"} out`;
25386
+ const formatUsagePair = (input, output, cacheRead, cacheWrite) => {
25387
+ if (input == null && output == null && cacheRead == null && cacheWrite == null) return null;
25388
+ const count = value => typeof value === "number" ? value.toLocaleString("en-US") : "?";
25389
+ return `🧮 Tokens: ${count((input ?? 0) + (cacheWrite ?? 0))} new in / ${count(cacheRead ?? 0)} cached / ${count(output)} out (last API call)`;
25444
25390
  };
25445
- const formatCacheLine = (input, cacheRead, cacheWrite) => {
25391
+ const formatCacheLine = (input, cacheRead, cacheWrite, usage) => {
25446
25392
  if (!cacheRead && !cacheWrite) return null;
25447
- if ((typeof cacheRead !== "number" || cacheRead <= 0) && (typeof cacheWrite !== "number" || cacheWrite <= 0)) return null;
25448
- const cachedLabel = typeof cacheRead === "number" ? formatTokenCount(cacheRead) : "0";
25449
- const newLabel = typeof cacheWrite === "number" ? formatTokenCount(cacheWrite) : "0";
25450
- const totalInput = (typeof cacheRead === "number" ? cacheRead : 0) + (typeof cacheWrite === "number" ? cacheWrite : 0) + (typeof input === "number" ? input : 0);
25451
- return `🗄️ Cache: ${totalInput > 0 && typeof cacheRead === "number" ? Math.round(cacheRead / totalInput * 100) : 0}% hit · ${cachedLabel} cached, ${newLabel} new`;
25393
+ const total = (input ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0);
25394
+ const count = value => (value ?? 0).toLocaleString("en-US");
25395
+ const ttl = usage?.cacheWrite5m !== undefined || usage?.cacheWrite1h !== undefined ? ` (${count(usage.cacheWrite5m)} 5m / ${count(usage.cacheWrite1h)} 1h)` : "";
25396
+ return `🗄️ Cache: ${total > 0 ? Math.round((cacheRead ?? 0) / total * 100) : 0}% hit · ${count(input)} uncached + ${count(cacheWrite)} written${ttl}`;
25452
25397
  };
25453
25398
  const formatMediaUnderstandingLine = (decisions) => {
25454
25399
  if (!decisions || decisions.length === 0) return null;
@@ -25527,10 +25472,14 @@ function buildStatusMessage(args) {
25527
25472
  let outputTokens = entry?.outputTokens;
25528
25473
  let cacheRead = entry?.cacheRead;
25529
25474
  let cacheWrite = entry?.cacheWrite;
25475
+ let billingUsage;
25530
25476
  let totalTokens = entry?.totalTokens ?? (entry?.inputTokens ?? 0) + (entry?.outputTokens ?? 0);
25531
- if (args.includeTranscriptUsage) {
25477
+ if (entry?.sessionId) { // Always use a coherent latest API call on both status paths.
25532
25478
  const logUsage = readUsageFromSessionLog(entry?.sessionId, entry, args.agentId, args.sessionKey, args.sessionStorePath);
25533
25479
  if (logUsage) {
25480
+ billingUsage = logUsage;
25481
+ cacheRead = logUsage.cacheRead ?? 0;
25482
+ cacheWrite = logUsage.cacheWrite ?? 0;
25534
25483
  const candidate = logUsage.promptTokens || logUsage.total;
25535
25484
  if (!totalTokens || totalTokens === 0 || candidate > totalTokens) totalTokens = candidate;
25536
25485
  if (!entry?.model && logUsage.model) {
@@ -25549,8 +25498,10 @@ function buildStatusMessage(args) {
25549
25498
  model: logUsage.model,
25550
25499
  fallbackContextTokens: contextTokens ?? void 0
25551
25500
  }) ?? contextTokens;
25552
- if (!inputTokens || inputTokens === 0) inputTokens = logUsage.input;
25553
- if (!outputTokens || outputTokens === 0) outputTokens = logUsage.output;
25501
+ inputTokens = logUsage.input ?? 0;
25502
+ outputTokens = logUsage.output ?? 0;
25503
+ if (logUsage.provider) activeProvider = logUsage.provider;
25504
+ if (logUsage.model) activeModel = logUsage.model;
25554
25505
  }
25555
25506
  }
25556
25507
  const thinkLevel = args.resolvedThink ?? args.sessionEntry?.thinkingLevel ?? args.agent?.thinkingDefault ?? "off";
@@ -25586,21 +25537,14 @@ function buildStatusMessage(args) {
25586
25537
  state: entry
25587
25538
  });
25588
25539
  const effectiveCostAuthMode = fallbackState.active ? activeAuthMode : selectedAuthMode ?? activeAuthMode;
25589
- const showCost = effectiveCostAuthMode === "api-key" || effectiveCostAuthMode === "mixed";
25540
+ const showCost = billingUsage?.cost?.total > 0 || effectiveCostAuthMode === "api-key" || effectiveCostAuthMode === "mixed";
25590
25541
  const costConfig = showCost ? resolveModelCostConfig({
25591
25542
  provider: activeProvider,
25592
25543
  model: activeModel,
25593
25544
  config: args.config
25594
25545
  }) : void 0;
25595
- const hasUsage = typeof inputTokens === "number" || typeof outputTokens === "number";
25596
- const cost = showCost && hasUsage ? estimateUsageCost({
25597
- usage: {
25598
- input: inputTokens ?? void 0,
25599
- output: outputTokens ?? void 0
25600
- },
25601
- cost: costConfig
25602
- }) : void 0;
25603
- const costLabel = showCost && hasUsage ? formatUsd(cost) : void 0;
25546
+ const hasUsage = [inputTokens, outputTokens, cacheRead, cacheWrite].some(value => typeof value === "number");
25547
+ billingUsage ??= { input: inputTokens, output: outputTokens, cacheRead, cacheWrite };
25604
25548
  const selectedAuthLabel = selectedAuthLabelValue ? ` · 🔑 ${selectedAuthLabelValue}` : "";
25605
25549
  const channelModelNote = (() => {
25606
25550
  if (!args.config || !entry) return;
@@ -25632,9 +25576,9 @@ function buildStatusMessage(args) {
25632
25576
  const fallbackLine = fallbackState.active ? `↪️ Fallback: ${activeModelLabel}${showFallbackAuth ? ` · 🔑 ${activeAuthLabelValue}` : ""} (${fallbackState.reason ?? "selected model unavailable"})` : null;
25633
25577
  const commit = resolveCommitHash();
25634
25578
  const versionLine = `🦞 Johnness ${VERSION}${commit ? ` (${commit})` : ""}`;
25635
- const usagePair = formatUsagePair(inputTokens, outputTokens);
25636
- const cacheLine = formatCacheLine(inputTokens, cacheRead, cacheWrite);
25637
- const costLine = costLabel ? `💵 Cost: ${costLabel}` : null;
25579
+ const usagePair = formatUsagePair(inputTokens, outputTokens, cacheRead, cacheWrite);
25580
+ const cacheLine = formatCacheLine(inputTokens, cacheRead, cacheWrite, billingUsage);
25581
+ const costLine = showCost && hasUsage ? formatBillingCost(billingUsage, costConfig) : null;
25638
25582
  const usageCostLine = usagePair && costLine ? `${usagePair} · ${costLine}` : usagePair ?? costLine;
25639
25583
  const mediaLine = formatMediaUnderstandingLine(args.mediaDecisions);
25640
25584
  const voiceLine = formatVoiceModeLine(args.config, args.sessionEntry);
@@ -27971,7 +27915,7 @@ function resolveModelAuthLabel(params) {
27971
27915
  });
27972
27916
  if (profile.type === "oauth") return `oauth${label ? ` (${label})` : ""}`;
27973
27917
  if (profile.type === "token") return `token${label ? ` (${label})` : ""}`;
27974
- return `api-key${label ? ` (${label})` : ""}`;
27918
+ return `api-key${label ? ` (${label})` : ""}${formatAuthProfileFallback(params.sessionEntry, profileId)}`;
27975
27919
  }
27976
27920
  const envKey = resolveEnvApiKey(providerKey);
27977
27921
  if (envKey?.apiKey) {
@@ -52922,6 +52866,7 @@ async function persistSessionUsageUpdate(params) {
52922
52866
  modelProvider: params.providerUsed ?? entry.modelProvider,
52923
52867
  model: params.modelUsed ?? entry.model,
52924
52868
  authProfileServed: params.authProfileServed ?? entry.authProfileServed, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
52869
+ authProfileFallback: params.authProfileFallback ?? null, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
52925
52870
  contextTokens: resolvedContextTokens,
52926
52871
  systemPromptReport: params.systemPromptReport ?? entry.systemPromptReport,
52927
52872
  updatedAt: Date.now()
@@ -53202,6 +53147,7 @@ function createFollowupRunner(params) {
53202
53147
  modelUsed,
53203
53148
  providerUsed: fallbackProvider,
53204
53149
  authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
53150
+ authProfileFallback: runResult.meta?.agentMeta?.authProfileFallback, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
53205
53151
  contextTokensUsed,
53206
53152
  systemPromptReport: runResult.meta?.systemPromptReport,
53207
53153
  logLabel: "followup"
@@ -53667,6 +53613,7 @@ async function runReplyAgent(params) {
53667
53613
  modelUsed,
53668
53614
  providerUsed,
53669
53615
  authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
53616
+ authProfileFallback: runResult.meta?.agentMeta?.authProfileFallback, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
53670
53617
  contextTokensUsed,
53671
53618
  systemPromptReport: runResult.meta?.systemPromptReport,
53672
53619
  cliSessionId
@@ -69838,6 +69785,7 @@ async function updateSessionStoreAfterAgentRun(params) {
69838
69785
  model: modelUsed
69839
69786
  });
69840
69787
  if (result.meta.agentMeta?.authProfileId) next.authProfileServed = result.meta.agentMeta.authProfileId; // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
69788
+ next.authProfileFallback = result.meta.agentMeta?.authProfileFallback ?? null; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
69841
69789
  if (isCliProvider(providerUsed, cfg)) {
69842
69790
  const cliSessionId = result.meta.agentMeta?.sessionId?.trim();
69843
69791
  if (cliSessionId) setCliSessionId(next, providerUsed, cliSessionId);
@@ -96745,6 +96693,8 @@ function normalizeAssistantUsageSnapshot(usage) {
96745
96693
  cacheRead,
96746
96694
  cacheWrite,
96747
96695
  totalTokens,
96696
+ ...normalized.cacheWrite5m !== undefined ? { cacheWrite5m: normalized.cacheWrite5m } : {},
96697
+ ...normalized.cacheWrite1h !== undefined ? { cacheWrite1h: normalized.cacheWrite1h } : {},
96748
96698
  ...cost ? { cost } : {}
96749
96699
  };
96750
96700
  }
@@ -104087,6 +104037,7 @@ async function runEmbeddedPiAgent(params) {
104087
104037
  });
104088
104038
  if (lockedProfileId && !profileOrder.includes(lockedProfileId)) throw new Error(`Auth profile "${lockedProfileId}" is not configured for ${provider}.`);
104089
104039
  const profileCandidates = lockedProfileId ? [lockedProfileId] : profileOrder.length > 0 ? profileOrder : [void 0];
104040
+ const subscriptionAuth = createSubscriptionAuthTracker({ provider, model: modelId, store: authStore, preferredProfileId, lockedProfileId }); // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
104090
104041
  let profileIndex = 0;
104091
104042
  const initialThinkLevel = params.thinkLevel ?? "off";
104092
104043
  let thinkLevel = initialThinkLevel;
@@ -104218,7 +104169,8 @@ async function runEmbeddedPiAgent(params) {
104218
104169
  } else authStorage.setRuntimeApiKey(model.provider, apiKeyInfo.apiKey);
104219
104170
  lastProfileId = apiKeyInfo.profileId;
104220
104171
  };
104221
- const advanceAuthProfile = async () => {
104172
+ const advanceAuthProfile = async (reason) => {
104173
+ subscriptionAuth.failed(profileCandidates[profileIndex], reason);
104222
104174
  if (lockedProfileId) return false;
104223
104175
  let nextIndex = profileIndex + 1;
104224
104176
  while (nextIndex < profileCandidates.length) {
@@ -104268,7 +104220,7 @@ async function runEmbeddedPiAgent(params) {
104268
104220
  allInCooldown: false,
104269
104221
  error: err
104270
104222
  });
104271
- if (!await advanceAuthProfile()) throwAuthProfileFailover({
104223
+ if (!await advanceAuthProfile(/refresh/i.test(String(err)) ? "oauth_refresh_failed" : "credential_unavailable")) throwAuthProfileFailover({
104272
104224
  allInCooldown: false,
104273
104225
  error: err
104274
104226
  });
@@ -104647,7 +104599,7 @@ async function runEmbeddedPiAgent(params) {
104647
104599
  reason: promptProfileFailureReason
104648
104600
  });
104649
104601
  const promptFailoverFailure = isFailoverErrorMessage(errorText);
104650
- if (promptFailoverFailure && promptFailoverReason !== "timeout" && await advanceAuthProfile()) {
104602
+ if (promptFailoverFailure && promptFailoverReason !== "timeout" && await advanceAuthProfile(promptFailoverReason)) {
104651
104603
  await maybeBackoffBeforeOverloadFailover(promptFailoverReason);
104652
104604
  continue;
104653
104605
  }
@@ -104710,7 +104662,7 @@ async function runEmbeddedPiAgent(params) {
104710
104662
  if (timedOut && !isProbeSession) log$3.warn(`Profile ${lastProfileId} timed out. Trying next account...`);
104711
104663
  if (cloudCodeAssistFormatError) log$3.warn(`Profile ${lastProfileId} hit Cloud Code Assist format error. Tool calls will be sanitized on retry.`);
104712
104664
  }
104713
- if (await advanceAuthProfile()) {
104665
+ if (await advanceAuthProfile(timedOut ? "timeout" : assistantFailoverReason)) {
104714
104666
  await maybeBackoffBeforeOverloadFailover(assistantFailoverReason);
104715
104667
  continue;
104716
104668
  }
@@ -104759,6 +104711,7 @@ async function runEmbeddedPiAgent(params) {
104759
104711
  lastCallUsage: lastCallUsage ?? void 0,
104760
104712
  promptTokens,
104761
104713
  compactionCount: autoCompactionCount > 0 ? autoCompactionCount : void 0,
104714
+ authProfileFallback: subscriptionAuth.result(lastProfileId), // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
104762
104715
  authProfileId: lastProfileId // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: profile that served this turn
104763
104716
  };
104764
104717
  const payloads = buildEmbeddedRunPayloads({
@@ -1,3 +1,5 @@
1
+ import { createSubscriptionAuthTracker, formatAuthProfileFallback } from "./anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
2
+ import { normalizeBillingUsage, readLatestBillingUsage, formatBillingCost } from "./usage-billing.js"; // JOHNNESS_PATCH_USAGE_BILLING_91 dist/pi-embedded-DoQsYfIY.js
1
3
  import { importOptional66 } from "./optional-module.js";
2
4
  const JOHNNESS_PATCH_SLIM_TREE_66 = true;
3
5
  import { createImageGenerateTool } from "./image-generate.js";
@@ -24987,21 +24989,7 @@ function hasNonzeroUsage(usage) {
24987
24989
  ].some((v) => typeof v === "number" && Number.isFinite(v) && v > 0);
24988
24990
  }
24989
24991
  function normalizeUsage(raw) {
24990
- if (!raw) return;
24991
- const rawInput = asFiniteNumber(raw.input ?? raw.inputTokens ?? raw.input_tokens ?? raw.promptTokens ?? raw.prompt_tokens);
24992
- const input = rawInput !== void 0 && rawInput < 0 ? 0 : rawInput;
24993
- const output = asFiniteNumber(raw.output ?? raw.outputTokens ?? raw.output_tokens ?? raw.completionTokens ?? raw.completion_tokens);
24994
- const cacheRead = asFiniteNumber(raw.cacheRead ?? raw.cache_read ?? raw.cache_read_input_tokens ?? raw.cached_tokens ?? raw.prompt_tokens_details?.cached_tokens);
24995
- const cacheWrite = asFiniteNumber(raw.cacheWrite ?? raw.cache_write ?? raw.cache_creation_input_tokens);
24996
- const total = asFiniteNumber(raw.total ?? raw.totalTokens ?? raw.total_tokens);
24997
- if (input === void 0 && output === void 0 && cacheRead === void 0 && cacheWrite === void 0 && total === void 0) return;
24998
- return {
24999
- input,
25000
- output,
25001
- cacheRead,
25002
- cacheWrite,
25003
- total
25004
- };
24992
+ return normalizeBillingUsage(raw);
25005
24993
  }
25006
24994
  function derivePromptTokens(usage) {
25007
24995
  if (!usage) return;
@@ -25389,62 +25377,19 @@ const readUsageFromSessionLog = (sessionId, sessionEntry, agentId, sessionKey, s
25389
25377
  } catch {
25390
25378
  return;
25391
25379
  }
25392
- if (!syncFs.existsSync(logPath)) return;
25393
- try {
25394
- const TAIL_BYTES = 8192;
25395
- const stat = syncFs.statSync(logPath);
25396
- const offset = Math.max(0, stat.size - TAIL_BYTES);
25397
- const buf = Buffer.alloc(Math.min(TAIL_BYTES, stat.size));
25398
- const fd = syncFs.openSync(logPath, "r");
25399
- try {
25400
- syncFs.readSync(fd, buf, 0, buf.length, offset);
25401
- } finally {
25402
- syncFs.closeSync(fd);
25403
- }
25404
- const tail = buf.toString("utf-8");
25405
- const lines = (offset > 0 ? tail.slice(tail.indexOf("\n") + 1) : tail).split(/\n+/);
25406
- let input = 0;
25407
- let output = 0;
25408
- let promptTokens = 0;
25409
- let model;
25410
- let lastUsage;
25411
- for (const line of lines) {
25412
- if (!line.trim()) continue;
25413
- try {
25414
- const parsed = JSON.parse(line);
25415
- const usage = normalizeUsage(parsed.message?.usage ?? parsed.usage);
25416
- if (usage) lastUsage = usage;
25417
- model = parsed.message?.model ?? parsed.model ?? model;
25418
- } catch {}
25419
- }
25420
- if (!lastUsage) return;
25421
- input = lastUsage.input ?? 0;
25422
- output = lastUsage.output ?? 0;
25423
- promptTokens = derivePromptTokens(lastUsage) ?? lastUsage.total ?? input + output;
25424
- const total = lastUsage.total ?? promptTokens + output;
25425
- if (promptTokens === 0 && total === 0) return;
25426
- return {
25427
- input,
25428
- output,
25429
- promptTokens,
25430
- total,
25431
- model
25432
- };
25433
- } catch {
25434
- return;
25435
- }
25380
+ return readLatestBillingUsage(logPath);
25436
25381
  };
25437
- const formatUsagePair = (input, output) => {
25438
- if (input == null && output == null) return null;
25439
- return `🧮 Tokens: ${typeof input === "number" ? formatTokenCount(input) : "?"} in / ${typeof output === "number" ? formatTokenCount(output) : "?"} out`;
25382
+ const formatUsagePair = (input, output, cacheRead, cacheWrite) => {
25383
+ if (input == null && output == null && cacheRead == null && cacheWrite == null) return null;
25384
+ const count = value => typeof value === "number" ? value.toLocaleString("en-US") : "?";
25385
+ return `🧮 Tokens: ${count((input ?? 0) + (cacheWrite ?? 0))} new in / ${count(cacheRead ?? 0)} cached / ${count(output)} out (last API call)`;
25440
25386
  };
25441
- const formatCacheLine = (input, cacheRead, cacheWrite) => {
25387
+ const formatCacheLine = (input, cacheRead, cacheWrite, usage) => {
25442
25388
  if (!cacheRead && !cacheWrite) return null;
25443
- if ((typeof cacheRead !== "number" || cacheRead <= 0) && (typeof cacheWrite !== "number" || cacheWrite <= 0)) return null;
25444
- const cachedLabel = typeof cacheRead === "number" ? formatTokenCount(cacheRead) : "0";
25445
- const newLabel = typeof cacheWrite === "number" ? formatTokenCount(cacheWrite) : "0";
25446
- const totalInput = (typeof cacheRead === "number" ? cacheRead : 0) + (typeof cacheWrite === "number" ? cacheWrite : 0) + (typeof input === "number" ? input : 0);
25447
- return `🗄️ Cache: ${totalInput > 0 && typeof cacheRead === "number" ? Math.round(cacheRead / totalInput * 100) : 0}% hit · ${cachedLabel} cached, ${newLabel} new`;
25389
+ const total = (input ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0);
25390
+ const count = value => (value ?? 0).toLocaleString("en-US");
25391
+ const ttl = usage?.cacheWrite5m !== undefined || usage?.cacheWrite1h !== undefined ? ` (${count(usage.cacheWrite5m)} 5m / ${count(usage.cacheWrite1h)} 1h)` : "";
25392
+ return `🗄️ Cache: ${total > 0 ? Math.round((cacheRead ?? 0) / total * 100) : 0}% hit · ${count(input)} uncached + ${count(cacheWrite)} written${ttl}`;
25448
25393
  };
25449
25394
  const formatMediaUnderstandingLine = (decisions) => {
25450
25395
  if (!decisions || decisions.length === 0) return null;
@@ -25523,10 +25468,14 @@ function buildStatusMessage(args) {
25523
25468
  let outputTokens = entry?.outputTokens;
25524
25469
  let cacheRead = entry?.cacheRead;
25525
25470
  let cacheWrite = entry?.cacheWrite;
25471
+ let billingUsage;
25526
25472
  let totalTokens = entry?.totalTokens ?? (entry?.inputTokens ?? 0) + (entry?.outputTokens ?? 0);
25527
- if (args.includeTranscriptUsage) {
25473
+ if (entry?.sessionId) { // Always use a coherent latest API call on both status paths.
25528
25474
  const logUsage = readUsageFromSessionLog(entry?.sessionId, entry, args.agentId, args.sessionKey, args.sessionStorePath);
25529
25475
  if (logUsage) {
25476
+ billingUsage = logUsage;
25477
+ cacheRead = logUsage.cacheRead ?? 0;
25478
+ cacheWrite = logUsage.cacheWrite ?? 0;
25530
25479
  const candidate = logUsage.promptTokens || logUsage.total;
25531
25480
  if (!totalTokens || totalTokens === 0 || candidate > totalTokens) totalTokens = candidate;
25532
25481
  if (!entry?.model && logUsage.model) {
@@ -25545,8 +25494,10 @@ function buildStatusMessage(args) {
25545
25494
  model: logUsage.model,
25546
25495
  fallbackContextTokens: contextTokens ?? void 0
25547
25496
  }) ?? contextTokens;
25548
- if (!inputTokens || inputTokens === 0) inputTokens = logUsage.input;
25549
- if (!outputTokens || outputTokens === 0) outputTokens = logUsage.output;
25497
+ inputTokens = logUsage.input ?? 0;
25498
+ outputTokens = logUsage.output ?? 0;
25499
+ if (logUsage.provider) activeProvider = logUsage.provider;
25500
+ if (logUsage.model) activeModel = logUsage.model;
25550
25501
  }
25551
25502
  }
25552
25503
  const thinkLevel = args.resolvedThink ?? args.sessionEntry?.thinkingLevel ?? args.agent?.thinkingDefault ?? "off";
@@ -25582,21 +25533,14 @@ function buildStatusMessage(args) {
25582
25533
  state: entry
25583
25534
  });
25584
25535
  const effectiveCostAuthMode = fallbackState.active ? activeAuthMode : selectedAuthMode ?? activeAuthMode;
25585
- const showCost = effectiveCostAuthMode === "api-key" || effectiveCostAuthMode === "mixed";
25536
+ const showCost = billingUsage?.cost?.total > 0 || effectiveCostAuthMode === "api-key" || effectiveCostAuthMode === "mixed";
25586
25537
  const costConfig = showCost ? resolveModelCostConfig({
25587
25538
  provider: activeProvider,
25588
25539
  model: activeModel,
25589
25540
  config: args.config
25590
25541
  }) : void 0;
25591
- const hasUsage = typeof inputTokens === "number" || typeof outputTokens === "number";
25592
- const cost = showCost && hasUsage ? estimateUsageCost({
25593
- usage: {
25594
- input: inputTokens ?? void 0,
25595
- output: outputTokens ?? void 0
25596
- },
25597
- cost: costConfig
25598
- }) : void 0;
25599
- const costLabel = showCost && hasUsage ? formatUsd(cost) : void 0;
25542
+ const hasUsage = [inputTokens, outputTokens, cacheRead, cacheWrite].some(value => typeof value === "number");
25543
+ billingUsage ??= { input: inputTokens, output: outputTokens, cacheRead, cacheWrite };
25600
25544
  const selectedAuthLabel = selectedAuthLabelValue ? ` · 🔑 ${selectedAuthLabelValue}` : "";
25601
25545
  const channelModelNote = (() => {
25602
25546
  if (!args.config || !entry) return;
@@ -25628,9 +25572,9 @@ function buildStatusMessage(args) {
25628
25572
  const fallbackLine = fallbackState.active ? `↪️ Fallback: ${activeModelLabel}${showFallbackAuth ? ` · 🔑 ${activeAuthLabelValue}` : ""} (${fallbackState.reason ?? "selected model unavailable"})` : null;
25629
25573
  const commit = resolveCommitHash();
25630
25574
  const versionLine = `🦞 Johnness ${VERSION}${commit ? ` (${commit})` : ""}`;
25631
- const usagePair = formatUsagePair(inputTokens, outputTokens);
25632
- const cacheLine = formatCacheLine(inputTokens, cacheRead, cacheWrite);
25633
- const costLine = costLabel ? `💵 Cost: ${costLabel}` : null;
25575
+ const usagePair = formatUsagePair(inputTokens, outputTokens, cacheRead, cacheWrite);
25576
+ const cacheLine = formatCacheLine(inputTokens, cacheRead, cacheWrite, billingUsage);
25577
+ const costLine = showCost && hasUsage ? formatBillingCost(billingUsage, costConfig) : null;
25634
25578
  const usageCostLine = usagePair && costLine ? `${usagePair} · ${costLine}` : usagePair ?? costLine;
25635
25579
  const mediaLine = formatMediaUnderstandingLine(args.mediaDecisions);
25636
25580
  const voiceLine = formatVoiceModeLine(args.config, args.sessionEntry);
@@ -27967,7 +27911,7 @@ function resolveModelAuthLabel(params) {
27967
27911
  });
27968
27912
  if (profile.type === "oauth") return `oauth${label ? ` (${label})` : ""}`;
27969
27913
  if (profile.type === "token") return `token${label ? ` (${label})` : ""}`;
27970
- return `api-key${label ? ` (${label})` : ""}`;
27914
+ return `api-key${label ? ` (${label})` : ""}${formatAuthProfileFallback(params.sessionEntry, profileId)}`;
27971
27915
  }
27972
27916
  const envKey = resolveEnvApiKey(providerKey);
27973
27917
  if (envKey?.apiKey) {
@@ -52918,6 +52862,7 @@ async function persistSessionUsageUpdate(params) {
52918
52862
  modelProvider: params.providerUsed ?? entry.modelProvider,
52919
52863
  model: params.modelUsed ?? entry.model,
52920
52864
  authProfileServed: params.authProfileServed ?? entry.authProfileServed, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
52865
+ authProfileFallback: params.authProfileFallback ?? null, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
52921
52866
  contextTokens: resolvedContextTokens,
52922
52867
  systemPromptReport: params.systemPromptReport ?? entry.systemPromptReport,
52923
52868
  updatedAt: Date.now()
@@ -53198,6 +53143,7 @@ function createFollowupRunner(params) {
53198
53143
  modelUsed,
53199
53144
  providerUsed: fallbackProvider,
53200
53145
  authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
53146
+ authProfileFallback: runResult.meta?.agentMeta?.authProfileFallback, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
53201
53147
  contextTokensUsed,
53202
53148
  systemPromptReport: runResult.meta?.systemPromptReport,
53203
53149
  logLabel: "followup"
@@ -53663,6 +53609,7 @@ async function runReplyAgent(params) {
53663
53609
  modelUsed,
53664
53610
  providerUsed,
53665
53611
  authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
53612
+ authProfileFallback: runResult.meta?.agentMeta?.authProfileFallback, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
53666
53613
  contextTokensUsed,
53667
53614
  systemPromptReport: runResult.meta?.systemPromptReport,
53668
53615
  cliSessionId
@@ -69834,6 +69781,7 @@ async function updateSessionStoreAfterAgentRun(params) {
69834
69781
  model: modelUsed
69835
69782
  });
69836
69783
  if (result.meta.agentMeta?.authProfileId) next.authProfileServed = result.meta.agentMeta.authProfileId; // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
69784
+ next.authProfileFallback = result.meta.agentMeta?.authProfileFallback ?? null; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
69837
69785
  if (isCliProvider(providerUsed, cfg)) {
69838
69786
  const cliSessionId = result.meta.agentMeta?.sessionId?.trim();
69839
69787
  if (cliSessionId) setCliSessionId(next, providerUsed, cliSessionId);
@@ -96735,6 +96683,8 @@ function normalizeAssistantUsageSnapshot(usage) {
96735
96683
  cacheRead,
96736
96684
  cacheWrite,
96737
96685
  totalTokens,
96686
+ ...normalized.cacheWrite5m !== undefined ? { cacheWrite5m: normalized.cacheWrite5m } : {},
96687
+ ...normalized.cacheWrite1h !== undefined ? { cacheWrite1h: normalized.cacheWrite1h } : {},
96738
96688
  ...cost ? { cost } : {}
96739
96689
  };
96740
96690
  }
@@ -104077,6 +104027,7 @@ async function runEmbeddedPiAgent(params) {
104077
104027
  });
104078
104028
  if (lockedProfileId && !profileOrder.includes(lockedProfileId)) throw new Error(`Auth profile "${lockedProfileId}" is not configured for ${provider}.`);
104079
104029
  const profileCandidates = lockedProfileId ? [lockedProfileId] : profileOrder.length > 0 ? profileOrder : [void 0];
104030
+ const subscriptionAuth = createSubscriptionAuthTracker({ provider, model: modelId, store: authStore, preferredProfileId, lockedProfileId }); // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
104080
104031
  let profileIndex = 0;
104081
104032
  const initialThinkLevel = params.thinkLevel ?? "off";
104082
104033
  let thinkLevel = initialThinkLevel;
@@ -104208,7 +104159,8 @@ async function runEmbeddedPiAgent(params) {
104208
104159
  } else authStorage.setRuntimeApiKey(model.provider, apiKeyInfo.apiKey);
104209
104160
  lastProfileId = apiKeyInfo.profileId;
104210
104161
  };
104211
- const advanceAuthProfile = async () => {
104162
+ const advanceAuthProfile = async (reason) => {
104163
+ subscriptionAuth.failed(profileCandidates[profileIndex], reason);
104212
104164
  if (lockedProfileId) return false;
104213
104165
  let nextIndex = profileIndex + 1;
104214
104166
  while (nextIndex < profileCandidates.length) {
@@ -104258,7 +104210,7 @@ async function runEmbeddedPiAgent(params) {
104258
104210
  allInCooldown: false,
104259
104211
  error: err
104260
104212
  });
104261
- if (!await advanceAuthProfile()) throwAuthProfileFailover({
104213
+ if (!await advanceAuthProfile(/refresh/i.test(String(err)) ? "oauth_refresh_failed" : "credential_unavailable")) throwAuthProfileFailover({
104262
104214
  allInCooldown: false,
104263
104215
  error: err
104264
104216
  });
@@ -104630,7 +104582,7 @@ async function runEmbeddedPiAgent(params) {
104630
104582
  reason: promptProfileFailureReason
104631
104583
  });
104632
104584
  const promptFailoverFailure = isFailoverErrorMessage(errorText);
104633
- if (promptFailoverFailure && promptFailoverReason !== "timeout" && await advanceAuthProfile()) {
104585
+ if (promptFailoverFailure && promptFailoverReason !== "timeout" && await advanceAuthProfile(promptFailoverReason)) {
104634
104586
  await maybeBackoffBeforeOverloadFailover(promptFailoverReason);
104635
104587
  continue;
104636
104588
  }
@@ -104693,7 +104645,7 @@ async function runEmbeddedPiAgent(params) {
104693
104645
  if (timedOut && !isProbeSession) log$3.warn(`Profile ${lastProfileId} timed out. Trying next account...`);
104694
104646
  if (cloudCodeAssistFormatError) log$3.warn(`Profile ${lastProfileId} hit Cloud Code Assist format error. Tool calls will be sanitized on retry.`);
104695
104647
  }
104696
- if (await advanceAuthProfile()) {
104648
+ if (await advanceAuthProfile(timedOut ? "timeout" : assistantFailoverReason)) {
104697
104649
  await maybeBackoffBeforeOverloadFailover(assistantFailoverReason);
104698
104650
  continue;
104699
104651
  }
@@ -104727,6 +104679,7 @@ async function runEmbeddedPiAgent(params) {
104727
104679
  lastCallUsage: lastCallUsage ?? void 0,
104728
104680
  promptTokens,
104729
104681
  compactionCount: autoCompactionCount > 0 ? autoCompactionCount : void 0,
104682
+ authProfileFallback: subscriptionAuth.result(lastProfileId), // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
104730
104683
  authProfileId: lastProfileId // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: profile that served this turn
104731
104684
  };
104732
104685
  const payloads = buildEmbeddedRunPayloads({
@@ -3880,7 +3880,8 @@ const ModelDefinitionSchema = z.object({
3880
3880
  input: z.number().optional(),
3881
3881
  output: z.number().optional(),
3882
3882
  cacheRead: z.number().optional(),
3883
- cacheWrite: z.number().optional()
3883
+ cacheWrite: z.number().optional(),
3884
+ cacheWrite1h: z.number().nonnegative().optional() // JOHNNESS_PATCH_USAGE_BILLING_91
3884
3885
  }).strict().optional(),
3885
3886
  contextWindow: z.number().positive().optional(),
3886
3887
  maxTokens: z.number().positive().optional(),
@@ -27,6 +27,7 @@ export type ModelDefinitionConfig = {
27
27
  output: number;
28
28
  cacheRead: number;
29
29
  cacheWrite: number;
30
+ cacheWrite1h?: number;
30
31
  };
31
32
  contextWindow: number;
32
33
  maxTokens: number;
@@ -127,6 +127,7 @@ export declare const ModelDefinitionSchema: z.ZodObject<{
127
127
  output: z.ZodOptional<z.ZodNumber>;
128
128
  cacheRead: z.ZodOptional<z.ZodNumber>;
129
129
  cacheWrite: z.ZodOptional<z.ZodNumber>;
130
+ cacheWrite1h: z.ZodOptional<z.ZodNumber>;
130
131
  }, z.core.$strict>>;
131
132
  contextWindow: z.ZodOptional<z.ZodNumber>;
132
133
  maxTokens: z.ZodOptional<z.ZodNumber>;
@@ -207,6 +208,7 @@ export declare const ModelProviderSchema: z.ZodObject<{
207
208
  output: z.ZodOptional<z.ZodNumber>;
208
209
  cacheRead: z.ZodOptional<z.ZodNumber>;
209
210
  cacheWrite: z.ZodOptional<z.ZodNumber>;
211
+ cacheWrite1h: z.ZodOptional<z.ZodNumber>;
210
212
  }, z.core.$strict>>;
211
213
  contextWindow: z.ZodOptional<z.ZodNumber>;
212
214
  maxTokens: z.ZodOptional<z.ZodNumber>;
@@ -298,6 +300,7 @@ export declare const ModelsConfigSchema: z.ZodOptional<z.ZodObject<{
298
300
  output: z.ZodOptional<z.ZodNumber>;
299
301
  cacheRead: z.ZodOptional<z.ZodNumber>;
300
302
  cacheWrite: z.ZodOptional<z.ZodNumber>;
303
+ cacheWrite1h: z.ZodOptional<z.ZodNumber>;
301
304
  }, z.core.$strict>>;
302
305
  contextWindow: z.ZodOptional<z.ZodNumber>;
303
306
  maxTokens: z.ZodOptional<z.ZodNumber>;
@@ -241,6 +241,7 @@ export declare const JohnnessSchema: z.ZodObject<{
241
241
  output: z.ZodOptional<z.ZodNumber>;
242
242
  cacheRead: z.ZodOptional<z.ZodNumber>;
243
243
  cacheWrite: z.ZodOptional<z.ZodNumber>;
244
+ cacheWrite1h: z.ZodOptional<z.ZodNumber>;
244
245
  }, z.core.$strict>>;
245
246
  contextWindow: z.ZodOptional<z.ZodNumber>;
246
247
  maxTokens: z.ZodOptional<z.ZodNumber>;
@@ -1,3 +1,4 @@
1
+ import { readCurrentAnthropicAuth } from "../anthropic-auth-runtime.js"; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
1
2
  import { claudeSubscriptionOrder } from "../subscription-login.js"; // JOHNNESS_PATCH_SUBSCRIPTION_LOGIN_86
2
3
  // JOHNNESS_PATCH_CATALOG_REFRESH_65
3
4
  import { mergeShippedCatalog65 } from "../catalog-refresh.js";
@@ -1129,8 +1130,10 @@ function codexOwnershipContext(agentDir) {
1129
1130
  log: (event) => log$9.info("Codex OAuth ownership", event)
1130
1131
  };
1131
1132
  }
1133
+ // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
1132
1134
  function readCodexOwnedAuthStore(agentDir, store) {
1133
- return readManagedCodexStore({ ...codexOwnershipContext(agentDir), store });
1135
+ const context = codexOwnershipContext(agentDir);
1136
+ return readCurrentAnthropicAuth({ ...context, store: readManagedCodexStore({ ...context, store }) });
1134
1137
  }
1135
1138
  function sanitizeAuthProfileCredential(credential) {
1136
1139
  const sanitized = { ...credential };
@@ -2755,7 +2758,7 @@ async function refreshUnmanagedOAuthTokenWithLock(params) {
2755
2758
  const authPath = resolveAuthStorePath(params.agentDir);
2756
2759
  fs.mkdirSync(path.dirname(authPath), { recursive: true, mode: 448 });
2757
2760
  return await withFileLock(authPath, AUTH_STORE_LOCK_OPTIONS, async () => {
2758
- const store = ensureAuthProfileStore(params.agentDir);
2761
+ const store = loadAuthProfileStoreForRuntime(params.agentDir, { allowKeychainPrompt: false }); // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92: reread under lock
2759
2762
  const cred = store.profiles[params.profileId];
2760
2763
  if (cred?.provider === "openai-codex") throw new Error("Auth profile changed to Codex; resolve again through its owner");
2761
2764
  if (!cred || cred.type !== "oauth") return null;
@@ -7129,7 +7132,8 @@ function resolveModelCost(raw) {
7129
7132
  input: typeof raw?.input === "number" ? raw.input : DEFAULT_MODEL_COST.input,
7130
7133
  output: typeof raw?.output === "number" ? raw.output : DEFAULT_MODEL_COST.output,
7131
7134
  cacheRead: typeof raw?.cacheRead === "number" ? raw.cacheRead : DEFAULT_MODEL_COST.cacheRead,
7132
- cacheWrite: typeof raw?.cacheWrite === "number" ? raw.cacheWrite : DEFAULT_MODEL_COST.cacheWrite
7135
+ cacheWrite: typeof raw?.cacheWrite === "number" ? raw.cacheWrite : DEFAULT_MODEL_COST.cacheWrite,
7136
+ ...typeof raw?.cacheWrite1h === "number" ? { cacheWrite1h: raw.cacheWrite1h } : {} // JOHNNESS_PATCH_USAGE_BILLING_91
7133
7137
  };
7134
7138
  }
7135
7139
  function resolveAnthropicDefaultAuthMode(cfg) {
@@ -13844,7 +13848,8 @@ const ModelDefinitionSchema = z.object({
13844
13848
  input: z.number().optional(),
13845
13849
  output: z.number().optional(),
13846
13850
  cacheRead: z.number().optional(),
13847
- cacheWrite: z.number().optional()
13851
+ cacheWrite: z.number().optional(),
13852
+ cacheWrite1h: z.number().nonnegative().optional() // JOHNNESS_PATCH_USAGE_BILLING_91
13848
13853
  }).strict().optional(),
13849
13854
  contextWindow: z.number().positive().optional(),
13850
13855
  maxTokens: z.number().positive().optional(),