pi-advisor-flow 0.15.1 → 0.15.2-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +17 -2
  3. package/dist/index.js +1194 -506
  4. package/docs/README.md +9 -0
  5. package/docs/benchmark.md +22 -0
  6. package/docs/configuration.md +194 -0
  7. package/docs/development.md +38 -0
  8. package/docs/herdr.md +169 -0
  9. package/docs/privacy.md +102 -0
  10. package/extensions/index.ts +23 -0
  11. package/locales/de.json +330 -0
  12. package/locales/en.json +331 -0
  13. package/locales/es.json +3 -0
  14. package/locales/fr.json +330 -0
  15. package/locales/pt-BR.json +3 -0
  16. package/locales/pt.json +3 -0
  17. package/locales/ru.json +3 -0
  18. package/locales/uk.json +3 -0
  19. package/locales/zh.json +3 -0
  20. package/package.json +15 -2
  21. package/skills/pi-advisor-flow/SKILL.md +62 -0
  22. package/src/commands/activation-preparation.ts +9 -2
  23. package/src/commands/activation.ts +28 -8
  24. package/src/commands/configuration-tool-models.ts +143 -0
  25. package/src/commands/configuration-tool-policy.ts +177 -0
  26. package/src/commands/configuration-tool-preview.ts +228 -0
  27. package/src/commands/configuration-tool-runtime.ts +40 -0
  28. package/src/commands/configuration-tool-transaction.ts +120 -0
  29. package/src/commands/configuration-tool-update.ts +230 -0
  30. package/src/commands/configuration-tool.ts +89 -0
  31. package/src/commands/lifecycle.ts +6 -1
  32. package/src/commands/manual-consultation.ts +6 -1
  33. package/src/commands/manual-progress.ts +4 -3
  34. package/src/commands/model-commands.ts +2 -1
  35. package/src/commands/model-options.ts +4 -6
  36. package/src/commands/model-picker.ts +16 -6
  37. package/src/commands/registration.ts +2 -0
  38. package/src/commands/runtime.ts +17 -4
  39. package/src/commands/settings-commands.ts +30 -7
  40. package/src/config/schema-validators.ts +104 -0
  41. package/src/config/schema.ts +35 -102
  42. package/src/config/storage.ts +160 -7
  43. package/src/i18n.ts +31 -0
  44. package/src/redaction.ts +64 -19
  45. package/src/scout-group-serialization.ts +66 -0
  46. package/src/scout-groups.ts +3 -66
  47. package/src/scout-selection.ts +99 -0
  48. package/src/scout.ts +6 -93
  49. package/src/session-state.ts +27 -137
  50. package/src/tool-input-normalization.ts +119 -0
  51. package/src/tools/gate-policy.ts +13 -5
  52. package/src/tools/jev-filter.ts +2 -1
  53. package/src/tools/jev-turn-gate.ts +2 -1
  54. package/src/tools/register-lifecycle.ts +5 -1
  55. package/src/tools/register-outcome.ts +5 -1
  56. package/src/tools/register-renderers.ts +5 -2
  57. package/src/tools/render-advisor-result.ts +20 -8
  58. package/src/tools/render-common.ts +16 -4
  59. package/src/tools/scout-status.ts +10 -2
  60. package/src/ui/jev-classifier-submenu.ts +143 -38
  61. package/src/ui/jev-filter-submenu.ts +52 -14
  62. package/src/ui/jev-provider-submenu-view.ts +72 -20
  63. package/src/ui/jev-provider-submenu.ts +40 -12
  64. package/src/ui/jev-setup-support.ts +48 -19
  65. package/src/ui/manual-dialog-render.ts +71 -25
  66. package/src/ui/searchable-model-list.ts +18 -4
  67. package/src/ui/settings-formatting.ts +5 -2
  68. package/src/ui/settings-items-jev.ts +216 -0
  69. package/src/ui/settings-items.ts +216 -259
  70. package/src/ui/settings-selector.ts +9 -2
  71. package/src/ui/text-setting-submenu.ts +8 -1
  72. package/src/usage.ts +9 -3
package/dist/index.js CHANGED
@@ -518,8 +518,7 @@ var normalizeJevBaseUrl = (input) => {
518
518
  return { baseUrl: `${parsed.origin}${stripContractPath(parsed.pathname)}` };
519
519
  };
520
520
 
521
- // src/config/schema.ts
522
- var configuredModelRef = (value) => value?.trim() || undefined;
521
+ // src/config/schema-validators.ts
523
522
  var isNonEmptyModel = (model) => typeof model === "string" && model.trim().length > 0;
524
523
  var isValidAdvisorModelWhitelist = (value) => Array.isArray(value) && value.every(isNonEmptyModel);
525
524
  var ADVISOR_TOOL_POLICY_NAMES = new Set(ADVISOR_TOOL_POLICIES);
@@ -529,17 +528,17 @@ var isValidAdvisorToolPolicies = (value) => {
529
528
  }
530
529
  return Object.entries(value).every(([toolName, policy]) => toolName.trim().length > 0 && isString(policy) && ADVISOR_TOOL_POLICY_NAMES.has(policy));
531
530
  };
532
- var nonNegativeSafeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
531
+ var isValidNonNegativeSafeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
533
532
  var isValidContextMaxChars = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= MAX_CONTEXT_MAX_CHARS;
534
533
  var isValidLoopThreshold = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 2;
535
- var isValidMaxCallsPerSession = (value) => nonNegativeSafeInteger(value);
534
+ var isValidMaxCallsPerSession = (value) => isValidNonNegativeSafeInteger(value);
536
535
  var GATE_FAILURE_MODE_NAMES = new Set(GATE_FAILURE_MODES);
537
536
  var isValidGateFailureMode = (value) => isString(value) && GATE_FAILURE_MODE_NAMES.has(value);
538
- var isValidToolResultMaxLines = (value) => nonNegativeSafeInteger(value);
539
- var isValidToolResultMaxBytes = (value) => nonNegativeSafeInteger(value);
537
+ var isValidToolResultMaxLines = (value) => isValidNonNegativeSafeInteger(value);
538
+ var isValidToolResultMaxBytes = (value) => isValidNonNegativeSafeInteger(value);
540
539
  var isValidJevTimeoutMs = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
541
540
  var isValidScoutTimeoutMs = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= MAX_SCOUT_TIMEOUT_MS;
542
- var isValidJevDigestMaxChars = (value) => nonNegativeSafeInteger(value);
541
+ var isValidJevDigestMaxChars = (value) => isValidNonNegativeSafeInteger(value);
543
542
  var isValidJevPricePerMtok = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
544
543
  var isValidJevSkipConfidence = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0.5 && value <= 1;
545
544
  var isValidJevNoulMargin = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 0.5;
@@ -547,6 +546,9 @@ var JEV_TRANSPORT_NAMES = new Set(JEV_TRANSPORTS);
547
546
  var isValidJevTransport = (value) => isString(value) && JEV_TRANSPORT_NAMES.has(value);
548
547
  var isValidJevBaseUrl = (value) => isString(value) && (value.trim() === "" || normalizeJevBaseUrl(value).baseUrl !== undefined);
549
548
  var isValidJevKeyProvider = (value) => isString(value) && (value.trim() === "" || !/\s/u.test(value.trim()));
