opencode-model-router 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +35 -3
  3. package/package.json +4 -1
  4. package/src/commands/output.ts +4 -1
  5. package/src/compat/child-session.ts +43 -0
  6. package/src/compat/v2-client.ts +107 -7
  7. package/src/compat/v2-hooks.ts +118 -31
  8. package/src/escalate/attempt-recorder.ts +263 -0
  9. package/src/escalate/ladder.ts +484 -10
  10. package/src/escalate/resume.ts +208 -0
  11. package/src/escalate/variants.ts +391 -0
  12. package/src/index.ts +486 -38
  13. package/src/router/build-info.ts +151 -0
  14. package/src/router/config.ts +1365 -19
  15. package/src/router/protocol.ts +47 -0
  16. package/src/router/sessions.ts +441 -9
  17. package/src/routing/advisor/findings.ts +706 -0
  18. package/src/routing/advisor/index.ts +606 -0
  19. package/src/routing/classify/backends/host.ts +163 -0
  20. package/src/routing/classify/backends/openai-compatible.ts +275 -0
  21. package/src/routing/classify/backends/shared.ts +741 -0
  22. package/src/routing/classify/backends/typesafe.ts +315 -0
  23. package/src/routing/classify/fences.ts +96 -0
  24. package/src/routing/classify/index.ts +576 -0
  25. package/src/routing/classify/route-line.ts +298 -0
  26. package/src/routing/classify/rules.ts +607 -0
  27. package/src/routing/classify/scrub.ts +214 -0
  28. package/src/routing/classify/state.ts +148 -0
  29. package/src/routing/classify/text.ts +20 -0
  30. package/src/routing/classify/types.ts +1280 -0
  31. package/src/routing/commands/annotate-plan.ts +652 -0
  32. package/src/routing/commands/stats.ts +131 -0
  33. package/src/routing/commands/v1-roles.ts +64 -0
  34. package/src/routing/engine/index.ts +32 -0
  35. package/src/routing/engine/kernel.ts +597 -0
  36. package/src/routing/engine/ladders.ts +561 -0
  37. package/src/routing/engine/plan.ts +404 -0
  38. package/src/routing/engine/protocol-line.ts +133 -0
  39. package/src/routing/engine/simulate.ts +167 -0
  40. package/src/routing/engine/types.ts +270 -0
  41. package/src/routing/file-lock.ts +53 -0
  42. package/src/routing/outcomes/beta.ts +141 -0
  43. package/src/routing/outcomes/cost.ts +313 -0
  44. package/src/routing/outcomes/index.ts +172 -0
  45. package/src/routing/outcomes/ingest.ts +812 -0
  46. package/src/routing/outcomes/persist.ts +1058 -0
  47. package/src/routing/outcomes/stats.ts +602 -0
  48. package/src/routing/outcomes/store.ts +653 -0
  49. package/src/routing/outcomes/types.ts +954 -0
  50. package/src/routing/wire/dispatch.ts +799 -0
  51. package/src/routing/wire/hint.ts +208 -0
  52. package/src/routing/wire/host-info.ts +256 -0
  53. package/src/routing/wire/runtime.ts +259 -0
  54. package/src/v2.ts +15 -1
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Hardened scrubber for everything that may leave the machine (D14) and for
3
+ * anything the classifier logs or keeps (`BackendResult.raw`, reasons).
4
+ *
5
+ * `src/guard/scrub.ts` (`scrubText`) only knows a handful of provider token
6
+ * shapes and `key=value` pairs whose value is an alphanumeric run; QA-1.2-1
7
+ * showed env-style names, quoted JSON keys, URL credentials, PEM blocks, more
8
+ * provider tokens and bare high-entropy runs all pass through it. This module
9
+ * layers the missing shapes on top of it (the guard module is not edited) and
10
+ * adds the policy gate `hasCredentialSignal`.
11
+ *
12
+ * Pure. Every quantifier is bounded or linear: no pattern can backtrack
13
+ * quadratically on a long run of word characters.
14
+ */
15
+
16
+ import { scrubText } from "../../guard/scrub";
17
+
18
+ const REDACTED = "[REDACTED]";
19
+
20
+ /** Words that name a secret in an env-style or JSON-style assignment. */
21
+ const SECRET_NAME =
22
+ "PASSWORD|PASSWD|PWD|PASSPHRASE|SECRET|TOKEN|API[_ -]?KEY|ACCESS[_ -]?KEY|PRIVATE[_ -]?KEY|CREDENTIALS?";
23
+
24
+ /**
25
+ * `NAME=value`, `NAME: value`, `"name": "value"`, `client_secret: value`.
26
+ * Group 1 = the secret word, the rest of the name and the separator (kept; the
27
+ * start of the name is left alone), group 2 = the value (replaced): an already
28
+ * redacted marker (idempotence), a double- or single-quoted string, or
29
+ * everything up to the next whitespace (so `secret=abc+def/ghi==` goes whole).
30
+ */
31
+ const ASSIGNMENT_RE = new RegExp(
32
+ `((?:${SECRET_NAME})[A-Z0-9_-]{0,48}["']?\\s*[:=]\\s*)(\\[REDACTED\\]|"(?:[^"\\\\\\n]|\\\\.)*"|'[^'\\n]*'|\\S+)`,
33
+ "gi",
34
+ );
35
+
36
+ /**
37
+ * Upper-case env-style names ending in `_KEY` (`OPENAI_KEY`, `MASTER_KEY`,
38
+ * `ENCRYPTION_KEY`; QA-1.2-24). Case-sensitive on purpose: a lower-case `key` is
39
+ * an ordinary word, `_KEY` in capitals is a configuration name. Same group
40
+ * layout as ASSIGNMENT_RE.
41
+ */
42
+ const ENV_KEY_ASSIGNMENT_RE =
43
+ /(\b[A-Z][A-Z0-9_]{0,48}_KEY["']?\s*[:=]\s*)(\[REDACTED\]|"(?:[^"\\\n]|\\.)*"|'[^'\n]*'|\S+)/g;
44
+
45
+ /** The name alone, without a value (`set OPENAI_KEY before running`): a credential mention. */
46
+ const ENV_KEY_NAME_RE = /\b[A-Z][A-Z0-9_]{0,48}_KEY\b/;
47
+
48
+ /** "password is hunter2", "the key is hunter2", "the token was abc123". Group 1 = words up to the value. */
49
+ const SPOKEN_RE =
50
+ /\b((?:pass(?:word|wd|phrase)|secret|token|(?:api|access|private|signing|ssh|master|encryption)[_ -]?key|key|credentials?|pin)\s+(?:is|are|was|were|=)\s+)["'`]?[^\s"'`]+["'`]?/gi;
51
+
52
+ /** `mysql -u root -pSecret` (the password is glued to `-p`; a bare `-p` prompts and carries none). */
53
+ const MYSQL_PASSWORD_RE = /(\b(?:mysql|mysqladmin|mysqldump)\b[^\n]{0,200}?\s)-p\S+/gi;
54
+
55
+ /** `scheme://user:pass@host` and `scheme://token@host`. */
56
+ const URL_USER_PASS_RE = /\b([a-z][a-z0-9+.-]{0,31}:\/\/[^\s/:@]+:)[^\s/]+@/gi;
57
+ const URL_USER_ONLY_RE = /\b([a-z][a-z0-9+.-]{0,31}:\/\/)[^\s/:@]+@/gi;
58
+
59
+ /** `Authorization: Basic xxx` / `Bearer xxx` / bare value; group 1 = the header name and separator. */
60
+ const AUTH_HEADER_RE = /(\bAuthorization["']?\s*[:=]\s*)(?:(?:Basic|Digest|Bearer|Token)\s+)?[^\s"']+/gi;
61
+
62
+ /** `curl -u user:pass`, `--user user:pass`. */
63
+ const CURL_USER_RE = /(\s(?:-u|--user)[\s=]+)[^\s:]+:\S+/g;
64
+
65
+ /** PEM blocks; an unterminated block (truncated paste) runs to the end of the text. */
66
+ const PEM_RE = /-----BEGIN [A-Z0-9 ]+-----[\s\S]*?(?:-----END [A-Z0-9 ]+-----|$)/g;
67
+
68
+ /** Provider token shapes `scrubText` does not know. */
69
+ const TOKEN_RES: readonly RegExp[] = [
70
+ /\b(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9]{6,}/g, // Stripe
71
+ /\brk_[A-Za-z0-9_]{10,}/g, // Stripe restricted / generic rk_
72
+ /\bwhsec_[A-Za-z0-9]{10,}/g, // Stripe webhook
73
+ /\bhf_[A-Za-z0-9]{12,}/g, // Hugging Face
74
+ /\bglpat-[A-Za-z0-9_-]{10,}/g, // GitLab personal access token
75
+ /\bnpm_[A-Za-z0-9]{12,}/g, // npm
76
+ /\bpypi-[A-Za-z0-9_-]{16,}/g, // PyPI
77
+ /\bSG\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, // SendGrid
78
+ /\bya29\.[A-Za-z0-9_-]{16,}/g, // Google OAuth
79
+ /\bdop_v1_[a-f0-9]{16,}/g, // DigitalOcean
80
+ /\bgithub_pat_[A-Za-z0-9_]{16,}/g, // GitHub fine-grained
81
+ ];
82
+
83
+ /**
84
+ * A hex run of 32+ characters is a key, token or hash whatever its entropy
85
+ * (QA-1.2-24: `a1b2c3d4` repeated has low entropy and is still a 128-bit key).
86
+ * It needs both a letter and a digit, so a run of zeros or a plain number stays.
87
+ */
88
+ const HEX_RUN_RE = /(?<![0-9A-Za-z])[0-9A-Fa-f]{32,}(?![0-9A-Za-z])/g;
89
+
90
+ /**
91
+ * A run this long that looks random is a key, hash or blob, not prose. `.` and
92
+ * `\` are part of the run so a whole path is judged as a path (QA-1.2-26).
93
+ */
94
+ const HIGH_ENTROPY_RUN_RE = /[A-Za-z0-9+/_=.\\-]{32,}/g;
95
+ const MIN_ENTROPY_BITS = 3.5;
96
+ /** A run whose characters belong to word-like segments this much (or more) is a path or identifier. */
97
+ const WORDLIKE_SHARE = 0.7;
98
+ const WORDLIKE_SEGMENT_RE = /^(?:[A-Z]?[a-z]{1,}\d{0,3}|\d{1,4})$/;
99
+
100
+ function shannonEntropy(text: string): number {
101
+ const counts = new Map<string, number>();
102
+ for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
103
+ let bits = 0;
104
+ for (const n of counts.values()) {
105
+ const p = n / text.length;
106
+ bits -= p * Math.log2(p);
107
+ }
108
+ return bits;
109
+ }
110
+
111
+ /**
112
+ * Share of the run's characters that sit in word-like segments (`docs`, `cost`,
113
+ * `p12`, `2026`, `Classify`) when it is cut at `/ \ . _ - + =`. A path or a
114
+ * kebab-case identifier is nearly all word-like; a base64 key almost never is.
115
+ */
116
+ function wordlikeShare(run: string): number {
117
+ let wordlike = 0;
118
+ let total = 0;
119
+ for (const segment of run.split(/[/\\._=+-]+/)) {
120
+ if (segment === "") continue;
121
+ total += segment.length;
122
+ if (WORDLIKE_SEGMENT_RE.test(segment)) wordlike += segment.length;
123
+ }
124
+ return total === 0 ? 0 : wordlike / total;
125
+ }
126
+
127
+ function looksRandom(run: string): boolean {
128
+ if (!/\d/.test(run) || !/[A-Za-z]/.test(run)) return false;
129
+ if (wordlikeShare(run) >= WORDLIKE_SHARE) return false;
130
+ return shannonEntropy(run) >= MIN_ENTROPY_BITS;
131
+ }
132
+
133
+ export interface ScrubOptions {
134
+ /**
135
+ * Also redact bare hex and high-entropy runs (default true). These are the
136
+ * guesses of the scrubber: a commit hash or a minified blob looks the same as a
137
+ * key. Everything else it redacts is a named or shaped secret.
138
+ */
139
+ readonly entropy?: boolean;
140
+ }
141
+
142
+ /**
143
+ * Redact every secret shape known to the classifier. Idempotent
144
+ * (`scrubState(scrubState(x)) === scrubState(x)`).
145
+ */
146
+ export function scrubState(input: string, options: ScrubOptions = {}): string {
147
+ if (typeof input !== "string" || input.length === 0) return input;
148
+ let out = input;
149
+ out = out.replace(PEM_RE, `${REDACTED} (PEM block)`);
150
+ out = out.replace(URL_USER_PASS_RE, `$1${REDACTED}@`);
151
+ out = out.replace(URL_USER_ONLY_RE, `$1${REDACTED}@`);
152
+ out = out.replace(CURL_USER_RE, `$1${REDACTED}`);
153
+ out = out.replace(MYSQL_PASSWORD_RE, `$1-p${REDACTED}`);
154
+ out = out.replace(AUTH_HEADER_RE, `$1${REDACTED}`);
155
+ out = out.replace(ASSIGNMENT_RE, `$1${REDACTED}`);
156
+ out = out.replace(ENV_KEY_ASSIGNMENT_RE, `$1${REDACTED}`);
157
+ out = out.replace(SPOKEN_RE, `$1${REDACTED}`);
158
+ for (const re of TOKEN_RES) out = out.replace(re, REDACTED);
159
+ out = scrubText(out);
160
+ if (options.entropy !== false) {
161
+ out = out.replace(HEX_RUN_RE, (run) => (/\d/.test(run) && /[A-Fa-f]/.test(run) ? REDACTED : run));
162
+ out = out.replace(HIGH_ENTROPY_RUN_RE, (run) => (looksRandom(run) ? REDACTED : run));
163
+ }
164
+ return out;
165
+ }
166
+
167
+ /**
168
+ * How much more than the cut a slice is scrubbed (QA-1.2-32). It must exceed the
169
+ * longest minimum a pattern needs to recognise a secret (a 32-character hex or
170
+ * entropy run, a 20-character token body), so a secret that starts inside the
171
+ * kept part and runs past the cut is still seen as a secret in the slice.
172
+ */
173
+ const CUT_MARGIN_CHARS = 256;
174
+
175
+ /**
176
+ * Scrub, then keep the first `max` characters. The scrubbing sees `max` plus a
177
+ * margin, never only the kept part (a secret cut in half would no longer match
178
+ * its pattern) and never the whole input (a megabyte answer would cost a megabyte
179
+ * of regex work to keep a thousand characters).
180
+ */
181
+ export function scrubAndCut(text: string, max: number, options: ScrubOptions = {}): string {
182
+ if (typeof text !== "string") return "";
183
+ const slice = text.length > max + CUT_MARGIN_CHARS ? text.slice(0, max + CUT_MARGIN_CHARS) : text;
184
+ return scrubState(slice, options).slice(0, max);
185
+ }
186
+
187
+ /**
188
+ * Words and shapes that mean the text is about, or contains, a credential.
189
+ * Whole words only ("tokenizer" is not a hit); env-style names such as
190
+ * `GITHUB_TOKEN` are. `token(s)` is a hit in its LLM sense too ("fix the token
191
+ * counter"): the text cannot tell the two apart, a false skip costs only the
192
+ * rules facts, a false pass sends a credential off the machine (D14). A lone
193
+ * `key` is prose ("cache key", "primary key") unless it is assigned ("the key is
194
+ * …", `SORT_KEY=…`, caught by the scrubber below); only api/access/private/ssh/
195
+ * signing key and capitalised `*_KEY` names are hits as words. The DF3 probe
196
+ * ("Which word is longer, …") is not a hit: see
197
+ * test/unit/routing-classify.index.test.ts.
198
+ */
199
+ const CREDENTIAL_WORD_RE =
200
+ /\b(?:passwords?|passwd|passphrases?|secrets?|credentials?|api[_ -]?keys?|access[_ -]?keys?|private[_ -]?keys?|ssh[_ -]?keys?|signing[_ -]?keys?|tokens?|bearer|authorization|oauth)\b|[A-Za-z0-9]_(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|ACCESS_KEY|PRIVATE_KEY|CREDENTIALS?)\b|-----BEGIN [A-Z ]*(?:PRIVATE KEY|CERTIFICATE)|(?<![\w])\.env\b/i;
201
+
202
+ /**
203
+ * Policy gate (QA-1.2-1, QA-1.2-26): no backend is consulted for a task that
204
+ * names a credential (a credential word or an env-style `*_KEY` name) or
205
+ * contains a named or shaped secret the scrubber had to redact. The rules facts
206
+ * stand; nothing leaves the machine. A redaction that is only the scrubber's
207
+ * entropy guess (a commit hash, a long identifier) does NOT skip the backend:
208
+ * the redacted state is sent.
209
+ */
210
+ export function hasCredentialSignal(text: string): boolean {
211
+ if (typeof text !== "string" || text.length === 0) return false;
212
+ if (CREDENTIAL_WORD_RE.test(text) || ENV_KEY_NAME_RE.test(text)) return true;
213
+ return scrubState(text, { entropy: false }) !== text;
214
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * D14 classifier state — the ONLY text a model backend may send off the machine.
3
+ * Design section 3 of `docs/qa/cost-aware-routing/phase-1.2.md`.
4
+ *
5
+ * Contents, in order: a one-line description, the first `[acceptance]` block
6
+ * (whole or omitted, never cut), the prompt head with code blocks replaced by a
7
+ * placeholder. Secrets are scrubbed before anything is bounded, `<<<` / `>>>`
8
+ * are neutralised so the state cannot close the backend's delimiter, and the
9
+ * whole text is at most `maxStateChars` long. Nothing else is ever read: no
10
+ * file contents, no system prompt, no session history.
11
+ */
12
+
13
+ import { replaceFences, replaceIndentedBlocks } from "./fences";
14
+ import { scrubState } from "./scrub";
15
+ import { collapseLongRuns } from "./text";
16
+ import {
17
+ ACCEPTANCE_BLOCK_RE,
18
+ CODE_BLOCK_PLACEHOLDER,
19
+ DIRECTIVE_LINE_RES,
20
+ RULES_MAX_CHARS,
21
+ STATE_DESCRIPTION_MAX_CHARS,
22
+ type ClassifierState,
23
+ } from "./types";
24
+
25
+ /** Used when `maxStateChars` is not a finite number. */
26
+ const FALLBACK_STATE_CHARS = 200;
27
+ /** Upper bound of the budget; a smaller configured value is honoured as given. */
28
+ const MAX_STATE_CHARS = 20_000;
29
+ const TASK_HEADER = "Task:\n";
30
+ const OPEN_TAG = "[acceptance]";
31
+ const CLOSE_TAG = "[/acceptance]";
32
+
33
+ const ACCEPTANCE_ALL_RE = new RegExp(ACCEPTANCE_BLOCK_RE.source, "gi");
34
+
35
+ /** Only the upper bound clamps (QA-1.2-18): an operator who asks for 100 characters gets at most 100. */
36
+ function budgetOf(value: number): number {
37
+ if (!Number.isFinite(value)) return FALLBACK_STATE_CHARS;
38
+ return Math.min(MAX_STATE_CHARS, Math.max(0, Math.floor(value)));
39
+ }
40
+
41
+ /** Neutralise the delimiter runs so state text can never close or forge a block. */
42
+ function neutralize(text: string): string {
43
+ return text.replaceAll("<<<", "\u2039\u2039\u2039").replaceAll(">>>", "\u203a\u203a\u203a");
44
+ }
45
+
46
+ function dropDirectiveLines(text: string): string {
47
+ return text
48
+ .split(/\r?\n/)
49
+ .filter((line) => !DIRECTIVE_LINE_RES.some((re) => re.test(line)))
50
+ .join("\n");
51
+ }
52
+
53
+ /**
54
+ * The first `[acceptance]` block and the text without any block, found with
55
+ * `indexOf` over the WHOLE prompt (an acceptance block conventionally sits at
56
+ * the end, past where the head of a long prompt is cut) in linear time.
57
+ */
58
+ function splitAcceptance(text: string): { readonly first: string | null; readonly rest: string } {
59
+ const lower = text.toLowerCase();
60
+ if (lower.length !== text.length) {
61
+ // Case folding changed the length (rare Unicode): offsets are unusable, fall back to the bounded regex.
62
+ const head = text.slice(0, RULES_MAX_CHARS);
63
+ const match = ACCEPTANCE_BLOCK_RE.exec(head);
64
+ return { first: match === null ? null : match[0], rest: head.replace(ACCEPTANCE_ALL_RE, "") };
65
+ }
66
+ let first: string | null = null;
67
+ const parts: string[] = [];
68
+ let pos = 0;
69
+ for (;;) {
70
+ const open = lower.indexOf(OPEN_TAG, pos);
71
+ if (open === -1) break;
72
+ const close = lower.indexOf(CLOSE_TAG, open + OPEN_TAG.length);
73
+ if (close === -1) break; // an unclosed tag is ordinary text
74
+ const end = close + CLOSE_TAG.length;
75
+ if (first === null) first = text.slice(open, end);
76
+ parts.push(text.slice(pos, open));
77
+ pos = end;
78
+ }
79
+ parts.push(text.slice(pos));
80
+ return { first, rest: parts.join("") };
81
+ }
82
+
83
+ /** The text sources shared by the credential gate and state builder, before secret scrubbing. */
84
+ export function classifierStateRawParts(input: { description?: string; prompt: string }): {
85
+ readonly description: string;
86
+ readonly acceptance: string | null;
87
+ readonly body: string;
88
+ } {
89
+ const { first, rest } = splitAcceptance(String(input.prompt ?? ""));
90
+ return {
91
+ description: String(input.description ?? "").slice(0, RULES_MAX_CHARS),
92
+ acceptance: first === null || first.length > RULES_MAX_CHARS
93
+ ? null
94
+ : dropDirectiveLines(first).split(/\r?\n/).filter((line) => !/^\s*cwd\s*:/i.test(line)).join("\n"),
95
+ body: rest.slice(0, RULES_MAX_CHARS),
96
+ };
97
+ }
98
+
99
+ export function buildClassifierState(
100
+ input: { description?: string; prompt: string },
101
+ maxStateChars: number,
102
+ ): ClassifierState {
103
+ const budget = budgetOf(maxStateChars);
104
+
105
+ // Nothing below runs a regex over more than RULES_MAX_CHARS characters of the prompt (QA-1.2-11),
106
+ // except the linear indexOf scan that keeps a trailing acceptance block reachable.
107
+ const raw = classifierStateRawParts(input);
108
+ const acceptanceRaw = raw.acceptance;
109
+ const bodyRaw = collapseLongRuns(
110
+ replaceIndentedBlocks(
111
+ replaceFences(dropDirectiveLines(raw.body), CODE_BLOCK_PLACEHOLDER),
112
+ CODE_BLOCK_PLACEHOLDER,
113
+ )
114
+ .replace(/\n{3,}/g, "\n\n")
115
+ .trim(),
116
+ "[long token omitted]",
117
+ );
118
+
119
+ // Scrub first, then bound: a secret cut in half by the bound would no longer match a token shape.
120
+ const description = neutralize(
121
+ scrubState(raw.description.replace(/\s+/g, " ").trim()),
122
+ ).slice(0, STATE_DESCRIPTION_MAX_CHARS);
123
+ const acceptance = acceptanceRaw === null ? null : neutralize(scrubState(acceptanceRaw));
124
+ const body = neutralize(scrubState(bodyRaw));
125
+
126
+ const parts: string[] = [];
127
+ let used = 0;
128
+ if (description !== "") {
129
+ const part = "Description: " + description;
130
+ parts.push(part);
131
+ used += part.length + 1;
132
+ }
133
+ let acceptanceIncluded = false;
134
+ if (acceptance !== null && acceptance.length <= Math.floor((budget - used) / 2)) {
135
+ const part = "Acceptance:\n" + acceptance;
136
+ parts.push(part);
137
+ used += part.length + 1;
138
+ acceptanceIncluded = true;
139
+ }
140
+ const room = budget - used - TASK_HEADER.length;
141
+ if (room > 0 && body !== "") parts.push(TASK_HEADER + body.slice(0, room));
142
+ const truncated = body.length > Math.max(room, 0);
143
+
144
+ const text = parts.join("\n").slice(0, budget);
145
+ const state = { text, maxStateChars: budget, truncated, acceptanceIncluded };
146
+ // The only cast that creates the brand: every ClassifierState comes from here.
147
+ return state as unknown as ClassifierState;
148
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Text hygiene shared by the rules and the D14 state builder.
3
+ */
4
+
5
+ /** A single run of this many path/word characters is a blob (base64, minified code, a hostile string), never prose. */
6
+ // Anchored at the start of a run (the lookbehind): an unanchored `{200,}` rescans a 199-character run from
7
+ // every offset, which is itself quadratic.
8
+ const LONG_RUN_RE = /(?<![\w./\\@+-])[\w./\\@+-]{200,}/g;
9
+ const LONG_SPACE_RE = /(?<!\s)\s{200,}/g;
10
+
11
+ /**
12
+ * Collapse runs that make the shape-gate and enumeration regexes of
13
+ * `classifyTrivial` (written for 240-character prompts) quadratic on a long
14
+ * prompt: runs of 200+ `[\w./\\@+-]` characters become one `placeholder` word,
15
+ * runs of 200+ whitespace characters become a blank line (QA-1.2-7). Linear.
16
+ */
17
+ export function collapseLongRuns(text: string, placeholder = "longrun"): string {
18
+ if (text.length < 200) return text;
19
+ return text.replace(LONG_RUN_RE, placeholder).replace(LONG_SPACE_RE, "\n\n");
20
+ }