token-harness 0.1.20 → 0.1.21

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "token-harness",
3
- "version": "0.1.20",
3
+ "version": "0.1.21",
4
4
  "description": "Quota-aware efficiency layer for Claude Code and Codex subscription limits.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
package/sbom.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "bomFormat": "CycloneDX",
3
3
  "specVersion": "1.5",
4
- "serialNumber": "urn:uuid:6a907cd9-4778-ca06-b653-78caf2cf25f0",
4
+ "serialNumber": "urn:uuid:c41dcc70-e6f7-7524-9366-fd396457b2bd",
5
5
  "version": 1,
6
6
  "metadata": {
7
7
  "component": {
8
8
  "type": "application",
9
9
  "bom-ref": "token-harness",
10
10
  "name": "token-harness",
11
- "version": "0.1.20",
11
+ "version": "0.1.21",
12
12
  "description": "Quota-aware efficiency layer for Claude Code and Codex subscription limits.",
13
13
  "licenses": [
14
14
  {
@@ -20,7 +20,7 @@
20
20
  "hashes": [
21
21
  {
22
22
  "alg": "SHA-256",
23
- "content": "6a907cd94778ca06b65378caf2cf25f060cc82a51168e1cd611f5f58b5e19e55"
23
+ "content": "c41dcc70e6f775249366fd396457b2bdfb915241c39f4f8a9784d040b86bce49"
24
24
  }
25
25
  ]
26
26
  },
package/token-harness.mjs CHANGED
@@ -10068,7 +10068,7 @@ var TOOL_VERSION;
10068
10068
  var init_version2 = __esm({
10069
10069
  "apps/cli/dist/src/version.js"() {
10070
10070
  "use strict";
10071
- TOOL_VERSION = "0.1.20";
10071
+ TOOL_VERSION = "0.1.21";
10072
10072
  }
10073
10073
  });
10074
10074
 
@@ -22263,9 +22263,6 @@ function stableJson(value3) {
22263
22263
  function isExactCcrSmartRoutingRule(value3, expected) {
22264
22264
  return isRecord6(value3) && stableJson(value3) === stableJson(expected);
22265
22265
  }
22266
- function isSameCcrConfig(left, right) {
22267
- return isRecord6(left) && isRecord6(right) && stableJson(left) === stableJson(right);
22268
- }
22269
22266
  function configRouter(config) {
22270
22267
  if (!isRecord6(config) || !isRecord6(config["Router"]) || !Array.isArray(config["Router"]["rules"])) {
22271
22268
  return null;
@@ -22831,7 +22828,9 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22831
22828
  nativePolicy: false,
22832
22829
  routingScript: false,
22833
22830
  routingMetrics: false,
22831
+ routingStatus: false,
22834
22832
  routingMode: "shadow",
22833
+ routingSimpleModel: null,
22835
22834
  routingPrune: false,
22836
22835
  routingCcrConfigure: false,
22837
22836
  routingCcrRollback: false,
@@ -22880,6 +22879,8 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22880
22879
  options.routingScript = true;
22881
22880
  if (name2 === "--route-metrics")
22882
22881
  options.routingMetrics = true;
22882
+ if (name2 === "--route-status")
22883
+ options.routingStatus = true;
22883
22884
  if (name2 === "--prune")
22884
22885
  options.routingPrune = true;
22885
22886
  if (name2 === "--configure-ccr")
@@ -23095,6 +23096,18 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
23095
23096
  }
23096
23097
  break;
23097
23098
  }
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;
23098
23111
  case "--route-mode":
23099
23112
  if (value3 !== "shadow" && value3 !== "conservative") {
23100
23113
  diagnostics.push(diagnostic({
@@ -23207,6 +23220,7 @@ var init_argv = __esm({
23207
23220
  "--reserve",
23208
23221
  "--tasks-left",
23209
23222
  "--route-mode",
23223
+ "--route-simple-model",
23210
23224
  "--context-snapshot"
23211
23225
  ]);
23212
23226
  BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
@@ -23217,6 +23231,7 @@ var init_argv = __esm({
23217
23231
  "--yes",
23218
23232
  "--script",
23219
23233
  "--route-metrics",
23234
+ "--route-status",
23220
23235
  "--prune",
23221
23236
  "--configure-ccr",
23222
23237
  "--rollback-ccr",
@@ -30755,7 +30770,7 @@ async function readOwnership(context, harness) {
30755
30770
  try {
30756
30771
  const bytes = await context.adapters.fs.readFile(path);
30757
30772
  const value3 = JSON.parse(new TextDecoder().decode(bytes));
30758
- if (isJsonRecord(value3) && value3["schemaVersion"] === 1 && (value3["status"] === "pending" || value3["status"] === "active") && value3["harnessId"] === harness && (value3["mode"] === "shadow" || value3["mode"] === "conservative") && value3["ruleId"] === ccrSmartRoutingRuleId(harness) && typeof value3["scriptPath"] === "string" && /^[a-f0-9]{64}$/.test(String(value3["scriptSha256"])) && (value3["profileId"] === void 0 || typeof value3["profileId"] === "string") && (value3["profileSha256"] === void 0 || /^[a-f0-9]{64}$/.test(String(value3["profileSha256"]))) && value3["profileId"] === void 0 === (value3["profileSha256"] === void 0) && typeof value3["installedAt"] === "string") {
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") {
30759
30774
  return value3;
30760
30775
  }
30761
30776
  } catch {
@@ -30894,6 +30909,15 @@ function planCcrProfile(config, harness, selectedModel) {
30894
30909
  }
30895
30910
  return { profile, profileContainer, conflict: false, reason: null };
30896
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
+ }
30897
30921
  function configuredCcrModel(config, requested) {
30898
30922
  const candidate = requested?.trim();
30899
30923
  if (candidate === void 0 || !/^[A-Za-z0-9_.:/@+ -]{1,160}$/.test(candidate))
@@ -30971,6 +30995,58 @@ function profilePlanDiagnostic(plan6) {
30971
30995
  remediation: `Resolve the CCR profile setup requirement and rerun routing setup; provider login/import and credential changes remain explicit CCR actions`
30972
30996
  });
30973
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
+ }
30974
31050
  async function ccrConfiguration(context) {
30975
31051
  const fs = context.adapters?.fs;
30976
31052
  if (fs === void 0 || context.stateRoot === null || !isSmartRoutingHarness(context.harness)) {
@@ -31000,7 +31076,7 @@ async function ccrConfiguration(context) {
31000
31076
  message: "TOKEN_HARNESS_ROUTING_PROFILE_MODEL did not match a model in the selected CCR provider and was not applied",
31001
31077
  remediation: "Set it to the exact Provider/model alias from CCR, then roll back and preview setup again"
31002
31078
  }) : null;
31003
- const requestedSimpleModel = context.env?.["TOKEN_HARNESS_ROUTING_SIMPLE_MODEL"];
31079
+ const requestedSimpleModel = context.routingSimpleModel ?? context.env?.["TOKEN_HARNESS_ROUTING_SIMPLE_MODEL"];
31004
31080
  const configuredSimpleModel = configuredCcrModel(ccr.config, requestedSimpleModel);
31005
31081
  const simpleModelWarning = requestedSimpleModel?.trim() && configuredSimpleModel === null ? diagnostic({
31006
31082
  severity: "warning",
@@ -31060,10 +31136,17 @@ async function ccrConfiguration(context) {
31060
31136
  ], String(profilePlan.profile["id"]), ccrLaunchCommand(harnessId2));
31061
31137
  }
31062
31138
  try {
31063
- const currentConfig = await ccr.client.call("getConfig");
31064
- if (!isSameCcrConfig(currentConfig, ccr.config))
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)
31065
31148
  throw new CcrManagementError("config-drift");
31066
- await ccr.client.call("saveConfig", [profileConfig, { applyProfile: false }]);
31149
+ await ccr.client.call("saveConfig", [latestProfileConfig, { applyProfile: false }]);
31067
31150
  const afterConfig = await ccr.client.call("getConfig");
31068
31151
  const afterRouter = isJsonRecord(afterConfig) ? afterConfig["Router"] : null;
31069
31152
  const afterRules = isJsonRecord(afterRouter) && Array.isArray(afterRouter["rules"]) ? afterRouter["rules"] : [];
@@ -31118,6 +31201,9 @@ async function ccrConfiguration(context) {
31118
31201
  if (targetFile !== null) {
31119
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");
31120
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
+ }
31121
31207
  if (!context.confirmed) {
31122
31208
  const profileDiagnostic = profilePlanDiagnostic(profilePlan);
31123
31209
  return configurationResult("configure", "preview", ccr, harnessId2, mode, ruleId, path, [
@@ -31156,14 +31242,6 @@ async function ccrConfiguration(context) {
31156
31242
  if (!validateRouteRuleResult(validation)) {
31157
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");
31158
31244
  }
31159
- const withRule = addCcrSmartRoutingRule(ccr.config, expectedRule);
31160
- if (withRule === null) {
31161
- return error("ccr-routing-rule-conflict", "CCR routing rules changed or cannot accept a script rule", "Refresh CCR state and review existing rules before retrying");
31162
- }
31163
- const nextConfig = profilePlan.profile === null ? withRule : withCcrProfile(withRule, profilePlan.profile);
31164
- if (nextConfig === null) {
31165
- return error("ccr-profile-config-conflict", "CCR Agent Profile settings changed or cannot accept the Token Harness profile", "Review CCR Agent Config and retry from a new preview");
31166
- }
31167
31245
  const now = context.now();
31168
31246
  const ownership = {
31169
31247
  schemaVersion: 1,
@@ -31173,6 +31251,7 @@ async function ccrConfiguration(context) {
31173
31251
  ruleId,
31174
31252
  scriptPath: path,
31175
31253
  scriptSha256: scriptHash(script),
31254
+ ...configuredSimpleModel === null ? {} : { simpleModel: configuredSimpleModel },
31176
31255
  installedAt: now
31177
31256
  };
31178
31257
  let saveAttempted = false;
@@ -31181,12 +31260,33 @@ async function ccrConfiguration(context) {
31181
31260
  await fs.createDirectory(scriptDirectory(context));
31182
31261
  await writeJson4(context, receiptPath3(context, harnessId2), ownership);
31183
31262
  await fs.writeFile(path, new TextEncoder().encode(script));
31184
- const currentConfig = await ccr.client.call("getConfig");
31185
- if (!isSameCcrConfig(currentConfig, ccr.config)) {
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)) {
31186
31280
  throw new CcrManagementError("config-drift");
31187
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");
31188
31288
  saveAttempted = true;
31189
- await ccr.client.call("saveConfig", [nextConfig, { applyProfile: false }]);
31289
+ await ccr.client.call("saveConfig", [latestNextConfig, { applyProfile: false }]);
31190
31290
  const afterConfig = await ccr.client.call("getConfig");
31191
31291
  const afterRouter = isJsonRecord(afterConfig) ? afterConfig["Router"] : null;
31192
31292
  const afterRules = isJsonRecord(afterRouter) && Array.isArray(afterRouter["rules"]) ? afterRouter["rules"] : [];
@@ -31305,15 +31405,18 @@ async function rollbackCcrConfiguration(context) {
31305
31405
  ], ownership.profileId ?? null, ownership.profileId === void 0 ? null : ccrLaunchCommand(harnessId2));
31306
31406
  }
31307
31407
  if (ownership.profileId !== void 0) {
31308
- const nextConfig2 = withoutOwnedCcrProfile(ccr.config, ownership.profileId, ownership.profileSha256);
31309
- if (nextConfig2 === null) {
31408
+ const nextConfig = withoutOwnedCcrProfile(ccr.config, ownership.profileId, ownership.profileSha256);
31409
+ if (nextConfig === null) {
31310
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");
31311
31411
  }
31312
31412
  try {
31313
- const currentConfig = await ccr.client.call("getConfig");
31314
- if (!isSameCcrConfig(currentConfig, ccr.config))
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)
31315
31418
  throw new CcrManagementError("config-drift");
31316
- await ccr.client.call("saveConfig", [nextConfig2, { applyProfile: false }]);
31419
+ await ccr.client.call("saveConfig", [latestNextConfig, { applyProfile: false }]);
31317
31420
  const afterConfig = await ccr.client.call("getConfig");
31318
31421
  if (profileRows(isJsonRecord(afterConfig) ? afterConfig : {}).some((item) => isJsonRecord(item) && item["id"] === ownership.profileId)) {
31319
31422
  throw new CcrManagementError("request-failed");
@@ -31356,20 +31459,17 @@ async function rollbackCcrConfiguration(context) {
31356
31459
  ]
31357
31460
  ], ownership.profileId ?? null, ownership.profileId === void 0 ? null : ccrLaunchCommand(harnessId2));
31358
31461
  }
31359
- const withoutRule = removeOwnedCcrSmartRoutingRule(ccr.config, ownership.ruleId, expectedRule);
31360
- if (withoutRule === null) {
31361
- return error("ccr-owned-rule-drift", "CCR rules changed while rollback was being prepared", "Refresh the CCR state and retry after reviewing the rule list");
31362
- }
31363
- const nextConfig = ownership.profileId === void 0 ? withoutRule : withoutOwnedCcrProfile(withoutRule, ownership.profileId, ownership.profileSha256);
31364
- if (nextConfig === null) {
31365
- return error("ccr-owned-profile-drift", "The Token Harness CCR profile changed while rollback was being prepared", "Refresh CCR state and retry after reviewing the profile");
31366
- }
31367
31462
  try {
31368
- const currentConfig = await ccr.client.call("getConfig");
31369
- if (!isSameCcrConfig(currentConfig, ccr.config)) {
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)
31370
31468
  throw new CcrManagementError("config-drift");
31371
- }
31372
- await ccr.client.call("saveConfig", [nextConfig, { applyProfile: false }]);
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 }]);
31373
31473
  const after = await ccr.client.call("getConfig");
31374
31474
  const afterRules = isJsonRecord(after) && isJsonRecord(after["Router"]) && Array.isArray(after["Router"]["rules"]) ? after["Router"]["rules"] : [];
31375
31475
  if (afterRules.some((item) => isJsonRecord(item) && item["id"] === ownership.ruleId)) {
@@ -31414,19 +31514,23 @@ async function rollbackCcrConfiguration(context) {
31414
31514
  async function runSmartRouting(context) {
31415
31515
  const wantsScript = context.routingScript === true;
31416
31516
  const wantsMetrics = context.routingMetrics === true;
31517
+ const wantsStatus = context.routingStatus === true;
31417
31518
  const wantsCcrConfigure = context.routingCcrConfigure === true;
31418
31519
  const wantsCcrRollback = context.routingCcrRollback === true;
31419
31520
  const wantsCcrUpdate = context.routingCcrUpdate === true;
31420
31521
  const requestedActions = [
31421
31522
  wantsScript,
31422
31523
  wantsMetrics,
31524
+ wantsStatus,
31423
31525
  wantsCcrConfigure,
31424
31526
  wantsCcrRollback,
31425
31527
  wantsCcrUpdate
31426
31528
  ].filter(Boolean).length;
31427
31529
  if (requestedActions !== 1) {
31428
- return error("routing-action-required", "Choose one Smart Model Routing action", "Use `token-harness routing --script --harness claude`, `--configure-ccr`, `--update-ccr`, `--rollback-ccr`, or `--route-metrics`");
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`");
31429
31531
  }
31532
+ if (wantsStatus)
31533
+ return smartRoutingStatus(context);
31430
31534
  if (context.routingPrune === true && !wantsMetrics) {
31431
31535
  return error("routing-prune-requires-metrics", "`--prune` is available only with the routing metrics action", "Use `token-harness routing --route-metrics --prune`");
31432
31536
  }
@@ -34888,6 +34992,16 @@ function renderSmartRoutingReport(report) {
34888
34992
  if (report.kind === "ccr-script")
34889
34993
  return `${report.script}
34890
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
+ }
34891
35005
  if (report.kind === "ccr-configuration") {
34892
35006
  return [
34893
35007
  `CCR ${report.action}: ${report.state}`,
@@ -35622,10 +35736,12 @@ Useful flags
35622
35736
  --harness <id> Restrict the operation to one harness
35623
35737
  --provider <id> Restrict the operation to one provider
35624
35738
  --script Export a CCR script rule (routing command)
35739
+ --route-status Show current Smart Model Routing state for one agent
35625
35740
  --route-metrics Show local routing decision telemetry
35626
35741
  --route-mode <mode> shadow by default; conservative requires opt-in
35742
+ --route-simple-model <Provider/model> Simple model for conservative routing
35627
35743
  --prune Keep only the 200 newest routing decision records
35628
- --configure-ccr Preview managed CCR setup; --yes applies one step
35744
+ --configure-ccr Preview CCR setup; --yes applies the reviewed change
35629
35745
  --update-ccr Preview update of the managed CCR CLI
35630
35746
  --rollback-ccr Preview rollback; --yes removes owned rule/profile
35631
35747
  --ccr-usage Read CCR model/token aggregates for local sessions
@@ -35896,7 +36012,10 @@ Exits 0 whatever the figures say \u2014 an empty report is a fact, not a failure
35896
36012
  Usage
35897
36013
  token-harness routing --script --harness <claude|codex>
35898
36014
  [--route-mode <shadow|conservative>] [--json]
35899
- token-harness routing --configure-ccr --harness <claude|codex> [--yes]
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]
35900
36019
  token-harness routing --update-ccr [--yes]
35901
36020
  token-harness routing --rollback-ccr --harness <claude|codex> [--yes]
35902
36021
  token-harness routing --route-metrics [--since <duration|date>]
@@ -35914,9 +36033,10 @@ telemetry write never blocks the agent request. Decision records contain no prom
35914
36033
  Routing choices are not measured token savings; this command keeps them separate from \`metrics\`.
35915
36034
  Use --prune to remove all but the 200 newest decision records.
35916
36035
 
35917
- When no authenticated local CCR service is present, configure first previews an npm install/start
35918
- of CCR 3.1.1 in Token Harness' protected local state; after approving that step, run configure again
35919
- to preview the routing rule and optional CCR-only CLI profile. A Token Harness-owned service keeps
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
35920
36040
  its Web RPC token in a private local file; existing services can use CCR_WEB_AUTH_TOKEN and
35921
36041
  optionally CCR_WEB_URL. --update-ccr only updates a Token Harness-owned CLI to the reviewed pin.
35922
36042
  Rollback removes only the exact rule, profile, and script Token Harness owns. CCR usage is observed
@@ -36203,7 +36323,9 @@ async function run(options) {
36203
36323
  nativePolicy: invocation.options.nativePolicy,
36204
36324
  routingScript: invocation.options.routingScript,
36205
36325
  routingMetrics: invocation.options.routingMetrics,
36326
+ routingStatus: invocation.options.routingStatus,
36206
36327
  routingMode: invocation.options.routingMode,
36328
+ routingSimpleModel: invocation.options.routingSimpleModel,
36207
36329
  routingPrune: invocation.options.routingPrune,
36208
36330
  routingCcrConfigure: invocation.options.routingCcrConfigure,
36209
36331
  routingCcrRollback: invocation.options.routingCcrRollback,
@@ -37127,6 +37249,10 @@ var init_guided = __esm({
37127
37249
  }
37128
37250
  ];
37129
37251
  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.",
37130
37256
  "cclimits-not-installed": "Claude allowance needs the optional cclimits companion. Output optimization does not depend on the allowance meter.",
37131
37257
  "cclimits-readonly-flags-unsupported": "The installed cclimits is too old for safe allowance reading. Version 1.7.0 includes the required support.",
37132
37258
  "cclimits-python-unavailable": "cclimits is installed, but Python could not start. Check the Python installation used by this terminal.",
@@ -37314,6 +37440,7 @@ var init_guided = __esm({
37314
37440
  const empty2 = () => ({ data: null, diagnostics: [], exitCode: 9 });
37315
37441
  let doctor = empty2(), budget = empty2(), context = empty2();
37316
37442
  let guidance;
37443
+ const routing = {};
37317
37444
  const observe = async (id, args) => {
37318
37445
  let result6;
37319
37446
  try {
@@ -37331,7 +37458,7 @@ var init_guided = __esm({
37331
37458
  loading.agents = this.agentView(doctor, budget, context, {
37332
37459
  rules: loading.stages.find((item) => item.id === "rules")?.state !== "working",
37333
37460
  allowance: loading.stages.find((item) => item.id === "allowance")?.state !== "working"
37334
- }, guidance);
37461
+ }, guidance, routing);
37335
37462
  };
37336
37463
  const [, , , metrics, status, benchmark] = await Promise.all([
37337
37464
  observe("agents", ["doctor"]).then((result6) => {
@@ -37371,7 +37498,30 @@ var init_guided = __esm({
37371
37498
  observe("checks", ["status"]),
37372
37499
  observe("value", ["benchmark-matrix"])
37373
37500
  ]);
37374
- const agents = this.agentView(doctor, budget, context, { rules: true, allowance: true }, guidance);
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);
37375
37525
  const notices = [];
37376
37526
  if (doctor.data === null)
37377
37527
  notices.push("The agent inventory could not be read. Check the local installation and refresh.");
@@ -37399,7 +37549,7 @@ var init_guided = __esm({
37399
37549
  notices
37400
37550
  };
37401
37551
  }
37402
- agentView(doctor, budget, context, complete2, guidance) {
37552
+ agentView(doctor, budget, context, complete2, guidance, routing) {
37403
37553
  const present = (doctor.data?.harnesses ?? []).filter((item) => item.state !== "absent" && (item.harnessId === "claude" || item.harnessId === "codex"));
37404
37554
  return present.map((agent) => {
37405
37555
  const providers = (doctor.data?.providers ?? []).filter((provider) => provider.state === "configured" && provider.configuredHarnesses.includes(agent.harnessId)).map((p) => p.providerId);
@@ -37421,6 +37571,16 @@ var init_guided = __esm({
37421
37571
  setup,
37422
37572
  effort: observed?.nativeEffort?.current ?? observed?.reasoningEffort ?? null,
37423
37573
  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
+ },
37424
37584
  ...guidance?.[agent.harnessId] ? { guidance: guidance[agent.harnessId] } : {},
37425
37585
  allowanceAction: allowanceAction(usage?.diagnostics ?? []),
37426
37586
  rules: agentRules(agent.harnessId, providers, context.data, guidance?.[agent.harnessId]),
@@ -37462,7 +37622,8 @@ var init_guided = __esm({
37462
37622
  "task",
37463
37623
  "provider",
37464
37624
  "candidate",
37465
- "routeMode"
37625
+ "routeMode",
37626
+ "simpleModel"
37466
37627
  ].includes(key)) || ![
37467
37628
  "setup",
37468
37629
  "effort",
@@ -37474,7 +37635,7 @@ var init_guided = __esm({
37474
37635
  "routing-setup",
37475
37636
  "routing-remove",
37476
37637
  "routing-metrics"
37477
- ].includes(action) || data["harness"] !== void 0 && !["claude", "codex"].includes(String(data["harness"])) || data["harnesses"] !== void 0 && !validHarnesses || data["harnesses"] !== void 0 && action !== "setup" || data["routeMode"] !== void 0 && !["shadow", "conservative"].includes(String(data["routeMode"])) || data["harnesses"] !== void 0 && data["harness"] !== void 0 || data["task"] !== void 0 && !TASKS.has(String(data["task"])) || data["provider"] !== void 0 && !["rtk", "harnesstrim", "mcptoon", "gitnexus", "headroom"].includes(String(data["provider"])) || data["candidate"] !== void 0 && !["mcptoon", "gitnexus"].includes(String(data["candidate"])) || action === "effort" && (data["harness"] === void 0 || data["task"] === void 0) || action === "skill" && data["harness"] === void 0 || routingAction && data["harness"] === void 0 || action !== "routing-setup" && data["routeMode"] !== void 0 || action === "remove" && (data["provider"] === void 0 || data["harness"] !== void 0 || data["harnesses"] !== void 0 || data["task"] !== void 0 || data["candidate"] !== void 0) || data["provider"] !== void 0 && action !== "remove" && action !== "setup" || candidateAction && (data["candidate"] === void 0 || data["harness"] === void 0 || data["provider"] !== void 0 || data["task"] !== void 0) || !candidateAction && data["candidate"] !== void 0 || routingAction && (data["provider"] !== void 0 || data["candidate"] !== void 0 || data["task"] !== void 0 || data["harnesses"] !== void 0))
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))
37478
37639
  throw new GuideError(400, "Choose a supported agent and action.");
37479
37640
  return this.exclusive(async () => {
37480
37641
  this.approval = null;
@@ -37525,9 +37686,19 @@ var init_guided = __esm({
37525
37686
  }
37526
37687
  const removing = action === "routing-remove";
37527
37688
  this.record(`${removing ? "Reviewing removal of" : "Reviewing"} Smart Model Routing for ${name(harness)}. Nothing has changed yet.`, "working");
37528
- const args = removing ? ["routing", "--rollback-ccr", "--harness", harness] : ["routing", "--configure-ccr", "--harness", harness, "--route-mode", mode];
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
+ ];
37529
37699
  const result6 = await this.call(args);
37530
- if (result6.exitCode !== 0 || result6.data === null) {
37700
+ const replacing = !removing && result6.diagnostics.some((entry) => entry.code === "ccr-route-mode-requires-rollback");
37701
+ if ((result6.exitCode !== 0 || result6.data === null) && !replacing) {
37531
37702
  const message = explainGuideIssue(result6.diagnostics, `No safe Smart Model Routing ${removing ? "removal" : "setup"} is available for ${name(harness)}. Nothing was changed.`);
37532
37703
  this.record(message, "attention");
37533
37704
  return {
@@ -37541,8 +37712,8 @@ var init_guided = __esm({
37541
37712
  };
37542
37713
  }
37543
37714
  const report = result6.data;
37544
- const alreadyConfigured = !removing && report.kind === "ccr-configuration" && report.state === "already-configured";
37545
- const alreadyAbsent = removing && report.kind === "ccr-configuration" && report.state === "already-absent";
37715
+ const alreadyConfigured = !removing && report?.kind === "ccr-configuration" && report.state === "already-configured";
37716
+ const alreadyAbsent = removing && report?.kind === "ccr-configuration" && report.state === "already-absent";
37546
37717
  if (alreadyConfigured || alreadyAbsent) {
37547
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.`;
37548
37719
  this.record(message, "success");
@@ -37558,8 +37729,8 @@ var init_guided = __esm({
37558
37729
  }
37559
37730
  const ticket = this.random();
37560
37731
  const expires2 = this.now() + 10 * 6e4;
37561
- const lifecycle = report.kind === "ccr-lifecycle";
37562
- const network2 = lifecycle && report.action !== "start";
37732
+ const lifecycle = report?.kind === "ccr-lifecycle";
37733
+ const network2 = Boolean(lifecycle && report?.kind === "ccr-lifecycle" && report.action !== "start");
37563
37734
  this.approval = {
37564
37735
  id: ticket,
37565
37736
  expires: expires2,
@@ -37570,9 +37741,15 @@ var init_guided = __esm({
37570
37741
  operation: removing ? "routing-rollback" : "routing-configure",
37571
37742
  network: network2,
37572
37743
  routingHarness: harness,
37573
- routingMode: mode
37744
+ routingMode: mode,
37745
+ ...simpleModel ? { routingSimpleModel: simpleModel } : {},
37746
+ ...replacing ? { routingReplace: true } : {}
37574
37747
  };
37575
- const change = report.kind === "ccr-lifecycle" ? {
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" ? {
37576
37753
  title: `${name(harness)}: prepare local CCR routing runtime`,
37577
37754
  files: 0,
37578
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.`
@@ -37587,8 +37764,8 @@ var init_guided = __esm({
37587
37764
  title: removing ? `Remove Smart Model Routing for ${name(harness)}?` : `Set up ${mode} Smart Model Routing for ${name(harness)}?`,
37588
37765
  changes: [change],
37589
37766
  notices: [
37590
- lifecycle && !removing ? "CCR runtime preparation and routing-rule configuration are deliberately separate safety stages. After the runtime is ready, open Manage routing again to review the exact rule/profile." : "Token Harness owns only its exact CCR rule/profile and local managed runtime. Provider credentials remain in CCR and are never imported silently.",
37591
- mode === "shadow" && !removing ? "Shadow mode is the default: it never changes the model selected for a request." : mode === "conservative" && !removing ? "Conservative routing requires TOKEN_HARNESS_ROUTING_SIMPLE_MODEL to name an exact model already configured in CCR. Without that explicit model the preview is refused." : "Removing routing does not uninstall CCR or delete provider credentials."
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."
37592
37769
  ],
37593
37770
  expiresAt: new Date(expires2).toISOString(),
37594
37771
  network: network2,
@@ -38003,8 +38180,36 @@ var init_guided = __esm({
38003
38180
  const removing = approval.operation === "routing-rollback";
38004
38181
  this.record((removing ? "Removing" : "Applying") + " Smart Model Routing for " + name(harness) + ".", "working");
38005
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
+ ];
38006
38193
  try {
38007
- result6 = await this.call(removing ? ["routing", "--rollback-ccr", "--harness", harness, "--yes"] : ["routing", "--configure-ccr", "--harness", harness, "--route-mode", mode, "--yes"]);
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
+ }
38008
38213
  } catch {
38009
38214
  this.invalidateObservedState();
38010
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.";
@@ -40894,6 +41099,40 @@ var init_guided_product_client = __esm({
40894
41099
  'caption',
40895
41100
  ),
40896
41101
  );
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);
40897
41136
  if (baseline.unavailable.length) {
40898
41137
  const details = node('details', undefined, 'agent-details');
40899
41138
  details.append(node('summary', 'Connection limitations'));
@@ -41519,15 +41758,15 @@ var init_guided_product_client = __esm({
41519
41758
  }
41520
41759
 
41521
41760
 
41522
- function reviewRoutingAction(harness, action, routeMode, run) {
41761
+ function reviewRoutingAction(harness, action, routeMode, run, simpleModel = null) {
41523
41762
  const label =
41524
41763
  action === 'routing-metrics'
41525
41764
  ? 'Reading routing activity'
41526
41765
  : action === 'routing-remove'
41527
41766
  ? 'Reviewing routing removal'
41528
- : 'Reviewing ' + routeMode + ' routing setup';
41767
+ : 'Reviewing ' + routeMode + ' routing';
41529
41768
  $('modal-content').replaceChildren(
41530
- progress(label, 'Nothing changes while Token Harness reads the local routing state.'),
41769
+ progress(label, 'Nothing changes while Token Harness checks the current local routing state.'),
41531
41770
  );
41532
41771
  $('modal-actions').replaceChildren(modalClose('Cancel'));
41533
41772
  setBusy(true, false);
@@ -41536,7 +41775,12 @@ var init_guided_product_client = __esm({
41536
41775
  request('/api/preview', {
41537
41776
  action,
41538
41777
  harness,
41539
- ...(action === 'routing-setup' ? { routeMode } : {}),
41778
+ ...(action === 'routing-setup'
41779
+ ? {
41780
+ routeMode,
41781
+ ...(simpleModel ? { simpleModel } : {}),
41782
+ }
41783
+ : {}),
41540
41784
  }),
41541
41785
  )
41542
41786
  .then(data => {
@@ -41546,12 +41790,12 @@ var init_guided_product_client = __esm({
41546
41790
  messageBox(
41547
41791
  'Smart Model Routing · ' + agentName(harness),
41548
41792
  action === 'routing-metrics'
41549
- ? 'Local classifier and CCR activity only. Prompt text and credentials are not shown.'
41793
+ ? 'Local routing activity only. Prompt text and credentials are not shown.'
41550
41794
  : action === 'routing-remove'
41551
- ? 'Only the Token Harness-owned CCR rule/profile is eligible for removal.'
41795
+ ? 'Smart Model Routing will be turned off for this coding agent. CCR and provider credentials stay in place.'
41552
41796
  : routeMode === 'shadow'
41553
- ? 'Shadow mode is the safe default: it classifies requests locally and records decisions without changing the selected model.'
41554
- : 'Conservative mode is opt-in: only high-confidence simple requests may request one already-configured simple model; safety-gated requests pass through unchanged.',
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.',
41555
41799
  ),
41556
41800
  );
41557
41801
  for (const change of data.changes || []) {
@@ -41564,8 +41808,8 @@ var init_guided_product_client = __esm({
41564
41808
  if (action !== 'routing-metrics')
41565
41809
  $('modal-content').append(
41566
41810
  messageBox(
41567
- 'Safety boundary',
41568
- 'Token Harness owns only its exact CCR runtime/rule/profile. Provider credentials remain in CCR, native Claude Code/Codex endpoints are not rewritten, and every mutation still requires this explicit approval.',
41811
+ 'Safety',
41812
+ 'Token Harness changes only its owned CCR routing state. Existing provider credentials and unrelated CCR settings are preserved.',
41569
41813
  'safe',
41570
41814
  ),
41571
41815
  );
@@ -41574,10 +41818,10 @@ var init_guided_product_client = __esm({
41574
41818
  $('modal-actions').append(
41575
41819
  actionButton(
41576
41820
  action === 'routing-remove'
41577
- ? 'Remove managed routing'
41821
+ ? 'Disable routing'
41578
41822
  : routeMode === 'conservative'
41579
- ? 'Apply conservative routing step'
41580
- : 'Apply shadow routing step',
41823
+ ? 'Apply conservative mode'
41824
+ : 'Enable shadow mode',
41581
41825
  () => applyTicket(data.ticket),
41582
41826
  ),
41583
41827
  );
@@ -41594,77 +41838,111 @@ var init_guided_product_client = __esm({
41594
41838
  });
41595
41839
  }
41596
41840
 
41597
- function manageRouting(harness) {
41841
+ function enableRouting(harness) {
41598
41842
  if (busy) return;
41599
- const run = modal('Smart Model Routing · ' + agentName(harness));
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));
41600
41864
  $('modal-content').append(
41601
41865
  messageBox(
41602
- 'Shadow-first routing',
41603
- 'The classifier runs locally with deterministic heuristics. It needs no paid routing API and no local LLM. The reviewed CCR gateway is used only as the local request-routing surface.',
41604
- ),
41605
- messageBox(
41606
- 'How to use it',
41607
- 'Start with Shadow. After CCR is prepared, review Shadow again to install the exact rule/profile. Launch the agent through the CCR profile shown after configuration. Conservative mode is optional and requires an exact simple model already configured in CCR.',
41608
- ),
41609
- messageBox(
41610
- 'What is measured',
41611
- 'Routing decisions are kept separate from optimizer token savings. A cheaper model is not counted as saved quota unless paired quality and allowance evidence proves it.',
41612
- 'safe',
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',
41613
41875
  ),
41614
41876
  );
41615
- $('modal-actions').append(
41616
- modalClose('Close'),
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(
41617
41923
  actionButton(
41618
41924
  'View 30-day activity',
41619
41925
  () => reviewRoutingAction(harness, 'routing-metrics', 'shadow', run),
41620
41926
  'secondary',
41621
41927
  ),
41622
- actionButton(
41623
- 'Remove managed rule',
41624
- () => reviewRoutingAction(harness, 'routing-remove', 'shadow', run),
41625
- 'secondary',
41626
- ),
41627
- actionButton(
41628
- 'Review conservative setup',
41629
- () => reviewRoutingAction(harness, 'routing-setup', 'conservative', run),
41630
- 'secondary',
41631
- ),
41632
- actionButton(
41633
- 'Review shadow setup',
41634
- () => reviewRoutingAction(harness, 'routing-setup', 'shadow', run),
41635
- ),
41636
41928
  );
41637
- }
41929
+ activityDetails.append(activityActions);
41930
+ $('modal-content').append(activityDetails);
41638
41931
 
41639
- function renderRouting() {
41640
- const root = $('routing-overview');
41641
- if (!root) return;
41642
- root.replaceChildren();
41643
- const agents = activeAgents();
41644
- if (!agents.length) {
41645
- root.append(
41646
- messageBox(
41647
- 'No supported coding agent detected',
41648
- 'Smart Model Routing is available for Claude Code and Codex after the agent is detected.',
41649
- 'warn',
41650
- ),
41651
- );
41652
- return;
41653
- }
41654
- for (const agent of agents) {
41655
- const row = node('article', undefined, 'maintenance-row');
41656
- const copy = node('div');
41657
- copy.append(
41658
- node('strong', agent.name),
41659
- node(
41660
- 'p',
41661
- 'Optional request routing through a local CCR profile. Shadow mode never changes models; conservative mode is explicit and safety-gated.',
41662
- 'caption',
41663
- ),
41664
- );
41665
- row.append(copy, actionButton('Manage routing', () => manageRouting(agent.id), 'secondary'));
41666
- root.append(row);
41667
- }
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();
41668
41946
  }
41669
41947
 
41670
41948
  function renderMaintenance() {
@@ -41731,7 +42009,6 @@ var init_guided_product_client = __esm({
41731
42009
  renderManagedSetup();
41732
42010
  renderExperimental();
41733
42011
  renderTuning();
41734
- renderRouting();
41735
42012
  renderMaintenance();
41736
42013
  }
41737
42014
 
@@ -42775,11 +43052,6 @@ ${GUIDE_CANDIDATE_READINESS_JS}`;
42775
43052
  <details class="disclosure"><summary>Remove Token Harness-managed configuration</summary><p class="caption">Removal is reviewed first. Token Harness removes only configuration it owns; installed provider software and user-owned configuration may remain.</p><div id="managed-removal-actions" class="maintenance-list"><p class="caption">Checking managed ownership\u2026</p></div></details>
42776
43053
  </section>
42777
43054
 
42778
- <section class="setup-step" id="smart-routing">
42779
- <div class="section-title"><div><h2>Smart Model Routing</h2><p>Optional shadow-first request routing for Claude Code and Codex. Shadow mode observes locally without changing models; conservative routing is an explicit opt-in.</p></div></div>
42780
- <div id="routing-overview" class="maintenance-list"><p class="empty">Checking supported coding agents\u2026</p></div>
42781
- </section>
42782
-
42783
43055
  <section class="setup-step" id="maintenance">
42784
43056
  <div class="section-title"><div><h2>Health and updates</h2><p>These are maintenance actions, not onboarding steps. Setup already performs its own safety checks.</p></div></div>
42785
43057
  <div id="maintenance-actions" class="maintenance-list"><p class="empty">Checking\u2026</p></div>