549
+
550
+ // src/config/schema.ts
551
+ var configuredModelRef = (value) => value?.trim() || undefined;
550
552
  var CONFIG_SCHEMA = {
551
553
  advisor: {
552
554
  accepted: "a provider/model string",
@@ -626,7 +628,7 @@ var CONFIG_SCHEMA = {
626
628
  current: () => advisorGitContextMaxCharsRef,
627
629
  persisted: true,
628
630
  type: "number",
629
- validate: nonNegativeSafeInteger
631
+ validate: isValidNonNegativeSafeInteger
630
632
  },
631
633
  advisorHerdrIntegration: {
632
634
  accepted: "true or false",
@@ -673,7 +675,7 @@ var CONFIG_SCHEMA = {
673
675
  current: () => advisorJevFilterOverrideWindowRef,
674
676
  persisted: true,
675
677
  type: "number",
676
- validate: nonNegativeSafeInteger
678
+ validate: isValidNonNegativeSafeInteger
677
679
  },
678
680
  advisorJevFilterSkipConfidence: {
679
681
  accepted: "a number between 0.5 and 1 inclusive",
@@ -721,7 +723,7 @@ var CONFIG_SCHEMA = {
721
723
  current: () => advisorJevTurnGateEveryTurnsRef,
722
724
  persisted: true,
723
725
  type: "number",
724
- validate: nonNegativeSafeInteger
726
+ validate: isValidNonNegativeSafeInteger
725
727
  },
726
728
  advisorJevTurnGateNoulThreshold: {
727
729
  accepted: "a number between 0.5 and 1 inclusive",
@@ -956,10 +958,32 @@ var parseArgs = (args) => {
956
958
  };
957
959
 
958
960
  // src/config/storage.ts
959
- import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
961
+ import { randomUUID } from "node:crypto";
962
+ import {
963
+ closeSync,
964
+ existsSync,
965
+ fsyncSync,
966
+ openSync,
967
+ readFileSync,
968
+ renameSync,
969
+ statSync,
970
+ unlinkSync,
971
+ writeFileSync
972
+ } from "node:fs";
960
973
  import { join } from "node:path";
961
974
  import { CONFIG_DIR_NAME, getAgentDir } from "@earendil-works/pi-coding-agent";
962
975
 
976
+ // src/i18n.ts
977
+ var I18N_NAMESPACE = "pi-advisor-flow";
978
+ var scopeImpl;
979
+ try {
980
+ const sdk = await import("@juicesharp/rpiv-i18n");
981
+ scopeImpl = sdk.scope(I18N_NAMESPACE);
982
+ } catch {
983
+ scopeImpl = (_key, fallback) => fallback;
984
+ }
985
+ var t = scopeImpl;
986
+
963
987
  // src/config/defaults.ts
964
988
  var resetDefaults = () => {
965
989
  setExecutorRef("");
@@ -1083,8 +1107,13 @@ var applyConfig = (config) => {
1083
1107
  };
1084
1108
 
1085
1109
  // src/config/storage.ts
1110
+ var configPaths = (ctx) => [
1111
+ ctx.isProjectTrusted() ? join(ctx.cwd, CONFIG_DIR_NAME, "advisor.json") : null,
1112
+ join(getAgentDir(), "advisor.json")
1113
+ ];
1086
1114
  var currentConfigState = () => Object.fromEntries(SAVED_CONFIG_KEYS.map((key) => [key, CONFIG_SCHEMA[key].current()]));
1087
1115
  var sameConfigValue = (left, right) => JSON.stringify(left) === JSON.stringify(right);
1116
+ var CONFIG_KEY_SET = new Set(Object.keys(CONFIG_SCHEMA));
1088
1117
  var RESERVED_ADVISOR_JSON_KEYS = new Set(["typesafe_api_key"]);
1089
1118
  var readConfigForSave = (path) => {
1090
1119
  if (!existsSync(path)) {
@@ -1151,6 +1180,7 @@ var configIdentity = (path) => {
1151
1180
  return `unstattable:${process.hrtime.bigint()}`;
1152
1181
  }
1153
1182
  };
1183
+ var configFileIdentity = (path) => existsSync(path) ? configIdentity(path) : null;
1154
1184
  var readConfigCached = (path) => {
1155
1185
  const identity = configIdentity(path);
1156
1186
  const cached = configCache.get(path);
@@ -1171,11 +1201,11 @@ var loadConfig = (_ctx) => {
1171
1201
  const warningIdentity = `${global}:${configIdentity(global)}`;
1172
1202
  if (advisorJevFilterEnabledRef && !advisorJevClassifierRef && _ctx.hasUI && !warnedFilterWithoutClassifierIdentities.has(warningIdentity)) {
1173
1203
  warnedFilterWithoutClassifierIdentities.add(warningIdentity);
1174
- _ctx.ui.notify("The Jev consultation filter is enabled but no Jev classifier is selected; consultations are not screened until you pick one in /advisor-settings.", "warning");
1204
+ _ctx.ui.notify(t("notify.jevFilterNoClassifier.message", "The Jev consultation filter is enabled but no Jev classifier is selected; consultations are not screened until you pick one in /advisor-settings."), "warning");
1175
1205
  }
1176
1206
  const unknownKeys = unknownConfigKeys(globalConfig).filter((key) => !RESERVED_ADVISOR_JSON_KEYS.has(key));
1177
1207
  if (unknownKeys.length > 0 && _ctx.hasUI && !warnedUnknownConfigIdentities.has(warningIdentity)) {
1178
- _ctx.ui.notify(`Advisor configuration at ${global} contains unrecognized key(s) ${unknownKeys.map((key) => JSON.stringify(key)).join(", ")}. They were preserved but ignored; check for typos or upgrade pi-advisor.`, "warning");
1208
+ _ctx.ui.notify(`${t("notify.unknownConfigKeys.at", "Advisor configuration at")} ${global} ${t("notify.unknownConfigKeys.contains", "contains unrecognized key(s)")} ${unknownKeys.map((key) => JSON.stringify(key)).join(", ")}. ${t("notify.unknownConfigKeys.preserved", "They were preserved but ignored; check for typos or upgrade pi-advisor.")}`, "warning");
1179
1209
  warnedUnknownConfigIdentities.add(warningIdentity);
1180
1210
  }
1181
1211
  }
@@ -1184,6 +1214,10 @@ var loadConfig = (_ctx) => {
1184
1214
  loadedConfigPath = global;
1185
1215
  return existsSync(global) ? global : null;
1186
1216
  };
1217
+ var rebaseConfigBaseline = () => {
1218
+ loadedConfigState = currentConfigState();
1219
+ loadedConfigPath = join(getAgentDir(), "advisor.json");
1220
+ };
1187
1221
  var saveConfig = (_ctx, options = {}) => {
1188
1222
  const path = join(getAgentDir(), "advisor.json");
1189
1223
  const persistAdvisor = options.persistAdvisor ?? true;
@@ -1211,11 +1245,75 @@ var saveConfig = (_ctx, options = {}) => {
1211
1245
  setPersistedModelRefs(configuredModelRef(nextLoadedState.advisor), configuredModelRef(nextLoadedState.executor));
1212
1246
  return path;
1213
1247
  };
1214
- var saveGlobalOutcomeLogging = (enabled) => {
1248
+ var writeConfigAtomically = (path, contents, expectedIdentity) => {
1249
+ const mode = existsSync(path) ? statSync(path).mode % 512 : 384;
1250
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
1251
+ let fileDescriptor;
1252
+ try {
1253
+ fileDescriptor = openSync(temporaryPath, "wx", mode);
1254
+ writeFileSync(fileDescriptor, contents, "utf-8");
1255
+ fsyncSync(fileDescriptor);
1256
+ closeSync(fileDescriptor);
1257
+ fileDescriptor = undefined;
1258
+ if (expectedIdentity !== undefined && configFileIdentity(path) !== expectedIdentity) {
1259
+ throw new Error("Advisor configuration changed during the update; retry so unrelated edits are preserved.");
1260
+ }
1261
+ renameSync(temporaryPath, path);
1262
+ } catch (error) {
1263
+ if (fileDescriptor !== undefined) {
1264
+ closeSync(fileDescriptor);
1265
+ }
1266
+ try {
1267
+ unlinkSync(temporaryPath);
1268
+ } catch {}
1269
+ throw error;
1270
+ }
1271
+ };
1272
+ var saveGlobalOutcomeLogging = (enabled, expected, expectedKeys = ["advisorOutcomeLogging"]) => {
1215
1273
  const path = join(getAgentDir(), "advisor.json");
1274
+ const identity = configFileIdentity(path);
1216
1275
  const existing = readConfigForSave(path);
1217
- writeFileSync(path, `${JSON.stringify({ ...existing, advisorOutcomeLogging: enabled }, null, 2)}
1218
- `);
1276
+ if (expected && expectedKeys.some((key) => Object.hasOwn(existing, key) !== Object.hasOwn(expected, key) || !sameConfigValue(existing[key], expected[key]))) {
1277
+ throw new Error("Advisor settings changed during confirmation; read the settings again and retry.");
1278
+ }
1279
+ if (enabled === null) {
1280
+ Reflect.deleteProperty(existing, "advisorOutcomeLogging");
1281
+ } else {
1282
+ existing.advisorOutcomeLogging = enabled;
1283
+ }
1284
+ writeConfigAtomically(path, `${JSON.stringify(existing, null, 2)}
1285
+ `, identity);
1286
+ resetConfigCache();
1287
+ return path;
1288
+ };
1289
+ var readGlobalAdvisorConfig = () => {
1290
+ const path = join(getAgentDir(), "advisor.json");
1291
+ const config = readConfigForSave(path);
1292
+ validateConfig(config, path);
1293
+ return config;
1294
+ };
1295
+ var saveGlobalAdvisorConfigPatch = (patch, expected, expectedKeys) => {
1296
+ const path = join(getAgentDir(), "advisor.json");
1297
+ const unknownKeys = Object.keys(patch).filter((key) => !CONFIG_KEY_SET.has(key));
1298
+ if (unknownKeys.length > 0) {
1299
+ throw new Error(`Cannot update Advisor configuration: unsupported key(s) ${unknownKeys.map((key) => JSON.stringify(key)).join(", ")}.`);
1300
+ }
1301
+ const identity = configFileIdentity(path);
1302
+ const next = readConfigForSave(path);
1303
+ const checkedKeys = expectedKeys ?? Object.keys(patch);
1304
+ if (expected && checkedKeys.some((key) => Object.hasOwn(next, key) !== Object.hasOwn(expected, key) || !sameConfigValue(next[key], expected[key]))) {
1305
+ throw new Error("Advisor settings changed during confirmation; read the settings again and retry.");
1306
+ }
1307
+ for (const [key, value] of Object.entries(patch)) {
1308
+ if (value === null) {
1309
+ Reflect.deleteProperty(next, key);
1310
+ } else {
1311
+ next[key] = value;
1312
+ }
1313
+ }
1314
+ validateConfig(next, path);
1315
+ writeConfigAtomically(path, `${JSON.stringify(next, null, 2)}
1316
+ `, identity);
1219
1317
  resetConfigCache();
1220
1318
  return path;
1221
1319
  };
@@ -1286,7 +1384,6 @@ var selectedEffort = (choice) => {
1286
1384
  const effort = choice.startsWith(SELECTED_PREFIX) ? choice.slice(SELECTED_PREFIX.length) : choice;
1287
1385
  return effort === DEFAULT_EFFORT_LEVEL ? undefined : effort;
1288
1386
  };
1289
- var ADVISOR_ACTIVATION_EXPLANATION = "The Advisor is a second-opinion model that reviews the Executor's context and returns risks, alternatives, and verification steps without changing files or running tools.";
1290
1387
  var ARGUMENT_WHITESPACE2 = /\s+/u;
1291
1388
  var hasModelOverride = (args, key) => args.trim().split(ARGUMENT_WHITESPACE2).some((token) => {
1292
1389
  const [tokenKey, value] = token.split("=");
@@ -1359,13 +1456,13 @@ var isSelectableModel = (ctx, ref, availableRefs) => {
1359
1456
  var getExplicitModelError = (ctx, ref, label, overridden, availableRefs) => {
1360
1457
  if (overridden) {
1361
1458
  if (!ref) {
1362
- return `${label} model not configured`;
1459
+ return `${label} ${t("activation.modelNotConfigured", "model not configured")}`;
1363
1460
  }
1364
1461
  if (!findConfiguredModel(ctx, ref)) {
1365
- return `${label} model not found: ${ref}`;
1462
+ return `${label} ${t("activation.modelNotFound.prefix", "model not found:")} ${ref}`;
1366
1463
  }
1367
1464
  if (availableRefs && !isSelectableModel(ctx, ref, availableRefs)) {
1368
- return `${label} model unavailable: ${ref}`;
1465
+ return `${label} ${t("activation.modelUnavailable.prefix", "model unavailable:")} ${ref}`;
1369
1466
  }
1370
1467
  }
1371
1468
  };
@@ -1405,7 +1502,6 @@ class ModelSelectorAdapter {
1405
1502
 
1406
1503
  // src/ui/searchable-model-list.ts
1407
1504
  import { fuzzyFilter, Input, truncateToWidth } from "@earendil-works/pi-tui";
1408
-
1409
1505
  class SearchableModelList {
1410
1506
  tui;
1411
1507
  searchInput;
@@ -1467,14 +1563,14 @@ class SearchableModelList {
1467
1563
  const lines = [this.theme.fg("border", "─".repeat(width))];
1468
1564
  lines.push(` ${this.theme.fg("accent", this.theme.bold(this.title))}`);
1469
1565
  const inputLines = this.searchInput.render(Math.max(1, width - 10));
1470
- lines.push(` ${this.theme.fg("accent", "Search: ")}${inputLines[0] || ""}`, "");
1566
+ lines.push(` ${this.theme.fg("accent", t("modelPicker.searchLabel", "Search:"))} ${inputLines[0] || ""}`, "");
1471
1567
  const query = this.searchInput.getValue().trim();
1472
1568
  this.filteredOptions = query ? fuzzyFilter(this.allOptions, query, (item) => item) : this.allOptions;
1473
1569
  this.selectedIndex = Math.min(this.selectedIndex, Math.max(0, this.filteredOptions.length - 1));
1474
1570
  const maxVisible = 10;
1475
1571
  const total = this.filteredOptions.length;
1476
1572
  if (total === 0) {
1477
- lines.push(` ${this.theme.fg("muted", "No matching models found.")}`);
1573
+ lines.push(` ${this.theme.fg("muted", t("modelPicker.noMatches", "No matching models found."))}`);
1478
1574
  } else {
1479
1575
  const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisible / 2), total - maxVisible));
1480
1576
  const endIndex = Math.min(startIndex + maxVisible, total);
@@ -1530,7 +1626,7 @@ class SearchableModelList {
1530
1626
  this.tui.requestRender();
1531
1627
  }
1532
1628
  interactionHint() {
1533
- return this.multiSelect ? "Type to search · ↑↓: navigate · Space: toggle · Enter: apply · Esc: cancel" : "Type to search · ↑↓: navigate · Enter: select · Esc: cancel";
1629
+ return this.multiSelect ? t("modelPicker.hintMulti", "Type to search · ↑↓: navigate · Space: toggle · Enter: apply · Esc: cancel") : t("modelPicker.hintSingle", "Type to search · ↑↓: navigate · Enter: select · Esc: cancel");
1534
1630
  }
1535
1631
  renderOption(item, index) {
1536
1632
  let tick = " ";
@@ -1588,7 +1684,7 @@ var selectAdvisorModels = async (ctx, options) => {
1588
1684
  }
1589
1685
  const refs = getAvailableModelRefs(ctx);
1590
1686
  if (refs && refs.length === 0) {
1591
- ctx.ui.notify("No selectable models are available. Configure a provider with /login or models.json, then retry.", "error");
1687
+ ctx.ui.notify(t("notify.noSelectableModels.message", "No selectable models are available. Configure a provider with /login or models.json, then retry."), "error");
1592
1688
  return;
1593
1689
  }
1594
1690
  const allOptions = [
@@ -1609,13 +1705,13 @@ var selectAdvisorModels = async (ctx, options) => {
1609
1705
  onCancel: () => done(undefined),
1610
1706
  onSelect: done,
1611
1707
  theme,
1612
- title: "Select Executor Model",
1708
+ title: t("modelPicker.selectExecutor", "Select Executor Model"),
1613
1709
  tui
1614
1710
  }));
1615
1711
  if (!selectedExecutor) {
1616
1712
  return;
1617
1713
  }
1618
- const selectedExecutorEffort = await ctx.ui.select("Select Executor Reasoning/Thinking Level", effortChoices(executorEffort));
1714
+ const selectedExecutorEffort = await ctx.ui.select(t("modelPicker.executorEffort", "Select Executor Reasoning/Thinking Level"), effortChoices(executorEffort));
1619
1715
  if (!selectedExecutorEffort) {
1620
1716
  return;
1621
1717
  }
@@ -1630,13 +1726,13 @@ var selectAdvisorModels = async (ctx, options) => {
1630
1726
  onCancel: () => done(undefined),
1631
1727
  onSelect: done,
1632
1728
  theme,
1633
- title: "Select Advisor Model",
1729
+ title: t("modelPicker.selectAdvisor", "Select Advisor Model"),
1634
1730
  tui
1635
1731
  }));
1636
1732
  if (!selectedAdvisor) {
1637
1733
  return;
1638
1734
  }
1639
- const selectedAdvisorEffort = await ctx.ui.select("Select Advisor Reasoning/Thinking Level", effortChoices(advisorEffort));
1735
+ const selectedAdvisorEffort = await ctx.ui.select(t("modelPicker.advisorEffort", "Select Advisor Reasoning/Thinking Level"), effortChoices(advisorEffort));
1640
1736
  if (!selectedAdvisorEffort) {
1641
1737
  return;
1642
1738
  }
@@ -1656,7 +1752,7 @@ var selectAdvisorModels = async (ctx, options) => {
1656
1752
  onCancel: () => done(undefined),
1657
1753
  onSelect: done,
1658
1754
  theme,
1659
- title: "Select Fallback Advisor Model (optional)",
1755
+ title: t("modelPicker.selectFallbackAdvisor", "Select Fallback Advisor Model (optional)"),
1660
1756
  tui
1661
1757
  }));
1662
1758
  if (selectedFallback === undefined) {
@@ -1680,29 +1776,62 @@ import net from "node:net";
1680
1776
 
1681
1777
  // src/redaction.ts
1682
1778
  var REDACTION_MARKER = "[REDACTED SECRET]";
1683
- var PEM_BEGIN_PATTERN = /-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----/giu;
1684
- var PEM_END_PATTERN = /-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/iu;
1779
+ var MAX_REDACTION_CHARS = 65536;
1780
+ var OVERSIZED_MARKER = "[Redaction omitted: input exceeds 65536 characters]";
1781
+ var PEM_MARKER_PATTERN = /-----(?<action>BEGIN|END)(?: (?<type>[A-Z0-9]+))? PRIVATE KEY-----/giu;
1685
1782
  var CREDENTIAL_NAME = String.raw`(?:api[_-]?key|token|secret|password|passwd)`;
1686
- var SECRET_ASSIGNMENT_PATTERN = new RegExp(String.raw`(?:(?:"(?:[a-z0-9]+[_-])*?${CREDENTIAL_NAME}"|'(?:[a-z0-9]+[_-])*?${CREDENTIAL_NAME}')|(?:\b|_)${CREDENTIAL_NAME})[ \t]*[:=][ \t]*(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|"(?:\\.|[^"\r\n])*(?=\r?\n|$)|'(?:\\.|[^'\r\n])*(?=\r?\n|$)|[^\s"'&,;)}\]]+)`, "giu");
1783
+ var ASSIGNMENT_START = String.raw`(?:(?:"(?:[a-z0-9]+[_-])*?${CREDENTIAL_NAME}"|'(?:[a-z0-9]+[_-])*?${CREDENTIAL_NAME}')|(?:\b|_)${CREDENTIAL_NAME})[ \t]*[:=][ \t]*`;
1784
+ var SECRET_ASSIGNMENT_PATTERN = new RegExp(String.raw`${ASSIGNMENT_START}(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|"(?:\\[^\r\n]|[^"\\\r\n]|\\(?=\r?\n|\r|$))*(?=\r?\n|\r|$)|'(?:\\[^\r\n]|[^'\\\r\n]|\\(?=\r?\n|\r|$))*(?=\r?\n|\r|$)|[^\s"'&,;)}\]]+)`, "giu");
1785
+ var ASSIGNMENT_START_PATTERN = new RegExp(ASSIGNMENT_START, "giu");
1786
+ var BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/giu;
1687
1787
  var SECRET_PATTERNS = [
1688
- /-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/giu,
1689
- /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/giu,
1690
- SECRET_ASSIGNMENT_PATTERN,
1691
- /(?<scheme>[a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/giu,
1788
+ /(?<scheme>(?<![a-z0-9+.-])[a-z0-9+.-]+:\/\/)[^\s/@:]+:[^\s/@]+@/giu,
1692
1789
  /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/gu,
1693
1790
  /\b(?:aws_secret_access_key|aws_session_token)\s*[:=]\s*[^\s"'&,;)}\]]+/giu
1694
1791
  ];
1695
- var redactUnterminatedPem = (value) => {
1696
- const begins = [...value.matchAll(PEM_BEGIN_PATTERN)];
1697
- const lastBegin = begins.at(-1);
1698
- if (lastBegin?.index === undefined) {
1699
- return value;
1792
+ var redactPem = (value) => {
1793
+ const parts = [];
1794
+ const stack = [];
1795
+ let copied = 0;
1796
+ for (const match of value.matchAll(PEM_MARKER_PATTERN)) {
1797
+ const type = (match.groups?.type ?? "").toUpperCase();
1798
+ if (match.groups?.action.toUpperCase() === "BEGIN") {
1799
+ if (stack.length === 0) {
1800
+ parts.push(value.slice(copied, match.index));
1801
+ }
1802
+ stack.push(type);
1803
+ } else if (stack.length > 0) {
1804
+ if (stack.pop() !== type) {
1805
+ return `${parts.join("")}${REDACTION_MARKER}`;
1806
+ }
1807
+ if (stack.length === 0) {
1808
+ parts.push(REDACTION_MARKER);
1809
+ copied = match.index + match[0].length;
1810
+ }
1811
+ }
1812
+ }
1813
+ return stack.length > 0 ? `${parts.join("")}${REDACTION_MARKER}` : `${parts.join("")}${value.slice(copied)}`;
1814
+ };
1815
+ var redactAssignments = (value) => {
1816
+ const parts = [];
1817
+ let copied = 0;
1818
+ for (const match of value.matchAll(SECRET_ASSIGNMENT_PATTERN)) {
1819
+ parts.push(value.slice(copied, match.index), REDACTION_MARKER);
1820
+ const starts = match[0].matchAll(ASSIGNMENT_START_PATTERN);
1821
+ starts.next();
1822
+ if (!starts.next().done) {
1823
+ return parts.join("");
1824
+ }
1825
+ copied = match.index + match[0].length;
1700
1826
  }
1701
- const hasEnd = PEM_END_PATTERN.test(value.slice(lastBegin.index + lastBegin[0].length));
1702
- return hasEnd ? value : `${value.slice(0, lastBegin.index)}${REDACTION_MARKER}`;
1827
+ return `${parts.join("")}${value.slice(copied)}`;
1703
1828
  };
1704
1829
  var redactSecrets = (value) => {
1705
- let redacted = redactUnterminatedPem(value);
1830
+ if (value.length > MAX_REDACTION_CHARS) {
1831
+ return OVERSIZED_MARKER;
1832
+ }
1833
+ let redacted = redactPem(value).replaceAll(BEARER_PATTERN, REDACTION_MARKER);
1834
+ redacted = redactAssignments(redacted);
1706
1835
  for (const pattern of SECRET_PATTERNS) {
1707
1836
  redacted = redacted.replace(pattern, (_match, scheme) => isString(scheme) ? `${scheme}${REDACTION_MARKER}@` : REDACTION_MARKER);
1708
1837
  }
@@ -2036,7 +2165,7 @@ var herdrAdvisorActivity = new HerdrAdvisorActivity(sendToHerdr, () => getAdviso
2036
2165
  var herdrAdvisorBlock = new HerdrAdvisorBlock(sendToHerdr, () => getAdvisorSettings().herdrIntegration);
2037
2166
 
2038
2167
  // src/tools/consultation.ts
2039
- import { randomUUID as randomUUID2 } from "node:crypto";
2168
+ import { randomUUID as randomUUID3 } from "node:crypto";
2040
2169
 
2041
2170
  // src/model-stream.ts
2042
2171
  import { stream } from "@earendil-works/pi-ai/compat";
@@ -2253,7 +2382,7 @@ var sessionContextEntries = (ctx) => {
2253
2382
  };
2254
2383
 
2255
2384
  // src/tools/consult-context.ts
2256
- import { randomUUID } from "node:crypto";
2385
+ import { randomUUID as randomUUID2 } from "node:crypto";
2257
2386
 
2258
2387
  // src/attachments.ts
2259
2388
  import { execFileSync as execFileSync2 } from "node:child_process";
@@ -2874,9 +3003,6 @@ var readProjectRules = async (ctx, maxBytes = PREFERENCES_MAX_BYTES, redact = tr
2874
3003
  };
2875
3004
  };
2876
3005
 
2877
- // src/scout-groups.ts
2878
- import { createHash as createHash2 } from "node:crypto";
2879
-
2880
3006
  // src/tool-result-cap.ts
2881
3007
  var OMITTED_MARKER = "[... omitted tool-result section ...]";
2882
3008
  var collect = (candidates, maxEntries, maxContentBytes) => {
@@ -3067,6 +3193,52 @@ var recentConversation = (ctx, maxChars = 15000, toolResultMaxLines = advisorToo
3067
3193
  return selectRecentEntries(entries, maxChars);
3068
3194
  };
3069
3195
 
3196
+ // src/scout-group-serialization.ts
3197
+ import { createHash as createHash2 } from "node:crypto";
3198
+
3199
+ // src/scout-types.ts
3200
+ var SCOUT_MANIFEST_MAX_BYTES = 64 * 1024;
3201
+ var SCOUT_MANIFEST_MAX_GROUPS = 64;
3202
+ var SCOUT_GROUP_MAX_BYTES = 24 * 1024;
3203
+ var SCOUT_LABEL_MAX_CHARS = 160;
3204
+ var SCOUT_SELECTION_MAX_IDS = 32;
3205
+ var SCOUT_SYNTHESIS_MAX_BYTES = 4 * 1024;
3206
+
3207
+ // src/scout-group-serialization.ts
3208
+ var SPEAKER_PREFIX = /^(?<speaker>User|Executor):\s*/u;
3209
+ var boundedLabel = (value) => [...value.replaceAll(/\s+/gu, " ").trim()].slice(0, SCOUT_LABEL_MAX_CHARS).join("");
3210
+ var labelFor = (kind, content) => {
3211
+ const preview = boundedLabel(content.replace(SPEAKER_PREFIX, ""));
3212
+ const prefix = {
3213
+ assistant: "Executor",
3214
+ compaction: "Compaction summary",
3215
+ "pending-invocation": "Current Advisor invocation",
3216
+ "tool-exchange": "Tool exchange",
3217
+ user: "User request"
3218
+ };
3219
+ return boundedLabel(`${prefix[kind]}: ${preview || "(no text)"}`);
3220
+ };
3221
+ var stableId = (index, entryIds, kind, content) => `g_${createHash2("sha256").update(JSON.stringify([index, entryIds, kind, content])).digest("hex").slice(0, 16)}`;
3222
+ var createScoutContextGroup = (originalIndex, entryIds, kind, content, required) => ({
3223
+ bytes: byteLength(content),
3224
+ content,
3225
+ entryIds,
3226
+ id: stableId(originalIndex, entryIds, kind, content),
3227
+ kind,
3228
+ label: labelFor(kind, content),
3229
+ originalIndex,
3230
+ required
3231
+ });
3232
+ var groupWire = (group) => ({
3233
+ bytes: group.bytes,
3234
+ content: group.content,
3235
+ id: group.id,
3236
+ kind: group.kind,
3237
+ label: group.label,
3238
+ required: group.required
3239
+ });
3240
+ var groupWireBytes = (group) => byteLength(JSON.stringify(groupWire(group)));
3241
+
3070
3242
  // src/scout-protocol.ts
3071
3243
  var invalid = (message) => ({
3072
3244
  message,
@@ -3141,48 +3313,7 @@ var indexToolCalls = (entries) => {
3141
3313
  };
3142
3314
  };
3143
3315
 
3144
- // src/scout-types.ts
3145
- var SCOUT_MANIFEST_MAX_BYTES = 64 * 1024;
3146
- var SCOUT_MANIFEST_MAX_GROUPS = 64;
3147
- var SCOUT_GROUP_MAX_BYTES = 24 * 1024;
3148
- var SCOUT_LABEL_MAX_CHARS = 160;
3149
- var SCOUT_SELECTION_MAX_IDS = 32;
3150
- var SCOUT_SYNTHESIS_MAX_BYTES = 4 * 1024;
3151
-
3152
3316
  // src/scout-groups.ts
3153
- var SPEAKER_PREFIX = /^(?<speaker>User|Executor):\s*/u;
3154
- var boundedLabel = (value) => [...value.replaceAll(/\s+/gu, " ").trim()].slice(0, SCOUT_LABEL_MAX_CHARS).join("");
3155
- var labelFor = (kind, content) => {
3156
- const preview = boundedLabel(content.replace(SPEAKER_PREFIX, ""));
3157
- const prefix = {
3158
- assistant: "Executor",
3159
- compaction: "Compaction summary",
3160
- "pending-invocation": "Current Advisor invocation",
3161
- "tool-exchange": "Tool exchange",
3162
- user: "User request"
3163
- };
3164
- return boundedLabel(`${prefix[kind]}: ${preview || "(no text)"}`);
3165
- };
3166
- var stableId = (index, entryIds, kind, content) => `g_${createHash2("sha256").update(JSON.stringify([index, entryIds, kind, content])).digest("hex").slice(0, 16)}`;
3167
- var groupWire = (group) => ({
3168
- bytes: group.bytes,
3169
- content: group.content,
3170
- id: group.id,
3171
- kind: group.kind,
3172
- label: group.label,
3173
- required: group.required
3174
- });
3175
- var groupWireBytes = (group) => byteLength(JSON.stringify(groupWire(group)));
3176
- var createGroup = (originalIndex, entryIds, kind, content, required) => ({
3177
- bytes: byteLength(content),
3178
- content,
3179
- entryIds,
3180
- id: stableId(originalIndex, entryIds, kind, content),
3181
- kind,
3182
- label: labelFor(kind, content),
3183
- originalIndex,
3184
- required
3185
- });
3186
3317
  var pendingAdvisorArguments = (part) => {
3187
3318
  const value = isRecord(part.arguments) ? part.arguments : {};
3188
3319
  const allowed = {};
@@ -3250,7 +3381,7 @@ var missingOutcome = (entry, index, entryId, disclosed, callIds, missing, result
3250
3381
  }
3251
3382
  const pendingDisclosed = pendingInvocationDisclosure(entry, currentInvocationId, caps.toolResultMaxLines, caps.toolResultMaxBytes, caps.policies, caps.redact, caps.imageNonce, disclosed);
3252
3383
  return {
3253
- group: createGroup(index, [entryId, ...resultEntryIds], "pending-invocation", [pendingDisclosed ?? disclosed, ...resultParts].join(`
3384
+ group: createScoutContextGroup(index, [entryId, ...resultEntryIds], "pending-invocation", [pendingDisclosed ?? disclosed, ...resultParts].join(`
3254
3385
 
3255
3386
  `), true),
3256
3387
  kind: "group"
@@ -3274,7 +3405,7 @@ var toolExchangeGroup = (entry, message, index, entryId, disclosed, immediate, i
3274
3405
  return missingOutcome(entry, index, entryId, disclosed, callIds, missing, resultParts, resultEntryIds, caps);
3275
3406
  }
3276
3407
  return {
3277
- group: createGroup(index, [entryId, ...resultEntryIds], "tool-exchange", [disclosed, ...resultParts].join(`
3408
+ group: createScoutContextGroup(index, [entryId, ...resultEntryIds], "tool-exchange", [disclosed, ...resultParts].join(`
3278
3409
 
3279
3410
  `), false),
3280
3411
  kind: "group"
@@ -3299,14 +3430,14 @@ var groupForEntry = (entry, index, disclosed, immediate, indexed, consumedResult
3299
3430
  const entryId = isString(entry.id) ? entry.id : String(index);
3300
3431
  if (entry.type !== "message" || !isRecord(entry.message)) {
3301
3432
  return {
3302
- group: createGroup(index, [entryId], "compaction", disclosed, false),
3433
+ group: createScoutContextGroup(index, [entryId], "compaction", disclosed, false),
3303
3434
  kind: "group"
3304
3435
  };
3305
3436
  }
3306
3437
  const { message } = entry;
3307
3438
  if (message.role === "user") {
3308
3439
  return {
3309
- group: createGroup(index, [entryId], "user", disclosed, index === indexed.latestUserIndex),
3440
+ group: createScoutContextGroup(index, [entryId], "user", disclosed, index === indexed.latestUserIndex),
3310
3441
  kind: "group"
3311
3442
  };
3312
3443
  }
@@ -3318,7 +3449,7 @@ var groupForEntry = (entry, index, disclosed, immediate, indexed, consumedResult
3318
3449
  }
3319
3450
  if (!hasCalls(message)) {
3320
3451
  return {
3321
- group: createGroup(index, [entryId], "assistant", disclosed, false),
3452
+ group: createScoutContextGroup(index, [entryId], "assistant", disclosed, false),
3322
3453
  kind: "group"
3323
3454
  };
3324
3455
  }
@@ -3489,6 +3620,55 @@ var buildScoutManifest = (ctx, options = {}) => {
3489
3620
  return fitToBudget(built, caps);
3490
3621
  };
3491
3622
 
3623
+ // src/scout-selection.ts
3624
+ var byteLength2 = (value) => Buffer.byteLength(value, "utf-8");
3625
+ var isStringArray = (value) => Array.isArray(value) && value.every(isString);
3626
+ var parseScoutSelection = (text, manifest) => {
3627
+ if (!text.trim()) {
3628
+ throw new Error("Scout returned an empty response.");
3629
+ }
3630
+ let value;
3631
+ try {
3632
+ value = JSON.parse(text);
3633
+ } catch (error) {
3634
+ throw new Error("Scout response is not a JSON object.", { cause: error });
3635
+ }
3636
+ if (!isRecord(value)) {
3637
+ throw new Error("Scout response must be a JSON object.");
3638
+ }
3639
+ const keys = Object.keys(value).toSorted();
3640
+ if (keys.length !== 2 || keys[0] !== "selectedIds" || keys[1] !== "synthesis") {
3641
+ throw new Error("Scout response must contain only selectedIds and synthesis.");
3642
+ }
3643
+ if (!isStringArray(value.selectedIds)) {
3644
+ throw new Error("Scout selectedIds must be an array of strings.");
3645
+ }
3646
+ const { selectedIds } = value;
3647
+ if (new Set(selectedIds).size !== selectedIds.length) {
3648
+ throw new Error("Scout selected duplicate group IDs.");
3649
+ }
3650
+ const known = new Set(manifest.groups.map((group) => group.id));
3651
+ const knownSelectedIds = selectedIds.filter((id) => known.has(id));
3652
+ const requiredIds = manifest.groups.filter((group) => group.required).map((group) => group.id);
3653
+ if (requiredIds.length > SCOUT_SELECTION_MAX_IDS) {
3654
+ throw new Error(`Manifest contains more than ${SCOUT_SELECTION_MAX_IDS} required groups.`);
3655
+ }
3656
+ const required = new Set(requiredIds);
3657
+ const optionalIds = knownSelectedIds.filter((id) => !required.has(id)).slice(0, SCOUT_SELECTION_MAX_IDS - requiredIds.length);
3658
+ const retained = new Set([...requiredIds, ...optionalIds]);
3659
+ const normalizedIds = manifest.groups.filter((group) => retained.has(group.id)).map((group) => group.id);
3660
+ if (!isString(value.synthesis)) {
3661
+ throw new TypeError("Scout synthesis must be a string.");
3662
+ }
3663
+ if (byteLength2(value.synthesis) > SCOUT_SYNTHESIS_MAX_BYTES) {
3664
+ throw new Error(`Scout synthesis exceeds ${SCOUT_SYNTHESIS_MAX_BYTES} UTF-8 bytes.`);
3665
+ }
3666
+ return {
3667
+ selectedIds: normalizedIds,
3668
+ synthesis: knownSelectedIds.length > 0 ? value.synthesis : ""
3669
+ };
3670
+ };
3671
+
3492
3672
  // src/usage.ts
3493
3673
  var finite = (value) => isNumber(value) && Number.isFinite(value) && value >= 0 ? value : undefined;
3494
3674
  var add = (left, right) => left === undefined || right === undefined ? left ?? right : left + right;
@@ -3664,13 +3844,16 @@ var formatAdvisorUsage = (usage) => {
3664
3844
  var formatAdvisorUsageTotals = (totals) => {
3665
3845
  const usage = formatUsageFields(totals);
3666
3846
  const missing = totals.calls - totals.knownCalls;
3667
- return [usage, missing > 0 ? `${missing} without usage data` : undefined].filter((value) => value !== undefined).join(" · ") || "unavailable";
3847
+ return [
3848
+ usage,
3849
+ missing > 0 ? `${missing} ${t("usage.withoutData", "without usage data")}` : undefined
3850
+ ].filter((value) => value !== undefined).join(" · ") || t("usage.unavailable", "unavailable");
3668
3851
  };
3669
3852
  var formatAdvisorUsageStatus = (totals) => {
3670
3853
  if (totals.calls === 0) {
3671
3854
  return;
3672
3855
  }
3673
- return `Advisor: ${totals.calls} call${totals.calls === 1 ? "" : "s"} · ${formatAdvisorUsageTotals(totals)}`;
3856
+ return `${t("usage.advisorPrefix", "Advisor:")} ${totals.calls} ${totals.calls === 1 ? t("usage.call", "call") : t("usage.calls", "calls")} · ${formatAdvisorUsageTotals(totals)}`;
3674
3857
  };
3675
3858
 
3676
3859
  // src/scout.ts
@@ -3690,7 +3873,6 @@ var defaultDependencies = {
3690
3873
  collect: collectTextStream,
3691
3874
  resolve: resolveConfiguredModel
3692
3875
  };
3693
- var byteLength2 = (value) => Buffer.byteLength(value, "utf-8");
3694
3876
  var AUTH_ERROR_PATTERN = /api key|auth|login|credential/iu;
3695
3877
  var manifestMessage = (manifest) => ({
3696
3878
  content: [
@@ -3708,52 +3890,6 @@ var manifestMessage = (manifest) => ({
3708
3890
  role: "user",
3709
3891
  timestamp: Date.now()
3710
3892
  });
3711
- var isStringArray = (value) => Array.isArray(value) && value.every(isString);
3712
- var parseScoutSelection = (text, manifest) => {
3713
- if (!text.trim()) {
3714
- throw new Error("Scout returned an empty response.");
3715
- }
3716
- let value;
3717
- try {
3718
- value = JSON.parse(text);
3719
- } catch (error) {
3720
- throw new Error("Scout response is not a JSON object.", { cause: error });
3721
- }
3722
- if (!isRecord(value)) {
3723
- throw new Error("Scout response must be a JSON object.");
3724
- }
3725
- const keys = Object.keys(value).toSorted();
3726
- if (keys.length !== 2 || keys[0] !== "selectedIds" || keys[1] !== "synthesis") {
3727
- throw new Error("Scout response must contain only selectedIds and synthesis.");
3728
- }
3729
- if (!isStringArray(value.selectedIds)) {
3730
- throw new Error("Scout selectedIds must be an array of strings.");
3731
- }
3732
- const { selectedIds } = value;
3733
- if (new Set(selectedIds).size !== selectedIds.length) {
3734
- throw new Error("Scout selected duplicate group IDs.");
3735
- }
3736
- const known = new Set(manifest.groups.map((group) => group.id));
3737
- const knownSelectedIds = selectedIds.filter((id) => known.has(id));
3738
- const requiredIds = manifest.groups.filter((group) => group.required).map((group) => group.id);
3739
- if (requiredIds.length > SCOUT_SELECTION_MAX_IDS) {
3740
- throw new Error(`Manifest contains more than ${SCOUT_SELECTION_MAX_IDS} required groups.`);
3741
- }
3742
- const required = new Set(requiredIds);
3743
- const optionalIds = knownSelectedIds.filter((id) => !required.has(id)).slice(0, SCOUT_SELECTION_MAX_IDS - requiredIds.length);
3744
- const retained = new Set([...requiredIds, ...optionalIds]);
3745
- const normalizedIds = manifest.groups.filter((group) => retained.has(group.id)).map((group) => group.id);
3746
- if (!isString(value.synthesis)) {
3747
- throw new TypeError("Scout synthesis must be a string.");
3748
- }
3749
- if (byteLength2(value.synthesis) > SCOUT_SYNTHESIS_MAX_BYTES) {
3750
- throw new Error(`Scout synthesis exceeds ${SCOUT_SYNTHESIS_MAX_BYTES} UTF-8 bytes.`);
3751
- }
3752
- return {
3753
- selectedIds: normalizedIds,
3754
- synthesis: knownSelectedIds.length > 0 ? value.synthesis : ""
3755
- };
3756
- };
3757
3893
  var baseMetrics = (manifest, startedAt) => ({
3758
3894
  availableCount: manifest.availableCount,
3759
3895
  inputBytes: manifest.availableBytes,
@@ -4080,7 +4216,7 @@ var assembleConsultationContext = async (options) => {
4080
4216
  const changes = collectGitContext(ctx.cwd, level, gitBudget, advisorRedactSecretsRef ? redactSecrets : undefined);
4081
4217
  const changeText = advisorRepositoryContext(changes, options.gitContext ?? allowed, level, gitBudget);
4082
4218
  const conversationBudget = Math.max(0, contextMaxCharsRef - changeText.length);
4083
- const imageNonce = randomUUID();
4219
+ const imageNonce = randomUUID2();
4084
4220
  const legacyConversation = advisorRequestConversation(ctx, conversationBudget, true, imageNonce);
4085
4221
  const curated = await curateAdvisorConversation(ctx, legacyConversation, options.signal, options.onScout, advisorScoutEnabledRef, runAdvisorScout, options.currentInvocationId, conversationBudget, imageNonce);
4086
4222
  const preferences = await readProjectPreferences(ctx, ATTACHMENT_TEXT_MAX_BYTES, advisorRedactSecretsRef);
@@ -4461,7 +4597,7 @@ var consultAdvisor = async (ctx, question, signal, onChunk, trigger = "executor-
4461
4597
  signal,
4462
4598
  systemPrompt: ADVISOR_SYSTEM
4463
4599
  });
4464
- const adviceId = randomUUID2();
4600
+ const adviceId = randomUUID3();
4465
4601
  const { followUpPayload, ...publicResult } = result;
4466
4602
  onFollowUpPayload?.(adviceId, followUpPayload, followUp?.adviceId);
4467
4603
  return { ...publicResult, adviceId, trigger };
@@ -4617,7 +4753,7 @@ class ThinkingMarkdown {
4617
4753
  }
4618
4754
  }
4619
4755
  var hiddenThinkingLabel = (theme) => {
4620
- const label = theme.fg("thinkingText", `${THINKING_PREFIX}Thinking…`);
4756
+ const label = theme.fg("thinkingText", `${THINKING_PREFIX}${t("render.thinking", "Thinking…")}`);
4621
4757
  return {
4622
4758
  invalidate: noop,
4623
4759
  render: () => [label]
@@ -4628,7 +4764,7 @@ var resolveAdvisorRequest = (question) => question?.trim() || undefined;
4628
4764
  var renderAdvisorCallBox = (question, theme, followUp = false) => {
4629
4765
  const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
4630
4766
  const label = theme.fg("customMessageLabel", theme.bold("[advisor]"));
4631
- const title = theme.fg("customMessageText", followUp ? "Executor → Advisor · Follow-up" : "Executor → Advisor");
4767
+ const title = theme.fg("customMessageText", followUp ? `${t("render.executorToAdvisor", "Executor → Advisor")} · ${t("render.followUp", "Follow-up")}` : t("render.executorToAdvisor", "Executor → Advisor"));
4632
4768
  box.addChild(new Text(question ? `${label} ${title}
4633
4769
  ${theme.fg("dim", ` ${question}`)}` : `${label} ${title}`, 0, 0));
4634
4770
  return box;
@@ -4637,7 +4773,7 @@ var COLLAPSED_ADVICE_LINES = 12;
4637
4773
  var SOUND_VERDICT = /^Verdict:\s*sound$/u;
4638
4774
  var hasSoundVerdict = (advice) => SOUND_VERDICT.test((advice.split(`
4639
4775
  `).find((line) => line.trim()) ?? "").trim());
4640
- var renderAdvisorResponseHeader = (sound, theme) => sound ? theme.fg("accent", theme.bold("◆ ADVISOR · SOUND")) : theme.fg("warning", theme.bold("◆ ADVISOR RESPONSE"));
4776
+ var renderAdvisorResponseHeader = (sound, theme) => sound ? theme.fg("accent", theme.bold(`◆ ADVISOR · ${t("render.sound", "SOUND")}`)) : theme.fg("warning", theme.bold(`◆ ADVISOR ${t("render.response", "RESPONSE")}`));
4641
4777
  var adviceForDisplay = (advice, expanded) => {
4642
4778
  if (!advisorCollapseResponsesRef || expanded) {
4643
4779
  return advice;
@@ -4723,7 +4859,7 @@ class ScoutStatusManager {
4723
4859
  if (event.type === "call" || event.type === "chunk") {
4724
4860
  this.#active.add(token);
4725
4861
  if (this.showStatus) {
4726
- uiAction(ctx, (ui) => ui.setStatus("advisor-scout", "Scout curating…"));
4862
+ uiAction(ctx, (ui) => ui.setStatus("advisor-scout", t("status.scoutCurating", "Scout curating…")));
4727
4863
  }
4728
4864
  return;
4729
4865
  }
@@ -4736,7 +4872,7 @@ class ScoutStatusManager {
4736
4872
  if (!(uiAvailable(ctx) && this.showStatus)) {
4737
4873
  return;
4738
4874
  }
4739
- uiAction(ctx, (ui) => ui.setStatus("advisor-scout", this.#active.size > 0 ? "Scout curating…" : undefined));
4875
+ uiAction(ctx, (ui) => ui.setStatus("advisor-scout", this.#active.size > 0 ? t("status.scoutCurating", "Scout curating…") : undefined));
4740
4876
  }
4741
4877
  clear(ctx) {
4742
4878
  for (const token of this.#known) {
@@ -5010,7 +5146,7 @@ class AdvisorJevLedgerState {
5010
5146
  }
5011
5147
  }
5012
5148
 
5013
- // src/session-state.ts
5149
+ // src/tool-input-normalization.ts
5014
5150
  var WHITESPACE = /\s/u;
5015
5151
  var TIMESTAMP_KEYS = new Set([
5016
5152
  "createdat",
@@ -5078,6 +5214,8 @@ var normalizeToolInput = (toolName, input) => {
5078
5214
  return visit(input);
5079
5215
  };
5080
5216
  var normalizedToolSignature = (toolName, input) => `${toolName}:${JSON.stringify(normalizeToolInput(toolName, input))}`;
5217
+
5218
+ // src/session-state.ts
5081
5219
  var freshRepetition = () => ({
5082
5220
  count: 0,
5083
5221
  interventions: 0
@@ -5293,7 +5431,7 @@ class AdvisorSessionState {
5293
5431
  parts.push(`${count} ${decision}`);
5294
5432
  }
5295
5433
  }
5296
- return parts.join(", ") || "none";
5434
+ return parts.join(", ") || t("sessionSummary.none", "none");
5297
5435
  }
5298
5436
  #countTrigger(trigger) {
5299
5437
  return this.#usage.invocations.filter((item) => item.trigger === trigger).length;
@@ -5306,7 +5444,7 @@ class AdvisorSessionState {
5306
5444
  "repeated-tool-call",
5307
5445
  "completion-review",
5308
5446
  "custom-rule"
5309
- ].filter((trigger) => this.#countTrigger(trigger) > 0).join(", ") || "none";
5447
+ ].filter((trigger) => this.#countTrigger(trigger) > 0).join(", ") || t("sessionSummary.none", "none");
5310
5448
  }
5311
5449
  recordJevFilterAllowed() {
5312
5450
  this.#jev.recordFilterAllowed();
@@ -5345,22 +5483,22 @@ class AdvisorSessionState {
5345
5483
  const gates = invocations.filter((item) => item.kind === "gate");
5346
5484
  const effects = (effect) => invocations.filter((item) => item.executionEffect === effect).length;
5347
5485
  const failures = invocations.filter((item) => item.failure).map((item) => item.failure);
5348
- const models = [...new Set(invocations.map((item) => item.model).filter(Boolean))].join(", ") || "unknown";
5349
- const budget = limit === undefined ? `${this.#consumedCalls} used; unlimited remaining` : `${this.#consumedCalls} / ${limit} used; ${Math.max(0, limit - this.#consumedCalls)} remaining`;
5486
+ const models = [...new Set(invocations.map((item) => item.model).filter(Boolean))].join(", ") || t("sessionSummary.models.unknown", "unknown");
5487
+ const budget = limit === undefined ? `${this.#consumedCalls} ${t("sessionSummary.budget.used", "used")}; ${t("sessionSummary.budget.unlimitedRemaining", "unlimited remaining")}` : `${this.#consumedCalls} / ${limit} ${t("sessionSummary.budget.used", "used")}; ${Math.max(0, limit - this.#consumedCalls)} ${t("sessionSummary.budget.remaining", "remaining")}`;
5350
5488
  return [
5351
- "[Session Advisor Summary]",
5352
- `Consultations: ${markdown.length} Markdown (${this.#countTrigger("manual")} manual, ${this.#countTrigger("executor-requested")} executor-requested), automatic gates: ${gates.length}`,
5353
- `Triggers: ${this.#triggersLine()}`,
5354
- `Models: ${models}`,
5355
- `Budget: ${budget}`,
5356
- `Usage: ${formatAdvisorUsageTotals(totals)}`,
5357
- `Markdown advice: ${markdown.length} responses (${this.#ledger.draftConsultations} with drafts)`,
5358
- `Follow-ups: ${markdown.filter((item) => item.followUp).length}`,
5359
- `Outcome reports: ${this.#ledger.outcomes}`,
5360
- `Gate decisions: ${this.#decisionsLine()}`,
5361
- `Loop matching: normalized tool signatures; ${this.#repetition.interventions} gate intervention${this.#repetition.interventions === 1 ? "" : "s"}`,
5362
- `Execution effects: ${effects("tool-blocked")} tool blocked, ${effects("session-blocked")} sessions blocked, ${effects("continued")} continued`,
5363
- `Failures: ${failures.length ? failures.join(", ") : "none"}`,
5489
+ t("sessionSummary.title", "[Session Advisor Summary]"),
5490
+ `${t("sessionSummary.consultations.label", "Consultations:")} ${markdown.length} ${t("sessionSummary.consultations.markdown", "Markdown")} (${this.#countTrigger("manual")} ${t("sessionSummary.consultations.manual", "manual")}, ${this.#countTrigger("executor-requested")} ${t("sessionSummary.consultations.executorRequested", "executor-requested")}), ${t("sessionSummary.consultations.automaticGates", "automatic gates:")} ${gates.length}`,
5491
+ `${t("sessionSummary.triggers.label", "Triggers:")} ${this.#triggersLine()}`,
5492
+ `${t("sessionSummary.models.label", "Models:")} ${models}`,
5493
+ `${t("sessionSummary.budget.label", "Budget:")} ${budget}`,
5494
+ `${t("sessionSummary.usage.label", "Usage:")} ${formatAdvisorUsageTotals(totals)}`,
5495
+ `${t("sessionSummary.markdownAdvice.label", "Markdown advice:")} ${markdown.length} ${t("sessionSummary.markdownAdvice.responses", "responses")} (${this.#ledger.draftConsultations} ${t("sessionSummary.markdownAdvice.withDrafts", "with drafts")})`,
5496
+ `${t("sessionSummary.followUps.label", "Follow-ups:")} ${markdown.filter((item) => item.followUp).length}`,
5497
+ `${t("sessionSummary.outcomeReports.label", "Outcome reports:")} ${this.#ledger.outcomes}`,
5498
+ `${t("sessionSummary.gateDecisions.label", "Gate decisions:")} ${this.#decisionsLine()}`,
5499
+ `${t("sessionSummary.loopMatching.label", "Loop matching: normalized tool signatures;")} ${this.#repetition.interventions} ${t("sessionSummary.loopMatching.gateIntervention", "gate intervention")}${this.#repetition.interventions === 1 ? "" : "s"}`,
5500
+ `${t("sessionSummary.executionEffects.label", "Execution effects:")} ${effects("tool-blocked")} ${t("sessionSummary.executionEffects.toolBlocked", "tool blocked")}, ${effects("session-blocked")} ${t("sessionSummary.executionEffects.sessionsBlocked", "sessions blocked")}, ${effects("continued")} ${t("sessionSummary.executionEffects.continued", "continued")}`,
5501
+ `${t("sessionSummary.failures.label", "Failures:")} ${failures.length ? failures.join(", ") : t("sessionSummary.none", "none")}`,
5364
5502
  ...jevLines
5365
5503
  ].join(`
5366
5504
  `);
@@ -5385,9 +5523,8 @@ var notify = (ctx, message, level) => {
5385
5523
  uiAction(ctx, (ui) => ui.notify(message, level));
5386
5524
  };
5387
5525
  var reportManualBudgetExhausted = (ctx) => {
5388
- const message = "Advisor call budget exhausted for this session.";
5389
- notify(ctx, message, "warning");
5390
- notifyHerdrAdvisorFailure("Advisor budget exhausted", message);
5526
+ notify(ctx, t("notify.budgetExhausted.message", "Advisor call budget exhausted for this session."), "warning");
5527
+ notifyHerdrAdvisorFailure("Advisor budget exhausted", "Advisor call budget exhausted for this session.");
5391
5528
  };
5392
5529
  var requestManualRender = (ctx) => {
5393
5530
  uiAction(ctx, (ui) => ui.setStatus("advisor-manual", undefined));
@@ -5433,7 +5570,7 @@ class CommandRuntime {
5433
5570
  if (disabled && this.lastSameModelDisabled !== true) {
5434
5571
  notify(ctx, sameModelAdvisorNotice, "info");
5435
5572
  } else if (!disabled && this.lastSameModelDisabled === true) {
5436
- notify(ctx, "Advisor re-enabled: executor and advisor models differ.", "info");
5573
+ notify(ctx, t("notify.sameModelReenabled.message", "Advisor re-enabled: executor and advisor models differ."), "info");
5437
5574
  }
5438
5575
  this.lastSameModelDisabled = disabled;
5439
5576
  }
@@ -5462,7 +5599,7 @@ var loadCommandConfig = (ctx) => {
5462
5599
  return true;
5463
5600
  } catch (error) {
5464
5601
  const message = error instanceof Error ? error.message : String(error);
5465
- notify(ctx, `Advisor command could not load configuration: ${message} Fix advisor.json and retry.`, "error");
5602
+ notify(ctx, `${t("notify.configLoadFailed.prefix", "Advisor command could not load configuration:")} ${message} ${t("notify.configLoadFailed.suffix", "Fix advisor.json and retry.")}`, "error");
5466
5603
  return false;
5467
5604
  }
5468
5605
  };
@@ -5481,7 +5618,7 @@ var prepareActivationModels = async (runtime, ctx, announce, executorOverride, a
5481
5618
  return { pendingExecutor: plan.pendingExecutor, pickedModels: false };
5482
5619
  }
5483
5620
  if (!announce) {
5484
- notify(ctx, "Advisor models are not configured or available. Run /advisor to choose them.", "error");
5621
+ notify(ctx, t("notify.modelsNotConfigured.message", "Advisor models are not configured or available. Run /advisor to choose them."), "error");
5485
5622
  return;
5486
5623
  }
5487
5624
  const selection = await selectAdvisorModels(ctx, {
@@ -5528,12 +5665,14 @@ var resolveActivationModels = async (runtime, ctx, canContinue) => {
5528
5665
  }
5529
5666
  const executor = executorRef ? findConfiguredModel(ctx, executorRef) : undefined;
5530
5667
  if (executorRef && !executor) {
5531
- return { error: `Executor model not found: ${executorRef}` };
5668
+ return {
5669
+ error: `${t("activation.executorNotFound.prefix", "Executor model not found:")} ${executorRef}`
5670
+ };
5532
5671
  }
5533
5672
  const advisor = findConfiguredModel(ctx, advisorRef);
5534
5673
  if (!advisor) {
5535
5674
  return {
5536
- error: advisorRef ? `Advisor model not found: ${advisorRef}` : "Advisor model not configured"
5675
+ error: advisorRef ? `${t("activation.advisorNotFound.prefix", "Advisor model not found:")} ${advisorRef}` : t("activation.advisorNotConfigured", "Advisor model not configured")
5537
5676
  };
5538
5677
  }
5539
5678
  if (advisor.api !== "pi-virtual") {
@@ -5542,11 +5681,15 @@ var resolveActivationModels = async (runtime, ctx, canContinue) => {
5542
5681
  return { cancelled: true };
5543
5682
  }
5544
5683
  if (!(advisorAuth.ok && hasUsableModelAuth(advisorAuth))) {
5545
- return { error: `No API key for Advisor ${advisorRef}` };
5684
+ return {
5685
+ error: `${t("activation.noAdvisorApiKey.prefix", "No API key for Advisor")} ${advisorRef}`
5686
+ };
5546
5687
  }
5547
5688
  }
5548
5689
  if (executor && !isMarkedSubagent() && !await runtime.setExecutorModel(executor)) {
5549
- return { error: `No API key for Executor ${executorRef}` };
5690
+ return {
5691
+ error: `${t("activation.noExecutorApiKey.prefix", "No API key for Executor")} ${executorRef}`
5692
+ };
5550
5693
  }
5551
5694
  return {};
5552
5695
  };
@@ -5575,7 +5718,7 @@ var persistSuccessfulActivation = (ctx, shouldSave, reenableTools, restoreRefs)
5575
5718
  setAdvisorToolsEnabledRef(false);
5576
5719
  restoreRefs();
5577
5720
  const message = saveError instanceof Error ? saveError.message : String(saveError);
5578
- notify(ctx, `Could not save Advisor activation: ${message}`, "error");
5721
+ notify(ctx, `${t("activation.saveFailed.prefix", "Could not save Advisor activation:")} ${message}`, "error");
5579
5722
  return false;
5580
5723
  }
5581
5724
  return true;
@@ -5654,34 +5797,540 @@ var activateAdvisor = async (runtime, args, ctx, announce = true) => {
5654
5797
  if (announce) {
5655
5798
  const activeExecutorRef = effectiveExecutorRef(ctx);
5656
5799
  const activeExecutorEffort = effectiveExecutorEffort(ctx);
5657
- notify(ctx, `${ADVISOR_ACTIVATION_EXPLANATION}
5800
+ notify(ctx, `${t("activation.explanation", "The Advisor is a second-opinion model that reviews the Executor's context and returns risks, alternatives, and verification steps without changing files or running tools.")}
5658
5801
 
5659
- Advisor flow ${sameModelAdvisorDisabled(ctx, activeModel) ? "configured" : "ready"} — Executor: ${activeExecutorRef} (thinking: ${activeExecutorEffort || "default"}) · Advisor: ${advisorRef} (thinking: ${advisorEffortRef || "default"})`, "info");
5802
+ ${t("activation.flow", "Advisor flow")} ${sameModelAdvisorDisabled(ctx, activeModel) ? t("activation.flowConfigured", "configured") : t("activation.flowReady", "ready")} — Executor: ${activeExecutorRef} (thinking: ${activeExecutorEffort || "default"}) · Advisor: ${advisorRef} (thinking: ${advisorEffortRef || "default"})`, "info");
5660
5803
  }
5661
5804
  };
5662
5805
 
5663
- // src/commands/lifecycle.ts
5664
- var registerCommandLifecycle = (runtime, activateAdvisor) => {
5665
- runtime.pi.on("session_start", async (_event, ctx) => {
5666
- runtime.pendingExecutorModelRef = undefined;
5667
- runtime.resetSameModelNotice();
5668
- try {
5669
- loadConfig(ctx);
5670
- if (!advisorToolsEnabledRef) {
5671
- setAdvisorToolsActive(runtime.pi, false);
5672
- runtime.updateSameModelNotice(ctx);
5673
- return;
5674
- }
5675
- if (alwaysOnRef) {
5676
- setAdvisorToolsActive(runtime.pi, false);
5677
- await activateAdvisor("", ctx, false);
5806
+ // src/commands/configuration-tool.ts
5807
+ import { Text as Text3 } from "@earendil-works/pi-tui";
5808
+ import { Type } from "typebox";
5809
+
5810
+ // src/commands/configuration-tool-policy.ts
5811
+ var UI_ONLY_KEYS = new Set([
5812
+ "advisorJevBaseUrl",
5813
+ "advisorJevClassifier",
5814
+ "advisorJevKeyProvider",
5815
+ "advisorJevModel",
5816
+ "advisorJevPricePerMtok",
5817
+ "advisorJevTransport"
5818
+ ]);
5819
+ var WRITABLE_KEYS = new Set(configKeys.filter((key) => !UI_ONLY_KEYS.has(key)));
5820
+ var ADVISOR_CONFIG_EFFORT_LEVELS = [
5821
+ "off",
5822
+ "minimal",
5823
+ "low",
5824
+ "medium",
5825
+ "high",
5826
+ "xhigh",
5827
+ "max"
5828
+ ];
5829
+ var ADVISOR_CONFIG_WRITABLE_KEYS = configKeys.filter((key) => !UI_ONLY_KEYS.has(key));
5830
+ var getAdvisorConfigSnapshot = () => {
5831
+ const snapshot = Object.fromEntries(configKeys.map((key) => [key, CONFIG_SCHEMA[key].current()]));
5832
+ return snapshot;
5833
+ };
5834
+ var getAdvisorConfigForAgent = (persisted) => {
5835
+ const snapshot = getAdvisorConfigSnapshot();
5836
+ const keys = configKeys.filter((key) => !UI_ONLY_KEYS.has(key));
5837
+ const effectiveSettings = Object.fromEntries(keys.map((key) => [key, snapshot[key] ?? null]));
5838
+ const globalOverrides = Object.fromEntries(keys.filter((key) => Object.hasOwn(persisted, key)).map((key) => [key, persisted[key]]));
5839
+ return {
5840
+ effectiveSettings,
5841
+ globalOverrides,
5842
+ jevClassifierConfigured: Boolean(persisted.advisorJevClassifier),
5843
+ readOnlyKeys: [...UI_ONLY_KEYS].toSorted(),
5844
+ writableKeys: [...ADVISOR_CONFIG_WRITABLE_KEYS].toSorted()
5845
+ };
5846
+ };
5847
+ var validateAdvisorConfigPatch = (value, jevClassifierConfigured) => {
5848
+ if (!isRecord(value)) {
5849
+ return false;
5850
+ }
5851
+ const keys = Object.keys(value);
5852
+ if (keys.length === 0) {
5853
+ throw new TypeError("Provide at least one Advisor setting to update.");
5854
+ }
5855
+ if (keys.length > 16) {
5856
+ throw new TypeError("Update at most 16 Advisor settings at a time.");
5857
+ }
5858
+ const unsupported = keys.filter((key) => !WRITABLE_KEYS.has(key));
5859
+ if (unsupported.length > 0) {
5860
+ throw new TypeError(`These Advisor settings require their dedicated UI flow: ${unsupported.map((key) => JSON.stringify(key)).join(", ")}. Use /advisor-settings for classifier and credential setup.`);
5861
+ }
5862
+ const setValues = {};
5863
+ for (const [key, setting] of Object.entries(value)) {
5864
+ if (setting !== null) {
5865
+ setValues[key] = setting;
5866
+ }
5867
+ }
5868
+ if (!validateConfig(setValues, "advisor_config changes")) {
5869
+ return false;
5870
+ }
5871
+ const effortLevels = ADVISOR_CONFIG_EFFORT_LEVELS;
5872
+ for (const key of ["advisorEffort", "executorEffort"]) {
5873
+ const effort = setValues[key];
5874
+ if (isString(effort) && !effortLevels.includes(effort)) {
5875
+ throw new TypeError(`${key} must be one of ${ADVISOR_CONFIG_EFFORT_LEVELS.join(", ")}; use null for the model default.`);
5876
+ }
5877
+ }
5878
+ if (value.advisor === null) {
5879
+ throw new TypeError("The Advisor model cannot be cleared from chat. Choose another model with the picker or use /advisor-models.");
5880
+ }
5881
+ const turnGateEveryTurns = isNumber(setValues.advisorJevTurnGateEveryTurns) ? setValues.advisorJevTurnGateEveryTurns : 0;
5882
+ if ((setValues.advisorJevFilterEnabled === true || turnGateEveryTurns > 0) && !jevClassifierConfigured) {
5883
+ throw new TypeError("Select and verify a Jev classifier in /advisor-settings before enabling Jev screening or the turn gate. No settings were changed.");
5884
+ }
5885
+ return true;
5886
+ };
5887
+ var addAdvisorConfigDependencies = (changes) => {
5888
+ const normalized = { ...changes };
5889
+ if (changes.advisorToolsEnabled === false) {
5890
+ if (changes.alwaysOn === true) {
5891
+ throw new TypeError("Advisor tools cannot be disabled while Always on is enabled in the same update. Set both to false.");
5892
+ }
5893
+ normalized.alwaysOn = false;
5894
+ }
5895
+ if (changes.alwaysOn === true) {
5896
+ if (changes.advisorToolsEnabled === false) {
5897
+ throw new TypeError("Always on requires Advisor tools. Enable both or keep Always on off.");
5898
+ }
5899
+ normalized.advisorToolsEnabled = true;
5900
+ }
5901
+ return normalized;
5902
+ };
5903
+
5904
+ // src/commands/configuration-tool-preview.ts
5905
+ var sameConfigValue2 = (left, right) => JSON.stringify(left) === JSON.stringify(right);
5906
+ var orderedPatchEntries = (patch) => configKeys.filter((key) => Object.hasOwn(patch, key)).map((key) => [key, patch[key]]);
5907
+ var sameConfigPatch = (left, right) => JSON.stringify(orderedPatchEntries(left)) === JSON.stringify(orderedPatchEntries(right));
5908
+ var effectiveChanges = (changes, persisted) => {
5909
+ const entries = [];
5910
+ for (const key of configKeys) {
5911
+ const value = changes[key];
5912
+ if (value === undefined) {
5913
+ continue;
5914
+ }
5915
+ if (value === null) {
5916
+ if (Object.hasOwn(persisted, key)) {
5917
+ entries.push([key, null]);
5918
+ }
5919
+ continue;
5920
+ }
5921
+ if (!sameConfigValue2(value, persisted[key] ?? null)) {
5922
+ entries.push([key, value]);
5923
+ }
5924
+ }
5925
+ return Object.fromEntries(entries);
5926
+ };
5927
+ var staleCheckKeys = (changes) => {
5928
+ const keys = new Set(configKeys.filter((key) => Object.hasOwn(changes, key)));
5929
+ if (keys.has("advisorToolsEnabled") || keys.has("alwaysOn")) {
5930
+ keys.add("advisorToolsEnabled");
5931
+ keys.add("alwaysOn");
5932
+ }
5933
+ if (keys.has("advisorJevFilterEnabled") || keys.has("advisorJevTurnGateEveryTurns")) {
5934
+ keys.add("advisorJevClassifier");
5935
+ }
5936
+ return [...keys];
5937
+ };
5938
+ var summarizeAdvisorConfigPatch = (changes, before, persisted) => configKeys.filter((key) => Object.hasOwn(changes, key)).map((key) => {
5939
+ const value = changes[key];
5940
+ const previous = Object.hasOwn(persisted, key) ? JSON.stringify(persisted[key]) : `unset (extension default; current session ${JSON.stringify(before[key] ?? null)})`;
5941
+ const next = value === null ? "reset to extension default" : JSON.stringify(value);
5942
+ return `- ${key}: ${previous} → ${next}`;
5943
+ }).join(`
5944
+ `);
5945
+ var automationRiskNotes = (changes, before) => {
5946
+ const notes = [];
5947
+ if (changes.simpleMode === true) {
5948
+ notes.push("Simple mode disables automatic gates, gate blocking, and configured call budgets; voluntary Advisor calls remain available.");
5949
+ }
5950
+ if (changes.advisorToolsEnabled === false) {
5951
+ notes.push("Advisor tools will be disabled immediately. advisor_config remains available to re-enable them.");
5952
+ }
5953
+ if (changes.alwaysOn === true) {
5954
+ notes.push("Always on enables automatic activation for future sessions.");
5955
+ }
5956
+ if (changes.advisorPlanGate === true || changes.advisorFailureGate === true || changes.advisorCompletionGate === true || changes.advisorAutoLoopGate === true) {
5957
+ notes.push("Automatic gates may request extra Advisor calls; loop-gate failures can block a tool or session under the selected failure policy.");
5958
+ }
5959
+ if (changes.gateFailureMode === "block-session" || changes.advisorBlockOnBlocked === true) {
5960
+ notes.push("A blocked gate may stop the current session.");
5961
+ }
5962
+ if (changes.advisorToolsEnabled === true) {
5963
+ notes.push(before.alwaysOn === true || changes.alwaysOn === true ? "Advisor tools become available, and saved Always on will activate the flow in future sessions." : "Advisor tools become available; this does not activate Always on.");
5964
+ }
5965
+ return notes;
5966
+ };
5967
+ var disclosureRiskNotes = (changes) => {
5968
+ const notes = [];
5969
+ if (changes.advisorGitContext === "full") {
5970
+ notes.push("Future Advisor requests may include repository patch contents.");
5971
+ }
5972
+ if (changes.advisorTrackedFileContent === true) {
5973
+ notes.push("This enables explicitly requested tracked file contents to be sent to the Advisor.");
5974
+ }
5975
+ if (changes.advisorUntrackedContent === true) {
5976
+ notes.push("This enables explicitly requested untracked file contents to be sent to the Advisor.");
5977
+ }
5978
+ if (changes.advisorAgentsMdContext === true) {
5979
+ notes.push("Trusted AGENTS.md instructions may be included in Advisor requests.");
5980
+ }
5981
+ if (changes.advisorToolPolicies && Object.values(changes.advisorToolPolicies).includes("full")) {
5982
+ notes.push("Tools set to full may send their arguments and result content to the Advisor.");
5983
+ }
5984
+ if (changes.advisorRedactSecrets === false) {
5985
+ notes.push("Credential-pattern redaction will be off for Advisor requests.");
5986
+ }
5987
+ return notes;
5988
+ };
5989
+ var costRiskNotes = (changes) => {
5990
+ const notes = [];
5991
+ if (changes.advisorOutcomeLogging === true) {
5992
+ notes.push("Outcome logging stores bounded adoption and validation metadata in the local ledger.");
5993
+ }
5994
+ if (changes.advisorMaxCallsPerSession === null) {
5995
+ notes.push("This removes the per-session Advisor call limit; calls may be unlimited.");
5996
+ }
5997
+ if ((changes.advisorJevTurnGateEveryTurns ?? 0) > 0) {
5998
+ notes.push("The Jev turn gate can initiate proactive Advisor calls and add cost.");
5999
+ }
6000
+ return notes;
6001
+ };
6002
+ var advisorConfigRiskNotes = (changes, before, persisted) => [
6003
+ ...automationRiskNotes(changes, {
6004
+ ...before,
6005
+ alwaysOn: Object.hasOwn(persisted, "alwaysOn") ? persisted.alwaysOn === true : before.alwaysOn
6006
+ }),
6007
+ ...disclosureRiskNotes(changes),
6008
+ ...costRiskNotes(changes)
6009
+ ];
6010
+
6011
+ // src/commands/configuration-tool-models.ts
6012
+ var MODEL_KEYS = [
6013
+ "advisor",
6014
+ "advisorEffort",
6015
+ "advisorFallbackModel",
6016
+ "executor",
6017
+ "executorEffort"
6018
+ ];
6019
+ var MODEL_REF_KEYS = [
6020
+ "advisor",
6021
+ "advisorFallbackModel",
6022
+ "executor"
6023
+ ];
6024
+ var isModelChange = (changes) => MODEL_KEYS.some((key) => Object.hasOwn(changes, key));
6025
+ var validateRequestedModels = (changes, modelRefs) => {
6026
+ for (const key of MODEL_REF_KEYS) {
6027
+ const requested = changes[key];
6028
+ if (requested !== null && requested !== undefined && !modelRefs.includes(requested)) {
6029
+ throw new Error(`${key} must name an available provider/model. Choose it from /advisor-models or use the model picker opened by advisor_config.`);
6030
+ }
6031
+ }
6032
+ };
6033
+ var pickerOptions = (changes, before) => ({
6034
+ advisor: changes.advisor ?? before.advisor,
6035
+ advisorEffort: changes.advisorEffort === null ? undefined : changes.advisorEffort ?? before.advisorEffort,
6036
+ advisorFallbackModel: changes.advisorFallbackModel === null ? undefined : changes.advisorFallbackModel ?? before.advisorFallbackModel,
6037
+ executor: changes.executor === null ? "" : changes.executor ?? before.executor,
6038
+ executorEffort: changes.executorEffort === null ? undefined : changes.executorEffort ?? before.executorEffort,
6039
+ selectAdvisor: Object.hasOwn(changes, "advisor") || Object.hasOwn(changes, "advisorEffort") || !before.advisor,
6040
+ selectExecutor: Object.hasOwn(changes, "executor") || Object.hasOwn(changes, "executorEffort")
6041
+ });
6042
+ var selectedModelChanges = (changes, selection, persisted) => {
6043
+ const selected = {
6044
+ advisor: selection.advisor,
6045
+ advisorEffort: selection.advisorEffort ?? null,
6046
+ advisorFallbackModel: selection.advisorFallbackModel ?? null,
6047
+ executor: selection.executor || null,
6048
+ executorEffort: selection.executorEffort ?? null
6049
+ };
6050
+ const resolved = {};
6051
+ for (const key of MODEL_KEYS) {
6052
+ const persistedValue = persisted[key] ?? null;
6053
+ if (!sameConfigValue2(selected[key], persistedValue)) {
6054
+ resolved[key] = selected[key];
6055
+ }
6056
+ }
6057
+ const {
6058
+ advisor: _requestedAdvisor,
6059
+ advisorEffort: _requestedAdvisorEffort,
6060
+ advisorFallbackModel: _requestedFallback,
6061
+ executor: _requestedExecutor,
6062
+ executorEffort: _requestedExecutorEffort,
6063
+ ...otherChanges
6064
+ } = changes;
6065
+ return { ...otherChanges, ...resolved };
6066
+ };
6067
+ var resolveModelChanges = async (ctx, changes, before, persisted, selectModels = selectAdvisorModels) => {
6068
+ if (!isModelChange(changes)) {
6069
+ return changes;
6070
+ }
6071
+ if (ctx.mode !== "tui") {
6072
+ throw new Error("Model changes require Pi's interactive TUI so you can choose from the existing model picker. No settings were changed.");
6073
+ }
6074
+ validateRequestedModels(changes, getConfiguredModelRefs(ctx));
6075
+ const selection = await selectModels(ctx, pickerOptions(changes, before));
6076
+ if (!selection) {
6077
+ return;
6078
+ }
6079
+ return selectedModelChanges(changes, selection, persisted);
6080
+ };
6081
+
6082
+ // src/commands/configuration-tool-runtime.ts
6083
+ var applyAdvisorConfigRuntimeSettings = (runtime, ctx, previous) => {
6084
+ const next = getAdvisorSettings();
6085
+ const shouldEnable = next.advisorToolsEnabled ?? true;
6086
+ const toolsAreActive = runtime.pi.getActiveTools().includes("ask_advisor");
6087
+ if (previous.advisorToolsEnabled !== next.advisorToolsEnabled || toolsAreActive !== shouldEnable) {
6088
+ runtime.noteAdvisorToolsStateChange();
6089
+ setAdvisorToolsActive(runtime.pi, shouldEnable);
6090
+ if (!shouldEnable) {
6091
+ runtime.resetSameModelNotice();
6092
+ }
6093
+ }
6094
+ runtime.updateSameModelNotice(ctx);
6095
+ runtime.updateAdvisorUsageStatus(ctx);
6096
+ };
6097
+ var cancelledAdvisorConfigResult = (message) => ({
6098
+ content: [{ text: message, type: "text" }],
6099
+ details: { action: "update", applied: false, cancelled: true }
6100
+ });
6101
+ var unchangedAdvisorConfigResult = (message) => ({
6102
+ content: [{ text: message, type: "text" }],
6103
+ details: { action: "update", applied: false, unchanged: true }
6104
+ });
6105
+
6106
+ // src/commands/configuration-tool-transaction.ts
6107
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
6108
+ var confirmAdvisorConfigUpdate = async (ctx, prepared, signal) => {
6109
+ const preview = summarizeAdvisorConfigPatch(prepared.proposed, prepared.before, prepared.existing);
6110
+ const risks = advisorConfigRiskNotes(prepared.proposed, prepared.before, prepared.existing);
6111
+ const confirmation = [
6112
+ "These changes apply to global Advisor settings, not a project config:",
6113
+ preview,
6114
+ ...risks.map((risk) => `
6115
+ Risk: ${risk}`)
6116
+ ].join(`
6117
+ `);
6118
+ const confirmed = await ctx.ui.confirm("Apply Advisor settings?", confirmation, { signal });
6119
+ return confirmed && !signal?.aborted;
6120
+ };
6121
+ var persistAdvisorConfigUpdate = (prepared, signal) => {
6122
+ const touched = staleCheckKeys(prepared.proposed);
6123
+ return withFileMutationQueue(prepared.configPath, () => Promise.resolve().then(() => {
6124
+ if (signal?.aborted) {
6125
+ throw new Error("Update cancelled before writing; no settings changed.");
6126
+ }
6127
+ const latest = readGlobalAdvisorConfig();
6128
+ const stale = touched.filter((key) => Object.hasOwn(latest, key) !== Object.hasOwn(prepared.existing, key) || !sameConfigValue2(latest[key] ?? null, prepared.existing[key] ?? null));
6129
+ if (stale.length > 0) {
6130
+ throw new Error(`Advisor settings changed while confirmation was open (${stale.join(", ")}). Read the settings again and retry; nothing was written.`);
6131
+ }
6132
+ const refreshed = effectiveChanges(addAdvisorConfigDependencies(prepared.proposed), latest);
6133
+ if (!sameConfigPatch(refreshed, prepared.proposed)) {
6134
+ throw new Error("Advisor setting dependencies changed while confirmation was open. Read the settings again and retry; nothing was written.");
6135
+ }
6136
+ if (Object.hasOwn(refreshed, "advisorOutcomeLogging")) {
6137
+ saveGlobalOutcomeLogging(refreshed.advisorOutcomeLogging === null ? null : refreshed.advisorOutcomeLogging === true, prepared.existing, touched);
6138
+ } else {
6139
+ saveGlobalAdvisorConfigPatch(refreshed, prepared.existing, touched);
6140
+ }
6141
+ return prepared.configPath;
6142
+ }));
6143
+ };
6144
+
6145
+ // src/commands/configuration-tool-update.ts
6146
+ var prepareAdvisorConfigUpdate = async (ctx, input, selectModels) => {
6147
+ const existing = readGlobalAdvisorConfig();
6148
+ const before = getAdvisorConfigSnapshot();
6149
+ const beforeSettings = getAdvisorSettings();
6150
+ const [, configPath] = configPaths(ctx);
6151
+ if (!configPath) {
6152
+ throw new Error("Could not resolve the global Advisor configuration path.");
6153
+ }
6154
+ if (input === undefined) {
6155
+ throw new TypeError("Provide Advisor settings changes for action=update.");
6156
+ }
6157
+ if (!validateAdvisorConfigPatch(input, Boolean(existing.advisorJevClassifier))) {
6158
+ throw new TypeError("Advisor settings changes must be a JSON object.");
6159
+ }
6160
+ const initialChanges = input;
6161
+ if (Object.hasOwn(initialChanges, "advisorOutcomeLogging") && Object.keys(initialChanges).length > 1) {
6162
+ throw new Error("Update advisorOutcomeLogging by itself so its separate consent path remains clear.");
6163
+ }
6164
+ const changesWithModels = await resolveModelChanges(ctx, initialChanges, before, existing, selectModels);
6165
+ if (!changesWithModels) {
6166
+ return;
6167
+ }
6168
+ const changes = addAdvisorConfigDependencies(changesWithModels);
6169
+ return {
6170
+ before,
6171
+ beforeSettings,
6172
+ configPath,
6173
+ existing,
6174
+ proposed: effectiveChanges(changes, existing)
6175
+ };
6176
+ };
6177
+ var appliedAdvisorConfigResult = (prepared, savedPath) => {
6178
+ const notices = [];
6179
+ if (Object.hasOwn(prepared.proposed, "alwaysOn") && prepared.proposed.alwaysOn === true) {
6180
+ notices.push("Always on applies to future sessions; this did not start an Advisor call.");
6181
+ }
6182
+ if (Object.hasOwn(prepared.proposed, "executor")) {
6183
+ notices.push(prepared.proposed.executor === null ? "The Executor pin was removed; it now follows the current Pi session model." : "Executor model selection is saved; run /advisor to activate it in this session.");
6184
+ }
6185
+ return {
6186
+ content: [
6187
+ {
6188
+ text: [
6189
+ `Saved Advisor settings to ${savedPath}.`,
6190
+ summarizeAdvisorConfigPatch(prepared.proposed, prepared.before, prepared.existing),
6191
+ ...notices
6192
+ ].join(`
6193
+ `),
6194
+ type: "text"
6195
+ }
6196
+ ],
6197
+ details: {
6198
+ action: "update",
6199
+ applied: true,
6200
+ changes: prepared.proposed,
6201
+ saved: true
6202
+ }
6203
+ };
6204
+ };
6205
+ var savedButNotAppliedResult = (prepared, savedPath, message) => ({
6206
+ content: [
6207
+ {
6208
+ text: `Advisor settings were saved to ${savedPath}, but could not be fully applied to the current session: ${message}`,
6209
+ type: "text"
6210
+ }
6211
+ ],
6212
+ details: {
6213
+ action: "update",
6214
+ applied: false,
6215
+ changes: prepared.proposed,
6216
+ saved: true
6217
+ }
6218
+ });
6219
+ var applyAdvisorConfigUpdate = (runtime, ctx, prepared, savedPath) => {
6220
+ try {
6221
+ loadConfig(ctx);
6222
+ if (!Object.hasOwn(prepared.proposed, "contextMaxChars") && prepared.before.contextMaxChars !== undefined) {
6223
+ setContextMaxCharsRef(prepared.before.contextMaxChars);
6224
+ rebaseConfigBaseline();
6225
+ }
6226
+ applyAdvisorConfigRuntimeSettings(runtime, ctx, prepared.beforeSettings);
6227
+ } catch (error) {
6228
+ const message = error instanceof Error ? error.message : String(error);
6229
+ return savedButNotAppliedResult(prepared, savedPath, message);
6230
+ }
6231
+ return appliedAdvisorConfigResult(prepared, savedPath);
6232
+ };
6233
+ var executeAdvisorConfigUpdate = async (runtime, ctx, input, signal, selectModels) => {
6234
+ if (!ctx.hasUI) {
6235
+ throw new Error("Advisor setting updates require an interactive confirmation. Use Pi's TUI or RPC UI; no settings were changed.");
6236
+ }
6237
+ const prepared = await prepareAdvisorConfigUpdate(ctx, input, selectModels);
6238
+ if (!prepared) {
6239
+ return cancelledAdvisorConfigResult("Model selection cancelled; no settings changed.");
6240
+ }
6241
+ if (Object.keys(prepared.proposed).length === 0) {
6242
+ return unchangedAdvisorConfigResult("Advisor settings already match the request.");
6243
+ }
6244
+ if (!await confirmAdvisorConfigUpdate(ctx, prepared, signal)) {
6245
+ return cancelledAdvisorConfigResult("Update cancelled; no settings changed.");
6246
+ }
6247
+ let savedPath;
6248
+ try {
6249
+ savedPath = await persistAdvisorConfigUpdate(prepared, signal);
6250
+ } catch (error) {
6251
+ const message = error instanceof Error ? error.message : String(error);
6252
+ throw new Error(`Advisor settings were not saved: ${message}`, {
6253
+ cause: error
6254
+ });
6255
+ }
6256
+ return applyAdvisorConfigUpdate(runtime, ctx, prepared, savedPath);
6257
+ };
6258
+
6259
+ // src/commands/configuration-tool.ts
6260
+ var CONFIGURATION_VALUE = Type.Union([
6261
+ Type.String(),
6262
+ Type.Number(),
6263
+ Type.Boolean(),
6264
+ Type.Null(),
6265
+ Type.Array(Type.String()),
6266
+ Type.Record(Type.String(), Type.String())
6267
+ ]);
6268
+ var CONFIGURATION_TOOL_PARAMETERS = Type.Object({
6269
+ action: Type.String({ enum: ["read", "update"] }),
6270
+ changes: Type.Optional(Type.Record(Type.String(), CONFIGURATION_VALUE))
6271
+ }, { additionalProperties: false });
6272
+ var readCurrentConfig = (ctx) => {
6273
+ const config = getAdvisorConfigForAgent(readGlobalAdvisorConfig());
6274
+ const currentSessionModel = ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : null;
6275
+ return {
6276
+ ...config,
6277
+ currentSessionModel,
6278
+ scope: "global"
6279
+ };
6280
+ };
6281
+ var registerAdvisorConfigurationTool = (runtime, dependencies = {}) => {
6282
+ runtime.pi.registerTool({
6283
+ description: "Read or update pi-advisor settings at the user's request. Start with action=read to inspect current effective settings, persisted global overrides, and writable keys. For action=update, pass a sparse changes object using exact keys from writableKeys; use null to remove a saved override and restore the extension default. Every changing update previews global old-to-new values and requires user confirmation. Model settings open the existing interactive model picker; supplied model strings are proposed selections, not approval. Jev classifier/credential setup must use /advisor-settings, and outcome logging must be changed by itself through its dedicated consent path.",
6284
+ async execute(_id, params, signal, _onUpdate, ctx) {
6285
+ if (params.action === "read") {
6286
+ if (params.changes) {
6287
+ throw new Error("Do not pass changes with action=read.");
6288
+ }
6289
+ const settings = readCurrentConfig(ctx);
6290
+ return {
6291
+ content: [{ text: JSON.stringify(settings, null, 2), type: "text" }],
6292
+ details: { action: "read", applied: false, settings }
6293
+ };
6294
+ }
6295
+ return await executeAdvisorConfigUpdate(runtime, ctx, params.changes, signal, dependencies.selectModels);
6296
+ },
6297
+ executionMode: "sequential",
6298
+ label: "Configure Advisor",
6299
+ name: "advisor_config",
6300
+ parameters: CONFIGURATION_TOOL_PARAMETERS,
6301
+ promptGuidelines: [
6302
+ "Use advisor_config when the user asks to inspect or change pi-advisor settings. Read before updates when the current value affects the requested outcome.",
6303
+ "Send only settings the user asked to change. advisor_config asks for confirmation before writing and preserves unrelated settings; do not edit advisor.json directly.",
6304
+ "Wait for advisor_config to report a successful update before saying a setting changed. Use /advisor-settings for Jev classifier/credential setup."
6305
+ ],
6306
+ promptSnippet: "Read or change the user's pi-advisor configuration",
6307
+ renderCall: () => new Text3("[advisor] Configure settings", 0, 0),
6308
+ renderResult: (result) => new Text3(textFrom(result.content), 0, 0)
6309
+ });
6310
+ };
6311
+
6312
+ // src/commands/lifecycle.ts
6313
+ var registerCommandLifecycle = (runtime, activateAdvisor) => {
6314
+ runtime.pi.on("session_start", async (_event, ctx) => {
6315
+ runtime.pendingExecutorModelRef = undefined;
6316
+ runtime.resetSameModelNotice();
6317
+ try {
6318
+ loadConfig(ctx);
6319
+ if (!advisorToolsEnabledRef) {
6320
+ setAdvisorToolsActive(runtime.pi, false);
6321
+ runtime.updateSameModelNotice(ctx);
6322
+ return;
6323
+ }
6324
+ if (alwaysOnRef) {
6325
+ setAdvisorToolsActive(runtime.pi, false);
6326
+ await activateAdvisor("", ctx, false);
5678
6327
  } else {
5679
6328
  runtime.updateSameModelNotice(ctx);
5680
6329
  }
5681
6330
  } catch (error) {
5682
6331
  setAdvisorToolsActive(runtime.pi, false);
5683
6332
  const message = error instanceof Error ? error.message : String(error);
5684
- notify(ctx, `Advisor activation failed: ${message}`, "error");
6333
+ notify(ctx, `${t("notify.activationFailed.prefix", "Advisor activation failed:")} ${message}`, "error");
5685
6334
  }
5686
6335
  });
5687
6336
  runtime.pi.on("model_select", (event, ctx) => {
@@ -5740,10 +6389,27 @@ import {
5740
6389
  visibleWidth as visibleWidth2,
5741
6390
  wrapTextWithAnsi
5742
6391
  } from "@earendil-works/pi-tui";
5743
- var MANUAL_GIT_CONTEXT_COPY = {
5744
- full: { description: "summary plus patch", label: "Full" },
5745
- off: { description: "no Git data", label: "None" },
5746
- summary: { description: "changed paths and status", label: "Summary" }
6392
+ var gitContextCopy = (level) => {
6393
+ switch (level) {
6394
+ case "full": {
6395
+ return {
6396
+ description: t("manualDialog.git.full.desc", "summary plus patch"),
6397
+ label: t("manualDialog.git.full.label", "Full")
6398
+ };
6399
+ }
6400
+ case "off": {
6401
+ return {
6402
+ description: t("manualDialog.git.off.desc", "no Git data"),
6403
+ label: t("manualDialog.git.off.label", "None")
6404
+ };
6405
+ }
6406
+ default: {
6407
+ return {
6408
+ description: t("manualDialog.git.summary.desc", "changed paths and status"),
6409
+ label: t("manualDialog.git.summary.label", "Summary")
6410
+ };
6411
+ }
6412
+ }
5747
6413
  };
5748
6414
  var renderManualAdvisorDialog = (view) => {
5749
6415
  const {
@@ -5776,7 +6442,7 @@ var renderManualAdvisorDialog = (view) => {
5776
6442
  }
5777
6443
  };
5778
6444
  if (renderWidth >= 2) {
5779
- const title = truncateToWidth3(" Ask Advisor ", Math.max(0, innerWidth), "", false);
6445
+ const title = truncateToWidth3(` ${t("manualDialog.title", "Ask Advisor")} `, Math.max(0, innerWidth), "", false);
5780
6446
  const titleWidth = visibleWidth2(title);
5781
6447
  const remaining = Math.max(0, innerWidth - titleWidth);
5782
6448
  const left = Math.floor(remaining / 2);
@@ -5784,20 +6450,20 @@ var renderManualAdvisorDialog = (view) => {
5784
6450
  lines.push(theme.fg("border", `╭${"─".repeat(left)}`) + theme.fg("accent", title) + theme.fg("border", `${"─".repeat(right)}╮`));
5785
6451
  addLine("");
5786
6452
  }
5787
- addLine(`${focusMarker("editor")}${theme.bold("Message for Advisor (optional)")}`);
6453
+ addLine(`${focusMarker("editor")}${theme.bold(t("manualDialog.messageLabel", "Message for Advisor (optional)"))}`);
5788
6454
  for (const editorLine of editorLines) {
5789
6455
  addLine(editorLine);
5790
6456
  }
5791
6457
  addLine("");
5792
- addWrapped("Automatic context follows your settings: conversation history, tool disclosure, project preferences, redaction, and configured limits remain unchanged.", "muted");
5793
- addWrapped("This dialog does not expose drafts or explicit file handoff controls.", "dim");
5794
- addWrapped("Git None only withholds repository data; it does not remove configured conversation history.", "dim");
6458
+ addWrapped(t("manualDialog.contextNote", "Automatic context follows your settings: conversation history, tool disclosure, project preferences, redaction, and configured limits remain unchanged."), "muted");
6459
+ addWrapped(t("manualDialog.noDraftsNote", "This dialog does not expose drafts or explicit file handoff controls."), "dim");
6460
+ addWrapped(t("manualDialog.gitNoneNote", "Git None only withholds repository data; it does not remove configured conversation history."), "dim");
5795
6461
  addLine("");
5796
- const gitCeiling = MANUAL_GIT_CONTEXT_COPY[gitContext].label;
5797
- addLine(`${focusMarker("git")}${theme.bold(`Git repository context (max: ${gitCeiling}; ↑/↓ or Space to choose)`)}`);
6462
+ const gitCeiling = gitContextCopy(gitContext).label;
6463
+ addLine(`${focusMarker("git")}${theme.bold(`${t("manualDialog.gitTitle", "Git repository context (max:")} ${gitCeiling}; ${t("manualDialog.gitChoose", "↑/↓ or Space to choose)")}`)}`);
5798
6464
  for (let index = 0;index < gitLevels.length; index += 1) {
5799
6465
  const level = gitLevels[index];
5800
- const copy = MANUAL_GIT_CONTEXT_COPY[level];
6466
+ const copy = gitContextCopy(level);
5801
6467
  const selected = index === gitIndex;
5802
6468
  const marker = selected ? "●" : "○";
5803
6469
  const optionFocus = focusTarget === "git" && selected ? "▸ " : " ";
@@ -5805,16 +6471,16 @@ var renderManualAdvisorDialog = (view) => {
5805
6471
  addWrapped(`${optionFocus}${marker} ${copy.label} — ${copy.description}`, color);
5806
6472
  }
5807
6473
  addLine("");
5808
- let interactionHint = "Enter submit · Shift+Enter newline · Tab/Shift+Tab focus · Esc cancel";
6474
+ let interactionHint = t("manualDialog.hint.editor", "Enter submit · Shift+Enter newline · Tab/Shift+Tab focus · Esc cancel");
5809
6475
  if (focusTarget === "git") {
5810
- interactionHint = "↑/↓ or Space choose · Enter next · Tab/Shift+Tab focus · Esc cancel";
6476
+ interactionHint = t("manualDialog.hint.git", "↑/↓ or Space choose · Enter next · Tab/Shift+Tab focus · Esc cancel");
5811
6477
  } else if (focusTarget === "actions") {
5812
- interactionHint = "←/→ choose · Enter/Space activate · Tab/Shift+Tab focus · Esc cancel";
6478
+ interactionHint = t("manualDialog.hint.actions", "←/→ choose · Enter/Space activate · Tab/Shift+Tab focus · Esc cancel");
5813
6479
  }
5814
6480
  const submit = focusTarget === "actions" && actionIndex === 0;
5815
- const submitLabel = submit ? theme.fg("accent", "[Submit]") : theme.fg("text", "[Submit]");
6481
+ const submitLabel = submit ? theme.fg("accent", t("manualDialog.submit", "[Submit]")) : theme.fg("text", t("manualDialog.submit", "[Submit]"));
5816
6482
  const cancel = focusTarget === "actions" && actionIndex === 1;
5817
- const cancelLabel = cancel ? theme.fg("accent", "[Cancel]") : theme.fg("text", "[Cancel]");
6483
+ const cancelLabel = cancel ? theme.fg("accent", t("manualDialog.cancel", "[Cancel]")) : theme.fg("text", t("manualDialog.cancel", "[Cancel]"));
5818
6484
  const actionButtons = `${submitLabel} ${cancelLabel}`;
5819
6485
  const buttonOffset = Math.max(0, Math.floor((contentWidth - visibleWidth2(actionButtons)) / 2) - 2);
5820
6486
  addLine(`${focusMarker("actions")}${" ".repeat(buttonOffset)}${actionButtons}`);
@@ -6482,7 +7148,7 @@ var SCREENED_SKIP_TEXT = "Advisor consultation skipped (screened out): the stake
6482
7148
  var repeatSkipText = (advice) => `Advisor consultation skipped (already answered): this question was answered earlier in this session; the earlier advice is reattached below. Consult again only if the situation has materially changed.
6483
7149
 
6484
7150
  ${advice}`;
6485
- var outageNotifier = createOutageNotifier((category, message) => `Advisor Jev classifier failed (${category}); allowing consultations. ${message}`);
7151
+ var outageNotifier = createOutageNotifier((category, message) => `${t("notify.jevFilterOutage.prefix", "Advisor Jev classifier failed")} (${category}); ${t("notify.jevFilterOutage.allowing", "allowing consultations.")} ${message}`);
6486
7152
  var notifyOutageOnce = outageNotifier.notify;
6487
7153
  var resetJevOutageNotification = outageNotifier.reset;
6488
7154
  var allow = () => ({ decision: "allow" });
@@ -6686,7 +7352,7 @@ ${markdown}`,
6686
7352
  },
6687
7353
  display: true
6688
7354
  }, { deliverAs: "steer", triggerTurn: !isPrintMode });
6689
- notify(ctx, `Advisor consultation failed: ${message}`, "error");
7355
+ notify(ctx, `${t("manualCmd.consultFailed.prefix", "Advisor consultation failed:")} ${message}`, "error");
6690
7356
  notifyHerdrAdvisorFailure("Advisor consultation failed", message);
6691
7357
  } finally {
6692
7358
  finishHerdrActivity();
@@ -6828,7 +7494,7 @@ var registerModelCommands = (runtime) => {
6828
7494
  });
6829
7495
  runtime.pendingExecutorModelRef = undefined;
6830
7496
  runtime.updateSameModelNotice(ctx);
6831
- ctx.ui.notify(`Saved Executor + Advisor configurations to ${path}`, "info");
7497
+ ctx.ui.notify(`${t("notify.modelsSaved.prefix", "Saved Executor + Advisor configurations to")} ${path}`, "info");
6832
7498
  }
6833
7499
  });
6834
7500
  };
@@ -7142,11 +7808,11 @@ var registerOutcomeStatsCommand = (runtime) => {
7142
7808
 
7143
7809
  // src/commands/renderers.ts
7144
7810
  import { getMarkdownTheme as getMarkdownTheme3 } from "@earendil-works/pi-coding-agent";
7145
- import { Box as Box2, Markdown as Markdown3, Text as Text4 } from "@earendil-works/pi-tui";
7811
+ import { Box as Box2, Markdown as Markdown3, Text as Text5 } from "@earendil-works/pi-tui";
7146
7812
 
7147
7813
  // src/commands/manual-progress.ts
7148
7814
  import { getMarkdownTheme as getMarkdownTheme2 } from "@earendil-works/pi-coding-agent";
7149
- import { Markdown as Markdown2, Text as Text3 } from "@earendil-works/pi-tui";
7815
+ import { Markdown as Markdown2, Text as Text4 } from "@earendil-works/pi-tui";
7150
7816
  class ManualAdvisorProgressComponent {
7151
7817
  question;
7152
7818
  state;
@@ -7173,17 +7839,17 @@ class ManualAdvisorProgressComponent {
7173
7839
  return box.render(width);
7174
7840
  }
7175
7841
  if (this.state.phase === "error") {
7176
- box.addChild(new Text3(this.theme.fg("error", this.theme.bold("◆ ADVISOR · FAILED")), 0, 0));
7842
+ box.addChild(new Text4(this.theme.fg("error", this.theme.bold("◆ ADVISOR · FAILED")), 0, 0));
7177
7843
  return box.render(width);
7178
7844
  }
7179
7845
  const frame = SPINNER_FRAMES[Math.floor(Date.now() / 80) % SPINNER_FRAMES.length];
7180
- let status = "Working…";
7846
+ let status = t("manualProgress.working", "Working…");
7181
7847
  if (this.state.phase === "preparing") {
7182
- status = "Preparing…";
7848
+ status = t("manualProgress.preparing", "Preparing…");
7183
7849
  } else if (this.state.text?.trim()) {
7184
- status = "Responding…";
7850
+ status = t("manualProgress.responding", "Responding…");
7185
7851
  }
7186
- box.addChild(new Text3(`${this.theme.fg("warning", this.theme.bold(`◆ ADVISOR ${frame}`))} ${this.theme.fg("dim", `· ${status}`)}`, 0, 0));
7852
+ box.addChild(new Text4(`${this.theme.fg("warning", this.theme.bold(`◆ ADVISOR ${frame}`))} ${this.theme.fg("dim", `· ${status}`)}`, 0, 0));
7187
7853
  if (this.state.thinking?.trim()) {
7188
7854
  box.addChild(renderThinkingMarkdown(this.state.thinking.slice(-200), this.theme));
7189
7855
  }
@@ -7214,14 +7880,14 @@ var manualResultRenderer = (message, { expanded }, theme) => {
7214
7880
  const { details } = message;
7215
7881
  const box = new Box2(1, 1, (text) => theme.bg("customMessageBg", text));
7216
7882
  const advice = details?.text ?? (isString(message.content) ? message.content : "(Advisor returned no advice.)");
7217
- box.addChild(new Text4(renderAdvisorResponseHeader(hasSoundVerdict(advice), theme), 0, 0));
7883
+ box.addChild(new Text5(renderAdvisorResponseHeader(hasSoundVerdict(advice), theme), 0, 0));
7218
7884
  if (details?.advisor) {
7219
- box.addChild(new Text4(theme.fg("dim", ` ${details.advisor}`), 0, 0));
7885
+ box.addChild(new Text5(theme.fg("dim", ` ${details.advisor}`), 0, 0));
7220
7886
  }
7221
7887
  if (getAdvisorSettings().showUsageDetails) {
7222
7888
  const usage = formatAdvisorUsage(details?.usage);
7223
7889
  if (usage) {
7224
- box.addChild(new Text4(theme.fg("dim", ` Usage: ${usage}`), 0, 0));
7890
+ box.addChild(new Text5(theme.fg("dim", ` Usage: ${usage}`), 0, 0));
7225
7891
  }
7226
7892
  }
7227
7893
  const attachments = [
@@ -7229,14 +7895,14 @@ var manualResultRenderer = (message, { expanded }, theme) => {
7229
7895
  details?.preferenceBytes ? `Project preferences attached · ${formatByteSize(details.preferenceBytes)}` : undefined
7230
7896
  ].filter((value) => value !== undefined);
7231
7897
  if (attachments.length) {
7232
- box.addChild(new Text4(theme.fg("dim", ` ${attachments.join(" · ")}`), 0, 0));
7898
+ box.addChild(new Text5(theme.fg("dim", ` ${attachments.join(" · ")}`), 0, 0));
7233
7899
  }
7234
7900
  box.addChild(new Markdown3(adviceForDisplay(advice, expanded), 0, 0, getMarkdownTheme3()));
7235
7901
  return box;
7236
7902
  };
7237
7903
  var outcomeStatsRenderer = (message, _options, theme) => {
7238
7904
  const box = new Box2(1, 1, (text) => theme.bg("customMessageBg", text));
7239
- box.addChild(new Text4(theme.fg("accent", theme.bold("◆ ADVISOR · OUTCOME STATS")), 0, 0));
7905
+ box.addChild(new Text5(theme.fg("accent", theme.bold("◆ ADVISOR · OUTCOME STATS")), 0, 0));
7240
7906
  box.addChild(new Markdown3(formatAdvisorStats(message.details ?? { malformedLines: 0 }), 0, 0, getMarkdownTheme3()));
7241
7907
  return box;
7242
7908
  };
@@ -7312,8 +7978,8 @@ var contextDescription = (presets, contextMaxChars) => {
7312
7978
  const markerColumn = meterPrefix.length + marker;
7313
7979
  const labelStart = Math.max(0, Math.min(meterPrefix.length + meter.length + 2 - labelWidth, markerColumn - Math.floor((labelWidth - 1) / 2)));
7314
7980
  const markerLabel = `${" ".repeat(labelStart)}${label}`;
7315
- const description = exactIndex === -1 ? "Custom context limit." : selectedPreset?.description;
7316
- return `${description ?? "Custom context limit."}
7981
+ const description = exactIndex === -1 ? t("settings.context.customLimit", "Custom context limit.") : selectedPreset?.description;
7982
+ return `${description ?? t("settings.context.customLimit", "Custom context limit.")}
7317
7983
  ${meterPrefix}${meter} full
7318
7984
  ${markerLabel}`;
7319
7985
  };
@@ -7338,6 +8004,16 @@ var rainbowGradient = (text, startedAt) => {
7338
8004
  };
7339
8005
 
7340
8006
  // src/ui/settings-items.ts
8007
+ import { getKeybindings as getKeybindings2 } from "@earendil-works/pi-tui";
8008
+
8009
+ // src/ui/model-multi-selector.ts
8010
+ class SearchableModelMultiSelector extends ModelSelectorAdapter {
8011
+ constructor(options) {
8012
+ super(new SearchableModelList(options));
8013
+ }
8014
+ }
8015
+
8016
+ // src/ui/settings-items-jev.ts
7341
8017
  import { getKeybindings } from "@earendil-works/pi-tui";
7342
8018
 
7343
8019
  // src/ui/jev-classifier-submenu.ts
@@ -7419,12 +8095,12 @@ class JevClassifierSubmenu {
7419
8095
  if (this.mode === "key") {
7420
8096
  return [
7421
8097
  border,
7422
- theme.fg("accent", theme.bold("Jev API Key")),
8098
+ theme.fg("accent", theme.bold(t("jevSubmenu.apiKeyTitle", "Jev API Key"))),
7423
8099
  "",
7424
- this.notice ?? "Enter a new TypeSafe Jev API key:",
8100
+ this.notice ?? t("jevSubmenu.enterNewKey", "Enter a new TypeSafe Jev API key:"),
7425
8101
  ` ${this.keyInput?.render(Math.max(1, width - 4))[0] ?? ""}`,
7426
8102
  "",
7427
- this.failClosedKeyMode ? "Key restore failed. Re-enter and verify a valid Jev key." : "Enter to verify · Esc to cancel",
8103
+ this.failClosedKeyMode ? t("jevSubmenu.keyRestoreFailed", "Key restore failed. Re-enter and verify a valid Jev key.") : t("jevSubmenu.keyEntryHint", "Enter to verify · Esc to cancel"),
7428
8104
  border
7429
8105
  ];
7430
8106
  }
@@ -7434,13 +8110,13 @@ class JevClassifierSubmenu {
7434
8110
  const rows = this.filtered.map((choice, index) => `${index === this.selectedIndex ? "›" : " "} ${choice.label}`);
7435
8111
  return [
7436
8112
  border,
7437
- theme.fg("accent", theme.bold("Jev classifier")),
8113
+ theme.fg("accent", theme.bold(t("jevSubmenu.classifierTitle", "Jev classifier"))),
7438
8114
  "",
7439
- this.mode === "loading" ? "Loading Pi classifier catalog…" : `Search: ${this.search.render(Math.max(1, width - 10))[0]}`,
8115
+ this.mode === "loading" ? t("jevSubmenu.loading", "Loading Pi classifier catalog…") : `${t("jevSubmenu.searchLabel", "Search:")} ${this.search.render(Math.max(1, width - 10))[0]}`,
7440
8116
  ...this.notice ? [this.notice] : [],
7441
8117
  ...rows.slice(0, 10),
7442
8118
  "",
7443
- "↑/↓ move · Enter select · Esc cancel",
8119
+ t("jevSubmenu.listHint", "↑/↓ move · Enter select · Esc cancel"),
7444
8120
  border
7445
8121
  ];
7446
8122
  }
@@ -7476,7 +8152,7 @@ class JevClassifierSubmenu {
7476
8152
  async loadChoices() {
7477
8153
  try {
7478
8154
  if (!this.options.modelRegistry) {
7479
- throw new Error("Pi classifier registry is unavailable.");
8155
+ throw new Error(t("jevSubmenu.registryUnavailable", "Pi classifier registry is unavailable."));
7480
8156
  }
7481
8157
  const models = await this.options.modelRegistry.getAvailableOfType("classifier");
7482
8158
  this.choices = (models ?? []).map((model) => ({
@@ -7489,27 +8165,27 @@ class JevClassifierSubmenu {
7489
8165
  if (stored.key) {
7490
8166
  this.choices.push({
7491
8167
  action: "use-key",
7492
- label: "Jev API Key (use stored key)",
8168
+ label: t("jevSubmenu.useStoredKey", "Jev API Key (use stored key)"),
7493
8169
  ref: JEV_API_KEY_CLASSIFIER
7494
8170
  }, {
7495
8171
  action: "replace-key",
7496
- label: "Replace Jev API Key…",
8172
+ label: t("jevSubmenu.replaceKey", "Replace Jev API Key…"),
7497
8173
  ref: JEV_API_KEY_CLASSIFIER
7498
8174
  });
7499
8175
  } else {
7500
8176
  this.choices.push({
7501
8177
  action: "replace-key",
7502
- label: "Jev API Key… (enter TypeSafe key)",
8178
+ label: t("jevSubmenu.enterKeyChoice", "Jev API Key… (enter TypeSafe key)"),
7503
8179
  ref: JEV_API_KEY_CLASSIFIER
7504
8180
  });
7505
8181
  }
7506
8182
  this.mode = "list";
7507
8183
  this.loaded.resolve(true);
7508
- this.notice = this.options.currentValue && this.options.currentValue !== "Choose classifier" ? `Current: ${this.options.currentValue}` : undefined;
8184
+ this.notice = this.options.currentValue && this.options.currentValue !== "Choose classifier" ? `${t("jevSubmenu.currentPrefix", "Current:")} ${this.options.currentValue}` : undefined;
7509
8185
  } catch (error) {
7510
8186
  this.mode = "list";
7511
8187
  this.loaded.resolve(false);
7512
- this.notice = `Could not load classifiers: ${error instanceof Error ? error.message : "unknown error"}. Retry /advisor-settings.`;
8188
+ this.notice = `${t("jevSubmenu.loadFailedPrefix", "Could not load classifiers:")} ${error instanceof Error ? error.message : t("jevSetup.unknownError", "unknown error")}${t("jevSubmenu.loadFailedSuffix", ". Retry /advisor-settings.")}`;
7513
8189
  }
7514
8190
  this.options.tui.requestRender();
7515
8191
  }
@@ -7518,7 +8194,7 @@ class JevClassifierSubmenu {
7518
8194
  }
7519
8195
  static rates(model) {
7520
8196
  const rates = model.cost;
7521
- return rates.input === 0 && rates.output === 0 ? "$0/M tokens" : `$${rates.input}/$${rates.output} per Mtok`;
8197
+ return rates.input === 0 && rates.output === 0 ? t("jevSubmenu.ratesFree", "$0/M tokens") : `$${rates.input}/$${rates.output} ${t("jevSubmenu.perMtok", "per Mtok")}`;
7522
8198
  }
7523
8199
  async choose(choice) {
7524
8200
  if (choice.action === "use-key") {
@@ -7538,24 +8214,24 @@ class JevClassifierSubmenu {
7538
8214
  return;
7539
8215
  }
7540
8216
  this.mode = "verifying";
7541
- this.notice = `Verifying ${choice.ref}…`;
8217
+ this.notice = `${t("jevSubmenu.verifying", "Verifying")} ${choice.ref}…`;
7542
8218
  this.options.tui.requestRender();
7543
8219
  try {
7544
8220
  await this.verify(choice.model);
7545
8221
  const saved = this.save({ classifier: choice.ref, transport: "auto" });
7546
8222
  if (!saved) {
7547
8223
  this.mode = "list";
7548
- this.notice = "Verified, but settings could not be saved.";
8224
+ this.notice = t("jevSubmenu.verifiedNotSaved", "Verified, but settings could not be saved.");
7549
8225
  }
7550
8226
  } catch (error) {
7551
- this.notice = `Verification failed for ${choice.ref}: ${error instanceof Error ? error.message : "provider error"}`;
8227
+ this.notice = `${t("jevSubmenu.verifyFailedFor", "Verification failed for")} ${choice.ref}: ${error instanceof Error ? error.message : t("jevSubmenu.providerError", "provider error")}`;
7552
8228
  this.mode = "list";
7553
8229
  }
7554
8230
  this.options.tui.requestRender();
7555
8231
  }
7556
8232
  async verify(model, apiKey) {
7557
8233
  if (!this.options.modelRegistry) {
7558
- throw new Error("Pi classifier registry is unavailable.");
8234
+ throw new Error(t("jevSubmenu.registryUnavailable", "Pi classifier registry is unavailable."));
7559
8235
  }
7560
8236
  const state = {
7561
8237
  recent_conversation: "Classifier verification check.",
@@ -7563,32 +8239,32 @@ class JevClassifierSubmenu {
7563
8239
  };
7564
8240
  const result = await classifyWithJev({ modelRegistry: this.options.modelRegistry, signal: undefined }, `${model.provider}/${model.id}`, state, nativeScreeningQuestions, { apiKey });
7565
8241
  if (!result.answers.self_answerable || !result.answers.stakes) {
7566
- throw new Error("Classifier returned an incomplete verification result.");
8242
+ throw new Error(t("jevSubmenu.incompleteResult", "Classifier returned an incomplete verification result."));
7567
8243
  }
7568
8244
  }
7569
8245
  async verifyKey() {
7570
8246
  const candidate = this.keyInput?.getValue().trim() ?? "";
7571
8247
  this.keyInput?.setValue("");
7572
8248
  if (!candidate) {
7573
- this.notice = "Enter a non-empty Jev API key.";
8249
+ this.notice = t("jevSubmenu.emptyKey", "Enter a non-empty Jev API key.");
7574
8250
  this.options.tui.requestRender();
7575
8251
  return;
7576
8252
  }
7577
8253
  const model = this.options.modelRegistry?.findOfType("classifier", "typesafe", "jev-latest");
7578
8254
  if (!model) {
7579
- this.notice = "TypeSafe Jev classifier is not present in Pi's catalog.";
8255
+ this.notice = t("jevSubmenu.classifierMissing", "TypeSafe Jev classifier is not present in Pi's catalog.");
7580
8256
  this.options.tui.requestRender();
7581
8257
  return;
7582
8258
  }
7583
8259
  const previous = await (this.options.resolveStoredKey ?? readJevClassifierKey)();
7584
8260
  if (previous.failed) {
7585
8261
  this.mode = "list";
7586
- this.notice = "Could not read the stored Jev API Key state; nothing was changed. Try again later.";
8262
+ this.notice = t("jevSubmenu.keyStateUnreadable", "Could not read the stored Jev API Key state; nothing was changed. Try again later.");
7587
8263
  this.options.tui.requestRender();
7588
8264
  return;
7589
8265
  }
7590
8266
  this.mode = "verifying";
7591
- this.notice = "Verifying Jev API Key…";
8267
+ this.notice = t("jevSubmenu.verifyingKey", "Verifying Jev API Key…");
7592
8268
  this.options.tui.requestRender();
7593
8269
  try {
7594
8270
  await this.verify(model, candidate);
@@ -7601,15 +8277,15 @@ class JevClassifierSubmenu {
7601
8277
  if (!await this.restorePreviousKey(previous)) {
7602
8278
  this.failClosedKeyMode = true;
7603
8279
  disableJevClassifierKeyForRuntime();
7604
- throw new Error("Settings save failed and the previous key could not be restored. Re-enter and verify a valid Jev key before continuing.");
8280
+ throw new Error(t("jevSubmenu.saveFailedNoRestore", "Settings save failed and the previous key could not be restored. Re-enter and verify a valid Jev key before continuing."));
7605
8281
  }
7606
- throw new Error("Could not save Jev classifier settings; existing key was restored.");
8282
+ throw new Error(t("jevSubmenu.saveFailedRestored", "Could not save Jev classifier settings; existing key was restored."));
7607
8283
  }
7608
8284
  this.mode = "list";
7609
- this.notice = "Jev API Key verified and saved securely.";
8285
+ this.notice = t("jevSubmenu.keyVerifiedSaved", "Jev API Key verified and saved securely.");
7610
8286
  } catch (error) {
7611
8287
  this.mode = "key";
7612
- this.notice = `Verification failed: ${error instanceof Error ? error.message : "provider error"}`;
8288
+ this.notice = `${t("jevSubmenu.verificationFailedPrefix", "Verification failed:")} ${error instanceof Error ? error.message : t("jevSubmenu.providerError", "provider error")}`;
7613
8289
  }
7614
8290
  this.options.tui.requestRender();
7615
8291
  }
@@ -7622,7 +8298,7 @@ class JevClassifierSubmenu {
7622
8298
  this.options.tui.requestRender();
7623
8299
  },
7624
8300
  onSubmit: () => this.handleKeySubmit(),
7625
- placeholder: "TypeSafe Jev API key"
8301
+ placeholder: t("jevSubmenu.keyPlaceholder", "TypeSafe Jev API key")
7626
8302
  });
7627
8303
  }
7628
8304
  restorePreviousKey(previous) {
@@ -7634,22 +8310,22 @@ class JevClassifierSubmenu {
7634
8310
  async verifyStoredKey(key) {
7635
8311
  const model = this.options.modelRegistry?.findOfType("classifier", "typesafe", "jev-latest");
7636
8312
  if (!model) {
7637
- this.notice = "TypeSafe Jev classifier is not present in Pi's catalog.";
8313
+ this.notice = t("jevSubmenu.classifierMissing", "TypeSafe Jev classifier is not present in Pi's catalog.");
7638
8314
  this.options.tui.requestRender();
7639
8315
  return;
7640
8316
  }
7641
8317
  this.mode = "verifying";
7642
- this.notice = "Verifying stored Jev API Key…";
8318
+ this.notice = t("jevSubmenu.verifyingStoredKey", "Verifying stored Jev API Key…");
7643
8319
  this.options.tui.requestRender();
7644
8320
  try {
7645
8321
  await this.verify(model, key);
7646
8322
  if (!this.save({ classifier: JEV_API_KEY_CLASSIFIER, transport: "auto" })) {
7647
- throw new Error("Could not save the Jev classifier selection.");
8323
+ throw new Error(t("jevSubmenu.selectionNotSaved", "Could not save the Jev classifier selection."));
7648
8324
  }
7649
- this.notice = "Stored Jev API Key verified.";
8325
+ this.notice = t("jevSubmenu.storedKeyVerified", "Stored Jev API Key verified.");
7650
8326
  } catch (error) {
7651
8327
  this.mode = "list";
7652
- this.notice = `Verification failed: ${error instanceof Error ? error.message : "provider error"}`;
8328
+ this.notice = `${t("jevSubmenu.verificationFailedPrefix", "Verification failed:")} ${error instanceof Error ? error.message : t("jevSubmenu.providerError", "provider error")}`;
7653
8329
  }
7654
8330
  this.options.tui.requestRender();
7655
8331
  }
@@ -7657,7 +8333,7 @@ class JevClassifierSubmenu {
7657
8333
  try {
7658
8334
  await this.verifyKey();
7659
8335
  } catch (error) {
7660
- this.notice = `Verification failed: ${error instanceof Error ? error.message : "provider error"}`;
8336
+ this.notice = `${t("jevSubmenu.verificationFailedPrefix", "Verification failed:")} ${error instanceof Error ? error.message : t("jevSubmenu.providerError", "provider error")}`;
7661
8337
  this.mode = "key";
7662
8338
  this.options.tui.requestRender();
7663
8339
  }
@@ -7668,7 +8344,7 @@ class JevClassifierSubmenu {
7668
8344
  this.options.done(selection.classifier);
7669
8345
  } else {
7670
8346
  this.mode = "list";
7671
- this.notice = "Verified, but settings could not be saved.";
8347
+ this.notice = t("jevSubmenu.verifiedNotSaved", "Verified, but settings could not be saved.");
7672
8348
  }
7673
8349
  return saved;
7674
8350
  }
@@ -7679,9 +8355,9 @@ import { Key as Key3, matchesKey as matchesKey3, truncateToWidth as truncateToWi
7679
8355
  var actionsFor = (enabled) => enabled ? ["disable", "done"] : ["enable", "done"];
7680
8356
  var labelFor2 = (action) => {
7681
8357
  if (action === "enable") {
7682
- return "Enable the filter";
8358
+ return t("jevSubmenu.filter.enable", "Enable the filter");
7683
8359
  }
7684
- return action === "disable" ? "Disable the filter" : "Done";
8360
+ return action === "disable" ? t("jevSubmenu.filter.disable", "Disable the filter") : t("jevSubmenu.filter.done", "Done");
7685
8361
  };
7686
8362
 
7687
8363
  class JevFilterSubmenu {
@@ -7711,13 +8387,13 @@ class JevFilterSubmenu {
7711
8387
  render(width) {
7712
8388
  const { theme } = this.options;
7713
8389
  const lines = [
7714
- theme.fg("accent", theme.bold(" Jev classifier consultation filter")),
8390
+ theme.fg("accent", theme.bold(` ${t("jevSubmenu.filter.title", "Jev classifier consultation filter")}`)),
7715
8391
  "",
7716
- ` Filter: ${this.enabled ? "On" : "Off"}`,
7717
- ` Classifier: ${this.options.currentClassifier ?? "not selected"}`
8392
+ ` ${t("jevSubmenu.filter.filterLabel", "Filter:")} ${this.enabled ? "On" : "Off"}`,
8393
+ ` ${t("jevSubmenu.filter.classifierLabel", "Classifier:")} ${this.options.currentClassifier ?? t("jevSubmenu.filter.notSelected", "not selected")}`
7718
8394
  ];
7719
8395
  if (this.mode === "resolving") {
7720
- lines.push("", " Checking selected classifier availability…");
8396
+ lines.push("", ` ${t("jevSubmenu.filter.checking", "Checking selected classifier availability…")}`);
7721
8397
  } else if (this.notice) {
7722
8398
  lines.push("", theme.fg("warning", ` ${this.notice}`));
7723
8399
  }
@@ -7752,9 +8428,9 @@ class JevFilterSubmenu {
7752
8428
  const stored = await (this.resolveClassifierKey ?? readJevClassifierKey)();
7753
8429
  this.classifierAvailable = Boolean(stored.key);
7754
8430
  if (stored.failed) {
7755
- this.notice = "Could not read the stored Jev API Key state; try again later.";
8431
+ this.notice = t("jevSubmenu.filter.keyStateUnreadable", "Could not read the stored Jev API Key state; try again later.");
7756
8432
  } else if (!this.classifierAvailable) {
7757
- this.notice = "No Jev API Key is stored. Choose Jev API Key in Jev classifier settings.";
8433
+ this.notice = t("jevSubmenu.filter.noStoredKey", "No Jev API Key is stored. Choose Jev API Key in Jev classifier settings.");
7758
8434
  }
7759
8435
  } else {
7760
8436
  const parsed = selected ? parseJevClassifierRef(selected) : undefined;
@@ -7764,11 +8440,11 @@ class JevFilterSubmenu {
7764
8440
  this.classifierAvailable = available.some((model) => model.id === parsed.modelId);
7765
8441
  }
7766
8442
  if (!this.classifierAvailable) {
7767
- this.notice = "Select an available authenticated classifier in Jev classifier settings first.";
8443
+ this.notice = t("jevSubmenu.filter.selectClassifierFirst", "Select an available authenticated classifier in Jev classifier settings first.");
7768
8444
  }
7769
8445
  }
7770
8446
  } catch (error) {
7771
- this.notice = `Classifier lookup failed: ${error instanceof Error ? error.message : "Pi error"}`;
8447
+ this.notice = `${t("jevSubmenu.filter.lookupFailedPrefix", "Classifier lookup failed:")} ${error instanceof Error ? error.message : t("jevSubmenu.filter.piError", "Pi error")}`;
7772
8448
  }
7773
8449
  this.mode = "menu";
7774
8450
  this.options.tui.requestRender();
@@ -7784,7 +8460,7 @@ class JevFilterSubmenu {
7784
8460
  return;
7785
8461
  }
7786
8462
  if (this.options.onSelection?.({ enabled }) === false) {
7787
- this.notice = "The filter state could not be saved.";
8463
+ this.notice = t("jevSubmenu.filter.stateNotSaved", "The filter state could not be saved.");
7788
8464
  this.options.tui.requestRender();
7789
8465
  return;
7790
8466
  }
@@ -7794,16 +8470,112 @@ class JevFilterSubmenu {
7794
8470
  }
7795
8471
  }
7796
8472
 
7797
- // src/ui/model-multi-selector.ts
7798
- class SearchableModelMultiSelector extends ModelSelectorAdapter {
7799
- constructor(options) {
7800
- super(new SearchableModelList(options));
8473
+ // src/ui/settings-items-jev.ts
8474
+ var jevFilterRowValue = (settings) => {
8475
+ if (!settings.jevFilterEnabled) {
8476
+ return "Off";
7801
8477
  }
7802
- }
8478
+ return settings.jevClassifier ? "On" : t("settings.jevFilter.onUnavailable", "On (unavailable: no classifier)");
8479
+ };
8480
+ var jevItems = (settings, theme, tui, {
8481
+ jevClassifierRegistry,
8482
+ jevKeyDeps,
8483
+ onJevFilter,
8484
+ onJevProvider
8485
+ }) => [
8486
+ {
8487
+ currentValue: settings.jevClassifier ?? t("settings.jevProvider.choose", "Choose classifier"),
8488
+ description: t("settings.jevProvider.desc", "Select a Pi-authenticated classifier or explicitly configure the separate Jev API Key option."),
8489
+ id: "jevProvider",
8490
+ label: t("settings.jevProvider.label", "Jev classifier"),
8491
+ submenu: (currentValue, done) => new JevClassifierSubmenu({
8492
+ currentValue,
8493
+ done,
8494
+ keybindings: getKeybindings(),
8495
+ modelRegistry: jevClassifierRegistry,
8496
+ onSelection: onJevProvider,
8497
+ persistKey: jevKeyDeps?.persistClassifierKey,
8498
+ resolveStoredKey: jevKeyDeps?.resolveClassifierKey,
8499
+ restoreKey: jevKeyDeps?.restoreClassifierKey,
8500
+ theme,
8501
+ tui
8502
+ })
8503
+ },
8504
+ {
8505
+ currentValue: jevFilterRowValue(settings),
8506
+ description: t("settings.jevFilter.desc", "Screen low-stakes ask_advisor consultations with the selected Jev provider."),
8507
+ id: "jevFilter",
8508
+ label: t("settings.jevFilter.label", "Jev/Decisions consultation filter"),
8509
+ submenu: (currentValue, done) => new JevFilterSubmenu({
8510
+ currentClassifier: settings.jevClassifier,
8511
+ currentValue,
8512
+ done,
8513
+ modelRegistry: jevClassifierRegistry,
8514
+ onSelection: onJevFilter,
8515
+ resolveClassifierKey: jevKeyDeps?.resolveClassifierKey,
8516
+ theme,
8517
+ tui
8518
+ })
8519
+ },
8520
+ {
8521
+ currentValue: String(settings.jevFilterSkipConfidence ?? DEFAULT_JEV_FILTER_SKIP_CONFIDENCE),
8522
+ description: t("settings.jevFilterSkipConfidence.desc", "Required probability on negligible stakes before a consultation is skipped."),
8523
+ id: "jevFilterSkipConfidence",
8524
+ label: t("settings.jevFilterSkipConfidence.label", "Jev skip confidence"),
8525
+ values: numericValues(settings.jevFilterSkipConfidence ?? DEFAULT_JEV_FILTER_SKIP_CONFIDENCE, [0.6, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95])
8526
+ },
8527
+ {
8528
+ currentValue: String(settings.jevFilterNoulMargin ?? DEFAULT_JEV_FILTER_NOUL_MARGIN),
8529
+ description: t("settings.jevFilterNoulMargin.desc", "Extra margin over a coin flip required on self-answerability before skipping."),
8530
+ id: "jevFilterNoulMargin",
8531
+ label: t("settings.jevFilterNoulMargin.label", "Jev Noul margin"),
8532
+ values: numericValues(settings.jevFilterNoulMargin ?? DEFAULT_JEV_FILTER_NOUL_MARGIN, [0.1, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45])
8533
+ },
8534
+ {
8535
+ currentValue: `${settings.jevFilterOverrideWindow ?? DEFAULT_JEV_FILTER_OVERRIDE_WINDOW} ${t("settings.jev.turnsUnit", "turns")}`,
8536
+ description: t("settings.jevFilterOverrideWindow.desc", "Turns after a skip during which the same question passes automatically."),
8537
+ id: "jevFilterOverrideWindow",
8538
+ label: t("settings.jevFilterOverrideWindow.label", "Jev override window"),
8539
+ values: numericValues(settings.jevFilterOverrideWindow ?? DEFAULT_JEV_FILTER_OVERRIDE_WINDOW, [0, 3, 5, 10, 20, 50]).map((value) => `${value} ${t("settings.jev.turnsUnit", "turns")}`)
8540
+ },
8541
+ {
8542
+ currentValue: String(settings.jevTimeoutMs ?? DEFAULT_JEV_TIMEOUT_MS),
8543
+ description: t("settings.jevTimeoutMs.desc", "Total wall-time budget for one Jev call, including retries."),
8544
+ id: "jevTimeoutMs",
8545
+ label: t("settings.jevTimeoutMs.label", "Jev timeout ms"),
8546
+ values: numericValues(settings.jevTimeoutMs ?? DEFAULT_JEV_TIMEOUT_MS, [1000, 2000, 5000, 8000, 15000, 30000])
8547
+ },
8548
+ {
8549
+ currentValue: String(settings.jevDigestMaxChars ?? DEFAULT_JEV_DIGEST_MAX_CHARS),
8550
+ description: t("settings.jevDigestMaxChars.desc", "Conversation characters sent to Jev as screening evidence."),
8551
+ id: "jevDigestMaxChars",
8552
+ label: t("settings.jevDigestMaxChars.label", "Jev digest chars"),
8553
+ values: numericValues(settings.jevDigestMaxChars ?? DEFAULT_JEV_DIGEST_MAX_CHARS, [0, 1000, 2000, 4000, 8000, 15000])
8554
+ },
8555
+ {
8556
+ currentValue: settings.jevTurnGateEveryTurns === 0 || settings.jevTurnGateEveryTurns === undefined ? "Off" : `every ${settings.jevTurnGateEveryTurns} turns`,
8557
+ description: t("settings.jevTurnGateEveryTurns.desc", "Proactively consult the Advisor every N turns without a consultation (0 = off)."),
8558
+ id: "jevTurnGateEveryTurns",
8559
+ label: t("settings.jevTurnGateEveryTurns.label", "Jev/Decisions turn gate"),
8560
+ values: [
8561
+ "Off",
8562
+ "every 3 turns",
8563
+ "every 5 turns",
8564
+ "every 10 turns",
8565
+ "every 20 turns"
8566
+ ]
8567
+ },
8568
+ {
8569
+ currentValue: String(settings.jevTurnGateNoulThreshold ?? DEFAULT_JEV_TURN_GATE_NOUL_THRESHOLD),
8570
+ description: t("settings.jevTurnGateNoulThreshold.desc", "Jev confidence required before the turn gate interrupts with advice."),
8571
+ id: "jevTurnGateNoulThreshold",
8572
+ label: t("settings.jevTurnGateNoulThreshold.label", "Jev/Decisions turn-gate threshold"),
8573
+ values: numericValues(settings.jevTurnGateNoulThreshold ?? DEFAULT_JEV_TURN_GATE_NOUL_THRESHOLD, [0.6, 0.7, 0.8, 0.85, 0.9, 0.95])
8574
+ }
8575
+ ];
7803
8576
 
7804
8577
  // src/ui/text-setting-submenu.ts
7805
8578
  import { Input as Input4, truncateToWidth as truncateToWidth6 } from "@earendil-works/pi-tui";
7806
-
7807
8579
  class TextSettingSubmenu {
7808
8580
  input = new Input4;
7809
8581
  options;
@@ -7848,7 +8620,7 @@ class TextSettingSubmenu {
7848
8620
  if (this.error) {
7849
8621
  lines.push(theme.fg("error", ` ${this.error}`));
7850
8622
  }
7851
- lines.push("", theme.fg("dim", " Enter: apply · Esc: cancel"));
8623
+ lines.push("", theme.fg("dim", ` ${t("textSetting.hint", "Enter: apply · Esc: cancel")}`));
7852
8624
  return lines.map((line) => truncateToWidth6(line, width));
7853
8625
  }
7854
8626
  handleInput(keyData) {
@@ -7872,144 +8644,47 @@ var scoutTimeoutItem = (settings) => {
7872
8644
  const timeoutMs = settings.scoutTimeoutMs ?? DEFAULT_SCOUT_TIMEOUT_MS;
7873
8645
  return {
7874
8646
  currentValue: String(timeoutMs),
7875
- description: "Maximum time for Scout's response stream; model and auth resolution happen before this timeout starts.",
8647
+ description: t("settings.scoutTimeoutMs.desc", "Maximum time for Scout's response stream; model and auth resolution happen before this timeout starts."),
7876
8648
  id: "scoutTimeoutMs",
7877
- label: "Scout timeout ms",
8649
+ label: t("settings.scoutTimeoutMs.label", "Scout timeout ms"),
7878
8650
  values: numericValues(timeoutMs, [5000, 1e4, 15000, 30000, 45000, 60000, 90000, 120000])
7879
8651
  };
7880
8652
  };
7881
- var jevFilterRowValue = (settings) => {
7882
- if (!settings.jevFilterEnabled) {
7883
- return "Off";
7884
- }
7885
- return settings.jevClassifier ? "On" : "On (unavailable: no classifier)";
7886
- };
7887
- var jevItems = (settings, theme, tui, jevClassifierRegistry, jevKeyDeps, onJevFilter, onJevProvider) => [
7888
- {
7889
- currentValue: settings.jevClassifier ?? "Choose classifier",
7890
- description: "Select a Pi-authenticated classifier or explicitly configure the separate Jev API Key option.",
7891
- id: "jevProvider",
7892
- label: "Jev classifier",
7893
- submenu: (currentValue, done) => new JevClassifierSubmenu({
7894
- currentValue,
7895
- done,
7896
- keybindings: getKeybindings(),
7897
- modelRegistry: jevClassifierRegistry,
7898
- onSelection: onJevProvider,
7899
- persistKey: jevKeyDeps?.persistClassifierKey,
7900
- resolveStoredKey: jevKeyDeps?.resolveClassifierKey,
7901
- restoreKey: jevKeyDeps?.restoreClassifierKey,
7902
- theme,
7903
- tui
7904
- })
7905
- },
7906
- {
7907
- currentValue: jevFilterRowValue(settings),
7908
- description: "Screen low-stakes ask_advisor consultations with the selected Jev provider.",
7909
- id: "jevFilter",
7910
- label: "Jev/Decisions consultation filter",
7911
- submenu: (currentValue, done) => new JevFilterSubmenu({
7912
- currentClassifier: settings.jevClassifier,
7913
- currentValue,
7914
- done,
7915
- modelRegistry: jevClassifierRegistry,
7916
- onSelection: onJevFilter,
7917
- resolveClassifierKey: jevKeyDeps?.resolveClassifierKey,
7918
- theme,
7919
- tui
7920
- })
7921
- },
7922
- {
7923
- currentValue: String(settings.jevFilterSkipConfidence ?? DEFAULT_JEV_FILTER_SKIP_CONFIDENCE),
7924
- description: "Required probability on negligible stakes before a consultation is skipped.",
7925
- id: "jevFilterSkipConfidence",
7926
- label: "Jev skip confidence",
7927
- values: numericValues(settings.jevFilterSkipConfidence ?? DEFAULT_JEV_FILTER_SKIP_CONFIDENCE, [0.6, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95])
7928
- },
7929
- {
7930
- currentValue: String(settings.jevFilterNoulMargin ?? DEFAULT_JEV_FILTER_NOUL_MARGIN),
7931
- description: "Extra margin over a coin flip required on self-answerability before skipping.",
7932
- id: "jevFilterNoulMargin",
7933
- label: "Jev Noul margin",
7934
- values: numericValues(settings.jevFilterNoulMargin ?? DEFAULT_JEV_FILTER_NOUL_MARGIN, [0.1, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45])
7935
- },
7936
- {
7937
- currentValue: `${settings.jevFilterOverrideWindow ?? DEFAULT_JEV_FILTER_OVERRIDE_WINDOW} turns`,
7938
- description: "Turns after a skip during which the same question passes automatically.",
7939
- id: "jevFilterOverrideWindow",
7940
- label: "Jev override window",
7941
- values: numericValues(settings.jevFilterOverrideWindow ?? DEFAULT_JEV_FILTER_OVERRIDE_WINDOW, [0, 3, 5, 10, 20, 50]).map((value) => `${value} turns`)
7942
- },
7943
- {
7944
- currentValue: String(settings.jevTimeoutMs ?? DEFAULT_JEV_TIMEOUT_MS),
7945
- description: "Total wall-time budget for one Jev call, including retries.",
7946
- id: "jevTimeoutMs",
7947
- label: "Jev timeout ms",
7948
- values: numericValues(settings.jevTimeoutMs ?? DEFAULT_JEV_TIMEOUT_MS, [1000, 2000, 5000, 8000, 15000, 30000])
7949
- },
7950
- {
7951
- currentValue: String(settings.jevDigestMaxChars ?? DEFAULT_JEV_DIGEST_MAX_CHARS),
7952
- description: "Conversation characters sent to Jev as screening evidence.",
7953
- id: "jevDigestMaxChars",
7954
- label: "Jev digest chars",
7955
- values: numericValues(settings.jevDigestMaxChars ?? DEFAULT_JEV_DIGEST_MAX_CHARS, [0, 1000, 2000, 4000, 8000, 15000])
7956
- },
7957
- {
7958
- currentValue: settings.jevTurnGateEveryTurns === 0 || settings.jevTurnGateEveryTurns === undefined ? "Off" : `every ${settings.jevTurnGateEveryTurns} turns`,
7959
- description: "Proactively consult the Advisor every N turns without a consultation (0 = off).",
7960
- id: "jevTurnGateEveryTurns",
7961
- label: "Jev/Decisions turn gate",
7962
- values: [
7963
- "Off",
7964
- "every 3 turns",
7965
- "every 5 turns",
7966
- "every 10 turns",
7967
- "every 20 turns"
7968
- ]
7969
- },
7970
- {
7971
- currentValue: String(settings.jevTurnGateNoulThreshold ?? DEFAULT_JEV_TURN_GATE_NOUL_THRESHOLD),
7972
- description: "Jev confidence required before the turn gate interrupts with advice.",
7973
- id: "jevTurnGateNoulThreshold",
7974
- label: "Jev/Decisions turn-gate threshold",
7975
- values: numericValues(settings.jevTurnGateNoulThreshold ?? DEFAULT_JEV_TURN_GATE_NOUL_THRESHOLD, [0.6, 0.7, 0.8, 0.85, 0.9, 0.95])
7976
- }
7977
- ];
7978
8653
  var advisorFallbackModelItem = (settings, modelRefs, keybindings, theme, tui) => ({
7979
8654
  currentValue: settings.fallbackModel ?? FALLBACK_ADVISOR_MODEL_DISABLED,
7980
- description: "Retry a failed Advisor request once with this optional model; the primary model remains unchanged.",
8655
+ description: t("settings.fallbackModel.desc", "Retry a failed Advisor request once with this optional model; the primary model remains unchanged."),
7981
8656
  id: "fallbackModel",
7982
- label: "Fallback Advisor model",
8657
+ label: t("settings.fallbackModel.label", "Fallback Advisor model"),
7983
8658
  submenu: (_currentValue, done) => new SearchableModelSelector({
7984
8659
  allOptions: [
7985
8660
  FALLBACK_ADVISOR_MODEL_DISABLED,
7986
8661
  ...new Set(modelRefs ?? (settings.fallbackModel ? [settings.fallbackModel] : []))
7987
8662
  ],
7988
8663
  currentOption: settings.fallbackModel ?? FALLBACK_ADVISOR_MODEL_DISABLED,
7989
- keybindings: keybindings ?? getKeybindings(),
8664
+ keybindings: keybindings ?? getKeybindings2(),
7990
8665
  onCancel: done,
7991
8666
  onSelect: (value) => done(value === FALLBACK_ADVISOR_MODEL_DISABLED ? "" : value),
7992
8667
  theme,
7993
- title: "Fallback Advisor model",
8668
+ title: t("settings.fallbackModel.label", "Fallback Advisor model"),
7994
8669
  tui
7995
8670
  })
7996
8671
  });
7997
8672
  var advisorModelWhitelistItem = (settings, modelRefs, keybindings, theme, tui) => ({
7998
- currentValue: settings.modelWhitelist?.length ? settings.modelWhitelist.join(", ") : "Any model",
7999
- description: "Only the exact provider/model references listed here may call the Advisor; an empty list allows every model.",
8673
+ currentValue: settings.modelWhitelist?.length ? settings.modelWhitelist.join(", ") : t("settings.modelWhitelist.any", "Any model"),
8674
+ description: t("settings.modelWhitelist.desc", "Only the exact provider/model references listed here may call the Advisor; an empty list allows every model."),
8000
8675
  id: "modelWhitelist",
8001
- label: "Advisor model whitelist",
8676
+ label: t("settings.modelWhitelist.label", "Advisor model whitelist"),
8002
8677
  submenu: (_currentValue, done) => new SearchableModelMultiSelector({
8003
8678
  allOptions: [
8004
8679
  ...new Set([...modelRefs ?? [], ...settings.modelWhitelist ?? []])
8005
8680
  ],
8006
8681
  currentOptions: settings.modelWhitelist ?? [],
8007
- keybindings: keybindings ?? getKeybindings(),
8682
+ keybindings: keybindings ?? getKeybindings2(),
8008
8683
  multiSelect: true,
8009
8684
  onCancel: done,
8010
8685
  onSelect: (values) => done(values.join(",")),
8011
8686
  theme,
8012
- title: "Advisor model whitelist",
8687
+ title: t("settings.modelWhitelist.label", "Advisor model whitelist"),
8013
8688
  tui
8014
8689
  })
8015
8690
  });
@@ -8031,89 +8706,89 @@ var createSettingsItems = ({
8031
8706
  currentValue: currentContextLabel(presets, settings.contextMaxChars),
8032
8707
  description: contextDescription(presets, settings.contextMaxChars),
8033
8708
  id: "context",
8034
- label: "Context window",
8709
+ label: t("settings.context.label", "Context window"),
8035
8710
  values: presets.map((preset) => preset.label)
8036
8711
  },
8037
8712
  {
8038
8713
  currentValue: settingValue(settings.advisorToolsEnabled, true),
8039
- description: "Allow the model to call the Advisor tools; /advisor-off disables them across sessions.",
8714
+ description: t("settings.advisorToolsEnabled.desc", "Allow the model to call the Advisor tools; /advisor-off disables them across sessions."),
8040
8715
  id: "advisorToolsEnabled",
8041
- label: "Advisor tools",
8716
+ label: t("settings.advisorToolsEnabled.label", "Advisor tools"),
8042
8717
  values: TOGGLE_VALUES
8043
8718
  },
8044
8719
  {
8045
8720
  currentValue: settingValue(settings.simpleMode, false),
8046
- description: "Keep enabled Advisor tools available on demand without automatic gates or blocks.",
8721
+ description: t("settings.simpleMode.desc", "Keep enabled Advisor tools available on demand without automatic gates or blocks."),
8047
8722
  id: "simpleMode",
8048
- label: "Simple mode",
8723
+ label: t("settings.simpleMode.label", "Simple mode"),
8049
8724
  values: TOGGLE_VALUES
8050
8725
  },
8051
8726
  {
8052
8727
  currentValue: settingValue(settings.alwaysOn, false),
8053
- description: "Run the Advisor flow automatically for supported agent turns.",
8728
+ description: t("settings.alwaysOn.desc", "Run the Advisor flow automatically for supported agent turns."),
8054
8729
  id: "alwaysOn",
8055
- label: "Always on",
8730
+ label: t("settings.alwaysOn.label", "Always on"),
8056
8731
  values: TOGGLE_VALUES
8057
8732
  },
8058
8733
  fallbackModel
8059
8734
  ];
8060
8735
  if (settings.simpleMode) {
8061
- items.push(modelWhitelist, toggle("disableSameModel", "Disable same-model Advisor", "Skip advice when the active Executor and Advisor use the same provider/model; turn off to allow higher-effort same-model reviews.", settings.disableSameModel, true));
8736
+ items.push(modelWhitelist, toggle("disableSameModel", t("settings.disableSameModel.label", "Disable same-model Advisor"), t("settings.disableSameModel.desc", "Skip advice when the active Executor and Advisor use the same provider/model; turn off to allow higher-effort same-model reviews."), settings.disableSameModel, true));
8062
8737
  return items;
8063
8738
  }
8064
8739
  items.push({
8065
8740
  currentValue: currentEffort(settings.effort),
8066
- description: "Reasoning level used for Advisor calls.",
8741
+ description: t("settings.effort.desc", "Reasoning level used for Advisor calls."),
8067
8742
  id: "effort",
8068
- label: "Advisor reasoning",
8743
+ label: t("settings.effort.label", "Advisor reasoning"),
8069
8744
  values: withCurrentValue(currentEffort(settings.effort), effortLevels)
8070
- }, modelWhitelist, toggle("disableSameModel", "Disable same-model Advisor", "Skip advice when the active Executor and Advisor use the same provider/model; turn off to allow higher-effort same-model reviews.", settings.disableSameModel, true), toggle("scoutEnabled", "Experimental Advisor Scout", "Enable the experimental Scout before Advisor calls.", settings.scoutEnabled, false), scoutTimeoutItem(settings), toggle("showUsageDetails", "Show usage and cost details", "Show token usage and cost details in Advisor responses.", settings.showUsageDetails, true), toggle("showUsageFooter", "Show usage in footer", "Show the current Advisor usage summary in the footer.", settings.showUsageFooter, false), toggle("planGate", "Plan gate", "Ask the Advisor to review implementation plans.", settings.planGate, true), toggle("failureGate", "Failure gate", "Ask the Advisor to review repeated failures.", settings.failureGate, true), toggle("completionGate", "Completion gate", "Ask the Advisor to review work before declaring success.", settings.completionGate, true), toggle("collapseResponses", "Collapse long responses", "Collapse long Advisor responses in the transcript.", settings.collapseResponses, false), {
8071
- currentValue: settings.customRule || "None",
8072
- description: "Add a rule that triggers Advisor involvement.",
8745
+ }, modelWhitelist, toggle("disableSameModel", t("settings.disableSameModel.label", "Disable same-model Advisor"), t("settings.disableSameModel.desc", "Skip advice when the active Executor and Advisor use the same provider/model; turn off to allow higher-effort same-model reviews."), settings.disableSameModel, true), toggle("scoutEnabled", t("settings.scoutEnabled.label", "Experimental Advisor Scout"), t("settings.scoutEnabled.desc", "Enable the experimental Scout before Advisor calls."), settings.scoutEnabled, false), scoutTimeoutItem(settings), toggle("showUsageDetails", t("settings.showUsageDetails.label", "Show usage and cost details"), t("settings.showUsageDetails.desc", "Show token usage and cost details in Advisor responses."), settings.showUsageDetails, true), toggle("showUsageFooter", t("settings.showUsageFooter.label", "Show usage in footer"), t("settings.showUsageFooter.desc", "Show the current Advisor usage summary in the footer."), settings.showUsageFooter, false), toggle("planGate", t("settings.planGate.label", "Plan gate"), t("settings.planGate.desc", "Ask the Advisor to review implementation plans."), settings.planGate, true), toggle("failureGate", t("settings.failureGate.label", "Failure gate"), t("settings.failureGate.desc", "Ask the Advisor to review repeated failures."), settings.failureGate, true), toggle("completionGate", t("settings.completionGate.label", "Completion gate"), t("settings.completionGate.desc", "Ask the Advisor to review work before declaring success."), settings.completionGate, true), toggle("collapseResponses", t("settings.collapseResponses.label", "Collapse long responses"), t("settings.collapseResponses.desc", "Collapse long Advisor responses in the transcript."), settings.collapseResponses, false), {
8746
+ currentValue: settings.customRule || t("settings.none", "None"),
8747
+ description: t("settings.customRule.desc", "Add a rule that triggers Advisor involvement."),
8073
8748
  id: "customRule",
8074
- label: "Custom invocation",
8749
+ label: t("settings.customRule.label", "Custom invocation"),
8075
8750
  submenu: (_currentValue, done) => new TextSettingSubmenu({
8076
- description: "Enter a custom invocation rule.",
8751
+ description: t("settings.customRule.submenuDesc", "Enter a custom invocation rule."),
8077
8752
  initial: settings.customRule || "",
8078
8753
  onCancel: done,
8079
8754
  onSubmit: (value) => ({ value: value.trim() }),
8080
8755
  theme,
8081
- title: "Custom invocation",
8756
+ title: t("settings.customRule.label", "Custom invocation"),
8082
8757
  tui
8083
8758
  })
8084
- }, toggle("blockOnBlocked", "Block on critical advice", "Block the agent when the Advisor returns a critical decision.", settings.blockOnBlocked, true), toggle("autoLoopGate", "Automatic loop gate", "Ask the Advisor to review repeated equivalent attempts.", settings.autoLoopGate, true), {
8085
- currentValue: `After ${settings.loopThreshold ?? 3} repeats`,
8086
- description: "Number of equivalent attempts before automatic review.",
8759
+ }, toggle("blockOnBlocked", t("settings.blockOnBlocked.label", "Block on critical advice"), t("settings.blockOnBlocked.desc", "Block the agent when the Advisor returns a critical decision."), settings.blockOnBlocked, true), toggle("autoLoopGate", t("settings.autoLoopGate.label", "Automatic loop gate"), t("settings.autoLoopGate.desc", "Ask the Advisor to review repeated equivalent attempts."), settings.autoLoopGate, true), {
8760
+ currentValue: `${t("settings.loopThreshold.after", "After")} ${settings.loopThreshold ?? 3} ${t("settings.loopThreshold.repeats", "repeats")}`,
8761
+ description: t("settings.loopThreshold.desc", "Number of equivalent attempts before automatic review."),
8087
8762
  id: "loopThreshold",
8088
- label: "Loop threshold",
8089
- values: numericValues(settings.loopThreshold ?? 3, Array.from({ length: 99 }, (_, index) => index + 2)).map((value) => `After ${value} repeats`)
8763
+ label: t("settings.loopThreshold.label", "Loop threshold"),
8764
+ values: numericValues(settings.loopThreshold ?? 3, Array.from({ length: 99 }, (_, index) => index + 2)).map((value) => `${t("settings.loopThreshold.after", "After")} ${value} ${t("settings.loopThreshold.repeats", "repeats")}`)
8090
8765
  }, {
8091
8766
  currentValue: settings.maxCallsPerSession === undefined ? "∞" : String(settings.maxCallsPerSession),
8092
- description: "Limit automatic Advisor calls in one session.",
8767
+ description: t("settings.maxCallsPerSession.desc", "Limit automatic Advisor calls in one session."),
8093
8768
  id: "maxCallsPerSession",
8094
- label: "Max Advisor calls/session",
8769
+ label: t("settings.maxCallsPerSession.label", "Max Advisor calls/session"),
8095
8770
  values: maxCallValues(settings.maxCallsPerSession === undefined ? "∞" : String(settings.maxCallsPerSession))
8096
- }, toggle("sessionSummary", "Session Advisor Summary", "Show a local summary when the session ends.", settings.sessionSummary, false), toggle("logFeedback", "Advisor log feedback", "Include budget and Scout status messages in session logs. Actual Advisor calls and results remain visible either way.", settings.logFeedback, false), {
8771
+ }, toggle("sessionSummary", t("settings.sessionSummary.label", "Session Advisor Summary"), t("settings.sessionSummary.desc", "Show a local summary when the session ends."), settings.sessionSummary, false), toggle("logFeedback", t("settings.logFeedback.label", "Advisor log feedback"), t("settings.logFeedback.desc", "Include budget and Scout status messages in session logs. Actual Advisor calls and results remain visible either way."), settings.logFeedback, false), {
8097
8772
  currentValue: settings.failureMode ?? "block-session",
8098
- description: "Choose what happens when an Advisor gate fails.",
8773
+ description: t("settings.failureMode.desc", "Choose what happens when an Advisor gate fails."),
8099
8774
  id: "failureMode",
8100
- label: "Gate failure mode",
8775
+ label: t("settings.failureMode.label", "Gate failure mode"),
8101
8776
  values: withCurrentValue(settings.failureMode ?? "block-session", [
8102
8777
  "block-session",
8103
8778
  "block-tool",
8104
8779
  "warn-and-continue"
8105
8780
  ])
8106
- }, toggle("herdrIntegration", "Herdr integration", "Send Advisor activity to the optional Herdr integration.", settings.herdrIntegration, true), {
8781
+ }, toggle("herdrIntegration", t("settings.herdrIntegration.label", "Herdr integration"), t("settings.herdrIntegration.desc", "Send Advisor activity to the optional Herdr integration."), settings.herdrIntegration, true), {
8107
8782
  currentValue: String(settings.toolResultMaxLines ?? 2000),
8108
- description: "Maximum lines included from a tool result.",
8783
+ description: t("settings.toolResultMaxLines.desc", "Maximum lines included from a tool result."),
8109
8784
  id: "toolResultMaxLines",
8110
- label: "Tool result lines",
8785
+ label: t("settings.toolResultMaxLines.label", "Tool result lines"),
8111
8786
  values: numericValues(settings.toolResultMaxLines ?? 2000, [0, 500, 1000, 2000, 5000, 1e4])
8112
8787
  }, {
8113
8788
  currentValue: String(settings.toolResultMaxBytes ?? 50 * 1024),
8114
- description: "Maximum bytes included from a tool result.",
8789
+ description: t("settings.toolResultMaxBytes.desc", "Maximum bytes included from a tool result."),
8115
8790
  id: "toolResultMaxBytes",
8116
- label: "Tool result bytes",
8791
+ label: t("settings.toolResultMaxBytes.label", "Tool result bytes"),
8117
8792
  values: numericValues(settings.toolResultMaxBytes ?? 50 * 1024, [
8118
8793
  0,
8119
8794
  10 * 1024,
@@ -8121,11 +8796,11 @@ var createSettingsItems = ({
8121
8796
  100 * 1024,
8122
8797
  500 * 1024
8123
8798
  ])
8124
- }, toggle("redactSecrets", "Redact common secrets", "Redact common credential patterns before Advisor calls.", settings.redactSecrets, false), toggle("agentsMdContext", "AGENTS.md context", "Include trusted project and global AGENTS.md rules in Advisor calls.", settings.agentsMdContext, true), {
8799
+ }, toggle("redactSecrets", t("settings.redactSecrets.label", "Redact common secrets"), t("settings.redactSecrets.desc", "Redact common credential patterns before Advisor calls."), settings.redactSecrets, false), toggle("agentsMdContext", t("settings.agentsMdContext.label", "AGENTS.md context"), t("settings.agentsMdContext.desc", "Include trusted project and global AGENTS.md rules in Advisor calls."), settings.agentsMdContext, true), {
8125
8800
  currentValue: settings.gitContext ?? "summary",
8126
- description: "How much repository context is shared with the Advisor.",
8801
+ description: t("settings.gitContext.desc", "How much repository context is shared with the Advisor."),
8127
8802
  id: "gitContext",
8128
- label: "Repository context",
8803
+ label: t("settings.gitContext.label", "Repository context"),
8129
8804
  values: withCurrentValue(settings.gitContext ?? "summary", [
8130
8805
  "off",
8131
8806
  "summary",
@@ -8133,17 +8808,17 @@ var createSettingsItems = ({
8133
8808
  ])
8134
8809
  }, {
8135
8810
  currentValue: String(settings.gitContextMaxChars ?? 20000),
8136
- description: "Maximum repository context characters included.",
8811
+ description: t("settings.gitContextMaxChars.desc", "Maximum repository context characters included."),
8137
8812
  id: "gitContextMaxChars",
8138
- label: "Repository context chars",
8813
+ label: t("settings.gitContextMaxChars.label", "Repository context chars"),
8139
8814
  values: numericValues(settings.gitContextMaxChars ?? 20000, [0, 5000, 1e4, 20000, 50000, 1e5])
8140
8815
  }, {
8141
- currentValue: Object.keys(settings.toolPolicies ?? {}).length ? "Configured" : "All tools: full",
8142
- description: "Choose which tools are shared in full, summarized, or excluded.",
8816
+ currentValue: Object.keys(settings.toolPolicies ?? {}).length ? t("settings.toolPolicies.configured", "Configured") : t("settings.toolPolicies.allToolsFull", "All tools: full"),
8817
+ description: t("settings.toolPolicies.desc", "Choose which tools are shared in full, summarized, or excluded."),
8143
8818
  id: "toolPolicies",
8144
- label: "Tool disclosure policies",
8819
+ label: t("settings.toolPolicies.label", "Tool disclosure policies"),
8145
8820
  submenu: (_currentValue, done) => new TextSettingSubmenu({
8146
- description: 'Enter a JSON object with "full", "summary", or "exclude" values.',
8821
+ description: t("settings.toolPolicies.submenuDesc", 'Enter a JSON object with "full", "summary", or "exclude" values.'),
8147
8822
  initial: JSON.stringify(settings.toolPolicies ?? {}),
8148
8823
  onCancel: done,
8149
8824
  onSubmit: (value) => {
@@ -8151,20 +8826,27 @@ var createSettingsItems = ({
8151
8826
  try {
8152
8827
  parsed = JSON.parse(value || "{}");
8153
8828
  } catch {
8154
- return { error: "Enter a valid JSON object." };
8829
+ return {
8830
+ error: t("settings.toolPolicies.invalidJson", "Enter a valid JSON object.")
8831
+ };
8155
8832
  }
8156
8833
  if (!isValidAdvisorToolPolicies(parsed)) {
8157
8834
  return {
8158
- error: "Use non-empty tool names with full, summary, or exclude values."
8835
+ error: t("settings.toolPolicies.invalidPolicies", "Use non-empty tool names with full, summary, or exclude values.")
8159
8836
  };
8160
8837
  }
8161
8838
  return { value: JSON.stringify(parsed) };
8162
8839
  },
8163
8840
  theme,
8164
- title: "Tool disclosure policies",
8841
+ title: t("settings.toolPolicies.label", "Tool disclosure policies"),
8165
8842
  tui
8166
8843
  })
8167
- }, toggle("trackedFileContent", "Tracked file content", "Allow tracked file contents to be sent with Advisor context.", settings.trackedFileContent, false), toggle("untrackedContent", "Untracked file content", "Allow untracked file contents to be sent with Advisor context.", settings.untrackedContent, false), toggle("outcomeLogging", "Outcome logging (global)", "Allow anonymized Advisor outcomes to be logged globally.", settings.outcomeLogging, false), ...jevItems(settings, theme, tui, jevClassifierRegistry, jevKeyDeps, onJevFilter, onJevProvider));
8844
+ }, toggle("trackedFileContent", t("settings.trackedFileContent.label", "Tracked file content"), t("settings.trackedFileContent.desc", "Allow tracked file contents to be sent with Advisor context."), settings.trackedFileContent, false), toggle("untrackedContent", t("settings.untrackedContent.label", "Untracked file content"), t("settings.untrackedContent.desc", "Allow untracked file contents to be sent with Advisor context."), settings.untrackedContent, false), toggle("outcomeLogging", t("settings.outcomeLogging.label", "Outcome logging (global)"), t("settings.outcomeLogging.desc", "Allow anonymized Advisor outcomes to be logged globally."), settings.outcomeLogging, false), ...jevItems(settings, theme, tui, {
8845
+ jevClassifierRegistry,
8846
+ jevKeyDeps,
8847
+ onJevFilter,
8848
+ onJevProvider
8849
+ }));
8168
8850
  return items;
8169
8851
  };
8170
8852
 
@@ -8439,7 +9121,7 @@ class AdvisorSettingsSelector {
8439
9121
  this.presets = options.presets.some((preset) => preset.value === configuredContext) ? [...options.presets] : [
8440
9122
  ...options.presets,
8441
9123
  {
8442
- description: "Current custom context limit",
9124
+ description: t("settingsSubmenu.customContextLimit", "Current custom context limit"),
8443
9125
  label: String(configuredContext),
8444
9126
  value: configuredContext
8445
9127
  }
@@ -8470,7 +9152,7 @@ class AdvisorSettingsSelector {
8470
9152
  const defaultLabel = listTheme.label;
8471
9153
  listTheme.label = (text, selected) => {
8472
9154
  if (this.settings.simpleMode && text.startsWith("Simple mode")) {
8473
- return `${rainbowGradient("Simple mode", this.simpleModeGradientStartedAt ?? 0)}${text.slice("Simple mode".length)}`;
9155
+ return `${rainbowGradient(t("settings.simpleMode.label", "Simple mode"), this.simpleModeGradientStartedAt ?? 0)}${text.slice("Simple mode".length)}`;
8474
9156
  }
8475
9157
  return defaultLabel(text, selected);
8476
9158
  };
@@ -8674,7 +9356,7 @@ var persistJevSettings = (ctx, settings, runtime) => {
8674
9356
  saveAdvisorSettings(ctx, settings, { skipOutcomeLogging: true });
8675
9357
  } catch (error) {
8676
9358
  const message = error instanceof Error ? error.message : String(error);
8677
- ctx.ui.notify(`Could not save Advisor settings: ${message}`, "error");
9359
+ ctx.ui.notify(`${t("settingsCmd.saveFailed.prefix", "Could not save Advisor settings:")} ${message}`, "error");
8678
9360
  return false;
8679
9361
  }
8680
9362
  try {
@@ -8683,7 +9365,7 @@ var persistJevSettings = (ctx, settings, runtime) => {
8683
9365
  runtime.updateAdvisorUsageStatus(ctx);
8684
9366
  } catch (error) {
8685
9367
  const message = error instanceof Error ? error.message : String(error);
8686
- ctx.ui.notify(`Advisor settings were saved, but the status refresh failed: ${message}`, "warning");
9368
+ ctx.ui.notify(`${t("settingsCmd.refreshFailed.prefix", "Advisor settings were saved, but the status refresh failed:")} ${message}`, "warning");
8687
9369
  }
8688
9370
  return true;
8689
9371
  };
@@ -8728,7 +9410,7 @@ var registerSettingsCommands = (runtime) => {
8728
9410
  runtime.resetSameModelNotice();
8729
9411
  }
8730
9412
  const message = error instanceof Error ? error.message : String(error);
8731
- ctx.ui.notify(toolsDisabled ? `Could not save Advisor settings; tools remain disabled for this session. ${message}` : `Could not save Advisor settings: ${message}`, "error");
9413
+ ctx.ui.notify(toolsDisabled ? `${t("settingsCmd.saveFailedToolsDisabled.prefix", "Could not save Advisor settings; tools remain disabled for this session.")} ${message}` : `${t("settingsCmd.saveFailed.prefix", "Could not save Advisor settings:")} ${message}`, "error");
8732
9414
  }
8733
9415
  },
8734
9416
  onJevFilter: (_selection, settings) => persistJevSettings(ctx, settings, runtime),
@@ -8751,7 +9433,7 @@ var registerSettingsCommands = (runtime) => {
8751
9433
  setAdvisorToolsEnabledRef(false);
8752
9434
  setAlwaysOnRef(false);
8753
9435
  const message = error instanceof Error ? error.message : String(error);
8754
- notify(ctx, `Advisor tools disabled for this session, but configuration could not be reloaded: ${message}`, "error");
9436
+ notify(ctx, `${t("settingsCmd.offReloadFailed.prefix", "Advisor tools disabled for this session, but configuration could not be reloaded:")} ${message}`, "error");
8755
9437
  return Promise.resolve();
8756
9438
  }
8757
9439
  const wasAlwaysOn = alwaysOnRef;
@@ -8767,10 +9449,10 @@ var registerSettingsCommands = (runtime) => {
8767
9449
  });
8768
9450
  } catch (error) {
8769
9451
  const message = error instanceof Error ? error.message : String(error);
8770
- notify(ctx, `Advisor tools disabled for this session, but the setting could not be saved: ${message}`, "error");
9452
+ notify(ctx, `${t("settingsCmd.offSaveFailed.prefix", "Advisor tools disabled for this session, but the setting could not be saved:")} ${message}`, "error");
8771
9453
  return Promise.resolve();
8772
9454
  }
8773
- notify(ctx, `Advisor tools disabled. Current model unchanged.${wasAlwaysOn ? " Always on turned off." : ""}`, "info");
9455
+ notify(ctx, `${t("settingsCmd.off.message", "Advisor tools disabled. Current model unchanged.")}${wasAlwaysOn ? ` ${t("settingsCmd.off.alwaysOnTurnedOff", "Always on turned off.")}` : ""}`, "info");
8774
9456
  return Promise.resolve();
8775
9457
  }
8776
9458
  });
@@ -8786,6 +9468,7 @@ var registerCommands = (pi, dependencies = {}) => {
8786
9468
  registerModelCommands(runtime);
8787
9469
  registerOutcomeStatsCommand(runtime);
8788
9470
  registerSettingsCommands(runtime);
9471
+ registerAdvisorConfigurationTool(runtime);
8789
9472
  };
8790
9473
 
8791
9474
  // src/tools/budget-feedback.ts
@@ -8833,7 +9516,8 @@ var updateAdvisorUsageStatus = (ctx, session) => {
8833
9516
  };
8834
9517
  var notifyLocalFailure = (ctx, message, sessionBlocked = false) => {
8835
9518
  if (ctx.hasUI) {
8836
- ctx.ui.notify(`Advisor ${sessionBlocked ? "gate failure; session blocked" : "consultation failed"}: ${message}`, "error");
9519
+ const prefix = sessionBlocked ? t("notify.localFailure.blockedPrefix", "Advisor gate failure; session blocked:") : t("notify.localFailure.failedPrefix", "Advisor consultation failed:");
9520
+ ctx.ui.notify(`${prefix} ${message}`, "error");
8837
9521
  }
8838
9522
  };
8839
9523
  var gateFailureEffectForMode = (mode) => {
@@ -8868,7 +9552,7 @@ var failureEffect = (category, message, ctx, session, failureMode, herdrBlock =
8868
9552
  var blockedDecisionEffect = (reason, ctx, session, failureMode, herdrBlock = herdrAdvisorBlock) => {
8869
9553
  if (failureMode === "warn-and-continue") {
8870
9554
  if (ctx.hasUI) {
8871
- ctx.ui.notify("Advisor gate returned blocked; continuing by configuration.", "warning");
9555
+ ctx.ui.notify(t("notify.gateBlockedContinued.message", "Advisor gate returned blocked; continuing by configuration."), "warning");
8872
9556
  }
8873
9557
  return { block: false, effect: "continued", reason };
8874
9558
  }
@@ -8899,7 +9583,7 @@ var reserveAdvisorCall = (event, ctx, session, reservedCalls) => {
8899
9583
  };
8900
9584
 
8901
9585
  // src/tools/jev-turn-gate.ts
8902
- var outageNotifier2 = createOutageNotifier((category, message) => `Advisor Jev classifier turn gate failed (${category}); continuing without a proactive consultation. ${message}`);
9586
+ var outageNotifier2 = createOutageNotifier((category, message) => `${t("notify.jevTurnGateOutage.prefix", "Advisor Jev classifier turn gate failed")} (${category}); ${t("notify.jevTurnGateOutage.continuing", "continuing without a proactive consultation.")} ${message}`);
8903
9587
  var notifyFailureOnce = outageNotifier2.notify;
8904
9588
  var shouldRunTurnGate = (registration, ctx, session) => {
8905
9589
  const interval = advisorJevTurnGateEveryTurnsRef;
@@ -9000,36 +9684,36 @@ var registerJevTurnGate = (on, registration) => {
9000
9684
  };
9001
9685
 
9002
9686
  // src/tools/register-ask-advisor.ts
9003
- import { Type as Type2 } from "typebox";
9687
+ import { Type as Type3 } from "typebox";
9004
9688
 
9005
9689
  // src/tools/advisor-output.ts
9006
- import { Type } from "typebox";
9007
- var advisorOutputSchema = Type.Object({
9008
- adviceId: Type.Optional(Type.String()),
9009
- advisor: Type.Optional(Type.String()),
9010
- followUp: Type.Optional(Type.Boolean()),
9011
- jev: Type.Optional(Type.Object({
9012
- kind: Type.Union([Type.Literal("screened"), Type.Literal("repeat")]),
9013
- reason: Type.String(),
9014
- skipped: Type.Boolean()
9690
+ import { Type as Type2 } from "typebox";
9691
+ var advisorOutputSchema = Type2.Object({
9692
+ adviceId: Type2.Optional(Type2.String()),
9693
+ advisor: Type2.Optional(Type2.String()),
9694
+ followUp: Type2.Optional(Type2.Boolean()),
9695
+ jev: Type2.Optional(Type2.Object({
9696
+ kind: Type2.Union([Type2.Literal("screened"), Type2.Literal("repeat")]),
9697
+ reason: Type2.String(),
9698
+ skipped: Type2.Boolean()
9015
9699
  })),
9016
- skipReason: Type.Optional(Type.String()),
9017
- text: Type.String({
9700
+ skipReason: Type2.Optional(Type2.String()),
9701
+ text: Type2.String({
9018
9702
  description: "Advisor Markdown or consultation skip notice."
9019
9703
  }),
9020
- usage: Type.Optional(Type.Object({
9021
- cacheRead: Type.Optional(Type.Number()),
9022
- cacheWrite: Type.Optional(Type.Number()),
9023
- cost: Type.Optional(Type.Number()),
9024
- input: Type.Optional(Type.Number()),
9025
- output: Type.Optional(Type.Number()),
9026
- totalTokens: Type.Optional(Type.Number())
9704
+ usage: Type2.Optional(Type2.Object({
9705
+ cacheRead: Type2.Optional(Type2.Number()),
9706
+ cacheWrite: Type2.Optional(Type2.Number()),
9707
+ cost: Type2.Optional(Type2.Number()),
9708
+ input: Type2.Optional(Type2.Number()),
9709
+ output: Type2.Optional(Type2.Number()),
9710
+ totalTokens: Type2.Optional(Type2.Number())
9027
9711
  }))
9028
9712
  });
9029
9713
 
9030
9714
  // src/tools/render-advisor-result.ts
9031
9715
  import { getMarkdownTheme as getMarkdownTheme4 } from "@earendil-works/pi-coding-agent";
9032
- import { Box as Box3, Markdown as Markdown4, Spacer, Text as Text5 } from "@earendil-works/pi-tui";
9716
+ import { Box as Box3, Markdown as Markdown4, Spacer, Text as Text6 } from "@earendil-works/pi-tui";
9033
9717
  var advisorResultDetails = (result) => result.details;
9034
9718
  var syncRenderPhase = (context, phase) => {
9035
9719
  if (context.state.phase !== phase && context.state.timerId) {
@@ -9066,17 +9750,17 @@ var attachmentLabels = (details) => [
9066
9750
  details?.agentRulesBytes ? `AGENTS.md rules attached · ${formatByteSize2(details.agentRulesBytes)}` : undefined,
9067
9751
  details?.draftBytes ? `Draft attached · ${formatByteSize2(details.draftBytes)}` : undefined,
9068
9752
  details?.preferenceBytes ? `Project preferences attached · ${formatByteSize2(details.preferenceBytes)}` : undefined,
9069
- details?.trackedBytes ? `Tracked files attached · ${formatByteSize2(details.trackedBytes)}` : undefined,
9070
- details?.untrackedBytes ? `Untracked files attached · ${formatByteSize2(details.untrackedBytes)}` : undefined,
9071
- details?.imageCount ? `${details.imageCount} image${details.imageCount === 1 ? "" : "s"} attached${details.imageBytes ? ` · ${formatByteSize2(details.imageBytes)}` : ""}${details.imageOmissions ? ` · ${details.imageOmissions} withheld` : ""}` : undefined
9753
+ details?.trackedBytes ? `${t("render.trackedAttached", "Tracked files attached")} · ${formatByteSize2(details.trackedBytes)}` : undefined,
9754
+ details?.untrackedBytes ? `${t("render.untrackedAttached", "Untracked files attached")} · ${formatByteSize2(details.untrackedBytes)}` : undefined,
9755
+ details?.imageCount ? `${details.imageCount} ${details.imageCount === 1 ? t("render.image", "image") : t("render.images", "images")} ${t("render.attached", "attached")}${details.imageBytes ? ` · ${formatByteSize2(details.imageBytes)}` : ""}${details.imageOmissions ? ` · ${details.imageOmissions} ${t("render.withheld", "withheld")}` : ""}` : undefined
9072
9756
  ].filter((label) => label !== undefined);
9073
9757
  var renderSkipBox = (box, result, expanded, theme) => {
9074
9758
  const details = advisorResultDetails(result);
9075
9759
  const lines = [
9076
- theme.fg("dim", theme.bold("◆ ADVISOR · SKIPPED")),
9760
+ theme.fg("dim", theme.bold(`◆ ADVISOR · ${t("render.skipped", "SKIPPED")}`)),
9077
9761
  theme.fg("dim", ` ${details?.skipReason ?? details?.jev?.reason ?? ""}`)
9078
9762
  ];
9079
- box.addChild(new Text5(lines.join(`
9763
+ box.addChild(new Text6(lines.join(`
9080
9764
  `), 0, 0));
9081
9765
  box.addChild(new Markdown4(adviceForDisplay(textFrom(result.content), expanded), 0, 0, getMarkdownTheme4()));
9082
9766
  };
@@ -9099,9 +9783,9 @@ var renderPartialAdvisorResult = (box, result, expanded, theme, context) => {
9099
9783
  }
9100
9784
  const frame = SPINNER_FRAMES[Math.floor(Date.now() / 80) % SPINNER_FRAMES.length];
9101
9785
  const lines = [
9102
- `${theme.fg("warning", theme.bold(`◆ ADVISOR ${frame}`))} ${theme.fg("dim", "· Working…")}`
9786
+ `${theme.fg("warning", theme.bold(`◆ ADVISOR ${frame}`))} ${theme.fg("dim", `· ${t("render.working", "Working…")}`)}`
9103
9787
  ];
9104
- box.addChild(new Text5(lines.join(`
9788
+ box.addChild(new Text6(lines.join(`
9105
9789
  `), 0, 0));
9106
9790
  if (details?.thinking?.trim()) {
9107
9791
  const thought = details.thinking.length > 200 ? details.thinking.slice(-200) : details.thinking;
@@ -9115,7 +9799,7 @@ var thinkingPreview = (details) => details?.thinking?.trim() ? `${details.thinki
9115
9799
  var finalResultLines = (details, advice, theme) => {
9116
9800
  const lines = [renderAdvisorResponseHeader(hasSoundVerdict(advice), theme)];
9117
9801
  if (details?.followUp) {
9118
- lines.push(theme.fg("dim", " Follow-up consultation"));
9802
+ lines.push(theme.fg("dim", ` ${t("render.followUpConsultation", "Follow-up consultation")}`));
9119
9803
  }
9120
9804
  if (details?.advisor) {
9121
9805
  lines.push(theme.fg("dim", ` ${details.advisor}`));
@@ -9123,7 +9807,7 @@ var finalResultLines = (details, advice, theme) => {
9123
9807
  if (getAdvisorSettings().showUsageDetails) {
9124
9808
  const usage = formatAdvisorUsage(details?.usage);
9125
9809
  if (usage) {
9126
- lines.push(theme.fg("dim", ` Usage: ${usage}`));
9810
+ lines.push(theme.fg("dim", ` ${t("render.usage", "Usage:")} ${usage}`));
9127
9811
  }
9128
9812
  }
9129
9813
  const attachments = attachmentLabels(details);
@@ -9156,8 +9840,8 @@ var renderFinalAdvisorResult = (box, result, expanded, theme, context) => {
9156
9840
  const advice = details?.text || textFrom(result.content);
9157
9841
  const thinking = thinkingPreview(details);
9158
9842
  const lines = finalResultLines(details, advice, theme);
9159
- const displayAdvice = advice || "(Advisor returned no advice.)";
9160
- box.addChild(new Text5(lines.join(`
9843
+ const displayAdvice = advice || t("render.noAdvice", "(Advisor returned no advice.)");
9844
+ box.addChild(new Text6(lines.join(`
9161
9845
  `), 0, 0));
9162
9846
  if (thinking) {
9163
9847
  box.addChild(renderThinkingMarkdown(thinking, theme));
@@ -9430,26 +10114,26 @@ ${result.markdown}`,
9430
10114
  label: "Ask Advisor",
9431
10115
  name: "ask_advisor",
9432
10116
  outputSchema: advisorOutputSchema,
9433
- parameters: Type2.Object({
9434
- draft: Type2.Optional(Type2.String({
10117
+ parameters: Type3.Object({
10118
+ draft: Type3.Optional(Type3.String({
9435
10119
  description: "Concise untrusted draft for plan or completion review; claims are not verification evidence."
9436
10120
  })),
9437
- followUpTo: Type2.Optional(Type2.String({
10121
+ followUpTo: Type3.Optional(Type3.String({
9438
10122
  description: "Opaque adviceId from a prior successful consultation. Requires a new non-empty question and reuses that consultation's redacted payload; do not combine with draft, Git context, or file attachments."
9439
10123
  })),
9440
- force: Type2.Optional(Type2.Boolean({
10124
+ force: Type3.Optional(Type3.Boolean({
9441
10125
  description: "Set true only when you judge a decision genuinely material after a consultation was screened out; bypasses screening."
9442
10126
  })),
9443
- gitContext: Type2.Optional(Type2.Union([Type2.Literal("none"), Type2.Literal("summary"), Type2.Literal("full")], {
10127
+ gitContext: Type3.Optional(Type3.Union([Type3.Literal("none"), Type3.Literal("summary"), Type3.Literal("full")], {
9444
10128
  description: "How much of the working tree to include. Use full when the review depends on the exact code changes, such as a completion review. Use summary for changed file names only, or none when the question is not about the current changes. The user's configured allowance is the ceiling and a larger request is narrowed to it."
9445
10129
  })),
9446
- includeTrackedFiles: Type2.Optional(Type2.Array(Type2.String({
10130
+ includeTrackedFiles: Type3.Optional(Type3.Array(Type3.String({
9447
10131
  description: "Exact tracked repository-relative files to attach after the Advisor explicitly names a file it cannot review. Requires global advisorTrackedFileContent consent; current working-tree contents are sent as untrusted data."
9448
10132
  }))),
9449
- includeUntracked: Type2.Optional(Type2.Array(Type2.String({
10133
+ includeUntracked: Type3.Optional(Type3.Array(Type3.String({
9450
10134
  description: "Exact new repository-relative files to include only when user configuration allows it."
9451
10135
  }))),
9452
- question: Type2.Optional(Type2.String({
10136
+ question: Type3.Optional(Type3.String({
9453
10137
  description: "The specific question or decision to get advice on. Omit this for normal reviews: the Advisor already has the conversation context."
9454
10138
  }))
9455
10139
  }),
@@ -9619,7 +10303,7 @@ var registerToolLifecycle = ({
9619
10303
  if (message !== lastConfigErrorNotified) {
9620
10304
  lastConfigErrorNotified = message;
9621
10305
  if (ctx.hasUI) {
9622
- ctx.ui.notify(`Advisor gating skipped; configuration is invalid. ${message} Fix advisor.json.`, "error");
10306
+ ctx.ui.notify(`${t("notify.gatingSkipped.prefix", "Advisor gating skipped; configuration is invalid.")} ${message} ${t("notify.gatingSkipped.suffix", "Fix advisor.json.")}`, "error");
9623
10307
  }
9624
10308
  }
9625
10309
  return false;
@@ -9733,8 +10417,8 @@ ${guidelines.map((rule) => `- ${rule}`).join(`
9733
10417
  };
9734
10418
 
9735
10419
  // src/tools/register-outcome.ts
9736
- import { Text as Text6 } from "@earendil-works/pi-tui";
9737
- import { Type as Type3 } from "typebox";
10420
+ import { Text as Text7 } from "@earendil-works/pi-tui";
10421
+ import { Type as Type4 } from "typebox";
9738
10422
  var registerOutcomeTool = ({
9739
10423
  appendOutcome: appendAdvisorOutcome,
9740
10424
  pi,
@@ -9773,7 +10457,7 @@ var registerOutcomeTool = ({
9773
10457
  } catch {
9774
10458
  session.releaseAdvice(params.adviceId);
9775
10459
  if (ctx.hasUI) {
9776
- ctx.ui.notify("Advisor outcome could not be recorded locally.", "warning");
10460
+ ctx.ui.notify(t("notify.outcomeRecordFailed.message", "Advisor outcome could not be recorded locally."), "warning");
9777
10461
  }
9778
10462
  return {
9779
10463
  content: [
@@ -9788,19 +10472,19 @@ var registerOutcomeTool = ({
9788
10472
  },
9789
10473
  label: "Record Advisor Outcome",
9790
10474
  name: "record_advisor_outcome",
9791
- parameters: Type3.Object({
9792
- adoption: Type3.String({ enum: ADOPTIONS }),
9793
- adviceId: Type3.String(),
9794
- validationStatus: Type3.String({ enum: VALIDATIONS })
10475
+ parameters: Type4.Object({
10476
+ adoption: Type4.String({ enum: ADOPTIONS }),
10477
+ adviceId: Type4.String(),
10478
+ validationStatus: Type4.String({ enum: VALIDATIONS })
9795
10479
  }),
9796
- renderCall: () => new Text6("[advisor] Record outcome", 0, 0),
9797
- renderResult: (result) => new Text6(textFrom(result.content), 0, 0)
10480
+ renderCall: () => new Text7("[advisor] Record outcome", 0, 0),
10481
+ renderResult: (result) => new Text7(textFrom(result.content), 0, 0)
9798
10482
  });
9799
10483
  };
9800
10484
 
9801
10485
  // src/tools/register-renderers.ts
9802
10486
  import { getMarkdownTheme as getMarkdownTheme5 } from "@earendil-works/pi-coding-agent";
9803
- import { Box as Box4, Markdown as Markdown5, Text as Text7 } from "@earendil-works/pi-tui";
10487
+ import { Box as Box4, Markdown as Markdown5, Text as Text8 } from "@earendil-works/pi-tui";
9804
10488
  var formatByteSize3 = (bytes) => {
9805
10489
  if (bytes >= 1024 ** 3) {
9806
10490
  return `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
@@ -9815,14 +10499,14 @@ var formatByteSize3 = (bytes) => {
9815
10499
  };
9816
10500
  var addAttachmentLine = (box, details, theme) => {
9817
10501
  if (details?.agentRulesBytes) {
9818
- box.addChild(new Text7(theme.fg("dim", ` AGENTS.md rules attached · ${formatByteSize3(details.agentRulesBytes)}`), 0, 0));
10502
+ box.addChild(new Text8(theme.fg("dim", ` AGENTS.md rules attached · ${formatByteSize3(details.agentRulesBytes)}`), 0, 0));
9819
10503
  }
9820
10504
  };
9821
10505
  var addUsageLine = (box, details, theme) => {
9822
10506
  if (getAdvisorSettings().showUsageDetails) {
9823
10507
  const usageText = formatAdvisorUsage(details?.usage);
9824
10508
  if (usageText) {
9825
- box.addChild(new Text7(theme.fg("dim", ` Usage: ${usageText}`), 0, 0));
10509
+ box.addChild(new Text8(theme.fg("dim", ` Usage: ${usageText}`), 0, 0));
9826
10510
  }
9827
10511
  }
9828
10512
  addAttachmentLine(box, details, theme);
@@ -9836,30 +10520,30 @@ var scoutResultRenderer = (entry, { expanded }, theme) => {
9836
10520
  var turnGateResultRenderer = (message, { expanded }, theme) => {
9837
10521
  const { details } = message;
9838
10522
  const box = new Box4(1, 1, (text) => theme.bg("customMessageBg", text));
9839
- box.addChild(new Text7(theme.fg("warning", theme.bold("◆ ADVISOR · TURN REVIEW")), 0, 0));
10523
+ box.addChild(new Text8(theme.fg("warning", theme.bold("◆ ADVISOR · TURN REVIEW")), 0, 0));
9840
10524
  if (details?.advisor) {
9841
- box.addChild(new Text7(theme.fg("dim", ` ${details.advisor}`), 0, 0));
10525
+ box.addChild(new Text8(theme.fg("dim", ` ${details.advisor}`), 0, 0));
9842
10526
  }
9843
10527
  addUsageLine(box, details, theme);
9844
10528
  if (details?.text) {
9845
10529
  box.addChild(new Markdown5(adviceForDisplay(details.text, Boolean(expanded)), 0, 0, getMarkdownTheme5()));
9846
10530
  } else {
9847
- box.addChild(new Text7(theme.fg("error", isString(message.content) ? message.content : "Advisor turn review failed."), 0, 0));
10531
+ box.addChild(new Text8(theme.fg("error", isString(message.content) ? message.content : t("render.turnReviewFailed", "Advisor turn review failed.")), 0, 0));
9848
10532
  }
9849
10533
  return box;
9850
10534
  };
9851
10535
  var loopResultRenderer = (message, { expanded }, theme) => {
9852
10536
  const { details } = message;
9853
10537
  const box = new Box4(1, 1, (text) => theme.bg("customMessageBg", text));
9854
- box.addChild(new Text7(theme.fg("warning", theme.bold(`◆ ADVISOR GATE: ${details?.decision ?? "failure"}`)), 0, 0));
10538
+ box.addChild(new Text8(theme.fg("warning", theme.bold(`◆ ADVISOR GATE: ${details?.decision ?? "failure"}`)), 0, 0));
9855
10539
  if (details?.advisor) {
9856
- box.addChild(new Text7(theme.fg("dim", ` ${details.advisor}`), 0, 0));
10540
+ box.addChild(new Text8(theme.fg("dim", ` ${details.advisor}`), 0, 0));
9857
10541
  }
9858
10542
  addUsageLine(box, details, theme);
9859
10543
  if (details?.text) {
9860
10544
  box.addChild(new Markdown5(adviceForDisplay(details.text, Boolean(expanded)), 0, 0, getMarkdownTheme5()));
9861
10545
  } else {
9862
- box.addChild(new Text7(theme.fg("error", isString(message.content) ? message.content : "Advisor gate failed."), 0, 0));
10546
+ box.addChild(new Text8(theme.fg("error", isString(message.content) ? message.content : t("render.gateFailed", "Advisor gate failed.")), 0, 0));
9863
10547
  }
9864
10548
  return box;
9865
10549
  };
@@ -9909,6 +10593,10 @@ var registerAdvisorTool = (pi, session = sessionStateFor(pi), dependencies = {})
9909
10593
  var consultAdvisor2 = (...args) => consultAdvisor(...args);
9910
10594
  var parseAutomaticDecision2 = (...args) => parseAutomaticDecision(...args);
9911
10595
  var runAdvisorGate2 = (...args) => runAdvisorGate(...args);
10596
+ try {
10597
+ const loader = await import("@juicesharp/rpiv-i18n/loader");
10598
+ loader.registerLocalesFromDir(I18N_NAMESPACE, new URL("../", import.meta.url).href, { label: "pi-advisor" });
10599
+ } catch {}
9912
10600
  function registerPiAdvisor(pi) {
9913
10601
  const sessionState = new AdvisorSessionState;
9914
10602
  const scoutStatus = new ScoutStatusManager;