pi-advisor-flow 0.13.2 → 0.13.3-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.
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ var DEFAULT_ADVISOR_TOOL_RESULT_MAX_LINES = PI_DEFAULT_MAX_LINES;
13
13
  var DEFAULT_ADVISOR_TOOL_RESULT_MAX_BYTES = PI_DEFAULT_MAX_BYTES;
14
14
  var DEFAULT_ADVISOR_GIT_CONTEXT_MAX_CHARS = 20000;
15
15
  var DEFAULT_JEV_MODEL = "jev-latest";
16
+ var JEV_API_KEY_CLASSIFIER = "jev-api-key";
16
17
  var DEFAULT_JEV_TIMEOUT_MS = 8000;
17
18
  var DEFAULT_SCOUT_TIMEOUT_MS = 30000;
18
19
  var MAX_SCOUT_TIMEOUT_MS = 2147483647;
@@ -74,6 +75,8 @@ var advisorJevFilterSkipConfidenceRef = DEFAULT_JEV_FILTER_SKIP_CONFIDENCE;
74
75
  var advisorJevFilterNoulMarginRef = DEFAULT_JEV_FILTER_NOUL_MARGIN;
75
76
  var advisorJevFilterOverrideWindowRef = DEFAULT_JEV_FILTER_OVERRIDE_WINDOW;
76
77
  var advisorJevModelRef = DEFAULT_JEV_MODEL;
78
+ var advisorJevClassifierRef;
79
+ var advisorJevClassifierModeRef = "pi";
77
80
  var advisorJevTimeoutMsRef = DEFAULT_JEV_TIMEOUT_MS;
78
81
  var advisorJevDigestMaxCharsRef = DEFAULT_JEV_DIGEST_MAX_CHARS;
79
82
  var advisorJevPricePerMtokRef = DEFAULT_JEV_PRICE_PER_MTOK;
