@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/documents.ts
CHANGED
|
@@ -53,7 +53,7 @@ export interface ModeratorGuideOptions {
|
|
|
53
53
|
export interface PolicyJson {
|
|
54
54
|
version: 1;
|
|
55
55
|
/** With `durations` and `customDuration` filled in, so a profile written for 0.1.1 reads back with the two new keys. */
|
|
56
|
-
profile: Omit<ResolvedProfile, 'ai'>;
|
|
56
|
+
profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals'>;
|
|
57
57
|
/** Every rule, retired ones included, in number order. */
|
|
58
58
|
rules: CommunityRule[];
|
|
59
59
|
}
|
|
@@ -705,9 +705,11 @@ export function agentBrief(policy: DocumentPolicy): string {
|
|
|
705
705
|
*/
|
|
706
706
|
export function policyJson(policy: DocumentPolicy): PolicyJson {
|
|
707
707
|
const snapshot = checkPolicy(policy);
|
|
708
|
-
// The AI settings
|
|
709
|
-
const profile: Omit<ResolvedProfile, 'ai'> & { ai?: unknown } = structuredClone(snapshot.profile);
|
|
708
|
+
// The AI settings, the pace settings and the signal settings are runtime switches, not policy text: the document tools never carry them.
|
|
709
|
+
const profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals'> & { ai?: unknown; pace?: unknown; signals?: unknown } = structuredClone(snapshot.profile);
|
|
710
710
|
delete profile.ai;
|
|
711
|
+
delete profile.pace;
|
|
712
|
+
delete profile.signals;
|
|
711
713
|
return { version: 1, profile, rules: snapshot.rules.all() };
|
|
712
714
|
}
|
|
713
715
|
|
package/src/freeze.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Freeze a value and everything inside it (plain data: objects, arrays, numbers, strings). Returns the same value. */
|
|
2
|
+
export function deepFreeze<T>(v: T): T {
|
|
3
|
+
if (typeof v === 'object' && v !== null && !Object.isFrozen(v)) {
|
|
4
|
+
Object.freeze(v);
|
|
5
|
+
for (const item of Object.values(v)) deepFreeze(item);
|
|
6
|
+
}
|
|
7
|
+
return v;
|
|
8
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const VERSION = '0.1.
|
|
1
|
+
export const VERSION = '0.1.8';
|
|
2
2
|
|
|
3
3
|
export type {
|
|
4
4
|
Clock,
|
|
@@ -45,6 +45,8 @@ export type {
|
|
|
45
45
|
ClaimRow,
|
|
46
46
|
OpenReportQuery,
|
|
47
47
|
ReasonRow,
|
|
48
|
+
SignalRow,
|
|
49
|
+
SignalSourceRow,
|
|
48
50
|
ConductLevel,
|
|
49
51
|
Source,
|
|
50
52
|
Store,
|
|
@@ -65,6 +67,7 @@ export {
|
|
|
65
67
|
REASONS_MAX,
|
|
66
68
|
ReasonBook,
|
|
67
69
|
ReasonError,
|
|
70
|
+
SIGNAL_BOOST_SCAN_MAX,
|
|
68
71
|
ViewingPresence,
|
|
69
72
|
VIEWING_TTL_MS,
|
|
70
73
|
} from './team.js';
|
|
@@ -277,7 +280,7 @@ export {
|
|
|
277
280
|
recordStep,
|
|
278
281
|
suggest,
|
|
279
282
|
} from './ladder.js';
|
|
280
|
-
export type { ActionRecord, LadderCell, LadderRow, LadderStep, Suggestion, SuggestContext } from './ladder.js';
|
|
283
|
+
export type { ActionRecord, LadderCell, LadderRow, LadderStep, Suggestion, SuggestContext, SignalHit } from './ladder.js';
|
|
281
284
|
export {
|
|
282
285
|
DECISION_EVIDENCE_MAX,
|
|
283
286
|
DECISION_REASON_MAX,
|
|
@@ -315,8 +318,43 @@ export {
|
|
|
315
318
|
resolveProfile,
|
|
316
319
|
validateProfile,
|
|
317
320
|
} from './profile.js';
|
|
321
|
+
// Pace settings (@experimental): slow mode, burst limit and repeat refusal, all off until set.
|
|
322
|
+
export { DUPLICATE_MIN_CHARS, DUPLICATE_RECENT, mergePace, PACE_KEYS_MAX, PACE_REASONS, PACE_SUGGESTIONS, resolvePace } from './pace.js';
|
|
323
|
+
export type { PaceReason, PaceSettings, ResolvedPace } from './pace.js';
|
|
324
|
+
// Signals (@experimental): kinds a game declares, the guards, and the feeds that say where counts may be read.
|
|
325
|
+
export {
|
|
326
|
+
BUILTIN_SIGNAL_KINDS,
|
|
327
|
+
checkSignalFeeds,
|
|
328
|
+
kindSpecOf,
|
|
329
|
+
pruneSignalFeeds,
|
|
330
|
+
resolveSignals,
|
|
331
|
+
SIGNAL_KIND_PATTERN,
|
|
332
|
+
SIGNAL_KINDS_MAX,
|
|
333
|
+
SIGNAL_WINDOW_DAYS_MAX,
|
|
334
|
+
} from './signals.js';
|
|
335
|
+
export { countSignals, evaluateThreshold } from './signalCounts.js';
|
|
336
|
+
export type { SignalRefusal } from './signalService.js';
|
|
337
|
+
export type { CountContext, ThresholdResult } from './signalCounts.js';
|
|
338
|
+
export type {
|
|
339
|
+
ResolvedSignalGuards,
|
|
340
|
+
ResolvedSignalKind,
|
|
341
|
+
ResolvedSignals,
|
|
342
|
+
SignalCount,
|
|
343
|
+
SignalDropReason,
|
|
344
|
+
SignalFeeds,
|
|
345
|
+
SignalGuards,
|
|
346
|
+
SignalInput,
|
|
347
|
+
SignalKindSpec,
|
|
348
|
+
SignalKindView,
|
|
349
|
+
SignalParty,
|
|
350
|
+
SignalPolarity,
|
|
351
|
+
SignalSettings,
|
|
352
|
+
SignalThreshold,
|
|
353
|
+
} from './signals.js';
|
|
318
354
|
export { POLICY_REFRESH_MS, PREVIEW_SAMPLES } from './policy.js';
|
|
319
355
|
export type {
|
|
356
|
+
PolicyDropped,
|
|
357
|
+
PolicyLimits,
|
|
320
358
|
PolicyPreview,
|
|
321
359
|
PolicySaveContext,
|
|
322
360
|
PolicySaveResult,
|
|
@@ -347,7 +385,7 @@ export type {
|
|
|
347
385
|
|
|
348
386
|
// AI levels 1 and 2: the provider-free contract (@experimental). Kept apart from the rest so a bundler can drop it.
|
|
349
387
|
export { AI_PROMPT_VERSION, AIError } from './ai/types.js';
|
|
350
|
-
export type { AbortSignalLike, AIExample, AIExampleInput, AIPerson, AIRead, AIReadInput, AIReadResult, AIStoredRead, AIUsage, ModerationAI } from './ai/types.js';
|
|
388
|
+
export type { AbortSignalLike, AIExample, AIExampleInput, AIPerson, AIRead, AIReadInput, AIReadResult, AISignal, AIStoredRead, AIUsage, ModerationAI } from './ai/types.js';
|
|
351
389
|
export { AI_OUTPUT_SCHEMA } from './ai/schema.js';
|
|
352
390
|
export { validateAIOutput } from './ai/validate.js';
|
|
353
391
|
export type { AIValidation, AIValidationContext } from './ai/validate.js';
|
package/src/ladder.ts
CHANGED
|
@@ -153,6 +153,30 @@ export interface SuggestContext {
|
|
|
153
153
|
* escalation never fires: without it this incident cannot count as a different game.
|
|
154
154
|
*/
|
|
155
155
|
roomId?: string | null;
|
|
156
|
+
/**
|
|
157
|
+
* The signal rules that fired for the reported person (design 5.6). Set by the facade (`cw.suggest` computes them from
|
|
158
|
+
* `feeds.ladder` and ignores a list passed to it); a rule only adds to the suggestion, never starts one: banter returns before any
|
|
159
|
+
* of this, and nothing here applies a sanction.
|
|
160
|
+
* @experimental
|
|
161
|
+
*/
|
|
162
|
+
signals?: readonly SignalHit[];
|
|
163
|
+
/**
|
|
164
|
+
* Leave the signal rules' sentences and the `signals` key out of the suggestion (the outcome still moves, which is the part a decider must
|
|
165
|
+
* see). For a caller who may not read the person's record: the sentence is a count of what other players did. Set by a route; default false.
|
|
166
|
+
* @experimental
|
|
167
|
+
*/
|
|
168
|
+
hideSignalText?: boolean;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* One signal rule that fired: its id, what it does and the sentence for the moderator ("Muted by other players: 5 players in 14
|
|
173
|
+
* days"). Carries no identifier.
|
|
174
|
+
* @experimental
|
|
175
|
+
*/
|
|
176
|
+
export interface SignalHit {
|
|
177
|
+
id: string;
|
|
178
|
+
effect: 'note' | 'raise';
|
|
179
|
+
text: string;
|
|
156
180
|
}
|
|
157
181
|
|
|
158
182
|
/** One suggested next action, with the plain reason a moderator can read out. Carries no identifier. */
|
|
@@ -162,6 +186,8 @@ export interface Suggestion {
|
|
|
162
186
|
label: string;
|
|
163
187
|
/** One plain sentence naming the profile and the reason. */
|
|
164
188
|
why: string;
|
|
189
|
+
/** Present only when a signal rule fired: the ids of the rules, and whether one of them raised the suggestion by a step. @experimental */
|
|
190
|
+
signals?: { raised: boolean; ids: string[] };
|
|
165
191
|
}
|
|
166
192
|
|
|
167
193
|
function plural(n: number, unit: string): string {
|
|
@@ -353,6 +379,24 @@ export function suggest(
|
|
|
353
379
|
}
|
|
354
380
|
}
|
|
355
381
|
|
|
382
|
+
// Signal rules (the ladder feed): a `raise` rule takes the ladder cell one step further down the column this suggestion read, only when
|
|
383
|
+
// it is stronger than the pick and not permanent; every other hit (and a raise that did nothing) is a sentence. Before the area swap.
|
|
384
|
+
const hits = usableHits(context.signals);
|
|
385
|
+
const sentences: string[] = [];
|
|
386
|
+
let raised = false;
|
|
387
|
+
if (hits.length > 0) {
|
|
388
|
+
const nextRow = step < 5 ? profile.ladder[step + 1] : undefined;
|
|
389
|
+
const cell = nextRow === undefined ? undefined : severe || read === 'hostile' ? nextRow.high : nextRow.lowMedium;
|
|
390
|
+
const target = cell === undefined || (cell.kind !== 'warning' && cell.durationMs === null) ? undefined : cellPick(cell);
|
|
391
|
+
for (const hit of hits) {
|
|
392
|
+
if (hit.effect === 'raise' && !raised && target !== undefined && !atLeast(pick.outcome, target.outcome)) {
|
|
393
|
+
pick = target;
|
|
394
|
+
raised = true;
|
|
395
|
+
if (context.hideSignalText !== true) sentences.push(`Raised one step: ${hit.text}.`);
|
|
396
|
+
} else if (context.hideSignalText !== true) sentences.push(`Also: ${hit.text}.`);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
356
400
|
let outcome = copyOutcome(pick.outcome);
|
|
357
401
|
let label = pick.label ?? outcomeLabel(outcome);
|
|
358
402
|
let areaNote = '';
|
|
@@ -361,5 +405,19 @@ export function suggest(
|
|
|
361
405
|
label = outcomeLabel(outcome);
|
|
362
406
|
areaNote = ' (this rule bans from public rooms instead of restricting chat)';
|
|
363
407
|
}
|
|
364
|
-
|
|
408
|
+
const why = `${name} profile: ${reason}${areaNote}.${sentences.map((s) => ` ${s}`).join('')}`;
|
|
409
|
+
return hits.length === 0 || context.hideSignalText === true ? { outcome, label, why } : { outcome, label, why, signals: { raised, ids: hits.map((h) => h.id) } };
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** The hits `suggest` will use: well-formed ones only (a string id and text, a known effect), at most 20. Never throws. */
|
|
413
|
+
function usableHits(v: unknown): SignalHit[] {
|
|
414
|
+
if (!Array.isArray(v)) return [];
|
|
415
|
+
const out: SignalHit[] = [];
|
|
416
|
+
for (const h of v.slice(0, 20) as unknown[]) {
|
|
417
|
+
if (typeof h !== 'object' || h === null) continue;
|
|
418
|
+
const { id, effect, text } = h as Record<string, unknown>;
|
|
419
|
+
if (typeof id !== 'string' || typeof text !== 'string' || (effect !== 'note' && effect !== 'raise')) continue;
|
|
420
|
+
out.push({ id, effect, text });
|
|
421
|
+
}
|
|
422
|
+
return out;
|
|
365
423
|
}
|
package/src/pace.ts
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { deepFreeze } from './freeze.js';
|
|
2
|
+
import { ProfileError } from './profileError.js';
|
|
3
|
+
|
|
4
|
+
// The pace settings: how a room paces a player's lines (a gap, a burst limit, no repeats). Pure data and validation, no state and no
|
|
5
|
+
// clock; the limiter that applies them is pacing.ts. Every setting is off until set, so a kit that sets none behaves as before.
|
|
6
|
+
|
|
7
|
+
/** The reasons a line can be refused for pacing, in the order they are checked. */
|
|
8
|
+
export const PACE_REASONS = ['slow_mode', 'flood', 'duplicate'] as const;
|
|
9
|
+
export type PaceReason = (typeof PACE_REASONS)[number];
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* How a room paces a player's lines. Every field optional on input; `null` or absent is off.
|
|
13
|
+
* @experimental
|
|
14
|
+
*/
|
|
15
|
+
export interface PaceSettings {
|
|
16
|
+
/** The least time between one player's lines in a room, ms. 500 to 600 000. */
|
|
17
|
+
slowModeMs?: number | null;
|
|
18
|
+
/** At most `lines` lines in any `windowMs`. `lines` 2 to 100, `windowMs` 1 000 to 600 000. */
|
|
19
|
+
burst?: { lines: number; windowMs: number } | null;
|
|
20
|
+
/** The same normalized line again inside this many ms is refused. 1 000 to 3 600 000. */
|
|
21
|
+
duplicateWindowMs?: number | null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* What the kit reads: every field filled, `null` meaning off.
|
|
26
|
+
* @experimental
|
|
27
|
+
*/
|
|
28
|
+
export interface ResolvedPace {
|
|
29
|
+
slowModeMs: number | null;
|
|
30
|
+
burst: { lines: number; windowMs: number } | null;
|
|
31
|
+
duplicateWindowMs: number | null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** A normalized line shorter than this (in characters) is never a duplicate, so "gg" and "ok" stay free. */
|
|
35
|
+
export const DUPLICATE_MIN_CHARS = 3;
|
|
36
|
+
/** How many of a player's most recent line hashes a repeat is compared with. */
|
|
37
|
+
export const DUPLICATE_RECENT = 8;
|
|
38
|
+
/**
|
|
39
|
+
* The most (room, player) states the limiter holds; the oldest go. A state is small (a time, a digest or two) but a burst of 100 lines
|
|
40
|
+
* keeps up to 100 times and 8 digests per player, roughly 1.5 KB: at the cap with the largest settings that is about 70 MB, so a game
|
|
41
|
+
* that sets `burst.lines` high and has very many players in one process should budget for it.
|
|
42
|
+
*/
|
|
43
|
+
export const PACE_KEYS_MAX = 50_000;
|
|
44
|
+
|
|
45
|
+
/** The allowed whole-number range of each number setting. */
|
|
46
|
+
const RANGES: Readonly<Record<string, readonly [number, number]>> = {
|
|
47
|
+
slowModeMs: [500, 600_000],
|
|
48
|
+
lines: [2, 100],
|
|
49
|
+
windowMs: [1000, 600_000],
|
|
50
|
+
duplicateWindowMs: [1000, 3_600_000],
|
|
51
|
+
};
|
|
52
|
+
const BURST_KEYS = ['lines', 'windowMs'] as const;
|
|
53
|
+
const PACE_KEYS = ['slowModeMs', 'burst', 'duplicateWindowMs'] as const;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Values the hub offers behind "Use suggested values". Never applied by themselves.
|
|
57
|
+
* @experimental
|
|
58
|
+
*/
|
|
59
|
+
export const PACE_SUGGESTIONS: Readonly<Record<'relaxed' | 'standard' | 'strict', ResolvedPace>> = deepFreeze({
|
|
60
|
+
relaxed: { slowModeMs: null, burst: { lines: 10, windowMs: 10_000 }, duplicateWindowMs: 10_000 },
|
|
61
|
+
standard: { slowModeMs: null, burst: { lines: 6, windowMs: 10_000 }, duplicateWindowMs: 15_000 },
|
|
62
|
+
strict: { slowModeMs: 2000, burst: { lines: 5, windowMs: 10_000 }, duplicateWindowMs: 30_000 },
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
function isPlain(v: unknown): v is Record<string, unknown> {
|
|
66
|
+
if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;
|
|
67
|
+
const proto: unknown = Object.getPrototypeOf(v);
|
|
68
|
+
return proto === Object.prototype || proto === null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** An own, defined value: a key left out, `undefined` and an inherited property all read as "not given". */
|
|
72
|
+
function given(o: Record<string, unknown>, key: string): unknown {
|
|
73
|
+
return Object.hasOwn(o, key) ? o[key] : undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `o` must be a plain object with no key outside `allowed`; a refusal names the key. */
|
|
77
|
+
function plain(o: unknown, allowed: readonly string[], path: string, what: string): Record<string, unknown> {
|
|
78
|
+
if (!isPlain(o)) throw new ProfileError(path, what);
|
|
79
|
+
for (const k of Object.keys(o)) if (!allowed.includes(k)) throw new ProfileError(`${path}.${k}`, 'is not a known setting');
|
|
80
|
+
return o;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function whole(v: unknown, key: string, path: string): number {
|
|
84
|
+
const [lo, hi] = RANGES[key]!;
|
|
85
|
+
if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < lo || v > hi) throw new ProfileError(path, `must be a whole number from ${lo} to ${hi}`);
|
|
86
|
+
return v;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function checkBurst(v: unknown, path: string): { lines: number; windowMs: number } {
|
|
90
|
+
const o = plain(v, BURST_KEYS, path, 'must be an object with lines and windowMs, or null');
|
|
91
|
+
for (const k of BURST_KEYS) if (given(o, k) === undefined) throw new ProfileError(`${path}.${k}`, 'is required');
|
|
92
|
+
return { lines: whole(o['lines'], 'lines', `${path}.lines`), windowMs: whole(o['windowMs'], 'windowMs', `${path}.windowMs`) };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Check the shape and ranges of `input` and return what is set, as a new object that shares nothing with it: a key is present only
|
|
97
|
+
* when it was given a value (`null` included), and each value was read from `input` exactly once, so what was validated is what is
|
|
98
|
+
* returned even for an object with getters. Throws ProfileError like {@link resolvePace}. For a caller that must keep the override a
|
|
99
|
+
* room was given (`cw.rooms.setPace`).
|
|
100
|
+
* @experimental
|
|
101
|
+
*/
|
|
102
|
+
export function checkPace(input: PaceSettings, path = 'pace'): PaceSettings {
|
|
103
|
+
return checked(input, path);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function checked(input: unknown, path: string): PaceSettings {
|
|
107
|
+
const o = plain(input, PACE_KEYS, path, 'must be an object');
|
|
108
|
+
const out: Record<string, unknown> = {};
|
|
109
|
+
for (const k of PACE_KEYS) {
|
|
110
|
+
const v = given(o, k);
|
|
111
|
+
if (v !== undefined) out[k] = v === null ? null : k === 'burst' ? checkBurst(v, `${path}.${k}`) : whole(v, k, `${path}.${k}`);
|
|
112
|
+
}
|
|
113
|
+
return out as PaceSettings;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Validate and fill. Throws ProfileError naming the field (`pace.burst.lines`), never echoing the value. `path` names the settings in
|
|
118
|
+
* the error (default `pace`). The result is a new object that shares nothing with the input.
|
|
119
|
+
* @experimental
|
|
120
|
+
*/
|
|
121
|
+
export function resolvePace(input: PaceSettings | undefined, path = 'pace'): ResolvedPace {
|
|
122
|
+
if (input === undefined) return { slowModeMs: null, burst: null, duplicateWindowMs: null };
|
|
123
|
+
const set = checked(input, path);
|
|
124
|
+
return { slowModeMs: set.slowModeMs ?? null, burst: set.burst ?? null, duplicateWindowMs: set.duplicateWindowMs ?? null };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* `over` on top of `base`: a field left out inherits, `null` turns it off, a value sets it. `burst` is replaced whole, never merged by
|
|
129
|
+
* member. `over` is validated (a ProfileError with the path `pace...`). Neither argument is changed or shared with the result.
|
|
130
|
+
* @experimental
|
|
131
|
+
*/
|
|
132
|
+
export function mergePace(base: ResolvedPace, over: PaceSettings): ResolvedPace {
|
|
133
|
+
const set = checked(over, 'pace');
|
|
134
|
+
return {
|
|
135
|
+
slowModeMs: set.slowModeMs !== undefined ? set.slowModeMs : base.slowModeMs,
|
|
136
|
+
burst: set.burst !== undefined ? set.burst : base.burst === null ? null : { lines: base.burst.lines, windowMs: base.burst.windowMs },
|
|
137
|
+
duplicateWindowMs: set.duplicateWindowMs !== undefined ? set.duplicateWindowMs : base.duplicateWindowMs,
|
|
138
|
+
};
|
|
139
|
+
}
|
package/src/pacing.ts
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { sha256Hex } from './crypto.js';
|
|
2
|
+
import { DUPLICATE_MIN_CHARS, DUPLICATE_RECENT, PACE_KEYS_MAX } from './pace.js';
|
|
3
|
+
import type { PaceReason, ResolvedPace } from './pace.js';
|
|
4
|
+
import type { Clock } from './types.js';
|
|
5
|
+
|
|
6
|
+
// The pacer: the in-memory limiter behind slow mode, the burst limit and repeat refusal. Pure and clocked: it reads the settings
|
|
7
|
+
// through a function on every call, holds no line text (a repeat is remembered as a short digest of the normalized line), and its
|
|
8
|
+
// `check` is timing-pure: a refusal changes nothing the next check reads. The one write `check` makes is the `floodSignalAt`
|
|
9
|
+
// bookkeeping, set when it returns `signalFlood: true`, so a flood is reported at most once per burst window.
|
|
10
|
+
//
|
|
11
|
+
// State is per process, a map of maps by room (so a room goes in one delete), swept every SWEEP_EVERY checks against the longest
|
|
12
|
+
// window the room has configured, and capped at PACE_KEYS_MAX keys (the oldest go).
|
|
13
|
+
|
|
14
|
+
/** Sweep quiet keys after this many `check` calls (the same cadence as `slidingWindow`). */
|
|
15
|
+
const SWEEP_EVERY = 256;
|
|
16
|
+
/** When the cap is hit, this many of the oldest keys go at once, so the scan is paid for once per batch and not once per new key. */
|
|
17
|
+
const EVICT_BATCH = Math.ceil(PACE_KEYS_MAX / 8);
|
|
18
|
+
/** Hex characters of the digest kept for a repeat: enough that two different lines do not meet, far too few to recover a line. */
|
|
19
|
+
const DIGEST_CHARS = 16;
|
|
20
|
+
|
|
21
|
+
/** Who a line is paced as: the room, and the canonical subject (or `seat:<seatId>` for a guest). */
|
|
22
|
+
export interface PaceKey {
|
|
23
|
+
roomId: string;
|
|
24
|
+
who: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The answer to one line. `retryAfterMs` is a whole number from 1 up to the window of the check that refused. */
|
|
28
|
+
export type PaceVerdict = { ok: true } | { ok: false; reason: PaceReason; retryAfterMs: number; signalFlood: boolean };
|
|
29
|
+
|
|
30
|
+
export interface Pacer {
|
|
31
|
+
/** Should this line be refused? Reads state, changes no timing state. Order: `slow_mode`, `flood`, `duplicate`. */
|
|
32
|
+
check(key: PaceKey, line: string): PaceVerdict;
|
|
33
|
+
/** Record that a line was accepted: it now counts toward the next check. A no-op while every check is off. */
|
|
34
|
+
commit(key: PaceKey, line: string): void;
|
|
35
|
+
/** Is any check on for this room right now? When not, `check` and `commit` do nothing and the caller need not build a key. */
|
|
36
|
+
active(roomId: string): boolean;
|
|
37
|
+
/** The line `check` accepted will not be committed (the fixed rate refused it): drop the digest memo that holds its text. */
|
|
38
|
+
discard(): void;
|
|
39
|
+
/** Is a line's text held in the digest memo (between a `check` that passed and its `commit` or `discard`)? A diagnostic. */
|
|
40
|
+
holdsText(): boolean;
|
|
41
|
+
/** Forget every key of a room in one step. */
|
|
42
|
+
dropRoom(roomId: string): void;
|
|
43
|
+
/** Keys held. A diagnostic: it stays at or under {@link PACE_KEYS_MAX}. */
|
|
44
|
+
size(): number;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** What the pacer keeps for one player in one room. @internal */
|
|
48
|
+
export interface KeyState {
|
|
49
|
+
/** When the last committed line was accepted. */
|
|
50
|
+
lastAt: number;
|
|
51
|
+
/** The times of the last committed lines, oldest first (at most the burst's `lines`). */
|
|
52
|
+
stamps: number[];
|
|
53
|
+
/** Digests of the last {@link DUPLICATE_RECENT} committed lines of enough length, oldest first. */
|
|
54
|
+
recent: Array<{ h: string; at: number }>;
|
|
55
|
+
/** When `check` last reported a flood for this key, or null. */
|
|
56
|
+
floodSignalAt: number | null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* NFKC, lower-case, then only letters, digits and the combining marks that belong to them: what "the same line again" means. Marks stay
|
|
61
|
+
* because in many scripts (Devanagari, Thai) the vowel signs are marks, and without them different words look alike. Variation
|
|
62
|
+
* selectors (U+FE00 to U+FE0F, which pick text or emoji presentation) are marks too but carry no meaning of their own, so they go
|
|
63
|
+
* first: `1\uFE0F\u20E3` and `1\u20E3` are one line, and an emoji line leaves nothing to count. Never stored.
|
|
64
|
+
*/
|
|
65
|
+
export function normalizeForRepeat(text: string): string {
|
|
66
|
+
return text.normalize('NFKC').toLowerCase().replace(/[\uFE00-\uFE0F]/g, '').replace(/[^\p{L}\p{N}\p{M}]/gu, '');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Letters and digits in a normalized line: marks do not count toward the minimum length, so a line of marks alone is never a repeat. */
|
|
70
|
+
const baseChars = (normalized: string): number => Array.from(normalized.replace(/\p{M}/gu, '')).length;
|
|
71
|
+
|
|
72
|
+
const OK: PaceVerdict = Object.freeze({ ok: true }) as PaceVerdict;
|
|
73
|
+
|
|
74
|
+
const allOff = (p: ResolvedPace): boolean => p.slowModeMs === null && p.burst === null && p.duplicateWindowMs === null;
|
|
75
|
+
|
|
76
|
+
/** A refusal with a whole-number wait of at least 1 and at most the refusing check's own window (a clock that stepped back cannot exceed it). */
|
|
77
|
+
function refusal(reason: PaceReason, waitMs: number, windowMs: number, signalFlood: boolean): PaceVerdict {
|
|
78
|
+
const wait = Number.isFinite(waitMs) ? Math.min(windowMs, Math.max(1, Math.ceil(waitMs))) : windowMs;
|
|
79
|
+
return { ok: false, reason, retryAfterMs: wait, signalFlood };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The longest window a room has configured, or 0 when every check is off. */
|
|
83
|
+
function longestWindow(p: ResolvedPace): number {
|
|
84
|
+
return Math.max(p.slowModeMs ?? 0, p.burst?.windowMs ?? 0, p.duplicateWindowMs ?? 0);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const touchedAt = (s: KeyState): number => (s.floodSignalAt !== null && s.floodSignalAt > s.lastAt ? s.floodSignalAt : s.lastAt);
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* `tap` is a test seam: it is handed the state (rooms by key) once, so a test can look at what a pacer holds. Nothing in the kit passes it.
|
|
91
|
+
* @internal
|
|
92
|
+
*/
|
|
93
|
+
export function createPacer(opts: { clock: Clock; settings: (roomId: string) => ResolvedPace; tap?: (rooms: ReadonlyMap<string, ReadonlyMap<string, Readonly<KeyState>>>) => void }): Pacer {
|
|
94
|
+
const { clock, settings } = opts;
|
|
95
|
+
const rooms = new Map<string, Map<string, KeyState>>();
|
|
96
|
+
opts.tap?.(rooms);
|
|
97
|
+
let keys = 0;
|
|
98
|
+
let calls = 0;
|
|
99
|
+
|
|
100
|
+
const sweep = (now: number): void => {
|
|
101
|
+
for (const [roomId, room] of rooms) {
|
|
102
|
+
let longest: number;
|
|
103
|
+
try {
|
|
104
|
+
longest = longestWindow(settings(roomId));
|
|
105
|
+
} catch {
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (longest === 0) {
|
|
109
|
+
keys -= room.size;
|
|
110
|
+
rooms.delete(roomId);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
for (const [who, state] of room) {
|
|
114
|
+
if (now - touchedAt(state) >= longest) {
|
|
115
|
+
room.delete(who);
|
|
116
|
+
keys -= 1;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (room.size === 0) rooms.delete(roomId);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/** Over the cap: drop the oldest keys, a batch at a time. */
|
|
124
|
+
const evict = (): void => {
|
|
125
|
+
const all: Array<{ roomId: string; who: string; at: number }> = [];
|
|
126
|
+
for (const [roomId, room] of rooms) for (const [who, state] of room) all.push({ roomId, who, at: touchedAt(state) });
|
|
127
|
+
all.sort((a, b) => a.at - b.at);
|
|
128
|
+
const drop = Math.min(all.length, keys - PACE_KEYS_MAX + EVICT_BATCH);
|
|
129
|
+
for (let i = 0; i < drop; i += 1) {
|
|
130
|
+
const { roomId, who } = all[i]!;
|
|
131
|
+
const room = rooms.get(roomId);
|
|
132
|
+
if (room?.delete(who) === true) keys -= 1;
|
|
133
|
+
if (room !== undefined && room.size === 0) rooms.delete(roomId);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const digest = (normalized: string): string => sha256Hex(normalized).slice(0, DIGEST_CHARS);
|
|
138
|
+
/**
|
|
139
|
+
* The digest `check` made of the line it just accepted, so `commit` of the same line does not hash it again. It holds that one line
|
|
140
|
+
* only from the check to the commit that follows it in the same call (and is replaced or cleared by the next call): the keyed state
|
|
141
|
+
* below never holds text.
|
|
142
|
+
*/
|
|
143
|
+
let memo: { line: string; h: string | null } | null = null;
|
|
144
|
+
/** A normalized line long enough to be called a repeat, as its digest; null for one that is not. */
|
|
145
|
+
const repeatHash = (line: string): string | null => {
|
|
146
|
+
if (memo !== null && memo.line === line) return memo.h;
|
|
147
|
+
const normalized = normalizeForRepeat(line);
|
|
148
|
+
return baseChars(normalized) < DUPLICATE_MIN_CHARS ? null : digest(normalized);
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const pacer: Pacer = {
|
|
152
|
+
active: (roomId) => !allOff(settings(roomId)),
|
|
153
|
+
|
|
154
|
+
check(key, line) {
|
|
155
|
+
const now = clock.now();
|
|
156
|
+
memo = null;
|
|
157
|
+
if (++calls % SWEEP_EVERY === 0) sweep(now);
|
|
158
|
+
const pace = settings(key.roomId);
|
|
159
|
+
if (allOff(pace)) return OK;
|
|
160
|
+
const state = rooms.get(key.roomId)?.get(key.who);
|
|
161
|
+
if (state === undefined) return OK;
|
|
162
|
+
|
|
163
|
+
const { slowModeMs, burst, duplicateWindowMs } = pace;
|
|
164
|
+
// State stamped after `now` (the clock stepped back) is stale, not "in the future": it never refuses, so a step back cannot lock
|
|
165
|
+
// a player out. The refusal clamp below is then a guard only.
|
|
166
|
+
if (slowModeMs !== null && state.lastAt <= now && now - state.lastAt < slowModeMs) {
|
|
167
|
+
return refusal('slow_mode', state.lastAt + slowModeMs - now, slowModeMs, false);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (burst !== null) {
|
|
171
|
+
const live = state.stamps.filter((t) => t <= now && now - t < burst.windowMs).sort((a, b) => a - b);
|
|
172
|
+
if (live.length >= burst.lines) {
|
|
173
|
+
// Enough must age out to leave room for one more: with exactly `lines` live that is the oldest, with more (a burst
|
|
174
|
+
// narrowed after the lines were sent) it is the one that leaves `lines - 1`.
|
|
175
|
+
const oldest = live[live.length - burst.lines]!;
|
|
176
|
+
const signal = state.floodSignalAt === null || now < state.floodSignalAt || now - state.floodSignalAt >= burst.windowMs;
|
|
177
|
+
if (signal) state.floodSignalAt = now;
|
|
178
|
+
return refusal('flood', oldest + burst.windowMs - now, burst.windowMs, signal);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
if (duplicateWindowMs !== null && state.recent.length > 0) {
|
|
183
|
+
const h = repeatHash(line);
|
|
184
|
+
if (h !== null) {
|
|
185
|
+
const seen = state.recent.find((e) => e.h === h && e.at <= now && now - e.at < duplicateWindowMs);
|
|
186
|
+
if (seen !== undefined) return refusal('duplicate', seen.at + duplicateWindowMs - now, duplicateWindowMs, false);
|
|
187
|
+
memo = { line, h };
|
|
188
|
+
} else memo = { line, h: null };
|
|
189
|
+
}
|
|
190
|
+
return OK;
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
commit(key, line) {
|
|
194
|
+
const now = clock.now();
|
|
195
|
+
const pace = settings(key.roomId);
|
|
196
|
+
if (allOff(pace)) return;
|
|
197
|
+
let room = rooms.get(key.roomId);
|
|
198
|
+
let state = room?.get(key.who);
|
|
199
|
+
if (state === undefined) {
|
|
200
|
+
if (keys >= PACE_KEYS_MAX) evict();
|
|
201
|
+
if (room === undefined || !rooms.has(key.roomId)) {
|
|
202
|
+
room = new Map();
|
|
203
|
+
rooms.set(key.roomId, room);
|
|
204
|
+
}
|
|
205
|
+
state = { lastAt: now, stamps: [], recent: [], floodSignalAt: null };
|
|
206
|
+
room.set(key.who, state);
|
|
207
|
+
keys += 1;
|
|
208
|
+
}
|
|
209
|
+
state.lastAt = now;
|
|
210
|
+
|
|
211
|
+
const { burst, duplicateWindowMs } = pace;
|
|
212
|
+
if (burst === null) state.stamps = [];
|
|
213
|
+
else state.stamps = [...state.stamps.filter((t) => t <= now && now - t < burst.windowMs), now].slice(-burst.lines);
|
|
214
|
+
|
|
215
|
+
if (duplicateWindowMs === null) state.recent = [];
|
|
216
|
+
else {
|
|
217
|
+
const h = repeatHash(line);
|
|
218
|
+
const kept = state.recent.filter((e) => e.h !== h && e.at <= now && now - e.at < duplicateWindowMs);
|
|
219
|
+
if (h !== null) kept.push({ h, at: now });
|
|
220
|
+
state.recent = kept.slice(-DUPLICATE_RECENT);
|
|
221
|
+
}
|
|
222
|
+
memo = null;
|
|
223
|
+
},
|
|
224
|
+
|
|
225
|
+
discard() {
|
|
226
|
+
memo = null;
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
holdsText: () => memo !== null,
|
|
230
|
+
|
|
231
|
+
dropRoom(roomId) {
|
|
232
|
+
const room = rooms.get(roomId);
|
|
233
|
+
if (room === undefined) return;
|
|
234
|
+
keys -= room.size;
|
|
235
|
+
rooms.delete(roomId);
|
|
236
|
+
},
|
|
237
|
+
|
|
238
|
+
size: () => keys,
|
|
239
|
+
};
|
|
240
|
+
|
|
241
|
+
return pacer;
|
|
242
|
+
}
|