token-harness 0.1.21 → 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.21";
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,376 +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 configRouter(config) {
22267
- if (!isRecord6(config) || !isRecord6(config["Router"]) || !Array.isArray(config["Router"]["rules"])) {
22268
- return null;
22269
- }
22270
- return {
22271
- config,
22272
- router: config["Router"],
22273
- rules: config["Router"]["rules"]
22274
- };
22275
- }
22276
- function addCcrSmartRoutingRule(config, rule) {
22277
- const current = configRouter(config);
22278
- if (current === null)
22279
- return null;
22280
- const existing = current.rules.find((item) => isRecord6(item) && item["id"] === rule["id"]);
22281
- if (existing !== void 0)
22282
- return isExactCcrSmartRoutingRule(existing, rule) ? current.config : null;
22283
- return {
22284
- ...current.config,
22285
- Router: { ...current.router, rules: [rule, ...current.rules] }
22286
- };
22287
- }
22288
- function removeOwnedCcrSmartRoutingRule(config, ruleId, expected) {
22289
- const current = configRouter(config);
22290
- if (current === null)
22291
- return null;
22292
- const matches = current.rules.filter((item) => isRecord6(item) && item["id"] === ruleId);
22293
- if (matches.length !== 1 || !isExactCcrSmartRoutingRule(matches[0], expected))
22294
- return null;
22295
- return {
22296
- ...current.config,
22297
- Router: {
22298
- ...current.router,
22299
- rules: current.rules.filter((item) => !(isRecord6(item) && item["id"] === ruleId))
22300
- }
22301
- };
22302
- }
22303
- function readCcrVersion(value3) {
22304
- if (!isRecord6(value3) || typeof value3["version"] !== "string")
22305
- return null;
22306
- return /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(value3["version"]) ? value3["version"] : null;
22307
- }
22308
- function reduceCcrSessionUsage(value3, expectedSessionId, expectedAgent, since, until) {
22309
- if (!isRecord6(value3) || value3["requestScanTruncated"] === true || !isRecord6(value3["selectedSession"])) {
22310
- return null;
22311
- }
22312
- const selected = value3["selectedSession"];
22313
- if (!isRecord6(selected["session"]) || selected["session"]["agent"] !== expectedAgent || selected["session"]["id"] !== `${expectedAgent}:${expectedSessionId}` || !Array.isArray(selected["requests"])) {
22314
- return null;
22315
- }
22316
- const start = Date.parse(since);
22317
- const end = Date.parse(until);
22318
- if (!Number.isFinite(start) || !Number.isFinite(end) || end < start)
22319
- return null;
22320
- const byModel = /* @__PURE__ */ new Map();
22321
- for (const item of selected["requests"]) {
22322
- if (!isRecord6(item) || item["sessionId"] !== expectedSessionId)
22323
- continue;
22324
- const createdAt = typeof item["createdAt"] === "string" ? Date.parse(item["createdAt"]) : Number.NaN;
22325
- if (!Number.isFinite(createdAt) || createdAt < start || createdAt > end)
22326
- continue;
22327
- const model = item["model"];
22328
- const inputTokens = numberField(item["inputTokens"]);
22329
- const outputTokens = numberField(item["outputTokens"]);
22330
- const cacheReadTokens = numberField(item["cacheReadTokens"]);
22331
- const cacheWriteTokens = numberField(item["cacheWriteTokens"]);
22332
- const totalTokens = numberField(item["totalTokens"]);
22333
- if (typeof model !== "string" || !MODEL_ID.test(model) || inputTokens === null || outputTokens === null || cacheReadTokens === null || cacheWriteTokens === null || totalTokens === null) {
22334
- continue;
22335
- }
22336
- const current = byModel.get(model) ?? {
22337
- model,
22338
- requestCount: 0,
22339
- inputTokens: 0,
22340
- outputTokens: 0,
22341
- cacheReadTokens: 0,
22342
- cacheWriteTokens: 0,
22343
- totalTokens: 0,
22344
- recordedCostUsd: 0
22345
- };
22346
- const recordedCostUsd = costField(item["costUsd"]);
22347
- current.requestCount += 1;
22348
- current.inputTokens += inputTokens;
22349
- current.outputTokens += outputTokens;
22350
- current.cacheReadTokens += cacheReadTokens;
22351
- current.cacheWriteTokens += cacheWriteTokens;
22352
- current.totalTokens += totalTokens;
22353
- if (recordedCostUsd === null)
22354
- current.recordedCostUsd = null;
22355
- else if (current.recordedCostUsd !== null)
22356
- current.recordedCostUsd += recordedCostUsd;
22357
- byModel.set(model, current);
22358
- }
22359
- const rows = [...byModel.values()].sort((left, right) => left.model.localeCompare(right.model));
22360
- if (rows.length === 0)
22361
- return null;
22362
- return {
22363
- sessionId: expectedSessionId,
22364
- requestCount: rows.reduce((total, row2) => total + row2.requestCount, 0),
22365
- inputTokens: rows.reduce((total, row2) => total + row2.inputTokens, 0),
22366
- outputTokens: rows.reduce((total, row2) => total + row2.outputTokens, 0),
22367
- cacheReadTokens: rows.reduce((total, row2) => total + row2.cacheReadTokens, 0),
22368
- cacheWriteTokens: rows.reduce((total, row2) => total + row2.cacheWriteTokens, 0),
22369
- totalTokens: rows.reduce((total, row2) => total + row2.totalTokens, 0),
22370
- recordedCostUsd: rows.length === 0 || rows.some((row2) => row2.recordedCostUsd === null) ? null : rows.reduce((total, row2) => total + (row2.recordedCostUsd ?? 0), 0),
22371
- byModel: rows
22372
- };
22373
- }
22374
- function ccrAgentForHarness(harness) {
22375
- return HARNESS_AGENTS[harness];
22376
- }
22377
- 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;
22378
- var init_ccr_management = __esm({
22379
- "packages/adapters/dist/src/routing/ccr-management.js"() {
22380
- "use strict";
22381
- CCR_REVIEWED_VERSION = "3.1.1";
22382
- CCR_ROUTING_RULE_ID_PREFIX = "token-harness-smart-routing";
22383
- CCR_ROUTING_RULE_API_VERSION = 1;
22384
- CCR_ROUTING_RULE_TIMEOUT_MS = 2e3;
22385
- CcrManagementError = class extends Error {
22386
- failure;
22387
- constructor(failure) {
22388
- super(`CCR management request failed (${failure})`);
22389
- this.name = "CcrManagementError";
22390
- this.failure = failure;
22391
- }
22392
- };
22393
- DEFAULT_CCR_WEB_URL = "http://127.0.0.1:3458";
22394
- CCR_RPC_PATH = "/api/ccr/rpc";
22395
- CCR_RESPONSE_MAX_BYTES = 8 * 1024 * 1024;
22396
- LOCAL_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
22397
- MODEL_ID = /^[A-Za-z0-9_.:/@+ -]{1,160}$/;
22398
- HARNESS_AGENTS = { claude: "claude-code", codex: "codex" };
22399
- CcrManagementClient = class {
22400
- baseUrl;
22401
- token;
22402
- fetcher;
22403
- constructor(options = {}) {
22404
- const baseUrl = resolveCcrManagementUrl(options.baseUrl);
22405
- if (baseUrl === null)
22406
- throw new CcrManagementError("endpoint-invalid");
22407
- const token = options.authToken?.trim();
22408
- if (!token || token.length > 512)
22409
- throw new CcrManagementError("token-missing");
22410
- this.baseUrl = baseUrl;
22411
- this.token = token;
22412
- this.fetcher = options.fetcher ?? globalThis.fetch;
22413
- }
22414
- async call(method, args = []) {
22415
- let response;
22416
- try {
22417
- response = await this.fetcher(`${this.baseUrl}${CCR_RPC_PATH}`, {
22418
- method: "POST",
22419
- redirect: "error",
22420
- signal: AbortSignal.timeout(8e3),
22421
- headers: {
22422
- "content-type": "application/json",
22423
- "x-ccr-web-auth": this.token
22424
- },
22425
- body: JSON.stringify({ method, args })
22426
- });
22427
- } catch {
22428
- throw new CcrManagementError("unreachable");
22429
- }
22430
- if (response.status === 401 || response.status === 403) {
22431
- throw new CcrManagementError("unauthorized");
22432
- }
22433
- if (response.status === 404)
22434
- throw new CcrManagementError("method-unavailable");
22435
- if (!response.ok)
22436
- throw new CcrManagementError("request-failed");
22437
- const contentLength = Number(response.headers.get("content-length"));
22438
- if (Number.isFinite(contentLength) && contentLength > CCR_RESPONSE_MAX_BYTES) {
22439
- throw new CcrManagementError("invalid-response");
22440
- }
22441
- let payload;
22442
- try {
22443
- const text3 = await response.text();
22444
- if (new TextEncoder().encode(text3).byteLength > CCR_RESPONSE_MAX_BYTES) {
22445
- throw new CcrManagementError("invalid-response");
22446
- }
22447
- payload = JSON.parse(text3);
22448
- } catch (error2) {
22449
- if (error2 instanceof CcrManagementError)
22450
- throw error2;
22451
- throw new CcrManagementError("invalid-response");
22452
- }
22453
- if (!isRecord6(payload))
22454
- throw new CcrManagementError("invalid-response");
22455
- if (payload["ok"] !== true) {
22456
- const message = isRecord6(payload["error"]) ? payload["error"]["message"] : void 0;
22457
- if (typeof message === "string" && /unknown ccr web rpc method/i.test(message)) {
22458
- throw new CcrManagementError("method-unavailable");
22459
- }
22460
- throw new CcrManagementError("request-failed");
22461
- }
22462
- return payload["value"];
22463
- }
22464
- };
22465
- }
22466
- });
22467
-
22468
21696
  // packages/adapters/dist/src/index.js
22469
21697
  var init_src3 = __esm({
22470
21698
  "packages/adapters/dist/src/index.js"() {
@@ -22472,8 +21700,6 @@ var init_src3 = __esm({
22472
21700
  init_harnesses();
22473
21701
  init_providers();
22474
21702
  init_rtk_plan();
22475
- init_ccr_smart_routing();
22476
- init_ccr_management();
22477
21703
  }
22478
21704
  });
22479
21705
 
@@ -22826,16 +22052,6 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22826
22052
  tasksLeft: null,
22827
22053
  contextSnapshot: null,
22828
22054
  nativePolicy: false,
22829
- routingScript: false,
22830
- routingMetrics: false,
22831
- routingStatus: false,
22832
- routingMode: "shadow",
22833
- routingSimpleModel: null,
22834
- routingPrune: false,
22835
- routingCcrConfigure: false,
22836
- routingCcrRollback: false,
22837
- routingCcrUpdate: false,
22838
- routingCcrUsage: false,
22839
22055
  agentSkill: false,
22840
22056
  verbose: false,
22841
22057
  yes: false
@@ -22875,22 +22091,6 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22875
22091
  options.nativePolicy = true;
22876
22092
  if (name2 === "--agent-skill")
22877
22093
  options.agentSkill = true;
22878
- if (name2 === "--script")
22879
- options.routingScript = true;
22880
- if (name2 === "--route-metrics")
22881
- options.routingMetrics = true;
22882
- if (name2 === "--route-status")
22883
- options.routingStatus = true;
22884
- if (name2 === "--prune")
22885
- options.routingPrune = true;
22886
- if (name2 === "--configure-ccr")
22887
- options.routingCcrConfigure = true;
22888
- if (name2 === "--rollback-ccr")
22889
- options.routingCcrRollback = true;
22890
- if (name2 === "--update-ccr")
22891
- options.routingCcrUpdate = true;
22892
- if (name2 === "--ccr-usage")
22893
- options.routingCcrUsage = true;
22894
22094
  if (name2 === "--verbose")
22895
22095
  options.verbose = true;
22896
22096
  continue;
@@ -23096,30 +22296,6 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
23096
22296
  }
23097
22297
  break;
23098
22298
  }
23099
- case "--route-simple-model":
23100
- if (!/^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(value3) || !value3.includes("/")) {
23101
- diagnostics.push(diagnostic({
23102
- severity: "error",
23103
- code: "invalid-routing-model",
23104
- message: "Routing model must be an exact CCR Provider/model identifier",
23105
- remediation: "Choose a configured model such as Codex API/gpt-5.6-luna"
23106
- }));
23107
- } else {
23108
- options.routingSimpleModel = value3;
23109
- }
23110
- break;
23111
- case "--route-mode":
23112
- if (value3 !== "shadow" && value3 !== "conservative") {
23113
- diagnostics.push(diagnostic({
23114
- severity: "error",
23115
- code: "invalid-routing-mode",
23116
- message: `Routing mode ${JSON.stringify(value3)} is not supported`,
23117
- remediation: "Use --route-mode shadow or --route-mode conservative"
23118
- }));
23119
- } else {
23120
- options.routingMode = value3;
23121
- }
23122
- break;
23123
22299
  case "--context-snapshot":
23124
22300
  options.contextSnapshot = value3;
23125
22301
  break;
@@ -23190,7 +22366,6 @@ var init_argv = __esm({
23190
22366
  "optimize",
23191
22367
  "plan",
23192
22368
  "rollback",
23193
- "routing",
23194
22369
  "setup",
23195
22370
  "status",
23196
22371
  "stack-review",
@@ -23219,25 +22394,9 @@ var init_argv = __esm({
23219
22394
  "--profile",
23220
22395
  "--reserve",
23221
22396
  "--tasks-left",
23222
- "--route-mode",
23223
- "--route-simple-model",
23224
22397
  "--context-snapshot"
23225
22398
  ]);
23226
- BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
23227
- "--json",
23228
- "--native-policy",
23229
- "--agent-skill",
23230
- "--verbose",
23231
- "--yes",
23232
- "--script",
23233
- "--route-metrics",
23234
- "--route-status",
23235
- "--prune",
23236
- "--configure-ccr",
23237
- "--rollback-ccr",
23238
- "--update-ccr",
23239
- "--ccr-usage"
23240
- ]);
22399
+ BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--json", "--native-policy", "--agent-skill", "--verbose", "--yes"]);
23241
22400
  }
23242
22401
  });
23243
22402
 
@@ -23287,12 +22446,12 @@ function parseGitNexusIndexReadiness(output) {
23287
22446
  if (receipt["schemaVersion"] !== 1)
23288
22447
  return { state: "invalid", detail: null };
23289
22448
  const status = safeGitNexusStatusLabel(receipt["status"]);
23290
- const error2 = safeGitNexusStatusLabel(receipt["error"]);
22449
+ const error = safeGitNexusStatusLabel(receipt["error"]);
23291
22450
  if (status === "up-to-date" && receipt["error"] === void 0) {
23292
22451
  return { state: "up-to-date", detail: null };
23293
22452
  }
23294
22453
  if (receipt["error"] !== void 0)
23295
- return { state: "not-ready", detail: error2 };
22454
+ return { state: "not-ready", detail: error };
23296
22455
  if (receipt["status"] !== void 0)
23297
22456
  return { state: "not-ready", detail: status };
23298
22457
  return { state: "invalid", detail: null };
@@ -25429,15 +24588,15 @@ async function readOptimizationHistory(context) {
25429
24588
  continue;
25430
24589
  result6.scannedBenchmarks += 1;
25431
24590
  for (const variant of ["baseline", "optimized"]) {
25432
- const receiptPath4 = fs.join(directory, `${variant}.json`);
25433
- if (await fs.stat(receiptPath4) === null)
24591
+ const receiptPath3 = fs.join(directory, `${variant}.json`);
24592
+ if (await fs.stat(receiptPath3) === null)
25434
24593
  continue;
25435
24594
  const capture = parseTaskBenchmarkCapture(await read(fs.join(directory, `${variant}.capture.json`)));
25436
24595
  if (!capture.ok)
25437
24596
  return result6;
25438
24597
  if (capture.capture.projectId !== project)
25439
24598
  continue;
25440
- const receipt = parseTaskBenchmarkReceipt(await read(receiptPath4));
24599
+ const receipt = parseTaskBenchmarkReceipt(await read(receiptPath3));
25441
24600
  if (!receipt.ok)
25442
24601
  return result6;
25443
24602
  const start = capture.capture;
@@ -26730,12 +25889,12 @@ async function verifyManagedIntegrationPostconditions(context, integrations) {
26730
25889
  remediation: runtimeProblem?.remediation ?? "Check that the newly installed provider executable is on PATH, then review a fresh setup preview"
26731
25890
  }));
26732
25891
  }
26733
- } catch (error2) {
25892
+ } catch (error) {
26734
25893
  diagnostics.push(diagnostic({
26735
25894
  severity: "error",
26736
25895
  code: "managed-setup-postcondition-unavailable",
26737
25896
  subject: integration.providerId,
26738
- 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)}`,
26739
25898
  remediation: "Refresh and inspect the provider runtime before retrying"
26740
25899
  }));
26741
25900
  }
@@ -26789,13 +25948,13 @@ async function loadStoredPlan(context, planId) {
26789
25948
  throw new TypeError("A stored plan must be a JSON object");
26790
25949
  }
26791
25950
  return { stored: parsed, diagnostic: null };
26792
- } catch (error2) {
25951
+ } catch (error) {
26793
25952
  return {
26794
25953
  stored: null,
26795
25954
  diagnostic: diagnostic({
26796
25955
  severity: "error",
26797
25956
  code: "plan-unreadable",
26798
- 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)}`,
26799
25958
  path,
26800
25959
  remediation: "Run `token-harness plan` to compute a new one"
26801
25960
  })
@@ -27184,596 +26343,6 @@ var init_benchmark2 = __esm({
27184
26343
  }
27185
26344
  });
27186
26345
 
