@hatk/hatk 0.0.1-alpha.95 → 0.0.1-alpha.97

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,168 @@
1
+ /** A typed question in the shape the System One API accepts. */
2
+ export interface ClassifierQuestion {
3
+ type: 'noul' | 'choice' | 'score';
4
+ instructions: string | Record<string, unknown> | unknown[];
5
+ criteria?: unknown;
6
+ }
7
+ /** The thing being scored: an account (by DID) or a single record. */
8
+ export interface ClassifierSubject {
9
+ /** `at://` URI for a record subject; the bare DID for an account subject. */
10
+ uri: string;
11
+ did: string;
12
+ handle?: string | null;
13
+ collection?: string;
14
+ value?: Record<string, any>;
15
+ }
16
+ export interface ClassifierContext {
17
+ db: {
18
+ query: (sql: string, params?: any[]) => Promise<any[]>;
19
+ run: (sql: string, ...params: any[]) => Promise<void>;
20
+ };
21
+ subject: ClassifierSubject;
22
+ }
23
+ export interface ClassifierModule {
24
+ /** `account` scans every indexed repo; `record` scans rows of `collections`. */
25
+ subject: 'account' | 'record';
26
+ /** Collections to scan. Required when `subject` is `record`. */
27
+ collections?: string[];
28
+ /** The questions to ask. Answers come back under the same keys. Omit when
29
+ * the classifier supplies its own `classify`. */
30
+ questions?: Record<string, ClassifierQuestion>;
31
+ /**
32
+ * Produce signals without asking a System One model.
33
+ *
34
+ * A classifier that runs its own model — an image classifier on the host, a
35
+ * hash lookup, a heuristic — sets this instead of `questions`. Everything
36
+ * downstream is unchanged: the same thresholds, the same report, the same
37
+ * review card. Return a bare number for a plain score.
38
+ */
39
+ classify?: (state: Record<string, unknown>, ctx: ClassifierContext) => Promise<Record<string, number | Signal>>;
40
+ /**
41
+ * Build the model `state` for this subject. Return `null` to skip it — a
42
+ * skipped subject costs no tokens. Gate on whatever makes the question
43
+ * answerable: an account with no content cannot be judged on its content.
44
+ */
45
+ buildState: (ctx: ClassifierContext) => Promise<Record<string, unknown> | null>;
46
+ /**
47
+ * Score at or above which a signal files a report. A number applies to every
48
+ * question; a map sets it per question. Questions absent from the map never
49
+ * file, though their scores are still stored and shown.
50
+ */
51
+ threshold?: number | Record<string, number>;
52
+ /** Label the filed report carries. A function receives the crossing signal. */
53
+ label?: string | ((signal: string, score: number) => string);
54
+ }
55
+ export declare function defineClassifier(module: ClassifierModule): {
56
+ /** `account` scans every indexed repo; `record` scans rows of `collections`. */
57
+ subject: "account" | "record";
58
+ /** Collections to scan. Required when `subject` is `record`. */
59
+ collections?: string[];
60
+ /** The questions to ask. Answers come back under the same keys. Omit when
61
+ * the classifier supplies its own `classify`. */
62
+ questions?: Record<string, ClassifierQuestion>;
63
+ /**
64
+ * Produce signals without asking a System One model.
65
+ *
66
+ * A classifier that runs its own model — an image classifier on the host, a
67
+ * hash lookup, a heuristic — sets this instead of `questions`. Everything
68
+ * downstream is unchanged: the same thresholds, the same report, the same
69
+ * review card. Return a bare number for a plain score.
70
+ */
71
+ classify?: (state: Record<string, unknown>, ctx: ClassifierContext) => Promise<Record<string, number | Signal>>;
72
+ /**
73
+ * Build the model `state` for this subject. Return `null` to skip it — a
74
+ * skipped subject costs no tokens. Gate on whatever makes the question
75
+ * answerable: an account with no content cannot be judged on its content.
76
+ */
77
+ buildState: (ctx: ClassifierContext) => Promise<Record<string, unknown> | null>;
78
+ /**
79
+ * Score at or above which a signal files a report. A number applies to every
80
+ * question; a map sets it per question. Questions absent from the map never
81
+ * file, though their scores are still stored and shown.
82
+ */
83
+ threshold?: number | Record<string, number>;
84
+ /** Label the filed report carries. A function receives the crossing signal. */
85
+ label?: string | ((signal: string, score: number) => string);
86
+ __type: "classifiers";
87
+ };
88
+ interface LoadedClassifier extends ClassifierModule {
89
+ name: string;
90
+ }
91
+ /** Discover and load classifier modules from the `classifiers/` directory. */
92
+ export declare function initClassifiers(classifiersDir: string): Promise<void>;
93
+ /**
94
+ * Register a classifier directly, bypassing directory discovery.
95
+ *
96
+ * Mirrors {@link registerLabelModule}: tests and embedders that build their own
97
+ * module graph have no `classifiers/` directory to read.
98
+ */
99
+ export declare function registerClassifier(name: string, module: ClassifierModule): void;
100
+ /** Clear all registered classifiers (for hot-reload). */
101
+ export declare function clearClassifiers(): void;
102
+ /** Names of all loaded classifiers. */
103
+ export declare function listClassifiers(): string[];
104
+ export declare function getClassifier(name: string): LoadedClassifier | undefined;
105
+ export interface SystemOneConfig {
106
+ apiKey: string;
107
+ model: string;
108
+ endpoint: string;
109
+ }
110
+ export declare function configureSystemOne(config: SystemOneConfig | null): void;
111
+ export declare function isSystemOneConfigured(): boolean;
112
+ /** A single answer, normalized to a 0–1 score regardless of question type. */
113
+ export interface Signal {
114
+ score: number;
115
+ type: string;
116
+ /** Choice/Score only: the selected option and its confidence. */
117
+ choice?: string;
118
+ confidence?: number;
119
+ }
120
+ /**
121
+ * Ask the model one request's worth of questions about one state.
122
+ *
123
+ * Retries on 429 and 5xx, honoring `retry-after` when the response carries one.
124
+ * The caller's concurrency is what keeps us under the rate limit; this only
125
+ * recovers the requests that still slip past it.
126
+ */
127
+ export declare function askSystemOne(state: Record<string, unknown>, questions: Record<string, ClassifierQuestion>, opts?: {
128
+ attempts?: number;
129
+ signal?: AbortSignal;
130
+ }): Promise<{
131
+ answers: Record<string, Signal>;
132
+ model: string;
133
+ inputTokens: number;
134
+ }>;
135
+ export interface ScanProgress {
136
+ /** Subjects considered. */
137
+ scanned: number;
138
+ /** Gated out by `buildState` returning null, or unchanged since the last scan. */
139
+ skipped: number;
140
+ /** Sent to the model and stored. */
141
+ scored: number;
142
+ /** Reports filed for crossing a threshold. */
143
+ filed: number;
144
+ errors: number;
145
+ inputTokens: number;
146
+ running: boolean;
147
+ startedAt: string;
148
+ finishedAt?: string;
149
+ error?: string;
150
+ }
151
+ /** Progress of the scan in flight, or the last one to finish. */
152
+ export declare function getScanProgress(): ScanProgress | null;
153
+ /**
154
+ * Score every subject a classifier applies to, storing results and filing a
155
+ * report for each crossing signal.
156
+ *
157
+ * Subjects whose state is unchanged since the last scan are skipped unless
158
+ * `force` is set, so a repeat scan costs only what actually moved.
159
+ */
160
+ export declare function runScan(opts?: {
161
+ classifier?: string;
162
+ force?: boolean;
163
+ limit?: number;
164
+ concurrency?: number;
165
+ signal?: AbortSignal;
166
+ }): Promise<ScanProgress>;
167
+ export {};
168
+ //# sourceMappingURL=classifiers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"classifiers.d.ts","sourceRoot":"","sources":["../src/classifiers.ts"],"names":[],"mappings":"AA+CA,gEAAgE;AAChE,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,GAAG,QAAQ,GAAG,OAAO,CAAA;IACjC,YAAY,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,EAAE,CAAA;IAC1D,QAAQ,CAAC,EAAE,OAAO,CAAA;CACnB;AAED,sEAAsE;AACtE,MAAM,WAAW,iBAAiB;IAChC,6EAA6E;IAC7E,GAAG,EAAE,MAAM,CAAA;IACX,GAAG,EAAE,MAAM,CAAA;IACX,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IACtB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CAC5B;AAED,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE;QACF,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,GAAG,EAAE,CAAC,CAAA;QACtD,GAAG,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,GAAG,EAAE,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;KACtD,CAAA;IACD,OAAO,EAAE,iBAAiB,CAAA;CAC3B;AAED,MAAM,WAAW,gBAAgB;IAC/B,gFAAgF;IAChF,OAAO,EAAE,SAAS,GAAG,QAAQ,CAAA;IAC7B,gEAAgE;IAChE,WAAW,CAAC,EAAE,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AAW,CAAA;CAAO,GACrD,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,CAAC,CAuClF;AA8BD,MAAM,WAAW,YAAY;IAC3B,2BAA2B;IAC3B,OAAO,EAAE,MAAM,CAAA;IACf,kFAAkF;IAClF,OAAO,EAAE,MAAM,CAAA;IACf,oCAAoC;IACpC,MAAM,EAAE,MAAM,CAAA;IACd,8CAA8C;IAC9C,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,WAAW,EAAE,MAAM,CAAA;IACnB,OAAO,EAAE,OAAO,CAAA;IAChB,SAAS,EAAE,MAAM,CAAA;IACjB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAqDD,iEAAiE;AACjE,wBAAgB,eAAe,IAAI,YAAY,GAAG,IAAI,CAErD;AAED;;;;;;GAMG;AACH,wBAAsB,OAAO,CAC3B,IAAI,GAAE;IACJ,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,MAAM,CAAC,EAAE,WAAW,CAAA;CAChB,GACL,OAAO,CAAC,YAAY,CAAC,CA4IvB"}
@@ -0,0 +1,370 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /**
10
+ * Classifier system for scoring accounts and records with a System One model.
11
+ *
12
+ * A classifier is the moderation counterpart to a label rule: where a label rule
13
+ * decides from the record alone, a classifier asks a model a set of narrow typed
14
+ * questions and stores the probabilities. Nothing acts on a score — crossing a
15
+ * threshold files a report into the same `_reports` queue a user report lands in,
16
+ * so a person still makes every enforcement decision.
17
+ *
18
+ * Place classifier modules in the `classifiers/` directory.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * // classifiers/impersonation.ts
23
+ * import { defineClassifier } from '$hatk'
24
+ *
25
+ * export default defineClassifier({
26
+ * subject: 'account',
27
+ * label: 'impersonation',
28
+ * threshold: 0.7,
29
+ * questions: {
30
+ * passing_as: {
31
+ * type: 'noul',
32
+ * instructions: 'Is this account trying to be mistaken for a famous person?',
33
+ * },
34
+ * },
35
+ * async buildState({ subject, db }) {
36
+ * const [p] = await db.query(`SELECT description FROM profile WHERE did = $1`, [subject.did])
37
+ * return { handle: subject.handle, bio: p?.description }
38
+ * },
39
+ * })
40
+ * ```
41
+ */
42
+ import { resolve } from 'node:path';
43
+ import { readdirSync } from 'node:fs';
44
+ import { createHash } from 'node:crypto';
45
+ import { querySQL, runSQL, getSchema, upsertClassification, getClassificationFingerprints, findOpenReport, insertReport, } from "./database/db.js";
46
+ import { log, emit } from "./logger.js";
47
+ export function defineClassifier(module) {
48
+ return { __type: 'classifiers', ...module };
49
+ }
50
+ const classifiers = [];
51
+ /** Discover and load classifier modules from the `classifiers/` directory. */
52
+ export async function initClassifiers(classifiersDir) {
53
+ let files;
54
+ try {
55
+ files = readdirSync(classifiersDir)
56
+ .filter((f) => (f.endsWith('.ts') || f.endsWith('.js')) && !f.startsWith('_'))
57
+ .sort();
58
+ }
59
+ catch {
60
+ return;
61
+ }
62
+ for (const file of files) {
63
+ const name = file.replace(/\.(ts|js)$/, '');
64
+ const scriptPath = resolve(classifiersDir, file);
65
+ const mod = await import(__rewriteRelativeImportExtension(/* @vite-ignore */ `${scriptPath}?t=${Date.now()}`));
66
+ const handler = mod.default;
67
+ if (!handler?.buildState || !(handler.questions || handler.classify)) {
68
+ log(`[classifiers] skipped ${name}: needs buildState plus questions or classify`);
69
+ continue;
70
+ }
71
+ classifiers.push({ name, ...handler });
72
+ log(`[classifiers] discovered: ${name} (${handler.subject})`);
73
+ }
74
+ }
75
+ /**
76
+ * Register a classifier directly, bypassing directory discovery.
77
+ *
78
+ * Mirrors {@link registerLabelModule}: tests and embedders that build their own
79
+ * module graph have no `classifiers/` directory to read.
80
+ */
81
+ export function registerClassifier(name, module) {
82
+ classifiers.push({ name, ...module });
83
+ }
84
+ /** Clear all registered classifiers (for hot-reload). */
85
+ export function clearClassifiers() {
86
+ classifiers.length = 0;
87
+ }
88
+ /** Names of all loaded classifiers. */
89
+ export function listClassifiers() {
90
+ return classifiers.map((c) => c.name);
91
+ }
92
+ export function getClassifier(name) {
93
+ return classifiers.find((c) => c.name === name);
94
+ }
95
+ let systemOne = null;
96
+ export function configureSystemOne(config) {
97
+ systemOne = config;
98
+ }
99
+ export function isSystemOneConfigured() {
100
+ return systemOne !== null;
101
+ }
102
+ const RETRYABLE = new Set([408, 429, 500, 502, 503, 504]);
103
+ /**
104
+ * Ask the model one request's worth of questions about one state.
105
+ *
106
+ * Retries on 429 and 5xx, honoring `retry-after` when the response carries one.
107
+ * The caller's concurrency is what keeps us under the rate limit; this only
108
+ * recovers the requests that still slip past it.
109
+ */
110
+ export async function askSystemOne(state, questions, opts = {}) {
111
+ if (!systemOne)
112
+ throw new Error('System One is not configured — set `typesafe` in hatk.config.ts');
113
+ const attempts = opts.attempts ?? 4;
114
+ const body = JSON.stringify({ state, model: systemOne.model, questions });
115
+ let lastError = null;
116
+ for (let attempt = 0; attempt < attempts; attempt++) {
117
+ try {
118
+ const res = await fetch(systemOne.endpoint, {
119
+ method: 'POST',
120
+ headers: { authorization: `Bearer ${systemOne.apiKey}`, 'content-type': 'application/json' },
121
+ body,
122
+ signal: opts.signal,
123
+ });
124
+ if (!res.ok) {
125
+ if (!RETRYABLE.has(res.status) || attempt === attempts - 1) {
126
+ throw new Error(`System One ${res.status}: ${(await res.text()).slice(0, 200)}`);
127
+ }
128
+ const retryAfter = Number(res.headers.get('retry-after'));
129
+ const waitMs = Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter * 1000 : 2 ** attempt * 500;
130
+ await new Promise((r) => setTimeout(r, waitMs));
131
+ continue;
132
+ }
133
+ const json = (await res.json());
134
+ const answers = {};
135
+ for (const [key, a] of Object.entries(json.answers ?? {})) {
136
+ answers[key] = normalizeAnswer(a);
137
+ }
138
+ return { answers, model: json.model ?? systemOne.model, inputTokens: json.usage?.input_tokens ?? 0 };
139
+ }
140
+ catch (err) {
141
+ if (err?.name === 'AbortError')
142
+ throw err;
143
+ lastError = err;
144
+ if (attempt === attempts - 1)
145
+ break;
146
+ await new Promise((r) => setTimeout(r, 2 ** attempt * 500));
147
+ }
148
+ }
149
+ throw lastError ?? new Error('System One request failed');
150
+ }
151
+ /**
152
+ * Collapse any answer type to one 0–1 number so a mixed question set can share a
153
+ * threshold. A Noul is already a probability. A Choice reports the probability
154
+ * of the option it picked, and a Score its position across the levels — both
155
+ * keep the original answer alongside, because the number alone loses which
156
+ * option was chosen.
157
+ */
158
+ function normalizeAnswer(a) {
159
+ if (a?.type === 'noul')
160
+ return { score: a.noul ?? 0, type: 'noul' };
161
+ if (a?.type === 'choice') {
162
+ const choice = a.choice;
163
+ return { score: a.probabilities?.[choice] ?? 0, type: 'choice', choice, confidence: a.confidence };
164
+ }
165
+ if (a?.type === 'score') {
166
+ const levels = a.probabilities ? Object.keys(a.probabilities).length : 0;
167
+ const raw = typeof a.score === 'number' ? a.score : 0;
168
+ return {
169
+ score: levels > 1 ? raw / (levels - 1) : raw,
170
+ type: 'score',
171
+ choice: String(a.score),
172
+ confidence: a.confidence,
173
+ };
174
+ }
175
+ return { score: 0, type: a?.type ?? 'unknown' };
176
+ }
177
+ function thresholdFor(c, signal) {
178
+ if (c.threshold == null)
179
+ return null;
180
+ if (typeof c.threshold === 'number')
181
+ return c.threshold;
182
+ return c.threshold[signal] ?? null;
183
+ }
184
+ function labelFor(c, signal, score) {
185
+ if (typeof c.label === 'function')
186
+ return c.label(signal, score);
187
+ return c.label ?? 'spam';
188
+ }
189
+ const dbCtx = {
190
+ query: (sql, params) => querySQL(sql, params),
191
+ run: (sql, ...params) => runSQL(sql, params).then(() => undefined),
192
+ };
193
+ /** Every subject a classifier applies to, as `{uri, did, handle, value}`. */
194
+ async function enumerateSubjects(c) {
195
+ if (c.subject === 'account') {
196
+ const rows = (await querySQL(`SELECT did, handle FROM _repos WHERE status = 'active'`));
197
+ return rows.map((r) => ({ uri: r.did, did: r.did, handle: r.handle }));
198
+ }
199
+ const out = [];
200
+ for (const collection of c.collections ?? []) {
201
+ const schema = getSchema(collection);
202
+ if (!schema)
203
+ continue;
204
+ const rows = (await querySQL(`SELECT * FROM ${schema.tableName}`));
205
+ for (const row of rows) {
206
+ const value = {};
207
+ for (const col of schema.columns) {
208
+ let v = row[col.name];
209
+ if (v === null || v === undefined)
210
+ continue;
211
+ if (col.isJson && typeof v === 'string') {
212
+ try {
213
+ v = JSON.parse(v);
214
+ }
215
+ catch { }
216
+ }
217
+ value[col.originalName] = v;
218
+ }
219
+ out.push({ uri: row.uri, did: row.did, collection, value });
220
+ }
221
+ }
222
+ return out;
223
+ }
224
+ let current = null;
225
+ /** Progress of the scan in flight, or the last one to finish. */
226
+ export function getScanProgress() {
227
+ return current;
228
+ }
229
+ /**
230
+ * Score every subject a classifier applies to, storing results and filing a
231
+ * report for each crossing signal.
232
+ *
233
+ * Subjects whose state is unchanged since the last scan are skipped unless
234
+ * `force` is set, so a repeat scan costs only what actually moved.
235
+ */
236
+ export async function runScan(opts = {}) {
237
+ if (current?.running)
238
+ throw new Error('A scan is already running');
239
+ const selected = opts.classifier ? classifiers.filter((c) => c.name === opts.classifier) : classifiers;
240
+ if (!selected.length)
241
+ throw new Error(opts.classifier ? `No classifier named ${opts.classifier}` : 'No classifiers');
242
+ // Only the classifiers that actually ask a model need one configured. A
243
+ // host-local classifier runs with no API key at all.
244
+ if (selected.some((c) => !c.classify) && !isSystemOneConfigured())
245
+ throw new Error('System One is not configured');
246
+ const progress = {
247
+ scanned: 0,
248
+ skipped: 0,
249
+ scored: 0,
250
+ filed: 0,
251
+ errors: 0,
252
+ inputTokens: 0,
253
+ running: true,
254
+ startedAt: new Date().toISOString(),
255
+ };
256
+ current = progress;
257
+ try {
258
+ for (const c of selected) {
259
+ const subjects = await enumerateSubjects(c);
260
+ const seen = opts.force ? new Map() : await getClassificationFingerprints(c.name);
261
+ // The questions are part of what produced a score, so the fingerprint
262
+ // covers them as well as the state: rewording a classifier's criteria
263
+ // invalidates every score written under the old wording.
264
+ const questionsHash = createHash('sha256')
265
+ .update(JSON.stringify(c.questions ?? c.classify?.toString() ?? ''))
266
+ .digest('hex')
267
+ .slice(0, 16);
268
+ const queue = opts.limit ? subjects.slice(0, opts.limit) : subjects;
269
+ const concurrency = opts.concurrency ?? 8;
270
+ let cursor = 0;
271
+ const worker = async () => {
272
+ while (cursor < queue.length) {
273
+ if (opts.signal?.aborted)
274
+ return;
275
+ const subject = queue[cursor++];
276
+ progress.scanned++;
277
+ try {
278
+ const state = await c.buildState({ db: dbCtx, subject });
279
+ if (!state) {
280
+ progress.skipped++;
281
+ continue;
282
+ }
283
+ const fingerprint = createHash('sha256')
284
+ .update(questionsHash)
285
+ .update(JSON.stringify(state))
286
+ .digest('hex')
287
+ .slice(0, 32);
288
+ if (seen.get(subject.uri) === fingerprint) {
289
+ progress.skipped++;
290
+ continue;
291
+ }
292
+ let answers;
293
+ let model;
294
+ if (c.classify) {
295
+ const raw = await c.classify(state, { db: dbCtx, subject });
296
+ answers = Object.fromEntries(Object.entries(raw).map(([k, v]) => [k, typeof v === 'number' ? { score: v, type: 'local' } : v]));
297
+ model = `local:${c.name}`;
298
+ }
299
+ else {
300
+ const res = await askSystemOne(state, c.questions, { signal: opts.signal });
301
+ answers = res.answers;
302
+ model = res.model;
303
+ progress.inputTokens += res.inputTokens;
304
+ }
305
+ let topSignal = null;
306
+ let topScore = 0;
307
+ for (const [name, sig] of Object.entries(answers)) {
308
+ if (sig.score > topScore) {
309
+ topScore = sig.score;
310
+ topSignal = name;
311
+ }
312
+ }
313
+ await upsertClassification({
314
+ subjectUri: subject.uri,
315
+ subjectDid: subject.did,
316
+ classifier: c.name,
317
+ signals: answers,
318
+ state,
319
+ topSignal,
320
+ topScore,
321
+ fingerprint,
322
+ model,
323
+ });
324
+ progress.scored++;
325
+ // File on the highest-scoring signal that crosses its own threshold —
326
+ // a second report for the same subject would only split the review.
327
+ let crossing = null;
328
+ for (const [name, sig] of Object.entries(answers)) {
329
+ const t = thresholdFor(c, name);
330
+ if (t != null && sig.score >= t && (!crossing || sig.score > crossing.score)) {
331
+ crossing = { signal: name, score: sig.score };
332
+ }
333
+ }
334
+ if (crossing) {
335
+ const label = labelFor(c, crossing.signal, crossing.score);
336
+ if (!(await findOpenReport(subject.uri, label))) {
337
+ await insertReport({
338
+ subjectUri: subject.uri,
339
+ subjectDid: subject.did,
340
+ label,
341
+ reason: `${c.name}: ${crossing.signal} ${crossing.score.toFixed(2)}`,
342
+ reportedBy: `system:${c.name}`,
343
+ });
344
+ progress.filed++;
345
+ }
346
+ }
347
+ }
348
+ catch (err) {
349
+ if (err?.name === 'AbortError')
350
+ return;
351
+ progress.errors++;
352
+ emit('classifiers', 'scan_error', { classifier: c.name, subject: subject.uri, error: err.message });
353
+ }
354
+ }
355
+ };
356
+ await Promise.all(Array.from({ length: Math.min(concurrency, queue.length) }, worker));
357
+ }
358
+ }
359
+ catch (err) {
360
+ progress.error = err.message;
361
+ throw err;
362
+ }
363
+ finally {
364
+ progress.running = false;
365
+ progress.finishedAt = new Date().toISOString();
366
+ log(`[classifiers] scan: ${progress.scored} scored, ${progress.skipped} skipped, ` +
367
+ `${progress.filed} filed, ${progress.errors} errors, ${progress.inputTokens} tokens`);
368
+ }
369
+ return progress;
370
+ }
package/dist/cli.js CHANGED
@@ -443,6 +443,7 @@ else if (command === 'generate') {
443
443
  out += `export { defineSetup } from '@hatk/hatk/setup'\n`;
444
444
  out += `export { defineHook } from '@hatk/hatk/hooks'\n`;
445
445
  out += `export { defineLabel } from '@hatk/hatk/labels'\n`;
446
+ out += `export { defineClassifier } from '@hatk/hatk/classifiers'\n`;
446
447
  out += `export { defineOG } from '@hatk/hatk/opengraph'\n`;
447
448
  out += `export { defineRenderer } from '@hatk/hatk/renderer'\n`;
448
449
  out += `export type Ctx<K extends keyof XrpcSchema & keyof Registry> = XrpcContext<\n`;
package/dist/config.d.ts CHANGED
@@ -171,9 +171,21 @@ export interface HatkConfig {
171
171
  push: PushConfig | null;
172
172
  admins: string[];
173
173
  spaces: SpacesConfig | null;
174
+ typesafe: TypeSafeConfig | null;
175
+ }
176
+ /**
177
+ * System One access for the classifier system. Without it, classifiers load but
178
+ * no scan can run. The key is read from `TYPESAFE_API_KEY` in preference to the
179
+ * config file, so it need not be committed.
180
+ */
181
+ export interface TypeSafeConfig {
182
+ apiKey: string;
183
+ /** Model name or alias. Pin a version to keep tuned thresholds stable. */
184
+ model: string;
185
+ endpoint: string;
174
186
  }
175
187
  /** Input type for defineConfig — fields that have defaults are optional. */
176
- export type HatkConfigInput = Partial<Omit<HatkConfig, 'oauth' | 'backfill' | 'push' | 'cdn' | 'jetstream' | 'spaces'>> & {
188
+ export type HatkConfigInput = Partial<Omit<HatkConfig, 'oauth' | 'backfill' | 'push' | 'cdn' | 'jetstream' | 'spaces' | 'typesafe'>> & {
177
189
  cdn?: CdnConfig | null;
178
190
  oauth?: (Partial<OAuthConfig> & {
179
191
  clients: OAuthClientConfig[];
@@ -182,6 +194,7 @@ export type HatkConfigInput = Partial<Omit<HatkConfig, 'oauth' | 'backfill' | 'p
182
194
  push?: PushConfig | null;
183
195
  jetstream?: JetstreamConfig | null;
184
196
  spaces?: SpacesConfig | null;
197
+ typesafe?: Partial<TypeSafeConfig> | null;
185
198
  };
186
199
  /** Identity function that provides type inference for hatk config files. */
187
200
  export declare function defineConfig(config: HatkConfigInput): HatkConfigInput;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,WAAW,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,MAAM,CAAA;IAClB,QAAQ,EAAE,OAAO,GAAG,QAAQ,GAAG,MAAM,CAAA;IACrC,KAAK,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,CAAA;IACnC,cAAc,EAAE,MAAM,GAAG,MAAM,GAAG,QAAQ,CAAA;IAC1C,OAAO,CAAC,EAAE,WAAW,EAAE,CAAA;CACxB;AAED,MAAM,WAAW,iBAAiB;IAChC,SAAS,EAAE,MAAM,CAAA;IACjB,WAAW,EAAE,MAAM,CAAA;IACnB,aAAa,EAAE,MAAM,EAAE,CAAA;IACvB,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,OAAO,EAAE,iBAAiB,EAAE,CAAA;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB;;;;;;;;OAQG;IACH,iBAAiB,CAAC,EAAE,sBAAsB,EAAE,CAAA;CAC7C;AAED,MAAM,WAAW,sBAAsB;IACrC,0EAA0E;IAC1E,UAAU,EAAE,MAAM,CAAA;IAClB,MAAM,EAAE,MAAM,EAAE,CAAA;CACjB;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,aAAa;IAC5B,UAAU,EAAE,MAAM,CAAA;IAClB,wFAAwF;IACxF,KAAK,EAAE,MAAM,CAAA;CACd;AAED,MAAM,WAAW,cAAc;IAC7B,iBAAiB,C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AAE,iBAAiB,EAAE,CAAA;KAAE,CAAC,GAAG,IAAI,CAAA;IACxE,QAAQ,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,CAAA;IAClC,IAAI,CAAC,EAAE,UAAU,GAAG,IAAI,CAAA;IACxB,SAAS,CAAC,EAAE,eAAe,GAAG,IAAI,CAAA;IAClC,MAAM,CAAC,EAAE,YAAY,GAAG,IAAI,CAAA;IAC5B,QAAQ,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,IAAI,CAAA;CAC1C,CAAA;AAED,4EAA4E;AAC5E,wBAAgB,YAAY,CAAC,MAAM,EAAE,eAAe,GAAG,eAAe,CAErE;AAED,yEAAyE;AACzE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAElD;AAED,wBAAsB,UAAU,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CA6FxE"}
package/dist/config.js CHANGED
@@ -69,6 +69,17 @@ export async function loadConfig(configPath) {
69
69
  oauth: null,
70
70
  push: parsed.push || null,
71
71
  admins: env.ADMINS ? env.ADMINS.split(',').map((s) => s.trim()) : parsed.admins || [],
72
+ typesafe: (() => {
73
+ const raw = parsed.typesafe;
74
+ const apiKey = env.TYPESAFE_API_KEY || raw?.apiKey;
75
+ if (!apiKey)
76
+ return null;
77
+ return {
78
+ apiKey,
79
+ model: env.TYPESAFE_MODEL || raw?.model || 'jev-latest',
80
+ endpoint: env.TYPESAFE_ENDPOINT || raw?.endpoint || 'https://api.typesafe.ai/v1/systemone',
81
+ };
82
+ })(),
72
83
  spaces: parsed.spaces
73
84
  ? {
74
85
  types: parsed.spaces.types || [],