pi-advisor-flow 0.13.3-dev.1 → 0.13.3-dev.3

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.
@@ -0,0 +1,421 @@
1
+ import type {
2
+ ClassifierApi,
3
+ ClassifierContext,
4
+ ClassifierModel,
5
+ ClassifierResult,
6
+ ModelsClassifierOptions,
7
+ Usage,
8
+ } from "@earendil-works/pi-ai";
9
+
10
+ import { advisorJevTimeoutMsRef } from "../config/state.ts";
11
+ import { isRecordOf, isString } from "../content-utils.ts";
12
+ import type { JsonValue } from "../content-utils.ts";
13
+ import { JevFailure } from "./failure.ts";
14
+ import { nativeScreeningQuestions } from "./questions.ts";
15
+ import type { JevState } from "./state.ts";
16
+
17
+ export type JevQuestionSet = ClassifierContext["questions"];
18
+
19
+ export interface JevBooleanPolicyAnswer {
20
+ noul: number;
21
+ type: "noul";
22
+ }
23
+
24
+ export interface JevChoicePolicyAnswer {
25
+ choice: string;
26
+ confidence: number;
27
+ probabilities: Record<string, number>;
28
+ type: "choice";
29
+ }
30
+
31
+ export type JevPolicyAnswer = JevBooleanPolicyAnswer | JevChoicePolicyAnswer;
32
+
33
+ export interface JevAnswers {
34
+ self_answerable?: JevPolicyAnswer;
35
+ should_consult?: JevPolicyAnswer;
36
+ stakes?: JevPolicyAnswer;
37
+ }
38
+
39
+ export interface JevClassifierUsage {
40
+ cost?: number;
41
+ inputTokens: number;
42
+ outputTokens: number;
43
+ piUsage?: Usage;
44
+ }
45
+
46
+ export interface JevClassifierResult {
47
+ answers: JevAnswers;
48
+ model: string;
49
+ usage?: JevClassifierUsage;
50
+ }
51
+
52
+ export interface JevClassifierOptions {
53
+ apiKey?: string;
54
+ signal?: AbortSignal;
55
+ }
56
+
57
+ export interface JevClassifierRegistry {
58
+ classify: (
59
+ model: ClassifierModel<ClassifierApi>,
60
+ context: ClassifierContext,
61
+ options?: ModelsClassifierOptions
62
+ ) => Promise<ClassifierResult>;
63
+ findOfType: (
64
+ type: "classifier",
65
+ provider: string,
66
+ modelId: string
67
+ ) => ClassifierModel<ClassifierApi> | undefined;
68
+ }
69
+
70
+ export interface JevClassifierContext {
71
+ modelRegistry: JevClassifierRegistry;
72
+ signal?: AbortSignal;
73
+ }
74
+
75
+ const REF_PATTERN = /^(?<provider>[^/]+)\/(?<modelId>.+)$/u;
76
+
77
+ export const parseJevClassifierRef = (ref: string) => {
78
+ const match = REF_PATTERN.exec(ref.trim());
79
+
80
+ const provider = match?.groups?.provider;
81
+ const modelId = match?.groups?.modelId;
82
+
83
+ return provider && modelId ? { modelId, provider } : undefined;
84
+ };
85
+
86
+ const isClassifierModel = (
87
+ model: unknown
88
+ ): model is ClassifierModel<ClassifierApi> =>
89
+ isRecordOf(model) &&
90
+ model.type === "classifier" &&
91
+ typeof model.provider === "string" &&
92
+ typeof model.id === "string" &&
93
+ typeof model.api === "string" &&
94
+ isRecordOf(model.cost);
95
+
96
+ const isProbability = (value: unknown): value is number =>
97
+ typeof value === "number" &&
98
+ Number.isFinite(value) &&
99
+ value >= 0 &&
100
+ value <= 1;
101
+
102
+ const normalizedUsage = (
103
+ usage: Usage | undefined
104
+ ): JevClassifierUsage | undefined => {
105
+ if (!usage) {
106
+ return undefined;
107
+ }
108
+
109
+ const inputTokens = usage.input;
110
+ const outputTokens = usage.output;
111
+ const inputCost = usage.cost?.input;
112
+ const cacheReadCost = usage.cost?.cacheRead;
113
+ const cacheWriteCost = usage.cost?.cacheWrite;
114
+
115
+ if (
116
+ !Number.isFinite(inputTokens) ||
117
+ inputTokens < 0 ||
118
+ !Number.isFinite(outputTokens) ||
119
+ outputTokens < 0
120
+ ) {
121
+ return undefined;
122
+ }
123
+
124
+ const completeCost =
125
+ Number.isFinite(inputCost) &&
126
+ inputCost >= 0 &&
127
+ Number.isFinite(cacheReadCost) &&
128
+ cacheReadCost >= 0 &&
129
+ Number.isFinite(cacheWriteCost) &&
130
+ cacheWriteCost >= 0;
131
+
132
+ const cost = completeCost
133
+ ? inputCost + cacheReadCost + cacheWriteCost
134
+ : undefined;
135
+
136
+ const piUsage =
137
+ completeCost && cost !== undefined
138
+ ? {
139
+ ...usage,
140
+ cost: {
141
+ ...usage.cost,
142
+ input: inputCost,
143
+ output: 0,
144
+ total: cost,
145
+ },
146
+ }
147
+ : undefined;
148
+
149
+ return { cost, inputTokens, outputTokens, piUsage };
150
+ };
151
+
152
+ const abortError = () =>
153
+ new DOMException("Jev classifier call aborted by the caller.", "AbortError");
154
+
155
+ export const normalizeClassifierAnswers = (
156
+ result: Pick<ClassifierResult, "answers">,
157
+ required: readonly (keyof JevAnswers)[]
158
+ ): JevAnswers => {
159
+ if (!isRecordOf(result.answers)) {
160
+ throw new JevFailure("malformed", "Classifier returned malformed answers.");
161
+ }
162
+
163
+ const answers: JevAnswers = {};
164
+
165
+ for (const name of required) {
166
+ const answer = result.answers[name];
167
+
168
+ if (
169
+ isRecordOf(answer) &&
170
+ answer.type === "bool" &&
171
+ isProbability(answer.probability)
172
+ ) {
173
+ if (name === "self_answerable" || name === "should_consult") {
174
+ answers[name] = { noul: answer.probability, type: "noul" };
175
+ } else {
176
+ throw new JevFailure(
177
+ "malformed",
178
+ `Classifier returned an unexpected bool answer for ${name}.`
179
+ );
180
+ }
181
+
182
+ continue;
183
+ }
184
+
185
+ if (isRecordOf(answer) && answer.type === "choice") {
186
+ if (!isRecordOf(answer.probabilities) || !isString(answer.choice)) {
187
+ throw new JevFailure(
188
+ "malformed",
189
+ `Classifier returned malformed ${name} choice.`
190
+ );
191
+ }
192
+
193
+ const probabilities: Record<string, number> = {};
194
+
195
+ for (const [label, probability] of Object.entries(answer.probabilities)) {
196
+ if (!isProbability(probability)) {
197
+ throw new JevFailure(
198
+ "malformed",
199
+ `Classifier returned an invalid ${name} probability.`
200
+ );
201
+ }
202
+
203
+ probabilities[label] = probability;
204
+ }
205
+
206
+ if (name === "stakes") {
207
+ const expected = ["high", "moderate", "negligible"];
208
+
209
+ const distributionTotal = expected.reduce(
210
+ (sum, label) => sum + (probabilities[label] ?? 0),
211
+ 0
212
+ );
213
+
214
+ if (
215
+ !expected.includes(answer.choice) ||
216
+ expected.some((label) => !Object.hasOwn(probabilities, label)) ||
217
+ distributionTotal <= 0 ||
218
+ Math.abs(distributionTotal - 1) > 0.05
219
+ ) {
220
+ throw new JevFailure(
221
+ "malformed",
222
+ "Classifier returned an incomplete stakes distribution."
223
+ );
224
+ }
225
+
226
+ if (!isProbability(answer.confidence)) {
227
+ throw new JevFailure(
228
+ "malformed",
229
+ "Classifier returned invalid stakes confidence."
230
+ );
231
+ }
232
+
233
+ answers.stakes = {
234
+ choice: answer.choice,
235
+ confidence: answer.confidence,
236
+ probabilities,
237
+ type: "choice",
238
+ };
239
+ } else {
240
+ throw new JevFailure(
241
+ "malformed",
242
+ `Classifier returned unsupported choice answer for ${name}.`
243
+ );
244
+ }
245
+
246
+ continue;
247
+ }
248
+
249
+ throw new JevFailure(
250
+ "malformed",
251
+ `Classifier omitted or invalidated ${name}.`
252
+ );
253
+ }
254
+
255
+ return answers;
256
+ };
257
+
258
+ const classifyWithinDeadline = async (
259
+ ctx: JevClassifierContext,
260
+ model: ClassifierModel<ClassifierApi>,
261
+ state: JevState,
262
+ questions: JevQuestionSet,
263
+ options: JevClassifierOptions,
264
+ timeoutMs: number
265
+ ): Promise<ClassifierResult> => {
266
+ const controller = new AbortController();
267
+ const callerSignal = options.signal ?? ctx.signal;
268
+ const abortFromCaller = () => controller.abort(callerSignal?.reason);
269
+
270
+ if (callerSignal?.aborted) {
271
+ throw abortError();
272
+ }
273
+
274
+ callerSignal?.addEventListener("abort", abortFromCaller, { once: true });
275
+
276
+ const timeout = setTimeout(() => {
277
+ controller.abort(new DOMException("Timed out", "TimeoutError"));
278
+ }, timeoutMs);
279
+
280
+ const apiOptions: ModelsClassifierOptions = {
281
+ maxRetries: 0,
282
+ signal: controller.signal,
283
+ timeoutMs,
284
+ };
285
+
286
+ if (options.apiKey !== undefined) {
287
+ apiOptions.apiKey = options.apiKey;
288
+ }
289
+
290
+ let abortListener: (() => void) | undefined;
291
+
292
+ try {
293
+ // SAFETY: JevState contains only JSON-compatible, redacted strings and its fixed role field.
294
+ const classification = ctx.modelRegistry.classify(
295
+ model,
296
+ { questions, state: state as Record<string, JsonValue> },
297
+ apiOptions
298
+ );
299
+
300
+ const aborted = Promise.withResolvers<never>();
301
+ abortListener = () => {
302
+ aborted.reject(controller.signal.reason ?? abortError());
303
+ };
304
+
305
+ controller.signal.addEventListener("abort", abortListener, { once: true });
306
+
307
+ const request = Promise.race([classification, aborted.promise]);
308
+
309
+ return await request;
310
+ } catch (error) {
311
+ if (callerSignal?.aborted) {
312
+ throw error;
313
+ }
314
+
315
+ if (controller.signal.aborted) {
316
+ throw new JevFailure(
317
+ "timeout",
318
+ `Jev classifier timed out after ${timeoutMs}ms.`
319
+ );
320
+ }
321
+
322
+ if (error instanceof JevFailure) {
323
+ throw error;
324
+ }
325
+
326
+ throw new JevFailure("error", "Jev classifier request failed.");
327
+ } finally {
328
+ clearTimeout(timeout);
329
+ callerSignal?.removeEventListener("abort", abortFromCaller);
330
+
331
+ if (abortListener) {
332
+ controller.signal.removeEventListener("abort", abortListener);
333
+ }
334
+ }
335
+ };
336
+
337
+ export const classifyWithJev = async (
338
+ ctx: JevClassifierContext,
339
+ ref: string,
340
+ state: JevState,
341
+ questions: JevQuestionSet,
342
+ options: JevClassifierOptions = {}
343
+ ): Promise<JevClassifierResult> => {
344
+ const parsed = parseJevClassifierRef(ref);
345
+
346
+ if (!parsed) {
347
+ throw new JevFailure("malformed", "No Jev classifier is selected.");
348
+ }
349
+
350
+ const model = ctx.modelRegistry.findOfType(
351
+ "classifier",
352
+ parsed.provider,
353
+ parsed.modelId
354
+ );
355
+
356
+ if (!isClassifierModel(model)) {
357
+ throw new JevFailure("error", `Selected classifier ${ref} is unavailable.`);
358
+ }
359
+
360
+ const timeoutMs = Math.max(1, advisorJevTimeoutMsRef);
361
+
362
+ const result = await classifyWithinDeadline(
363
+ ctx,
364
+ model,
365
+ state,
366
+ questions,
367
+ options,
368
+ timeoutMs
369
+ );
370
+
371
+ const stopped = result.stopReason !== "stop";
372
+
373
+ if (stopped) {
374
+ throw new JevFailure(
375
+ "error",
376
+ `Jev classifier stopped: ${result.stopReason}.`
377
+ );
378
+ }
379
+
380
+ return {
381
+ // SAFETY: caller questions are built from the fixed Jev policy sets.
382
+ answers: normalizeClassifierAnswers(
383
+ result,
384
+ Object.keys(questions) as (keyof JevAnswers)[]
385
+ ),
386
+ model: `${result.provider}/${result.model}`,
387
+ usage: normalizedUsage(result.usage),
388
+ };
389
+ };
390
+
391
+ export const classifyScreening = (
392
+ ctx: JevClassifierContext,
393
+ ref: string,
394
+ state: JevState,
395
+ options?: JevClassifierOptions
396
+ ) => classifyWithJev(ctx, ref, state, nativeScreeningQuestions, options);
397
+
398
+ export const classifyTurnGate = (
399
+ ctx: JevClassifierContext,
400
+ ref: string,
401
+ state: JevState,
402
+ options?: JevClassifierOptions
403
+ ) =>
404
+ classifyWithJev(
405
+ ctx,
406
+ ref,
407
+ state,
408
+ {
409
+ should_consult: {
410
+ criteria: {
411
+ false:
412
+ "The executor is progressing soundly on work that matches the user's intent; interrupting would add nothing material.",
413
+ 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.",
414
+ },
415
+ instructions:
416
+ "Should a senior engineering advisor be consulted right now, before the executor continues? Judge from `recent_conversation`.",
417
+ type: "bool",
418
+ },
419
+ },
420
+ options
421
+ );
package/src/jev/ledger.ts CHANGED
@@ -97,8 +97,8 @@ const formatJevTokens = (usage: AdvisorJevUsageTotals) =>
97
97
  const jevCostText = (usage: AdvisorJevUsageTotals) => {
98
98
  if (usage.unavailableCostCalls > 0) {
99
99
  return usage.knownCostCalls > 0
100
- ? `cost unavailable (known-provider estimates $${usage.cost.toFixed(4)}; Decisions billing unconfirmed)`
101
- : "cost unavailable (Decisions billing unconfirmed)";
100
+ ? `cost unavailable (known catalog-priced usage $${usage.cost.toFixed(4)})`
101
+ : "cost unavailable (classifier usage was not reported)";
102
102
  }
103
103
 
104
104
  return `$${usage.cost.toFixed(4)}`;
@@ -241,7 +241,7 @@ export class AdvisorJevLedgerState {
241
241
  const cost =
242
242
  usage.unavailableCostCalls > 0
243
243
  ? jevCostText(usage)
244
- : `$${usage.cost.toFixed(4)} (input only; output free)`;
244
+ : `$${usage.cost.toFixed(4)} (catalog-priced input/cache; output free)`;
245
245
 
246
246
  lines.push(
247
247
  `Jev/Decisions cost: ${formatJevTokens(usage)} tokens · ${cost}`
@@ -1,3 +1,4 @@
1
+ import type { ClassifierQuestion } from "@earendil-works/pi-ai";
1
2
  import type { Questions } from "@typesafe-ai/sdk";
2
3
 
3
4
  import { isNumber, isRecordOf } from "../content-utils.ts";
@@ -29,6 +30,37 @@ export const screeningQuestions: Questions = {
29
30
  },
30
31
  };
31
32
 
33
+ export const nativeTurnGateQuestion: ClassifierQuestion = {
34
+ criteria: {
35
+ false:
36
+ "The executor is progressing soundly on work that matches the user's intent; interrupting would add nothing material.",
37
+ 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.",
38
+ },
39
+ instructions:
40
+ "Should a senior engineering advisor be consulted right now, before the executor continues? Judge from `recent_conversation`.",
41
+ type: "bool",
42
+ };
43
+
44
+ export const nativeScreeningQuestions = {
45
+ self_answerable: {
46
+ criteria: {
47
+ false: "The executor needs the Advisor's second opinion.",
48
+ true: "The executor can resolve this alone with available tools and context.",
49
+ },
50
+ instructions: `Can the executor confidently resolve this request alone, using available tools and context? ${EVIDENCE_RULE}`,
51
+ type: "bool",
52
+ },
53
+ stakes: {
54
+ criteria: {
55
+ high: STAKES_RUBRIC[2],
56
+ moderate: STAKES_RUBRIC[1],
57
+ negligible: STAKES_RUBRIC[0],
58
+ },
59
+ instructions: `How material are the stakes of the decision behind this consultation request? ${EVIDENCE_RULE}`,
60
+ type: "choice",
61
+ },
62
+ } satisfies Record<string, ClassifierQuestion>;
63
+
32
64
  export interface TurnGateQuestions {
33
65
  instructions: string;
34
66
  }
@@ -42,15 +74,12 @@ export type ScreeningVerdict = { skip: false } | { skip: true };
42
74
 
43
75
  const NUMERIC_KEY_PATTERN = /^\d+$/u;
44
76
 
45
- const finiteNumber = (value: JsonValue | undefined): number | undefined =>
46
- isNumber(value) && Number.isFinite(value) ? value : undefined;
77
+ const finiteProbability = (value: JsonValue | undefined): number | undefined =>
78
+ isNumber(value) && Number.isFinite(value) && value >= 0 && value <= 1
79
+ ? value
80
+ : undefined;
47
81
 
48
- /**
49
- * Probability mass on the lowest stakes level, resolved through the answer's
50
- * legend (the key whose description equals level 0), falling back to the
51
- * smallest numeric index key only when no legend resolves. Shape-independent:
52
- * never hardcodes a level key and never uses `ceil(score)`.
53
- */
82
+ /** Lowest-stakes probability via rubric legend or the canonical native choice label. */
54
83
  export const lowestStakesProbability = <Answer>(
55
84
  answer: Answer
56
85
  ): number | undefined => {
@@ -70,10 +99,14 @@ export const lowestStakesProbability = <Answer>(
70
99
  );
71
100
 
72
101
  if (exact) {
73
- return finiteNumber(probabilities[exact]);
102
+ return finiteProbability(probabilities[exact]);
74
103
  }
75
104
  }
76
105
 
106
+ if (Object.hasOwn(probabilities, "negligible")) {
107
+ return finiteProbability(probabilities.negligible);
108
+ }
109
+
77
110
  const numericKeys = Object.keys(probabilities).filter((key) =>
78
111
  NUMERIC_KEY_PATTERN.test(key)
79
112
  );
@@ -90,15 +123,22 @@ export const lowestStakesProbability = <Answer>(
90
123
  }
91
124
  }
92
125
 
93
- return finiteNumber(probabilities[lowest]);
126
+ return finiteProbability(probabilities[lowest]);
94
127
  };
