pi-smart-router 1.2.1 → 1.3.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.
- package/.pi/extensions/smart-router/delegation-runtime.ts +12 -2
- package/.pi/extensions/smart-router/fleet-bootstrap.ts +22 -0
- package/.pi/extensions/smart-router/routing-context.ts +85 -11
- package/README.md +47 -1
- package/config/benchmark-profiles.json +124 -33
- package/dist/config/defaults.d.ts +2 -2
- package/dist/config/defaults.d.ts.map +1 -1
- package/dist/config/defaults.js +6 -3
- package/dist/config/defaults.js.map +1 -1
- package/dist/config/pi-model-mapper.d.ts +37 -1
- package/dist/config/pi-model-mapper.d.ts.map +1 -1
- package/dist/config/pi-model-mapper.js +120 -7
- package/dist/config/pi-model-mapper.js.map +1 -1
- package/dist/domain/delegation/delegation-context.d.ts +49 -0
- package/dist/domain/delegation/delegation-context.d.ts.map +1 -1
- package/dist/domain/delegation/delegation-context.js +92 -0
- package/dist/domain/delegation/delegation-context.js.map +1 -1
- package/dist/domain/judgment/answer-mapper.d.ts +49 -0
- package/dist/domain/judgment/answer-mapper.d.ts.map +1 -0
- package/dist/domain/judgment/answer-mapper.js +124 -0
- package/dist/domain/judgment/answer-mapper.js.map +1 -0
- package/dist/domain/judgment/index.d.ts +8 -0
- package/dist/domain/judgment/index.d.ts.map +1 -0
- package/dist/domain/judgment/index.js +8 -0
- package/dist/domain/judgment/index.js.map +1 -0
- package/dist/domain/judgment/judge-state.d.ts +70 -0
- package/dist/domain/judgment/judge-state.d.ts.map +1 -0
- package/dist/domain/judgment/judge-state.js +227 -0
- package/dist/domain/judgment/judge-state.js.map +1 -0
- package/dist/domain/judgment/questions.d.ts +58 -0
- package/dist/domain/judgment/questions.d.ts.map +1 -0
- package/dist/domain/judgment/questions.js +157 -0
- package/dist/domain/judgment/questions.js.map +1 -0
- package/dist/domain/matching/hydra-input.d.ts.map +1 -1
- package/dist/domain/matching/hydra-input.js +4 -17
- package/dist/domain/matching/hydra-input.js.map +1 -1
- package/dist/domain/pinning/loop-escalation.d.ts.map +1 -1
- package/dist/domain/pinning/loop-escalation.js +1 -49
- package/dist/domain/pinning/loop-escalation.js.map +1 -1
- package/dist/domain/pinning/tool-failure.d.ts +20 -0
- package/dist/domain/pinning/tool-failure.d.ts.map +1 -0
- package/dist/domain/pinning/tool-failure.js +62 -0
- package/dist/domain/pinning/tool-failure.js.map +1 -0
- package/dist/domain/pipeline/pipeline-stage.d.ts +11 -0
- package/dist/domain/pipeline/pipeline-stage.d.ts.map +1 -1
- package/dist/domain/pipeline/pipeline-stage.js +3 -0
- package/dist/domain/pipeline/pipeline-stage.js.map +1 -1
- package/dist/domain/pipeline/router-pipeline.d.ts +32 -6
- package/dist/domain/pipeline/router-pipeline.d.ts.map +1 -1
- package/dist/domain/pipeline/router-pipeline.js +49 -4
- package/dist/domain/pipeline/router-pipeline.js.map +1 -1
- package/dist/domain/pipeline/typed-judgment-stage.d.ts +44 -0
- package/dist/domain/pipeline/typed-judgment-stage.d.ts.map +1 -0
- package/dist/domain/pipeline/typed-judgment-stage.js +144 -0
- package/dist/domain/pipeline/typed-judgment-stage.js.map +1 -0
- package/dist/domain/ports/typed-judgment-port.d.ts +138 -0
- package/dist/domain/ports/typed-judgment-port.d.ts.map +1 -0
- package/dist/domain/ports/typed-judgment-port.js +28 -0
- package/dist/domain/ports/typed-judgment-port.js.map +1 -0
- package/dist/domain/types/entities.d.ts +42 -1
- package/dist/domain/types/entities.d.ts.map +1 -1
- package/dist/domain/types/index.d.ts +1 -1
- package/dist/domain/types/index.d.ts.map +1 -1
- package/dist/domain/types/schemas.d.ts +140 -0
- package/dist/domain/types/schemas.d.ts.map +1 -1
- package/dist/domain/types/schemas.js +191 -0
- package/dist/domain/types/schemas.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/infrastructure/judgment/jev-typed-judgment-adapter.d.ts +67 -0
- package/dist/infrastructure/judgment/jev-typed-judgment-adapter.d.ts.map +1 -0
- package/dist/infrastructure/judgment/jev-typed-judgment-adapter.js +411 -0
- package/dist/infrastructure/judgment/jev-typed-judgment-adapter.js.map +1 -0
- package/dist/infrastructure/persistence/sqlite-store.d.ts.map +1 -1
- package/dist/infrastructure/persistence/sqlite-store.js +37 -9
- package/dist/infrastructure/persistence/sqlite-store.js.map +1 -1
- package/package.json +1 -1
- package/src/config/defaults.ts +8 -1
- package/src/config/pi-model-mapper.ts +146 -7
- package/src/domain/delegation/delegation-context.ts +123 -0
- package/src/domain/judgment/answer-mapper.ts +210 -0
- package/src/domain/judgment/index.ts +32 -0
- package/src/domain/judgment/judge-state.ts +294 -0
- package/src/domain/judgment/questions.ts +198 -0
- package/src/domain/matching/hydra-input.ts +4 -19
- package/src/domain/pinning/loop-escalation.ts +1 -52
- package/src/domain/pinning/tool-failure.ts +66 -0
- package/src/domain/pipeline/pipeline-stage.ts +17 -0
- package/src/domain/pipeline/router-pipeline.ts +83 -6
- package/src/domain/pipeline/typed-judgment-stage.ts +165 -0
- package/src/domain/ports/typed-judgment-port.ts +186 -0
- package/src/domain/types/entities.ts +54 -0
- package/src/domain/types/index.ts +1 -0
- package/src/domain/types/schemas.ts +206 -0
- package/src/index.ts +19 -2
- package/src/infrastructure/judgment/jev-typed-judgment-adapter.ts +564 -0
- package/src/infrastructure/persistence/sqlite-store.ts +45 -9
package/dist/index.js
CHANGED
|
@@ -58,13 +58,15 @@ export function createRouterFromFleet(fleet, options) {
|
|
|
58
58
|
export { loadRoutingClusters, clusterReasonCode, };
|
|
59
59
|
export { createPiRouterMiddleware, LifecycleHookState } from './api/middleware/pi-router-middleware.js';
|
|
60
60
|
export { evictInMemorySessionState } from './api/session-eviction.js';
|
|
61
|
-
export { DEFAULT_PLANNING_DELEGATE_CONFIG } from './domain/types/schemas.js';
|
|
61
|
+
export { DEFAULT_PLANNING_DELEGATE_CONFIG, DEFAULT_TYPED_JUDGMENT_CONFIG, resolveTypedJudgmentConfigFromEnv, } from './domain/types/schemas.js';
|
|
62
|
+
// Typed judgment (SP-308, #187): composition-root adapter binding
|
|
63
|
+
export { createTypedJudgmentPort, } from './infrastructure/judgment/jev-typed-judgment-adapter.js';
|
|
62
64
|
// Config
|
|
63
65
|
export { DEFAULT_OPERATOR_CONFIG, resolveOperatorConfigFromEnv, } from './config/defaults.js';
|
|
64
66
|
export { mapFleetFromRegistry } from './config/pi-model-mapper.js';
|
|
65
67
|
// Domain — delegation
|
|
66
68
|
export { applyConcisenessHint, resolveAdaptiveReasoning, } from './domain/delegation/adaptive-reasoning.js';
|
|
67
|
-
export { isGoogleDelegationTarget, normalizeDelegationContext, repairGeminiReplayContext, } from './domain/delegation/delegation-context.js';
|
|
69
|
+
export { isGoogleDelegationTarget, isCursorDelegationTarget, isCursorOriginAssistantMessage, normalizeDelegationContext, repairGeminiReplayContext, stripCursorLifecycleThinking, STRIP_CURSOR_LIFECYCLE_ENV, } from './domain/delegation/delegation-context.js';
|
|
68
70
|
export { ExecutionLedger } from './domain/delegation/execution-ledger.js';
|
|
69
71
|
export { computeOutputHeadroom, } from './domain/delegation/output-headroom.js';
|
|
70
72
|
// Domain — matching, pinning, pipeline, pricing, routing
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,UAAU,EAAqB,MAAM,2BAA2B,CAAC;AAC1E,OAAO,EACL,mBAAmB,EACnB,iBAAiB,GAElB,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EACL,eAAe,GAEhB,MAAM,8CAA8C,CAAC;AACtD,OAAO,EACL,wBAAwB,GAIzB,MAAM,0CAA0C,CAAC;AAElD,wDAAwD;AACxD,MAAM,CAAC,MAAM,YAAY,GAAG,iBAA0B,CAAC;AAgBvD,gFAAgF;AAEhF;;;;;;;;;;;;;;;;GAgBG;AACH,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1
|
+
/**
|
|
2
|
+
* Jev-compatible typed judgment HTTP adapter (SP-305, #184).
|
|
3
|
+
*
|
|
4
|
+
* Implements the domain `TypedJudgmentPort` over Node's global `fetch`
|
|
5
|
+
* (Node ≥ 22.19; no new npm dependencies) against `POST /v1/systemone`.
|
|
6
|
+
* Local OpenJev is the default endpoint; hosted Jev (TypeSafe / Codiv) is
|
|
7
|
+
* opt-in via `allow_remote` (enforced by the config schema) plus a key from
|
|
8
|
+
* the env var named by `api_key_env` (enforced by the factory — fail closed).
|
|
9
|
+
*
|
|
10
|
+
* Wire notes (OpenJev README + `openjev/api.py`, `openjev/engine.py`):
|
|
11
|
+
* - Request: `{model, state, questions: {id: {type, instructions, criteria}}}`
|
|
12
|
+
* plus the OpenJev-only `samples` extension, sent for loopback endpoints
|
|
13
|
+
* only (hosted Jev rejects unknown fields).
|
|
14
|
+
* - Success: `{model, answers: {id: {type, …}}, usage}`. `noul` answers carry
|
|
15
|
+
* P(yes) ∈ [0,1]; `score` answers are 0-indexed expected levels — this
|
|
16
|
+
* adapter lifts them onto the question's anchor scores.
|
|
17
|
+
* - Errors: 400 (`detail` string or `{error_type, message}`), 422 (FastAPI
|
|
18
|
+
* validation list), 401/403 (`{detail: {error_type, message}}`), 429, 529.
|
|
19
|
+
* Only 429/529 are retried (max 2, linear backoff, inside `timeout_ms`).
|
|
20
|
+
*
|
|
21
|
+
* Privacy: thrown errors and logs never include state or question prompt
|
|
22
|
+
* text; every constructed message passes through `redactPromptFromError`.
|
|
23
|
+
* The API key is read from the environment at construction, never from
|
|
24
|
+
* config files, and is never logged.
|
|
25
|
+
*/
|
|
26
|
+
import { type TypedJudgmentAnswers, type TypedJudgmentPort, type TypedJudgmentQuestion } from '../../domain/ports/typed-judgment-port.js';
|
|
27
|
+
import type { TypedJudgmentConfig } from '../../domain/types/index.js';
|
|
28
|
+
type FetchLike = (url: string, init: RequestInit) => Promise<Response>;
|
|
29
|
+
/** True when the endpoint is loopback (local OpenJev). */
|
|
30
|
+
export declare function isLoopbackEndpoint(endpoint: string): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* `TypedJudgmentPort` over global fetch against a Jev-compatible endpoint.
|
|
33
|
+
*
|
|
34
|
+
* Construction is cheap and side-effect free apart from reading no env —
|
|
35
|
+
* the API key (remote endpoints only) is handed in by
|
|
36
|
+
* {@link createTypedJudgmentPort}, which is the fail-closed composition path.
|
|
37
|
+
* Direct construction is intended for tests; the factory enforces remote-key
|
|
38
|
+
* gating.
|
|
39
|
+
*/
|
|
40
|
+
export declare class JevTypedJudgmentAdapter implements TypedJudgmentPort {
|
|
41
|
+
#private;
|
|
42
|
+
constructor(config: TypedJudgmentConfig, apiKey?: string, fetchImpl?: FetchLike);
|
|
43
|
+
judge(state: string, questions: readonly TypedJudgmentQuestion[], options: {
|
|
44
|
+
signal: AbortSignal;
|
|
45
|
+
}): Promise<TypedJudgmentAnswers>;
|
|
46
|
+
}
|
|
47
|
+
/** Why no typed judgment port was created. */
|
|
48
|
+
export type TypedJudgmentUnavailableReason = 'typed_judgment_disabled' | 'typed_judgment_remote_key_missing';
|
|
49
|
+
export type CreateTypedJudgmentPortResult = {
|
|
50
|
+
port: TypedJudgmentPort;
|
|
51
|
+
} | {
|
|
52
|
+
port: null;
|
|
53
|
+
reason: TypedJudgmentUnavailableReason;
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Composition-root factory (SP-305, #184). Fails closed:
|
|
57
|
+
* - `enabled: false` → `{ port: null, reason: 'typed_judgment_disabled' }`
|
|
58
|
+
* - remote endpoint with an empty/missing `api_key_env` value →
|
|
59
|
+
* `{ port: null, reason: 'typed_judgment_remote_key_missing' }`
|
|
60
|
+
*
|
|
61
|
+
* The key is read from `env[config.api_key_env]` here (at construction) and
|
|
62
|
+
* only ever lives inside the adapter; it is never read from config files
|
|
63
|
+
* and never logged.
|
|
64
|
+
*/
|
|
65
|
+
export declare function createTypedJudgmentPort(config: TypedJudgmentConfig, env?: Readonly<Record<string, string | undefined>>): CreateTypedJudgmentPortResult;
|
|
66
|
+
export {};
|
|
67
|
+
//# sourceMappingURL=jev-typed-judgment-adapter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jev-typed-judgment-adapter.d.ts","sourceRoot":"","sources":["../../../src/infrastructure/judgment/jev-typed-judgment-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAIH,OAAO,EAGL,KAAK,oBAAoB,EAGzB,KAAK,iBAAiB,EACtB,KAAK,qBAAqB,EAE3B,MAAM,2CAA2C,CAAC;AAEnD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAiBvE,KAAK,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAkBvE,0DAA0D;AAC1D,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAG5D;AAsSD;;;;;;;;GAQG;AACH,qBAAa,uBAAwB,YAAW,iBAAiB;;gBAO7D,MAAM,EAAE,mBAAmB,EAC3B,MAAM,CAAC,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,SAAS;IAQjB,KAAK,CACT,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,SAAS,qBAAqB,EAAE,EAC3C,OAAO,EAAE;QAAE,MAAM,EAAE,WAAW,CAAA;KAAE,GAC/B,OAAO,CAAC,oBAAoB,CAAC;CA2HjC;AAID,8CAA8C;AAC9C,MAAM,MAAM,8BAA8B,GACtC,yBAAyB,GACzB,mCAAmC,CAAC;AAExC,MAAM,MAAM,6BAA6B,GACrC;IAAE,IAAI,EAAE,iBAAiB,CAAA;CAAE,GAC3B;IAAE,IAAI,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,8BAA8B,CAAA;CAAE,CAAC;AAE3D;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,mBAAmB,EAC3B,GAAG,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GAC9D,6BAA6B,CAY/B"}
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Jev-compatible typed judgment HTTP adapter (SP-305, #184).
|
|
3
|
+
*
|
|
4
|
+
* Implements the domain `TypedJudgmentPort` over Node's global `fetch`
|
|
5
|
+
* (Node ≥ 22.19; no new npm dependencies) against `POST /v1/systemone`.
|
|
6
|
+
* Local OpenJev is the default endpoint; hosted Jev (TypeSafe / Codiv) is
|
|
7
|
+
* opt-in via `allow_remote` (enforced by the config schema) plus a key from
|
|
8
|
+
* the env var named by `api_key_env` (enforced by the factory — fail closed).
|
|
9
|
+
*
|
|
10
|
+
* Wire notes (OpenJev README + `openjev/api.py`, `openjev/engine.py`):
|
|
11
|
+
* - Request: `{model, state, questions: {id: {type, instructions, criteria}}}`
|
|
12
|
+
* plus the OpenJev-only `samples` extension, sent for loopback endpoints
|
|
13
|
+
* only (hosted Jev rejects unknown fields).
|
|
14
|
+
* - Success: `{model, answers: {id: {type, …}}, usage}`. `noul` answers carry
|
|
15
|
+
* P(yes) ∈ [0,1]; `score` answers are 0-indexed expected levels — this
|
|
16
|
+
* adapter lifts them onto the question's anchor scores.
|
|
17
|
+
* - Errors: 400 (`detail` string or `{error_type, message}`), 422 (FastAPI
|
|
18
|
+
* validation list), 401/403 (`{detail: {error_type, message}}`), 429, 529.
|
|
19
|
+
* Only 429/529 are retried (max 2, linear backoff, inside `timeout_ms`).
|
|
20
|
+
*
|
|
21
|
+
* Privacy: thrown errors and logs never include state or question prompt
|
|
22
|
+
* text; every constructed message passes through `redactPromptFromError`.
|
|
23
|
+
* The API key is read from the environment at construction, never from
|
|
24
|
+
* config files, and is never logged.
|
|
25
|
+
*/
|
|
26
|
+
import { z } from 'zod';
|
|
27
|
+
import { TypedJudgmentError, } from '../../domain/ports/typed-judgment-port.js';
|
|
28
|
+
import { redactPromptFromError } from '../../domain/pipeline/stage-helpers.js';
|
|
29
|
+
// ─── Constants ───────────────────────────────────────────────────────────────
|
|
30
|
+
/** Max retries after the initial attempt (429/529 only). */
|
|
31
|
+
const MAX_RETRIES = 2;
|
|
32
|
+
/** Linear backoff base: retry N waits `BACKOFF_BASE_MS * N` (250 ms, 500 ms). */
|
|
33
|
+
const BACKOFF_BASE_MS = 250;
|
|
34
|
+
/**
|
|
35
|
+
* Loopback hosts matching `TypedJudgmentConfigSchema` in
|
|
36
|
+
* `src/domain/types/schemas.ts` (duplicated: the schema's helper is
|
|
37
|
+
* module-private and the schema file is out of this task's change scope).
|
|
38
|
+
*/
|
|
39
|
+
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);
|
|
40
|
+
// ─── Endpoint classification ─────────────────────────────────────────────────
|
|
41
|
+
/** Normalized hostname of an endpoint URL, or undefined when unparseable. */
|
|
42
|
+
function parseEndpointHostname(endpoint) {
|
|
43
|
+
let url;
|
|
44
|
+
try {
|
|
45
|
+
url = new URL(endpoint);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
const hostname = url.hostname;
|
|
51
|
+
return hostname.startsWith('[') && hostname.endsWith(']')
|
|
52
|
+
? hostname.slice(1, -1)
|
|
53
|
+
: hostname;
|
|
54
|
+
}
|
|
55
|
+
/** True when the endpoint is loopback (local OpenJev). */
|
|
56
|
+
export function isLoopbackEndpoint(endpoint) {
|
|
57
|
+
const hostname = parseEndpointHostname(endpoint);
|
|
58
|
+
return hostname !== undefined && LOOPBACK_HOSTS.has(hostname);
|
|
59
|
+
}
|
|
60
|
+
function toWireQuestion(question) {
|
|
61
|
+
switch (question.kind) {
|
|
62
|
+
case 'choice':
|
|
63
|
+
// Jev choice criteria map each option name to a description; the
|
|
64
|
+
// domain carries option labels only, so each option describes itself.
|
|
65
|
+
return {
|
|
66
|
+
type: 'choice',
|
|
67
|
+
instructions: question.prompt,
|
|
68
|
+
criteria: Object.fromEntries(question.options.map((option) => [option, option])),
|
|
69
|
+
};
|
|
70
|
+
case 'score':
|
|
71
|
+
// Jev score criteria are level descriptions in ascending order
|
|
72
|
+
// (0-indexed on the wire; the domain anchors carry explicit scores).
|
|
73
|
+
return {
|
|
74
|
+
type: 'score',
|
|
75
|
+
instructions: question.prompt,
|
|
76
|
+
criteria: question.anchors.map((anchor) => anchor.description),
|
|
77
|
+
};
|
|
78
|
+
case 'noul':
|
|
79
|
+
return {
|
|
80
|
+
type: 'noul',
|
|
81
|
+
instructions: question.prompt,
|
|
82
|
+
criteria: { true: question.criteria_true, false: question.criteria_false },
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
// ─── Wire response validation (zod) ─────────────────────────────────────────
|
|
87
|
+
const probabilityRecordSchema = z.record(z.string(), z.number());
|
|
88
|
+
/** Wire `choice` answer: `{type, choice, probabilities, confidence}`. */
|
|
89
|
+
const wireChoiceAnswerSchema = z.object({
|
|
90
|
+
type: z.literal('choice'),
|
|
91
|
+
choice: z.string(),
|
|
92
|
+
probabilities: probabilityRecordSchema,
|
|
93
|
+
confidence: z.number().min(0).max(1),
|
|
94
|
+
});
|
|
95
|
+
/** Wire `score` answer: `{type, score, legend, probabilities, confidence}` (0-indexed levels). */
|
|
96
|
+
const wireScoreAnswerSchema = z.object({
|
|
97
|
+
type: z.literal('score'),
|
|
98
|
+
score: z.number(),
|
|
99
|
+
legend: z.record(z.string(), z.string()),
|
|
100
|
+
probabilities: probabilityRecordSchema,
|
|
101
|
+
confidence: z.number().min(0).max(1),
|
|
102
|
+
});
|
|
103
|
+
/** Wire `noul` answer: `{type, noul}` where `noul` is P(yes) ∈ [0,1]. */
|
|
104
|
+
const wireNoulAnswerSchema = z.object({
|
|
105
|
+
type: z.literal('noul'),
|
|
106
|
+
noul: z.number().min(0).max(1),
|
|
107
|
+
});
|
|
108
|
+
const wireAnswerSchema = z.discriminatedUnion('type', [
|
|
109
|
+
wireChoiceAnswerSchema,
|
|
110
|
+
wireScoreAnswerSchema,
|
|
111
|
+
wireNoulAnswerSchema,
|
|
112
|
+
]);
|
|
113
|
+
/** Success envelope; `model`/`usage` are informational and ignored. */
|
|
114
|
+
const wireResponseSchema = z.object({
|
|
115
|
+
answers: z.record(z.string(), wireAnswerSchema),
|
|
116
|
+
});
|
|
117
|
+
/** `{detail: {error_type, message}}` — auth errors (401/403) and api errors. */
|
|
118
|
+
const wireObjectErrorSchema = z.object({
|
|
119
|
+
detail: z.object({
|
|
120
|
+
error_type: z.string(),
|
|
121
|
+
message: z.string().optional(),
|
|
122
|
+
}),
|
|
123
|
+
});
|
|
124
|
+
/** `{detail: "plain text reason"}` — 400 semantic errors (unaskable question). */
|
|
125
|
+
const wireStringErrorSchema = z.object({
|
|
126
|
+
detail: z.string(),
|
|
127
|
+
});
|
|
128
|
+
/** `{detail: [{type, loc, msg, …}]}` — 422 FastAPI validation list. */
|
|
129
|
+
const wireValidationErrorSchema = z.object({
|
|
130
|
+
detail: z.array(z.object({
|
|
131
|
+
loc: z.array(z.union([z.string(), z.number()])).optional(),
|
|
132
|
+
msg: z.string().optional(),
|
|
133
|
+
type: z.string().optional(),
|
|
134
|
+
})),
|
|
135
|
+
});
|
|
136
|
+
function invalidResponse(redact, message) {
|
|
137
|
+
return new TypedJudgmentError('invalid_response', redact(message));
|
|
138
|
+
}
|
|
139
|
+
function mapChoiceAnswer(question, wire, redact) {
|
|
140
|
+
if (!question.options.includes(wire.choice)) {
|
|
141
|
+
throw invalidResponse(redact, `judge answered choice '${wire.choice}' for question '${question.id}', ` +
|
|
142
|
+
'which is not one of the declared options');
|
|
143
|
+
}
|
|
144
|
+
for (const key of Object.keys(wire.probabilities)) {
|
|
145
|
+
if (!question.options.includes(key)) {
|
|
146
|
+
throw invalidResponse(redact, `judge returned a probability for unknown option '${key}' ` +
|
|
147
|
+
`on question '${question.id}'`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
kind: 'choice',
|
|
152
|
+
choice: wire.choice,
|
|
153
|
+
probabilities: wire.probabilities,
|
|
154
|
+
confidence: wire.confidence,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
function mapScoreAnswer(question, wire, redact) {
|
|
158
|
+
// The wire is 0-indexed over the level list; the domain carries explicit
|
|
159
|
+
// anchor scores. Re-key legend/probabilities onto anchor scores and lift
|
|
160
|
+
// the expected level into anchor-score space (Σ pᵢ·anchorᵢ.score).
|
|
161
|
+
const legend = {};
|
|
162
|
+
const probabilities = {};
|
|
163
|
+
let expected = 0;
|
|
164
|
+
question.anchors.forEach((anchor, index) => {
|
|
165
|
+
const wireKey = String(index);
|
|
166
|
+
const probability = wire.probabilities[wireKey];
|
|
167
|
+
if (probability === undefined) {
|
|
168
|
+
throw invalidResponse(redact, `judge score answer for question '${question.id}' is missing ` +
|
|
169
|
+
`a probability for level ${wireKey}`);
|
|
170
|
+
}
|
|
171
|
+
const domainKey = String(anchor.score);
|
|
172
|
+
legend[domainKey] = wire.legend[wireKey] ?? anchor.description;
|
|
173
|
+
probabilities[domainKey] = probability;
|
|
174
|
+
expected += probability * anchor.score;
|
|
175
|
+
});
|
|
176
|
+
return {
|
|
177
|
+
kind: 'score',
|
|
178
|
+
score: expected,
|
|
179
|
+
legend,
|
|
180
|
+
probabilities,
|
|
181
|
+
confidence: wire.confidence,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function mapNoulAnswer(_question, wire) {
|
|
185
|
+
return { kind: 'noul', noul: wire.noul };
|
|
186
|
+
}
|
|
187
|
+
function mapAnswer(question, wire, redact) {
|
|
188
|
+
if (wire.type !== question.kind) {
|
|
189
|
+
throw invalidResponse(redact, `judge answered question '${question.id}' with type '${wire.type}', ` +
|
|
190
|
+
`expected '${question.kind}'`);
|
|
191
|
+
}
|
|
192
|
+
switch (question.kind) {
|
|
193
|
+
case 'choice':
|
|
194
|
+
return mapChoiceAnswer(question, wire, redact);
|
|
195
|
+
case 'score':
|
|
196
|
+
return mapScoreAnswer(question, wire, redact);
|
|
197
|
+
case 'noul':
|
|
198
|
+
return mapNoulAnswer(question, wire);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// ─── HTTP error mapping ──────────────────────────────────────────────────────
|
|
202
|
+
/**
|
|
203
|
+
* Map an HTTP error status + parsed body to a `TypedJudgmentError`. Auth
|
|
204
|
+
* errors carry `detail.error_type` only (never the provider message); all
|
|
205
|
+
* messages are redacted by the caller.
|
|
206
|
+
*/
|
|
207
|
+
function mapHttpError(status, body, redact) {
|
|
208
|
+
if (status === 400) {
|
|
209
|
+
const objectError = wireObjectErrorSchema.safeParse(body);
|
|
210
|
+
if (objectError.success) {
|
|
211
|
+
const { error_type, message } = objectError.data.detail;
|
|
212
|
+
return new TypedJudgmentError('bad_request', redact(`judge rejected the request (${error_type})` + (message ? `: ${message}` : '')));
|
|
213
|
+
}
|
|
214
|
+
const stringError = wireStringErrorSchema.safeParse(body);
|
|
215
|
+
const reason = stringError.success ? `: ${stringError.data.detail}` : '';
|
|
216
|
+
return new TypedJudgmentError('bad_request', redact(`judge rejected the request${reason}`));
|
|
217
|
+
}
|
|
218
|
+
if (status === 422) {
|
|
219
|
+
const validationError = wireValidationErrorSchema.safeParse(body);
|
|
220
|
+
const summary = validationError.success
|
|
221
|
+
? validationError.data.detail
|
|
222
|
+
.map((item) => {
|
|
223
|
+
const loc = item.loc?.join('.') ?? '';
|
|
224
|
+
const parts = [loc, item.type, item.msg].filter((part) => part !== undefined && part !== '');
|
|
225
|
+
return parts.join(': ');
|
|
226
|
+
})
|
|
227
|
+
.join('; ')
|
|
228
|
+
: '';
|
|
229
|
+
return new TypedJudgmentError('validation', redact(`judge could not validate the request${summary ? `: ${summary}` : ''}`));
|
|
230
|
+
}
|
|
231
|
+
if (status === 401 || status === 403) {
|
|
232
|
+
// Carry detail.error_type only — the provider message is not forwarded.
|
|
233
|
+
const objectError = wireObjectErrorSchema.safeParse(body);
|
|
234
|
+
const errorType = objectError.success ? objectError.data.detail.error_type : 'unknown';
|
|
235
|
+
return new TypedJudgmentError('auth', `judge authentication failed (${errorType})`);
|
|
236
|
+
}
|
|
237
|
+
if (status === 429) {
|
|
238
|
+
return new TypedJudgmentError('rate_limited', 'judge rate limited the request');
|
|
239
|
+
}
|
|
240
|
+
if (status === 529) {
|
|
241
|
+
return new TypedJudgmentError('overloaded', 'judge is overloaded');
|
|
242
|
+
}
|
|
243
|
+
return new TypedJudgmentError('transport', `judge returned unexpected HTTP ${status}`);
|
|
244
|
+
}
|
|
245
|
+
// ─── Abort helpers ───────────────────────────────────────────────────────────
|
|
246
|
+
/** True for the abort/timeout reasons fetch rejects with. */
|
|
247
|
+
function isAbortError(error) {
|
|
248
|
+
return (error instanceof Error &&
|
|
249
|
+
(error.name === 'AbortError' || error.name === 'TimeoutError'));
|
|
250
|
+
}
|
|
251
|
+
/** Sleep, rejecting with the signal's reason when the signal aborts. */
|
|
252
|
+
function sleep(ms, signal) {
|
|
253
|
+
return new Promise((resolve, reject) => {
|
|
254
|
+
if (signal.aborted) {
|
|
255
|
+
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const timer = setTimeout(() => {
|
|
259
|
+
signal.removeEventListener('abort', onAbort);
|
|
260
|
+
resolve();
|
|
261
|
+
}, ms);
|
|
262
|
+
const onAbort = () => {
|
|
263
|
+
clearTimeout(timer);
|
|
264
|
+
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
|
265
|
+
};
|
|
266
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
// ─── Adapter ─────────────────────────────────────────────────────────────────
|
|
270
|
+
/**
|
|
271
|
+
* `TypedJudgmentPort` over global fetch against a Jev-compatible endpoint.
|
|
272
|
+
*
|
|
273
|
+
* Construction is cheap and side-effect free apart from reading no env —
|
|
274
|
+
* the API key (remote endpoints only) is handed in by
|
|
275
|
+
* {@link createTypedJudgmentPort}, which is the fail-closed composition path.
|
|
276
|
+
* Direct construction is intended for tests; the factory enforces remote-key
|
|
277
|
+
* gating.
|
|
278
|
+
*/
|
|
279
|
+
export class JevTypedJudgmentAdapter {
|
|
280
|
+
#config;
|
|
281
|
+
#apiKey;
|
|
282
|
+
#remote;
|
|
283
|
+
#fetchImpl;
|
|
284
|
+
constructor(config, apiKey, fetchImpl) {
|
|
285
|
+
this.#config = config;
|
|
286
|
+
this.#apiKey = apiKey;
|
|
287
|
+
this.#remote = !isLoopbackEndpoint(config.endpoint);
|
|
288
|
+
this.#fetchImpl = fetchImpl;
|
|
289
|
+
}
|
|
290
|
+
async judge(state, questions, options) {
|
|
291
|
+
const redact = (message) => {
|
|
292
|
+
let out = redactPromptFromError(message, state);
|
|
293
|
+
for (const question of questions) {
|
|
294
|
+
out = redactPromptFromError(out, question.prompt);
|
|
295
|
+
}
|
|
296
|
+
return out;
|
|
297
|
+
};
|
|
298
|
+
// One deadline covers the whole call including retries; the caller's
|
|
299
|
+
// signal composes with it so either can abort the in-flight request.
|
|
300
|
+
const timeoutSignal = AbortSignal.timeout(this.#config.timeout_ms);
|
|
301
|
+
const callerSignal = options.signal;
|
|
302
|
+
const signal = AbortSignal.any([callerSignal, timeoutSignal]);
|
|
303
|
+
const headers = {
|
|
304
|
+
'content-type': 'application/json',
|
|
305
|
+
accept: 'application/json',
|
|
306
|
+
};
|
|
307
|
+
// Remote endpoints authenticate; loopback (local OpenJev) never sees the
|
|
308
|
+
// key. The key itself never appears in errors or logs.
|
|
309
|
+
if (this.#remote && this.#apiKey !== undefined) {
|
|
310
|
+
headers.authorization = `Bearer ${this.#apiKey}`;
|
|
311
|
+
}
|
|
312
|
+
const wireQuestions = {};
|
|
313
|
+
for (const question of questions) {
|
|
314
|
+
wireQuestions[question.id] = toWireQuestion(question);
|
|
315
|
+
}
|
|
316
|
+
const body = {
|
|
317
|
+
model: this.#config.model,
|
|
318
|
+
state,
|
|
319
|
+
questions: wireQuestions,
|
|
320
|
+
};
|
|
321
|
+
// `samples` is an OpenJev extension; hosted Jev rejects unknown fields.
|
|
322
|
+
if (!this.#remote) {
|
|
323
|
+
body.samples = this.#config.samples;
|
|
324
|
+
}
|
|
325
|
+
try {
|
|
326
|
+
const response = await this.#postWithRetry(JSON.stringify(body), headers, signal, timeoutSignal);
|
|
327
|
+
if (!response.ok) {
|
|
328
|
+
const errorBody = await response.json().catch(() => undefined);
|
|
329
|
+
throw mapHttpError(response.status, errorBody, redact);
|
|
330
|
+
}
|
|
331
|
+
const payload = await response.json().catch(() => undefined);
|
|
332
|
+
const parsed = wireResponseSchema.safeParse(payload);
|
|
333
|
+
if (!parsed.success) {
|
|
334
|
+
throw invalidResponse(redact, 'judge returned a malformed response envelope');
|
|
335
|
+
}
|
|
336
|
+
const answers = {};
|
|
337
|
+
for (const question of questions) {
|
|
338
|
+
const wire = parsed.data.answers[question.id];
|
|
339
|
+
if (wire === undefined) {
|
|
340
|
+
throw invalidResponse(redact, `judge response is missing an answer for question '${question.id}'`);
|
|
341
|
+
}
|
|
342
|
+
answers[question.id] = mapAnswer(question, wire, redact);
|
|
343
|
+
}
|
|
344
|
+
return answers;
|
|
345
|
+
}
|
|
346
|
+
catch (error) {
|
|
347
|
+
if (error instanceof TypedJudgmentError) {
|
|
348
|
+
throw error;
|
|
349
|
+
}
|
|
350
|
+
if (isAbortError(error) || signal.aborted) {
|
|
351
|
+
// Caller abort wins over timeout when both fired together.
|
|
352
|
+
if (callerSignal.aborted) {
|
|
353
|
+
throw new TypedJudgmentError('aborted', 'typed judgment aborted by caller');
|
|
354
|
+
}
|
|
355
|
+
if (timeoutSignal.aborted) {
|
|
356
|
+
throw new TypedJudgmentError('timeout', `typed judgment timed out after ${this.#config.timeout_ms} ms`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
360
|
+
throw new TypedJudgmentError('transport', redact(`typed judgment transport failure: ${message}`));
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
/** POST with bounded retries on 429/529 (linear backoff, shared deadline). */
|
|
364
|
+
async #postWithRetry(body, headers, signal, timeoutSignal) {
|
|
365
|
+
const doFetch = this.#fetchImpl ?? ((url, init) => globalThis.fetch(url, init));
|
|
366
|
+
let retries = 0;
|
|
367
|
+
for (;;) {
|
|
368
|
+
if (signal.aborted) {
|
|
369
|
+
throw signal.reason ?? new DOMException('Aborted', 'AbortError');
|
|
370
|
+
}
|
|
371
|
+
const response = await doFetch(this.#config.endpoint, {
|
|
372
|
+
method: 'POST',
|
|
373
|
+
headers,
|
|
374
|
+
body,
|
|
375
|
+
signal,
|
|
376
|
+
});
|
|
377
|
+
const retryable = response.status === 429 || response.status === 529;
|
|
378
|
+
// Retry only while retries remain and the deadline has not passed —
|
|
379
|
+
// the backoff sleep and the next attempt share `timeoutSignal`.
|
|
380
|
+
if (!retryable || retries >= MAX_RETRIES || timeoutSignal.aborted) {
|
|
381
|
+
return response;
|
|
382
|
+
}
|
|
383
|
+
retries += 1;
|
|
384
|
+
await sleep(BACKOFF_BASE_MS * retries, signal);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Composition-root factory (SP-305, #184). Fails closed:
|
|
390
|
+
* - `enabled: false` → `{ port: null, reason: 'typed_judgment_disabled' }`
|
|
391
|
+
* - remote endpoint with an empty/missing `api_key_env` value →
|
|
392
|
+
* `{ port: null, reason: 'typed_judgment_remote_key_missing' }`
|
|
393
|
+
*
|
|
394
|
+
* The key is read from `env[config.api_key_env]` here (at construction) and
|
|
395
|
+
* only ever lives inside the adapter; it is never read from config files
|
|
396
|
+
* and never logged.
|
|
397
|
+
*/
|
|
398
|
+
export function createTypedJudgmentPort(config, env = process.env) {
|
|
399
|
+
if (!config.enabled) {
|
|
400
|
+
return { port: null, reason: 'typed_judgment_disabled' };
|
|
401
|
+
}
|
|
402
|
+
if (!isLoopbackEndpoint(config.endpoint)) {
|
|
403
|
+
const key = env[config.api_key_env];
|
|
404
|
+
if (key === undefined || key.trim() === '') {
|
|
405
|
+
return { port: null, reason: 'typed_judgment_remote_key_missing' };
|
|
406
|
+
}
|
|
407
|
+
return { port: new JevTypedJudgmentAdapter(config, key) };
|
|
408
|
+
}
|
|
409
|
+
return { port: new JevTypedJudgmentAdapter(config) };
|
|
410
|
+
}
|
|
411
|
+
//# sourceMappingURL=jev-typed-judgment-adapter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jev-typed-judgment-adapter.js","sourceRoot":"","sources":["../../../src/infrastructure/judgment/jev-typed-judgment-adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,EACL,kBAAkB,GAQnB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAG/E,gFAAgF;AAEhF,4DAA4D;AAC5D,MAAM,WAAW,GAAG,CAAC,CAAC;AAEtB,iFAAiF;AACjF,MAAM,eAAe,GAAG,GAAG,CAAC;AAE5B;;;;GAIG;AACH,MAAM,cAAc,GAAwB,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;AAIvF,gFAAgF;AAEhF,6EAA6E;AAC7E,SAAS,qBAAqB,CAAC,QAAgB;IAC7C,IAAI,GAAQ,CAAC;IACb,IAAI,CAAC;QACH,GAAG,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC1B,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;IAC9B,OAAO,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,QAAQ,CAAC,QAAQ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/outcome-limits.js';
|
|
19
19
|
import { EMBEDDING_DIM } from '../../domain/matching/embedding-provider.js';
|
|
20
20
|
// ─── Schema version & migrations ────────────────────────────────────────────
|
|
21
|
-
const CURRENT_SCHEMA_VERSION =
|
|
21
|
+
const CURRENT_SCHEMA_VERSION = 9;
|
|
22
22
|
const MIGRATION_V1 = `
|
|
23
23
|
CREATE TABLE IF NOT EXISTS pins (
|
|
24
24
|
session_id TEXT PRIMARY KEY,
|
|
@@ -164,6 +164,17 @@ const MIGRATION_V7 = `
|
|
|
164
164
|
const MIGRATION_V8 = `
|
|
165
165
|
ALTER TABLE dataset ADD COLUMN embedding_json TEXT;
|
|
166
166
|
`;
|
|
167
|
+
// SP-301 / #171: persist context-fit gate telemetry so router-explain and
|
|
168
|
+
// exports can surface why a request overflowed after restart. Previously the
|
|
169
|
+
// fields were dropped on insert and read back as null literals.
|
|
170
|
+
const MIGRATION_V9 = `
|
|
171
|
+
ALTER TABLE telemetry ADD COLUMN estimated_input_tokens INTEGER;
|
|
172
|
+
ALTER TABLE telemetry ADD COLUMN context_fit_viable_count INTEGER;
|
|
173
|
+
ALTER TABLE telemetry ADD COLUMN context_fit_rejected_json TEXT;
|
|
174
|
+
ALTER TABLE telemetry ADD COLUMN context_overflow_pin_break INTEGER NOT NULL DEFAULT 0;
|
|
175
|
+
ALTER TABLE telemetry ADD COLUMN selected_model_max_input_tokens INTEGER;
|
|
176
|
+
ALTER TABLE telemetry ADD COLUMN context_fit_reason_code TEXT;
|
|
177
|
+
`;
|
|
167
178
|
/**
|
|
168
179
|
* Create a persistence store with corrupt-DB recovery.
|
|
169
180
|
*
|
|
@@ -552,14 +563,20 @@ export class SqliteStore {
|
|
|
552
563
|
estimated_cost_usd, routing_latency_ms, pin_reason,
|
|
553
564
|
actual_cost_usd, actual_input_tokens, actual_output_tokens,
|
|
554
565
|
actual_cache_read_tokens, actual_cache_write_tokens,
|
|
555
|
-
reasoning_level_requested, reasoning_level_applied, reasoning_reason_code
|
|
566
|
+
reasoning_level_requested, reasoning_level_applied, reasoning_reason_code,
|
|
567
|
+
estimated_input_tokens, context_fit_viable_count,
|
|
568
|
+
context_fit_rejected_json, context_overflow_pin_break,
|
|
569
|
+
selected_model_max_input_tokens, context_fit_reason_code
|
|
556
570
|
) VALUES (
|
|
557
571
|
@timestamp, @session_id, @request_id, @turn_type,
|
|
558
572
|
@stage, @reason_code, @selected_model_id,
|
|
559
573
|
@estimated_cost_usd, @routing_latency_ms, @pin_reason,
|
|
560
574
|
@actual_cost_usd, @actual_input_tokens, @actual_output_tokens,
|
|
561
575
|
@actual_cache_read_tokens, @actual_cache_write_tokens,
|
|
562
|
-
@reasoning_level_requested, @reasoning_level_applied, @reasoning_reason_code
|
|
576
|
+
@reasoning_level_requested, @reasoning_level_applied, @reasoning_reason_code,
|
|
577
|
+
@estimated_input_tokens, @context_fit_viable_count,
|
|
578
|
+
@context_fit_rejected_json, @context_overflow_pin_break,
|
|
579
|
+
@selected_model_max_input_tokens, @context_fit_reason_code
|
|
563
580
|
)`)
|
|
564
581
|
.run({
|
|
565
582
|
timestamp: entry.timestamp,
|
|
@@ -580,6 +597,12 @@ export class SqliteStore {
|
|
|
580
597
|
reasoning_level_requested: entry.reasoning_level_requested ?? null,
|
|
581
598
|
reasoning_level_applied: entry.reasoning_level_applied ?? null,
|
|
582
599
|
reasoning_reason_code: entry.reasoning_reason_code ?? null,
|
|
600
|
+
estimated_input_tokens: entry.estimated_input_tokens ?? null,
|
|
601
|
+
context_fit_viable_count: entry.context_fit_viable_count ?? null,
|
|
602
|
+
context_fit_rejected_json: entry.context_fit_rejected_json ?? null,
|
|
603
|
+
context_overflow_pin_break: entry.context_overflow_pin_break ? 1 : 0,
|
|
604
|
+
selected_model_max_input_tokens: entry.selected_model_max_input_tokens ?? null,
|
|
605
|
+
context_fit_reason_code: entry.context_fit_reason_code ?? null,
|
|
583
606
|
});
|
|
584
607
|
}
|
|
585
608
|
/**
|
|
@@ -755,6 +778,11 @@ export class SqliteStore {
|
|
|
755
778
|
if (version < 8) {
|
|
756
779
|
this.db.exec(MIGRATION_V8);
|
|
757
780
|
version = 8;
|
|
781
|
+
this.db.pragma(`user_version = ${version}`);
|
|
782
|
+
}
|
|
783
|
+
if (version < 9) {
|
|
784
|
+
this.db.exec(MIGRATION_V9);
|
|
785
|
+
version = 9;
|
|
758
786
|
this.db.pragma(`user_version = ${CURRENT_SCHEMA_VERSION}`);
|
|
759
787
|
}
|
|
760
788
|
}
|
|
@@ -844,12 +872,12 @@ function telemetryRowToEntity(row) {
|
|
|
844
872
|
estimated_cost_usd: row.estimated_cost_usd,
|
|
845
873
|
routing_latency_ms: row.routing_latency_ms,
|
|
846
874
|
pin_reason: row.pin_reason,
|
|
847
|
-
estimated_input_tokens:
|
|
848
|
-
context_fit_viable_count:
|
|
849
|
-
context_fit_rejected_json:
|
|
850
|
-
context_overflow_pin_break:
|
|
851
|
-
selected_model_max_input_tokens:
|
|
852
|
-
context_fit_reason_code:
|
|
875
|
+
estimated_input_tokens: row.estimated_input_tokens,
|
|
876
|
+
context_fit_viable_count: row.context_fit_viable_count,
|
|
877
|
+
context_fit_rejected_json: row.context_fit_rejected_json,
|
|
878
|
+
context_overflow_pin_break: row.context_overflow_pin_break === 1,
|
|
879
|
+
selected_model_max_input_tokens: row.selected_model_max_input_tokens,
|
|
880
|
+
context_fit_reason_code: row.context_fit_reason_code,
|
|
853
881
|
cluster_id: null,
|
|
854
882
|
cluster_similarity: null,
|
|
855
883
|
cluster_margin: null,
|