token-harness 0.1.20 → 0.1.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/token-harness.mjs CHANGED
@@ -656,65 +656,6 @@ 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
- }
718
659
  function parseLocalSessionSnapshot(value3) {
719
660
  const row2 = record(value3);
720
661
  if (row2 === null)
@@ -901,9 +842,7 @@ function parseTaskBenchmarkReceipt(value3) {
901
842
  const contextAtStart = hasContextAtStart ? parseTaskBenchmarkContextSnapshot(row2["contextAtStart"]) : void 0;
902
843
  const hasContextAtFinish = Object.hasOwn(row2, "contextAtFinish");
903
844
  const contextAtFinish = hasContextAtFinish ? parseTaskBenchmarkContextSnapshot(row2["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) {
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) {
907
846
  return {
908
847
  ok: false,
909
848
  reason: "invalid-shape",
@@ -929,8 +868,7 @@ function parseTaskBenchmarkReceipt(value3) {
929
868
  outcome: outcome2,
930
869
  ...hasContextAtStart ? { contextAtStart: contextAtStart ?? null } : {},
931
870
  ...hasContextAtFinish ? { contextAtFinish: contextAtFinish ?? null } : {},
932
- ...hasBoundaryPolicy ? { policyAtFinish: policyAtFinish ?? null } : {},
933
- ...hasCcrUsage ? { ccrUsage: ccrUsage ?? null } : {}
871
+ ...hasBoundaryPolicy ? { policyAtFinish: policyAtFinish ?? null } : {}
934
872
  }
935
873
  };
936
874
  }
@@ -952,7 +890,6 @@ function completeTaskBenchmarkCapture(capture, input) {
952
890
  ...capture.contextAtStart !== void 0 ? { contextAtStart: capture.contextAtStart } : {},
953
891
  ...input.contextAtFinish !== void 0 ? { contextAtFinish: input.contextAtFinish } : {},
954
892
  ...input.policyAtFinish !== void 0 ? { policyAtFinish: input.policyAtFinish } : {},
955
- ...input.ccrUsage !== void 0 ? { ccrUsage: input.ccrUsage } : {},
956
893
  outcome: {
957
894
  qualityGate: input.qualityGate,
958
895
  attempts: input.attempts,
@@ -1107,48 +1044,8 @@ function compareTaskBenchmarkReceiptsCore(baseline, optimized) {
1107
1044
  "quality matched but no efficiency evidence separated the receipts"
1108
1045
  ]);
1109
1046
  }
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
1047
  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
- };
1048
+ return compareTaskBenchmarkReceiptsCore(baseline, optimized);
1152
1049
  }
1153
1050
  function roundedPercent(numerator, denominator) {
1154
1051
  if (denominator <= 0)
@@ -1159,14 +1056,6 @@ function summarizeMatrixEntries(entries, taskClass) {
1159
1056
  const local = entries.filter((entry) => entry.localTokenSavingPercent !== null && entry.baselineLocalTokens !== null && entry.optimizedLocalTokens !== null);
1160
1057
  const baselineLocalTokens = local.length === 0 ? null : local.reduce((total, entry) => total + (entry.baselineLocalTokens ?? 0), 0);
1161
1058
  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);
1170
1059
  return {
1171
1060
  taskClass,
1172
1061
  pairs: entries.length,
@@ -1181,24 +1070,7 @@ function summarizeMatrixEntries(entries, taskClass) {
1181
1070
  localComparablePairs: local.length,
1182
1071
  baselineLocalTokens,
1183
1072
  optimizedLocalTokens,
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
- } : {}
1073
+ localTokenSavingPercent: baselineLocalTokens === null || optimizedLocalTokens === null ? null : roundedPercent(baselineLocalTokens - optimizedLocalTokens, baselineLocalTokens)
1202
1074
  };
1203
1075
  }
1204
1076
  function buildTaskBenchmarkMatrix(pairs, selection = {
@@ -1224,8 +1096,7 @@ function buildTaskBenchmarkMatrix(pairs, selection = {
1224
1096
  baselineLocalTokens,
1225
1097
  optimizedLocalTokens,
1226
1098
  localTokenSavingPercent: !bothQualityPassed || baselineLocalTokens === null || optimizedLocalTokens === null ? null : roundedPercent(baselineLocalTokens - optimizedLocalTokens, baselineLocalTokens),
1227
- quota: comparison.quota,
1228
- ...comparison.ccrUsage === void 0 ? {} : { ccrUsage: comparison.ccrUsage }
1099
+ quota: comparison.quota
1229
1100
  };
1230
1101
  }).sort((left, right) => TASK_CLASS_ORDER.indexOf(left.taskClass) - TASK_CLASS_ORDER.indexOf(right.taskClass) || left.benchmarkId.localeCompare(right.benchmarkId));
1231
1102
  const byTaskClass = TASK_CLASS_ORDER.map((taskClass) => ({
@@ -3922,280 +3793,6 @@ var init_model_learning = __esm({
3922
3793
  }
3923
3794
  });
3924
3795
 
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
-
4199
3796
  // packages/core/dist/src/domain/action-conflicts.js
4200
3797
  function markerAction(action) {
4201
3798
  return action.kind === "patch-marker-block";
@@ -7552,8 +7149,8 @@ function parseJsonDocumentText(text3) {
7552
7149
  document: JSON.parse(body),
7553
7150
  formatting: detectJsonFormatting(text3)
7554
7151
  };
7555
- } catch (error2) {
7556
- return { state: "malformed", reason: error2 instanceof Error ? error2.message : String(error2) };
7152
+ } catch (error) {
7153
+ return { state: "malformed", reason: error instanceof Error ? error.message : String(error) };
7557
7154
  }
7558
7155
  }
7559
7156
  function clone(value3) {
@@ -8924,12 +8521,12 @@ async function applyCodexConfigBatchWrite(action, context) {
8924
8521
  }
8925
8522
  }
8926
8523
  const response = messages.find((message) => typeof message === "object" && message !== null && !Array.isArray(message) && (message["id"] === CODEX_CONFIG_WRITE_REQUEST_ID || message["id"] === 2));
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(" ");
8524
+ const error = response !== void 0 && typeof response["error"] === "object" && response["error"] !== null && !Array.isArray(response["error"]) ? response["error"] : null;
8525
+ const errorText = error === null ? "" : [error["message"], error["data"]].map((value3) => typeof value3 === "string" ? value3 : JSON.stringify(value3)).filter((value3) => value3 !== void 0 && value3 !== "").join(" ");
8929
8526
  if (/configVersionConflict/i.test(errorText)) {
8930
8527
  return drift(action, action.path, "Codex reports that config.toml changed after this plan observed its config version");
8931
8528
  }
8932
- if (result6.exitCode !== 0 || response === void 0 || error2 !== null || !("result" in response)) {
8529
+ if (result6.exitCode !== 0 || response === void 0 || error !== null || !("result" in response)) {
8933
8530
  return outcome(action, "failed", {
8934
8531
  snapshots: [snapshot],
8935
8532
  diagnostics: [
@@ -9433,8 +9030,8 @@ function parseJsoncDocumentText(text3) {
9433
9030
  state: "parsed",
9434
9031
  document: JSON.parse(withoutTrailingCommas(withoutComments(text3)))
9435
9032
  };
9436
- } catch (error2) {
9437
- return { state: "malformed", reason: error2 instanceof Error ? error2.message : String(error2) };
9033
+ } catch (error) {
9034
+ return { state: "malformed", reason: error instanceof Error ? error.message : String(error) };
9438
9035
  }
9439
9036
  }
9440
9037
  var init_jsonc = __esm({
@@ -9778,8 +9375,8 @@ async function executeTransaction(request) {
9778
9375
  let restoreError = null;
9779
9376
  try {
9780
9377
  await request.snapshots.restoreAll(snapshots);
9781
- } catch (error2) {
9782
- restoreError = error2 instanceof Error ? error2.message : String(error2);
9378
+ } catch (error) {
9379
+ restoreError = error instanceof Error ? error.message : String(error);
9783
9380
  }
9784
9381
  const unrestored = await verifyRestoration(request.fs, snapshots);
9785
9382
  const packageDiagnostics = await restorePackageInventories(applied, request.runner ?? null, request.projectRoot);
@@ -9806,7 +9403,7 @@ async function executeTransaction(request) {
9806
9403
  let result6;
9807
9404
  try {
9808
9405
  result6 = await applyAction(action, context);
9809
- } catch (error2) {
9406
+ } catch (error) {
9810
9407
  result6 = {
9811
9408
  actionId: action.id,
9812
9409
  kind: action.kind,
@@ -9818,7 +9415,7 @@ async function executeTransaction(request) {
9818
9415
  diagnostic({
9819
9416
  severity: "error",
9820
9417
  code: "action-failed",
9821
- message: `The action ${action.id} failed: ${error2 instanceof Error ? error2.message : String(error2)}`,
9418
+ message: `The action ${action.id} failed: ${error instanceof Error ? error.message : String(error)}`,
9822
9419
  path: action.affectedPaths[0] ?? null,
9823
9420
  remediation: "Check the path is writable, then run the command again"
9824
9421
  })
@@ -9913,8 +9510,8 @@ async function rollbackTransaction(request) {
9913
9510
  let restoreError = null;
9914
9511
  try {
9915
9512
  await request.snapshots.restoreAll(snapshots);
9916
- } catch (error2) {
9917
- restoreError = error2 instanceof Error ? error2.message : String(error2);
9513
+ } catch (error) {
9514
+ restoreError = error instanceof Error ? error.message : String(error);
9918
9515
  }
9919
9516
  const unrestored = await verifyRestoration(request.fs, snapshots);
9920
9517
  const packageDiagnostics = await restorePackageInventories(journal.entries, request.runner ?? null, request.cwd ?? journal.projectRoot);
@@ -10007,8 +9604,6 @@ var init_src = __esm({
10007
9604
  init_outcome_learning();
10008
9605
  init_verbosity_learning();
10009
9606
  init_model_learning();
10010
- init_smart_routing();
10011
- init_smart_routing_telemetry();
10012
9607
  init_action_conflicts();
10013
9608
  init_capabilities();
10014
9609
  init_compatibility_rows();
@@ -10068,7 +9663,7 @@ var TOOL_VERSION;
10068
9663
  var init_version2 = __esm({
10069
9664
  "apps/cli/dist/src/version.js"() {
10070
9665
  "use strict";
10071
- TOOL_VERSION = "0.1.20";
9666
+ TOOL_VERSION = "0.1.22";
10072
9667
  }
10073
9668
  });
10074
9669
 
@@ -10667,19 +10262,19 @@ var init_node_filesystem = __esm({
10667
10262
  // reporting them would invite a caller to treat them as one.
10668
10263
  mode: this.nativeWindows ? null : octal(info.mode)
10669
10264
  };
10670
- } catch (error2) {
10671
- if (error2.code === "ENOENT")
10265
+ } catch (error) {
10266
+ if (error.code === "ENOENT")
10672
10267
  return null;
10673
- throw error2;
10268
+ throw error;
10674
10269
  }
10675
10270
  }
10676
10271
  async canonicalPath(path) {
10677
10272
  try {
10678
10273
  return await realpath(path);
10679
- } catch (error2) {
10680
- if (error2.code === "ENOENT")
10274
+ } catch (error) {
10275
+ if (error.code === "ENOENT")
10681
10276
  return null;
10682
- throw error2;
10277
+ throw error;
10683
10278
  }
10684
10279
  }
10685
10280
  async readFile(path) {
@@ -10703,10 +10298,10 @@ var init_node_filesystem = __esm({
10703
10298
  async readDirectory(path) {
10704
10299
  try {
10705
10300
  return (await readdir(path)).sort();
10706
- } catch (error2) {
10707
- if (error2.code === "ENOENT")
10301
+ } catch (error) {
10302
+ if (error.code === "ENOENT")
10708
10303
  return [];
10709
- throw error2;
10304
+ throw error;
10710
10305
  }
10711
10306
  }
10712
10307
  };
@@ -10759,7 +10354,7 @@ function rtkReleaseAssetForPlatform(platform) {
10759
10354
  }
10760
10355
  return null;
10761
10356
  }
10762
- function isRecord2(value3) {
10357
+ function isRecord(value3) {
10763
10358
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
10764
10359
  }
10765
10360
  function integer(value3) {
@@ -10853,7 +10448,7 @@ async function fetchBounded(input) {
10853
10448
  }
10854
10449
  }
10855
10450
  function parseReleaseMetadata(value3, version3, selection) {
10856
- if (!isRecord2(value3))
10451
+ if (!isRecord(value3))
10857
10452
  return { status: "invalid", message: "release metadata is not an object" };
10858
10453
  const tag = `v${version3}`;
10859
10454
  if (value3["tag_name"] !== tag || value3["draft"] !== false || value3["prerelease"] !== false) {
@@ -10865,7 +10460,7 @@ function parseReleaseMetadata(value3, version3, selection) {
10865
10460
  const assets = value3["assets"];
10866
10461
  if (!Array.isArray(assets))
10867
10462
  return { status: "invalid", message: "release metadata has no asset list" };
10868
- const matching = assets.filter((asset2) => isRecord2(asset2) && asset2["name"] === selection.name);
10463
+ const matching = assets.filter((asset2) => isRecord(asset2) && asset2["name"] === selection.name);
10869
10464
  if (matching.length !== 1) {
10870
10465
  return {
10871
10466
  status: "invalid",
@@ -10873,7 +10468,7 @@ function parseReleaseMetadata(value3, version3, selection) {
10873
10468
  };
10874
10469
  }
10875
10470
  const asset = matching[0];
10876
- if (!isRecord2(asset))
10471
+ if (!isRecord(asset))
10877
10472
  return { status: "invalid", message: "release asset is malformed" };
10878
10473
  const digest = normalizeSha256(asset["digest"]);
10879
10474
  const size = integer(asset["size"]);
@@ -11152,19 +10747,19 @@ var init_rtk_release = __esm({
11152
10747
  maximumBytes: MAX_METADATA_BYTES,
11153
10748
  kind: "metadata"
11154
10749
  });
11155
- } catch (error2) {
10750
+ } catch (error) {
11156
10751
  return {
11157
10752
  status: "unavailable",
11158
- message: `RTK release metadata could not be read: ${error2 instanceof Error ? error2.message : String(error2)}`
10753
+ message: `RTK release metadata could not be read: ${error instanceof Error ? error.message : String(error)}`
11159
10754
  };
11160
10755
  }
11161
10756
  try {
11162
10757
  const value3 = JSON.parse(new TextDecoder().decode(bytes));
11163
10758
  return parseReleaseMetadata(value3, version3, selection);
11164
- } catch (error2) {
10759
+ } catch (error) {
11165
10760
  return {
11166
10761
  status: "invalid",
11167
- message: `RTK release metadata is not valid JSON: ${error2 instanceof Error ? error2.message : String(error2)}`
10762
+ message: `RTK release metadata is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
11168
10763
  };
11169
10764
  }
11170
10765
  }
@@ -11230,12 +10825,12 @@ ${result6.stderr}`, version3);
11230
10825
  await rename(handle.targetPath, displaced);
11231
10826
  try {
11232
10827
  await rename(stage, handle.targetPath);
11233
- } catch (error2) {
10828
+ } catch (error) {
11234
10829
  await rename(displaced, handle.targetPath).catch(() => void 0);
11235
10830
  await rm2(stage, { force: true }).catch(() => void 0);
11236
10831
  return {
11237
10832
  status: "dirty",
11238
- message: `RTK rollback could not replace the executable: ${error2 instanceof Error ? error2.message : String(error2)}`
10833
+ message: `RTK rollback could not replace the executable: ${error instanceof Error ? error.message : String(error)}`
11239
10834
  };
11240
10835
  }
11241
10836
  await rm2(displaced, { force: true });
@@ -11256,10 +10851,10 @@ ${result6.stderr}`, version3);
11256
10851
  status: "rolled-back",
11257
10852
  message: "RTK previous executable bytes and version were restored and verified"
11258
10853
  };
11259
- } catch (error2) {
10854
+ } catch (error) {
11260
10855
  return {
11261
10856
  status: "dirty",
11262
- message: `RTK rollback failed: ${error2 instanceof Error ? error2.message : String(error2)}`
10857
+ message: `RTK rollback failed: ${error instanceof Error ? error.message : String(error)}`
11263
10858
  };
11264
10859
  }
11265
10860
  }
@@ -11298,11 +10893,11 @@ ${result6.stderr}`, version3);
11298
10893
  try {
11299
10894
  archive = await this.download(input.asset);
11300
10895
  replacement = input.asset.archiveFormat === "zip" ? extractRtkExeFromVerifiedZip(archive) : extractRtkBinaryFromVerifiedTarGz(archive);
11301
- } catch (error2) {
10896
+ } catch (error) {
11302
10897
  return {
11303
10898
  status: "failed",
11304
10899
  code: "rtk-release-artifact-invalid",
11305
- message: error2 instanceof Error ? error2.message : String(error2),
10900
+ message: error instanceof Error ? error.message : String(error),
11306
10901
  backupPath: null
11307
10902
  };
11308
10903
  }
@@ -11342,11 +10937,11 @@ ${result6.stderr}`, version3);
11342
10937
  await rename(input.targetPath, displaced);
11343
10938
  try {
11344
10939
  await rename(stage, input.targetPath);
11345
- } catch (error2) {
10940
+ } catch (error) {
11346
10941
  await rename(displaced, input.targetPath).catch(() => void 0);
11347
- throw error2;
10942
+ throw error;
11348
10943
  }
11349
- } catch (error2) {
10944
+ } catch (error) {
11350
10945
  await rm2(stage, { force: true }).catch(() => void 0);
11351
10946
  const live = await this.fs.stat(input.targetPath);
11352
10947
  if (live !== null && live.kind === "file" && digestBytes(await this.fs.readFile(input.targetPath)) === previousDigest) {
@@ -11354,14 +10949,14 @@ ${result6.stderr}`, version3);
11354
10949
  return {
11355
10950
  status: "rolled-back",
11356
10951
  code: "rtk-release-replacement-failed",
11357
- message: `RTK replacement failed before commit and the previous executable is intact: ${error2 instanceof Error ? error2.message : String(error2)}`,
10952
+ message: `RTK replacement failed before commit and the previous executable is intact: ${error instanceof Error ? error.message : String(error)}`,
11358
10953
  backupPath
11359
10954
  };
11360
10955
  }
11361
10956
  return {
11362
10957
  status: "dirty",
11363
10958
  code: "rtk-release-replacement-dirty",
11364
- message: `RTK replacement failed and exact restoration could not be verified: ${error2 instanceof Error ? error2.message : String(error2)}`,
10959
+ message: `RTK replacement failed and exact restoration could not be verified: ${error instanceof Error ? error.message : String(error)}`,
11365
10960
  backupPath
11366
10961
  };
11367
10962
  }
@@ -11428,7 +11023,7 @@ async function resolveAttributionSalt(fs, stateRoot) {
11428
11023
  try {
11429
11024
  await fs.writeFile(path, new TextEncoder().encode(`${salt}
11430
11025
  `), "0600");
11431
- } catch (error2) {
11026
+ } catch (error) {
11432
11027
  return {
11433
11028
  salt: null,
11434
11029
  diagnostics: [
@@ -11436,7 +11031,7 @@ async function resolveAttributionSalt(fs, stateRoot) {
11436
11031
  diagnostic({
11437
11032
  severity: "warning",
11438
11033
  code: "attribution-salt-unwritable",
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)}`,
11034
+ message: `The project attribution salt could not be stored, so metrics cannot be attributed to a project: ${error instanceof Error ? error.message : String(error)}`,
11440
11035
  path,
11441
11036
  remediation: "Check that the Token Harness state directory is writable"
11442
11037
  })
@@ -11472,9 +11067,9 @@ function toValue(value3) {
11472
11067
  return value3 ? 1 : 0;
11473
11068
  return null;
11474
11069
  }
11475
- function classify2(error2) {
11476
- const message = error2 instanceof Error ? error2.message : String(error2);
11477
- const code = error2?.code;
11070
+ function classify2(error) {
11071
+ const message = error instanceof Error ? error.message : String(error);
11072
+ const code = error?.code;
11478
11073
  if (code === "ERR_UNKNOWN_BUILTIN_MODULE" || /Cannot find module 'node:sqlite'/.test(message)) {
11479
11074
  return { failure: "driver-unavailable", detail: "this runtime has no node:sqlite" };
11480
11075
  }
@@ -11490,8 +11085,8 @@ async function readLocalDatabase(request) {
11490
11085
  let construct;
11491
11086
  try {
11492
11087
  ({ DatabaseSync: construct } = await import("node:sqlite"));
11493
- } catch (error2) {
11494
- return { rows: [], ...classify2(error2) };
11088
+ } catch (error) {
11089
+ return { rows: [], ...classify2(error) };
11495
11090
  }
11496
11091
  let database = null;
11497
11092
  try {
@@ -11505,8 +11100,8 @@ async function readLocalDatabase(request) {
11505
11100
  return mapped;
11506
11101
  });
11507
11102
  return { rows, failure: null, detail: null };
11508
- } catch (error2) {
11509
- return { rows: [], ...classify2(error2) };
11103
+ } catch (error) {
11104
+ return { rows: [], ...classify2(error) };
11510
11105
  } finally {
11511
11106
  try {
11512
11107
  database?.close();
@@ -12359,8 +11954,8 @@ var init_node_runner = __esm({
12359
11954
  killTimer = setTimeout(() => this.terminateTree(child.pid, onPosix, true), this.options.killGraceMs ?? DEFAULT_KILL_GRACE_MS);
12360
11955
  }, timeoutMs);
12361
11956
  }
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));
11957
+ child.on("error", (error) => {
11958
+ 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));
12364
11959
  });
12365
11960
  child.on("close", (code, signal) => {
12366
11961
  const durationMs = now() - started;
@@ -12651,12 +12246,12 @@ async function recordProjectTransferEvidence(input) {
12651
12246
  reason: "observed transfer experiment is missing its measured payload"
12652
12247
  };
12653
12248
  }
12654
- const receiptPath4 = input.fs.join(input.stateRoot, "benchmarks", input.benchmarkId, "transfer.json");
12655
- if (await input.fs.stat(receiptPath4) !== null) {
12249
+ const receiptPath3 = input.fs.join(input.stateRoot, "benchmarks", input.benchmarkId, "transfer.json");
12250
+ if (await input.fs.stat(receiptPath3) !== null) {
12656
12251
  return {
12657
12252
  status: "exists",
12658
12253
  receipt: null,
12659
- receiptPath: receiptPath4,
12254
+ receiptPath: receiptPath3,
12660
12255
  reason: "transfer evidence receipt already exists and is immutable"
12661
12256
  };
12662
12257
  }
@@ -12675,17 +12270,17 @@ async function recordProjectTransferEvidence(input) {
12675
12270
  taskClass: experiment.stay.taskClass
12676
12271
  });
12677
12272
  try {
12678
- await input.fs.writeFile(receiptPath4, new TextEncoder().encode(`${JSON.stringify(receipt, null, 2)}
12273
+ await input.fs.writeFile(receiptPath3, new TextEncoder().encode(`${JSON.stringify(receipt, null, 2)}
12679
12274
  `));
12680
12275
  } catch {
12681
12276
  return {
12682
12277
  status: "write-failed",
12683
12278
  receipt: null,
12684
- receiptPath: receiptPath4,
12279
+ receiptPath: receiptPath3,
12685
12280
  reason: "transfer evidence receipt could not be written"
12686
12281
  };
12687
12282
  }
12688
- return { status: "recorded", receipt, receiptPath: receiptPath4, reason: null };
12283
+ return { status: "recorded", receipt, receiptPath: receiptPath3, reason: null };
12689
12284
  }
12690
12285
  async function resolveLocalTransferContext(cwd) {
12691
12286
  const resolution = resolveHostEnvironment();
@@ -14394,15 +13989,15 @@ var init_claude_benchmark_policy = __esm({
14394
13989
  });
14395
13990
 
14396
13991
  // packages/adapters/dist/src/harnesses/claude.js
14397
- function isRecord3(value3) {
13992
+ function isRecord2(value3) {
14398
13993
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
14399
13994
  }
14400
13995
  function readHooks(document2) {
14401
13996
  const found = /* @__PURE__ */ new Map();
14402
- if (!isRecord3(document2))
13997
+ if (!isRecord2(document2))
14403
13998
  return found;
14404
13999
  const hooks = document2["hooks"];
14405
- if (!isRecord3(hooks))
14000
+ if (!isRecord2(hooks))
14406
14001
  return found;
14407
14002
  for (const point of MANIFEST.interceptionPoints) {
14408
14003
  const list = hooks[point.eventName];
@@ -14410,12 +14005,12 @@ function readHooks(document2) {
14410
14005
  continue;
14411
14006
  const entries = [];
14412
14007
  for (const [entryIndex, item] of list.entries()) {
14413
- if (!isRecord3(item))
14008
+ if (!isRecord2(item))
14414
14009
  continue;
14415
14010
  const matcher = item["matcher"];
14416
14011
  const inner = item["hooks"];
14417
14012
  const hookCommands = Array.isArray(inner) ? inner.flatMap((hook, hookIndex) => {
14418
- if (!isRecord3(hook) || typeof hook["command"] !== "string")
14013
+ if (!isRecord2(hook) || typeof hook["command"] !== "string")
14419
14014
  return [];
14420
14015
  const eventSegment = point.eventName.replace(/\./g, "\\.");
14421
14016
  const entryPointer = `hooks.${eventSegment}.${String(entryIndex)}`;
@@ -14723,7 +14318,7 @@ function cclimitsReset(value3) {
14723
14318
  return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
14724
14319
  }
14725
14320
  function cclimitsUsageWindow(value3, input) {
14726
- if (!isRecord3(value3))
14321
+ if (!isRecord2(value3))
14727
14322
  return null;
14728
14323
  const usedPercent = cclimitsPercent(value3["used"]);
14729
14324
  const remainingPercent = cclimitsPercent(value3["remaining"]);
@@ -14790,7 +14385,7 @@ async function observeUsage(context, observedAt) {
14790
14385
  } catch {
14791
14386
  return unavailable3("cclimits-claude-schema-unrecognized", "cclimits returned output that is not valid JSON");
14792
14387
  }
14793
- if (!isRecord3(parsed) || !isRecord3(parsed["claude"])) {
14388
+ if (!isRecord2(parsed) || !isRecord2(parsed["claude"])) {
14794
14389
  return unavailable3("cclimits-claude-schema-unrecognized", "cclimits JSON did not contain a Claude usage object");
14795
14390
  }
14796
14391
  const claude = parsed["claude"];
@@ -15153,11 +14748,11 @@ var init_codex_hooks = __esm({
15153
14748
  });
15154
14749
 
15155
14750
  // packages/adapters/dist/src/harnesses/codex.js
15156
- function isRecord4(value3) {
14751
+ function isRecord3(value3) {
15157
14752
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
15158
14753
  }
15159
14754
  function readHooks2(document2) {
15160
- if (!isRecord4(document2) || !isRecord4(document2["hooks"]))
14755
+ if (!isRecord3(document2) || !isRecord3(document2["hooks"]))
15161
14756
  return { points: [], matchers: [], commands: [], hookCommands: [] };
15162
14757
  const hooks = document2["hooks"];
15163
14758
  const points = [];
@@ -15170,14 +14765,14 @@ function readHooks2(document2) {
15170
14765
  continue;
15171
14766
  let carries = false;
15172
14767
  for (const [entryIndex, entry] of entries.entries()) {
15173
- if (!isRecord4(entry))
14768
+ if (!isRecord3(entry))
15174
14769
  continue;
15175
14770
  const matcher = typeof entry["matcher"] === "string" ? entry["matcher"] : null;
15176
14771
  if (matcher !== null)
15177
14772
  matchers.push(matcher);
15178
14773
  if (Array.isArray(entry["hooks"])) {
15179
14774
  for (const [hookIndex, hook] of entry["hooks"].entries()) {
15180
- if (isRecord4(hook) && typeof hook["command"] === "string") {
14775
+ if (isRecord3(hook) && typeof hook["command"] === "string") {
15181
14776
  commands.push(hook["command"]);
15182
14777
  const entryPointer = `hooks.${point.eventName}.${String(entryIndex)}`;
15183
14778
  hookCommands.push({
@@ -15418,7 +15013,7 @@ async function verify2(context) {
15418
15013
  summary: configured ? "Native enablement/trust metadata was unavailable; the declared file alone does not prove activation" : "No declared hook has enablement to inspect",
15419
15014
  achievedTier: null,
15420
15015
  evidence: [],
15421
- remediation: configured ? "Confirm in the Codex TUI that the hook is enabled and trusted" : null
15016
+ remediation: configured ? "Open Codex and manually enable and trust the hook; Token Harness cannot grant trust. Then run verify again." : null
15422
15017
  },
15423
15018
  {
15424
15019
  id: "canary-intercepted",
@@ -15468,7 +15063,7 @@ function resetInstant(epochSeconds) {
15468
15063
  return Number.isNaN(date.getTime()) ? null : date.toISOString();
15469
15064
  }
15470
15065
  function rateWindow(value3, input) {
15471
- if (!isRecord4(value3))
15066
+ if (!isRecord3(value3))
15472
15067
  return null;
15473
15068
  const usedPercent = readNumber(value3, "usedPercent");
15474
15069
  const duration2 = readNumber(value3, "windowDurationMins");
@@ -15489,7 +15084,7 @@ function rateWindow(value3, input) {
15489
15084
  };
15490
15085
  }
15491
15086
  function snapshotWindows(value3, observedAt, fallbackBucketId) {
15492
- if (!isRecord4(value3))
15087
+ if (!isRecord3(value3))
15493
15088
  return { windows: [], planType: null, rateLimitReachedType: null };
15494
15089
  const bucketId = readString(value3, "limitId") ?? fallbackBucketId;
15495
15090
  const bucketName = readString(value3, "limitName");
@@ -15521,13 +15116,13 @@ function parseRateLimitResponse(stdout, observedAt) {
15521
15116
  } catch {
15522
15117
  }
15523
15118
  }
15524
- const response = messages.find((message) => isRecord4(message) && message["id"] === RATE_LIMIT_REQUEST_ID && isRecord4(message["result"]));
15525
- if (!isRecord4(response) || !isRecord4(response["result"]))
15119
+ const response = messages.find((message) => isRecord3(message) && message["id"] === RATE_LIMIT_REQUEST_ID && isRecord3(message["result"]));
15120
+ if (!isRecord3(response) || !isRecord3(response["result"]))
15526
15121
  return null;
15527
15122
  const result6 = response["result"];
15528
15123
  const snapshots = [];
15529
15124
  const byId = result6["rateLimitsByLimitId"];
15530
- if (isRecord4(byId)) {
15125
+ if (isRecord3(byId)) {
15531
15126
  for (const [id, value3] of Object.entries(byId)) {
15532
15127
  if (value3 !== void 0)
15533
15128
  snapshots.push({ id, value: value3 });
@@ -15547,7 +15142,7 @@ function parseRateLimitResponse(stdout, observedAt) {
15547
15142
  }
15548
15143
  let resetCreditsAvailable = null;
15549
15144
  const resetCredits = result6["rateLimitResetCredits"];
15550
- if (isRecord4(resetCredits)) {
15145
+ if (isRecord3(resetCredits)) {
15551
15146
  const available = readNumber(resetCredits, "availableCount");
15552
15147
  resetCreditsAvailable = available === null ? null : Math.max(0, Math.trunc(available));
15553
15148
  }
@@ -15566,7 +15161,7 @@ function cclimitsPercent2(value3) {
15566
15161
  return Number.isFinite(parsed) && parsed >= 0 && parsed <= 100 ? parsed : null;
15567
15162
  }
15568
15163
  function cclimitsWindow(value3, input) {
15569
- if (!isRecord4(value3))
15164
+ if (!isRecord3(value3))
15570
15165
  return null;
15571
15166
  const usedPercent = cclimitsPercent2(value3["used_percent"]) ?? cclimitsPercent2(value3["used"]);
15572
15167
  const remainingPercent = cclimitsPercent2(value3["remaining_percent"]) ?? cclimitsPercent2(value3["remaining"]);
@@ -15597,7 +15192,7 @@ function parseCclimitsCodexResponse(stdout, observedAt) {
15597
15192
  } catch {
15598
15193
  return null;
15599
15194
  }
15600
- if (!isRecord4(parsed) || !isRecord4(parsed["codex"]))
15195
+ if (!isRecord3(parsed) || !isRecord3(parsed["codex"]))
15601
15196
  return null;
15602
15197
  const codex = parsed["codex"];
15603
15198
  if (codex["status"] !== "ok")
@@ -15774,8 +15369,8 @@ function utf8Bytes(value3) {
15774
15369
  return value3 === null ? 0 : new TextEncoder().encode(value3).byteLength;
15775
15370
  }
15776
15371
  function rpcResult(messages, id) {
15777
- const response = messages.find((message) => isRecord4(message) && message["id"] === id && isRecord4(message["result"]));
15778
- return isRecord4(response) && isRecord4(response["result"]) ? response["result"] : null;
15372
+ const response = messages.find((message) => isRecord3(message) && message["id"] === id && isRecord3(message["result"]));
15373
+ return isRecord3(response) && isRecord3(response["result"]) ? response["result"] : null;
15779
15374
  }
15780
15375
  function parseJsonLines(stdout) {
15781
15376
  const messages = [];
@@ -15905,15 +15500,15 @@ async function observeContext2(context, _observedAt) {
15905
15500
  const mcpMessages = parseJsonLines(mcpOutcome.stdout);
15906
15501
  mcpResponse = rpcResult(mcpMessages, CONTEXT_MCP_REQUEST_ID) ?? rpcResult(mcpMessages, 3);
15907
15502
  }
15908
- const config = configResponse !== null && isRecord4(configResponse["config"]) ? configResponse["config"] : null;
15503
+ const config = configResponse !== null && isRecord3(configResponse["config"]) ? configResponse["config"] : null;
15909
15504
  const managedConfigTarget = (() => {
15910
15505
  const layers = configResponse?.["layers"];
15911
15506
  if (!Array.isArray(layers))
15912
15507
  return null;
15913
15508
  for (const layer of layers) {
15914
- if (!isRecord4(layer))
15509
+ if (!isRecord3(layer))
15915
15510
  continue;
15916
- const source = isRecord4(layer["name"]) ? layer["name"] : null;
15511
+ const source = isRecord3(layer["name"]) ? layer["name"] : null;
15917
15512
  if (source === null || readString(source, "type") !== "user")
15918
15513
  continue;
15919
15514
  if (readString(source, "profile") !== null)
@@ -15933,11 +15528,11 @@ async function observeContext2(context, _observedAt) {
15933
15528
  return null;
15934
15529
  })();
15935
15530
  const managedConfigFieldOrigins = [];
15936
- const origins = configResponse !== null && isRecord4(configResponse["origins"]) ? configResponse["origins"] : null;
15531
+ const origins = configResponse !== null && isRecord3(configResponse["origins"]) ? configResponse["origins"] : null;
15937
15532
  const managedConfigOriginsObserved = origins !== null;
15938
15533
  for (const keyPath of ["model", "model_reasoning_effort", "model_verbosity"]) {
15939
- const metadata = origins !== null && isRecord4(origins[keyPath]) ? origins[keyPath] : null;
15940
- const source = metadata !== null && isRecord4(metadata["name"]) ? metadata["name"] : null;
15534
+ const metadata = origins !== null && isRecord3(origins[keyPath]) ? origins[keyPath] : null;
15535
+ const source = metadata !== null && isRecord3(metadata["name"]) ? metadata["name"] : null;
15941
15536
  if (metadata === null || source === null)
15942
15537
  continue;
15943
15538
  const sourceType = readString(source, "type");
@@ -15957,14 +15552,14 @@ async function observeContext2(context, _observedAt) {
15957
15552
  source: "native-rpc"
15958
15553
  });
15959
15554
  }
15960
- const features = config !== null && isRecord4(config["features"]) ? config["features"] : null;
15555
+ const features = config !== null && isRecord3(config["features"]) ? config["features"] : null;
15961
15556
  const instructions = config === null ? null : readString(config, "instructions");
15962
15557
  const developerInstructions = config === null ? null : readString(config, "developer_instructions");
15963
15558
  const availableModels = [];
15964
15559
  const modelData = modelResponse?.["data"];
15965
15560
  if (Array.isArray(modelData)) {
15966
15561
  for (const item of modelData) {
15967
- if (!isRecord4(item))
15562
+ if (!isRecord3(item))
15968
15563
  continue;
15969
15564
  const id = readString(item, "id");
15970
15565
  const model = readString(item, "model");
@@ -15975,7 +15570,7 @@ async function observeContext2(context, _observedAt) {
15975
15570
  const effortOptions = item["supportedReasoningEfforts"];
15976
15571
  if (Array.isArray(effortOptions)) {
15977
15572
  for (const option of effortOptions) {
15978
- if (!isRecord4(option))
15573
+ if (!isRecord3(option))
15979
15574
  continue;
15980
15575
  const effort = readString(option, "reasoningEffort");
15981
15576
  if (effort !== null)
@@ -16000,12 +15595,12 @@ async function observeContext2(context, _observedAt) {
16000
15595
  const data = mcpResponse?.["data"];
16001
15596
  if (Array.isArray(data)) {
16002
15597
  for (const item of data) {
16003
- if (!isRecord4(item))
15598
+ if (!isRecord3(item))
16004
15599
  continue;
16005
15600
  const name2 = readString(item, "name");
16006
15601
  if (name2 === null)
16007
15602
  continue;
16008
- const tools = isRecord4(item["tools"]) ? item["tools"] : null;
15603
+ const tools = isRecord3(item["tools"]) ? item["tools"] : null;
16009
15604
  mcpServers.push({
16010
15605
  harnessId: CODEX,
16011
15606
  name: name2,
@@ -16395,11 +15990,11 @@ var init_hermes = __esm({
16395
15990
  });
16396
15991
 
16397
15992
  // packages/adapters/dist/src/harnesses/opencode.js
16398
- function isRecord5(value3) {
15993
+ function isRecord4(value3) {
16399
15994
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
16400
15995
  }
16401
15996
  function pluginEntries(document2) {
16402
- if (!isRecord5(document2) || !Array.isArray(document2["plugin"]))
15997
+ if (!isRecord4(document2) || !Array.isArray(document2["plugin"]))
16403
15998
  return [];
16404
15999
  return document2["plugin"].filter((item) => typeof item === "string");
16405
16000
  }
@@ -18009,6 +17604,9 @@ function hookEntryFor(harnessId2, matcher, restoreNativeHookOnUninstall = false)
18009
17604
  ]
18010
17605
  };
18011
17606
  }
17607
+ function hookActivationNote(target) {
17608
+ return target.harness.id === "codex" ? ". After applying, manually enable and trust this hook in Codex; Token Harness writes hooks.json but cannot activate the hook or grant trust" : "";
17609
+ }
18012
17610
  function matcherCoversFamily2(matcher, family) {
18013
17611
  if (matcher === family)
18014
17612
  return true;
@@ -18099,7 +17697,7 @@ function hookAction(target, entry) {
18099
17697
  "every other entry in the list is unchanged"
18100
17698
  ],
18101
17699
  rollbackData: "file-snapshot",
18102
- explanation: `Register RTK with separate savings tracking for ${target.harness.displayName} on ${target.scope.toolFamily} tools`,
17700
+ explanation: `Register RTK with separate savings tracking for ${target.harness.displayName} on ${target.scope.toolFamily} tools${hookActivationNote(target)}`,
18103
17701
  path: target.configPath,
18104
17702
  // The pointer names the *list*, and the operation owns one element of it. What Token
18105
17703
  // Harness may later remove is that element, never the list.
@@ -18133,7 +17731,7 @@ function migrationAction(target, current) {
18133
17731
  preconditions: [`${current.commandPointer} still contains the reviewed RTK command`],
18134
17732
  postconditions: [`${current.commandPointer} routes RTK through per-agent tracking`],
18135
17733
  rollbackData: "file-snapshot",
18136
- explanation: `Enable separate ${target.harness.displayName} savings while preserving its existing RTK hook`,
17734
+ explanation: `Enable separate ${target.harness.displayName} savings while preserving its existing RTK hook${hookActivationNote(target)}`,
18137
17735
  path: target.configPath,
18138
17736
  ownedPointers: [current.commandPointer],
18139
17737
  operations: [
@@ -22095,379 +21693,6 @@ var init_providers = __esm({
22095
21693
  }
22096
21694
  });
22097
21695
 
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
-
22471
21696
  // packages/adapters/dist/src/index.js
22472
21697
  var init_src3 = __esm({
22473
21698
  "packages/adapters/dist/src/index.js"() {
@@ -22475,8 +21700,6 @@ var init_src3 = __esm({
22475
21700
  init_harnesses();
22476
21701
  init_providers();
22477
21702
  init_rtk_plan();
22478
- init_ccr_smart_routing();
22479
- init_ccr_management();
22480
21703
  }
22481
21704
  });
22482
21705
 
@@ -22829,14 +22052,6 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22829
22052
  tasksLeft: null,
22830
22053
  contextSnapshot: null,
22831
22054
  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,
22840
22055
  agentSkill: false,
22841
22056
  verbose: false,
22842
22057
  yes: false
@@ -22876,20 +22091,6 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22876
22091
  options.nativePolicy = true;
22877
22092
  if (name2 === "--agent-skill")
22878
22093
  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;
22893
22094
  if (name2 === "--verbose")
22894
22095
  options.verbose = true;
22895
22096
  continue;
@@ -23095,18 +22296,6 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
23095
22296
  }
23096
22297
  break;
23097
22298
  }
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;
23110
22299
  case "--context-snapshot":
23111
22300
  options.contextSnapshot = value3;
23112
22301
  break;
@@ -23177,7 +22366,6 @@ var init_argv = __esm({
23177
22366
  "optimize",
23178
22367
  "plan",
23179
22368
  "rollback",
23180
- "routing",
23181
22369
  "setup",
23182
22370
  "status",
23183
22371
  "stack-review",
@@ -23206,23 +22394,9 @@ var init_argv = __esm({
23206
22394
  "--profile",
23207
22395
  "--reserve",
23208
22396
  "--tasks-left",
23209
- "--route-mode",
23210
22397
  "--context-snapshot"
23211
22398
  ]);
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
- ]);
22399
+ BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--json", "--native-policy", "--agent-skill", "--verbose", "--yes"]);
23226
22400
  }
23227
22401
  });
23228
22402
 
@@ -23272,12 +22446,12 @@ function parseGitNexusIndexReadiness(output) {
23272
22446
  if (receipt["schemaVersion"] !== 1)
23273
22447
  return { state: "invalid", detail: null };
23274
22448
  const status = safeGitNexusStatusLabel(receipt["status"]);
23275
- const error2 = safeGitNexusStatusLabel(receipt["error"]);
22449
+ const error = safeGitNexusStatusLabel(receipt["error"]);
23276
22450
  if (status === "up-to-date" && receipt["error"] === void 0) {
23277
22451
  return { state: "up-to-date", detail: null };
23278
22452
  }
23279
22453
  if (receipt["error"] !== void 0)
23280
- return { state: "not-ready", detail: error2 };
22454
+ return { state: "not-ready", detail: error };
23281
22455
  if (receipt["status"] !== void 0)
23282
22456
  return { state: "not-ready", detail: status };
23283
22457
  return { state: "invalid", detail: null };
@@ -25414,15 +24588,15 @@ async function readOptimizationHistory(context) {
25414
24588
  continue;
25415
24589
  result6.scannedBenchmarks += 1;
25416
24590
  for (const variant of ["baseline", "optimized"]) {
25417
- const receiptPath4 = fs.join(directory, `${variant}.json`);
25418
- if (await fs.stat(receiptPath4) === null)
24591
+ const receiptPath3 = fs.join(directory, `${variant}.json`);
24592
+ if (await fs.stat(receiptPath3) === null)
25419
24593
  continue;
25420
24594
  const capture = parseTaskBenchmarkCapture(await read(fs.join(directory, `${variant}.capture.json`)));
25421
24595
  if (!capture.ok)
25422
24596
  return result6;
25423
24597
  if (capture.capture.projectId !== project)
25424
24598
  continue;
25425
- const receipt = parseTaskBenchmarkReceipt(await read(receiptPath4));
24599
+ const receipt = parseTaskBenchmarkReceipt(await read(receiptPath3));
25426
24600
  if (!receipt.ok)
25427
24601
  return result6;
25428
24602
  const start = capture.capture;
@@ -26715,12 +25889,12 @@ async function verifyManagedIntegrationPostconditions(context, integrations) {
26715
25889
  remediation: runtimeProblem?.remediation ?? "Check that the newly installed provider executable is on PATH, then review a fresh setup preview"
26716
25890
  }));
26717
25891
  }
26718
- } catch (error2) {
25892
+ } catch (error) {
26719
25893
  diagnostics.push(diagnostic({
26720
25894
  severity: "error",
26721
25895
  code: "managed-setup-postcondition-unavailable",
26722
25896
  subject: integration.providerId,
26723
- message: `The provider could not be re-observed after setup: ${error2 instanceof Error ? error2.message : String(error2)}`,
25897
+ message: `The provider could not be re-observed after setup: ${error instanceof Error ? error.message : String(error)}`,
26724
25898
  remediation: "Refresh and inspect the provider runtime before retrying"
26725
25899
  }));
26726
25900
  }
@@ -26774,13 +25948,13 @@ async function loadStoredPlan(context, planId) {
26774
25948
  throw new TypeError("A stored plan must be a JSON object");
26775
25949
  }
26776
25950
  return { stored: parsed, diagnostic: null };
26777
- } catch (error2) {
25951
+ } catch (error) {
26778
25952
  return {
26779
25953
  stored: null,
26780
25954
  diagnostic: diagnostic({
26781
25955
  severity: "error",
26782
25956
  code: "plan-unreadable",
26783
- message: `The stored plan could not be read: ${error2 instanceof Error ? error2.message : String(error2)}`,
25957
+ message: `The stored plan could not be read: ${error instanceof Error ? error.message : String(error)}`,
26784
25958
  path,
26785
25959
  remediation: "Run `token-harness plan` to compute a new one"
26786
25960
  })
@@ -27169,596 +26343,6 @@ var init_benchmark2 = __esm({
27169
26343
  }
27170
26344
  });
27171
26345
 
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
-
27762
26346
  // apps/cli/dist/src/commands/benchmark-capture.js
27763
26347
  function statePaths(context, benchmarkId, variant) {
27764
26348
  if (context.adapters === null || context.stateRoot === null)
@@ -28108,59 +26692,6 @@ async function runBenchmarkFinish(context) {
28108
26692
  const budget = budgetResult.data?.harnesses.find((item) => item.harnessId === parsed.capture.harnessId);
28109
26693
  const localUsage = parsed.capture.localSessionsBefore !== null && historyResult.data?.source.state === "available" ? deriveTaskLocalUsage(parsed.capture.localSessionsBefore, snapshotTaskLocalSessions(historyResult.data.sessions), parsed.capture.startedAt, completedAt) : null;
28110
26694
  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
- }
28164
26695
  const completed = completeTaskBenchmarkCapture(parsed.capture, {
28165
26696
  completedAt,
28166
26697
  usageAfter: budget?.windows ?? [],
@@ -28169,8 +26700,7 @@ async function runBenchmarkFinish(context) {
28169
26700
  failedAttempts,
28170
26701
  localUsage,
28171
26702
  contextAtFinish: taskBenchmarkContextSnapshot(finishContextObservation),
28172
- policyAtFinish: benchmarkPolicySnapshot(finishContextObservation),
28173
- ...ccrUsage === void 0 ? {} : { ccrUsage }
26703
+ policyAtFinish: benchmarkPolicySnapshot(finishContextObservation)
28174
26704
  });
28175
26705
  if (!completed.ok) {
28176
26706
  return commandResult({
@@ -28215,8 +26745,7 @@ async function runBenchmarkFinish(context) {
28215
26745
  diagnostics: [
28216
26746
  ...budgetResult.diagnostics,
28217
26747
  ...historyResult.diagnostics,
28218
- ...contextResult.diagnostics,
28219
- ...ccrUsageDiagnostics
26748
+ ...contextResult.diagnostics
28220
26749
  ]
28221
26750
  });
28222
26751
  }
@@ -28228,7 +26757,6 @@ var init_benchmark_capture = __esm({
28228
26757
  init_budget2();
28229
26758
  init_context_cost2();
28230
26759
  init_history2();
28231
- init_routing_usage();
28232
26760
  CLAUDE12 = harnessId("claude");
28233
26761
  CODEX12 = harnessId("codex");
28234
26762
  CAPTURE_HARNESSES = /* @__PURE__ */ new Set([CLAUDE12, CODEX12]);
@@ -28442,11 +26970,11 @@ async function readJsonArtifact(context, path) {
28442
26970
  }
28443
26971
  }
28444
26972
  async function gitNexusBaselinePurity(context, benchmarkId) {
28445
- const receiptPath4 = benchmarkArtifactPath(context, benchmarkId, "baseline.json");
26973
+ const receiptPath3 = benchmarkArtifactPath(context, benchmarkId, "baseline.json");
28446
26974
  const capturePath = benchmarkArtifactPath(context, benchmarkId, "baseline.capture.json");
28447
- if (receiptPath4 === null || capturePath === null)
26975
+ if (receiptPath3 === null || capturePath === null)
28448
26976
  return "absent";
28449
- const rawReceipt = await readJsonArtifact(context, receiptPath4);
26977
+ const rawReceipt = await readJsonArtifact(context, receiptPath3);
28450
26978
  if (rawReceipt.state !== "absent") {
28451
26979
  if (rawReceipt.state === "invalid")
28452
26980
  return "invalid";
@@ -30661,1031 +29189,6 @@ var init_rollback = __esm({
30661
29189
  }
30662
29190
  });
30663
29191
 
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
-
31689
29192
  // apps/cli/dist/src/commands/verify.js
31690
29193
  async function runVerify(context) {
31691
29194
  const diagnostics = [];
@@ -33124,7 +30627,7 @@ async function runUpdate(context) {
33124
30627
  let snapshot;
33125
30628
  try {
33126
30629
  snapshot = await snapshotCreation.store.capture(plan6.targetPath);
33127
- } catch (error2) {
30630
+ } catch (error) {
33128
30631
  return result5(EXIT_CODES["internal-error"], null, [
33129
30632
  ...preparedDiagnostics,
33130
30633
  diagnostic({
@@ -33132,7 +30635,7 @@ async function runUpdate(context) {
33132
30635
  code: "rtk-release-snapshot-failed",
33133
30636
  subject: "rtk",
33134
30637
  path: plan6.targetPath,
33135
- message: `RTK was not touched because its pre-update snapshot could not be captured: ${error2 instanceof Error ? error2.message : String(error2)}`,
30638
+ message: `RTK was not touched because its pre-update snapshot could not be captured: ${error instanceof Error ? error.message : String(error)}`,
33136
30639
  remediation: "Check the state directory and executable permissions, then retry"
33137
30640
  })
33138
30641
  ]);
@@ -33166,7 +30669,7 @@ async function runUpdate(context) {
33166
30669
  };
33167
30670
  try {
33168
30671
  await journalStore.write(directJournal);
33169
- } catch (error2) {
30672
+ } catch (error) {
33170
30673
  return result5(EXIT_CODES["internal-error"], null, [
33171
30674
  ...preparedDiagnostics,
33172
30675
  diagnostic({
@@ -33174,7 +30677,7 @@ async function runUpdate(context) {
33174
30677
  code: "rtk-release-journal-failed",
33175
30678
  subject: "rtk",
33176
30679
  path: plan6.targetPath,
33177
- message: `RTK was not touched because its in-progress transaction journal could not be persisted: ${error2 instanceof Error ? error2.message : String(error2)}`,
30680
+ message: `RTK was not touched because its in-progress transaction journal could not be persisted: ${error instanceof Error ? error.message : String(error)}`,
33178
30681
  remediation: "Check the Token Harness state directory, then retry"
33179
30682
  })
33180
30683
  ]);
@@ -33219,7 +30722,7 @@ async function runUpdate(context) {
33219
30722
  await finishDirectJournal(installed2.status === "dirty" ? "dirty" : "rolled-back", "failed", [
33220
30723
  failureDiagnostic
33221
30724
  ]);
33222
- } catch (error2) {
30725
+ } catch (error) {
33223
30726
  return result5(EXIT_CODES["apply-failed-dirty"], null, [
33224
30727
  ...preparedDiagnostics,
33225
30728
  failureDiagnostic,
@@ -33228,7 +30731,7 @@ async function runUpdate(context) {
33228
30731
  code: "rtk-release-failure-journal-write-failed",
33229
30732
  subject: "rtk",
33230
30733
  path: plan6.targetPath,
33231
- message: `RTK update failed and its final journal state could not be persisted: ${error2 instanceof Error ? error2.message : String(error2)}`,
30734
+ message: `RTK update failed and its final journal state could not be persisted: ${error instanceof Error ? error.message : String(error)}`,
33232
30735
  remediation: `Inspect transaction ${transactionId2} and its backups before retrying`
33233
30736
  })
33234
30737
  ]);
@@ -33247,7 +30750,7 @@ async function runUpdate(context) {
33247
30750
  }
33248
30751
  try {
33249
30752
  await markDirectAppliedInProgress();
33250
- } catch (error2) {
30753
+ } catch (error) {
33251
30754
  const rollback = await plan6.runtime.rollback(installed2.handle, context.projectRoot);
33252
30755
  const dirty = rollback.status === "dirty";
33253
30756
  const persistenceDiagnostic = diagnostic({
@@ -33255,7 +30758,7 @@ async function runUpdate(context) {
33255
30758
  code: "rtk-release-applied-journal-write-failed",
33256
30759
  subject: "rtk",
33257
30760
  path: plan6.targetPath,
33258
- 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}`,
30761
+ 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}`,
33259
30762
  remediation: `Inspect transaction ${transactionId2} and its backups before retrying`
33260
30763
  });
33261
30764
  try {
@@ -33332,7 +30835,7 @@ async function runUpdate(context) {
33332
30835
  });
33333
30836
  try {
33334
30837
  await finishDirectJournal("committed", "applied", [committedDiagnostic]);
33335
- } catch (error2) {
30838
+ } catch (error) {
33336
30839
  const rollback = await plan6.runtime.rollback(installed2.handle, context.projectRoot);
33337
30840
  const dirty = rollback.status === "dirty";
33338
30841
  const persistenceDiagnostic = diagnostic({
@@ -33340,7 +30843,7 @@ async function runUpdate(context) {
33340
30843
  code: "rtk-release-commit-journal-write-failed",
33341
30844
  subject: "rtk",
33342
30845
  path: plan6.targetPath,
33343
- message: `RTK ${plan6.target} was installed but the committed journal could not be persisted: ${error2 instanceof Error ? error2.message : String(error2)}. ${rollback.message}`,
30846
+ message: `RTK ${plan6.target} was installed but the committed journal could not be persisted: ${error instanceof Error ? error.message : String(error)}. ${rollback.message}`,
33344
30847
  remediation: `Inspect transaction ${transactionId2} and its backups before retrying`
33345
30848
  });
33346
30849
  await finishDirectJournal(dirty ? "dirty" : "rolled-back", "failed", [
@@ -33577,8 +31080,7 @@ var init_apply2 = __esm({
33577
31080
  // apps/cli/dist/src/render/benchmark.js
33578
31081
  function receiptLine(label, receipt) {
33579
31082
  const local = receipt.localUsage === null ? "local tokens unknown" : `local ${formatCount(receipt.localUsage.totalTokens)} tokens`;
33580
- 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`;
33581
- return `${label}: quality ${receipt.outcome.qualityGate}; attempts ${String(receipt.outcome.attempts)}; failed ${String(receipt.outcome.failedAttempts)}; errors ${String(receipt.outcome.errorCodes.length)}; ${local}; ${ccr}`;
31083
+ return `${label}: quality ${receipt.outcome.qualityGate}; attempts ${String(receipt.outcome.attempts)}; failed ${String(receipt.outcome.failedAttempts)}; errors ${String(receipt.outcome.errorCodes.length)}; ${local}`;
33582
31084
  }
33583
31085
  function policyLine(label, receipt) {
33584
31086
  const parts = [
@@ -33606,21 +31108,6 @@ function renderBenchmarkReport(report, _context) {
33606
31108
  } else {
33607
31109
  lines.push(...wrap(`Backend quota (${comparison.quota.scope}, ${comparison.quota.confidence}): baseline +${String(comparison.quota.baselineDeltaUsedPercent)}% vs optimized +${String(comparison.quota.optimizedDeltaUsedPercent)}%`, 0));
33608
31110
  }
33609
- const ccrUsage = comparison.ccrUsage;
33610
- if (ccrUsage === void 0 || ccrUsage.status === "not-measured") {
33611
- lines.push("CCR observed usage: not measured for both variants");
33612
- } else if (ccrUsage.status === "comparable") {
33613
- const modelPair = `${ccrUsage.baselineModels.join(", ") || "unknown"} \u2192 ${ccrUsage.optimizedModels.join(", ") || "unknown"}`;
33614
- lines.push(...wrap(`CCR request usage: ${formatCount(ccrUsage.baselineTokens ?? 0)} \u2192 ${formatCount(ccrUsage.optimizedTokens ?? 0)} tokens; delta ${String(ccrUsage.totalTokenDelta ?? 0)}; models ${modelPair}`, 0));
33615
- if (ccrUsage.recordedCostDeltaUsd !== null) {
33616
- lines.push(`CCR recorded provider-cost estimate delta: ${ccrUsage.recordedCostDeltaUsd.toFixed(6)} USD`);
33617
- }
33618
- lines.push("CCR request tokens and price estimates remain separate from subscription quota");
33619
- } else if (ccrUsage.status === "quality-gated") {
33620
- lines.push("CCR request usage: observed, but delta withheld until both task quality gates pass");
33621
- } else {
33622
- lines.push("CCR request usage: partial or ambiguous, not compared");
33623
- }
33624
31111
  const contextCounts = context.baseline === null || context.optimized === null ? "" : ` \u2014 static MCP tools ${String(context.baseline.effectiveStaticMcpToolCount)} \u2192 ${String(context.optimized.effectiveStaticMcpToolCount)}`;
33625
31112
  lines.push(...wrap(`Context: ${context.verdict}${contextCounts}`, 0));
33626
31113
  lines.push(...wrap(`Context evidence: ${context.reason}`, 2));
@@ -33677,7 +31164,7 @@ function renderBenchmarkStartReport(report, context) {
33677
31164
  }
33678
31165
  function renderBenchmarkFinishReport(report, context) {
33679
31166
  const { receipt } = report;
33680
- const receiptPath4 = truncatePath(displayPath(report.receiptPath, context.home), MAX_WIDTH - "Receipt: ".length);
31167
+ const receiptPath3 = truncatePath(displayPath(report.receiptPath, context.home), MAX_WIDTH - "Receipt: ".length);
33681
31168
  return document([
33682
31169
  `Benchmark receipt \u2014 ${receipt.benchmarkId} / ${receipt.variant}`,
33683
31170
  `${receipt.taskClass} on ${receipt.harnessId}`,
@@ -33685,7 +31172,7 @@ function renderBenchmarkFinishReport(report, context) {
33685
31172
  ...wrap(`Quality ${receipt.outcome.qualityGate}; attempts ${String(receipt.outcome.attempts)}; failed attempts ${String(receipt.outcome.failedAttempts)}`, 0),
33686
31173
  `Quota windows: ${String(receipt.usageBefore.length)} before / ${String(receipt.usageAfter.length)} after`,
33687
31174
  receipt.localUsage === null ? "Local usage: unavailable or ambiguous" : `Local usage: ${String(receipt.localUsage.totalTokens)} tokens (local evidence only)`,
33688
- `Receipt: ${receiptPath4}`,
31175
+ `Receipt: ${receiptPath3}`,
33689
31176
  "",
33690
31177
  ...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)
33691
31178
  ]);
@@ -33726,30 +31213,6 @@ function localLine(summary) {
33726
31213
  }
33727
31214
  return `local tokens across ${String(summary.localComparablePairs)} quality-passed pairs \u2014 baseline ${formatCount(summary.baselineLocalTokens)}, optimized ${formatCount(summary.optimizedLocalTokens)}, delta ${percent2(summary.localTokenSavingPercent)}`;
33728
31215
  }
33729
- function signedCount(value3) {
33730
- return `${value3 > 0 ? "+" : ""}${formatCount(value3)}`;
33731
- }
33732
- function signedUsd(value3) {
33733
- return `${value3 > 0 ? "+" : ""}${value3.toFixed(6)}`;
33734
- }
33735
- function ccrUsageLines(summary, indent) {
33736
- const usage = summary.ccrUsage;
33737
- if (usage === void 0)
33738
- return [];
33739
- const lines = [];
33740
- if (usage.comparablePairs > 0 && usage.baselineTokens !== null && usage.optimizedTokens !== null && usage.totalTokenDelta !== null) {
33741
- 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));
33742
- } else if (usage.partialPairs > 0 || usage.qualityGatedPairs > 0) {
33743
- lines.push(...wrap(`CCR usage deltas withheld \u2014 partial ${String(usage.partialPairs)}, quality-gated ${String(usage.qualityGatedPairs)}`, indent));
33744
- }
33745
- if (usage.recordedCostPairs > 0 && usage.baselineRecordedCostUsd !== null && usage.optimizedRecordedCostUsd !== null && usage.recordedCostDeltaUsd !== null) {
33746
- 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));
33747
- }
33748
- if (usage.comparablePairs > 0 || usage.partialPairs > 0 || usage.qualityGatedPairs > 0) {
33749
- lines.push(...wrap("CCR usage and cost estimates are separate from subscription quota and billed savings.", indent));
33750
- }
33751
- return lines;
33752
- }
33753
31216
  function candidateSummaryLine(summary) {
33754
31217
  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)}`;
33755
31218
  }
@@ -33767,12 +31230,11 @@ function candidateTimingLine(summary) {
33767
31230
  }
33768
31231
  function entryLine(entry) {
33769
31232
  const local = entry.localTokenSavingPercent === null ? "" : `; local delta ${percent2(entry.localTokenSavingPercent)}`;
33770
- const ccr = entry.ccrUsage?.status === "comparable" && entry.ccrUsage.totalTokenDelta !== null ? `; CCR ${signedCount(entry.ccrUsage.totalTokenDelta)} tokens` : "";
33771
31233
  if (!("context" in entry)) {
33772
- return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}${ccr}`;
31234
+ return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}`;
33773
31235
  }
33774
31236
  const contextCounts = entry.context.baseline === null || entry.context.optimized === null ? "" : ` ${String(entry.context.baseline.effectiveStaticMcpToolCount)}\u2192${String(entry.context.optimized.effectiveStaticMcpToolCount)} static tools`;
33775
- return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}${ccr}; context ${entry.context.verdict}${contextCounts}`;
31237
+ return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}; context ${entry.context.verdict}${contextCounts}`;
33776
31238
  }
33777
31239
  function renderCampaign(lines, campaign) {
33778
31240
  lines.push("", "Candidate campaign \u2014 experimental");
@@ -33830,7 +31292,6 @@ function renderBenchmarkMatrixReport(report, _context) {
33830
31292
  const local = localLine(summary);
33831
31293
  if (local !== null)
33832
31294
  lines.push(...wrap(local, 4));
33833
- lines.push(...ccrUsageLines(summary, 4));
33834
31295
  }
33835
31296
  lines.push("", "Overall");
33836
31297
  lines.push(...wrap(summaryLine(report.overall), 2));
@@ -33840,7 +31301,6 @@ function renderBenchmarkMatrixReport(report, _context) {
33840
31301
  const overallLocal = localLine(report.overall);
33841
31302
  if (overallLocal !== null)
33842
31303
  lines.push(...wrap(overallLocal, 2));
33843
- lines.push(...ccrUsageLines(report.overall, 2));
33844
31304
  if (report.candidateEvidence !== void 0 && report.campaign === void 0) {
33845
31305
  lines.push("", "Candidate evidence \u2014 experimental");
33846
31306
  for (const candidate of report.candidateEvidence) {
@@ -34533,14 +31993,14 @@ function renderMetricsReport(report, _context) {
34533
31993
  if (report.errorBreakdown.length > 0) {
34534
31994
  lines.push("");
34535
31995
  lines.push("Errors by code");
34536
- for (const error2 of report.errorBreakdown) {
34537
- lines.push(...wrap(error2.code, 2));
31996
+ for (const error of report.errorBreakdown) {
31997
+ lines.push(...wrap(error.code, 2));
34538
31998
  const scope = [];
34539
- if (error2.providerIds.length > 0)
34540
- scope.push(`providers ${error2.providerIds.join(", ")}`);
34541
- if (error2.harnesses.length > 0)
34542
- scope.push(`harnesses ${error2.harnesses.join(", ")}`);
34543
- lines.push(...wrap(`${formatCount(error2.count)} operation${error2.count === 1 ? "" : "s"}` + (scope.length > 0 ? ` - ${scope.join(" - ")}` : ""), 4));
31999
+ if (error.providerIds.length > 0)
32000
+ scope.push(`providers ${error.providerIds.join(", ")}`);
32001
+ if (error.harnesses.length > 0)
32002
+ scope.push(`harnesses ${error.harnesses.join(", ")}`);
32003
+ lines.push(...wrap(`${formatCount(error.count)} operation${error.count === 1 ? "" : "s"}` + (scope.length > 0 ? ` - ${scope.join(" - ")}` : ""), 4));
34544
32004
  }
34545
32005
  }
34546
32006
  return document(lines);
@@ -34883,63 +32343,6 @@ var init_stack_review2 = __esm({
34883
32343
  }
34884
32344
  });
34885
32345
 
34886
- // apps/cli/dist/src/render/smart-routing.js
34887
- function renderSmartRoutingReport(report) {
34888
- if (report.kind === "ccr-script")
34889
- return `${report.script}
34890
- `;
34891
- if (report.kind === "ccr-configuration") {
34892
- return [
34893
- `CCR ${report.action}: ${report.state}`,
34894
- `Harness: ${report.harnessId}`,
34895
- `Mode: ${report.mode}`,
34896
- `CCR version: ${report.ccrVersion}`,
34897
- `Gateway: ${report.gatewayState}`,
34898
- `Rule: ${report.ruleId}`,
34899
- `Script: ${report.scriptPath}`,
34900
- `Management endpoint: ${report.managementEndpoint}`,
34901
- ...report.profileId === void 0 || report.profileId === null ? [] : [`CCR profile: ${report.profileId}`],
34902
- ...report.launchCommand === void 0 || report.launchCommand === null ? [] : [`Launch: ${report.launchCommand}`]
34903
- ].join("\n");
34904
- }
34905
- if (report.kind === "ccr-lifecycle") {
34906
- return [
34907
- `CCR ${report.action}: ${report.state}`,
34908
- `Version: ${report.version}`,
34909
- `Package: ${report.packagePath}`,
34910
- `CLI: ${report.executablePath}`,
34911
- `Management endpoint: ${report.managementEndpoint}`
34912
- ].join("\n");
34913
- }
34914
- const { metrics } = report;
34915
- const harnesses = Object.entries(metrics.byHarness).filter(([, count]) => count > 0).map(([name2, count]) => `${name2} ${String(count)}`).join(", ") || "none";
34916
- const tiers = Object.entries(metrics.byTier).filter(([, count]) => count > 0).map(([name2, count]) => `${name2} ${String(count)}`).join(", ") || "none";
34917
- const modes = Object.entries(metrics.byMode).filter(([, count]) => count > 0).map(([name2, count]) => `${name2} ${String(count)}`).join(", ") || "none";
34918
- const lines = [
34919
- "Smart Model Routing decisions",
34920
- `Window: ${report.since} to ${report.until}`,
34921
- `Retained decisions: ${String(metrics.retainedDecisionCount)}`,
34922
- `By harness: ${harnesses}`,
34923
- `By mode: ${modes}`,
34924
- `By tier: ${tiers}`,
34925
- `CCR route changes requested: ${String(metrics.routeMutationRequestCount)}`,
34926
- `Malformed records: ${String(metrics.malformedRecordCount)}`,
34927
- `Pruned records: ${String(metrics.prunedRecordCount)}`,
34928
- "Model savings: not measured",
34929
- `Cleanup: token-harness routing --route-metrics --prune (keeps ${String(metrics.retentionLimit)} newest records)`
34930
- ];
34931
- if (report.ccrUsage !== void 0) {
34932
- const models = report.ccrUsage.byModel.map((item) => item.model).join(", ") || "none";
34933
- 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");
34934
- }
34935
- return lines.join("\n");
34936
- }
34937
- var init_smart_routing3 = __esm({
34938
- "apps/cli/dist/src/render/smart-routing.js"() {
34939
- "use strict";
34940
- }
34941
- });
34942
-
34943
32346
  // apps/cli/dist/src/render/update.js
34944
32347
  function widthOf(values, floor) {
34945
32348
  return Math.max(floor, ...values.map((value3) => value3.length + 2));
@@ -35480,8 +32883,6 @@ function renderHuman(result6, context) {
35480
32883
  return plain(renderSimpleMcp(data));
35481
32884
  case "metrics":
35482
32885
  return plain(renderSimpleMetrics(data));
35483
- case "routing":
35484
- return plain(renderSmartRoutingReport(data));
35485
32886
  case "optimize":
35486
32887
  return plain(renderSimpleOptimize(data));
35487
32888
  case "plan":
@@ -35535,8 +32936,6 @@ function renderHuman(result6, context) {
35535
32936
  return plain(renderVerifyReport(data, context));
35536
32937
  case "metrics":
35537
32938
  return plain(renderMetricsReport(data, context));
35538
- case "routing":
35539
- return plain(renderSmartRoutingReport(data));
35540
32939
  case "update":
35541
32940
  return plain(renderUpdateReport(data, context));
35542
32941
  default:
@@ -35560,7 +32959,6 @@ var init_render = __esm({
35560
32959
  init_plan3();
35561
32960
  init_status2();
35562
32961
  init_stack_review2();
35563
- init_smart_routing3();
35564
32962
  init_update2();
35565
32963
  init_verify2();
35566
32964
  init_simple();
@@ -35608,7 +33006,6 @@ Advanced commands
35608
33006
  apply Apply a reviewed plan
35609
33007
  verify Check that configured integrations work
35610
33008
  metrics Show measured savings
35611
- routing Install/configure CCR or inspect routing decisions
35612
33009
  update Check or update installed providers
35613
33010
  rollback Restore the previous configuration
35614
33011
  uninstall Remove only configuration Token Harness owns
@@ -35621,14 +33018,6 @@ Useful flags
35621
33018
  --yes Confirm a configuration-changing operation
35622
33019
  --harness <id> Restrict the operation to one harness
35623
33020
  --provider <id> Restrict the operation to one provider
35624
- --script Export a CCR script rule (routing command)
35625
- --route-metrics Show local routing decision telemetry
35626
- --route-mode <mode> shadow by default; conservative requires opt-in
35627
- --prune Keep only the 200 newest routing decision records
35628
- --configure-ccr Preview managed CCR setup; --yes applies one step
35629
- --update-ccr Preview update of the managed CCR CLI
35630
- --rollback-ccr Preview rollback; --yes removes owned rule/profile
35631
- --ccr-usage Read CCR model/token aggregates for local sessions
35632
33021
  --project <dir> Use that project instead of the current directory
35633
33022
  --help Show help for a command
35634
33023
  --version Print the version
@@ -35891,36 +33280,6 @@ Figures are never merged across measurement classes or units: tokens are not
35891
33280
  added to characters, and an estimate is not added to an exact figure. A
35892
33281
  counterfactual reduction is reported on its own line and never as a saving.
35893
33282
  Exits 0 whatever the figures say \u2014 an empty report is a fact, not a failure.`,
35894
- routing: `token-harness routing \u2014 inspect or export Smart Model Routing
35895
-
35896
- Usage
35897
- token-harness routing --script --harness <claude|codex>
35898
- [--route-mode <shadow|conservative>] [--json]
35899
- token-harness routing --configure-ccr --harness <claude|codex> [--yes]
35900
- token-harness routing --update-ccr [--yes]
35901
- token-harness routing --rollback-ccr --harness <claude|codex> [--yes]
35902
- token-harness routing --route-metrics [--since <duration|date>]
35903
- [--until <date>] [--harness <claude|codex>]
35904
- [--ccr-usage] [--prune] [--json]
35905
-
35906
- Script export defaults to shadow mode. Add the generated script as a Node.js script rule in CCR;
35907
- it records local, prompt-free decisions and returns no route rewrite in shadow mode. Conservative
35908
- mode is explicit and only proposes a configured simple model for high-confidence, low-risk requests.
35909
- It leaves requests with tool schemas unchanged unless the CCR process explicitly sets
35910
- TOKEN_HARNESS_ROUTING_ALLOW_TOOLS=true. No API call or local model is used to classify.
35911
-
35912
- CCR must run on this machine as the same user for the local telemetry path to be writable. A failed
35913
- telemetry write never blocks the agent request. Decision records contain no prompt or credentials.
35914
- Routing choices are not measured token savings; this command keeps them separate from \`metrics\`.
35915
- Use --prune to remove all but the 200 newest decision records.
35916
-
35917
- When no authenticated local CCR service is present, configure first previews an npm install/start
35918
- of CCR 3.1.1 in Token Harness' protected local state; after approving that step, run configure again
35919
- to preview the routing rule and optional CCR-only CLI profile. A Token Harness-owned service keeps
35920
- its Web RPC token in a private local file; existing services can use CCR_WEB_AUTH_TOKEN and
35921
- optionally CCR_WEB_URL. --update-ccr only updates a Token Harness-owned CLI to the reviewed pin.
35922
- Rollback removes only the exact rule, profile, and script Token Harness owns. CCR usage is observed
35923
- request telemetry, not subscription quota or measured savings.`,
35924
33283
  uninstall: `token-harness uninstall \u2014 remove what Token Harness owns
35925
33284
 
35926
33285
  Usage
@@ -36081,8 +33440,8 @@ function emit(result6, options, renderContext, json) {
36081
33440
  if (json) {
36082
33441
  try {
36083
33442
  options.streams.out(serializeEnvelope(toEnvelope(result6, toolVersion)));
36084
- } catch (error2) {
36085
- options.streams.err(`internal-error envelope-serialization-failed: ${error2 instanceof Error ? error2.message : String(error2)}
33443
+ } catch (error) {
33444
+ options.streams.err(`internal-error envelope-serialization-failed: ${error instanceof Error ? error.message : String(error)}
36086
33445
  `);
36087
33446
  return EXIT_CODES["internal-error"];
36088
33447
  }
@@ -36201,16 +33560,7 @@ async function run(options) {
36201
33560
  tasksRemaining: invocation.options.tasksLeft,
36202
33561
  contextSnapshotPath: invocation.options.contextSnapshot,
36203
33562
  nativePolicy: invocation.options.nativePolicy,
36204
- routingScript: invocation.options.routingScript,
36205
- routingMetrics: invocation.options.routingMetrics,
36206
- routingMode: invocation.options.routingMode,
36207
- routingPrune: invocation.options.routingPrune,
36208
- routingCcrConfigure: invocation.options.routingCcrConfigure,
36209
- routingCcrRollback: invocation.options.routingCcrRollback,
36210
- routingCcrUpdate: invocation.options.routingCcrUpdate,
36211
- routingCcrUsage: invocation.options.routingCcrUsage,
36212
33563
  env: options.env ?? {},
36213
- ...options.ccrFetch === void 0 ? {} : { ccrFetch: options.ccrFetch },
36214
33564
  agentSkill: invocation.options.agentSkill,
36215
33565
  since: invocation.options.since,
36216
33566
  until: invocation.options.until,
@@ -36234,7 +33584,7 @@ async function run(options) {
36234
33584
  let result6;
36235
33585
  try {
36236
33586
  result6 = await table[invocation.command](context);
36237
- } catch (error2) {
33587
+ } catch (error) {
36238
33588
  result6 = commandResult({
36239
33589
  command: invocation.command,
36240
33590
  exitCode: EXIT_CODES["internal-error"],
@@ -36242,7 +33592,7 @@ async function run(options) {
36242
33592
  diagnostic({
36243
33593
  severity: "error",
36244
33594
  code: "internal-error",
36245
- message: `The command \`${invocation.command}\` failed unexpectedly: ${error2 instanceof Error ? error2.message : String(error2)}`,
33595
+ message: `The command \`${invocation.command}\` failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`,
36246
33596
  remediation: "Report this with the command you ran at https://github.com/giuliastro/TokenHarness/issues"
36247
33597
  })
36248
33598
  ]
@@ -36269,7 +33619,6 @@ var init_run = __esm({
36269
33619
  init_optimize();
36270
33620
  init_plan2();
36271
33621
  init_rollback();
36272
- init_smart_routing2();
36273
33622
  init_setup2();
36274
33623
  init_status();
36275
33624
  init_stack_review();
@@ -36293,7 +33642,6 @@ var init_run = __esm({
36293
33642
  optimize: runOptimize,
36294
33643
  plan: runPlan,
36295
33644
  rollback: runRollback,
36296
- routing: runSmartRouting,
36297
33645
  setup: runSetup,
36298
33646
  status: runStatus,
36299
33647
  "stack-review": runStackReview,
@@ -37026,6 +34374,7 @@ function agentRules(id, providers, context, guidance) {
37026
34374
  }
37027
34375
  function describeChange(action, harness) {
37028
34376
  const prefix = name(harness);
34377
+ const codexHookActivationNote = harness === "codex" && action.kind === "merge-json" && action.explanation.includes("manually enable and trust this hook in Codex") ? " After applying, manually enable and trust this hook in Codex; Token Harness cannot activate it or grant trust." : "";
37029
34378
  if (action.kind === "merge-json" && action.ownedPointers?.includes("effortLevel")) {
37030
34379
  const operation = action.operations.find((item) => item.kind === "set");
37031
34380
  const value3 = operation?.kind === "set" ? String(operation.value) : "reviewed";
@@ -37053,7 +34402,7 @@ function describeChange(action, harness) {
37053
34402
  };
37054
34403
  return {
37055
34404
  title: `${prefix}: ${descriptions[action.kind] ?? "Apply the reviewed integration change"}`,
37056
- description: "Preserves unrelated settings. Existing safety checks and backups apply; unsupported versions are not forced.",
34405
+ description: "Preserves unrelated settings. Existing safety checks and backups apply; unsupported versions are not forced." + codexHookActivationNote,
37057
34406
  files: action.affectedPaths.length
37058
34407
  };
37059
34408
  }
@@ -37452,149 +34801,20 @@ var init_guided = __esm({
37452
34801
  const data = input;
37453
34802
  const action = String(data["action"]);
37454
34803
  const candidateAction = action === "candidate-setup" || action === "candidate-remove";
37455
- const routingAction = action === "routing-setup" || action === "routing-remove" || action === "routing-metrics";
37456
34804
  const requestedHarnesses = data["harnesses"];
37457
34805
  const validHarnesses = Array.isArray(requestedHarnesses) && requestedHarnesses.length > 0 && requestedHarnesses.length <= 20 && requestedHarnesses.every((value3) => typeof value3 === "string" && ["claude", "codex"].includes(value3)) && new Set(requestedHarnesses).size === requestedHarnesses.length;
37458
- if (Object.keys(data).some((key) => ![
37459
- "action",
37460
- "harness",
37461
- "harnesses",
37462
- "task",
37463
- "provider",
37464
- "candidate",
37465
- "routeMode"
37466
- ].includes(key)) || ![
34806
+ if (Object.keys(data).some((key) => !["action", "harness", "harnesses", "task", "provider", "candidate"].includes(key)) || ![
37467
34807
  "setup",
37468
34808
  "effort",
37469
34809
  "skill",
37470
34810
  "undo",
37471
34811
  "remove",
37472
34812
  "candidate-setup",
37473
- "candidate-remove",
37474
- "routing-setup",
37475
- "routing-remove",
37476
- "routing-metrics"
37477
- ].includes(action) || data["harness"] !== void 0 && !["claude", "codex"].includes(String(data["harness"])) || data["harnesses"] !== void 0 && !validHarnesses || data["harnesses"] !== void 0 && action !== "setup" || data["routeMode"] !== void 0 && !["shadow", "conservative"].includes(String(data["routeMode"])) || data["harnesses"] !== void 0 && data["harness"] !== void 0 || data["task"] !== void 0 && !TASKS.has(String(data["task"])) || data["provider"] !== void 0 && !["rtk", "harnesstrim", "mcptoon", "gitnexus", "headroom"].includes(String(data["provider"])) || data["candidate"] !== void 0 && !["mcptoon", "gitnexus"].includes(String(data["candidate"])) || action === "effort" && (data["harness"] === void 0 || data["task"] === void 0) || action === "skill" && data["harness"] === void 0 || routingAction && data["harness"] === void 0 || action !== "routing-setup" && data["routeMode"] !== void 0 || action === "remove" && (data["provider"] === void 0 || data["harness"] !== void 0 || data["harnesses"] !== void 0 || data["task"] !== void 0 || data["candidate"] !== void 0) || data["provider"] !== void 0 && action !== "remove" && action !== "setup" || candidateAction && (data["candidate"] === void 0 || data["harness"] === void 0 || data["provider"] !== void 0 || data["task"] !== void 0) || !candidateAction && data["candidate"] !== void 0 || routingAction && (data["provider"] !== void 0 || data["candidate"] !== void 0 || data["task"] !== void 0 || data["harnesses"] !== void 0))
34813
+ "candidate-remove"
34814
+ ].includes(action) || data["harness"] !== void 0 && !["claude", "codex"].includes(String(data["harness"])) || data["harnesses"] !== void 0 && !validHarnesses || data["harnesses"] !== void 0 && action !== "setup" || data["harnesses"] !== void 0 && data["harness"] !== void 0 || data["task"] !== void 0 && !TASKS.has(String(data["task"])) || data["provider"] !== void 0 && !["rtk", "harnesstrim", "mcptoon", "gitnexus", "headroom"].includes(String(data["provider"])) || data["candidate"] !== void 0 && !["mcptoon", "gitnexus"].includes(String(data["candidate"])) || action === "effort" && (data["harness"] === void 0 || data["task"] === void 0) || action === "skill" && data["harness"] === void 0 || action === "remove" && (data["provider"] === void 0 || data["harness"] !== void 0 || data["harnesses"] !== void 0 || data["task"] !== void 0 || data["candidate"] !== void 0) || data["provider"] !== void 0 && action !== "remove" && action !== "setup" || candidateAction && (data["candidate"] === void 0 || data["harness"] === void 0 || data["provider"] !== void 0 || data["task"] !== void 0) || !candidateAction && data["candidate"] !== void 0)
37478
34815
  throw new GuideError(400, "Choose a supported agent and action.");
37479
34816
  return this.exclusive(async () => {
37480
34817
  this.approval = null;
37481
- if (routingAction) {
37482
- const harness = String(data["harness"]);
37483
- const mode = data["routeMode"] === "conservative" ? "conservative" : "shadow";
37484
- if (action === "routing-metrics") {
37485
- this.record(`Reading local Smart Model Routing decisions for ${name(harness)}. No configuration is changed.`, "working");
37486
- const result7 = await this.call([
37487
- "routing",
37488
- "--route-metrics",
37489
- "--ccr-usage",
37490
- "--harness",
37491
- harness,
37492
- "--since",
37493
- "30d"
37494
- ]);
37495
- if (result7.exitCode !== 0 || result7.data?.kind !== "metrics") {
37496
- const message = explainGuideIssue(result7.diagnostics, `Routing activity for ${name(harness)} could not be read. No configuration changed.`);
37497
- this.record(message, "attention");
37498
- return {
37499
- ticket: null,
37500
- title: "Routing activity needs attention",
37501
- changes: [],
37502
- notices: [message],
37503
- expiresAt: null,
37504
- network: false,
37505
- restart: false
37506
- };
37507
- }
37508
- const metrics = result7.data.metrics;
37509
- const notices2 = [
37510
- `${String(metrics.retainedDecisionCount)} local routing decision${metrics.retainedDecisionCount === 1 ? "" : "s"} recorded in the last 30 days for ${name(harness)}.`,
37511
- `Shadow decisions: ${String(metrics.byMode.shadow)}. Conservative route requests: ${String(metrics.routeMutationRequestCount)}.`,
37512
- `Tiers: simple ${String(metrics.byTier.simple)}, standard ${String(metrics.byTier.standard)}, complex ${String(metrics.byTier.complex)}, critical ${String(metrics.byTier.critical)}.`,
37513
- "Routing telemetry stores classifier features and model identifiers, not prompt text. Subscription savings remain not measured until paired quality and allowance evidence exists."
37514
- ];
37515
- this.record("Routing activity read successfully.", "success");
37516
- return {
37517
- ticket: null,
37518
- title: `Smart Model Routing \xB7 ${name(harness)}`,
37519
- changes: [],
37520
- notices: notices2,
37521
- expiresAt: null,
37522
- network: false,
37523
- restart: false
37524
- };
37525
- }
37526
- const removing = action === "routing-remove";
37527
- this.record(`${removing ? "Reviewing removal of" : "Reviewing"} Smart Model Routing for ${name(harness)}. Nothing has changed yet.`, "working");
37528
- const args = removing ? ["routing", "--rollback-ccr", "--harness", harness] : ["routing", "--configure-ccr", "--harness", harness, "--route-mode", mode];
37529
- const result6 = await this.call(args);
37530
- if (result6.exitCode !== 0 || result6.data === null) {
37531
- const message = explainGuideIssue(result6.diagnostics, `No safe Smart Model Routing ${removing ? "removal" : "setup"} is available for ${name(harness)}. Nothing was changed.`);
37532
- this.record(message, "attention");
37533
- return {
37534
- ticket: null,
37535
- title: "No routing change to apply",
37536
- changes: [],
37537
- notices: [message],
37538
- expiresAt: null,
37539
- network: false,
37540
- restart: false
37541
- };
37542
- }
37543
- const report = result6.data;
37544
- const alreadyConfigured = !removing && report.kind === "ccr-configuration" && report.state === "already-configured";
37545
- const alreadyAbsent = removing && report.kind === "ccr-configuration" && report.state === "already-absent";
37546
- if (alreadyConfigured || alreadyAbsent) {
37547
- const message = alreadyConfigured ? `${name(harness)} already has the Token Harness-owned ${mode} routing rule.` : `${name(harness)} has no Token Harness-owned routing rule to remove.`;
37548
- this.record(message, "success");
37549
- return {
37550
- ticket: null,
37551
- title: alreadyConfigured ? "Routing already configured" : "Routing already absent",
37552
- changes: [],
37553
- notices: [message],
37554
- expiresAt: null,
37555
- network: false,
37556
- restart: false
37557
- };
37558
- }
37559
- const ticket = this.random();
37560
- const expires2 = this.now() + 10 * 6e4;
37561
- const lifecycle = report.kind === "ccr-lifecycle";
37562
- const network2 = lifecycle && report.action !== "start";
37563
- this.approval = {
37564
- id: ticket,
37565
- expires: expires2,
37566
- plans: [],
37567
- transactionId: null,
37568
- provider: null,
37569
- description: `Smart Model Routing ${removing ? "removal" : mode}`,
37570
- operation: removing ? "routing-rollback" : "routing-configure",
37571
- network: network2,
37572
- routingHarness: harness,
37573
- routingMode: mode
37574
- };
37575
- const change = report.kind === "ccr-lifecycle" ? {
37576
- title: `${name(harness)}: prepare local CCR routing runtime`,
37577
- files: 0,
37578
- description: report.action === "install" ? `Install the reviewed CCR ${report.version} CLI inside Token Harness protected local state, start its loopback gateway and verify it. No global CCR package, provider login or native harness endpoint is replaced.` : `Start or update the Token Harness-owned CCR ${report.version} runtime and verify its loopback gateway before any routing rule is configured.`
37579
- } : {
37580
- title: `${name(harness)}: ${removing ? "remove" : "configure"} Smart Model Routing`,
37581
- files: 0,
37582
- description: removing ? "Remove only the Token Harness-owned CCR rule/profile for this coding agent. Provider credentials and unrelated CCR configuration are left untouched." : mode === "shadow" ? "Install the Token Harness-owned CCR rule in shadow mode. Requests keep their current model; only local routing decisions are recorded." : "Install the conservative opt-in rule. Only high-confidence simple requests may request the already-configured simple model; complex, ambiguous, image and unsafe tool requests pass through unchanged."
37583
- };
37584
- this.record("Smart Model Routing preview ready. Waiting for your approval.", "success");
37585
- return {
37586
- ticket,
37587
- title: removing ? `Remove Smart Model Routing for ${name(harness)}?` : `Set up ${mode} Smart Model Routing for ${name(harness)}?`,
37588
- changes: [change],
37589
- notices: [
37590
- lifecycle && !removing ? "CCR runtime preparation and routing-rule configuration are deliberately separate safety stages. After the runtime is ready, open Manage routing again to review the exact rule/profile." : "Token Harness owns only its exact CCR rule/profile and local managed runtime. Provider credentials remain in CCR and are never imported silently.",
37591
- mode === "shadow" && !removing ? "Shadow mode is the default: it never changes the model selected for a request." : mode === "conservative" && !removing ? "Conservative routing requires TOKEN_HARNESS_ROUTING_SIMPLE_MODEL to name an exact model already configured in CCR. Without that explicit model the preview is refused." : "Removing routing does not uninstall CCR or delete provider credentials."
37592
- ],
37593
- expiresAt: new Date(expires2).toISOString(),
37594
- network: network2,
37595
- restart: false
37596
- };
37597
- }
37598
34818
  if (candidateAction) {
37599
34819
  const candidate = String(data["candidate"]);
37600
34820
  const harness = String(data["harness"]);
@@ -37995,86 +35215,6 @@ var init_guided = __esm({
37995
35215
  appliedPlans: appliedCount
37996
35216
  };
37997
35217
  }
37998
- if (approval.operation === "routing-configure" || approval.operation === "routing-rollback") {
37999
- if (approval.routingHarness === void 0 || approval.routingMode === void 0)
38000
- throw new GuideError(409, "This Smart Model Routing preview is incomplete. Review it again.");
38001
- const harness = approval.routingHarness;
38002
- const mode = approval.routingMode;
38003
- const removing = approval.operation === "routing-rollback";
38004
- this.record((removing ? "Removing" : "Applying") + " Smart Model Routing for " + name(harness) + ".", "working");
38005
- let result6;
38006
- try {
38007
- result6 = await this.call(removing ? ["routing", "--rollback-ccr", "--harness", harness, "--yes"] : ["routing", "--configure-ccr", "--harness", harness, "--route-mode", mode, "--yes"]);
38008
- } catch {
38009
- this.invalidateObservedState();
38010
- const message = "The Smart Model Routing operation stopped before its final result could be read. No automatic retry was made. Review the local routing state before retrying.";
38011
- this.record(message, "attention");
38012
- return {
38013
- ok: false,
38014
- title: "Routing result needs checking",
38015
- messages: [message],
38016
- appliedPlans: 0
38017
- };
38018
- }
38019
- if (result6.exitCode !== 0 || result6.data === null) {
38020
- const message = explainGuideIssue(result6.diagnostics, "Smart Model Routing for " + name(harness) + " was not changed. The local CCR runtime, provider model selection or owned rule state no longer matches the preview.");
38021
- this.invalidateObservedState();
38022
- this.record(message, "attention");
38023
- return {
38024
- ok: false,
38025
- title: "Routing change was not applied",
38026
- messages: [message],
38027
- appliedPlans: 0
38028
- };
38029
- }
38030
- const report = result6.data;
38031
- this.lastApplied = null;
38032
- this.invalidateObservedState();
38033
- if (report.kind === "ccr-lifecycle") {
38034
- const message = "The Token Harness-owned CCR " + report.version + " runtime is ready and verified on loopback. No routing rule has been assumed from this runtime step. Open Manage routing again to review the exact shadow or conservative rule/profile.";
38035
- this.record("CCR routing runtime prepared and verified.", "success");
38036
- return {
38037
- ok: true,
38038
- title: "Routing runtime ready",
38039
- messages: [
38040
- message,
38041
- "Provider login/import remains an explicit CCR choice; Token Harness did not change Claude Code or Codex native endpoints."
38042
- ],
38043
- appliedPlans: report.state === "already-current" ? 0 : 1
38044
- };
38045
- }
38046
- if (report.kind !== "ccr-configuration") {
38047
- const message = "The routing command returned an unexpected result shape after approval. No success is being reported; review the local CCR routing state before retrying.";
38048
- this.record(message, "attention");
38049
- return {
38050
- ok: false,
38051
- title: "Routing result needs checking",
38052
- messages: [message],
38053
- appliedPlans: 0
38054
- };
38055
- }
38056
- const changed = report.state === "configured" || report.state === "rolled-back";
38057
- const messages2 = removing ? [
38058
- report.state === "already-absent" ? name(harness) + " already had no Token Harness-owned routing rule." : "The Token Harness-owned Smart Model Routing rule/profile for " + name(harness) + " was removed. CCR and provider credentials were left in place."
38059
- ] : [
38060
- report.state === "already-configured" ? name(harness) + " already has the Token Harness-owned " + mode + " routing rule." : name(harness) + " Smart Model Routing is configured in " + mode + " mode.",
38061
- ...mode === "shadow" ? [
38062
- "Shadow mode records local routing decisions but does not change the request model."
38063
- ] : [
38064
- "Conservative mode may request the configured simple model only for high-confidence simple prompts; safety-gated requests pass through unchanged."
38065
- ],
38066
- ...report.launchCommand ? ["Launch through the CCR profile to use the rule: " + report.launchCommand] : [
38067
- "CCR still needs an unambiguous provider/model profile before a routed launch can be verified."
38068
- ]
38069
- ];
38070
- this.record(removing ? "Smart Model Routing rule removed." : "Smart Model Routing configured.", "success");
38071
- return {
38072
- ok: true,
38073
- title: removing ? "Routing removed" : "Smart Model Routing configured",
38074
- messages: messages2,
38075
- appliedPlans: changed ? 1 : 0
38076
- };
38077
- }
38078
35218
  if (approval.operation === "candidate-apply" || approval.operation === "candidate-uninstall") {
38079
35219
  if (approval.candidate === void 0 || approval.candidateHarness === void 0)
38080
35220
  throw new GuideError(409, "This experimental preview is incomplete. Review it again.");
@@ -41519,154 +38659,6 @@ var init_guided_product_client = __esm({
41519
38659
  }
41520
38660
 
41521
38661
 
41522
- function reviewRoutingAction(harness, action, routeMode, run) {
41523
- const label =
41524
- action === 'routing-metrics'
41525
- ? 'Reading routing activity'
41526
- : action === 'routing-remove'
41527
- ? 'Reviewing routing removal'
41528
- : 'Reviewing ' + routeMode + ' routing setup';
41529
- $('modal-content').replaceChildren(
41530
- progress(label, 'Nothing changes while Token Harness reads the local routing state.'),
41531
- );
41532
- $('modal-actions').replaceChildren(modalClose('Cancel'));
41533
- setBusy(true, false);
41534
- ensureSession()
41535
- .then(() =>
41536
- request('/api/preview', {
41537
- action,
41538
- harness,
41539
- ...(action === 'routing-setup' ? { routeMode } : {}),
41540
- }),
41541
- )
41542
- .then(data => {
41543
- if (run !== modalRun || !$('modal').open) return;
41544
- pendingTicket = data.ticket;
41545
- $('modal-content').replaceChildren(
41546
- messageBox(
41547
- 'Smart Model Routing · ' + agentName(harness),
41548
- action === 'routing-metrics'
41549
- ? 'Local classifier and CCR activity only. Prompt text and credentials are not shown.'
41550
- : action === 'routing-remove'
41551
- ? 'Only the Token Harness-owned CCR rule/profile is eligible for removal.'
41552
- : routeMode === 'shadow'
41553
- ? 'Shadow mode is the safe default: it classifies requests locally and records decisions without changing the selected model.'
41554
- : 'Conservative mode is opt-in: only high-confidence simple requests may request one already-configured simple model; safety-gated requests pass through unchanged.',
41555
- ),
41556
- );
41557
- for (const change of data.changes || []) {
41558
- const item = node('article', undefined, 'preview-change');
41559
- item.append(node('h3', change.title), node('p', change.description));
41560
- $('modal-content').append(item);
41561
- }
41562
- for (const notice of data.notices || [])
41563
- $('modal-content').append(node('p', notice, 'notice-row'));
41564
- if (action !== 'routing-metrics')
41565
- $('modal-content').append(
41566
- messageBox(
41567
- 'Safety boundary',
41568
- 'Token Harness owns only its exact CCR runtime/rule/profile. Provider credentials remain in CCR, native Claude Code/Codex endpoints are not rewritten, and every mutation still requires this explicit approval.',
41569
- 'safe',
41570
- ),
41571
- );
41572
- $('modal-actions').replaceChildren(modalClose(data.ticket ? 'Cancel' : 'Done'));
41573
- if (data.ticket)
41574
- $('modal-actions').append(
41575
- actionButton(
41576
- action === 'routing-remove'
41577
- ? 'Remove managed routing'
41578
- : routeMode === 'conservative'
41579
- ? 'Apply conservative routing step'
41580
- : 'Apply shadow routing step',
41581
- () => applyTicket(data.ticket),
41582
- ),
41583
- );
41584
- })
41585
- .catch(error => {
41586
- if (run !== modalRun) return;
41587
- $('modal-error').textContent = error.message;
41588
- $('modal-error').hidden = false;
41589
- $('modal-actions').replaceChildren(modalClose('Close'));
41590
- })
41591
- .finally(() => {
41592
- if (run === modalRun) setBusy(false, false);
41593
- loadActivity();
41594
- });
41595
- }
41596
-
41597
- function manageRouting(harness) {
41598
- if (busy) return;
41599
- const run = modal('Smart Model Routing · ' + agentName(harness));
41600
- $('modal-content').append(
41601
- messageBox(
41602
- 'Shadow-first routing',
41603
- 'The classifier runs locally with deterministic heuristics. It needs no paid routing API and no local LLM. The reviewed CCR gateway is used only as the local request-routing surface.',
41604
- ),
41605
- messageBox(
41606
- 'How to use it',
41607
- 'Start with Shadow. After CCR is prepared, review Shadow again to install the exact rule/profile. Launch the agent through the CCR profile shown after configuration. Conservative mode is optional and requires an exact simple model already configured in CCR.',
41608
- ),
41609
- messageBox(
41610
- 'What is measured',
41611
- 'Routing decisions are kept separate from optimizer token savings. A cheaper model is not counted as saved quota unless paired quality and allowance evidence proves it.',
41612
- 'safe',
41613
- ),
41614
- );
41615
- $('modal-actions').append(
41616
- modalClose('Close'),
41617
- actionButton(
41618
- 'View 30-day activity',
41619
- () => reviewRoutingAction(harness, 'routing-metrics', 'shadow', run),
41620
- 'secondary',
41621
- ),
41622
- actionButton(
41623
- 'Remove managed rule',
41624
- () => reviewRoutingAction(harness, 'routing-remove', 'shadow', run),
41625
- 'secondary',
41626
- ),
41627
- actionButton(
41628
- 'Review conservative setup',
41629
- () => reviewRoutingAction(harness, 'routing-setup', 'conservative', run),
41630
- 'secondary',
41631
- ),
41632
- actionButton(
41633
- 'Review shadow setup',
41634
- () => reviewRoutingAction(harness, 'routing-setup', 'shadow', run),
41635
- ),
41636
- );
41637
- }
41638
-
41639
- function renderRouting() {
41640
- const root = $('routing-overview');
41641
- if (!root) return;
41642
- root.replaceChildren();
41643
- const agents = activeAgents();
41644
- if (!agents.length) {
41645
- root.append(
41646
- messageBox(
41647
- 'No supported coding agent detected',
41648
- 'Smart Model Routing is available for Claude Code and Codex after the agent is detected.',
41649
- 'warn',
41650
- ),
41651
- );
41652
- return;
41653
- }
41654
- for (const agent of agents) {
41655
- const row = node('article', undefined, 'maintenance-row');
41656
- const copy = node('div');
41657
- copy.append(
41658
- node('strong', agent.name),
41659
- node(
41660
- 'p',
41661
- 'Optional request routing through a local CCR profile. Shadow mode never changes models; conservative mode is explicit and safety-gated.',
41662
- 'caption',
41663
- ),
41664
- );
41665
- row.append(copy, actionButton('Manage routing', () => manageRouting(agent.id), 'secondary'));
41666
- root.append(row);
41667
- }
41668
- }
41669
-
41670
38662
  function renderMaintenance() {
41671
38663
  const root = $('maintenance-actions');
41672
38664
  root.replaceChildren();
@@ -41731,7 +38723,6 @@ var init_guided_product_client = __esm({
41731
38723
  renderManagedSetup();
41732
38724
  renderExperimental();
41733
38725
  renderTuning();
41734
- renderRouting();
41735
38726
  renderMaintenance();
41736
38727
  }
41737
38728
 
@@ -42775,11 +39766,6 @@ ${GUIDE_CANDIDATE_READINESS_JS}`;
42775
39766
  <details class="disclosure"><summary>Remove Token Harness-managed configuration</summary><p class="caption">Removal is reviewed first. Token Harness removes only configuration it owns; installed provider software and user-owned configuration may remain.</p><div id="managed-removal-actions" class="maintenance-list"><p class="caption">Checking managed ownership\u2026</p></div></details>
42776
39767
  </section>
42777
39768
 
42778
- <section class="setup-step" id="smart-routing">
42779
- <div class="section-title"><div><h2>Smart Model Routing</h2><p>Optional shadow-first request routing for Claude Code and Codex. Shadow mode observes locally without changing models; conservative routing is an explicit opt-in.</p></div></div>
42780
- <div id="routing-overview" class="maintenance-list"><p class="empty">Checking supported coding agents\u2026</p></div>
42781
- </section>
42782
-
42783
39769
  <section class="setup-step" id="maintenance">
42784
39770
  <div class="section-title"><div><h2>Health and updates</h2><p>These are maintenance actions, not onboarding steps. Setup already performs its own safety checks.</p></div></div>
42785
39771
  <div id="maintenance-actions" class="maintenance-list"><p class="empty">Checking\u2026</p></div>
@@ -43089,9 +40075,9 @@ function createGuideHandler(input) {
43089
40075
  return;
43090
40076
  }
43091
40077
  send(404, '{"error":"Not found"}');
43092
- } catch (error2) {
43093
- send(error2 instanceof GuideError ? error2.status : 500, JSON.stringify({
43094
- error: error2 instanceof GuideError ? error2.message : "The operation could not finish. No automatic retry was made. Refresh and check the current state."
40078
+ } catch (error) {
40079
+ send(error instanceof GuideError ? error.status : 500, JSON.stringify({
40080
+ error: error instanceof GuideError ? error.message : "The operation could not finish. No automatic retry was made. Refresh and check the current state."
43095
40081
  }));
43096
40082
  }
43097
40083
  };
@@ -43118,7 +40104,7 @@ var init_guided_http = __esm({
43118
40104
  });
43119
40105
 
43120
40106
  // apps/cli/dist/src/commands/rtk-hook-proxy.js
43121
- function isRecord7(value3) {
40107
+ function isRecord5(value3) {
43122
40108
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
43123
40109
  }
43124
40110
  function shellQuote(value3) {
@@ -43130,7 +40116,7 @@ function powershellQuote(value3) {
43130
40116
  function toolNameFromInput(input, harness) {
43131
40117
  try {
43132
40118
  const parsed = JSON.parse(input);
43133
- if (!isRecord7(parsed))
40119
+ if (!isRecord5(parsed))
43134
40120
  return null;
43135
40121
  const name2 = parsed["tool_name"] ?? parsed["toolName"];
43136
40122
  if (typeof name2 === "string")
@@ -43158,13 +40144,13 @@ function attributeRtkHookResponse(stdout, input, databasePath, harness) {
43158
40144
  } catch {
43159
40145
  return stdout;
43160
40146
  }
43161
- if (!isRecord7(response))
40147
+ if (!isRecord5(response))
43162
40148
  return stdout;
43163
40149
  const hookOutput = response["hookSpecificOutput"];
43164
- if (!isRecord7(hookOutput))
40150
+ if (!isRecord5(hookOutput))
43165
40151
  return stdout;
43166
40152
  const updatedInput = hookOutput["updatedInput"];
43167
- if (!isRecord7(updatedInput) || typeof updatedInput["command"] !== "string")
40153
+ if (!isRecord5(updatedInput) || typeof updatedInput["command"] !== "string")
43168
40154
  return stdout;
43169
40155
  const attributed = withDatabaseEnvironment(updatedInput["command"], databasePath, toolNameFromInput(input, harness));
43170
40156
  if (attributed === null)
@@ -43216,7 +40202,7 @@ __export(main_exports, {
43216
40202
  });
43217
40203
  import process5 from "node:process";
43218
40204
  import { createServer } from "node:http";
43219
- import { randomBytes as randomBytes3 } from "node:crypto";
40205
+ import { randomBytes as randomBytes2 } from "node:crypto";
43220
40206
  async function runAsDatabaseReader(argv2) {
43221
40207
  if (argv2[0] !== SQLITE_CHILD_FLAG)
43222
40208
  return false;
@@ -43429,8 +40415,8 @@ async function runUi(options, baseOptions) {
43429
40415
  let initial;
43430
40416
  try {
43431
40417
  initial = await collectDashboard(baseOptions);
43432
- } catch (error2) {
43433
- const message = error2 instanceof Error ? error2.message : String(error2);
40418
+ } catch (error) {
40419
+ const message = error instanceof Error ? error.message : String(error);
43434
40420
  if (options.json) {
43435
40421
  process5.stdout.write(serializeEnvelope(toEnvelope(commandResult({
43436
40422
  command: "ui",
@@ -43504,8 +40490,8 @@ async function runUi(options, baseOptions) {
43504
40490
  server.once("error", reject);
43505
40491
  server.listen(options.port, "127.0.0.1", () => resolve());
43506
40492
  });
43507
- } catch (error2) {
43508
- process5.stderr.write(`Token Harness dashboard could not listen locally: ${error2 instanceof Error ? error2.message : String(error2)}
40493
+ } catch (error) {
40494
+ process5.stderr.write(`Token Harness dashboard could not listen locally: ${error instanceof Error ? error.message : String(error)}
43509
40495
  `);
43510
40496
  return EXIT_CODES["internal-error"];
43511
40497
  }
@@ -43532,7 +40518,7 @@ async function runGuidedUi(options, base) {
43532
40518
  }
43533
40519
  return result6;
43534
40520
  };
43535
- const service = new GuideService(guideCall, () => Date.now(), () => randomBytes3(32).toString("hex"), async (harness) => {
40521
+ const service = new GuideService(guideCall, () => Date.now(), () => randomBytes2(32).toString("hex"), async (harness) => {
43536
40522
  if (base.adapters === null || base.adapters === void 0) {
43537
40523
  return {
43538
40524
  state: "unavailable",
@@ -43547,7 +40533,7 @@ async function runGuidedUi(options, base) {
43547
40533
  harness
43548
40534
  });
43549
40535
  });
43550
- const token = randomBytes3(32).toString("hex");
40536
+ const token = randomBytes2(32).toString("hex");
43551
40537
  let authority = "";
43552
40538
  const server = createServer(createGuideHandler({
43553
40539
  service,