@ftrdotdev/pi-tracker 0.5.1 → 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,415 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect, Fiber, Option } from "effect";
3
+ import { TestClock } from "effect/testing";
4
+ import type {
5
+ ClassifierApi,
6
+ ClassifierChoiceAnswer,
7
+ ClassifierModel,
8
+ ClassifierQuestion,
9
+ ClassifierResult,
10
+ JsonObject,
11
+ } from "@earendil-works/pi-ai";
12
+ import {
13
+ CLASSIFY_TIMEOUT_MILLIS,
14
+ DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE,
15
+ DEFAULT_KEEP_CONTEXT_THRESHOLD,
16
+ NEEDS_CONTEXT_LABEL,
17
+ NEEDS_NONE_LABEL,
18
+ ClassifierGateway,
19
+ classifyVerdict,
20
+ resolveClassifier,
21
+ type ClassifierIdentity,
22
+ type ClassifierRegistry,
23
+ type CompactionQuestion,
24
+ } from "./classifier.ts";
25
+
26
+ const model = (provider: string, id: string): ClassifierModel<ClassifierApi> => ({
27
+ id,
28
+ name: id,
29
+ api: "typesafe-system-one",
30
+ provider,
31
+ baseUrl: "https://example.invalid",
32
+ input: ["text"],
33
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
34
+ type: "classifier",
35
+ contextWindow: 8192,
36
+ });
37
+
38
+ const clefFlash = model("cloudflare-workers-ai", "@cf/cloudflare/clef-flash");
39
+ const jev = model("typesafe", "jev-latest");
40
+ const opencodeJev = model("opencode", "jev-1.13");
41
+ const opencodeJevFree = model("opencode", "jev-1.13-free");
42
+
43
+ const QUESTION_KEY = "successorNeedsCompletedContext";
44
+ const DIGEST: JsonObject = { candidate: { ref: "Work:2" } };
45
+
46
+ const question: CompactionQuestion = {
47
+ key: QUESTION_KEY,
48
+ question: {
49
+ type: "choice",
50
+ instructions: "Does the next item need the completed item's detail?",
51
+ criteria: {
52
+ [NEEDS_CONTEXT_LABEL]: "It needs the detail",
53
+ [NEEDS_NONE_LABEL]: "It does not need the detail",
54
+ },
55
+ },
56
+ };
57
+
58
+ const choiceAnswer = (needsMass: number, confidence = 1): ClassifierChoiceAnswer => ({
59
+ type: "choice",
60
+ choice: needsMass >= 0.5 ? NEEDS_CONTEXT_LABEL : NEEDS_NONE_LABEL,
61
+ probabilities: { [NEEDS_CONTEXT_LABEL]: needsMass, [NEEDS_NONE_LABEL]: 1 - needsMass },
62
+ confidence,
63
+ });
64
+
65
+ const choiceResult = (needsMass: number, confidence = 1, key = QUESTION_KEY): ClassifierResult => ({
66
+ api: "typesafe-system-one",
67
+ provider: "typesafe",
68
+ model: "jev-latest",
69
+ answers: { [key]: choiceAnswer(needsMass, confidence) },
70
+ stopReason: "stop",
71
+ timestamp: 0,
72
+ });
73
+
74
+ const verdict = (
75
+ result: ClassifierResult,
76
+ questionKeys: readonly string[],
77
+ keepContextThreshold = DEFAULT_KEEP_CONTEXT_THRESHOLD,
78
+ keepContextMinConfidence = DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE,
79
+ ) => classifyVerdict(result, questionKeys, keepContextThreshold, keepContextMinConfidence);
80
+
81
+ const input = (
82
+ registry: ClassifierRegistry,
83
+ overrides: {
84
+ enabled?: boolean;
85
+ chosen?: Option.Option<ClassifierIdentity>;
86
+ keepContextThreshold?: number;
87
+ keepContextMinConfidence?: number;
88
+ digest?: JsonObject;
89
+ questions?: readonly CompactionQuestion[];
90
+ signal?: AbortSignal;
91
+ } = {},
92
+ ) => ({
93
+ registry,
94
+ enabled: overrides.enabled ?? true,
95
+ chosen: overrides.chosen ?? Option.none(),
96
+ keepContextThreshold: overrides.keepContextThreshold ?? DEFAULT_KEEP_CONTEXT_THRESHOLD,
97
+ keepContextMinConfidence:
98
+ overrides.keepContextMinConfidence ?? DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE,
99
+ digest: overrides.digest ?? DIGEST,
100
+ questions: overrides.questions ?? [question],
101
+ signal: overrides.signal,
102
+ });
103
+
104
+ const withGateway = <A, E>(
105
+ program: Effect.Effect<A, E, ClassifierGateway>,
106
+ ): Effect.Effect<A, E> => program.pipe(Effect.provide(ClassifierGateway.layer));
107
+
108
+ // ---------------------------------------------------------------------------
109
+ // resolveClassifier
110
+ // ---------------------------------------------------------------------------
111
+
112
+ it("resolveClassifier prefers Clef Flash over Jev when both are credential-available", () => {
113
+ const resolved = resolveClassifier([clefFlash, jev], Option.none());
114
+ assert.strictEqual(Option.isSome(resolved), true);
115
+ assert.strictEqual(Option.getOrThrow(resolved).provider, "cloudflare-workers-ai");
116
+ assert.strictEqual(Option.getOrThrow(resolved).id, "@cf/cloudflare/clef-flash");
117
+ });
118
+
119
+ it("resolveClassifier falls back to Jev when Clef Flash is not credential-available", () => {
120
+ const resolved = resolveClassifier([jev], Option.none());
121
+ assert.strictEqual(Option.getOrThrow(resolved).provider, "typesafe");
122
+ assert.strictEqual(Option.getOrThrow(resolved).id, "jev-latest");
123
+ });
124
+
125
+ it("resolveClassifier prefers TypeSafe Jev over OpenCode Jev when both are credential-available", () => {
126
+ const resolved = resolveClassifier([opencodeJev, jev], Option.none());
127
+ assert.strictEqual(Option.getOrThrow(resolved).provider, "typesafe");
128
+ assert.strictEqual(Option.getOrThrow(resolved).id, "jev-latest");
129
+ });
130
+
131
+ it("resolveClassifier falls back to OpenCode Jev when Cloudflare and TypeSafe are not credential-available", () => {
132
+ const resolved = resolveClassifier([opencodeJev], Option.none());
133
+ assert.strictEqual(Option.getOrThrow(resolved).provider, "opencode");
134
+ assert.strictEqual(Option.getOrThrow(resolved).id, "jev-1.13");
135
+ });
136
+
137
+ it("resolveClassifier prefers the OpenCode Jev standard tier over the free tier", () => {
138
+ const resolved = resolveClassifier([opencodeJevFree, opencodeJev], Option.none());
139
+ assert.strictEqual(Option.getOrThrow(resolved).provider, "opencode");
140
+ assert.strictEqual(Option.getOrThrow(resolved).id, "jev-1.13");
141
+ });
142
+
143
+ it("resolveClassifier falls back to the OpenCode free Jev tier as the last preference", () => {
144
+ const resolved = resolveClassifier([opencodeJevFree], Option.none());
145
+ assert.strictEqual(Option.getOrThrow(resolved).provider, "opencode");
146
+ assert.strictEqual(Option.getOrThrow(resolved).id, "jev-1.13-free");
147
+ });
148
+
149
+ it("resolveClassifier uses the chosen identity ahead of the preference order", () => {
150
+ const chosen: Option.Option<ClassifierIdentity> = Option.some({
151
+ provider: "typesafe",
152
+ modelId: "jev-latest",
153
+ });
154
+ const resolved = resolveClassifier([clefFlash, jev], chosen);
155
+ assert.strictEqual(Option.getOrThrow(resolved).provider, "typesafe");
156
+ assert.strictEqual(Option.getOrThrow(resolved).id, "jev-latest");
157
+ });
158
+
159
+ it("resolveClassifier falls back to the preference order when the chosen identity is not available", () => {
160
+ const chosen: Option.Option<ClassifierIdentity> = Option.some({
161
+ provider: "typesafe",
162
+ modelId: "jev-latest",
163
+ });
164
+ const resolved = resolveClassifier([clefFlash], chosen);
165
+ assert.strictEqual(Option.getOrThrow(resolved).provider, "cloudflare-workers-ai");
166
+ assert.strictEqual(Option.getOrThrow(resolved).id, "@cf/cloudflare/clef-flash");
167
+ });
168
+
169
+ it("resolveClassifier returns none when no classifier is credential-available", () => {
170
+ const chosen: Option.Option<ClassifierIdentity> = Option.some({
171
+ provider: "typesafe",
172
+ modelId: "jev-latest",
173
+ });
174
+ assert.strictEqual(Option.isNone(resolveClassifier([], chosen)), true);
175
+ });
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // classifyVerdict
179
+ // ---------------------------------------------------------------------------
180
+
181
+ it("classifyVerdict keeps context at the threshold", () => {
182
+ assert.deepStrictEqual(verdict(choiceResult(DEFAULT_KEEP_CONTEXT_THRESHOLD), [QUESTION_KEY]), {
183
+ kind: "keep",
184
+ });
185
+ });
186
+
187
+ it("classifyVerdict compacts below the threshold", () => {
188
+ assert.deepStrictEqual(verdict(choiceResult(0.2), [QUESTION_KEY]), { kind: "compact" });
189
+ });
190
+
191
+ it("classifyVerdict honors a raised threshold by compacting an answer the default would keep", () => {
192
+ assert.deepStrictEqual(verdict(choiceResult(0.6), [QUESTION_KEY], 0.9), { kind: "compact" });
193
+ });
194
+
195
+ it("classifyVerdict honors a lowered threshold by keeping an answer the default would compact", () => {
196
+ assert.deepStrictEqual(verdict(choiceResult(0.6), [QUESTION_KEY], 0.2), { kind: "keep" });
197
+ });
198
+
199
+ it("classifyVerdict keeps context when any judged candidate needs the detail", () => {
200
+ const result: ClassifierResult = {
201
+ ...choiceResult(0.1, 1, "a"),
202
+ answers: { a: choiceAnswer(0.1), b: choiceAnswer(0.9) },
203
+ };
204
+ assert.deepStrictEqual(verdict(result, ["a", "b"]), { kind: "keep" });
205
+ });
206
+
207
+ it("classifyVerdict keeps context when an answer is below the confidence floor", () => {
208
+ assert.deepStrictEqual(verdict(choiceResult(0.1, 0.2), [QUESTION_KEY]), { kind: "keep" });
209
+ });
210
+
211
+ it("classifyVerdict compacts when the answer reaches the confidence floor", () => {
212
+ assert.deepStrictEqual(
213
+ verdict(choiceResult(0.1, DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE), [QUESTION_KEY]),
214
+ { kind: "compact" },
215
+ );
216
+ });
217
+
218
+ it("classifyVerdict keeps context when the answer does not carry a usable confidence", () => {
219
+ const result: ClassifierResult = {
220
+ ...choiceResult(0.1),
221
+ answers: { [QUESTION_KEY]: { ...choiceAnswer(0.1), confidence: Number.NaN } },
222
+ };
223
+ assert.deepStrictEqual(verdict(result, [QUESTION_KEY]), { kind: "keep" });
224
+ });
225
+
226
+ it("classifyVerdict is disabled when any judged candidate has no choice answer", () => {
227
+ const result: ClassifierResult = {
228
+ ...choiceResult(0.1, 1, "a"),
229
+ answers: { a: choiceAnswer(0.1) },
230
+ };
231
+ assert.deepStrictEqual(verdict(result, ["a", "b"]), { kind: "disabled" });
232
+ });
233
+
234
+ it("classifyVerdict is disabled when there is no candidate to judge", () => {
235
+ assert.deepStrictEqual(verdict(choiceResult(0.1), []), { kind: "disabled" });
236
+ });
237
+
238
+ it("classifyVerdict is disabled when the service did not stop", () => {
239
+ const result: ClassifierResult = { ...choiceResult(0.1), stopReason: "error" };
240
+ assert.deepStrictEqual(verdict(result, [QUESTION_KEY]), { kind: "disabled" });
241
+ });
242
+
243
+ it("classifyVerdict is disabled when the answer for the question key is missing", () => {
244
+ const result: ClassifierResult = { ...choiceResult(0.1), answers: {} };
245
+ assert.deepStrictEqual(verdict(result, [QUESTION_KEY]), { kind: "disabled" });
246
+ });
247
+
248
+ it("classifyVerdict is disabled when the answer is not a choice answer", () => {
249
+ const result: ClassifierResult = {
250
+ ...choiceResult(0.1),
251
+ answers: { [QUESTION_KEY]: { type: "bool", probability: 1 } },
252
+ };
253
+ assert.deepStrictEqual(verdict(result, [QUESTION_KEY]), { kind: "disabled" });
254
+ });
255
+
256
+ // ---------------------------------------------------------------------------
257
+ // ClassifierGateway
258
+ // ---------------------------------------------------------------------------
259
+
260
+ it.effect("gateway disables discovery when the feature is disabled", () =>
261
+ withGateway(
262
+ Effect.gen(function* () {
263
+ const gateway = yield* ClassifierGateway;
264
+ let discoveryCalls = 0;
265
+ const registry: ClassifierRegistry = {
266
+ getAvailableOfType: async () => {
267
+ discoveryCalls += 1;
268
+ return [jev];
269
+ },
270
+ classify: async () => choiceResult(0.1),
271
+ };
272
+ const result = yield* gateway.verdict(input(registry, { enabled: false }));
273
+ assert.deepStrictEqual(result, { kind: "disabled" });
274
+ assert.strictEqual(discoveryCalls, 0);
275
+ }),
276
+ ),
277
+ );
278
+
279
+ it.effect("gateway requires a credential-available classifier when the feature is enabled", () =>
280
+ withGateway(
281
+ Effect.gen(function* () {
282
+ const gateway = yield* ClassifierGateway;
283
+ let classifyCalls = 0;
284
+ const registry: ClassifierRegistry = {
285
+ getAvailableOfType: async () => [],
286
+ classify: async () => {
287
+ classifyCalls += 1;
288
+ return choiceResult(0.1);
289
+ },
290
+ };
291
+ const result = yield* gateway.verdict(input(registry));
292
+ assert.deepStrictEqual(result, { kind: "disabled" });
293
+ assert.strictEqual(classifyCalls, 0);
294
+ }),
295
+ ),
296
+ );
297
+
298
+ it.effect("gateway returns disabled when the classifier call throws", () =>
299
+ withGateway(
300
+ Effect.gen(function* () {
301
+ const gateway = yield* ClassifierGateway;
302
+ const registry: ClassifierRegistry = {
303
+ getAvailableOfType: async () => [jev],
304
+ classify: async () => {
305
+ throw new Error("provider unreachable");
306
+ },
307
+ };
308
+ const result = yield* gateway.verdict(input(registry));
309
+ assert.deepStrictEqual(result, { kind: "disabled" });
310
+ }),
311
+ ),
312
+ );
313
+
314
+ it.effect("gateway returns disabled when the classifier call exceeds the deadline", () =>
315
+ withGateway(
316
+ Effect.gen(function* () {
317
+ const gateway = yield* ClassifierGateway;
318
+ const captured: { signal?: AbortSignal } = {};
319
+ const registry: ClassifierRegistry = {
320
+ getAvailableOfType: async () => [jev],
321
+ classify: (_model, _context, options) => {
322
+ captured.signal = options?.signal;
323
+ return new Promise((_resolve, reject) => {
324
+ options?.signal?.addEventListener("abort", () => reject(new Error("aborted")));
325
+ });
326
+ },
327
+ };
328
+ const fiber = yield* Effect.forkChild(gateway.verdict(input(registry)));
329
+ yield* TestClock.adjust(CLASSIFY_TIMEOUT_MILLIS);
330
+ const result = yield* Fiber.join(fiber);
331
+ assert.deepStrictEqual(result, { kind: "disabled" });
332
+ assert.strictEqual(captured.signal?.aborted, true);
333
+ }),
334
+ ),
335
+ );
336
+
337
+ it.effect("gateway returns a compact verdict for an available classifier and a low probability", () =>
338
+ withGateway(
339
+ Effect.gen(function* () {
340
+ const gateway = yield* ClassifierGateway;
341
+ const registry: ClassifierRegistry = {
342
+ getAvailableOfType: async () => [clefFlash, jev],
343
+ classify: async () => choiceResult(0.1, 0.9),
344
+ };
345
+ const result = yield* gateway.verdict(input(registry));
346
+ assert.deepStrictEqual(result, { kind: "compact" });
347
+ }),
348
+ ),
349
+ );
350
+
351
+ it.effect("gateway forwards the run signal to the classifier call and returns disabled on abort", () => {
352
+ // Constructed outside the Effect program so the run signal is a plain value.
353
+ const controller = new AbortController();
354
+ return withGateway(
355
+ Effect.gen(function* () {
356
+ const gateway = yield* ClassifierGateway;
357
+ const captured: { signal?: AbortSignal } = {};
358
+ const registry: ClassifierRegistry = {
359
+ getAvailableOfType: async () => [jev],
360
+ classify: (_model, _context, options) => {
361
+ captured.signal = options?.signal;
362
+ return new Promise((_resolve, reject) => {
363
+ options?.signal?.addEventListener("abort", () => reject(new Error("run abort")));
364
+ });
365
+ },
366
+ };
367
+ const fiber = yield* Effect.forkChild(
368
+ gateway.verdict(input(registry, { signal: controller.signal })),
369
+ );
370
+ let attempts = 0;
371
+ while (captured.signal === undefined && attempts < 1000) {
372
+ yield* Effect.yieldNow;
373
+ attempts += 1;
374
+ }
375
+ controller.abort();
376
+ const result = yield* Fiber.join(fiber);
377
+ assert.deepStrictEqual(result, { kind: "disabled" });
378
+ assert.strictEqual(captured.signal?.aborted, true);
379
+ }),
380
+ );
381
+ });
382
+
383
+ it.effect("gateway sends exactly one choice question with the digest as the classifier state", () =>
384
+ withGateway(
385
+ Effect.gen(function* () {
386
+ const gateway = yield* ClassifierGateway;
387
+ const captured: {
388
+ state?: JsonObject;
389
+ questions?: Record<string, ClassifierQuestion>;
390
+ } = {};
391
+ const registry: ClassifierRegistry = {
392
+ getAvailableOfType: async () => [jev],
393
+ classify: async (_model, context) => {
394
+ captured.state = context.state;
395
+ captured.questions = context.questions;
396
+ return choiceResult(0.1);
397
+ },
398
+ };
399
+ const result = yield* gateway.verdict(input(registry));
400
+ assert.deepStrictEqual(result, { kind: "compact" });
401
+ assert.deepStrictEqual(captured.state, DIGEST);
402
+ const questions = captured.questions ?? {};
403
+ const keys = Object.keys(questions);
404
+ assert.strictEqual(keys.length, 1);
405
+ assert.strictEqual(keys[0], QUESTION_KEY);
406
+ const asked = questions[QUESTION_KEY];
407
+ assert.strictEqual(asked?.type, "choice");
408
+ const criteria = asked?.type === "choice" ? asked.criteria : {};
409
+ assert.strictEqual(typeof asked?.instructions, "string");
410
+ assert.isAtLeast(asked?.instructions.length ?? 0, 1);
411
+ assert.isAtLeast((criteria[NEEDS_CONTEXT_LABEL] ?? "").length, 1);
412
+ assert.isAtLeast((criteria[NEEDS_NONE_LABEL] ?? "").length, 1);
413
+ }),
414
+ ),
415
+ );
@@ -0,0 +1,196 @@
1
+ import { Context, Effect, Layer, Option } from "effect";
2
+ import type {
3
+ ClassifierApi,
4
+ ClassifierModel,
5
+ ClassifierQuestion,
6
+ ClassifierResult,
7
+ JsonObject,
8
+ } from "@earendil-works/pi-ai";
9
+
10
+ /**
11
+ * One question the gateway asks a classifier about a candidate. Built by
12
+ * `digest.ts`; owned here because it is the gateway's input contract.
13
+ */
14
+ export interface CompactionQuestion {
15
+ readonly key: string;
16
+ readonly question: ClassifierQuestion;
17
+ }
18
+
19
+ /**
20
+ * The slice of pi's `ModelRegistry` this gateway uses. Structural, so the
21
+ * bridge passes `ctx.modelRegistry` and tests pass a plain object.
22
+ */
23
+ export interface ClassifierRegistry {
24
+ readonly getAvailableOfType: (
25
+ type: "classifier",
26
+ ) => Promise<readonly ClassifierModel<ClassifierApi>[]>;
27
+ readonly classify: (
28
+ model: ClassifierModel<ClassifierApi>,
29
+ context: {
30
+ readonly state: JsonObject;
31
+ readonly questions: Record<string, ClassifierQuestion>;
32
+ },
33
+ options?: { readonly signal?: AbortSignal | undefined },
34
+ ) => Promise<ClassifierResult>;
35
+ }
36
+
37
+ /** A `provider/modelId` classifier choice. */
38
+ export interface ClassifierIdentity {
39
+ readonly provider: string;
40
+ readonly modelId: string;
41
+ }
42
+
43
+ const CLASSIFICATION_VERDICT = {
44
+ compact: { kind: "compact" },
45
+ keep: { kind: "keep" },
46
+ disabled: { kind: "disabled" },
47
+ } as const;
48
+
49
+ export type ClassificationVerdict =
50
+ (typeof CLASSIFICATION_VERDICT)[keyof typeof CLASSIFICATION_VERDICT];
51
+
52
+ /**
53
+ * Preference order, resolved against the credential-available classifiers at
54
+ * runtime. Cloudflare first; then a direct TypeSafe key; then OpenCode's Jev
55
+ * for the setups that configure OpenCode instead of `TYPESAFE_API_KEY`; the
56
+ * OpenCode free tier last, so a rate-limited free model is the final fallback.
57
+ */
58
+ export const PREFERRED_CLASSIFIERS: readonly ClassifierIdentity[] = [
59
+ { provider: "cloudflare-workers-ai", modelId: "@cf/cloudflare/clef-flash" },
60
+ { provider: "typesafe", modelId: "jev-latest" },
61
+ { provider: "opencode", modelId: "jev-1.13" },
62
+ { provider: "opencode", modelId: "jev-1.13-free" },
63
+ ];
64
+
65
+ /**
66
+ * The default probability at or above which the candidate is judged to need
67
+ * the prior context. A user overrides it with
68
+ * `smartCompaction.keepContextThreshold`; the default keeps context on an
69
+ * uncertain answer.
70
+ */
71
+ export const DEFAULT_KEEP_CONTEXT_THRESHOLD = 0.5;
72
+
73
+ /**
74
+ * The default `confidence` below which the answer is distrusted and the context
75
+ * is kept. A user overrides it with `smartCompaction.keepContextMinConfidence`.
76
+ */
77
+ export const DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE = 0.5;
78
+
79
+ /** The `choice` label that means the candidate needs the completed context. */
80
+ export const NEEDS_CONTEXT_LABEL = "needs-context";
81
+ /** The `choice` label that means the candidate needs nothing from the work. */
82
+ export const NEEDS_NONE_LABEL = "stands-alone";
83
+
84
+ /** The settle boundary awaits this call, so it is bounded. */
85
+ export const CLASSIFY_TIMEOUT_MILLIS = 5_000;
86
+
87
+ export const resolveClassifier = (
88
+ available: readonly ClassifierModel<ClassifierApi>[],
89
+ chosen: Option.Option<ClassifierIdentity>,
90
+ ): Option.Option<ClassifierModel<ClassifierApi>> => {
91
+ const matches = (identity: ClassifierIdentity) =>
92
+ available.find(
93
+ (model) => model.provider === identity.provider && model.id === identity.modelId,
94
+ );
95
+ if (Option.isSome(chosen)) {
96
+ const selected = matches(chosen.value);
97
+ if (selected !== undefined) return Option.some(selected);
98
+ }
99
+ for (const identity of PREFERRED_CLASSIFIERS) {
100
+ const preferred = matches(identity);
101
+ if (preferred !== undefined) return Option.some(preferred);
102
+ }
103
+ return Option.none();
104
+ };
105
+
106
+ /**
107
+ * The verdict over every judged candidate. Keep context when any candidate
108
+ * needs the completed detail, or when an answer is below the confidence floor.
109
+ * Compact only when every answer is above the floor and self-contained. A
110
+ * non-stop or malformed answer, or an empty question set, keeps the context.
111
+ */
112
+ export const classifyVerdict = (
113
+ result: ClassifierResult,
114
+ questionKeys: readonly string[],
115
+ keepContextThreshold: number,
116
+ keepContextMinConfidence: number,
117
+ ): ClassificationVerdict => {
118
+ if (result.stopReason !== "stop") return CLASSIFICATION_VERDICT.disabled;
119
+ if (questionKeys.length === 0) return CLASSIFICATION_VERDICT.disabled;
120
+ for (const questionKey of questionKeys) {
121
+ const answer = result.answers[questionKey];
122
+ if (answer === undefined || answer.type !== "choice") return CLASSIFICATION_VERDICT.disabled;
123
+ if ((answer.probabilities[NEEDS_CONTEXT_LABEL] ?? 0) >= keepContextThreshold) {
124
+ return CLASSIFICATION_VERDICT.keep;
125
+ }
126
+ // A provider that omits or mangles confidence keeps the context.
127
+ const confidence = Number.isFinite(answer.confidence) ? answer.confidence : 0;
128
+ if (confidence < keepContextMinConfidence) return CLASSIFICATION_VERDICT.keep;
129
+ }
130
+ return CLASSIFICATION_VERDICT.compact;
131
+ };
132
+
133
+ /** Fail-open boolean-classification gateway. Never fails its caller. */
134
+ export class ClassifierGateway extends Context.Service<
135
+ ClassifierGateway,
136
+ {
137
+ readonly verdict: (input: {
138
+ readonly registry: ClassifierRegistry;
139
+ readonly enabled: boolean;
140
+ readonly chosen: Option.Option<ClassifierIdentity>;
141
+ readonly keepContextThreshold: number;
142
+ readonly keepContextMinConfidence: number;
143
+ readonly digest: JsonObject;
144
+ readonly questions: readonly CompactionQuestion[];
145
+ readonly signal?: AbortSignal | undefined;
146
+ }) => Effect.Effect<ClassificationVerdict>;
147
+ }
148
+ >()("tracker/ClassifierGateway") {
149
+ static readonly layer: Layer.Layer<ClassifierGateway> = Layer.sync(ClassifierGateway, () => {
150
+ const verdict = Effect.fn("ClassifierGateway.verdict")(function* (input: {
151
+ readonly registry: ClassifierRegistry;
152
+ readonly enabled: boolean;
153
+ readonly chosen: Option.Option<ClassifierIdentity>;
154
+ readonly keepContextThreshold: number;
155
+ readonly keepContextMinConfidence: number;
156
+ readonly digest: JsonObject;
157
+ readonly questions: readonly CompactionQuestion[];
158
+ readonly signal?: AbortSignal | undefined;
159
+ }) {
160
+ if (!input.enabled || input.signal?.aborted) return CLASSIFICATION_VERDICT.disabled;
161
+
162
+ const available = yield* Effect.tryPromise(() =>
163
+ input.registry.getAvailableOfType("classifier"),
164
+ ).pipe(Effect.catchCause(() => Effect.succeed([])));
165
+ const model = resolveClassifier(available, input.chosen);
166
+ if (Option.isNone(model)) return CLASSIFICATION_VERDICT.disabled;
167
+ const result = yield* Effect.tryPromise((signal) =>
168
+ input.registry.classify(
169
+ model.value,
170
+ {
171
+ state: input.digest,
172
+ questions: Object.fromEntries(
173
+ input.questions.map((question) => [question.key, question.question]),
174
+ ),
175
+ },
176
+ {
177
+ signal: input.signal === undefined ? signal : AbortSignal.any([signal, input.signal]),
178
+ },
179
+ ),
180
+ ).pipe(
181
+ Effect.timeoutOption(CLASSIFY_TIMEOUT_MILLIS),
182
+ Effect.catchCause(() => Effect.succeedNone),
183
+ );
184
+ if (input.signal?.aborted) return CLASSIFICATION_VERDICT.disabled;
185
+ return Option.isNone(result)
186
+ ? CLASSIFICATION_VERDICT.disabled
187
+ : classifyVerdict(
188
+ result.value,
189
+ input.questions.map((question) => question.key),
190
+ input.keepContextThreshold,
191
+ input.keepContextMinConfidence,
192
+ );
193
+ });
194
+ return ClassifierGateway.of({ verdict });
195
+ });
196
+ }