@seanhogg/builderforce-memory 2026.9.30 → 2026.9.32

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/dist/bridges/FetchBridge.d.ts +12 -5
  2. package/dist/bridges/FetchBridge.d.ts.map +1 -1
  3. package/dist/bridges/FetchBridge.js +6 -4
  4. package/dist/bridges/FetchBridge.js.map +1 -1
  5. package/dist/bridges/OpenAIBridge.d.ts +17 -4
  6. package/dist/bridges/OpenAIBridge.d.ts.map +1 -1
  7. package/dist/bridges/OpenAIBridge.js +68 -57
  8. package/dist/bridges/OpenAIBridge.js.map +1 -1
  9. package/dist/bridges/TransformerBridge.d.ts +6 -0
  10. package/dist/bridges/TransformerBridge.d.ts.map +1 -1
  11. package/dist/evermind/index.d.ts +6 -0
  12. package/dist/evermind/index.d.ts.map +1 -1
  13. package/dist/evermind/index.js +5 -0
  14. package/dist/evermind/index.js.map +1 -1
  15. package/dist/evermind/runtime.d.ts +158 -0
  16. package/dist/evermind/runtime.d.ts.map +1 -0
  17. package/dist/evermind/runtime.js +236 -0
  18. package/dist/evermind/runtime.js.map +1 -0
  19. package/dist/evermind/textCoherence.d.ts +55 -0
  20. package/dist/evermind/textCoherence.d.ts.map +1 -0
  21. package/dist/evermind/textCoherence.js +218 -0
  22. package/dist/evermind/textCoherence.js.map +1 -0
  23. package/dist/evermind/toolCall.d.ts +175 -0
  24. package/dist/evermind/toolCall.d.ts.map +1 -0
  25. package/dist/evermind/toolCall.js +398 -0
  26. package/dist/evermind/toolCall.js.map +1 -0
  27. package/dist/evermind/wordLexicon.d.ts +103 -0
  28. package/dist/evermind/wordLexicon.d.ts.map +1 -0
  29. package/dist/evermind/wordLexicon.js +361 -0
  30. package/dist/evermind/wordLexicon.js.map +1 -0
  31. package/dist/wire/chatClient.d.ts +100 -0
  32. package/dist/wire/chatClient.d.ts.map +1 -0
  33. package/dist/wire/chatClient.js +123 -0
  34. package/dist/wire/chatClient.js.map +1 -0
  35. package/dist/wire/index.d.ts +3 -1
  36. package/dist/wire/index.d.ts.map +1 -1
  37. package/dist/wire/index.js +2 -1
  38. package/dist/wire/index.js.map +1 -1
  39. package/dist/wire/sse.d.ts +17 -9
  40. package/dist/wire/sse.d.ts.map +1 -1
  41. package/dist/wire/sse.js +45 -22
  42. package/dist/wire/sse.js.map +1 -1
  43. package/package.json +3 -3
  44. package/src/bridges/FetchBridge.ts +15 -6
  45. package/src/bridges/OpenAIBridge.ts +82 -72
  46. package/src/bridges/TransformerBridge.ts +6 -0
  47. package/src/evermind/index.ts +48 -0
  48. package/src/evermind/runtime.ts +364 -0
  49. package/src/evermind/textCoherence.ts +248 -0
  50. package/src/evermind/toolCall.ts +523 -0
  51. package/src/evermind/wordLexicon.ts +395 -0
  52. package/src/wire/chatClient.ts +196 -0
  53. package/src/wire/index.ts +3 -1
  54. package/src/wire/sse.ts +43 -21
