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/plugin-sdk/dispatch-Cerq29sy.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";
@@ -25003,7 +25005,7 @@ function resolveModelAuthLabel(params) {
25003
25005
  });
25004
25006
  if (profile.type === "oauth") return `oauth${label ? ` (${label})` : ""}`;
25005
25007
  if (profile.type === "token") return `token${label ? ` (${label})` : ""}`;
25006
- return `api-key${label ? ` (${label})` : ""}`;
25008
+ return `api-key${label ? ` (${label})` : ""}${formatAuthProfileFallback(params.sessionEntry, profileId)}`;
25007
25009
  }
25008
25010
  const envKey = resolveEnvApiKey(providerKey);
25009
25011
  if (envKey?.apiKey) {
@@ -34654,21 +34656,7 @@ function hasNonzeroUsage(usage) {
34654
34656
  ].some((v) => typeof v === "number" && Number.isFinite(v) && v > 0);
34655
34657
  }
34656
34658
  function normalizeUsage(raw) {
34657
- if (!raw) return;
34658
- const rawInput = asFiniteNumber(raw.input ?? raw.inputTokens ?? raw.input_tokens ?? raw.promptTokens ?? raw.prompt_tokens);
34659
- const input = rawInput !== void 0 && rawInput < 0 ? 0 : rawInput;
34660
- const output = asFiniteNumber(raw.output ?? raw.outputTokens ?? raw.output_tokens ?? raw.completionTokens ?? raw.completion_tokens);
34661
- const cacheRead = asFiniteNumber(raw.cacheRead ?? raw.cache_read ?? raw.cache_read_input_tokens ?? raw.cached_tokens ?? raw.prompt_tokens_details?.cached_tokens);
34662
- const cacheWrite = asFiniteNumber(raw.cacheWrite ?? raw.cache_write ?? raw.cache_creation_input_tokens);
34663
- const total = asFiniteNumber(raw.total ?? raw.totalTokens ?? raw.total_tokens);
34664
- if (input === void 0 && output === void 0 && cacheRead === void 0 && cacheWrite === void 0 && total === void 0) return;
34665
- return {
34666
- input,
34667
- output,
34668
- cacheRead,
34669
- cacheWrite,
34670
- total
34671
- };
34659
+ return normalizeBillingUsage(raw);
34672
34660
  }
34673
34661
  function derivePromptTokens(usage) {
34674
34662
  if (!usage) return;
@@ -34722,6 +34710,7 @@ async function updateSessionStoreAfterAgentRun(params) {
34722
34710
  model: modelUsed
34723
34711
  });
34724
34712
  if (result.meta.agentMeta?.authProfileId) next.authProfileServed = result.meta.agentMeta.authProfileId; // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
34713
+ next.authProfileFallback = result.meta.agentMeta?.authProfileFallback ?? null; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
34725
34714
  if (isCliProvider(providerUsed, cfg)) {
34726
34715
  const cliSessionId = result.meta.agentMeta?.sessionId?.trim();
34727
34716
  if (cliSessionId) setCliSessionId(next, providerUsed, cliSessionId);
@@ -49202,62 +49191,19 @@ const readUsageFromSessionLog = (sessionId, sessionEntry, agentId, sessionKey, s
49202
49191
  } catch {
49203
49192
  return;
49204
49193
  }
49205
- if (!fs.existsSync(logPath)) return;
49206
- try {
49207
- const TAIL_BYTES = 8192;
49208
- const stat = fs.statSync(logPath);
49209
- const offset = Math.max(0, stat.size - TAIL_BYTES);
49210
- const buf = Buffer.alloc(Math.min(TAIL_BYTES, stat.size));
49211
- const fd = fs.openSync(logPath, "r");
49212
- try {
49213
- fs.readSync(fd, buf, 0, buf.length, offset);
49214
- } finally {
49215
- fs.closeSync(fd);
49216
- }
49217
- const tail = buf.toString("utf-8");
49218
- const lines = (offset > 0 ? tail.slice(tail.indexOf("\n") + 1) : tail).split(/\n+/);
49219
- let input = 0;
49220
- let output = 0;
49221
- let promptTokens = 0;
49222
- let model;
49223
- let lastUsage;
49224
- for (const line of lines) {
49225
- if (!line.trim()) continue;
49226
- try {
49227
- const parsed = JSON.parse(line);
49228
- const usage = normalizeUsage(parsed.message?.usage ?? parsed.usage);
49229
- if (usage) lastUsage = usage;
49230
- model = parsed.message?.model ?? parsed.model ?? model;
49231
- } catch {}
49232
- }
49233
- if (!lastUsage) return;
49234
- input = lastUsage.input ?? 0;
49235
- output = lastUsage.output ?? 0;
49236
- promptTokens = derivePromptTokens(lastUsage) ?? lastUsage.total ?? input + output;
49237
- const total = lastUsage.total ?? promptTokens + output;
49238
- if (promptTokens === 0 && total === 0) return;
49239
- return {
49240
- input,
49241
- output,
49242
- promptTokens,
49243
- total,
49244
- model
49245
- };
49246
- } catch {
49247
- return;
49248
- }
49194
+ return readLatestBillingUsage(logPath);
49249
49195
  };
