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.
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "pi-permission-classifier",
3
+ "version": "0.5.0",
4
+ "description": "Auto-classifier Authorizer chain link for pi-permission-system: a light model reviews each ask and returns allow, deny, or defer",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "files": [
8
+ "src",
9
+ "config/config.example.json",
10
+ "README.md",
11
+ "CHANGELOG.md"
12
+ ],
13
+ "imports": {
14
+ "#src/*": "./src/*",
15
+ "#test/*": "./test/*"
16
+ },
17
+ "keywords": [
18
+ "pi-package",
19
+ "pi",
20
+ "pi-extension",
21
+ "pi-coding-agent",
22
+ "permissions",
23
+ "authorizer",
24
+ "classifier",
25
+ "policy",
26
+ "access-control"
27
+ ],
28
+ "engines": {
29
+ "node": ">=22"
30
+ },
31
+ "pi": {
32
+ "extensions": [
33
+ "./src/index.ts"
34
+ ]
35
+ },
36
+ "scripts": {
37
+ "check": "tsc --noEmit",
38
+ "test": "vitest run",
39
+ "test:watch": "vitest"
40
+ },
41
+ "dependencies": {
42
+ "zod": "4.4.3"
43
+ },
44
+ "peerDependencies": {
45
+ "@earendil-works/pi-coding-agent": ">=0.84.3",
46
+ "@gotgenes/pi-permission-system": ">=27.0.0"
47
+ },
48
+ "devDependencies": {
49
+ "@earendil-works/pi-ai": "0.84.3",
50
+ "@earendil-works/pi-coding-agent": "0.84.3",
51
+ "@gotgenes/pi-permission-system": "file:../pi-env/gh/pi-packages/packages/pi-permission-system",
52
+ "@types/node": "24.13.3",
53
+ "typescript": "6.0.3",
54
+ "vitest": "4.1.11"
55
+ }
56
+ }
package/src/breaker.ts ADDED
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Circuit breaker for the judge model call: 3 consecutive failures
3
+ * or timeouts open it for a 60-second cooldown, during which asks defer
4
+ * instantly with no model call. After the cooldown the next ask tries the
5
+ * model again (half-open); a success closes the breaker and resets the
6
+ * counter. Open and close are recorded to the review log, on the log of the
7
+ * ask that crossed the transition.
8
+ *
9
+ * Failing open (deferring) matches the package invariant: a broken judge
10
+ * means more prompting, never less — and no per-ask timeout pile-up while
11
+ * the model is down.
12
+ */
13
+
14
+ import type { AuthorizerLog } from "@gotgenes/pi-permission-system";
15
+
16
+ /** Consecutive failures that open the breaker. */
17
+ export const BREAKER_FAILURE_THRESHOLD = 3;
18
+
19
+ /** How long an open breaker short-circuits asks, in milliseconds. */
20
+ export const BREAKER_COOLDOWN_MS = 60_000;
21
+
22
+ /** Review-log event: the breaker opened (threshold reached). */
23
+ const BREAKER_OPEN_EVENT = "classifier.breaker_open";
24
+ /** Review-log event: the breaker closed (post-cooldown success). */
25
+ const BREAKER_CLOSE_EVENT = "classifier.breaker_close";
26
+
27
+ export class CircuitBreaker {
28
+ private consecutiveFailures = 0;
29
+ private openedAt: number | undefined;
30
+
31
+ /**
32
+ * Milliseconds of cooldown left: 0 while closed or once the cooldown has
33
+ * elapsed, else the time until the next ask may try the model again.
34
+ */
35
+ remainingMs(): number {
36
+ if (this.openedAt === undefined) {
37
+ return 0;
38
+ }
39
+ return Math.max(0, BREAKER_COOLDOWN_MS - (Date.now() - this.openedAt));
40
+ }
41
+
42
+ /** Whether asks should short-circuit right now (open and cooling down). */
43
+ isOpen(): boolean {
44
+ return this.remainingMs() > 0;
45
+ }
46
+
47
+ /**
48
+ * Record a model-call failure or timeout. Opens (and logs) when the
49
+ * consecutive count reaches the threshold; a failure on the post-cooldown
50
+ * retry restarts the cooldown window.
51
+ */
52
+ recordFailure(log: AuthorizerLog, requestId: string): void {
53
+ this.consecutiveFailures += 1;
54
+ if (this.consecutiveFailures < BREAKER_FAILURE_THRESHOLD) {
55
+ return;
56
+ }
57
+ const reopening = this.openedAt !== undefined;
58
+ this.openedAt = Date.now();
59
+ if (!reopening) {
60
+ log.review(BREAKER_OPEN_EVENT, {
61
+ requestId,
62
+ consecutiveFailures: this.consecutiveFailures,
63
+ cooldownMs: BREAKER_COOLDOWN_MS,
64
+ });
65
+ }
66
+ }
67
+
68
+ /** Record a completed model call; closes (and logs) an open breaker. */
69
+ recordSuccess(log: AuthorizerLog, requestId: string): void {
70
+ const wasOpen = this.openedAt !== undefined;
71
+ this.consecutiveFailures = 0;
72
+ this.openedAt = undefined;
73
+ if (wasOpen) {
74
+ log.review(BREAKER_CLOSE_EVENT, { requestId });
75
+ }
76
+ }
77
+ }
package/src/command.ts ADDED
@@ -0,0 +1,403 @@
1
+ /**
2
+ * The `/permission-model` command: choose the judge model for the permission
3
+ * classifier.
4
+ *
5
+ * Forms:
6
+ * - `<provider>/<id>`: validate through the model registry, persist the
7
+ * pair to the global config, reload, and apply live for the next ask.
8
+ * - `session`: remove the pair from the global config so the session's
9
+ * active model judges again.
10
+ * - no argument in the TUI: mount pi's own searchable model selector
11
+ * through `ctx.ui.custom`, built from the registry's runtime (reached
12
+ * behind a shape check, since it is a private field), the session's
13
+ * scoped models, and the current judge preselected, with no
14
+ * set-as-default callback so the operator's default model is never
15
+ * touched. A selection applies exactly like the typed form; a cancel
16
+ * changes nothing. When the runtime does not have the expected shape (a pi
17
+ * update moved it), the form degrades to `ctx.ui.select` over
18
+ * `provider/id` labels from `getAvailable()` with a warning.
19
+ * - no argument outside the TUI: print the current judge and the usage
20
+ * line (pi's `ctx.ui.custom` returns nothing in rpc/json/print modes).
21
+ *
22
+ * Argument completion offers `provider/id` labels from the registry's
23
+ * available models whose label starts with the typed prefix, plus the
24
+ * literal `session` when it matches.
25
+ *
26
+ * Every write form refuses when the global config file is absent or there is
27
+ * no valid merged config - no config file found, or the files found failed
28
+ * validation: nothing is written and the operator gets the setup hint naming
29
+ * the global path. The precondition is the config, not registration: with a
30
+ * valid config and a link that never registers a write still succeeds, and the
31
+ * new judge applies once the link does. Writes always target the global file;
32
+ * when the project layer sets its own pair the operator is warned that it
33
+ * shadows the choice.
34
+ *
35
+ * Choosing a judge never touches pi's session model or the operator's default
36
+ * model. This module performs no filesystem or network access of its own:
37
+ * persistence and reload go through the injected dependencies, which the
38
+ * extension wires to the config loader. Every failure path leaves the
39
+ * in-memory config as it was, so a bad pick can never widen a verdict.
40
+ */
41
+
42
+ import type { Model } from "@earendil-works/pi-ai";
43
+ import {
44
+ type ExtensionAPI,
45
+ type ExtensionUIContext,
46
+ ModelSelectorComponent,
47
+ type ModelRuntime,
48
+ type ScopedModel,
49
+ } from "@earendil-works/pi-coding-agent";
50
+
51
+ import { formatConfigIssue, type LoadConfigResult } from "./config-loader";
52
+ import type { ClassifierConfig } from "./config-schema";
53
+ import {
54
+ formatJudgeStatus,
55
+ type JudgePair,
56
+ parseJudgePair,
57
+ resolveJudge,
58
+ } from "./judge";
59
+
60
+ /** The slash command name (`/permission-model`). */
61
+ export const COMMAND_NAME = "permission-model";
62
+
63
+ const SESSION_FORM = "session";
64
+
65
+ const USAGE = `/${COMMAND_NAME} <provider>/<id> | ${SESSION_FORM}`;
66
+
67
+ type CommandOptions = Parameters<ExtensionAPI["registerCommand"]>[1];
68
+ /** pi's completion result, restricted to the synchronous half this command returns. */
69
+ type ArgumentCompletions = Exclude<
70
+ ReturnType<NonNullable<CommandOptions["getArgumentCompletions"]>>,
71
+ Promise<unknown>
72
+ >;
73
+
74
+ type PickerFactory = Parameters<ExtensionUIContext["custom"]>[0];
75
+ /** pi's TUI handle, as `ctx.ui.custom` hands it to the factory. */
76
+ export type PickerTui = Parameters<PickerFactory>[0];
77
+ /** What the factory returns: a component, optionally disposable. */
78
+ export type PickerComponent = ReturnType<PickerFactory>;
79
+
80
+ /** The narrow registry projection the command needs. */
81
+ export interface CommandRegistryLike {
82
+ find(provider: string, modelId: string): Model<any> | undefined;
83
+ hasConfiguredAuth(model: Model<any>): boolean;
84
+ getAvailable(): Model<any>[];
85
+ }
86
+
87
+ /**
88
+ * The slice of pi's command context the handler reads. `ui` is pi's own type
89
+ * projected with `Pick`, so a pi signature change to `notify`, `select` or
90
+ * `custom` is a compile error here instead of a runtime failure in the picker
91
+ * (a hand copy would be compared bivariantly and drift silently).
92
+ */
93
+ export interface CommandContextLike {
94
+ cwd: string;
95
+ mode: "tui" | "rpc" | "json" | "print";
96
+ model: Model<any> | undefined;
97
+ modelRegistry: CommandRegistryLike;
98
+ scopedModels: readonly ScopedModel[];
99
+ ui: Pick<ExtensionUIContext, "notify" | "select" | "custom">;
100
+ }
101
+
102
+ /** Everything the picker component is built from. */
103
+ export interface PickerRequest {
104
+ tui: PickerTui;
105
+ /** The current judge, preselected in the list; `undefined` when unresolved. */
106
+ currentModel: Model<any> | undefined;
107
+ runtime: ModelRuntime;
108
+ scopedModels: readonly ScopedModel[];
109
+ onSelect(model: Model<any>): void;
110
+ onCancel(): void;
111
+ }
112
+
113
+ /** Builds the picker component; injectable so tests never mount a real TUI. */
114
+ export type PickerSeam = (request: PickerRequest) => PickerComponent;
115
+
116
+ /**
117
+ * The production picker: pi's own model selector, in its pi 0.84.3 form
118
+ * (tui, currentModel, modelRuntime, scopedModels, onSelect, onCancel; the
119
+ * trailing optional arguments are omitted). The optional set-as-default
120
+ * callback is deliberately not passed, so the selector has no way to rewrite
121
+ * the operator's default model.
122
+ */
123
+ export const buildModelSelector: PickerSeam = (request) =>
124
+ new ModelSelectorComponent(
125
+ request.tui,
126
+ request.currentModel,
127
+ request.runtime,
128
+ request.scopedModels,
129
+ request.onSelect,
130
+ request.onCancel,
131
+ );
132
+
133
+ /**
134
+ * The registry's runtime, reached behind a shape check: `runtime` is a
135
+ * private field of `ModelRegistry`, so a pi update that moves or reshapes it
136
+ * yields `undefined` here (and a degraded picker) instead of a crash.
137
+ */
138
+ function runtimeOf(registry: CommandRegistryLike): ModelRuntime | undefined {
139
+ const runtime = (registry as { runtime?: unknown }).runtime;
140
+ if (
141
+ typeof runtime === "object" &&
142
+ runtime !== null &&
143
+ typeof (runtime as { getAvailableSnapshot?: unknown })
144
+ .getAvailableSnapshot === "function"
145
+ ) {
146
+ return runtime as ModelRuntime;
147
+ }
148
+ return undefined;
149
+ }
150
+
151
+ /** Seams the extension supplies; none of them are called on a rejected pick. */
152
+ export interface CommandDependencies {
153
+ /** The merged config the reviewer judges with; `undefined` when invalid or absent. */
154
+ getConfig(): ClassifierConfig | undefined;
155
+ /** The active session-only flag override, if any. */
156
+ getOverride(): JudgePair | undefined;
157
+ /** The session's model registry (captured at `session_start`), for completion. */
158
+ getRegistry(): CommandRegistryLike | undefined;
159
+ /** Whether the global config file exists (the precondition for a write). */
160
+ globalConfigExists(): boolean;
161
+ /** The global config path, for operator hints. */
162
+ globalConfigPath(): string;
163
+ /** The project config path for `cwd`, for the shadow warning. */
164
+ projectConfigPath(cwd: string): string;
165
+ /** Persist the pair to the global config (both `undefined` removes it). */
166
+ writeJudge(provider: string | undefined, model: string | undefined): void;
167
+ /** Reload the merged config from disk after a write. */
168
+ reload(cwd: string): LoadConfigResult;
169
+ /** Replace the live config, drop any flag override, refresh the status. */
170
+ apply(config: ClassifierConfig): void;
171
+ /** Builds the picker component; defaults to {@link buildModelSelector}. */
172
+ buildPicker?: PickerSeam;
173
+ }
174
+
175
+ /** What `registerCommand` receives, with the handler typed to the slice it reads. */
176
+ export interface PermissionModelCommand {
177
+ description: string;
178
+ getArgumentCompletions(prefix: string): ArgumentCompletions;
179
+ handler(args: string, ctx: CommandContextLike): Promise<void>;
180
+ }
181
+
182
+ export function createPermissionModelCommand(
183
+ deps: CommandDependencies,
184
+ ): PermissionModelCommand {
185
+ function setupHint(): string {
186
+ return `The permission classifier is not set up: create ${deps.globalConfigPath()} first.`;
187
+ }
188
+
189
+ /**
190
+ * Whether a write can proceed: a valid merged config must be live and the
191
+ * global file must exist. Otherwise notify the setup hint. Neither check is
192
+ * on registration.
193
+ */
194
+ function canWrite(ctx: CommandContextLike): boolean {
195
+ if (deps.getConfig() === undefined || !deps.globalConfigExists()) {
196
+ ctx.ui.notify(`${setupHint()} Nothing changed.`, "warning");
197
+ return false;
198
+ }
199
+ return true;
200
+ }
201
+
202
+ function describeIssues(issues: LoadConfigResult["issues"]): string {
203
+ if (issues.length === 0) {
204
+ return "no config file was found";
205
+ }
206
+ return issues.map(formatConfigIssue).join("; ");
207
+ }
208
+
209
+ /**
210
+ * Write the pair (or its removal), reload, apply, and report. Returns
211
+ * whether the new config went live.
212
+ */
213
+ function persist(
214
+ pair: JudgePair | undefined,
215
+ ctx: CommandContextLike,
216
+ ): boolean {
217
+ try {
218
+ deps.writeJudge(pair?.provider, pair?.model);
219
+ } catch (error) {
220
+ const message = error instanceof Error ? error.message : String(error);
221
+ ctx.ui.notify(
222
+ `Could not write ${deps.globalConfigPath()}: ${message}. Nothing changed.`,
223
+ "error",
224
+ );
225
+ return false;
226
+ }
227
+ const result = deps.reload(ctx.cwd);
228
+ if (result.config === undefined) {
229
+ // The write landed, but the merged global-plus-project config no
230
+ // longer validates. Applying `undefined` would leave a registered link
231
+ // deferring every ask behind a footer that says otherwise, so keep the
232
+ // previous config live and tell the operator what to fix.
233
+ ctx.ui.notify(
234
+ `Saved to ${deps.globalConfigPath()}, but the merged config is now invalid (${describeIssues(result.issues)}). The previous judge stays active for this session; fix the config and restart.`,
235
+ "error",
236
+ );
237
+ return false;
238
+ }
239
+ deps.apply(result.config);
240
+ ctx.ui.notify(
241
+ pair
242
+ ? `Permission judge set to ${pair.provider}/${pair.model} (saved to the global config).`
243
+ : "Permission judge follows the session model (provider/model removed from the global config).",
244
+ "info",
245
+ );
246
+ if (result.issues.length > 0) {
247
+ ctx.ui.notify(
248
+ `Config issues after reload: ${describeIssues(result.issues)}.`,
249
+ "warning",
250
+ );
251
+ }
252
+ if (result.projectSetsJudge) {
253
+ ctx.ui.notify(
254
+ `${deps.projectConfigPath(ctx.cwd)} sets its own provider/model and shadows this choice in this project.`,
255
+ "warning",
256
+ );
257
+ }
258
+ return true;
259
+ }
260
+
261
+ const buildPicker = deps.buildPicker ?? buildModelSelector;
262
+
263
+ /** The judge the next ask would use. */
264
+ function currentJudge(ctx: CommandContextLike) {
265
+ return resolveJudge(
266
+ deps.getOverride(),
267
+ deps.getConfig(),
268
+ ctx.modelRegistry,
269
+ ctx.model,
270
+ );
271
+ }
272
+
273
+ function printJudge(ctx: CommandContextLike): void {
274
+ if (deps.getConfig() === undefined) {
275
+ ctx.ui.notify(setupHint(), "warning");
276
+ return;
277
+ }
278
+ ctx.ui.notify(
279
+ `Permission classifier ${formatJudgeStatus(currentJudge(ctx))}. Usage: ${USAGE}`,
280
+ "info",
281
+ );
282
+ }
283
+
284
+ /** Persist a registry model as the judge; warn when it has no auth. */
285
+ function applyModel(model: Model<any>, ctx: CommandContextLike): void {
286
+ const pair: JudgePair = { provider: model.provider, model: model.id };
287
+ const hasAuth = ctx.modelRegistry.hasConfiguredAuth(model);
288
+ if (persist(pair, ctx) && !hasAuth) {
289
+ ctx.ui.notify(
290
+ `No auth is configured for ${pair.provider}/${pair.model}; permission asks will defer to the prompt until it is.`,
291
+ "warning",
292
+ );
293
+ }
294
+ }
295
+
296
+ /** Resolve a `<provider>/<id>` pair through the registry and apply it. */
297
+ function applyPair(pair: JudgePair, ctx: CommandContextLike): void {
298
+ const model = ctx.modelRegistry.find(pair.provider, pair.model);
299
+ if (!model) {
300
+ ctx.ui.notify(
301
+ `Unknown model ${pair.provider}/${pair.model}: not in the model registry. Nothing changed.`,
302
+ "error",
303
+ );
304
+ return;
305
+ }
306
+ applyModel(model, ctx);
307
+ }
308
+
309
+ /** The degraded picker: a plain list of `provider/id` labels. */
310
+ async function pickFromList(ctx: CommandContextLike): Promise<void> {
311
+ const labels = ctx.modelRegistry
312
+ .getAvailable()
313
+ .map((model) => `${model.provider}/${model.id}`);
314
+ if (labels.length === 0) {
315
+ ctx.ui.notify(
316
+ "No models are available to pick from. Nothing changed.",
317
+ "warning",
318
+ );
319
+ return;
320
+ }
321
+ ctx.ui.notify(
322
+ "The model picker degraded to a plain list: this pi version does not expose the registry runtime the searchable selector needs.",
323
+ "warning",
324
+ );
325
+ const chosen = await ctx.ui.select("Permission judge model", labels);
326
+ // Labels are built as provider/id above, so the parse cannot fail.
327
+ const pair = chosen === undefined ? undefined : parseJudgePair(chosen);
328
+ if (pair) {
329
+ applyPair(pair, ctx);
330
+ }
331
+ }
332
+
333
+ /** The no-argument TUI form: mount the picker; apply a selection. */
334
+ async function pick(ctx: CommandContextLike): Promise<void> {
335
+ const runtime = runtimeOf(ctx.modelRegistry);
336
+ if (!runtime) {
337
+ await pickFromList(ctx);
338
+ return;
339
+ }
340
+ const currentModel = currentJudge(ctx).model;
341
+ await ctx.ui.custom<void>((tui, _theme, _keybindings, done) =>
342
+ buildPicker({
343
+ tui,
344
+ currentModel,
345
+ runtime,
346
+ scopedModels: ctx.scopedModels,
347
+ onSelect: (model) => {
348
+ done();
349
+ applyModel(model, ctx);
350
+ },
351
+ onCancel: () => done(),
352
+ }),
353
+ );
354
+ }
355
+
356
+ function getArgumentCompletions(prefix: string): ArgumentCompletions {
357
+ const registry = deps.getRegistry();
358
+ if (!registry) {
359
+ return null;
360
+ }
361
+ const wanted = prefix.trim().toLowerCase();
362
+ const labels = [
363
+ ...registry.getAvailable().map((model) => `${model.provider}/${model.id}`),
364
+ SESSION_FORM,
365
+ ];
366
+ const items = labels
367
+ .filter((label) => label.toLowerCase().startsWith(wanted))
368
+ .map((label) => ({ value: label, label }));
369
+ return items.length > 0 ? items : null;
370
+ }
371
+
372
+ async function handler(args: string, ctx: CommandContextLike): Promise<void> {
373
+ const text = args.trim();
374
+ if (text === "") {
375
+ if (ctx.mode !== "tui") {
376
+ printJudge(ctx);
377
+ } else if (canWrite(ctx)) {
378
+ await pick(ctx);
379
+ }
380
+ return;
381
+ }
382
+ if (text === SESSION_FORM) {
383
+ if (canWrite(ctx)) {
384
+ persist(undefined, ctx);
385
+ }
386
+ return;
387
+ }
388
+ const pair = parseJudgePair(text);
389
+ if (!pair) {
390
+ ctx.ui.notify(`Expected a model reference. Usage: ${USAGE}`, "error");
391
+ return;
392
+ }
393
+ if (canWrite(ctx)) {
394
+ applyPair(pair, ctx);
395
+ }
396
+ }
397
+
398
+ return {
399
+ description: "Choose the judge model for the permission classifier",
400
+ getArgumentCompletions,
401
+ handler,
402
+ };
403
+ }