@@ -0,0 +1,103 @@
1
+ /**
2
+ * wordLexicon — a compact, zero-dependency lexicon + language guard used by the text
3
+ * coherence gate to catch the ONE failure mode the structural checks cannot see: an
4
+ * under-trained byte-BPE head emitting fluent-SHAPED prose made of INVENTED WORDS that
5
+ * balances its punctuation and never repeats itself ("…oredionisiing chats code related
6
+ * tot, bound reposea this inatic exie. The cainstiel.ts, ore…").
7
+ *
8
+ * Every structural signal (repetition, dominant-token collapse, replacement chars,
9
+ * orphaned delimiters) is blind to that text, and — measured on real samples —
10
+ * no dictionary-free feature separates it: long-token share, type-token ratio and
11
+ * character-cluster anomalies all score German/technical prose *worse* than the
12
+ * gibberish. So this module supplies the missing signal: **is this token a word?**
13
+ *
14
+ * Three deliberate design constraints, because a false positive here silently drops a
15
+ * legitimate reply:
16
+ *
17
+ * 1. **Language guard.** The lexicon is English-only, so it is consulted ONLY when the
18
+ * text is Latin-script AND English wins the function-word vote against es/fr/de/pt/it.
19
+ * A Spanish, French, German or Chinese reply is never judged by it. See
20
+ * {@link detectLatinLanguage}.
21
+ * 2. **Small lexicon + generous escapes.** ~2.5k high-frequency stems (plus suffix
22
+ * stripping) can't possibly cover domain jargon, so a token also counts as known
23
+ * when it REPEATS in the text or appears in the caller's context (the prompt/question).
24
+ * Real jargon echoes the question or recurs; invented gibberish words are each
25
+ * different — that asymmetry is the observed signature.
26
+ * 3. **Code is excluded, not judged.** Identifiers, paths, URLs, numbers and fenced
27
+ * blocks are stripped before scoring — they are legitimately non-words.
28
+ *
29
+ * Zero-dep and pure (no db/env/engine imports) so it can sit under `textCoherence`,
30
+ * which every surface imports.
31
+ */
32
+ /**
33
+ * Is `word` a plausible English word — either present in the lexicon directly, or a
34
+ * regular inflection of a stem that is? Lowercase input; punctuation already stripped.
35
+ * Deliberately GENEROUS (it decides whether to *accuse* text of being gibberish).
36
+ */
37
+ export declare function isKnownEnglishWord(word: string): boolean;
38
+ /** The verdict of the language guard — which Latin language won, and how strongly. */
39
+ export interface LanguageVerdict {
40
+ /** Winning language code, or null when the text isn't Latin-script or no language wins. */
41
+ language: string | null;
42
+ /** Share of tokens that are function words of the winning language (0..1). */
43
+ share: number;
44
+ /** Share of tokens that are function words of ANY supported language (0..1). */
45
+ anyShare: number;
46
+ /** True when the text is predominantly Latin-script (so the guard even applies). */
47
+ latin: boolean;
48
+ /**
49
+ * True when English is the LEADING candidate — no other supported language scored
50
+ * strictly more function-word hits. This, not {@link language}, is what gates the
51
+ * English lexicon, because the two things it must separate are "a genuine Spanish
52
+ * reply" and "English-shaped gibberish", and only the former votes decisively for
53
+ * another language. Gibberish sprays short tokens that happen to be Spanish or
54
+ * French function words (`se`, `te`, `al`, `mis`), which is enough to TIE the vote
55
+ * or squeak past English — and treating that ambiguity as "not English, don't
56
+ * judge it" is exactly how invented-word output escapes the dictionary.
57
+ */
58
+ englishLeads: boolean;
59
+ }
60
+ /**
61
+ * Decide which supported Latin-script language a text is in, by function-word vote.
62
+ * Returns `language: null` for non-Latin scripts (CJK, Cyrillic, Arabic, …) and when
63
+ * no language clears the floor — in both cases the English lexicon must NOT be applied.
64
+ */
65
+ export declare function detectLatinLanguage(words: readonly string[], text: string): LanguageVerdict;
66
+ /**
67
+ * Is this token a function word in ANY supported Latin-script language?
68
+ *
69
+ * Used to tell CONTENT words from grammar. Repetition is what function words are FOR
70
+ * ("the … the … the"), so counting them as evidence of a collapsed head is a category
71
+ * error — and the length-based proxy that stood in for this (any token of 3+ letters)
72
+ * quietly classified `the`, `and`, `for`, `was` and `not` as content.
73
+ */
74
+ export declare function isFunctionWord(word: string): boolean;
75
+ /**
76
+ * Is this raw token code rather than prose? Used to EXCLUDE tokens from word scoring —
77
+ * `projectEvermindRef`, `api/src/foo.ts`, `v2.1`, `https://…` are all legitimately
78
+ * absent from any dictionary.
79
+ */
80
+ export declare function isCodeishToken(raw: string): boolean;
81
+ /** The measured outcome of {@link scoreEnglishWordiness}. */
82
+ export interface WordinessScore {
83
+ /** True when the scorer actually ran (English text, enough eligible tokens). */
84
+ scored: boolean;
85
+ /** Eligible content tokens considered. */
86
+ eligible: number;
87
+ /** How many of them matched nothing — not the lexicon, not the context, not a repeat. */
88
+ unknown: number;
89
+ /** unknown / eligible (0 when not scored). */
90
+ unknownShare: number;
91
+ }
92
+ /**
93
+ * Score what fraction of a text's CONTENT words are unrecognisable. Only meaningful for
94
+ * confidently-English text — the caller must consult {@link detectLatinLanguage} first.
95
+ *
96
+ * A token counts as KNOWN when any of these hold, in order of cost:
97
+ * - it is code-ish (identifier / path / acronym) → excluded from scoring entirely;
98
+ * - the lexicon recognises it (with inflection stripping);
99
+ * - it appears in `context` (the prompt/question) — domain jargon echoes the ask;
100
+ * - it occurs more than once in the text — real jargon recurs, invented words don't.
101
+ */
102
+ export declare function scoreEnglishWordiness(words: readonly string[], rawTokens: readonly string[], context?: string): WordinessScore;
103
+ //# sourceMappingURL=wordLexicon.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wordLexicon.d.ts","sourceRoot":"","sources":["../../src/evermind/wordLexicon.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAqJH;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAQxD;AA4BD,sFAAsF;AACtF,MAAM,WAAW,eAAe;IAC9B,2FAA2F;IAC3F,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,8EAA8E;IAC9E,KAAK,EAAE,MAAM,CAAC;IACd,gFAAgF;IAChF,QAAQ,EAAE,MAAM,CAAC;IACjB,oFAAoF;IACpF,KAAK,EAAE,OAAO,CAAC;IACf;;;;;;;;;OASG;IACH,YAAY,EAAE,OAAO,CAAC;CACvB;AAYD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,eAAe,CA6C3F;AAMD;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEpD;AAKD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAOnD;AAED,6DAA6D;AAC7D,MAAM,WAAW,cAAc;IAC7B,gFAAgF;IAChF,MAAM,EAAE,OAAO,CAAC;IAChB,0CAA0C;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,yFAAyF;IACzF,OAAO,EAAE,MAAM,CAAC;IAChB,8CAA8C;IAC9C,YAAY,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,SAAS,EAAE,SAAS,MAAM,EAAE,EAC5B,OAAO,CAAC,EAAE,MAAM,GACf,cAAc,CA8BhB"}
@@ -0,0 +1,361 @@
1
+ /**
2
+ * wordLexicon — a compact, zero-dependency lexicon + language guard used by the text
3
+ * coherence gate to catch the ONE failure mode the structural checks cannot see: an
4
+ * under-trained byte-BPE head emitting fluent-SHAPED prose made of INVENTED WORDS that
5
+ * balances its punctuation and never repeats itself ("…oredionisiing chats code related
6
+ * tot, bound reposea this inatic exie. The cainstiel.ts, ore…").
7
+ *
8
+ * Every structural signal (repetition, dominant-token collapse, replacement chars,
9
+ * orphaned delimiters) is blind to that text, and — measured on real samples —
10
+ * no dictionary-free feature separates it: long-token share, type-token ratio and
11
+ * character-cluster anomalies all score German/technical prose *worse* than the
12
+ * gibberish. So this module supplies the missing signal: **is this token a word?**
13
+ *
14
+ * Three deliberate design constraints, because a false positive here silently drops a
15
+ * legitimate reply:
16
+ *
17
+ * 1. **Language guard.** The lexicon is English-only, so it is consulted ONLY when the
18
+ * text is Latin-script AND English wins the function-word vote against es/fr/de/pt/it.
19
+ * A Spanish, French, German or Chinese reply is never judged by it. See
20
+ * {@link detectLatinLanguage}.
21
+ * 2. **Small lexicon + generous escapes.** ~2.5k high-frequency stems (plus suffix
22
+ * stripping) can't possibly cover domain jargon, so a token also counts as known
23
+ * when it REPEATS in the text or appears in the caller's context (the prompt/question).
24
+ * Real jargon echoes the question or recurs; invented gibberish words are each
25
+ * different — that asymmetry is the observed signature.
26
+ * 3. **Code is excluded, not judged.** Identifiers, paths, URLs, numbers and fenced
27
+ * blocks are stripped before scoring — they are legitimately non-words.
28
+ *
29
+ * Zero-dep and pure (no db/env/engine imports) so it can sit under `textCoherence`,
30
+ * which every surface imports.
31
+ */
32
+ /**
33
+ * High-frequency English stems. Deliberately a STEM list — {@link isKnownEnglishWord}
34
+ * strips regular inflections, so `merge` covers merged/merges/merging/merger(s).
35
+ * Written as space-separated groups purely for readability; deduped by the Set.
36
+ */
37
+ const ENGLISH_STEMS_RAW = [
38
+ // Function words / pronouns / determiners / prepositions / conjunctions.
39
+ `a an the this that these those there here it its it's they them their theirs he him his she her hers we us our ours you your yours i me my mine who whom whose which what when where why how
40
+ and or but nor so yet for as if then than because while although though unless until since whether either neither both each every all any some none no not none other another same such own
41
+ is am are was were be been being do does did done doing have has had having will would shall should can could may might must ought need dare used
42
+ in on at by to from of with without within into onto out off over under above below between among across through during before after around near behind beyond against about upon toward towards along beside besides despite per via versus
43
+ very too also just only even still already almost enough quite rather almost mostly always never often sometimes usually rarely again once twice more most less least much many few several little lot lots
44
+ here there now then today tonight tomorrow yesterday soon later early late ago
45
+ yes no maybe perhaps please thanks thank hello hi okay ok sure`,
46
+ // Core verbs.
47
+ `accept access add adjust admit adopt advise affect afford agree allow analyse analyze announce answer apply appear approve argue arise arrange arrive ask assign assume attach attempt attend avoid
48
+ base become begin believe belong break bring build buy calculate call cancel capture carry catch cause change charge check choose claim clean clear click close collect combine come comment commit compare complete compute concern confirm connect consider consist contain continue contribute control convert copy correct cost cover create cut
49
+ deal decide declare decrease define delete deliver depend describe design detect determine develop die differ disable discover discuss display divide document download draw drive drop
50
+ earn edit effect elect enable encourage end enforce engage enjoy ensure enter escape establish estimate evaluate examine exceed exchange exclude execute exist expand expect experience explain explore export express extend extract
51
+ face fail fall fetch fight fill filter find finish fit fix flag flow focus follow force forget form format forward free fund
52
+ gain gather generate get give go grant grow guess guide handle happen help hide hire hit hold hope host identify ignore illustrate imagine implement import improve include increase indicate influence inform initialise initialize insert inspect install instruct intend introduce invest invite involve issue
53
+ join judge keep kill know label last launch lead learn leave lend let level lie lift like limit link list listen live load locate lock log look lose love
54
+ maintain make manage map mark match matter mean measure meet mention merge migrate mind miss mix modify monitor move
55
+ name navigate need note notice notify observe obtain occur offer open operate order organise organize outline overwrite own
56
+ pack parse partner pass pause pay perform permit persist pick place plan play point poll post practise practice predict prefer prepare present preserve press prevent print process produce program promise promote propose protect prove provide publish pull purchase push put
57
+ qualify query queue quit quote raise rank reach react read realise realize receive recognise recognize recommend record recover reduce refer reflect refresh refuse register regret reject relate release rely remain remember remind remove rename render repair repeat replace reply report represent request require reset resolve respond rest restart restore restrict result resume retain retry return reveal review revert reward rewrite roll run
58
+ save say scale scan schedule score search secure seed seek seem select sell send separate serve set settle share ship show shut sign signal simplify sit skip sleep slow solve sort sound speak specify spend split spread stand start state stay step stick stop store stream stretch strike study submit succeed suggest supply support suppose surface survive suspend sustain switch sync
59
+ take talk target teach tell tend test thank think threaten throw tie touch trace track trade train transfer transform translate travel treat trigger trust try turn
60
+ understand undo unlock update upgrade upload use validate value verify view visit vote wait wake walk want warn wash watch wear win wish wonder work worry wrap write`,
61
+ // Core nouns.
62
+ `ability access account action activity address advantage advice age agency agent agreement aim air alert amount analysis answer api app application approach approval area argument array article aspect asset assistant attempt attention audience audit author authority availability average
63
+ background backup balance bar base baseline batch behaviour behavior benchmark benefit bill block board body book bottom boundary branch brand break budget bug build building business button
64
+ cache calendar call capability capacity card care career case cash category cause cell center centre chain chance change channel chapter character chart chat check child choice church city claim class client cloud code collection college colour color column combination command comment commit committee community company comparison competition component computer concept concern condition conference config configuration confidence connection consequence consideration content context contract contrast contribution control conversation copy core corner cost council count country couple course court cover credit crisis criteria culture currency current customer cycle
65
+ damage data database date day deal debt decade decision default defence defense degree delay demand department dependency deployment depth description design desk detail development device diagram dialog difference difficulty direction director discussion disk display distance distribution district document documentation dollar domain door draft drive driver drop duration duty
66
+ earth economy edge edition editor education effect effort element email emergency employee employer end energy engine engineer entry environment episode equipment error estate estimate evaluation evening event evidence example exception exchange exercise existence expense experience experiment expert explanation export expression extension
67
+ face fact factor failure family fault feature fee feed feedback field figure file film filter finance finding fix flag flow focus folder food foot force forecast form format formula forum foundation frame framework friend front function fund future
68
+ game gap gateway generation girl goal government grade graph group growth guide
69
+ habit half hand handler hardware head header health heart height help history hit hold home hook hope host hour house human hypothesis
70
+ icon idea identity image impact implementation import importance improvement incident income increase index indicator individual industry influence information infrastructure initiative input insight instance institution instruction integration intent interaction interest interface internet interval interview introduction investment issue item
71
+ job join journey judgement judgment jump
72
+ key keyword kind king kitchen knowledge
73
+ lab label lack land language latency law layer layout leader leadership league learning length lesson letter level library licence license life light limit line link list literature load loan location lock log logic login loop loss love
74
+ machine magazine mail main maintenance majority manager map margin mark market material matter meaning measure media meeting member memory message metadata method metric middle migration milestone military million mind minute mission mistake mode model module moment money monitor month morning mother motion mountain mouse movement movie music
75
+ name nation nature need network news night node noise note notice notification number
76
+ object objective observation offer office officer operation opinion opportunity option order organisation organization origin outcome output overhead overview owner
77
+ package page pain pair panel paper paragraph parameter parent park part participant partner party password patch path pattern payment peace people percent performance period permission person perspective phase phone photo phrase picture piece pipeline place plan plant platform player point policy politics pool population port portfolio position possibility post potential power practice practise prediction preference presence president pressure price principle priority privacy problem procedure process product profile program progress project promise proof property proposal protection protocol provider public purpose
78
+ quality quantity query question queue quota
79
+ race radio range rank rate ratio reaction reader reality reason record recovery reference region registry regression relation relationship release relevance reliability remainder report repository representation request requirement research resolution resource response responsibility rest restriction result retry return revenue review reward risk road role room root round route row rule run runtime
80
+ safety sale sample scale scenario schedule scheme school science scope score screen script search season seat second secret section sector security seed segment selection sense sentence sequence series server service session set setting shape share sheet shell shift ship shop side sign signal significance similarity site situation size skill sky sleep slot snapshot society software solution son song sound source space span speaker specification speech speed spirit sport spot spread stack staff stage standard star start state statement station statistic status step stock storage store story strategy stream street strength stress string structure student study style subject subset success summary supply support surface survey symbol syntax system
81
+ table tag target task tax team technique technology telephone television temperature template term test text theme theory thing thought thread threshold ticket time timeline timeout title today token tool top topic total town track trade traffic training transaction transfer transition tree trend trial trip trouble truth turn type
82
+ understanding union unit university update upgrade usage user utility
83
+ value variable variant variety vector vendor version video view viewer village vision visitor voice volume vote
84
+ wall war warning water wave way weather web website week weight west wheel while window winter woman word work worker workflow world worth writer writing
85
+ yard year youth zone`,
86
+ // Adjectives / adverbs / qualifiers.
87
+ `able absolute abstract active actual additional adequate advanced adverse affordable aggregate alternative ambiguous ancient annual anonymous apparent appropriate arbitrary asynchronous atomic automatic available average aware awful
88
+ bad basic beautiful best better big binary blank blue bold boring bottom brief bright broad broken busy
89
+ calm capable careful central certain cheap chief civil classic clean clear clever close closed cold collective comfortable commercial common competitive complete complex comprehensive concrete confident confusing conscious consistent constant convenient cool core correct costly creative critical crucial cultural current custom
90
+ daily dangerous dark dead deep default defensive deliberate dense dependent desirable detailed different difficult digital direct dirty disabled distinct distributed diverse domestic dominant double downstream dry due dynamic
91
+ eager early easy economic effective efficient elaborate electric elegant eligible embedded empty enabled entire environmental equal equivalent essential eventual evident exact excellent exceptional excited exclusive existing expensive experimental explicit extensive external extra extreme
92
+ fair false familiar famous fast fatal favourite favorite federal final financial fine firm first fit fixed flat flexible foreign formal former forward fragile free frequent fresh friendly full functional fundamental funny future fuzzy
93
+ general generic gentle genuine giant global golden good graceful gradual grand grateful great green gross
94
+ happy hard harmful healthy heavy helpful hidden high historical hollow honest horizontal hostile hot huge human hybrid
95
+ ideal identical idle illegal immediate immutable important impossible improper inactive inclusive incoherent incomplete inconsistent incorrect independent indirect individual industrial inevitable infinite informal initial inner innovative input insufficient intact integral intelligent intended interactive interesting interim intermediate internal international invalid inverse isolated
96
+ joint junior just
97
+ key kind known
98
+ large last late later latest lawful lazy leading legal legitimate lengthy level liable light likely limited linear liquid literal little live lively living local logical long loose lost loud low lower loyal
99
+ main major manual massive mature maximum mean meaningful measurable mechanical medical medium mental mere middle mild military minimal minimum minor missing mixed mobile modern modest modular monthly moral multiple mutual
100
+ narrow national native natural near nearby necessary negative net neutral new next nice noisy normal notable novel numerous
101
+ objective obvious occasional odd official old ongoing online only open operational opposite optimal optional ordinary organic original other outer outstanding overall
102
+ parallel partial particular passive past patient perfect periodic permanent persistent personal physical plain pleasant plural political poor popular positive possible potential powerful practical precise predictable preferred premium present previous primary prime principal prior private probable productive professional profitable progressive prominent proper proportional protective proud public pure
103
+ qualified quality quick quiet
104
+ random rapid rare raw ready real realistic reasonable recent redundant regional regular related relative relevant reliable remaining remote repeated representative required resilient responsible restricted retail reverse rich right rigid robust rough round routine royal rural
105
+ sad safe same satisfied scarce scientific secondary secret secure select selective senior sensible sensitive separate serious severe shallow shared sharp short sick significant silent similar simple single skilled slight slow small smart smooth social soft solid sophisticated sound sour southern spare spatial special specific stable standard static steady steep sticky still straight strange strategic strict strong structural stuck subsequent substantial subtle successful sudden sufficient suitable superior supportive supposed sure surprising suspicious sustainable sweet swift synthetic systematic
106
+ tall technical temporary terrible thick thin third thorough tight tiny tired top total tough toxic traditional transparent tremendous tricky trivial true typical
107
+ ugly ultimate unable unavailable uncertain unclear uncommon underlying undesirable unexpected unfair unfortunate uniform unique universal unknown unlikely unnecessary unrelated unsafe unstable unusual upcoming upper upstream urban urgent useful useless usual
108
+ vague valid valuable variable various vast verbal vertical viable visible visual vital vocal void volatile voluntary vulnerable
109
+ warm weak wealthy weekly weird western wet white whole wide widespread wild willing wise wooden worse worst worthy written wrong
110
+ yearly young zero`,
111
+ // Software / product / business vocabulary the assistant genuinely uses.
112
+ `agent agile algorithm allocation analytics annotation architecture archive argument artifact assertion assignment async attribute authentication authorization automation availability
113
+ backend backlog bandwidth binary boolean bootstrap bottleneck breakpoint broker browser buffer bundle
114
+ callback capacity certificate changelog checkpoint checksum classifier cluster codebase collaboration commit compiler compliance component composite compression concurrency connector console constant constraint container context contributor controller cookie coordinator corpus coverage credential cron cursor
115
+ daemon dashboard debug debugger decorator delegate dependency deploy deployment deprecation descriptor developer diff directory dispatch distribution docker domain driver duplicate
116
+ embedding encoder encryption endpoint entity enumeration environment escalation event exception executor exporter extension
117
+ fallback feature federation fetch fixture flag fork formatter forwarding fragment framework frontend function
118
+ garbage gateway generator governance gradient granularity graph grid guard
119
+ handler hash header heap heuristic hook hostname hypervisor
120
+ identifier idempotent image importer index inference ingestion inheritance initialiser initializer injection instance instrumentation integer integration interceptor interface interpreter invariant iteration iterator
121
+ json kernel keyword kubernetes
122
+ latency layer ledger lexicon lifecycle linter listener literal locale localisation localization locking logger lookup
123
+ manifest mapper marshalling matrix memoization merge metadata microservice middleware migration mock modality model modifier monolith mutation mutex
124
+ namespace neural nightly normalisation normalization notation nullable
125
+ observability observer offset onboarding operator optimisation optimization orchestration ordering overflow override
126
+ packet parameter parser partition payload permission persistence pipeline plugin pointer policy polling pooling portal predicate prefix preprocessing primitive priority procedure processor producer profiler prompt provider provisioning proxy publisher
127
+ quantisation quantization quota
128
+ race recall reconciliation recursion redirect refactor reference regex registry regression release rendering replica repository request resolver response retention retry rollback rollout router routing runbook runtime
129
+ sandbox scaffolding schema scheduler scope screenshot sdk secret selector semantic serialisation serialization serverless service session shard signature simulation singleton snapshot socket specification sprint stack stakeholder standup state stateless storage strategy stream subscription subsystem suite superset supervisor swagger symbol synchronisation synchronization
130
+ telemetry template tenant terminal test testing throughput throttle timestamp tokeniser tokenizer topology trace transaction transformer transpiler traversal trigger tuple typescript
131
+ unit upstream uptime usage utilisation utilization
132
+ validation validator variable vector versioning viewport virtualisation virtualization visualisation visualization
133
+ warehouse watcher webhook websocket widget worker workspace wrapper
134
+ yaml
135
+ ticket sprint roadmap milestone stakeholder retrospective onboarding offboarding compliance invoice payroll headcount revenue margin forecast pipeline quota churn retention acquisition conversion engagement adoption`,
136
+ ].join(' ');
137
+ /** The lexicon set — lowercase stems only. */
138
+ const ENGLISH_STEMS = new Set(ENGLISH_STEMS_RAW.split(/\s+/u).map((w) => w.trim().toLowerCase()).filter(Boolean));
139
+ /**
140
+ * Regular inflectional/derivational suffixes stripped before a lexicon lookup, longest
141
+ * first. Keeping the lexicon as STEMS (and stripping here) is what lets ~2.5k entries
142
+ * cover ordinary English text without a megabyte of word forms.
143
+ */
144
+ const SUFFIXES = [
145
+ 'ationally', 'ability', 'ibility', 'ational', 'iveness', 'fulness', 'lessness',
146
+ 'ations', 'ments', 'nesses', 'ingly', 'ation', 'ition', 'ement', 'ments', 'ition',
147
+ 'ings', 'ness', 'ment', 'able', 'ible', 'ally', 'ical', 'ance', 'ence', 'sion', 'tion',
148
+ 'ised', 'ized', 'ises', 'izes', 'ising', 'izing', 'ise', 'ize',
149
+ 'ing', 'ers', 'est', 'ies', 'ied', 'ive', 'ous', 'ful', 'ity', 'ary', 'ory', 'ent', 'ant',
150
+ 'ed', 'er', 'es', 'ly', 'al', 'ic', 's', 'y',
151
+ ];
152
+ /** Undo consonant doubling ("commit" + "ing" → "committ" → "commit"). */
153
+ function undouble(stem) {
154
+ const n = stem.length;
155
+ if (n >= 4 && stem[n - 1] === stem[n - 2] && !'aeiou'.includes(stem[n - 1]))
156
+ return stem.slice(0, -1);
157
+ return stem;
158
+ }
159
+ /** Does the lexicon know this stem, allowing the usual spelling repairs (drop-e, y→i)? */
160
+ function stemKnown(stem) {
161
+ if (stem.length < 3)
162
+ return false;
163
+ if (ENGLISH_STEMS.has(stem))
164
+ return true;
165
+ if (ENGLISH_STEMS.has(`${stem}e`))
166
+ return true; // us + e → use
167
+ const un = undouble(stem);
168
+ if (un !== stem && ENGLISH_STEMS.has(un))
169
+ return true; // committ → commit
170
+ if (stem.endsWith('i') && ENGLISH_STEMS.has(`${stem.slice(0, -1)}y`))
171
+ return true; // appli → apply
172
+ return false;
173
+ }
174
+ /**
175
+ * Is `word` a plausible English word — either present in the lexicon directly, or a
176
+ * regular inflection of a stem that is? Lowercase input; punctuation already stripped.
177
+ * Deliberately GENEROUS (it decides whether to *accuse* text of being gibberish).
178
+ */
179
+ export function isKnownEnglishWord(word) {
180
+ const w = word.toLowerCase();
181
+ if (w.length < 3)
182
+ return true; // too short to judge — never an accusation
183
+ if (ENGLISH_STEMS.has(w))
184
+ return true;
185
+ for (const suf of SUFFIXES) {
186
+ if (w.length > suf.length + 2 && w.endsWith(suf) && stemKnown(w.slice(0, -suf.length)))
187
+ return true;
188
+ }
189
+ return false;
190
+ }
191
+ /**
192
+ * Function words for each supported Latin-script language, used ONLY to decide which
193
+ * language (if any) the text is in — never to score quality. Kept deliberately short:
194
+ * these are the highest-frequency, most distinctive markers of each language.
195
+ */
196
+ const FUNCTION_WORDS = {
197
+ en: ['the', 'and', 'that', 'with', 'this', 'for', 'you', 'not', 'are', 'was', 'have', 'from', 'they', 'but', 'what', 'when', 'which', 'there', 'their', 'would', 'about', 'your', 'been', 'will', 'can', 'has', 'its', 'it', 'is', 'of', 'to', 'in', 'on', 'at', 'as', 'by', 'or', 'an', 'be', 'if'],
198
+ es: ['que', 'los', 'las', 'del', 'una', 'por', 'con', 'para', 'como', 'pero', 'este', 'esta', 'son', 'más', 'sus', 'sobre', 'todo', 'ser', 'hay', 'el', 'la', 'de', 'un', 'se', 'no', 'lo', 'al', 'es', 'y'],
199
+ fr: ['les', 'des', 'est', 'une', 'que', 'pour', 'dans', 'sur', 'pas', 'avec', 'sont', 'plus', 'vous', 'nous', 'cette', 'mais', 'aux', 'par', 'ils', 'ce', 'le', 'la', 'de', 'un', 'et', 'du', 'au', 'en', 'il'],
200
+ de: ['der', 'die', 'das', 'und', 'ist', 'nicht', 'mit', 'den', 'von', 'für', 'auf', 'ein', 'eine', 'sich', 'auch', 'dem', 'werden', 'wird', 'aber', 'oder', 'sie', 'wir', 'zu', 'im', 'es', 'als', 'bei', 'nach', 'sind'],
201
+ pt: ['que', 'não', 'uma', 'com', 'para', 'como', 'mais', 'dos', 'das', 'por', 'este', 'esta', 'são', 'ser', 'seu', 'sua', 'pelo', 'ao', 'os', 'as', 'de', 'do', 'da', 'em', 'um', 'no', 'na'],
202
+ it: ['che', 'per', 'con', 'del', 'della', 'una', 'sono', 'più', 'come', 'anche', 'nella', 'questo', 'questa', 'gli', 'nel', 'il', 'la', 'di', 'un', 'da', 'si', 'le', 'ed', 'ma'],
203
+ };
204
+ /** How many alphabetic characters are Latin-script (a–z plus the accented Latin range). */
205
+ function latinLetterShare(text) {
206
+ let letters = 0;
207
+ let latin = 0;
208
+ for (const ch of text) {
209
+ if (!/\p{L}/u.test(ch))
210
+ continue;
211
+ letters++;
212
+ if (/[A-Za-zÀ-ɏ]/u.test(ch))
213
+ latin++;
214
+ }
215
+ return letters === 0 ? 0 : latin / letters;
216
+ }
217
+ /**
218
+ * How many DISTINCT function words a language needs before it wins outright. Raw hit
219
+ * counts are not enough: two occurrences of `se` plus one `al` outvoted English on a
220
+ * real gibberish sample, so the passage was measured against no lexicon at all.
221
+ * Genuine prose in any of these languages uses many different function words (the
222
+ * shortest real Spanish/French replies observed still clear 3), while gibberish
223
+ * repeats the same one or two accidental fragments.
224
+ */
225
+ const MIN_DISTINCT_FUNCTION_WORDS = 3;
226
+ /**
227
+ * Decide which supported Latin-script language a text is in, by function-word vote.
228
+ * Returns `language: null` for non-Latin scripts (CJK, Cyrillic, Arabic, …) and when
229
+ * no language clears the floor — in both cases the English lexicon must NOT be applied.
230
+ */
231
+ export function detectLatinLanguage(words, text) {
232
+ const latin = latinLetterShare(text) >= 0.6;
233
+ if (!latin || words.length === 0)
234
+ return { language: null, share: 0, anyShare: 0, latin, englishLeads: false };
235
+ const counts = new Map();
236
+ const distinct = new Map();
237
+ const anyHit = new Set();
238
+ for (const [lang, list] of Object.entries(FUNCTION_WORDS)) {
239
+ const set = new Set(list);
240
+ let hits = 0;
241
+ const seen = new Set();
242
+ words.forEach((w, i) => {
243
+ if (set.has(w)) {
244
+ hits++;
245
+ seen.add(w);
246
+ anyHit.add(i);
247
+ }
248
+ });
249
+ counts.set(lang, hits);
250
+ distinct.set(lang, seen.size);
251
+ }
252
+ let best = null;
253
+ let bestHits = 0;
254
+ let runnerUp = 0;
255
+ for (const [lang, hits] of counts) {
256
+ if (hits > bestHits) {
257
+ runnerUp = bestHits;
258
+ bestHits = hits;
259
+ best = lang;
260
+ }
261
+ else if (hits > runnerUp)
262
+ runnerUp = hits;
263
+ }
264
+ const share = bestHits / words.length;
265
+ const anyShare = anyHit.size / words.length;
266
+ // English leads unless some other language beat it on EVIDENCE — more hits AND enough
267
+ // different function words to be a language rather than one repeated fragment. A tie
268
+ // counts as a lead, and so does losing to a single token sprayed three times: see
269
+ // {@link LanguageVerdict.englishLeads}.
270
+ const englishHits = counts.get('en') ?? 0;
271
+ const englishLeads = [...counts].every(([lang, hits]) => (lang === 'en'
272
+ || hits <= englishHits
273
+ || (distinct.get(lang) ?? 0) < MIN_DISTINCT_FUNCTION_WORDS));
274
+ // A win must be present (≥8% of tokens), unambiguous (strictly beats the runner-up)
275
+ // — "in/an/no/de" are shared across languages, so a tie decides nothing — and backed
276
+ // by enough DIFFERENT function words to be a language rather than a repeated fragment.
277
+ const decisive = !!best
278
+ && share >= 0.08
279
+ && bestHits > runnerUp
280
+ && (distinct.get(best) ?? 0) >= MIN_DISTINCT_FUNCTION_WORDS;
281
+ if (!decisive)
282
+ return { language: null, share, anyShare, latin, englishLeads };
283
+ return { language: best, share, anyShare, latin, englishLeads };
284
+ }
285
+ /** Every supported language's function words in one set, built from the SAME table the
286
+ * language vote uses so the two can never disagree about what a function word is. */
287
+ const ANY_FUNCTION_WORD = new Set(Object.values(FUNCTION_WORDS).flat());
288
+ /**
289
+ * Is this token a function word in ANY supported Latin-script language?
290
+ *
291
+ * Used to tell CONTENT words from grammar. Repetition is what function words are FOR
292
+ * ("the … the … the"), so counting them as evidence of a collapsed head is a category
293
+ * error — and the length-based proxy that stood in for this (any token of 3+ letters)
294
+ * quietly classified `the`, `and`, `for`, `was` and `not` as content.
295
+ */
296
+ export function isFunctionWord(word) {
297
+ return ANY_FUNCTION_WORD.has(word.toLowerCase());
298
+ }
299
+ /** Tokens that are legitimately not words: identifiers, paths, urls, numbers, versions. */
300
+ const CODEISH = /[0-9_@#$/\\<>{}[\]|`~^*+=]|::|\.\w|--/u;
301
+ /**
302
+ * Is this raw token code rather than prose? Used to EXCLUDE tokens from word scoring —
303
+ * `projectEvermindRef`, `api/src/foo.ts`, `v2.1`, `https://…` are all legitimately
304
+ * absent from any dictionary.
305
+ */
306
+ export function isCodeishToken(raw) {
307
+ if (CODEISH.test(raw))
308
+ return true;
309
+ // camelCase / PascalCase with an internal capital → an identifier, not a word.
310
+ if (/^[A-Za-z]+$/u.test(raw) && /[a-z][A-Z]/u.test(raw))
311
+ return true;
312
+ // ALLCAPS acronyms (SSM, HTTP, R2) — real, just not lexicon entries.
313
+ if (/^[A-Z]{2,}$/u.test(raw))
314
+ return true;
315
+ return false;
316
+ }
317
+ /**
318
+ * Score what fraction of a text's CONTENT words are unrecognisable. Only meaningful for
319
+ * confidently-English text — the caller must consult {@link detectLatinLanguage} first.
320
+ *
321
+ * A token counts as KNOWN when any of these hold, in order of cost:
322
+ * - it is code-ish (identifier / path / acronym) → excluded from scoring entirely;
323
+ * - the lexicon recognises it (with inflection stripping);
324
+ * - it appears in `context` (the prompt/question) — domain jargon echoes the ask;
325
+ * - it occurs more than once in the text — real jargon recurs, invented words don't.
326
+ */
327
+ export function scoreEnglishWordiness(words, rawTokens, context) {
328
+ const contextWords = new Set((context ?? '').toLowerCase().match(/\p{L}[\p{L}'-]*/gu)?.map((w) => w.replace(/[''-]/gu, '')) ?? []);
329
+ const freq = new Map();
330
+ for (const w of words)
331
+ freq.set(w, (freq.get(w) ?? 0) + 1);
332
+ let eligible = 0;
333
+ let unknown = 0;
334
+ words.forEach((w, i) => {
335
+ // Judge exactly the words the lexicon is willing to judge. {@link isKnownEnglishWord}
336
+ // already forgives everything under 3 characters outright, so excluding 3-letter
337
+ // tokens on top of that discarded a third of the tokens in a short reply and left
338
+ // the probe-length samples below the evidence floor — unscoreable, hence "coherent".
339
+ // Measured on real samples, including them RAISES the unknown share of gibberish and
340
+ // LOWERS it for genuine English (3-letter English words are almost all in the
341
+ // lexicon), so it widens the margin in both directions.
342
+ if (w.length < 3)
343
+ return;
344
+ const raw = rawTokens[i] ?? w;
345
+ if (isCodeishToken(raw))
346
+ return;
347
+ eligible++;
348
+ if (isKnownEnglishWord(w))
349
+ return;
350
+ if (contextWords.has(w))
351
+ return;
352
+ if ((freq.get(w) ?? 0) > 1)
353
+ return;
354
+ unknown++;
355
+ });
356
+ // Below this there isn't enough evidence for a verdict either way.
357
+ if (eligible < 10)
358
+ return { scored: false, eligible, unknown, unknownShare: 0 };
359
+ return { scored: true, eligible, unknown, unknownShare: unknown / eligible };
360
+ }
361
+ //# sourceMappingURL=wordLexicon.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wordLexicon.js","sourceRoot":"","sources":["../../src/evermind/wordLexicon.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;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AC9E,wDAAwD;QACxD,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC;YAAE,OAAO;QACzB,MAAM,GAAG,GAAG,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,cAAc,CAAC,GAAG,CAAC;YAAE,OAAO;QAChC,QAAQ,EAAE,CAAC;QACX,IAAI,kBAAkB,CAAC,CAAC,CAAC;YAAE,OAAO;QAClC,IAAI,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC;YAAE,OAAO;QAChC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC;YAAE,OAAO;QACnC,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;IAEH,mEAAmE;IACnE,IAAI,QAAQ,GAAG,EAAE;QAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE,CAAC,EAAE,CAAC;IAChF,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE,OAAO,GAAG,QAAQ,EAAE,CAAC;AAC/E,CAAC"}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The OpenAI-compatible chat-completions client — ONE request builder, error mapping
3
+ * and stream reader for every caller that speaks `/chat/completions`: this package's
4
+ * `OpenAIBridge` / `FetchBridge`, and any host that reaches models through an
5
+ * OpenAI-compatible gateway (tools, streamed tool-call deltas, vendor extras).
6
+ *
7
+ * The body carries exactly what the request states — no sampling defaults are added
8
+ * here, so a routing gateway that picks the model and limits can be called with none.
9
+ * Callers that want defaults (the bridges) state them.
10
+ *
11
+ * Zero-dependency and engine-free (part of the `/wire` subpath).
12
+ */
13
+ /** An OpenAI-compatible chat message. */
14
+ export interface ChatMessage {
15
+ role: 'system' | 'user' | 'assistant' | 'tool';
16
+ /** Text, or an OpenAI multi-part array (text + `image_url`, …). */
17
+ content?: string | null | unknown[];
18
+ tool_calls?: unknown;
19
+ tool_call_id?: string;
20
+ [k: string]: unknown;
21
+ }
22
+ /** An OpenAI-compatible function-tool schema. */
23
+ export interface ChatToolSchema {
24
+ type: 'function';
25
+ function: {
26
+ name: string;
27
+ description: string;
28
+ parameters: Record<string, unknown>;
29
+ };
30
+ }
31
+ export interface ChatRequest {
32
+ messages: ChatMessage[];
33
+ tools?: ChatToolSchema[];
34
+ model?: string;
35
+ maxTokens?: number;
36
+ temperature?: number;
37
+ topP?: number;
38
+ /**
39
+ * On a stream, ask for the closing usage block (`stream_options.include_usage`).
40
+ * Opt-in: not every OpenAI-compatible server accepts the field.
41
+ */
42
+ includeUsage?: boolean;
43
+ /** Vendor extras merged into the body last (a routing `provider`, `response_format`, …). */
44
+ extra?: Record<string, unknown>;
45
+ }
46
+ export interface ChatToolCall {
47
+ id?: string;
48
+ type?: string;
49
+ function?: {
50
+ name?: string;
51
+ arguments?: string;
52
+ };
53
+ }
54
+ export interface ChatResult {
55
+ /** The reply text ('' when there was none — e.g. a tool-call-only turn). */
56
+ content: string;
57
+ /** True when the server sent text content (a string), false when it sent none. */
58
+ hasTextContent: boolean;
59
+ toolCalls: ChatToolCall[];
60
+ finishReason?: string;
61
+ /** The model the server reports having used. */
62
+ model?: string;
63
+ /** The raw `usage` object, when the server sent one — read it with `readUsageFields`. */
64
+ usage?: unknown;
65
+ }
66
+ /** Incremental events of a streamed completion. */
67
+ export type ChatStreamEvent = {
68
+ type: 'text-delta';
69
+ delta: string;
70
+ } | {
71
+ type: 'tool-call';
72
+ index: number;
73
+ id?: string;
74
+ name?: string;
75
+ argsDelta?: string;
76
+ } | {
77
+ type: 'done';
78
+ result: ChatResult;
79
+ };
80
+ export interface ChatClient {
81
+ /** The OpenAI-style base, e.g. `https://api.openai.com/v1`; `/chat/completions` is appended. */
82
+ baseUrl: string;
83
+ apiKey: string;
84
+ /** Abort a request after this long. Default: no limit beyond the caller's signal. */
85
+ timeoutMs?: number;
86
+ }
87
+ /** A non-2xx answer, with the status and (bounded) body kept apart for the caller's message. */
88
+ export declare class ChatCompletionError extends Error {
89
+ readonly status: number;
90
+ readonly body: string;
91
+ constructor(status: number, body: string);
92
+ }
93
+ /** One non-streamed completion. Throws {@link ChatCompletionError} on a non-2xx answer. */
94
+ export declare function chatComplete(client: ChatClient, req: ChatRequest, signal?: AbortSignal): Promise<ChatResult>;
95
+ /**
96
+ * A streamed completion as events: text and tool-call deltas as they arrive, then one
97
+ * `done` carrying the assembled result (tool-call arguments concatenated per index).
98
+ */
99
+ export declare function chatStream(client: ChatClient, req: ChatRequest, signal?: AbortSignal): AsyncGenerator<ChatStreamEvent>;
100
+ //# sourceMappingURL=chatClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chatClient.d.ts","sourceRoot":"","sources":["../../src/wire/chatClient.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,yCAAyC;AACzC,MAAM,WAAW,WAAW;IACxB,IAAI,EAAE,QAAQ,GAAG,MAAM,GAAG,WAAW,GAAG,MAAM,CAAC;IAC/C,mEAAmE;IACnE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,OAAO,EAAE,CAAC;IACpC,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,iDAAiD;AACjD,MAAM,WAAW,cAAc;IAC3B,IAAI,EAAE,UAAU,CAAC;IACjB,QAAQ,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;CACxF;AAED,MAAM,WAAW,WAAW;IACxB,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,KAAK,CAAC,EAAE,cAAc,EAAE,CAAC;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,C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