27187
- // apps/cli/dist/src/commands/ccr-runtime.js
27188
- import { randomBytes as randomBytes2 } from "node:crypto";
27189
- function ccrRuntimeRoot(context) {
27190
- return context.adapters.fs.join(context.stateRoot, "smart-routing", "ccr");
27191
- }
27192
- function runtimeReceiptPath(context) {
27193
- return context.adapters.fs.join(ccrRuntimeRoot(context), "runtime.json");
27194
- }
27195
- function runtimeTokenPath(context) {
27196
- return context.adapters.fs.join(ccrRuntimeRoot(context), "web-auth-token");
27197
- }
27198
- function packagePrefix(context, version3) {
27199
- return context.adapters.fs.join(ccrRuntimeRoot(context), "versions", version3);
27200
- }
27201
- function ccrExecutable(context, prefix) {
27202
- const suffix = context.platform.os === "windows" && !context.platform.isWsl ? ".cmd" : "";
27203
- return context.adapters.fs.join(prefix, "node_modules", ".bin", `ccr${suffix}`);
27204
- }
27205
- function parseJsonRecord(value3) {
27206
- return typeof value3 === "object" && value3 !== null && !Array.isArray(value3) ? value3 : null;
27207
- }
27208
- async function readManagedCcrRuntime(context) {
27209
- if (context.adapters === null || context.stateRoot === null)
27210
- return null;
27211
- try {
27212
- const bytes = await context.adapters.fs.readFile(runtimeReceiptPath(context));
27213
- const receipt = parseJsonRecord(JSON.parse(new TextDecoder().decode(bytes)));
27214
- 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") {
27215
- return null;
27216
- }
27217
- const expectedPrefix = packagePrefix(context, receipt["version"]);
27218
- if (receipt["installPrefix"] !== expectedPrefix || receipt["executablePath"] !== ccrExecutable(context, expectedPrefix) || resolveCcrManagementUrl(receipt["managementEndpoint"]) !== receipt["managementEndpoint"]) {
27219
- return null;
27220
- }
27221
- return receipt;
27222
- } catch {
27223
- return null;
27224
- }
27225
- }
27226
- async function readPrivateToken(context) {
27227
- if (context.adapters === null || context.stateRoot === null)
27228
- return null;
27229
- try {
27230
- const value3 = new TextDecoder().decode(await context.adapters.fs.readFile(runtimeTokenPath(context))).trim();
27231
- return /^[A-Za-z0-9_-]{32,128}$/.test(value3) ? value3 : null;
27232
- } catch {
27233
- return null;
27234
- }
27235
- }
27236
- async function resolveManagedCcr(context) {
27237
- const envToken = context.env?.["CCR_WEB_AUTH_TOKEN"]?.trim();
27238
- const envUrl = context.env?.["CCR_WEB_URL"];
27239
- if (envToken) {
27240
- const endpoint = resolveCcrManagementUrl(envUrl);
27241
- if (endpoint === null)
27242
- throw new CcrManagementError("endpoint-invalid");
27243
- return { kind: "external", endpoint, token: envToken };
27244
- }
27245
- if (envUrl !== void 0 && envUrl.trim() !== "")
27246
- throw new CcrManagementError("token-missing");
27247
- const receipt = await readManagedCcrRuntime(context);
27248
- const token = await readPrivateToken(context);
27249
- if (receipt !== null && token !== null) {
27250
- return {
27251
- kind: "managed",
27252
- endpoint: receipt.managementEndpoint,
27253
- token,
27254
- receipt
27255
- };
27256
- }
27257
- const service = await readCcrServiceState(context);
27258
- if (service !== null)
27259
- return service;
27260
- return { kind: "unavailable" };
27261
- }
27262
- async function readCcrServiceState(context) {
27263
- if (context.adapters === null || context.home === null)
27264
- return null;
27265
- const windows = context.platform.os === "windows" && !context.platform.isWsl;
27266
- const appData = context.env?.["APPDATA"];
27267
- 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");
27268
- try {
27269
- const bytes = await context.adapters.fs.readFile(context.adapters.fs.join(configDirectory, "service.json"));
27270
- const state = parseJsonRecord(JSON.parse(new TextDecoder().decode(bytes)));
27271
- if (typeof state?.["url"] !== "string")
27272
- return null;
27273
- const serviceUrl = new URL(state["url"]);
27274
- const endpoint = resolveCcrManagementUrl(serviceUrl.origin);
27275
- const token = serviceUrl.searchParams.get("ccr_web_token")?.trim();
27276
- if (endpoint === null || token === void 0 || !/^[A-Za-z0-9_-]{32,128}$/.test(token))
27277
- return null;
27278
- const client = new CcrManagementClient({
27279
- baseUrl: endpoint,
27280
- authToken: token,
27281
- ...context.ccrFetch === void 0 ? {} : { fetcher: context.ccrFetch }
27282
- });
27283
- const version3 = readCcrVersion(await client.call("getAppInfo"));
27284
- if (version3 === null)
27285
- return null;
27286
- return { kind: "external", endpoint, token };
27287
- } catch {
27288
- return null;
27289
- }
27290
- }
27291
- async function localManagementPortIsOccupied(context) {
27292
- const fetcher = context.ccrFetch ?? globalThis.fetch;
27293
- try {
27294
- const response = await fetcher(`http://127.0.0.1:${String(DEFAULT_WEB_PORT)}/api/ccr/rpc`, {
27295
- method: "POST",
27296
- redirect: "error",
27297
- signal: AbortSignal.timeout(1e3),
27298
- headers: { "content-type": "application/json" },
27299
- body: JSON.stringify({ method: "getAppInfo", args: [] })
27300
- });
27301
- return response.status >= 100 && response.status <= 599;
27302
- } catch {
27303
- return false;
27304
- }
27305
- }
27306
- function lifecycleError(code, message, remediation) {
27307
- return commandResult({
27308
- command: "routing",
27309
- exitCode: EXIT_CODES["problems-found"],
27310
- diagnostics: [diagnostic({ severity: "error", code, message, remediation })]
27311
- });
27312
- }
27313
- function lifecyclePreview(action, state, context, receipt) {
27314
- const fs = context.adapters.fs;
27315
- const prefix = packagePrefix(context, CCR_REVIEWED_VERSION);
27316
- const executable = ccrExecutable(context, prefix);
27317
- const endpoint = receipt?.managementEndpoint ?? `http://127.0.0.1:${String(DEFAULT_WEB_PORT)}`;
27318
- return commandResult({
27319
- command: "routing",
27320
- exitCode: EXIT_CODES.ok,
27321
- data: {
27322
- kind: "ccr-lifecycle",
27323
- action,
27324
- state,
27325
- version: CCR_REVIEWED_VERSION,
27326
- packagePath: prefix,
27327
- executablePath: executable,
27328
- managementEndpoint: endpoint
27329
- },
27330
- diagnostics: [
27331
- diagnostic({
27332
- severity: "info",
27333
- code: `ccr-${action}-preview`,
27334
- 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`,
27335
- path: fs.join(ccrRuntimeRoot(context), "runtime.json"),
27336
- 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"
27337
- })
27338
- ]
27339
- });
27340
- }
27341
- function successfulProcess(outcome2) {
27342
- return outcome2.failure === null && outcome2.exitCode === 0;
27343
- }
27344
- function managementPortFromOutput(output) {
27345
- const match = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/i.exec(output);
27346
- const port = Number(match?.[1]);
27347
- return Number.isInteger(port) && port > 0 && port <= 65535 ? port : DEFAULT_WEB_PORT;
27348
- }
27349
- async function packageVersionAt(context, prefix) {
27350
- try {
27351
- const path = context.adapters.fs.join(prefix, "node_modules", "@musistudio", "claude-code-router", "package.json");
27352
- const parsed = parseJsonRecord(JSON.parse(new TextDecoder().decode(await context.adapters.fs.readFile(path))));
27353
- return typeof parsed?.["version"] === "string" ? parsed["version"] : null;
27354
- } catch {
27355
- return null;
27356
- }
27357
- }
27358
- async function runCcrExecutable(context, executable, args, token) {
27359
- const env = { CCR_WEB_AUTH_TOKEN: token };
27360
- const simpleModel = context.env?.["TOKEN_HARNESS_ROUTING_SIMPLE_MODEL"]?.trim();
27361
- if (simpleModel && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(simpleModel)) {
27362
- env["TOKEN_HARNESS_ROUTING_SIMPLE_MODEL"] = simpleModel;
27363
- }
27364
- return context.adapters.runner.run({
27365
- executable,
27366
- args,
27367
- cwd: context.projectRoot,
27368
- env,
27369
- timeoutMs: 45e3,
27370
- maxOutputBytes: 128 * 1024,
27371
- secretValues: [token]
27372
- });
27373
- }
27374
- async function startAndVerify(context, receipt, token, expectedVersion = CCR_REVIEWED_VERSION) {
27375
- const start = await runCcrExecutable(context, receipt.executablePath, [
27376
- "start",
27377
- "--daemon",
27378
- "--host",
27379
- "127.0.0.1",
27380
- "--port",
27381
- String(DEFAULT_WEB_PORT),
27382
- "--no-open",
27383
- "--gateway"
27384
- ], token);
27385
- if (!successfulProcess(start))
27386
- return null;
27387
- const port = managementPortFromOutput(`${start.stdout}
27388
- ${start.stderr}`);
27389
- const endpoint = resolveCcrManagementUrl(`http://127.0.0.1:${String(port)}`);
27390
- if (endpoint === null)
27391
- return null;
27392
- const client = new CcrManagementClient({
27393
- baseUrl: endpoint,
27394
- authToken: token,
27395
- ...context.ccrFetch === void 0 ? {} : { fetcher: context.ccrFetch }
27396
- });
27397
- try {
27398
- const version3 = readCcrVersion(await client.call("getAppInfo"));
27399
- const gateway = parseJsonRecord(await client.call("getGatewayStatus"));
27400
- if (version3 !== expectedVersion || gateway?.["state"] !== "running")
27401
- return null;
27402
- return { endpoint, version: version3 };
27403
- } catch {
27404
- return null;
27405
- }
27406
- }
27407
- async function verifyManagedService(context, receipt, token) {
27408
- const client = new CcrManagementClient({
27409
- baseUrl: receipt.managementEndpoint,
27410
- authToken: token,
27411
- ...context.ccrFetch === void 0 ? {} : { fetcher: context.ccrFetch }
27412
- });
27413
- try {
27414
- const version3 = readCcrVersion(await client.call("getAppInfo"));
27415
- const gateway = parseJsonRecord(await client.call("getGatewayStatus"));
27416
- if (version3 === null)
27417
- return null;
27418
- return { version: version3, running: gateway?.["state"] === "running" };
27419
- } catch {
27420
- return null;
27421
- }
27422
- }
27423
- async function ensureManagedCcrRuntime(input) {
27424
- const { context } = input;
27425
- if (context.adapters === null || context.stateRoot === null) {
27426
- return {
27427
- kind: "result",
27428
- 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")
27429
- };
27430
- }
27431
- const nodeMajor = Number(/^v?(\d+)/.exec(context.platform.nodeVersion ?? "")?.[1]);
27432
- if (!Number.isInteger(nodeMajor) || nodeMajor < 22) {
27433
- return {
27434
- kind: "result",
27435
- result: lifecycleError("ccr-node-version-unsupported", "CCR CLI requires Node.js 22 or newer", "Run Token Harness with Node.js 22+ and retry")
27436
- };
27437
- }
27438
- const fs = context.adapters.fs;
27439
- const root = ccrRuntimeRoot(context);
27440
- const prior = await readManagedCcrRuntime(context);
27441
- const token = await readPrivateToken(context);
27442
- if (prior === null && await fs.stat(runtimeReceiptPath(context)) !== null) {
27443
- return {
27444
- kind: "result",
27445
- 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")
27446
- };
27447
- }
27448
- if (prior === null && await fs.stat(runtimeTokenPath(context)) !== null) {
27449
- return {
27450
- kind: "result",
27451
- 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")
27452
- };
27453
- }
27454
- if (prior !== null && token === null) {
27455
- return {
27456
- kind: "result",
27457
- 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")
27458
- };
27459
- }
27460
- if (prior === null && await localManagementPortIsOccupied(context)) {
27461
- return {
27462
- kind: "result",
27463
- 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")
27464
- };
27465
- }
27466
- if (input.action === "update" && prior === null) {
27467
- return {
27468
- kind: "result",
27469
- 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")
27470
- };
27471
- }
27472
- if (prior?.version === CCR_REVIEWED_VERSION) {
27473
- if (token === null)
27474
- return {
27475
- kind: "result",
27476
- 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")
27477
- };
27478
- const current = await verifyManagedService(context, prior, token);
27479
- if (current?.version === CCR_REVIEWED_VERSION && current.running) {
27480
- return input.action === "update" ? { kind: "result", result: lifecyclePreview("update", "already-current", context, prior) } : {
27481
- kind: "ready",
27482
- endpoint: prior.managementEndpoint,
27483
- token,
27484
- changed: false,
27485
- lifecycleAction: "start",
27486
- packagePath: prior.installPrefix,
27487
- executablePath: prior.executablePath
27488
- };
27489
- }
27490
- }
27491
- if (!context.confirmed) {
27492
- const action = prior === null ? "install" : prior.version === CCR_REVIEWED_VERSION ? "start" : "update";
27493
- return {
27494
- kind: "result",
27495
- result: lifecyclePreview(action, "preview", context, prior ?? void 0)
27496
- };
27497
- }
27498
- const runtimeToken = token ?? randomBytes2(32).toString("base64url");
27499
- const prefix = packagePrefix(context, CCR_REVIEWED_VERSION);
27500
- const executable = ccrExecutable(context, prefix);
27501
- const existingPrefixStat = await fs.stat(prefix);
27502
- if (prior === null && existingPrefixStat !== null) {
27503
- return {
27504
- kind: "result",
27505
- 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")
27506
- };
27507
- }
27508
- let changed = false;
27509
- if (await packageVersionAt(context, prefix) !== CCR_REVIEWED_VERSION) {
27510
- const npm = context.adapters.resolveExecutables?.("npm") ?? [];
27511
- if (npm.length === 0 && context.adapters.resolveExecutables !== void 0) {
27512
- return {
27513
- kind: "result",
27514
- result: lifecycleError("ccr-npm-not-found", "npm could not be resolved, so CCR was not installed", "Install npm with Node.js 22+ and retry")
27515
- };
27516
- }
27517
- if (prior !== null) {
27518
- const stop = await runCcrExecutable(context, prior.executablePath, ["stop"], runtimeToken);
27519
- if (!successfulProcess(stop)) {
27520
- return {
27521
- kind: "result",
27522
- 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")
27523
- };
27524
- }
27525
- }
27526
- const install = await context.adapters.runner.run({
27527
- executable: "npm",
27528
- args: [
27529
- "install",
27530
- "--prefix",
27531
- prefix,
27532
- "--no-save",
27533
- "--package-lock=true",
27534
- `${CCR_PACKAGE}@${CCR_REVIEWED_VERSION}`
27535
- ],
27536
- cwd: context.projectRoot,
27537
- timeoutMs: 10 * 6e4,
27538
- maxOutputBytes: 256 * 1024
27539
- });
27540
- if (!successfulProcess(install) || await packageVersionAt(context, prefix) !== CCR_REVIEWED_VERSION) {
27541
- const restored = prior !== null && await startAndVerify(context, prior, runtimeToken, prior.version) !== null;
27542
- return {
27543
- kind: "result",
27544
- 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")
27545
- };
27546
- }
27547
- changed = true;
27548
- }
27549
- const provisional = {
27550
- schemaVersion: 1,
27551
- version: CCR_REVIEWED_VERSION,
27552
- installPrefix: prefix,
27553
- executablePath: executable,
27554
- managementEndpoint: prior?.managementEndpoint ?? `http://127.0.0.1:${String(DEFAULT_WEB_PORT)}`,
27555
- installedAt: prior?.installedAt ?? context.now()
27556
- };
27557
- try {
27558
- await fs.createDirectory(root);
27559
- await fs.writeFile(runtimeTokenPath(context), new TextEncoder().encode(`${runtimeToken}
27560
- `), "0600");
27561
- } catch {
27562
- return {
27563
- kind: "result",
27564
- 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")
27565
- };
27566
- }
27567
- try {
27568
- await fs.writeFile(runtimeReceiptPath(context), new TextEncoder().encode(`${JSON.stringify(provisional, null, 2)}
27569
- `), "0600");
27570
- } catch {
27571
- return {
27572
- kind: "result",
27573
- 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")
27574
- };
27575
- }
27576
- const started = await startAndVerify(context, provisional, runtimeToken);
27577
- if (started === null) {
27578
- if (prior !== null) {
27579
- const restored = await startAndVerify(context, prior, runtimeToken, prior.version) !== null;
27580
- if (!restored)
27581
- return {
27582
- kind: "result",
27583
- 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")
27584
- };
27585
- await fs.writeFile(runtimeReceiptPath(context), new TextEncoder().encode(`${JSON.stringify(prior, null, 2)}
27586
- `), "0600");
27587
- }
27588
- return {
27589
- kind: "result",
27590
- 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")
27591
- };
27592
- }
27593
- const active = { ...provisional, managementEndpoint: started.endpoint };
27594
- try {
27595
- await fs.writeFile(runtimeReceiptPath(context), new TextEncoder().encode(`${JSON.stringify(active, null, 2)}
27596
- `), "0600");
27597
- } catch {
27598
- return {
27599
- kind: "result",
27600
- 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")
27601
- };
27602
- }
27603
- changed = true;
27604
- return {
27605
- kind: "ready",
27606
- endpoint: started.endpoint,
27607
- token: runtimeToken,
27608
- changed,
27609
- lifecycleAction: prior === null ? "install" : prior.version === CCR_REVIEWED_VERSION ? "start" : "update",
27610
- packagePath: prefix,
27611
- executablePath: executable
27612
- };
27613
- }
27614
- var CCR_PACKAGE, DEFAULT_WEB_PORT;
27615
- var init_ccr_runtime = __esm({
27616
- "apps/cli/dist/src/commands/ccr-runtime.js"() {
27617
- "use strict";
27618
- init_src3();
27619
- init_src();
27620
- CCR_PACKAGE = "@musistudio/claude-code-router";
27621
- DEFAULT_WEB_PORT = 3458;
27622
- }
27623
- });
27624
-
27625
- // apps/cli/dist/src/commands/routing-usage.js
27626
- function combineSessionUsage(rows) {
27627
- const byModel = /* @__PURE__ */ new Map();
27628
- for (const row2 of rows) {
27629
- for (const model of row2.byModel) {
27630
- const current = byModel.get(model.model) ?? {
27631
- ...model,
27632
- requestCount: 0,
27633
- inputTokens: 0,
27634
- outputTokens: 0,
27635
- cacheReadTokens: 0,
27636
- cacheWriteTokens: 0,
27637
- totalTokens: 0,
27638
- recordedCostUsd: 0
27639
- };
27640
- current.requestCount += model.requestCount;
27641
- current.inputTokens += model.inputTokens;
27642
- current.outputTokens += model.outputTokens;
27643
- current.cacheReadTokens += model.cacheReadTokens;
27644
- current.cacheWriteTokens += model.cacheWriteTokens;
27645
- current.totalTokens += model.totalTokens;
27646
- if (current.recordedCostUsd === null || model.recordedCostUsd === null) {
27647
- current.recordedCostUsd = null;
27648
- } else {
27649
- current.recordedCostUsd += model.recordedCostUsd;
27650
- }
27651
- byModel.set(model.model, current);
27652
- }
27653
- }
27654
- const models = [...byModel.values()].sort((left, right) => left.model.localeCompare(right.model));
27655
- const allCostsKnown = rows.length > 0 && rows.every((row2) => row2.recordedCostUsd !== null);
27656
- return {
27657
- status: rows.length === 0 ? "unavailable" : "observed",
27658
- sessionCount: rows.length,
27659
- observedSessionCount: rows.length,
27660
- requestCount: rows.reduce((total, row2) => total + row2.requestCount, 0),
27661
- inputTokens: rows.reduce((total, row2) => total + row2.inputTokens, 0),
27662
- outputTokens: rows.reduce((total, row2) => total + row2.outputTokens, 0),
27663
- cacheReadTokens: rows.reduce((total, row2) => total + row2.cacheReadTokens, 0),
27664
- cacheWriteTokens: rows.reduce((total, row2) => total + row2.cacheWriteTokens, 0),
27665
- totalTokens: rows.reduce((total, row2) => total + row2.totalTokens, 0),
27666
- recordedCostUsd: allCostsKnown ? rows.reduce((total, row2) => total + (row2.recordedCostUsd ?? 0), 0) : null,
27667
- byModel: models
27668
- };
27669
- }
27670
- async function observeCcrUsage(input) {
27671
- const unique = /* @__PURE__ */ new Map();
27672
- for (const event of input.events) {
27673
- if (event.sessionId) {
27674
- unique.set(`${event.harnessId}:${event.sessionId}`, {
27675
- harness: event.harnessId,
27676
- sessionId: event.sessionId
27677
- });
27678
- }
27679
- }
27680
- const entries = [...unique.values()];
27681
- const bounded = entries.slice(0, 20);
27682
- if (bounded.length === 0) {
27683
- return {
27684
- usage: {
27685
- status: "unavailable",
27686
- sessionCount: 0,
27687
- observedSessionCount: 0,
27688
- requestCount: 0,
27689
- inputTokens: 0,
27690
- outputTokens: 0,
27691
- cacheReadTokens: 0,
27692
- cacheWriteTokens: 0,
27693
- totalTokens: 0,
27694
- recordedCostUsd: null,
27695
- byModel: []
27696
- },
27697
- failedSessions: 0
27698
- };
27699
- }
27700
- const managed = await resolveManagedCcr(input.context);
27701
- if (managed.kind === "unavailable")
27702
- throw new Error("CCR management credentials are unavailable");
27703
- const client = new CcrManagementClient({
27704
- baseUrl: managed.endpoint,
27705
- authToken: managed.token,
27706
- ...input.context.ccrFetch === void 0 ? {} : { fetcher: input.context.ccrFetch }
27707
- });
27708
- const appInfo = await client.call("getAppInfo");
27709
- if (readCcrVersion(appInfo) !== CCR_REVIEWED_VERSION) {
27710
- throw new Error("CCR version is outside the reviewed metadata interface");
27711
- }
27712
- const rows = [];
27713
- let failedSessions = entries.length - bounded.length;
27714
- for (const item of bounded) {
27715
- try {
27716
- const response = await client.call("getAgentAnalysis", [
27717
- {
27718
- agent: ccrAgentForHarness(item.harness),
27719
- sessionAgent: ccrAgentForHarness(item.harness),
27720
- sessionId: item.sessionId,
27721
- range: "7d"
27722
- }
27723
- ]);
27724
- const usage2 = reduceCcrSessionUsage(response, item.sessionId, ccrAgentForHarness(item.harness), input.since, input.until);
27725
- if (usage2 === null)
27726
- failedSessions += 1;
27727
- else
27728
- rows.push(usage2);
27729
- } catch {
27730
- failedSessions += 1;
27731
- }
27732
- }
27733
- const usage = combineSessionUsage(rows);
27734
- if (failedSessions > 0 && usage.status !== "unavailable")
27735
- usage.status = "partial";
27736
- return { usage: { ...usage, sessionCount: entries.length }, failedSessions };
27737
- }
27738
- async function loadSmartRoutingEventsForWindow(input) {
27739
- const fs = input.context.adapters?.fs;
27740
- const stateRoot = input.context.stateRoot;
27741
- if (fs === void 0 || stateRoot === null)
27742
- return [];
27743
- const directory = fs.join(stateRoot, "smart-routing");
27744
- let names;
27745
- try {
27746
- names = (await fs.readDirectory(directory)).filter((name2) => new RegExp(`^${SMART_ROUTING_EVENT_PREFIX}\\d{13}-[a-z0-9]+\\.json$`).test(name2)).sort();
27747
- } catch {
27748
- return [];
27749
- }
27750
- const start = Date.parse(input.since);
27751
- const end = Date.parse(input.until);
27752
- if (!Number.isFinite(start) || !Number.isFinite(end) || end < start)
27753
- return [];
27754
- const events = [];
27755
- for (const name2 of names) {
27756
- try {
27757
- const value3 = JSON.parse(new TextDecoder().decode(await fs.readFile(fs.join(directory, name2))));
27758
- if (!isSmartRoutingDecisionEvent(value3) || value3.harnessId !== input.harness)
27759
- continue;
27760
- const timestamp = Date.parse(value3.timestamp);
27761
- if (Number.isFinite(timestamp) && timestamp >= start && timestamp <= end)
27762
- events.push(value3);
27763
- } catch {
27764
- }
27765
- }
27766
- return events;
27767
- }
27768
- var init_routing_usage = __esm({
27769
- "apps/cli/dist/src/commands/routing-usage.js"() {
27770
- "use strict";
27771
- init_src3();
27772
- init_ccr_runtime();
27773
- init_src();
27774
- }
27775
- });
27776
-
27777
26346
  // apps/cli/dist/src/commands/benchmark-capture.js
27778
26347
  function statePaths(context, benchmarkId, variant) {
27779
26348
  if (context.adapters === null || context.stateRoot === null)
@@ -28123,59 +26692,6 @@ async function runBenchmarkFinish(context) {
28123
26692
  const budget = budgetResult.data?.harnesses.find((item) => item.harnessId === parsed.capture.harnessId);
28124
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;
28125
26694
  const finishContextObservation = contextResult.data?.harnesses.find((item) => item.harnessId === parsed.capture.harnessId);
28126
- const routingHarness = parsed.capture.harnessId === CLAUDE12 ? "claude" : "codex";
28127
- const routingEvents = await loadSmartRoutingEventsForWindow({
28128
- context,
28129
- harness: routingHarness,
28130
- since: parsed.capture.startedAt,
28131
- until: completedAt
28132
- });
28133
- let ccrUsage;
28134
- let ccrUsageDiagnostics = [];
28135
- if (routingEvents.length > 0) {
28136
- try {
28137
- const observed = await observeCcrUsage({
28138
- context,
28139
- events: routingEvents,
28140
- since: parsed.capture.startedAt,
28141
- until: completedAt
28142
- });
28143
- ccrUsage = { schemaVersion: 1, ...observed.usage };
28144
- if (observed.usage.status !== "observed") {
28145
- ccrUsageDiagnostics = [
28146
- diagnostic({
28147
- severity: "warning",
28148
- code: "benchmark-ccr-usage-partial",
28149
- message: `CCR request usage was ${observed.usage.status} for this capture`,
28150
- remediation: "Check CCR Web RPC logging and keep one harness session active during the benchmark task"
28151
- })
28152
- ];
28153
- }
28154
- } catch {
28155
- ccrUsage = {
28156
- schemaVersion: 1,
28157
- status: "unavailable",
28158
- sessionCount: 0,
28159
- observedSessionCount: 0,
28160
- requestCount: 0,
28161
- inputTokens: 0,
28162
- outputTokens: 0,
28163
- cacheReadTokens: 0,
28164
- cacheWriteTokens: 0,
28165
- totalTokens: 0,
28166
- recordedCostUsd: null,
28167
- byModel: []
28168
- };
28169
- ccrUsageDiagnostics = [
28170
- diagnostic({
28171
- severity: "warning",
28172
- code: "benchmark-ccr-usage-unavailable",
28173
- message: "CCR request usage could not be read; the task receipt is still valid without it",
28174
- remediation: "Set the local CCR Web RPC token and verify CCR 3.1.1 request logging before the next paired capture"
28175
- })
28176
- ];
28177
- }
28178
- }
28179
26695
  const completed = completeTaskBenchmarkCapture(parsed.capture, {
28180
26696
  completedAt,
28181
26697
  usageAfter: budget?.windows ?? [],
@@ -28184,8 +26700,7 @@ async function runBenchmarkFinish(context) {
28184
26700
  failedAttempts,
28185
26701
  localUsage,
28186
26702
  contextAtFinish: taskBenchmarkContextSnapshot(finishContextObservation),
28187
- policyAtFinish: benchmarkPolicySnapshot(finishContextObservation),
28188
- ...ccrUsage === void 0 ? {} : { ccrUsage }
26703
+ policyAtFinish: benchmarkPolicySnapshot(finishContextObservation)
28189
26704
  });
28190
26705
  if (!completed.ok) {
28191
26706
  return commandResult({
@@ -28230,8 +26745,7 @@ async function runBenchmarkFinish(context) {
28230
26745
  diagnostics: [
28231
26746
  ...budgetResult.diagnostics,
28232
26747
  ...historyResult.diagnostics,
28233
- ...contextResult.diagnostics,
28234
- ...ccrUsageDiagnostics
26748
+ ...contextResult.diagnostics
28235
26749
  ]
28236
26750
  });
28237
26751
  }
@@ -28243,7 +26757,6 @@ var init_benchmark_capture = __esm({
28243
26757
  init_budget2();
28244
26758
  init_context_cost2();
28245
26759
  init_history2();
28246
- init_routing_usage();
28247
26760
  CLAUDE12 = harnessId("claude");
28248
26761
  CODEX12 = harnessId("codex");
28249
26762
  CAPTURE_HARNESSES = /* @__PURE__ */ new Set([CLAUDE12, CODEX12]);
@@ -28457,11 +26970,11 @@ async function readJsonArtifact(context, path) {
28457
26970
  }
28458
26971
  }
28459
26972
  async function gitNexusBaselinePurity(context, benchmarkId) {
28460
- const receiptPath4 = benchmarkArtifactPath(context, benchmarkId, "baseline.json");
26973
+ const receiptPath3 = benchmarkArtifactPath(context, benchmarkId, "baseline.json");
28461
26974
  const capturePath = benchmarkArtifactPath(context, benchmarkId, "baseline.capture.json");
28462
- if (receiptPath4 === null || capturePath === null)
26975
+ if (receiptPath3 === null || capturePath === null)
28463
26976
  return "absent";
28464
- const rawReceipt = await readJsonArtifact(context, receiptPath4);
26977
+ const rawReceipt = await readJsonArtifact(context, receiptPath3);
28465
26978
  if (rawReceipt.state !== "absent") {
28466
26979
  if (rawReceipt.state === "invalid")
28467
26980
  return "invalid";
@@ -30676,1120 +29189,6 @@ var init_rollback = __esm({
30676
29189
  }
30677
29190
  });
30678
29191
 
30679
- // apps/cli/dist/src/commands/smart-routing.js
30680
- import { createHash as createHash3 } from "node:crypto";
30681
- function safeGatewayState(value3) {
30682
- if (!isJsonRecord(value3) || typeof value3["state"] !== "string")
30683
- return "unknown";
30684
- const state = value3["state"];
30685
- return ["running", "stopped", "starting", "stopping", "error"].includes(state) ? state : "unknown";
30686
- }
30687
- function isSmartRoutingHarness(value3) {
30688
- return value3 === "claude" || value3 === "codex";
30689
- }
30690
- function error(code, message, remediation) {
30691
- return commandResult({
30692
- command: "routing",
30693
- exitCode: EXIT_CODES["usage-error"],
30694
- diagnostics: [diagnostic({ severity: "error", code, message, remediation })]
30695
- });
30696
- }
30697
- function ccrFailure(errorValue) {
30698
- if (!(errorValue instanceof CcrManagementError)) {
30699
- return {
30700
- code: "ccr-management-failed",
30701
- message: "CCR management operation failed",
30702
- remediation: "Check the local CCR management service and repeat the command"
30703
- };
30704
- }
30705
- const rows = {
30706
- "endpoint-invalid": {
30707
- code: "ccr-endpoint-not-local",
30708
- message: "CCR management URL must use a loopback address on this machine",
30709
- remediation: "Use CCR_WEB_URL=http://127.0.0.1:3458 or another local loopback port"
30710
- },
30711
- "token-missing": {
30712
- code: "ccr-auth-token-required",
30713
- message: "CCR Web RPC authentication is not configured for Token Harness",
30714
- 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"
30715
- },
30716
- unreachable: {
30717
- code: "ccr-management-unreachable",
30718
- message: "The local CCR management service could not be reached",
30719
- remediation: "Start CCR Web Management on this machine and set CCR_WEB_URL to its loopback address"
30720
- },
30721
- unauthorized: {
30722
- code: "ccr-management-unauthorized",
30723
- message: "CCR rejected the local management token",
30724
- remediation: "Use the same CCR_WEB_AUTH_TOKEN in the CCR service and Token Harness process"
30725
- },
30726
- "method-unavailable": {
30727
- code: "ccr-management-api-unsupported",
30728
- message: "This CCR build does not expose the reviewed management operation",
30729
- remediation: `Use CCR ${CCR_REVIEWED_VERSION} for managed setup, or add the exported rule through CCR Routing manually`
30730
- },
30731
- "config-drift": {
30732
- code: "ccr-config-changed-during-operation",
30733
- message: "CCR configuration changed while Token Harness was preparing the rule update",
30734
- remediation: "Review the latest CCR configuration and retry from a fresh preview"
30735
- },
30736
- "invalid-response": {
30737
- code: "ccr-management-response-invalid",
30738
- message: "CCR returned an unsupported or oversized management response",
30739
- remediation: "Check the CCR version and retry with a local CCR service"
30740
- },
30741
- "request-failed": {
30742
- code: "ccr-management-operation-failed",
30743
- message: "CCR could not complete the management operation",
30744
- remediation: "Review CCR status and retry; Token Harness did not print CCR response contents"
30745
- }
30746
- };
30747
- return rows[errorValue.failure];
30748
- }
30749
- function isJsonRecord(value3) {
30750
- return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
30751
- }
30752
- function receiptPath3(context, harness) {
30753
- const fs = context.adapters.fs;
30754
- return fs.join(stateDirectory(context), `ccr-ownership-${harness}.json`);
30755
- }
30756
- function scriptDirectory(context) {
30757
- return context.adapters.fs.join(stateDirectory(context), "ccr-scripts");
30758
- }
30759
- function scriptPath(context, harness) {
30760
- return context.adapters.fs.join(scriptDirectory(context), `smart-routing-${harness}.js`);
30761
- }
30762
- function stateDirectory(context) {
30763
- return context.adapters.fs.join(context.stateRoot, "smart-routing");
30764
- }
30765
- function scriptHash(script) {
30766
- return createHash3("sha256").update(script, "utf8").digest("hex");
30767
- }
30768
- async function readOwnership(context, harness) {
30769
- const path = receiptPath3(context, harness);
30770
- try {
30771
- const bytes = await context.adapters.fs.readFile(path);
30772
- const value3 = JSON.parse(new TextDecoder().decode(bytes));
30773
- 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) && (value3["simpleModel"] === void 0 || typeof value3["simpleModel"] === "string" && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(value3["simpleModel"])) && typeof value3["installedAt"] === "string") {
30774
- return value3;
30775
- }
30776
- } catch {
30777
- return null;
30778
- }
30779
- return null;
30780
- }
30781
- async function writeJson4(context, path, value3) {
30782
- await context.adapters.fs.writeFile(path, new TextEncoder().encode(`${JSON.stringify(value3, null, 2)}
30783
- `));
30784
- }
30785
- async function cleanupUnappliedCcrFiles(context, harness, ownership) {
30786
- const fs = context.adapters.fs;
30787
- const receipt = await readOwnership(context, harness);
30788
- if (receipt !== null && receipt.status === "pending" && receipt.scriptPath === ownership.scriptPath && receipt.scriptSha256 === ownership.scriptSha256) {
30789
- await fs.remove(receiptPath3(context, harness)).catch(() => void 0);
30790
- }
30791
- const scriptBytes = await fs.readFile(ownership.scriptPath).catch(() => null);
30792
- if (scriptBytes !== null && scriptHash(new TextDecoder().decode(scriptBytes)) === ownership.scriptSha256) {
30793
- await fs.remove(ownership.scriptPath).catch(() => void 0);
30794
- }
30795
- }
30796
- async function readCcrState(context) {
30797
- const managed = await resolveManagedCcr(context);
30798
- if (managed.kind === "unavailable")
30799
- throw new CcrManagementError("token-missing");
30800
- const client = new CcrManagementClient({
30801
- baseUrl: managed.endpoint,
30802
- authToken: managed.token,
30803
- ...context.ccrFetch === void 0 ? {} : { fetcher: context.ccrFetch }
30804
- });
30805
- const [appInfo, configValue, gatewayValue] = await Promise.all([
30806
- client.call("getAppInfo"),
30807
- client.call("getConfig"),
30808
- client.call("getGatewayStatus")
30809
- ]);
30810
- const version3 = readCcrVersion(appInfo);
30811
- if (version3 !== CCR_REVIEWED_VERSION) {
30812
- throw new CcrManagementError("method-unavailable");
30813
- }
30814
- if (!isJsonRecord(configValue) || !isJsonRecord(configValue["Router"])) {
30815
- throw new CcrManagementError("invalid-response");
30816
- }
30817
- const gatewayState = safeGatewayState(gatewayValue);
30818
- return { client, endpoint: managed.endpoint, version: version3, config: configValue, gatewayState };
30819
- }
30820
- function validateRouteRuleResult(value3) {
30821
- return isJsonRecord(value3) && value3["ok"] === true;
30822
- }
30823
- function profileSlug(value3) {
30824
- return value3.toLowerCase().replace(/[^a-z0-9_.-]+/g, "-").replace(/^-+|-+$/g, "") || "provider";
30825
- }
30826
- function planCcrProfile(config, harness, selectedModel) {
30827
- const profileContainer = isJsonRecord(config["profile"]) ? config["profile"] : null;
30828
- const profiles = profileContainer && Array.isArray(profileContainer["profiles"]) ? profileContainer["profiles"] : null;
30829
- if (profileContainer === null || profiles === null || profileContainer["enabled"] === false) {
30830
- return {
30831
- profile: null,
30832
- profileContainer,
30833
- conflict: false,
30834
- reason: "CCR Agent Profiles are unavailable or disabled"
30835
- };
30836
- }
30837
- const providerName3 = harness === "claude" ? "Claude Code API" : "Codex API";
30838
- const protocol = harness === "claude" ? "anthropic_messages" : "openai_responses";
30839
- const providers = Array.isArray(config["Providers"]) ? config["Providers"] : [];
30840
- 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)));
30841
- if (matches.length !== 1 || !isJsonRecord(matches[0])) {
30842
- return {
30843
- profile: null,
30844
- profileContainer,
30845
- conflict: false,
30846
- 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`
30847
- };
30848
- }
30849
- const provider = matches[0];
30850
- const models = provider["models"].filter((model2) => typeof model2 === "string" && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(model2));
30851
- let model;
30852
- const selectedModelValue = selectedModel?.trim();
30853
- if (selectedModelValue) {
30854
- if (!selectedModelValue.startsWith(`${providerName3}/`)) {
30855
- return {
30856
- profile: null,
30857
- profileContainer,
30858
- conflict: false,
30859
- reason: "TOKEN_HARNESS_ROUTING_PROFILE_MODEL must name a model from the matching CCR provider"
30860
- };
30861
- }
30862
- const selectedId = selectedModelValue.slice(providerName3.length + 1);
30863
- if (models.includes(selectedId))
30864
- model = selectedId;
30865
- else
30866
- return {
30867
- profile: null,
30868
- profileContainer,
30869
- conflict: false,
30870
- reason: "TOKEN_HARNESS_ROUTING_PROFILE_MODEL is not present in the matching CCR provider model list"
30871
- };
30872
- }
30873
- const providerDefault = typeof provider["defaultModel"] === "string" ? provider["defaultModel"] : typeof provider["model"] === "string" ? provider["model"] : null;
30874
- if (model === void 0 && providerDefault !== null) {
30875
- const providerDefaultId = providerDefault.startsWith(`${providerName3}/`) ? providerDefault.slice(providerName3.length + 1) : providerDefault;
30876
- if (models.includes(providerDefaultId))
30877
- model = providerDefaultId;
30878
- }
30879
- if (model === void 0 && models.length === 1)
30880
- model = models[0];
30881
- if (model === void 0) {
30882
- return {
30883
- profile: null,
30884
- profileContainer,
30885
- conflict: false,
30886
- reason: `${providerName3} has multiple models; set TOKEN_HARNESS_ROUTING_PROFILE_MODEL to the exact Provider/model you want as the CCR CLI default`
30887
- };
30888
- }
30889
- const id = OWNED_PROFILE_IDS[harness];
30890
- const profile = {
30891
- agent: harness === "claude" ? "claude-code" : "codex",
30892
- enabled: true,
30893
- id,
30894
- model: `${providerName3}/${model}`,
30895
- name: `Token Harness ${harness === "claude" ? "Claude Code" : "Codex"}`,
30896
- providerId: typeof provider["id"] === "string" ? provider["id"] : profileSlug(providerName3),
30897
- providerName: providerName3,
30898
- scope: "ccr",
30899
- surface: "cli"
30900
- };
30901
- const existing = profiles.filter((item) => isJsonRecord(item) && item["id"] === id);
30902
- if (existing.length > 0) {
30903
- return {
30904
- profile,
30905
- profileContainer,
30906
- conflict: true,
30907
- reason: "A CCR Agent Profile already uses the Token Harness profile id"
30908
- };
30909
- }
30910
- return { profile, profileContainer, conflict: false, reason: null };
30911
- }
30912
- function configuredCcrModels(config) {
30913
- const providers = Array.isArray(config["Providers"]) ? config["Providers"] : [];
30914
- const models = providers.flatMap((provider) => {
30915
- if (!isJsonRecord(provider) || typeof provider["name"] !== "string" || !Array.isArray(provider["models"]))
30916
- return [];
30917
- return provider["models"].flatMap((model) => typeof model === "string" && /^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(model) ? [`${provider["name"]}/${model}`] : []);
30918
- });
30919
- return [...new Set(models)].sort((left, right) => left.localeCompare(right)).slice(0, 200);
30920
- }
30921
- function configuredCcrModel(config, requested) {
30922
- const candidate = requested?.trim();
30923
- if (candidate === void 0 || !/^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(candidate))
30924
- return null;
30925
- const providers = Array.isArray(config["Providers"]) ? config["Providers"] : [];
30926
- 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;
30927
- }
30928
- function stableJson2(value3) {
30929
- if (Array.isArray(value3))
30930
- return `[${value3.map(stableJson2).join(",")}]`;
30931
- if (!isJsonRecord(value3))
30932
- return JSON.stringify(value3);
30933
- return `{${Object.keys(value3).sort().map((key) => `${JSON.stringify(key)}:${stableJson2(value3[key])}`).join(",")}}`;
30934
- }
30935
- function profileRows(config) {
30936
- const container = config["profile"];
30937
- return isJsonRecord(container) && Array.isArray(container["profiles"]) ? container["profiles"] : [];
30938
- }
30939
- function withCcrProfile(config, profile) {
30940
- const container = config["profile"];
30941
- if (!isJsonRecord(container) || container["enabled"] === false || !Array.isArray(container["profiles"])) {
30942
- return null;
30943
- }
30944
- if (container["profiles"].some((item) => isJsonRecord(item) && item["id"] === profile["id"])) {
30945
- return null;
30946
- }
30947
- return {
30948
- ...config,
30949
- profile: { ...container, profiles: [profile, ...container["profiles"]] }
30950
- };
30951
- }
30952
- function withoutOwnedCcrProfile(config, profileId, expectedSha256) {
30953
- const container = config["profile"];
30954
- if (!isJsonRecord(container) || !Array.isArray(container["profiles"]))
30955
- return config;
30956
- const matches = container["profiles"].filter((item) => isJsonRecord(item) && item["id"] === profileId);
30957
- if (matches.length === 0)
30958
- return config;
30959
- if (matches.length !== 1 || scriptHash(stableJson2(matches[0])) !== expectedSha256)
30960
- return null;
30961
- return {
30962
- ...config,
30963
- profile: {
30964
- ...container,
30965
- profiles: container["profiles"].filter((item) => !(isJsonRecord(item) && item["id"] === profileId))
30966
- }
30967
- };
30968
- }
30969
- function isExpectedCcrProfile(value3, expected) {
30970
- if (!isJsonRecord(value3))
30971
- return false;
30972
- const requiredKeys = [
30973
- "agent",
30974
- "enabled",
30975
- "id",
30976
- "model",
30977
- "name",
30978
- "providerId",
30979
- "providerName",
30980
- "scope",
30981
- "surface"
30982
- ];
30983
- return requiredKeys.every((key) => stableJson2(value3[key]) === stableJson2(expected[key]));
30984
- }
30985
- function ccrLaunchCommand(harness) {
30986
- return `ccr "Token Harness ${harness === "claude" ? "Claude Code" : "Codex"}"`;
30987
- }
30988
- function profilePlanDiagnostic(plan6) {
30989
- if (plan6.reason === null)
30990
- return null;
30991
- return diagnostic({
30992
- severity: "warning",
30993
- code: "ccr-profile-not-created",
30994
- message: plan6.reason,
30995
- remediation: `Resolve the CCR profile setup requirement and rerun routing setup; provider login/import and credential changes remain explicit CCR actions`
30996
- });
30997
- }
30998
- function routingStatusResult(harnessId2, state, detail2, gatewayState = "unknown", profileId = null, simpleModel = null, availableModels = []) {
30999
- return commandResult({
31000
- command: "routing",
31001
- exitCode: EXIT_CODES.ok,
31002
- data: {
31003
- kind: "status",
31004
- harnessId: harnessId2,
31005
- state,
31006
- mode: state === "shadow" || state === "conservative" ? state : null,
31007
- gatewayState,
31008
- profileId,
31009
- launchCommand: profileId === null ? null : ccrLaunchCommand(harnessId2),
31010
- simpleModel,
31011
- availableModels,
31012
- detail: detail2
31013
- }
31014
- });
31015
- }
31016
- async function smartRoutingStatus(context) {
31017
- const fs = context.adapters?.fs;
31018
- if (fs === void 0 || context.stateRoot === null || !isSmartRoutingHarness(context.harness)) {
31019
- return error("routing-status-context-required", "Smart Model Routing status needs local state and a Claude Code or Codex harness", "Pass `--harness claude` or `--harness codex` from the local Token Harness installation");
31020
- }
31021
- const harnessId2 = context.harness;
31022
- const owned = await readOwnership(context, harnessId2);
31023
- let ccr;
31024
- try {
31025
- ccr = await readCcrState(context);
31026
- } catch {
31027
- return owned === null ? routingStatusResult(harnessId2, "off", "No Token Harness-owned routing configuration is active.") : routingStatusResult(harnessId2, "attention", "Token Harness has routing ownership state, but the local CCR service cannot currently be verified.");
31028
- }
31029
- const path = scriptPath(context, harnessId2);
31030
- const expectedRule = createCcrSmartRoutingRule(harnessId2, path);
31031
- const router = ccr.config["Router"];
31032
- const rules = isJsonRecord(router) && Array.isArray(router["rules"]) ? router["rules"] : [];
31033
- const matching = rules.filter((item) => isJsonRecord(item) && item["id"] === ccrSmartRoutingRuleId(harnessId2));
31034
- if (owned === null) {
31035
- return matching.length === 0 ? routingStatusResult(harnessId2, "off", "Smart Model Routing is off for this coding agent.", ccr.gatewayState, null, null, configuredCcrModels(ccr.config)) : routingStatusResult(harnessId2, "attention", "A routing rule uses the Token Harness id, but no matching ownership receipt exists.", ccr.gatewayState, null, null, configuredCcrModels(ccr.config));
31036
- }
31037
- const bytes = await fs.readFile(owned.scriptPath).catch(() => null);
31038
- const scriptMatches = bytes !== null && scriptHash(new TextDecoder().decode(bytes)) === owned.scriptSha256;
31039
- const ruleMatches = matching.length === 1 && isExactCcrSmartRoutingRule(matching[0], expectedRule);
31040
- let profileMatches = true;
31041
- if (owned.profileId !== void 0) {
31042
- const profile = profileRows(ccr.config).find((item) => isJsonRecord(item) && item["id"] === owned.profileId);
31043
- profileMatches = isJsonRecord(profile) && owned.profileSha256 !== void 0 && scriptHash(stableJson2(profile)) === owned.profileSha256;
31044
- }
31045
- if (!scriptMatches || !ruleMatches || !profileMatches) {
31046
- return routingStatusResult(harnessId2, "attention", "The owned routing rule, script or launcher profile no longer matches the recorded Token Harness state.", ccr.gatewayState, owned.profileId ?? null, owned.simpleModel ?? null, configuredCcrModels(ccr.config));
31047
- }
31048
- return routingStatusResult(harnessId2, owned.mode, owned.mode === "shadow" ? "Shadow routing is configured. Requests keep their selected model while local routing decisions are recorded." : "Conservative routing is configured. Eligible high-confidence simple requests may use the configured simple model.", ccr.gatewayState, owned.profileId ?? null, owned.simpleModel ?? null, configuredCcrModels(ccr.config));
31049
- }
31050
- async function ccrConfiguration(context) {
31051
- const fs = context.adapters?.fs;
31052
- if (fs === void 0 || context.stateRoot === null || !isSmartRoutingHarness(context.harness)) {
31053
- 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");
31054
- }
31055
- const mode = context.routingMode ?? "shadow";
31056
- const harnessId2 = context.harness;
31057
- const ruleId = ccrSmartRoutingRuleId(harnessId2);
31058
- const path = scriptPath(context, harnessId2);
31059
- const telemetryDirectory = stateDirectory(context);
31060
- let ccr;
31061
- try {
31062
- ccr = await readCcrState(context);
31063
- } catch (errorValue) {
31064
- const issue = ccrFailure(errorValue);
31065
- return commandResult({
31066
- command: "routing",
31067
- exitCode: EXIT_CODES["problems-found"],
31068
- diagnostics: [diagnostic({ severity: "error", ...issue })]
31069
- });
31070
- }
31071
- const requestedProfileModel = context.env?.["TOKEN_HARNESS_ROUTING_PROFILE_MODEL"];
31072
- const profilePlan = planCcrProfile(ccr.config, harnessId2, requestedProfileModel);
31073
- const profileModelWarning = requestedProfileModel?.trim() && (profilePlan.profile === null || profilePlan.profile["model"] !== requestedProfileModel.trim()) ? diagnostic({
31074
- severity: "warning",
31075
- code: "ccr-profile-model-not-configured",
31076
- message: "TOKEN_HARNESS_ROUTING_PROFILE_MODEL did not match a model in the selected CCR provider and was not applied",
31077
- remediation: "Set it to the exact Provider/model alias from CCR, then roll back and preview setup again"
31078
- }) : null;
31079
- const requestedSimpleModel = context.routingSimpleModel ?? context.env?.["TOKEN_HARNESS_ROUTING_SIMPLE_MODEL"];
31080
- const configuredSimpleModel = configuredCcrModel(ccr.config, requestedSimpleModel);
31081
- const simpleModelWarning = requestedSimpleModel?.trim() && configuredSimpleModel === null ? diagnostic({
31082
- severity: "warning",
31083
- code: "ccr-simple-model-not-configured",
31084
- message: "TOKEN_HARNESS_ROUTING_SIMPLE_MODEL did not match a model in the selected CCR configuration and was not embedded",
31085
- remediation: "Set it to the exact Provider/model alias from CCR, then roll back and preview setup again"
31086
- }) : null;
31087
- const script = createCcrSmartRoutingScript({
31088
- harnessId: harnessId2,
31089
- mode,
31090
- telemetryDirectory,
31091
- pathSeparator: context.platform.os === "windows" ? "\\" : "/",
31092
- simpleModel: configuredSimpleModel
31093
- });
31094
- const expectedRule = createCcrSmartRoutingRule(harnessId2, path);
31095
- const router = ccr.config["Router"];
31096
- const rules = isJsonRecord(router) && Array.isArray(router["rules"]) ? router["rules"] : null;
31097
- if (rules === null) {
31098
- 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");
31099
- }
31100
- const matching = rules.filter((item) => isJsonRecord(item) && item["id"] === ruleId);
31101
- const owned = await readOwnership(context, harnessId2);
31102
- const profileList = profilePlan.profileContainer && Array.isArray(profilePlan.profileContainer["profiles"]) ? profilePlan.profileContainer["profiles"] : [];
31103
- const currentOwnedProfile = owned?.profileId ? profileList.find((item) => isJsonRecord(item) && item["id"] === owned.profileId) : void 0;
31104
- const ownedProfileMatches = owned?.profileId === void 0 || isJsonRecord(currentOwnedProfile) && owned.profileSha256 === scriptHash(stableJson2(currentOwnedProfile));
31105
- if (owned !== null && !ownedProfileMatches) {
31106
- 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");
31107
- }
31108
- if (profilePlan.conflict && !owned?.profileId) {
31109
- 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");
31110
- }
31111
- const ownershipStat = await fs.stat(receiptPath3(context, harnessId2));
31112
- if (owned === null && ownershipStat !== null) {
31113
- 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");
31114
- }
31115
- const targetFile = await fs.stat(path);
31116
- if (matching.length > 0) {
31117
- if (matching.length === 1 && isExactCcrSmartRoutingRule(matching[0], expectedRule) && owned) {
31118
- const currentScript = await fs.readFile(path).catch(() => null);
31119
- if (currentScript !== null && scriptHash(new TextDecoder().decode(currentScript)) === owned.scriptSha256) {
31120
- if (owned.mode !== mode || owned.scriptSha256 !== scriptHash(script)) {
31121
- 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`);
31122
- }
31123
- if (owned.profileId === void 0 && profilePlan.profile !== null && !profilePlan.conflict) {
31124
- const profileConfig = withCcrProfile(ccr.config, profilePlan.profile);
31125
- if (profileConfig === null) {
31126
- 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");
31127
- }
31128
- if (!context.confirmed) {
31129
- return configurationResult("configure", "preview", ccr, harnessId2, mode, ruleId, path, [
31130
- diagnostic({
31131
- severity: "info",
31132
- code: "ccr-profile-preview",
31133
- message: "The CCR routing rule is already owned; Token Harness would add its scoped CLI profile using the existing provider",
31134
- remediation: `Review the CCR-only profile and rerun with --yes. Launch it with ${ccrLaunchCommand(harnessId2)}`
31135
- })
31136
- ], String(profilePlan.profile["id"]), ccrLaunchCommand(harnessId2));
31137
- }
31138
- try {
31139
- const currentConfigValue = await ccr.client.call("getConfig");
31140
- if (!isJsonRecord(currentConfigValue))
31141
- throw new CcrManagementError("invalid-response");
31142
- const latestPlan = planCcrProfile(currentConfigValue, harnessId2, requestedProfileModel);
31143
- if (latestPlan.profile === null || profilePlan.profile === null || !isExpectedCcrProfile(latestPlan.profile, profilePlan.profile)) {
31144
- throw new CcrManagementError("config-drift");
31145
- }
31146
- const latestProfileConfig = withCcrProfile(currentConfigValue, latestPlan.profile);
31147
- if (latestProfileConfig === null)
31148
- throw new CcrManagementError("config-drift");
31149
- await ccr.client.call("saveConfig", [latestProfileConfig, { applyProfile: false }]);
31150
- const afterConfig = await ccr.client.call("getConfig");
31151
- const afterRouter = isJsonRecord(afterConfig) ? afterConfig["Router"] : null;
31152
- const afterRules = isJsonRecord(afterRouter) && Array.isArray(afterRouter["rules"]) ? afterRouter["rules"] : [];
31153
- if (!afterRules.some((item) => isExactCcrSmartRoutingRule(item, expectedRule)))
31154
- throw new CcrManagementError("request-failed");
31155
- const savedProfile = profileRows(isJsonRecord(afterConfig) ? afterConfig : {}).find((item) => isJsonRecord(item) && item["id"] === profilePlan.profile?.["id"]);
31156
- if (!isExpectedCcrProfile(savedProfile, profilePlan.profile))
31157
- throw new CcrManagementError("request-failed");
31158
- const updatedOwnership = {
31159
- ...owned,
31160
- profileId: String(profilePlan.profile["id"]),
31161
- profileSha256: scriptHash(stableJson2(savedProfile))
31162
- };
31163
- await writeJson4(context, receiptPath3(context, harnessId2), updatedOwnership);
31164
- return configurationResult("configure", "configured", ccr, harnessId2, mode, ruleId, path, [
31165
- diagnostic({
31166
- severity: "info",
31167
- code: "ccr-profile-verified",
31168
- message: "CCR saved and verified the Token Harness scoped CLI profile using an existing provider",
31169
- remediation: `Launch Claude Code or Codex through ${ccrLaunchCommand(harnessId2)} and verify requests in CCR logs`
31170
- })
31171
- ], updatedOwnership.profileId, ccrLaunchCommand(harnessId2));
31172
- } catch (errorValue) {
31173
- const issue = ccrFailure(errorValue);
31174
- return commandResult({
31175
- command: "routing",
31176
- exitCode: EXIT_CODES["problems-found"],
31177
- diagnostics: [diagnostic({ severity: "error", ...issue })]
31178
- });
31179
- }
31180
- }
31181
- const profileWarning = owned.profileId === void 0 ? profilePlanDiagnostic(profilePlan) : null;
31182
- return configurationResult("configure", "already-configured", ccr, harnessId2, mode, ruleId, path, profileWarning === null ? [] : [profileWarning], owned.profileId ?? null, owned.profileId ? ccrLaunchCommand(harnessId2) : null);
31183
- }
31184
- }
31185
- return commandResult({
31186
- command: "routing",
31187
- exitCode: EXIT_CODES["precondition-drift"],
31188
- diagnostics: [
31189
- diagnostic({
31190
- severity: "error",
31191
- code: "ccr-routing-rule-conflict",
31192
- message: "A CCR rule already uses the Token Harness rule id, so it was left unchanged",
31193
- remediation: "Inspect that rule in CCR Routing and remove or rename it before retrying"
31194
- })
31195
- ]
31196
- });
31197
- }
31198
- if (owned !== null) {
31199
- 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");
31200
- }
31201
- if (targetFile !== null) {
31202
- 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");
31203
- }
31204
- if (mode === "conservative" && configuredSimpleModel === null) {
31205
- return error("ccr-simple-model-required", "Conservative routing needs an exact simple model that already exists in CCR", "Choose a configured Provider/model in Token Harness before enabling conservative routing");
31206
- }
31207
- if (!context.confirmed) {
31208
- const profileDiagnostic = profilePlanDiagnostic(profilePlan);
31209
- return configurationResult("configure", "preview", ccr, harnessId2, mode, ruleId, path, [
31210
- diagnostic({
31211
- severity: "info",
31212
- code: "ccr-configure-preview",
31213
- 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"])}`,
31214
- path,
31215
- 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\``
31216
- }),
31217
- ...profileDiagnostic === null ? [] : [profileDiagnostic],
31218
- ...profileModelWarning === null ? [] : [profileModelWarning],
31219
- ...simpleModelWarning === null ? [] : [simpleModelWarning]
31220
- ], profilePlan.profile === null ? null : String(profilePlan.profile["id"]), profilePlan.profile === null ? null : ccrLaunchCommand(harnessId2));
31221
- }
31222
- let validation;
31223
- try {
31224
- validation = await ccr.client.call("validateRouteScript", [
31225
- {
31226
- script: {
31227
- apiVersion: 1,
31228
- language: "javascript",
31229
- source: script,
31230
- timeoutMs: 2e3
31231
- }
31232
- }
31233
- ]);
31234
- } catch (errorValue) {
31235
- const issue = ccrFailure(errorValue);
31236
- return commandResult({
31237
- command: "routing",
31238
- exitCode: EXIT_CODES["problems-found"],
31239
- diagnostics: [diagnostic({ severity: "error", ...issue })]
31240
- });
31241
- }
31242
- if (!validateRouteRuleResult(validation)) {
31243
- 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");
31244
- }
31245
- const now = context.now();
31246
- const ownership = {
31247
- schemaVersion: 1,
31248
- status: "pending",
31249
- harnessId: harnessId2,
31250
- mode,
31251
- ruleId,
31252
- scriptPath: path,
31253
- scriptSha256: scriptHash(script),
31254
- ...configuredSimpleModel === null ? {} : { simpleModel: configuredSimpleModel },
31255
- installedAt: now
31256
- };
31257
- let saveAttempted = false;
31258
- try {
31259
- await fs.createDirectory(telemetryDirectory);
31260
- await fs.createDirectory(scriptDirectory(context));
31261
- await writeJson4(context, receiptPath3(context, harnessId2), ownership);
31262
- await fs.writeFile(path, new TextEncoder().encode(script));
31263
- const currentConfigValue = await ccr.client.call("getConfig");
31264
- if (!isJsonRecord(currentConfigValue))
31265
- throw new CcrManagementError("invalid-response");
31266
- const latestSimpleModel = configuredCcrModel(currentConfigValue, requestedSimpleModel);
31267
- if (latestSimpleModel !== configuredSimpleModel)
31268
- throw new CcrManagementError("config-drift");
31269
- const latestScript = createCcrSmartRoutingScript({
31270
- harnessId: harnessId2,
31271
- mode,
31272
- telemetryDirectory,
31273
- pathSeparator: context.platform.os === "windows" ? "\\" : "/",
31274
- simpleModel: latestSimpleModel
31275
- });
31276
- if (scriptHash(latestScript) !== ownership.scriptSha256)
31277
- throw new CcrManagementError("config-drift");
31278
- const latestProfilePlan = planCcrProfile(currentConfigValue, harnessId2, requestedProfileModel);
31279
- if (profilePlan.profile === null !== (latestProfilePlan.profile === null) || profilePlan.profile !== null && latestProfilePlan.profile !== null && !isExpectedCcrProfile(latestProfilePlan.profile, profilePlan.profile)) {
31280
- throw new CcrManagementError("config-drift");
31281
- }
31282
- const latestWithRule = addCcrSmartRoutingRule(currentConfigValue, expectedRule);
31283
- if (latestWithRule === null)
31284
- throw new CcrManagementError("config-drift");
31285
- const latestNextConfig = latestProfilePlan.profile === null ? latestWithRule : withCcrProfile(latestWithRule, latestProfilePlan.profile);
31286
- if (latestNextConfig === null)
31287
- throw new CcrManagementError("config-drift");
31288
- saveAttempted = true;
31289
- await ccr.client.call("saveConfig", [latestNextConfig, { applyProfile: false }]);
31290
- const afterConfig = await ccr.client.call("getConfig");
31291
- const afterRouter = isJsonRecord(afterConfig) ? afterConfig["Router"] : null;
31292
- const afterRules = isJsonRecord(afterRouter) && Array.isArray(afterRouter["rules"]) ? afterRouter["rules"] : [];
31293
- if (!afterRules.some((item) => isExactCcrSmartRoutingRule(item, expectedRule))) {
31294
- throw new CcrManagementError("request-failed");
31295
- }
31296
- let savedProfile = null;
31297
- if (profilePlan.profile !== null) {
31298
- const saved = profileRows(isJsonRecord(afterConfig) ? afterConfig : {}).find((item) => isJsonRecord(item) && item["id"] === profilePlan.profile?.["id"]);
31299
- if (!isExpectedCcrProfile(saved, profilePlan.profile))
31300
- throw new CcrManagementError("request-failed");
31301
- savedProfile = saved;
31302
- }
31303
- const activeOwnership2 = {
31304
- ...ownership,
31305
- status: "active",
31306
- ...savedProfile === null || profilePlan.profile === null ? {} : {
31307
- profileId: String(profilePlan.profile["id"]),
31308
- profileSha256: scriptHash(stableJson2(savedProfile))
31309
- }
31310
- };
31311
- await writeJson4(context, receiptPath3(context, harnessId2), activeOwnership2);
31312
- const gatewayValue = await ccr.client.call("getGatewayStatus");
31313
- const gatewayState = safeGatewayState(gatewayValue);
31314
- const finalCcr = { ...ccr, gatewayState };
31315
- const profileDiagnostic = profilePlanDiagnostic(profilePlan);
31316
- return configurationResult("configure", "configured", finalCcr, harnessId2, mode, ruleId, path, [
31317
- diagnostic({
31318
- severity: gatewayState === "running" ? "info" : "warning",
31319
- code: gatewayState === "running" ? "ccr-config-verified" : "ccr-gateway-not-running",
31320
- 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}`,
31321
- path,
31322
- 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"
31323
- }),
31324
- ...profileDiagnostic === null ? [] : [profileDiagnostic],
31325
- ...profileModelWarning === null ? [] : [profileModelWarning],
31326
- ...simpleModelWarning === null ? [] : [simpleModelWarning]
31327
- ], activeOwnership2.profileId ?? null, activeOwnership2.profileId ? ccrLaunchCommand(harnessId2) : null);
31328
- } catch (errorValue) {
31329
- if (!saveAttempted)
31330
- await cleanupUnappliedCcrFiles(context, harnessId2, ownership);
31331
- const issue = ccrFailure(errorValue);
31332
- return commandResult({
31333
- command: "routing",
31334
- exitCode: EXIT_CODES["problems-found"],
31335
- diagnostics: [
31336
- diagnostic({
31337
- severity: "error",
31338
- code: issue.code,
31339
- message: saveAttempted ? `${issue.message}; the ownership receipt was retained for safe recovery` : `${issue.message}; CCR configuration was not changed`,
31340
- ...saveAttempted ? { path: receiptPath3(context, harnessId2) } : {},
31341
- 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"
31342
- })
31343
- ]
31344
- });
31345
- }
31346
- }
31347
- function configurationResult(action, state, ccr, harnessId2, mode, ruleId, path, diagnostics = [], profileId = null, launchCommand = null) {
31348
- return commandResult({
31349
- command: "routing",
31350
- exitCode: EXIT_CODES.ok,
31351
- data: {
31352
- kind: "ccr-configuration",
31353
- action,
31354
- state,
31355
- harnessId: harnessId2,
31356
- mode,
31357
- ccrVersion: ccr.version,
31358
- gatewayState: ccr.gatewayState,
31359
- ruleId,
31360
- scriptPath: path,
31361
- managementEndpoint: ccr.endpoint,
31362
- profileId,
31363
- launchCommand
31364
- },
31365
- diagnostics
31366
- });
31367
- }
31368
- async function rollbackCcrConfiguration(context) {
31369
- const fs = context.adapters?.fs;
31370
- if (fs === void 0 || context.stateRoot === null || !isSmartRoutingHarness(context.harness)) {
31371
- 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");
31372
- }
31373
- const harnessId2 = context.harness;
31374
- const ownership = await readOwnership(context, harnessId2);
31375
- if (ownership === null) {
31376
- 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");
31377
- }
31378
- let ccr;
31379
- try {
31380
- ccr = await readCcrState(context);
31381
- } catch (errorValue) {
31382
- const issue = ccrFailure(errorValue);
31383
- return commandResult({
31384
- command: "routing",
31385
- exitCode: EXIT_CODES["problems-found"],
31386
- diagnostics: [diagnostic({ severity: "error", ...issue })]
31387
- });
31388
- }
31389
- const expectedRule = createCcrSmartRoutingRule(harnessId2, ownership.scriptPath);
31390
- const profileValue = ownership.profileId === void 0 ? null : profileRows(ccr.config).find((item) => isJsonRecord(item) && item["id"] === ownership.profileId) ?? null;
31391
- if (ownership.profileId !== void 0 && profileValue !== null && (ownership.profileSha256 === void 0 || scriptHash(stableJson2(profileValue)) !== ownership.profileSha256)) {
31392
- 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");
31393
- }
31394
- const rules = isJsonRecord(ccr.config["Router"]) && Array.isArray(ccr.config["Router"]["rules"]) ? ccr.config["Router"]["rules"] : [];
31395
- const ownedRule = rules.find((item) => isJsonRecord(item) && item["id"] === ownership.ruleId);
31396
- if (ownedRule === void 0) {
31397
- if (!context.confirmed) {
31398
- return configurationResult("rollback", ownership.profileId === void 0 ? "already-absent" : "preview", ccr, harnessId2, ownership.mode, ownership.ruleId, ownership.scriptPath, ownership.profileId === void 0 ? [] : [
31399
- diagnostic({
31400
- severity: "info",
31401
- code: "ccr-rollback-profile-preview",
31402
- message: "Rollback would remove the remaining exact Token Harness CLI profile and local script",
31403
- remediation: "Review the change and rerun with --yes to apply it"
31404
- })
31405
- ], ownership.profileId ?? null, ownership.profileId === void 0 ? null : ccrLaunchCommand(harnessId2));
31406
- }
31407
- if (ownership.profileId !== void 0) {
31408
- const nextConfig = withoutOwnedCcrProfile(ccr.config, ownership.profileId, ownership.profileSha256);
31409
- if (nextConfig === null) {
31410
- 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");
31411
- }
31412
- try {
31413
- const currentConfigValue = await ccr.client.call("getConfig");
31414
- if (!isJsonRecord(currentConfigValue))
31415
- throw new CcrManagementError("invalid-response");
31416
- const latestNextConfig = withoutOwnedCcrProfile(currentConfigValue, ownership.profileId, ownership.profileSha256);
31417
- if (latestNextConfig === null)
31418
- throw new CcrManagementError("config-drift");
31419
- await ccr.client.call("saveConfig", [latestNextConfig, { applyProfile: false }]);
31420
- const afterConfig = await ccr.client.call("getConfig");
31421
- if (profileRows(isJsonRecord(afterConfig) ? afterConfig : {}).some((item) => isJsonRecord(item) && item["id"] === ownership.profileId)) {
31422
- throw new CcrManagementError("request-failed");
31423
- }
31424
- } catch (errorValue) {
31425
- const issue = ccrFailure(errorValue);
31426
- return commandResult({
31427
- command: "routing",
31428
- exitCode: EXIT_CODES["problems-found"],
31429
- diagnostics: [diagnostic({ severity: "error", ...issue })]
31430
- });
31431
- }
31432
- }
31433
- const bytes = await fs.readFile(ownership.scriptPath).catch(() => null);
31434
- if (bytes !== null && scriptHash(new TextDecoder().decode(bytes)) === ownership.scriptSha256) {
31435
- await fs.remove(ownership.scriptPath);
31436
- }
31437
- await fs.remove(receiptPath3(context, harnessId2));
31438
- return configurationResult("rollback", "already-absent", ccr, harnessId2, ownership.mode, ownership.ruleId, ownership.scriptPath);
31439
- }
31440
- if (!isExactCcrSmartRoutingRule(ownedRule, expectedRule)) {
31441
- 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");
31442
- }
31443
- if (!context.confirmed) {
31444
- return configurationResult("rollback", "preview", ccr, harnessId2, ownership.mode, ownership.ruleId, ownership.scriptPath, [
31445
- diagnostic({
31446
- severity: "info",
31447
- code: "ccr-rollback-preview",
31448
- message: "Rollback would remove the exact Token Harness rule and script while preserving other CCR settings",
31449
- path: ownership.scriptPath,
31450
- remediation: "Review the change and rerun with --yes to apply it"
31451
- }),
31452
- ...ownership.profileId === void 0 ? [] : [
31453
- diagnostic({
31454
- severity: "info",
31455
- code: "ccr-rollback-profile-preview",
31456
- message: "Rollback also removes the exact Token Harness scoped CLI profile; providers and credentials remain unchanged",
31457
- remediation: "Review the change and rerun with --yes to apply it"
31458
- })
31459
- ]
31460
- ], ownership.profileId ?? null, ownership.profileId === void 0 ? null : ccrLaunchCommand(harnessId2));
31461
- }
31462
- try {
31463
- const currentConfigValue = await ccr.client.call("getConfig");
31464
- if (!isJsonRecord(currentConfigValue))
31465
- throw new CcrManagementError("invalid-response");
31466
- const latestWithoutRule = removeOwnedCcrSmartRoutingRule(currentConfigValue, ownership.ruleId, expectedRule);
31467
- if (latestWithoutRule === null)
31468
- throw new CcrManagementError("config-drift");
31469
- const latestNextConfig = ownership.profileId === void 0 ? latestWithoutRule : withoutOwnedCcrProfile(latestWithoutRule, ownership.profileId, ownership.profileSha256);
31470
- if (latestNextConfig === null)
31471
- throw new CcrManagementError("config-drift");
31472
- await ccr.client.call("saveConfig", [latestNextConfig, { applyProfile: false }]);
31473
- const after = await ccr.client.call("getConfig");
31474
- const afterRules = isJsonRecord(after) && isJsonRecord(after["Router"]) && Array.isArray(after["Router"]["rules"]) ? after["Router"]["rules"] : [];
31475
- if (afterRules.some((item) => isJsonRecord(item) && item["id"] === ownership.ruleId)) {
31476
- throw new CcrManagementError("request-failed");
31477
- }
31478
- if (ownership.profileId !== void 0 && profileRows(isJsonRecord(after) ? after : {}).some((item) => isJsonRecord(item) && item["id"] === ownership.profileId)) {
31479
- throw new CcrManagementError("request-failed");
31480
- }
31481
- const gatewayValue = await ccr.client.call("getGatewayStatus");
31482
- const gatewayState = safeGatewayState(gatewayValue);
31483
- const bytes = await fs.readFile(ownership.scriptPath).catch(() => null);
31484
- if (bytes !== null && scriptHash(new TextDecoder().decode(bytes)) === ownership.scriptSha256) {
31485
- await fs.remove(ownership.scriptPath);
31486
- }
31487
- await fs.remove(receiptPath3(context, harnessId2));
31488
- return configurationResult("rollback", "rolled-back", { ...ccr, gatewayState }, harnessId2, ownership.mode, ownership.ruleId, ownership.scriptPath, [
31489
- diagnostic({
31490
- severity: "info",
31491
- code: "ccr-rollback-verified",
31492
- message: "CCR no longer contains the owned rule; other routing rules were preserved",
31493
- path: ownership.scriptPath,
31494
- remediation: "No further action is required"
31495
- })
31496
- ]);
31497
- } catch (errorValue) {
31498
- const issue = ccrFailure(errorValue);
31499
- return commandResult({
31500
- command: "routing",
31501
- exitCode: EXIT_CODES["problems-found"],
31502
- diagnostics: [
31503
- diagnostic({
31504
- severity: "error",
31505
- code: issue.code,
31506
- message: `${issue.message}; the ownership receipt was retained for another rollback attempt`,
31507
- path: receiptPath3(context, harnessId2),
31508
- remediation: "Check CCR status and retry the rollback after it is reachable"
31509
- })
31510
- ]
31511
- });
31512
- }
31513
- }
31514
- async function runSmartRouting(context) {
31515
- const wantsScript = context.routingScript === true;
31516
- const wantsMetrics = context.routingMetrics === true;
31517
- const wantsStatus = context.routingStatus === true;
31518
- const wantsCcrConfigure = context.routingCcrConfigure === true;
31519
- const wantsCcrRollback = context.routingCcrRollback === true;
31520
- const wantsCcrUpdate = context.routingCcrUpdate === true;
31521
- const requestedActions = [
31522
- wantsScript,
31523
- wantsMetrics,
31524
- wantsStatus,
31525
- wantsCcrConfigure,
31526
- wantsCcrRollback,
31527
- wantsCcrUpdate
31528
- ].filter(Boolean).length;
31529
- if (requestedActions !== 1) {
31530
- return error("routing-action-required", "Choose one Smart Model Routing action", "Use `token-harness routing --route-status --harness codex`, `--script`, `--configure-ccr`, `--update-ccr`, `--rollback-ccr`, or `--route-metrics`");
31531
- }
31532
- if (wantsStatus)
31533
- return smartRoutingStatus(context);
31534
- if (context.routingPrune === true && !wantsMetrics) {
31535
- return error("routing-prune-requires-metrics", "`--prune` is available only with the routing metrics action", "Use `token-harness routing --route-metrics --prune`");
31536
- }
31537
- if (context.routingCcrUsage === true && !wantsMetrics) {
31538
- return error("ccr-usage-requires-metrics", "`--ccr-usage` is available only with routing metrics", "Use `token-harness routing --route-metrics --ccr-usage`");
31539
- }
31540
- if (context.routingMode === "conservative" && !wantsScript && !wantsCcrConfigure) {
31541
- 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`");
31542
- }
31543
- if (wantsCcrConfigure) {
31544
- let managed;
31545
- try {
31546
- managed = await resolveManagedCcr(context);
31547
- } catch (errorValue) {
31548
- const issue = ccrFailure(errorValue);
31549
- return commandResult({
31550
- command: "routing",
31551
- exitCode: EXIT_CODES["problems-found"],
31552
- diagnostics: [diagnostic({ severity: "error", ...issue })]
31553
- });
31554
- }
31555
- if (managed.kind === "external")
31556
- return ccrConfiguration(context);
31557
- const ensured = await ensureManagedCcrRuntime({ context, action: "configure" });
31558
- if (ensured.kind === "result")
31559
- return ensured.result;
31560
- if (ensured.changed) {
31561
- const state = ensured.lifecycleAction === "install" ? "installed" : ensured.lifecycleAction === "update" ? "updated" : "started";
31562
- return commandResult({
31563
- command: "routing",
31564
- exitCode: EXIT_CODES.ok,
31565
- data: {
31566
- kind: "ccr-lifecycle",
31567
- action: ensured.lifecycleAction,
31568
- state,
31569
- version: CCR_REVIEWED_VERSION,
31570
- packagePath: ensured.packagePath,
31571
- executablePath: ensured.executablePath,
31572
- managementEndpoint: ensured.endpoint
31573
- },
31574
- diagnostics: [
31575
- diagnostic({
31576
- severity: "info",
31577
- code: `ccr-${ensured.lifecycleAction}-verified`,
31578
- message: `Token Harness ${state} and verified the local CCR CLI and gateway`,
31579
- 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`
31580
- })
31581
- ]
31582
- });
31583
- }
31584
- const configured = await ccrConfiguration({
31585
- ...context,
31586
- env: {
31587
- ...context.env ?? {},
31588
- CCR_WEB_URL: ensured.endpoint,
31589
- CCR_WEB_AUTH_TOKEN: ensured.token
31590
- }
31591
- });
31592
- return configured;
31593
- }
31594
- if (wantsCcrUpdate) {
31595
- let managed;
31596
- try {
31597
- managed = await resolveManagedCcr(context);
31598
- } catch (errorValue) {
31599
- const issue = ccrFailure(errorValue);
31600
- return commandResult({
31601
- command: "routing",
31602
- exitCode: EXIT_CODES["problems-found"],
31603
- diagnostics: [diagnostic({ severity: "error", ...issue })]
31604
- });
31605
- }
31606
- if (managed.kind !== "managed") {
31607
- 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");
31608
- }
31609
- const updated = await ensureManagedCcrRuntime({ context, action: "update" });
31610
- if (updated.kind === "result")
31611
- return updated.result;
31612
- return commandResult({
31613
- command: "routing",
31614
- exitCode: EXIT_CODES.ok,
31615
- data: {
31616
- kind: "ccr-lifecycle",
31617
- action: updated.lifecycleAction,
31618
- state: updated.lifecycleAction === "start" ? "started" : updated.lifecycleAction === "update" ? "updated" : "installed",
31619
- version: CCR_REVIEWED_VERSION,
31620
- packagePath: updated.packagePath,
31621
- executablePath: updated.executablePath,
31622
- managementEndpoint: updated.endpoint
31623
- },
31624
- diagnostics: [
31625
- diagnostic({
31626
- severity: "info",
31627
- code: `ccr-${updated.lifecycleAction}-verified`,
31628
- 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`,
31629
- 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"
31630
- })
31631
- ]
31632
- });
31633
- }
31634
- if (wantsCcrRollback)
31635
- return rollbackCcrConfiguration(context);
31636
- const fs = context.adapters?.fs;
31637
- const stateRoot = context.stateRoot;
31638
- if (fs === void 0 || stateRoot === null) {
31639
- return commandResult({
31640
- command: "routing",
31641
- exitCode: EXIT_CODES["unsupported-environment"],
31642
- diagnostics: [
31643
- diagnostic({
31644
- severity: "error",
31645
- code: "routing-state-unavailable",
31646
- message: "Smart Model Routing requires the protected local Token Harness state directory",
31647
- remediation: "Resolve the local state directory with `token-harness doctor`"
31648
- })
31649
- ]
31650
- });
31651
- }
31652
- const telemetryDirectory = fs.join(stateRoot, "smart-routing");
31653
- if (wantsScript) {
31654
- if (!isSmartRoutingHarness(context.harness)) {
31655
- return error("routing-harness-required", "CCR script generation needs Claude Code or Codex as its harness", "Pass `--harness claude` or `--harness codex`");
31656
- }
31657
- await fs.createDirectory(telemetryDirectory);
31658
- const script = createCcrSmartRoutingScript({
31659
- harnessId: context.harness,
31660
- mode: context.routingMode ?? "shadow",
31661
- telemetryDirectory,
31662
- pathSeparator: context.platform.os === "windows" ? "\\" : "/"
31663
- });
31664
- return commandResult({
31665
- command: "routing",
31666
- exitCode: EXIT_CODES.ok,
31667
- data: {
31668
- kind: "ccr-script",
31669
- harnessId: context.harness,
31670
- mode: context.routingMode ?? "shadow",
31671
- telemetryDirectory,
31672
- script
31673
- }
31674
- });
31675
- }
31676
- const resolved = resolveMetricsWindow({
31677
- since: context.since,
31678
- until: context.until,
31679
- now: context.now()
31680
- });
31681
- if (!resolved.ok) {
31682
- 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`");
31683
- }
31684
- const directoryEntries = (await fs.readDirectory(telemetryDirectory)).filter((name2) => new RegExp(`^${SMART_ROUTING_EVENT_PREFIX}\\d{13}-[a-z0-9]+\\.json$`).test(name2)).sort();
31685
- let prunedRecordCount = 0;
31686
- if (context.routingPrune === true && directoryEntries.length > SMART_ROUTING_EVENT_RETENTION_LIMIT) {
31687
- const removeCount = directoryEntries.length - SMART_ROUTING_EVENT_RETENTION_LIMIT;
31688
- for (const name2 of directoryEntries.slice(0, removeCount)) {
31689
- await fs.remove(fs.join(telemetryDirectory, name2));
31690
- }
31691
- prunedRecordCount = removeCount;
31692
- }
31693
- const retainedNames = context.routingPrune === true ? directoryEntries.slice(prunedRecordCount) : directoryEntries;
31694
- const events = [];
31695
- let malformedRecordCount = 0;
31696
- for (const name2 of retainedNames) {
31697
- try {
31698
- const content = new TextDecoder().decode(await fs.readFile(fs.join(telemetryDirectory, name2)));
31699
- const parsed = JSON.parse(content);
31700
- if (!isSmartRoutingDecisionEvent(parsed)) {
31701
- malformedRecordCount += 1;
31702
- continue;
31703
- }
31704
- const timestamp = Date.parse(parsed.timestamp);
31705
- if (!Number.isFinite(timestamp)) {
31706
- malformedRecordCount += 1;
31707
- continue;
31708
- }
31709
- if (timestamp < Date.parse(resolved.window.sinceInstant))
31710
- continue;
31711
- if (timestamp >= Date.parse(resolved.window.untilInstant))
31712
- continue;
31713
- if (context.harness !== null && parsed.harnessId !== context.harness)
31714
- continue;
31715
- events.push(parsed);
31716
- } catch {
31717
- malformedRecordCount += 1;
31718
- }
31719
- }
31720
- const metrics = aggregateSmartRoutingEvents({ events, malformedRecordCount, prunedRecordCount });
31721
- let ccrUsage;
31722
- const diagnostics = events.length === 0 && malformedRecordCount === 0 ? [
31723
- diagnostic({
31724
- severity: "info",
31725
- code: "routing-decisions-unavailable",
31726
- message: "No CCR routing decisions are stored for this window",
31727
- remediation: "Generate a CCR rule with `token-harness routing --script --harness codex` or configure one with `--configure-ccr`"
31728
- })
31729
- ] : [];
31730
- if (context.routingCcrUsage === true) {
31731
- try {
31732
- const observed = await observeCcrUsage({
31733
- context,
31734
- events,
31735
- since: resolved.window.sinceInstant,
31736
- until: resolved.window.untilInstant
31737
- });
31738
- ccrUsage = observed.usage;
31739
- if (observed.failedSessions > 0 || observed.usage.status === "unavailable") {
31740
- diagnostics.push(diagnostic({
31741
- severity: "warning",
31742
- code: observed.usage.status === "unavailable" ? "ccr-usage-unavailable" : "ccr-usage-partial",
31743
- 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`,
31744
- remediation: "Keep CCR request logging enabled, use the same local session, and rerun with a narrower time window"
31745
- }));
31746
- }
31747
- } catch (errorValue) {
31748
- const issue = ccrFailure(errorValue);
31749
- diagnostics.push(diagnostic({ severity: "warning", ...issue }));
31750
- ccrUsage = {
31751
- status: "unavailable",
31752
- sessionCount: 0,
31753
- observedSessionCount: 0,
31754
- requestCount: 0,
31755
- inputTokens: 0,
31756
- outputTokens: 0,
31757
- cacheReadTokens: 0,
31758
- cacheWriteTokens: 0,
31759
- totalTokens: 0,
31760
- recordedCostUsd: null,
31761
- byModel: []
31762
- };
31763
- }
31764
- }
31765
- return commandResult({
31766
- command: "routing",
31767
- exitCode: EXIT_CODES.ok,
31768
- data: {
31769
- kind: "metrics",
31770
- since: resolved.window.sinceInstant,
31771
- until: resolved.window.untilInstant,
31772
- metrics,
31773
- ...ccrUsage === void 0 ? {} : { ccrUsage }
31774
- },
31775
- diagnostics
31776
- });
31777
- }
31778
- var OWNED_PROFILE_IDS;
31779
- var init_smart_routing2 = __esm({
31780
- "apps/cli/dist/src/commands/smart-routing.js"() {
31781
- "use strict";
31782
- init_src3();
31783
- init_src();
31784
- init_routing_usage();
31785
- init_ccr_runtime();
31786
- OWNED_PROFILE_IDS = {
31787
- claude: "token-harness-smart-routing-claude-v1",
31788
- codex: "token-harness-smart-routing-codex-v1"
31789
- };
31790
- }
31791
- });
31792
-
31793
29192
  // apps/cli/dist/src/commands/verify.js
31794
29193
  async function runVerify(context) {
31795
29194
  const diagnostics = [];
@@ -33228,7 +30627,7 @@ async function runUpdate(context) {
33228
30627
  let snapshot;
33229
30628
  try {
33230
30629
  snapshot = await snapshotCreation.store.capture(plan6.targetPath);
33231
- } catch (error2) {
30630
+ } catch (error) {
33232
30631
  return result5(EXIT_CODES["internal-error"], null, [
33233
30632
  ...preparedDiagnostics,
33234
30633
  diagnostic({
@@ -33236,7 +30635,7 @@ async function runUpdate(context) {
33236
30635
  code: "rtk-release-snapshot-failed",
33237
30636
  subject: "rtk",
33238
30637
  path: plan6.targetPath,
33239
- 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)}`,
33240
30639
  remediation: "Check the state directory and executable permissions, then retry"
33241
30640
  })
33242
30641
  ]);
@@ -33270,7 +30669,7 @@ async function runUpdate(context) {
33270
30669
  };
33271
30670
  try {
33272
30671
  await journalStore.write(directJournal);
33273
- } catch (error2) {
30672
+ } catch (error) {
33274
30673
  return result5(EXIT_CODES["internal-error"], null, [
33275
30674
  ...preparedDiagnostics,
33276
30675
  diagnostic({
@@ -33278,7 +30677,7 @@ async function runUpdate(context) {
33278
30677
  code: "rtk-release-journal-failed",
33279
30678
  subject: "rtk",
33280
30679
  path: plan6.targetPath,
33281
- 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)}`,
33282
30681
  remediation: "Check the Token Harness state directory, then retry"
33283
30682
  })
33284
30683
  ]);
@@ -33323,7 +30722,7 @@ async function runUpdate(context) {
33323
30722
  await finishDirectJournal(installed2.status === "dirty" ? "dirty" : "rolled-back", "failed", [
33324
30723
  failureDiagnostic
33325
30724
  ]);
33326
- } catch (error2) {
30725
+ } catch (error) {
33327
30726
  return result5(EXIT_CODES["apply-failed-dirty"], null, [
33328
30727
  ...preparedDiagnostics,
33329
30728
  failureDiagnostic,
@@ -33332,7 +30731,7 @@ async function runUpdate(context) {
33332
30731
  code: "rtk-release-failure-journal-write-failed",
33333
30732
  subject: "rtk",
33334
30733
  path: plan6.targetPath,
33335
- 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)}`,
33336
30735
  remediation: `Inspect transaction ${transactionId2} and its backups before retrying`
33337
30736
  })
33338
30737
  ]);
@@ -33351,7 +30750,7 @@ async function runUpdate(context) {
33351
30750
  }
33352
30751
  try {
33353
30752
  await markDirectAppliedInProgress();
33354
- } catch (error2) {
30753
+ } catch (error) {
33355
30754
  const rollback = await plan6.runtime.rollback(installed2.handle, context.projectRoot);
33356
30755
  const dirty = rollback.status === "dirty";
33357
30756
  const persistenceDiagnostic = diagnostic({
@@ -33359,7 +30758,7 @@ async function runUpdate(context) {
33359
30758
  code: "rtk-release-applied-journal-write-failed",
33360
30759
  subject: "rtk",
33361
30760
  path: plan6.targetPath,
33362
- 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}`,
33363
30762
  remediation: `Inspect transaction ${transactionId2} and its backups before retrying`
33364
30763
  });
33365
30764
  try {
@@ -33436,7 +30835,7 @@ async function runUpdate(context) {
33436
30835
  });
33437
30836
  try {
33438
30837
  await finishDirectJournal("committed", "applied", [committedDiagnostic]);
33439
- } catch (error2) {
30838
+ } catch (error) {
33440
30839
  const rollback = await plan6.runtime.rollback(installed2.handle, context.projectRoot);
33441
30840
  const dirty = rollback.status === "dirty";
33442
30841
  const persistenceDiagnostic = diagnostic({
@@ -33444,7 +30843,7 @@ async function runUpdate(context) {
33444
30843
  code: "rtk-release-commit-journal-write-failed",
33445
30844
  subject: "rtk",
33446
30845
  path: plan6.targetPath,
33447
- 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}`,
33448
30847
  remediation: `Inspect transaction ${transactionId2} and its backups before retrying`
33449
30848
  });
33450
30849
  await finishDirectJournal(dirty ? "dirty" : "rolled-back", "failed", [
@@ -33681,8 +31080,7 @@ var init_apply2 = __esm({
33681
31080
  // apps/cli/dist/src/render/benchmark.js
33682
31081
  function receiptLine(label, receipt) {
33683
31082
  const local = receipt.localUsage === null ? "local tokens unknown" : `local ${formatCount(receipt.localUsage.totalTokens)} tokens`;
33684
- 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`;
33685
- 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}`;
33686
31084
  }
33687
31085
  function policyLine(label, receipt) {
33688
31086
  const parts = [
@@ -33710,21 +31108,6 @@ function renderBenchmarkReport(report, _context) {
33710
31108
  } else {
33711
31109
  lines.push(...wrap(`Backend quota (${comparison.quota.scope}, ${comparison.quota.confidence}): baseline +${String(comparison.quota.baselineDeltaUsedPercent)}% vs optimized +${String(comparison.quota.optimizedDeltaUsedPercent)}%`, 0));
33712
31110
  }
33713
- const ccrUsage = comparison.ccrUsage;
33714
- if (ccrUsage === void 0 || ccrUsage.status === "not-measured") {
33715
- lines.push("CCR observed usage: not measured for both variants");
33716
- } else if (ccrUsage.status === "comparable") {
33717
- const modelPair = `${ccrUsage.baselineModels.join(", ") || "unknown"} \u2192 ${ccrUsage.optimizedModels.join(", ") || "unknown"}`;
33718
- lines.push(...wrap(`CCR request usage: ${formatCount(ccrUsage.baselineTokens ?? 0)} \u2192 ${formatCount(ccrUsage.optimizedTokens ?? 0)} tokens; delta ${String(ccrUsage.totalTokenDelta ?? 0)}; models ${modelPair}`, 0));
33719
- if (ccrUsage.recordedCostDeltaUsd !== null) {
33720
- lines.push(`CCR recorded provider-cost estimate delta: ${ccrUsage.recordedCostDeltaUsd.toFixed(6)} USD`);
33721
- }
33722
- lines.push("CCR request tokens and price estimates remain separate from subscription quota");
33723
- } else if (ccrUsage.status === "quality-gated") {
33724
- lines.push("CCR request usage: observed, but delta withheld until both task quality gates pass");
33725
- } else {
33726
- lines.push("CCR request usage: partial or ambiguous, not compared");
33727
- }
33728
31111
  const contextCounts = context.baseline === null || context.optimized === null ? "" : ` \u2014 static MCP tools ${String(context.baseline.effectiveStaticMcpToolCount)} \u2192 ${String(context.optimized.effectiveStaticMcpToolCount)}`;
33729
31112
  lines.push(...wrap(`Context: ${context.verdict}${contextCounts}`, 0));
33730
31113
  lines.push(...wrap(`Context evidence: ${context.reason}`, 2));
@@ -33781,7 +31164,7 @@ function renderBenchmarkStartReport(report, context) {
33781
31164
  }
33782
31165
  function renderBenchmarkFinishReport(report, context) {
33783
31166
  const { receipt } = report;
33784
- 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);
33785
31168
  return document([
33786
31169
  `Benchmark receipt \u2014 ${receipt.benchmarkId} / ${receipt.variant}`,
33787
31170
  `${receipt.taskClass} on ${receipt.harnessId}`,
@@ -33789,7 +31172,7 @@ function renderBenchmarkFinishReport(report, context) {
33789
31172
  ...wrap(`Quality ${receipt.outcome.qualityGate}; attempts ${String(receipt.outcome.attempts)}; failed attempts ${String(receipt.outcome.failedAttempts)}`, 0),
33790
31173
  `Quota windows: ${String(receipt.usageBefore.length)} before / ${String(receipt.usageAfter.length)} after`,
33791
31174
  receipt.localUsage === null ? "Local usage: unavailable or ambiguous" : `Local usage: ${String(receipt.localUsage.totalTokens)} tokens (local evidence only)`,
33792
- `Receipt: ${receiptPath4}`,
31175
+ `Receipt: ${receiptPath3}`,
33793
31176
  "",
33794
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)
33795
31178
  ]);
@@ -33830,30 +31213,6 @@ function localLine(summary) {
33830
31213
  }
33831
31214
  return `local tokens across ${String(summary.localComparablePairs)} quality-passed pairs \u2014 baseline ${formatCount(summary.baselineLocalTokens)}, optimized ${formatCount(summary.optimizedLocalTokens)}, delta ${percent2(summary.localTokenSavingPercent)}`;
33832
31215
  }
33833
- function signedCount(value3) {
33834
- return `${value3 > 0 ? "+" : ""}${formatCount(value3)}`;
33835
- }
33836
- function signedUsd(value3) {
33837
- return `${value3 > 0 ? "+" : ""}${value3.toFixed(6)}`;
33838
- }
33839
- function ccrUsageLines(summary, indent) {
33840
- const usage = summary.ccrUsage;
33841
- if (usage === void 0)
33842
- return [];
33843
- const lines = [];
33844
- if (usage.comparablePairs > 0 && usage.baselineTokens !== null && usage.optimizedTokens !== null && usage.totalTokenDelta !== null) {
33845
- 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));
33846
- } else if (usage.partialPairs > 0 || usage.qualityGatedPairs > 0) {
33847
- lines.push(...wrap(`CCR usage deltas withheld \u2014 partial ${String(usage.partialPairs)}, quality-gated ${String(usage.qualityGatedPairs)}`, indent));
33848
- }
33849
- if (usage.recordedCostPairs > 0 && usage.baselineRecordedCostUsd !== null && usage.optimizedRecordedCostUsd !== null && usage.recordedCostDeltaUsd !== null) {
33850
- 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));
33851
- }
33852
- if (usage.comparablePairs > 0 || usage.partialPairs > 0 || usage.qualityGatedPairs > 0) {
33853
- lines.push(...wrap("CCR usage and cost estimates are separate from subscription quota and billed savings.", indent));
33854
- }
33855
- return lines;
33856
- }
33857
31216
  function candidateSummaryLine(summary) {
33858
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)}`;
33859
31218
  }
@@ -33871,12 +31230,11 @@ function candidateTimingLine(summary) {
33871
31230
  }
33872
31231
  function entryLine(entry) {
33873
31232
  const local = entry.localTokenSavingPercent === null ? "" : `; local delta ${percent2(entry.localTokenSavingPercent)}`;
33874
- const ccr = entry.ccrUsage?.status === "comparable" && entry.ccrUsage.totalTokenDelta !== null ? `; CCR ${signedCount(entry.ccrUsage.totalTokenDelta)} tokens` : "";
33875
31233
  if (!("context" in entry)) {
33876
- return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}${ccr}`;
31234
+ return `${entry.benchmarkId} \u2014 ${entry.verdict}; ${entry.basis}; ${entry.evidenceLevel}${local}`;
33877
31235
  }
33878
31236
  const contextCounts = entry.context.baseline === null || entry.context.optimized === null ? "" : ` ${String(entry.context.baseline.effectiveStaticMcpToolCount)}\u2192${String(entry.context.optimized.effectiveStaticMcpToolCount)} static tools`;
33879
- 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}`;
33880
31238
  }
33881
31239
  function renderCampaign(lines, campaign) {
33882
31240
  lines.push("", "Candidate campaign \u2014 experimental");
@@ -33934,7 +31292,6 @@ function renderBenchmarkMatrixReport(report, _context) {
33934
31292
  const local = localLine(summary);
33935
31293
  if (local !== null)
33936
31294
  lines.push(...wrap(local, 4));
33937
- lines.push(...ccrUsageLines(summary, 4));
33938
31295
  }
33939
31296
  lines.push("", "Overall");
33940
31297
  lines.push(...wrap(summaryLine(report.overall), 2));
@@ -33944,7 +31301,6 @@ function renderBenchmarkMatrixReport(report, _context) {
33944
31301
  const overallLocal = localLine(report.overall);
33945
31302
  if (overallLocal !== null)
33946
31303
  lines.push(...wrap(overallLocal, 2));
33947
- lines.push(...ccrUsageLines(report.overall, 2));
33948
31304
  if (report.candidateEvidence !== void 0 && report.campaign === void 0) {
33949
31305
  lines.push("", "Candidate evidence \u2014 experimental");
33950
31306
  for (const candidate of report.candidateEvidence) {
@@ -34637,14 +31993,14 @@ function renderMetricsReport(report, _context) {
34637
31993
  if (report.errorBreakdown.length > 0) {
34638
31994
  lines.push("");
34639
31995
  lines.push("Errors by code");
34640
- for (const error2 of report.errorBreakdown) {
34641
- lines.push(...wrap(error2.code, 2));
31996
+ for (const error of report.errorBreakdown) {
31997
+ lines.push(...wrap(error.code, 2));
34642
31998
  const scope = [];
34643
- if (error2.providerIds.length > 0)
34644
- scope.push(`providers ${error2.providerIds.join(", ")}`);
34645
- if (error2.harnesses.length > 0)
34646
- scope.push(`harnesses ${error2.harnesses.join(", ")}`);
34647
- 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));
34648
32004
  }
34649
32005
  }
34650
32006
  return document(lines);
@@ -34987,73 +32343,6 @@ var init_stack_review2 = __esm({
34987
32343
  }
34988
32344
  });
34989
32345
 
34990
- // apps/cli/dist/src/render/smart-routing.js
34991
- function renderSmartRoutingReport(report) {
34992
- if (report.kind === "ccr-script")
34993
- return `${report.script}
34994
- `;
34995
- if (report.kind === "status") {
34996
- return [
34997
- `Smart Model Routing: ${report.state}`,
34998
- `Harness: ${report.harnessId}`,
34999
- `Gateway: ${report.gatewayState}`,
35000
- ...report.simpleModel === null ? [] : [`Simple model: ${report.simpleModel}`],
35001
- ...report.launchCommand === null ? [] : [`Launch: ${report.launchCommand}`],
35002
- report.detail
35003
- ].join("\n");
35004
- }
35005
- if (report.kind === "ccr-configuration") {
35006
- return [
35007
- `CCR ${report.action}: ${report.state}`,
35008
- `Harness: ${report.harnessId}`,
35009
- `Mode: ${report.mode}`,
35010
- `CCR version: ${report.ccrVersion}`,
35011
- `Gateway: ${report.gatewayState}`,
35012
- `Rule: ${report.ruleId}`,
35013
- `Script: ${report.scriptPath}`,
35014
- `Management endpoint: ${report.managementEndpoint}`,
35015
- ...report.profileId === void 0 || report.profileId === null ? [] : [`CCR profile: ${report.profileId}`],
35016
- ...report.launchCommand === void 0 || report.launchCommand === null ? [] : [`Launch: ${report.launchCommand}`]
35017
- ].join("\n");
35018
- }
35019
- if (report.kind === "ccr-lifecycle") {
35020
- return [
35021
- `CCR ${report.action}: ${report.state}`,
35022
- `Version: ${report.version}`,
35023
- `Package: ${report.packagePath}`,
35024
- `CLI: ${report.executablePath}`,
35025
- `Management endpoint: ${report.managementEndpoint}`
35026
- ].join("\n");
35027
- }
35028
- const { metrics } = report;
35029
- const harnesses = Object.entries(metrics.byHarness).filter(([, count]) => count > 0).map(([name2, count]) => `${name2} ${String(count)}`).join(", ") || "none";
35030
- const tiers = Object.entries(metrics.byTier).filter(([, count]) => count > 0).map(([name2, count]) => `${name2} ${String(count)}`).join(", ") || "none";
35031
- const modes = Object.entries(metrics.byMode).filter(([, count]) => count > 0).map(([name2, count]) => `${name2} ${String(count)}`).join(", ") || "none";
35032
- const lines = [
35033
- "Smart Model Routing decisions",
35034
- `Window: ${report.since} to ${report.until}`,
35035
- `Retained decisions: ${String(metrics.retainedDecisionCount)}`,
35036
- `By harness: ${harnesses}`,
35037
- `By mode: ${modes}`,
35038
- `By tier: ${tiers}`,
35039
- `CCR route changes requested: ${String(metrics.routeMutationRequestCount)}`,
35040
- `Malformed records: ${String(metrics.malformedRecordCount)}`,
35041
- `Pruned records: ${String(metrics.prunedRecordCount)}`,
35042
- "Model savings: not measured",
35043
- `Cleanup: token-harness routing --route-metrics --prune (keeps ${String(metrics.retentionLimit)} newest records)`
35044
- ];
35045
- if (report.ccrUsage !== void 0) {
35046
- const models = report.ccrUsage.byModel.map((item) => item.model).join(", ") || "none";
35047
- 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");
35048
- }
35049
- return lines.join("\n");
35050
- }
35051
- var init_smart_routing3 = __esm({
35052
- "apps/cli/dist/src/render/smart-routing.js"() {
35053
- "use strict";
35054
- }
35055
- });
35056
-
35057
32346
  // apps/cli/dist/src/render/update.js
35058
32347
  function widthOf(values, floor) {
35059
32348
  return Math.max(floor, ...values.map((value3) => value3.length + 2));
@@ -35594,8 +32883,6 @@ function renderHuman(result6, context) {
35594
32883
  return plain(renderSimpleMcp(data));
35595
32884
  case "metrics":
35596
32885
  return plain(renderSimpleMetrics(data));
35597
- case "routing":
35598
- return plain(renderSmartRoutingReport(data));
35599
32886
  case "optimize":
35600
32887
  return plain(renderSimpleOptimize(data));
35601
32888
  case "plan":
@@ -35649,8 +32936,6 @@ function renderHuman(result6, context) {
35649
32936
  return plain(renderVerifyReport(data, context));
35650
32937
  case "metrics":
35651
32938
  return plain(renderMetricsReport(data, context));
35652
- case "routing":
35653
- return plain(renderSmartRoutingReport(data));
35654
32939
  case "update":
35655
32940
  return plain(renderUpdateReport(data, context));
35656
32941
  default:
@@ -35674,7 +32959,6 @@ var init_render = __esm({
35674
32959
  init_plan3();
35675
32960
  init_status2();
35676
32961
  init_stack_review2();
35677
- init_smart_routing3();
35678
32962
  init_update2();
35679
32963
  init_verify2();
35680
32964
  init_simple();
@@ -35722,7 +33006,6 @@ Advanced commands
35722
33006
  apply Apply a reviewed plan
35723
33007
  verify Check that configured integrations work
35724
33008
  metrics Show measured savings
35725
- routing Install/configure CCR or inspect routing decisions
35726
33009
  update Check or update installed providers
35727
33010
  rollback Restore the previous configuration
35728
33011
  uninstall Remove only configuration Token Harness owns
@@ -35735,16 +33018,6 @@ Useful flags
35735
33018
  --yes Confirm a configuration-changing operation
35736
33019
  --harness <id> Restrict the operation to one harness
35737
33020
  --provider <id> Restrict the operation to one provider
35738
- --script Export a CCR script rule (routing command)
35739
- --route-status Show current Smart Model Routing state for one agent
35740
- --route-metrics Show local routing decision telemetry
35741
- --route-mode <mode> shadow by default; conservative requires opt-in
35742
- --route-simple-model <Provider/model> Simple model for conservative routing
35743
- --prune Keep only the 200 newest routing decision records
35744
- --configure-ccr Preview CCR setup; --yes applies the reviewed change
35745
- --update-ccr Preview update of the managed CCR CLI
35746
- --rollback-ccr Preview rollback; --yes removes owned rule/profile
35747
- --ccr-usage Read CCR model/token aggregates for local sessions
35748
33021
  --project <dir> Use that project instead of the current directory
35749
33022
  --help Show help for a command
35750
33023
  --version Print the version
@@ -36007,40 +33280,6 @@ Figures are never merged across measurement classes or units: tokens are not
36007
33280
  added to characters, and an estimate is not added to an exact figure. A
36008
33281
  counterfactual reduction is reported on its own line and never as a saving.
36009
33282
  Exits 0 whatever the figures say \u2014 an empty report is a fact, not a failure.`,
36010
- routing: `token-harness routing \u2014 inspect or export Smart Model Routing
36011
-
36012
- Usage
36013
- token-harness routing --script --harness <claude|codex>
36014
- [--route-mode <shadow|conservative>] [--json]
36015
- token-harness routing --route-status --harness <claude|codex> [--json]
36016
- token-harness routing --configure-ccr --harness <claude|codex>
36017
- [--route-mode <shadow|conservative>]
36018
- [--route-simple-model <Provider/model>] [--yes]
36019
- token-harness routing --update-ccr [--yes]
36020
- token-harness routing --rollback-ccr --harness <claude|codex> [--yes]
36021
- token-harness routing --route-metrics [--since <duration|date>]
36022
- [--until <date>] [--harness <claude|codex>]
36023
- [--ccr-usage] [--prune] [--json]
36024
-
36025
- Script export defaults to shadow mode. Add the generated script as a Node.js script rule in CCR;
36026
- it records local, prompt-free decisions and returns no route rewrite in shadow mode. Conservative
36027
- mode is explicit and only proposes a configured simple model for high-confidence, low-risk requests.
36028
- It leaves requests with tool schemas unchanged unless the CCR process explicitly sets
36029
- TOKEN_HARNESS_ROUTING_ALLOW_TOOLS=true. No API call or local model is used to classify.
36030
-
36031
- CCR must run on this machine as the same user for the local telemetry path to be writable. A failed
36032
- telemetry write never blocks the agent request. Decision records contain no prompt or credentials.
36033
- Routing choices are not measured token savings; this command keeps them separate from \`metrics\`.
36034
- Use --prune to remove all but the 200 newest decision records.
36035
-
36036
- When no authenticated local CCR service is present, configure previews the managed CCR runtime
36037
- preparation required for the selected routing mode. The browser workflow completes runtime
36038
- preparation and the reviewed routing configuration in one approved flow. Conservative mode
36039
- requires --route-simple-model to name an exact model already configured in CCR. A Token Harness-owned service keeps
36040
- its Web RPC token in a private local file; existing services can use CCR_WEB_AUTH_TOKEN and
36041
- optionally CCR_WEB_URL. --update-ccr only updates a Token Harness-owned CLI to the reviewed pin.
36042
- Rollback removes only the exact rule, profile, and script Token Harness owns. CCR usage is observed
36043
- request telemetry, not subscription quota or measured savings.`,
36044
33283
  uninstall: `token-harness uninstall \u2014 remove what Token Harness owns
36045
33284
 
36046
33285
  Usage
@@ -36201,8 +33440,8 @@ function emit(result6, options, renderContext, json) {
36201
33440
  if (json) {
36202
33441
  try {
36203
33442
  options.streams.out(serializeEnvelope(toEnvelope(result6, toolVersion)));
36204
- } catch (error2) {
36205
- 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)}
36206
33445
  `);
36207
33446
  return EXIT_CODES["internal-error"];
36208
33447
  }
@@ -36321,18 +33560,7 @@ async function run(options) {
36321
33560
  tasksRemaining: invocation.options.tasksLeft,
36322
33561
  contextSnapshotPath: invocation.options.contextSnapshot,
36323
33562
  nativePolicy: invocation.options.nativePolicy,
36324
- routingScript: invocation.options.routingScript,
36325
- routingMetrics: invocation.options.routingMetrics,
36326
- routingStatus: invocation.options.routingStatus,
36327
- routingMode: invocation.options.routingMode,
36328
- routingSimpleModel: invocation.options.routingSimpleModel,
36329
- routingPrune: invocation.options.routingPrune,
36330
- routingCcrConfigure: invocation.options.routingCcrConfigure,
36331
- routingCcrRollback: invocation.options.routingCcrRollback,
36332
- routingCcrUpdate: invocation.options.routingCcrUpdate,
36333
- routingCcrUsage: invocation.options.routingCcrUsage,
36334
33563
  env: options.env ?? {},
36335
- ...options.ccrFetch === void 0 ? {} : { ccrFetch: options.ccrFetch },
36336
33564
  agentSkill: invocation.options.agentSkill,
36337
33565
  since: invocation.options.since,
36338
33566
  until: invocation.options.until,
@@ -36356,7 +33584,7 @@ async function run(options) {
36356
33584
  let result6;
36357
33585
  try {
36358
33586
  result6 = await table[invocation.command](context);
36359
- } catch (error2) {
33587
+ } catch (error) {
36360
33588
  result6 = commandResult({
36361
33589
  command: invocation.command,
36362
33590
  exitCode: EXIT_CODES["internal-error"],
@@ -36364,7 +33592,7 @@ async function run(options) {
36364
33592
  diagnostic({
36365
33593
  severity: "error",
36366
33594
  code: "internal-error",
36367
- 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)}`,
36368
33596
  remediation: "Report this with the command you ran at https://github.com/giuliastro/TokenHarness/issues"
36369
33597
  })
36370
33598
  ]
@@ -36391,7 +33619,6 @@ var init_run = __esm({
36391
33619
  init_optimize();
36392
33620
  init_plan2();
36393
33621
  init_rollback();
36394
- init_smart_routing2();
36395
33622
  init_setup2();
36396
33623
  init_status();
36397
33624
  init_stack_review();
@@ -36415,7 +33642,6 @@ var init_run = __esm({
36415
33642
  optimize: runOptimize,
36416
33643
  plan: runPlan,
36417
33644
  rollback: runRollback,
36418
- routing: runSmartRouting,
36419
33645
  setup: runSetup,
36420
33646
  status: runStatus,
36421
33647
  "stack-review": runStackReview,
@@ -37148,6 +34374,7 @@ function agentRules(id, providers, context, guidance) {
37148
34374
  }
37149
34375
  function describeChange(action, harness) {
37150
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." : "";
37151
34378
  if (action.kind === "merge-json" && action.ownedPointers?.includes("effortLevel")) {
37152
34379
  const operation = action.operations.find((item) => item.kind === "set");
37153
34380
  const value3 = operation?.kind === "set" ? String(operation.value) : "reviewed";
@@ -37175,7 +34402,7 @@ function describeChange(action, harness) {
37175
34402
  };
37176
34403
  return {
37177
34404
  title: `${prefix}: ${descriptions[action.kind] ?? "Apply the reviewed integration change"}`,
37178
- 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,
37179
34406
  files: action.affectedPaths.length
37180
34407
  };
37181
34408
  }
@@ -37249,10 +34476,6 @@ var init_guided = __esm({
37249
34476
  }
37250
34477
  ];
37251
34478
  ISSUE_COPY = {
37252
- "ccr-simple-model-required": "Conservative routing needs a simple model selected from the models already configured in CCR.",
37253
- "ccr-config-changed-during-operation": "CCR changed configuration while routing was being prepared. Token Harness preserved the latest CCR state instead of overwriting it; refresh and retry.",
37254
- "ccr-profile-id-conflict": "A Token Harness routing profile already exists but its ownership cannot be verified. Disable or repair that routing state before enabling it again.",
37255
- "ccr-management-operation-failed": "CCR rejected the routing configuration change. The existing routing state was left unchanged.",
37256
34479
  "cclimits-not-installed": "Claude allowance needs the optional cclimits companion. Output optimization does not depend on the allowance meter.",
37257
34480
  "cclimits-readonly-flags-unsupported": "The installed cclimits is too old for safe allowance reading. Version 1.7.0 includes the required support.",
37258
34481
  "cclimits-python-unavailable": "cclimits is installed, but Python could not start. Check the Python installation used by this terminal.",
@@ -37440,7 +34663,6 @@ var init_guided = __esm({
37440
34663
  const empty2 = () => ({ data: null, diagnostics: [], exitCode: 9 });
37441
34664
  let doctor = empty2(), budget = empty2(), context = empty2();
37442
34665
  let guidance;
37443
- const routing = {};
37444
34666
  const observe = async (id, args) => {
37445
34667
  let result6;
37446
34668
  try {
@@ -37458,7 +34680,7 @@ var init_guided = __esm({
37458
34680
  loading.agents = this.agentView(doctor, budget, context, {
37459
34681
  rules: loading.stages.find((item) => item.id === "rules")?.state !== "working",
37460
34682
  allowance: loading.stages.find((item) => item.id === "allowance")?.state !== "working"
37461
- }, guidance, routing);
34683
+ }, guidance);
37462
34684
  };
37463
34685
  const [, , , metrics, status, benchmark] = await Promise.all([
37464
34686
  observe("agents", ["doctor"]).then((result6) => {
@@ -37498,30 +34720,7 @@ var init_guided = __esm({
37498
34720
  observe("checks", ["status"]),
37499
34721
  observe("value", ["benchmark-matrix"])
37500
34722
  ]);
37501
- await Promise.all(["claude", "codex"].map(async (harness) => {
37502
- try {
37503
- const result6 = await this.call([
37504
- "routing",
37505
- "--route-status",
37506
- "--harness",
37507
- harness
37508
- ]);
37509
- if (result6.exitCode === 0 && result6.data?.kind === "status") {
37510
- routing[harness] = {
37511
- state: result6.data.state,
37512
- mode: result6.data.mode,
37513
- gatewayState: result6.data.gatewayState,
37514
- profileId: result6.data.profileId,
37515
- launchCommand: result6.data.launchCommand,
37516
- simpleModel: result6.data.simpleModel,
37517
- availableModels: result6.data.availableModels,
37518
- detail: result6.data.detail
37519
- };
37520
- }
37521
- } catch {
37522
- }
37523
- }));
37524
- const agents = this.agentView(doctor, budget, context, { rules: true, allowance: true }, guidance, routing);
34723
+ const agents = this.agentView(doctor, budget, context, { rules: true, allowance: true }, guidance);
37525
34724
  const notices = [];
37526
34725
  if (doctor.data === null)
37527
34726
  notices.push("The agent inventory could not be read. Check the local installation and refresh.");
@@ -37549,7 +34748,7 @@ var init_guided = __esm({
37549
34748
  notices
37550
34749
  };
37551
34750
  }
37552
- agentView(doctor, budget, context, complete2, guidance, routing) {
34751
+ agentView(doctor, budget, context, complete2, guidance) {
37553
34752
  const present = (doctor.data?.harnesses ?? []).filter((item) => item.state !== "absent" && (item.harnessId === "claude" || item.harnessId === "codex"));
37554
34753
  return present.map((agent) => {
37555
34754
  const providers = (doctor.data?.providers ?? []).filter((provider) => provider.state === "configured" && provider.configuredHarnesses.includes(agent.harnessId)).map((p) => p.providerId);
@@ -37571,16 +34770,6 @@ var init_guided = __esm({
37571
34770
  setup,
37572
34771
  effort: observed?.nativeEffort?.current ?? observed?.reasoningEffort ?? null,
37573
34772
  reasoning: reasoningView(agent.harnessId, observed),
37574
- routing: routing?.[agent.harnessId] ?? {
37575
- state: "off",
37576
- mode: null,
37577
- gatewayState: "unknown",
37578
- profileId: null,
37579
- launchCommand: null,
37580
- simpleModel: null,
37581
- availableModels: [],
37582
- detail: "Smart Model Routing is not configured."
37583
- },
37584
34773
  ...guidance?.[agent.harnessId] ? { guidance: guidance[agent.harnessId] } : {},
37585
34774
  allowanceAction: allowanceAction(usage?.diagnostics ?? []),
37586
34775
  rules: agentRules(agent.harnessId, providers, context.data, guidance?.[agent.harnessId]),
@@ -37612,166 +34801,20 @@ var init_guided = __esm({
37612
34801
  const data = input;
37613
34802
  const action = String(data["action"]);
37614
34803
  const candidateAction = action === "candidate-setup" || action === "candidate-remove";
37615
- const routingAction = action === "routing-setup" || action === "routing-remove" || action === "routing-metrics";
37616
34804
  const requestedHarnesses = data["harnesses"];
37617
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;
37618
- if (Object.keys(data).some((key) => ![
37619
- "action",
37620
- "harness",
37621
- "harnesses",
37622
- "task",
37623
- "provider",
37624
- "candidate",
37625
- "routeMode",
37626
- "simpleModel"
37627
- ].includes(key)) || ![
34806
+ if (Object.keys(data).some((key) => !["action", "harness", "harnesses", "task", "provider", "candidate"].includes(key)) || ![
37628
34807
  "setup",
37629
34808
  "effort",
37630
34809
  "skill",
37631
34810
  "undo",
37632
34811
  "remove",
37633
34812
  "candidate-setup",
37634
- "candidate-remove",
37635
- "routing-setup",
37636
- "routing-remove",
37637
- "routing-metrics"
37638
- ].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["simpleModel"] !== void 0 && (typeof data["simpleModel"] !== "string" || !/^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(data["simpleModel"]) || !String(data["simpleModel"]).includes("/")) || 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 || data["simpleModel"] !== 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)
37639
34815
  throw new GuideError(400, "Choose a supported agent and action.");
37640
34816
  return this.exclusive(async () => {
37641
34817
  this.approval = null;
37642
- if (routingAction) {
37643
- const harness = String(data["harness"]);
37644
- const mode = data["routeMode"] === "conservative" ? "conservative" : "shadow";
37645
- if (action === "routing-metrics") {
37646
- this.record(`Reading local Smart Model Routing decisions for ${name(harness)}. No configuration is changed.`, "working");
37647
- const result7 = await this.call([
37648
- "routing",
37649
- "--route-metrics",
37650
- "--ccr-usage",
37651
- "--harness",
37652
- harness,
37653
- "--since",
37654
- "30d"
37655
- ]);
37656
- if (result7.exitCode !== 0 || result7.data?.kind !== "metrics") {
37657
- const message = explainGuideIssue(result7.diagnostics, `Routing activity for ${name(harness)} could not be read. No configuration changed.`);
37658
- this.record(message, "attention");
37659
- return {
37660
- ticket: null,
37661
- title: "Routing activity needs attention",
37662
- changes: [],
37663
- notices: [message],
37664
- expiresAt: null,
37665
- network: false,
37666
- restart: false
37667
- };
37668
- }
37669
- const metrics = result7.data.metrics;
37670
- const notices2 = [
37671
- `${String(metrics.retainedDecisionCount)} local routing decision${metrics.retainedDecisionCount === 1 ? "" : "s"} recorded in the last 30 days for ${name(harness)}.`,
37672
- `Shadow decisions: ${String(metrics.byMode.shadow)}. Conservative route requests: ${String(metrics.routeMutationRequestCount)}.`,
37673
- `Tiers: simple ${String(metrics.byTier.simple)}, standard ${String(metrics.byTier.standard)}, complex ${String(metrics.byTier.complex)}, critical ${String(metrics.byTier.critical)}.`,
37674
- "Routing telemetry stores classifier features and model identifiers, not prompt text. Subscription savings remain not measured until paired quality and allowance evidence exists."
37675
- ];
37676
- this.record("Routing activity read successfully.", "success");
37677
- return {
37678
- ticket: null,
37679
- title: `Smart Model Routing \xB7 ${name(harness)}`,
37680
- changes: [],
37681
- notices: notices2,
37682
- expiresAt: null,
37683
- network: false,
37684
- restart: false
37685
- };
37686
- }
37687
- const removing = action === "routing-remove";
37688
- this.record(`${removing ? "Reviewing removal of" : "Reviewing"} Smart Model Routing for ${name(harness)}. Nothing has changed yet.`, "working");
37689
- const simpleModel = mode === "conservative" && typeof data["simpleModel"] === "string" ? data["simpleModel"] : void 0;
37690
- const args = removing ? ["routing", "--rollback-ccr", "--harness", harness] : [
37691
- "routing",
37692
- "--configure-ccr",
37693
- "--harness",
37694
- harness,
37695
- "--route-mode",
37696
- mode,
37697
- ...simpleModel ? ["--route-simple-model", simpleModel] : []
37698
- ];
37699
- const result6 = await this.call(args);
37700
- const replacing = !removing && result6.diagnostics.some((entry) => entry.code === "ccr-route-mode-requires-rollback");
37701
- if ((result6.exitCode !== 0 || result6.data === null) && !replacing) {
37702
- const message = explainGuideIssue(result6.diagnostics, `No safe Smart Model Routing ${removing ? "removal" : "setup"} is available for ${name(harness)}. Nothing was changed.`);
37703
- this.record(message, "attention");
37704
- return {
37705
- ticket: null,
37706
- title: "No routing change to apply",
37707
- changes: [],
37708
- notices: [message],
37709
- expiresAt: null,
37710
- network: false,
37711
- restart: false
37712
- };
37713
- }
37714
- const report = result6.data;
37715
- const alreadyConfigured = !removing && report?.kind === "ccr-configuration" && report.state === "already-configured";
37716
- const alreadyAbsent = removing && report?.kind === "ccr-configuration" && report.state === "already-absent";
37717
- if (alreadyConfigured || alreadyAbsent) {
37718
- 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.`;
37719
- this.record(message, "success");
37720
- return {
37721
- ticket: null,
37722
- title: alreadyConfigured ? "Routing already configured" : "Routing already absent",
37723
- changes: [],
37724
- notices: [message],
37725
- expiresAt: null,
37726
- network: false,
37727
- restart: false
37728
- };
37729
- }
37730
- const ticket = this.random();
37731
- const expires2 = this.now() + 10 * 6e4;
37732
- const lifecycle = report?.kind === "ccr-lifecycle";
37733
- const network2 = Boolean(lifecycle && report?.kind === "ccr-lifecycle" && report.action !== "start");
37734
- this.approval = {
37735
- id: ticket,
37736
- expires: expires2,
37737
- plans: [],
37738
- transactionId: null,
37739
- provider: null,
37740
- description: `Smart Model Routing ${removing ? "removal" : mode}`,
37741
- operation: removing ? "routing-rollback" : "routing-configure",
37742
- network: network2,
37743
- routingHarness: harness,
37744
- routingMode: mode,
37745
- ...simpleModel ? { routingSimpleModel: simpleModel } : {},
37746
- ...replacing ? { routingReplace: true } : {}
37747
- };
37748
- const change = replacing ? {
37749
- title: `${name(harness)}: change Smart Model Routing to ${mode}`,
37750
- files: 0,
37751
- description: "Replace only the Token Harness-owned routing rule/profile for this coding agent, preserving unrelated CCR settings and provider credentials."
37752
- } : report?.kind === "ccr-lifecycle" ? {
37753
- title: `${name(harness)}: prepare local CCR routing runtime`,
37754
- files: 0,
37755
- 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.`
37756
- } : {
37757
- title: `${name(harness)}: ${removing ? "remove" : "configure"} Smart Model Routing`,
37758
- files: 0,
37759
- 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."
37760
- };
37761
- this.record("Smart Model Routing preview ready. Waiting for your approval.", "success");
37762
- return {
37763
- ticket,
37764
- title: removing ? `Remove Smart Model Routing for ${name(harness)}?` : `Set up ${mode} Smart Model Routing for ${name(harness)}?`,
37765
- changes: [change],
37766
- notices: [
37767
- lifecycle && !removing ? "This approval prepares the Token Harness-owned CCR runtime and then completes the selected routing mode in the same flow." : replacing ? "This approval removes only the existing Token Harness-owned routing rule/profile and replaces it with the selected mode." : "Token Harness owns only its exact CCR rule/profile and local managed runtime. Provider credentials remain in CCR and are never imported silently.",
37768
- mode === "shadow" && !removing ? "Shadow mode is the default: it never changes the model selected for a request." : mode === "conservative" && !removing ? `Conservative routing will use ${simpleModel ?? "no selected model"} for high-confidence simple requests.` : "Removing routing does not uninstall CCR or delete provider credentials."
37769
- ],
37770
- expiresAt: new Date(expires2).toISOString(),
37771
- network: network2,
37772
- restart: false
37773
- };
37774
- }
37775
34818
  if (candidateAction) {
37776
34819
  const candidate = String(data["candidate"]);
37777
34820
  const harness = String(data["harness"]);
@@ -38172,114 +35215,6 @@ var init_guided = __esm({
38172
35215
  appliedPlans: appliedCount
38173
35216
  };
38174
35217
  }
38175
- if (approval.operation === "routing-configure" || approval.operation === "routing-rollback") {
38176
- if (approval.routingHarness === void 0 || approval.routingMode === void 0)
38177
- throw new GuideError(409, "This Smart Model Routing preview is incomplete. Review it again.");
38178
- const harness = approval.routingHarness;
38179
- const mode = approval.routingMode;
38180
- const removing = approval.operation === "routing-rollback";
38181
- this.record((removing ? "Removing" : "Applying") + " Smart Model Routing for " + name(harness) + ".", "working");
38182
- let result6;
38183
- const configureArgs = [
38184
- "routing",
38185
- "--configure-ccr",
38186
- "--harness",
38187
- harness,
38188
- "--route-mode",
38189
- mode,
38190
- ...approval.routingSimpleModel ? ["--route-simple-model", approval.routingSimpleModel] : [],
38191
- "--yes"
38192
- ];
38193
- try {
38194
- if (!removing && approval.routingReplace) {
38195
- const removed = await this.call([
38196
- "routing",
38197
- "--rollback-ccr",
38198
- "--harness",
38199
- harness,
38200
- "--yes"
38201
- ]);
38202
- if (removed.exitCode !== 0 || removed.data?.kind !== "ccr-configuration" || !["rolled-back", "already-absent"].includes(removed.data.state)) {
38203
- result6 = removed;
38204
- } else {
38205
- result6 = await this.call(configureArgs);
38206
- }
38207
- } else {
38208
- result6 = await this.call(removing ? ["routing", "--rollback-ccr", "--harness", harness, "--yes"] : configureArgs);
38209
- }
38210
- if (!removing && result6.exitCode === 0 && result6.data?.kind === "ccr-lifecycle") {
38211
- result6 = await this.call(configureArgs);
38212
- }
38213
- } catch {
38214
- this.invalidateObservedState();
38215
- 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.";
38216
- this.record(message, "attention");
38217
- return {
38218
- ok: false,
38219
- title: "Routing result needs checking",
38220
- messages: [message],
38221
- appliedPlans: 0
38222
- };
38223
- }
38224
- if (result6.exitCode !== 0 || result6.data === null) {
38225
- 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.");
38226
- this.invalidateObservedState();
38227
- this.record(message, "attention");
38228
- return {
38229
- ok: false,
38230
- title: "Routing change was not applied",
38231
- messages: [message],
38232
- appliedPlans: 0
38233
- };
38234
- }
38235
- const report = result6.data;
38236
- this.lastApplied = null;
38237
- this.invalidateObservedState();
38238
- if (report.kind === "ccr-lifecycle") {
38239
- 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.";
38240
- this.record("CCR routing runtime prepared and verified.", "success");
38241
- return {
38242
- ok: true,
38243
- title: "Routing runtime ready",
38244
- messages: [
38245
- message,
38246
- "Provider login/import remains an explicit CCR choice; Token Harness did not change Claude Code or Codex native endpoints."
38247
- ],
38248
- appliedPlans: report.state === "already-current" ? 0 : 1
38249
- };
38250
- }
38251
- if (report.kind !== "ccr-configuration") {
38252
- 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.";
38253
- this.record(message, "attention");
38254
- return {
38255
- ok: false,
38256
- title: "Routing result needs checking",
38257
- messages: [message],
38258
- appliedPlans: 0
38259
- };
38260
- }
38261
- const changed = report.state === "configured" || report.state === "rolled-back";
38262
- const messages2 = removing ? [
38263
- 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."
38264
- ] : [
38265
- 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.",
38266
- ...mode === "shadow" ? [
38267
- "Shadow mode records local routing decisions but does not change the request model."
38268
- ] : [
38269
- "Conservative mode may request the configured simple model only for high-confidence simple prompts; safety-gated requests pass through unchanged."
38270
- ],
38271
- ...report.launchCommand ? ["Launch through the CCR profile to use the rule: " + report.launchCommand] : [
38272
- "CCR still needs an unambiguous provider/model profile before a routed launch can be verified."
38273
- ]
38274
- ];
38275
- this.record(removing ? "Smart Model Routing rule removed." : "Smart Model Routing configured.", "success");
38276
- return {
38277
- ok: true,
38278
- title: removing ? "Routing removed" : "Smart Model Routing configured",
38279
- messages: messages2,
38280
- appliedPlans: changed ? 1 : 0
38281
- };
38282
- }
38283
35218
  if (approval.operation === "candidate-apply" || approval.operation === "candidate-uninstall") {
38284
35219
  if (approval.candidate === void 0 || approval.candidateHarness === void 0)
38285
35220
  throw new GuideError(409, "This experimental preview is incomplete. Review it again.");
@@ -41099,40 +38034,6 @@ var init_guided_product_client = __esm({
41099
38034
  'caption',
41100
38035
  ),
41101
38036
  );
41102
- const routing = agent.routing || {
41103
- state: 'off',
41104
- mode: null,
41105
- detail: 'Smart Model Routing is not configured.',
41106
- simpleModel: null,
41107
- availableModels: [],
41108
- };
41109
- const routingRow = node('div', undefined, 'maintenance-row agent-routing-row');
41110
- const routingCopy = node('div');
41111
- const routingLabel =
41112
- routing.state === 'shadow'
41113
- ? 'Shadow'
41114
- : routing.state === 'conservative'
41115
- ? 'Conservative'
41116
- : routing.state === 'attention'
41117
- ? 'Needs attention'
41118
- : 'Off';
41119
- routingCopy.append(
41120
- node('strong', 'Smart Model Routing'),
41121
- node('p', routing.detail || 'Optional prompt routing for this coding agent.', 'caption'),
41122
- );
41123
- const routingActions = node('div', undefined, 'inline-actions');
41124
- if (routing.state === 'off') {
41125
- routingActions.append(
41126
- actionButton('Enable', () => enableRouting(agent.id)),
41127
- );
41128
- } else {
41129
- routingActions.append(
41130
- actionButton('Configure', () => configureRouting(agent.id), routing.state === 'attention' ? '' : 'secondary'),
41131
- actionButton('Disable', () => disableRouting(agent.id), 'secondary'),
41132
- );
41133
- }
41134
- routingRow.append(routingCopy, pill(routingLabel, routing.state === 'attention' ? 'warn' : routing.state === 'off' ? '' : 'good'), routingActions);
41135
- card.append(routingRow);
41136
38037
  if (baseline.unavailable.length) {
41137
38038
  const details = node('details', undefined, 'agent-details');
41138
38039
  details.append(node('summary', 'Connection limitations'));
@@ -41758,193 +38659,6 @@ var init_guided_product_client = __esm({
41758
38659
  }
41759
38660
 
41760
38661
 
41761
- function reviewRoutingAction(harness, action, routeMode, run, simpleModel = null) {
41762
- const label =
41763
- action === 'routing-metrics'
41764
- ? 'Reading routing activity'
41765
- : action === 'routing-remove'
41766
- ? 'Reviewing routing removal'
41767
- : 'Reviewing ' + routeMode + ' routing';
41768
- $('modal-content').replaceChildren(
41769
- progress(label, 'Nothing changes while Token Harness checks the current local routing state.'),
41770
- );
41771
- $('modal-actions').replaceChildren(modalClose('Cancel'));
41772
- setBusy(true, false);
41773
- ensureSession()
41774
- .then(() =>
41775
- request('/api/preview', {
41776
- action,
41777
- harness,
41778
- ...(action === 'routing-setup'
41779
- ? {
41780
- routeMode,
41781
- ...(simpleModel ? { simpleModel } : {}),
41782
- }
41783
- : {}),
41784
- }),
41785
- )
41786
- .then(data => {
41787
- if (run !== modalRun || !$('modal').open) return;
41788
- pendingTicket = data.ticket;
41789
- $('modal-content').replaceChildren(
41790
- messageBox(
41791
- 'Smart Model Routing · ' + agentName(harness),
41792
- action === 'routing-metrics'
41793
- ? 'Local routing activity only. Prompt text and credentials are not shown.'
41794
- : action === 'routing-remove'
41795
- ? 'Smart Model Routing will be turned off for this coding agent. CCR and provider credentials stay in place.'
41796
- : routeMode === 'shadow'
41797
- ? 'Shadow mode observes and classifies requests locally without changing the selected model.'
41798
- : 'Conservative mode may use ' + simpleModel + ' only for high-confidence simple requests; safety-gated requests keep their current model.',
41799
- ),
41800
- );
41801
- for (const change of data.changes || []) {
41802
- const item = node('article', undefined, 'preview-change');
41803
- item.append(node('h3', change.title), node('p', change.description));
41804
- $('modal-content').append(item);
41805
- }
41806
- for (const notice of data.notices || [])
41807
- $('modal-content').append(node('p', notice, 'notice-row'));
41808
- if (action !== 'routing-metrics')
41809
- $('modal-content').append(
41810
- messageBox(
41811
- 'Safety',
41812
- 'Token Harness changes only its owned CCR routing state. Existing provider credentials and unrelated CCR settings are preserved.',
41813
- 'safe',
41814
- ),
41815
- );
41816
- $('modal-actions').replaceChildren(modalClose(data.ticket ? 'Cancel' : 'Done'));
41817
- if (data.ticket)
41818
- $('modal-actions').append(
41819
- actionButton(
41820
- action === 'routing-remove'
41821
- ? 'Disable routing'
41822
- : routeMode === 'conservative'
41823
- ? 'Apply conservative mode'
41824
- : 'Enable shadow mode',
41825
- () => applyTicket(data.ticket),
41826
- ),
41827
- );
41828
- })
41829
- .catch(error => {
41830
- if (run !== modalRun) return;
41831
- $('modal-error').textContent = error.message;
41832
- $('modal-error').hidden = false;
41833
- $('modal-actions').replaceChildren(modalClose('Close'));
41834
- })
41835
- .finally(() => {
41836
- if (run === modalRun) setBusy(false, false);
41837
- loadActivity();
41838
- });
41839
- }
41840
-
41841
- function enableRouting(harness) {
41842
- if (busy) return;
41843
- const run = modal('Enable Smart Model Routing · ' + agentName(harness));
41844
- reviewRoutingAction(harness, 'routing-setup', 'shadow', run);
41845
- }
41846
-
41847
- function disableRouting(harness) {
41848
- if (busy) return;
41849
- const run = modal('Disable Smart Model Routing · ' + agentName(harness));
41850
- reviewRoutingAction(harness, 'routing-remove', 'shadow', run);
41851
- }
41852
-
41853
- function configureRouting(harness) {
41854
- if (busy) return;
41855
- const agent = activeAgents().find(item => item.id === harness);
41856
- const routing = agent?.routing || {
41857
- state: 'off',
41858
- mode: null,
41859
- simpleModel: null,
41860
- availableModels: [],
41861
- detail: '',
41862
- };
41863
- const run = modal('Configure Smart Model Routing · ' + agentName(harness));
41864
- $('modal-content').append(
41865
- messageBox(
41866
- 'Current state',
41867
- routing.state === 'shadow'
41868
- ? 'Shadow is enabled. Requests keep their selected model.'
41869
- : routing.state === 'conservative'
41870
- ? 'Conservative routing is enabled' + (routing.simpleModel ? ' with ' + routing.simpleModel + '.' : '.')
41871
- : routing.state === 'attention'
41872
- ? 'The saved routing state needs attention. Reviewing a configuration change will re-check ownership before anything is modified.'
41873
- : 'Smart Model Routing is currently off.',
41874
- routing.state === 'attention' ? 'warn' : routing.state === 'off' ? '' : 'safe',
41875
- ),
41876
- );
41877
-
41878
- const form = node('div', undefined, 'setup-choice-list');
41879
- const modeLabel = node('label', undefined, 'setup-choice-copy');
41880
- modeLabel.append(node('strong', 'Mode'));
41881
- const modeSelect = node('select');
41882
- const shadow = node('option', 'Shadow — observe only');
41883
- shadow.value = 'shadow';
41884
- const conservative = node('option', 'Conservative — route simple prompts');
41885
- conservative.value = 'conservative';
41886
- modeSelect.append(shadow, conservative);
41887
- modeSelect.value = routing.mode || 'shadow';
41888
- modeLabel.append(modeSelect);
41889
- form.append(modeLabel);
41890
-
41891
- const modelWrap = node('label', undefined, 'setup-choice-copy');
41892
- modelWrap.append(node('strong', 'Simple model'));
41893
- const modelSelect = node('select');
41894
- const models = routing.availableModels || [];
41895
- if (!models.length) {
41896
- const none = node('option', 'No configured CCR model available');
41897
- none.value = '';
41898
- modelSelect.append(none);
41899
- modelSelect.disabled = true;
41900
- } else {
41901
- for (const model of models) {
41902
- const option = node('option', model);
41903
- option.value = model;
41904
- modelSelect.append(option);
41905
- }
41906
- if (routing.simpleModel && models.includes(routing.simpleModel))
41907
- modelSelect.value = routing.simpleModel;
41908
- }
41909
- modelWrap.append(
41910
- modelSelect,
41911
- node('span', 'Used only in Conservative mode. The model must already exist in CCR.', 'caption'),
41912
- );
41913
- form.append(modelWrap);
41914
- $('modal-content').append(form);
41915
-
41916
- const activityDetails = node('details', undefined, 'agent-details');
41917
- activityDetails.append(
41918
- node('summary', 'Advanced'),
41919
- node('p', 'Routing decisions are stored separately from optimizer savings. Shadow activity can be inspected without enabling model changes.', 'caption'),
41920
- );
41921
- const activityActions = node('div', undefined, 'inline-actions');
41922
- activityActions.append(
41923
- actionButton(
41924
- 'View 30-day activity',
41925
- () => reviewRoutingAction(harness, 'routing-metrics', 'shadow', run),
41926
- 'secondary',
41927
- ),
41928
- );
41929
- activityDetails.append(activityActions);
41930
- $('modal-content').append(activityDetails);
41931
-
41932
- const review = actionButton('Review change', () => {
41933
- const mode = modeSelect.value;
41934
- const model = mode === 'conservative' ? modelSelect.value : null;
41935
- reviewRoutingAction(harness, 'routing-setup', mode, run, model);
41936
- });
41937
- const update = () => {
41938
- const conservativeMode = modeSelect.value === 'conservative';
41939
- modelWrap.hidden = !conservativeMode;
41940
- review.disabled = conservativeMode && !modelSelect.value;
41941
- };
41942
- modeSelect.addEventListener('change', update);
41943
- modelSelect.addEventListener('change', update);
41944
- $('modal-actions').append(modalClose('Cancel'), review);
41945
- update();
41946
- }
41947
-
41948
38662
  function renderMaintenance() {
41949
38663
  const root = $('maintenance-actions');
41950
38664
  root.replaceChildren();
@@ -43361,9 +40075,9 @@ function createGuideHandler(input) {
43361
40075
  return;
43362
40076
  }
43363
40077
  send(404, '{"error":"Not found"}');
43364
- } catch (error2) {
43365
- send(error2 instanceof GuideError ? error2.status : 500, JSON.stringify({
43366
- 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."
43367
40081
  }));
43368
40082
  }
43369
40083
  };
@@ -43390,7 +40104,7 @@ var init_guided_http = __esm({
43390
40104
  });
43391
40105
 
43392
40106
  // apps/cli/dist/src/commands/rtk-hook-proxy.js
43393
- function isRecord7(value3) {
40107
+ function isRecord5(value3) {
43394
40108
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
43395
40109
  }
43396
40110
  function shellQuote(value3) {
@@ -43402,7 +40116,7 @@ function powershellQuote(value3) {
43402
40116
  function toolNameFromInput(input, harness) {
43403
40117
  try {
43404
40118
  const parsed = JSON.parse(input);
43405
- if (!isRecord7(parsed))
40119
+ if (!isRecord5(parsed))
43406
40120
  return null;
43407
40121
  const name2 = parsed["tool_name"] ?? parsed["toolName"];
43408
40122
  if (typeof name2 === "string")
@@ -43430,13 +40144,13 @@ function attributeRtkHookResponse(stdout, input, databasePath, harness) {
43430
40144
  } catch {
43431
40145
  return stdout;
43432
40146
  }
43433
- if (!isRecord7(response))
40147
+ if (!isRecord5(response))
43434
40148
  return stdout;
43435
40149
  const hookOutput = response["hookSpecificOutput"];
43436
- if (!isRecord7(hookOutput))
40150
+ if (!isRecord5(hookOutput))
43437
40151
  return stdout;
43438
40152
  const updatedInput = hookOutput["updatedInput"];
43439
- if (!isRecord7(updatedInput) || typeof updatedInput["command"] !== "string")
40153
+ if (!isRecord5(updatedInput) || typeof updatedInput["command"] !== "string")
43440
40154
  return stdout;
43441
40155
  const attributed = withDatabaseEnvironment(updatedInput["command"], databasePath, toolNameFromInput(input, harness));
43442
40156
  if (attributed === null)
@@ -43488,7 +40202,7 @@ __export(main_exports, {
43488
40202
  });
43489
40203
  import process5 from "node:process";
43490
40204
  import { createServer } from "node:http";
43491
- import { randomBytes as randomBytes3 } from "node:crypto";
40205
+ import { randomBytes as randomBytes2 } from "node:crypto";
43492
40206
  async function runAsDatabaseReader(argv2) {
43493
40207
  if (argv2[0] !== SQLITE_CHILD_FLAG)
43494
40208
  return false;
@@ -43701,8 +40415,8 @@ async function runUi(options, baseOptions) {
43701
40415
  let initial;
43702
40416
  try {
43703
40417
  initial = await collectDashboard(baseOptions);
43704
- } catch (error2) {
43705
- const message = error2 instanceof Error ? error2.message : String(error2);
40418
+ } catch (error) {
40419
+ const message = error instanceof Error ? error.message : String(error);
43706
40420
  if (options.json) {
43707
40421
  process5.stdout.write(serializeEnvelope(toEnvelope(commandResult({
43708
40422
  command: "ui",
@@ -43776,8 +40490,8 @@ async function runUi(options, baseOptions) {
43776
40490
  server.once("error", reject);
43777
40491
  server.listen(options.port, "127.0.0.1", () => resolve());
43778
40492
  });
43779
- } catch (error2) {
43780
- 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)}
43781
40495
  `);
43782
40496
  return EXIT_CODES["internal-error"];
43783
40497
  }
@@ -43804,7 +40518,7 @@ async function runGuidedUi(options, base) {
43804
40518
  }
43805
40519
  return result6;
43806
40520
  };
43807
- 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) => {
43808
40522
  if (base.adapters === null || base.adapters === void 0) {
43809
40523
  return {
43810
40524
  state: "unavailable",
@@ -43819,7 +40533,7 @@ async function runGuidedUi(options, base) {
43819
40533
  harness
43820
40534
  });
43821
40535
  });
43822
- const token = randomBytes3(32).toString("hex");
40536
+ const token = randomBytes2(32).toString("hex");
43823
40537
  let authority = "";
43824
40538
  const server = createServer(createGuideHandler({
43825
40539
  service,