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