token-harness 0.1.18 → 0.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/token-harness.mjs CHANGED
@@ -656,6 +656,65 @@ function parseLocalUsage(value3) {
656
656
  }
657
657
  return { inputTokens, cacheCreationTokens, cacheReadTokens, outputTokens, totalTokens };
658
658
  }
659
+ function parseTaskBenchmarkCcrUsage(value3) {
660
+ if (value3 === null)
661
+ return null;
662
+ const row2 = record(value3);
663
+ if (row2 === null || row2["schemaVersion"] !== 1)
664
+ return void 0;
665
+ const status = row2["status"];
666
+ const sessionCount = finiteNonNegative(row2["sessionCount"]);
667
+ const observedSessionCount = finiteNonNegative(row2["observedSessionCount"]);
668
+ const requestCount = finiteNonNegative(row2["requestCount"]);
669
+ const inputTokens = finiteNonNegative(row2["inputTokens"]);
670
+ const outputTokens = finiteNonNegative(row2["outputTokens"]);
671
+ const cacheReadTokens = finiteNonNegative(row2["cacheReadTokens"]);
672
+ const cacheWriteTokens = finiteNonNegative(row2["cacheWriteTokens"]);
673
+ const totalTokens = finiteNonNegative(row2["totalTokens"]);
674
+ const recordedCostUsd = nullableFiniteNonNegative(row2["recordedCostUsd"]);
675
+ if (status !== "observed" && status !== "partial" && status !== "unavailable" || sessionCount === null || observedSessionCount === null || requestCount === null || inputTokens === null || outputTokens === null || cacheReadTokens === null || cacheWriteTokens === null || totalTokens === null || recordedCostUsd === void 0 || observedSessionCount > sessionCount || !Array.isArray(row2["byModel"])) {
676
+ return void 0;
677
+ }
678
+ const byModel = [];
679
+ for (const item of row2["byModel"]) {
680
+ const modelRow = record(item);
681
+ if (modelRow === null || typeof modelRow["model"] !== "string" || !/^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(modelRow["model"]))
682
+ return void 0;
683
+ const modelRequestCount = finiteNonNegative(modelRow["requestCount"]);
684
+ const modelInputTokens = finiteNonNegative(modelRow["inputTokens"]);
685
+ const modelOutputTokens = finiteNonNegative(modelRow["outputTokens"]);
686
+ const modelCacheReadTokens = finiteNonNegative(modelRow["cacheReadTokens"]);
687
+ const modelCacheWriteTokens = finiteNonNegative(modelRow["cacheWriteTokens"]);
688
+ const modelTotalTokens = finiteNonNegative(modelRow["totalTokens"]);
689
+ const modelCost = nullableFiniteNonNegative(modelRow["recordedCostUsd"]);
690
+ if (modelRequestCount === null || modelInputTokens === null || modelOutputTokens === null || modelCacheReadTokens === null || modelCacheWriteTokens === null || modelTotalTokens === null || modelCost === void 0)
691
+ return void 0;
692
+ byModel.push({
693
+ model: modelRow["model"],
694
+ requestCount: modelRequestCount,
695
+ inputTokens: modelInputTokens,
696
+ outputTokens: modelOutputTokens,
697
+ cacheReadTokens: modelCacheReadTokens,
698
+ cacheWriteTokens: modelCacheWriteTokens,
699
+ totalTokens: modelTotalTokens,
700
+ recordedCostUsd: modelCost
701
+ });
702
+ }
703
+ return {
704
+ schemaVersion: 1,
705
+ status,
706
+ sessionCount,
707
+ observedSessionCount,
708
+ requestCount,
709
+ inputTokens,
710
+ outputTokens,
711
+ cacheReadTokens,
712
+ cacheWriteTokens,
713
+ totalTokens,
714
+ recordedCostUsd,
715
+ byModel
716
+ };
717
+ }
659
718
  function parseLocalSessionSnapshot(value3) {
660
719
  const row2 = record(value3);
661
720
  if (row2 === null)
@@ -842,7 +901,9 @@ function parseTaskBenchmarkReceipt(value3) {
842
901
  const contextAtStart = hasContextAtStart ? parseTaskBenchmarkContextSnapshot(row2["contextAtStart"]) : void 0;
843
902
  const hasContextAtFinish = Object.hasOwn(row2, "contextAtFinish");
844
903
  const contextAtFinish = hasContextAtFinish ? parseTaskBenchmarkContextSnapshot(row2["contextAtFinish"]) : void 0;
845
- if (typeof benchmarkId !== "string" || benchmarkId === "" || typeof variant !== "string" || !isTaskBenchmarkVariant(variant) || typeof taskClass !== "string" || !isTaskClass(taskClass) || typeof harnessId2 !== "string" || !isHarnessId(harnessId2) || model === void 0 || reasoningEffort === void 0 || verbosity === void 0 || !validInstant(startedAt) || !validInstant(completedAt) || Date.parse(completedAt) < Date.parse(startedAt) || usageBefore === null || usageAfter === null || localUsage === void 0 || outcome2 === null || hasBoundaryPolicy && policyAtFinish === void 0 || hasContextAtStart && contextAtStart === void 0 || hasContextAtFinish && contextAtFinish === void 0) {
904
+ const hasCcrUsage = Object.hasOwn(row2, "ccrUsage");
905
+ const ccrUsage = hasCcrUsage ? parseTaskBenchmarkCcrUsage(row2["ccrUsage"]) : void 0;
906
+ if (typeof benchmarkId !== "string" || benchmarkId === "" || typeof variant !== "string" || !isTaskBenchmarkVariant(variant) || typeof taskClass !== "string" || !isTaskClass(taskClass) || typeof harnessId2 !== "string" || !isHarnessId(harnessId2) || model === void 0 || reasoningEffort === void 0 || verbosity === void 0 || !validInstant(startedAt) || !validInstant(completedAt) || Date.parse(completedAt) < Date.parse(startedAt) || usageBefore === null || usageAfter === null || localUsage === void 0 || outcome2 === null || hasBoundaryPolicy && policyAtFinish === void 0 || hasContextAtStart && contextAtStart === void 0 || hasContextAtFinish && contextAtFinish === void 0 || hasCcrUsage && ccrUsage === void 0) {
846
907
  return {
847
908
  ok: false,
848
909
  reason: "invalid-shape",
@@ -868,7 +929,8 @@ function parseTaskBenchmarkReceipt(value3) {
868
929
  outcome: outcome2,
869
930
  ...hasContextAtStart ? { contextAtStart: contextAtStart ?? null } : {},
870
931
  ...hasContextAtFinish ? { contextAtFinish: contextAtFinish ?? null } : {},
871
- ...hasBoundaryPolicy ? { policyAtFinish: policyAtFinish ?? null } : {}
932
+ ...hasBoundaryPolicy ? { policyAtFinish: policyAtFinish ?? null } : {},
933
+ ...hasCcrUsage ? { ccrUsage: ccrUsage ?? null } : {}
872
934
  }
873
935
  };
874
936
  }
@@ -890,6 +952,7 @@ function completeTaskBenchmarkCapture(capture, input) {
890
952
  ...capture.contextAtStart !== void 0 ? { contextAtStart: capture.contextAtStart } : {},
891
953
  ...input.contextAtFinish !== void 0 ? { contextAtFinish: input.contextAtFinish } : {},
892
954
  ...input.policyAtFinish !== void 0 ? { policyAtFinish: input.policyAtFinish } : {},
955
+ ...input.ccrUsage !== void 0 ? { ccrUsage: input.ccrUsage } : {},
893
956
  outcome: {
894
957
  qualityGate: input.qualityGate,
895
958
  attempts: input.attempts,
@@ -973,7 +1036,7 @@ function pairedQuota(baseline, optimized) {
973
1036
  function result(benchmarkId, verdict, basis, evidenceLevel, quota, reasons) {
974
1037
  return { benchmarkId, verdict, basis, evidenceLevel, quota, reasons };
975
1038
  }
976
- function compareTaskBenchmarkReceipts(baseline, optimized) {
1039
+ function compareTaskBenchmarkReceiptsCore(baseline, optimized) {
977
1040
  const reasons = [];
978
1041
  if (baseline.benchmarkId !== optimized.benchmarkId || baseline.taskClass !== optimized.taskClass || baseline.harnessId !== optimized.harnessId || baseline.variant !== "baseline" || optimized.variant !== "optimized") {
979
1042
  return result(baseline.benchmarkId, "incomparable", "none", "none", null, [
@@ -1044,6 +1107,49 @@ function compareTaskBenchmarkReceipts(baseline, optimized) {
1044
1107
  "quality matched but no efficiency evidence separated the receipts"
1045
1108
  ]);
1046
1109
  }
1110
+ function compareCcrUsage(baseline, optimized, samePair) {
1111
+ if (!samePair) {
1112
+ return {
1113
+ status: "not-measured",
1114
+ baselineRequests: null,
1115
+ optimizedRequests: null,
1116
+ baselineTokens: null,
1117
+ optimizedTokens: null,
1118
+ totalTokenDelta: null,
1119
+ baselineModels: [],
1120
+ optimizedModels: [],
1121
+ baselineRecordedCostUsd: null,
1122
+ optimizedRecordedCostUsd: null,
1123
+ recordedCostDeltaUsd: null
1124
+ };
1125
+ }
1126
+ const left = baseline.ccrUsage ?? null;
1127
+ const right = optimized.ccrUsage ?? null;
1128
+ const status = left === null || right === null || left.status === "unavailable" || right.status === "unavailable" ? "not-measured" : left.status !== "observed" || right.status !== "observed" ? "partial" : baseline.outcome.qualityGate !== "passed" || optimized.outcome.qualityGate !== "passed" ? "quality-gated" : "comparable";
1129
+ const canCompare = status === "comparable";
1130
+ const baselineRecordedCostUsd = left?.recordedCostUsd ?? null;
1131
+ const optimizedRecordedCostUsd = right?.recordedCostUsd ?? null;
1132
+ return {
1133
+ status,
1134
+ baselineRequests: left?.requestCount ?? null,
1135
+ optimizedRequests: right?.requestCount ?? null,
1136
+ baselineTokens: left?.totalTokens ?? null,
1137
+ optimizedTokens: right?.totalTokens ?? null,
1138
+ totalTokenDelta: canCompare && left && right ? right.totalTokens - left.totalTokens : null,
1139
+ baselineModels: left?.byModel.map((row2) => row2.model) ?? [],
1140
+ optimizedModels: right?.byModel.map((row2) => row2.model) ?? [],
1141
+ baselineRecordedCostUsd,
1142
+ optimizedRecordedCostUsd,
1143
+ recordedCostDeltaUsd: canCompare && baselineRecordedCostUsd !== null && optimizedRecordedCostUsd !== null ? optimizedRecordedCostUsd - baselineRecordedCostUsd : null
1144
+ };
1145
+ }
1146
+ function compareTaskBenchmarkReceipts(baseline, optimized) {
1147
+ const samePair = baseline.benchmarkId === optimized.benchmarkId && baseline.taskClass === optimized.taskClass && baseline.harnessId === optimized.harnessId && baseline.variant === "baseline" && optimized.variant === "optimized";
1148
+ return {
1149
+ ...compareTaskBenchmarkReceiptsCore(baseline, optimized),
1150
+ ccrUsage: compareCcrUsage(baseline, optimized, samePair)
1151
+ };
1152
+ }
1047
1153
  function roundedPercent(numerator, denominator) {
1048
1154
  if (denominator <= 0)
1049
1155
  return null;
@@ -1053,6 +1159,14 @@ function summarizeMatrixEntries(entries, taskClass) {
1053
1159
  const local = entries.filter((entry) => entry.localTokenSavingPercent !== null && entry.baselineLocalTokens !== null && entry.optimizedLocalTokens !== null);
1054
1160
  const baselineLocalTokens = local.length === 0 ? null : local.reduce((total, entry) => total + (entry.baselineLocalTokens ?? 0), 0);
1055
1161
  const optimizedLocalTokens = local.length === 0 ? null : local.reduce((total, entry) => total + (entry.optimizedLocalTokens ?? 0), 0);
1162
+ const ccrRows = entries.flatMap((entry) => entry.ccrUsage === void 0 ? [] : [entry.ccrUsage]);
1163
+ const comparableCcrRows = ccrRows.filter((row2) => row2.status === "comparable");
1164
+ const ccrCostRows = comparableCcrRows.filter((row2) => row2.recordedCostDeltaUsd !== null);
1165
+ const hasCcrEvidence = ccrRows.some((row2) => row2.status !== "not-measured");
1166
+ const baselineCcrTokens = comparableCcrRows.length === 0 ? null : comparableCcrRows.reduce((total, row2) => total + (row2.baselineTokens ?? 0), 0);
1167
+ const optimizedCcrTokens = comparableCcrRows.length === 0 ? null : comparableCcrRows.reduce((total, row2) => total + (row2.optimizedTokens ?? 0), 0);
1168
+ const baselineRecordedCostUsd = ccrCostRows.length === 0 ? null : ccrCostRows.reduce((total, row2) => total + (row2.baselineRecordedCostUsd ?? 0), 0);
1169
+ const optimizedRecordedCostUsd = ccrCostRows.length === 0 ? null : ccrCostRows.reduce((total, row2) => total + (row2.optimizedRecordedCostUsd ?? 0), 0);
1056
1170
  return {
1057
1171
  taskClass,
1058
1172
  pairs: entries.length,
@@ -1067,7 +1181,24 @@ function summarizeMatrixEntries(entries, taskClass) {
1067
1181
  localComparablePairs: local.length,
1068
1182
  baselineLocalTokens,
1069
1183
  optimizedLocalTokens,
1070
- localTokenSavingPercent: baselineLocalTokens === null || optimizedLocalTokens === null ? null : roundedPercent(baselineLocalTokens - optimizedLocalTokens, baselineLocalTokens)
1184
+ localTokenSavingPercent: baselineLocalTokens === null || optimizedLocalTokens === null ? null : roundedPercent(baselineLocalTokens - optimizedLocalTokens, baselineLocalTokens),
1185
+ ...hasCcrEvidence ? {
1186
+ ccrUsage: {
1187
+ comparablePairs: comparableCcrRows.length,
1188
+ partialPairs: ccrRows.filter((row2) => row2.status === "partial").length,
1189
+ qualityGatedPairs: ccrRows.filter((row2) => row2.status === "quality-gated").length,
1190
+ notMeasuredPairs: ccrRows.filter((row2) => row2.status === "not-measured").length,
1191
+ baselineRequests: comparableCcrRows.length === 0 ? null : comparableCcrRows.reduce((total, row2) => total + (row2.baselineRequests ?? 0), 0),
1192
+ optimizedRequests: comparableCcrRows.length === 0 ? null : comparableCcrRows.reduce((total, row2) => total + (row2.optimizedRequests ?? 0), 0),
1193
+ baselineTokens: baselineCcrTokens,
1194
+ optimizedTokens: optimizedCcrTokens,
1195
+ totalTokenDelta: baselineCcrTokens === null || optimizedCcrTokens === null ? null : optimizedCcrTokens - baselineCcrTokens,
1196
+ recordedCostPairs: ccrCostRows.length,
1197
+ baselineRecordedCostUsd,
1198
+ optimizedRecordedCostUsd,
1199
+ recordedCostDeltaUsd: baselineRecordedCostUsd === null || optimizedRecordedCostUsd === null ? null : optimizedRecordedCostUsd - baselineRecordedCostUsd
1200
+ }
1201
+ } : {}
1071
1202
  };
1072
1203
  }
1073
1204
  function buildTaskBenchmarkMatrix(pairs, selection = {
@@ -1093,7 +1224,8 @@ function buildTaskBenchmarkMatrix(pairs, selection = {
1093
1224
  baselineLocalTokens,
1094
1225
  optimizedLocalTokens,
1095
1226
  localTokenSavingPercent: !bothQualityPassed || baselineLocalTokens === null || optimizedLocalTokens === null ? null : roundedPercent(baselineLocalTokens - optimizedLocalTokens, baselineLocalTokens),
1096
- quota: comparison.quota
1227
+ quota: comparison.quota,
1228
+ ...comparison.ccrUsage === void 0 ? {} : { ccrUsage: comparison.ccrUsage }
1097
1229
  };
1098
1230
  }).sort((left, right) => TASK_CLASS_ORDER.indexOf(left.taskClass) - TASK_CLASS_ORDER.indexOf(right.taskClass) || left.benchmarkId.localeCompare(right.benchmarkId));
1099
1231
  const byTaskClass = TASK_CLASS_ORDER.map((taskClass) => ({
@@ -3790,6 +3922,280 @@ var init_model_learning = __esm({
3790
3922
  }
3791
3923
  });
3792
3924
 
3925
+ // packages/core/dist/src/domain/smart-routing.js
3926
+ function classifySmartRoutingPrompt(input) {
3927
+ const original = typeof input.text === "string" ? input.text : "";
3928
+ const text3 = original.trim();
3929
+ const normalized = text3.toLowerCase();
3930
+ const words = normalized.match(/[\p{L}\p{N}_]+/gu) ?? [];
3931
+ const wordCount = words.length;
3932
+ const hasImage = input.hasImage === true;
3933
+ const toolCount = Number.isSafeInteger(input.toolCount) && (input.toolCount ?? 0) > 0 ? input.toolCount : 0;
3934
+ const codePresent = /```|(?:^|\n)\s*(?:function|class|interface|type|import|export|const|let|var)\s+\w/m.test(text3) || /\b(?:stack trace|traceback|SELECT\s+.+\s+FROM|npm ERR!|TS\d{3,5})\b/i.test(text3) || /(?:=>|\b\w+\([^\n)]*\)\s*\{|\b(?:def|fn)\s+\w+\s*\()/m.test(text3);
3935
+ const technicalTerms = [
3936
+ "api",
3937
+ "architecture",
3938
+ "async",
3939
+ "authentication",
3940
+ "database",
3941
+ "distributed",
3942
+ "encryption",
3943
+ "filesystem",
3944
+ "invariant",
3945
+ "migration",
3946
+ "network",
3947
+ "parallel",
3948
+ "protocol",
3949
+ "race condition",
3950
+ "regression",
3951
+ "security",
3952
+ "sql",
3953
+ "thread",
3954
+ "transaction",
3955
+ "typescript"
3956
+ ];
3957
+ let technicalTermCount = 0;
3958
+ for (const term of technicalTerms) {
3959
+ if (normalized.includes(term))
3960
+ technicalTermCount += 1;
3961
+ }
3962
+ const reasoningMarkers = [
3963
+ "analyze",
3964
+ "analyse",
3965
+ "compare",
3966
+ "debug",
3967
+ "design",
3968
+ "evaluate",
3969
+ "investigate",
3970
+ "optimize",
3971
+ "reason through",
3972
+ "root cause",
3973
+ "trade-off",
3974
+ "tradeoff",
3975
+ "why",
3976
+ "step by step"
3977
+ ];
3978
+ let reasoningMarkerCount = 0;
3979
+ for (const marker of reasoningMarkers) {
3980
+ if (normalized.includes(marker))
3981
+ reasoningMarkerCount += 1;
3982
+ }
3983
+ const simpleIndicator = /^(?:hi|hello|hey|thanks|thank you|define\b|what is\b|what does\b|translate\b|rewrite\b|fix typo\b|format\b|summarize\b|summarise\b)/i.test(text3);
3984
+ const multiStep = /\b(?:first|then|finally|step\s+\d+|in\s+three\s+steps)\b/i.test(text3) || /(?:^|\n)\s*\d+[.)]\s+\S/m.test(text3) || /\b(?:and then|after that|before you)\b/i.test(text3);
3985
+ const questionCount = (text3.match(/\?/g) ?? []).length;
3986
+ const longPrompt = wordCount >= 100 || Number.isFinite(input.inputTokens) && (input.inputTokens ?? 0) >= 1200;
3987
+ const veryLongPrompt = wordCount >= 300 || Number.isFinite(input.inputTokens) && (input.inputTokens ?? 0) >= 5e3;
3988
+ const reasonCodes = [];
3989
+ let score = 0;
3990
+ if (wordCount > 0 && wordCount <= 12) {
3991
+ score -= 1.5;
3992
+ reasonCodes.push("short-prompt");
3993
+ } else if (wordCount >= 30 && wordCount < 100) {
3994
+ score += 0.5;
3995
+ reasonCodes.push("medium-prompt");
3996
+ } else if (longPrompt) {
3997
+ score += 1.5;
3998
+ reasonCodes.push("long-prompt");
3999
+ }
4000
+ if (veryLongPrompt) {
4001
+ score += 1;
4002
+ reasonCodes.push("very-long-prompt");
4003
+ }
4004
+ if (codePresent) {
4005
+ score += 2.5;
4006
+ reasonCodes.push("code-present");
4007
+ }
4008
+ if (technicalTermCount > 0) {
4009
+ score += Math.min(technicalTermCount, 3) * 0.75;
4010
+ reasonCodes.push("technical-terms");
4011
+ }
4012
+ if (reasoningMarkerCount > 0) {
4013
+ score += reasoningMarkerCount >= 2 ? 3.5 : 1.5;
4014
+ reasonCodes.push(reasoningMarkerCount >= 2 ? "multiple-reasoning-markers" : "reasoning-marker");
4015
+ }
4016
+ if (multiStep) {
4017
+ score += 1.5;
4018
+ reasonCodes.push("multi-step-request");
4019
+ }
4020
+ if (questionCount > 1) {
4021
+ score += Math.min(questionCount - 1, 3) * 0.5;
4022
+ reasonCodes.push("multiple-questions");
4023
+ }
4024
+ if (simpleIndicator) {
4025
+ score -= 2;
4026
+ reasonCodes.push("simple-language-indicator");
4027
+ }
4028
+ if (hasImage) {
4029
+ score += 3;
4030
+ reasonCodes.push("image-input");
4031
+ }
4032
+ if (wordCount === 0)
4033
+ reasonCodes.push("empty-user-text");
4034
+ if (toolCount > 0)
4035
+ reasonCodes.push("tool-schema-present");
4036
+ const shortFollowUp = wordCount > 0 && wordCount <= 4 && !simpleIndicator;
4037
+ if (shortFollowUp) {
4038
+ score = Math.max(score, 0.25);
4039
+ reasonCodes.push("possible-contextual-follow-up");
4040
+ }
4041
+ let tier;
4042
+ if (hasImage)
4043
+ tier = "complex";
4044
+ else if (reasoningMarkerCount >= 2 || score >= 5)
4045
+ tier = "critical";
4046
+ else if (codePresent || technicalTermCount >= 2 || score >= 1.75)
4047
+ tier = "complex";
4048
+ else if (score <= -1.25 && simpleIndicator && !shortFollowUp)
4049
+ tier = "simple";
4050
+ else
4051
+ tier = "standard";
4052
+ const boundaries = [-1.25, 1.75, 5];
4053
+ let boundaryDistance = Number.POSITIVE_INFINITY;
4054
+ for (const boundary of boundaries)
4055
+ boundaryDistance = Math.min(boundaryDistance, Math.abs(score - boundary));
4056
+ const signalCount = reasonCodes.length;
4057
+ const confidence = wordCount === 0 ? "low" : signalCount >= 2 && boundaryDistance >= 1.25 && tier !== "standard" ? "high" : signalCount >= 1 && boundaryDistance >= 0.5 ? "medium" : "low";
4058
+ const conservativeEligible = tier === "simple" && confidence === "high" && simpleIndicator && !codePresent && technicalTermCount === 0 && reasoningMarkerCount === 0 && !multiStep && questionCount <= 1 && !hasImage && text3.length <= 320;
4059
+ return {
4060
+ classifierVersion: "heuristic-v1",
4061
+ tier,
4062
+ score: Math.round(score * 100) / 100,
4063
+ confidence,
4064
+ reasonCodes,
4065
+ promptChars: text3.length,
4066
+ wordCount,
4067
+ codePresent,
4068
+ technicalTermCount,
4069
+ reasoningMarkerCount,
4070
+ multiStep,
4071
+ hasImage,
4072
+ toolCount,
4073
+ conservativeEligible
4074
+ };
4075
+ }
4076
+ var SMART_ROUTING_CLASSIFIER_VERSION;
4077
+ var init_smart_routing = __esm({
4078
+ "packages/core/dist/src/domain/smart-routing.js"() {
4079
+ "use strict";
4080
+ SMART_ROUTING_CLASSIFIER_VERSION = "heuristic-v1";
4081
+ }
4082
+ });
4083
+
4084
+ // packages/core/dist/src/domain/smart-routing-telemetry.js
4085
+ function isRecord(value3) {
4086
+ return value3 !== null && typeof value3 === "object" && !Array.isArray(value3);
4087
+ }
4088
+ function isTier(value3) {
4089
+ return value3 === "simple" || value3 === "standard" || value3 === "complex" || value3 === "critical";
4090
+ }
4091
+ function hasExactKeys(value3, keys) {
4092
+ const actual = Object.keys(value3).sort();
4093
+ const expected = [...keys].sort();
4094
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
4095
+ }
4096
+ function isSafeModelId(value3) {
4097
+ return value3 === null || typeof value3 === "string" && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(value3);
4098
+ }
4099
+ function isSmartRoutingDecisionEvent(value3) {
4100
+ if (!isRecord(value3) || !isRecord(value3["measurement"]))
4101
+ return false;
4102
+ const event = value3;
4103
+ const measurement = event.measurement;
4104
+ const schemaVersion = value3["schemaVersion"];
4105
+ const keys = [
4106
+ "schemaVersion",
4107
+ "eventId",
4108
+ "timestamp",
4109
+ "source",
4110
+ "harnessId",
4111
+ "mode",
4112
+ "classifierVersion",
4113
+ "tier",
4114
+ "score",
4115
+ "confidence",
4116
+ "reasonCodes",
4117
+ "requestModel",
4118
+ "candidateModel",
4119
+ "routeMutationRequested",
4120
+ "routeSkipReason",
4121
+ "promptChars",
4122
+ "requestInputTokenEstimate",
4123
+ "toolCount",
4124
+ "hasImage",
4125
+ "decisionLatencyMs",
4126
+ "measurement"
4127
+ ];
4128
+ const isV2 = schemaVersion === SMART_ROUTING_EVENT_SCHEMA_VERSION;
4129
+ if (isV2)
4130
+ keys.push("sessionId");
4131
+ return hasExactKeys(value3, keys) && hasExactKeys(value3["measurement"], [
4132
+ "status",
4133
+ "resolvedModel",
4134
+ "providerInputTokens",
4135
+ "providerOutputTokens",
4136
+ "qualityGate"
4137
+ ]) && (event.schemaVersion === 1 || event.schemaVersion === SMART_ROUTING_EVENT_SCHEMA_VERSION) && typeof event.eventId === "string" && /^[0-9]{13}-[a-z0-9]+$/.test(event.eventId) && typeof event.timestamp === "string" && event.source === "ccr" && (event.harnessId === "claude" || event.harnessId === "codex") && (event.mode === "shadow" || event.mode === "conservative") && event.classifierVersion === "heuristic-v1" && isTier(event.tier) && Number.isFinite(event.score) && (event.confidence === "low" || event.confidence === "medium" || event.confidence === "high") && Array.isArray(value3["reasonCodes"]) && event.reasonCodes.every((item) => typeof item === "string" && ALLOWED_REASON_CODES.has(item)) && isSafeModelId(event.requestModel) && isSafeModelId(event.candidateModel) && typeof event.routeMutationRequested === "boolean" && (event.routeSkipReason === null || ALLOWED_SKIP_REASONS.has(event.routeSkipReason)) && Number.isSafeInteger(event.promptChars) && event.promptChars >= 0 && (event.requestInputTokenEstimate === null || Number.isSafeInteger(event.requestInputTokenEstimate) && event.requestInputTokenEstimate >= 0) && Number.isSafeInteger(event.toolCount) && event.toolCount >= 0 && typeof event.hasImage === "boolean" && Number.isFinite(event.decisionLatencyMs) && event.decisionLatencyMs >= 0 && (!isV2 || event.sessionId === null || typeof event.sessionId === "string" && /^[A-Za-z0-9_.:-]{1,256}$/.test(event.sessionId)) && measurement.status === "not-measured" && measurement.resolvedModel === null && measurement.providerInputTokens === null && measurement.providerOutputTokens === null && measurement.qualityGate === "unknown";
4138
+ }
4139
+ function aggregateSmartRoutingEvents(input) {
4140
+ const report = {
4141
+ schemaVersion: 1,
4142
+ retainedDecisionCount: input.events.length,
4143
+ byHarness: { claude: 0, codex: 0 },
4144
+ byMode: { shadow: 0, conservative: 0 },
4145
+ byTier: { simple: 0, standard: 0, complex: 0, critical: 0 },
4146
+ routeMutationRequestCount: 0,
4147
+ malformedRecordCount: input.malformedRecordCount ?? 0,
4148
+ prunedRecordCount: input.prunedRecordCount ?? 0,
4149
+ retentionLimit: SMART_ROUTING_EVENT_RETENTION_LIMIT,
4150
+ savingsStatus: "not-measured",
4151
+ savingsMeasurementCount: 0
4152
+ };
4153
+ for (const event of input.events) {
4154
+ report.byHarness[event.harnessId] += 1;
4155
+ report.byMode[event.mode] += 1;
4156
+ report.byTier[event.tier] += 1;
4157
+ if (event.routeMutationRequested)
4158
+ report.routeMutationRequestCount += 1;
4159
+ }
4160
+ return report;
4161
+ }
4162
+ var SMART_ROUTING_EVENT_SCHEMA_VERSION, SMART_ROUTING_EVENT_PREFIX, SMART_ROUTING_EVENT_RETENTION_LIMIT, ALLOWED_REASON_CODES, ALLOWED_SKIP_REASONS;
4163
+ var init_smart_routing_telemetry = __esm({
4164
+ "packages/core/dist/src/domain/smart-routing-telemetry.js"() {
4165
+ "use strict";
4166
+ SMART_ROUTING_EVENT_SCHEMA_VERSION = 2;
4167
+ SMART_ROUTING_EVENT_PREFIX = "smart-routing-";
4168
+ SMART_ROUTING_EVENT_RETENTION_LIMIT = 200;
4169
+ ALLOWED_REASON_CODES = /* @__PURE__ */ new Set([
4170
+ "short-prompt",
4171
+ "medium-prompt",
4172
+ "long-prompt",
4173
+ "very-long-prompt",
4174
+ "code-present",
4175
+ "technical-terms",
4176
+ "reasoning-marker",
4177
+ "multiple-reasoning-markers",
4178
+ "multi-step-request",
4179
+ "multiple-questions",
4180
+ "simple-language-indicator",
4181
+ "image-input",
4182
+ "empty-user-text",
4183
+ "tool-schema-present",
4184
+ "possible-contextual-follow-up"
4185
+ ]);
4186
+ ALLOWED_SKIP_REASONS = /* @__PURE__ */ new Set([
4187
+ "shadow-mode",
4188
+ "unsupported-mode",
4189
+ "complexity-not-simple",
4190
+ "simple-model-not-configured",
4191
+ "request-model-unavailable",
4192
+ "conservative-safety-gate",
4193
+ "tool-compatibility-unconfirmed",
4194
+ "model-already-selected"
4195
+ ]);
4196
+ }
4197
+ });
4198
+
3793
4199
  // packages/core/dist/src/domain/action-conflicts.js
3794
4200
  function markerAction(action) {
3795
4201
  return action.kind === "patch-marker-block";
@@ -7146,8 +7552,8 @@ function parseJsonDocumentText(text3) {
7146
7552
  document: JSON.parse(body),
7147
7553
  formatting: detectJsonFormatting(text3)
7148
7554
  };
7149
- } catch (error) {
7150
- return { state: "malformed", reason: error instanceof Error ? error.message : String(error) };
7555
+ } catch (error2) {
7556
+ return { state: "malformed", reason: error2 instanceof Error ? error2.message : String(error2) };
7151
7557
  }
7152
7558
  }
7153
7559
  function clone(value3) {
@@ -8518,12 +8924,12 @@ async function applyCodexConfigBatchWrite(action, context) {
8518
8924
  }
8519
8925
  }
8520
8926
  const response = messages.find((message) => typeof message === "object" && message !== null && !Array.isArray(message) && (message["id"] === CODEX_CONFIG_WRITE_REQUEST_ID || message["id"] === 2));
8521
- const error = response !== void 0 && typeof response["error"] === "object" && response["error"] !== null && !Array.isArray(response["error"]) ? response["error"] : null;
8522
- const errorText = error === null ? "" : [error["message"], error["data"]].map((value3) => typeof value3 === "string" ? value3 : JSON.stringify(value3)).filter((value3) => value3 !== void 0 && value3 !== "").join(" ");
8927
+ const error2 = response !== void 0 && typeof response["error"] === "object" && response["error"] !== null && !Array.isArray(response["error"]) ? response["error"] : null;
8928
+ const errorText = error2 === null ? "" : [error2["message"], error2["data"]].map((value3) => typeof value3 === "string" ? value3 : JSON.stringify(value3)).filter((value3) => value3 !== void 0 && value3 !== "").join(" ");
8523
8929
  if (/configVersionConflict/i.test(errorText)) {
8524
8930
  return drift(action, action.path, "Codex reports that config.toml changed after this plan observed its config version");
8525
8931
  }
8526
- if (result6.exitCode !== 0 || response === void 0 || error !== null || !("result" in response)) {
8932
+ if (result6.exitCode !== 0 || response === void 0 || error2 !== null || !("result" in response)) {
8527
8933
  return outcome(action, "failed", {
8528
8934
  snapshots: [snapshot],
8529
8935
  diagnostics: [
@@ -9027,8 +9433,8 @@ function parseJsoncDocumentText(text3) {
9027
9433
  state: "parsed",
9028
9434
  document: JSON.parse(withoutTrailingCommas(withoutComments(text3)))
9029
9435
  };
9030
- } catch (error) {
9031
- return { state: "malformed", reason: error instanceof Error ? error.message : String(error) };
9436
+ } catch (error2) {
9437
+ return { state: "malformed", reason: error2 instanceof Error ? error2.message : String(error2) };
9032
9438
  }
9033
9439
  }
9034
9440
  var init_jsonc = __esm({
@@ -9372,8 +9778,8 @@ async function executeTransaction(request) {
9372
9778
  let restoreError = null;
9373
9779
  try {
9374
9780
  await request.snapshots.restoreAll(snapshots);
9375
- } catch (error) {
9376
- restoreError = error instanceof Error ? error.message : String(error);
9781
+ } catch (error2) {
9782
+ restoreError = error2 instanceof Error ? error2.message : String(error2);
9377
9783
  }
9378
9784
  const unrestored = await verifyRestoration(request.fs, snapshots);
9379
9785
  const packageDiagnostics = await restorePackageInventories(applied, request.runner ?? null, request.projectRoot);
@@ -9400,7 +9806,7 @@ async function executeTransaction(request) {
9400
9806
  let result6;
9401
9807
  try {
9402
9808
  result6 = await applyAction(action, context);
9403
- } catch (error) {
9809
+ } catch (error2) {
9404
9810
  result6 = {
9405
9811
  actionId: action.id,
9406
9812
  kind: action.kind,
@@ -9412,7 +9818,7 @@ async function executeTransaction(request) {
9412
9818
  diagnostic({
9413
9819
  severity: "error",
9414
9820
  code: "action-failed",
9415
- message: `The action ${action.id} failed: ${error instanceof Error ? error.message : String(error)}`,
9821
+ message: `The action ${action.id} failed: ${error2 instanceof Error ? error2.message : String(error2)}`,
9416
9822
  path: action.affectedPaths[0] ?? null,
9417
9823
  remediation: "Check the path is writable, then run the command again"
9418
9824
  })
@@ -9507,8 +9913,8 @@ async function rollbackTransaction(request) {
9507
9913
  let restoreError = null;
9508
9914
  try {
9509
9915
  await request.snapshots.restoreAll(snapshots);
9510
- } catch (error) {
9511
- restoreError = error instanceof Error ? error.message : String(error);
9916
+ } catch (error2) {
9917
+ restoreError = error2 instanceof Error ? error2.message : String(error2);
9512
9918
  }
9513
9919
  const unrestored = await verifyRestoration(request.fs, snapshots);
9514
9920
  const packageDiagnostics = await restorePackageInventories(journal.entries, request.runner ?? null, request.cwd ?? journal.projectRoot);
@@ -9601,6 +10007,8 @@ var init_src = __esm({
9601
10007
  init_outcome_learning();
9602
10008
  init_verbosity_learning();
9603
10009
  init_model_learning();
10010
+ init_smart_routing();
10011
+ init_smart_routing_telemetry();
9604
10012
  init_action_conflicts();
9605
10013
  init_capabilities();
9606
10014
  init_compatibility_rows();
@@ -9660,7 +10068,7 @@ var TOOL_VERSION;
9660
10068
  var init_version2 = __esm({
9661
10069
  "apps/cli/dist/src/version.js"() {
9662
10070
  "use strict";
9663
- TOOL_VERSION = "0.1.18";
10071
+ TOOL_VERSION = "0.1.19";
9664
10072
  }
9665
10073
  });
9666
10074
 
@@ -10259,19 +10667,19 @@ var init_node_filesystem = __esm({
10259
10667
  // reporting them would invite a caller to treat them as one.
10260
10668
  mode: this.nativeWindows ? null : octal(info.mode)
10261
10669
  };
10262
- } catch (error) {
10263
- if (error.code === "ENOENT")
10670
+ } catch (error2) {
10671
+ if (error2.code === "ENOENT")
10264
10672
  return null;
10265
- throw error;
10673
+ throw error2;
10266
10674
  }
10267
10675
  }
10268
10676
  async canonicalPath(path) {
10269
10677
  try {
10270
10678
  return await realpath(path);
10271
- } catch (error) {
10272
- if (error.code === "ENOENT")
10679
+ } catch (error2) {
10680
+ if (error2.code === "ENOENT")
10273
10681
  return null;
10274
- throw error;
10682
+ throw error2;
10275
10683
  }
10276
10684
  }
10277
10685
  async readFile(path) {
@@ -10295,21 +10703,63 @@ var init_node_filesystem = __esm({
10295
10703
  async readDirectory(path) {
10296
10704
  try {
10297
10705
  return (await readdir(path)).sort();
10298
- } catch (error) {
10299
- if (error.code === "ENOENT")
10706
+ } catch (error2) {
10707
+ if (error2.code === "ENOENT")
10300
10708
  return [];
10301
- throw error;
10709
+ throw error2;
10302
10710
  }
10303
10711
  }
10304
10712
  };
10305
10713
  }
10306
10714
  });
10307
10715
 
10308
- // packages/platform/dist/src/artifacts/rtk-windows-release.js
10716
+ // packages/platform/dist/src/artifacts/rtk-release.js
10309
10717
  import { createHash as createHash2 } from "node:crypto";
10310
10718
  import { rename, rm as rm2 } from "node:fs/promises";
10311
- import { inflateRawSync } from "node:zlib";
10312
- function isRecord(value3) {
10719
+ import { gunzipSync, inflateRawSync } from "node:zlib";
10720
+ function rtkReleaseAssetForPlatform(platform) {
10721
+ if (platform.os === "windows" && !platform.isWsl && platform.arch === "x64") {
10722
+ return {
10723
+ name: RTK_WINDOWS_RELEASE_ASSET,
10724
+ executableName: "rtk.exe",
10725
+ archiveFormat: "zip"
10726
+ };
10727
+ }
10728
+ if (platform.os === "linux") {
10729
+ if (platform.arch === "x64") {
10730
+ return {
10731
+ name: "rtk-x86_64-unknown-linux-musl.tar.gz",
10732
+ executableName: "rtk",
10733
+ archiveFormat: "tar.gz"
10734
+ };
10735
+ }
10736
+ if (platform.arch === "arm64") {
10737
+ return {
10738
+ name: "rtk-aarch64-unknown-linux-gnu.tar.gz",
10739
+ executableName: "rtk",
10740
+ archiveFormat: "tar.gz"
10741
+ };
10742
+ }
10743
+ }
10744
+ if (platform.os === "macos") {
10745
+ if (platform.arch === "x64") {
10746
+ return {
10747
+ name: "rtk-x86_64-apple-darwin.tar.gz",
10748
+ executableName: "rtk",
10749
+ archiveFormat: "tar.gz"
10750
+ };
10751
+ }
10752
+ if (platform.arch === "arm64") {
10753
+ return {
10754
+ name: "rtk-aarch64-apple-darwin.tar.gz",
10755
+ executableName: "rtk",
10756
+ archiveFormat: "tar.gz"
10757
+ };
10758
+ }
10759
+ }
10760
+ return null;
10761
+ }
10762
+ function isRecord2(value3) {
10313
10763
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
10314
10764
  }
10315
10765
  function integer(value3) {
@@ -10402,8 +10852,8 @@ async function fetchBounded(input) {
10402
10852
  clearTimeout(timer);
10403
10853
  }
10404
10854
  }
10405
- function parseReleaseMetadata(value3, version3) {
10406
- if (!isRecord(value3))
10855
+ function parseReleaseMetadata(value3, version3, selection) {
10856
+ if (!isRecord2(value3))
10407
10857
  return { status: "invalid", message: "release metadata is not an object" };
10408
10858
  const tag = `v${version3}`;
10409
10859
  if (value3["tag_name"] !== tag || value3["draft"] !== false || value3["prerelease"] !== false) {
@@ -10415,30 +10865,30 @@ function parseReleaseMetadata(value3, version3) {
10415
10865
  const assets = value3["assets"];
10416
10866
  if (!Array.isArray(assets))
10417
10867
  return { status: "invalid", message: "release metadata has no asset list" };
10418
- const matching = assets.filter((asset2) => isRecord(asset2) && asset2["name"] === RTK_WINDOWS_RELEASE_ASSET);
10868
+ const matching = assets.filter((asset2) => isRecord2(asset2) && asset2["name"] === selection.name);
10419
10869
  if (matching.length !== 1) {
10420
10870
  return {
10421
10871
  status: "invalid",
10422
- message: `release ${tag} must contain exactly one ${RTK_WINDOWS_RELEASE_ASSET} asset`
10872
+ message: `release ${tag} must contain exactly one ${selection.name} asset`
10423
10873
  };
10424
10874
  }
10425
10875
  const asset = matching[0];
10426
- if (!isRecord(asset))
10876
+ if (!isRecord2(asset))
10427
10877
  return { status: "invalid", message: "release asset is malformed" };
10428
10878
  const digest = normalizeSha256(asset["digest"]);
10429
10879
  const size = integer(asset["size"]);
10430
10880
  const downloadUrl = typeof asset["browser_download_url"] === "string" ? asset["browser_download_url"] : null;
10431
10881
  if (digest === null) {
10432
- return { status: "invalid", message: `${RTK_WINDOWS_RELEASE_ASSET} has no published SHA-256` };
10882
+ return { status: "invalid", message: `${selection.name} has no published SHA-256` };
10433
10883
  }
10434
10884
  if (size === null || size <= 0 || size > MAX_ARCHIVE_BYTES) {
10435
10885
  return {
10436
10886
  status: "invalid",
10437
- message: `${RTK_WINDOWS_RELEASE_ASSET} has an invalid or excessive published size`
10887
+ message: `${selection.name} has an invalid or excessive published size`
10438
10888
  };
10439
10889
  }
10440
10890
  if (downloadUrl === null) {
10441
- return { status: "invalid", message: `${RTK_WINDOWS_RELEASE_ASSET} has no download URL` };
10891
+ return { status: "invalid", message: `${selection.name} has no download URL` };
10442
10892
  }
10443
10893
  let parsedUrl;
10444
10894
  try {
@@ -10446,25 +10896,29 @@ function parseReleaseMetadata(value3, version3) {
10446
10896
  } catch {
10447
10897
  return {
10448
10898
  status: "invalid",
10449
- message: `${RTK_WINDOWS_RELEASE_ASSET} has an invalid download URL`
10899
+ message: `${selection.name} has an invalid download URL`
10450
10900
  };
10451
10901
  }
10452
10902
  const expectedPrefix = `${RELEASE_DOWNLOAD_PREFIX}${tag}/`;
10453
10903
  if (!allowedAssetUrl(parsedUrl, true) || !downloadUrl.startsWith(expectedPrefix)) {
10454
10904
  return {
10455
10905
  status: "invalid",
10456
- message: `${RTK_WINDOWS_RELEASE_ASSET} points outside the reviewed rtk-ai/rtk release path`
10906
+ message: `${selection.name} points outside the reviewed rtk-ai/rtk release path`
10457
10907
  };
10458
10908
  }
10459
- if (asset["content_type"] !== "application/zip") {
10460
- return { status: "invalid", message: `${RTK_WINDOWS_RELEASE_ASSET} is not published as a ZIP` };
10909
+ const expectedContentType = selection.archiveFormat === "zip" ? "application/zip" : "application/gzip";
10910
+ if (asset["content_type"] !== expectedContentType) {
10911
+ return {
10912
+ status: "invalid",
10913
+ message: `${selection.name} is not published as ${expectedContentType}`
10914
+ };
10461
10915
  }
10462
10916
  return {
10463
10917
  status: "found",
10464
10918
  asset: {
10919
+ ...selection,
10465
10920
  version: version3,
10466
10921
  tag,
10467
- name: RTK_WINDOWS_RELEASE_ASSET,
10468
10922
  downloadUrl,
10469
10923
  sha256: digest,
10470
10924
  sizeBytes: size
@@ -10573,16 +11027,83 @@ function extractRtkExeFromVerifiedZip(bytes) {
10573
11027
  throw new Error("release ZIP contains no root rtk.exe");
10574
11028
  return extracted;
10575
11029
  }
11030
+ function tarText(buffer, offset, length) {
11031
+ const field = buffer.subarray(offset, offset + length);
11032
+ const end = field.indexOf(0);
11033
+ return field.subarray(0, end < 0 ? field.length : end).toString("utf8");
11034
+ }
11035
+ function tarOctal(buffer, offset, length, fieldName) {
11036
+ const raw = tarText(buffer, offset, length).trim();
11037
+ if (raw === "")
11038
+ return 0;
11039
+ if (!/^[0-7]+$/.test(raw))
11040
+ throw new Error(`tar ${fieldName} is not an octal value`);
11041
+ const value3 = Number.parseInt(raw, 8);
11042
+ if (!Number.isSafeInteger(value3) || value3 < 0)
11043
+ throw new Error(`tar ${fieldName} is outside the supported range`);
11044
+ return value3;
11045
+ }
11046
+ function extractRtkBinaryFromVerifiedTarGz(bytes) {
11047
+ const compressed = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
11048
+ const tar = gunzipSync(compressed, { maxOutputLength: MAX_EXPANDED_ARCHIVE_BYTES });
11049
+ let cursor = 0;
11050
+ let sawEnd = false;
11051
+ let extracted = null;
11052
+ while (cursor + TAR_BLOCK_BYTES <= tar.length) {
11053
+ const header = tar.subarray(cursor, cursor + TAR_BLOCK_BYTES);
11054
+ if (header.every((byte) => byte === 0)) {
11055
+ sawEnd = true;
11056
+ break;
11057
+ }
11058
+ const expectedChecksum = tarOctal(header, 148, 8, "checksum");
11059
+ let checksum = 0;
11060
+ for (let index = 0; index < TAR_BLOCK_BYTES; index += 1) {
11061
+ checksum += index >= 148 && index < 156 ? 32 : header[index] ?? 0;
11062
+ }
11063
+ if (checksum !== expectedChecksum)
11064
+ throw new Error("tar header checksum does not match");
11065
+ const name2 = tarText(header, 0, 100);
11066
+ const prefix = tarText(header, 345, 155);
11067
+ const path = prefix === "" ? name2 : `${prefix}/${name2}`;
11068
+ const type = header[156] === 0 ? "\0" : String.fromCharCode(header[156] ?? 0);
11069
+ const size = tarOctal(header, 124, 12, "file size");
11070
+ if (size > MAX_EXECUTABLE_BYTES)
11071
+ throw new Error("tar entry exceeds the RTK executable size limit");
11072
+ if (type !== "\0" && type !== "0" && type !== "5") {
11073
+ throw new Error(`tar entry type ${JSON.stringify(type)} is not supported`);
11074
+ }
11075
+ const dataStart = cursor + TAR_BLOCK_BYTES;
11076
+ const dataEnd = dataStart + size;
11077
+ const next2 = dataStart + Math.ceil(size / TAR_BLOCK_BYTES) * TAR_BLOCK_BYTES;
11078
+ if (dataEnd > tar.length || next2 > tar.length)
11079
+ throw new Error("tar entry exceeds archive bounds");
11080
+ if (path === "rtk") {
11081
+ if (type === "5")
11082
+ throw new Error("root rtk tar entry is a directory");
11083
+ if (extracted !== null)
11084
+ throw new Error("release tar contains more than one root rtk file");
11085
+ if (size === 0)
11086
+ throw new Error("root rtk tar entry is empty");
11087
+ extracted = new Uint8Array(tar.subarray(dataStart, dataEnd));
11088
+ }
11089
+ cursor = next2;
11090
+ }
11091
+ if (!sawEnd)
11092
+ throw new Error("tar end marker was not found");
11093
+ if (extracted === null)
11094
+ throw new Error("release tar contains no root rtk file");
11095
+ return extracted;
11096
+ }
10576
11097
  function versionAppears(output, version3) {
10577
11098
  const escaped = version3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
10578
11099
  return new RegExp(`(?:^|\\s)v?${escaped}(?:\\s|$)`, "m").test(output.trim());
10579
11100
  }
10580
- function rtkWindowsReleaseRuntimeFor(fs, runner) {
10581
- return fs instanceof NodeFileSystem ? new NodeRtkWindowsReleaseRuntime({ fs, runner }) : null;
11101
+ function rtkReleaseRuntimeFor(fs, runner, fetchImpl) {
11102
+ return fs instanceof NodeFileSystem ? new NodeRtkReleaseRuntime({ fs, runner, ...fetchImpl === void 0 ? {} : { fetchImpl } }) : null;
10582
11103
  }
10583
- var RTK_WINDOWS_RELEASE_ASSET, RTK_RELEASE_METADATA_DESTINATION, RTK_RELEASE_ASSET_DESTINATION, RELEASE_API_PREFIX, RELEASE_DOWNLOAD_PREFIX, MAX_METADATA_BYTES, MAX_ARCHIVE_BYTES, MAX_EXECUTABLE_BYTES, MAX_REDIRECTS, FETCH_TIMEOUT_MS, ZIP_EOCD_SIGNATURE, ZIP_CENTRAL_SIGNATURE, ZIP_LOCAL_SIGNATURE, nativeFetch, NodeRtkWindowsReleaseRuntime;
10584
- var init_rtk_windows_release = __esm({
10585
- "packages/platform/dist/src/artifacts/rtk-windows-release.js"() {
11104
+ var RTK_WINDOWS_RELEASE_ASSET, RTK_RELEASE_METADATA_DESTINATION, RTK_RELEASE_ASSET_DESTINATION, RELEASE_API_PREFIX, RELEASE_DOWNLOAD_PREFIX, MAX_METADATA_BYTES, MAX_ARCHIVE_BYTES, MAX_EXPANDED_ARCHIVE_BYTES, MAX_EXECUTABLE_BYTES, MAX_REDIRECTS, FETCH_TIMEOUT_MS, ZIP_EOCD_SIGNATURE, ZIP_CENTRAL_SIGNATURE, ZIP_LOCAL_SIGNATURE, TAR_BLOCK_BYTES, nativeFetch, NodeRtkReleaseRuntime;
11105
+ var init_rtk_release = __esm({
11106
+ "packages/platform/dist/src/artifacts/rtk-release.js"() {
10586
11107
  "use strict";
10587
11108
  init_src();
10588
11109
  init_node_filesystem();
@@ -10593,14 +11114,16 @@ var init_rtk_windows_release = __esm({
10593
11114
  RELEASE_DOWNLOAD_PREFIX = "https://github.com/rtk-ai/rtk/releases/download/";
10594
11115
  MAX_METADATA_BYTES = 1024 * 1024;
10595
11116
  MAX_ARCHIVE_BYTES = 32 * 1024 * 1024;
11117
+ MAX_EXPANDED_ARCHIVE_BYTES = 128 * 1024 * 1024;
10596
11118
  MAX_EXECUTABLE_BYTES = 64 * 1024 * 1024;
10597
11119
  MAX_REDIRECTS = 5;
10598
11120
  FETCH_TIMEOUT_MS = 2e4;
10599
11121
  ZIP_EOCD_SIGNATURE = 101010256;
10600
11122
  ZIP_CENTRAL_SIGNATURE = 33639248;
10601
11123
  ZIP_LOCAL_SIGNATURE = 67324752;
11124
+ TAR_BLOCK_BYTES = 512;
10602
11125
  nativeFetch = async (url, init) => fetch(url, init);
10603
- NodeRtkWindowsReleaseRuntime = class {
11126
+ NodeRtkReleaseRuntime = class {
10604
11127
  fs;
10605
11128
  runner;
10606
11129
  fetchImpl;
@@ -10609,10 +11132,17 @@ var init_rtk_windows_release = __esm({
10609
11132
  this.runner = input.runner;
10610
11133
  this.fetchImpl = input.fetchImpl ?? nativeFetch;
10611
11134
  }
10612
- async query(version3) {
11135
+ async query(version3, platform) {
10613
11136
  if (parseSemanticVersion(version3) === null) {
10614
11137
  return { status: "invalid", message: `${version3} is not a semantic RTK release` };
10615
11138
  }
11139
+ const selection = rtkReleaseAssetForPlatform(platform);
11140
+ if (selection === null) {
11141
+ return {
11142
+ status: "invalid",
11143
+ message: `RTK ${version3} does not publish a managed binary for ${platform.os}/${platform.arch}`
11144
+ };
11145
+ }
10616
11146
  const url = `${RELEASE_API_PREFIX}v${version3}`;
10617
11147
  let bytes;
10618
11148
  try {
@@ -10622,19 +11152,19 @@ var init_rtk_windows_release = __esm({
10622
11152
  maximumBytes: MAX_METADATA_BYTES,
10623
11153
  kind: "metadata"
10624
11154
  });
10625
- } catch (error) {
11155
+ } catch (error2) {
10626
11156
  return {
10627
11157
  status: "unavailable",
10628
- message: `RTK release metadata could not be read: ${error instanceof Error ? error.message : String(error)}`
11158
+ message: `RTK release metadata could not be read: ${error2 instanceof Error ? error2.message : String(error2)}`
10629
11159
  };
10630
11160
  }
10631
11161
  try {
10632
11162
  const value3 = JSON.parse(new TextDecoder().decode(bytes));
10633
- return parseReleaseMetadata(value3, version3);
10634
- } catch (error) {
11163
+ return parseReleaseMetadata(value3, version3, selection);
11164
+ } catch (error2) {
10635
11165
  return {
10636
11166
  status: "invalid",
10637
- message: `RTK release metadata is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
11167
+ message: `RTK release metadata is not valid JSON: ${error2 instanceof Error ? error2.message : String(error2)}`
10638
11168
  };
10639
11169
  }
10640
11170
  }
@@ -10650,7 +11180,7 @@ var init_rtk_windows_release = __esm({
10650
11180
  }
10651
11181
  const digest = createHash2("sha256").update(archive).digest("hex");
10652
11182
  if (digest !== asset.sha256)
10653
- throw new Error("downloaded RTK ZIP does not match GitHub published SHA-256");
11183
+ throw new Error("downloaded RTK release archive does not match GitHub published SHA-256");
10654
11184
  return archive;
10655
11185
  }
10656
11186
  async verifyExecutable(path, version3, cwd) {
@@ -10689,23 +11219,23 @@ ${result6.stderr}`, version3);
10689
11219
  }
10690
11220
  const directory = this.fs.dirname(handle.targetPath);
10691
11221
  const stage = this.fs.join(directory, `.rtk.token-harness.rollback-${handle.previousDigest.slice(-12)}.tmp`);
10692
- const displaced = this.fs.join(directory, ".rtk.token-harness.rollback-displaced.exe");
11222
+ const displaced = this.fs.join(directory, ".rtk.token-harness.rollback-displaced");
10693
11223
  if (await this.fs.stat(displaced) !== null) {
10694
11224
  return {
10695
11225
  status: "dirty",
10696
11226
  message: `RTK rollback staging path already exists: ${displaced}`
10697
11227
  };
10698
11228
  }
10699
- await this.fs.writeFile(stage, backup);
11229
+ await this.fs.writeFile(stage, backup, handle.previousMode);
10700
11230
  await rename(handle.targetPath, displaced);
10701
11231
  try {
10702
11232
  await rename(stage, handle.targetPath);
10703
- } catch (error) {
11233
+ } catch (error2) {
10704
11234
  await rename(displaced, handle.targetPath).catch(() => void 0);
10705
11235
  await rm2(stage, { force: true }).catch(() => void 0);
10706
11236
  return {
10707
11237
  status: "dirty",
10708
- message: `RTK rollback could not replace the executable: ${error instanceof Error ? error.message : String(error)}`
11238
+ message: `RTK rollback could not replace the executable: ${error2 instanceof Error ? error2.message : String(error2)}`
10709
11239
  };
10710
11240
  }
10711
11241
  await rm2(displaced, { force: true });
@@ -10726,10 +11256,10 @@ ${result6.stderr}`, version3);
10726
11256
  status: "rolled-back",
10727
11257
  message: "RTK previous executable bytes and version were restored and verified"
10728
11258
  };
10729
- } catch (error) {
11259
+ } catch (error2) {
10730
11260
  return {
10731
11261
  status: "dirty",
10732
- message: `RTK rollback failed: ${error instanceof Error ? error.message : String(error)}`
11262
+ message: `RTK rollback failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10733
11263
  };
10734
11264
  }
10735
11265
  }
@@ -10738,11 +11268,11 @@ ${result6.stderr}`, version3);
10738
11268
  }
10739
11269
  async install(input) {
10740
11270
  const targetName = this.fs.basename(input.targetPath).toLowerCase();
10741
- if (targetName !== "rtk.exe") {
11271
+ if (targetName !== input.asset.executableName.toLowerCase()) {
10742
11272
  return {
10743
11273
  status: "failed",
10744
11274
  code: "rtk-release-target-refused",
10745
- message: `Resolved RTK target is not rtk.exe: ${input.targetPath}`,
11275
+ message: `Resolved RTK target does not match the release executable name ${input.asset.executableName}: ${input.targetPath}`,
10746
11276
  backupPath: null
10747
11277
  };
10748
11278
  }
@@ -10755,16 +11285,24 @@ ${result6.stderr}`, version3);
10755
11285
  backupPath: null
10756
11286
  };
10757
11287
  }
11288
+ if (input.asset.executableName === "rtk" && (targetStat.mode === null || (Number.parseInt(targetStat.mode, 8) & 73) === 0)) {
11289
+ return {
11290
+ status: "failed",
11291
+ code: "rtk-release-target-not-executable",
11292
+ message: `Resolved RTK target does not have readable POSIX executable permissions: ${input.targetPath}`,
11293
+ backupPath: null
11294
+ };
11295
+ }
10758
11296
  let archive;
10759
11297
  let replacement;
10760
11298
  try {
10761
11299
  archive = await this.download(input.asset);
10762
- replacement = extractRtkExeFromVerifiedZip(archive);
10763
- } catch (error) {
11300
+ replacement = input.asset.archiveFormat === "zip" ? extractRtkExeFromVerifiedZip(archive) : extractRtkBinaryFromVerifiedTarGz(archive);
11301
+ } catch (error2) {
10764
11302
  return {
10765
11303
  status: "failed",
10766
11304
  code: "rtk-release-artifact-invalid",
10767
- message: error instanceof Error ? error.message : String(error),
11305
+ message: error2 instanceof Error ? error2.message : String(error2),
10768
11306
  backupPath: null
10769
11307
  };
10770
11308
  }
@@ -10772,7 +11310,7 @@ ${result6.stderr}`, version3);
10772
11310
  const previousDigest = digestBytes(previous);
10773
11311
  const replacementDigest = digestBytes(replacement);
10774
11312
  const backupDirectory = this.fs.join(input.stateRoot, "backups", "rtk-release");
10775
- const backupPath = this.fs.join(backupDirectory, `rtk-${input.previousVersion ?? "unknown"}-${previousDigest.slice(-16)}.exe`);
11313
+ const backupPath = this.fs.join(backupDirectory, `rtk-${input.previousVersion ?? "unknown"}-${previousDigest.slice(-16)}.bin`);
10776
11314
  await this.fs.createDirectory(backupDirectory);
10777
11315
  const existingBackup = await this.fs.stat(backupPath);
10778
11316
  if (existingBackup === null)
@@ -10787,7 +11325,7 @@ ${result6.stderr}`, version3);
10787
11325
  }
10788
11326
  const directory = this.fs.dirname(input.targetPath);
10789
11327
  const stage = this.fs.join(directory, `.rtk.token-harness-${input.asset.version}.tmp`);
10790
- const displaced = this.fs.join(directory, ".rtk.token-harness-previous.exe");
11328
+ const displaced = this.fs.join(directory, ".rtk.token-harness-previous");
10791
11329
  if (await this.fs.stat(stage) !== null || await this.fs.stat(displaced) !== null) {
10792
11330
  return {
10793
11331
  status: "failed",
@@ -10797,18 +11335,18 @@ ${result6.stderr}`, version3);
10797
11335
  };
10798
11336
  }
10799
11337
  try {
10800
- await this.fs.writeFile(stage, replacement);
11338
+ await this.fs.writeFile(stage, replacement, targetStat.mode);
10801
11339
  if (digestBytes(await this.fs.readFile(stage)) !== replacementDigest) {
10802
- throw new Error("staged rtk.exe does not match the extracted bytes");
11340
+ throw new Error("staged RTK executable does not match the extracted bytes");
10803
11341
  }
10804
11342
  await rename(input.targetPath, displaced);
10805
11343
  try {
10806
11344
  await rename(stage, input.targetPath);
10807
- } catch (error) {
11345
+ } catch (error2) {
10808
11346
  await rename(displaced, input.targetPath).catch(() => void 0);
10809
- throw error;
11347
+ throw error2;
10810
11348
  }
10811
- } catch (error) {
11349
+ } catch (error2) {
10812
11350
  await rm2(stage, { force: true }).catch(() => void 0);
10813
11351
  const live = await this.fs.stat(input.targetPath);
10814
11352
  if (live !== null && live.kind === "file" && digestBytes(await this.fs.readFile(input.targetPath)) === previousDigest) {
@@ -10816,14 +11354,14 @@ ${result6.stderr}`, version3);
10816
11354
  return {
10817
11355
  status: "rolled-back",
10818
11356
  code: "rtk-release-replacement-failed",
10819
- message: `RTK replacement failed before commit and the previous executable is intact: ${error instanceof Error ? error.message : String(error)}`,
11357
+ message: `RTK replacement failed before commit and the previous executable is intact: ${error2 instanceof Error ? error2.message : String(error2)}`,
10820
11358
  backupPath
10821
11359
  };
10822
11360
  }
10823
11361
  return {
10824
11362
  status: "dirty",
10825
11363
  code: "rtk-release-replacement-dirty",
10826
- message: `RTK replacement failed and exact restoration could not be verified: ${error instanceof Error ? error.message : String(error)}`,
11364
+ message: `RTK replacement failed and exact restoration could not be verified: ${error2 instanceof Error ? error2.message : String(error2)}`,
10827
11365
  backupPath
10828
11366
  };
10829
11367
  }
@@ -10832,6 +11370,7 @@ ${result6.stderr}`, version3);
10832
11370
  backupPath,
10833
11371
  previousDigest,
10834
11372
  replacementDigest,
11373
+ previousMode: targetStat.mode,
10835
11374
  previousVersion: input.previousVersion,
10836
11375
  replacementVersion: input.asset.version
10837
11376
  };
@@ -10842,7 +11381,7 @@ ${result6.stderr}`, version3);
10842
11381
  return {
10843
11382
  status: "rolled-back",
10844
11383
  code: "rtk-release-postcondition-failed",
10845
- message: "The verified RTK release bytes were installed but Windows could not verify the new version; the previous executable was restored. Smart App Control or another application-control policy may have blocked the freshly released unsigned binary.",
11384
+ message: "The verified RTK release bytes were installed but the new version could not be verified; the previous executable was restored. Check OS application-control policy and binary compatibility.",
10846
11385
  backupPath
10847
11386
  };
10848
11387
  }
@@ -10889,7 +11428,7 @@ async function resolveAttributionSalt(fs, stateRoot) {
10889
11428
  try {
10890
11429
  await fs.writeFile(path, new TextEncoder().encode(`${salt}
10891
11430
  `), "0600");
10892
- } catch (error) {
11431
+ } catch (error2) {
10893
11432
  return {
10894
11433
  salt: null,
10895
11434
  diagnostics: [
@@ -10897,7 +11436,7 @@ async function resolveAttributionSalt(fs, stateRoot) {
10897
11436
  diagnostic({
10898
11437
  severity: "warning",
10899
11438
  code: "attribution-salt-unwritable",
10900
- message: `The project attribution salt could not be stored, so metrics cannot be attributed to a project: ${error instanceof Error ? error.message : String(error)}`,
11439
+ message: `The project attribution salt could not be stored, so metrics cannot be attributed to a project: ${error2 instanceof Error ? error2.message : String(error2)}`,
10901
11440
  path,
10902
11441
  remediation: "Check that the Token Harness state directory is writable"
10903
11442
  })
@@ -10933,9 +11472,9 @@ function toValue(value3) {
10933
11472
  return value3 ? 1 : 0;
10934
11473
  return null;
10935
11474
  }
10936
- function classify2(error) {
10937
- const message = error instanceof Error ? error.message : String(error);
10938
- const code = error?.code;
11475
+ function classify2(error2) {
11476
+ const message = error2 instanceof Error ? error2.message : String(error2);
11477
+ const code = error2?.code;
10939
11478
  if (code === "ERR_UNKNOWN_BUILTIN_MODULE" || /Cannot find module 'node:sqlite'/.test(message)) {
10940
11479
  return { failure: "driver-unavailable", detail: "this runtime has no node:sqlite" };
10941
11480
  }
@@ -10951,8 +11490,8 @@ async function readLocalDatabase(request) {
10951
11490
  let construct;
10952
11491
  try {
10953
11492
  ({ DatabaseSync: construct } = await import("node:sqlite"));
10954
- } catch (error) {
10955
- return { rows: [], ...classify2(error) };
11493
+ } catch (error2) {
11494
+ return { rows: [], ...classify2(error2) };
10956
11495
  }
10957
11496
  let database = null;
10958
11497
  try {
@@ -10966,8 +11505,8 @@ async function readLocalDatabase(request) {
10966
11505
  return mapped;
10967
11506
  });
10968
11507
  return { rows, failure: null, detail: null };
10969
- } catch (error) {
10970
- return { rows: [], ...classify2(error) };
11508
+ } catch (error2) {
11509
+ return { rows: [], ...classify2(error2) };
10971
11510
  } finally {
10972
11511
  try {
10973
11512
  database?.close();
@@ -11820,8 +12359,8 @@ var init_node_runner = __esm({
11820
12359
  killTimer = setTimeout(() => this.terminateTree(child.pid, onPosix, true), this.options.killGraceMs ?? DEFAULT_KILL_GRACE_MS);
11821
12360
  }, timeoutMs);
11822
12361
  }
11823
- child.on("error", (error) => {
11824
- finish5(failureOutcome({ displayCommand, interpreter: plan6.interpreter, executablePath: resolved.path }, spawnFailureReason(error.code), redactText(`Starting ${resolved.path} failed: ${error.code ?? "unknown"} ${error.message}`, policy), now() - started));
12362
+ child.on("error", (error2) => {
12363
+ finish5(failureOutcome({ displayCommand, interpreter: plan6.interpreter, executablePath: resolved.path }, spawnFailureReason(error2.code), redactText(`Starting ${resolved.path} failed: ${error2.code ?? "unknown"} ${error2.message}`, policy), now() - started));
11825
12364
  });
11826
12365
  child.on("close", (code, signal) => {
11827
12366
  const durationMs = now() - started;
@@ -11973,7 +12512,7 @@ var init_host = __esm({
11973
12512
  var init_src2 = __esm({
11974
12513
  "packages/platform/dist/src/index.js"() {
11975
12514
  "use strict";
11976
- init_rtk_windows_release();
12515
+ init_rtk_release();
11977
12516
  init_node_filesystem();
11978
12517
  init_attribution_salt();
11979
12518
  init_sqlite_child();
@@ -12112,12 +12651,12 @@ async function recordProjectTransferEvidence(input) {
12112
12651
  reason: "observed transfer experiment is missing its measured payload"
12113
12652
  };
12114
12653
  }
12115
- const receiptPath3 = input.fs.join(input.stateRoot, "benchmarks", input.benchmarkId, "transfer.json");
12116
- if (await input.fs.stat(receiptPath3) !== null) {
12654
+ const receiptPath4 = input.fs.join(input.stateRoot, "benchmarks", input.benchmarkId, "transfer.json");
12655
+ if (await input.fs.stat(receiptPath4) !== null) {
12117
12656
  return {
12118
12657
  status: "exists",
12119
12658
  receipt: null,
12120
- receiptPath: receiptPath3,
12659
+ receiptPath: receiptPath4,
12121
12660
  reason: "transfer evidence receipt already exists and is immutable"
12122
12661
  };
12123
12662
  }
@@ -12136,17 +12675,17 @@ async function recordProjectTransferEvidence(input) {
12136
12675
  taskClass: experiment.stay.taskClass
12137
12676
  });
12138
12677
  try {
12139
- await input.fs.writeFile(receiptPath3, new TextEncoder().encode(`${JSON.stringify(receipt, null, 2)}
12678
+ await input.fs.writeFile(receiptPath4, new TextEncoder().encode(`${JSON.stringify(receipt, null, 2)}
12140
12679
  `));
12141
12680
  } catch {
12142
12681
  return {
12143
12682
  status: "write-failed",
12144
12683
  receipt: null,
12145
- receiptPath: receiptPath3,
12684
+ receiptPath: receiptPath4,
12146
12685
  reason: "transfer evidence receipt could not be written"
12147
12686
  };
12148
12687
  }
12149
- return { status: "recorded", receipt, receiptPath: receiptPath3, reason: null };
12688
+ return { status: "recorded", receipt, receiptPath: receiptPath4, reason: null };
12150
12689
  }
12151
12690
  async function resolveLocalTransferContext(cwd) {
12152
12691
  const resolution = resolveHostEnvironment();
@@ -13855,15 +14394,15 @@ var init_claude_benchmark_policy = __esm({
13855
14394
  });
13856
14395
 
13857
14396
  // packages/adapters/dist/src/harnesses/claude.js
13858
- function isRecord2(value3) {
14397
+ function isRecord3(value3) {
13859
14398
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
13860
14399
  }
13861
14400
  function readHooks(document2) {
13862
14401
  const found = /* @__PURE__ */ new Map();
13863
- if (!isRecord2(document2))
14402
+ if (!isRecord3(document2))
13864
14403
  return found;
13865
14404
  const hooks = document2["hooks"];
13866
- if (!isRecord2(hooks))
14405
+ if (!isRecord3(hooks))
13867
14406
  return found;
13868
14407
  for (const point of MANIFEST.interceptionPoints) {
13869
14408
  const list = hooks[point.eventName];
@@ -13871,12 +14410,12 @@ function readHooks(document2) {
13871
14410
  continue;
13872
14411
  const entries = [];
13873
14412
  for (const [entryIndex, item] of list.entries()) {
13874
- if (!isRecord2(item))
14413
+ if (!isRecord3(item))
13875
14414
  continue;
13876
14415
  const matcher = item["matcher"];
13877
14416
  const inner = item["hooks"];
13878
14417
  const hookCommands = Array.isArray(inner) ? inner.flatMap((hook, hookIndex) => {
13879
- if (!isRecord2(hook) || typeof hook["command"] !== "string")
14418
+ if (!isRecord3(hook) || typeof hook["command"] !== "string")
13880
14419
  return [];
13881
14420
  const eventSegment = point.eventName.replace(/\./g, "\\.");
13882
14421
  const entryPointer = `hooks.${eventSegment}.${String(entryIndex)}`;
@@ -14184,7 +14723,7 @@ function cclimitsReset(value3) {
14184
14723
  return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
14185
14724
  }
14186
14725
  function cclimitsUsageWindow(value3, input) {
14187
- if (!isRecord2(value3))
14726
+ if (!isRecord3(value3))
14188
14727
  return null;
14189
14728
  const usedPercent = cclimitsPercent(value3["used"]);
14190
14729
  const remainingPercent = cclimitsPercent(value3["remaining"]);
@@ -14251,7 +14790,7 @@ async function observeUsage(context, observedAt) {
14251
14790
  } catch {
14252
14791
  return unavailable3("cclimits-claude-schema-unrecognized", "cclimits returned output that is not valid JSON");
14253
14792
  }
14254
- if (!isRecord2(parsed) || !isRecord2(parsed["claude"])) {
14793
+ if (!isRecord3(parsed) || !isRecord3(parsed["claude"])) {
14255
14794
  return unavailable3("cclimits-claude-schema-unrecognized", "cclimits JSON did not contain a Claude usage object");
14256
14795
  }
14257
14796
  const claude = parsed["claude"];
@@ -14614,11 +15153,11 @@ var init_codex_hooks = __esm({
14614
15153
  });
14615
15154
 
14616
15155
  // packages/adapters/dist/src/harnesses/codex.js
14617
- function isRecord3(value3) {
15156
+ function isRecord4(value3) {
14618
15157
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
14619
15158
  }
14620
15159
  function readHooks2(document2) {
14621
- if (!isRecord3(document2) || !isRecord3(document2["hooks"]))
15160
+ if (!isRecord4(document2) || !isRecord4(document2["hooks"]))
14622
15161
  return { points: [], matchers: [], commands: [], hookCommands: [] };
14623
15162
  const hooks = document2["hooks"];
14624
15163
  const points = [];
@@ -14631,14 +15170,14 @@ function readHooks2(document2) {
14631
15170
  continue;
14632
15171
  let carries = false;
14633
15172
  for (const [entryIndex, entry] of entries.entries()) {
14634
- if (!isRecord3(entry))
15173
+ if (!isRecord4(entry))
14635
15174
  continue;
14636
15175
  const matcher = typeof entry["matcher"] === "string" ? entry["matcher"] : null;
14637
15176
  if (matcher !== null)
14638
15177
  matchers.push(matcher);
14639
15178
  if (Array.isArray(entry["hooks"])) {
14640
15179
  for (const [hookIndex, hook] of entry["hooks"].entries()) {
14641
- if (isRecord3(hook) && typeof hook["command"] === "string") {
15180
+ if (isRecord4(hook) && typeof hook["command"] === "string") {
14642
15181
  commands.push(hook["command"]);
14643
15182
  const entryPointer = `hooks.${point.eventName}.${String(entryIndex)}`;
14644
15183
  hookCommands.push({
@@ -14929,7 +15468,7 @@ function resetInstant(epochSeconds) {
14929
15468
  return Number.isNaN(date.getTime()) ? null : date.toISOString();
14930
15469
  }
14931
15470
  function rateWindow(value3, input) {
14932
- if (!isRecord3(value3))
15471
+ if (!isRecord4(value3))
14933
15472
  return null;
14934
15473
  const usedPercent = readNumber(value3, "usedPercent");
14935
15474
  const duration2 = readNumber(value3, "windowDurationMins");
@@ -14950,7 +15489,7 @@ function rateWindow(value3, input) {
14950
15489
  };
14951
15490
  }
14952
15491
  function snapshotWindows(value3, observedAt, fallbackBucketId) {
14953
- if (!isRecord3(value3))
15492
+ if (!isRecord4(value3))
14954
15493
  return { windows: [], planType: null, rateLimitReachedType: null };
14955
15494
  const bucketId = readString(value3, "limitId") ?? fallbackBucketId;
14956
15495
  const bucketName = readString(value3, "limitName");
@@ -14982,13 +15521,13 @@ function parseRateLimitResponse(stdout, observedAt) {
14982
15521
  } catch {
14983
15522
  }
14984
15523
  }
14985
- const response = messages.find((message) => isRecord3(message) && message["id"] === RATE_LIMIT_REQUEST_ID && isRecord3(message["result"]));
14986
- if (!isRecord3(response) || !isRecord3(response["result"]))
15524
+ const response = messages.find((message) => isRecord4(message) && message["id"] === RATE_LIMIT_REQUEST_ID && isRecord4(message["result"]));
15525
+ if (!isRecord4(response) || !isRecord4(response["result"]))
14987
15526
  return null;
14988
15527
  const result6 = response["result"];
14989
15528
  const snapshots = [];
14990
15529
  const byId = result6["rateLimitsByLimitId"];
14991
- if (isRecord3(byId)) {
15530
+ if (isRecord4(byId)) {
14992
15531
  for (const [id, value3] of Object.entries(byId)) {
14993
15532
  if (value3 !== void 0)
14994
15533
  snapshots.push({ id, value: value3 });
@@ -15008,7 +15547,7 @@ function parseRateLimitResponse(stdout, observedAt) {
15008
15547
  }
15009
15548
  let resetCreditsAvailable = null;
15010
15549
  const resetCredits = result6["rateLimitResetCredits"];
15011
- if (isRecord3(resetCredits)) {
15550
+ if (isRecord4(resetCredits)) {
15012
15551
  const available = readNumber(resetCredits, "availableCount");
15013
15552
  resetCreditsAvailable = available === null ? null : Math.max(0, Math.trunc(available));
15014
15553
  }
@@ -15027,7 +15566,7 @@ function cclimitsPercent2(value3) {
15027
15566
  return Number.isFinite(parsed) && parsed >= 0 && parsed <= 100 ? parsed : null;
15028
15567
  }
15029
15568
  function cclimitsWindow(value3, input) {
15030
- if (!isRecord3(value3))
15569
+ if (!isRecord4(value3))
15031
15570
  return null;
15032
15571
  const usedPercent = cclimitsPercent2(value3["used_percent"]) ?? cclimitsPercent2(value3["used"]);
15033
15572
  const remainingPercent = cclimitsPercent2(value3["remaining_percent"]) ?? cclimitsPercent2(value3["remaining"]);
@@ -15058,7 +15597,7 @@ function parseCclimitsCodexResponse(stdout, observedAt) {
15058
15597
  } catch {
15059
15598
  return null;
15060
15599
  }
15061
- if (!isRecord3(parsed) || !isRecord3(parsed["codex"]))
15600
+ if (!isRecord4(parsed) || !isRecord4(parsed["codex"]))
15062
15601
  return null;
15063
15602
  const codex = parsed["codex"];
15064
15603
  if (codex["status"] !== "ok")
@@ -15235,8 +15774,8 @@ function utf8Bytes(value3) {
15235
15774
  return value3 === null ? 0 : new TextEncoder().encode(value3).byteLength;
15236
15775
  }
15237
15776
  function rpcResult(messages, id) {
15238
- const response = messages.find((message) => isRecord3(message) && message["id"] === id && isRecord3(message["result"]));
15239
- return isRecord3(response) && isRecord3(response["result"]) ? response["result"] : null;
15777
+ const response = messages.find((message) => isRecord4(message) && message["id"] === id && isRecord4(message["result"]));
15778
+ return isRecord4(response) && isRecord4(response["result"]) ? response["result"] : null;
15240
15779
  }
15241
15780
  function parseJsonLines(stdout) {
15242
15781
  const messages = [];
@@ -15366,15 +15905,15 @@ async function observeContext2(context, _observedAt) {
15366
15905
  const mcpMessages = parseJsonLines(mcpOutcome.stdout);
15367
15906
  mcpResponse = rpcResult(mcpMessages, CONTEXT_MCP_REQUEST_ID) ?? rpcResult(mcpMessages, 3);
15368
15907
  }
15369
- const config = configResponse !== null && isRecord3(configResponse["config"]) ? configResponse["config"] : null;
15908
+ const config = configResponse !== null && isRecord4(configResponse["config"]) ? configResponse["config"] : null;
15370
15909
  const managedConfigTarget = (() => {
15371
15910
  const layers = configResponse?.["layers"];
15372
15911
  if (!Array.isArray(layers))
15373
15912
  return null;
15374
15913
  for (const layer of layers) {
15375
- if (!isRecord3(layer))
15914
+ if (!isRecord4(layer))
15376
15915
  continue;
15377
- const source = isRecord3(layer["name"]) ? layer["name"] : null;
15916
+ const source = isRecord4(layer["name"]) ? layer["name"] : null;
15378
15917
  if (source === null || readString(source, "type") !== "user")
15379
15918
  continue;
15380
15919
  if (readString(source, "profile") !== null)
@@ -15394,11 +15933,11 @@ async function observeContext2(context, _observedAt) {
15394
15933
  return null;
15395
15934
  })();
15396
15935
  const managedConfigFieldOrigins = [];
15397
- const origins = configResponse !== null && isRecord3(configResponse["origins"]) ? configResponse["origins"] : null;
15936
+ const origins = configResponse !== null && isRecord4(configResponse["origins"]) ? configResponse["origins"] : null;
15398
15937
  const managedConfigOriginsObserved = origins !== null;
15399
15938
  for (const keyPath of ["model", "model_reasoning_effort", "model_verbosity"]) {
15400
- const metadata = origins !== null && isRecord3(origins[keyPath]) ? origins[keyPath] : null;
15401
- const source = metadata !== null && isRecord3(metadata["name"]) ? metadata["name"] : null;
15939
+ const metadata = origins !== null && isRecord4(origins[keyPath]) ? origins[keyPath] : null;
15940
+ const source = metadata !== null && isRecord4(metadata["name"]) ? metadata["name"] : null;
15402
15941
  if (metadata === null || source === null)
15403
15942
  continue;
15404
15943
  const sourceType = readString(source, "type");
@@ -15418,14 +15957,14 @@ async function observeContext2(context, _observedAt) {
15418
15957
  source: "native-rpc"
15419
15958
  });
15420
15959
  }
15421
- const features = config !== null && isRecord3(config["features"]) ? config["features"] : null;
15960
+ const features = config !== null && isRecord4(config["features"]) ? config["features"] : null;
15422
15961
  const instructions = config === null ? null : readString(config, "instructions");
15423
15962
  const developerInstructions = config === null ? null : readString(config, "developer_instructions");
15424
15963
  const availableModels = [];
15425
15964
  const modelData = modelResponse?.["data"];
15426
15965
  if (Array.isArray(modelData)) {
15427
15966
  for (const item of modelData) {
15428
- if (!isRecord3(item))
15967
+ if (!isRecord4(item))
15429
15968
  continue;
15430
15969
  const id = readString(item, "id");
15431
15970
  const model = readString(item, "model");
@@ -15436,7 +15975,7 @@ async function observeContext2(context, _observedAt) {
15436
15975
  const effortOptions = item["supportedReasoningEfforts"];
15437
15976
  if (Array.isArray(effortOptions)) {
15438
15977
  for (const option of effortOptions) {
15439
- if (!isRecord3(option))
15978
+ if (!isRecord4(option))
15440
15979
  continue;
15441
15980
  const effort = readString(option, "reasoningEffort");
15442
15981
  if (effort !== null)
@@ -15461,12 +16000,12 @@ async function observeContext2(context, _observedAt) {
15461
16000
  const data = mcpResponse?.["data"];
15462
16001
  if (Array.isArray(data)) {
15463
16002
  for (const item of data) {
15464
- if (!isRecord3(item))
16003
+ if (!isRecord4(item))
15465
16004
  continue;
15466
16005
  const name2 = readString(item, "name");
15467
16006
  if (name2 === null)
15468
16007
  continue;
15469
- const tools = isRecord3(item["tools"]) ? item["tools"] : null;
16008
+ const tools = isRecord4(item["tools"]) ? item["tools"] : null;
15470
16009
  mcpServers.push({
15471
16010
  harnessId: CODEX,
15472
16011
  name: name2,
@@ -15856,11 +16395,11 @@ var init_hermes = __esm({
15856
16395
  });
15857
16396
 
15858
16397
  // packages/adapters/dist/src/harnesses/opencode.js
15859
- function isRecord4(value3) {
16398
+ function isRecord5(value3) {
15860
16399
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
15861
16400
  }
15862
16401
  function pluginEntries(document2) {
15863
- if (!isRecord4(document2) || !Array.isArray(document2["plugin"]))
16402
+ if (!isRecord5(document2) || !Array.isArray(document2["plugin"]))
15864
16403
  return [];
15865
16404
  return document2["plugin"].filter((item) => typeof item === "string");
15866
16405
  }
@@ -21556,6 +22095,379 @@ var init_providers = __esm({
21556
22095
  }
21557
22096
  });
21558
22097
 
22098
+ // packages/adapters/dist/src/routing/ccr-smart-routing.js
22099
+ function createCcrSmartRoutingScript(options) {
22100
+ const mode = options.mode ?? "shadow";
22101
+ const eventPathPrefix = `${options.telemetryDirectory}${options.pathSeparator}`;
22102
+ const classifierSource = classifySmartRoutingPrompt.toString();
22103
+ const eventSchemaVersion = 2;
22104
+ const classifierVersion = SMART_ROUTING_CLASSIFIER_VERSION;
22105
+ const configuredSimpleModel = typeof options.simpleModel === "string" && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(options.simpleModel) ? options.simpleModel : null;
22106
+ return `const classifySmartRoutingPrompt = (${classifierSource});
22107
+ const telemetryPathPrefix = ${JSON.stringify(eventPathPrefix)};
22108
+ const harnessId = ${JSON.stringify(options.harnessId)};
22109
+ const mode = ${JSON.stringify(mode)};
22110
+ const startedAt = Date.now();
22111
+ const safeInput = input && typeof input === "object" ? input : {};
22112
+ const summary = safeInput.summary && typeof safeInput.summary === "object" ? safeInput.summary : {};
22113
+ const headers = safeInput.headers && typeof safeInput.headers === "object" ? safeInput.headers : {};
22114
+ const headerSignals = [];
22115
+ for (const [name, rawValue] of Object.entries(headers)) {
22116
+ const key = name.toLowerCase();
22117
+ if (key !== "user-agent" && key !== "x-user-agent" && key !== "x-client-user-agent" && key !== "x-ccr-client" && key !== "x-client-name") continue;
22118
+ if (Array.isArray(rawValue)) headerSignals.push(rawValue.join(" "));
22119
+ else if (typeof rawValue === "string") headerSignals.push(rawValue);
22120
+ }
22121
+ const agentSignal = headerSignals.join(" ").toLowerCase();
22122
+ const detectedHarness = /openai-codex|codex[_ -]?cli/.test(agentSignal)
22123
+ ? "codex"
22124
+ : /@anthropic-ai\\/claude-code|claude[-_ ]code|claude[_ -]?cli/.test(agentSignal)
22125
+ ? "claude"
22126
+ : null;
22127
+ if (detectedHarness !== harnessId) return null;
22128
+ const prompt = typeof summary.lastUserText === "string" ? summary.lastUserText : "";
22129
+ const toolCount = Array.isArray(summary.toolNames) ? summary.toolNames.length : 0;
22130
+ const tokenCount = Number.isSafeInteger(safeInput.tokenCount) && safeInput.tokenCount > 0 ? safeInput.tokenCount : null;
22131
+ const decision = classifySmartRoutingPrompt({
22132
+ text: prompt,
22133
+ hasImage: summary.hasImage === true,
22134
+ toolCount,
22135
+ inputTokens: tokenCount
22136
+ });
22137
+ const rawSimpleModel = api.env("TOKEN_HARNESS_ROUTING_SIMPLE_MODEL");
22138
+ const simpleModel = typeof rawSimpleModel === "string" && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(rawSimpleModel)
22139
+ ? rawSimpleModel
22140
+ : ${JSON.stringify(configuredSimpleModel)};
22141
+ const requestModel = typeof safeInput.model === "string" && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(safeInput.model)
22142
+ ? safeInput.model
22143
+ : null;
22144
+ const rawSessionId = typeof safeInput.sessionId === "string" ? safeInput.sessionId : null;
22145
+ const sessionId = rawSessionId !== null && /^[A-Za-z0-9_.:-]{1,256}$/.test(rawSessionId) ? rawSessionId : null;
22146
+ const candidateModel = decision.tier === "simple" ? simpleModel : null;
22147
+ let routeMutationRequested = false;
22148
+ let routeSkipReason = null;
22149
+ if (mode === "shadow") {
22150
+ routeSkipReason = "shadow-mode";
22151
+ } else if (mode !== "conservative") {
22152
+ routeSkipReason = "unsupported-mode";
22153
+ } else if (decision.tier !== "simple") {
22154
+ routeSkipReason = "complexity-not-simple";
22155
+ } else if (candidateModel === null) {
22156
+ routeSkipReason = "simple-model-not-configured";
22157
+ } else if (requestModel === null) {
22158
+ routeSkipReason = "request-model-unavailable";
22159
+ } else if (!decision.conservativeEligible) {
22160
+ routeSkipReason = "conservative-safety-gate";
22161
+ } else if (toolCount > 0 && api.env("TOKEN_HARNESS_ROUTING_ALLOW_TOOLS") !== "true") {
22162
+ routeSkipReason = "tool-compatibility-unconfirmed";
22163
+ } else if (candidateModel === requestModel) {
22164
+ routeSkipReason = "model-already-selected";
22165
+ } else {
22166
+ routeMutationRequested = true;
22167
+ }
22168
+ const now = new Date();
22169
+ const epoch = now.getTime();
22170
+ const suffix = Math.random().toString(36).slice(2, 10);
22171
+ const eventId = String(epoch) + "-" + suffix;
22172
+ const event = {
22173
+ schemaVersion: ${eventSchemaVersion},
22174
+ eventId,
22175
+ timestamp: now.toISOString(),
22176
+ source: "ccr",
22177
+ harnessId,
22178
+ mode,
22179
+ classifierVersion: ${JSON.stringify(classifierVersion)},
22180
+ tier: decision.tier,
22181
+ score: decision.score,
22182
+ confidence: decision.confidence,
22183
+ reasonCodes: decision.reasonCodes,
22184
+ requestModel,
22185
+ candidateModel,
22186
+ routeMutationRequested,
22187
+ routeSkipReason,
22188
+ promptChars: decision.promptChars,
22189
+ requestInputTokenEstimate: tokenCount,
22190
+ toolCount,
22191
+ hasImage: decision.hasImage,
22192
+ decisionLatencyMs: Math.max(0, Date.now() - startedAt),
22193
+ sessionId,
22194
+ measurement: {
22195
+ status: "not-measured",
22196
+ resolvedModel: null,
22197
+ providerInputTokens: null,
22198
+ providerOutputTokens: null,
22199
+ qualityGate: "unknown"
22200
+ }
22201
+ };
22202
+ try {
22203
+ await api.fs.writeJson(telemetryPathPrefix + "smart-routing-" + String(epoch).padStart(13, "0") + "-" + suffix + ".json", event);
22204
+ } catch {
22205
+ // A telemetry write failure must never break the user's CCR request path.
22206
+ }
22207
+ if (routeMutationRequested) return { model: candidateModel };
22208
+ return null;`;
22209
+ }
22210
+ var init_ccr_smart_routing = __esm({
22211
+ "packages/adapters/dist/src/routing/ccr-smart-routing.js"() {
22212
+ "use strict";
22213
+ init_src();
22214
+ }
22215
+ });
22216
+
22217
+ // packages/adapters/dist/src/routing/ccr-management.js
22218
+ function isRecord6(value3) {
22219
+ return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
22220
+ }
22221
+ function numberField(value3) {
22222
+ return typeof value3 === "number" && Number.isSafeInteger(value3) && value3 >= 0 ? value3 : null;
22223
+ }
22224
+ function costField(value3) {
22225
+ return typeof value3 === "number" && Number.isFinite(value3) && value3 >= 0 ? value3 : null;
22226
+ }
22227
+ function resolveCcrManagementUrl(value3) {
22228
+ try {
22229
+ const url = new URL(value3?.trim() || DEFAULT_CCR_WEB_URL);
22230
+ if (url.protocol !== "http:" && url.protocol !== "https:" || !LOCAL_HOSTS.has(url.hostname.toLowerCase()) || url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") {
22231
+ return null;
22232
+ }
22233
+ url.pathname = "/";
22234
+ return url.toString().replace(/\/$/, "");
22235
+ } catch {
22236
+ return null;
22237
+ }
22238
+ }
22239
+ function ccrSmartRoutingRuleId(harness) {
22240
+ return `${CCR_ROUTING_RULE_ID_PREFIX}-${harness}-v1`;
22241
+ }
22242
+ function createCcrSmartRoutingRule(harness, scriptPath2) {
22243
+ return {
22244
+ enabled: true,
22245
+ id: ccrSmartRoutingRuleId(harness),
22246
+ name: `Token Harness Smart Routing (${harness}, shadow-first)`,
22247
+ script: {
22248
+ apiVersion: CCR_ROUTING_RULE_API_VERSION,
22249
+ file: scriptPath2,
22250
+ language: "javascript",
22251
+ timeoutMs: CCR_ROUTING_RULE_TIMEOUT_MS
22252
+ },
22253
+ type: "script"
22254
+ };
22255
+ }
22256
+ function stableJson(value3) {
22257
+ if (Array.isArray(value3))
22258
+ return `[${value3.map(stableJson).join(",")}]`;
22259
+ if (!isRecord6(value3))
22260
+ return JSON.stringify(value3);
22261
+ return `{${Object.keys(value3).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value3[key])}`).join(",")}}`;
22262
+ }
22263
+ function isExactCcrSmartRoutingRule(value3, expected) {
22264
+ return isRecord6(value3) && stableJson(value3) === stableJson(expected);
22265
+ }
22266
+ function isSameCcrConfig(left, right) {
22267
+ return isRecord6(left) && isRecord6(right) && stableJson(left) === stableJson(right);
22268
+ }
22269
+ function configRouter(config) {
22270
+ if (!isRecord6(config) || !isRecord6(config["Router"]) || !Array.isArray(config["Router"]["rules"])) {
22271
+ return null;
22272
+ }
22273
+ return {
22274
+ config,
22275
+ router: config["Router"],
22276
+ rules: config["Router"]["rules"]
22277
+ };
22278
+ }
22279
+ function addCcrSmartRoutingRule(config, rule) {
22280
+ const current = configRouter(config);
22281
+ if (current === null)
22282
+ return null;
22283
+ const existing = current.rules.find((item) => isRecord6(item) && item["id"] === rule["id"]);
22284
+ if (existing !== void 0)
22285
+ return isExactCcrSmartRoutingRule(existing, rule) ? current.config : null;
22286
+ return {
22287
+ ...current.config,
22288
+ Router: { ...current.router, rules: [rule, ...current.rules] }
22289
+ };
22290
+ }
22291
+ function removeOwnedCcrSmartRoutingRule(config, ruleId, expected) {
22292
+ const current = configRouter(config);
22293
+ if (current === null)
22294
+ return null;
22295
+ const matches = current.rules.filter((item) => isRecord6(item) && item["id"] === ruleId);
22296
+ if (matches.length !== 1 || !isExactCcrSmartRoutingRule(matches[0], expected))
22297
+ return null;
22298
+ return {
22299
+ ...current.config,
22300
+ Router: {
22301
+ ...current.router,
22302
+ rules: current.rules.filter((item) => !(isRecord6(item) && item["id"] === ruleId))
22303
+ }
22304
+ };
22305
+ }
22306
+ function readCcrVersion(value3) {
22307
+ if (!isRecord6(value3) || typeof value3["version"] !== "string")
22308
+ return null;
22309
+ return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(value3["version"]) ? value3["version"] : null;
22310
+ }
22311
+ function reduceCcrSessionUsage(value3, expectedSessionId, expectedAgent, since, until) {
22312
+ if (!isRecord6(value3) || value3["requestScanTruncated"] === true || !isRecord6(value3["selectedSession"])) {
22313
+ return null;
22314
+ }
22315
+ const selected = value3["selectedSession"];
22316
+ if (!isRecord6(selected["session"]) || selected["session"]["agent"] !== expectedAgent || selected["session"]["id"] !== `${expectedAgent}:${expectedSessionId}` || !Array.isArray(selected["requests"])) {
22317
+ return null;
22318
+ }
22319
+ const start = Date.parse(since);
22320
+ const end = Date.parse(until);
22321
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start)
22322
+ return null;
22323
+ const byModel = /* @__PURE__ */ new Map();
22324
+ for (const item of selected["requests"]) {
22325
+ if (!isRecord6(item) || item["sessionId"] !== expectedSessionId)
22326
+ continue;
22327
+ const createdAt = typeof item["createdAt"] === "string" ? Date.parse(item["createdAt"]) : Number.NaN;
22328
+ if (!Number.isFinite(createdAt) || createdAt < start || createdAt > end)
22329
+ continue;
22330
+ const model = item["model"];
22331
+ const inputTokens = numberField(item["inputTokens"]);
22332
+ const outputTokens = numberField(item["outputTokens"]);
22333
+ const cacheReadTokens = numberField(item["cacheReadTokens"]);
22334
+ const cacheWriteTokens = numberField(item["cacheWriteTokens"]);
22335
+ const totalTokens = numberField(item["totalTokens"]);
22336
+ if (typeof model !== "string" || !MODEL_ID.test(model) || inputTokens === null || outputTokens === null || cacheReadTokens === null || cacheWriteTokens === null || totalTokens === null) {
22337
+ continue;
22338
+ }
22339
+ const current = byModel.get(model) ?? {
22340
+ model,
22341
+ requestCount: 0,
22342
+ inputTokens: 0,
22343
+ outputTokens: 0,
22344
+ cacheReadTokens: 0,
22345
+ cacheWriteTokens: 0,
22346
+ totalTokens: 0,
22347
+ recordedCostUsd: 0
22348
+ };
22349
+ const recordedCostUsd = costField(item["costUsd"]);
22350
+ current.requestCount += 1;
22351
+ current.inputTokens += inputTokens;
22352
+ current.outputTokens += outputTokens;
22353
+ current.cacheReadTokens += cacheReadTokens;
22354
+ current.cacheWriteTokens += cacheWriteTokens;
22355
+ current.totalTokens += totalTokens;
22356
+ if (recordedCostUsd === null)
22357
+ current.recordedCostUsd = null;
22358
+ else if (current.recordedCostUsd !== null)
22359
+ current.recordedCostUsd += recordedCostUsd;
22360
+ byModel.set(model, current);
22361
+ }
22362
+ const rows = [...byModel.values()].sort((left, right) => left.model.localeCompare(right.model));
22363
+ if (rows.length === 0)
22364
+ return null;
22365
+ return {
22366
+ sessionId: expectedSessionId,
22367
+ requestCount: rows.reduce((total, row2) => total + row2.requestCount, 0),
22368
+ inputTokens: rows.reduce((total, row2) => total + row2.inputTokens, 0),
22369
+ outputTokens: rows.reduce((total, row2) => total + row2.outputTokens, 0),
22370
+ cacheReadTokens: rows.reduce((total, row2) => total + row2.cacheReadTokens, 0),
22371
+ cacheWriteTokens: rows.reduce((total, row2) => total + row2.cacheWriteTokens, 0),
22372
+ totalTokens: rows.reduce((total, row2) => total + row2.totalTokens, 0),
22373
+ recordedCostUsd: rows.length === 0 || rows.some((row2) => row2.recordedCostUsd === null) ? null : rows.reduce((total, row2) => total + (row2.recordedCostUsd ?? 0), 0),
22374
+ byModel: rows
22375
+ };
22376
+ }
22377
+ function ccrAgentForHarness(harness) {
22378
+ return HARNESS_AGENTS[harness];
22379
+ }
22380
+ var CCR_REVIEWED_VERSION, CCR_ROUTING_RULE_ID_PREFIX, CCR_ROUTING_RULE_API_VERSION, CCR_ROUTING_RULE_TIMEOUT_MS, CcrManagementError, DEFAULT_CCR_WEB_URL, CCR_RPC_PATH, CCR_RESPONSE_MAX_BYTES, LOCAL_HOSTS, MODEL_ID, HARNESS_AGENTS, CcrManagementClient;
22381
+ var init_ccr_management = __esm({
22382
+ "packages/adapters/dist/src/routing/ccr-management.js"() {
22383
+ "use strict";
22384
+ CCR_REVIEWED_VERSION = "3.1.1";
22385
+ CCR_ROUTING_RULE_ID_PREFIX = "token-harness-smart-routing";
22386
+ CCR_ROUTING_RULE_API_VERSION = 1;
22387
+ CCR_ROUTING_RULE_TIMEOUT_MS = 2e3;
22388
+ CcrManagementError = class extends Error {
22389
+ failure;
22390
+ constructor(failure) {
22391
+ super(`CCR management request failed (${failure})`);
22392
+ this.name = "CcrManagementError";
22393
+ this.failure = failure;
22394
+ }
22395
+ };
22396
+ DEFAULT_CCR_WEB_URL = "http://127.0.0.1:3458";
22397
+ CCR_RPC_PATH = "/api/ccr/rpc";
22398
+ CCR_RESPONSE_MAX_BYTES = 8 * 1024 * 1024;
22399
+ LOCAL_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
22400
+ MODEL_ID = /^[A-Za-z0-9_.:/@+ -]{1,160}$/;
22401
+ HARNESS_AGENTS = { claude: "claude-code", codex: "codex" };
22402
+ CcrManagementClient = class {
22403
+ baseUrl;
22404
+ token;
22405
+ fetcher;
22406
+ constructor(options = {}) {
22407
+ const baseUrl = resolveCcrManagementUrl(options.baseUrl);
22408
+ if (baseUrl === null)
22409
+ throw new CcrManagementError("endpoint-invalid");
22410
+ const token = options.authToken?.trim();
22411
+ if (!token || token.length > 512)
22412
+ throw new CcrManagementError("token-missing");
22413
+ this.baseUrl = baseUrl;
22414
+ this.token = token;
22415
+ this.fetcher = options.fetcher ?? globalThis.fetch;
22416
+ }
22417
+ async call(method, args = []) {
22418
+ let response;
22419
+ try {
22420
+ response = await this.fetcher(`${this.baseUrl}${CCR_RPC_PATH}`, {
22421
+ method: "POST",
22422
+ redirect: "error",
22423
+ signal: AbortSignal.timeout(8e3),
22424
+ headers: {
22425
+ "content-type": "application/json",
22426
+ "x-ccr-web-auth": this.token
22427
+ },
22428
+ body: JSON.stringify({ method, args })
22429
+ });
22430
+ } catch {
22431
+ throw new CcrManagementError("unreachable");
22432
+ }
22433
+ if (response.status === 401 || response.status === 403) {
22434
+ throw new CcrManagementError("unauthorized");
22435
+ }
22436
+ if (response.status === 404)
22437
+ throw new CcrManagementError("method-unavailable");
22438
+ if (!response.ok)
22439
+ throw new CcrManagementError("request-failed");
22440
+ const contentLength = Number(response.headers.get("content-length"));
22441
+ if (Number.isFinite(contentLength) && contentLength > CCR_RESPONSE_MAX_BYTES) {
22442
+ throw new CcrManagementError("invalid-response");
22443
+ }
22444
+ let payload;
22445
+ try {
22446
+ const text3 = await response.text();
22447
+ if (new TextEncoder().encode(text3).byteLength > CCR_RESPONSE_MAX_BYTES) {
22448
+ throw new CcrManagementError("invalid-response");
22449
+ }
22450
+ payload = JSON.parse(text3);
22451
+ } catch (error2) {
22452
+ if (error2 instanceof CcrManagementError)
22453
+ throw error2;
22454
+ throw new CcrManagementError("invalid-response");
22455
+ }
22456
+ if (!isRecord6(payload))
22457
+ throw new CcrManagementError("invalid-response");
22458
+ if (payload["ok"] !== true) {
22459
+ const message = isRecord6(payload["error"]) ? payload["error"]["message"] : void 0;
22460
+ if (typeof message === "string" && /unknown ccr web rpc method/i.test(message)) {
22461
+ throw new CcrManagementError("method-unavailable");
22462
+ }
22463
+ throw new CcrManagementError("request-failed");
22464
+ }
22465
+ return payload["value"];
22466
+ }
22467
+ };
22468
+ }
22469
+ });
22470
+
21559
22471
  // packages/adapters/dist/src/index.js
21560
22472
  var init_src3 = __esm({
21561
22473
  "packages/adapters/dist/src/index.js"() {
@@ -21563,6 +22475,8 @@ var init_src3 = __esm({
21563
22475
  init_harnesses();
21564
22476
  init_providers();
21565
22477
  init_rtk_plan();
22478
+ init_ccr_smart_routing();
22479
+ init_ccr_management();
21566
22480
  }
21567
22481
  });
21568
22482
 
@@ -21915,6 +22829,14 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
21915
22829
  tasksLeft: null,
21916
22830
  contextSnapshot: null,
21917
22831
  nativePolicy: false,
22832
+ routingScript: false,
22833
+ routingMetrics: false,
22834
+ routingMode: "shadow",
22835
+ routingPrune: false,
22836
+ routingCcrConfigure: false,
22837
+ routingCcrRollback: false,
22838
+ routingCcrUpdate: false,
22839
+ routingCcrUsage: false,
21918
22840
  agentSkill: false,
21919
22841
  verbose: false,
21920
22842
  yes: false
@@ -21954,6 +22876,20 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
21954
22876
  options.nativePolicy = true;
21955
22877
  if (name2 === "--agent-skill")
21956
22878
  options.agentSkill = true;
22879
+ if (name2 === "--script")
22880
+ options.routingScript = true;
22881
+ if (name2 === "--route-metrics")
22882
+ options.routingMetrics = true;
22883
+ if (name2 === "--prune")
22884
+ options.routingPrune = true;
22885
+ if (name2 === "--configure-ccr")
22886
+ options.routingCcrConfigure = true;
22887
+ if (name2 === "--rollback-ccr")
22888
+ options.routingCcrRollback = true;
22889
+ if (name2 === "--update-ccr")
22890
+ options.routingCcrUpdate = true;
22891
+ if (name2 === "--ccr-usage")
22892
+ options.routingCcrUsage = true;
21957
22893
  if (name2 === "--verbose")
21958
22894
  options.verbose = true;
21959
22895
  continue;
@@ -22159,6 +23095,18 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22159
23095
  }
22160
23096
  break;
22161
23097
  }
23098
+ case "--route-mode":
23099
+ if (value3 !== "shadow" && value3 !== "conservative") {
23100
+ diagnostics.push(diagnostic({
23101
+ severity: "error",
23102
+ code: "invalid-routing-mode",
23103
+ message: `Routing mode ${JSON.stringify(value3)} is not supported`,
23104
+ remediation: "Use --route-mode shadow or --route-mode conservative"
23105
+ }));
23106
+ } else {
23107
+ options.routingMode = value3;
23108
+ }
23109
+ break;
22162
23110
  case "--context-snapshot":
22163
23111
  options.contextSnapshot = value3;
22164
23112
  break;
@@ -22229,6 +23177,7 @@ var init_argv = __esm({
22229
23177
  "optimize",
22230
23178
  "plan",
22231
23179
  "rollback",
23180
+ "routing",
22232
23181
  "setup",
22233
23182
  "status",
22234
23183
  "stack-review",
@@ -22257,9 +23206,23 @@ var init_argv = __esm({
22257
23206
  "--profile",
22258
23207
  "--reserve",
22259
23208
  "--tasks-left",
23209
+ "--route-mode",
22260
23210
  "--context-snapshot"
22261
23211
  ]);
22262
- BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--json", "--native-policy", "--agent-skill", "--verbose", "--yes"]);
23212
+ BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
23213
+ "--json",
23214
+ "--native-policy",
23215
+ "--agent-skill",
23216
+ "--verbose",
23217
+ "--yes",
23218
+ "--script",
23219
+ "--route-metrics",
23220
+ "--prune",
23221
+ "--configure-ccr",
23222
+ "--rollback-ccr",
23223
+ "--update-ccr",
23224
+ "--ccr-usage"
23225
+ ]);
22263
23226
  }
22264
23227
  });
22265
23228
 
@@ -22309,12 +23272,12 @@ function parseGitNexusIndexReadiness(output) {
22309
23272
  if (receipt["schemaVersion"] !== 1)
22310
23273
  return { state: "invalid", detail: null };
22311
23274
  const status = safeGitNexusStatusLabel(receipt["status"]);
22312
- const error = safeGitNexusStatusLabel(receipt["error"]);
23275
+ const error2 = safeGitNexusStatusLabel(receipt["error"]);
22313
23276
  if (status === "up-to-date" && receipt["error"] === void 0) {
22314
23277
  return { state: "up-to-date", detail: null };
22315
23278
  }
22316
23279
  if (receipt["error"] !== void 0)
22317
- return { state: "not-ready", detail: error };
23280
+ return { state: "not-ready", detail: error2 };
22318
23281
  if (receipt["status"] !== void 0)
22319
23282
  return { state: "not-ready", detail: status };
22320
23283
  return { state: "invalid", detail: null };
@@ -24451,15 +25414,15 @@ async function readOptimizationHistory(context) {
24451
25414
  continue;
24452
25415
  result6.scannedBenchmarks += 1;
24453
25416
  for (const variant of ["baseline", "optimized"]) {
24454
- const receiptPath3 = fs.join(directory, `${variant}.json`);
24455
- if (await fs.stat(receiptPath3) === null)
25417
+ const receiptPath4 = fs.join(directory, `${variant}.json`);
25418
+ if (await fs.stat(receiptPath4) === null)
24456
25419
  continue;
24457
25420
  const capture = parseTaskBenchmarkCapture(await read(fs.join(directory, `${variant}.capture.json`)));
24458
25421
  if (!capture.ok)
24459
25422
  return result6;
24460
25423
  if (capture.capture.projectId !== project)
24461
25424
  continue;
24462
- const receipt = parseTaskBenchmarkReceipt(await read(receiptPath3));
25425
+ const receipt = parseTaskBenchmarkReceipt(await read(receiptPath4));
24463
25426
  if (!receipt.ok)
24464
25427
  return result6;
24465
25428
  const start = capture.capture;
@@ -25752,12 +26715,12 @@ async function verifyManagedIntegrationPostconditions(context, integrations) {
25752
26715
  remediation: runtimeProblem?.remediation ?? "Check that the newly installed provider executable is on PATH, then review a fresh setup preview"
25753
26716
  }));
25754
26717
  }
25755
- } catch (error) {
26718
+ } catch (error2) {
25756
26719
  diagnostics.push(diagnostic({
25757
26720
  severity: "error",
25758
26721
  code: "managed-setup-postcondition-unavailable",
25759
26722
  subject: integration.providerId,
25760
- message: `The provider could not be re-observed after setup: ${error instanceof Error ? error.message : String(error)}`,
26723
+ message: `The provider could not be re-observed after setup: ${error2 instanceof Error ? error2.message : String(error2)}`,
25761
26724
  remediation: "Refresh and inspect the provider runtime before retrying"
25762
26725
  }));
25763
26726
  }
@@ -25811,13 +26774,13 @@ async function loadStoredPlan(context, planId) {
25811
26774
  throw new TypeError("A stored plan must be a JSON object");
25812
26775
  }
25813
26776
  return { stored: parsed, diagnostic: null };
25814
- } catch (error) {
26777
+ } catch (error2) {
25815
26778
  return {
25816
26779
  stored: null,
25817
26780
  diagnostic: diagnostic({
25818
26781
  severity: "error",
25819
26782
  code: "plan-unreadable",
25820
- message: `The stored plan could not be read: ${error instanceof Error ? error.message : String(error)}`,
26783
+ message: `The stored plan could not be read: ${error2 instanceof Error ? error2.message : String(error2)}`,
25821
26784
  path,
25822
26785
  remediation: "Run `token-harness plan` to compute a new one"
25823
26786
  })
@@ -26206,6 +27169,596 @@ var init_benchmark2 = __esm({
26206
27169
  }
26207
27170
  });
26208
27171
 
27172
+ // apps/cli/dist/src/commands/ccr-runtime.js
27173
+ import { randomBytes as randomBytes2 } from "node:crypto";
27174
+ function ccrRuntimeRoot(context) {
27175
+ return context.adapters.fs.join(context.stateRoot, "smart-routing", "ccr");
27176
+ }
27177
+ function runtimeReceiptPath(context) {
27178
+ return context.adapters.fs.join(ccrRuntimeRoot(context), "runtime.json");
27179
+ }
27180
+ function runtimeTokenPath(context) {
27181
+ return context.adapters.fs.join(ccrRuntimeRoot(context), "web-auth-token");
27182
+ }
27183
+ function packagePrefix(context, version3) {
27184
+ return context.adapters.fs.join(ccrRuntimeRoot(context), "versions", version3);
27185
+ }
27186
+ function ccrExecutable(context, prefix) {
27187
+ const suffix = context.platform.os === "windows" && !context.platform.isWsl ? ".cmd" : "";
27188
+ return context.adapters.fs.join(prefix, "node_modules", ".bin", `ccr${suffix}`);
27189
+ }
27190
+ function parseJsonRecord(value3) {
27191
+ return typeof value3 === "object" && value3 !== null && !Array.isArray(value3) ? value3 : null;
27192
+ }
27193
+ async function readManagedCcrRuntime(context) {
27194
+ if (context.adapters === null || context.stateRoot === null)
27195
+ return null;
27196
+ try {
27197
+ const bytes = await context.adapters.fs.readFile(runtimeReceiptPath(context));
27198
+ const receipt = parseJsonRecord(JSON.parse(new TextDecoder().decode(bytes)));
27199
+ if (receipt?.["schemaVersion"] !== 1 || typeof receipt["version"] !== "string" || !/^\d+\.\d+\.\d+$/.test(receipt["version"]) || typeof receipt["installPrefix"] !== "string" || typeof receipt["executablePath"] !== "string" || typeof receipt["managementEndpoint"] !== "string" || typeof receipt["installedAt"] !== "string") {
27200
+ return null;
27201
+ }
27202
+ const expectedPrefix = packagePrefix(context, receipt["version"]);
27203
+ if (receipt["installPrefix"] !== expectedPrefix || receipt["executablePath"] !== ccrExecutable(context, expectedPrefix) || resolveCcrManagementUrl(receipt["managementEndpoint"]) !== receipt["managementEndpoint"]) {
27204
+ return null;
27205
+ }
27206
+ return receipt;
27207
+ } catch {
27208
+ return null;
27209
+ }
27210
+ }
27211
+ async function readPrivateToken(context) {
27212
+ if (context.adapters === null || context.stateRoot === null)
27213
+ return null;
27214
+ try {
27215
+ const value3 = new TextDecoder().decode(await context.adapters.fs.readFile(runtimeTokenPath(context))).trim();
27216
+ return /^[A-Za-z0-9_-]{32,128}$/.test(value3) ? value3 : null;
27217
+ } catch {
27218
+ return null;
27219
+ }
27220
+ }
27221
+ async function resolveManagedCcr(context) {
27222
+ const envToken = context.env?.["CCR_WEB_AUTH_TOKEN"]?.trim();
27223
+ const envUrl = context.env?.["CCR_WEB_URL"];
27224
+ if (envToken) {
27225
+ const endpoint = resolveCcrManagementUrl(envUrl);
27226
+ if (endpoint === null)
27227
+ throw new CcrManagementError("endpoint-invalid");
27228
+ return { kind: "external", endpoint, token: envToken };
27229
+ }
27230
+ if (envUrl !== void 0 && envUrl.trim() !== "")
27231
+ throw new CcrManagementError("token-missing");
27232
+ const receipt = await readManagedCcrRuntime(context);
27233
+ const token = await readPrivateToken(context);
27234
+ if (receipt !== null && token !== null) {
27235
+ return {
27236
+ kind: "managed",
27237
+ endpoint: receipt.managementEndpoint,
27238
+ token,
27239
+ receipt
27240
+ };
27241
+ }
27242
+ const service = await readCcrServiceState(context);
27243
+ if (service !== null)
27244
+ return service;
27245
+ return { kind: "unavailable" };
27246
+ }
27247
+ async function readCcrServiceState(context) {
27248
+ if (context.adapters === null || context.home === null)
27249
+ return null;
27250
+ const windows = context.platform.os === "windows" && !context.platform.isWsl;
27251
+ const appData = context.env?.["APPDATA"];
27252
+ const configDirectory = windows ? context.adapters.fs.join(appData || context.adapters.fs.join(context.home, "AppData", "Roaming"), "claude-code-router") : context.adapters.fs.join(context.home, ".claude-code-router");
27253
+ try {
27254
+ const bytes = await context.adapters.fs.readFile(context.adapters.fs.join(configDirectory, "service.json"));
27255
+ const state = parseJsonRecord(JSON.parse(new TextDecoder().decode(bytes)));
27256
+ if (typeof state?.["url"] !== "string")
27257
+ return null;
27258
+ const serviceUrl = new URL(state["url"]);
27259
+ const endpoint = resolveCcrManagementUrl(serviceUrl.origin);
27260
+ const token = serviceUrl.searchParams.get("ccr_web_token")?.trim();
27261
+ if (endpoint === null || token === void 0 || !/^[A-Za-z0-9_-]{32,128}$/.test(token))
27262
+ return null;
27263
+ const client = new CcrManagementClient({
27264
+ baseUrl: endpoint,
27265
+ authToken: token,
27266
+ ...context.ccrFetch === void 0 ? {} : { fetcher: context.ccrFetch }
27267
+ });
27268
+ const version3 = readCcrVersion(await client.call("getAppInfo"));
27269
+ if (version3 === null)
27270
+ return null;
27271
+ return { kind: "external", endpoint, token };
27272
+ } catch {
27273
+ return null;
27274
+ }
27275
+ }
27276
+ async function localManagementPortIsOccupied(context) {
27277
+ const fetcher = context.ccrFetch ?? globalThis.fetch;
27278
+ try {
27279
+ const response = await fetcher(`http://127.0.0.1:${String(DEFAULT_WEB_PORT)}/api/ccr/rpc`, {
27280
+ method: "POST",
27281
+ redirect: "error",
27282
+ signal: AbortSignal.timeout(1e3),
27283
+ headers: { "content-type": "application/json" },
27284
+ body: JSON.stringify({ method: "getAppInfo", args: [] })
27285
+ });
27286
+ return response.status >= 100 && response.status <= 599;
27287
+ } catch {
27288
+ return false;
27289
+ }
27290
+ }
27291
+ function lifecycleError(code, message, remediation) {
27292
+ return commandResult({
27293
+ command: "routing",
27294
+ exitCode: EXIT_CODES["problems-found"],
27295
+ diagnostics: [diagnostic({ severity: "error", code, message, remediation })]
27296
+ });
27297
+ }
27298
+ function lifecyclePreview(action, state, context, receipt) {
27299
+ const fs = context.adapters.fs;
27300
+ const prefix = packagePrefix(context, CCR_REVIEWED_VERSION);
27301
+ const executable = ccrExecutable(context, prefix);
27302
+ const endpoint = receipt?.managementEndpoint ?? `http://127.0.0.1:${String(DEFAULT_WEB_PORT)}`;
27303
+ return commandResult({
27304
+ command: "routing",
27305
+ exitCode: EXIT_CODES.ok,
27306
+ data: {
27307
+ kind: "ccr-lifecycle",
27308
+ action,
27309
+ state,
27310
+ version: CCR_REVIEWED_VERSION,
27311
+ packagePath: prefix,
27312
+ executablePath: executable,
27313
+ managementEndpoint: endpoint
27314
+ },
27315
+ diagnostics: [
27316
+ diagnostic({
27317
+ severity: "info",
27318
+ code: `ccr-${action}-preview`,
27319
+ message: state === "already-current" ? `Token Harness manages CCR CLI ${CCR_REVIEWED_VERSION}; no package update is needed` : action === "install" ? `Token Harness would install CCR CLI ${CCR_REVIEWED_VERSION} in its protected local state directory` : action === "update" ? `Token Harness would stop its managed CCR service, install reviewed CCR ${CCR_REVIEWED_VERSION}, then restart and verify it` : `Token Harness would start its managed CCR ${CCR_REVIEWED_VERSION} service on loopback`,
27320
+ path: fs.join(ccrRuntimeRoot(context), "runtime.json"),
27321
+ remediation: state === "already-current" ? "Use `token-harness routing --configure-ccr --harness <claude|codex> --yes` to verify or configure the owned shadow rule" : "Review the local package installation and gateway restart, then rerun with `--yes`; no global CCR package or harness configuration is replaced"
27322
+ })
27323
+ ]
27324
+ });
27325
+ }
27326
+ function successfulProcess(outcome2) {
27327
+ return outcome2.failure === null && outcome2.exitCode === 0;
27328
+ }
27329
+ function managementPortFromOutput(output) {
27330
+ const match = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/i.exec(output);
27331
+ const port = Number(match?.[1]);
27332
+ return Number.isInteger(port) && port > 0 && port <= 65535 ? port : DEFAULT_WEB_PORT;
27333
+ }
27334
+ async function packageVersionAt(context, prefix) {
27335
+ try {
27336
+ const path = context.adapters.fs.join(prefix, "node_modules", "@musistudio", "claude-code-router", "package.json");
27337
+ const parsed = parseJsonRecord(JSON.parse(new TextDecoder().decode(await context.adapters.fs.readFile(path))));
27338
+ return typeof parsed?.["version"] === "string" ? parsed["version"] : null;
27339
+ } catch {
27340
+ return null;
27341
+ }
27342
+ }
27343
+ async function runCcrExecutable(context, executable, args, token) {
27344
+ const env = { CCR_WEB_AUTH_TOKEN: token };
27345
+ const simpleModel = context.env?.["TOKEN_HARNESS_ROUTING_SIMPLE_MODEL"]?.trim();
27346
+ if (simpleModel && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(simpleModel)) {
27347
+ env["TOKEN_HARNESS_ROUTING_SIMPLE_MODEL"] = simpleModel;
27348
+ }
27349
+ return context.adapters.runner.run({
27350
+ executable,
27351
+ args,
27352
+ cwd: context.projectRoot,
27353
+ env,
27354
+ timeoutMs: 45e3,
27355
+ maxOutputBytes: 128 * 1024,
27356
+ secretValues: [token]
27357
+ });
27358
+ }
27359
+ async function startAndVerify(context, receipt, token, expectedVersion = CCR_REVIEWED_VERSION) {
27360
+ const start = await runCcrExecutable(context, receipt.executablePath, [
27361
+ "start",
27362
+ "--daemon",
27363
+ "--host",
27364
+ "127.0.0.1",
27365
+ "--port",
27366
+ String(DEFAULT_WEB_PORT),
27367
+ "--no-open",
27368
+ "--gateway"
27369
+ ], token);
27370
+ if (!successfulProcess(start))
27371
+ return null;
27372
+ const port = managementPortFromOutput(`${start.stdout}
27373
+ ${start.stderr}`);
27374
+ const endpoint = resolveCcrManagementUrl(`http://127.0.0.1:${String(port)}`);
27375
+ if (endpoint === null)
27376
+ return null;
27377
+ const client = new CcrManagementClient({
27378
+ baseUrl: endpoint,
27379
+ authToken: token,
27380
+ ...context.ccrFetch === void 0 ? {} : { fetcher: context.ccrFetch }
27381
+ });
27382
+ try {
27383
+ const version3 = readCcrVersion(await client.call("getAppInfo"));
27384
+ const gateway = parseJsonRecord(await client.call("getGatewayStatus"));
27385
+ if (version3 !== expectedVersion || gateway?.["state"] !== "running")
27386
+ return null;
27387
+ return { endpoint, version: version3 };
27388
+ } catch {
27389
+ return null;
27390
+ }
27391
+ }
27392
+ async function verifyManagedService(context, receipt, token) {
27393
+ const client = new CcrManagementClient({
27394
+ baseUrl: receipt.managementEndpoint,
27395
+ authToken: token,
27396
+ ...context.ccrFetch === void 0 ? {} : { fetcher: context.ccrFetch }
27397
+ });
27398
+ try {
27399
+ const version3 = readCcrVersion(await client.call("getAppInfo"));
27400
+ const gateway = parseJsonRecord(await client.call("getGatewayStatus"));
27401
+ if (version3 === null)
27402
+ return null;
27403
+ return { version: version3, running: gateway?.["state"] === "running" };
27404
+ } catch {
27405
+ return null;
27406
+ }
27407
+ }
27408
+ async function ensureManagedCcrRuntime(input) {
27409
+ const { context } = input;
27410
+ if (context.adapters === null || context.stateRoot === null) {
27411
+ return {
27412
+ kind: "result",
27413
+ result: lifecycleError("ccr-local-state-required", "Managed CCR needs Token Harness local state and process adapters", "Run this command from the local Token Harness installation")
27414
+ };
27415
+ }
27416
+ const nodeMajor = Number(/^v?(\d+)/.exec(context.platform.nodeVersion ?? "")?.[1]);
27417
+ if (!Number.isInteger(nodeMajor) || nodeMajor < 22) {
27418
+ return {
27419
+ kind: "result",
27420
+ result: lifecycleError("ccr-node-version-unsupported", "CCR CLI requires Node.js 22 or newer", "Run Token Harness with Node.js 22+ and retry")
27421
+ };
27422
+ }
27423
+ const fs = context.adapters.fs;
27424
+ const root = ccrRuntimeRoot(context);
27425
+ const prior = await readManagedCcrRuntime(context);
27426
+ const token = await readPrivateToken(context);
27427
+ if (prior === null && await fs.stat(runtimeReceiptPath(context)) !== null) {
27428
+ return {
27429
+ kind: "result",
27430
+ result: lifecycleError("ccr-runtime-receipt-unrecognized", "The local CCR runtime receipt exists but is not a valid Token Harness ownership record", "Inspect or move the receipt before setup; Token Harness will not overwrite unrecognized runtime state")
27431
+ };
27432
+ }
27433
+ if (prior === null && await fs.stat(runtimeTokenPath(context)) !== null) {
27434
+ return {
27435
+ kind: "result",
27436
+ result: lifecycleError("ccr-runtime-token-unrecognized", "A local CCR credential exists without a valid Token Harness ownership receipt", "Inspect or move the credential before setup; Token Harness will not replace unrecognized authentication state")
27437
+ };
27438
+ }
27439
+ if (prior !== null && token === null) {
27440
+ return {
27441
+ kind: "result",
27442
+ result: lifecycleError("ccr-managed-token-missing", "Token Harness could not read the private credential for its managed CCR service", "Restore the private credential from a backup or remove the managed runtime manually before reinstalling")
27443
+ };
27444
+ }
27445
+ if (prior === null && await localManagementPortIsOccupied(context)) {
27446
+ return {
27447
+ kind: "result",
27448
+ result: lifecycleError("ccr-existing-service-auth-required", "A local service is already listening on CCR\u2019s default management port, but Token Harness cannot authenticate to it", "Set CCR_WEB_AUTH_TOKEN and optionally CCR_WEB_URL to connect to that CCR instance; Token Harness will not start a second gateway beside it")
27449
+ };
27450
+ }
27451
+ if (input.action === "update" && prior === null) {
27452
+ return {
27453
+ kind: "result",
27454
+ result: lifecycleError("ccr-managed-runtime-required", "Token Harness has no CCR CLI installation to update", "Run `token-harness routing --configure-ccr --harness <claude|codex>` first")
27455
+ };
27456
+ }
27457
+ if (prior?.version === CCR_REVIEWED_VERSION) {
27458
+ if (token === null)
27459
+ return {
27460
+ kind: "result",
27461
+ result: lifecycleError("ccr-managed-token-missing", "Token Harness could not read its private CCR management credential", "Inspect the protected Token Harness smart-routing state and rerun setup if the credential was removed")
27462
+ };
27463
+ const current = await verifyManagedService(context, prior, token);
27464
+ if (current?.version === CCR_REVIEWED_VERSION && current.running) {
27465
+ return input.action === "update" ? { kind: "result", result: lifecyclePreview("update", "already-current", context, prior) } : {
27466
+ kind: "ready",
27467
+ endpoint: prior.managementEndpoint,
27468
+ token,
27469
+ changed: false,
27470
+ lifecycleAction: "start",
27471
+ packagePath: prior.installPrefix,
27472
+ executablePath: prior.executablePath
27473
+ };
27474
+ }
27475
+ }
27476
+ if (!context.confirmed) {
27477
+ const action = prior === null ? "install" : prior.version === CCR_REVIEWED_VERSION ? "start" : "update";
27478
+ return {
27479
+ kind: "result",
27480
+ result: lifecyclePreview(action, "preview", context, prior ?? void 0)
27481
+ };
27482
+ }
27483
+ const runtimeToken = token ?? randomBytes2(32).toString("base64url");
27484
+ const prefix = packagePrefix(context, CCR_REVIEWED_VERSION);
27485
+ const executable = ccrExecutable(context, prefix);
27486
+ const existingPrefixStat = await fs.stat(prefix);
27487
+ if (prior === null && existingPrefixStat !== null) {
27488
+ return {
27489
+ kind: "result",
27490
+ result: lifecycleError("ccr-install-path-unowned", "The Token Harness CCR package path already contains files with no ownership receipt", "Inspect the path reported in the preview and move it before setup; Token Harness will not adopt unknown files")
27491
+ };
27492
+ }
27493
+ let changed = false;
27494
+ if (await packageVersionAt(context, prefix) !== CCR_REVIEWED_VERSION) {
27495
+ const npm = context.adapters.resolveExecutables?.("npm") ?? [];
27496
+ if (npm.length === 0 && context.adapters.resolveExecutables !== void 0) {
27497
+ return {
27498
+ kind: "result",
27499
+ result: lifecycleError("ccr-npm-not-found", "npm could not be resolved, so CCR was not installed", "Install npm with Node.js 22+ and retry")
27500
+ };
27501
+ }
27502
+ if (prior !== null) {
27503
+ const stop = await runCcrExecutable(context, prior.executablePath, ["stop"], runtimeToken);
27504
+ if (!successfulProcess(stop)) {
27505
+ return {
27506
+ kind: "result",
27507
+ result: lifecycleError("ccr-stop-before-update-failed", "Token Harness could not stop its managed CCR service before updating", "Review the local CCR service and retry; the current installation was left in place")
27508
+ };
27509
+ }
27510
+ }
27511
+ const install = await context.adapters.runner.run({
27512
+ executable: "npm",
27513
+ args: [
27514
+ "install",
27515
+ "--prefix",
27516
+ prefix,
27517
+ "--no-save",
27518
+ "--package-lock=true",
27519
+ `${CCR_PACKAGE}@${CCR_REVIEWED_VERSION}`
27520
+ ],
27521
+ cwd: context.projectRoot,
27522
+ timeoutMs: 10 * 6e4,
27523
+ maxOutputBytes: 256 * 1024
27524
+ });
27525
+ if (!successfulProcess(install) || await packageVersionAt(context, prefix) !== CCR_REVIEWED_VERSION) {
27526
+ const restored = prior !== null && await startAndVerify(context, prior, runtimeToken, prior.version) !== null;
27527
+ return {
27528
+ kind: "result",
27529
+ result: lifecycleError("ccr-npm-install-failed", `npm did not install the reviewed CCR CLI ${CCR_REVIEWED_VERSION}`, restored ? "The previously managed CCR package and gateway were restored; check npm connectivity and retry from a fresh preview" : prior !== null ? "The package update failed and Token Harness could not verify restart of the previous gateway; inspect local CCR status before retrying" : "Check npm connectivity and retry from a fresh preview; no global npm package was modified")
27530
+ };
27531
+ }
27532
+ changed = true;
27533
+ }
27534
+ const provisional = {
27535
+ schemaVersion: 1,
27536
+ version: CCR_REVIEWED_VERSION,
27537
+ installPrefix: prefix,
27538
+ executablePath: executable,
27539
+ managementEndpoint: prior?.managementEndpoint ?? `http://127.0.0.1:${String(DEFAULT_WEB_PORT)}`,
27540
+ installedAt: prior?.installedAt ?? context.now()
27541
+ };
27542
+ try {
27543
+ await fs.createDirectory(root);
27544
+ await fs.writeFile(runtimeTokenPath(context), new TextEncoder().encode(`${runtimeToken}
27545
+ `), "0600");
27546
+ } catch {
27547
+ return {
27548
+ kind: "result",
27549
+ result: lifecycleError("ccr-token-store-failed", "Token Harness could not store the local CCR management credential securely", "Check Token Harness state-directory permissions; no CCR profile or route change was applied")
27550
+ };
27551
+ }
27552
+ try {
27553
+ await fs.writeFile(runtimeReceiptPath(context), new TextEncoder().encode(`${JSON.stringify(provisional, null, 2)}
27554
+ `), "0600");
27555
+ } catch {
27556
+ return {
27557
+ kind: "result",
27558
+ result: lifecycleError("ccr-receipt-write-failed", "Token Harness could not save the local CCR ownership receipt before starting the service", "Repair the protected Token Harness state directory; CCR was not started")
27559
+ };
27560
+ }
27561
+ const started = await startAndVerify(context, provisional, runtimeToken);
27562
+ if (started === null) {
27563
+ if (prior !== null) {
27564
+ const restored = await startAndVerify(context, prior, runtimeToken, prior.version) !== null;
27565
+ if (!restored)
27566
+ return {
27567
+ kind: "result",
27568
+ result: lifecycleError("ccr-start-verification-failed", "The new CCR service failed verification and Token Harness could not verify restart of the previous gateway", "Inspect local CCR status before retrying; the ownership receipt was retained for recovery")
27569
+ };
27570
+ await fs.writeFile(runtimeReceiptPath(context), new TextEncoder().encode(`${JSON.stringify(prior, null, 2)}
27571
+ `), "0600");
27572
+ }
27573
+ return {
27574
+ kind: "result",
27575
+ result: lifecycleError("ccr-start-verification-failed", "The managed CCR service did not pass its local version and gateway checks", "Inspect CCR service status and retry; Token Harness did not report live routing or savings")
27576
+ };
27577
+ }
27578
+ const active = { ...provisional, managementEndpoint: started.endpoint };
27579
+ try {
27580
+ await fs.writeFile(runtimeReceiptPath(context), new TextEncoder().encode(`${JSON.stringify(active, null, 2)}
27581
+ `), "0600");
27582
+ } catch {
27583
+ return {
27584
+ kind: "result",
27585
+ result: lifecycleError("ccr-receipt-write-failed", "CCR started, but Token Harness could not save its ownership receipt", "Keep CCR running; repair the protected Token Harness state directory, then rerun setup")
27586
+ };
27587
+ }
27588
+ changed = true;
27589
+ return {
27590
+ kind: "ready",
27591
+ endpoint: started.endpoint,
27592
+ token: runtimeToken,
27593
+ changed,
27594
+ lifecycleAction: prior === null ? "install" : prior.version === CCR_REVIEWED_VERSION ? "start" : "update",
27595
+ packagePath: prefix,
27596
+ executablePath: executable
27597
+ };
27598
+ }
27599
+ var CCR_PACKAGE, DEFAULT_WEB_PORT;
27600
+ var init_ccr_runtime = __esm({
27601
+ "apps/cli/dist/src/commands/ccr-runtime.js"() {
27602
+ "use strict";
27603
+ init_src3();
27604
+ init_src();
27605
+ CCR_PACKAGE = "@musistudio/claude-code-router";
27606
+ DEFAULT_WEB_PORT = 3458;
27607
+ }
27608
+ });
27609
+
27610
+ // apps/cli/dist/src/commands/routing-usage.js
27611
+ function combineSessionUsage(rows) {
27612
+ const byModel = /* @__PURE__ */ new Map();
27613
+ for (const row2 of rows) {
27614
+ for (const model of row2.byModel) {
27615
+ const current = byModel.get(model.model) ?? {
27616
+ ...model,
27617
+ requestCount: 0,
27618
+ inputTokens: 0,
27619
+ outputTokens: 0,
27620
+ cacheReadTokens: 0,
27621
+ cacheWriteTokens: 0,
27622
+ totalTokens: 0,
27623
+ recordedCostUsd: 0
27624
+ };
27625
+ current.requestCount += model.requestCount;
27626
+ current.inputTokens += model.inputTokens;
27627
+ current.outputTokens += model.outputTokens;
27628
+ current.cacheReadTokens += model.cacheReadTokens;
27629
+ current.cacheWriteTokens += model.cacheWriteTokens;
27630
+ current.totalTokens += model.totalTokens;
27631
+ if (current.recordedCostUsd === null || model.recordedCostUsd === null) {
27632
+ current.recordedCostUsd = null;
27633
+ } else {
27634
+ current.recordedCostUsd += model.recordedCostUsd;
27635
+ }
27636
+ byModel.set(model.model, current);
27637
+ }
27638
+ }
27639
+ const models = [...byModel.values()].sort((left, right) => left.model.localeCompare(right.model));
27640
+ const allCostsKnown = rows.length > 0 && rows.every((row2) => row2.recordedCostUsd !== null);
27641
+ return {
27642
+ status: rows.length === 0 ? "unavailable" : "observed",
27643
+ sessionCount: rows.length,
27644
+ observedSessionCount: rows.length,
27645
+ requestCount: rows.reduce((total, row2) => total + row2.requestCount, 0),
27646
+ inputTokens: rows.reduce((total, row2) => total + row2.inputTokens, 0),
27647
+ outputTokens: rows.reduce((total, row2) => total + row2.outputTokens, 0),
27648
+ cacheReadTokens: rows.reduce((total, row2) => total + row2.cacheReadTokens, 0),
27649
+ cacheWriteTokens: rows.reduce((total, row2) => total + row2.cacheWriteTokens, 0),
27650
+ totalTokens: rows.reduce((total, row2) => total + row2.totalTokens, 0),
27651
+ recordedCostUsd: allCostsKnown ? rows.reduce((total, row2) => total + (row2.recordedCostUsd ?? 0), 0) : null,
27652
+ byModel: models
27653
+ };
27654
+ }
27655
+ async function observeCcrUsage(input) {
27656
+ const unique = /* @__PURE__ */ new Map();
27657
+ for (const event of input.events) {
27658
+ if (event.sessionId) {
27659
+ unique.set(`${event.harnessId}:${event.sessionId}`, {
27660
+ harness: event.harnessId,
27661
+ sessionId: event.sessionId
27662
+ });
27663
+ }
27664
+ }
27665
+ const entries = [...unique.values()];
27666
+ const bounded = entries.slice(0, 20);
27667
+ if (bounded.length === 0) {
27668
+ return {
27669
+ usage: {
27670
+ status: "unavailable",
27671
+ sessionCount: 0,
27672
+ observedSessionCount: 0,
27673
+ requestCount: 0,
27674
+ inputTokens: 0,
27675
+ outputTokens: 0,
27676
+ cacheReadTokens: 0,
27677
+ cacheWriteTokens: 0,
27678
+ totalTokens: 0,
27679
+ recordedCostUsd: null,
27680
+ byModel: []
27681
+ },
27682
+ failedSessions: 0
27683
+ };
27684
+ }
27685
+ const managed = await resolveManagedCcr(input.context);
27686
+ if (managed.kind === "unavailable")
27687
+ throw new Error("CCR management credentials are unavailable");
27688
+ const client = new CcrManagementClient({
27689
+ baseUrl: managed.endpoint,
27690
+ authToken: managed.token,
27691
+ ...input.context.ccrFetch === void 0 ? {} : { fetcher: input.context.ccrFetch }
27692
+ });
27693
+ const appInfo = await client.call("getAppInfo");
27694
+ if (readCcrVersion(appInfo) !== CCR_REVIEWED_VERSION) {
27695
+ throw new Error("CCR version is outside the reviewed metadata interface");
27696
+ }
27697
+ const rows = [];
27698
+ let failedSessions = entries.length - bounded.length;
27699
+ for (const item of bounded) {
27700
+ try {
27701
+ const response = await client.call("getAgentAnalysis", [
27702
+ {
27703
+ agent: ccrAgentForHarness(item.harness),
27704
+ sessionAgent: ccrAgentForHarness(item.harness),
27705
+ sessionId: item.sessionId,
27706
+ range: "7d"
27707
+ }
27708
+ ]);
27709
+ const usage2 = reduceCcrSessionUsage(response, item.sessionId, ccrAgentForHarness(item.harness), input.since, input.until);
27710
+ if (usage2 === null)
27711
+ failedSessions += 1;
27712
+ else
27713
+ rows.push(usage2);
27714
+ } catch {
27715
+ failedSessions += 1;
27716
+ }
27717
+ }
27718
+ const usage = combineSessionUsage(rows);
27719
+ if (failedSessions > 0 && usage.status !== "unavailable")
27720
+ usage.status = "partial";
27721
+ return { usage: { ...usage, sessionCount: entries.length }, failedSessions };
27722
+ }
27723
+ async function loadSmartRoutingEventsForWindow(input) {
27724
+ const fs = input.context.adapters?.fs;
27725
+ const stateRoot = input.context.stateRoot;
27726
+ if (fs === void 0 || stateRoot === null)
27727
+ return [];
27728
+ const directory = fs.join(stateRoot, "smart-routing");
27729
+ let names;
27730
+ try {
27731
+ names = (await fs.readDirectory(directory)).filter((name2) => new RegExp(`^${SMART_ROUTING_EVENT_PREFIX}\\d{13}-[a-z0-9]+\\.json$`).test(name2)).sort();
27732
+ } catch {
27733
+ return [];
27734
+ }
27735
+ const start = Date.parse(input.since);
27736
+ const end = Date.parse(input.until);
27737
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start)
27738
+ return [];
27739
+ const events = [];
27740
+ for (const name2 of names) {
27741
+ try {
27742
+ const value3 = JSON.parse(new TextDecoder().decode(await fs.readFile(fs.join(directory, name2))));
27743
+ if (!isSmartRoutingDecisionEvent(value3) || value3.harnessId !== input.harness)
27744
+ continue;
27745
+ const timestamp = Date.parse(value3.timestamp);
27746
+ if (Number.isFinite(timestamp) && timestamp >= start && timestamp <= end)
27747
+ events.push(value3);
27748
+ } catch {
27749
+ }
27750
+ }
27751
+ return events;
27752
+ }
27753
+ var init_routing_usage = __esm({
27754
+ "apps/cli/dist/src/commands/routing-usage.js"() {
27755
+ "use strict";
27756
+ init_src3();
27757
+ init_ccr_runtime();
27758
+ init_src();
27759
+ }
27760
+ });
27761
+
26209
27762
  // apps/cli/dist/src/commands/benchmark-capture.js
26210
27763
  function statePaths(context, benchmarkId, variant) {
26211
27764
  if (context.adapters === null || context.stateRoot === null)
@@ -26555,6 +28108,59 @@ async function runBenchmarkFinish(context) {
26555
28108
  const budget = budgetResult.data?.harnesses.find((item) => item.harnessId === parsed.capture.harnessId);
26556
28109
  const localUsage = parsed.capture.localSessionsBefore !== null && historyResult.data?.source.state === "available" ? deriveTaskLocalUsage(parsed.capture.localSessionsBefore, snapshotTaskLocalSessions(historyResult.data.sessions), parsed.capture.startedAt, completedAt) : null;
26557
28110
  const finishContextObservation = contextResult.data?.harnesses.find((item) => item.harnessId === parsed.capture.harnessId);
28111
+ const routingHarness = parsed.capture.harnessId === CLAUDE12 ? "claude" : "codex";
28112
+ const routingEvents = await loadSmartRoutingEventsForWindow({
28113
+ context,
28114
+ harness: routingHarness,
28115
+ since: parsed.capture.startedAt,
28116
+ until: completedAt
28117
+ });
28118
+ let ccrUsage;
28119
+ let ccrUsageDiagnostics = [];
28120
+ if (routingEvents.length > 0) {
28121
+ try {
28122
+ const observed = await observeCcrUsage({
28123
+ context,
28124
+ events: routingEvents,
28125
+ since: parsed.capture.startedAt,
28126
+ until: completedAt
28127
+ });
28128
+ ccrUsage = { schemaVersion: 1, ...observed.usage };
28129
+ if (observed.usage.status !== "observed") {
28130
+ ccrUsageDiagnostics = [
28131
+ diagnostic({
28132
+ severity: "warning",
28133
+ code: "benchmark-ccr-usage-partial",
28134
+ message: `CCR request usage was ${observed.usage.status} for this capture`,
28135
+ remediation: "Check CCR Web RPC logging and keep one harness session active during the benchmark task"
28136
+ })
28137
+ ];
28138
+ }
28139
+ } catch {
28140
+ ccrUsage = {
28141
+ schemaVersion: 1,
28142
+ status: "unavailable",
28143
+ sessionCount: 0,
28144
+ observedSessionCount: 0,
28145
+ requestCount: 0,
28146
+ inputTokens: 0,
28147
+ outputTokens: 0,
28148
+ cacheReadTokens: 0,
28149
+ cacheWriteTokens: 0,
28150
+ totalTokens: 0,
28151
+ recordedCostUsd: null,
28152
+ byModel: []
28153
+ };
28154
+ ccrUsageDiagnostics = [
28155
+ diagnostic({
28156
+ severity: "warning",
28157
+ code: "benchmark-ccr-usage-unavailable",
28158
+ message: "CCR request usage could not be read; the task receipt is still valid without it",
28159
+ remediation: "Set the local CCR Web RPC token and verify CCR 3.1.1 request logging before the next paired capture"
28160
+ })
28161
+ ];
28162
+ }
28163
+ }
26558
28164
  const completed = completeTaskBenchmarkCapture(parsed.capture, {
26559
28165
  completedAt,
26560
28166
  usageAfter: budget?.windows ?? [],
@@ -26563,7 +28169,8 @@ async function runBenchmarkFinish(context) {
26563
28169
  failedAttempts,
26564
28170
  localUsage,
26565
28171
  contextAtFinish: taskBenchmarkContextSnapshot(finishContextObservation),
26566
- policyAtFinish: benchmarkPolicySnapshot(finishContextObservation)
28172
+ policyAtFinish: benchmarkPolicySnapshot(finishContextObservation),
28173
+ ...ccrUsage === void 0 ? {} : { ccrUsage }
26567
28174
  });
26568
28175
  if (!completed.ok) {
26569
28176
  return commandResult({
@@ -26608,7 +28215,8 @@ async function runBenchmarkFinish(context) {
26608
28215
  diagnostics: [
26609
28216
  ...budgetResult.diagnostics,
26610
28217
  ...historyResult.diagnostics,
26611
- ...contextResult.diagnostics
28218
+ ...contextResult.diagnostics,
28219
+ ...ccrUsageDiagnostics
26612
28220
  ]
26613
28221
  });
26614
28222
  }
@@ -26620,6 +28228,7 @@ var init_benchmark_capture = __esm({
26620
28228
  init_budget2();
26621
28229
  init_context_cost2();
26622
28230
  init_history2();
28231
+ init_routing_usage();
26623
28232
  CLAUDE12 = harnessId("claude");
26624
28233
  CODEX12 = harnessId("codex");
26625
28234
  CAPTURE_HARNESSES = /* @__PURE__ */ new Set([CLAUDE12, CODEX12]);
@@ -26833,11 +28442,11 @@ async function readJsonArtifact(context, path) {
26833
28442
  }
26834
28443
  }
26835
28444
  async function gitNexusBaselinePurity(context, benchmarkId) {
26836
- const receiptPath3 = benchmarkArtifactPath(context, benchmarkId, "baseline.json");
28445
+ const receiptPath4 = benchmarkArtifactPath(context, benchmarkId, "baseline.json");
26837
28446
  const capturePath = benchmarkArtifactPath(context, benchmarkId, "baseline.capture.json");
26838
- if (receiptPath3 === null || capturePath === null)
28447
+ if (receiptPath4 === null || capturePath === null)
26839
28448
  return "absent";
26840
- const rawReceipt = await readJsonArtifact(context, receiptPath3);
28449
+ const rawReceipt = await readJsonArtifact(context, receiptPath4);
26841
28450
  if (rawReceipt.state !== "absent") {
26842
28451
  if (rawReceipt.state === "invalid")
26843
28452
  return "invalid";
@@ -29052,6 +30661,1031 @@ var init_rollback = __esm({
29052
30661
  }
29053
30662
  });
29054
30663
 
30664
+ // apps/cli/dist/src/commands/smart-routing.js
30665
+ import { createHash as createHash3 } from "node:crypto";
30666
+ function safeGatewayState(value3) {
30667
+ if (!isJsonRecord(value3) || typeof value3["state"] !== "string")
30668
+ return "unknown";
30669
+ const state = value3["state"];
30670
+ return ["running", "stopped", "starting", "stopping", "error"].includes(state) ? state : "unknown";
30671
+ }
30672
+ function isSmartRoutingHarness(value3) {
30673
+ return value3 === "claude" || value3 === "codex";
30674
+ }
30675
+ function error(code, message, remediation) {
30676
+ return commandResult({
30677
+ command: "routing",
30678
+ exitCode: EXIT_CODES["usage-error"],
30679
+ diagnostics: [diagnostic({ severity: "error", code, message, remediation })]
30680
+ });
30681
+ }
30682
+ function ccrFailure(errorValue) {
30683
+ if (!(errorValue instanceof CcrManagementError)) {
30684
+ return {
30685
+ code: "ccr-management-failed",
30686
+ message: "CCR management operation failed",
30687
+ remediation: "Check the local CCR management service and repeat the command"
30688
+ };
30689
+ }
30690
+ const rows = {
30691
+ "endpoint-invalid": {
30692
+ code: "ccr-endpoint-not-local",
30693
+ message: "CCR management URL must use a loopback address on this machine",
30694
+ remediation: "Use CCR_WEB_URL=http://127.0.0.1:3458 or another local loopback port"
30695
+ },
30696
+ "token-missing": {
30697
+ code: "ccr-auth-token-required",
30698
+ message: "CCR Web RPC authentication is not configured for Token Harness",
30699
+ remediation: "Start the local CCR service or set CCR_WEB_AUTH_TOKEN and optionally CCR_WEB_URL; Token Harness never prints credentials, and managed credentials are stored only in protected local state"
30700
+ },
30701
+ unreachable: {
30702
+ code: "ccr-management-unreachable",
30703
+ message: "The local CCR management service could not be reached",
30704
+ remediation: "Start CCR Web Management on this machine and set CCR_WEB_URL to its loopback address"
30705
+ },
30706
+ unauthorized: {
30707
+ code: "ccr-management-unauthorized",
30708
+ message: "CCR rejected the local management token",
30709
+ remediation: "Use the same CCR_WEB_AUTH_TOKEN in the CCR service and Token Harness process"
30710
+ },
30711
+ "method-unavailable": {
30712
+ code: "ccr-management-api-unsupported",
30713
+ message: "This CCR build does not expose the reviewed management operation",
30714
+ remediation: `Use CCR ${CCR_REVIEWED_VERSION} for managed setup, or add the exported rule through CCR Routing manually`
30715
+ },
30716
+ "config-drift": {
30717
+ code: "ccr-config-changed-during-operation",
30718
+ message: "CCR configuration changed while Token Harness was preparing the rule update",
30719
+ remediation: "Review the latest CCR configuration and retry from a fresh preview"
30720
+ },
30721
+ "invalid-response": {
30722
+ code: "ccr-management-response-invalid",
30723
+ message: "CCR returned an unsupported or oversized management response",
30724
+ remediation: "Check the CCR version and retry with a local CCR service"
30725
+ },
30726
+ "request-failed": {
30727
+ code: "ccr-management-operation-failed",
30728
+ message: "CCR could not complete the management operation",
30729
+ remediation: "Review CCR status and retry; Token Harness did not print CCR response contents"
30730
+ }
30731
+ };
30732
+ return rows[errorValue.failure];
30733
+ }
30734
+ function isJsonRecord(value3) {
30735
+ return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
30736
+ }
30737
+ function receiptPath3(context, harness) {
30738
+ const fs = context.adapters.fs;
30739
+ return fs.join(stateDirectory(context), `ccr-ownership-${harness}.json`);
30740
+ }
30741
+ function scriptDirectory(context) {
30742
+ return context.adapters.fs.join(stateDirectory(context), "ccr-scripts");
30743
+ }
30744
+ function scriptPath(context, harness) {
30745
+ return context.adapters.fs.join(scriptDirectory(context), `smart-routing-${harness}.js`);
30746
+ }
30747
+ function stateDirectory(context) {
30748
+ return context.adapters.fs.join(context.stateRoot, "smart-routing");
30749
+ }
30750
+ function scriptHash(script) {
30751
+ return createHash3("sha256").update(script, "utf8").digest("hex");
30752
+ }
30753
+ async function readOwnership(context, harness) {
30754
+ const path = receiptPath3(context, harness);
30755
+ try {
30756
+ const bytes = await context.adapters.fs.readFile(path);
30757
+ const value3 = JSON.parse(new TextDecoder().decode(bytes));
30758
+ if (isJsonRecord(value3) && value3["schemaVersion"] === 1 && (value3["status"] === "pending" || value3["status"] === "active") && value3["harnessId"] === harness && (value3["mode"] === "shadow" || value3["mode"] === "conservative") && value3["ruleId"] === ccrSmartRoutingRuleId(harness) && typeof value3["scriptPath"] === "string" && /^[a-f0-9]{64}$/.test(String(value3["scriptSha256"])) && (value3["profileId"] === void 0 || typeof value3["profileId"] === "string") && (value3["profileSha256"] === void 0 || /^[a-f0-9]{64}$/.test(String(value3["profileSha256"]))) && value3["profileId"] === void 0 === (value3["profileSha256"] === void 0) && typeof value3["installedAt"] === "string") {
30759
+ return value3;
30760
+ }
30761
+ } catch {
30762
+ return null;
30763
+ }
30764
+ return null;
30765
+ }
30766
+ async function writeJson4(context, path, value3) {
30767
+ await context.adapters.fs.writeFile(path, new TextEncoder().encode(`${JSON.stringify(value3, null, 2)}
30768
+ `));
30769
+ }
30770
+ async function cleanupUnappliedCcrFiles(context, harness, ownership) {
30771
+ const fs = context.adapters.fs;
30772
+ const receipt = await readOwnership(context, harness);
30773
+ if (receipt !== null && receipt.status === "pending" && receipt.scriptPath === ownership.scriptPath && receipt.scriptSha256 === ownership.scriptSha256) {
30774
+ await fs.remove(receiptPath3(context, harness)).catch(() => void 0);
30775
+ }
30776
+ const scriptBytes = await fs.readFile(ownership.scriptPath).catch(() => null);
30777
+ if (scriptBytes !== null && scriptHash(new TextDecoder().decode(scriptBytes)) === ownership.scriptSha256) {
30778
+ await fs.remove(ownership.scriptPath).catch(() => void 0);
30779
+ }
30780
+ }
30781
+ async function readCcrState(context) {
30782
+ const managed = await resolveManagedCcr(context);
30783
+ if (managed.kind === "unavailable")
30784
+ throw new CcrManagementError("token-missing");
30785
+ const client = new CcrManagementClient({
30786
+ baseUrl: managed.endpoint,
30787
+ authToken: managed.token,
30788
+ ...context.ccrFetch === void 0 ? {} : { fetcher: context.ccrFetch }
30789
+ });
30790
+ const [appInfo, configValue, gatewayValue] = await Promise.all([
30791
+ client.call("getAppInfo"),
30792
+ client.call("getConfig"),
30793
+ client.call("getGatewayStatus")
30794
+ ]);
30795
+ const version3 = readCcrVersion(appInfo);
30796
+ if (version3 !== CCR_REVIEWED_VERSION) {
30797
+ throw new CcrManagementError("method-unavailable");
30798
+ }
30799
+ if (!isJsonRecord(configValue) || !isJsonRecord(configValue["Router"])) {
30800
+ throw new CcrManagementError("invalid-response");
30801
+ }
30802
+ const gatewayState = safeGatewayState(gatewayValue);
30803
+ return { client, endpoint: managed.endpoint, version: version3, config: configValue, gatewayState };
30804
+ }
30805
+ function validateRouteRuleResult(value3) {
30806
+ return isJsonRecord(value3) && value3["ok"] === true;
30807
+ }
30808
+ function profileSlug(value3) {
30809
+ return value3.toLowerCase().replace(/[^a-z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "") || "provider";
30810
+ }
30811
+ function planCcrProfile(config, harness, selectedModel) {
30812
+ const profileContainer = isJsonRecord(config["profile"]) ? config["profile"] : null;
30813
+ const profiles = profileContainer && Array.isArray(profileContainer["profiles"]) ? profileContainer["profiles"] : null;
30814
+ if (profileContainer === null || profiles === null || profileContainer["enabled"] === false) {
30815
+ return {
30816
+ profile: null,
30817
+ profileContainer,
30818
+ conflict: false,
30819
+ reason: "CCR Agent Profiles are unavailable or disabled"
30820
+ };
30821
+ }
30822
+ const providerName3 = harness === "claude" ? "Claude Code API" : "Codex API";
30823
+ const protocol = harness === "claude" ? "anthropic_messages" : "openai_responses";
30824
+ const providers = Array.isArray(config["Providers"]) ? config["Providers"] : [];
30825
+ const matches = providers.filter((item) => isJsonRecord(item) && item["name"] === providerName3 && item["type"] === protocol && Array.isArray(item["models"]) && item["models"].some((model2) => typeof model2 === "string" && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(model2)));
30826
+ if (matches.length !== 1 || !isJsonRecord(matches[0])) {
30827
+ return {
30828
+ profile: null,
30829
+ profileContainer,
30830
+ conflict: false,
30831
+ reason: matches.length === 0 ? `Import the existing ${providerName3} login/provider in CCR before Token Harness can create a safe launcher profile` : `CCR has multiple ${providerName3} providers; select the intended subscription account explicitly in CCR`
30832
+ };
30833
+ }
30834
+ const provider = matches[0];
30835
+ const models = provider["models"].filter((model2) => typeof model2 === "string" && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(model2));
30836
+ let model;
30837
+ const selectedModelValue = selectedModel?.trim();
30838
+ if (selectedModelValue) {
30839
+ if (!selectedModelValue.startsWith(`${providerName3}/`)) {
30840
+ return {
30841
+ profile: null,
30842
+ profileContainer,
30843
+ conflict: false,
30844
+ reason: "TOKEN_HARNESS_ROUTING_PROFILE_MODEL must name a model from the matching CCR provider"
30845
+ };
30846
+ }
30847
+ const selectedId = selectedModelValue.slice(providerName3.length + 1);
30848
+ if (models.includes(selectedId))
30849
+ model = selectedId;
30850
+ else
30851
+ return {
30852
+ profile: null,
30853
+ profileContainer,
30854
+ conflict: false,
30855
+ reason: "TOKEN_HARNESS_ROUTING_PROFILE_MODEL is not present in the matching CCR provider model list"
30856
+ };
30857
+ }
30858
+ const providerDefault = typeof provider["defaultModel"] === "string" ? provider["defaultModel"] : typeof provider["model"] === "string" ? provider["model"] : null;
30859
+ if (model === void 0 && providerDefault !== null) {
30860
+ const providerDefaultId = providerDefault.startsWith(`${providerName3}/`) ? providerDefault.slice(providerName3.length + 1) : providerDefault;
30861
+ if (models.includes(providerDefaultId))
30862
+ model = providerDefaultId;
30863
+ }
30864
+ if (model === void 0 && models.length === 1)
30865
+ model = models[0];
30866
+ if (model === void 0) {
30867
+ return {
30868
+ profile: null,
30869
+ profileContainer,
30870
+ conflict: false,
30871
+ reason: `${providerName3} has multiple models; set TOKEN_HARNESS_ROUTING_PROFILE_MODEL to the exact Provider/model you want as the CCR CLI default`
30872
+ };
30873
+ }
30874
+ const id = OWNED_PROFILE_IDS[harness];
30875
+ const profile = {
30876
+ agent: harness === "claude" ? "claude-code" : "codex",
30877
+ enabled: true,
30878
+ id,
30879
+ model: `${providerName3}/${model}`,
30880
+ name: `Token Harness ${harness === "claude" ? "Claude Code" : "Codex"}`,
30881
+ providerId: typeof provider["id"] === "string" ? provider["id"] : profileSlug(providerName3),
30882
+ providerName: providerName3,
30883
+ scope: "ccr",
30884
+ surface: "cli"
30885
+ };
30886
+ const existing = profiles.filter((item) => isJsonRecord(item) && item["id"] === id);
30887
+ if (existing.length > 0) {
30888
+ return {
30889
+ profile,
30890
+ profileContainer,
30891
+ conflict: true,
30892
+ reason: "A CCR Agent Profile already uses the Token Harness profile id"
30893
+ };
30894
+ }
30895
+ return { profile, profileContainer, conflict: false, reason: null };
30896
+ }
30897
+ function configuredCcrModel(config, requested) {
30898
+ const candidate = requested?.trim();
30899
+ if (candidate === void 0 || !/^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(candidate))
30900
+ return null;
30901
+ const providers = Array.isArray(config["Providers"]) ? config["Providers"] : [];
30902
+ return providers.some((provider) => isJsonRecord(provider) && typeof provider["name"] === "string" && Array.isArray(provider["models"]) && provider["models"].some((model) => typeof model === "string" && candidate === `${provider["name"]}/${model}`)) ? candidate : null;
30903
+ }
30904
+ function stableJson2(value3) {
30905
+ if (Array.isArray(value3))
30906
+ return `[${value3.map(stableJson2).join(",")}]`;
30907
+ if (!isJsonRecord(value3))
30908
+ return JSON.stringify(value3);
30909
+ return `{${Object.keys(value3).sort().map((key) => `${JSON.stringify(key)}:${stableJson2(value3[key])}`).join(",")}}`;
30910
+ }
30911
+ function profileRows(config) {
30912
+ const container = config["profile"];
30913
+ return isJsonRecord(container) && Array.isArray(container["profiles"]) ? container["profiles"] : [];
30914
+ }
30915
+ function withCcrProfile(config, profile) {
30916
+ const container = config["profile"];
30917
+ if (!isJsonRecord(container) || container["enabled"] === false || !Array.isArray(container["profiles"])) {
30918
+ return null;
30919
+ }
30920
+ if (container["profiles"].some((item) => isJsonRecord(item) && item["id"] === profile["id"])) {
30921
+ return null;
30922
+ }
30923
+ return {
30924
+ ...config,
30925
+ profile: { ...container, profiles: [profile, ...container["profiles"]] }
30926
+ };
30927
+ }
30928
+ function withoutOwnedCcrProfile(config, profileId, expectedSha256) {
30929
+ const container = config["profile"];
30930
+ if (!isJsonRecord(container) || !Array.isArray(container["profiles"]))
30931
+ return config;
30932
+ const matches = container["profiles"].filter((item) => isJsonRecord(item) && item["id"] === profileId);
30933
+ if (matches.length === 0)
30934
+ return config;
30935
+ if (matches.length !== 1 || scriptHash(stableJson2(matches[0])) !== expectedSha256)
30936
+ return null;
30937
+ return {
30938
+ ...config,
30939
+ profile: {
30940
+ ...container,
30941
+ profiles: container["profiles"].filter((item) => !(isJsonRecord(item) && item["id"] === profileId))
30942
+ }
30943
+ };
30944
+ }
30945
+ function isExpectedCcrProfile(value3, expected) {
30946
+ if (!isJsonRecord(value3))
30947
+ return false;
30948
+ const requiredKeys = [
30949
+ "agent",
30950
+ "enabled",
30951
+ "id",
30952
+ "model",
30953
+ "name",
30954
+ "providerId",
30955
+ "providerName",
30956
+ "scope",
30957
+ "surface"
30958
+ ];
30959
+ return requiredKeys.every((key) => stableJson2(value3[key]) === stableJson2(expected[key]));
30960
+ }
30961
+ function ccrLaunchCommand(harness) {
30962
+ return `ccr "Token Harness ${harness === "claude" ? "Claude Code" : "Codex"}"`;
30963
+ }
30964
+ function profilePlanDiagnostic(plan6) {
30965
+ if (plan6.reason === null)
30966
+ return null;
30967
+ return diagnostic({
30968
+ severity: "warning",
30969
+ code: "ccr-profile-not-created",
30970
+ message: plan6.reason,
30971
+ remediation: `Resolve the CCR profile setup requirement and rerun routing setup; provider login/import and credential changes remain explicit CCR actions`
30972
+ });
30973
+ }
30974
+ async function ccrConfiguration(context) {
30975
+ const fs = context.adapters?.fs;
30976
+ if (fs === void 0 || context.stateRoot === null || !isSmartRoutingHarness(context.harness)) {
30977
+ return error("ccr-configuration-context-required", "Managed CCR setup needs a local state directory and a Claude Code or Codex harness", "Pass `--harness claude` or `--harness codex` from a local Token Harness installation");
30978
+ }
30979
+ const mode = context.routingMode ?? "shadow";
30980
+ const harnessId2 = context.harness;
30981
+ const ruleId = ccrSmartRoutingRuleId(harnessId2);
30982
+ const path = scriptPath(context, harnessId2);
30983
+ const telemetryDirectory = stateDirectory(context);
30984
+ let ccr;
30985
+ try {
30986
+ ccr = await readCcrState(context);
30987
+ } catch (errorValue) {
30988
+ const issue = ccrFailure(errorValue);
30989
+ return commandResult({
30990
+ command: "routing",
30991
+ exitCode: EXIT_CODES["problems-found"],
30992
+ diagnostics: [diagnostic({ severity: "error", ...issue })]
30993
+ });
30994
+ }
30995
+ const requestedProfileModel = context.env?.["TOKEN_HARNESS_ROUTING_PROFILE_MODEL"];
30996
+ const profilePlan = planCcrProfile(ccr.config, harnessId2, requestedProfileModel);
30997
+ const profileModelWarning = requestedProfileModel?.trim() && (profilePlan.profile === null || profilePlan.profile["model"] !== requestedProfileModel.trim()) ? diagnostic({
30998
+ severity: "warning",
30999
+ code: "ccr-profile-model-not-configured",
31000
+ message: "TOKEN_HARNESS_ROUTING_PROFILE_MODEL did not match a model in the selected CCR provider and was not applied",
31001
+ remediation: "Set it to the exact Provider/model alias from CCR, then roll back and preview setup again"
31002
+ }) : null;
31003
+ const requestedSimpleModel = context.env?.["TOKEN_HARNESS_ROUTING_SIMPLE_MODEL"];
31004
+ const configuredSimpleModel = configuredCcrModel(ccr.config, requestedSimpleModel);
31005
+ const simpleModelWarning = requestedSimpleModel?.trim() && configuredSimpleModel === null ? diagnostic({
31006
+ severity: "warning",
31007
+ code: "ccr-simple-model-not-configured",
31008
+ message: "TOKEN_HARNESS_ROUTING_SIMPLE_MODEL did not match a model in the selected CCR configuration and was not embedded",
31009
+ remediation: "Set it to the exact Provider/model alias from CCR, then roll back and preview setup again"
31010
+ }) : null;
31011
+ const script = createCcrSmartRoutingScript({
31012
+ harnessId: harnessId2,
31013
+ mode,
31014
+ telemetryDirectory,
31015
+ pathSeparator: context.platform.os === "windows" ? "\\" : "/",
31016
+ simpleModel: configuredSimpleModel
31017
+ });
31018
+ const expectedRule = createCcrSmartRoutingRule(harnessId2, path);
31019
+ const router = ccr.config["Router"];
31020
+ const rules = isJsonRecord(router) && Array.isArray(router["rules"]) ? router["rules"] : null;
31021
+ if (rules === null) {
31022
+ return error("ccr-routing-config-unavailable", "CCR configuration does not contain the reviewed routing-rule list", "Review CCR Routing manually and use `token-harness routing --script` to export the rule");
31023
+ }
31024
+ const matching = rules.filter((item) => isJsonRecord(item) && item["id"] === ruleId);
31025
+ const owned = await readOwnership(context, harnessId2);
31026
+ const profileList = profilePlan.profileContainer && Array.isArray(profilePlan.profileContainer["profiles"]) ? profilePlan.profileContainer["profiles"] : [];
31027
+ const currentOwnedProfile = owned?.profileId ? profileList.find((item) => isJsonRecord(item) && item["id"] === owned.profileId) : void 0;
31028
+ const ownedProfileMatches = owned?.profileId === void 0 || isJsonRecord(currentOwnedProfile) && owned.profileSha256 === scriptHash(stableJson2(currentOwnedProfile));
31029
+ if (owned !== null && !ownedProfileMatches) {
31030
+ return error("ccr-owned-profile-drift", "The Token Harness CCR profile changed or disappeared after setup, so configuration was left untouched", "Review the profile in CCR Agent Config; restore it or remove it manually before retrying");
31031
+ }
31032
+ if (profilePlan.conflict && !owned?.profileId) {
31033
+ return error("ccr-profile-id-conflict", "A CCR Agent Profile already uses the Token Harness profile id, so it was left unchanged", "Rename or remove that profile in CCR Agent Config before retrying");
31034
+ }
31035
+ const ownershipStat = await fs.stat(receiptPath3(context, harnessId2));
31036
+ if (owned === null && ownershipStat !== null) {
31037
+ return error("ccr-ownership-state-invalid", "The local CCR ownership path already contains unrecognized data and was left unchanged", "Inspect or move the local ownership file before retrying CCR setup");
31038
+ }
31039
+ const targetFile = await fs.stat(path);
31040
+ if (matching.length > 0) {
31041
+ if (matching.length === 1 && isExactCcrSmartRoutingRule(matching[0], expectedRule) && owned) {
31042
+ const currentScript = await fs.readFile(path).catch(() => null);
31043
+ if (currentScript !== null && scriptHash(new TextDecoder().decode(currentScript)) === owned.scriptSha256) {
31044
+ if (owned.mode !== mode || owned.scriptSha256 !== scriptHash(script)) {
31045
+ return error("ccr-route-mode-requires-rollback", `CCR is already configured in ${owned.mode} mode; changing the mode requires an explicit rollback first`, `Review the active routing rule, run \`token-harness routing --rollback-ccr --harness ${harnessId2} --yes\`, then configure again in ${mode} mode`);
31046
+ }
31047
+ if (owned.profileId === void 0 && profilePlan.profile !== null && !profilePlan.conflict) {
31048
+ const profileConfig = withCcrProfile(ccr.config, profilePlan.profile);
31049
+ if (profileConfig === null) {
31050
+ return error("ccr-profile-config-conflict", "CCR Agent Profile settings changed or cannot accept the Token Harness profile", "Review CCR Agent Config and retry from a new preview");
31051
+ }
31052
+ if (!context.confirmed) {
31053
+ return configurationResult("configure", "preview", ccr, harnessId2, mode, ruleId, path, [
31054
+ diagnostic({
31055
+ severity: "info",
31056
+ code: "ccr-profile-preview",
31057
+ message: "The CCR routing rule is already owned; Token Harness would add its scoped CLI profile using the existing provider",
31058
+ remediation: `Review the CCR-only profile and rerun with --yes. Launch it with ${ccrLaunchCommand(harnessId2)}`
31059
+ })
31060
+ ], String(profilePlan.profile["id"]), ccrLaunchCommand(harnessId2));
31061
+ }
31062
+ try {
31063
+ const currentConfig = await ccr.client.call("getConfig");
31064
+ if (!isSameCcrConfig(currentConfig, ccr.config))
31065
+ throw new CcrManagementError("config-drift");
31066
+ await ccr.client.call("saveConfig", [profileConfig, { applyProfile: false }]);
31067
+ const afterConfig = await ccr.client.call("getConfig");
31068
+ const afterRouter = isJsonRecord(afterConfig) ? afterConfig["Router"] : null;
31069
+ const afterRules = isJsonRecord(afterRouter) && Array.isArray(afterRouter["rules"]) ? afterRouter["rules"] : [];
31070
+ if (!afterRules.some((item) => isExactCcrSmartRoutingRule(item, expectedRule)))
31071
+ throw new CcrManagementError("request-failed");
31072
+ const savedProfile = profileRows(isJsonRecord(afterConfig) ? afterConfig : {}).find((item) => isJsonRecord(item) && item["id"] === profilePlan.profile?.["id"]);
31073
+ if (!isExpectedCcrProfile(savedProfile, profilePlan.profile))
31074
+ throw new CcrManagementError("request-failed");
31075
+ const updatedOwnership = {
31076
+ ...owned,
31077
+ profileId: String(profilePlan.profile["id"]),
31078
+ profileSha256: scriptHash(stableJson2(savedProfile))
31079
+ };
31080
+ await writeJson4(context, receiptPath3(context, harnessId2), updatedOwnership);
31081
+ return configurationResult("configure", "configured", ccr, harnessId2, mode, ruleId, path, [
31082
+ diagnostic({
31083
+ severity: "info",
31084
+ code: "ccr-profile-verified",
31085
+ message: "CCR saved and verified the Token Harness scoped CLI profile using an existing provider",
31086
+ remediation: `Launch Claude Code or Codex through ${ccrLaunchCommand(harnessId2)} and verify requests in CCR logs`
31087
+ })
31088
+ ], updatedOwnership.profileId, ccrLaunchCommand(harnessId2));
31089
+ } catch (errorValue) {
31090
+ const issue = ccrFailure(errorValue);
31091
+ return commandResult({
31092
+ command: "routing",
31093
+ exitCode: EXIT_CODES["problems-found"],
31094
+ diagnostics: [diagnostic({ severity: "error", ...issue })]
31095
+ });
31096
+ }
31097
+ }
31098
+ const profileWarning = owned.profileId === void 0 ? profilePlanDiagnostic(profilePlan) : null;
31099
+ return configurationResult("configure", "already-configured", ccr, harnessId2, mode, ruleId, path, profileWarning === null ? [] : [profileWarning], owned.profileId ?? null, owned.profileId ? ccrLaunchCommand(harnessId2) : null);
31100
+ }
31101
+ }
31102
+ return commandResult({
31103
+ command: "routing",
31104
+ exitCode: EXIT_CODES["precondition-drift"],
31105
+ diagnostics: [
31106
+ diagnostic({
31107
+ severity: "error",
31108
+ code: "ccr-routing-rule-conflict",
31109
+ message: "A CCR rule already uses the Token Harness rule id, so it was left unchanged",
31110
+ remediation: "Inspect that rule in CCR Routing and remove or rename it before retrying"
31111
+ })
31112
+ ]
31113
+ });
31114
+ }
31115
+ if (owned !== null) {
31116
+ return error("ccr-ownership-state-drift", "Token Harness has an ownership receipt but the CCR rule is missing or changed", "Run `token-harness routing --rollback-ccr --harness <id> --yes` after reviewing the CCR state");
31117
+ }
31118
+ if (targetFile !== null) {
31119
+ return error("ccr-script-file-conflict", "The managed CCR script path already contains a file that Token Harness does not own", "Move that file or use the exported script with CCR Routing manually");
31120
+ }
31121
+ if (!context.confirmed) {
31122
+ const profileDiagnostic = profilePlanDiagnostic(profilePlan);
31123
+ return configurationResult("configure", "preview", ccr, harnessId2, mode, ruleId, path, [
31124
+ diagnostic({
31125
+ severity: "info",
31126
+ code: "ccr-configure-preview",
31127
+ message: profilePlan.profile === null ? `CCR ${ccr.version} would receive one ${mode} Node.js routing rule for ${harnessId2}` : `CCR ${ccr.version} would receive one ${mode} Node.js routing rule and a CCR-only CLI profile for ${harnessId2} using ${String(profilePlan.profile["model"])}`,
31128
+ path,
31129
+ remediation: `Review the exact CCR changes and rerun with --yes to apply them; CCR may restart. The profile uses an existing provider and affects only CLI launches through CCR. Rollback: \`token-harness routing --rollback-ccr --harness ${harnessId2} --yes\``
31130
+ }),
31131
+ ...profileDiagnostic === null ? [] : [profileDiagnostic],
31132
+ ...profileModelWarning === null ? [] : [profileModelWarning],
31133
+ ...simpleModelWarning === null ? [] : [simpleModelWarning]
31134
+ ], profilePlan.profile === null ? null : String(profilePlan.profile["id"]), profilePlan.profile === null ? null : ccrLaunchCommand(harnessId2));
31135
+ }
31136
+ let validation;
31137
+ try {
31138
+ validation = await ccr.client.call("validateRouteScript", [
31139
+ {
31140
+ script: {
31141
+ apiVersion: 1,
31142
+ language: "javascript",
31143
+ source: script,
31144
+ timeoutMs: 2e3
31145
+ }
31146
+ }
31147
+ ]);
31148
+ } catch (errorValue) {
31149
+ const issue = ccrFailure(errorValue);
31150
+ return commandResult({
31151
+ command: "routing",
31152
+ exitCode: EXIT_CODES["problems-found"],
31153
+ diagnostics: [diagnostic({ severity: "error", ...issue })]
31154
+ });
31155
+ }
31156
+ if (!validateRouteRuleResult(validation)) {
31157
+ return error("ccr-script-validation-failed", "CCR did not validate the generated routing script", "No CCR or harness configuration was changed; inspect CCR compatibility and retry");
31158
+ }
31159
+ const withRule = addCcrSmartRoutingRule(ccr.config, expectedRule);
31160
+ if (withRule === null) {
31161
+ return error("ccr-routing-rule-conflict", "CCR routing rules changed or cannot accept a script rule", "Refresh CCR state and review existing rules before retrying");
31162
+ }
31163
+ const nextConfig = profilePlan.profile === null ? withRule : withCcrProfile(withRule, profilePlan.profile);
31164
+ if (nextConfig === null) {
31165
+ return error("ccr-profile-config-conflict", "CCR Agent Profile settings changed or cannot accept the Token Harness profile", "Review CCR Agent Config and retry from a new preview");
31166
+ }
31167
+ const now = context.now();
31168
+ const ownership = {
31169
+ schemaVersion: 1,
31170
+ status: "pending",
31171
+ harnessId: harnessId2,
31172
+ mode,
31173
+ ruleId,
31174
+ scriptPath: path,
31175
+ scriptSha256: scriptHash(script),
31176
+ installedAt: now
31177
+ };
31178
+ let saveAttempted = false;
31179
+ try {
31180
+ await fs.createDirectory(telemetryDirectory);
31181
+ await fs.createDirectory(scriptDirectory(context));
31182
+ await writeJson4(context, receiptPath3(context, harnessId2), ownership);
31183
+ await fs.writeFile(path, new TextEncoder().encode(script));
31184
+ const currentConfig = await ccr.client.call("getConfig");
31185
+ if (!isSameCcrConfig(currentConfig, ccr.config)) {
31186
+ throw new CcrManagementError("config-drift");
31187
+ }
31188
+ saveAttempted = true;
31189
+ await ccr.client.call("saveConfig", [nextConfig, { applyProfile: false }]);
31190
+ const afterConfig = await ccr.client.call("getConfig");
31191
+ const afterRouter = isJsonRecord(afterConfig) ? afterConfig["Router"] : null;
31192
+ const afterRules = isJsonRecord(afterRouter) && Array.isArray(afterRouter["rules"]) ? afterRouter["rules"] : [];
31193
+ if (!afterRules.some((item) => isExactCcrSmartRoutingRule(item, expectedRule))) {
31194
+ throw new CcrManagementError("request-failed");
31195
+ }
31196
+ let savedProfile = null;
31197
+ if (profilePlan.profile !== null) {
31198
+ const saved = profileRows(isJsonRecord(afterConfig) ? afterConfig : {}).find((item) => isJsonRecord(item) && item["id"] === profilePlan.profile?.["id"]);
31199
+ if (!isExpectedCcrProfile(saved, profilePlan.profile))
31200
+ throw new CcrManagementError("request-failed");
31201
+ savedProfile = saved;
31202
+ }
31203
+ const activeOwnership2 = {
31204
+ ...ownership,
31205
+ status: "active",
31206
+ ...savedProfile === null || profilePlan.profile === null ? {} : {
31207
+ profileId: String(profilePlan.profile["id"]),
31208
+ profileSha256: scriptHash(stableJson2(savedProfile))
31209
+ }
31210
+ };
31211
+ await writeJson4(context, receiptPath3(context, harnessId2), activeOwnership2);
31212
+ const gatewayValue = await ccr.client.call("getGatewayStatus");
31213
+ const gatewayState = safeGatewayState(gatewayValue);
31214
+ const finalCcr = { ...ccr, gatewayState };
31215
+ const profileDiagnostic = profilePlanDiagnostic(profilePlan);
31216
+ return configurationResult("configure", "configured", finalCcr, harnessId2, mode, ruleId, path, [
31217
+ diagnostic({
31218
+ severity: gatewayState === "running" ? "info" : "warning",
31219
+ code: gatewayState === "running" ? "ccr-config-verified" : "ccr-gateway-not-running",
31220
+ message: gatewayState === "running" ? "CCR accepted the rule and its gateway reports running; live request routing has not been exercised" : `CCR saved and verified the rule, but its gateway reports ${gatewayState}`,
31221
+ path,
31222
+ remediation: gatewayState === "running" ? "Use shadow mode first, then inspect local decisions with `token-harness routing --route-metrics`" : "Start or repair the CCR gateway, then verify it before sending a model request"
31223
+ }),
31224
+ ...profileDiagnostic === null ? [] : [profileDiagnostic],
31225
+ ...profileModelWarning === null ? [] : [profileModelWarning],
31226
+ ...simpleModelWarning === null ? [] : [simpleModelWarning]
31227
+ ], activeOwnership2.profileId ?? null, activeOwnership2.profileId ? ccrLaunchCommand(harnessId2) : null);
31228
+ } catch (errorValue) {
31229
+ if (!saveAttempted)
31230
+ await cleanupUnappliedCcrFiles(context, harnessId2, ownership);
31231
+ const issue = ccrFailure(errorValue);
31232
+ return commandResult({
31233
+ command: "routing",
31234
+ exitCode: EXIT_CODES["problems-found"],
31235
+ diagnostics: [
31236
+ diagnostic({
31237
+ severity: "error",
31238
+ code: issue.code,
31239
+ message: saveAttempted ? `${issue.message}; the ownership receipt was retained for safe recovery` : `${issue.message}; CCR configuration was not changed`,
31240
+ ...saveAttempted ? { path: receiptPath3(context, harnessId2) } : {},
31241
+ remediation: saveAttempted ? `Run \`token-harness routing --rollback-ccr --harness ${harnessId2} --yes\` to remove only the owned rule, or inspect the ownership receipt first` : "Resolve the local or CCR issue and start again from a new preview"
31242
+ })
31243
+ ]
31244
+ });
31245
+ }
31246
+ }
31247
+ function configurationResult(action, state, ccr, harnessId2, mode, ruleId, path, diagnostics = [], profileId = null, launchCommand = null) {
31248
+ return commandResult({
31249
+ command: "routing",
31250
+ exitCode: EXIT_CODES.ok,
31251
+ data: {
31252
+ kind: "ccr-configuration",
31253
+ action,
31254
+ state,
31255
+ harnessId: harnessId2,
31256
+ mode,
31257
+ ccrVersion: ccr.version,
31258
+ gatewayState: ccr.gatewayState,
31259
+ ruleId,
31260
+ scriptPath: path,
31261
+ managementEndpoint: ccr.endpoint,
31262
+ profileId,
31263
+ launchCommand
31264
+ },
31265
+ diagnostics
31266
+ });
31267
+ }
31268
+ async function rollbackCcrConfiguration(context) {
31269
+ const fs = context.adapters?.fs;
31270
+ if (fs === void 0 || context.stateRoot === null || !isSmartRoutingHarness(context.harness)) {
31271
+ return error("ccr-rollback-context-required", "CCR rollback needs the local ownership receipt and a Claude Code or Codex harness", "Pass the same `--harness` used for CCR configuration");
31272
+ }
31273
+ const harnessId2 = context.harness;
31274
+ const ownership = await readOwnership(context, harnessId2);
31275
+ if (ownership === null) {
31276
+ return error("ccr-ownership-receipt-missing", "Token Harness has no valid CCR ownership receipt for this harness", "Review the rule in CCR manually; Token Harness removes only rules it recorded as owned");
31277
+ }
31278
+ let ccr;
31279
+ try {
31280
+ ccr = await readCcrState(context);
31281
+ } catch (errorValue) {
31282
+ const issue = ccrFailure(errorValue);
31283
+ return commandResult({
31284
+ command: "routing",
31285
+ exitCode: EXIT_CODES["problems-found"],
31286
+ diagnostics: [diagnostic({ severity: "error", ...issue })]
31287
+ });
31288
+ }
31289
+ const expectedRule = createCcrSmartRoutingRule(harnessId2, ownership.scriptPath);
31290
+ const profileValue = ownership.profileId === void 0 ? null : profileRows(ccr.config).find((item) => isJsonRecord(item) && item["id"] === ownership.profileId) ?? null;
31291
+ if (ownership.profileId !== void 0 && profileValue !== null && (ownership.profileSha256 === void 0 || scriptHash(stableJson2(profileValue)) !== ownership.profileSha256)) {
31292
+ return error("ccr-owned-profile-drift", "The CCR profile changed after Token Harness created it, so rollback left it untouched", "Review the profile in CCR Agent Config; restore it or remove it manually before retrying rollback");
31293
+ }
31294
+ const rules = isJsonRecord(ccr.config["Router"]) && Array.isArray(ccr.config["Router"]["rules"]) ? ccr.config["Router"]["rules"] : [];
31295
+ const ownedRule = rules.find((item) => isJsonRecord(item) && item["id"] === ownership.ruleId);
31296
+ if (ownedRule === void 0) {
31297
+ if (!context.confirmed) {
31298
+ return configurationResult("rollback", ownership.profileId === void 0 ? "already-absent" : "preview", ccr, harnessId2, ownership.mode, ownership.ruleId, ownership.scriptPath, ownership.profileId === void 0 ? [] : [
31299
+ diagnostic({
31300
+ severity: "info",
31301
+ code: "ccr-rollback-profile-preview",
31302
+ message: "Rollback would remove the remaining exact Token Harness CLI profile and local script",
31303
+ remediation: "Review the change and rerun with --yes to apply it"
31304
+ })
31305
+ ], ownership.profileId ?? null, ownership.profileId === void 0 ? null : ccrLaunchCommand(harnessId2));
31306
+ }
31307
+ if (ownership.profileId !== void 0) {
31308
+ const nextConfig2 = withoutOwnedCcrProfile(ccr.config, ownership.profileId, ownership.profileSha256);
31309
+ if (nextConfig2 === null) {
31310
+ return error("ccr-owned-profile-drift", "The CCR profile is duplicated or changed, so rollback left it untouched", "Review CCR Agent Config and retry after restoring the exact owned profile");
31311
+ }
31312
+ try {
31313
+ const currentConfig = await ccr.client.call("getConfig");
31314
+ if (!isSameCcrConfig(currentConfig, ccr.config))
31315
+ throw new CcrManagementError("config-drift");
31316
+ await ccr.client.call("saveConfig", [nextConfig2, { applyProfile: false }]);
31317
+ const afterConfig = await ccr.client.call("getConfig");
31318
+ if (profileRows(isJsonRecord(afterConfig) ? afterConfig : {}).some((item) => isJsonRecord(item) && item["id"] === ownership.profileId)) {
31319
+ throw new CcrManagementError("request-failed");
31320
+ }
31321
+ } catch (errorValue) {
31322
+ const issue = ccrFailure(errorValue);
31323
+ return commandResult({
31324
+ command: "routing",
31325
+ exitCode: EXIT_CODES["problems-found"],
31326
+ diagnostics: [diagnostic({ severity: "error", ...issue })]
31327
+ });
31328
+ }
31329
+ }
31330
+ const bytes = await fs.readFile(ownership.scriptPath).catch(() => null);
31331
+ if (bytes !== null && scriptHash(new TextDecoder().decode(bytes)) === ownership.scriptSha256) {
31332
+ await fs.remove(ownership.scriptPath);
31333
+ }
31334
+ await fs.remove(receiptPath3(context, harnessId2));
31335
+ return configurationResult("rollback", "already-absent", ccr, harnessId2, ownership.mode, ownership.ruleId, ownership.scriptPath);
31336
+ }
31337
+ if (!isExactCcrSmartRoutingRule(ownedRule, expectedRule)) {
31338
+ return error("ccr-owned-rule-drift", "The CCR rule changed after Token Harness installed it, so rollback left it untouched", "Review the rule in CCR Routing and restore or remove it manually before retrying");
31339
+ }
31340
+ if (!context.confirmed) {
31341
+ return configurationResult("rollback", "preview", ccr, harnessId2, ownership.mode, ownership.ruleId, ownership.scriptPath, [
31342
+ diagnostic({
31343
+ severity: "info",
31344
+ code: "ccr-rollback-preview",
31345
+ message: "Rollback would remove the exact Token Harness rule and script while preserving other CCR settings",
31346
+ path: ownership.scriptPath,
31347
+ remediation: "Review the change and rerun with --yes to apply it"
31348
+ }),
31349
+ ...ownership.profileId === void 0 ? [] : [
31350
+ diagnostic({
31351
+ severity: "info",
31352
+ code: "ccr-rollback-profile-preview",
31353
+ message: "Rollback also removes the exact Token Harness scoped CLI profile; providers and credentials remain unchanged",
31354
+ remediation: "Review the change and rerun with --yes to apply it"
31355
+ })
31356
+ ]
31357
+ ], ownership.profileId ?? null, ownership.profileId === void 0 ? null : ccrLaunchCommand(harnessId2));
31358
+ }
31359
+ const withoutRule = removeOwnedCcrSmartRoutingRule(ccr.config, ownership.ruleId, expectedRule);
31360
+ if (withoutRule === null) {
31361
+ return error("ccr-owned-rule-drift", "CCR rules changed while rollback was being prepared", "Refresh the CCR state and retry after reviewing the rule list");
31362
+ }
31363
+ const nextConfig = ownership.profileId === void 0 ? withoutRule : withoutOwnedCcrProfile(withoutRule, ownership.profileId, ownership.profileSha256);
31364
+ if (nextConfig === null) {
31365
+ return error("ccr-owned-profile-drift", "The Token Harness CCR profile changed while rollback was being prepared", "Refresh CCR state and retry after reviewing the profile");
31366
+ }
31367
+ try {
31368
+ const currentConfig = await ccr.client.call("getConfig");
31369
+ if (!isSameCcrConfig(currentConfig, ccr.config)) {
31370
+ throw new CcrManagementError("config-drift");
31371
+ }
31372
+ await ccr.client.call("saveConfig", [nextConfig, { applyProfile: false }]);
31373
+ const after = await ccr.client.call("getConfig");
31374
+ const afterRules = isJsonRecord(after) && isJsonRecord(after["Router"]) && Array.isArray(after["Router"]["rules"]) ? after["Router"]["rules"] : [];
31375
+ if (afterRules.some((item) => isJsonRecord(item) && item["id"] === ownership.ruleId)) {
31376
+ throw new CcrManagementError("request-failed");
31377
+ }
31378
+ if (ownership.profileId !== void 0 && profileRows(isJsonRecord(after) ? after : {}).some((item) => isJsonRecord(item) && item["id"] === ownership.profileId)) {
31379
+ throw new CcrManagementError("request-failed");
31380
+ }
31381
+ const gatewayValue = await ccr.client.call("getGatewayStatus");
31382
+ const gatewayState = safeGatewayState(gatewayValue);
31383
+ const bytes = await fs.readFile(ownership.scriptPath).catch(() => null);
31384
+ if (bytes !== null && scriptHash(new TextDecoder().decode(bytes)) === ownership.scriptSha256) {
31385
+ await fs.remove(ownership.scriptPath);
31386
+ }
31387
+ await fs.remove(receiptPath3(context, harnessId2));
31388
+ return configurationResult("rollback", "rolled-back", { ...ccr, gatewayState }, harnessId2, ownership.mode, ownership.ruleId, ownership.scriptPath, [
31389
+ diagnostic({
31390
+ severity: "info",
31391
+ code: "ccr-rollback-verified",
31392
+ message: "CCR no longer contains the owned rule; other routing rules were preserved",
31393
+ path: ownership.scriptPath,
31394
+ remediation: "No further action is required"
31395
+ })
31396
+ ]);
31397
+ } catch (errorValue) {
31398
+ const issue = ccrFailure(errorValue);
31399
+ return commandResult({
31400
+ command: "routing",
31401
+ exitCode: EXIT_CODES["problems-found"],
31402
+ diagnostics: [
31403
+ diagnostic({
31404
+ severity: "error",
31405
+ code: issue.code,
31406
+ message: `${issue.message}; the ownership receipt was retained for another rollback attempt`,
31407
+ path: receiptPath3(context, harnessId2),
31408
+ remediation: "Check CCR status and retry the rollback after it is reachable"
31409
+ })
31410
+ ]
31411
+ });
31412
+ }
31413
+ }
31414
+ async function runSmartRouting(context) {
31415
+ const wantsScript = context.routingScript === true;
31416
+ const wantsMetrics = context.routingMetrics === true;
31417
+ const wantsCcrConfigure = context.routingCcrConfigure === true;
31418
+ const wantsCcrRollback = context.routingCcrRollback === true;
31419
+ const wantsCcrUpdate = context.routingCcrUpdate === true;
31420
+ const requestedActions = [
31421
+ wantsScript,
31422
+ wantsMetrics,
31423
+ wantsCcrConfigure,
31424
+ wantsCcrRollback,
31425
+ wantsCcrUpdate
31426
+ ].filter(Boolean).length;
31427
+ if (requestedActions !== 1) {
31428
+ return error("routing-action-required", "Choose one Smart Model Routing action", "Use `token-harness routing --script --harness claude`, `--configure-ccr`, `--update-ccr`, `--rollback-ccr`, or `--route-metrics`");
31429
+ }
31430
+ if (context.routingPrune === true && !wantsMetrics) {
31431
+ return error("routing-prune-requires-metrics", "`--prune` is available only with the routing metrics action", "Use `token-harness routing --route-metrics --prune`");
31432
+ }
31433
+ if (context.routingCcrUsage === true && !wantsMetrics) {
31434
+ return error("ccr-usage-requires-metrics", "`--ccr-usage` is available only with routing metrics", "Use `token-harness routing --route-metrics --ccr-usage`");
31435
+ }
31436
+ if (context.routingMode === "conservative" && !wantsScript && !wantsCcrConfigure) {
31437
+ return error("routing-mode-requires-configuration", "`--route-mode` applies only when exporting or configuring a CCR rule", "Use `token-harness routing --configure-ccr --harness codex --route-mode conservative`");
31438
+ }
31439
+ if (wantsCcrConfigure) {
31440
+ let managed;
31441
+ try {
31442
+ managed = await resolveManagedCcr(context);
31443
+ } catch (errorValue) {
31444
+ const issue = ccrFailure(errorValue);
31445
+ return commandResult({
31446
+ command: "routing",
31447
+ exitCode: EXIT_CODES["problems-found"],
31448
+ diagnostics: [diagnostic({ severity: "error", ...issue })]
31449
+ });
31450
+ }
31451
+ if (managed.kind === "external")
31452
+ return ccrConfiguration(context);
31453
+ const ensured = await ensureManagedCcrRuntime({ context, action: "configure" });
31454
+ if (ensured.kind === "result")
31455
+ return ensured.result;
31456
+ if (ensured.changed) {
31457
+ const state = ensured.lifecycleAction === "install" ? "installed" : ensured.lifecycleAction === "update" ? "updated" : "started";
31458
+ return commandResult({
31459
+ command: "routing",
31460
+ exitCode: EXIT_CODES.ok,
31461
+ data: {
31462
+ kind: "ccr-lifecycle",
31463
+ action: ensured.lifecycleAction,
31464
+ state,
31465
+ version: CCR_REVIEWED_VERSION,
31466
+ packagePath: ensured.packagePath,
31467
+ executablePath: ensured.executablePath,
31468
+ managementEndpoint: ensured.endpoint
31469
+ },
31470
+ diagnostics: [
31471
+ diagnostic({
31472
+ severity: "info",
31473
+ code: `ccr-${ensured.lifecycleAction}-verified`,
31474
+ message: `Token Harness ${state} and verified the local CCR CLI and gateway`,
31475
+ remediation: `Next preview and configure the ${context.routingMode ?? "shadow"} routing rule with token-harness routing --configure-ccr --harness ${String(context.harness ?? "<claude|codex>")}; provider login/import remains a separate CCR choice`
31476
+ })
31477
+ ]
31478
+ });
31479
+ }
31480
+ const configured = await ccrConfiguration({
31481
+ ...context,
31482
+ env: {
31483
+ ...context.env ?? {},
31484
+ CCR_WEB_URL: ensured.endpoint,
31485
+ CCR_WEB_AUTH_TOKEN: ensured.token
31486
+ }
31487
+ });
31488
+ return configured;
31489
+ }
31490
+ if (wantsCcrUpdate) {
31491
+ let managed;
31492
+ try {
31493
+ managed = await resolveManagedCcr(context);
31494
+ } catch (errorValue) {
31495
+ const issue = ccrFailure(errorValue);
31496
+ return commandResult({
31497
+ command: "routing",
31498
+ exitCode: EXIT_CODES["problems-found"],
31499
+ diagnostics: [diagnostic({ severity: "error", ...issue })]
31500
+ });
31501
+ }
31502
+ if (managed.kind !== "managed") {
31503
+ return error("ccr-update-not-managed", "Token Harness updates only the CCR CLI installation it owns", "Install CCR through `token-harness routing --configure-ccr --harness <claude|codex>` first; external CCR installations are left to their owner");
31504
+ }
31505
+ const updated = await ensureManagedCcrRuntime({ context, action: "update" });
31506
+ if (updated.kind === "result")
31507
+ return updated.result;
31508
+ return commandResult({
31509
+ command: "routing",
31510
+ exitCode: EXIT_CODES.ok,
31511
+ data: {
31512
+ kind: "ccr-lifecycle",
31513
+ action: updated.lifecycleAction,
31514
+ state: updated.lifecycleAction === "start" ? "started" : updated.lifecycleAction === "update" ? "updated" : "installed",
31515
+ version: CCR_REVIEWED_VERSION,
31516
+ packagePath: updated.packagePath,
31517
+ executablePath: updated.executablePath,
31518
+ managementEndpoint: updated.endpoint
31519
+ },
31520
+ diagnostics: [
31521
+ diagnostic({
31522
+ severity: "info",
31523
+ code: `ccr-${updated.lifecycleAction}-verified`,
31524
+ message: updated.lifecycleAction === "update" ? `Token Harness updated its managed CCR CLI to ${CCR_REVIEWED_VERSION} and verified the gateway` : updated.lifecycleAction === "start" ? `Token Harness started its managed CCR ${CCR_REVIEWED_VERSION} service` : `Token Harness installed its managed CCR ${CCR_REVIEWED_VERSION} service`,
31525
+ remediation: "This verifies the local gateway only; it does not prove that a Claude Code or Codex request was routed or that subscription quota was saved"
31526
+ })
31527
+ ]
31528
+ });
31529
+ }
31530
+ if (wantsCcrRollback)
31531
+ return rollbackCcrConfiguration(context);
31532
+ const fs = context.adapters?.fs;
31533
+ const stateRoot = context.stateRoot;
31534
+ if (fs === void 0 || stateRoot === null) {
31535
+ return commandResult({
31536
+ command: "routing",
31537
+ exitCode: EXIT_CODES["unsupported-environment"],
31538
+ diagnostics: [
31539
+ diagnostic({
31540
+ severity: "error",
31541
+ code: "routing-state-unavailable",
31542
+ message: "Smart Model Routing requires the protected local Token Harness state directory",
31543
+ remediation: "Resolve the local state directory with `token-harness doctor`"
31544
+ })
31545
+ ]
31546
+ });
31547
+ }
31548
+ const telemetryDirectory = fs.join(stateRoot, "smart-routing");
31549
+ if (wantsScript) {
31550
+ if (!isSmartRoutingHarness(context.harness)) {
31551
+ return error("routing-harness-required", "CCR script generation needs Claude Code or Codex as its harness", "Pass `--harness claude` or `--harness codex`");
31552
+ }
31553
+ await fs.createDirectory(telemetryDirectory);
31554
+ const script = createCcrSmartRoutingScript({
31555
+ harnessId: context.harness,
31556
+ mode: context.routingMode ?? "shadow",
31557
+ telemetryDirectory,
31558
+ pathSeparator: context.platform.os === "windows" ? "\\" : "/"
31559
+ });
31560
+ return commandResult({
31561
+ command: "routing",
31562
+ exitCode: EXIT_CODES.ok,
31563
+ data: {
31564
+ kind: "ccr-script",
31565
+ harnessId: context.harness,
31566
+ mode: context.routingMode ?? "shadow",
31567
+ telemetryDirectory,
31568
+ script
31569
+ }
31570
+ });
31571
+ }
31572
+ const resolved = resolveMetricsWindow({
31573
+ since: context.since,
31574
+ until: context.until,
31575
+ now: context.now()
31576
+ });
31577
+ if (!resolved.ok) {
31578
+ return error("invalid-routing-window", resolved.failure === "start-after-end" ? `The routing metrics window is empty: ${resolved.detail}` : `${JSON.stringify(resolved.detail)} is not a duration such as \`7d\` or a date such as \`2026-09-01\``, "Pass `--since 7d`, or `--since 2026-09-01 --until 2026-09-24`");
31579
+ }
31580
+ const directoryEntries = (await fs.readDirectory(telemetryDirectory)).filter((name2) => new RegExp(`^${SMART_ROUTING_EVENT_PREFIX}\\d{13}-[a-z0-9]+\\.json$`).test(name2)).sort();
31581
+ let prunedRecordCount = 0;
31582
+ if (context.routingPrune === true && directoryEntries.length > SMART_ROUTING_EVENT_RETENTION_LIMIT) {
31583
+ const removeCount = directoryEntries.length - SMART_ROUTING_EVENT_RETENTION_LIMIT;
31584
+ for (const name2 of directoryEntries.slice(0, removeCount)) {
31585
+ await fs.remove(fs.join(telemetryDirectory, name2));
31586
+ }
31587
+ prunedRecordCount = removeCount;
31588
+ }
31589
+ const retainedNames = context.routingPrune === true ? directoryEntries.slice(prunedRecordCount) : directoryEntries;
31590
+ const events = [];
31591
+ let malformedRecordCount = 0;
31592
+ for (const name2 of retainedNames) {
31593
+ try {
31594
+ const content = new TextDecoder().decode(await fs.readFile(fs.join(telemetryDirectory, name2)));
31595
+ const parsed = JSON.parse(content);
31596
+ if (!isSmartRoutingDecisionEvent(parsed)) {
31597
+ malformedRecordCount += 1;
31598
+ continue;
31599
+ }
31600
+ const timestamp = Date.parse(parsed.timestamp);
31601
+ if (!Number.isFinite(timestamp)) {
31602
+ malformedRecordCount += 1;
31603
+ continue;
31604
+ }
31605
+ if (timestamp < Date.parse(resolved.window.sinceInstant))
31606
+ continue;
31607
+ if (timestamp >= Date.parse(resolved.window.untilInstant))
31608
+ continue;
31609
+ if (context.harness !== null && parsed.harnessId !== context.harness)
31610
+ continue;
31611
+ events.push(parsed);
31612
+ } catch {
31613
+ malformedRecordCount += 1;
31614
+ }
31615
+ }
31616
+ const metrics = aggregateSmartRoutingEvents({ events, malformedRecordCount, prunedRecordCount });
31617
+ let ccrUsage;
31618
+ const diagnostics = events.length === 0 && malformedRecordCount === 0 ? [
31619
+ diagnostic({
31620
+ severity: "info",
31621
+ code: "routing-decisions-unavailable",
31622
+ message: "No CCR routing decisions are stored for this window",
31623
+ remediation: "Generate a CCR rule with `token-harness routing --script --harness codex` or configure one with `--configure-ccr`"
31624
+ })
31625
+ ] : [];
31626
+ if (context.routingCcrUsage === true) {
31627
+ try {
31628
+ const observed = await observeCcrUsage({
31629
+ context,
31630
+ events,
31631
+ since: resolved.window.sinceInstant,
31632
+ until: resolved.window.untilInstant
31633
+ });
31634
+ ccrUsage = observed.usage;
31635
+ if (observed.failedSessions > 0 || observed.usage.status === "unavailable") {
31636
+ diagnostics.push(diagnostic({
31637
+ severity: "warning",
31638
+ code: observed.usage.status === "unavailable" ? "ccr-usage-unavailable" : "ccr-usage-partial",
31639
+ message: observed.usage.status === "unavailable" ? "CCR request usage could not be matched to any retained routing session" : `CCR usage was read for ${String(observed.usage.observedSessionCount)} of ${String(observed.usage.sessionCount)} sessions`,
31640
+ remediation: "Keep CCR request logging enabled, use the same local session, and rerun with a narrower time window"
31641
+ }));
31642
+ }
31643
+ } catch (errorValue) {
31644
+ const issue = ccrFailure(errorValue);
31645
+ diagnostics.push(diagnostic({ severity: "warning", ...issue }));
31646
+ ccrUsage = {
31647
+ status: "unavailable",
31648
+ sessionCount: 0,
31649
+ observedSessionCount: 0,
31650
+ requestCount: 0,
31651
+ inputTokens: 0,
31652
+ outputTokens: 0,
31653
+ cacheReadTokens: 0,
31654
+ cacheWriteTokens: 0,
31655
+ totalTokens: 0,
31656
+ recordedCostUsd: null,
31657
+ byModel: []
31658
+ };
31659
+ }
31660
+ }
31661
+ return commandResult({
31662
+ command: "routing",
31663
+ exitCode: EXIT_CODES.ok,
31664
+ data: {
31665
+ kind: "metrics",
31666
+ since: resolved.window.sinceInstant,
31667
+ until: resolved.window.untilInstant,
31668
+ metrics,
31669
+ ...ccrUsage === void 0 ? {} : { ccrUsage }
31670
+ },
31671
+ diagnostics
31672
+ });
31673
+ }
31674
+ var OWNED_PROFILE_IDS;
31675
+ var init_smart_routing2 = __esm({
31676
+ "apps/cli/dist/src/commands/smart-routing.js"() {
31677
+ "use strict";
31678
+ init_src3();
31679
+ init_src();
31680
+ init_routing_usage();
31681
+ init_ccr_runtime();
31682
+ OWNED_PROFILE_IDS = {
31683
+ claude: "token-harness-smart-routing-claude-v1",
31684
+ codex: "token-harness-smart-routing-codex-v1"
31685
+ };
31686
+ }
31687
+ });
31688
+
29055
31689
  // apps/cli/dist/src/commands/verify.js
29056
31690
  async function runVerify(context) {
29057
31691
  const diagnostics = [];
@@ -29848,6 +32482,12 @@ async function runPackageChannelUpdate(context, options = {}) {
29848
32482
  report.providers.push(row2);
29849
32483
  continue;
29850
32484
  }
32485
+ if (adapter.manifest.id === "rtk" && context.adapters.resolveExecutables !== void 0 && (context.platform.os === "linux" || context.platform.os === "macos")) {
32486
+ row2.channel = "github-release";
32487
+ row2.verdict = "unknown";
32488
+ report.providers.push(row2);
32489
+ continue;
32490
+ }
29851
32491
  const packageName = channel.packageId ?? adapter.manifest.id;
29852
32492
  const query = await queryAvailableVersion({
29853
32493
  packageManager: channel.id,
@@ -30142,80 +32782,123 @@ var init_update_base = __esm({
30142
32782
  });
30143
32783
 
30144
32784
  // apps/cli/dist/src/commands/rtk-release-update.js
30145
- async function planDirectRtkWindowsRelease(input) {
30146
- const empty2 = () => ({
32785
+ async function planDirectRtkRelease(input) {
32786
+ const empty2 = (verdict = "unsupported", diagnostics = []) => ({
30147
32787
  plan: null,
30148
- diagnostics: [],
32788
+ availableVersion: null,
32789
+ verdict,
32790
+ diagnostics,
30149
32791
  destinations: []
30150
32792
  });
30151
32793
  if (input.providerId !== "rtk")
30152
32794
  return empty2();
30153
- if (input.platform.os !== "windows" || input.platform.isWsl)
30154
- return empty2();
30155
- if (input.installedVersion === null)
30156
- return empty2();
30157
- const installed2 = parseSemanticVersion(input.installedVersion);
30158
32795
  const targetText = reviewedProviderPackageMaximum(input.providerId);
30159
- const target = targetText === null ? null : parseSemanticVersion(targetText);
30160
- if (installed2 === null || target === null || targetText === null)
30161
- return empty2();
30162
- if (compareVersions(target, installed2) <= 0)
30163
- return empty2();
30164
- const channel = input.channelAvailableVersion === null ? null : parseSemanticVersion(input.channelAvailableVersion);
30165
- if (channel !== null && compareVersions(channel, target) >= 0)
32796
+ if (targetText === null)
30166
32797
  return empty2();
30167
- const admission = admitProviderPackageUpdate(input.providerId, targetText);
30168
- if (admission.state !== "admitted")
30169
- return empty2();
30170
- if (input.executablePaths.length !== 1) {
30171
- const detail2 = input.executablePaths.length === 0 ? "no concrete rtk.exe path could be resolved" : `${String(input.executablePaths.length)} different rtk.exe paths resolve: ${input.executablePaths.join(", ")}`;
32798
+ const windows = input.platform.os === "windows" && !input.platform.isWsl;
32799
+ if (rtkReleaseAssetForPlatform(input.platform) === null) {
32800
+ return windows ? empty2("defer") : empty2("unavailable", [
32801
+ diagnostic({
32802
+ severity: "warning",
32803
+ code: "rtk-release-platform-unsupported",
32804
+ subject: input.providerId,
32805
+ message: `The RTK GitHub release has no managed artifact for ${input.platform.os}/${input.platform.arch}`,
32806
+ remediation: "Update RTK manually from its official installation instructions"
32807
+ })
32808
+ ]);
32809
+ }
32810
+ const installedText = input.installedVersion;
32811
+ if (installedText === null)
32812
+ return empty2("unavailable");
32813
+ const installed2 = parseSemanticVersion(installedText);
32814
+ const target = parseSemanticVersion(targetText);
32815
+ if (installed2 === null || target === null)
32816
+ return empty2("unavailable");
32817
+ if (windows) {
32818
+ const channel = input.channelAvailableVersion === null ? null : parseSemanticVersion(input.channelAvailableVersion);
32819
+ if (channel !== null && compareVersions(channel, target) >= 0)
32820
+ return empty2("defer");
32821
+ }
32822
+ if (compareVersions(target, installed2) <= 0) {
30172
32823
  return {
30173
- plan: null,
30174
- destinations: [],
30175
- diagnostics: [
30176
- diagnostic({
30177
- severity: "warning",
30178
- code: "rtk-release-target-ambiguous",
30179
- subject: input.providerId,
30180
- message: `The verified GitHub release fallback was not planned because ${detail2}`,
30181
- remediation: "Make exactly one intended RTK executable resolve on PATH, then re-run update; Token Harness will not choose an arbitrary binary to overwrite"
30182
- })
30183
- ]
32824
+ ...empty2("current"),
32825
+ availableVersion: targetText
30184
32826
  };
30185
32827
  }
30186
- const executablePath = input.executablePaths[0];
30187
- if (executablePath === void 0)
30188
- return empty2();
30189
- const runtime = rtkWindowsReleaseRuntimeFor(input.fs, input.runner);
32828
+ const admission = admitProviderPackageUpdate(input.providerId, targetText);
32829
+ if (admission.state !== "admitted")
32830
+ return empty2("unavailable");
32831
+ if (input.executables.length !== 1) {
32832
+ const detail2 = input.executables.length === 0 ? "no concrete RTK executable path could be resolved" : `${String(input.executables.length)} RTK executable paths resolve: ${input.executables.map((entry) => entry.path).join(", ")}`;
32833
+ return empty2("unavailable", [
32834
+ diagnostic({
32835
+ severity: "warning",
32836
+ code: "rtk-release-target-ambiguous",
32837
+ subject: input.providerId,
32838
+ message: `The verified GitHub release update was not planned because ${detail2}`,
32839
+ remediation: "Make exactly one intended RTK executable resolve on PATH, then re-run Check for updates; Token Harness will not choose an arbitrary binary to replace"
32840
+ })
32841
+ ]);
32842
+ }
32843
+ const executable = input.executables[0];
32844
+ if (executable === void 0 || executable.kind !== "native") {
32845
+ return empty2("unavailable", [
32846
+ diagnostic({
32847
+ severity: "warning",
32848
+ code: "rtk-release-target-not-native",
32849
+ subject: input.providerId,
32850
+ message: "The resolved RTK path is not a native executable, so its file will not be replaced",
32851
+ remediation: "Install RTK as a native binary, then retry the update check"
32852
+ })
32853
+ ]);
32854
+ }
32855
+ const canonicalPath = input.fs.canonicalPath;
32856
+ if (canonicalPath === void 0)
32857
+ return empty2("unavailable");
32858
+ const targetPath = await canonicalPath.call(input.fs, executable.path);
32859
+ if (targetPath === null) {
32860
+ return empty2("unavailable", [
32861
+ diagnostic({
32862
+ severity: "warning",
32863
+ code: "rtk-release-target-unresolved",
32864
+ subject: input.providerId,
32865
+ path: executable.path,
32866
+ message: "The resolved RTK executable path could not be canonicalized",
32867
+ remediation: "Check PATH and filesystem access, then retry the update check"
32868
+ })
32869
+ ]);
32870
+ }
32871
+ const runtime = rtkReleaseRuntimeFor(input.fs, input.runner, input.releaseFetch);
30190
32872
  if (runtime === null)
30191
- return empty2();
30192
- const queried = await runtime.query(targetText);
32873
+ return empty2("unavailable");
32874
+ const queried = await runtime.query(targetText, input.platform);
30193
32875
  if (queried.status !== "found") {
30194
32876
  return {
30195
- plan: null,
30196
- destinations: [RTK_RELEASE_METADATA_DESTINATION],
30197
- diagnostics: [
32877
+ ...empty2("unavailable", [
30198
32878
  diagnostic({
30199
32879
  severity: "warning",
30200
32880
  code: "rtk-release-fallback-unavailable",
30201
32881
  subject: input.providerId,
30202
- message: `RTK ${targetText} is reviewed but its verified Windows GitHub release could not be selected: ${queried.message}`,
30203
- remediation: "Token Harness will keep using the ordinary package channel; retry after checking GitHub connectivity or release metadata"
32882
+ message: `RTK ${targetText} is reviewed but its official GitHub release could not be selected: ${queried.message}`,
32883
+ remediation: "Retry after checking GitHub connectivity and confirm that the RTK release includes an asset for this platform"
30204
32884
  })
30205
- ]
32885
+ ]),
32886
+ destinations: [RTK_RELEASE_METADATA_DESTINATION]
30206
32887
  };
30207
32888
  }
30208
- const digest = digestText(`${input.providerId} github-release ${input.installedVersion} ${targetText} ${executablePath}`);
32889
+ const digest = digestText(`${input.providerId} github-release ${installedText} ${targetText} ${targetPath}`);
30209
32890
  return {
30210
32891
  plan: {
30211
32892
  id: digest.slice(digest.indexOf(":") + 1, digest.indexOf(":") + 9),
30212
32893
  providerId: input.providerId,
30213
- installed: input.installedVersion,
32894
+ installed: installedText,
30214
32895
  target: targetText,
30215
- targetPath: executablePath,
32896
+ targetPath,
30216
32897
  asset: queried.asset,
30217
32898
  runtime
30218
32899
  },
32900
+ availableVersion: targetText,
32901
+ verdict: "upgradable",
30219
32902
  diagnostics: [],
30220
32903
  destinations: [RTK_RELEASE_METADATA_DESTINATION]
30221
32904
  };
@@ -30251,47 +32934,50 @@ function execution(input) {
30251
32934
  receiptId: input.base?.receiptId ?? (input.outcome === "committed" && input.transactionId !== null ? input.transactionId : null)
30252
32935
  };
30253
32936
  }
30254
- function withDirectRow(report, plan6, destinations) {
32937
+ function withDirectRow(report, direct) {
30255
32938
  return {
30256
- providers: report.providers.map((row2) => row2.providerId === plan6.providerId ? {
32939
+ providers: report.providers.map((row2) => row2.providerId === "rtk" ? {
30257
32940
  ...row2,
30258
- available: plan6.target,
32941
+ available: direct.availableVersion,
30259
32942
  channel: "github-release",
30260
- verdict: "upgradable"
32943
+ verdict: direct.verdict === "current" ? "current" : direct.plan ? "upgradable" : "unavailable"
30261
32944
  } : row2),
30262
32945
  ...report.application === void 0 ? {} : { application: report.application },
30263
- network: [.../* @__PURE__ */ new Set([...report.network, ...destinations])].sort(),
32946
+ network: [.../* @__PURE__ */ new Set([...report.network, ...direct.destinations])].sort(),
30264
32947
  execution: report.execution
30265
32948
  };
30266
32949
  }
30267
32950
  async function prepareDirectRtkUpdate(context) {
30268
32951
  if (context.adapters === null)
30269
32952
  return null;
30270
- if (context.platform.os !== "windows" || context.platform.isWsl)
32953
+ if (!["windows", "linux", "macos"].includes(context.platform.os))
30271
32954
  return null;
30272
32955
  if (context.provider !== null && context.provider !== "rtk")
30273
32956
  return null;
32957
+ if (context.adapters.resolveExecutables === void 0)
32958
+ return null;
30274
32959
  const ordinary = await runPackageChannelUpdateCheck(context);
30275
32960
  if (ordinary.data === null)
30276
32961
  return null;
30277
32962
  const row2 = ordinary.data.providers.find((entry) => entry.providerId === "rtk");
30278
32963
  if (row2 === void 0 || row2.installed === null || row2.pin !== null)
30279
32964
  return null;
30280
- const resolved = context.adapters.resolveExecutables?.("rtk") ?? [];
30281
- const direct = await planDirectRtkWindowsRelease({
32965
+ const executables = context.adapters.resolveExecutables("rtk");
32966
+ const direct = await planDirectRtkRelease({
30282
32967
  providerId: row2.providerId,
30283
32968
  installedVersion: row2.installed,
30284
- executablePaths: resolved.map((entry) => entry.path),
32969
+ executables,
30285
32970
  channelAvailableVersion: row2.available,
30286
32971
  platform: context.platform,
30287
32972
  fs: context.adapters.fs,
30288
- runner: context.adapters.runner
32973
+ runner: context.adapters.runner,
32974
+ ...context.adapters.rtkReleaseFetch === void 0 ? {} : { releaseFetch: context.adapters.rtkReleaseFetch }
30289
32975
  });
30290
- if (direct.plan === null && direct.diagnostics.length === 0)
32976
+ if (direct.verdict === "defer" || direct.verdict === "unsupported")
30291
32977
  return null;
30292
32978
  return {
30293
32979
  ordinary,
30294
- report: direct.plan === null ? ordinary.data : withDirectRow(ordinary.data, direct.plan, direct.destinations),
32980
+ report: withDirectRow(ordinary.data, direct),
30295
32981
  plan: direct.plan,
30296
32982
  directDiagnostics: direct.diagnostics
30297
32983
  };
@@ -30328,13 +33014,27 @@ function provenanceDiagnostic(plan6) {
30328
33014
  function result5(exitCode, data, diagnostics) {
30329
33015
  return commandResult({ command: "update", exitCode, data, diagnostics: [...diagnostics] });
30330
33016
  }
33017
+ function mergePreparedRtkRow(report, prepared) {
33018
+ if (report === null)
33019
+ return null;
33020
+ const rtk = prepared.providers.find((row2) => row2.providerId === "rtk");
33021
+ if (rtk === void 0)
33022
+ return report;
33023
+ return {
33024
+ ...report,
33025
+ providers: report.providers.some((row2) => row2.providerId === "rtk") ? report.providers.map((row2) => row2.providerId === "rtk" ? rtk : row2) : [...report.providers, rtk],
33026
+ ...report.application === void 0 && prepared.application !== void 0 ? { application: prepared.application } : {},
33027
+ network: [.../* @__PURE__ */ new Set([...report.network, ...prepared.network])].sort()
33028
+ };
33029
+ }
30331
33030
  async function runUpdate(context) {
30332
33031
  const prepared = await prepareDirectRtkUpdate(context);
30333
33032
  if (prepared === null)
30334
33033
  return runPackageChannelUpdate(context);
30335
33034
  if (prepared.plan === null) {
30336
33035
  const ordinary = await runPackageChannelUpdate(context);
30337
- return result5(ordinary.exitCode, ordinary.data, [
33036
+ const report2 = mergePreparedRtkRow(ordinary.data, prepared.report);
33037
+ return result5(ordinary.exitCode, report2, [
30338
33038
  ...ordinary.diagnostics,
30339
33039
  ...prepared.directDiagnostics
30340
33040
  ]);
@@ -30412,7 +33112,7 @@ async function runUpdate(context) {
30412
33112
  let snapshot;
30413
33113
  try {
30414
33114
  snapshot = await snapshotCreation.store.capture(plan6.targetPath);
30415
- } catch (error) {
33115
+ } catch (error2) {
30416
33116
  return result5(EXIT_CODES["internal-error"], null, [
30417
33117
  ...preparedDiagnostics,
30418
33118
  diagnostic({
@@ -30420,7 +33120,7 @@ async function runUpdate(context) {
30420
33120
  code: "rtk-release-snapshot-failed",
30421
33121
  subject: "rtk",
30422
33122
  path: plan6.targetPath,
30423
- message: `RTK was not touched because its pre-update snapshot could not be captured: ${error instanceof Error ? error.message : String(error)}`,
33123
+ message: `RTK was not touched because its pre-update snapshot could not be captured: ${error2 instanceof Error ? error2.message : String(error2)}`,
30424
33124
  remediation: "Check the state directory and executable permissions, then retry"
30425
33125
  })
30426
33126
  ]);
@@ -30454,7 +33154,7 @@ async function runUpdate(context) {
30454
33154
  };
30455
33155
  try {
30456
33156
  await journalStore.write(directJournal);
30457
- } catch (error) {
33157
+ } catch (error2) {
30458
33158
  return result5(EXIT_CODES["internal-error"], null, [
30459
33159
  ...preparedDiagnostics,
30460
33160
  diagnostic({
@@ -30462,7 +33162,7 @@ async function runUpdate(context) {
30462
33162
  code: "rtk-release-journal-failed",
30463
33163
  subject: "rtk",
30464
33164
  path: plan6.targetPath,
30465
- message: `RTK was not touched because its in-progress transaction journal could not be persisted: ${error instanceof Error ? error.message : String(error)}`,
33165
+ message: `RTK was not touched because its in-progress transaction journal could not be persisted: ${error2 instanceof Error ? error2.message : String(error2)}`,
30466
33166
  remediation: "Check the Token Harness state directory, then retry"
30467
33167
  })
30468
33168
  ]);
@@ -30501,13 +33201,13 @@ async function runUpdate(context) {
30501
33201
  subject: "rtk",
30502
33202
  path: plan6.targetPath,
30503
33203
  message: installed2.message,
30504
- remediation: installed2.status === "dirty" ? `Recovery backup: ${installed2.backupPath ?? "unavailable"}. Do not retry until the executable path is inspected.` : "Correct the reported release or Windows application-control problem, then retry the update"
33204
+ remediation: installed2.status === "dirty" ? `Recovery backup: ${installed2.backupPath ?? "unavailable"}. Do not retry until the executable path is inspected.` : "Correct the reported release or executable policy problem, then retry the update"
30505
33205
  });
30506
33206
  try {
30507
33207
  await finishDirectJournal(installed2.status === "dirty" ? "dirty" : "rolled-back", "failed", [
30508
33208
  failureDiagnostic
30509
33209
  ]);
30510
- } catch (error) {
33210
+ } catch (error2) {
30511
33211
  return result5(EXIT_CODES["apply-failed-dirty"], null, [
30512
33212
  ...preparedDiagnostics,
30513
33213
  failureDiagnostic,
@@ -30516,7 +33216,7 @@ async function runUpdate(context) {
30516
33216
  code: "rtk-release-failure-journal-write-failed",
30517
33217
  subject: "rtk",
30518
33218
  path: plan6.targetPath,
30519
- message: `RTK update failed and its final journal state could not be persisted: ${error instanceof Error ? error.message : String(error)}`,
33219
+ message: `RTK update failed and its final journal state could not be persisted: ${error2 instanceof Error ? error2.message : String(error2)}`,
30520
33220
  remediation: `Inspect transaction ${transactionId2} and its backups before retrying`
30521
33221
  })
30522
33222
  ]);
@@ -30535,7 +33235,7 @@ async function runUpdate(context) {
30535
33235
  }
30536
33236
  try {
30537
33237
  await markDirectAppliedInProgress();
30538
- } catch (error) {
33238
+ } catch (error2) {
30539
33239
  const rollback = await plan6.runtime.rollback(installed2.handle, context.projectRoot);
30540
33240
  const dirty = rollback.status === "dirty";
30541
33241
  const persistenceDiagnostic = diagnostic({
@@ -30543,7 +33243,7 @@ async function runUpdate(context) {
30543
33243
  code: "rtk-release-applied-journal-write-failed",
30544
33244
  subject: "rtk",
30545
33245
  path: plan6.targetPath,
30546
- message: `RTK ${plan6.target} was installed but Token Harness could not persist the applied journal state: ${error instanceof Error ? error.message : String(error)}. ${rollback.message}`,
33246
+ message: `RTK ${plan6.target} was installed but Token Harness could not persist the applied journal state: ${error2 instanceof Error ? error2.message : String(error2)}. ${rollback.message}`,
30547
33247
  remediation: `Inspect transaction ${transactionId2} and its backups before retrying`
30548
33248
  });
30549
33249
  try {
@@ -30620,7 +33320,7 @@ async function runUpdate(context) {
30620
33320
  });
30621
33321
  try {
30622
33322
  await finishDirectJournal("committed", "applied", [committedDiagnostic]);
30623
- } catch (error) {
33323
+ } catch (error2) {
30624
33324
  const rollback = await plan6.runtime.rollback(installed2.handle, context.projectRoot);
30625
33325
  const dirty = rollback.status === "dirty";
30626
33326
  const persistenceDiagnostic = diagnostic({
@@ -30628,7 +33328,7 @@ async function runUpdate(context) {
30628
33328
  code: "rtk-release-commit-journal-write-failed",
30629
33329
  subject: "rtk",
30630
33330
  path: plan6.targetPath,
30631
- message: `RTK ${plan6.target} was installed but the committed journal could not be persisted: ${error instanceof Error ? error.message : String(error)}. ${rollback.message}`,
33331
+ message: `RTK ${plan6.target} was installed but the committed journal could not be persisted: ${error2 instanceof Error ? error2.message : String(error2)}. ${rollback.message}`,
30632
33332
  remediation: `Inspect transaction ${transactionId2} and its backups before retrying`
30633
33333
  });
30634
33334
  await finishDirectJournal(dirty ? "dirty" : "rolled-back", "failed", [
@@ -30650,7 +33350,7 @@ async function runUpdateCheck(context) {
30650
33350
  if (prepared === null)
30651
33351
  return runPackageChannelUpdateCheck(context);
30652
33352
  if (prepared.plan === null) {
30653
- return result5(prepared.ordinary.exitCode, prepared.ordinary.data, [
33353
+ return result5(prepared.ordinary.exitCode, prepared.report, [
30654
33354
  ...prepared.ordinary.diagnostics,
30655
33355
  ...prepared.directDiagnostics
30656
33356
  ]);
@@ -30865,7 +33565,8 @@ var init_apply2 = __esm({
30865
33565
  // apps/cli/dist/src/render/benchmark.js
30866
33566
  function receiptLine(label, receipt) {
30867
33567
  const local = receipt.localUsage === null ? "local tokens unknown" : `local ${formatCount(receipt.localUsage.totalTokens)} tokens`;
30868
- return `${label}: quality ${receipt.outcome.qualityGate}; attempts ${String(receipt.outcome.attempts)}; failed ${String(receipt.outcome.failedAttempts)}; errors ${String(receipt.outcome.errorCodes.length)}; ${local}`;
33568
+ const ccr = receipt.ccrUsage === void 0 || receipt.ccrUsage === null ? "CCR usage not captured" : `CCR ${receipt.ccrUsage.status}, ${formatCount(receipt.ccrUsage.totalTokens)} tokens across ${String(receipt.ccrUsage.requestCount)} requests`;
33569
+ return `${label}: quality ${receipt.outcome.qualityGate}; attempts ${String(receipt.outcome.attempts)}; failed ${String(receipt.outcome.failedAttempts)}; errors ${String(receipt.outcome.errorCodes.length)}; ${local}; ${ccr}`;
30869
33570
  }
30870
33571
  function policyLine(label, receipt) {
30871
33572
  const parts = [
@@ -30893,6 +33594,21 @@ function renderBenchmarkReport(report, _context) {
30893
33594
  } else {
30894
33595
  lines.push(...wrap(`Backend quota (${comparison.quota.scope}, ${comparison.quota.confidence}): baseline +${String(comparison.quota.baselineDeltaUsedPercent)}% vs optimized +${String(comparison.quota.optimizedDeltaUsedPercent)}%`, 0));
30895
33596
  }
33597
+ const ccrUsage = comparison.ccrUsage;
33598
+ if (ccrUsage === void 0 || ccrUsage.status === "not-measured") {
33599
+ lines.push("CCR observed usage: not measured for both variants");
33600
+ } else if (ccrUsage.status === "comparable") {
33601
+ const modelPair = `${ccrUsage.baselineModels.join(", ") || "unknown"} \u2192 ${ccrUsage.optimizedModels.join(", ") || "unknown"}`;
33602
+ lines.push(...wrap(`CCR request usage: ${formatCount(ccrUsage.baselineTokens ?? 0)} \u2192 ${formatCount(ccrUsage.optimizedTokens ?? 0)} tokens; delta ${String(ccrUsage.totalTokenDelta ?? 0)}; models ${modelPair}`, 0));
33603
+ if (ccrUsage.recordedCostDeltaUsd !== null) {
33604
+ lines.push(`CCR recorded provider-cost estimate delta: ${ccrUsage.recordedCostDeltaUsd.toFixed(6)} USD`);
33605
+ }
33606
+ lines.push("CCR request tokens and price estimates remain separate from subscription quota");
33607
+ } else if (ccrUsage.status === "quality-gated") {
33608
+ lines.push("CCR request usage: observed, but delta withheld until both task quality gates pass");
33609
+ } else {
33610
+ lines.push("CCR request usage: partial or ambiguous, not compared");
33611
+ }
30896
33612
  const contextCounts = context.baseline === null || context.optimized === null ? "" : ` \u2014 static MCP tools ${String(context.baseline.effectiveStaticMcpToolCount)} \u2192 ${String(context.optimized.effectiveStaticMcpToolCount)}`;
30897
33613
  lines.push(...wrap(`Context: ${context.verdict}${contextCounts}`, 0));
30898
33614
  lines.push(...wrap(`Context evidence: ${context.reason}`, 2));
@@ -30949,7 +33665,7 @@ function renderBenchmarkStartReport(report, context) {
30949
33665
  }
30950
33666
  function renderBenchmarkFinishReport(report, context) {
30951
33667
  const { receipt } = report;
30952
- const receiptPath3 = truncatePath(displayPath(report.receiptPath, context.home), MAX_WIDTH - "Receipt: ".length);
33668
+ const receiptPath4 = truncatePath(displayPath(report.receiptPath, context.home), MAX_WIDTH - "Receipt: ".length);
30953
33669
  return document([
30954
33670
  `Benchmark receipt \u2014 ${receipt.benchmarkId} / ${receipt.variant}`,
30955
33671
  `${receipt.taskClass} on ${receipt.harnessId}`,
@@ -30957,7 +33673,7 @@ function renderBenchmarkFinishReport(report, context) {
30957
33673
  ...wrap(`Quality ${receipt.outcome.qualityGate}; attempts ${String(receipt.outcome.attempts)}; failed attempts ${String(receipt.outcome.failedAttempts)}`, 0),
30958
33674
  `Quota windows: ${String(receipt.usageBefore.length)} before / ${String(receipt.usageAfter.length)} after`,
30959
33675
  receipt.localUsage === null ? "Local usage: unavailable or ambiguous" : `Local usage: ${String(receipt.localUsage.totalTokens)} tokens (local evidence only)`,
30960
- `Receipt: ${receiptPath3}`,
33676
+ `Receipt: ${receiptPath4}`,
30961
33677
  "",
30962
33678
  ...wrap(`After both variants are complete, review the project evidence with: token-harness benchmark-matrix --harness ${receipt.harnessId} --task ${receipt.taskClass}. Use token-harness benchmark --baseline <baseline.json> --optimized <optimized.json> only when you need one specific pair.`, 0)
30963
33679
  ]);
@@ -30998,6 +33714,30 @@ function localLine(summary) {
30998
33714
  }
30999
33715
  return `local tokens across ${String(summary.localComparablePairs)} quality-passed pairs \u2014 baseline ${formatCount(summary.baselineLocalTokens)}, optimized ${formatCount(summary.optimizedLocalTokens)}, delta ${percent2(summary.localTokenSavingPercent)}`;
31000
33716
  }
33717
+ function signedCount(value3) {
33718
+ return `${value3 > 0 ? "+" : ""}${formatCount(value3)}`;
33719
+ }
33720
+ function signedUsd(value3) {
33721
+ return `${value3 > 0 ? "+" : ""}${value3.toFixed(6)}`;
33722
+ }
33723
+ function ccrUsageLines(summary, indent) {
33724
+ const usage = summary.ccrUsage;
33725
+ if (usage === void 0)
33726
+ return [];
33727
+ const lines = [];
33728
+ if (usage.comparablePairs > 0 && usage.baselineTokens !== null && usage.optimizedTokens !== null && usage.totalTokenDelta !== null) {
33729
+ lines.push(...wrap(`CCR observed tokens across ${String(usage.comparablePairs)} quality-passed pairs \u2014 baseline ${formatCount(usage.baselineTokens)}, optimized ${formatCount(usage.optimizedTokens)}, delta ${signedCount(usage.totalTokenDelta)}`, indent));
33730
+ } else if (usage.partialPairs > 0 || usage.qualityGatedPairs > 0) {
33731
+ lines.push(...wrap(`CCR usage deltas withheld \u2014 partial ${String(usage.partialPairs)}, quality-gated ${String(usage.qualityGatedPairs)}`, indent));
33732
+ }
33733
+ if (usage.recordedCostPairs > 0 && usage.baselineRecordedCostUsd !== null && usage.optimizedRecordedCostUsd !== null && usage.recordedCostDeltaUsd !== null) {
33734
+ lines.push(...wrap(`CCR recorded provider-cost estimate across ${String(usage.recordedCostPairs)} pairs \u2014 baseline ${usage.baselineRecordedCostUsd.toFixed(6)} USD, optimized ${usage.optimizedRecordedCostUsd.toFixed(6)} USD, delta ${signedUsd(usage.recordedCostDeltaUsd)} USD`, indent));
33735
+ }
33736
+ if (usage.comparablePairs > 0 || usage.partialPairs > 0 || usage.qualityGatedPairs > 0) {
33737
+ lines.push(...wrap("CCR usage and cost estimates are separate from subscription quota and billed savings.", indent));
33738
+ }
33739
+ return lines;
33740
+ }
31001
33741
  function candidateSummaryLine(summary) {
31002
33742
  return `${String(summary.pairs)} pairs; evidence ${String(summary.evidencePairs)}/${String(summary.pairs)} (${percent2(summary.evidenceCoveragePercent)}); optimized ${String(summary.optimizedBetter)}, baseline ${String(summary.baselineBetter)}, equal ${String(summary.equivalent)}, inconclusive ${String(summary.inconclusive)}, incomparable ${String(summary.incomparable)}`;
31003
33743
  }
@@ -31015,11 +33755,12 @@ function candidateTimingLine(summary) {
31015
33755
  }
31016
33756
  function entryLine(entry) {
31017
33757
  const local = entry.localTokenSavingPercent === null ? "" : `; local delta ${percent2(entry.localTokenSavingPercent)}`;
33758
+ const ccr = entry.ccrUsage?.status === "comparable" && entry.ccrUsage.totalTokenDelta !== null ? `; CCR ${signedCount(entry.ccrUsage.totalTokenDelta)} tokens` : "";
31018
33759
  if (!("context" in entry)) {
31019
- return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}`;
33760
+ return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}${ccr}`;
31020
33761
  }
31021
33762
  const contextCounts = entry.context.baseline === null || entry.context.optimized === null ? "" : ` ${String(entry.context.baseline.effectiveStaticMcpToolCount)}\u2192${String(entry.context.optimized.effectiveStaticMcpToolCount)} static tools`;
31022
- return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}; context ${entry.context.verdict}${contextCounts}`;
33763
+ return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}${ccr}; context ${entry.context.verdict}${contextCounts}`;
31023
33764
  }
31024
33765
  function renderCampaign(lines, campaign) {
31025
33766
  lines.push("", "Candidate campaign \u2014 experimental");
@@ -31077,6 +33818,7 @@ function renderBenchmarkMatrixReport(report, _context) {
31077
33818
  const local = localLine(summary);
31078
33819
  if (local !== null)
31079
33820
  lines.push(...wrap(local, 4));
33821
+ lines.push(...ccrUsageLines(summary, 4));
31080
33822
  }
31081
33823
  lines.push("", "Overall");
31082
33824
  lines.push(...wrap(summaryLine(report.overall), 2));
@@ -31086,6 +33828,7 @@ function renderBenchmarkMatrixReport(report, _context) {
31086
33828
  const overallLocal = localLine(report.overall);
31087
33829
  if (overallLocal !== null)
31088
33830
  lines.push(...wrap(overallLocal, 2));
33831
+ lines.push(...ccrUsageLines(report.overall, 2));
31089
33832
  if (report.candidateEvidence !== void 0 && report.campaign === void 0) {
31090
33833
  lines.push("", "Candidate evidence \u2014 experimental");
31091
33834
  for (const candidate of report.candidateEvidence) {
@@ -31778,14 +34521,14 @@ function renderMetricsReport(report, _context) {
31778
34521
  if (report.errorBreakdown.length > 0) {
31779
34522
  lines.push("");
31780
34523
  lines.push("Errors by code");
31781
- for (const error of report.errorBreakdown) {
31782
- lines.push(...wrap(error.code, 2));
34524
+ for (const error2 of report.errorBreakdown) {
34525
+ lines.push(...wrap(error2.code, 2));
31783
34526
  const scope = [];
31784
- if (error.providerIds.length > 0)
31785
- scope.push(`providers ${error.providerIds.join(", ")}`);
31786
- if (error.harnesses.length > 0)
31787
- scope.push(`harnesses ${error.harnesses.join(", ")}`);
31788
- lines.push(...wrap(`${formatCount(error.count)} operation${error.count === 1 ? "" : "s"}` + (scope.length > 0 ? ` - ${scope.join(" - ")}` : ""), 4));
34527
+ if (error2.providerIds.length > 0)
34528
+ scope.push(`providers ${error2.providerIds.join(", ")}`);
34529
+ if (error2.harnesses.length > 0)
34530
+ scope.push(`harnesses ${error2.harnesses.join(", ")}`);
34531
+ lines.push(...wrap(`${formatCount(error2.count)} operation${error2.count === 1 ? "" : "s"}` + (scope.length > 0 ? ` - ${scope.join(" - ")}` : ""), 4));
31789
34532
  }
31790
34533
  }
31791
34534
  return document(lines);
@@ -32128,6 +34871,63 @@ var init_stack_review2 = __esm({
32128
34871
  }
32129
34872
  });
32130
34873
 
34874
+ // apps/cli/dist/src/render/smart-routing.js
34875
+ function renderSmartRoutingReport(report) {
34876
+ if (report.kind === "ccr-script")
34877
+ return `${report.script}
34878
+ `;
34879
+ if (report.kind === "ccr-configuration") {
34880
+ return [
34881
+ `CCR ${report.action}: ${report.state}`,
34882
+ `Harness: ${report.harnessId}`,
34883
+ `Mode: ${report.mode}`,
34884
+ `CCR version: ${report.ccrVersion}`,
34885
+ `Gateway: ${report.gatewayState}`,
34886
+ `Rule: ${report.ruleId}`,
34887
+ `Script: ${report.scriptPath}`,
34888
+ `Management endpoint: ${report.managementEndpoint}`,
34889
+ ...report.profileId === void 0 || report.profileId === null ? [] : [`CCR profile: ${report.profileId}`],
34890
+ ...report.launchCommand === void 0 || report.launchCommand === null ? [] : [`Launch: ${report.launchCommand}`]
34891
+ ].join("\n");
34892
+ }
34893
+ if (report.kind === "ccr-lifecycle") {
34894
+ return [
34895
+ `CCR ${report.action}: ${report.state}`,
34896
+ `Version: ${report.version}`,
34897
+ `Package: ${report.packagePath}`,
34898
+ `CLI: ${report.executablePath}`,
34899
+ `Management endpoint: ${report.managementEndpoint}`
34900
+ ].join("\n");
34901
+ }
34902
+ const { metrics } = report;
34903
+ const harnesses = Object.entries(metrics.byHarness).filter(([, count]) => count > 0).map(([name2, count]) => `${name2} ${String(count)}`).join(", ") || "none";
34904
+ const tiers = Object.entries(metrics.byTier).filter(([, count]) => count > 0).map(([name2, count]) => `${name2} ${String(count)}`).join(", ") || "none";
34905
+ const modes = Object.entries(metrics.byMode).filter(([, count]) => count > 0).map(([name2, count]) => `${name2} ${String(count)}`).join(", ") || "none";
34906
+ const lines = [
34907
+ "Smart Model Routing decisions",
34908
+ `Window: ${report.since} to ${report.until}`,
34909
+ `Retained decisions: ${String(metrics.retainedDecisionCount)}`,
34910
+ `By harness: ${harnesses}`,
34911
+ `By mode: ${modes}`,
34912
+ `By tier: ${tiers}`,
34913
+ `CCR route changes requested: ${String(metrics.routeMutationRequestCount)}`,
34914
+ `Malformed records: ${String(metrics.malformedRecordCount)}`,
34915
+ `Pruned records: ${String(metrics.prunedRecordCount)}`,
34916
+ "Model savings: not measured",
34917
+ `Cleanup: token-harness routing --route-metrics --prune (keeps ${String(metrics.retentionLimit)} newest records)`
34918
+ ];
34919
+ if (report.ccrUsage !== void 0) {
34920
+ const models = report.ccrUsage.byModel.map((item) => item.model).join(", ") || "none";
34921
+ lines.push(`CCR observed requests: ${String(report.ccrUsage.requestCount)} across ${String(report.ccrUsage.observedSessionCount)}/${String(report.ccrUsage.sessionCount)} sessions (${report.ccrUsage.status})`, `CCR reported tokens: ${String(report.ccrUsage.totalTokens)} total, ${String(report.ccrUsage.inputTokens)} input, ${String(report.ccrUsage.outputTokens)} output`, `CCR logged models: ${models}`, `CCR recorded cost: ${report.ccrUsage.recordedCostUsd === null ? "unavailable" : report.ccrUsage.recordedCostUsd.toFixed(6) + " USD (provider estimate)"}`, "CCR usage is observed request telemetry, not subscription quota or measured savings");
34922
+ }
34923
+ return lines.join("\n");
34924
+ }
34925
+ var init_smart_routing3 = __esm({
34926
+ "apps/cli/dist/src/render/smart-routing.js"() {
34927
+ "use strict";
34928
+ }
34929
+ });
34930
+
32131
34931
  // apps/cli/dist/src/render/update.js
32132
34932
  function widthOf(values, floor) {
32133
34933
  return Math.max(floor, ...values.map((value3) => value3.length + 2));
@@ -32668,6 +35468,8 @@ function renderHuman(result6, context) {
32668
35468
  return plain(renderSimpleMcp(data));
32669
35469
  case "metrics":
32670
35470
  return plain(renderSimpleMetrics(data));
35471
+ case "routing":
35472
+ return plain(renderSmartRoutingReport(data));
32671
35473
  case "optimize":
32672
35474
  return plain(renderSimpleOptimize(data));
32673
35475
  case "plan":
@@ -32721,6 +35523,8 @@ function renderHuman(result6, context) {
32721
35523
  return plain(renderVerifyReport(data, context));
32722
35524
  case "metrics":
32723
35525
  return plain(renderMetricsReport(data, context));
35526
+ case "routing":
35527
+ return plain(renderSmartRoutingReport(data));
32724
35528
  case "update":
32725
35529
  return plain(renderUpdateReport(data, context));
32726
35530
  default:
@@ -32744,6 +35548,7 @@ var init_render = __esm({
32744
35548
  init_plan3();
32745
35549
  init_status2();
32746
35550
  init_stack_review2();
35551
+ init_smart_routing3();
32747
35552
  init_update2();
32748
35553
  init_verify2();
32749
35554
  init_simple();
@@ -32791,6 +35596,7 @@ Advanced commands
32791
35596
  apply Apply a reviewed plan
32792
35597
  verify Check that configured integrations work
32793
35598
  metrics Show measured savings
35599
+ routing Install/configure CCR or inspect routing decisions
32794
35600
  update Check or update installed providers
32795
35601
  rollback Restore the previous configuration
32796
35602
  uninstall Remove only configuration Token Harness owns
@@ -32803,6 +35609,14 @@ Useful flags
32803
35609
  --yes Confirm a configuration-changing operation
32804
35610
  --harness <id> Restrict the operation to one harness
32805
35611
  --provider <id> Restrict the operation to one provider
35612
+ --script Export a CCR script rule (routing command)
35613
+ --route-metrics Show local routing decision telemetry
35614
+ --route-mode <mode> shadow by default; conservative requires opt-in
35615
+ --prune Keep only the 200 newest routing decision records
35616
+ --configure-ccr Preview managed CCR setup; --yes applies one step
35617
+ --update-ccr Preview update of the managed CCR CLI
35618
+ --rollback-ccr Preview rollback; --yes removes owned rule/profile
35619
+ --ccr-usage Read CCR model/token aggregates for local sessions
32806
35620
  --project <dir> Use that project instead of the current directory
32807
35621
  --help Show help for a command
32808
35622
  --version Print the version
@@ -33065,6 +35879,36 @@ Figures are never merged across measurement classes or units: tokens are not
33065
35879
  added to characters, and an estimate is not added to an exact figure. A
33066
35880
  counterfactual reduction is reported on its own line and never as a saving.
33067
35881
  Exits 0 whatever the figures say \u2014 an empty report is a fact, not a failure.`,
35882
+ routing: `token-harness routing \u2014 inspect or export Smart Model Routing
35883
+
35884
+ Usage
35885
+ token-harness routing --script --harness <claude|codex>
35886
+ [--route-mode <shadow|conservative>] [--json]
35887
+ token-harness routing --configure-ccr --harness <claude|codex> [--yes]
35888
+ token-harness routing --update-ccr [--yes]
35889
+ token-harness routing --rollback-ccr --harness <claude|codex> [--yes]
35890
+ token-harness routing --route-metrics [--since <duration|date>]
35891
+ [--until <date>] [--harness <claude|codex>]
35892
+ [--ccr-usage] [--prune] [--json]
35893
+
35894
+ Script export defaults to shadow mode. Add the generated script as a Node.js script rule in CCR;
35895
+ it records local, prompt-free decisions and returns no route rewrite in shadow mode. Conservative
35896
+ mode is explicit and only proposes a configured simple model for high-confidence, low-risk requests.
35897
+ It leaves requests with tool schemas unchanged unless the CCR process explicitly sets
35898
+ TOKEN_HARNESS_ROUTING_ALLOW_TOOLS=true. No API call or local model is used to classify.
35899
+
35900
+ CCR must run on this machine as the same user for the local telemetry path to be writable. A failed
35901
+ telemetry write never blocks the agent request. Decision records contain no prompt or credentials.
35902
+ Routing choices are not measured token savings; this command keeps them separate from \`metrics\`.
35903
+ Use --prune to remove all but the 200 newest decision records.
35904
+
35905
+ When no authenticated local CCR service is present, configure first previews an npm install/start
35906
+ of CCR 3.1.1 in Token Harness' protected local state; after approving that step, run configure again
35907
+ to preview the routing rule and optional CCR-only CLI profile. A Token Harness-owned service keeps
35908
+ its Web RPC token in a private local file; existing services can use CCR_WEB_AUTH_TOKEN and
35909
+ optionally CCR_WEB_URL. --update-ccr only updates a Token Harness-owned CLI to the reviewed pin.
35910
+ Rollback removes only the exact rule, profile, and script Token Harness owns. CCR usage is observed
35911
+ request telemetry, not subscription quota or measured savings.`,
33068
35912
  uninstall: `token-harness uninstall \u2014 remove what Token Harness owns
33069
35913
 
33070
35914
  Usage
@@ -33225,8 +36069,8 @@ function emit(result6, options, renderContext, json) {
33225
36069
  if (json) {
33226
36070
  try {
33227
36071
  options.streams.out(serializeEnvelope(toEnvelope(result6, toolVersion)));
33228
- } catch (error) {
33229
- options.streams.err(`internal-error envelope-serialization-failed: ${error instanceof Error ? error.message : String(error)}
36072
+ } catch (error2) {
36073
+ options.streams.err(`internal-error envelope-serialization-failed: ${error2 instanceof Error ? error2.message : String(error2)}
33230
36074
  `);
33231
36075
  return EXIT_CODES["internal-error"];
33232
36076
  }
@@ -33345,6 +36189,16 @@ async function run(options) {
33345
36189
  tasksRemaining: invocation.options.tasksLeft,
33346
36190
  contextSnapshotPath: invocation.options.contextSnapshot,
33347
36191
  nativePolicy: invocation.options.nativePolicy,
36192
+ routingScript: invocation.options.routingScript,
36193
+ routingMetrics: invocation.options.routingMetrics,
36194
+ routingMode: invocation.options.routingMode,
36195
+ routingPrune: invocation.options.routingPrune,
36196
+ routingCcrConfigure: invocation.options.routingCcrConfigure,
36197
+ routingCcrRollback: invocation.options.routingCcrRollback,
36198
+ routingCcrUpdate: invocation.options.routingCcrUpdate,
36199
+ routingCcrUsage: invocation.options.routingCcrUsage,
36200
+ env: options.env ?? {},
36201
+ ...options.ccrFetch === void 0 ? {} : { ccrFetch: options.ccrFetch },
33348
36202
  agentSkill: invocation.options.agentSkill,
33349
36203
  since: invocation.options.since,
33350
36204
  until: invocation.options.until,
@@ -33368,7 +36222,7 @@ async function run(options) {
33368
36222
  let result6;
33369
36223
  try {
33370
36224
  result6 = await table[invocation.command](context);
33371
- } catch (error) {
36225
+ } catch (error2) {
33372
36226
  result6 = commandResult({
33373
36227
  command: invocation.command,
33374
36228
  exitCode: EXIT_CODES["internal-error"],
@@ -33376,7 +36230,7 @@ async function run(options) {
33376
36230
  diagnostic({
33377
36231
  severity: "error",
33378
36232
  code: "internal-error",
33379
- message: `The command \`${invocation.command}\` failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`,
36233
+ message: `The command \`${invocation.command}\` failed unexpectedly: ${error2 instanceof Error ? error2.message : String(error2)}`,
33380
36234
  remediation: "Report this with the command you ran at https://github.com/giuliastro/TokenHarness/issues"
33381
36235
  })
33382
36236
  ]
@@ -33403,6 +36257,7 @@ var init_run = __esm({
33403
36257
  init_optimize();
33404
36258
  init_plan2();
33405
36259
  init_rollback();
36260
+ init_smart_routing2();
33406
36261
  init_setup2();
33407
36262
  init_status();
33408
36263
  init_stack_review();
@@ -33426,6 +36281,7 @@ var init_run = __esm({
33426
36281
  optimize: runOptimize,
33427
36282
  plan: runPlan,
33428
36283
  rollback: runRollback,
36284
+ routing: runSmartRouting,
33429
36285
  setup: runSetup,
33430
36286
  status: runStatus,
33431
36287
  "stack-review": runStackReview,
@@ -39850,9 +42706,9 @@ function createGuideHandler(input) {
39850
42706
  return;
39851
42707
  }
39852
42708
  send(404, '{"error":"Not found"}');
39853
- } catch (error) {
39854
- send(error instanceof GuideError ? error.status : 500, JSON.stringify({
39855
- error: error instanceof GuideError ? error.message : "The operation could not finish. No automatic retry was made. Refresh and check the current state."
42709
+ } catch (error2) {
42710
+ send(error2 instanceof GuideError ? error2.status : 500, JSON.stringify({
42711
+ error: error2 instanceof GuideError ? error2.message : "The operation could not finish. No automatic retry was made. Refresh and check the current state."
39856
42712
  }));
39857
42713
  }
39858
42714
  };
@@ -39879,7 +42735,7 @@ var init_guided_http = __esm({
39879
42735
  });
39880
42736
 
39881
42737
  // apps/cli/dist/src/commands/rtk-hook-proxy.js
39882
- function isRecord5(value3) {
42738
+ function isRecord7(value3) {
39883
42739
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
39884
42740
  }
39885
42741
  function shellQuote(value3) {
@@ -39891,7 +42747,7 @@ function powershellQuote(value3) {
39891
42747
  function toolNameFromInput(input, harness) {
39892
42748
  try {
39893
42749
  const parsed = JSON.parse(input);
39894
- if (!isRecord5(parsed))
42750
+ if (!isRecord7(parsed))
39895
42751
  return null;
39896
42752
  const name2 = parsed["tool_name"] ?? parsed["toolName"];
39897
42753
  if (typeof name2 === "string")
@@ -39919,13 +42775,13 @@ function attributeRtkHookResponse(stdout, input, databasePath, harness) {
39919
42775
  } catch {
39920
42776
  return stdout;
39921
42777
  }
39922
- if (!isRecord5(response))
42778
+ if (!isRecord7(response))
39923
42779
  return stdout;
39924
42780
  const hookOutput = response["hookSpecificOutput"];
39925
- if (!isRecord5(hookOutput))
42781
+ if (!isRecord7(hookOutput))
39926
42782
  return stdout;
39927
42783
  const updatedInput = hookOutput["updatedInput"];
39928
- if (!isRecord5(updatedInput) || typeof updatedInput["command"] !== "string")
42784
+ if (!isRecord7(updatedInput) || typeof updatedInput["command"] !== "string")
39929
42785
  return stdout;
39930
42786
  const attributed = withDatabaseEnvironment(updatedInput["command"], databasePath, toolNameFromInput(input, harness));
39931
42787
  if (attributed === null)
@@ -39977,7 +42833,7 @@ __export(main_exports, {
39977
42833
  });
39978
42834
  import process5 from "node:process";
39979
42835
  import { createServer } from "node:http";
39980
- import { randomBytes as randomBytes2 } from "node:crypto";
42836
+ import { randomBytes as randomBytes3 } from "node:crypto";
39981
42837
  async function runAsDatabaseReader(argv2) {
39982
42838
  if (argv2[0] !== SQLITE_CHILD_FLAG)
39983
42839
  return false;
@@ -40190,8 +43046,8 @@ async function runUi(options, baseOptions) {
40190
43046
  let initial;
40191
43047
  try {
40192
43048
  initial = await collectDashboard(baseOptions);
40193
- } catch (error) {
40194
- const message = error instanceof Error ? error.message : String(error);
43049
+ } catch (error2) {
43050
+ const message = error2 instanceof Error ? error2.message : String(error2);
40195
43051
  if (options.json) {
40196
43052
  process5.stdout.write(serializeEnvelope(toEnvelope(commandResult({
40197
43053
  command: "ui",
@@ -40265,8 +43121,8 @@ async function runUi(options, baseOptions) {
40265
43121
  server.once("error", reject);
40266
43122
  server.listen(options.port, "127.0.0.1", () => resolve());
40267
43123
  });
40268
- } catch (error) {
40269
- process5.stderr.write(`Token Harness dashboard could not listen locally: ${error instanceof Error ? error.message : String(error)}
43124
+ } catch (error2) {
43125
+ process5.stderr.write(`Token Harness dashboard could not listen locally: ${error2 instanceof Error ? error2.message : String(error2)}
40270
43126
  `);
40271
43127
  return EXIT_CODES["internal-error"];
40272
43128
  }
@@ -40293,7 +43149,7 @@ async function runGuidedUi(options, base) {
40293
43149
  }
40294
43150
  return result6;
40295
43151
  };
40296
- const service = new GuideService(guideCall, () => Date.now(), () => randomBytes2(32).toString("hex"), async (harness) => {
43152
+ const service = new GuideService(guideCall, () => Date.now(), () => randomBytes3(32).toString("hex"), async (harness) => {
40297
43153
  if (base.adapters === null || base.adapters === void 0) {
40298
43154
  return {
40299
43155
  state: "unavailable",
@@ -40308,7 +43164,7 @@ async function runGuidedUi(options, base) {
40308
43164
  harness
40309
43165
  });
40310
43166
  });
40311
- const token = randomBytes2(32).toString("hex");
43167
+ const token = randomBytes3(32).toString("hex");
40312
43168
  let authority = "";
40313
43169
  const server = createServer(createGuideHandler({
40314
43170
  service,