95
128
 
96
- const selfAnswerableNoul = <Answer>(answer: Answer): number | undefined =>
97
- isRecordOf(answer) ? finiteNumber(answer.noul) : undefined;
129
+ const selfAnswerableProbability = <Answer>(
130
+ answer: Answer
131
+ ): number | undefined => {
132
+ if (!isRecordOf(answer)) {
133
+ return undefined;
134
+ }
135
+
136
+ const value = answer.type === "bool" ? answer.probability : answer.noul;
98
137
 
99
- /** Pure composition: skip requires the hard conjunction of confident
100
- * negligible stakes AND confident self-answerability. Any missing, NaN, or
101
- * malformed input allows. Never a weighted sum. */
138
+ return finiteProbability(value);
139
+ };
140
+
141
+ /** Pure composition; any missing, out-of-range, NaN, or malformed input allows. */
102
142
  export const composeScreeningVerdict = <Answers>(
103
143
  answers: Answers,
104
144
  { noulMargin, skipConfidence }: ScreeningCriteria
@@ -108,16 +148,15 @@ export const composeScreeningVerdict = <Answers>(
108
148
  }
109
149
 
110
150
  const negligibleMass = lowestStakesProbability(answers.stakes);
111
- const noul = selfAnswerableNoul(answers.self_answerable);
151
+ const selfAnswerable = selfAnswerableProbability(answers.self_answerable);
112
152
 
113
- if (negligibleMass === undefined || noul === undefined) {
153
+ if (negligibleMass === undefined || selfAnswerable === undefined) {
114
154
  return { skip: false };
115
155
  }
116
156
 
117
- const confidentlySelfAnswerable = noul >= 0.5 + noulMargin;
118
-
119
157
  return {
120
- skip: negligibleMass >= skipConfidence && confidentlySelfAnswerable,
158
+ skip:
159
+ negligibleMass >= skipConfidence && selfAnswerable >= 0.5 + noulMargin,
121
160
  };
122
161
  };
123
162
 
@@ -130,8 +169,7 @@ export const composeTurnGateVerdict = <Answers>(
130
169
  return false;
131
170
  }
132
171
 
133
- const answer = answers.should_consult;
134
- const noul = isRecordOf(answer) ? finiteNumber(answer.noul) : undefined;
172
+ const probability = selfAnswerableProbability(answers.should_consult);
135
173
 
136
- return noul !== undefined && noul >= threshold;
174
+ return probability !== undefined && probability >= threshold;
137
175
  };