pi-permission-classifier 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,441 @@
1
+ /**
2
+ * The auto-classifier reviewer: the `Authorizer` chain link this package
3
+ * registers as `"classifier"`.
4
+ *
5
+ * The decision runs top to bottom, deferring at the first miss so the cheap
6
+ * gates short-circuit before any model call:
7
+ * 1. a config is loaded (else defer, recorded),
8
+ * 2. the gate-authoritative surface is determinable and outside the `path`
9
+ * and `external_directory` families — the bare name or any directional
10
+ * member such as `path_read` or `external_directory_write` (else defer —
11
+ * the engine caps any allow on those families anyway, so the classifier
12
+ * never attempts them); every other surface, whatever its name, is
13
+ * judged,
14
+ * 3. the extracted full-command context fits `contextBudgetBytes` (else
15
+ * defer, recorded — over-budget context is never rendered),
16
+ * 4. the judge model and its auth resolve (else defer, recorded),
17
+ * 5. the guidance seam selects the operator and trusted-project guidance
18
+ * files for this ask (a throw defers, recorded — no model call),
19
+ * 6. the model reviews the ask facts plus guidance and its verdict is
20
+ * returned uncapped.
21
+ *
22
+ * Every failure path defers — more prompting, never less (ADR 0007
23
+ * invariant). Each reviewed ask writes exactly one `classifier.decision`
24
+ * review entry; raw model replies and the cheap short-circuits go to the
25
+ * debug log.
26
+ */
27
+
28
+ import type { Model } from "@earendil-works/pi-ai";
29
+ import type {
30
+ Authorizer,
31
+ AuthorizerLog,
32
+ AuthorizerVerdict,
33
+ PromptPermissionDetails,
34
+ } from "@gotgenes/pi-permission-system";
35
+
36
+ import { CircuitBreaker } from "./breaker";
37
+ import type { ClassifierConfig } from "./config-schema";
38
+ import { extractFullCommandContext, type FullCommandContext } from "./context";
39
+ import type { GuidanceSelection } from "./guidance";
40
+ import type { HealthOutcome } from "./health";
41
+ import { type CompleteFn, reviewAsk } from "./model-review";
42
+
43
+ /**
44
+ * Surface families the engine caps to defer; the classifier never even asks.
45
+ * A family covers its bare name and every `<name>_*` member, the shape the
46
+ * engine's delegation envelope uses (`path_read`, `path_write`,
47
+ * `external_directory_read`, `external_directory_write`); an unknown
48
+ * member is excluded too, which only ever defers.
49
+ */
50
+ const EXCLUDED_SURFACE_FAMILIES = ["path", "external_directory"] as const;
51
+
52
+ /** Whether `surface` is the bare name or a directional member of an excluded family. */
53
+ function isExcludedSurface(surface: string): boolean {
54
+ return EXCLUDED_SURFACE_FAMILIES.some(
55
+ (family) => surface === family || surface.startsWith(`${family}_`),
56
+ );
57
+ }
58
+
59
+ /** Review-log event: one positive decision record per reviewed ask. */
60
+ const DECISION_EVENT = "classifier.decision";
61
+ /** Debug-log event: a cheap short-circuit before the model stage. */
62
+ const SHORT_CIRCUIT_EVENT = "classifier.short_circuit";
63
+ /** Debug-log event: the raw model reply, gated behind `debugLog`. */
64
+ const MODEL_REPLY_EVENT = "classifier.model_reply";
65
+
66
+ /** A defer decided before the model call, still recorded positively. */
67
+ type PreModelDeferReason =
68
+ | "no-config"
69
+ | "model-unresolved"
70
+ | "auth-failed"
71
+ | "breaker-open"
72
+ | "context-over-budget"
73
+ | "guidance-load-failed";
74
+
75
+ /** Model-call outcomes that count against the circuit breaker. */
76
+ const BREAKER_FAILURE_REASONS = new Set(["timeout", "call-failed"]);
77
+
78
+ /**
79
+ * The auth resolved for a model call — structurally the `ResolvedRequestAuth`
80
+ * of the core `ModelRegistry`, redeclared here because that type is not
81
+ * re-exported from `@earendil-works/pi-coding-agent`.
82
+ */
83
+ export type ResolvedRequestAuth =
84
+ | {
85
+ ok: true;
86
+ apiKey?: string;
87
+ headers?: Record<string, string | null>;
88
+ baseUrl?: string;
89
+ env?: Record<string, string>;
90
+ }
91
+ | { ok: false; error: string };
92
+
93
+ /** The narrow model-registry projection the reviewer needs (ISP). */
94
+ export interface ModelRegistryLike {
95
+ find(provider: string, modelId: string): Model<any> | undefined;
96
+ getApiKeyAndHeaders(model: Model<any>): Promise<ResolvedRequestAuth>;
97
+ }
98
+
99
+ /** Collaborators for the reviewer, injected so the extension and tests wire them. */
100
+ export interface ClassifierReviewerDeps {
101
+ /** The loaded config, read live (absent until session config loads). */
102
+ getConfig: () => ClassifierConfig | undefined;
103
+ /** The session's active model, read live (tracks `model_select`). */
104
+ getSessionModel: () => Model<any> | undefined;
105
+ /** The session model registry, read live (captured at `session_start`). */
106
+ getRegistry: () => ModelRegistryLike | undefined;
107
+ /** The model-completion seam (production: `complete` from `@earendil-works/pi-ai`). */
108
+ complete: CompleteFn;
109
+ /** The shared circuit breaker; the reviewer makes its own when absent. */
110
+ breaker?: CircuitBreaker;
111
+ /**
112
+ * Guidance seam: called once per judged ask, right before the model stage,
113
+ * to load and select the guidance files for this ask (production: pi's
114
+ * context loader, the trust check, and the selection in src/guidance.ts).
115
+ * Absent means no guidance. A throw defers the ask (guidance-load-failed).
116
+ */
117
+ getGuidance?: () => GuidanceSelection;
118
+ /**
119
+ * Outcome seam: called once per `classifier.decision` entry with the
120
+ * verdict and defer reason, after the entry is logged. Never called for
121
+ * the surface short-circuits, which write no entry. The reviewer knows
122
+ * nothing about what listens; the extension folds it into session health.
123
+ */
124
+ onOutcome?: (outcome: HealthOutcome) => void;
125
+ }
126
+
127
+ /**
128
+ * Report an outcome through the seam, if any. A throwing listener is
129
+ * swallowed: health is observability, and it must never change a verdict or
130
+ * add a second decision entry.
131
+ */
132
+ function report(deps: ClassifierReviewerDeps, outcome: HealthOutcome): void {
133
+ try {
134
+ deps.onOutcome?.(outcome);
135
+ } catch {
136
+ // The listener failed; the decision stands as logged.
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Build the `authorize` callback registered on the chain. The `query`
142
+ * argument is unused — the classifier decides from the ask facts and the
143
+ * model, not from an engine re-query. The `log` argument is the injected
144
+ * review-log seam the decision trail records to.
145
+ */
146
+ export function createClassifierReviewer(
147
+ deps: ClassifierReviewerDeps,
148
+ ): Authorizer["authorize"] {
149
+ const breaker = deps.breaker ?? new CircuitBreaker();
150
+
151
+ return async (details, _query, log) => {
152
+ // What the guidance stage selected, so the backstop entry below can say
153
+ // what the judge actually saw even when a later stage threw.
154
+ const trail = { guidance: EMPTY_GUIDANCE };
155
+ try {
156
+ return await decide(deps, breaker, details, log, trail);
157
+ } catch {
158
+ // The unconditional backstop: whatever threw — an injected seam
159
+ // rejecting instead of returning ok:false, a malformed details bag,
160
+ // even the log itself — the ask defers (more prompting, never less).
161
+ try {
162
+ const context = extractFullCommandContext(details.payload);
163
+ log.review(DECISION_EVENT, {
164
+ requestId: details.requestId,
165
+ surface: gateSurfaceOf(details) ?? null,
166
+ value: details.payload?.request?.value ?? null,
167
+ modelCalled: false,
168
+ modelId: null,
169
+ latencyMs: null,
170
+ verdict: "defer",
171
+ deferReason: "internal-error",
172
+ ...contextFields(false, context),
173
+ ...guidanceFields(trail.guidance),
174
+ });
175
+ } catch {
176
+ // The log failed too; there is nothing left to record on.
177
+ }
178
+ report(deps, { verdict: "defer", deferReason: "internal-error" });
179
+ return { kind: "defer" };
180
+ }
181
+ };
182
+ }
183
+
184
+ async function decide(
185
+ deps: ClassifierReviewerDeps,
186
+ breaker: CircuitBreaker,
187
+ details: PromptPermissionDetails,
188
+ log: AuthorizerLog,
189
+ trail: { guidance: GuidanceSelection },
190
+ ): Promise<AuthorizerVerdict> {
191
+ const { requestId } = details;
192
+ const surface = gateSurfaceOf(details);
193
+ const value = details.payload.request.value;
194
+ const context = extractFullCommandContext(details.payload);
195
+
196
+ const config = deps.getConfig();
197
+ if (!config) {
198
+ return deferWith(deps, log, {
199
+ requestId,
200
+ surface: surface ?? null,
201
+ value,
202
+ modelId: null,
203
+ deferReason: "no-config",
204
+ context,
205
+ });
206
+ }
207
+
208
+ if (surface === undefined) {
209
+ log.debug(SHORT_CIRCUIT_EVENT, {
210
+ requestId,
211
+ reason: "undeterminable-surface",
212
+ });
213
+ return { kind: "defer" };
214
+ }
215
+ if (isExcludedSurface(surface)) {
216
+ log.debug(SHORT_CIRCUIT_EVENT, {
217
+ requestId,
218
+ surface,
219
+ reason: "excluded-surface",
220
+ });
221
+ return { kind: "defer" };
222
+ }
223
+ // The budget gate: an over-budget full command is never rendered,
224
+ // not even truncated — the ask defers to the human with the measurements on
225
+ // record. Decided before the breaker and model stages: it is a property of
226
+ // the ask and the config alone.
227
+ if (context !== null && context.bytes > config.contextBudgetBytes) {
228
+ return deferWith(deps, log, {
229
+ requestId,
230
+ surface,
231
+ value,
232
+ modelId: null,
233
+ deferReason: "context-over-budget",
234
+ context,
235
+ });
236
+ }
237
+
238
+ if (breaker.isOpen()) {
239
+ return deferWith(deps, log, {
240
+ requestId,
241
+ surface,
242
+ value,
243
+ modelId: null,
244
+ deferReason: "breaker-open",
245
+ context,
246
+ });
247
+ }
248
+
249
+ const registry = deps.getRegistry();
250
+ const model =
251
+ config.provider !== undefined && config.model !== undefined
252
+ ? registry?.find(config.provider, config.model)
253
+ : deps.getSessionModel();
254
+ if (!registry || !model) {
255
+ return deferWith(deps, log, {
256
+ requestId,
257
+ surface,
258
+ value,
259
+ modelId:
260
+ config.provider !== undefined && config.model !== undefined
261
+ ? `${config.provider}/${config.model}`
262
+ : null,
263
+ deferReason: "model-unresolved",
264
+ context,
265
+ });
266
+ }
267
+ const modelId = `${model.provider}/${model.id}`;
268
+
269
+ const auth = await registry.getApiKeyAndHeaders(model);
270
+ if (!auth.ok) {
271
+ return deferWith(deps, log, {
272
+ requestId,
273
+ surface,
274
+ value,
275
+ modelId,
276
+ deferReason: "auth-failed",
277
+ context,
278
+ });
279
+ }
280
+
281
+ // The guidance stage: read from disk for every judged ask so an edit takes
282
+ // effect on the next ask, and read only now so the cheap short-circuits
283
+ // above never touch the filesystem. A loader failure is a failure path:
284
+ // defer, never judge without the guidance the operator expects.
285
+ let guidance: GuidanceSelection;
286
+ try {
287
+ guidance = deps.getGuidance?.() ?? EMPTY_GUIDANCE;
288
+ trail.guidance = guidance;
289
+ } catch {
290
+ return deferWith(deps, log, {
291
+ requestId,
292
+ surface,
293
+ value,
294
+ modelId,
295
+ deferReason: "guidance-load-failed",
296
+ context,
297
+ });
298
+ }
299
+
300
+ const outcome = await reviewAsk({
301
+ details,
302
+ config,
303
+ model,
304
+ complete: deps.complete,
305
+ apiKey: auth.apiKey,
306
+ headers: auth.headers,
307
+ context,
308
+ guidance: guidance.included,
309
+ });
310
+ if (
311
+ outcome.deferReason !== undefined &&
312
+ BREAKER_FAILURE_REASONS.has(outcome.deferReason)
313
+ ) {
314
+ breaker.recordFailure(log, requestId);
315
+ } else {
316
+ breaker.recordSuccess(log, requestId);
317
+ }
318
+ if (outcome.rawReply !== undefined) {
319
+ log.debug(MODEL_REPLY_EVENT, {
320
+ requestId,
321
+ modelId,
322
+ rawReply: outcome.rawReply,
323
+ });
324
+ }
325
+ // One reason for both the decision entry and the health seam, so the two
326
+ // can never disagree. Set on every defer model-review produces; the
327
+ // fallback only guards the type.
328
+ const deferReason =
329
+ outcome.verdict.kind === "defer"
330
+ ? (outcome.deferReason ?? "unrecognized-verdict")
331
+ : null;
332
+ log.review(DECISION_EVENT, {
333
+ requestId,
334
+ surface,
335
+ value,
336
+ modelCalled: true,
337
+ modelId,
338
+ latencyMs: outcome.latencyMs,
339
+ verdict: outcome.verdict.kind,
340
+ deferReason,
341
+ ...contextFields(context !== null, context),
342
+ ...guidanceFields(guidance),
343
+ });
344
+ report(
345
+ deps,
346
+ outcome.verdict.kind === "defer"
347
+ ? { verdict: "defer", deferReason: deferReason ?? "unrecognized-verdict" }
348
+ : { verdict: outcome.verdict.kind },
349
+ );
350
+ // Returned uncapped: the engine envelope, not this link, owns any
351
+ // downgrade.
352
+ return outcome.verdict;
353
+ }
354
+
355
+ /**
356
+ * Record a pre-model defer as a positive `classifier.decision` entry and
357
+ * return the defer verdict — so a resolution failure leaves evidence on
358
+ * record, not a silent absence.
359
+ */
360
+ function deferWith(
361
+ deps: ClassifierReviewerDeps,
362
+ log: AuthorizerLog,
363
+ entry: {
364
+ requestId: string;
365
+ surface: string | null;
366
+ value: string;
367
+ modelId: string | null;
368
+ deferReason: PreModelDeferReason;
369
+ context: FullCommandContext | null;
370
+ },
371
+ ): AuthorizerVerdict {
372
+ log.review(DECISION_EVENT, {
373
+ requestId: entry.requestId,
374
+ surface: entry.surface,
375
+ value: entry.value,
376
+ modelCalled: false,
377
+ modelId: entry.modelId,
378
+ latencyMs: null,
379
+ verdict: "defer",
380
+ deferReason: entry.deferReason,
381
+ ...contextFields(false, entry.context),
382
+ ...guidanceFields(EMPTY_GUIDANCE),
383
+ });
384
+ report(deps, { verdict: "defer", deferReason: entry.deferReason });
385
+ return { kind: "defer" };
386
+ }
387
+
388
+ /**
389
+ * The three context fields every decision entry carries. Only the
390
+ * measurements are logged — bytes and a hash prefix — never the text, so the
391
+ * review log stays free of command content beyond the gated value itself.
392
+ */
393
+ function contextFields(
394
+ included: boolean,
395
+ context: FullCommandContext | null,
396
+ ): {
397
+ contextIncluded: boolean;
398
+ contextBytes: number | null;
399
+ contextHash: string | null;
400
+ } {
401
+ return {
402
+ contextIncluded: included,
403
+ contextBytes: context?.bytes ?? null,
404
+ contextHash: context?.hash12 ?? null,
405
+ };
406
+ }
407
+
408
+ /** No guidance: the render before the seam runs, and after it fails. */
409
+ const EMPTY_GUIDANCE: GuidanceSelection = { included: [], dropped: [] };
410
+
411
+ /**
412
+ * The two guidance lists every decision entry carries. Included files are
413
+ * logged by path, bytes, and hash prefix — never their content — and dropped
414
+ * files by path, bytes, and the rule that excluded them.
415
+ */
416
+ function guidanceFields(guidance: GuidanceSelection): {
417
+ guidanceIncluded: { path: string; bytes: number; hash12: string }[];
418
+ guidanceDropped: { path: string; bytes: number; reason: string }[];
419
+ } {
420
+ return {
421
+ guidanceIncluded: guidance.included.map(({ path, bytes, hash12 }) => ({
422
+ path,
423
+ bytes,
424
+ hash12,
425
+ })),
426
+ guidanceDropped: guidance.dropped.map(({ path, bytes, reason }) => ({
427
+ path,
428
+ bytes,
429
+ reason,
430
+ })),
431
+ };
432
+ }
433
+
434
+ /**
435
+ * The gate-authoritative surface: the raising gate's access-intent surface
436
+ * when present, else the display surface; `undefined` when neither is set
437
+ * (undeterminable — defer without a model call).
438
+ */
439
+ function gateSurfaceOf(details: PromptPermissionDetails): string | undefined {
440
+ return details.accessIntent?.surface ?? details.surface ?? undefined;
441
+ }