@@ -181,6 +184,10 @@ var setAdvisorFailureModeRef = (value) => {
181
184
  var setAdvisorHerdrIntegrationRef = (enabled) => {
182
185
  advisorHerdrIntegrationRef = enabled;
183
186
  };
187
+ var setAdvisorJevClassifierRef = (ref) => {
188
+ advisorJevClassifierRef = ref?.trim() || undefined;
189
+ advisorJevClassifierModeRef = advisorJevClassifierRef === "jev-api-key" ? "api-key" : "pi";
190
+ };
184
191
  var setAdvisorJevFilterEnabledRef = (enabled) => {
185
192
  advisorJevFilterEnabledRef = enabled;
186
193
  };
@@ -278,6 +285,7 @@ var getAdvisorSettings = () => ({
278
285
  gitContextMaxChars: advisorGitContextMaxCharsRef,
279
286
  herdrIntegration: advisorHerdrIntegrationRef,
280
287
  jevBaseUrl: advisorJevBaseUrlRef,
288
+ jevClassifier: advisorJevClassifierRef,
281
289
  jevDigestMaxChars: advisorJevDigestMaxCharsRef,
282
290
  jevFilterEnabled: advisorJevFilterEnabledRef,
283
291
  jevFilterNoulMargin: advisorJevFilterNoulMarginRef,
@@ -316,13 +324,14 @@ var splitRef = (ref) => {
316
324
 
317
325
  // src/child-session.ts
318
326
  var isMarkedSubagent = () => process.env.PI_SUBAGENT_CHILD === "1";
327
+ var followsSessionExecutor = () => isMarkedSubagent() || !executorRef;
319
328
  var effectiveExecutorRef = (ctx) => {
320
- if (isMarkedSubagent() && ctx.model) {
329
+ if (followsSessionExecutor() && ctx.model) {
321
330
  return `${ctx.model.provider}/${ctx.model.id}`;
322
331
  }
323
332
  return executorRef;
324
333
  };
325
- var effectiveExecutorEffort = (ctx) => isMarkedSubagent() ? ctx.thinkingLevel : executorEffortRef;
334
+ var effectiveExecutorEffort = (ctx) => isMarkedSubagent() || !(executorRef || executorEffortRef) ? ctx.thinkingLevel : executorEffortRef;
326
335
 
327
336
  // src/content-utils.ts
328
337
  var isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -507,7 +516,6 @@ var normalizeJevBaseUrl = (input) => {
507
516
  }
508
517
  return { baseUrl: `${parsed.origin}${stripContractPath(parsed.pathname)}` };
509
518
  };
510
- var jevSystemOneEndpoint = (baseUrl) => `${baseUrl}${JEV_SYSTEM_ONE_PATH}`;
511
519
 
512
520
  // src/config/schema.ts
513
521
  var configuredModelRef = (value) => value?.trim() || undefined;
@@ -632,6 +640,13 @@ var CONFIG_SCHEMA = {
632
640
  type: "string",
633
641
  validate: isValidJevBaseUrl
634
642
  },
643
+ advisorJevClassifier: {
644
+ accepted: "a concrete provider/model classifier reference or jev-api-key",
645
+ current: () => advisorJevClassifierRef,
646
+ persisted: true,
647
+ type: "string",
648
+ validate: (value) => isString(value) && (value === "jev-api-key" || /^[^/]+\/.+$/u.test(value.trim()))
649
+ },
635
650
  advisorJevDigestMaxChars: {
636
651
  accepted: "a non-negative safe integer",
637
652
  current: () => advisorJevDigestMaxCharsRef,
@@ -966,6 +981,7 @@ var resetDefaults = () => {
966
981
  setAdvisorFailureModeRef("block-session");
967
982
  setAdvisorHerdrIntegrationRef(true);
968
983
  setAdvisorJevModelRef(DEFAULT_JEV_MODEL);
984
+ setAdvisorJevClassifierRef(undefined);
969
985
  setAdvisorJevBaseUrlRef(undefined);
970
986
  setAdvisorJevKeyProviderRef(undefined);
971
987
  setAdvisorJevFilterEnabledRef(false);
@@ -1037,6 +1053,7 @@ var applyConfig = (config) => {
1037
1053
  applyOptionalConfig(config, "advisorJevFilterNoulMargin", setAdvisorJevFilterNoulMarginRef);
1038
1054
  applyOptionalConfig(config, "advisorJevFilterOverrideWindow", setAdvisorJevFilterOverrideWindowRef);
1039
1055
  applyNonEmptyStringConfig(config.advisorJevModel, setAdvisorJevModelRef);
1056
+ applyOptionalConfig(config, "advisorJevClassifier", setAdvisorJevClassifierRef);
1040
1057
  applyOptionalConfig(config, "advisorJevBaseUrl", setAdvisorJevBaseUrlRef);
1041
1058
  applyOptionalConfig(config, "advisorJevKeyProvider", setAdvisorJevKeyProviderRef);
1042
1059
  applyOptionalConfig(config, "advisorJevTimeoutMs", setAdvisorJevTimeoutMsRef);
@@ -1060,14 +1077,6 @@ var applyConfig = (config) => {
1060
1077
  var currentConfigState = () => Object.fromEntries(SAVED_CONFIG_KEYS.map((key) => [key, CONFIG_SCHEMA[key].current()]));
1061
1078
  var sameConfigValue = (left, right) => JSON.stringify(left) === JSON.stringify(right);
1062
1079
  var RESERVED_ADVISOR_JSON_KEYS = new Set(["typesafe_api_key"]);
1063
- var readExistingConfig = (path) => {
1064
- try {
1065
- const parsed = JSON.parse(readFileSync(path, "utf-8"));
1066
- return isRecord(parsed) ? parsed : {};
1067
- } catch {
1068
- return {};
1069
- }
1070
- };
1071
1080
  var readConfigForSave = (path) => {
1072
1081
  if (!existsSync(path)) {
1073
1082
  return {};
@@ -1119,9 +1128,11 @@ var readConfig = (path) => {
1119
1128
  };
1120
1129
  var configCache = new Map;
1121
1130
  var warnedUnknownConfigIdentities = new Set;
1131
+ var warnedFilterWithoutClassifierIdentities = new Set;
1122
1132
  var resetConfigCache = () => {
1123
1133
  configCache.clear();
1124
1134
  warnedUnknownConfigIdentities.clear();
1135
+ warnedFilterWithoutClassifierIdentities.clear();
1125
1136
  };
1126
1137
  var configIdentity = (path) => {
1127
1138
  try {
@@ -1148,8 +1159,12 @@ var loadConfig = (_ctx) => {
1148
1159
  setPersistedModelRefs(configuredModelRef(globalConfig?.advisor), configuredModelRef(globalConfig?.executor));
1149
1160
  if (globalConfig) {
1150
1161
  applyConfig(globalConfig);
1151
- const unknownKeys = unknownConfigKeys(globalConfig).filter((key) => !RESERVED_ADVISOR_JSON_KEYS.has(key));
1152
1162
  const warningIdentity = `${global}:${configIdentity(global)}`;
1163
+ if (advisorJevFilterEnabledRef && !advisorJevClassifierRef && _ctx.hasUI && !warnedFilterWithoutClassifierIdentities.has(warningIdentity)) {
1164
+ warnedFilterWithoutClassifierIdentities.add(warningIdentity);
1165
+ _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");
1166
+ }
1167
+ const unknownKeys = unknownConfigKeys(globalConfig).filter((key) => !RESERVED_ADVISOR_JSON_KEYS.has(key));
1153
1168
  if (unknownKeys.length > 0 && _ctx.hasUI && !warnedUnknownConfigIdentities.has(warningIdentity)) {
1154
1169
  _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");
1155
1170
  warnedUnknownConfigIdentities.add(warningIdentity);
@@ -1184,6 +1199,7 @@ var saveConfig = (_ctx, options = {}) => {
1184
1199
  }
1185
1200
  loadedConfigState = nextLoadedState;
1186
1201
  loadedConfigPath = path;
1202
+ setPersistedModelRefs(configuredModelRef(nextLoadedState.advisor), configuredModelRef(nextLoadedState.executor));
1187
1203
  return path;
1188
1204
  };
1189
1205
  var saveGlobalOutcomeLogging = (enabled) => {
@@ -1342,8 +1358,8 @@ var getExplicitModelError = (ctx, ref, label, overridden, availableRefs) => {
1342
1358
  }
1343
1359
  };
1344
1360
  var planActivationModels = (ctx, executor, advisor, pendingExecutorRef, persisted, executorOverride, advisorOverride, availableRefs) => {
1345
- const pendingExecutor = !executorOverride && pendingExecutorRef && isSelectableModel(ctx, pendingExecutorRef, availableRefs) ? pendingExecutorRef : undefined;
1346
- const executorConfigured = executorOverride || Boolean(pendingExecutor) || Boolean(persisted.executor && isSelectableModel(ctx, executor, availableRefs));
1361
+ const pendingExecutor = !executorOverride && persisted.executor && pendingExecutorRef && isSelectableModel(ctx, pendingExecutorRef, availableRefs) ? pendingExecutorRef : undefined;
1362
+ const executorConfigured = executorOverride || Boolean(pendingExecutor) || !persisted.executor || isSelectableModel(ctx, executor, availableRefs);
1347
1363
  const advisorConfigured = advisorOverride || Boolean(persisted.advisor && isSelectableModel(ctx, advisor, availableRefs));
1348
1364
  return {
1349
1365
  pendingExecutor,
@@ -1551,6 +1567,7 @@ class SearchableModelSelector extends ModelSelectorAdapter {
1551
1567
 
1552
1568
  // src/ui/types.ts
1553
1569
  var FALLBACK_ADVISOR_MODEL_DISABLED = "Disabled (no fallback)";
1570
+ var EXECUTOR_FOLLOWS_SESSION_MODEL = "Current session model (no override)";
1554
1571
 
1555
1572
  // src/commands/model-picker.ts
1556
1573
  var selectAdvisorModels = async (ctx, options) => {
@@ -1574,8 +1591,8 @@ var selectAdvisorModels = async (ctx, options) => {
1574
1591
  } = options;
1575
1592
  if (options.selectExecutor) {
1576
1593
  const selectedExecutor = await ctx.ui.custom((tui, theme, keybindings, done) => new SearchableModelSelector({
1577
- allOptions,
1578
- currentOption: executor || undefined,
1594
+ allOptions: [EXECUTOR_FOLLOWS_SESSION_MODEL, ...allOptions],
1595
+ currentOption: executor || EXECUTOR_FOLLOWS_SESSION_MODEL,
1579
1596
  keybindings,
1580
1597
  onCancel: () => done(undefined),
1581
1598
  onSelect: done,
@@ -1590,7 +1607,7 @@ var selectAdvisorModels = async (ctx, options) => {
1590
1607
  if (!selectedExecutorEffort) {
1591
1608
  return;
1592
1609
  }
1593
- executor = selectedExecutor;
1610
+ executor = selectedExecutor === EXECUTOR_FOLLOWS_SESSION_MODEL ? "" : selectedExecutor;
1594
1611
  executorEffort = selectedEffort(selectedExecutorEffort);
1595
1612
  }
1596
1613
  if (options.selectAdvisor) {
@@ -1634,14 +1651,14 @@ var selectAdvisorModels = async (ctx, options) => {
1634
1651
  return;
1635
1652
  }
1636
1653
  advisorFallbackModel = selectedFallback === FALLBACK_ADVISOR_MODEL_DISABLED ? undefined : selectedFallback;
1637
- if (!(advisor && executor)) {
1654
+ if (!advisor) {
1638
1655
  return;
1639
1656
  }
1640
1657
  return {
1641
1658
  advisor,
1642
1659
  advisorEffort,
1643
1660
  advisorFallbackModel,
1644
- executor,
1661
+ executor: executor ?? "",
1645
1662
  executorEffort
1646
1663
  };
1647
1664
  };
@@ -3487,6 +3504,51 @@ var completeUsageSnapshot = (usage) => {
3487
3504
  }
3488
3505
  return { snapshot, usage };
3489
3506
  };
3507
+ var cleanUsage = (usage) => {
3508
+ const { cost } = usage;
3509
+ const totalTokens = usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
3510
+ return {
3511
+ cacheRead: usage.cacheRead,
3512
+ cacheWrite: usage.cacheWrite,
3513
+ cost: {
3514
+ cacheRead: cost.cacheRead,
3515
+ cacheWrite: cost.cacheWrite,
3516
+ input: cost.input,
3517
+ output: cost.output,
3518
+ total: cost.total
3519
+ },
3520
+ input: usage.input,
3521
+ output: usage.output,
3522
+ totalTokens
3523
+ };
3524
+ };
3525
+ var combineAdvisorAndClassifierUsage = (advisor, classifier) => {
3526
+ if (!(advisor || classifier)) {
3527
+ return;
3528
+ }
3529
+ const left = advisor ? cleanUsage(advisor) : undefined;
3530
+ const right = classifier ? cleanUsage(classifier) : undefined;
3531
+ if (!left) {
3532
+ return right;
3533
+ }
3534
+ if (!right) {
3535
+ return left;
3536
+ }
3537
+ return {
3538
+ cacheRead: left.cacheRead + right.cacheRead,
3539
+ cacheWrite: left.cacheWrite + right.cacheWrite,
3540
+ cost: {
3541
+ cacheRead: left.cost.cacheRead + right.cost.cacheRead,
3542
+ cacheWrite: left.cost.cacheWrite + right.cost.cacheWrite,
3543
+ input: left.cost.input + right.cost.input,
3544
+ output: left.cost.output,
3545
+ total: left.cost.total + right.cost.input + right.cost.cacheRead + right.cost.cacheWrite
3546
+ },
3547
+ input: left.input + right.input,
3548
+ output: left.output + right.output,
3549
+ totalTokens: left.totalTokens + right.totalTokens
3550
+ };
3551
+ };
3490
3552
  var advisorUsageForPi = (usage) => {
3491
3553
  const complete = completeUsageSnapshot(usage);
3492
3554
  if (!complete) {
@@ -3498,8 +3560,6 @@ var advisorUsageForPi = (usage) => {
3498
3560
  const output = snapshot.output ?? 0;
3499
3561
  const cacheRead = snapshot.cacheRead ?? 0;
3500
3562
  const cacheWrite = snapshot.cacheWrite ?? 0;
3501
- const cacheWrite1h = finite(complete.usage.cacheWrite1h);
3502
- const reasoning = finite(complete.usage.reasoning);
3503
3563
  const piUsage = {
3504
3564
  cacheRead,
3505
3565
  cacheWrite,
@@ -3514,6 +3574,8 @@ var advisorUsageForPi = (usage) => {
3514
3574
  output,
3515
3575
  totalTokens: snapshot.totalTokens ?? input + output + cacheRead + cacheWrite
3516
3576
  };
3577
+ const cacheWrite1h = finite(complete.usage.cacheWrite1h);
3578
+ const reasoning = finite(complete.usage.reasoning);
3517
3579
  if (cacheWrite1h !== undefined) {
3518
3580
  piUsage.cacheWrite1h = cacheWrite1h;
3519
3581
  }
@@ -3559,17 +3621,16 @@ var formatTokenCount = (value) => {
3559
3621
  }
3560
3622
  return `${Math.round(value / 1e6)}M`;
3561
3623
  };
3562
- var formatTokens = formatTokenCount;
3563
3624
  var formatCost = (value) => `$${value.toFixed(4)}`;
3564
3625
  var formatUsageFields = (usage) => {
3565
3626
  const tokens = [
3566
- usage.input === undefined ? undefined : `↑${formatTokens(usage.input)}`,
3567
- usage.output === undefined ? undefined : `↓${formatTokens(usage.output)}`,
3568
- usage.cacheRead === undefined ? undefined : `cr:${formatTokens(usage.cacheRead)}`,
3569
- usage.cacheWrite === undefined ? undefined : `cw:${formatTokens(usage.cacheWrite)}`
3627
+ usage.input === undefined ? undefined : `↑${formatTokenCount(usage.input)}`,
3628
+ usage.output === undefined ? undefined : `↓${formatTokenCount(usage.output)}`,
3629
+ usage.cacheRead === undefined ? undefined : `cr:${formatTokenCount(usage.cacheRead)}`,
3630
+ usage.cacheWrite === undefined ? undefined : `cw:${formatTokenCount(usage.cacheWrite)}`
3570
3631
  ].filter((value) => value !== undefined);
3571
3632
  if (tokens.length === 0 && usage.totalTokens !== undefined) {
3572
- tokens.push(`tokens:${formatTokens(usage.totalTokens)}`);
3633
+ tokens.push(`tokens:${formatTokenCount(usage.totalTokens)}`);
3573
3634
  }
3574
3635
  if (usage.cost !== undefined) {
3575
3636
  tokens.push(formatCost(usage.cost));
@@ -3583,18 +3644,13 @@ var formatAdvisorUsage = (usage) => {
3583
3644
  var formatAdvisorUsageTotals = (totals) => {
3584
3645
  const usage = formatUsageFields(totals);
3585
3646
  const missing = totals.calls - totals.knownCalls;
3586
- const parts = [
3587
- usage,
3588
- missing > 0 ? `${missing} without usage data` : undefined
3589
- ];
3590
- return parts.filter((value) => value !== undefined).join(" · ") || "unavailable";
3647
+ return [usage, missing > 0 ? `${missing} without usage data` : undefined].filter((value) => value !== undefined).join(" · ") || "unavailable";
3591
3648
  };
3592
3649
  var formatAdvisorUsageStatus = (totals) => {
3593
3650
  if (totals.calls === 0) {
3594
3651
  return;
3595
3652
  }
3596
- const label = `Advisor: ${totals.calls} call${totals.calls === 1 ? "" : "s"}`;
3597
- return `${label} · ${formatAdvisorUsageTotals(totals)}`;
3653
+ return `Advisor: ${totals.calls} call${totals.calls === 1 ? "" : "s"} · ${formatAdvisorUsageTotals(totals)}`;
3598
3654
  };
3599
3655
 
3600
3656
  // src/scout.ts
@@ -3849,7 +3905,7 @@ var curateAdvisorConversation = async (ctx, legacyConversation, signal, onScout,
3849
3905
  omittedBeforeScout: 0,
3850
3906
  selectedCount: 0
3851
3907
  },
3852
- model: executorRef,
3908
+ model: effectiveExecutorRef(ctx),
3853
3909
  ok: false
3854
3910
  };
3855
3911
  onScout?.({ outcome: scout, type: "fallback" });
@@ -4829,7 +4885,7 @@ var savingsLine = (costs, skipped) => {
4829
4885
  var formatJevTokens = (usage) => `↑${formatTokenCount(usage.inputTokens + usage.outputTokens)}`;
4830
4886
  var jevCostText = (usage) => {
4831
4887
  if (usage.unavailableCostCalls > 0) {
4832
- return usage.knownCostCalls > 0 ? `cost unavailable (known-provider estimates $${usage.cost.toFixed(4)}; Decisions billing unconfirmed)` : "cost unavailable (Decisions billing unconfirmed)";
4888
+ return usage.knownCostCalls > 0 ? `cost unavailable (known catalog-priced usage $${usage.cost.toFixed(4)})` : "cost unavailable (classifier usage was not reported)";
4833
4889
  }
4834
4890
  return `$${usage.cost.toFixed(4)}`;
4835
4891
  };
@@ -4914,7 +4970,7 @@ class AdvisorJevLedgerState {
4914
4970
  lines.push(filterLine(filter));
4915
4971
  const jevTokens = usage.inputTokens + usage.outputTokens;
4916
4972
  if (jevTokens > 0 || usage.unavailableCostCalls > 0) {
4917
- const cost = usage.unavailableCostCalls > 0 ? jevCostText(usage) : `$${usage.cost.toFixed(4)} (input only; output free)`;
4973
+ const cost = usage.unavailableCostCalls > 0 ? jevCostText(usage) : `$${usage.cost.toFixed(4)} (catalog-priced input/cache; output free)`;
4918
4974
  lines.push(`Jev/Decisions cost: ${formatJevTokens(usage)} tokens · ${cost}`);
4919
4975
  }
4920
4976
  if (filter.skipped > 0) {
@@ -5448,11 +5504,9 @@ var resolveActivationModels = async (runtime, ctx, canContinue) => {
5448
5504
  if (!canContinue()) {
5449
5505
  return { cancelled: true };
5450
5506
  }
5451
- const executor = findConfiguredModel(ctx, executorRef);
5452
- if (!executor) {
5453
- return {
5454
- error: executorRef ? `Executor model not found: ${executorRef}` : "Executor model not configured"
5455
- };
5507
+ const executor = executorRef ? findConfiguredModel(ctx, executorRef) : undefined;
5508
+ if (executorRef && !executor) {
5509
+ return { error: `Executor model not found: ${executorRef}` };
5456
5510
  }
5457
5511
  const advisor = findConfiguredModel(ctx, advisorRef);
5458
5512
  if (!advisor) {
@@ -5467,7 +5521,7 @@ var resolveActivationModels = async (runtime, ctx, canContinue) => {
5467
5521
  if (!(advisorAuth.ok && advisorAuth.apiKey)) {
5468
5522
  return { error: `No API key for Advisor ${advisorRef}` };
5469
5523
  }
5470
- if (!isMarkedSubagent() && !await runtime.setExecutorModel(executor)) {
5524
+ if (executor && !isMarkedSubagent() && !await runtime.setExecutorModel(executor)) {
5471
5525
  return { error: `No API key for Executor ${executorRef}` };
5472
5526
  }
5473
5527
  return {};
@@ -5571,7 +5625,7 @@ var activateAdvisor = async (runtime, args, ctx, announce = true) => {
5571
5625
  runtime.pi.setThinkingLevel(executorEffortRef);
5572
5626
  }
5573
5627
  setAdvisorToolsActive(runtime.pi, true);
5574
- const activeModel = isMarkedSubagent() ? ctx.model : findConfiguredModel(ctx, executorRef);
5628
+ const activeModel = followsSessionExecutor() ? ctx.model : findConfiguredModel(ctx, executorRef);
5575
5629
  runtime.updateSameModelNotice(ctx, activeModel);
5576
5630
  if (announce) {
5577
5631
  const activeExecutorRef = effectiveExecutorRef(ctx);
@@ -5614,6 +5668,9 @@ var registerCommandLifecycle = (runtime, activateAdvisor) => {
5614
5668
  return;
5615
5669
  }
5616
5670
  const selected = `${event.model.provider}/${event.model.id}`;
5671
+ if (!getPersistedModelRefs().executor) {
5672
+ return;
5673
+ }
5617
5674
  if (!runtime.flowEnabled()) {
5618
5675
  runtime.pendingExecutorModelRef = selected;
5619
5676
  return;
@@ -5957,556 +6014,59 @@ class ManualAdvisorDialog {
5957
6014
  }
5958
6015
  }
5959
6016
 
5960
- // src/jev/failure.ts
5961
- class JevFailureError extends Error {
5962
- category;
5963
- constructor(category, message) {
5964
- super(message);
5965
- this.name = "JevFailureError";
5966
- this.category = category;
5967
- }
5968
- }
5969
-
5970
- // src/jev/decisions-client.ts
5971
- var OPENAI_DECISIONS_ENDPOINT = "https://api.openai.com/v1/decisions";
5972
- var OPENAI_DECISIONS_MODEL = "gpt-6-luna";
5973
- var formatEntry = (entry) => {
5974
- if (isString(entry)) {
5975
- return entry;
5976
- }
5977
- return entry === undefined ? "" : JSON.stringify(entry);
5978
- };
5979
- var predicateInstructions = (question) => {
5980
- const parts = [formatEntry(question.instructions)];
5981
- if (question.type === "noul") {
5982
- if (question.criteria?.true !== undefined) {
5983
- parts.push(`A true answer means: ${formatEntry(question.criteria.true)}`);
5984
- }
5985
- if (question.criteria?.false !== undefined) {
5986
- parts.push(`A false answer means: ${formatEntry(question.criteria.false)}`);
5987
- }
5988
- }
5989
- return parts.filter(Boolean).join(`
5990
-
5991
- `);
5992
- };
5993
- var scoreLevelLabel = (description, index) => {
5994
- const text = formatEntry(description);
5995
- const colon = text.indexOf(":");
5996
- const label = (colon === -1 ? text : text.slice(0, colon)).trim();
5997
- return label || `Level ${index}`;
5998
- };
5999
- var decisionQuestion = (name, question) => {
6000
- if (question.type === "noul") {
6001
- return {
6002
- instructions: predicateInstructions(question),
6003
- name,
6004
- type: "predicate"
6005
- };
6006
- }
6007
- if (question.type === "score") {
6008
- const labels = new Set;
6009
- const levels = question.criteria.map((description, index) => {
6010
- const label = scoreLevelLabel(description, index);
6011
- if (labels.has(label)) {
6012
- throw new JevFailureError("malformed", `Jev score question ${name} has duplicate level labels.`);
6013
- }
6014
- labels.add(label);
6015
- return { description: formatEntry(description), label };
6016
- });
6017
- return {
6018
- instructions: formatEntry(question.instructions),
6019
- levels,
6020
- name,
6021
- type: "score"
6022
- };
6023
- }
6024
- throw new JevFailureError("malformed", `Jev question ${name} has an unsupported type.`);
6025
- };
6026
- var formatDecisionsInput = (state) => {
6027
- if (isString(state)) {
6028
- return state;
6029
- }
6030
- return JSON.stringify(state, null, 2);
6031
- };
6032
- var buildDecisionsRequest = (state, questions) => {
6033
- if (!isRecordOf(questions) || Object.keys(questions).length === 0) {
6034
- throw new JevFailureError("malformed", "Jev questions are empty.");
6035
- }
6036
- return {
6037
- input: formatDecisionsInput(state),
6038
- model: OPENAI_DECISIONS_MODEL,
6039
- questions: Object.entries(questions).map(([name, question]) => decisionQuestion(name, question))
6040
- };
6041
- };
6042
-
6043
- // src/jev/decisions-response.ts
6044
- var malformedResponse = (detail) => new JevFailureError("malformed", `OpenAI Decisions response ${detail}.`);
6045
- var boundedProbability = (value) => isNumber(value) && Number.isFinite(value) && value >= 0 && value <= 1 ? value : undefined;
6046
- var normalizePredicateAnswer = (answer) => {
6047
- const probability = boundedProbability(answer.probability);
6048
- if (probability === undefined) {
6049
- throw malformedResponse("has an invalid predicate probability");
6050
- }
6051
- return { noul: probability, type: "noul" };
6052
- };
6053
- var normalizeScoreAnswer = (answer, question) => {
6054
- if (!Array.isArray(answer.probabilities)) {
6055
- throw malformedResponse("has no score probability array");
6056
- }
6057
- if (answer.probabilities.length !== question.levels.length) {
6058
- throw malformedResponse("has an incomplete score probability array");
6059
- }
6060
- const probabilities = {};
6061
- const legend = {};
6062
- const seenLabels = new Set;
6063
- const seenValues = new Set;
6064
- let probabilityTotal = 0;
6065
- for (const entry of answer.probabilities) {
6066
- if (!isRecord(entry)) {
6067
- throw malformedResponse("has an invalid score probability entry");
6068
- }
6069
- const { label, value } = entry;
6070
- const probability = boundedProbability(entry.probability);
6071
- if (!isString(label) || !isNumber(value) || !Number.isSafeInteger(value) || value < 0 || value >= question.levels.length || probability === undefined || seenLabels.has(label) || seenValues.has(value)) {
6072
- throw malformedResponse("has an invalid or duplicate score level");
6073
- }
6074
- const level = question.levels[value];
6075
- if (label !== level.label) {
6076
- throw malformedResponse("has an ambiguous score label/value pair");
6077
- }
6078
- seenLabels.add(label);
6079
- seenValues.add(value);
6080
- probabilities[String(value)] = probability;
6081
- legend[String(value)] = level.description;
6082
- probabilityTotal += probability;
6083
- }
6084
- if (Math.abs(probabilityTotal - 1) > 0.02 || question.levels.some((level, index) => !seenValues.has(index) || !seenLabels.has(level.label))) {
6085
- throw malformedResponse("has an incomplete or ambiguous score distribution");
6086
- }
6087
- return { legend, probabilities, type: "score" };
6088
- };
6089
- var usageTokenCount = (value) => isNumber(value) && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
6090
- var parseDecisionsApiResponse = async (response) => {
6091
- let value;
6092
- try {
6093
- value = await response.json();
6094
- } catch {
6095
- throw malformedResponse("was not valid JSON");
6096
- }
6097
- if (!isRecord(value)) {
6098
- throw malformedResponse("is not an object");
6099
- }
6100
- const { answers: rawAnswers, model, usage } = value;
6101
- if (!Array.isArray(rawAnswers)) {
6102
- throw malformedResponse("did not include an answers array");
6103
- }
6104
- if (!isRecord(usage)) {
6105
- throw malformedResponse("has malformed usage");
6106
- }
6107
- if (model !== undefined && !isString(model)) {
6108
- throw malformedResponse("has an invalid model name");
6109
- }
6110
- const answers = [];
6111
- for (const answer of rawAnswers) {
6112
- if (!isRecord(answer)) {
6113
- throw malformedResponse("contains an invalid answer");
6114
- }
6115
- answers.push(answer);
6116
- }
6117
- return { answers, model: isString(model) ? model : undefined, usage };
6118
- };
6119
- var normalizeAnswers = (responseAnswers, questions) => {
6120
- const expected = new Map(questions.map((question) => [question.name, question]));
6121
- if (expected.size !== questions.length || expected.size === 0) {
6122
- throw malformedResponse("has duplicate or missing requested question names");
6123
- }
6124
- const received = new Map;
6125
- for (const answer of responseAnswers) {
6126
- const { name } = answer;
6127
- if (!isString(name) || !name) {
6128
- throw malformedResponse("contains an unnamed answer");
6129
- }
6130
- if (!expected.has(name)) {
6131
- throw malformedResponse("contains an unexpected answer");
6132
- }
6133
- if (received.has(name)) {
6134
- throw malformedResponse("contains duplicate answer names");
6135
- }
6136
- if (answer.type === "refusal") {
6137
- throw malformedResponse("contains a refusal");
6138
- }
6139
- received.set(name, answer);
6140
- }
6141
- if (received.size !== expected.size) {
6142
- throw malformedResponse("is missing one or more named answers");
6143
- }
6144
- const answers = {};
6145
- for (const question of questions) {
6146
- const answer = received.get(question.name);
6147
- if (!answer || answer.type !== question.type) {
6148
- throw malformedResponse("has an answer with the wrong type");
6149
- }
6150
- answers[question.name] = question.type === "predicate" ? normalizePredicateAnswer(answer) : normalizeScoreAnswer(answer, question);
6151
- }
6152
- return answers;
6153
- };
6154
- var normalizeDecisionsResponse = (response, questions) => {
6155
- const inputTokens = usageTokenCount(response.usage.input_tokens);
6156
- const outputTokens = usageTokenCount(response.usage.output_tokens);
6157
- if (inputTokens === undefined || outputTokens === undefined) {
6158
- throw malformedResponse("has malformed usage");
6159
- }
6160
- return {
6161
- answers: normalizeAnswers(response.answers, questions),
6162
- model: response.model || OPENAI_DECISIONS_MODEL,
6163
- usage: { inputTokens, outputTokens }
6164
- };
6165
- };
6166
-
6167
- // src/jev/client.ts
6168
- var FIXED_ENDPOINTS = {
6169
- "openai-decisions": OPENAI_DECISIONS_ENDPOINT,
6170
- openrouter: "https://openrouter.ai/api/alpha/decisions",
6171
- typesafe: "https://api.typesafe.ai/v1/systemone"
6172
- };
6173
- var range = (from, to) => Array.from({ length: to - from + 1 }, (_, index) => from + index);
6174
- var RETRYABLE_STATUSES = new Set([408, 429, ...range(500, 599)]);
6175
- var RETRY_BACKOFF_MS = 250;
6176
- var MAX_ATTEMPTS = 2;
6177
- var finiteTokens = (value) => isNumber(value) && Number.isFinite(value) && value >= 0 ? value : 0;
6178
- var errorDetail = (error) => {
6179
- if (isString(error)) {
6180
- return error;
6181
- }
6182
- if (isRecordOf(error) && "message" in error) {
6183
- return String(error.message);
6184
- }
6185
- return "";
6186
- };
6187
- var statusCategory = (status) => {
6188
- if (status === 401 || status === 403) {
6189
- return "auth";
6190
- }
6191
- if (status === 400 || status === 422) {
6192
- return "malformed";
6193
- }
6194
- return "error";
6195
- };
6196
- var openRouterModelId = (model) => model.includes("/") ? model : `~typesafe/${model}`;
6197
- var buildClientRequest = (transport, model, state, questions) => {
6198
- if (transport === "openai-decisions") {
6199
- const request = buildDecisionsRequest(state, questions);
6200
- return {
6201
- body: JSON.stringify(request),
6202
- decisionQuestions: request.questions
6203
- };
6204
- }
6205
- return {
6206
- body: JSON.stringify({ model, questions, state })
6207
- };
6208
- };
6209
- var connectionFailure = (error) => {
6210
- const message = redactSecrets(error instanceof Error ? error.message : String(error));
6211
- return {
6212
- failure: new JevFailureError("network", `Jev connection failed: ${message}`)
6213
- };
6214
- };
6215
- var sleepWithAbort = (signal, ms) => {
6216
- if (signal.aborted) {
6217
- return Promise.resolve();
6218
- }
6219
- return new Promise((resolve) => {
6220
- const timer = setTimeout(resolve, ms);
6221
- timer.unref?.();
6222
- signal.addEventListener("abort", () => {
6223
- clearTimeout(timer);
6224
- resolve();
6225
- }, { once: true });
6226
- });
6227
- };
6228
-
6229
- class JevClient {
6230
- #apiKey;
6231
- #endpoint;
6232
- #fetch;
6233
- #model;
6234
- #pricePerMtok;
6235
- #timeoutMs;
6236
- #transport;
6237
- constructor({
6238
- apiKey,
6239
- baseUrl,
6240
- fetch,
6241
- model,
6242
- pricePerMtok,
6243
- timeoutMs,
6244
- transport
6245
- }) {
6246
- this.#apiKey = apiKey;
6247
- if (transport === "typesafe-compatible") {
6248
- if (!baseUrl) {
6249
- throw new JevFailureError("malformed", "The System One–compatible endpoint has no Base URL.");
6250
- }
6251
- this.#endpoint = jevSystemOneEndpoint(baseUrl);
6252
- } else {
6253
- this.#endpoint = FIXED_ENDPOINTS[transport];
6254
- }
6255
- this.#fetch = fetch ?? globalThis.fetch.bind(globalThis);
6256
- if (transport === "openai-decisions") {
6257
- this.#model = OPENAI_DECISIONS_MODEL;
6258
- } else if (transport === "openrouter") {
6259
- this.#model = openRouterModelId(model);
6260
- } else {
6261
- this.#model = model;
6262
- }
6263
- this.#pricePerMtok = pricePerMtok;
6264
- this.#timeoutMs = timeoutMs;
6265
- this.#transport = transport;
6266
- }
6267
- async ask(state, questions, signal) {
6268
- const { body, decisionQuestions } = buildClientRequest(this.#transport, this.#model, state, questions);
6269
- const deadline = new AbortController;
6270
- const abortFromCaller = () => deadline.abort(signal?.reason);
6271
- signal?.addEventListener("abort", abortFromCaller, { once: true });
6272
- if (signal?.aborted) {
6273
- abortFromCaller();
6274
- }
6275
- let deadlineHit = false;
6276
- const timer = setTimeout(() => {
6277
- deadlineHit = true;
6278
- deadline.abort(new Error("Jev wall-time budget elapsed"));
6279
- }, this.#timeoutMs);
6280
- timer.unref?.();
6281
- try {
6282
- let outcome = {};
6283
- for (let attempt = 1;; attempt += 1) {
6284
- outcome = await this.#attempt(body, deadline.signal, decisionQuestions);
6285
- if (!outcome.retryable || attempt >= MAX_ATTEMPTS || deadline.signal.aborted) {
6286
- break;
6287
- }
6288
- await sleepWithAbort(deadline.signal, RETRY_BACKOFF_MS);
6289
- if (deadline.signal.aborted) {
6290
- break;
6291
- }
6292
- }
6293
- return this.#settle(outcome, deadlineHit, signal);
6294
- } catch (error) {
6295
- if (signal?.aborted && !deadlineHit) {
6296
- throw error;
6297
- }
6298
- if (error instanceof JevFailureError) {
6299
- throw error;
6300
- }
6301
- const message = redactSecrets(error instanceof Error ? error.message : String(error));
6302
- throw deadlineHit ? new JevFailureError("timeout", `Jev call exceeded its ${this.#timeoutMs} ms wall-time budget.`) : new JevFailureError("error", message);
6303
- } finally {
6304
- clearTimeout(timer);
6305
- signal?.removeEventListener("abort", abortFromCaller);
6306
- }
6307
- }
6308
- #settle(outcome, deadlineHit, signal) {
6309
- if (outcome.answers) {
6310
- return this.#result(outcome);
6311
- }
6312
- if (deadlineHit && outcome.failure?.category !== "auth") {
6313
- throw new JevFailureError("timeout", `Jev call exceeded its ${this.#timeoutMs} ms wall-time budget.`);
6314
- }
6315
- if (signal?.aborted) {
6316
- throw new Error("Jev call aborted by the caller.");
6317
- }
6318
- if (outcome.failure) {
6319
- throw outcome.failure;
6320
- }
6321
- throw new JevFailureError("error", "Jev call failed.");
6322
- }
6323
- async#attempt(body, signal, decisionQuestions) {
6324
- if (signal.aborted) {
6325
- return { retryable: false };
6326
- }
6327
- let response;
6328
- try {
6329
- response = await this.#fetch(this.#endpoint, {
6330
- body,
6331
- headers: {
6332
- authorization: `Bearer ${this.#apiKey}`,
6333
- "content-type": "application/json"
6334
- },
6335
- method: "POST",
6336
- signal
6337
- });
6338
- } catch (error) {
6339
- if (signal.aborted) {
6340
- return { retryable: false };
6341
- }
6342
- return {
6343
- retryable: true,
6344
- ...connectionFailure(error)
6345
- };
6346
- }
6347
- if (response.ok) {
6348
- return this.#parseSuccess(response, decisionQuestions);
6349
- }
6350
- const failure = await this.#failureFromStatus(response);
6351
- return {
6352
- failure,
6353
- retryable: RETRYABLE_STATUSES.has(response.status)
6354
- };
6355
- }
6356
- async#failureFromStatus(response) {
6357
- let detail = "";
6358
- try {
6359
- const parsed = await response.json();
6360
- const error = isRecord(parsed) ? parsed.error : undefined;
6361
- detail = errorDetail(error);
6362
- } catch {
6363
- detail = "";
6364
- }
6365
- const message = redactSecrets(`Jev ${this.#transportLabel()} request failed with HTTP ${response.status}${detail ? `: ${detail}` : ""}.`);
6366
- return new JevFailureError(statusCategory(response.status), message);
6367
- }
6368
- #transportLabel() {
6369
- if (this.#transport === "openrouter") {
6370
- return "OpenRouter";
6371
- }
6372
- if (this.#transport === "openai-decisions") {
6373
- return "OpenAI Decisions";
6374
- }
6375
- return this.#transport === "typesafe" ? "TypeSafe" : "endpoint";
6376
- }
6377
- async#parseSuccess(response, decisionQuestions) {
6378
- if (this.#transport === "openai-decisions") {
6379
- const normalized = normalizeDecisionsResponse(await parseDecisionsApiResponse(response), decisionQuestions ?? []);
6380
- return {
6381
- answers: normalized.answers,
6382
- model: normalized.model,
6383
- usage: {
6384
- input_tokens: normalized.usage.inputTokens,
6385
- output_tokens: normalized.usage.outputTokens
6386
- }
6387
- };
6388
- }
6389
- let parsed;
6390
- try {
6391
- parsed = await response.json();
6392
- } catch (error) {
6393
- return {
6394
- failure: new JevFailureError("malformed", `Jev response was not JSON: ${redactSecrets(error instanceof Error ? error.message : String(error))}`)
6395
- };
6396
- }
6397
- if (!isRecord(parsed) || !isRecord(parsed.answers)) {
6398
- return {
6399
- failure: new JevFailureError("malformed", "Jev response did not include an answers object.")
6400
- };
6401
- }
6402
- return {
6403
- answers: parsed.answers,
6404
- model: isString(parsed.model) ? parsed.model : this.#model,
6405
- usage: isRecordOf(parsed.usage) ? {
6406
- input_tokens: parsed.usage.input_tokens,
6407
- output_tokens: parsed.usage.output_tokens
6408
- } : undefined
6409
- };
6410
- }
6411
- #result(outcome) {
6412
- const { usage } = outcome;
6413
- const inputTokens = finiteTokens(usage?.input_tokens);
6414
- const outputTokens = finiteTokens(usage?.output_tokens);
6415
- const price = this.#pricePerMtok ?? advisorJevPricePerMtokRef;
6416
- return {
6417
- answers: outcome.answers ?? {},
6418
- model: outcome.model ?? this.#model,
6419
- usage: {
6420
- cost: this.#transport === "openai-decisions" ? undefined : inputTokens / 1e6 * price,
6421
- inputTokens,
6422
- outputTokens
6423
- }
6424
- };
6425
- }
6426
- }
6427
- var jevClientFromCredentials = (credentials, fetch) => new JevClient({
6428
- apiKey: credentials.apiKey,
6429
- baseUrl: credentials.baseUrl,
6430
- fetch,
6431
- model: advisorJevModelRef,
6432
- timeoutMs: advisorJevTimeoutMsRef,
6433
- transport: credentials.transport
6434
- });
6435
-
6436
- // src/jev/key-store.ts
6437
- import {
6438
- chmodSync,
6439
- existsSync as existsSync3,
6440
- readFileSync as readFileSync3,
6441
- rmSync,
6442
- writeFileSync as writeFileSync2
6443
- } from "node:fs";
6017
+ // src/jev/classifier-key-store.ts
6018
+ import { chmodSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
6444
6019
  import { join as join4 } from "node:path";
6445
6020
  import { getAgentDir as getAgentDir4 } from "@earendil-works/pi-coding-agent";
6446
- var TYPESAFE_KEY_ENV_VAR = "TYPESAFE_API_KEY";
6447
- var TYPESAFE_KEY_SERVICE = "pi-advisor";
6448
- var TYPESAFE_KEY_NAME = "typesafe-api-key";
6449
- var TYPESAFE_KEY_CONFIG_FIELD = "typesafe_api_key";
6021
+ var JEV_CLASSIFIER_KEY_SERVICE = "pi-advisor-jev-classifier";
6022
+ var JEV_CLASSIFIER_KEY_NAME = "classifier-api-key";
6450
6023
  var KEY_FILE_MODE = 384;
6451
- var keyFilePath = () => join4(getAgentDir4(), "typesafe_api_key");
6024
+ var keyFilePath = () => join4(getAgentDir4(), "jev_classifier_api_key");
6025
+ var classifierKeyFailClosed = false;
6026
+ var disableJevClassifierKeyForRuntime = () => {
6027
+ classifierKeyFailClosed = true;
6028
+ };
6029
+ var enableJevClassifierKeyForRuntime = () => {
6030
+ classifierKeyFailClosed = false;
6031
+ };
6452
6032
  var runtimeSecrets = () => {
6453
6033
  const bun = globalThis;
6454
6034
  return bun.Bun?.secrets;
6455
6035
  };
6456
- var normalizeKey = (value) => value?.trim() || undefined;
6457
- var readAdvisorJsonConfig = () => readExistingConfig(join4(getAgentDir4(), "advisor.json"));
6458
- var defaultReadFileStore = () => {
6036
+ var defaultReadFile = () => {
6459
6037
  try {
6460
- return normalizeKey(readFileSync3(keyFilePath(), "utf-8"));
6038
+ return readFileSync3(keyFilePath(), "utf-8").trim() || undefined;
6461
6039
  } catch {
6462
6040
  return;
6463
6041
  }
6464
6042
  };
6465
- var defaultWriteFileStore = (key) => {
6043
+ var defaultWriteFile = (key) => {
6466
6044
  const path = keyFilePath();
6467
6045
  writeFileSync2(path, `${key}
6468
6046
  `, { mode: KEY_FILE_MODE });
6469
6047
  chmodSync(path, KEY_FILE_MODE);
6470
6048
  };
6471
- var defaultDeleteFileStore = () => {
6472
- rmSync(keyFilePath(), { force: true });
6473
- };
6474
- var messageOf = (error) => redactSecrets(error instanceof Error ? error.message : String(error));
6475
- var resolveTypeSafeKey = async (deps = {}) => {
6049
+ var readJevClassifierKey = async (deps = {}) => {
6476
6050
  const secrets = deps.secrets === undefined ? runtimeSecrets() : deps.secrets;
6477
6051
  if (secrets) {
6478
6052
  try {
6479
- const stored = normalizeKey(await secrets.get({
6480
- name: TYPESAFE_KEY_NAME,
6481
- service: TYPESAFE_KEY_SERVICE
6482
- }));
6483
- if (stored) {
6484
- return { key: stored, source: "bun-secrets" };
6053
+ const storedValue = await secrets.get({
6054
+ name: JEV_CLASSIFIER_KEY_NAME,
6055
+ service: JEV_CLASSIFIER_KEY_SERVICE
6056
+ });
6057
+ const key = storedValue?.trim();
6058
+ if (key) {
6059
+ return { key, source: "bun-secrets" };
6485
6060
  }
6486
- } catch {}
6487
- }
6488
- const env = deps.env ?? process.env;
6489
- const fromEnv = normalizeKey(env[TYPESAFE_KEY_ENV_VAR]);
6490
- if (fromEnv) {
6491
- return { key: fromEnv, source: "env" };
6492
- }
6493
- const readFileStore = deps.readFileStore ?? defaultReadFileStore;
6494
- const fromFile = normalizeKey(readFileStore());
6495
- if (fromFile) {
6496
- return { key: fromFile, source: "file" };
6497
- }
6498
- const config = (deps.readAdvisorJson ?? readAdvisorJsonConfig)();
6499
- const staged = config[TYPESAFE_KEY_CONFIG_FIELD];
6500
- if (isString(staged)) {
6501
- const fromConfig = normalizeKey(staged);
6502
- if (fromConfig) {
6503
- return { key: fromConfig, source: "advisor-json" };
6061
+ } catch {
6062
+ return { failed: true };
6504
6063
  }
6505
6064
  }
6506
- return {};
6065
+ const key = (deps.readFile ?? defaultReadFile)();
6066
+ return key ? { key, source: "file" } : {};
6507
6067
  };
6508
- var writeKeyTypeSafeKey = async (key, deps = {}) => {
6509
- const normalized = normalizeKey(key);
6068
+ var writeJevClassifierKey = async (key, deps = {}) => {
6069
+ const normalized = key.trim();
6510
6070
  if (!normalized) {
6511
6071
  return { message: "The key is empty.", ok: false };
6512
6072
  }
@@ -6514,100 +6074,86 @@ var writeKeyTypeSafeKey = async (key, deps = {}) => {
6514
6074
  if (secrets) {
6515
6075
  try {
6516
6076
  await secrets.set({
6517
- name: TYPESAFE_KEY_NAME,
6518
- service: TYPESAFE_KEY_SERVICE,
6077
+ name: JEV_CLASSIFIER_KEY_NAME,
6078
+ service: JEV_CLASSIFIER_KEY_SERVICE,
6519
6079
  value: normalized
6520
6080
  });
6521
- return { message: "Key stored in Bun.secrets.", ok: true };
6522
- } catch (error) {
6081
+ return { message: "Jev classifier key stored securely.", ok: true };
6082
+ } catch {
6523
6083
  return {
6524
- message: `Storing the key in Bun.secrets failed: ${messageOf(error)}. Alternatively set the ${TYPESAFE_KEY_ENV_VAR} environment variable in your shell profile.`,
6084
+ message: "Could not store the Jev classifier key securely.",
6525
6085
  ok: false
6526
6086
  };
6527
6087
  }
6528
6088
  }
6529
6089
  try {
6530
- (deps.writeFileStore ?? defaultWriteFileStore)(normalized);
6090
+ (deps.writeFile ?? defaultWriteFile)(normalized);
6531
6091
  return {
6532
- message: "Key stored in ~/.pi/agent/typesafe_api_key (mode 0600).",
6092
+ message: "Jev classifier key stored in a 0600-mode file.",
6533
6093
  ok: true
6534
6094
  };
6535
- } catch (error) {
6095
+ } catch {
6536
6096
  return {
6537
- message: `Storing the key failed: ${messageOf(error)}. Alternatively set the ${TYPESAFE_KEY_ENV_VAR} environment variable in your shell profile.`,
6097
+ message: "Could not store the Jev classifier key securely.",
6538
6098
  ok: false
6539
6099
  };
6540
6100
  }
6541
6101
  };
6542
- var clearKeyTypeSafeKey = async (deps = {}) => {
6543
- let clearedSomething = false;
6544
- let firstError;
6102
+ var restoreJevClassifierKey = async (previous, deps = {}) => {
6103
+ if (previous.failed) {
6104
+ return false;
6105
+ }
6106
+ if (previous.key) {
6107
+ const result = await writeJevClassifierKey(previous.key, deps);
6108
+ return result.ok;
6109
+ }
6110
+ if (deps.secrets === null && deps.writeFile) {
6111
+ return true;
6112
+ }
6545
6113
  const secrets = deps.secrets === undefined ? runtimeSecrets() : deps.secrets;
6114
+ let secretCleared = true;
6546
6115
  if (secrets) {
6547
6116
  try {
6548
6117
  await secrets.delete({
6549
- name: TYPESAFE_KEY_NAME,
6550
- service: TYPESAFE_KEY_SERVICE
6118
+ name: JEV_CLASSIFIER_KEY_NAME,
6119
+ service: JEV_CLASSIFIER_KEY_SERVICE
6551
6120
  });
6552
- clearedSomething = true;
6553
- } catch (error) {
6554
- firstError = messageOf(error);
6555
- }
6556
- }
6557
- try {
6558
- if (deps.deleteFileStore) {
6559
- deps.deleteFileStore();
6560
- } else if (existsSync3(keyFilePath())) {
6561
- defaultDeleteFileStore();
6121
+ } catch {
6122
+ secretCleared = false;
6562
6123
  }
6563
- clearedSomething = true;
6564
- } catch (error) {
6565
- firstError ??= messageOf(error);
6566
- }
6567
- if (firstError) {
6568
- return {
6569
- message: `Clearing the stored key failed: ${firstError}.`,
6570
- ok: false
6571
- };
6572
6124
  }
6573
- return {
6574
- message: `Stored key cleared.${clearedSomething ? "" : ` Nothing was stored; unset ${TYPESAFE_KEY_ENV_VAR} and remove ${TYPESAFE_KEY_CONFIG_FIELD} from advisor.json yourself if you use them.`}`,
6575
- ok: true
6576
- };
6577
- };
6578
- var removeTypeSafeKeyFromAdvisorJson = () => {
6579
6125
  try {
6580
- const path = join4(getAgentDir4(), "advisor.json");
6581
- const existing = readExistingConfig(path);
6582
- if (!(TYPESAFE_KEY_CONFIG_FIELD in existing)) {
6583
- return { message: "No plaintext key in advisor.json.", ok: true };
6126
+ if (deps.secrets === undefined && !secrets) {
6127
+ rmSync(keyFilePath(), { force: true });
6584
6128
  }
6585
- const retained = Object.fromEntries(Object.entries(existing).filter(([key]) => key !== TYPESAFE_KEY_CONFIG_FIELD));
6586
- writeFileSync2(path, `${JSON.stringify(retained, null, 2)}
6587
- `);
6588
- resetConfigCache();
6589
- return { message: "Plaintext key removed from advisor.json.", ok: true };
6590
- } catch (error) {
6591
- return {
6592
- message: `Removing the plaintext key failed: ${messageOf(error)}.`,
6593
- ok: false
6594
- };
6129
+ } catch {
6130
+ return false;
6595
6131
  }
6132
+ return secretCleared;
6596
6133
  };
6597
- var warnedPlaintextKey = false;
6598
- var consumePlaintextKeyWarning = () => {
6599
- if (warnedPlaintextKey) {
6134
+ var consumeJevClassifierKey = async () => {
6135
+ if (classifierKeyFailClosed) {
6600
6136
  return;
6601
6137
  }
6602
- warnedPlaintextKey = true;
6603
- return `Advisor is using a plaintext ${TYPESAFE_KEY_CONFIG_FIELD} from advisor.json; this is not recommended. Open /advisor-settings → Jev/Decisions consultation filter to migrate it into a secure store, or use the ${TYPESAFE_KEY_ENV_VAR} environment variable.`;
6138
+ const stored = await readJevClassifierKey();
6139
+ return stored.key;
6604
6140
  };
6605
6141
 
6606
- // src/jev/questions.ts
6607
- var STAKES_RUBRIC = [
6608
- "Negligible: routine, low-risk, mechanical, or reversible; a wrong call costs little and is easy to undo.",
6609
- "Moderate: some risk or rework, but bounded and recoverable.",
6610
- "High: material consequences for correctness, security, cost, user trust, or irreversibility."
6142
+ // src/jev/failure.ts
6143
+ class JevFailureError extends Error {
6144
+ category;
6145
+ constructor(category, message) {
6146
+ super(message);
6147
+ this.name = "JevFailureError";
6148
+ this.category = category;
6149
+ }
6150
+ }
6151
+
6152
+ // src/jev/questions.ts
6153
+ var STAKES_RUBRIC = [
6154
+ "Negligible: routine, low-risk, mechanical, or reversible; a wrong call costs little and is easy to undo.",
6155
+ "Moderate: some risk or rework, but bounded and recoverable.",
6156
+ "High: material consequences for correctness, security, cost, user trust, or irreversibility."
6611
6157
  ];
6612
6158
  var EVIDENCE_RULE = "Judge from `executor_question` and `executor_draft` when present, otherwise from `recent_conversation`; when both are absent, `recent_conversation` is the evidence to judge from.";
6613
6159
  var screeningQuestions = {
@@ -6625,8 +6171,27 @@ var screeningQuestions = {
6625
6171
  type: "score"
6626
6172
  }
6627
6173
  };
6174
+ var nativeScreeningQuestions = {
6175
+ self_answerable: {
6176
+ criteria: {
6177
+ false: "The executor needs the Advisor's second opinion.",
6178
+ true: "The executor can resolve this alone with available tools and context."
6179
+ },
6180
+ instructions: `Can the executor confidently resolve this request alone, using available tools and context? ${EVIDENCE_RULE}`,
6181
+ type: "bool"
6182
+ },
6183
+ stakes: {
6184
+ criteria: {
6185
+ high: STAKES_RUBRIC[2],
6186
+ moderate: STAKES_RUBRIC[1],
6187
+ negligible: STAKES_RUBRIC[0]
6188
+ },
6189
+ instructions: `How material are the stakes of the decision behind this consultation request? ${EVIDENCE_RULE}`,
6190
+ type: "choice"
6191
+ }
6192
+ };
6628
6193
  var NUMERIC_KEY_PATTERN = /^\d+$/u;
6629
- var finiteNumber = (value) => isNumber(value) && Number.isFinite(value) ? value : undefined;
6194
+ var finiteProbability = (value) => isNumber(value) && Number.isFinite(value) && value >= 0 && value <= 1 ? value : undefined;
6630
6195
  var lowestStakesProbability = (answer) => {
6631
6196
  if (!isRecordOf(answer)) {
6632
6197
  return;
@@ -6636,9 +6201,12 @@ var lowestStakesProbability = (answer) => {
6636
6201
  if (legend) {
6637
6202
  const exact = Object.keys(legend).find((key) => legend[key] === STAKES_RUBRIC[0]);
6638
6203
  if (exact) {
6639
- return finiteNumber(probabilities[exact]);
6204
+ return finiteProbability(probabilities[exact]);
6640
6205
  }
6641
6206
  }
6207
+ if (Object.hasOwn(probabilities, "negligible")) {
6208
+ return finiteProbability(probabilities.negligible);
6209
+ }
6642
6210
  const numericKeys = Object.keys(probabilities).filter((key) => NUMERIC_KEY_PATTERN.test(key));
6643
6211
  if (numericKeys.length === 0) {
6644
6212
  return;
@@ -6649,418 +6217,218 @@ var lowestStakesProbability = (answer) => {
6649
6217
  lowest = key;
6650
6218
  }
6651
6219
  }
6652
- return finiteNumber(probabilities[lowest]);
6220
+ return finiteProbability(probabilities[lowest]);
6221
+ };
6222
+ var selfAnswerableProbability = (answer) => {
6223
+ if (!isRecordOf(answer)) {
6224
+ return;
6225
+ }
6226
+ const value = answer.type === "bool" ? answer.probability : answer.noul;
6227
+ return finiteProbability(value);
6653
6228
  };
6654
- var selfAnswerableNoul = (answer) => isRecordOf(answer) ? finiteNumber(answer.noul) : undefined;
6655
6229
  var composeScreeningVerdict = (answers, { noulMargin, skipConfidence }) => {
6656
6230
  if (!isRecordOf(answers)) {
6657
6231
  return { skip: false };
6658
6232
  }
6659
6233
  const negligibleMass = lowestStakesProbability(answers.stakes);
6660
- const noul = selfAnswerableNoul(answers.self_answerable);
6661
- if (negligibleMass === undefined || noul === undefined) {
6234
+ const selfAnswerable = selfAnswerableProbability(answers.self_answerable);
6235
+ if (negligibleMass === undefined || selfAnswerable === undefined) {
6662
6236
  return { skip: false };
6663
6237
  }
6664
- const confidentlySelfAnswerable = noul >= 0.5 + noulMargin;
6665
6238
  return {
6666
- skip: negligibleMass >= skipConfidence && confidentlySelfAnswerable
6239
+ skip: negligibleMass >= skipConfidence && selfAnswerable >= 0.5 + noulMargin
6667
6240
  };
6668
6241
  };
6669
6242
  var composeTurnGateVerdict = (answers, threshold) => {
6670
6243
  if (!isRecordOf(answers)) {
6671
6244
  return false;
6672
6245
  }
6673
- const answer = answers.should_consult;
6674
- const noul = isRecordOf(answer) ? finiteNumber(answer.noul) : undefined;
6675
- return noul !== undefined && noul >= threshold;
6246
+ const probability = selfAnswerableProbability(answers.should_consult);
6247
+ return probability !== undefined && probability >= threshold;
6676
6248
  };
6677
6249
 
6678
- // src/jev/state.ts
6679
- var JEV_TEXT_CAP_BYTES = 8 * 1024;
6680
- var buildJevState = (ctx, input = {}) => {
6681
- const fields = new Map([["role", "executor"]]);
6682
- if (input.question) {
6683
- fields.set("executor_question", redactAndCapText(input.question, JEV_TEXT_CAP_BYTES, advisorRedactSecretsRef));
6684
- }
6685
- if (input.draft) {
6686
- fields.set("executor_draft", redactAndCapText(input.draft, JEV_TEXT_CAP_BYTES, advisorRedactSecretsRef));
6687
- }
6688
- const digest = recentConversation(ctx, advisorJevDigestMaxCharsRef);
6689
- if (digest) {
6690
- fields.set("recent_conversation", digest);
6691
- }
6692
- return Object.fromEntries(fields);
6250
+ // src/jev/classifier.ts
6251
+ var REF_PATTERN = /^(?<provider>[^/]+)\/(?<modelId>.+)$/u;
6252
+ var parseJevClassifierRef = (ref) => {
6253
+ const match = REF_PATTERN.exec(ref.trim());
6254
+ const provider = match?.groups?.provider;
6255
+ const modelId = match?.groups?.modelId;
6256
+ return provider && modelId ? { modelId, provider } : undefined;
6693
6257
  };
6694
-
6695
- // src/jev/endpoint-key-store.ts
6696
- import {
6697
- chmodSync as chmodSync2,
6698
- existsSync as existsSync4,
6699
- readFileSync as readFileSync4,
6700
- rmSync as rmSync2,
6701
- writeFileSync as writeFileSync3
6702
- } from "node:fs";
6703
- import { join as join5 } from "node:path";
6704
- import { getAgentDir as getAgentDir5 } from "@earendil-works/pi-coding-agent";
6705
- var JEV_ENDPOINT_KEY_ENV_VAR = "JEV_API_KEY";
6706
- var JEV_ENDPOINT_KEY_SERVICE = "pi-advisor";
6707
- var JEV_ENDPOINT_KEY_NAME = "jev-api-key";
6708
- var KEY_FILE_MODE2 = 384;
6709
- var runtimeSecrets2 = () => {
6710
- const bun = globalThis;
6711
- return bun.Bun?.secrets;
6712
- };
6713
- var keyFilePath2 = () => join5(getAgentDir5(), "jev_api_key");
6714
- var normalizeKey2 = (value) => value?.trim() || undefined;
6715
- var readDefaultFileStore = () => {
6716
- try {
6717
- return normalizeKey2(readFileSync4(keyFilePath2(), "utf-8"));
6718
- } catch {
6258
+ var isClassifierModel = (model) => isRecordOf(model) && model.type === "classifier" && typeof model.provider === "string" && typeof model.id === "string" && typeof model.api === "string" && isRecordOf(model.cost);
6259
+ var isProbability = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
6260
+ var normalizedUsage = (usage) => {
6261
+ if (!usage) {
6719
6262
  return;
6720
6263
  }
6721
- };
6722
- var writeDefaultFileStore = (key) => {
6723
- const path = keyFilePath2();
6724
- writeFileSync3(path, `${key}
6725
- `, { mode: KEY_FILE_MODE2 });
6726
- chmodSync2(path, KEY_FILE_MODE2);
6727
- };
6728
- var deleteDefaultFileStore = () => rmSync2(keyFilePath2(), { force: true });
6729
- var messageOf2 = (error) => redactSecrets(error instanceof Error ? error.message : String(error));
6730
- var resolveJevEndpointKey = async (deps = {}) => {
6731
- const secrets = deps.secrets === undefined ? runtimeSecrets2() : deps.secrets;
6732
- if (secrets) {
6733
- try {
6734
- const stored = normalizeKey2(await secrets.get({
6735
- name: JEV_ENDPOINT_KEY_NAME,
6736
- service: JEV_ENDPOINT_KEY_SERVICE
6737
- }));
6738
- if (stored) {
6739
- return { key: stored, source: "jev-bun-secrets" };
6740
- }
6741
- } catch {}
6742
- }
6743
- const env = deps.env ?? process.env;
6744
- const fromEnv = normalizeKey2(env[JEV_ENDPOINT_KEY_ENV_VAR]);
6745
- if (fromEnv) {
6746
- return { key: fromEnv, source: "jev-env" };
6747
- }
6748
- const fromFile = normalizeKey2((deps.readFileStore ?? readDefaultFileStore)());
6749
- return fromFile ? { key: fromFile, source: "jev-file" } : {};
6750
- };
6751
- var writeJevEndpointKey = async (key, deps = {}) => {
6752
- const normalized = normalizeKey2(key);
6753
- if (!normalized) {
6754
- return { message: "The endpoint API key is empty.", ok: false };
6755
- }
6756
- const secrets = deps.secrets === undefined ? runtimeSecrets2() : deps.secrets;
6757
- if (secrets) {
6758
- try {
6759
- await secrets.set({
6760
- name: JEV_ENDPOINT_KEY_NAME,
6761
- service: JEV_ENDPOINT_KEY_SERVICE,
6762
- value: normalized
6763
- });
6764
- return {
6765
- message: "Endpoint API key stored in Bun.secrets.",
6766
- ok: true
6767
- };
6768
- } catch (error) {
6769
- return {
6770
- message: `Storing the endpoint API key in Bun.secrets failed: ${messageOf2(error)}. Alternatively set ${JEV_ENDPOINT_KEY_ENV_VAR} in your shell profile.`,
6771
- ok: false
6772
- };
6773
- }
6774
- }
6775
- try {
6776
- (deps.writeFileStore ?? writeDefaultFileStore)(normalized);
6777
- return {
6778
- message: "Endpoint API key stored in the Pi agent directory (mode 0600).",
6779
- ok: true
6780
- };
6781
- } catch (error) {
6782
- return {
6783
- message: `Storing the endpoint API key failed: ${messageOf2(error)}. Alternatively set ${JEV_ENDPOINT_KEY_ENV_VAR} in your shell profile.`,
6784
- ok: false
6785
- };
6786
- }
6787
- };
6788
- var clearJevEndpointKey = async (deps = {}) => {
6789
- let clearedSomething = false;
6790
- let firstError;
6791
- const secrets = deps.secrets === undefined ? runtimeSecrets2() : deps.secrets;
6792
- if (secrets) {
6793
- try {
6794
- await secrets.delete({
6795
- name: JEV_ENDPOINT_KEY_NAME,
6796
- service: JEV_ENDPOINT_KEY_SERVICE
6797
- });
6798
- clearedSomething = true;
6799
- } catch (error) {
6800
- firstError = messageOf2(error);
6801
- }
6264
+ const inputTokens = usage.input;
6265
+ const outputTokens = usage.output;
6266
+ const inputCost = usage.cost?.input;
6267
+ const cacheReadCost = usage.cost?.cacheRead;
6268
+ const cacheWriteCost = usage.cost?.cacheWrite;
6269
+ if (!Number.isFinite(inputTokens) || inputTokens < 0 || !Number.isFinite(outputTokens) || outputTokens < 0) {
6270
+ return;
6802
6271
  }
6803
- try {
6804
- if (deps.deleteFileStore) {
6805
- deps.deleteFileStore();
6806
- } else if (existsSync4(keyFilePath2())) {
6807
- deleteDefaultFileStore();
6272
+ const completeCost = Number.isFinite(inputCost) && inputCost >= 0 && Number.isFinite(cacheReadCost) && cacheReadCost >= 0 && Number.isFinite(cacheWriteCost) && cacheWriteCost >= 0;
6273
+ const cost = completeCost ? inputCost + cacheReadCost + cacheWriteCost : undefined;
6274
+ const piUsage = completeCost && cost !== undefined ? {
6275
+ ...usage,
6276
+ cost: {
6277
+ ...usage.cost,
6278
+ input: inputCost,
6279
+ output: 0,
6280
+ total: cost
6808
6281
  }
6809
- clearedSomething = true;
6810
- } catch (error) {
6811
- firstError ??= messageOf2(error);
6812
- }
6813
- if (firstError) {
6814
- return {
6815
- message: `Clearing the stored endpoint API key failed: ${firstError}.`,
6816
- ok: false
6817
- };
6818
- }
6819
- return {
6820
- message: `Stored endpoint API key cleared.${clearedSomething ? "" : ` Nothing was stored; unset ${JEV_ENDPOINT_KEY_ENV_VAR} yourself if you use it.`}`,
6821
- ok: true
6822
- };
6823
- };
6824
-
6825
- // src/jev/openai-key-store.ts
6826
- import {
6827
- chmodSync as chmodSync3,
6828
- existsSync as existsSync5,
6829
- readFileSync as readFileSync5,
6830
- rmSync as rmSync3,
6831
- writeFileSync as writeFileSync4
6832
- } from "node:fs";
6833
- import { join as join6 } from "node:path";
6834
- import { getAgentDir as getAgentDir6 } from "@earendil-works/pi-coding-agent";
6835
- var OPENAI_DECISIONS_KEY_SERVICE = "pi-advisor";
6836
- var OPENAI_DECISIONS_KEY_NAME = "openai-decisions-api-key";
6837
- var KEY_FILE_MODE3 = 384;
6838
- var runtimeSecrets3 = () => {
6839
- const bun = globalThis;
6840
- return bun.Bun?.secrets;
6282
+ } : undefined;
6283
+ return { cost, inputTokens, outputTokens, piUsage };
6841
6284
  };
6842
- var keyFilePath3 = () => join6(getAgentDir6(), "openai_api_key");
6843
- var normalizeKey3 = (value) => value?.trim() || undefined;
6844
- var readDefaultFileStore2 = () => {
6845
- try {
6846
- return normalizeKey3(readFileSync5(keyFilePath3(), "utf-8"));
6847
- } catch {
6848
- return;
6285
+ var abortError = () => new DOMException("Jev classifier call aborted by the caller.", "AbortError");
6286
+ var normalizeClassifierAnswers = (result, required) => {
6287
+ if (!isRecordOf(result.answers)) {
6288
+ throw new JevFailureError("malformed", "Classifier returned malformed answers.");
6849
6289
  }
6850
- };
6851
- var writeDefaultFileStore2 = (key) => {
6852
- const path = keyFilePath3();
6853
- writeFileSync4(path, `${key}
6854
- `, { mode: KEY_FILE_MODE3 });
6855
- chmodSync3(path, KEY_FILE_MODE3);
6856
- };
6857
- var deleteDefaultFileStore2 = () => rmSync3(keyFilePath3(), { force: true });
6858
- var messageOf3 = (error) => redactSecrets(error instanceof Error ? error.message : String(error));
6859
- var resolveOpenAIDecisionsKey = async (deps = {}) => {
6860
- const secrets = deps.secrets === undefined ? runtimeSecrets3() : deps.secrets;
6861
- if (secrets) {
6862
- let secretKey;
6863
- try {
6864
- secretKey = normalizeKey3(await secrets.get({
6865
- name: OPENAI_DECISIONS_KEY_NAME,
6866
- service: OPENAI_DECISIONS_KEY_SERVICE
6867
- }));
6868
- } catch {
6869
- secretKey = undefined;
6290
+ const answers = {};
6291
+ for (const name of required) {
6292
+ const answer = result.answers[name];
6293
+ if (isRecordOf(answer) && answer.type === "bool" && isProbability(answer.probability)) {
6294
+ if (name === "self_answerable" || name === "should_consult") {
6295
+ answers[name] = { noul: answer.probability, type: "noul" };
6296
+ } else {
6297
+ throw new JevFailureError("malformed", `Classifier returned an unexpected bool answer for ${name}.`);
6298
+ }
6299
+ continue;
6870
6300
  }
6871
- if (secretKey) {
6872
- return { key: secretKey, source: "openai-bun-secrets" };
6301
+ if (isRecordOf(answer) && answer.type === "choice") {
6302
+ if (!isRecordOf(answer.probabilities) || !isString(answer.choice)) {
6303
+ throw new JevFailureError("malformed", `Classifier returned malformed ${name} choice.`);
6304
+ }
6305
+ const probabilities = {};
6306
+ for (const [label, probability] of Object.entries(answer.probabilities)) {
6307
+ if (!isProbability(probability)) {
6308
+ throw new JevFailureError("malformed", `Classifier returned an invalid ${name} probability.`);
6309
+ }
6310
+ probabilities[label] = probability;
6311
+ }
6312
+ if (name === "stakes") {
6313
+ const expected = ["high", "moderate", "negligible"];
6314
+ const distributionTotal = expected.reduce((sum, label) => sum + (probabilities[label] ?? 0), 0);
6315
+ if (!expected.includes(answer.choice) || expected.some((label) => !Object.hasOwn(probabilities, label)) || distributionTotal <= 0 || Math.abs(distributionTotal - 1) > 0.05) {
6316
+ throw new JevFailureError("malformed", "Classifier returned an incomplete stakes distribution.");
6317
+ }
6318
+ if (!isProbability(answer.confidence)) {
6319
+ throw new JevFailureError("malformed", "Classifier returned invalid stakes confidence.");
6320
+ }
6321
+ answers.stakes = {
6322
+ choice: answer.choice,
6323
+ confidence: answer.confidence,
6324
+ probabilities,
6325
+ type: "choice"
6326
+ };
6327
+ } else {
6328
+ throw new JevFailureError("malformed", `Classifier returned unsupported choice answer for ${name}.`);
6329
+ }
6330
+ continue;
6873
6331
  }
6332
+ throw new JevFailureError("malformed", `Classifier omitted or invalidated ${name}.`);
6874
6333
  }
6875
- const key = normalizeKey3((deps.readFileStore ?? readDefaultFileStore2)());
6876
- return key ? { key, source: "openai-file" } : {};
6334
+ return answers;
6877
6335
  };
6878
- var writeOpenAIDecisionsKey = async (key, deps = {}) => {
6879
- const normalized = normalizeKey3(key);
6880
- if (!normalized) {
6881
- return { message: "The OpenAI API key is empty.", ok: false };
6882
- }
6883
- const secrets = deps.secrets === undefined ? runtimeSecrets3() : deps.secrets;
6884
- if (secrets) {
6885
- try {
6886
- await secrets.set({
6887
- name: OPENAI_DECISIONS_KEY_NAME,
6888
- service: OPENAI_DECISIONS_KEY_SERVICE,
6889
- value: normalized
6890
- });
6891
- return { message: "OpenAI API key stored in Bun.secrets.", ok: true };
6892
- } catch (error) {
6893
- return {
6894
- message: `Storing the OpenAI API key in Bun.secrets failed: ${messageOf3(error)}. Configure OPENAI_API_KEY in Pi or retry secure storage.`,
6895
- ok: false
6896
- };
6897
- }
6336
+ var classifyWithinDeadline = async (ctx, model, state, questions, options, timeoutMs) => {
6337
+ const controller = new AbortController;
6338
+ const callerSignal = options.signal ?? ctx.signal;
6339
+ const abortFromCaller = () => controller.abort(callerSignal?.reason);
6340
+ if (callerSignal?.aborted) {
6341
+ throw abortError();
6342
+ }
6343
+ callerSignal?.addEventListener("abort", abortFromCaller, { once: true });
6344
+ const timeout = setTimeout(() => {
6345
+ controller.abort(new DOMException("Timed out", "TimeoutError"));
6346
+ }, timeoutMs);
6347
+ const apiOptions = {
6348
+ maxRetries: 0,
6349
+ signal: controller.signal,
6350
+ timeoutMs
6351
+ };
6352
+ if (options.apiKey !== undefined) {
6353
+ apiOptions.apiKey = options.apiKey;
6898
6354
  }
6355
+ let abortListener;
6899
6356
  try {
6900
- (deps.writeFileStore ?? writeDefaultFileStore2)(normalized);
6901
- return {
6902
- message: "OpenAI API key stored in the Pi agent directory (mode 0600).",
6903
- ok: true
6357
+ const classification = ctx.modelRegistry.classify(model, { questions, state }, apiOptions);
6358
+ const aborted = Promise.withResolvers();
6359
+ abortListener = () => {
6360
+ aborted.reject(controller.signal.reason ?? abortError());
6904
6361
  };
6362
+ controller.signal.addEventListener("abort", abortListener, { once: true });
6363
+ const request = Promise.race([classification, aborted.promise]);
6364
+ return await request;
6905
6365
  } catch (error) {
6906
- return {
6907
- message: `Storing the OpenAI API key failed: ${messageOf3(error)}. Configure OPENAI_API_KEY in Pi or retry secure storage.`,
6908
- ok: false
6909
- };
6910
- }
6911
- };
6912
- var clearOpenAIDecisionsKey = async (deps = {}) => {
6913
- let firstError;
6914
- const secrets = deps.secrets === undefined ? runtimeSecrets3() : deps.secrets;
6915
- if (secrets) {
6916
- try {
6917
- await secrets.delete({
6918
- name: OPENAI_DECISIONS_KEY_NAME,
6919
- service: OPENAI_DECISIONS_KEY_SERVICE
6920
- });
6921
- } catch (error) {
6922
- firstError = messageOf3(error);
6366
+ if (callerSignal?.aborted) {
6367
+ throw error;
6923
6368
  }
6924
- }
6925
- try {
6926
- if (deps.deleteFileStore) {
6927
- deps.deleteFileStore();
6928
- } else if (existsSync5(keyFilePath3())) {
6929
- deleteDefaultFileStore2();
6369
+ if (controller.signal.aborted) {
6370
+ throw new JevFailureError("timeout", `Jev classifier timed out after ${timeoutMs}ms.`);
6930
6371
  }
6931
- } catch (error) {
6932
- firstError ??= messageOf3(error);
6933
- }
6934
- if (firstError) {
6935
- return {
6936
- message: `Clearing the OpenAI API key failed: ${firstError}.`,
6937
- ok: false
6938
- };
6939
- }
6940
- return { message: "Stored OpenAI API key cleared.", ok: true };
6941
- };
6942
-
6943
- // src/jev/transport.ts
6944
- var OPENROUTER_PROVIDER = "openrouter";
6945
- var OPENAI_PROVIDER = "openai";
6946
- var OPENAI_API_KEY_SOURCES = new Map([
6947
- ["OPENAI_API_KEY", "openai-env"],
6948
- ["stored credential", "openai-provider-credential"]
6949
- ]);
6950
- var openAiPlatformCredentials = async (ctx, deps) => {
6951
- let result;
6952
- try {
6953
- result = deps.getProviderAuth ? await deps.getProviderAuth(OPENAI_PROVIDER) : await ctx?.modelRegistry?.getProviderAuth(OPENAI_PROVIDER);
6954
- } catch {
6955
- result = undefined;
6956
- }
6957
- const source = result?.source;
6958
- const credentialSource = source ? OPENAI_API_KEY_SOURCES.get(source) : undefined;
6959
- const apiKey = result?.auth.apiKey?.trim();
6960
- if (credentialSource && apiKey) {
6961
- return {
6962
- apiKey,
6963
- source: credentialSource,
6964
- transport: "openai-decisions"
6965
- };
6966
- }
6967
- try {
6968
- const stored = await (deps.resolveOpenAIKey ?? resolveOpenAIDecisionsKey)();
6969
- const storedKey = stored.key?.trim();
6970
- return storedKey && stored.source ? {
6971
- apiKey: storedKey,
6972
- source: stored.source,
6973
- transport: "openai-decisions"
6974
- } : undefined;
6975
- } catch {
6976
- return;
6977
- }
6978
- };
6979
- var openRouterKey = async (ctx, deps) => {
6980
- const key = deps.getProviderKey ? await deps.getProviderKey(OPENROUTER_PROVIDER) : await ctx?.modelRegistry?.getApiKeyForProvider(OPENROUTER_PROVIDER);
6981
- return key?.trim() || undefined;
6982
- };
6983
- var typeSafeCredentials = async (deps) => {
6984
- const resolution = await (deps.resolveTypesafe ?? resolveTypeSafeKey)();
6985
- if (!resolution.key) {
6986
- return;
6987
- }
6988
- const credentials = {
6989
- apiKey: resolution.key,
6990
- transport: "typesafe"
6991
- };
6992
- if (resolution.source) {
6993
- credentials.source = resolution.source;
6994
- }
6995
- return credentials;
6996
- };
6997
- var resolveTypesafeCompatibleCredentials = async (target, ctx, deps = {}) => {
6998
- const { baseUrl } = target;
6999
- const provider = target.keyProvider;
7000
- if (provider) {
7001
- let providerKey;
7002
- try {
7003
- providerKey = deps.getProviderKey ? await deps.getProviderKey(provider) : await ctx?.modelRegistry?.getApiKeyForProvider(provider);
7004
- } catch {
7005
- providerKey = undefined;
6372
+ if (error instanceof JevFailureError) {
6373
+ throw error;
7006
6374
  }
7007
- const trimmed = providerKey?.trim();
7008
- if (!trimmed) {
7009
- return;
6375
+ throw new JevFailureError("error", "Jev classifier request failed.");
6376
+ } finally {
6377
+ clearTimeout(timeout);
6378
+ callerSignal?.removeEventListener("abort", abortFromCaller);
6379
+ if (abortListener) {
6380
+ controller.signal.removeEventListener("abort", abortListener);
7010
6381
  }
7011
- return {
7012
- apiKey: trimmed,
7013
- baseUrl,
7014
- source: "provider-credential",
7015
- transport: "typesafe-compatible"
7016
- };
7017
6382
  }
7018
- const resolution = await (deps.resolveEndpointKey ?? resolveJevEndpointKey)();
7019
- if (!resolution.key) {
7020
- return;
7021
- }
7022
- const credentials = {
7023
- apiKey: resolution.key,
7024
- baseUrl,
7025
- transport: "typesafe-compatible"
7026
- };
7027
- if (resolution.source) {
7028
- credentials.source = resolution.source;
7029
- }
7030
- return credentials;
7031
6383
  };
7032
- var typeSafeCompatibleCredentials = (ctx, deps) => {
7033
- const configured = advisorJevBaseUrlRef;
7034
- if (!configured) {
7035
- return Promise.resolve(undefined);
6384
+ var classifyWithJev = async (ctx, ref, state, questions, options = {}) => {
6385
+ const parsed = parseJevClassifierRef(ref);
6386
+ if (!parsed) {
6387
+ throw new JevFailureError("malformed", "No Jev classifier is selected.");
7036
6388
  }
7037
- const { baseUrl } = normalizeJevBaseUrl(configured);
7038
- if (!baseUrl) {
7039
- return Promise.resolve(undefined);
6389
+ const model = ctx.modelRegistry.findOfType("classifier", parsed.provider, parsed.modelId);
6390
+ if (!isClassifierModel(model)) {
6391
+ throw new JevFailureError("error", `Selected classifier ${ref} is unavailable.`);
6392
+ }
6393
+ const timeoutMs = Math.max(1, advisorJevTimeoutMsRef);
6394
+ const result = await classifyWithinDeadline(ctx, model, state, questions, options, timeoutMs);
6395
+ const stopped = result.stopReason !== "stop";
6396
+ if (stopped) {
6397
+ throw new JevFailureError("error", `Jev classifier stopped: ${result.stopReason}.`);
7040
6398
  }
7041
- const options = advisorJevKeyProviderRef ? { baseUrl, keyProvider: advisorJevKeyProviderRef } : { baseUrl };
7042
- return resolveTypesafeCompatibleCredentials(options, ctx, deps);
6399
+ return {
6400
+ answers: normalizeClassifierAnswers(result, Object.keys(questions)),
6401
+ model: `${result.provider}/${result.model}`,
6402
+ usage: normalizedUsage(result.usage)
6403
+ };
7043
6404
  };
7044
- var resolveJevTransportFor = async (transport, ctx, deps = {}) => {
7045
- if (transport === "typesafe") {
7046
- return typeSafeCredentials(deps);
6405
+ var classifyScreening = (ctx, ref, state, options) => classifyWithJev(ctx, ref, state, nativeScreeningQuestions, options);
6406
+ var classifyTurnGate = (ctx, ref, state, options) => classifyWithJev(ctx, ref, state, {
6407
+ should_consult: {
6408
+ criteria: {
6409
+ false: "The executor is progressing soundly on work that matches the user's intent; interrupting would add nothing material.",
6410
+ true: "The executor is approaching a material decision, repeating a failure, about to claim success without validation, or drifting from the user's intent; a second opinion now would change what happens next."
6411
+ },
6412
+ instructions: "Should a senior engineering advisor be consulted right now, before the executor continues? Judge from `recent_conversation`.",
6413
+ type: "bool"
7047
6414
  }
7048
- if (transport === "typesafe-compatible") {
7049
- return typeSafeCompatibleCredentials(ctx, deps);
6415
+ }, options);
6416
+
6417
+ // src/jev/state.ts
6418
+ var JEV_TEXT_CAP_BYTES = 8 * 1024;
6419
+ var buildJevState = (ctx, input = {}) => {
6420
+ const fields = new Map([["role", "executor"]]);
6421
+ if (input.question) {
6422
+ fields.set("executor_question", redactAndCapText(input.question, JEV_TEXT_CAP_BYTES, advisorRedactSecretsRef));
7050
6423
  }
7051
- if (transport === "openrouter") {
7052
- const key = await openRouterKey(ctx, deps);
7053
- return key ? { apiKey: key, transport } : undefined;
6424
+ if (input.draft) {
6425
+ fields.set("executor_draft", redactAndCapText(input.draft, JEV_TEXT_CAP_BYTES, advisorRedactSecretsRef));
7054
6426
  }
7055
- return openAiPlatformCredentials(ctx, deps);
7056
- };
7057
- var resolveJevTransport = async (ctx, deps = {}) => {
7058
- const preference = advisorJevTransportRef;
7059
- if (preference !== "auto") {
7060
- return resolveJevTransportFor(preference, ctx, deps);
6427
+ const digest = recentConversation(ctx, advisorJevDigestMaxCharsRef);
6428
+ if (digest) {
6429
+ fields.set("recent_conversation", digest);
7061
6430
  }
7062
- const typesafe = await typeSafeCredentials(deps);
7063
- return typesafe ?? resolveJevTransportFor("openrouter", ctx, deps);
6431
+ return Object.fromEntries(fields);
7064
6432
  };
7065
6433
 
7066
6434
  // src/tools/outage-notifier.ts
@@ -7090,7 +6458,7 @@ var SCREENED_SKIP_TEXT = "Advisor consultation skipped (screened out): the stake
7090
6458
  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.
7091
6459
 
7092
6460
  ${advice}`;
7093
- var outageNotifier = createOutageNotifier((category, message) => `Advisor Jev/Decisions filter failed (${category}); allowing consultations. ${message}`);
6461
+ var outageNotifier = createOutageNotifier((category, message) => `Advisor Jev classifier failed (${category}); allowing consultations. ${message}`);
7094
6462
  var notifyOutageOnce = outageNotifier.notify;
7095
6463
  var resetJevOutageNotification = outageNotifier.reset;
7096
6464
  var allow = () => ({ decision: "allow" });
@@ -7108,23 +6476,29 @@ var bypassOutcome = (session, options, normalizedQuestion) => {
7108
6476
  }
7109
6477
  return;
7110
6478
  };
6479
+ var classifierRef = (deps) => advisorJevClassifierModeRef === "api-key" ? "typesafe/jev-latest" : deps.selectedRef?.() ?? advisorJevClassifierRef;
6480
+ var apiKeyFor = (deps) => advisorJevClassifierModeRef === "api-key" ? (deps.resolveApiKey ?? consumeJevClassifierKey)() : Promise.resolve(undefined);
7111
6481
  var screenWithJev = async (ctx, session, options, deps, normalizedQuestion) => {
7112
- const credentials = await (deps.resolveTransport ?? resolveJevTransport)(ctx);
7113
- if (!credentials) {
6482
+ const selectedRef = classifierRef(deps);
6483
+ const apiKey = await apiKeyFor(deps);
6484
+ if (!selectedRef || advisorJevClassifierModeRef === "api-key" && !apiKey) {
7114
6485
  session.recordJevFilterFailure();
7115
- notifyOutageOnce(ctx, "missing-key", "No credentials resolved for the selected Jev/Decisions provider.");
6486
+ notifyOutageOnce(ctx, "missing-key", "No credentials resolved for the selected Jev classifier.");
7116
6487
  return allow();
7117
6488
  }
7118
- if (credentials.source === "advisor-json") {
7119
- const warning = consumePlaintextKeyWarning();
7120
- if (warning && ctx.hasUI) {
7121
- ctx.ui.notify(warning, "warning");
7122
- }
7123
- }
7124
- const client = jevClientFromCredentials(credentials, deps.fetch);
7125
6489
  try {
7126
- const result = await client.ask(buildJevState(ctx, options), screeningQuestions, options.signal);
7127
- session.recordJevFilterUsage(result.usage);
6490
+ const state = buildJevState(ctx, options);
6491
+ const result = deps.classifyResult ? await deps.classifyResult(state, options.signal) : await (deps.classify ?? classifyScreening)(ctx, selectedRef, state, {
6492
+ apiKey: advisorJevClassifierModeRef === "api-key" ? apiKey : undefined,
6493
+ signal: options.signal
6494
+ });
6495
+ if (result.usage) {
6496
+ session.recordJevFilterUsage({
6497
+ cost: result.usage.cost,
6498
+ inputTokens: result.usage.inputTokens,
6499
+ outputTokens: result.usage.outputTokens
6500
+ });
6501
+ }
7128
6502
  const verdict = composeScreeningVerdict(result.answers, {
7129
6503
  noulMargin: advisorJevFilterNoulMarginRef,
7130
6504
  skipConfidence: advisorJevFilterSkipConfidenceRef
@@ -7134,11 +6508,12 @@ var screenWithJev = async (ctx, session, options, deps, normalizedQuestion) => {
7134
6508
  return {
7135
6509
  decision: "skip",
7136
6510
  kind: "screened",
7137
- reason: "low stakes and resolvable without a consultation"
6511
+ reason: "low stakes and resolvable without a consultation",
6512
+ usage: result.usage?.piUsage
7138
6513
  };
7139
6514
  }
7140
6515
  session.recordJevFilterAllowed();
7141
- return allow();
6516
+ return { decision: "allow", usage: result.usage?.piUsage };
7142
6517
  } catch (error) {
7143
6518
  if (options.signal?.aborted) {
7144
6519
  throw error;
@@ -7450,9 +6825,9 @@ import {
7450
6825
  unlink,
7451
6826
  writeFile
7452
6827
  } from "node:fs/promises";
7453
- import { join as join7 } from "node:path";
6828
+ import { join as join5 } from "node:path";
7454
6829
  import { setTimeout as sleep } from "node:timers/promises";
7455
- import { getAgentDir as getAgentDir7 } from "@earendil-works/pi-coding-agent";
6830
+ import { getAgentDir as getAgentDir5 } from "@earendil-works/pi-coding-agent";
7456
6831
  var ADOPTIONS = [
7457
6832
  "followed",
7458
6833
  "not-followed",
@@ -7472,12 +6847,12 @@ var OUTCOME_TRIGGERS = [
7472
6847
  ];
7473
6848
  var MAX_LOG_BYTES = 1024 * 1024;
7474
6849
  var OUTCOME_LOG_MAX_BYTES = MAX_LOG_BYTES;
7475
- var statePath = () => join7(getAgentDir7(), "advisor-outcomes-salt");
7476
- var outcomeLogPath = () => join7(getAgentDir7(), "advisor-outcomes.jsonl");
6850
+ var statePath = () => join5(getAgentDir5(), "advisor-outcomes-salt");
6851
+ var outcomeLogPath = () => join5(getAgentDir5(), "advisor-outcomes.jsonl");
7477
6852
  var isErrnoException = (error) => error instanceof Error && ("code" in error);
7478
6853
  var salt = async () => {
7479
6854
  const path = statePath();
7480
- await mkdir(getAgentDir7(), { mode: 448, recursive: true });
6855
+ await mkdir(getAgentDir5(), { mode: 448, recursive: true });
7481
6856
  for (let attempt = 0;attempt < 20; attempt += 1) {
7482
6857
  try {
7483
6858
  const existing = await readFile(path);
@@ -7554,7 +6929,7 @@ var withOutcomeLock = async (run) => {
7554
6929
  var adviceDigest = (advice, key) => createHmac("sha256", key).update(advice).digest("hex").slice(0, 16);
7555
6930
  var appendOutcome = async (record) => {
7556
6931
  const path = outcomeLogPath();
7557
- await mkdir(getAgentDir7(), { mode: 448, recursive: true });
6932
+ await mkdir(getAgentDir5(), { mode: 448, recursive: true });
7558
6933
  return withOutcomeLock(async () => {
7559
6934
  const next = {
7560
6935
  adoption: record.adoption,
@@ -7849,7 +7224,7 @@ var registerCommandRenderers = (runtime) => {
7849
7224
 
7850
7225
  // src/ui/settings-selector.ts
7851
7226
  import { getSettingsListTheme } from "@earendil-works/pi-coding-agent";
7852
- import { SettingsList, truncateToWidth as truncateToWidth8 } from "@earendil-works/pi-tui";
7227
+ import { SettingsList, truncateToWidth as truncateToWidth7 } from "@earendil-works/pi-tui";
7853
7228
 
7854
7229
  // src/ui/settings-formatting.ts
7855
7230
  import { visibleWidth as visibleWidth3 } from "@earendil-works/pi-tui";
@@ -7941,407 +7316,11 @@ var rainbowGradient = (text, startedAt) => {
7941
7316
  // src/ui/settings-items.ts
7942
7317
  import { getKeybindings } from "@earendil-works/pi-tui";
7943
7318
 
7944
- // src/ui/jev-filter-submenu.ts
7945
- import { Key as Key2, matchesKey as matchesKey2, truncateToWidth as truncateToWidth4 } from "@earendil-works/pi-tui";
7946
-
7947
- // node_modules/@typesafe-ai/sdk/dist/index.mjs
7948
- var range2 = (from, to) => Array.from({ length: to - from }, (_, i) => from + i);
7949
- var DEFAULT_RETRY_POLICY = {
7950
- maxRetries: 2,
7951
- backoffInitialMs: 500,
7952
- backoffMaxMs: 5000,
7953
- backoffJitter: 0.25,
7954
- httpStatuses: /* @__PURE__ */ new Set([
7955
- 408,
7956
- 429,
7957
- ...range2(500, 600)
7958
- ]),
7959
- respectRetryAfter: true,
7960
- maxRetryAfterMs: 60000,
7961
- apiConnectionError: true,
7962
- apiTimeoutError: true
7963
- };
7964
- DEFAULT_RETRY_POLICY.maxRetries;
7965
- var noul = (instructions = null, criteria) => ({
7966
- type: "noul",
7967
- instructions,
7968
- criteria
7969
- });
7970
- var g = globalThis;
7971
- var isBrowser = () => typeof g.window !== "undefined" && typeof g.window.document !== "undefined" && typeof g.navigator !== "undefined";
7972
- var describeRuntime = () => {
7973
- const platform = g.process?.platform && g.process?.arch ? ` (${g.process.platform}; ${g.process.arch})` : "";
7974
- if (g.Bun?.version)
7975
- return `bun/${g.Bun.version}${platform}`;
7976
- if (g.Deno?.version?.deno)
7977
- return `deno/${g.Deno.version.deno}${platform}`;
7978
- if (g.EdgeRuntime !== undefined)
7979
- return "vercel-edge";
7980
- if (g.navigator?.userAgent === "Cloudflare-Workers")
7981
- return "cloudflare-workers";
7982
- if (g.process?.versions?.node)
7983
- return `node/${g.process.versions.node}${platform}`;
7984
- if (isBrowser())
7985
- return "browser";
7986
- return "unknown";
7987
- };
7988
- var RUNTIME = describeRuntime();
7989
-
7990
- // src/ui/jev-setup-support.ts
7991
- var fireAndForget = async (action, onError) => {
7992
- try {
7993
- await action;
7994
- } catch (error) {
7995
- const message = error instanceof Error ? error.message : String(error);
7996
- onError(redactSecrets(message));
7997
- }
7998
- };
7999
- var providerName = (transport) => {
8000
- if (transport === "typesafe") {
8001
- return "TypeSafe Jev";
8002
- }
8003
- if (transport === "openrouter") {
8004
- return "OpenRouter (Pi login)";
8005
- }
8006
- if (transport === "typesafe-compatible") {
8007
- return "System One–compatible endpoint";
8008
- }
8009
- return `OpenAI Decisions (${OPENAI_DECISIONS_MODEL})`;
8010
- };
8011
- var endpointSourceLabel = (source) => {
8012
- switch (source) {
8013
- case "provider-credential": {
8014
- return "Pi provider login";
8015
- }
8016
- case "jev-bun-secrets": {
8017
- return "Bun.secrets";
8018
- }
8019
- case "jev-file": {
8020
- return "stored file, mode 0600";
8021
- }
8022
- default: {
8023
- return "JEV_API_KEY";
8024
- }
8025
- }
8026
- };
8027
- var transportLabel = (credentials) => {
8028
- if (credentials.transport === "openrouter") {
8029
- return "OpenRouter (reusing Pi login)";
8030
- }
8031
- if (credentials.transport === "typesafe-compatible") {
8032
- return `System One–compatible (${credentials.baseUrl ?? "no Base URL"}; key: ${endpointSourceLabel(credentials.source)})`;
8033
- }
8034
- if (credentials.transport === "openai-decisions") {
8035
- let source = "verified API key";
8036
- switch (credentials.source) {
8037
- case "openai-bun-secrets": {
8038
- source = "Bun.secrets";
8039
- break;
8040
- }
8041
- case "openai-env": {
8042
- source = "OPENAI_API_KEY";
8043
- break;
8044
- }
8045
- case "openai-file": {
8046
- source = "stored file, mode 0600";
8047
- break;
8048
- }
8049
- case "openai-provider-credential": {
8050
- source = "Pi stored API key";
8051
- break;
8052
- }
8053
- default: {
8054
- break;
8055
- }
8056
- }
8057
- return `OpenAI Decisions (${OPENAI_DECISIONS_MODEL}; key: ${source})`;
8058
- }
8059
- switch (credentials.source) {
8060
- case "advisor-json": {
8061
- return "TypeSafe (key: advisor.json — plaintext, not recommended)";
8062
- }
8063
- case "bun-secrets": {
8064
- return "TypeSafe (key: Bun.secrets)";
8065
- }
8066
- case "file": {
8067
- return "TypeSafe (key: stored file, mode 0600)";
8068
- }
8069
- default: {
8070
- return "TypeSafe (key: TYPESAFE_API_KEY)";
8071
- }
8072
- }
8073
- };
8074
- var canClearCredential = (credentials) => credentials.source === "bun-secrets" || credentials.source === "file" || credentials.source === "openai-bun-secrets" || credentials.source === "openai-file" || credentials.source === "jev-bun-secrets" || credentials.source === "jev-file";
8075
- var canReplaceWithEnteredKey = (credentials) => credentials.transport === "typesafe" || credentials.transport === "typesafe-compatible" || credentials.transport === "openai-decisions" && (credentials.source === "openai-bun-secrets" || credentials.source === "openai-file");
8076
- var keyEntryPrompt = (transport) => {
8077
- if (transport === "openai-decisions") {
8078
- return "Paste an OpenAI Platform API key";
8079
- }
8080
- if (transport === "typesafe-compatible") {
8081
- return "Paste the endpoint API key";
8082
- }
8083
- return "Paste a TypeSafe API key";
8084
- };
8085
- var defaultVerify = async (credentials) => {
8086
- const client = jevClientFromCredentials(credentials);
8087
- try {
8088
- await client.ask({ purpose: "pi-advisor setup verification" }, { verified: noul("Answer yes.") });
8089
- return { ok: true };
8090
- } catch (error) {
8091
- return {
8092
- message: error instanceof Error ? error.message : String(error),
8093
- ok: false
8094
- };
8095
- }
8096
- };
8097
- var writeKeyFor = (key, transport) => {
8098
- if (transport === "openai-decisions") {
8099
- return writeOpenAIDecisionsKey(key);
8100
- }
8101
- if (transport === "typesafe-compatible") {
8102
- return writeJevEndpointKey(key);
8103
- }
8104
- return writeKeyTypeSafeKey(key);
8105
- };
8106
- var clearKeyFor = (transport) => {
8107
- if (transport === "openai-decisions") {
8108
- return clearOpenAIDecisionsKey();
8109
- }
8110
- if (transport === "typesafe-compatible") {
8111
- return clearJevEndpointKey();
8112
- }
8113
- return clearKeyTypeSafeKey();
8114
- };
8115
- var defaultSetupDeps = {
8116
- clearStoredKey: (transport) => clearKeyFor(transport),
8117
- removePlaintextKey: removeTypeSafeKeyFromAdvisorJson,
8118
- resolveEndpoint: (options) => resolveTypesafeCompatibleCredentials(options),
8119
- resolveTransport: (transport) => transport ? resolveJevTransportFor(transport) : resolveJevTransport(),
8120
- verify: defaultVerify,
8121
- writeKey: (key, transport) => writeKeyFor(key, transport)
8122
- };
8123
-
8124
- // src/ui/jev-filter-submenu.ts
8125
- var actionsFor = (enabled) => enabled ? ["disable", "done"] : ["enable", "done"];
8126
- var labelFor2 = (action) => {
8127
- if (action === "enable") {
8128
- return "Enable the filter";
8129
- }
8130
- return action === "disable" ? "Disable the filter" : "Done";
8131
- };
8132
-
8133
- class JevFilterSubmenu {
8134
- options;
8135
- deps;
8136
- credentials;
8137
- mode = "resolving";
8138
- notice;
8139
- selectedIndex = 0;
8140
- enabled;
8141
- _focused = true;
8142
- constructor(options, deps = {}) {
8143
- this.options = options;
8144
- this.enabled = options.currentValue === "On";
8145
- this.deps = { ...defaultSetupDeps, ...options.setupDeps, ...deps };
8146
- fireAndForget(this.refresh(), this.reportBackgroundError);
8147
- }
8148
- get focused() {
8149
- return this._focused;
8150
- }
8151
- set focused(value) {
8152
- this._focused = value;
8153
- }
8154
- invalidate() {}
8155
- render(width) {
8156
- const { theme } = this.options;
8157
- const lines = [
8158
- theme.fg("accent", theme.bold(" Jev/Decisions consultation filter")),
8159
- "",
8160
- ` Filter: ${this.enabled ? "On" : "Off"}`,
8161
- ` Provider: ${this.options.currentTransport}`
8162
- ];
8163
- if (this.mode === "resolving") {
8164
- lines.push("", " Checking the selected provider credentials…");
8165
- } else if (this.notice) {
8166
- lines.push("", theme.fg("warning", ` ${this.notice}`));
8167
- }
8168
- if (this.mode === "menu") {
8169
- lines.push("");
8170
- for (const [index, action] of actionsFor(this.enabled).entries()) {
8171
- const prefix = index === this.selectedIndex ? "→ " : " ";
8172
- lines.push(`${prefix}${labelFor2(action)}`);
8173
- }
8174
- }
8175
- return lines.map((line) => truncateToWidth4(line, width));
8176
- }
8177
- handleInput(keyData) {
8178
- if (this.mode !== "menu") {
8179
- return;
8180
- }
8181
- const actions = actionsFor(this.enabled);
8182
- if (matchesKey2(keyData, Key2.down) || keyData === "\x1B[B" || keyData === "\x1BOB") {
8183
- this.selectedIndex = (this.selectedIndex + 1) % actions.length;
8184
- } else if (matchesKey2(keyData, Key2.up) || keyData === "\x1B[A" || keyData === "\x1BOA") {
8185
- this.selectedIndex = (this.selectedIndex - 1 + actions.length) % actions.length;
8186
- } else if (matchesKey2(keyData, Key2.enter) || keyData === "\r") {
8187
- this.activate(actions[this.selectedIndex]);
8188
- } else {
8189
- return;
8190
- }
8191
- this.options.tui.requestRender();
8192
- }
8193
- async refresh() {
8194
- const transport = this.options.currentTransport;
8195
- try {
8196
- this.credentials = await this.deps.resolveTransport(transport === "auto" ? undefined : transport);
8197
- } catch (error) {
8198
- this.credentials = undefined;
8199
- this.notice = `Credential lookup failed: ${error instanceof Error ? error.message : String(error)}`;
8200
- }
8201
- if (!this.credentials && !this.notice) {
8202
- this.notice = `No Jev provider resolves for "${transport}". Open Jev provider to configure one.`;
8203
- }
8204
- this.mode = "menu";
8205
- this.options.tui.requestRender();
8206
- }
8207
- reportBackgroundError = (message) => {
8208
- this.mode = "menu";
8209
- this.notice = `Setup failed: ${message}`;
8210
- this.options.tui.requestRender();
8211
- };
8212
- activate(action) {
8213
- if (action === "done") {
8214
- this.options.done();
8215
- return;
8216
- }
8217
- const enabled = action === "enable";
8218
- if (enabled && !this.credentials) {
8219
- this.options.tui.requestRender();
8220
- return;
8221
- }
8222
- const saved = this.commit({ enabled });
8223
- if (!saved) {
8224
- this.notice = "The filter state could not be saved.";
8225
- this.options.tui.requestRender();
8226
- return;
8227
- }
8228
- this.enabled = enabled;
8229
- this.notice = undefined;
8230
- this.options.done(enabled ? "On" : "Off");
8231
- }
8232
- commit(selection) {
8233
- if (!this.options.onSelection) {
8234
- return true;
8235
- }
8236
- return this.options.onSelection(selection);
8237
- }
8238
- }
8239
-
8240
- // src/ui/jev-provider-submenu.ts
8241
- import { Input as Input3, Key as Key3, matchesKey as matchesKey3 } from "@earendil-works/pi-tui";
8242
-
8243
- // src/ui/jev-provider-submenu-view.ts
8244
- import { truncateToWidth as truncateToWidth5 } from "@earendil-works/pi-tui";
8245
- var providerActions = () => [
8246
- "typesafe",
8247
- "openrouter",
8248
- "openai-decisions",
8249
- "typesafe-compatible"
8250
- ];
8251
- var setupActions = (state) => {
8252
- const actions = providerActions();
8253
- if (state.canEnterKey) {
8254
- actions.push("enter-key");
8255
- }
8256
- if (state.canReuseProviderLogin) {
8257
- actions.push("reuse-provider-login");
8258
- }
8259
- if (state.credentials && canClearCredential(state.credentials)) {
8260
- actions.push("clear-stored-key");
8261
- }
8262
- actions.push("done");
8263
- return actions;
8264
- };
8265
- var setupLabels = (state) => setupActions(state).map((action) => {
8266
- if (action === "clear-stored-key") {
8267
- return "Clear stored key";
8268
- }
8269
- if (action === "done") {
8270
- return "Done";
8271
- }
8272
- if (action === "enter-key") {
8273
- return `Enter an API key for ${providerName(state.selectedTransport ?? "typesafe")}`;
8274
- }
8275
- if (action === "reuse-provider-login") {
8276
- return "Reuse a Pi provider login";
8277
- }
8278
- if (action === "typesafe-compatible") {
8279
- return `${providerName(action)}…`;
8280
- }
8281
- return providerName(action);
8282
- });
8283
- var inputLines = (key, state, input, width) => {
8284
- const rendered = input.render(Math.max(10, width - 4))[0] ?? "";
8285
- const titles = {
8286
- "base-url": [
8287
- "Base URL of a System One–compatible endpoint",
8288
- "Origin, for example https://api.codiv.ai. /v1/systemone is appended; plain http works on localhost."
8289
- ],
8290
- "key-entry": [
8291
- providerName(state.selectedTransport ?? "typesafe"),
8292
- state.selectedTransport === "openai-decisions" ? "No OpenAI Platform API key found. ChatGPT subscription OAuth is not accepted." : `No API key found for ${providerName(state.selectedTransport ?? "typesafe")}.`
8293
- ],
8294
- "provider-id": [
8295
- "Pi provider id",
8296
- "The Pi provider whose stored login supplies this endpoint's key, for example openrouter."
8297
- ]
8298
- };
8299
- const [title, description] = titles[key];
8300
- return [` ${title}`, ` ${description}`, ` ${rendered}`];
8301
- };
8302
- var renderJevProvider = (options, state, input, width) => {
8303
- const { theme } = options;
8304
- const lines = [theme.fg("accent", theme.bold(" Jev provider")), ""];
8305
- if (state.credentials) {
8306
- lines.push(` Credential: ${transportLabel(state.credentials)}`);
8307
- } else if (state.selectedTransport) {
8308
- lines.push(` Selected provider: ${providerName(state.selectedTransport)}`);
8309
- } else {
8310
- lines.push(` Saved transport: ${options.currentTransport}`);
8311
- }
8312
- if (state.baseUrl) {
8313
- lines.push(` Base URL: ${state.baseUrl}`);
8314
- }
8315
- if (state.providerId) {
8316
- lines.push(` Pi provider: ${state.providerId}`);
8317
- }
8318
- if (state.notice) {
8319
- lines.push("", theme.fg("warning", ` ${state.notice}`));
8320
- }
8321
- lines.push("");
8322
- if (state.mode === "resolving") {
8323
- lines.push(" Checking the selected provider credentials…");
8324
- } else if (state.mode === "verifying") {
8325
- lines.push(" Verifying with a live Jev call…");
8326
- } else if (state.mode === "clearing") {
8327
- lines.push(" Clearing the selected provider's stored key…");
8328
- } else if (state.mode === "base-url" || state.mode === "key-entry" || state.mode === "provider-id") {
8329
- lines.push(...inputLines(state.mode, state, input, width));
8330
- if (state.inputError) {
8331
- lines.push(theme.fg("error", ` ${state.inputError}`));
8332
- }
8333
- lines.push(theme.fg("dim", " Enter: continue · Esc: return"));
8334
- } else {
8335
- for (const [index, label] of setupLabels(state).entries()) {
8336
- const prefix = index === state.selectedIndex ? "→ " : " ";
8337
- lines.push(`${prefix}${label}`);
8338
- }
8339
- }
8340
- return lines.map((line) => truncateToWidth5(line, width));
8341
- };
7319
+ // src/ui/jev-classifier-submenu.ts
7320
+ import { Input as Input3, Key as Key2, matchesKey as matchesKey2 } from "@earendil-works/pi-tui";
8342
7321
 
8343
7322
  // src/ui/masked-input.ts
8344
- import { Input as Input2, truncateToWidth as truncateToWidth6 } from "@earendil-works/pi-tui";
7323
+ import { Input as Input2, truncateToWidth as truncateToWidth4 } from "@earendil-works/pi-tui";
8345
7324
 
8346
7325
  class MaskedInput {
8347
7326
  input;
@@ -8378,373 +7357,416 @@ class MaskedInput {
8378
7357
  const { cursor } = this.input;
8379
7358
  const masked = `${"•".repeat(Math.min(cursor, value.length))}█${"•".repeat(Math.max(0, value.length - cursor))}`;
8380
7359
  const placeholder = value.length === 0 && this.options.placeholder ? this.options.placeholder : masked;
8381
- return [truncateToWidth6(placeholder, Math.max(1, width))];
7360
+ return [truncateToWidth4(placeholder, Math.max(1, width))];
8382
7361
  }
8383
7362
  }
8384
7363
 
8385
- // src/ui/jev-provider-submenu.ts
8386
- class JevProviderSubmenu {
7364
+ // src/ui/jev-classifier-submenu.ts
7365
+ class JevClassifierSubmenu {
8387
7366
  options;
8388
- deps;
8389
- maskedInput;
8390
- textInput = new Input3;
8391
- credentials;
8392
- selectedTransport;
8393
- mode = "menu";
8394
- notice;
8395
- inputError;
7367
+ search = new Input3;
7368
+ loaded = Promise.withResolvers();
7369
+ keyInput;
7370
+ choices = [];
7371
+ filtered = [];
8396
7372
  selectedIndex = 0;
8397
- baseUrl;
8398
- providerId;
8399
- canEnterKey = false;
8400
- pendingSelectionRefresh = false;
7373
+ mode = "loading";
7374
+ notice;
7375
+ failClosedKeyMode = false;
8401
7376
  _focused = true;
8402
- constructor(options, deps = {}) {
7377
+ constructor(options) {
8403
7378
  this.options = options;
8404
- this.deps = { ...defaultSetupDeps, ...options.setupDeps, ...deps };
8405
- this.baseUrl = options.currentBaseUrl;
8406
- this.providerId = options.currentKeyProvider;
8407
- this.maskedInput = this.createMaskedInput(keyEntryPrompt("typesafe"));
8408
- this.textInput.focused = true;
8409
- this.textInput.onSubmit = (value) => this.submitText(value);
8410
- this.textInput.onEscape = () => this.returnToMenu();
8411
- fireAndForget(this.refresh(), this.reportBackgroundError);
7379
+ this.search.focused = true;
7380
+ this.loadChoices();
8412
7381
  }
8413
7382
  get focused() {
8414
7383
  return this._focused;
8415
7384
  }
8416
7385
  set focused(value) {
8417
7386
  this._focused = value;
8418
- this.maskedInput.focused = value;
8419
- this.textInput.focused = value;
7387
+ this.search.focused = value;
8420
7388
  }
8421
7389
  invalidate() {
8422
- this.maskedInput.invalidate();
8423
- this.textInput.invalidate();
7390
+ this.search.invalidate();
8424
7391
  }
8425
- handleInput(keyData) {
8426
- if (this.mode === "key-entry") {
8427
- this.maskedInput.handleInput(keyData);
8428
- this.options.tui.requestRender();
8429
- return;
7392
+ render(width) {
7393
+ const { theme } = this.options;
7394
+ const border = theme.fg("border", "─".repeat(Math.max(1, width)));
7395
+ if (this.mode === "key") {
7396
+ return [
7397
+ border,
7398
+ theme.fg("accent", theme.bold("Jev API Key")),
7399
+ "",
7400
+ this.notice ?? "Enter a new TypeSafe Jev API key:",
7401
+ ` ${this.keyInput?.render(Math.max(1, width - 4))[0] ?? ""}`,
7402
+ "",
7403
+ this.failClosedKeyMode ? "Key restore failed. Re-enter and verify a valid Jev key." : "Enter to verify · Esc to cancel",
7404
+ border
7405
+ ];
8430
7406
  }
8431
- if (this.mode === "base-url" || this.mode === "provider-id") {
8432
- const before = this.textInput.getValue();
8433
- this.textInput.handleInput(keyData);
8434
- if (this.inputError && this.textInput.getValue() !== before) {
8435
- this.inputError = undefined;
8436
- }
7407
+ const query = this.search.getValue().trim().toLowerCase();
7408
+ const filteredChoices = this.choices.filter((choice) => choice.label.toLowerCase().includes(query));
7409
+ this.filtered = filteredChoices;
7410
+ const rows = this.filtered.map((choice, index) => `${index === this.selectedIndex ? "›" : " "} ${choice.label}`);
7411
+ return [
7412
+ border,
7413
+ theme.fg("accent", theme.bold("Jev classifier")),
7414
+ "",
7415
+ this.mode === "loading" ? "Loading Pi classifier catalog…" : `Search: ${this.search.render(Math.max(1, width - 10))[0]}`,
7416
+ ...this.notice ? [this.notice] : [],
7417
+ ...rows.slice(0, 10),
7418
+ "",
7419
+ "↑/↓ move · Enter select · Esc cancel",
7420
+ border
7421
+ ];
7422
+ }
7423
+ handleInput(data) {
7424
+ if (this.mode === "key") {
7425
+ this.keyInput?.handleInput(data);
8437
7426
  this.options.tui.requestRender();
8438
7427
  return;
8439
7428
  }
8440
- if (this.mode !== "menu") {
7429
+ if (this.mode !== "list") {
8441
7430
  return;
8442
7431
  }
8443
- const actions = setupActions(this.viewState());
8444
- if (matchesKey3(keyData, Key3.down) || keyData === "\x1B[B" || keyData === "\x1BOB") {
8445
- this.selectedIndex = (this.selectedIndex + 1) % actions.length;
8446
- } else if (matchesKey3(keyData, Key3.up) || keyData === "\x1B[A" || keyData === "\x1BOA") {
8447
- this.selectedIndex = (this.selectedIndex - 1 + actions.length) % actions.length;
8448
- } else if (matchesKey3(keyData, Key3.enter) || keyData === "\r") {
8449
- this.activate(actions[this.selectedIndex]);
8450
- } else {
7432
+ if (data === "\x1B[B" || matchesKey2(data, Key2.down)) {
7433
+ if (this.selectedIndex + 1 < this.filtered.length) {
7434
+ this.selectedIndex += 1;
7435
+ }
7436
+ } else if (data === "\x1B[A" || matchesKey2(data, Key2.up)) {
7437
+ this.selectedIndex = Math.max(0, this.selectedIndex - 1);
7438
+ } else if (matchesKey2(data, Key2.escape) || data === "\x1B") {
7439
+ this.options.done();
8451
7440
  return;
7441
+ } else if (matchesKey2(data, Key2.enter) || data === "\r") {
7442
+ const selected = this.filtered[this.selectedIndex];
7443
+ if (selected) {
7444
+ this.choose(selected);
7445
+ }
7446
+ } else {
7447
+ this.search.handleInput(data);
7448
+ this.selectedIndex = 0;
8452
7449
  }
8453
7450
  this.options.tui.requestRender();
8454
7451
  }
8455
- render(width) {
8456
- const input = this.mode === "key-entry" ? this.maskedInput : this.textInput;
8457
- return renderJevProvider(this.options, this.viewState(), input, width);
8458
- }
8459
- viewState() {
8460
- return {
8461
- baseUrl: this.baseUrl,
8462
- canEnterKey: this.canEnterKey,
8463
- canReuseProviderLogin: Boolean(this.baseUrl),
8464
- credentials: this.credentials,
8465
- inputError: this.inputError,
8466
- mode: this.mode,
8467
- notice: this.notice,
8468
- providerId: this.providerId,
8469
- selectedIndex: this.selectedIndex,
8470
- selectedTransport: this.selectedTransport
8471
- };
8472
- }
8473
- createMaskedInput(placeholder) {
8474
- return new MaskedInput({
8475
- onEscape: () => this.returnToMenu(),
8476
- onSubmit: (value) => this.submitEnteredKey(value),
8477
- placeholder
8478
- });
8479
- }
8480
- async refresh() {
8481
- this.mode = "resolving";
8482
- this.options.tui.requestRender();
7452
+ async loadChoices() {
8483
7453
  try {
8484
- const credentials = await this.deps.resolveTransport(this.options.currentTransport === "auto" ? undefined : this.options.currentTransport);
8485
- this.credentials = credentials;
8486
- this.selectedTransport = credentials?.transport;
8487
- if (credentials?.transport === "typesafe-compatible") {
8488
- this.baseUrl = credentials.baseUrl ?? this.baseUrl;
7454
+ if (!this.options.modelRegistry) {
7455
+ throw new Error("Pi classifier registry is unavailable.");
8489
7456
  }
8490
- this.mode = "menu";
8491
- this.selectedIndex = 0;
8492
- if (credentials?.source === "advisor-json") {
8493
- this.notice = consumePlaintextKeyWarning();
7457
+ const models = await this.options.modelRegistry.getAvailableOfType("classifier");
7458
+ this.choices = (models ?? []).map((model) => ({
7459
+ action: "classifier",
7460
+ label: `${this.options.modelRegistry?.getProviderDisplayName(model.provider) ?? model.provider} / ${model.id} (${JevClassifierSubmenu.rates(model)})`,
7461
+ model,
7462
+ ref: `${model.provider}/${model.id}`
7463
+ }));
7464
+ const stored = await (this.options.resolveStoredKey ?? readJevClassifierKey)();
7465
+ if (stored.key) {
7466
+ this.choices.push({
7467
+ action: "use-key",
7468
+ label: "Jev API Key (use stored key)",
7469
+ ref: JEV_API_KEY_CLASSIFIER
7470
+ }, {
7471
+ action: "replace-key",
7472
+ label: "Replace Jev API Key…",
7473
+ ref: JEV_API_KEY_CLASSIFIER
7474
+ });
7475
+ } else {
7476
+ this.choices.push({
7477
+ action: "replace-key",
7478
+ label: "Jev API Key… (enter TypeSafe key)",
7479
+ ref: JEV_API_KEY_CLASSIFIER
7480
+ });
8494
7481
  }
8495
- this.options.tui.requestRender();
7482
+ this.mode = "list";
7483
+ this.loaded.resolve(true);
7484
+ this.notice = this.options.currentValue && this.options.currentValue !== "Choose classifier" ? `Current: ${this.options.currentValue}` : undefined;
8496
7485
  } catch (error) {
8497
- this.reportBackgroundError(error instanceof Error ? error.message : String(error));
7486
+ this.mode = "list";
7487
+ this.loaded.resolve(false);
7488
+ this.notice = `Could not load classifiers: ${error instanceof Error ? error.message : "unknown error"}. Retry /advisor-settings.`;
8498
7489
  }
8499
- }
8500
- reportBackgroundError = (message) => {
8501
- this.mode = "menu";
8502
- this.notice = `Setup failed: ${message}`;
8503
- this.options.tui.requestRender();
8504
- };
8505
- returnToMenu() {
8506
- this.mode = "menu";
8507
- this.inputError = undefined;
8508
- this.maskedInput.setValue("");
8509
7490
  this.options.tui.requestRender();
8510
7491
  }
8511
- activate(action) {
8512
- if (action === "done") {
8513
- this.closeSetup();
8514
- return;
8515
- }
8516
- if (action === "clear-stored-key") {
8517
- fireAndForget(this.clearStoredKey(), this.reportBackgroundError);
8518
- return;
8519
- }
8520
- if (action === "enter-key") {
8521
- if (this.selectedTransport) {
8522
- this.openKeyEntry(this.selectedTransport);
7492
+ whenLoaded() {
7493
+ return this.loaded.promise;
7494
+ }
7495
+ static rates(model) {
7496
+ const rates = model.cost;
7497
+ return rates.input === 0 && rates.output === 0 ? "$0/M tokens" : `$${rates.input}/$${rates.output} per Mtok`;
7498
+ }
7499
+ async choose(choice) {
7500
+ if (choice.action === "use-key") {
7501
+ const stored = await (this.options.resolveStoredKey ?? readJevClassifierKey)();
7502
+ if (stored.key) {
7503
+ await this.verifyStoredKey(stored.key);
7504
+ } else {
7505
+ this.openKeyEntry();
8523
7506
  }
8524
7507
  return;
8525
7508
  }
8526
- if (action === "reuse-provider-login") {
8527
- this.openProviderIdEntry();
8528
- return;
8529
- }
8530
- if (action === "typesafe-compatible") {
8531
- this.openBaseUrlEntry();
7509
+ if (choice.action === "replace-key") {
7510
+ this.openKeyEntry();
8532
7511
  return;
8533
7512
  }
8534
- if (this.mode !== "menu") {
7513
+ if (!choice.model) {
8535
7514
  return;
8536
7515
  }
8537
- fireAndForget(this.selectProvider(action), this.reportBackgroundError);
8538
- }
8539
- openBaseUrlEntry() {
8540
- this.mode = "base-url";
8541
- this.inputError = undefined;
8542
- this.notice = undefined;
8543
- this.textInput.setValue(this.baseUrl ?? "");
8544
- this.textInput.focused = this._focused;
8545
- this.options.tui.requestRender();
8546
- }
8547
- openProviderIdEntry() {
8548
- this.mode = "provider-id";
8549
- this.inputError = undefined;
8550
- this.notice = undefined;
8551
- this.textInput.setValue(this.providerId ?? "");
8552
- this.textInput.focused = this._focused;
7516
+ this.mode = "verifying";
7517
+ this.notice = `Verifying ${choice.ref}…`;
8553
7518
  this.options.tui.requestRender();
8554
- }
8555
- openKeyEntry(transport) {
8556
- this.selectedTransport = transport;
8557
- this.mode = "key-entry";
8558
- this.inputError = undefined;
8559
- this.maskedInput = this.createMaskedInput(keyEntryPrompt(transport));
8560
- this.maskedInput.focused = this._focused;
7519
+ try {
7520
+ await this.verify(choice.model);
7521
+ const saved = this.save({ classifier: choice.ref, transport: "auto" });
7522
+ if (!saved) {
7523
+ this.mode = "list";
7524
+ this.notice = "Verified, but settings could not be saved.";
7525
+ }
7526
+ } catch (error) {
7527
+ this.notice = `Verification failed for ${choice.ref}: ${error instanceof Error ? error.message : "provider error"}`;
7528
+ this.mode = "list";
7529
+ }
8561
7530
  this.options.tui.requestRender();
8562
7531
  }
8563
- submitText(value) {
8564
- if (this.mode === "base-url") {
8565
- fireAndForget(this.submitBaseUrl(value), this.reportBackgroundError);
8566
- return;
7532
+ async verify(model, apiKey) {
7533
+ if (!this.options.modelRegistry) {
7534
+ throw new Error("Pi classifier registry is unavailable.");
8567
7535
  }
8568
- if (this.mode === "provider-id") {
8569
- fireAndForget(this.submitProviderId(value), this.reportBackgroundError);
7536
+ const state = {
7537
+ recent_conversation: "Classifier verification check.",
7538
+ role: "executor"
7539
+ };
7540
+ const result = await classifyWithJev({ modelRegistry: this.options.modelRegistry, signal: undefined }, `${model.provider}/${model.id}`, state, nativeScreeningQuestions, { apiKey });
7541
+ if (!result.answers.self_answerable || !result.answers.stakes) {
7542
+ throw new Error("Classifier returned an incomplete verification result.");
8570
7543
  }
8571
7544
  }
8572
- async submitBaseUrl(value) {
8573
- const { baseUrl, error } = normalizeJevBaseUrl(value);
8574
- if (!baseUrl) {
8575
- this.inputError = error;
7545
+ async verifyKey() {
7546
+ const candidate = this.keyInput?.getValue().trim() ?? "";
7547
+ this.keyInput?.setValue("");
7548
+ if (!candidate) {
7549
+ this.notice = "Enter a non-empty Jev API key.";
8576
7550
  this.options.tui.requestRender();
8577
7551
  return;
8578
7552
  }
8579
- this.baseUrl = baseUrl;
8580
- this.selectedTransport = "typesafe-compatible";
8581
- this.mode = "resolving";
8582
- this.inputError = undefined;
8583
- this.options.tui.requestRender();
8584
- const options = this.providerId ? { baseUrl, keyProvider: this.providerId } : { baseUrl };
8585
- const credentials = await this.deps.resolveEndpoint(options);
8586
- if (!credentials) {
8587
- this.openKeyEntry("typesafe-compatible");
8588
- return;
8589
- }
8590
- await this.verifyAndSave(credentials);
8591
- }
8592
- async submitProviderId(value) {
8593
- const providerId = value.trim();
8594
- if (!providerId || /\s/u.test(providerId)) {
8595
- this.inputError = "Enter a single Pi provider id, for example openrouter.";
7553
+ const model = this.options.modelRegistry?.findOfType("classifier", "typesafe", "jev-latest");
7554
+ if (!model) {
7555
+ this.notice = "TypeSafe Jev classifier is not present in Pi's catalog.";
8596
7556
  this.options.tui.requestRender();
8597
7557
  return;
8598
7558
  }
8599
- if (!this.baseUrl) {
8600
- this.inputError = "Enter the Base URL first.";
7559
+ const previous = await (this.options.resolveStoredKey ?? readJevClassifierKey)();
7560
+ if (previous.failed) {
7561
+ this.mode = "list";
7562
+ this.notice = "Could not read the stored Jev API Key state; nothing was changed. Try again later.";
8601
7563
  this.options.tui.requestRender();
8602
7564
  return;
8603
7565
  }
8604
- this.providerId = providerId;
8605
- this.selectedTransport = "typesafe-compatible";
8606
- this.mode = "resolving";
8607
- this.inputError = undefined;
7566
+ this.mode = "verifying";
7567
+ this.notice = "Verifying Jev API Key…";
7568
+ this.options.tui.requestRender();
7569
+ try {
7570
+ await this.verify(model, candidate);
7571
+ const stored = await (this.options.persistKey ?? writeJevClassifierKey)(candidate);
7572
+ if (!stored.ok) {
7573
+ throw new Error(stored.message);
7574
+ }
7575
+ enableJevClassifierKeyForRuntime();
7576
+ if (!this.save({ classifier: JEV_API_KEY_CLASSIFIER, transport: "auto" })) {
7577
+ if (!await this.restorePreviousKey(previous)) {
7578
+ this.failClosedKeyMode = true;
7579
+ disableJevClassifierKeyForRuntime();
7580
+ throw new Error("Settings save failed and the previous key could not be restored. Re-enter and verify a valid Jev key before continuing.");
7581
+ }
7582
+ throw new Error("Could not save Jev classifier settings; existing key was restored.");
7583
+ }
7584
+ this.mode = "list";
7585
+ this.notice = "Jev API Key verified and saved securely.";
7586
+ } catch (error) {
7587
+ this.mode = "key";
7588
+ this.notice = `Verification failed: ${error instanceof Error ? error.message : "provider error"}`;
7589
+ }
8608
7590
  this.options.tui.requestRender();
8609
- const credentials = await this.deps.resolveEndpoint({
8610
- baseUrl: this.baseUrl,
8611
- keyProvider: providerId
7591
+ }
7592
+ openKeyEntry() {
7593
+ this.mode = "key";
7594
+ this.keyInput = new MaskedInput({
7595
+ onEscape: () => {
7596
+ this.mode = "list";
7597
+ this.keyInput?.setValue("");
7598
+ this.options.tui.requestRender();
7599
+ },
7600
+ onSubmit: () => this.handleKeySubmit(),
7601
+ placeholder: "TypeSafe Jev API key"
8612
7602
  });
8613
- if (!credentials) {
8614
- this.mode = "menu";
8615
- this.notice = `No stored login for Pi provider "${providerId}". Add one in Pi and retry.`;
7603
+ }
7604
+ restorePreviousKey(previous) {
7605
+ if (this.options.restoreKey) {
7606
+ return this.options.restoreKey(previous);
7607
+ }
7608
+ return restoreJevClassifierKey(previous);
7609
+ }
7610
+ async verifyStoredKey(key) {
7611
+ const model = this.options.modelRegistry?.findOfType("classifier", "typesafe", "jev-latest");
7612
+ if (!model) {
7613
+ this.notice = "TypeSafe Jev classifier is not present in Pi's catalog.";
8616
7614
  this.options.tui.requestRender();
8617
7615
  return;
8618
7616
  }
8619
- await this.verifyAndSave(credentials);
8620
- }
8621
- async selectProvider(transport) {
8622
- this.selectedTransport = transport;
8623
- this.mode = "resolving";
8624
- this.notice = undefined;
8625
- this.canEnterKey = false;
7617
+ this.mode = "verifying";
7618
+ this.notice = "Verifying stored Jev API Key…";
8626
7619
  this.options.tui.requestRender();
8627
- let credentials;
8628
7620
  try {
8629
- credentials = await this.deps.resolveTransport(transport);
7621
+ await this.verify(model, key);
7622
+ if (!this.save({ classifier: JEV_API_KEY_CLASSIFIER, transport: "auto" })) {
7623
+ throw new Error("Could not save the Jev classifier selection.");
7624
+ }
7625
+ this.notice = "Stored Jev API Key verified.";
8630
7626
  } catch (error) {
8631
- this.mode = "menu";
8632
- this.notice = `Credential lookup failed: ${error instanceof Error ? error.message : String(error)}`;
8633
- this.options.tui.requestRender();
8634
- return;
7627
+ this.mode = "list";
7628
+ this.notice = `Verification failed: ${error instanceof Error ? error.message : "provider error"}`;
8635
7629
  }
8636
- this.credentials = credentials;
8637
- this.mode = "menu";
8638
- if (!credentials) {
8639
- if (transport === "typesafe" || transport === "openai-decisions") {
8640
- this.notice = undefined;
8641
- this.openKeyEntry(transport);
8642
- } else {
8643
- this.notice = "No OpenRouter Pi login found. Add one in Pi and retry.";
8644
- }
7630
+ this.options.tui.requestRender();
7631
+ }
7632
+ async handleKeySubmit() {
7633
+ try {
7634
+ await this.verifyKey();
7635
+ } catch (error) {
7636
+ this.notice = `Verification failed: ${error instanceof Error ? error.message : "provider error"}`;
7637
+ this.mode = "key";
8645
7638
  this.options.tui.requestRender();
8646
- return;
8647
7639
  }
8648
- if (credentials.transport !== transport) {
8649
- this.notice = "The selected provider did not resolve matching credentials.";
8650
- this.options.tui.requestRender();
8651
- return;
7640
+ }
7641
+ save(selection) {
7642
+ const saved = this.options.onSelection?.(selection) ?? false;
7643
+ if (saved) {
7644
+ this.options.done(selection.classifier);
7645
+ } else {
7646
+ this.mode = "list";
7647
+ this.notice = "Verified, but settings could not be saved.";
8652
7648
  }
8653
- await this.verifyAndSave(credentials);
7649
+ return saved;
8654
7650
  }
8655
- async submitEnteredKey(value) {
8656
- const transport = this.selectedTransport;
8657
- const key = value.trim();
8658
- this.maskedInput.setValue("");
8659
- if (!transport || !key) {
8660
- return;
7651
+ }
7652
+
7653
+ // src/ui/jev-filter-submenu.ts
7654
+ import { Key as Key3, matchesKey as matchesKey3, truncateToWidth as truncateToWidth5 } from "@earendil-works/pi-tui";
7655
+ var actionsFor = (enabled) => enabled ? ["disable", "done"] : ["enable", "done"];
7656
+ var labelFor2 = (action) => {
7657
+ if (action === "enable") {
7658
+ return "Enable the filter";
7659
+ }
7660
+ return action === "disable" ? "Disable the filter" : "Done";
7661
+ };
7662
+
7663
+ class JevFilterSubmenu {
7664
+ options;
7665
+ mode = "resolving";
7666
+ notice;
7667
+ selectedIndex = 0;
7668
+ enabled;
7669
+ classifierAvailable = false;
7670
+ modelRegistry;
7671
+ resolveClassifierKey;
7672
+ _focused = true;
7673
+ constructor(options) {
7674
+ this.options = options;
7675
+ this.modelRegistry = options.modelRegistry;
7676
+ this.resolveClassifierKey = options.resolveClassifierKey;
7677
+ this.enabled = options.currentValue.startsWith("On");
7678
+ this.refresh();
7679
+ }
7680
+ get focused() {
7681
+ return this._focused;
7682
+ }
7683
+ set focused(value) {
7684
+ this._focused = value;
7685
+ }
7686
+ invalidate() {}
7687
+ render(width) {
7688
+ const { theme } = this.options;
7689
+ const lines = [
7690
+ theme.fg("accent", theme.bold(" Jev classifier consultation filter")),
7691
+ "",
7692
+ ` Filter: ${this.enabled ? "On" : "Off"}`,
7693
+ ` Classifier: ${this.options.currentClassifier ?? "not selected"}`
7694
+ ];
7695
+ if (this.mode === "resolving") {
7696
+ lines.push("", " Checking selected classifier availability…");
7697
+ } else if (this.notice) {
7698
+ lines.push("", theme.fg("warning", ` ${this.notice}`));
8661
7699
  }
8662
- const credentials = { apiKey: key, transport };
8663
- if (transport === "typesafe-compatible" && this.baseUrl) {
8664
- credentials.baseUrl = this.baseUrl;
7700
+ if (this.mode === "menu") {
7701
+ lines.push("");
7702
+ for (const [index, action] of actionsFor(this.enabled).entries()) {
7703
+ lines.push(`${index === this.selectedIndex ? "→ " : " "}${labelFor2(action)}`);
7704
+ }
8665
7705
  }
8666
- await this.verifyAndSave(credentials, key);
7706
+ return lines.map((line) => truncateToWidth5(line, width));
8667
7707
  }
8668
- async verifyAndSave(credentials, enteredKey) {
8669
- this.mode = "verifying";
8670
- this.notice = undefined;
8671
- this.options.tui.requestRender();
8672
- const outcome = await this.deps.verify(credentials);
8673
- if (!outcome.ok) {
8674
- this.notice = `Verification failed: ${outcome.message ?? "unknown error"}`;
8675
- this.mode = enteredKey ? "key-entry" : "menu";
8676
- this.canEnterKey = !enteredKey && canReplaceWithEnteredKey(credentials);
8677
- this.options.tui.requestRender();
7708
+ handleInput(keyData) {
7709
+ if (this.mode !== "menu") {
8678
7710
  return;
8679
7711
  }
8680
- if (enteredKey) {
8681
- const stored = await this.deps.writeKey(enteredKey, credentials.transport);
8682
- if (!stored.ok) {
8683
- this.notice = stored.message;
8684
- this.mode = "key-entry";
8685
- this.canEnterKey = false;
8686
- this.options.tui.requestRender();
8687
- return;
8688
- }
8689
- this.notice = `${stored.message} Verification succeeded.`;
8690
- if (credentials.transport === "typesafe-compatible") {
8691
- this.providerId = undefined;
8692
- }
8693
- }
8694
- this.credentials = credentials;
8695
- if (this.commitSelection(credentials)) {
8696
- this.closeSetup(true);
7712
+ const actions = actionsFor(this.enabled);
7713
+ if (matchesKey3(keyData, Key3.down) || keyData === "\x1B[B" || keyData === "\x1BOB") {
7714
+ this.selectedIndex = (this.selectedIndex + 1) % actions.length;
7715
+ } else if (matchesKey3(keyData, Key3.up) || keyData === "\x1B[A" || keyData === "\x1BOA") {
7716
+ this.selectedIndex = (this.selectedIndex - 1 + actions.length) % actions.length;
7717
+ } else if (matchesKey3(keyData, Key3.enter) || keyData === "\r") {
7718
+ this.activate(actions[this.selectedIndex]);
7719
+ } else {
8697
7720
  return;
8698
7721
  }
8699
- this.mode = "menu";
8700
- this.canEnterKey = false;
8701
- this.notice = "Provider verified, but settings could not be saved.";
8702
7722
  this.options.tui.requestRender();
8703
7723
  }
8704
- commitSelection(credentials) {
8705
- if (!this.options.onSelection) {
8706
- return false;
7724
+ async refresh() {
7725
+ const selected = this.options.currentClassifier;
7726
+ try {
7727
+ if (selected === JEV_API_KEY_CLASSIFIER) {
7728
+ const stored = await (this.resolveClassifierKey ?? readJevClassifierKey)();
7729
+ this.classifierAvailable = Boolean(stored.key);
7730
+ if (stored.failed) {
7731
+ this.notice = "Could not read the stored Jev API Key state; try again later.";
7732
+ } else if (!this.classifierAvailable) {
7733
+ this.notice = "No Jev API Key is stored. Choose Jev API Key in Jev classifier settings.";
7734
+ }
7735
+ } else {
7736
+ const parsed = selected ? parseJevClassifierRef(selected) : undefined;
7737
+ const registry = this.modelRegistry;
7738
+ if (parsed && registry) {
7739
+ const available = await registry.getAvailableOfType("classifier", parsed.provider);
7740
+ this.classifierAvailable = available.some((model) => model.id === parsed.modelId);
7741
+ }
7742
+ if (!this.classifierAvailable) {
7743
+ this.notice = "Select an available authenticated classifier in Jev classifier settings first.";
7744
+ }
7745
+ }
7746
+ } catch (error) {
7747
+ this.notice = `Classifier lookup failed: ${error instanceof Error ? error.message : "Pi error"}`;
8707
7748
  }
8708
- return this.options.onSelection(this.selectionFor(credentials));
7749
+ this.mode = "menu";
7750
+ this.options.tui.requestRender();
8709
7751
  }
8710
- selectionFor(credentials) {
8711
- if (credentials.transport !== "typesafe-compatible") {
8712
- return { transport: credentials.transport };
8713
- }
8714
- const selection = {
8715
- transport: credentials.transport
8716
- };
8717
- if (this.baseUrl) {
8718
- selection.baseUrl = this.baseUrl;
7752
+ activate(action) {
7753
+ if (action === "done") {
7754
+ this.options.done();
7755
+ return;
8719
7756
  }
8720
- if (this.providerId) {
8721
- selection.keyProvider = this.providerId;
7757
+ const enabled = action === "enable";
7758
+ if (enabled && !this.classifierAvailable) {
7759
+ this.options.tui.requestRender();
7760
+ return;
8722
7761
  }
8723
- return selection;
8724
- }
8725
- async clearStoredKey() {
8726
- const { credentials } = this;
8727
- if (!(credentials && credentials.source)) {
7762
+ if (this.options.onSelection?.({ enabled }) === false) {
7763
+ this.notice = "The filter state could not be saved.";
7764
+ this.options.tui.requestRender();
8728
7765
  return;
8729
7766
  }
8730
- this.mode = "clearing";
7767
+ this.enabled = enabled;
8731
7768
  this.notice = undefined;
8732
- this.options.tui.requestRender();
8733
- const result = await this.deps.clearStoredKey(credentials.transport);
8734
- this.mode = "menu";
8735
- this.notice = result.message;
8736
- if (result.ok) {
8737
- this.credentials = undefined;
8738
- this.pendingSelectionRefresh = true;
8739
- }
8740
- this.options.tui.requestRender();
8741
- }
8742
- closeSetup(refreshSettings = false) {
8743
- this.options.done();
8744
- if (refreshSettings || this.pendingSelectionRefresh) {
8745
- this.options.afterSelection?.();
8746
- }
8747
- this.pendingSelectionRefresh = false;
7769
+ this.options.done(enabled ? "On" : "Off");
8748
7770
  }
8749
7771
  }
8750
7772
 
@@ -8756,7 +7778,7 @@ class SearchableModelMultiSelector extends ModelSelectorAdapter {
8756
7778
  }
8757
7779
 
8758
7780
  // src/ui/text-setting-submenu.ts
8759
- import { Input as Input4, truncateToWidth as truncateToWidth7 } from "@earendil-works/pi-tui";
7781
+ import { Input as Input4, truncateToWidth as truncateToWidth6 } from "@earendil-works/pi-tui";
8760
7782
 
8761
7783
  class TextSettingSubmenu {
8762
7784
  input = new Input4;
@@ -8803,7 +7825,7 @@ class TextSettingSubmenu {
8803
7825
  lines.push(theme.fg("error", ` ${this.error}`));
8804
7826
  }
8805
7827
  lines.push("", theme.fg("dim", " Enter: apply · Esc: cancel"));
8806
- return lines.map((line) => truncateToWidth7(line, width));
7828
+ return lines.map((line) => truncateToWidth6(line, width));
8807
7829
  }
8808
7830
  handleInput(keyData) {
8809
7831
  const before = this.input.getValue();
@@ -8832,47 +7854,43 @@ var scoutTimeoutItem = (settings) => {
8832
7854
  values: numericValues(timeoutMs, [5000, 1e4, 15000, 30000, 45000, 60000, 90000, 120000])
8833
7855
  };
8834
7856
  };
8835
- var jevProviderLabel = (settings) => {
8836
- const transport = settings.jevTransport ?? DEFAULT_JEV_TRANSPORT;
8837
- if (transport === "auto") {
8838
- return "Auto (TypeSafe → OpenRouter)";
7857
+ var jevFilterRowValue = (settings) => {
7858
+ if (!settings.jevFilterEnabled) {
7859
+ return "Off";
8839
7860
  }
8840
- if (transport === "typesafe-compatible") {
8841
- const baseUrl = settings.jevBaseUrl ?? "no Base URL";
8842
- return settings.jevKeyProvider ? `System One–compatible (${baseUrl}; Pi login "${settings.jevKeyProvider}")` : `System One–compatible (${baseUrl})`;
8843
- }
8844
- return providerName(transport);
7861
+ return settings.jevClassifier ? "On" : "On (unavailable: no classifier)";
8845
7862
  };
8846
- var jevItems = (settings, theme, tui, jevSetupDeps, onJevFilter, onJevProvider, afterJevSetup) => [
7863
+ var jevItems = (settings, theme, tui, jevClassifierRegistry, jevKeyDeps, onJevFilter, onJevProvider) => [
8847
7864
  {
8848
- currentValue: jevProviderLabel(settings),
8849
- description: "Provider used for screening and the turn gate. Credentials are live-verified before a provider is saved.",
7865
+ currentValue: settings.jevClassifier ?? "Choose classifier",
7866
+ description: "Select a Pi-authenticated classifier or explicitly configure the separate Jev API Key option.",
8850
7867
  id: "jevProvider",
8851
- label: "Jev provider",
8852
- submenu: (currentValue, done) => new JevProviderSubmenu({
8853
- afterSelection: afterJevSetup,
8854
- currentBaseUrl: settings.jevBaseUrl,
8855
- currentKeyProvider: settings.jevKeyProvider,
8856
- currentTransport: settings.jevTransport ?? DEFAULT_JEV_TRANSPORT,
7868
+ label: "Jev classifier",
7869
+ submenu: (currentValue, done) => new JevClassifierSubmenu({
8857
7870
  currentValue,
8858
7871
  done,
7872
+ keybindings: getKeybindings(),
7873
+ modelRegistry: jevClassifierRegistry,
8859
7874
  onSelection: onJevProvider,
8860
- setupDeps: jevSetupDeps,
7875
+ persistKey: jevKeyDeps?.persistClassifierKey,
7876
+ resolveStoredKey: jevKeyDeps?.resolveClassifierKey,
7877
+ restoreKey: jevKeyDeps?.restoreClassifierKey,
8861
7878
  theme,
8862
7879
  tui
8863
7880
  })
8864
7881
  },
8865
7882
  {
8866
- currentValue: settingValue(settings.jevFilterEnabled, false),
7883
+ currentValue: jevFilterRowValue(settings),
8867
7884
  description: "Screen low-stakes ask_advisor consultations with the selected Jev provider.",
8868
7885
  id: "jevFilter",
8869
7886
  label: "Jev/Decisions consultation filter",
8870
7887
  submenu: (currentValue, done) => new JevFilterSubmenu({
8871
- currentTransport: settings.jevTransport ?? DEFAULT_JEV_TRANSPORT,
7888
+ currentClassifier: settings.jevClassifier,
8872
7889
  currentValue,
8873
7890
  done,
7891
+ modelRegistry: jevClassifierRegistry,
8874
7892
  onSelection: onJevFilter,
8875
- setupDeps: jevSetupDeps,
7893
+ resolveClassifierKey: jevKeyDeps?.resolveClassifierKey,
8876
7894
  theme,
8877
7895
  tui
8878
7896
  })
@@ -8898,21 +7916,6 @@ var jevItems = (settings, theme, tui, jevSetupDeps, onJevFilter, onJevProvider,
8898
7916
  label: "Jev override window",
8899
7917
  values: numericValues(settings.jevFilterOverrideWindow ?? DEFAULT_JEV_FILTER_OVERRIDE_WINDOW, [0, 3, 5, 10, 20, 50]).map((value) => `${value} turns`)
8900
7918
  },
8901
- {
8902
- currentValue: settings.jevModel ?? DEFAULT_JEV_MODEL,
8903
- description: "TypeSafe Jev model used for screening and turn-gate checks.",
8904
- id: "jevModel",
8905
- label: "Jev model",
8906
- submenu: (_currentValue, done) => new TextSettingSubmenu({
8907
- description: "Enter a TypeSafe model name (for example jev-latest or jev-1.13.0).",
8908
- initial: settings.jevModel ?? DEFAULT_JEV_MODEL,
8909
- onCancel: done,
8910
- onSubmit: (value) => ({ value: value.trim() || DEFAULT_JEV_MODEL }),
8911
- theme,
8912
- title: "Jev model",
8913
- tui
8914
- })
8915
- },
8916
7919
  {
8917
7920
  currentValue: String(settings.jevTimeoutMs ?? DEFAULT_JEV_TIMEOUT_MS),
8918
7921
  description: "Total wall-time budget for one Jev call, including retries.",
@@ -8927,13 +7930,6 @@ var jevItems = (settings, theme, tui, jevSetupDeps, onJevFilter, onJevProvider,
8927
7930
  label: "Jev digest chars",
8928
7931
  values: numericValues(settings.jevDigestMaxChars ?? DEFAULT_JEV_DIGEST_MAX_CHARS, [0, 1000, 2000, 4000, 8000, 15000])
8929
7932
  },
8930
- {
8931
- currentValue: String(settings.jevPricePerMtok ?? DEFAULT_JEV_PRICE_PER_MTOK),
8932
- description: "TypeSafe/OpenRouter estimated input price per million tokens; ignored for OpenAI Decisions, whose cost is unavailable.",
8933
- id: "jevPricePerMtok",
8934
- label: "Jev price/Mtok",
8935
- values: numericValues(settings.jevPricePerMtok ?? DEFAULT_JEV_PRICE_PER_MTOK, [0.01, 0.02, 0.042, 0.05, 0.1])
8936
- },
8937
7933
  {
8938
7934
  currentValue: settings.jevTurnGateEveryTurns === 0 || settings.jevTurnGateEveryTurns === undefined ? "Off" : `every ${settings.jevTurnGateEveryTurns} turns`,
8939
7935
  description: "Proactively consult the Advisor every N turns without a consultation (0 = off).",
@@ -8999,8 +7995,8 @@ var createSettingsItems = ({
8999
7995
  modelWhitelist,
9000
7996
  presets,
9001
7997
  settings,
9002
- afterJevSetup,
9003
- jevSetupDeps,
7998
+ jevClassifierRegistry,
7999
+ jevKeyDeps,
9004
8000
  onJevFilter,
9005
8001
  onJevProvider,
9006
8002
  theme,
@@ -9144,7 +8140,7 @@ var createSettingsItems = ({
9144
8140
  title: "Tool disclosure policies",
9145
8141
  tui
9146
8142
  })
9147
- }, 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, jevSetupDeps, onJevFilter, onJevProvider, afterJevSetup));
8143
+ }, 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));
9148
8144
  return items;
9149
8145
  };
9150
8146
 
@@ -9360,10 +8356,6 @@ var applyJevMutation = (settings, id, value) => {
9360
8356
  settings.jevTurnGateNoulThreshold = Number(value);
9361
8357
  return true;
9362
8358
  }
9363
- case "jevModel": {
9364
- settings.jevModel = value.trim() || DEFAULT_JEV_MODEL;
9365
- return true;
9366
- }
9367
8359
  case "jevTimeoutMs": {
9368
8360
  settings.jevTimeoutMs = Number(value);
9369
8361
  return true;
@@ -9376,10 +8368,6 @@ var applyJevMutation = (settings, id, value) => {
9376
8368
  settings.jevDigestMaxChars = Number(value);
9377
8369
  return true;
9378
8370
  }
9379
- case "jevPricePerMtok": {
9380
- settings.jevPricePerMtok = Number(value);
9381
- return true;
9382
- }
9383
8371
  default: {
9384
8372
  return false;
9385
8373
  }
@@ -9444,7 +8432,7 @@ class AdvisorSettingsSelector {
9444
8432
  }
9445
8433
  render(width) {
9446
8434
  const border = this.options.theme.fg("border", "─".repeat(Math.max(1, width)));
9447
- return [border, ...this.settingsList.render(width), border].map((line) => truncateToWidth8(line, width));
8435
+ return [border, ...this.settingsList.render(width), border].map((line) => truncateToWidth7(line, width));
9448
8436
  }
9449
8437
  handleInput(keyData) {
9450
8438
  if (!this.settingsList.changeWithArrow(keyData, (id, value) => this.change(id, value))) {
@@ -9464,13 +8452,14 @@ class AdvisorSettingsSelector {
9464
8452
  const fallbackModel = advisorFallbackModelItem(this.settings, this.options.modelRefs, this.options.keybindings, this.options.theme, this.options.tui);
9465
8453
  const modelWhitelist = advisorModelWhitelistItem(this.settings, this.options.modelRefs, this.options.keybindings, this.options.theme, this.options.tui);
9466
8454
  const items = createSettingsItems({
9467
- afterJevSetup: () => {
9468
- this.settingsList = this.createSettingsList("jevFilter");
9469
- this.options.tui.requestRender();
9470
- },
9471
8455
  effortLevels: this.options.effortLevels,
9472
8456
  fallbackModel,
9473
- jevSetupDeps: this.options.jevSetupDeps,
8457
+ jevClassifierRegistry: this.options.jevSetupDeps?.modelRegistry,
8458
+ jevKeyDeps: {
8459
+ persistClassifierKey: this.options.jevSetupDeps?.persistClassifierKey,
8460
+ resolveClassifierKey: this.options.jevSetupDeps?.resolveClassifierKey,
8461
+ restoreClassifierKey: this.options.jevSetupDeps?.restoreClassifierKey
8462
+ },
9474
8463
  modelWhitelist,
9475
8464
  onJevFilter: (selection) => this.applyJevFilter(selection),
9476
8465
  onJevProvider: (selection) => this.applyJevProvider(selection),
@@ -9514,24 +8503,30 @@ class AdvisorSettingsSelector {
9514
8503
  if (legacy) {
9515
8504
  return this.applyJevSelection(patch, (settings) => legacy({
9516
8505
  enabled: selection.enabled,
9517
- transport: settings.jevTransport ?? DEFAULT_JEV_TRANSPORT
8506
+ transport: settings.jevTransport ?? "auto"
9518
8507
  }, settings));
9519
8508
  }
9520
8509
  return this.applyJevSelection(patch);
9521
8510
  }
9522
8511
  applyJevProvider(selection) {
9523
- const custom = selection.transport === "typesafe-compatible";
9524
- const patch = {
9525
- jevBaseUrl: custom ? selection.baseUrl : this.settings.jevBaseUrl,
9526
- jevKeyProvider: custom ? selection.keyProvider : this.settings.jevKeyProvider,
9527
- jevTransport: selection.transport
9528
- };
8512
+ let patch;
8513
+ if (selection.classifier) {
8514
+ patch = { jevClassifier: selection.classifier };
8515
+ } else if (selection.transport) {
8516
+ patch = {
8517
+ jevBaseUrl: selection.baseUrl,
8518
+ jevKeyProvider: selection.keyProvider,
8519
+ jevTransport: selection.transport
8520
+ };
8521
+ } else {
8522
+ patch = {};
8523
+ }
9529
8524
  const handler = this.options.onJevProvider;
9530
8525
  if (handler) {
9531
8526
  return this.applyJevSelection(patch, (settings) => handler(selection, settings));
9532
8527
  }
9533
8528
  const legacy = this.options.onJevSetup;
9534
- if (legacy) {
8529
+ if (legacy && selection.transport) {
9535
8530
  return this.applyJevSelection(patch, (settings) => legacy({
9536
8531
  enabled: settings.jevFilterEnabled ?? false,
9537
8532
  transport: selection.transport
@@ -9603,16 +8598,12 @@ var applySessionSettings = (settings) => {
9603
8598
  };
9604
8599
  var applyJevSettings = (settings) => {
9605
8600
  setAdvisorJevFilterEnabledRef(settings.jevFilterEnabled ?? false);
9606
- setAdvisorJevBaseUrlRef(settings.jevBaseUrl);
9607
- setAdvisorJevKeyProviderRef(settings.jevKeyProvider);
8601
+ setAdvisorJevClassifierRef(settings.jevClassifier);
9608
8602
  setAdvisorJevFilterSkipConfidenceRef(settings.jevFilterSkipConfidence ?? DEFAULT_JEV_FILTER_SKIP_CONFIDENCE);
9609
8603
  setAdvisorJevFilterNoulMarginRef(settings.jevFilterNoulMargin ?? DEFAULT_JEV_FILTER_NOUL_MARGIN);
9610
8604
  setAdvisorJevFilterOverrideWindowRef(settings.jevFilterOverrideWindow ?? DEFAULT_JEV_FILTER_OVERRIDE_WINDOW);
9611
- setAdvisorJevModelRef(settings.jevModel ?? DEFAULT_JEV_MODEL);
9612
8605
  setAdvisorJevTimeoutMsRef(settings.jevTimeoutMs ?? DEFAULT_JEV_TIMEOUT_MS);
9613
8606
  setAdvisorJevDigestMaxCharsRef(settings.jevDigestMaxChars ?? DEFAULT_JEV_DIGEST_MAX_CHARS);
9614
- setAdvisorJevPricePerMtokRef(settings.jevPricePerMtok ?? DEFAULT_JEV_PRICE_PER_MTOK);
9615
- setAdvisorJevTransportRef(settings.jevTransport ?? DEFAULT_JEV_TRANSPORT);
9616
8607
  setAdvisorJevTurnGateEveryTurnsRef(settings.jevTurnGateEveryTurns ?? DEFAULT_JEV_TURN_GATE_EVERY_TURNS);
9617
8608
  setAdvisorJevTurnGateNoulThresholdRef(settings.jevTurnGateNoulThreshold ?? DEFAULT_JEV_TURN_GATE_NOUL_THRESHOLD);
9618
8609
  };
@@ -9682,8 +8673,10 @@ var registerSettingsCommands = (runtime) => {
9682
8673
  effortLevels: EFFORT_LEVELS,
9683
8674
  initial,
9684
8675
  jevSetupDeps: {
9685
- resolveEndpoint: (options) => resolveTypesafeCompatibleCredentials(options, ctx),
9686
- resolveTransport: (transport) => transport ? resolveJevTransportFor(transport, ctx) : resolveJevTransport(ctx)
8676
+ modelRegistry: ctx.modelRegistry,
8677
+ persistClassifierKey: writeJevClassifierKey,
8678
+ resolveClassifierKey: readJevClassifierKey,
8679
+ restoreClassifierKey: restoreJevClassifierKey
9687
8680
  },
9688
8681
  keybindings,
9689
8682
  modelRefs: getConfiguredModelRefs(ctx),
@@ -9843,15 +8836,7 @@ var reserveAdvisorCall = (event, ctx, session, reservedCalls) => {
9843
8836
  };
9844
8837
 
9845
8838
  // src/tools/jev-turn-gate.ts
9846
- var turnGateQuestion = {
9847
- criteria: {
9848
- false: "The executor is progressing soundly on work that matches the user's intent; interrupting would add nothing material.",
9849
- true: "The executor is approaching a material decision, repeating a failure, about to claim success without validation, or drifting from the user's intent; a second opinion now would change what happens next."
9850
- },
9851
- instructions: "Should a senior engineering advisor be consulted right now, before the executor continues? Judge from `recent_conversation`.",
9852
- type: "noul"
9853
- };
9854
- var outageNotifier2 = createOutageNotifier((category, message) => `Advisor Jev/Decisions turn gate failed (${category}); continuing without a proactive consultation. ${message}`);
8839
+ var outageNotifier2 = createOutageNotifier((category, message) => `Advisor Jev classifier turn gate failed (${category}); continuing without a proactive consultation. ${message}`);
9855
8840
  var notifyFailureOnce = outageNotifier2.notify;
9856
8841
  var shouldRunTurnGate = (registration, ctx, session) => {
9857
8842
  const interval = advisorJevTurnGateEveryTurnsRef;
@@ -9865,6 +8850,61 @@ var consumeTurnGateBudget = (session, shouldConsult) => {
9865
8850
  return true;
9866
8851
  };
9867
8852
  var resetJevTurnGateNotification = outageNotifier2.reset;
8853
+ var classifyGate = async (ctx, deps) => {
8854
+ if (deps.classifyResult) {
8855
+ return deps.classifyResult();
8856
+ }
8857
+ const selectedRef = advisorJevClassifierModeRef === "api-key" ? "typesafe/jev-latest" : deps.selectedRef?.() ?? advisorJevClassifierRef;
8858
+ const apiKey = advisorJevClassifierModeRef === "api-key" ? await (deps.resolveApiKey ?? consumeJevClassifierKey)() : undefined;
8859
+ if (!selectedRef || advisorJevClassifierModeRef === "api-key" && !apiKey) {
8860
+ throw new JevFailureError("auth", "No credentials resolved for the selected Jev classifier.");
8861
+ }
8862
+ return classifyTurnGate(ctx, selectedRef, buildJevState(ctx, {}), {
8863
+ apiKey,
8864
+ signal: ctx.signal
8865
+ });
8866
+ };
8867
+ var sendProactiveConsultation = async (registration, ctx, consult) => {
8868
+ const { session } = registration;
8869
+ const activity = registration.herdrActivity ?? herdrAdvisorActivity;
8870
+ const finishHerdrActivity = activity.start();
8871
+ try {
8872
+ registration.send({
8873
+ content: "Proactive Advisor turn review",
8874
+ customType: "advisor-turn-gate-call",
8875
+ details: {
8876
+ question: `Turn gate: ${session.turnsSinceConsultation} turns without a consultation`,
8877
+ turn: session.sessionTurnOrdinal
8878
+ },
8879
+ display: true
8880
+ });
8881
+ const consulted = await consult(ctx, undefined, ctx.signal, undefined, "turn-gate");
8882
+ session.recordJevGateConsultation();
8883
+ session.resetTurnsSinceConsultation();
8884
+ session.recordInvocation({
8885
+ cost: advisorUsageCost(consulted.usage),
8886
+ executionEffect: "continued",
8887
+ kind: "markdown",
8888
+ model: consulted.model,
8889
+ trigger: "turn-gate",
8890
+ usage: consulted.usage
8891
+ });
8892
+ updateAdvisorUsageStatus(ctx, session);
8893
+ registration.send({
8894
+ content: consulted.markdown,
8895
+ customType: "advisor-turn-gate-result",
8896
+ details: {
8897
+ advisor: consulted.model,
8898
+ agentRulesBytes: consulted.agentRulesBytes,
8899
+ text: consulted.markdown,
8900
+ usage: consulted.usage
8901
+ },
8902
+ display: true
8903
+ });
8904
+ } finally {
8905
+ finishHerdrActivity();
8906
+ }
8907
+ };
9868
8908
  var handleJevTurnEnd = async (registration, ctx) => {
9869
8909
  const { session } = registration;
9870
8910
  session.recordCompletedTurn();
@@ -9872,60 +8912,16 @@ var handleJevTurnEnd = async (registration, ctx) => {
9872
8912
  return;
9873
8913
  }
9874
8914
  const consult = registration.deps?.consult ?? registration.consult;
9875
- const deps = registration.deps ?? {};
9876
8915
  try {
9877
- const credentials = await (deps.resolveTransport ?? resolveJevTransport)(ctx);
9878
- if (!credentials) {
9879
- session.recordJevGateFailure();
9880
- notifyFailureOnce(ctx, "missing-key", "No credentials resolved for the selected Jev/Decisions provider.");
9881
- return;
9882
- }
9883
- const client = jevClientFromCredentials(credentials, deps.fetch);
9884
- const result = await client.ask(buildJevState(ctx, {}), {
9885
- should_consult: turnGateQuestion
9886
- });
9887
- session.recordJevGateCheck(result.usage);
8916
+ const result = await classifyGate(ctx, registration.deps ?? {});
8917
+ session.recordJevGateCheck(result.usage ? {
8918
+ cost: result.usage.cost,
8919
+ inputTokens: result.usage.inputTokens,
8920
+ outputTokens: result.usage.outputTokens
8921
+ } : undefined);
9888
8922
  const shouldConsult = composeTurnGateVerdict(result.answers, advisorJevTurnGateNoulThresholdRef);
9889
- if (!advisorModelIsAllowed(ctx) || !consumeTurnGateBudget(session, shouldConsult)) {
9890
- return;
9891
- }
9892
- const herdrActivity = registration.herdrActivity ?? herdrAdvisorActivity;
9893
- const finishHerdrActivity = herdrActivity.start();
9894
- try {
9895
- registration.send({
9896
- content: "Proactive Advisor turn review",
9897
- customType: "advisor-turn-gate-call",
9898
- details: {
9899
- question: `Turn gate: ${session.turnsSinceConsultation} turns without a consultation`,
9900
- turn: session.sessionTurnOrdinal
9901
- },
9902
- display: true
9903
- });
9904
- const consulted = await consult(ctx, undefined, ctx.signal, undefined, "turn-gate");
9905
- session.recordJevGateConsultation();
9906
- session.resetTurnsSinceConsultation();
9907
- session.recordInvocation({
9908
- cost: advisorUsageCost(consulted.usage),
9909
- executionEffect: "continued",
9910
- kind: "markdown",
9911
- model: consulted.model,
9912
- trigger: "turn-gate",
9913
- usage: consulted.usage
9914
- });
9915
- updateAdvisorUsageStatus(ctx, session);
9916
- registration.send({
9917
- content: consulted.markdown,
9918
- customType: "advisor-turn-gate-result",
9919
- details: {
9920
- advisor: consulted.model,
9921
- agentRulesBytes: consulted.agentRulesBytes,
9922
- text: consulted.markdown,
9923
- usage: consulted.usage
9924
- },
9925
- display: true
9926
- });
9927
- } finally {
9928
- finishHerdrActivity();
8923
+ if (advisorModelIsAllowed(ctx) && consumeTurnGateBudget(session, shouldConsult)) {
8924
+ await sendProactiveConsultation(registration, ctx, consult);
9929
8925
  }
9930
8926
  } catch (error) {
9931
8927
  session.recordJevGateFailure();
@@ -10190,6 +9186,7 @@ var registerAskAdvisorTool = ({
10190
9186
  reservedCalls.delete(_id);
10191
9187
  throw error;
10192
9188
  }
9189
+ let classifierUsage;
10193
9190
  const simpleMode = isSimpleMode();
10194
9191
  if (!simpleMode && !session.reserveCall(_id, getAdvisorMaxCallsPerSession())) {
10195
9192
  throw new Error("Advisor call budget exhausted for this session.");
@@ -10212,6 +9209,7 @@ var registerAskAdvisorTool = ({
10212
9209
  question: resolveAdvisorRequest(params.question),
10213
9210
  signal
10214
9211
  });
9212
+ classifierUsage = screening.usage;
10215
9213
  if (screening.decision === "skip") {
10216
9214
  const skipText = screeningSkipText(screening);
10217
9215
  session.releaseCall(_id);
@@ -10224,11 +9222,15 @@ var registerAskAdvisorTool = ({
10224
9222
  },
10225
9223
  text: skipText
10226
9224
  };
10227
- return {
9225
+ const skipResult = {
10228
9226
  content: [{ text: skipText, type: "text" }],
10229
9227
  details: skipped,
10230
9228
  structuredContent: skipped
10231
9229
  };
9230
+ if (classifierUsage) {
9231
+ skipResult.usage = classifierUsage;
9232
+ }
9233
+ return skipResult;
10232
9234
  }
10233
9235
  if (sameModelAdvisorDisabled(ctx, ctx.model, followUp?.payload.model)) {
10234
9236
  return skippedSameModelResult(_id, sameModelNoticeFor(followUp?.payload.model), reservedCalls, session);
@@ -10292,7 +9294,8 @@ var registerAskAdvisorTool = ({
10292
9294
  usage: result.usage
10293
9295
  });
10294
9296
  const usage = snapshotAdvisorUsage(result.usage);
10295
- const piUsage = advisorUsageForPi(result.usage);
9297
+ const advisorPiUsage = advisorUsageForPi(result.usage);
9298
+ const piUsage = combineAdvisorAndClassifierUsage(advisorPiUsage, classifierUsage);
10296
9299
  updateAdvisorUsageStatus(ctx, session);
10297
9300
  const details = {
10298
9301
  adviceId: result.adviceId,