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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,9 @@
1
+ import type { Usage } from "@earendil-works/pi-ai";
1
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { Fetch } from "@typesafe-ai/sdk";
3
3
 
4
4
  import {
5
+ advisorJevClassifierModeRef,
6
+ advisorJevClassifierRef,
5
7
  advisorJevFilterEnabledRef,
6
8
  advisorJevFilterNoulMarginRef,
7
9
  advisorJevFilterOverrideWindowRef,
@@ -9,27 +11,24 @@ import {
9
11
  isSimpleMode,
10
12
  } from "../config/state.ts";
11
13
  import { capUtf8Bytes } from "../content-utils.ts";
12
- import { JevFailure, jevClientFromCredentials } from "../jev/client.ts";
13
- import { consumePlaintextKeyWarning } from "../jev/key-store.ts";
14
- import {
15
- composeScreeningVerdict,
16
- screeningQuestions,
17
- } from "../jev/questions.ts";
14
+ import { consumeJevClassifierKey } from "../jev/classifier-key-store.ts";
15
+ import { classifyScreening } from "../jev/classifier.ts";
16
+ import { JevFailure } from "../jev/failure.ts";
17
+ import { composeScreeningVerdict } from "../jev/questions.ts";
18
18
  import { buildJevState } from "../jev/state.ts";
19
- import { resolveJevTransport } from "../jev/transport.ts";
20
- import type { JevCredentials } from "../jev/transport.ts";
21
19
  import type { AdvisorSessionState } from "../session-state.ts";
22
20
  import { createOutageNotifier } from "./outage-notifier.ts";
23
21
 
24
22
  export type JevSkipKind = "screened" | "repeat";
25
23
 
26
24
  export type ScreeningOutcome =
27
- | { decision: "allow" }
25
+ | { decision: "allow"; usage?: Usage }
28
26
  | {
29
27
  decision: "skip";
30
28
  kind: JevSkipKind;
31
29
  reason: string;
32
30
  reattachedAdvice?: string;
31
+ usage?: Usage;
33
32
  };
34
33
 
35
34
  export interface ScreenConsultationOptions {
@@ -40,8 +39,17 @@ export interface ScreenConsultationOptions {
40
39
  }
41
40
 
42
41
  export interface ScreeningDeps {
43
- fetch?: Fetch;
44
- resolveTransport?: () => Promise<JevCredentials | undefined>;
42
+ classify?: typeof classifyScreening;
43
+ classifyResult?: (
44
+ state: ReturnType<typeof buildJevState>,
45
+ signal?: AbortSignal
46
+ ) => Promise<
47
+ ReturnType<typeof classifyScreening> extends Promise<infer Result>
48
+ ? Result
49
+ : never
50
+ >;
51
+ resolveApiKey?: () => Promise<string | undefined>;
52
+ selectedRef?: () => string | undefined;
45
53
  }
46
54
 
47
55
  export const normalizeScreeningQuestion = (question: string | undefined) =>
@@ -57,7 +65,7 @@ const repeatSkipText = (advice: string) =>
57
65
 
58
66
  const outageNotifier = createOutageNotifier(
59
67
  (category, message) =>
60
- `Advisor Jev/Decisions filter failed (${category}); allowing consultations. ${message}`
68
+ `Advisor Jev classifier failed (${category}); allowing consultations. ${message}`
61
69
  );
62
70
 
63
71
  const notifyOutageOnce = outageNotifier.notify;
@@ -99,6 +107,16 @@ const bypassOutcome = (
99
107
  return undefined;
100
108
  };
101
109
 
110
+ const classifierRef = (deps: ScreeningDeps) =>
111
+ advisorJevClassifierModeRef === "api-key"
112
+ ? "typesafe/jev-latest"
113
+ : (deps.selectedRef?.() ?? advisorJevClassifierRef);
114
+
115
+ const apiKeyFor = (deps: ScreeningDeps) =>
116
+ advisorJevClassifierModeRef === "api-key"
117
+ ? (deps.resolveApiKey ?? consumeJevClassifierKey)()
118
+ : Promise.resolve(undefined);
119
+
102
120
  const screenWithJev = async (
103
121
  ctx: ExtensionContext,
104
122
  session: AdvisorSessionState,
@@ -106,37 +124,38 @@ const screenWithJev = async (
106
124
  deps: ScreeningDeps,
107
125
  normalizedQuestion: string | undefined
108
126
  ): Promise<ScreeningOutcome> => {
109
- const credentials = await (deps.resolveTransport ?? resolveJevTransport)(ctx);
127
+ const selectedRef = classifierRef(deps);
128
+ const apiKey = await apiKeyFor(deps);
110
129
 
111
- if (!credentials) {
130
+ if (!selectedRef || (advisorJevClassifierModeRef === "api-key" && !apiKey)) {
112
131
  session.recordJevFilterFailure();
113
132
  notifyOutageOnce(
114
133
  ctx,
115
134
  "missing-key",
116
- "No credentials resolved for the selected Jev/Decisions provider."
135
+ "No credentials resolved for the selected Jev classifier."
117
136
  );
118
137
 
119
138
  return allow();
120
139
  }
121
140
 
122
- if (credentials.source === "advisor-json") {
123
- const warning = consumePlaintextKeyWarning();
124
-
125
- if (warning && ctx.hasUI) {
126
- ctx.ui.notify(warning, "warning");
127
- }
128
- }
129
-
130
- const client = jevClientFromCredentials(credentials, deps.fetch);
131
-
132
141
  try {
133
- const result = await client.ask(
134
- buildJevState(ctx, options),
135
- screeningQuestions,
136
- options.signal
137
- );
138
-
139
- session.recordJevFilterUsage(result.usage);
142
+ const state = buildJevState(ctx, options);
143
+
144
+ const result = deps.classifyResult
145
+ ? await deps.classifyResult(state, options.signal)
146
+ : await (deps.classify ?? classifyScreening)(ctx, selectedRef, state, {
147
+ apiKey:
148
+ advisorJevClassifierModeRef === "api-key" ? apiKey : undefined,
149
+ signal: options.signal,
150
+ });
151
+
152
+ if (result.usage) {
153
+ session.recordJevFilterUsage({
154
+ cost: result.usage.cost,
155
+ inputTokens: result.usage.inputTokens,
156
+ outputTokens: result.usage.outputTokens,
157
+ });
158
+ }
140
159
 
141
160
  const verdict = composeScreeningVerdict(result.answers, {
142
161
  noulMargin: advisorJevFilterNoulMarginRef,
@@ -150,12 +169,13 @@ const screenWithJev = async (
150
169
  decision: "skip",
151
170
  kind: "screened",
152
171
  reason: "low stakes and resolvable without a consultation",
172
+ usage: result.usage?.piUsage,
153
173
  };
154
174
  }
155
175
 
156
176
  session.recordJevFilterAllowed();
157
177
 
158
- return allow();
178
+ return { decision: "allow", usage: result.usage?.piUsage };
159
179
  } catch (error) {
160
180
  if (options.signal?.aborted) {
161
181
  throw error;
@@ -2,9 +2,10 @@ import type {
2
2
  ExtensionContext,
3
3
  TurnEndEvent,
4
4
  } from "@earendil-works/pi-coding-agent";
5
- import type { Fetch } from "@typesafe-ai/sdk";
6
5
 
7
6
  import {
7
+ advisorJevClassifierModeRef,
8
+ advisorJevClassifierRef,
8
9
  advisorJevTurnGateEveryTurnsRef,
9
10
  advisorJevTurnGateNoulThresholdRef,
10
11
  getAdvisorMaxCallsPerSession,
@@ -12,11 +13,11 @@ import {
12
13
  } from "../config/state.ts";
13
14
  import { herdrAdvisorActivity } from "../herdr.ts";
14
15
  import type { HerdrAdvisorActivityScope } from "../herdr.ts";
15
- import { JevFailure, jevClientFromCredentials } from "../jev/client.ts";
16
+ import { consumeJevClassifierKey } from "../jev/classifier-key-store.ts";
17
+ import { classifyTurnGate } from "../jev/classifier.ts";
18
+ import { JevFailure } from "../jev/failure.ts";
16
19
  import { composeTurnGateVerdict } from "../jev/questions.ts";
17
20
  import { buildJevState } from "../jev/state.ts";
18
- import { resolveJevTransport } from "../jev/transport.ts";
19
- import type { JevCredentials } from "../jev/transport.ts";
20
21
  import type { AdvisorSessionState } from "../session-state.ts";
21
22
  import { advisorUsageCost } from "../usage.ts";
22
23
  import type { consultAdvisor } from "./consultation.ts";
@@ -24,21 +25,11 @@ import { updateAdvisorUsageStatus } from "./gate-policy.ts";
24
25
  import { advisorModelIsAllowed } from "./model-access.ts";
25
26
  import { createOutageNotifier } from "./outage-notifier.ts";
26
27
 
27
- export const turnGateQuestion = {
28
- criteria: {
29
- false:
30
- "The executor is progressing soundly on work that matches the user's intent; interrupting would add nothing material.",
31
- 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.",
32
- },
33
- instructions:
34
- "Should a senior engineering advisor be consulted right now, before the executor continues? Judge from `recent_conversation`.",
35
- type: "noul",
36
- } as const;
37
-
38
28
  export interface JevTurnGateDeps {
29
+ classifyResult?: () => ReturnType<typeof classifyTurnGate>;
39
30
  consult?: typeof consultAdvisor;
40
- fetch?: Fetch;
41
- resolveTransport?: () => Promise<JevCredentials | undefined>;
31
+ resolveApiKey?: () => Promise<string | undefined>;
32
+ selectedRef?: () => string | undefined;
42
33
  }
43
34
 
44
35
  export interface TurnGateCallDetails {
@@ -69,7 +60,7 @@ export interface JevTurnGateRegistration {
69
60
 
70
61
  const outageNotifier = createOutageNotifier(
71
62
  (category, message) =>
72
- `Advisor Jev/Decisions turn gate failed (${category}); continuing without a proactive consultation. ${message}`
63
+ `Advisor Jev classifier turn gate failed (${category}); continuing without a proactive consultation. ${message}`
73
64
  );
74
65
 
75
66
  const notifyFailureOnce = outageNotifier.notify;
@@ -109,12 +100,90 @@ const consumeTurnGateBudget = (
109
100
  /** Test-only: re-arms the once-per-outage notification. */
110
101
  export const resetJevTurnGateNotification = outageNotifier.reset;
111
102
 
112
- /**
113
- * turn_end handler: counts turns without a consultation and, every Nth such
114
- * turn, asks Jev whether the Advisor should proactively weigh in. Confident
115
- * true runs a real consultation delivered as a steer message; everything else
116
- * keeps the status quo.
117
- */
103
+ const classifyGate = async (ctx: ExtensionContext, deps: JevTurnGateDeps) => {
104
+ if (deps.classifyResult) {
105
+ return deps.classifyResult();
106
+ }
107
+
108
+ const selectedRef =
109
+ advisorJevClassifierModeRef === "api-key"
110
+ ? "typesafe/jev-latest"
111
+ : (deps.selectedRef?.() ?? advisorJevClassifierRef);
112
+
113
+ const apiKey =
114
+ advisorJevClassifierModeRef === "api-key"
115
+ ? await (deps.resolveApiKey ?? consumeJevClassifierKey)()
116
+ : undefined;
117
+
118
+ if (!selectedRef || (advisorJevClassifierModeRef === "api-key" && !apiKey)) {
119
+ throw new JevFailure(
120
+ "auth",
121
+ "No credentials resolved for the selected Jev classifier."
122
+ );
123
+ }
124
+
125
+ return classifyTurnGate(ctx, selectedRef, buildJevState(ctx, {}), {
126
+ apiKey,
127
+ signal: ctx.signal,
128
+ });
129
+ };
130
+
131
+ const sendProactiveConsultation = async (
132
+ registration: JevTurnGateRegistration,
133
+ ctx: ExtensionContext,
134
+ consult: typeof consultAdvisor
135
+ ) => {
136
+ const { session } = registration;
137
+ const activity = registration.herdrActivity ?? herdrAdvisorActivity;
138
+ const finishHerdrActivity = activity.start();
139
+
140
+ try {
141
+ registration.send({
142
+ content: "Proactive Advisor turn review",
143
+ customType: "advisor-turn-gate-call",
144
+ details: {
145
+ question: `Turn gate: ${session.turnsSinceConsultation} turns without a consultation`,
146
+ turn: session.sessionTurnOrdinal,
147
+ },
148
+ display: true,
149
+ });
150
+
151
+ const consulted = await consult(
152
+ ctx,
153
+ undefined,
154
+ ctx.signal,
155
+ undefined,
156
+ "turn-gate"
157
+ );
158
+
159
+ session.recordJevGateConsultation();
160
+ session.resetTurnsSinceConsultation();
161
+ session.recordInvocation({
162
+ cost: advisorUsageCost(consulted.usage),
163
+ executionEffect: "continued",
164
+ kind: "markdown",
165
+ model: consulted.model,
166
+ trigger: "turn-gate",
167
+ usage: consulted.usage,
168
+ });
169
+ updateAdvisorUsageStatus(ctx, session);
170
+ registration.send({
171
+ content: consulted.markdown,
172
+ customType: "advisor-turn-gate-result",
173
+ details: {
174
+ advisor: consulted.model,
175
+ agentRulesBytes: consulted.agentRulesBytes,
176
+ text: consulted.markdown,
177
+ usage: consulted.usage,
178
+ },
179
+ display: true,
180
+ });
181
+ } finally {
182
+ finishHerdrActivity();
183
+ }
184
+ };
185
+
186
+ /** Run the periodic policy check and optional proactive consultation. */
118
187
  export const handleJevTurnEnd = async (
119
188
  registration: JevTurnGateRegistration,
120
189
  ctx: ExtensionContext
@@ -127,90 +196,29 @@ export const handleJevTurnEnd = async (
127
196
  }
128
197
 
129
198
  const consult = registration.deps?.consult ?? registration.consult;
130
- const deps = registration.deps ?? {};
131
199
 
132
200
  try {
133
- const credentials = await (deps.resolveTransport ?? resolveJevTransport)(
134
- ctx
201
+ const result = await classifyGate(ctx, registration.deps ?? {});
202
+ session.recordJevGateCheck(
203
+ result.usage
204
+ ? {
205
+ cost: result.usage.cost,
206
+ inputTokens: result.usage.inputTokens,
207
+ outputTokens: result.usage.outputTokens,
208
+ }
209
+ : undefined
135
210
  );
136
211
 
137
- if (!credentials) {
138
- session.recordJevGateFailure();
139
- notifyFailureOnce(
140
- ctx,
141
- "missing-key",
142
- "No credentials resolved for the selected Jev/Decisions provider."
143
- );
144
-
145
- return;
146
- }
147
-
148
- const client = jevClientFromCredentials(credentials, deps.fetch);
149
-
150
- const result = await client.ask(buildJevState(ctx, {}), {
151
- should_consult: turnGateQuestion,
152
- });
153
-
154
- session.recordJevGateCheck(result.usage);
155
-
156
212
  const shouldConsult = composeTurnGateVerdict(
157
213
  result.answers,
158
214
  advisorJevTurnGateNoulThresholdRef
159
215
  );
160
216
 
161
217
  if (
162
- !advisorModelIsAllowed(ctx) ||
163
- !consumeTurnGateBudget(session, shouldConsult)
218
+ advisorModelIsAllowed(ctx) &&
219
+ consumeTurnGateBudget(session, shouldConsult)
164
220
  ) {
165
- return;
166
- }
167
-
168
- const herdrActivity = registration.herdrActivity ?? herdrAdvisorActivity;
169
- const finishHerdrActivity = herdrActivity.start();
170
-
171
- try {
172
- registration.send({
173
- content: "Proactive Advisor turn review",
174
- customType: "advisor-turn-gate-call",
175
- details: {
176
- question: `Turn gate: ${session.turnsSinceConsultation} turns without a consultation`,
177
- turn: session.sessionTurnOrdinal,
178
- },
179
- display: true,
180
- });
181
-
182
- const consulted = await consult(
183
- ctx,
184
- undefined,
185
- ctx.signal,
186
- undefined,
187
- "turn-gate"
188
- );
189
-
190
- session.recordJevGateConsultation();
191
- session.resetTurnsSinceConsultation();
192
- session.recordInvocation({
193
- cost: advisorUsageCost(consulted.usage),
194
- executionEffect: "continued",
195
- kind: "markdown",
196
- model: consulted.model,
197
- trigger: "turn-gate",
198
- usage: consulted.usage,
199
- });
200
- updateAdvisorUsageStatus(ctx, session);
201
- registration.send({
202
- content: consulted.markdown,
203
- customType: "advisor-turn-gate-result",
204
- details: {
205
- advisor: consulted.model,
206
- agentRulesBytes: consulted.agentRulesBytes,
207
- text: consulted.markdown,
208
- usage: consulted.usage,
209
- },
210
- display: true,
211
- });
212
- } finally {
213
- finishHerdrActivity();
221
+ await sendProactiveConsultation(registration, ctx, consult);
214
222
  }
215
223
  } catch (error) {
216
224
  session.recordJevGateFailure();
@@ -1,3 +1,4 @@
1
+ import type { Usage } from "@earendil-works/pi-ai";
1
2
  import type {
2
3
  AgentToolResult,
3
4
  ExtensionContext,
@@ -21,6 +22,7 @@ import {
21
22
  import {
22
23
  advisorUsageCost,
23
24
  advisorUsageForPi,
25
+ combineAdvisorAndClassifierUsage,
24
26
  snapshotAdvisorUsage,
25
27
  } from "../usage.ts";
26
28
  import { advisorOutputSchema } from "./advisor-output.ts";
@@ -181,6 +183,7 @@ export const registerAskAdvisorTool = ({
181
183
  throw error;
182
184
  }
183
185
 
186
+ let classifierUsage: Usage | undefined;
184
187
  const simpleMode = isSimpleMode();
185
188
 
186
189
  if (
@@ -220,6 +223,8 @@ export const registerAskAdvisorTool = ({
220
223
  signal,
221
224
  });
222
225
 
226
+ classifierUsage = screening.usage;
227
+
223
228
  if (screening.decision === "skip") {
224
229
  const skipText = screeningSkipText(screening);
225
230
  session.releaseCall(_id);
@@ -234,11 +239,17 @@ export const registerAskAdvisorTool = ({
234
239
  text: skipText,
235
240
  };
236
241
 
237
- return {
242
+ const skipResult: AgentToolResult<AdvisorToolDetails> = {
238
243
  content: [{ text: skipText, type: "text" }],
239
244
  details: skipped,
240
245
  structuredContent: skipped,
241
246
  };
247
+
248
+ if (classifierUsage) {
249
+ skipResult.usage = classifierUsage;
250
+ }
251
+
252
+ return skipResult;
242
253
  }
243
254
 
244
255
  if (sameModelAdvisorDisabled(ctx, ctx.model, followUp?.payload.model)) {
@@ -348,7 +359,13 @@ export const registerAskAdvisorTool = ({
348
359
  usage: result.usage,
349
360
  });
350
361
  const usage = snapshotAdvisorUsage(result.usage);
351
- const piUsage = advisorUsageForPi(result.usage);
362
+ const advisorPiUsage = advisorUsageForPi(result.usage);
363
+
364
+ const piUsage = combineAdvisorAndClassifierUsage(
365
+ advisorPiUsage,
366
+ classifierUsage
367
+ );
368
+
352
369
  updateAdvisorUsageStatus(ctx, session);
353
370
 
354
371
  const details: AdvisorToolDetails = {