@chatwarden/core 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +124 -4
- package/dist/src/ai/case.d.ts +3 -3
- package/dist/src/ai/case.d.ts.map +1 -1
- package/dist/src/ai/case.js +1 -1
- package/dist/src/ai/case.js.map +1 -1
- package/dist/src/ai/hash.d.ts +3 -1
- package/dist/src/ai/hash.d.ts.map +1 -1
- package/dist/src/ai/hash.js +5 -2
- package/dist/src/ai/hash.js.map +1 -1
- package/dist/src/ai/prompt.d.ts +6 -2
- package/dist/src/ai/prompt.d.ts.map +1 -1
- package/dist/src/ai/prompt.js +11 -0
- package/dist/src/ai/prompt.js.map +1 -1
- package/dist/src/ai/service.d.ts +5 -1
- package/dist/src/ai/service.d.ts.map +1 -1
- package/dist/src/ai/service.js +2 -0
- package/dist/src/ai/service.js.map +1 -1
- package/dist/src/ai/types.d.ts +18 -2
- package/dist/src/ai/types.d.ts.map +1 -1
- package/dist/src/ai/types.js +2 -2
- package/dist/src/ai/types.js.map +1 -1
- package/dist/src/ai/worker.d.ts +3 -1
- package/dist/src/ai/worker.d.ts.map +1 -1
- package/dist/src/ai/worker.js +10 -3
- package/dist/src/ai/worker.js.map +1 -1
- package/dist/src/chat.d.ts +39 -1
- package/dist/src/chat.d.ts.map +1 -1
- package/dist/src/chat.js +85 -6
- package/dist/src/chat.js.map +1 -1
- package/dist/src/chatwarden.d.ts +68 -1
- package/dist/src/chatwarden.d.ts.map +1 -1
- package/dist/src/chatwarden.js +119 -5
- package/dist/src/chatwarden.js.map +1 -1
- package/dist/src/documents.d.ts +1 -1
- package/dist/src/documents.d.ts.map +1 -1
- package/dist/src/documents.js +3 -1
- package/dist/src/documents.js.map +1 -1
- package/dist/src/freeze.d.ts +3 -0
- package/dist/src/freeze.d.ts.map +1 -0
- package/dist/src/freeze.js +10 -0
- package/dist/src/freeze.js.map +1 -0
- package/dist/src/index.d.ts +13 -6
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +7 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/ladder.d.ts +28 -0
- package/dist/src/ladder.d.ts.map +1 -1
- package/dist/src/ladder.js +37 -1
- package/dist/src/ladder.js.map +1 -1
- package/dist/src/pace.d.ts +66 -0
- package/dist/src/pace.d.ts.map +1 -0
- package/dist/src/pace.js +111 -0
- package/dist/src/pace.js.map +1 -0
- package/dist/src/pacing.d.ts +63 -0
- package/dist/src/pacing.d.ts.map +1 -0
- package/dist/src/pacing.js +198 -0
- package/dist/src/pacing.js.map +1 -0
- package/dist/src/policy.d.ts +57 -1
- package/dist/src/policy.d.ts.map +1 -1
- package/dist/src/policy.js +67 -4
- package/dist/src/policy.js.map +1 -1
- package/dist/src/profile.d.ts +35 -8
- package/dist/src/profile.d.ts.map +1 -1
- package/dist/src/profile.js +57 -25
- package/dist/src/profile.js.map +1 -1
- package/dist/src/profileError.d.ts +10 -0
- package/dist/src/profileError.d.ts.map +1 -0
- package/dist/src/profileError.js +17 -0
- package/dist/src/profileError.js.map +1 -0
- package/dist/src/retention.d.ts +9 -0
- package/dist/src/retention.d.ts.map +1 -1
- package/dist/src/retention.js +10 -1
- package/dist/src/retention.js.map +1 -1
- package/dist/src/signalCounts.d.ts +37 -0
- package/dist/src/signalCounts.d.ts.map +1 -0
- package/dist/src/signalCounts.js +117 -0
- package/dist/src/signalCounts.js.map +1 -0
- package/dist/src/signalInert.d.ts +10 -0
- package/dist/src/signalInert.d.ts.map +1 -0
- package/dist/src/signalInert.js +28 -0
- package/dist/src/signalInert.js.map +1 -0
- package/dist/src/signalService.d.ts +101 -0
- package/dist/src/signalService.d.ts.map +1 -0
- package/dist/src/signalService.js +383 -0
- package/dist/src/signalService.js.map +1 -0
- package/dist/src/signals.d.ts +186 -0
- package/dist/src/signals.d.ts.map +1 -0
- package/dist/src/signals.js +361 -0
- package/dist/src/signals.js.map +1 -0
- package/dist/src/subjects.d.ts +2 -0
- package/dist/src/subjects.d.ts.map +1 -1
- package/dist/src/subjects.js +4 -0
- package/dist/src/subjects.js.map +1 -1
- package/dist/src/team.d.ts +27 -0
- package/dist/src/team.d.ts.map +1 -1
- package/dist/src/team.js +92 -4
- package/dist/src/team.js.map +1 -1
- package/dist/src/types.d.ts +56 -1
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/types.js.map +1 -1
- package/package.json +2 -2
- package/src/ai/case.ts +4 -4
- package/src/ai/hash.ts +5 -2
- package/src/ai/prompt.ts +16 -1
- package/src/ai/service.ts +8 -2
- package/src/ai/types.ts +19 -2
- package/src/ai/worker.ts +12 -4
- package/src/chat.ts +109 -8
- package/src/chatwarden.ts +184 -7
- package/src/documents.ts +5 -3
- package/src/freeze.ts +8 -0
- package/src/index.ts +41 -3
- package/src/ladder.ts +59 -1
- package/src/pace.ts +139 -0
- package/src/pacing.ts +242 -0
- package/src/policy.ts +107 -7
- package/src/profile.ts +83 -25
- package/src/profileError.ts +17 -0
- package/src/retention.ts +17 -1
- package/src/signalCounts.ts +133 -0
- package/src/signalInert.ts +31 -0
- package/src/signalService.ts +406 -0
- package/src/signals.ts +489 -0
- package/src/subjects.ts +5 -0
- package/src/team.ts +93 -5
- package/src/types.ts +65 -1
package/src/ai/service.ts
CHANGED
|
@@ -21,7 +21,7 @@ import { actionsOnTarget, AI_EXAMPLES_MIN, pickExampleLines } from './casebook.j
|
|
|
21
21
|
import type { AiOutcomeArgs } from './casebook.js';
|
|
22
22
|
import { aiPolicyText } from './prompt.js';
|
|
23
23
|
import { sha256Hex } from '../crypto.js';
|
|
24
|
-
import type { AIExampleInput, AIRead, ModerationAI } from './types.js';
|
|
24
|
+
import type { AIExampleInput, AIRead, AISignal, ModerationAI } from './types.js';
|
|
25
25
|
import { isFinalRow, Meter, runRead } from './worker.js';
|
|
26
26
|
import type { AiStore, ReadEnd, WorkerEnv } from './worker.js';
|
|
27
27
|
|
|
@@ -114,6 +114,8 @@ export interface AiReadView {
|
|
|
114
114
|
model: string | null;
|
|
115
115
|
/** When the read was started, epoch ms. */
|
|
116
116
|
at: number;
|
|
117
|
+
/** How many signal counts the read was shown (`feeds.ai`); absent when it was shown none. Only the number: the counts stay in the stored row. */
|
|
118
|
+
contextSignals?: number;
|
|
117
119
|
/** Level 2 only. */
|
|
118
120
|
recommendation: null | {
|
|
119
121
|
verdict: 'upheld' | 'noted' | 'no_action' | 'unclear';
|
|
@@ -317,6 +319,8 @@ export interface AiServiceDeps {
|
|
|
317
319
|
audit: (input: AuditRecordInput) => boolean;
|
|
318
320
|
/** How long the text of a casebook example is kept (`retention.aiExamplesMs`); 0 keeps none. */
|
|
319
321
|
exampleRetentionMs: () => number;
|
|
322
|
+
/** The signal counts about a person for the AI read (`feeds.ai`): empty with the feed off. Without it no signals are sent. */
|
|
323
|
+
signals?: (subject: SubjectId) => AISignal[];
|
|
320
324
|
}
|
|
321
325
|
|
|
322
326
|
const ruleOfText = (rule: string | null): number | 'uncovered' | null => (rule === null ? null : /^\d+$/.test(rule) ? Number(rule) : rule === 'uncovered' ? 'uncovered' : null);
|
|
@@ -764,7 +768,7 @@ export class AiService implements AiFacade {
|
|
|
764
768
|
return made;
|
|
765
769
|
}
|
|
766
770
|
|
|
767
|
-
private view(row: { id: string; read: AIRead | null; inputHash: string; model: string | null; createdAt: number }, report: ReportRecord, prepared: Prepared, level: number): AiReadView {
|
|
771
|
+
private view(row: { id: string; read: AIRead | null; inputHash: string; model: string | null; createdAt: number; signals?: readonly AISignal[] | null }, report: ReportRecord, prepared: Prepared, level: number): AiReadView {
|
|
768
772
|
const read = row.read as AIRead;
|
|
769
773
|
const rec = read.recommendation;
|
|
770
774
|
return {
|
|
@@ -778,6 +782,7 @@ export class AiService implements AiFacade {
|
|
|
778
782
|
injectionSuspected: read.injectionSuspected,
|
|
779
783
|
model: row.model,
|
|
780
784
|
at: row.createdAt,
|
|
785
|
+
...(row.signals === null || row.signals === undefined ? {} : { contextSignals: row.signals.length }),
|
|
781
786
|
recommendation: level >= 2 && rec !== null ? { verdict: rec.verdict, severity: rec.severity, rule: rec.rule, evidenceLineIds: [...rec.evidence], ...this.stepFor(report, prepared, rec) } : null,
|
|
782
787
|
};
|
|
783
788
|
}
|
|
@@ -823,6 +828,7 @@ export class AiService implements AiFacade {
|
|
|
823
828
|
closed: () => this.isClosed,
|
|
824
829
|
prepare: (report) => this.prepare(report),
|
|
825
830
|
examplesFor: (report, prepared) => this.examplesFor(report, prepared),
|
|
831
|
+
signalsFor: (report) => this.deps.signals?.(report.targetSubject) ?? [],
|
|
826
832
|
track: (c) => void this.controllers.add(c),
|
|
827
833
|
untrack: (c) => void this.controllers.delete(c),
|
|
828
834
|
auditRead: (reportId) => {
|
package/src/ai/types.ts
CHANGED
|
@@ -6,10 +6,22 @@ import type { ConductLevel } from '../types.js';
|
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* The prompt version. Bumped when the prompt or the output schema changes; part of the input hash, so a bump makes every stored
|
|
9
|
-
* read stale.
|
|
9
|
+
* read stale. 2 added the full-stop spacing line; 3 added the stable paragraph about signal counts.
|
|
10
10
|
* @experimental
|
|
11
11
|
*/
|
|
12
|
-
export const AI_PROMPT_VERSION =
|
|
12
|
+
export const AI_PROMPT_VERSION = 3;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* One signal count about the reported person (P1), as the model is shown it: the adopter's own short label, whether it counts for or
|
|
16
|
+
* against, how many DIFFERENT players, and over how many days. Nothing else about a signal ever leaves the process.
|
|
17
|
+
* @experimental
|
|
18
|
+
*/
|
|
19
|
+
export interface AISignal {
|
|
20
|
+
label: string;
|
|
21
|
+
polarity: 'negative' | 'positive';
|
|
22
|
+
distinct: number;
|
|
23
|
+
windowDays: number;
|
|
24
|
+
}
|
|
13
25
|
|
|
14
26
|
/**
|
|
15
27
|
* One speaker in a read: an alias (`P1` is the reported person, `P2` the reporter, the rest `P3...` in order of first appearance)
|
|
@@ -66,6 +78,11 @@ export interface AIReadInput {
|
|
|
66
78
|
standard: string;
|
|
67
79
|
/** Casebook, at most 2, pseudonymised. */
|
|
68
80
|
examples: AIExample[];
|
|
81
|
+
/**
|
|
82
|
+
* Counts of signals about P1 (`feeds.ai`), a snapshot taken when the read is made; absent with the feed off or nothing to say. Rendered as
|
|
83
|
+
* the last row of `prompt.variable`; the input hash leaves it out.
|
|
84
|
+
*/
|
|
85
|
+
signals?: AISignal[];
|
|
69
86
|
/** The same content rendered by core. An adapter should use it as is. */
|
|
70
87
|
prompt: { stable: string; variable: string; schema: object };
|
|
71
88
|
}
|
package/src/ai/worker.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { Breaker } from './breaker.js';
|
|
|
5
5
|
import type { Prepared } from './case.js';
|
|
6
6
|
import { usedExampleIds } from './prompt.js';
|
|
7
7
|
import { validateAIOutput } from './validate.js';
|
|
8
|
-
import type { AbortSignalLike, AIExampleInput, AIRead, AIReadInput, AIReadResult, AIUsage, ModerationAI } from './types.js';
|
|
8
|
+
import type { AbortSignalLike, AIExampleInput, AIRead, AIReadInput, AIReadResult, AISignal, AIUsage, ModerationAI } from './types.js';
|
|
9
9
|
|
|
10
10
|
// One read, start to finish (design section 4). The job reserves the right to call (one atomic write on the store, so two processes
|
|
11
11
|
// make one call), checks the budget, the breaker and the rate, calls the adapter under a deadline, validates the answer in core,
|
|
@@ -94,6 +94,8 @@ export interface WorkerEnv {
|
|
|
94
94
|
prepare(report: ReportRecord): Prepared;
|
|
95
95
|
/** Casebook examples for this case, newest first; empty when there are none, learning is off or something fails. */
|
|
96
96
|
examplesFor(report: ReportRecord, prepared: Prepared): AIExampleInput[];
|
|
97
|
+
/** The signal counts about the reported person (`feeds.ai`): a snapshot for this read; empty when the feed is off or nothing qualifies. Fenced by the caller. */
|
|
98
|
+
signalsFor(report: ReportRecord): AISignal[];
|
|
97
99
|
track(controller: Abortable): void;
|
|
98
100
|
untrack(controller: Abortable): void;
|
|
99
101
|
/** The `ai.read` audit row for a terminal outcome. Fenced by the caller. */
|
|
@@ -244,11 +246,17 @@ export async function runRead(env: WorkerEnv, reportId: string, opts?: { retake?
|
|
|
244
246
|
} catch (err) {
|
|
245
247
|
env.warn('ai.examples_failed', { error: errName(err) });
|
|
246
248
|
}
|
|
249
|
+
let signals: AISignal[] = [];
|
|
250
|
+
try {
|
|
251
|
+
signals = env.signalsFor(report);
|
|
252
|
+
} catch (err) {
|
|
253
|
+
env.warn('ai.signals_failed', { error: errName(err) });
|
|
254
|
+
}
|
|
247
255
|
let input: AIReadInput = prepared.input;
|
|
248
256
|
let exampleIds: string[] = [];
|
|
249
257
|
try {
|
|
250
|
-
if (examples.length > 0) {
|
|
251
|
-
input = prepared.build(examples);
|
|
258
|
+
if (examples.length > 0 || signals.length > 0) {
|
|
259
|
+
input = prepared.build(examples, signals);
|
|
252
260
|
exampleIds = usedExampleIds(examples);
|
|
253
261
|
}
|
|
254
262
|
} catch (err) {
|
|
@@ -327,7 +335,7 @@ export async function runRead(env: WorkerEnv, reportId: string, opts?: { retake?
|
|
|
327
335
|
recommendation: rec === null ? null : { ...rec, evidence: toIds(rec.evidence) },
|
|
328
336
|
};
|
|
329
337
|
env.breaker.success();
|
|
330
|
-
const stored = env.store.completeAiRead(id, lease, { ...usage, read, exampleIds });
|
|
338
|
+
const stored = env.store.completeAiRead(id, lease, { ...usage, read, exampleIds, signals: input.signals ?? [] });
|
|
331
339
|
if (!stored) {
|
|
332
340
|
env.warn('ai.read_superseded');
|
|
333
341
|
return NOTHING;
|
package/src/chat.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import type { EvidenceBuffer, RoomRoster } from './evidence.js';
|
|
2
|
-
import { safeWarn, ThrottledWarn } from './log.js';
|
|
2
|
+
import { errorClass, safeWarn, ThrottledWarn } from './log.js';
|
|
3
3
|
import type { MuteService } from './mutes.js';
|
|
4
4
|
import type { NoticeService } from './notices.js';
|
|
5
|
+
import type { PaceReason, ResolvedPace } from './pace.js';
|
|
6
|
+
import { createPacer } from './pacing.js';
|
|
7
|
+
import type { PaceKey, Pacer } from './pacing.js';
|
|
5
8
|
import type { Limits } from './limits.js';
|
|
6
9
|
import { slidingWindow } from './rateLimit.js';
|
|
7
10
|
import type { SlidingWindow } from './rateLimit.js';
|
|
@@ -28,11 +31,14 @@ import type {
|
|
|
28
31
|
// 2. the seat's occupant, then the gate hook
|
|
29
32
|
// 3. active restriction -> 'restricted' (chat, ban, or the in-memory automatic one)
|
|
30
33
|
// 4. length > 200 -> 'length'
|
|
31
|
-
// 5.
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
+
// 5. pacing, when configured -> 'slow_mode' | 'flood' | 'duplicate' (read only: a refusal writes nothing and
|
|
35
|
+
// spends nothing; it carries `retryAfterMs`)
|
|
36
|
+
// 6. rate, 3 per 5 s per room:seat -> 'rate' (spent even when the line is then blocked)
|
|
37
|
+
// 7. pacing commit -- only now does the line count toward the next pacing check
|
|
38
|
+
// 8. matcher hit -> buffered as blocked, one strike, maybe an automatic timeout, 'blocked'
|
|
39
|
+
// 9. profanity, by the profile's mode -> allow: untouched; star: masked; refuse: 'profanity' (never a strike,
|
|
34
40
|
// never buffered, never a notice: swearing is not a rule violation)
|
|
35
|
-
//
|
|
41
|
+
// 10. buffer the delivered line -> its lineId
|
|
36
42
|
// It never throws. Everything on this path reads in-memory state; the only store writes are the strike
|
|
37
43
|
// (inside StrikeService) and the automatic timeout, and a failure of either is logged and absorbed.
|
|
38
44
|
|
|
@@ -64,8 +70,12 @@ interface BlockedLine {
|
|
|
64
70
|
* automatic-filter rule (`autoRestrictRule`, CR 1 by default) for `blocked`, and for `restricted` the sanction's
|
|
65
71
|
* own rule (omitted when it is `'uncovered'` or unknown; the in-memory fallback cites the automatic-filter rule). `noticeId` is the player's notice that explains a restriction, when one
|
|
66
72
|
* exists. Never an identifier, a rule's private note or the matched term. `'empty'` means stay silent.
|
|
73
|
+
*
|
|
74
|
+
* `'slow_mode'`, `'flood'` and `'duplicate'` are pacing refusals and only ever appear once pacing is configured (`profile.pace`, a
|
|
75
|
+
* stored layer or `cw.rooms.setPace`). They carry `retryAfterMs` and nothing else: a pause, not a sanction, so no rule, notice or end
|
|
76
|
+
* time, and never the line.
|
|
67
77
|
*/
|
|
68
|
-
export type RefuseReason = 'empty' | 'length' | 'rate' | 'gate' | 'restricted' | 'blocked' | 'profanity';
|
|
78
|
+
export type RefuseReason = 'empty' | 'length' | 'rate' | 'gate' | 'restricted' | 'blocked' | 'profanity' | PaceReason;
|
|
69
79
|
|
|
70
80
|
export type ChatResult =
|
|
71
81
|
| { deliver: { lineId: string; text: string } }
|
|
@@ -76,6 +86,8 @@ export type ChatResult =
|
|
|
76
86
|
byModerator?: boolean;
|
|
77
87
|
rule?: number;
|
|
78
88
|
noticeId?: string;
|
|
89
|
+
/** Present for `slow_mode`, `flood` and `duplicate`: when the same player may try again, in ms from now (a whole number, at least 1). @experimental */
|
|
90
|
+
retryAfterMs?: number;
|
|
79
91
|
};
|
|
80
92
|
};
|
|
81
93
|
|
|
@@ -136,13 +148,32 @@ export interface ChatServiceDeps {
|
|
|
136
148
|
* `roomId:seatId`. The service trusts the numbers; the facade validates them.
|
|
137
149
|
*/
|
|
138
150
|
limits?: { maxLength: Limits['chatMaxLength']; rate: Limits['chatRate'] };
|
|
151
|
+
/**
|
|
152
|
+
* Pacing: slow mode, a burst limit and repeat refusal. `settings` is read on every line (so a saved change applies at once) and
|
|
153
|
+
* answers every check off for a room that is not paced: such a line builds no key and makes no `canonical` call, and keeps no state.
|
|
154
|
+
* `canonical` folds a merged subject into the person the state is kept under. `onFlood` is told once per burst window when a known person trips the burst
|
|
155
|
+
* limit; a throw from it is logged by class and absorbed. Without `pace` nothing is paced.
|
|
156
|
+
* @experimental
|
|
157
|
+
*/
|
|
158
|
+
pace?: {
|
|
159
|
+
settings: (roomId: string) => ResolvedPace;
|
|
160
|
+
canonical: (subject: SubjectId) => SubjectId;
|
|
161
|
+
onFlood?: (info: { roomId: string; subject: SubjectId }) => void;
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** What pacing says about a line: a refusal, or the key to commit under; neither when nothing is paced. */
|
|
166
|
+
interface Paced {
|
|
167
|
+
refusal: ChatResult | null;
|
|
168
|
+
key: PaceKey | null;
|
|
139
169
|
}
|
|
170
|
+
const NOT_PACED: Paced = Object.freeze({ refusal: null, key: null });
|
|
140
171
|
|
|
141
172
|
const errName = (err: unknown): string => (err instanceof Error ? err.name : typeof err);
|
|
142
173
|
|
|
143
174
|
const refuse = (
|
|
144
175
|
reason: RefuseReason,
|
|
145
|
-
extra?: { until?: number | null; byModerator?: boolean; rule?: number; noticeId?: string },
|
|
176
|
+
extra?: { until?: number | null; byModerator?: boolean; rule?: number; noticeId?: string; retryAfterMs?: number },
|
|
146
177
|
): ChatResult => ({ refuse: extra === undefined ? { reason } : { reason, ...extra } });
|
|
147
178
|
|
|
148
179
|
interface Restriction {
|
|
@@ -203,6 +234,10 @@ export class ChatService {
|
|
|
203
234
|
private readonly rate: SlidingWindow;
|
|
204
235
|
/** The typing lookup runs at keystroke rate: its failure line is limited to one a minute. */
|
|
205
236
|
private readonly typingWarn: ThrottledWarn;
|
|
237
|
+
/** Pacing runs on every line: a failure of it is limited to one log line a minute. */
|
|
238
|
+
private readonly paceWarn: ThrottledWarn;
|
|
239
|
+
private readonly pacer: Pacer | undefined;
|
|
240
|
+
private readonly pace: ChatServiceDeps['pace'];
|
|
206
241
|
|
|
207
242
|
/**
|
|
208
243
|
* Automatic restrictions that could not be stored (no subject to put a row on, or the write failed), by
|
|
@@ -229,6 +264,9 @@ export class ChatService {
|
|
|
229
264
|
this.onAutoRestricted = deps.onAutoRestricted;
|
|
230
265
|
this.logger = deps.logger;
|
|
231
266
|
this.typingWarn = new ThrottledWarn(deps.logger, deps.clock);
|
|
267
|
+
this.paceWarn = new ThrottledWarn(deps.logger, deps.clock);
|
|
268
|
+
this.pace = deps.pace;
|
|
269
|
+
this.pacer = deps.pace === undefined ? undefined : createPacer({ clock: deps.clock, settings: deps.pace.settings });
|
|
232
270
|
this.notices = deps.notices;
|
|
233
271
|
this.autoRestrictRule = deps.autoRestrictRule ?? DEFAULT_AUTO_RESTRICT_RULE;
|
|
234
272
|
this.maxLength = deps.limits?.maxLength ?? MAX_LEN;
|
|
@@ -309,6 +347,11 @@ export class ChatService {
|
|
|
309
347
|
}
|
|
310
348
|
}
|
|
311
349
|
|
|
350
|
+
/** Forget a room's pacing state (the room is closing). */
|
|
351
|
+
dropPaceRoom(roomId: string): void {
|
|
352
|
+
this.pacer?.dropRoom(roomId);
|
|
353
|
+
}
|
|
354
|
+
|
|
312
355
|
// --- internals -----------------------------------------------------------
|
|
313
356
|
|
|
314
357
|
private run(roomId: string, seatId: string, text: string, opts?: { audience?: string[] }): ChatResult {
|
|
@@ -335,9 +378,20 @@ export class ChatService {
|
|
|
335
378
|
}
|
|
336
379
|
|
|
337
380
|
if (trimmed.length > this.maxLength) return refuse('length');
|
|
381
|
+
|
|
382
|
+
// Pacing asks before `rate` so the specific, retryable message wins over the blunt one; it only reads, so a refusal spends nothing.
|
|
383
|
+
// With every check off it builds nothing (no key, no canonical lookup) and there is nothing to commit.
|
|
384
|
+
const paced = this.pacer === undefined ? NOT_PACED : this.paceCheck(this.pacer, roomId, seatId, subject, trimmed);
|
|
385
|
+
if (paced.refusal !== null) return paced.refusal;
|
|
338
386
|
// Spent even when the line is then blocked, so a flood of slurs is throttled like any flood and cannot
|
|
339
387
|
// probe the term list faster than ordinary chat.
|
|
340
|
-
if (!this.rate.check(rateKey))
|
|
388
|
+
if (!this.rate.check(rateKey)) {
|
|
389
|
+
// The line passed pacing but never commits: the pacer must not keep its text.
|
|
390
|
+
this.paceDiscard(this.pacer);
|
|
391
|
+
return refuse('rate');
|
|
392
|
+
}
|
|
393
|
+
// Past `rate` the line has happened as far as pacing is concerned (a blocked or profane line has spent its slot too).
|
|
394
|
+
if (this.pacer !== undefined && paced.key !== null) this.paceCommit(this.pacer, paced.key, trimmed);
|
|
341
395
|
|
|
342
396
|
const audience = opts?.audience === undefined ? null : [...opts.audience];
|
|
343
397
|
|
|
@@ -389,6 +443,53 @@ export class ChatService {
|
|
|
389
443
|
return { deliver: { lineId, text: delivered } };
|
|
390
444
|
}
|
|
391
445
|
|
|
446
|
+
/**
|
|
447
|
+
* Ask pacing about a line: a refusal to return, or the key to commit under once `rate` passes. Everything that can throw is in the
|
|
448
|
+
* fence (the settings, the canonical lookup, the pacer), and it fails open: a broken pacer must not silence chat, so the line goes on
|
|
449
|
+
* with nothing to commit and the class is logged (at most once a minute).
|
|
450
|
+
*/
|
|
451
|
+
private paceCheck(pacer: Pacer, roomId: string, seatId: string, subject: SubjectId | null, text: string): Paced {
|
|
452
|
+
try {
|
|
453
|
+
if (!pacer.active(roomId)) return NOT_PACED;
|
|
454
|
+
const key: PaceKey = { roomId, who: subject === null ? `seat:${seatId}` : (this.pace?.canonical(subject) ?? subject) };
|
|
455
|
+
const verdict = pacer.check(key, text);
|
|
456
|
+
if (verdict.ok) return { refusal: null, key };
|
|
457
|
+
if (verdict.reason === 'flood' && verdict.signalFlood && subject !== null) this.tellFlood(roomId, key.who);
|
|
458
|
+
return { refusal: refuse(verdict.reason, { retryAfterMs: verdict.retryAfterMs }), key: null };
|
|
459
|
+
} catch (err) {
|
|
460
|
+
this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) });
|
|
461
|
+
return NOT_PACED;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
private paceDiscard(pacer: Pacer | undefined): void {
|
|
466
|
+
try {
|
|
467
|
+
pacer?.discard();
|
|
468
|
+
} catch (err) {
|
|
469
|
+
this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
private paceCommit(pacer: Pacer, key: PaceKey, text: string): void {
|
|
474
|
+
try {
|
|
475
|
+
pacer.commit(key, text);
|
|
476
|
+
} catch (err) {
|
|
477
|
+
this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) });
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Tell the facade a known person tripped the burst limit. Never changes the verdict: a throw or a rejection is logged by class and dropped. */
|
|
482
|
+
private tellFlood(roomId: string, subject: SubjectId): void {
|
|
483
|
+
const onFlood = this.pace?.onFlood;
|
|
484
|
+
if (onFlood === undefined) return;
|
|
485
|
+
try {
|
|
486
|
+
const out: unknown = onFlood({ roomId, subject });
|
|
487
|
+
if (isThenable(out)) out.then(undefined, (err: unknown) => this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) }));
|
|
488
|
+
} catch (err) {
|
|
489
|
+
this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) });
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
392
493
|
/** The gate hook; a throw is a refusal (it is access control, so it fails closed). */
|
|
393
494
|
private gateAllows(roomId: string, subject: SubjectId | null): boolean {
|
|
394
495
|
if (this.gate === undefined) return true;
|
package/src/chatwarden.ts
CHANGED
|
@@ -23,7 +23,13 @@ import { dismissMany } from './dismissMany.js';
|
|
|
23
23
|
import type { DismissManyInput, DismissManyResult } from './dismissMany.js';
|
|
24
24
|
import { PolicyService } from './policy.js';
|
|
25
25
|
import type { PolicyPreview, PolicySaveContext, PolicySaveResult, PolicyState } from './policy.js';
|
|
26
|
-
import {
|
|
26
|
+
import { checkPace, mergePace } from './pace.js';
|
|
27
|
+
import { createInertSignals } from './signalInert.js';
|
|
28
|
+
import type { SignalRuntime } from './signalService.js';
|
|
29
|
+
import { BUILTIN_SIGNAL_KINDS, checkSignalFeeds } from './signals.js';
|
|
30
|
+
import type { SignalCount, SignalInput, SignalKindView } from './signals.js';
|
|
31
|
+
import type { PaceSettings, ResolvedPace } from './pace.js';
|
|
32
|
+
import { ProfileError, resolveProfile } from './profile.js';
|
|
27
33
|
import type { ModerationProfile, PolicyLayer, PolicySection, PresetName, ProfanityConfig, ProfileOverrides, ResolvedProfile } from './profile.js';
|
|
28
34
|
import { MuteService } from './mutes.js';
|
|
29
35
|
import { NoticeService } from './notices.js';
|
|
@@ -204,6 +210,22 @@ export interface ChatwardenOptions {
|
|
|
204
210
|
* @experimental
|
|
205
211
|
*/
|
|
206
212
|
ai?: AiOptions;
|
|
213
|
+
/**
|
|
214
|
+
* Signals: what the game records about a player. The kinds, the guards and the feeds are in the profile (`profile.signals`); this
|
|
215
|
+
* holds the one hook the profile cannot. Signals need a store with the three signal methods (SQLite has them; the in-memory store has them
|
|
216
|
+
* through `withMemorySignals`): declaring kinds or feeds over a store without them is refused at creation, and the kit loads its signal
|
|
217
|
+
* service only for a store that has them.
|
|
218
|
+
* @experimental
|
|
219
|
+
*/
|
|
220
|
+
signals?: {
|
|
221
|
+
/**
|
|
222
|
+
* How old is this player's account, in days, from the account ids the kit has for them (the strings your game gave it as
|
|
223
|
+
* `RawWho.accountId`)? Return null or undefined when unknown. Called synchronously at record time for `by`, and only for a player with
|
|
224
|
+
* at least one account id; a throw reads as unknown (logged by error class). Without this hook the new-account guard is not used,
|
|
225
|
+
* whatever the profile says.
|
|
226
|
+
*/
|
|
227
|
+
accountAgeDays?: (accountIds: readonly string[]) => number | null | undefined;
|
|
228
|
+
};
|
|
207
229
|
}
|
|
208
230
|
|
|
209
231
|
/** The moderation kit as an adopter uses it. Nothing here returns an identifier meant for a player. */
|
|
@@ -226,6 +248,17 @@ export interface Chatwarden {
|
|
|
226
248
|
* Carries subject ids: staff channels only, never send to a player.
|
|
227
249
|
*/
|
|
228
250
|
subjectAt(roomId: string, seatId: string): SubjectId | null;
|
|
251
|
+
/**
|
|
252
|
+
* Pace this room differently from the defaults until it closes. Per field: absent inherits, `null` turns that check off, a value sets
|
|
253
|
+
* it. `null` instead of an object removes the override (`{}` is the same: nothing to override). A second call replaces the room's earlier
|
|
254
|
+
* override whole; it is not merged into it. The object is read once, so changing it afterwards changes nothing. Throws `ProfileError` for an invalid
|
|
255
|
+
* value (a setup mistake, not a hot-path call), and changes nothing when it does. In memory, this process only: `rooms.close(roomId)`
|
|
256
|
+
* drops it, and a game that runs several processes calls it in each process that serves the room. The override sits on top of the
|
|
257
|
+
* stored layer, which sits on top of the profile in code. @experimental
|
|
258
|
+
*/
|
|
259
|
+
setPace(roomId: string, pace: PaceSettings | null): void;
|
|
260
|
+
/** The pace in force for the room: the profile's (code, then the stored layer) with the room's override applied. Every field filled, `null` is off. @experimental */
|
|
261
|
+
pace(roomId: string): ResolvedPace;
|
|
229
262
|
};
|
|
230
263
|
chat: {
|
|
231
264
|
accept(roomId: string, seatId: string, text: string, opts?: { audience?: string[] }): ChatResult;
|
|
@@ -382,9 +415,14 @@ export interface Chatwarden {
|
|
|
382
415
|
* (see `cw.reports.reporterAccuracy`) and none of which has waited 24 hours (`REPORTER_RANK_LAPSE_MS`) is served after the ordinary
|
|
383
416
|
* ones, oldest first; it is never skipped, so a queue holding only such cases still serves them. One ordinary reporter, or no
|
|
384
417
|
* accuracy data (a store without `reporterOutcomes`), keeps a case normal. A non-boolean value is a `RangeError`.
|
|
385
|
-
*
|
|
418
|
+
*
|
|
419
|
+
* With `signalBoost` (default false: behaviour unchanged; use it when the queue signal feed, `feeds.queue`, is on), the scan stays oldest
|
|
420
|
+
* first but a case is claimed only when it is overdue (its oldest open report has waited 24 hours) or boosted (the person meets the
|
|
421
|
+
* feed's threshold); the first such case wins. If the queue, or the first 200 people, hold neither, the oldest free case is claimed as
|
|
422
|
+
* usual, so nothing is ever left out. A boosted case is never ranked down. A non-boolean value is a `RangeError`.
|
|
423
|
+
* @experimental (the `rankDownHabitual` and `signalBoost` filters)
|
|
386
424
|
*/
|
|
387
|
-
next(actor: string, filter?: { category?: ReportCategory; reason?: string | null; rankDownHabitual?: boolean }): NextCase | null;
|
|
425
|
+
next(actor: string, filter?: { category?: ReportCategory; reason?: string | null; rankDownHabitual?: boolean; signalBoost?: boolean }): NextCase | null;
|
|
388
426
|
/**
|
|
389
427
|
* `actor` has the person's case open now. A hint for 30 seconds (`VIEWING_TTL_MS`), in this process's memory only.
|
|
390
428
|
* Only a person with an open report is tracked (false otherwise, nothing recorded); one actor keeps at most 20 cases
|
|
@@ -477,6 +515,35 @@ export interface Chatwarden {
|
|
|
477
515
|
* @experimental
|
|
478
516
|
*/
|
|
479
517
|
ai: AiFacade;
|
|
518
|
+
/**
|
|
519
|
+
* Signals: what the game records about a player (muted by others, kicked, left mid-game), counted by distinct source. A signal never
|
|
520
|
+
* acts: it is read only where a profile rule says so (the Person page record, the ladder suggestion, the AI read, the queue order).
|
|
521
|
+
* Staff-side data: never send any of this to a player.
|
|
522
|
+
* @experimental
|
|
523
|
+
*/
|
|
524
|
+
signals: {
|
|
525
|
+
/**
|
|
526
|
+
* Record one signal. Synchronous, fenced, never throws: it returns false (and logs `chatwarden.signal_refused` with a reason code,
|
|
527
|
+
* at most once a minute) for an undeclared or malformed kind, a party it cannot resolve (an unknown subject id, or a `RawWho` the kit
|
|
528
|
+
* has never seen: nobody is created), `subject` equal to `by` (also across a merge), a time out of range, the per-source cap, a
|
|
529
|
+
* store without signals, or a store failure. True means a row was written. One small write: record events, not every chat line.
|
|
530
|
+
*/
|
|
531
|
+
record(input: SignalInput): boolean;
|
|
532
|
+
/**
|
|
533
|
+
* The counts for a person now: one entry per declared kind that has at least one source in the window (default 30 days, held to
|
|
534
|
+
* the retention and to 90), aliases folded. Never throws; a store failure reads []. Never send to a player.
|
|
535
|
+
*/
|
|
536
|
+
counts(subject: SubjectId, opts?: { windowDays?: number; kinds?: readonly string[] }): SignalCount[];
|
|
537
|
+
/** The declared kinds, built-ins included, for building a form. */
|
|
538
|
+
kinds(): SignalKindView[];
|
|
539
|
+
/**
|
|
540
|
+
* Which of these people meet the queue feed (`feeds.queue`), as canonical ids, from one grouped read. Empty, with no store read,
|
|
541
|
+
* when the feed is off. Never throws.
|
|
542
|
+
*/
|
|
543
|
+
boosted(people: readonly SubjectId[]): Set<SubjectId>;
|
|
544
|
+
/** The lines the Person page record shows (`feeds.record`: its kinds and window). `[]` when the feed is off. Never throws. */
|
|
545
|
+
forRecord(subject: SubjectId): SignalCount[];
|
|
546
|
+
};
|
|
480
547
|
/** The registry in use (the one given, or the starter rules for the profile). Retired rules stay listed. */
|
|
481
548
|
rules: CommunityRules;
|
|
482
549
|
/**
|
|
@@ -642,6 +709,9 @@ export interface Chatwarden {
|
|
|
642
709
|
* The profanity filter for the profile, or undefined. Mode `allow` builds nothing; a ready filter wins over the
|
|
643
710
|
* package; a package that throws fails creation and one that returns a non-filter is a TypeError.
|
|
644
711
|
*/
|
|
712
|
+
/** Does the store keep signals (all three optional methods)? */
|
|
713
|
+
const storeKeepsSignals = (s: Store): boolean => typeof s.insertSignal === 'function' && typeof s.listSignalSources === 'function' && typeof s.purgeSignals === 'function';
|
|
714
|
+
|
|
645
715
|
function buildProfanityFilter(opts: ChatwardenOptions, config: ProfanityConfig): ProfanityFilter | undefined {
|
|
646
716
|
if (config.mode === 'allow') return undefined;
|
|
647
717
|
if (opts.profanity !== undefined) return opts.profanity;
|
|
@@ -682,6 +752,28 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
682
752
|
badFaithMs: givenRetention.badFaithMs ?? Math.max(RETENTION_DEFAULTS.badFaithMs, limits.reports.suspendWindowMs),
|
|
683
753
|
};
|
|
684
754
|
checkRetentionFloors(retentionPolicy, limits.reports.suspendWindowMs);
|
|
755
|
+
// A feed window longer than the signal retention could never be met (rows older than that are deleted): refuse it in code too.
|
|
756
|
+
checkSignalFeeds(baseProfile.signals.feeds, baseProfile.signals.kinds, { signalsMs: retentionPolicy.signalsMs ?? RETENTION_DEFAULTS.signalsMs }, 'profile.signals.feeds');
|
|
757
|
+
// Declaring kinds or feeds is an explicit opt-in that a store without the signal methods would silently turn into nothing: refuse it.
|
|
758
|
+
// (Only the built-in `flood_triggered` and pacing: nothing declared, so the kit starts and skips that record, logged once.)
|
|
759
|
+
const declaresSignals =
|
|
760
|
+
Object.keys(baseProfile.signals.feeds).length > 0 ||
|
|
761
|
+
Object.keys(baseProfile.signals.kinds).some((id) => {
|
|
762
|
+
const k = baseProfile.signals.kinds[id]!;
|
|
763
|
+
const builtin = Object.hasOwn(BUILTIN_SIGNAL_KINDS, id) ? BUILTIN_SIGNAL_KINDS[id as 'flood_triggered'] : undefined;
|
|
764
|
+
return builtin === undefined || builtin.label !== k.label || k.weight !== 1;
|
|
765
|
+
});
|
|
766
|
+
if (declaresSignals && !storeKeepsSignals(opts.store)) {
|
|
767
|
+
throw new Error(
|
|
768
|
+
'createChatwarden: the profile declares signal kinds or feeds, but the store has no signal methods (insertSignal, listSignalSources, purgeSignals); use the memory or SQLite store, or leave "signals" out of the profile',
|
|
769
|
+
);
|
|
770
|
+
}
|
|
771
|
+
if (opts.signals?.accountAgeDays !== undefined && typeof opts.signals.accountAgeDays !== 'function') {
|
|
772
|
+
throw new TypeError('createChatwarden: signals.accountAgeDays must be a function');
|
|
773
|
+
}
|
|
774
|
+
// The signal service (and the counting under it) is loaded only for a store that can keep signals, so a bundler can leave it out of a build
|
|
775
|
+
// that never has one (the in-memory store has the methods only through `withMemorySignals`). Without it `cw.signals` is inert.
|
|
776
|
+
const signalModule = storeKeepsSignals(opts.store) ? await import('./signalService.js') : undefined;
|
|
685
777
|
const purgeEveryMs = everyMs ?? DEFAULT_PURGE_EVERY_MS;
|
|
686
778
|
if (opts.retention !== false && (!Number.isFinite(purgeEveryMs) || purgeEveryMs <= 0)) {
|
|
687
779
|
throw new Error('createChatwarden: retention.everyMs must be a positive finite number');
|
|
@@ -718,7 +810,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
718
810
|
await mutes.load();
|
|
719
811
|
await strikes.load();
|
|
720
812
|
// The stored edits to the profile. Read last, so a store that fails here has not left anything half built.
|
|
721
|
-
const policy = new PolicyService({ store, clock, logger, base: baseProfile });
|
|
813
|
+
const policy = new PolicyService({ store, clock, logger, base: baseProfile, signalsMs: () => retentionPolicy.signalsMs ?? RETENTION_DEFAULTS.signalsMs, chatRate: limits.chatRate });
|
|
722
814
|
policy.load();
|
|
723
815
|
|
|
724
816
|
// ONE notice service for the whole kit: chat (the automatic timeout), the doors (the refusal's pointer) and
|
|
@@ -734,6 +826,30 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
734
826
|
notify: typeof platformNotify === 'function' ? (who, event) => platformNotify.call(platform, who, event) : undefined,
|
|
735
827
|
});
|
|
736
828
|
|
|
829
|
+
/** The signal service, set once `personOf` exists (the chat path above it only calls it later, never during creation). */
|
|
830
|
+
const signalRef: { service?: SignalRuntime } = {};
|
|
831
|
+
|
|
832
|
+
// Room overrides of the pace: this process only, dropped by `rooms.close`. Each is the validated sparse override as given (a field
|
|
833
|
+
// left out inherits), kept as a frozen copy so the caller's object cannot change it later.
|
|
834
|
+
const paceOverrides = new Map<string, Readonly<PaceSettings>>();
|
|
835
|
+
/** The merged pace of a room with an override, with the profile pace it was merged onto: valid while that object is the one in force. */
|
|
836
|
+
const paceMerged = new Map<string, { base: ResolvedPace; merged: ResolvedPace }>();
|
|
837
|
+
/**
|
|
838
|
+
* The pace in force for a room: the override over the profile's (the layer over the code). A room without an override gets the
|
|
839
|
+
* profile's own object; one with an override is merged once per change of the profile's pace (it is a new object on every layer
|
|
840
|
+
* change), not once per line.
|
|
841
|
+
*/
|
|
842
|
+
const paceOf = (roomId: string): ResolvedPace => {
|
|
843
|
+
const base = policy.profileNow().pace;
|
|
844
|
+
const over = paceOverrides.get(roomId);
|
|
845
|
+
if (over === undefined) return base;
|
|
846
|
+
const cached = paceMerged.get(roomId);
|
|
847
|
+
if (cached !== undefined && cached.base === base) return cached.merged;
|
|
848
|
+
const merged = mergePace(base, over);
|
|
849
|
+
paceMerged.set(roomId, { base, merged });
|
|
850
|
+
return merged;
|
|
851
|
+
};
|
|
852
|
+
|
|
737
853
|
const chat = new ChatService({
|
|
738
854
|
roster,
|
|
739
855
|
buffer,
|
|
@@ -755,6 +871,21 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
755
871
|
notices,
|
|
756
872
|
autoRestrictRule,
|
|
757
873
|
limits: { maxLength: limits.chatMaxLength, rate: limits.chatRate },
|
|
874
|
+
pace: {
|
|
875
|
+
settings: paceOf,
|
|
876
|
+
canonical: (subject) => subjects.canonical(subject),
|
|
877
|
+
// A flood trip records the built-in kind, deferred so the verdict is returned first. `flood` never throws and logs its own
|
|
878
|
+
// refusals; a room id the signal rules do not accept is left out (the trip is then a day source, not dropped).
|
|
879
|
+
onFlood: ({ roomId, subject }) => {
|
|
880
|
+
queueMicrotask(() => {
|
|
881
|
+
try {
|
|
882
|
+
signalRef.service?.flood(subject, roomId);
|
|
883
|
+
} catch (err) {
|
|
884
|
+
safeWarn(logger, 'chatwarden.pace_failed', { error: err instanceof Error ? err.name : typeof err });
|
|
885
|
+
}
|
|
886
|
+
});
|
|
887
|
+
},
|
|
888
|
+
},
|
|
758
889
|
});
|
|
759
890
|
const reports = new ReportService({
|
|
760
891
|
roster,
|
|
@@ -788,6 +919,17 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
788
919
|
const ids = hashWho(hasher, who);
|
|
789
920
|
return subjects.lookup({ clientKey: ids.clientKey, accountId: ids.accountId, ipHash: null });
|
|
790
921
|
};
|
|
922
|
+
signalRef.service = signalModule === undefined ? createInertSignals(logger, () => policy.profileNow().signals) : new signalModule.SignalService({
|
|
923
|
+
store,
|
|
924
|
+
clock,
|
|
925
|
+
logger,
|
|
926
|
+
subjects,
|
|
927
|
+
personOf,
|
|
928
|
+
settings: () => policy.profileNow().signals,
|
|
929
|
+
signalsMs: () => retentionPolicy.signalsMs ?? RETENTION_DEFAULTS.signalsMs,
|
|
930
|
+
...(opts.signals?.accountAgeDays === undefined ? {} : { accountAgeDays: opts.signals.accountAgeDays }),
|
|
931
|
+
});
|
|
932
|
+
const signals = signalRef.service;
|
|
791
933
|
/** A player-facing read: a store failure is logged (class only) and reads as `fallback`. */
|
|
792
934
|
const forPlayer = <T>(who: RawWho, fallback: T, read: (subject: SubjectId) => T): T => {
|
|
793
935
|
try {
|
|
@@ -892,6 +1034,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
892
1034
|
clock,
|
|
893
1035
|
reasons: () => policy.profileNow().reporting.reasons,
|
|
894
1036
|
accuracy: (people) => reporterAccuracyFor(store, subjects, people, clock.now()),
|
|
1037
|
+
boosted: (people) => signals.boosted(people),
|
|
895
1038
|
});
|
|
896
1039
|
const reasonBook = new ReasonBook(store);
|
|
897
1040
|
|
|
@@ -910,12 +1053,21 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
910
1053
|
subscribe: bus.on,
|
|
911
1054
|
audit: (input) => audit.record(input),
|
|
912
1055
|
exampleRetentionMs: () => retentionPolicy.aiExamplesMs ?? RETENTION_DEFAULTS.aiExamplesMs,
|
|
1056
|
+
// The counts about the reported person the feed allows (`feeds.ai`), as label, polarity, distinct and window: nothing else leaves.
|
|
1057
|
+
signals: (subject) => signals.forAi(subject).map((c) => ({ label: c.label, polarity: c.polarity, distinct: c.distinct, windowDays: c.windowDays })),
|
|
913
1058
|
});
|
|
914
1059
|
aiRef.service = aiService;
|
|
915
1060
|
const ai: AiFacade = aiService ?? createInertAi();
|
|
916
1061
|
|
|
917
1062
|
return {
|
|
918
1063
|
ai,
|
|
1064
|
+
signals: {
|
|
1065
|
+
record: (input) => signals.record(input),
|
|
1066
|
+
counts: (subject, o) => signals.counts(subject, o),
|
|
1067
|
+
kinds: () => signals.kinds(),
|
|
1068
|
+
boosted: (people) => signals.boosted(people),
|
|
1069
|
+
forRecord: (subject) => signals.forRecord(subject),
|
|
1070
|
+
},
|
|
919
1071
|
rooms: {
|
|
920
1072
|
seat,
|
|
921
1073
|
seatConnection: (roomId, seatId, ctx, handle, tags) => {
|
|
@@ -927,11 +1079,29 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
927
1079
|
close: (roomId) => {
|
|
928
1080
|
roster.close(roomId);
|
|
929
1081
|
buffer.drop(roomId);
|
|
1082
|
+
paceOverrides.delete(roomId);
|
|
1083
|
+
paceMerged.delete(roomId);
|
|
1084
|
+
chat.dropPaceRoom(roomId);
|
|
930
1085
|
},
|
|
931
1086
|
subjectAt: (roomId, seatId) => {
|
|
932
1087
|
const subject = roster.occupant(roomId, seatId)?.subject ?? null;
|
|
933
1088
|
return subject === null ? null : subjects.canonical(subject);
|
|
934
1089
|
},
|
|
1090
|
+
setPace: (roomId, pace) => {
|
|
1091
|
+
if (typeof roomId !== 'string' || roomId === '') throw new ProfileError('roomId', 'must be a non-empty string');
|
|
1092
|
+
paceMerged.delete(roomId);
|
|
1093
|
+
if (pace === null) {
|
|
1094
|
+
paceOverrides.delete(roomId);
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
// The caller's object is read once, into a validated snapshot of the fields it gave (a field left out inherits); that
|
|
1098
|
+
// snapshot is what is kept, so nothing about it can change after the check.
|
|
1099
|
+
const kept = checkPace(pace);
|
|
1100
|
+
if (kept.burst !== undefined && kept.burst !== null) Object.freeze(kept.burst);
|
|
1101
|
+
if (Object.keys(kept).length === 0) paceOverrides.delete(roomId);
|
|
1102
|
+
else paceOverrides.set(roomId, Object.freeze(kept));
|
|
1103
|
+
},
|
|
1104
|
+
pace: (roomId) => paceOf(roomId),
|
|
935
1105
|
},
|
|
936
1106
|
chat: {
|
|
937
1107
|
accept: (roomId, seatId, text, o) => chat.accept(roomId, seatId, text, o),
|
|
@@ -1114,7 +1284,11 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
1114
1284
|
history: (subject) => historyOf(store, subjects, subject, clock.now()),
|
|
1115
1285
|
suggest: (subject, level, rule, context) => {
|
|
1116
1286
|
const now = clock.now();
|
|
1117
|
-
|
|
1287
|
+
// The signal hits are the kit's to compute: a list the caller passes is dropped, the real one set when a ladder rule is met.
|
|
1288
|
+
const { signals: _ignored, ...given } = (context ?? {}) as SuggestContext;
|
|
1289
|
+
void _ignored;
|
|
1290
|
+
const hits = signals.ladderHits(subject);
|
|
1291
|
+
return suggest(policy.profileNow(), historyOf(store, subjects, subject, now), level, rule, now, hits.length === 0 ? given : { ...given, signals: hits });
|
|
1118
1292
|
},
|
|
1119
1293
|
gaps: {
|
|
1120
1294
|
list: () =>
|
|
@@ -1151,10 +1325,13 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
|
|
|
1151
1325
|
get: (subject) => store.transaction(() => store.getDiscordThread(subject)),
|
|
1152
1326
|
put: (row) => store.transaction(() => store.putDiscordThread(row)),
|
|
1153
1327
|
},
|
|
1154
|
-
purge: async (
|
|
1328
|
+
purge: async (override) => {
|
|
1155
1329
|
const merged: Partial<RetentionPolicy> = { ...retentionPolicy };
|
|
1156
|
-
for (const [k, v] of Object.entries(
|
|
1330
|
+
for (const [k, v] of Object.entries(override ?? {})) if (v !== undefined) (merged as Record<string, unknown>)[k] = v;
|
|
1157
1331
|
checkRetentionFloors(merged, limits.reports.suspendWindowMs);
|
|
1332
|
+
// A feed window longer than the signal retention could never be met: refuse the purge that would make it so, deleting nothing.
|
|
1333
|
+
const { kinds, feeds } = policy.profileNow().signals;
|
|
1334
|
+
checkSignalFeeds(feeds, kinds, { signalsMs: merged.signalsMs ?? RETENTION_DEFAULTS.signalsMs }, 'profile.signals.feeds');
|
|
1158
1335
|
return await purge(store, clock.now(), merged);
|
|
1159
1336
|
},
|
|
1160
1337
|
ready: () => {
|