pi-smart-router 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/.pi/extensions/smart-router/delegate-stream.ts +36 -4
  2. package/.pi/extensions/smart-router/route-and-delegate.ts +111 -17
  3. package/README.md +25 -13
  4. package/dist/domain/delegation/degenerate-output.d.ts +36 -0
  5. package/dist/domain/delegation/degenerate-output.d.ts.map +1 -0
  6. package/dist/domain/delegation/degenerate-output.js +75 -0
  7. package/dist/domain/delegation/degenerate-output.js.map +1 -0
  8. package/dist/domain/pipeline/local-zero-stage.d.ts +4 -0
  9. package/dist/domain/pipeline/local-zero-stage.d.ts.map +1 -1
  10. package/dist/domain/pipeline/local-zero-stage.js +23 -3
  11. package/dist/domain/pipeline/local-zero-stage.js.map +1 -1
  12. package/dist/domain/pipeline/low-intensity-stage.d.ts +3 -0
  13. package/dist/domain/pipeline/low-intensity-stage.d.ts.map +1 -1
  14. package/dist/domain/pipeline/low-intensity-stage.js +96 -14
  15. package/dist/domain/pipeline/low-intensity-stage.js.map +1 -1
  16. package/dist/domain/pipeline/router-pipeline.d.ts.map +1 -1
  17. package/dist/domain/pipeline/router-pipeline.js +39 -7
  18. package/dist/domain/pipeline/router-pipeline.js.map +1 -1
  19. package/dist/domain/pipeline/turn-envelope-stage.d.ts +1 -0
  20. package/dist/domain/pipeline/turn-envelope-stage.d.ts.map +1 -1
  21. package/dist/domain/pipeline/turn-envelope-stage.js +59 -2
  22. package/dist/domain/pipeline/turn-envelope-stage.js.map +1 -1
  23. package/dist/domain/routing/cross-provider-handoff.d.ts +39 -0
  24. package/dist/domain/routing/cross-provider-handoff.d.ts.map +1 -0
  25. package/dist/domain/routing/cross-provider-handoff.js +66 -0
  26. package/dist/domain/routing/cross-provider-handoff.js.map +1 -0
  27. package/dist/domain/routing/flash-class.d.ts +32 -0
  28. package/dist/domain/routing/flash-class.d.ts.map +1 -0
  29. package/dist/domain/routing/flash-class.js +58 -0
  30. package/dist/domain/routing/flash-class.js.map +1 -0
  31. package/dist/index.d.ts +1 -0
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +1 -0
  34. package/dist/index.js.map +1 -1
  35. package/dist/infrastructure/delegation/provider-error.d.ts.map +1 -1
  36. package/dist/infrastructure/delegation/provider-error.js +12 -4
  37. package/dist/infrastructure/delegation/provider-error.js.map +1 -1
  38. package/dist/infrastructure/gateway/gateway-dispatch.d.ts +31 -6
  39. package/dist/infrastructure/gateway/gateway-dispatch.d.ts.map +1 -1
  40. package/dist/infrastructure/gateway/gateway-dispatch.js +154 -13
  41. package/dist/infrastructure/gateway/gateway-dispatch.js.map +1 -1
  42. package/package.json +1 -1
  43. package/src/domain/delegation/degenerate-output.ts +124 -0
  44. package/src/domain/pipeline/local-zero-stage.ts +29 -3
  45. package/src/domain/pipeline/low-intensity-stage.ts +136 -19
  46. package/src/domain/pipeline/router-pipeline.ts +57 -7
  47. package/src/domain/pipeline/turn-envelope-stage.ts +81 -2
  48. package/src/domain/routing/cross-provider-handoff.ts +104 -0
  49. package/src/domain/routing/flash-class.ts +95 -0
  50. package/src/index.ts +11 -0
  51. package/src/infrastructure/delegation/provider-error.ts +13 -4
  52. package/src/infrastructure/gateway/gateway-dispatch.ts +193 -13
@@ -13,6 +13,8 @@ import {
13
13
  parseAssistantMessageError,
14
14
  extractUsageActuals,
15
15
  resolveAdaptiveReasoning,
16
+ DEGENERATE_OUTPUT_ERROR_CODE,
17
+ isDegenerateOutput,
16
18
  } from '../../../src/index.js';
