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,378 @@
1
+ /**
2
+ * Extension wiring: load the config at `session_start`, register the
3
+ * `"classifier"` link from `permissions:ready`, and dispose on shutdown.
4
+ *
5
+ * The ready handler is the sole registration site. pi-permission-system
6
+ * >=27.0.0 emits `permissions:ready` at least once after every extension's
7
+ * `session_start` (and it may repeat), so registering there needs no second
8
+ * attempt from this extension's own `session_start` — only an idempotency
9
+ * guard, because `registerAuthorizer` rejects a duplicate name.
10
+ *
11
+ * The service is resolved per node with the session-keyed locator, using the
12
+ * sessionId carried by the ready payload. When that id is missing, or the
13
+ * locator has no service for it, the permission system in this session is too
14
+ * old (or absent): warn once per session and register nothing — never fall
15
+ * back to the process root's service, which is another node's inside an
16
+ * in-process subagent child.
17
+ *
18
+ * The session's active model is captured at `session_start` and follows
19
+ * `model_select`, so with no config override the judge is always the model
20
+ * the session is actually running.
21
+ *
22
+ * Guidance files are read for every judged ask through the reviewer's
23
+ * guidance seam: the loader walks the disk with the session cwd and the
24
+ * agent dir, project trust is read from the session context at that moment
25
+ * (never cached at ready), and the selection applies the trust gate and the
26
+ * byte caps. An older pi without a trust query counts as untrusted.
27
+ *
28
+ * Once the link registers, the footer status `zz-permission-classifier` names
29
+ * the effective judge (see `judge.ts`); it follows `model_select` and is
30
+ * cleared at `session_shutdown`. No status is set when the link does not
31
+ * register.
32
+ *
33
+ * The `--permission-model <provider>/<id>` launch flag is read at
34
+ * `session_start`. A value the registry knows becomes a session-only judge
35
+ * override with precedence over the merged config and the session model;
36
+ * nothing is written, and the override is dropped at `session_shutdown`. An
37
+ * unknown value is ignored with a warning, so the merged config (or the
38
+ * session model) applies as if no flag were given.
39
+ */
40
+
41
+ import type { Model } from "@earendil-works/pi-ai";
42
+ import { complete as realComplete } from "@earendil-works/pi-ai/compat";
43
+ import {
44
+ type ExtensionAPI,
45
+ type ExtensionContext,
46
+ getAgentDir,
47
+ } from "@earendil-works/pi-coding-agent";
48
+ import {
49
+ getPermissionsService,
50
+ PERMISSIONS_READY_CHANNEL,
51
+ type PermissionsReadyEvent,
52
+ } from "@gotgenes/pi-permission-system";
53
+
54
+ import {
55
+ COMMAND_NAME,
56
+ type CommandRegistryLike,
57
+ createPermissionModelCommand,
58
+ type PickerSeam,
59
+ } from "./command";
60
+ import {
61
+ formatConfigIssue,
62
+ getGlobalConfigPath,
63
+ getProjectConfigPath,
64
+ globalConfigExists,
65
+ type LoadConfigResult,
66
+ loadClassifierConfig,
67
+ writeGlobalJudge,
68
+ } from "./config-loader";
69
+ import { CircuitBreaker } from "./breaker";
70
+ import {
71
+ CLASSIFIER_EXTENSION_ID,
72
+ type ClassifierConfig,
73
+ } from "./config-schema";
74
+ import {
75
+ findGlobalGuidancePath,
76
+ type GuidanceLoader,
77
+ type GuidanceSelection,
78
+ loadGuidanceFromDisk,
79
+ selectGuidance,
80
+ } from "./guidance";
81
+ import { formatHealthSuffix, SessionHealth } from "./health";
82
+ import {
83
+ formatJudgeStatus,
84
+ type JudgePair,
85
+ parseJudgePair,
86
+ resolveJudge,
87
+ } from "./judge";
88
+ import type { CompleteFn } from "./model-review";
89
+ import {
90
+ createClassifierReviewer,
91
+ type ModelRegistryLike,
92
+ } from "./reviewer";
93
+
94
+ /** The operator-facing chain-link name referenced from `authorizerChain`. */
95
+ const LINK_NAME = "classifier";
96
+
97
+ /** The footer status key naming the effective judge. pi sorts extension
98
+ * statuses by key on one footer line; the `zz-` prefix keeps this entry last. */
99
+ const STATUS_KEY = "zz-permission-classifier";
100
+
101
+ /** The launch flag carrying a session-only judge override. */
102
+ const FLAG_NAME = "permission-model";
103
+
104
+ /** Footer refresh period while the breaker counts down, in milliseconds. */
105
+ const COUNTDOWN_TICK_MS = 1000;
106
+
107
+ /** Injectable seams; production defaults read the filesystem and call the model. */
108
+ export interface ClassifierDependencies {
109
+ /** The pi agent dir holding the global config; defaults to `getAgentDir()`. */
110
+ agentDir?: () => string;
111
+ /** Load the layered config; the project layer applies only when trusted. */
112
+ loadConfig?: (cwd: string, projectTrusted: boolean) => LoadConfigResult;
113
+ complete?: CompleteFn;
114
+ /** Persist a judge pair to the global config; both `undefined` removes it. */
115
+ writeJudge?: (provider: string | undefined, model: string | undefined) => void;
116
+ /** Builds the /permission-model picker; the default mounts pi's selector. */
117
+ buildPicker?: PickerSeam;
118
+ /** Reads the context files from disk; defaults to pi's context-file walk. */
119
+ loadGuidance?: GuidanceLoader;
120
+ }
121
+
122
+ function warn(message: string): void {
123
+ console.warn(`[${CLASSIFIER_EXTENSION_ID}] ${message}`);
124
+ }
125
+
126
+ export function createClassifierExtension(
127
+ pi: ExtensionAPI,
128
+ dependencies: ClassifierDependencies = {},
129
+ ): void {
130
+ // `agentDir()` is called inside each lambda rather than hoisted so the env
131
+ // read happens only on the production path, and only when a config is
132
+ // actually touched — `getAgentDir()` honors `PI_CODING_AGENT_DIR`, matching
133
+ // where pi-permission-system looks for the same global scope.
134
+ const agentDir = dependencies.agentDir ?? getAgentDir;
135
+ const loadConfig =
136
+ dependencies.loadConfig ??
137
+ ((cwd: string, projectTrusted: boolean) =>
138
+ loadClassifierConfig({ cwd, agentDir: agentDir(), projectTrusted }));
139
+ const complete: CompleteFn =
140
+ dependencies.complete ??
141
+ ((model, context, options) => realComplete(model, context, options));
142
+ const writeJudge =
143
+ dependencies.writeJudge ??
144
+ ((provider: string | undefined, model: string | undefined) =>
145
+ writeGlobalJudge(agentDir(), provider, model));
146
+ const loadGuidance = dependencies.loadGuidance ?? loadGuidanceFromDisk;
147
+
148
+ pi.registerFlag(FLAG_NAME, {
149
+ description:
150
+ "Judge model for the permission classifier this session only " +
151
+ "(<provider>/<id>); overrides the configured judge, writes nothing.",
152
+ type: "string",
153
+ });
154
+
155
+ let config: ClassifierConfig | undefined;
156
+ let sessionModel: Model<any> | undefined;
157
+ let registry: (ModelRegistryLike & CommandRegistryLike) | undefined;
158
+ let ui: ExtensionContext["ui"] | undefined;
159
+ /** The session context, for the per-ask cwd and trust reads. */
160
+ let session: ExtensionContext | undefined;
161
+ let override: JudgePair | undefined;
162
+ let dispose: (() => void) | undefined;
163
+ let warnedUnreachable = false;
164
+ /** Per-session judge health and breaker; both start fresh at shutdown. */
165
+ const health = new SessionHealth();
166
+ let breaker = new CircuitBreaker();
167
+ /** The once-per-second footer refresh while the breaker cools down. */
168
+ let countdown: ReturnType<typeof setInterval> | undefined;
169
+
170
+ /**
171
+ * The config the reviewer judges with: the merged config, with the
172
+ * provider/model pair replaced by the session-only override when one is
173
+ * active. The reviewer's own resolution (registry lookup, auth check,
174
+ * defer on failure) is unchanged, so an override can never widen a verdict.
175
+ */
176
+ function effectiveConfig(): ClassifierConfig | undefined {
177
+ if (!config || !override) {
178
+ return config;
179
+ }
180
+ return { ...config, provider: override.provider, model: override.model };
181
+ }
182
+
183
+ /**
184
+ * The project's trust state right now, from the session context. A pi
185
+ * without the trust query, or no context yet, counts as untrusted.
186
+ */
187
+ function projectTrusted(ctx: ExtensionContext | undefined = session): boolean {
188
+ return typeof ctx?.isProjectTrusted === "function"
189
+ ? ctx.isProjectTrusted()
190
+ : false;
191
+ }
192
+
193
+ /**
194
+ * Load and select this ask's guidance. Called by the reviewer once per
195
+ * judged ask; every read here is live — the disk walk, the agent dir, and
196
+ * the trust query — so nothing decided at ready can go stale. Throws
197
+ * propagate: the reviewer turns them into a guidance-load-failed defer.
198
+ */
199
+ function getGuidance(): GuidanceSelection {
200
+ if (!session) {
201
+ throw new Error("no session context to read guidance for");
202
+ }
203
+ const dir = agentDir();
204
+ const files = loadGuidance({ cwd: session.cwd, agentDir: dir });
205
+ return selectGuidance(
206
+ files,
207
+ findGlobalGuidancePath(files, dir),
208
+ projectTrusted(session),
209
+ );
210
+ }
211
+
212
+ /** Read the launch flag; a value the registry does not know is ignored. */
213
+ function readFlagOverride(): JudgePair | undefined {
214
+ const raw = pi.getFlag(FLAG_NAME);
215
+ if (typeof raw !== "string" || raw.length === 0) {
216
+ return undefined;
217
+ }
218
+ const pair = parseJudgePair(raw);
219
+ if (pair && registry?.find(pair.provider, pair.model)) {
220
+ return pair;
221
+ }
222
+ const message =
223
+ `--${FLAG_NAME} ${raw} is not a known <provider>/<id>; ` +
224
+ "the configured judge applies.";
225
+ warn(message);
226
+ ui?.notify(message, "warning");
227
+ return undefined;
228
+ }
229
+
230
+ /**
231
+ * Name the effective judge in the footer with the session health suffix;
232
+ * a no-op until the link registers. Refreshed on judge changes and after
233
+ * every reviewer outcome.
234
+ */
235
+ function refreshStatus(): void {
236
+ if (!dispose) {
237
+ return;
238
+ }
239
+ ui?.setStatus(
240
+ STATUS_KEY,
241
+ formatJudgeStatus(resolveJudge(override, config, registry, sessionModel)) +
242
+ formatHealthSuffix(health, breaker.remainingMs()),
243
+ );
244
+ }
245
+
246
+ function stopCountdown(): void {
247
+ if (countdown !== undefined) {
248
+ clearInterval(countdown);
249
+ countdown = undefined;
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Keep the breaker countdown in step with the breaker: start one interval
255
+ * when the breaker is open, stop it once the cooldown has elapsed (the tick
256
+ * that reaches zero repaints without the breaker suffix) or the breaker
257
+ * closed. The interval never keeps the process alive.
258
+ */
259
+ function syncCountdown(): void {
260
+ if (breaker.remainingMs() === 0) {
261
+ stopCountdown();
262
+ return;
263
+ }
264
+ if (countdown !== undefined) {
265
+ return;
266
+ }
267
+ countdown = setInterval(() => {
268
+ refreshStatus();
269
+ if (breaker.remainingMs() === 0) {
270
+ stopCountdown();
271
+ }
272
+ }, COUNTDOWN_TICK_MS);
273
+ countdown.unref?.();
274
+ }
275
+
276
+ pi.registerCommand(
277
+ COMMAND_NAME,
278
+ createPermissionModelCommand({
279
+ getConfig: () => config,
280
+ getOverride: () => override,
281
+ getRegistry: () => registry,
282
+ ...(dependencies.buildPicker
283
+ ? { buildPicker: dependencies.buildPicker }
284
+ : {}),
285
+ globalConfigExists: () => globalConfigExists(agentDir()),
286
+ globalConfigPath: () => getGlobalConfigPath(agentDir()),
287
+ projectConfigPath: getProjectConfigPath,
288
+ writeJudge,
289
+ reload: (cwd) => loadConfig(cwd, projectTrusted()),
290
+ apply: (next) => {
291
+ // An explicit choice replaces a flag override for the rest of the session.
292
+ config = next;
293
+ override = undefined;
294
+ refreshStatus();
295
+ },
296
+ }),
297
+ );
298
+
299
+ function warnUnreachableOnce(): void {
300
+ if (warnedUnreachable) {
301
+ return;
302
+ }
303
+ warnedUnreachable = true;
304
+ warn(
305
+ "could not resolve this session's permission service — " +
306
+ "pi-permission-system 27.0.0 or later must be loaded in the same " +
307
+ "session; the classifier link is not registered.",
308
+ );
309
+ }
310
+
311
+ pi.on("session_start", (_event, ctx) => {
312
+ const result = loadConfig(ctx.cwd, projectTrusted(ctx));
313
+ config = result.config;
314
+ sessionModel = ctx.model;
315
+ registry = ctx.modelRegistry;
316
+ ui = ctx.ui;
317
+ session = ctx;
318
+ override = readFlagOverride();
319
+ for (const issue of result.issues) {
320
+ warn(`config issue: ${formatConfigIssue(issue)}`);
321
+ }
322
+ });
323
+
324
+ pi.on("model_select", (event) => {
325
+ sessionModel = event.model;
326
+ refreshStatus();
327
+ });
328
+
329
+ pi.events.on(PERMISSIONS_READY_CHANNEL, (event) => {
330
+ // Idempotent: ready fires at least once per session and may repeat.
331
+ if (dispose || !config) {
332
+ return;
333
+ }
334
+ const sessionId = (event as PermissionsReadyEvent | undefined)?.sessionId;
335
+ if (typeof sessionId !== "string") {
336
+ warnUnreachableOnce();
337
+ return;
338
+ }
339
+ const service = getPermissionsService(sessionId);
340
+ if (!service) {
341
+ warnUnreachableOnce();
342
+ return;
343
+ }
344
+ const authorize = createClassifierReviewer({
345
+ getConfig: effectiveConfig,
346
+ getSessionModel: () => sessionModel,
347
+ getRegistry: () => registry,
348
+ complete,
349
+ breaker,
350
+ getGuidance,
351
+ onOutcome: (outcome) => {
352
+ health.record(outcome);
353
+ refreshStatus();
354
+ syncCountdown();
355
+ },
356
+ });
357
+ dispose = service.registerAuthorizer(LINK_NAME, authorize);
358
+ refreshStatus();
359
+ });
360
+
361
+ pi.on("session_shutdown", () => {
362
+ if (dispose) {
363
+ ui?.setStatus(STATUS_KEY, undefined);
364
+ }
365
+ dispose?.();
366
+ dispose = undefined;
367
+ config = undefined;
368
+ sessionModel = undefined;
369
+ registry = undefined;
370
+ ui = undefined;
371
+ session = undefined;
372
+ override = undefined;
373
+ warnedUnreachable = false;
374
+ stopCountdown();
375
+ health.reset();
376
+ breaker = new CircuitBreaker();
377
+ });
378
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Guidance: which context files (the operator's global AGENTS.md and the
3
+ * trusted project's own) reach the judge prompt, and why the rest do not.
4
+ *
5
+ * This module is the classifier's only reader of context files, and it reads
6
+ * them through pi's own context-file walk (`loadProjectContextFiles`), never
7
+ * node:fs, so the candidates are the same walk the main agent uses: override
8
+ * names, the CLAUDE.md fallback, worktree shadowing. Files are read
9
+ * from disk on every judged ask, so an edit takes effect on the next ask;
10
+ * nothing is cached.
11
+ *
12
+ * Selection itself is pure. It receives the loader's file list, decides
13
+ * inclusion, and measures every file for the audit trail. The rules, applied
14
+ * in loader order:
15
+ *
16
+ * - The global file is always a candidate; every other file is a candidate
17
+ * only when the project is trusted (dropped as `untrusted` otherwise).
18
+ * - A file over 16 KiB of UTF-8 is dropped whole, never truncated
19
+ * (`over-file-cap`).
20
+ * - Included bytes accumulate; the first file that would push the total past
21
+ * 32 KiB and every later file are dropped whole (`over-total-cap`).
22
+ *
23
+ * Bytes and hash12 follow the same conventions as the full-command evidence
24
+ * read: UTF-8 byte length, first 12 hex chars of sha256.
25
+ */
26
+
27
+ import { createHash } from "node:crypto";
28
+ import { dirname, resolve } from "node:path";
29
+
30
+ import { loadProjectContextFiles } from "@earendil-works/pi-coding-agent";
31
+
32
+ /** Maximum UTF-8 bytes for a single included file. */
33
+ export const GUIDANCE_FILE_CAP_BYTES = 16 * 1024;
34
+
35
+ /** Maximum UTF-8 bytes across every included file. */
36
+ export const GUIDANCE_TOTAL_CAP_BYTES = 32 * 1024;
37
+
38
+ /** One context file as the loader reports it. */
39
+ export interface GuidanceSource {
40
+ readonly path: string;
41
+ readonly content: string;
42
+ }
43
+
44
+ /** A file that reaches the judge prompt. */
45
+ export interface IncludedGuidance {
46
+ readonly path: string;
47
+ /** The file text exactly as loaded; rendered verbatim. */
48
+ readonly content: string;
49
+ /** UTF-8 byte length of the content. */
50
+ readonly bytes: number;
51
+ /** First 12 lowercase hex chars of sha256(content). */
52
+ readonly hash12: string;
53
+ /** True for the operator's global file, false for a project file. */
54
+ readonly isGlobal: boolean;
55
+ }
56
+
57
+ /** Why a file was excluded from the judge prompt. */
58
+ export type GuidanceDropReason = "untrusted" | "over-file-cap" | "over-total-cap";
59
+
60
+ /** A file that was excluded, with the first rule that excluded it. */
61
+ export interface DroppedGuidance {
62
+ readonly path: string;
63
+ readonly bytes: number;
64
+ readonly reason: GuidanceDropReason;
65
+ }
66
+
67
+ /** The selection outcome, both lists in loader order. */
68
+ export interface GuidanceSelection {
69
+ readonly included: readonly IncludedGuidance[];
70
+ readonly dropped: readonly DroppedGuidance[];
71
+ }
72
+
73
+ /** Where to look: the session cwd and the pi agent dir. */
74
+ export interface GuidanceLoadOptions {
75
+ readonly cwd: string;
76
+ readonly agentDir: string;
77
+ }
78
+
79
+ /** The disk seam: pi's context-file walk, or a test double. */
80
+ export type GuidanceLoader = (
81
+ options: GuidanceLoadOptions,
82
+ ) => readonly GuidanceSource[];
83
+
84
+ /**
85
+ * Read the context files from disk through pi's loader: the agent dir file
86
+ * first (when present), then each ancestor of cwd from the root down to cwd.
87
+ */
88
+ export const loadGuidanceFromDisk: GuidanceLoader = (options) =>
89
+ loadProjectContextFiles({ cwd: options.cwd, agentDir: options.agentDir });
90
+
91
+ /**
92
+ * The global file among the loader's entries: the one that lives directly in
93
+ * the agent dir, whatever its name. Undefined when the agent dir holds none.
94
+ */
95
+ export function findGlobalGuidancePath(
96
+ files: readonly GuidanceSource[],
97
+ agentDir: string,
98
+ ): string | undefined {
99
+ const dir = resolve(agentDir);
100
+ return files.find((file) => dirname(resolve(file.path)) === dir)?.path;
101
+ }
102
+
103
+ /**
104
+ * Select the guidance files for one ask.
105
+ *
106
+ * `files` is the loader's list in loader order, `globalPath` identifies the
107
+ * operator's global file within it (undefined when there is none), and
108
+ * `trusted` is the project's trust state for this ask.
109
+ */
110
+ export function selectGuidance(
111
+ files: readonly GuidanceSource[],
112
+ globalPath: string | undefined,
113
+ trusted: boolean,
114
+ ): GuidanceSelection {
115
+ const included: IncludedGuidance[] = [];
116
+ const dropped: DroppedGuidance[] = [];
117
+ let total = 0;
118
+ // Latched on the first overflow: from then on every later file is dropped,
119
+ // however small, so the prompt never carries a file out of loader order.
120
+ let totalCapHit = false;
121
+
122
+ for (const { path, content } of files) {
123
+ const isGlobal = globalPath !== undefined && path === globalPath;
124
+ const bytes = Buffer.byteLength(content, "utf8");
125
+
126
+ if (!isGlobal && !trusted) {
127
+ dropped.push({ path, bytes, reason: "untrusted" });
128
+ continue;
129
+ }
130
+ if (bytes > GUIDANCE_FILE_CAP_BYTES) {
131
+ dropped.push({ path, bytes, reason: "over-file-cap" });
132
+ continue;
133
+ }
134
+ if (totalCapHit || total + bytes > GUIDANCE_TOTAL_CAP_BYTES) {
135
+ totalCapHit = true;
136
+ dropped.push({ path, bytes, reason: "over-total-cap" });
137
+ continue;
138
+ }
139
+
140
+ total += bytes;
141
+ included.push({
142
+ path,
143
+ content,
144
+ bytes,
145
+ hash12: createHash("sha256").update(content, "utf8").digest("hex").slice(0, 12),
146
+ isGlobal,
147
+ });
148
+ }
149
+
150
+ return { included, dropped };
151
+ }
package/src/health.ts ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Per-session judge health: how often the classifier fell back to the
3
+ * dialog this session, why it last did, and what the footer should say
4
+ * about it. The reviewer reports each recorded decision through an injected
5
+ * seam; the extension owns the record, appends the suffix to the footer
6
+ * status, and resets the record at session shutdown.
7
+ *
8
+ * Only failure-path defers are health events (a model call that failed or
9
+ * timed out, an unresolved model, a guidance load that threw, and the
10
+ * like). A model verdict (allow, deny, or the judge's own defer) is the
11
+ * classifier working as designed: allow and a model defer clear the pending
12
+ * reason, deny changes nothing, and neither ever shows in the footer.
13
+ *
14
+ * Pure module: no UI, no filesystem, no node builtins.
15
+ */
16
+
17
+ /** One recorded decision, as the reviewer reports it. */
18
+ export type HealthOutcome =
19
+ | { verdict: "allow" }
20
+ | { verdict: "deny" }
21
+ | { verdict: "defer"; deferReason: string };
22
+
23
+ /** The judge's own defer: a model verdict, not a failure. */
24
+ const MODEL_DEFER_REASON = "model-verdict";
25
+
26
+ /** The read side of the record, all the formatter needs. */
27
+ export interface HealthSnapshot {
28
+ /** Failure-path defers this session. */
29
+ readonly count: number;
30
+ /** Reason of the last failure defer; cleared by a later model verdict. */
31
+ readonly lastFailureReason: string | undefined;
32
+ }
33
+
34
+ export class SessionHealth implements HealthSnapshot {
35
+ private failures = 0;
36
+ private reason: string | undefined;
37
+
38
+ get count(): number {
39
+ return this.failures;
40
+ }
41
+
42
+ get lastFailureReason(): string | undefined {
43
+ return this.reason;
44
+ }
45
+
46
+ /** Fold one decision into the record. */
47
+ record(outcome: HealthOutcome): void {
48
+ switch (outcome.verdict) {
49
+ case "allow":
50
+ this.reason = undefined;
51
+ return;
52
+ case "deny":
53
+ return;
54
+ case "defer":
55
+ if (outcome.deferReason === MODEL_DEFER_REASON) {
56
+ this.reason = undefined;
57
+ return;
58
+ }
59
+ this.failures += 1;
60
+ this.reason = outcome.deferReason;
61
+ return;
62
+ }
63
+ }
64
+
65
+ /** Back to a fresh session: count 0, no reason. */
66
+ reset(): void {
67
+ this.failures = 0;
68
+ this.reason = undefined;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * The footer suffix for a health snapshot and the breaker's remaining
74
+ * cooldown. Breaker open wins over everything and shows whole seconds,
75
+ * rounded up. Otherwise the last failure reason with the count, or just the
76
+ * count once a model verdict cleared the reason. Empty when there is nothing
77
+ * to report.
78
+ */
79
+ export function formatHealthSuffix(
80
+ health: HealthSnapshot,
81
+ breakerRemainingMs: number,
82
+ ): string {
83
+ if (breakerRemainingMs > 0) {
84
+ return ` | breaker open ${Math.ceil(breakerRemainingMs / 1000)}s`;
85
+ }
86
+ if (health.count === 0) {
87
+ return "";
88
+ }
89
+ const label = health.lastFailureReason ?? "defers";
90
+ return ` | ${label} x${health.count}`;
91
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { createClassifierExtension } from "./extension";
4
+
5
+ /**
6
+ * Entry point: register the auto-classifier as a pi-permission-system
7
+ * Authorizer chain link named `"classifier"`.
8
+ */
9
+ export default function piPermissionClassifier(pi: ExtensionAPI): void {
10
+ createClassifierExtension(pi);
11
+ }