49250
- const formatUsagePair = (input, output) => {
49251
- if (input == null && output == null) return null;
49252
- return `๐Ÿงฎ Tokens: ${typeof input === "number" ? formatTokenCount$1(input) : "?"} in / ${typeof output === "number" ? formatTokenCount$1(output) : "?"} out`;
49196
+ const formatUsagePair = (input, output, cacheRead, cacheWrite) => {
49197
+ if (input == null && output == null && cacheRead == null && cacheWrite == null) return null;
49198
+ const count = value => typeof value === "number" ? value.toLocaleString("en-US") : "?";
49199
+ return `๐Ÿงฎ Tokens: ${count((input ?? 0) + (cacheWrite ?? 0))} new in / ${count(cacheRead ?? 0)} cached / ${count(output)} out (last API call)`;
49253
49200
  };
49254
- const formatCacheLine = (input, cacheRead, cacheWrite) => {
49201
+ const formatCacheLine = (input, cacheRead, cacheWrite, usage) => {
49255
49202
  if (!cacheRead && !cacheWrite) return null;
49256
- if ((typeof cacheRead !== "number" || cacheRead <= 0) && (typeof cacheWrite !== "number" || cacheWrite <= 0)) return null;
49257
- const cachedLabel = typeof cacheRead === "number" ? formatTokenCount$1(cacheRead) : "0";
49258
- const newLabel = typeof cacheWrite === "number" ? formatTokenCount$1(cacheWrite) : "0";
49259
- const totalInput = (typeof cacheRead === "number" ? cacheRead : 0) + (typeof cacheWrite === "number" ? cacheWrite : 0) + (typeof input === "number" ? input : 0);
49260
- return `๐Ÿ—„๏ธ Cache: ${totalInput > 0 && typeof cacheRead === "number" ? Math.round(cacheRead / totalInput * 100) : 0}% hit ยท ${cachedLabel} cached, ${newLabel} new`;
49203
+ const total = (input ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0);
49204
+ const count = value => (value ?? 0).toLocaleString("en-US");
49205
+ const ttl = usage?.cacheWrite5m !== undefined || usage?.cacheWrite1h !== undefined ? ` (${count(usage.cacheWrite5m)} 5m / ${count(usage.cacheWrite1h)} 1h)` : "";
49206
+ return `๐Ÿ—„๏ธ Cache: ${total > 0 ? Math.round((cacheRead ?? 0) / total * 100) : 0}% hit ยท ${count(input)} uncached + ${count(cacheWrite)} written${ttl}`;
49261
49207
  };
49262
49208
  const formatMediaUnderstandingLine = (decisions) => {
49263
49209
  if (!decisions || decisions.length === 0) return null;
@@ -49336,10 +49282,14 @@ function buildStatusMessage(args) {
49336
49282
  let outputTokens = entry?.outputTokens;
49337
49283
  let cacheRead = entry?.cacheRead;
49338
49284
  let cacheWrite = entry?.cacheWrite;
49285
+ let billingUsage;
49339
49286
  let totalTokens = entry?.totalTokens ?? (entry?.inputTokens ?? 0) + (entry?.outputTokens ?? 0);
49340
- if (args.includeTranscriptUsage) {
49287
+ if (entry?.sessionId) { // Always use a coherent latest API call on both status paths.
49341
49288
  const logUsage = readUsageFromSessionLog(entry?.sessionId, entry, args.agentId, args.sessionKey, args.sessionStorePath);
49342
49289
  if (logUsage) {
49290
+ billingUsage = logUsage;
49291
+ cacheRead = logUsage.cacheRead ?? 0;
49292
+ cacheWrite = logUsage.cacheWrite ?? 0;
49343
49293
  const candidate = logUsage.promptTokens || logUsage.total;
49344
49294
  if (!totalTokens || totalTokens === 0 || candidate > totalTokens) totalTokens = candidate;
49345
49295
  if (!entry?.model && logUsage.model) {
@@ -49358,8 +49308,10 @@ function buildStatusMessage(args) {
49358
49308
  model: logUsage.model,
49359
49309
  fallbackContextTokens: contextTokens ?? void 0
49360
49310
  }) ?? contextTokens;
49361
- if (!inputTokens || inputTokens === 0) inputTokens = logUsage.input;
49362
- if (!outputTokens || outputTokens === 0) outputTokens = logUsage.output;
49311
+ inputTokens = logUsage.input ?? 0;
49312
+ outputTokens = logUsage.output ?? 0;
49313
+ if (logUsage.provider) activeProvider = logUsage.provider;
49314
+ if (logUsage.model) activeModel = logUsage.model;
49363
49315
  }
49364
49316
  }
49365
49317
  const thinkLevel = args.resolvedThink ?? args.sessionEntry?.thinkingLevel ?? args.agent?.thinkingDefault ?? "off";
@@ -49395,21 +49347,14 @@ function buildStatusMessage(args) {
49395
49347
  state: entry
49396
49348
  });
49397
49349
  const effectiveCostAuthMode = fallbackState.active ? activeAuthMode : selectedAuthMode ?? activeAuthMode;
49398
- const showCost = effectiveCostAuthMode === "api-key" || effectiveCostAuthMode === "mixed";
49350
+ const showCost = billingUsage?.cost?.total > 0 || effectiveCostAuthMode === "api-key" || effectiveCostAuthMode === "mixed";
49399
49351
  const costConfig = showCost ? resolveModelCostConfig({
49400
49352
  provider: activeProvider,
49401
49353
  model: activeModel,
49402
49354
  config: args.config
49403
49355
  }) : void 0;
49404
- const hasUsage = typeof inputTokens === "number" || typeof outputTokens === "number";
49405
- const cost = showCost && hasUsage ? estimateUsageCost({
49406
- usage: {
49407
- input: inputTokens ?? void 0,
49408
- output: outputTokens ?? void 0
49409
- },
49410
- cost: costConfig
49411
- }) : void 0;
49412
- const costLabel = showCost && hasUsage ? formatUsd(cost) : void 0;
49356
+ const hasUsage = [inputTokens, outputTokens, cacheRead, cacheWrite].some(value => typeof value === "number");
49357
+ billingUsage ??= { input: inputTokens, output: outputTokens, cacheRead, cacheWrite };
49413
49358
  const selectedAuthLabel = selectedAuthLabelValue ? ` ยท ๐Ÿ”‘ ${selectedAuthLabelValue}` : "";
49414
49359
  const channelModelNote = (() => {
49415
49360
  if (!args.config || !entry) return;
@@ -49441,9 +49386,9 @@ function buildStatusMessage(args) {
49441
49386
  const fallbackLine = fallbackState.active ? `โ†ช๏ธ Fallback: ${activeModelLabel}${showFallbackAuth ? ` ยท ๐Ÿ”‘ ${activeAuthLabelValue}` : ""} (${fallbackState.reason ?? "selected model unavailable"})` : null;
49442
49387
  const commit = resolveCommitHash();
49443
49388
  const versionLine = `๐Ÿฆž Johnness ${VERSION}${commit ? ` (${commit})` : ""}`;
49444
- const usagePair = formatUsagePair(inputTokens, outputTokens);
49445
- const cacheLine = formatCacheLine(inputTokens, cacheRead, cacheWrite);
49446
- const costLine = costLabel ? `๐Ÿ’ต Cost: ${costLabel}` : null;
49389
+ const usagePair = formatUsagePair(inputTokens, outputTokens, cacheRead, cacheWrite);
49390
+ const cacheLine = formatCacheLine(inputTokens, cacheRead, cacheWrite, billingUsage);
49391
+ const costLine = showCost && hasUsage ? formatBillingCost(billingUsage, costConfig) : null;
49447
49392
  const usageCostLine = usagePair && costLine ? `${usagePair} ยท ${costLine}` : usagePair ?? costLine;
49448
49393
  const mediaLine = formatMediaUnderstandingLine(args.mediaDecisions);
49449
49394
  const voiceLine = formatVoiceModeLine(args.config, args.sessionEntry);
@@ -81448,6 +81393,8 @@ function normalizeAssistantUsageSnapshot(usage) {
81448
81393
  cacheRead,
81449
81394
  cacheWrite,
81450
81395
  totalTokens,
81396
+ ...normalized.cacheWrite5m !== undefined ? { cacheWrite5m: normalized.cacheWrite5m } : {},
81397
+ ...normalized.cacheWrite1h !== undefined ? { cacheWrite1h: normalized.cacheWrite1h } : {},
81451
81398
  ...cost ? { cost } : {}
81452
81399
  };
81453
81400
  }
@@ -88635,6 +88582,7 @@ async function runEmbeddedPiAgent(params) {
88635
88582
  });
88636
88583
  if (lockedProfileId && !profileOrder.includes(lockedProfileId)) throw new Error(`Auth profile "${lockedProfileId}" is not configured for ${provider}.`);
88637
88584
  const profileCandidates = lockedProfileId ? [lockedProfileId] : profileOrder.length > 0 ? profileOrder : [void 0];
88585
+ const subscriptionAuth = createSubscriptionAuthTracker({ provider, model: modelId, store: authStore, preferredProfileId, lockedProfileId }); // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
88638
88586
  let profileIndex = 0;
88639
88587
  const initialThinkLevel = params.thinkLevel ?? "off";
88640
88588
  let thinkLevel = initialThinkLevel;
@@ -88766,7 +88714,8 @@ async function runEmbeddedPiAgent(params) {
88766
88714
  } else authStorage.setRuntimeApiKey(model.provider, apiKeyInfo.apiKey);
88767
88715
  lastProfileId = apiKeyInfo.profileId;
88768
88716
  };
88769
- const advanceAuthProfile = async () => {
88717
+ const advanceAuthProfile = async (reason) => {
88718
+ subscriptionAuth.failed(profileCandidates[profileIndex], reason);
88770
88719
  if (lockedProfileId) return false;
88771
88720
  let nextIndex = profileIndex + 1;
88772
88721
  while (nextIndex < profileCandidates.length) {
@@ -88816,7 +88765,7 @@ async function runEmbeddedPiAgent(params) {
88816
88765
  allInCooldown: false,
88817
88766
  error: err
88818
88767
  });
88819
- if (!await advanceAuthProfile()) throwAuthProfileFailover({
88768
+ if (!await advanceAuthProfile(/refresh/i.test(String(err)) ? "oauth_refresh_failed" : "credential_unavailable")) throwAuthProfileFailover({
88820
88769
  allInCooldown: false,
88821
88770
  error: err
88822
88771
  });
@@ -89185,7 +89134,7 @@ async function runEmbeddedPiAgent(params) {
89185
89134
  reason: promptProfileFailureReason
89186
89135
  });
89187
89136
  const promptFailoverFailure = isFailoverErrorMessage(errorText);
89188
- if (promptFailoverFailure && promptFailoverReason !== "timeout" && await advanceAuthProfile()) {
89137
+ if (promptFailoverFailure && promptFailoverReason !== "timeout" && await advanceAuthProfile(promptFailoverReason)) {
89189
89138
  await maybeBackoffBeforeOverloadFailover(promptFailoverReason);
89190
89139
  continue;
89191
89140
  }
@@ -89248,7 +89197,7 @@ async function runEmbeddedPiAgent(params) {
89248
89197
  if (timedOut && !isProbeSession) log$7.warn(`Profile ${lastProfileId} timed out. Trying next account...`);
89249
89198
  if (cloudCodeAssistFormatError) log$7.warn(`Profile ${lastProfileId} hit Cloud Code Assist format error. Tool calls will be sanitized on retry.`);
89250
89199
  }
89251
- if (await advanceAuthProfile()) {
89200
+ if (await advanceAuthProfile(timedOut ? "timeout" : assistantFailoverReason)) {
89252
89201
  await maybeBackoffBeforeOverloadFailover(assistantFailoverReason);
89253
89202
  continue;
89254
89203
  }
@@ -89282,6 +89231,7 @@ async function runEmbeddedPiAgent(params) {
89282
89231
  lastCallUsage: lastCallUsage ?? void 0,
89283
89232
  promptTokens,
89284
89233
  compactionCount: autoCompactionCount > 0 ? autoCompactionCount : void 0,
89234
+ authProfileFallback: subscriptionAuth.result(lastProfileId), // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
89285
89235
  authProfileId: lastProfileId // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: profile that served this turn
89286
89236
  };
89287
89237
  const payloads = buildEmbeddedRunPayloads({
@@ -100676,6 +100626,7 @@ async function persistSessionUsageUpdate(params) {
100676
100626
  modelProvider: params.providerUsed ?? entry.modelProvider,
100677
100627
  model: params.modelUsed ?? entry.model,
100678
100628
  authProfileServed: params.authProfileServed ?? entry.authProfileServed, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
100629
+ authProfileFallback: params.authProfileFallback ?? null, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
100679
100630
  contextTokens: resolvedContextTokens,
100680
100631
  systemPromptReport: params.systemPromptReport ?? entry.systemPromptReport,
100681
100632
  updatedAt: Date.now()
@@ -100956,6 +100907,7 @@ function createFollowupRunner(params) {
100956
100907
  modelUsed,
100957
100908
  providerUsed: fallbackProvider,
100958
100909
  authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
100910
+ authProfileFallback: runResult.meta?.agentMeta?.authProfileFallback, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
100959
100911
  contextTokensUsed,
100960
100912
  systemPromptReport: runResult.meta?.systemPromptReport,
100961
100913
  logLabel: "followup"
@@ -101294,6 +101246,7 @@ async function runReplyAgent(params) {
101294
101246
  modelUsed,
101295
101247
  providerUsed,
101296
101248
  authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
101249
+ authProfileFallback: runResult.meta?.agentMeta?.authProfileFallback, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
101297
101250
  contextTokensUsed,
101298
101251
  systemPromptReport: runResult.meta?.systemPromptReport,
101299
101252
  cliSessionId
@@ -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/plugin-sdk/dispatch-Cndjtt0g.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";
@@ -24684,7 +24686,7 @@ function resolveModelAuthLabel(params) {
24684
24686
  });
24685
24687
  if (profile.type === "oauth") return `oauth${label ? ` (${label})` : ""}`;
24686
24688
  if (profile.type === "token") return `token${label ? ` (${label})` : ""}`;
24687
- return `api-key${label ? ` (${label})` : ""}`;
24689
+ return `api-key${label ? ` (${label})` : ""}${formatAuthProfileFallback(params.sessionEntry, profileId)}`;
24688
24690
  }
24689
24691
  const envKey = resolveEnvApiKey(providerKey);
24690
24692
  if (envKey?.apiKey) {
@@ -34325,21 +34327,7 @@ function hasNonzeroUsage(usage) {
34325
34327
  ].some((v) => typeof v === "number" && Number.isFinite(v) && v > 0);
34326
34328
  }
34327
34329
  function normalizeUsage(raw) {
34328
- if (!raw) return;
34329
- const rawInput = asFiniteNumber(raw.input ?? raw.inputTokens ?? raw.input_tokens ?? raw.promptTokens ?? raw.prompt_tokens);
34330
- const input = rawInput !== void 0 && rawInput < 0 ? 0 : rawInput;
34331
- const output = asFiniteNumber(raw.output ?? raw.outputTokens ?? raw.output_tokens ?? raw.completionTokens ?? raw.completion_tokens);
34332
- const cacheRead = asFiniteNumber(raw.cacheRead ?? raw.cache_read ?? raw.cache_read_input_tokens ?? raw.cached_tokens ?? raw.prompt_tokens_details?.cached_tokens);
34333
- const cacheWrite = asFiniteNumber(raw.cacheWrite ?? raw.cache_write ?? raw.cache_creation_input_tokens);
34334
- const total = asFiniteNumber(raw.total ?? raw.totalTokens ?? raw.total_tokens);
34335
- if (input === void 0 && output === void 0 && cacheRead === void 0 && cacheWrite === void 0 && total === void 0) return;
34336
- return {
34337
- input,
34338
- output,
34339
- cacheRead,
34340
- cacheWrite,
34341
- total
34342
- };
34330
+ return normalizeBillingUsage(raw);
34343
34331
  }
34344
34332
  function derivePromptTokens(usage) {
34345
34333
  if (!usage) return;
@@ -34393,6 +34381,7 @@ async function updateSessionStoreAfterAgentRun(params) {
34393
34381
  model: modelUsed
34394
34382
  });
34395
34383
  if (result.meta.agentMeta?.authProfileId) next.authProfileServed = result.meta.agentMeta.authProfileId; // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
34384
+ next.authProfileFallback = result.meta.agentMeta?.authProfileFallback ?? null; // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
34396
34385
  if (isCliProvider(providerUsed, cfg)) {
34397
34386
  const cliSessionId = result.meta.agentMeta?.sessionId?.trim();
34398
34387
  if (cliSessionId) setCliSessionId(next, providerUsed, cliSessionId);
@@ -48852,62 +48841,19 @@ const readUsageFromSessionLog = (sessionId, sessionEntry, agentId, sessionKey, s
48852
48841
  } catch {
48853
48842
  return;
48854
48843
  }
48855
- if (!fs.existsSync(logPath)) return;
48856
- try {
48857
- const TAIL_BYTES = 8192;
48858
- const stat = fs.statSync(logPath);
48859
- const offset = Math.max(0, stat.size - TAIL_BYTES);
48860
- const buf = Buffer.alloc(Math.min(TAIL_BYTES, stat.size));
48861
- const fd = fs.openSync(logPath, "r");
48862
- try {
48863
- fs.readSync(fd, buf, 0, buf.length, offset);
48864
- } finally {
48865
- fs.closeSync(fd);
48866
- }
48867
- const tail = buf.toString("utf-8");
48868
- const lines = (offset > 0 ? tail.slice(tail.indexOf("\n") + 1) : tail).split(/\n+/);
48869
- let input = 0;
48870
- let output = 0;
48871
- let promptTokens = 0;
48872
- let model;
48873
- let lastUsage;
48874
- for (const line of lines) {
48875
- if (!line.trim()) continue;
48876
- try {
48877
- const parsed = JSON.parse(line);
48878
- const usage = normalizeUsage(parsed.message?.usage ?? parsed.usage);
48879
- if (usage) lastUsage = usage;
48880
- model = parsed.message?.model ?? parsed.model ?? model;
48881
- } catch {}
48882
- }
48883
- if (!lastUsage) return;
48884
- input = lastUsage.input ?? 0;
48885
- output = lastUsage.output ?? 0;
48886
- promptTokens = derivePromptTokens(lastUsage) ?? lastUsage.total ?? input + output;
48887
- const total = lastUsage.total ?? promptTokens + output;
48888
- if (promptTokens === 0 && total === 0) return;
48889
- return {
48890
- input,
48891
- output,
48892
- promptTokens,
48893
- total,
48894
- model
48895
- };
48896
- } catch {
48897
- return;
48898
- }
48844
+ return readLatestBillingUsage(logPath);
48899
48845
  };
48900
- const formatUsagePair = (input, output) => {
48901
- if (input == null && output == null) return null;
48902
- return `๐Ÿงฎ Tokens: ${typeof input === "number" ? formatTokenCount$1(input) : "?"} in / ${typeof output === "number" ? formatTokenCount$1(output) : "?"} out`;
48846
+ const formatUsagePair = (input, output, cacheRead, cacheWrite) => {
48847
+ if (input == null && output == null && cacheRead == null && cacheWrite == null) return null;
48848
+ const count = value => typeof value === "number" ? value.toLocaleString("en-US") : "?";
48849
+ return `๐Ÿงฎ Tokens: ${count((input ?? 0) + (cacheWrite ?? 0))} new in / ${count(cacheRead ?? 0)} cached / ${count(output)} out (last API call)`;
48903
48850
  };
48904
- const formatCacheLine = (input, cacheRead, cacheWrite) => {
48851
+ const formatCacheLine = (input, cacheRead, cacheWrite, usage) => {
48905
48852
  if (!cacheRead && !cacheWrite) return null;
48906
- if ((typeof cacheRead !== "number" || cacheRead <= 0) && (typeof cacheWrite !== "number" || cacheWrite <= 0)) return null;
48907
- const cachedLabel = typeof cacheRead === "number" ? formatTokenCount$1(cacheRead) : "0";
48908
- const newLabel = typeof cacheWrite === "number" ? formatTokenCount$1(cacheWrite) : "0";
48909
- const totalInput = (typeof cacheRead === "number" ? cacheRead : 0) + (typeof cacheWrite === "number" ? cacheWrite : 0) + (typeof input === "number" ? input : 0);
48910
- return `๐Ÿ—„๏ธ Cache: ${totalInput > 0 && typeof cacheRead === "number" ? Math.round(cacheRead / totalInput * 100) : 0}% hit ยท ${cachedLabel} cached, ${newLabel} new`;
48853
+ const total = (input ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0);
48854
+ const count = value => (value ?? 0).toLocaleString("en-US");
48855
+ const ttl = usage?.cacheWrite5m !== undefined || usage?.cacheWrite1h !== undefined ? ` (${count(usage.cacheWrite5m)} 5m / ${count(usage.cacheWrite1h)} 1h)` : "";
48856
+ return `๐Ÿ—„๏ธ Cache: ${total > 0 ? Math.round((cacheRead ?? 0) / total * 100) : 0}% hit ยท ${count(input)} uncached + ${count(cacheWrite)} written${ttl}`;
48911
48857
  };
48912
48858
  const formatMediaUnderstandingLine = (decisions) => {
48913
48859
  if (!decisions || decisions.length === 0) return null;
@@ -48986,10 +48932,14 @@ function buildStatusMessage(args) {
48986
48932
  let outputTokens = entry?.outputTokens;
48987
48933
  let cacheRead = entry?.cacheRead;
48988
48934
  let cacheWrite = entry?.cacheWrite;
48935
+ let billingUsage;
48989
48936
  let totalTokens = entry?.totalTokens ?? (entry?.inputTokens ?? 0) + (entry?.outputTokens ?? 0);
48990
- if (args.includeTranscriptUsage) {
48937
+ if (entry?.sessionId) { // Always use a coherent latest API call on both status paths.
48991
48938
  const logUsage = readUsageFromSessionLog(entry?.sessionId, entry, args.agentId, args.sessionKey, args.sessionStorePath);
48992
48939
  if (logUsage) {
48940
+ billingUsage = logUsage;
48941
+ cacheRead = logUsage.cacheRead ?? 0;
48942
+ cacheWrite = logUsage.cacheWrite ?? 0;
48993
48943
  const candidate = logUsage.promptTokens || logUsage.total;
48994
48944
  if (!totalTokens || totalTokens === 0 || candidate > totalTokens) totalTokens = candidate;
48995
48945
  if (!entry?.model && logUsage.model) {
@@ -49008,8 +48958,10 @@ function buildStatusMessage(args) {
49008
48958
  model: logUsage.model,
49009
48959
  fallbackContextTokens: contextTokens ?? void 0
49010
48960
  }) ?? contextTokens;
49011
- if (!inputTokens || inputTokens === 0) inputTokens = logUsage.input;
49012
- if (!outputTokens || outputTokens === 0) outputTokens = logUsage.output;
48961
+ inputTokens = logUsage.input ?? 0;
48962
+ outputTokens = logUsage.output ?? 0;
48963
+ if (logUsage.provider) activeProvider = logUsage.provider;
48964
+ if (logUsage.model) activeModel = logUsage.model;
49013
48965
  }
49014
48966
  }
49015
48967
  const thinkLevel = args.resolvedThink ?? args.sessionEntry?.thinkingLevel ?? args.agent?.thinkingDefault ?? "off";
@@ -49045,21 +48997,14 @@ function buildStatusMessage(args) {
49045
48997
  state: entry
49046
48998
  });
49047
48999
  const effectiveCostAuthMode = fallbackState.active ? activeAuthMode : selectedAuthMode ?? activeAuthMode;
49048
- const showCost = effectiveCostAuthMode === "api-key" || effectiveCostAuthMode === "mixed";
49000
+ const showCost = billingUsage?.cost?.total > 0 || effectiveCostAuthMode === "api-key" || effectiveCostAuthMode === "mixed";
49049
49001
  const costConfig = showCost ? resolveModelCostConfig({
49050
49002
  provider: activeProvider,
49051
49003
  model: activeModel,
49052
49004
  config: args.config
49053
49005
  }) : void 0;
49054
- const hasUsage = typeof inputTokens === "number" || typeof outputTokens === "number";
49055
- const cost = showCost && hasUsage ? estimateUsageCost({
49056
- usage: {
49057
- input: inputTokens ?? void 0,
49058
- output: outputTokens ?? void 0
49059
- },
49060
- cost: costConfig
49061
- }) : void 0;
49062
- const costLabel = showCost && hasUsage ? formatUsd(cost) : void 0;
49006
+ const hasUsage = [inputTokens, outputTokens, cacheRead, cacheWrite].some(value => typeof value === "number");
49007
+ billingUsage ??= { input: inputTokens, output: outputTokens, cacheRead, cacheWrite };
49063
49008
  const selectedAuthLabel = selectedAuthLabelValue ? ` ยท ๐Ÿ”‘ ${selectedAuthLabelValue}` : "";
49064
49009
  const channelModelNote = (() => {
49065
49010
  if (!args.config || !entry) return;
@@ -49091,9 +49036,9 @@ function buildStatusMessage(args) {
49091
49036
  const fallbackLine = fallbackState.active ? `โ†ช๏ธ Fallback: ${activeModelLabel}${showFallbackAuth ? ` ยท ๐Ÿ”‘ ${activeAuthLabelValue}` : ""} (${fallbackState.reason ?? "selected model unavailable"})` : null;
49092
49037
  const commit = resolveCommitHash();
49093
49038
  const versionLine = `๐Ÿฆž Johnness ${VERSION}${commit ? ` (${commit})` : ""}`;
49094
- const usagePair = formatUsagePair(inputTokens, outputTokens);
49095
- const cacheLine = formatCacheLine(inputTokens, cacheRead, cacheWrite);
49096
- const costLine = costLabel ? `๐Ÿ’ต Cost: ${costLabel}` : null;
49039
+ const usagePair = formatUsagePair(inputTokens, outputTokens, cacheRead, cacheWrite);
49040
+ const cacheLine = formatCacheLine(inputTokens, cacheRead, cacheWrite, billingUsage);
49041
+ const costLine = showCost && hasUsage ? formatBillingCost(billingUsage, costConfig) : null;
49097
49042
  const usageCostLine = usagePair && costLine ? `${usagePair} ยท ${costLine}` : usagePair ?? costLine;
49098
49043
  const mediaLine = formatMediaUnderstandingLine(args.mediaDecisions);
49099
49044
  const voiceLine = formatVoiceModeLine(args.config, args.sessionEntry);
@@ -81175,6 +81120,8 @@ function normalizeAssistantUsageSnapshot(usage) {
81175
81120
  cacheRead,
81176
81121
  cacheWrite,
81177
81122
  totalTokens,
81123
+ ...normalized.cacheWrite5m !== undefined ? { cacheWrite5m: normalized.cacheWrite5m } : {},
81124
+ ...normalized.cacheWrite1h !== undefined ? { cacheWrite1h: normalized.cacheWrite1h } : {},
81178
81125
  ...cost ? { cost } : {}
81179
81126
  };
81180
81127
  }
@@ -88362,6 +88309,7 @@ async function runEmbeddedPiAgent(params) {
88362
88309
  });
88363
88310
  if (lockedProfileId && !profileOrder.includes(lockedProfileId)) throw new Error(`Auth profile "${lockedProfileId}" is not configured for ${provider}.`);
88364
88311
  const profileCandidates = lockedProfileId ? [lockedProfileId] : profileOrder.length > 0 ? profileOrder : [void 0];
88312
+ const subscriptionAuth = createSubscriptionAuthTracker({ provider, model: modelId, store: authStore, preferredProfileId, lockedProfileId }); // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
88365
88313
  let profileIndex = 0;
88366
88314
  const initialThinkLevel = params.thinkLevel ?? "off";
88367
88315
  let thinkLevel = initialThinkLevel;
@@ -88493,7 +88441,8 @@ async function runEmbeddedPiAgent(params) {
88493
88441
  } else authStorage.setRuntimeApiKey(model.provider, apiKeyInfo.apiKey);
88494
88442
  lastProfileId = apiKeyInfo.profileId;
88495
88443
  };
88496
- const advanceAuthProfile = async () => {
88444
+ const advanceAuthProfile = async (reason) => {
88445
+ subscriptionAuth.failed(profileCandidates[profileIndex], reason);
88497
88446
  if (lockedProfileId) return false;
88498
88447
  let nextIndex = profileIndex + 1;
88499
88448
  while (nextIndex < profileCandidates.length) {
@@ -88543,7 +88492,7 @@ async function runEmbeddedPiAgent(params) {
88543
88492
  allInCooldown: false,
88544
88493
  error: err
88545
88494
  });
88546
- if (!await advanceAuthProfile()) throwAuthProfileFailover({
88495
+ if (!await advanceAuthProfile(/refresh/i.test(String(err)) ? "oauth_refresh_failed" : "credential_unavailable")) throwAuthProfileFailover({
88547
88496
  allInCooldown: false,
88548
88497
  error: err
88549
88498
  });
@@ -88912,7 +88861,7 @@ async function runEmbeddedPiAgent(params) {
88912
88861
  reason: promptProfileFailureReason
88913
88862
  });
88914
88863
  const promptFailoverFailure = isFailoverErrorMessage(errorText);
88915
- if (promptFailoverFailure && promptFailoverReason !== "timeout" && await advanceAuthProfile()) {
88864
+ if (promptFailoverFailure && promptFailoverReason !== "timeout" && await advanceAuthProfile(promptFailoverReason)) {
88916
88865
  await maybeBackoffBeforeOverloadFailover(promptFailoverReason);
88917
88866
  continue;
88918
88867
  }
@@ -88975,7 +88924,7 @@ async function runEmbeddedPiAgent(params) {
88975
88924
  if (timedOut && !isProbeSession) log$7.warn(`Profile ${lastProfileId} timed out. Trying next account...`);
88976
88925
  if (cloudCodeAssistFormatError) log$7.warn(`Profile ${lastProfileId} hit Cloud Code Assist format error. Tool calls will be sanitized on retry.`);
88977
88926
  }
88978
- if (await advanceAuthProfile()) {
88927
+ if (await advanceAuthProfile(timedOut ? "timeout" : assistantFailoverReason)) {
88979
88928
  await maybeBackoffBeforeOverloadFailover(assistantFailoverReason);
88980
88929
  continue;
88981
88930
  }
@@ -89009,6 +88958,7 @@ async function runEmbeddedPiAgent(params) {
89009
88958
  lastCallUsage: lastCallUsage ?? void 0,
89010
88959
  promptTokens,
89011
88960
  compactionCount: autoCompactionCount > 0 ? autoCompactionCount : void 0,
88961
+ authProfileFallback: subscriptionAuth.result(lastProfileId), // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
89012
88962
  authProfileId: lastProfileId // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89: profile that served this turn
89013
88963
  };
89014
88964
  const payloads = buildEmbeddedRunPayloads({
@@ -100403,6 +100353,7 @@ async function persistSessionUsageUpdate(params) {
100403
100353
  modelProvider: params.providerUsed ?? entry.modelProvider,
100404
100354
  model: params.modelUsed ?? entry.model,
100405
100355
  authProfileServed: params.authProfileServed ?? entry.authProfileServed, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
100356
+ authProfileFallback: params.authProfileFallback ?? null, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
100406
100357
  contextTokens: resolvedContextTokens,
100407
100358
  systemPromptReport: params.systemPromptReport ?? entry.systemPromptReport,
100408
100359
  updatedAt: Date.now()
@@ -100683,6 +100634,7 @@ function createFollowupRunner(params) {
100683
100634
  modelUsed,
100684
100635
  providerUsed: fallbackProvider,
100685
100636
  authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
100637
+ authProfileFallback: runResult.meta?.agentMeta?.authProfileFallback, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
100686
100638
  contextTokensUsed,
100687
100639
  systemPromptReport: runResult.meta?.systemPromptReport,
100688
100640
  logLabel: "followup"
@@ -101021,6 +100973,7 @@ async function runReplyAgent(params) {
101021
100973
  modelUsed,
101022
100974
  providerUsed,
101023
100975
  authProfileServed: runResult.meta?.agentMeta?.authProfileId, // JOHNNESS_PATCH_SUBSCRIPTION_ACTIVATE_89
100976
+ authProfileFallback: runResult.meta?.agentMeta?.authProfileFallback, // JOHNNESS_PATCH_SUBSCRIPTION_RUNTIME_92
101024
100977
  contextTokensUsed,
101025
100978
  systemPromptReport: runResult.meta?.systemPromptReport,
101026
100979
  cliSessionId