17
19
  import type {
18
20
  AdaptiveReasoningResult,
@@ -271,6 +273,19 @@ export function commitPipedTerminal(
271
273
  outer.end(endMessage);
272
274
  }
273
275
 
276
+ export function resolveFailoverProviderError(
277
+ message: AssistantMessage,
278
+ ): ReturnType<typeof parseAssistantMessageError> {
279
+ const parsed = parseAssistantMessageError(message);
280
+ if (parsed) {
281
+ return parsed;
282
+ }
283
+ if (message.stopReason === 'error' && message.errorMessage) {
284
+ return { message: message.errorMessage };
285
+ }
286
+ return undefined;
287
+ }
288
+
274
289
  function recordDelegateOutcome(
275
290
  targetModel: Model<Api>,
276
291
  deps: StreamDelegationDeps,
@@ -299,11 +314,28 @@ function recordDelegateOutcome(
299
314
  }
300
315
  }
301
316
 
302
- if (result.failed) {
303
- const parsed = parseAssistantMessageError(result.finalMessage);
304
- deps.router.dispatch.recordOutcome(targetModel.id, parsed);
317
+ const degenerate = isDegenerateOutput(result.finalMessage);
318
+ if (result.failed || degenerate) {
319
+ const providerError = degenerate
320
+ ? {
321
+ code: DEGENERATE_OUTPUT_ERROR_CODE,
322
+ message: 'Model produced degenerate output',
323
+ truncated: true,
324
+ }
325
+ : resolveFailoverProviderError(result.finalMessage) ?? {
326
+ message: `Delegation failed (${result.finalMessage.stopReason})`,
327
+ };
328
+ if (requestId === undefined) {
329
+ deps.router.dispatch.recordOutcome(targetModel.id, providerError);
330
+ } else {
331
+ deps.router.dispatch.recordOutcome(targetModel.id, providerError, requestId);
332
+ }
305
333
  } else {
306
- deps.router.dispatch.recordOutcome(targetModel.id);
334
+ if (requestId === undefined) {
335
+ deps.router.dispatch.recordOutcome(targetModel.id);
336
+ } else {
337
+ deps.router.dispatch.recordOutcome(targetModel.id, undefined, requestId);
338
+ }
307
339
  if (sessionId) {
308
340
  deps.executionLedger.recordSuccess(sessionId, modelToExecutionModel(targetModel));
309
341
  }
@@ -18,7 +18,6 @@ import {
18
18
  isGoogleGeminiProfile,
19
19
  resolveEffectiveFleet,
20
20
  isGeminiThoughtSignatureAssistantError,
21
- parseAssistantMessageError,
22
21
  GEMINI_REPLAY_INCOMPATIBLE,
23
22
  shouldFailoverOnProviderError,
24
23
  } from '../../../src/index.js';
@@ -32,8 +31,14 @@ import type {
32
31
  import {
33
32
  commitPipedTerminal,
34
33
  delegateWithOutcome,
34
+ resolveFailoverProviderError,
35
35
  type PipedDelegatedStreamResult,
36
36
  } from './delegate-stream.js';
37
+ import {
38
+ DEGENERATE_OUTPUT,
39
+ DEGENERATE_OUTPUT_ERROR_CODE,
40
+ isDegenerateOutput,
41
+ } from '../../../src/index.js';
37
42
  import {
38
43
  createErrorMessage,
39
44
  findFleetProfile,
@@ -65,19 +70,6 @@ function isRoutingLogEnabled(): boolean {
65
70
  return process.env.SMART_ROUTER_LOG_ROUTING === '1';
66
71
  }
67
72
 
68
- function resolveFailoverProviderError(
69
- message: AssistantMessage,
70
- ): ReturnType<typeof parseAssistantMessageError> {
71
- const parsed = parseAssistantMessageError(message);
72
- if (parsed) {
73
- return parsed;
74
- }
75
- if (message.stopReason === 'error' && message.errorMessage) {
76
- return { message: message.errorMessage };
77
- }
78
- return undefined;
79
- }
80
-
81
73
  function logRoutingDecision(
82
74
  decision: RoutingDecision,
83
75
  delegate?: { provider: string; modelId: string; api: Api },
@@ -175,6 +167,21 @@ function isZeroOutputLengthStop(message: AssistantMessage): boolean {
175
167
  return message.stopReason === 'length' && message.usage.output === 0;
176
168
  }
177
169
 
170
+ type DelegationProviderError = NonNullable<ReturnType<typeof resolveFailoverProviderError>>;
171
+
172
+ function isSameRequestCaused4xx(
173
+ current: DelegationProviderError,
174
+ previous: DelegationProviderError,
175
+ ): boolean {
176
+ return (
177
+ current.statusCode !== undefined &&
178
+ current.statusCode === previous.statusCode &&
179
+ current.statusCode >= 400 &&
180
+ current.statusCode < 500 &&
181
+ current.statusCode !== 429
182
+ );
183
+ }
184
+
178
185
  /** Minimal model identity for degraded terminal messages when no Model resolved. */
179
186
  interface DegradedModelRef {
180
187
  readonly api: Api;
@@ -463,8 +470,10 @@ export async function routeAndDelegate(
463
470
  });
464
471
 
465
472
  const failedModelIds: string[] = [];
473
+ const failedAttempts: Array<{ modelId: string; error: DelegationProviderError }> = [];
466
474
  const headroomExcludedModelIds: string[] = [];
467
475
  let geminiReplayFailoverAttempted = false;
476
+ let degenerateOutputFailoverAttempted = false;
468
477
  const estimatedInputTokens =
469
478
  request.estimated_input_tokens ?? request.prompt_text.length;
470
479
  let pendingFailoverInfo: FailoverNoticeInfo | undefined;
@@ -593,6 +602,63 @@ export async function routeAndDelegate(
593
602
  }
594
603
  }
595
604
 
605
+ if (result.finalMessage && isDegenerateOutput(result.finalMessage)) {
606
+ // SP-325 / #181: discard the repetitive terminal, count it through the
607
+ // SP-322 model-failure policy (in recordDelegateOutcome), and retry the
608
+ // original context. The bad assistant turn was never added to that context.
609
+ if (!failedModelIds.includes(targetModel.id)) {
610
+ failedModelIds.push(targetModel.id);
611
+ }
612
+ const selectedFailover = degenerateOutputFailoverAttempted
613
+ ? undefined
614
+ : deps.router.dispatch.selectFailover(
615
+ decision,
616
+ failedModelIds,
617
+ effectiveFleet,
618
+ );
619
+ // Bound this post-stream retry independently of selector behavior. A
620
+ // repetitive alternate must terminate instead of cycling indefinitely.
621
+ degenerateOutputFailoverAttempted = true;
622
+ const failover = selectedFailover
623
+ ? { ...selectedFailover, reason_code: DEGENERATE_OUTPUT }
624
+ : undefined;
625
+ const alternateModel = failover ? resolveTargetModel(deps, failover) : undefined;
626
+
627
+ if (failover && alternateModel && alternateModel.id !== targetModel.id) {
628
+ console.warn(
629
+ '[smart-router] degenerate output, failing over to alternate model',
630
+ JSON.stringify({
631
+ reason_code: DEGENERATE_OUTPUT,
632
+ failed_model_id: targetModel.id,
633
+ selected_model_id: alternateModel.id,
634
+ }),
635
+ );
636
+ pendingFailoverInfo = {
637
+ failedModelId: targetModel.id,
638
+ alternateModelId: alternateModel.id,
639
+ errorObj: {
640
+ code: DEGENERATE_OUTPUT_ERROR_CODE,
641
+ message: 'Model produced degenerate output',
642
+ },
643
+ };
644
+ decision = failover;
645
+ deps.onRoutingDecision?.(decision);
646
+ targetModel = alternateModel;
647
+ continue;
648
+ }
649
+
650
+ decision = { ...decision, reason_code: DEGENERATE_OUTPUT };
651
+ deps.onRoutingDecision?.(decision);
652
+ emitDegradedFailure(
653
+ outer,
654
+ targetModel,
655
+ targetModel.id,
656
+ DEGENERATE_OUTPUT,
657
+ 'Model produced degenerate output; no failover model available',
658
+ );
659
+ return;
660
+ }
661
+
596
662
  if (
597
663
  result.failed &&
598
664
  result.finalMessage &&
@@ -659,12 +725,37 @@ export async function routeAndDelegate(
659
725
  if (result.failed && result.finalMessage) {
660
726
  const providerError = resolveFailoverProviderError(result.finalMessage);
661
727
  const failedProfile = findFleetProfile(effectiveFleet, targetModel.id);
728
+ if (providerError) {
729
+ const currentTargetModelId = targetModel.id;
730
+ if (
731
+ failedAttempts.some(
732
+ (attempt) =>
733
+ attempt.modelId !== currentTargetModelId &&
734
+ isSameRequestCaused4xx(providerError, attempt.error),
735
+ )
736
+ ) {
737
+ // The same status on a distinct alternate points to the request,
738
+ // not either model. Undo all non-infra counts from this request.
739
+ deps.router.dispatch.recordRequestCausedFailure(decision.request_id);
740
+ console.warn(
741
+ '[smart-router] matching alternate 4xx, treating failure as request-caused',
742
+ JSON.stringify({
743
+ request_id: request.request_id,
744
+ status_code: providerError.statusCode,
745
+ }),
746
+ );
747
+ commitPipedTerminal(result, { sanitizeErrors: true });
748
+ return;
749
+ }
750
+ failedAttempts.push({ modelId: currentTargetModelId, error: providerError });
751
+ }
662
752
  if (
663
753
  providerError &&
664
754
  shouldFailoverOnProviderError(providerError, failedProfile)
665
755
  ) {
666
- deps.router.dispatch.recordOutcome(targetModel.id, providerError);
667
- failedModelIds.push(targetModel.id);
756
+ if (!failedModelIds.includes(targetModel.id)) {
757
+ failedModelIds.push(targetModel.id);
758
+ }
668
759
  const failover = deps.router.dispatch.selectFailover(
669
760
  decision,
670
761
  failedModelIds,
@@ -682,7 +773,9 @@ export async function routeAndDelegate(
682
773
  }
683
774
 
684
775
  console.warn(
685
- '[smart-router] infra error, failing over to alternate model',
776
+ failover.reason_code === 'model_repeated_failure'
777
+ ? '[smart-router] repeated model failure, failing over to alternate model'
778
+ : '[smart-router] infra error, failing over to alternate model',
686
779
  alternateModel.id,
687
780
  );
688
781
  // Discard held terminal from the failed attempt — do not forward to outer.
@@ -693,6 +786,7 @@ export async function routeAndDelegate(
693
786
  };
694
787
  decision = failover;
695
788
  targetModel = alternateModel;
789
+ deps.onRoutingDecision?.(decision);
696
790
  continue;
697
791
  }
698
792
  }
package/README.md CHANGED
@@ -24,14 +24,14 @@ request → hardware probe → loop escalation → turn envelope → typed judgm
24
24
 
25
25
  The pipeline runs **12 stages sequentially with early exit** — the moment any stage reaches a routing decision, subsequent stages are skipped. Every decision includes the stage name, reason code, candidates considered, estimated cost, and routing latency for full observability.
26
26
 
27
- \* `typed_judgment` is an additional **opt-in, non-deciding** stage (default off) that runs between turn envelope and the context-fit gate when enabled — it records judge answers for later consumers and never decides. See [Typed judgment (opt-in)](#typed-judgment-opt-in-183).
27
+ \* `typed_judgment` is an additional **opt-in, non-deciding** stage (default off) that runs between turn envelope and the context-fit gate when enabled — it records judge answers and never selects a model itself. Its [#188](https://github.com/beettlle/pi-smart-router/issues/188) consumers can use those answers for planning classification, tier hints, and local safety gates. See [Typed judgment (opt-in)](#typed-judgment-opt-in-183).
28
28
 
29
29
  | Stage | Budget | What it does |
30
30
  |-------|--------|--------------|
31
31
  | Hardware Probe | — | Checks platform/RAM/battery to gate local inference |
32
32
  | Loop Escalation | — | Detects repeated identical tool failures; escalates session to frontier |
33
33
  | Turn Envelope | <2ms | Classifies turn type: tool_result, planning, subagent, main_loop |
34
- | Typed Judgment (opt-in) | ~385–990ms per judged user turn when enabled; 0 otherwise | **Non-deciding** (default off): asks a Jev-compatible judge six questions about the turn and records the answers — never decides |
34
+ | Typed Judgment (opt-in) | ~385–990ms per judged user turn when enabled; 0 otherwise | **Non-deciding** (default off): asks a Jev-compatible judge six questions and records the answers; downstream #188 consumers may use them for planning, tier hints, and local gates |
35
35
  | Context-Fit Gate | — | Filters fleet to models whose context window fits estimated input tokens |
36
36
  | Low-Intensity Gate | — | Structural tier hint, cluster match, and P(success) expected-cost scoring |
37
37
  | Session Pin | <1ms | Returns pinned model if session has one; breaks pin on compaction or overflow |
@@ -569,18 +569,30 @@ Floor/ceiling bind only what the policy itself derives. An explicit operator `/t
569
569
 
570
570
  ### Typed judgment (opt-in) (#183)
571
571
 
572
- Typed judgment is an **opt-in, non-deciding** pipeline stage (`typed_judgment`, directly after `turn_envelope` and before `context_fit`) that asks a Jev-compatible “systemone” semantic judge six structured questions about each user-prompt turn and records the normalized answers on the routing context. **In v1.3.0 the answers are recorded only — they do not change routing decisions.** Downstream consumers (tier hints, capability gating, adaptive reasoning) land in later trains ([#188](https://github.com/beettlle/pi-smart-router/issues/188)–[#190](https://github.com/beettlle/pi-smart-router/issues/190)); do not expect any routing behavior change from enabling the stage today.
572
+ Typed judgment is an **opt-in, non-deciding** pipeline stage (`typed_judgment`, directly after `turn_envelope` and before `context_fit`) that asks a Jev-compatible “systemone” semantic judge six structured questions about each user-prompt turn and records the normalized answers on the routing context. The stage itself never selects a model. With [#188](https://github.com/beettlle/pi-smart-router/issues/188) landed, enabling the stage allows downstream `turn_envelope`, `low_intensity`, and `local_zero` consumers to use those answers as described below. The default remains **off**, and a missing judgment preserves the deterministic / regex fallback behavior.
573
573
 
574
- The six questions (stable ids):
574
+ The six questions (stable ids), their normalized forms, and their consumers:
575
575
 
576
- | Question id | Kind | What it asks |
577
- |-------------|------|--------------|
578
- | `task_kind` | choice (10 anchored options) | The single kind of work the user message asks for: `plan`, `implement`, `debug`, `refactor`, `review`, `research`, `explain`, `operate`, `write`, `chat` |
579
- | `capability_deserved` | score 0–3 | Setting price aside, how much model capability the request deserves |
580
- | `needs_deep_reasoning` | noul (yes/no) | Whether the turn needs extended multi-step reasoning rather than recall, lookup, or a short direct edit |
581
- | `code_gen` | score 0–3 | How much code or configuration must be written or modified |
582
- | `tool_use` | score 0–3 | How much tool execution (shell, file, search, agentic calls) the turn requires |
583
- | `destructive` | noul (yes/no) | Whether satisfying the request could destroy, overwrite, or irreversibly modify data, state, or history |
576
+ | Question id | Kind | What it asks | Normalized signal and consumer |
577
+ |-------------|------|--------------|--------------------------------|
578
+ | `task_kind` | choice (10 anchored options) | The single kind of work the user message asks for: `plan`, `implement`, `debug`, `refactor`, `review`, `research`, `explain`, `operate`, `write`, `chat` | `task_kind` plus `task_kind_confidence`; consumed by `turn_envelope` for planning classification (#188) |
579
+ | `capability_deserved` | score 0–3 | Setting price aside, how much model capability the request deserves | `0`, `1/3`, `2/3`, or `1`; consumed by `low_intensity` for tier hints and capability filtering (#188) |
580
+ | `needs_deep_reasoning` | noul (yes/no) | Whether the turn needs extended multi-step reasoning rather than recall, lookup, or a short direct edit | `deep_reasoning_p` (0–1); recorded only — the adaptive-reasoning consumer remains [#190](https://github.com/beettlle/pi-smart-router/issues/190) |
581
+ | `code_gen` | score 0–3 | How much code or configuration must be written or modified | `0`, `1/3`, `2/3`, or `1`; recorded only — the HyDRA requirement-source consumer remains [#189](https://github.com/beettlle/pi-smart-router/issues/189) |
582
+ | `tool_use` | score 0–3 | How much tool execution (shell, file, search, agentic calls) the turn requires | `0`, `1/3`, `2/3`, or `1`; consumed by the `local_zero` capability gate (#188) |
583
+ | `destructive` | noul (yes/no) | Whether satisfying the request could destroy, overwrite, or irreversibly modify data, state, or history | `destructive_p` (0–1); consumed by the `local_zero` safety gate (#188) |
584
+
585
+ **Landed #188 consumer behavior:**
586
+
587
+ | Consumer | Judgment field | Behavior and attribution |
588
+ |----------|----------------|--------------------------|
589
+ | `turn_envelope` | `task_kind` | At confidence ≥ `typed_judgment.min_confidence`, `plan`, `debug`, or `review` selects planning classification. A confident non-planning answer can replace only regex-derived planning when the host did not explicitly set `turn_type`. A positive judgment-driven planning override uses reason code `typed_judgment_planning`. |
590
+ | `low_intensity` | `capability_deserved` | Level 0 hints `zero-tier`, level 1 (`1/3`) hints `economical-cloud`, and levels 2–3 (`≥2/3`) hint `frontier-cloud`. Any non-zero level removes zero-tier and flash-class candidates when another healthy candidate remains. At confidence ≥ `min_confidence` the judgment may replace the prior hint in either direction; below the threshold it may only raise a tier. Session-depth and loop-escalation frontier floors still win, and context-fit constraints remain authoritative. Explain attribution uses `typed_judgment_tier_zero-tier`, `typed_judgment_tier_economical-cloud`, or `typed_judgment_tier_frontier-cloud`. |
591
+ | `local_zero` | `destructive`, `tool_use` | `destructive_p ≥ 0.7` or judged `tool_use` above the effective local ceiling skips local dispatch with `typed_judgment_destructive` or `typed_judgment_tool_use_shortfall`. The ceiling is `min(local model tool_use capability, local_zero.max_tool_use_requirement)`. These safety gates may skip local dispatch even below `min_confidence`; a missing `tool_use` answer retains the legacy cue-count gate, and a null judgment retains prior behavior. |
592
+
593
+ **Remaining Sprint 2 work:** [#189](https://github.com/beettlle/pi-smart-router/issues/189) (typed judgment as a HyDRA requirement source), [#190](https://github.com/beettlle/pi-smart-router/issues/190) (adaptive reasoning from `needs_deep_reasoning`), and [#191](https://github.com/beettlle/pi-smart-router/issues/191) (eval comparison and latency benchmark). Epic [#183](https://github.com/beettlle/pi-smart-router/issues/183) therefore remains open; enabling #188 does **not** change those consumers or flip any encoder, requirement-source, frugality, or reasoning default.
594
+
595
+ **Observability:** explain and `LOG_ROUTING` expose the normalized signal in `features.typed_judgment` (including confidences, `skip_reason`, and `latency_ms`), tier attribution in `features.tier_hint_reason_code`, and local gate outcomes in `features.tier_selection.local_zero_skip_reasons`.
584
596
 
585
597
  **Default off.** `typed_judgment.enabled` defaults to `false` — existing installs make no judge call and pay zero added latency. When enabled, the stage runs only on user-prompt turns: `tool_result` turns, acknowledgement-only turns, and explicit `force_model_id` turns skip it, and any timeout or judge error **fails open** — routing proceeds exactly as if the stage were unwired. Skip/failure reason codes recorded on the routing context: `typed_judgment_disabled`, `typed_judgment_tool_result`, `typed_judgment_acknowledgement`, `typed_judgment_force_model`, `typed_judgment_timeout`, `typed_judgment_error` (plus `typed_judgment_remote_key_missing` when a remote endpoint has no API key available — see privacy note below).
586
598
 
@@ -602,7 +614,7 @@ The six questions (stable ids):
602
614
  | `samples` | `SMART_ROUTER_TYPED_JUDGMENT_SAMPLES` | `1` | Judge samples per question (OpenJev self-consistency extension; omitted for hosted Jev) |
603
615
  | `api_key_env` | `SMART_ROUTER_TYPED_JUDGMENT_API_KEY_ENV` | `TYPESAFE_API_KEY` | **Name** of the env var holding the API key — never the key itself |
604
616
  | `allow_remote` | `SMART_ROUTER_TYPED_JUDGMENT_ALLOW_REMOTE` | `false` | Permit non-loopback (hosted) endpoints; default false = fail closed to local judge only |
605
- | `min_confidence` | `SMART_ROUTER_TYPED_JUDGMENT_MIN_CONFIDENCE` | `0.6` | Minimum answer confidence for a judgment to influence routing (consumed by later trains; defined now to stabilize the config shape) |
617
+ | `min_confidence` | `SMART_ROUTER_TYPED_JUDGMENT_MIN_CONFIDENCE` | `0.6` | Confidence threshold for `task_kind` planning overrides and `capability_deserved` tier replacement; below it, capability judgments may raise but never lower a tier. The `local_zero` safety gates still apply |
606
618
 
607
619
  Invalid env overrides (e.g. a remote endpoint without `allow_remote`) fail closed: the base config stays intact and disabled, and no judge call is made.
608
620
 
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Post-stream degenerate output detection (SP-325 / #181).
3
+ *
4
+ * A delegated response is degenerate only when it stopped for length, contains
5
+ * no tool calls, and its trailing text is highly repetitive. The default
6
+ * repetition metric is the repeated 5-gram ratio over whitespace-delimited
7
+ * tokens in the last 8,192 characters. Numeric fragments are normalized so
8
+ * runaway sequences with changing counters still match. At least 24 windows
9
+ * are required and the default repeated-window threshold is 0.65.
10
+ */
11
+ import type { AssistantMessage } from '@earendil-works/pi-ai/compat';
12
+ export declare const DEGENERATE_OUTPUT: "degenerate_output";
13
+ export declare const DEGENERATE_OUTPUT_ERROR_CODE: "DEGENERATE_OUTPUT";
14
+ export declare const DEFAULT_DEGENERATE_OUTPUT_CONFIG: {
15
+ readonly trailingCharacters: 8192;
16
+ readonly ngramSize: 5;
17
+ readonly minNgramWindows: 24;
18
+ readonly minRepeatedNgramRatio: 0.65;
19
+ };
20
+ export interface DegenerateOutputConfig {
21
+ readonly trailingCharacters?: number;
22
+ readonly ngramSize?: number;
23
+ readonly minNgramWindows?: number;
24
+ readonly minRepeatedNgramRatio?: number;
25
+ }
26
+ export type DegenerateOutputMessage = Pick<AssistantMessage, 'stopReason' | 'content'>;
27
+ export interface DegenerateOutputClassification {
28
+ readonly degenerate: boolean;
29
+ readonly reasonCode: typeof DEGENERATE_OUTPUT | null;
30
+ readonly repeatedNgramRatio: number;
31
+ readonly sampledNgrams: number;
32
+ }
33
+ export declare function repeatedNgramRatio(text: string, config?: DegenerateOutputConfig): Pick<DegenerateOutputClassification, 'repeatedNgramRatio' | 'sampledNgrams'>;
34
+ export declare function classifyDegenerateOutput(message: DegenerateOutputMessage, config?: DegenerateOutputConfig): DegenerateOutputClassification;
35
+ export declare function isDegenerateOutput(message: DegenerateOutputMessage, config?: DegenerateOutputConfig): boolean;
36
+ //# sourceMappingURL=degenerate-output.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"degenerate-output.d.ts","sourceRoot":"","sources":["../../../src/domain/delegation/degenerate-output.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAErE,eAAO,MAAM,iBAAiB,EAAG,mBAA4B,CAAC;AAC9D,eAAO,MAAM,4BAA4B,EAAG,mBAA4B,CAAC;AAEzE,eAAO,MAAM,gCAAgC;;;;;CAKnC,CAAC;AAEX,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAC;CACzC;AAED,MAAM,MAAM,uBAAuB,GAAG,IAAI,CAAC,gBAAgB,EAAE,YAAY,GAAG,SAAS,CAAC,CAAC;AAEvF,MAAM,WAAW,8BAA8B;IAC7C,QAAQ,CAAC,UAAU,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,UAAU,EAAE,OAAO,iBAAiB,GAAG,IAAI,CAAC;IACrD,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;CAChC;AAmBD,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,MAAM,GAAE,sBAA2B,GAClC,IAAI,CAAC,8BAA8B,EAAE,oBAAoB,GAAG,eAAe,CAAC,CAqB9E;AAED,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,uBAAuB,EAChC,MAAM,GAAE,sBAA2B,GAClC,8BAA8B,CA+BhC;AAED,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,uBAAuB,EAChC,MAAM,GAAE,sBAA2B,GAClC,OAAO,CAET"}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Post-stream degenerate output detection (SP-325 / #181).
3
+ *
4
+ * A delegated response is degenerate only when it stopped for length, contains
5
+ * no tool calls, and its trailing text is highly repetitive. The default
6
+ * repetition metric is the repeated 5-gram ratio over whitespace-delimited
7
+ * tokens in the last 8,192 characters. Numeric fragments are normalized so
8
+ * runaway sequences with changing counters still match. At least 24 windows
9
+ * are required and the default repeated-window threshold is 0.65.
10
+ */
11
+ export const DEGENERATE_OUTPUT = 'degenerate_output';
12
+ export const DEGENERATE_OUTPUT_ERROR_CODE = 'DEGENERATE_OUTPUT';
13
+ export const DEFAULT_DEGENERATE_OUTPUT_CONFIG = {
14
+ trailingCharacters: 8_192,
15
+ ngramSize: 5,
16
+ minNgramWindows: 24,
17
+ minRepeatedNgramRatio: 0.65,
18
+ };
19
+ function nonDegenerate(repeatedNgramRatio = 0, sampledNgrams = 0) {
20
+ return {
21
+ degenerate: false,
22
+ reasonCode: null,
23
+ repeatedNgramRatio,
24
+ sampledNgrams,
25
+ };
26
+ }
27
+ /** Normalize changing numeric counters without hiding the surrounding loop. */
28
+ function normalizeToken(token) {
29
+ return token.replace(/\d+(?:\.\d+)?/g, '#');
30
+ }
31
+ export function repeatedNgramRatio(text, config = {}) {
32
+ const trailingCharacters = config.trailingCharacters ?? DEFAULT_DEGENERATE_OUTPUT_CONFIG.trailingCharacters;
33
+ const ngramSize = config.ngramSize ?? DEFAULT_DEGENERATE_OUTPUT_CONFIG.ngramSize;
34
+ const tail = trailingCharacters >= 0 ? text.slice(-trailingCharacters) : text;
35
+ const tokens = (tail.match(/\S+/gu) ?? []).map(normalizeToken);
36
+ const sampledNgrams = Math.max(0, tokens.length - ngramSize + 1);
37
+ if (sampledNgrams === 0 || ngramSize <= 0) {
38
+ return { repeatedNgramRatio: 0, sampledNgrams: 0 };
39
+ }
40
+ const unique = new Set();
41
+ for (let index = 0; index < sampledNgrams; index += 1) {
42
+ unique.add(tokens.slice(index, index + ngramSize).join('\u0000'));
43
+ }
44
+ return {
45
+ repeatedNgramRatio: 1 - unique.size / sampledNgrams,
46
+ sampledNgrams,
47
+ };
48
+ }
49
+ export function classifyDegenerateOutput(message, config = {}) {
50
+ if (message.stopReason !== 'length' ||
51
+ message.content.some((block) => block.type === 'toolCall')) {
52
+ return nonDegenerate();
53
+ }
54
+ const text = message.content
55
+ .filter((block) => block.type === 'text')
56
+ .map((block) => block.text)
57
+ .join('\n');
58
+ const repetition = repeatedNgramRatio(text, config);
59
+ const minNgramWindows = config.minNgramWindows ?? DEFAULT_DEGENERATE_OUTPUT_CONFIG.minNgramWindows;
60
+ const minRepeatedNgramRatio = config.minRepeatedNgramRatio ??
61
+ DEFAULT_DEGENERATE_OUTPUT_CONFIG.minRepeatedNgramRatio;
62
+ if (repetition.sampledNgrams < minNgramWindows ||
63
+ repetition.repeatedNgramRatio < minRepeatedNgramRatio) {
64
+ return nonDegenerate(repetition.repeatedNgramRatio, repetition.sampledNgrams);
65
+ }
66
+ return {
67
+ degenerate: true,
68
+ reasonCode: DEGENERATE_OUTPUT,
69
+ ...repetition,
70
+ };
71
+ }
72
+ export function isDegenerateOutput(message, config = {}) {
73
+ return classifyDegenerateOutput(message, config).degenerate;
74
+ }
75
+ //# sourceMappingURL=degenerate-output.js.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,CAAC;IAC7E,MAAM,qBAAqB,GACzB,MAAM,CAAC,qBAAqB;QAC5B,gCAAgC,CAAC,qBAAqB,CAAC;IAEzD,IACE,UAAU,CAAC,aAAa,GAAG,eAAe;QAC1C,UAAU,CAAC,kBAAkB,GAAG,qBAAqB,EACrD,CAAC;QACD,OAAO,aAAa,CAAC,UAAU,CAAC,kBAAkB,EAAE,UAAU,CAAC,aAAa,CAAC,CAAC;IAChF,CAAC;IAED,OAAO;QACL,UAAU,EAAE,IAAI;QAChB,UAAU,EAAE,iBAAiB;QAC7B,GAAG,UAAU;KACd,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,OAAgC,EAChC,SAAiC,EAAE;IAEnC,OAAO,wBAAwB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,UAAU,CAAC;AAC9D,CAAC"}
@@ -18,6 +18,10 @@
18
18
  * it replaces.
19
19
  */
20
20
  import type { PipelineStage } from './pipeline-stage.js';
21
+ /** Judged destructive probability at or above which local dispatch is unsafe (#188). */
22
+ export declare const TYPED_JUDGMENT_DESTRUCTIVE_THRESHOLD = 0.7;
23
+ export declare const TYPED_JUDGMENT_DESTRUCTIVE = "typed_judgment_destructive";
24
+ export declare const TYPED_JUDGMENT_TOOL_USE_SHORTFALL = "typed_judgment_tool_use_shortfall";
21
25
  /** Local zero-tier dispatch with eligibility, capability, throughput, readiness gates. */
22
26
  export declare function createLocalZeroStage(): PipelineStage;
23
27
  //# sourceMappingURL=local-zero-stage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"local-zero-stage.d.ts","sourceRoot":"","sources":["../../../src/domain/pipeline/local-zero-stage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAgBH,OAAO,KAAK,EAAE,aAAa,EAAkB,MAAM,qBAAqB,CAAC;AA8DzE,0FAA0F;AAC1F,wBAAgB,oBAAoB,IAAI,aAAa,CAkIpD"}
1
+ {"version":3,"file":"local-zero-stage.d.ts","sourceRoot":"","sources":["../../../src/domain/pipeline/local-zero-stage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAgBH,OAAO,KAAK,EAAE,aAAa,EAAkB,MAAM,qBAAqB,CAAC;AAQzE,wFAAwF;AACxF,eAAO,MAAM,oCAAoC,MAAM,CAAC;AACxD,eAAO,MAAM,0BAA0B,+BAA+B,CAAC;AACvE,eAAO,MAAM,iCAAiC,sCACT,CAAC;AAwDtC,0FAA0F;AAC1F,wBAAgB,oBAAoB,IAAI,aAAa,CAsJpD"}
@@ -23,6 +23,10 @@ import { DEFAULT_OPERATOR_CONFIG } from '../../config/defaults.js';
23
23
  import { LOCAL_ZERO_DISABLED, THROUGHPUT_BELOW_THRESHOLD, TOOL_USE_CAPABILITY_SHORTFALL, } from '../ports/telemetry-emitter-port.js';
24
24
  import { DEFAULT_SPECULATIVE_PREWARM_CONFIG, PREWARM_DISABLED_LOW_ACCEPTANCE, SpeculativePrewarmGuard, } from '../routing/speculative-prewarm.js';
25
25
  import { estimateCheapToolUseRequirement, resolveLocalEligible, resolveLocalZeroToolUseCeiling, } from './stage-helpers.js';
26
+ /** Judged destructive probability at or above which local dispatch is unsafe (#188). */
27
+ export const TYPED_JUDGMENT_DESTRUCTIVE_THRESHOLD = 0.7;
28
+ export const TYPED_JUDGMENT_DESTRUCTIVE = 'typed_judgment_destructive';
29
+ export const TYPED_JUDGMENT_TOOL_USE_SHORTFALL = 'typed_judgment_tool_use_shortfall';
26
30
  /**
27
31
  * Bounded speculative prewarm of the local runtime (Colibri PILOT pattern).
28
32
  * Runs only when local_zero eligibility already passed and the operator
@@ -108,11 +112,27 @@ export function createLocalZeroStage() {
108
112
  if (!localModel) {
109
113
  return { decided: false, stage: 'local_zero' };
110
114
  }
111
- const predictedToolUse = estimateCheapToolUseRequirement(request.prompt_text);
112
115
  const ceiling = resolveLocalZeroToolUseCeiling(localModel.capabilities.tool_use, localZeroConfig.max_tool_use_requirement);
113
- if (predictedToolUse > ceiling) {
116
+ const typedJudgment = ctx.typedJudgment;
117
+ const typedToolUse = typedJudgment?.toolUse;
118
+ const typedDestructive = typedJudgment?.destructiveP;
119
+ const destructiveShortfall = typedDestructive !== null &&
120
+ typedDestructive !== undefined &&
121
+ typedDestructive >= TYPED_JUDGMENT_DESTRUCTIVE_THRESHOLD;
122
+ const typedToolUseShortfall = typedToolUse !== null &&
123
+ typedToolUse !== undefined &&
124
+ typedToolUse > ceiling;
125
+ // A missing tool_use answer is no signal, including on partial judgments:
126
+ // retain the pre-#188 cue-count gate rather than weakening local safety.
127
+ const cheapToolUseShortfall = (typedToolUse === null || typedToolUse === undefined) &&
128
+ estimateCheapToolUseRequirement(request.prompt_text) > ceiling;
129
+ if (destructiveShortfall || typedToolUseShortfall || cheapToolUseShortfall) {
114
130
  ctx.localEligibleReason = eligibility.reason;
115
- ctx.localZeroGateSkipReasons = [TOOL_USE_CAPABILITY_SHORTFALL];
131
+ ctx.localZeroGateSkipReasons = [
132
+ ...(destructiveShortfall ? [TYPED_JUDGMENT_DESTRUCTIVE] : []),
133
+ ...(typedToolUseShortfall ? [TYPED_JUDGMENT_TOOL_USE_SHORTFALL] : []),
134
+ ...(cheapToolUseShortfall ? [TOOL_USE_CAPABILITY_SHORTFALL] : []),
135
+ ];
116
136
  return { decided: false, stage: 'local_zero' };
117
137
  }
118
138
  const throughputMeter = ctx.options.throughputMeter;
@@ -1 +1 @@
1
- {"version":3,"file":"local-zero-stage.js","sourceRoot":"","sources":["../../../src/domain/pipeline/local-zero-stage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,qBAAqB,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,6BAA6B,GAC9B,MAAM,oCAAoC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B;oBAChC,kBAAkB,EAAE,SAAS,CAAC,iBAAiB;oBAC/C,UAAU,EAAE,IAAI;iBACjB;aACF,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -14,7 +14,10 @@
14
14
  * cached in the stage factory closure — one cache per RouterPipeline
15
15
  * instance, exactly as the orchestrator fields they replace.
16
16
  */
17
+ import type { Tier } from '../types/index.js';
17
18
  import type { PipelineStage } from './pipeline-stage.js';
19
+ /** Stable explain / LOG_ROUTING attribution for a judgment-driven tier hint. */
20
+ export declare function typedJudgmentTierReasonCode(tier: Tier): string;
18
21
  /** Low-intensity tier gate: structural score → tier hint (never decides). */
19
22
  export declare function createLowIntensityStage(): PipelineStage;
20
23
  //# sourceMappingURL=low-intensity-stage.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"low-intensity-stage.d.ts","sourceRoot":"","sources":["../../../src/domain/pipeline/low-intensity-stage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAyBH,OAAO,KAAK,EAAE,aAAa,EAAkB,MAAM,qBAAqB,CAAC;AA0JzE,6EAA6E;AAC7E,wBAAgB,uBAAuB,IAAI,aAAa,CAuIvD"}
1
+ {"version":3,"file":"low-intensity-stage.d.ts","sourceRoot":"","sources":["../../../src/domain/pipeline/low-intensity-stage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AA2BH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAG9C,OAAO,KAAK,EAAE,aAAa,EAAkB,MAAM,qBAAqB,CAAC;AA6EzE,gFAAgF;AAChF,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,CAE9D;AAmLD,6EAA6E;AAC7E,wBAAgB,uBAAuB,IAAI,aAAa,CA8IvD"}