pi-permission-classifier 0.5.2 → 0.6.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.
@@ -0,0 +1,452 @@
1
+ /**
2
+ * The quick judge: a System One decision model answers a fixed question set
3
+ * about each ask through the registry's `classify`, and the answers map to a
4
+ * verdict. It runs inside the permission-judge link when the mode includes
5
+ * it.
6
+ *
7
+ * The decision runs top to bottom, so the cheap gates short-circuit before
8
+ * any model call:
9
+ * 1. settings are loaded (else defer, recorded),
10
+ * 2. the gate-authoritative surface is determinable and outside the `path`
11
+ * and `external_directory` families (else defer, not recorded),
12
+ * 3. the full command fits `contextBudgetBytes` (else over-budget),
13
+ * 4. the judge's own circuit breaker is closed (else breaker-open),
14
+ * 5. the classifier model resolves through `findOfType("classifier", ...)`
15
+ * (else model-unresolved; there is no session-model fallback),
16
+ * 6. with `quickJudge.guidance` on, the guidance seam selects this ask's
17
+ * files, read per ask (a throw is guidance-load-failed),
18
+ * 7. the user intent seam gives the user's own messages, or none,
19
+ * 8. `classify` runs under an abort signal bounded by `quickJudge.timeoutMs`.
20
+ *
21
+ * With intent the request adds the user messages and the requested and
22
+ * forbidden questions, and the mapping counts their answers; without it the
23
+ * request and the mapping are the ones without intent.
24
+ *
25
+ * From step 3 on every outcome goes through the verdict policy with the
26
+ * judge's `verdicts` and `onError`. A failure never allows. Each recorded
27
+ * decision writes one `classifier.decision` entry tagged `judge: "quick"`,
28
+ * with the per-question answers when the model answered.
29
+ */
30
+
31
+ import type {
32
+ ClassifierAnswer,
33
+ ClassifierApi,
34
+ ClassifierContext,
35
+ ClassifierModel,
36
+ ClassifierResult,
37
+ JsonValue,
38
+ } from "@earendil-works/pi-ai";
39
+ import type {
40
+ Authorizer,
41
+ AuthorizerLog,
42
+ AuthorizerVerdict,
43
+ PromptPermissionDetails,
44
+ } from "@gotgenes/pi-permission-system";
45
+
46
+ import { CircuitBreaker } from "./breaker";
47
+ import type { QuickJudgeConfig } from "./config-schema";
48
+ import { extractFullCommandContext, type FullCommandContext } from "./context";
49
+ import type { GuidanceSelection } from "./guidance";
50
+ import type { HealthOutcome } from "./health";
51
+ import {
52
+ contextFields,
53
+ DECISION_EVENT,
54
+ DENY_CAPPED_REASON,
55
+ EMPTY_GUIDANCE,
56
+ gateSurfaceOf,
57
+ guidanceFields,
58
+ isExcludedSurface,
59
+ SHORT_CIRCUIT_EVENT,
60
+ userIntentFor,
61
+ } from "./reviewer";
62
+ import { buildSystemOneContext, mapSystemOneResult } from "./system-one-review";
63
+ import type { UserIntent } from "./user-intent";
64
+ import {
65
+ applyVerdictPolicy,
66
+ type LinkOutcome,
67
+ type VerdictPolicy,
68
+ } from "./verdict-policy";
69
+
70
+ /** The judge tag every decision entry of this judge carries. */
71
+ const JUDGE_TAG = "quick";
72
+
73
+ /**
74
+ * The recorded reason for an answer below the thresholds: the model judged
75
+ * and did not clear the bar, the same reason the LLM judge records for its
76
+ * model's own defer, so health treats both as a verdict.
77
+ */
78
+ const UNCERTAIN_REASON = "model-verdict";
79
+
80
+ /** The policy when no settings can be read: never deny, never allow. */
81
+ const DEFAULT_POLICY: VerdictPolicy = { verdicts: "allow-defer", onError: "defer" };
82
+
83
+ /** The narrow model-registry projection the quick judge needs. */
84
+ export interface QuickJudgeRegistryLike {
85
+ findOfType(
86
+ type: "classifier",
87
+ provider: string,
88
+ modelId: string,
89
+ ): ClassifierModel<ClassifierApi> | undefined;
90
+ classify(
91
+ model: ClassifierModel<ClassifierApi>,
92
+ context: ClassifierContext,
93
+ options?: { signal?: AbortSignal },
94
+ ): Promise<ClassifierResult>;
95
+ }
96
+
97
+ /** What the quick judge reads per ask: its own settings and the shared budget. */
98
+ export interface QuickJudgeSettings {
99
+ quickJudge: QuickJudgeConfig;
100
+ contextBudgetBytes: number;
101
+ }
102
+
103
+ /** Collaborators for the quick judge, injected so the extension and tests wire them. */
104
+ export interface QuickJudgeDeps {
105
+ /** The settings in effect, read live (absent until session config loads). */
106
+ getSettings: () => QuickJudgeSettings | undefined;
107
+ /** The session model registry, read live. */
108
+ getRegistry: () => QuickJudgeRegistryLike | undefined;
109
+ /** The session cwd, sent to the model as part of the state. */
110
+ getCwd: () => string;
111
+ /**
112
+ * Guidance seam: called once per judged ask when `quickJudge.guidance` is
113
+ * on, right before the model call (production: the same loader, trust
114
+ * check and selection as the LLM judge). Absent means no guidance.
115
+ * A throw is a guidance-load-failed failure.
116
+ */
117
+ getGuidance?: () => GuidanceSelection;
118
+ /**
119
+ * User intent seam: called once per judged ask right before the model
120
+ * call, with whether the ask was forwarded. Absent, undefined or a throw
121
+ * means no intent.
122
+ */
123
+ getUserIntent?: (forwarded: boolean) => UserIntent | undefined;
124
+ /** This judge's own circuit breaker; the judge makes one when absent. */
125
+ breaker?: CircuitBreaker;
126
+ /**
127
+ * Outcome seam: called once per decision entry with what the judge did,
128
+ * so a failure counts even when onError turns it into a deny.
129
+ */
130
+ onOutcome?: (outcome: HealthOutcome) => void;
131
+ }
132
+
133
+ /** Report through the health seam; a throwing listener never changes a verdict. */
134
+ function report(deps: QuickJudgeDeps, outcome: HealthOutcome): void {
135
+ try {
136
+ deps.onOutcome?.(outcome);
137
+ } catch {
138
+ // The listener failed; the decision stands as logged.
139
+ }
140
+ }
141
+
142
+ /** The health outcome for a link outcome and its recorded reason. */
143
+ function healthOf(outcome: LinkOutcome, reason: string | null): HealthOutcome {
144
+ if (outcome.kind === "allow" || outcome.kind === "deny") {
145
+ return { verdict: outcome.kind };
146
+ }
147
+ return { verdict: "defer", deferReason: reason ?? UNCERTAIN_REASON };
148
+ }
149
+
150
+ /** Build the quick judge's `authorize` callback. */
151
+ export function createQuickJudge(deps: QuickJudgeDeps): Authorizer["authorize"] {
152
+ const breaker = deps.breaker ?? new CircuitBreaker("quick");
153
+
154
+ return async (details, _query, log) => {
155
+ // What the guidance stage selected, so the backstop entry can say what
156
+ // the model saw even when a later stage threw.
157
+ const trail = { guidance: EMPTY_GUIDANCE };
158
+ try {
159
+ return await decide(deps, breaker, details, log, trail);
160
+ } catch {
161
+ // The backstop: whatever threw is an internal-error failure under the
162
+ // judge's onError, and never an allow.
163
+ const verdict = applyVerdictPolicy(
164
+ { kind: "failure", failure: "internal-error" },
165
+ backstopPolicy(deps),
166
+ );
167
+ try {
168
+ log.review(DECISION_EVENT, {
169
+ ...baseEntry(details, gateSurfaceOf(details) ?? null, null),
170
+ modelCalled: false,
171
+ latencyMs: null,
172
+ verdict: verdict.kind,
173
+ deferReason: "internal-error",
174
+ ...contextFields(false, extractFullCommandContext(details.payload)),
175
+ ...guidanceFields(trail.guidance),
176
+ });
177
+ } catch {
178
+ // The log failed too; there is nothing left to record on.
179
+ }
180
+ report(deps, { verdict: "defer", deferReason: "internal-error" });
181
+ return verdict;
182
+ }
183
+ };
184
+ }
185
+
186
+ function backstopPolicy(deps: QuickJudgeDeps): VerdictPolicy {
187
+ try {
188
+ const settings = deps.getSettings();
189
+ return settings ? policyOf(settings) : DEFAULT_POLICY;
190
+ } catch {
191
+ return DEFAULT_POLICY;
192
+ }
193
+ }
194
+
195
+ function policyOf(settings: QuickJudgeSettings): VerdictPolicy {
196
+ return { verdicts: settings.quickJudge.verdicts, onError: settings.quickJudge.onError };
197
+ }
198
+
199
+ async function decide(
200
+ deps: QuickJudgeDeps,
201
+ breaker: CircuitBreaker,
202
+ details: PromptPermissionDetails,
203
+ log: AuthorizerLog,
204
+ trail: { guidance: GuidanceSelection },
205
+ ): Promise<AuthorizerVerdict> {
206
+ const surface = gateSurfaceOf(details);
207
+ const fullCommand = extractFullCommandContext(details.payload);
208
+
209
+ const settings = deps.getSettings();
210
+ if (!settings) {
211
+ log.review(DECISION_EVENT, {
212
+ ...baseEntry(details, surface ?? null, null),
213
+ modelCalled: false,
214
+ latencyMs: null,
215
+ verdict: "defer",
216
+ deferReason: "no-config",
217
+ ...contextFields(false, fullCommand),
218
+ ...guidanceFields(EMPTY_GUIDANCE),
219
+ });
220
+ report(deps, { verdict: "defer", deferReason: "no-config" });
221
+ return { kind: "defer" };
222
+ }
223
+
224
+ if (surface === undefined || isExcludedSurface(surface)) {
225
+ log.debug(SHORT_CIRCUIT_EVENT, {
226
+ judge: JUDGE_TAG,
227
+ requestId: details.requestId,
228
+ surface: surface ?? null,
229
+ reason: surface === undefined ? "undeterminable-surface" : "excluded-surface",
230
+ });
231
+ return { kind: "defer" };
232
+ }
233
+
234
+ const policy = policyOf(settings);
235
+ const { quickJudge } = settings;
236
+ const pairId =
237
+ quickJudge.provider !== undefined && quickJudge.model !== undefined
238
+ ? `${quickJudge.provider}/${quickJudge.model}`
239
+ : null;
240
+ const preModel = (outcome: LinkOutcome, deferReason: string): AuthorizerVerdict =>
241
+ record(deps, log, details, surface, policy, outcome, {
242
+ modelId: pairId,
243
+ modelCalled: false,
244
+ latencyMs: null,
245
+ deferReason,
246
+ fullCommand,
247
+ contextIncluded: false,
248
+ guidance: EMPTY_GUIDANCE,
249
+ });
250
+
251
+ if (fullCommand !== null && fullCommand.bytes > settings.contextBudgetBytes) {
252
+ return preModel({ kind: "over-budget" }, "context-over-budget");
253
+ }
254
+
255
+ if (breaker.isOpen()) {
256
+ return preModel({ kind: "failure", failure: "breaker-open" }, "breaker-open");
257
+ }
258
+
259
+ const registry = deps.getRegistry();
260
+ const model =
261
+ quickJudge.provider !== undefined && quickJudge.model !== undefined
262
+ ? registry?.findOfType("classifier", quickJudge.provider, quickJudge.model)
263
+ : undefined;
264
+ if (!registry || !model) {
265
+ return preModel({ kind: "failure", failure: "model-unresolved" }, "model-unresolved");
266
+ }
267
+
268
+ // Read from disk for every judged ask so an edit takes effect on the next
269
+ // one, and only now so the short-circuits above never touch the disk.
270
+ let guidance: GuidanceSelection | undefined;
271
+ if (quickJudge.guidance) {
272
+ try {
273
+ guidance = deps.getGuidance?.() ?? EMPTY_GUIDANCE;
274
+ trail.guidance = guidance;
275
+ } catch {
276
+ return preModel(
277
+ { kind: "failure", failure: "guidance-load-failed" },
278
+ "guidance-load-failed",
279
+ );
280
+ }
281
+ }
282
+
283
+ const userIntent = userIntentFor(deps.getUserIntent, details);
284
+ const context = buildSystemOneContext({
285
+ details,
286
+ surface,
287
+ cwd: deps.getCwd(),
288
+ fullCommand,
289
+ contextBudgetBytes: settings.contextBudgetBytes,
290
+ ...(guidance === undefined ? {} : { guidance: guidance.included }),
291
+ ...(userIntent === undefined ? {} : { userIntent }),
292
+ });
293
+ const startedAt = Date.now();
294
+ const result = await classifyWithin(registry, model, context, quickJudge.timeoutMs);
295
+ const latencyMs = Date.now() - startedAt;
296
+ if (result === "timeout" || result === "threw" || result.stopReason !== "stop") {
297
+ breaker.recordFailure(log, details.requestId);
298
+ } else {
299
+ breaker.recordSuccess(log, details.requestId);
300
+ }
301
+
302
+ const outcome: LinkOutcome =
303
+ result === "timeout"
304
+ ? { kind: "failure", failure: "timeout" }
305
+ : result === "threw"
306
+ ? { kind: "failure", failure: "call-failed" }
307
+ : mapSystemOneResult(result, quickJudge, userIntent !== undefined);
308
+ const answers =
309
+ typeof result === "object" && result.stopReason === "stop"
310
+ ? summarizeAnswers(result.answers)
311
+ : undefined;
312
+ return record(deps, log, details, surface, policy, outcome, {
313
+ modelId: `${model.provider}/${model.id}`,
314
+ modelCalled: true,
315
+ latencyMs,
316
+ deferReason: undefined,
317
+ fullCommand,
318
+ contextIncluded: fullCommand !== null,
319
+ guidance: guidance ?? EMPTY_GUIDANCE,
320
+ answers,
321
+ });
322
+ }
323
+
324
+ /**
325
+ * Run `classify` under an abort signal that fires at `timeoutMs`. Resolves
326
+ * `"timeout"` at the deadline even when the call never settles, and
327
+ * `"threw"` when the call rejects.
328
+ */
329
+ async function classifyWithin(
330
+ registry: QuickJudgeRegistryLike,
331
+ model: ClassifierModel<ClassifierApi>,
332
+ context: ClassifierContext,
333
+ timeoutMs: number,
334
+ ): Promise<ClassifierResult | "timeout" | "threw"> {
335
+ const controller = new AbortController();
336
+ let timer: ReturnType<typeof setTimeout> | undefined;
337
+ const deadline = new Promise<"timeout">((resolve) => {
338
+ timer = setTimeout(() => {
339
+ controller.abort();
340
+ resolve("timeout");
341
+ }, timeoutMs);
342
+ });
343
+ const call = registry
344
+ .classify(model, context, { signal: controller.signal })
345
+ .then(
346
+ (result) => (controller.signal.aborted ? ("timeout" as const) : result),
347
+ () => (controller.signal.aborted ? ("timeout" as const) : ("threw" as const)),
348
+ );
349
+ try {
350
+ return await Promise.race([call, deadline]);
351
+ } finally {
352
+ clearTimeout(timer);
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Per-question answers for the log: a bool's probability, a choice's
358
+ * `[option, probability]` pairs highest first. The pairs keep option ids out
359
+ * of the JSON keys: the permission log masks any value whose key looks like
360
+ * a credential name, which would hide `credential_access`.
361
+ */
362
+ function summarizeAnswers(
363
+ answers: Record<string, ClassifierAnswer>,
364
+ ): Record<string, JsonValue> | undefined {
365
+ const entries = Object.entries(answers);
366
+ if (entries.length === 0) {
367
+ return undefined;
368
+ }
369
+ return Object.fromEntries(
370
+ entries.map(([id, answer]) => {
371
+ switch (answer.type) {
372
+ case "bool":
373
+ return [id, answer.probability];
374
+ case "choice":
375
+ return [
376
+ id,
377
+ Object.entries(answer.probabilities).sort((left, right) => right[1] - left[1]),
378
+ ];
379
+ case "score":
380
+ return [id, answer.score];
381
+ }
382
+ }),
383
+ );
384
+ }
385
+
386
+ /**
387
+ * Apply the policy to an outcome, write the decision entry, report health,
388
+ * and return the verdict. The recorded reason is the given one, else the
389
+ * reason the outcome implies.
390
+ */
391
+ function record(
392
+ deps: QuickJudgeDeps,
393
+ log: AuthorizerLog,
394
+ details: PromptPermissionDetails,
395
+ surface: string,
396
+ policy: VerdictPolicy,
397
+ outcome: LinkOutcome,
398
+ facts: {
399
+ modelId: string | null;
400
+ modelCalled: boolean;
401
+ latencyMs: number | null;
402
+ deferReason: string | undefined;
403
+ fullCommand: FullCommandContext | null;
404
+ contextIncluded: boolean;
405
+ guidance: GuidanceSelection;
406
+ answers?: Record<string, JsonValue>;
407
+ },
408
+ ): AuthorizerVerdict {
409
+ const verdict = applyVerdictPolicy(outcome, policy);
410
+ const reason = facts.deferReason ?? recordedReason(outcome, verdict);
411
+ log.review(DECISION_EVENT, {
412
+ ...baseEntry(details, surface, facts.modelId),
413
+ modelCalled: facts.modelCalled,
414
+ latencyMs: facts.latencyMs,
415
+ verdict: verdict.kind,
416
+ deferReason: reason,
417
+ ...contextFields(facts.contextIncluded, facts.fullCommand),
418
+ ...guidanceFields(facts.guidance),
419
+ ...(facts.answers === undefined ? {} : { answers: facts.answers }),
420
+ });
421
+ report(deps, healthOf(outcome, reason));
422
+ return verdict;
423
+ }
424
+
425
+ function recordedReason(outcome: LinkOutcome, verdict: AuthorizerVerdict): string | null {
426
+ switch (outcome.kind) {
427
+ case "allow":
428
+ return null;
429
+ case "deny":
430
+ return verdict.kind === "defer" ? DENY_CAPPED_REASON : null;
431
+ case "uncertain":
432
+ return UNCERTAIN_REASON;
433
+ case "over-budget":
434
+ return "context-over-budget";
435
+ case "failure":
436
+ return outcome.failure;
437
+ }
438
+ }
439
+
440
+ function baseEntry(
441
+ details: PromptPermissionDetails,
442
+ surface: string | null,
443
+ modelId: string | null,
444
+ ) {
445
+ return {
446
+ judge: JUDGE_TAG,
447
+ requestId: details.requestId,
448
+ surface,
449
+ value: details.payload?.request?.value ?? null,
450
+ modelId,
451
+ };
452
+ }