@hourslabs/domovoi 0.1.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 (74) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +312 -0
  4. package/dist/cache.d.ts +102 -0
  5. package/dist/cache.d.ts.map +1 -0
  6. package/dist/calibration/index.d.ts +45 -0
  7. package/dist/calibration/index.d.ts.map +1 -0
  8. package/dist/calibration/index.js +95 -0
  9. package/dist/calibration/index.js.map +1 -0
  10. package/dist/engine/abort.d.ts +43 -0
  11. package/dist/engine/abort.d.ts.map +1 -0
  12. package/dist/engine/config.d.ts +79 -0
  13. package/dist/engine/config.d.ts.map +1 -0
  14. package/dist/engine/decide.d.ts +18 -0
  15. package/dist/engine/decide.d.ts.map +1 -0
  16. package/dist/engine/distribution.d.ts +18 -0
  17. package/dist/engine/distribution.d.ts.map +1 -0
  18. package/dist/engine/error-recording.d.ts +35 -0
  19. package/dist/engine/error-recording.d.ts.map +1 -0
  20. package/dist/engine/finalize.d.ts +12 -0
  21. package/dist/engine/finalize.d.ts.map +1 -0
  22. package/dist/engine/hooks.d.ts +12 -0
  23. package/dist/engine/hooks.d.ts.map +1 -0
  24. package/dist/engine/index.d.ts +7 -0
  25. package/dist/engine/index.d.ts.map +1 -0
  26. package/dist/engine/meta.d.ts +37 -0
  27. package/dist/engine/meta.d.ts.map +1 -0
  28. package/dist/engine/threshold.d.ts +31 -0
  29. package/dist/engine/threshold.d.ts.map +1 -0
  30. package/dist/env.d.ts +46 -0
  31. package/dist/env.d.ts.map +1 -0
  32. package/dist/errors.d.ts +66 -0
  33. package/dist/errors.d.ts.map +1 -0
  34. package/dist/hash.d.ts +27 -0
  35. package/dist/hash.d.ts.map +1 -0
  36. package/dist/index.d.ts +34 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +1263 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/prompt.d.ts +14 -0
  41. package/dist/prompt.d.ts.map +1 -0
  42. package/dist/providers/index.d.ts +6 -0
  43. package/dist/providers/index.d.ts.map +1 -0
  44. package/dist/providers/index.js +301 -0
  45. package/dist/providers/index.js.map +1 -0
  46. package/dist/providers/openai/adapter.d.ts +25 -0
  47. package/dist/providers/openai/adapter.d.ts.map +1 -0
  48. package/dist/providers/openai/distribution.d.ts +26 -0
  49. package/dist/providers/openai/distribution.d.ts.map +1 -0
  50. package/dist/providers/openai/factory.d.ts +76 -0
  51. package/dist/providers/openai/factory.d.ts.map +1 -0
  52. package/dist/providers/openai/index.d.ts +6 -0
  53. package/dist/providers/openai/index.d.ts.map +1 -0
  54. package/dist/providers/provider.d.ts +50 -0
  55. package/dist/providers/provider.d.ts.map +1 -0
  56. package/dist/testing/index.d.ts +40 -0
  57. package/dist/testing/index.d.ts.map +1 -0
  58. package/dist/testing/index.js +34 -0
  59. package/dist/testing/index.js.map +1 -0
  60. package/dist/tokenizer.d.ts +56 -0
  61. package/dist/tokenizer.d.ts.map +1 -0
  62. package/dist/types.d.ts +180 -0
  63. package/dist/types.d.ts.map +1 -0
  64. package/dist/validate.d.ts +47 -0
  65. package/dist/validate.d.ts.map +1 -0
  66. package/dist/verbs/boolean.d.ts +26 -0
  67. package/dist/verbs/boolean.d.ts.map +1 -0
  68. package/dist/verbs/classifier.d.ts +63 -0
  69. package/dist/verbs/classifier.d.ts.map +1 -0
  70. package/dist/verbs/classify.d.ts +24 -0
  71. package/dist/verbs/classify.d.ts.map +1 -0
  72. package/dist/verdict.d.ts +38 -0
  73. package/dist/verdict.d.ts.map +1 -0
  74. package/package.json +108 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend, and
172
+ hold each Contributor harmless for any liability incurred by, or
173
+ claims asserted against, such Contributor by reason of your accepting
174
+ any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Alex Roh
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
200
+ implied. See the License for the specific language governing permissions
201
+ and limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ domovoi
2
+ Copyright 2026 Alex Roh
3
+
4
+ This product includes software developed by Alex Roh and contributors.
package/README.md ADDED
@@ -0,0 +1,312 @@
1
+ <div align="center">
2
+ <img alt="domovoi — a small lit cabin in a forest of binary digits, where a craftsman gnome works at his bench" src=".github/assets/cover.png" width="100%" />
3
+ </div>
4
+
5
+ # domovoi
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@hourslabs/domovoi)](https://www.npmjs.com/package/@hourslabs/domovoi)
8
+ [![node](https://img.shields.io/badge/node-%3E%3D18-brightgreen)](https://nodejs.org)
9
+ [![typescript](https://img.shields.io/badge/typescript-%3E%3D5-blue)](https://www.typescriptlang.org)
10
+ [![license](https://img.shields.io/badge/license-Apache%202.0-lightgrey)](LICENSE)
11
+
12
+ **domovoi is an embedded intelligence in the runtime — a primitive that lives inside your software.** Ask at the forks where rules break down, get a typed Verdict, and direct it with bounded cost and full observability.
13
+
14
+ ---
15
+
16
+ - [What is domovoi](#what-is-domovoi)
17
+ - [Install](#install)
18
+ - [Typed Verdicts](#typed-verdicts)
19
+ - [When to Use It](#when-to-use-it)
20
+ - [API](#api)
21
+ - [Chaining](#chaining)
22
+ - [Provider Chain and Escalation](#provider-chain-and-escalation)
23
+ - [Local LLMs](#local-llms)
24
+ - [Configuration](#configuration)
25
+ - [Cancellation](#cancellation)
26
+ - [Calibration](#calibration)
27
+ - [Cache](#cache)
28
+ - [Current Limitations](#current-limitations)
29
+ - [Roadmap](#roadmap)
30
+ - [Origin](#origin)
31
+
32
+ ---
33
+
34
+ ## What is domovoi
35
+
36
+ Some decisions in software resist code. Is "SQ *COFFEE 0421" a restaurant or a grocery store? Is this message a refund request or a complaint? Is this form submission an abandoned checkout or a contact inquiry? A human decides in seconds. Code never will.
37
+
38
+ Rules and trained classifiers have tackled this for decades. Rules break on edge cases, then multiply until they collapse under their own weight. Classifiers return a confidence score and leave the handling to you. They don't know what they don't know.
39
+
40
+ domovoi is a single function call at the decision point. Unlike agent frameworks or workflow engines, it doesn't restructure how you build — it drops into existing code like any other dependency. Ask it, get a typed `Verdict`, continue.
41
+
42
+ The `Verdict` is the core idea. Not a string, not a confidence score — one of three typed states: `Classified` when confident, `Uncertain` when the top answer falls below threshold, `Unknown` when no answer is possible. Uncertainty becomes a first-class value your type system understands, not a silent wrong answer. Everything around the `Verdict` stays deterministic.
43
+
44
+ ```tsx
45
+ import { domovoi, match } from "@hourslabs/domovoi";
46
+
47
+ async function processTransaction(txn: Transaction) {
48
+ const account = await accounts.get(txn.accountId);
49
+ if (await fraud.isSuspicious(txn)) return holds.queue(txn);
50
+
51
+ const verdict = await domovoi.classify(
52
+ txn.merchant, // e.g. "NETFLIX.COM"
53
+ account.budget.categories // e.g. ["shopping", "groceries", ...]
54
+ );
55
+
56
+ await match(verdict, {
57
+ classified: ({ value }) => budget.attribute(account, txn, value),
58
+ uncertain: ({ top, runnerUp }) =>
59
+ budget.attributePending(account, txn, top, runnerUp),
60
+ unknown: ({ reason }) =>
61
+ retryQueue.schedule(txn, { reason, delayMs: 5 * 60_000 }),
62
+ });
63
+
64
+ await receipts.archive(txn);
65
+ events.emit("txn.processed", txn.id);
66
+ }
67
+ ```
68
+
69
+ ---
70
+
71
+ ## Install
72
+
73
+ ```bash
74
+ npm install @hourslabs/domovoi
75
+
76
+ # set your provider credentials
77
+ OPENAI_API_KEY=sk-...
78
+ ```
79
+
80
+ ---
81
+
82
+ ## Typed Verdicts
83
+
84
+ domovoi treats classification as a probabilistic decision over a finite space and returns one of three typed variants:
85
+
86
+ - **`Classified<T>`** — confident answer with `value: T` and calibrated `probability`.
87
+ - **`Uncertain<T>`** — top class below threshold; carries `top`, `runnerUp`, and the full `distribution`.
88
+ - **`Unknown<T>`** — no answer; `reason` discriminates `out_of_distribution`, `chain_exhausted`, `provider_failure`, `predicate_rejected`, `budget_exhausted`, or `cancelled`.
89
+
90
+ Failure-to-classify is a typed result, not an exception. Dispatch is exhaustive at the type level.
91
+
92
+ ```
93
+ "NETFLIX.COM" → subscriptions (p=1.00)
94
+ "WHOLE FOODS MARKET #10293" → groceries (p=0.99)
95
+ "UBER EATS" → dining (p=0.99)
96
+ "SHELL OIL 12345" → transportation (p=0.93)
97
+ "AMZN MKTP US*A12B3C4D5" → uncertain (shopping vs groceries, p=0.55)
98
+ ```
99
+
100
+ The `AMZN MKTP` row shows why the third state exists: it could be shopping or groceries depending on the cart. A forced `argmax` would silently pick the wrong one. domovoi surfaces the ambiguity as a first-class result instead.
101
+
102
+ ---
103
+
104
+ ## When to Use It
105
+
106
+ The pattern that fits: *a decision that's obvious to a person but impossible to write rules for, with a bounded downside when you get it wrong.*
107
+
108
+ - **Intent routing** — refund, complaint, or question. Rules and regex can't cover the full input space.
109
+ - **Content classification** — tag an article, ticket, or submission against your taxonomy. Replace brittle keyword rules with a classifier that handles edge cases.
110
+ - **Tiered dispatch** — chain `[gpt-4o-mini, gpt-5]`. The cheap model handles the easy cases; the expensive one runs only on `Uncertain`. Cost savings are meaningful when ≥70–80% of calls resolve at the cheaper tier.
111
+ - **Free-form validation + privacy filters** — does this description match the product? Does this profile bio violate guidelines? Does this user input contain PII or a prompt-injection attempt?
112
+
113
+ ---
114
+
115
+ ## API
116
+
117
+ Three core verbs:
118
+
119
+ ```tsx
120
+ domovoi.classify(input, space, opts?) // multi-class one-shot
121
+ domovoi.boolean(input, question, opts?) // binary one-shot
122
+ domovoi.classifier({ ... }) // reusable, configured → Classifier<T, I>
123
+ ```
124
+
125
+ Three ways to consume a Verdict:
126
+
127
+ ```tsx
128
+ // Type guard — single-variant cases
129
+ if (isClassified(verdict)) save(verdict.value);
130
+
131
+ // switch — when each Unknown reason needs its own handler
132
+ switch (verdict.kind) { ... }
133
+
134
+ // match — exhaustive expression form, type-checked
135
+ match(verdict, {
136
+ classified: ({ value }) => save(value),
137
+ uncertain: ({ top, runnerUp }) => saveTentative(top, runnerUp),
138
+ unknown: ({ reason }) => handleUnknown(reason),
139
+ });
140
+ ```
141
+
142
+ `Verdict.filter(pred)` rejects domain-invalid `Classified` or `Uncertain` to `Unknown { predicate_rejected }`; `Unknown` passes through untouched.
143
+
144
+ Three extension interfaces let you write your own without forking: **`Provider`** for any LLM API, **`Calibrator`** for custom calibration math, **`Cache`** for persistent or distributed backends. `mockProvider` from `@hourslabs/domovoi/testing` covers unit tests with controllable Distributions.
145
+
146
+ ---
147
+
148
+ ## Chaining
149
+
150
+ Verdicts compose. A Verdict can gate the next call, so each classifier works over a small, coherent space rather than one flat list of labels:
151
+
152
+ ```tsx
153
+ import { domovoi, isClassified } from "@hourslabs/domovoi";
154
+
155
+ const kind = await domovoi.classify(issue.body, [
156
+ "bug", "feature", "question", "docs",
157
+ ]);
158
+
159
+ // only bugs need surface-area triage — the first Verdict gates the second call
160
+ const surface =
161
+ isClassified(kind) && kind.value === "bug"
162
+ ? await domovoi.classify(issue.body, [
163
+ "frontend", "backend", "infra", "data",
164
+ ])
165
+ : null;
166
+
167
+ await issues.label(issue, {
168
+ kind: isClassified(kind) ? kind.value : "triage",
169
+ surface: surface && isClassified(surface) ? surface.value : null,
170
+ });
171
+ ```
172
+
173
+ ---
174
+
175
+ ## Provider Chain and Escalation
176
+
177
+ Configure a named classifier with a provider chain, thresholds, and a calibrator using `domovoi.classifier`:
178
+
179
+ ```tsx
180
+ const articleClassifier = domovoi.classifier({
181
+ name: "articles",
182
+ space: ["news", "sports", "music"],
183
+ question: "Which category fits this article?",
184
+ format: (article: Article) => `${article.title}\n\n${article.body}`,
185
+ thresholds: { high: 0.7, coverageMin: 0.5 },
186
+ providers: [openai("gpt-4o-mini"), openai("gpt-4o")],
187
+ calibrator: temperatureScaling(0.85),
188
+ });
189
+ ```
190
+
191
+ If the first provider returns `Uncertain` or errors, the engine tries the next. Errors land in `verdict.meta.providerErrors`. The default `onErrorPolicy: "fallback"` returns `Unknown { provider_failure }` on full-chain failure — it never throws. Set `onErrorPolicy: "throw"` for `AggregateError`.
192
+
193
+ Every Verdict includes rich metadata — provider, attempted chain, latency, cache hits, distribution source, and swallowed fallback errors — without extra instrumentation.
194
+
195
+ ---
196
+
197
+ ## Local LLMs
198
+
199
+ Local runtimes ship OpenAI-compatible APIs, so you can mix them freely with hosted models in a single chain:
200
+
201
+ ```tsx
202
+ // local primary, hosted fallback
203
+ providers: [ollama("llama-3.1-70b"), openai("gpt-4o")]
204
+ ```
205
+
206
+ `ollama(model)` defaults to `localhost:11434`. `openaiCompat(model, { baseURL, apiKey })` covers LM Studio, vLLM, Together, Fireworks, and OpenRouter.
207
+
208
+ ---
209
+
210
+ ## Configuration
211
+
212
+ ```bash
213
+ # Credentials — provider factories pick these up automatically
214
+ OPENAI_API_KEY=sk-...
215
+
216
+ # Default provider chain — comma-separated factory/model
217
+ DOMOVOI_PROVIDERS=openai/gpt-4o-mini,openai/gpt-4o
218
+
219
+ # Per-classifier override — when the classifier has `name: "articles"`
220
+ DOMOVOI_PROVIDERS_ARTICLES=openai/gpt-4o-mini,ollama/llama-3.1-70b
221
+ ```
222
+
223
+ Format: `factory/model[,factory/model...]`. Whitespace is trimmed; empty entries are skipped. In-code overrides win — pass `providers` to `domovoi.classifier({ ... })` and the env is ignored.
224
+
225
+ ---
226
+
227
+ ## Cancellation
228
+
229
+ Pass `signal` to any call. Standard Web API throughout:
230
+
231
+ ```tsx
232
+ // per-call timeout
233
+ const verdict = await domovoi.classify(input, space, {
234
+ signal: AbortSignal.timeout(2000),
235
+ });
236
+
237
+ // composing signals
238
+ const signal = AbortSignal.any([parentSignal, AbortSignal.timeout(5000)]);
239
+
240
+ // abort with reason
241
+ controller.abort("budget_exceeded");
242
+ // → Unknown { kind: "cancelled", reason: "budget_exceeded" }
243
+ ```
244
+
245
+ `.batch` always returns partial results. Finished items keep their Verdicts; in-flight and queued items become `Unknown { cancelled }`. The Promise resolves; it does not reject.
246
+
247
+ ---
248
+
249
+ ## Calibration
250
+
251
+ Three closed-form scaling factories from `@hourslabs/domovoi/calibration`:
252
+
253
+ | Factory | When to use |
254
+ |---|---|
255
+ | `identity` | Default. No calibration applied. |
256
+ | `temperatureScaling(T)` | Works on any space size. |
257
+ | `plattScaling({ a, b })` | Binary classifiers only. |
258
+
259
+ Fit the parameters on your held-out eval set. `Calibrator.fit(eval)` is on the roadmap; until then, fitting is manual. Calibrators run per-caller after cache resolution, so different configs on the same cache key produce different Verdicts from the same raw Distribution.
260
+
261
+ ---
262
+
263
+ ## Cache
264
+
265
+ Raw distributions are cached per `(input, provider)` keyed by SHA-256. The default is an in-memory LRU at 10k entries per classifier:
266
+
267
+ ```tsx
268
+ // override the default
269
+ domovoi.classifier({
270
+ cache: domovoi.memoryCache({ maxEntries: 50_000 }),
271
+ // ...
272
+ });
273
+ ```
274
+
275
+ The cache hashes the *output* of `format(input)`, not the function itself. Two classifiers with different `format` implementations but identical output share cache rows.
276
+
277
+ Custom backends implement the public `Cache` interface. Redis, SQLite, and Cloudflare KV are planned as first-party packages; they're implementable today via the interface.
278
+
279
+ ---
280
+
281
+ ## Current Limitations
282
+
283
+ 1. **Single adapter family.** OpenAI Chat plus OpenAI-compatible runtimes (Ollama, vLLM, LM Studio, Together, Fireworks). Anthropic native and Gemini are on the roadmap.
284
+ 2. **In-memory cache only.** Process-local; serverless cold starts begin empty. Persistent backends are implementable today via the public `Cache` interface; first-party Redis, SQLite, and KV packages are planned.
285
+ 3. **Identity calibrator default.** Provide `temperatureScaling(T)` or `plattScaling({ a, b })` with parameters you fit on your eval set for real calibration. Automated fitting (`Calibrator.fit(eval)`) is planned.
286
+ 4. **No per-provider retries.** Chain fallback covers between-provider failures; per-provider retries are planned.
287
+ 5. **No streaming.** `.stream` on `Classifier` is planned; `.batch` ships today.
288
+ 6. **No few-shot prompting.** Input passes verbatim; wrap with your own example-injection if needed.
289
+
290
+ ---
291
+
292
+ ## Roadmap
293
+
294
+ Milestones are ordered; dates are not. For exact versions, see the npm package page and GitHub Releases.
295
+
296
+ **Today.** The Verdict primitive — `Classified<T>`, `Uncertain<T>`, and `Unknown<T>` with structured failure modes. The `classify`, `boolean`, and `classifier` verbs. Calibration infrastructure, pluggable provider chain, tokenizer-aware OpenAI adapter, and the `Provider` / `Calibrator` / `Cache` extension points.
297
+
298
+ **Next.** Ambient context propagation via `domovoi.scope({ budget, signal, tracer }, fn)` — opt into budget enforcement, tracing, and cancellation across all `domovoi.classify(...)` calls deep in your call tree. New public extension point: `ContextStorage<T>`, backed by Node `AsyncLocalStorage`. Calls outside a scope continue to work exactly as today.
299
+
300
+ **Stability.** The Verdict shape, the three core verbs, and the four error classes are stable across releases. The `Provider` / `Calibrator` / `Cache` extension interfaces are public — breaking changes require a major version bump. Pre-1.0 releases may break anything outside these interfaces; pin an exact version if stability is required today.
301
+
302
+ ---
303
+
304
+ ## Origin
305
+
306
+ In Slavic folklore, a _domovoi_ (домово́й — "of the house") is a household spirit, not summoned from outside but bound to the home itself. It belongs to whoever lives there, watches over the household, and tends to what needs tending. domovoi is that spirit for your software: present at every decision, bound to you.
307
+
308
+ ---
309
+
310
+ ## License
311
+
312
+ Apache License 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Cache primitives.
3
+ *
4
+ * The public `Cache` interface is async, opaque-string-valued, and requires
5
+ * `delete`. The engine owns serialization; backends (Redis, KV, SQLite,
6
+ * in-memory) just round-trip strings.
7
+ *
8
+ * `InFlight` is the engine-side dedup table — concurrent calls with the same
9
+ * key share one Promise. Distinct from the `Cache` interface so external
10
+ * backends never see in-flight state.
11
+ */
12
+ import type { Distribution } from "./types.js";
13
+ /**
14
+ * Bump manually only when a change would make existing cache entries
15
+ * semantically wrong (cache key composition, stored value shape, provider
16
+ * distribution computation). Library-version bumps alone do not bump this.
17
+ */
18
+ export declare const CACHE_SCHEMA_VERSION = 1;
19
+ type CacheKeyInputs = {
20
+ readonly providerId: string;
21
+ readonly modelId: string;
22
+ readonly tokenizerId: string;
23
+ readonly templateHash: string;
24
+ /**
25
+ * Decision space in user-given order. Re-ordering changes the prompt — and
26
+ * therefore the model output — so it must change the cache key.
27
+ */
28
+ readonly decisionSpace: readonly string[];
29
+ readonly temperature: number;
30
+ /**
31
+ * Stable hash of provider options that affect Distribution shape (e.g.
32
+ * `multiSampleN`). Empty string for providers without such options.
33
+ */
34
+ readonly providerConfigHash: string;
35
+ /** Output of `classifier({ format })`, not the raw input. */
36
+ readonly formattedInput: string;
37
+ };
38
+ /**
39
+ * SHA-256 hex digest over canonical-JSON of all inputs. Stable across
40
+ * processes — safe for persistent backends.
41
+ */
42
+ export declare function computeCacheKey(inputs: CacheKeyInputs): string;
43
+ export declare function serializeCachedValue<T extends string>(d: Distribution<T>): string;
44
+ /**
45
+ * Returns `undefined` on a stored-schema-version mismatch; the engine treats
46
+ * that as a miss and re-samples from the provider.
47
+ */
48
+ export declare function deserializeCachedValue<T extends string>(raw: string): Distribution<T> | undefined;
49
+ /**
50
+ * @example
51
+ * const redisCache: Cache = {
52
+ * async get(key) { return await redis.get(key); },
53
+ * async set(key, value, ttlMs) {
54
+ * if (ttlMs !== undefined) await redis.set(key, value, "PX", ttlMs);
55
+ * else await redis.set(key, value);
56
+ * },
57
+ * async delete(key) { await redis.del(key); },
58
+ * };
59
+ */
60
+ export interface Cache {
61
+ get(key: string): Promise<string | undefined>;
62
+ set(key: string, value: string, ttlMs?: number): Promise<void>;
63
+ delete(key: string): Promise<void>;
64
+ }
65
+ export type CacheStats = {
66
+ readonly size: number;
67
+ readonly hits: number;
68
+ readonly misses: number;
69
+ readonly evictions: number;
70
+ };
71
+ /**
72
+ * Optional extension over `Cache`. The built-in `memoryCache` implements it;
73
+ * external backends may opt in.
74
+ */
75
+ export interface CacheWithStats extends Cache {
76
+ stats(): CacheStats;
77
+ }
78
+ /**
79
+ * Count-bounded in-memory LRU cache. Used as the per-classifier default when
80
+ * `cache` isn't supplied. Eviction runs after every successful `set`; the
81
+ * cache may briefly hold `maxEntries + concurrent-in-flight` entries during
82
+ * concurrent writes, then drops back to bound.
83
+ *
84
+ * @param options.maxEntries Default 10_000.
85
+ * @param options.defaultTtlMs Optional fallback TTL when `set` omits it.
86
+ */
87
+ export declare function memoryCache(options?: {
88
+ maxEntries?: number;
89
+ defaultTtlMs?: number;
90
+ }): CacheWithStats;
91
+ /**
92
+ * Engine-side dedup table. Two callers hitting the same key concurrently
93
+ * share a single Promise; on settle the slot is cleared.
94
+ */
95
+ export declare class InFlight<V> {
96
+ private readonly map;
97
+ run(key: string, factory: () => Promise<V>): Promise<V>;
98
+ /** Drop the in-flight slot for `key`, allowing the next caller to retry. */
99
+ forget(key: string): void;
100
+ }
101
+ export {};
102
+ //# sourceMappingURL=cache.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../src/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,IAAI,CAAC;AAEtC,KAAK,cAAc,GAAG;IACpB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B;;;OAGG;IACH,QAAQ,CAAC,kBAAkB,EAAE,MAAM,CAAC;IACpC,6DAA6D;IAC7D,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;CACjC,CAAC;AAEF;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,CAc9D;AAQD,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,MAAM,CAOjF;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC,GAAG,SAAS,CAQjG;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,KAAK;IACpB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC9C,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/D,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACpC;AAED,MAAM,MAAM,UAAU,GAAG;IACvB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;;GAGG;AACH,MAAM,WAAW,cAAe,SAAQ,KAAK;IAC3C,KAAK,IAAI,UAAU,CAAC;CACrB;AAOD;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,OAAO,CAAC,EAAE;IACpC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,cAAc,CA0DjB;AAED;;;GAGG;AACH,qBAAa,QAAQ,CAAC,CAAC;IACrB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAiC;IAE/C,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAU7D,4EAA4E;IAC5E,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;CAG1B"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Built-in calibrator factories.
3
+ *
4
+ * - `identity` — pass-through; the default.
5
+ * - `temperatureScaling(T)` — `p^(1/T) / Σ p_j^(1/T)`; equivalent to
6
+ * scaling logits before softmax.
7
+ * - `plattScaling({ a, b })` — sigmoid scaling; binary spaces only.
8
+ *
9
+ * `Calibrator.apply` must be pure and stateless. The engine runs it
10
+ * per-caller after the Distribution is loaded from the cache, so impurity
11
+ * would leak across callers sharing a cache row.
12
+ */
13
+ import type { Distribution } from "../types.js";
14
+ export interface Calibrator {
15
+ /** Identifier; `"identity"` is reserved and recognized by the engine. */
16
+ readonly kind: string;
17
+ apply<T extends string>(d: Distribution<T>): Distribution<T>;
18
+ }
19
+ export declare const identity: Calibrator;
20
+ /**
21
+ * - `T = 1` → identity.
22
+ * - `T > 1` → softens (less peaked).
23
+ * - `T < 1` → sharpens (more peaked).
24
+ *
25
+ * Operates on probabilities (not logits) and leaves `coverage` unchanged.
26
+ * Throws `ConfigError` on `T <= 0`.
27
+ *
28
+ * @example
29
+ * calibrator: temperatureScaling(0.85) // user-fit on held-out eval set
30
+ */
31
+ export declare function temperatureScaling(T: number): Calibrator;
32
+ /**
33
+ * Platt scaling: `sigmoid(a*z + b)` where `z = logit(p_pos)`.
34
+ *
35
+ * Binary-only — the second label in the distribution (in user-given order)
36
+ * is treated as the positive class. Construction-time space-size validation
37
+ * happens in the classifier; `apply()` re-checks at runtime as a defensive
38
+ * guard against direct misuse.
39
+ */
40
+ export declare function plattScaling(params: {
41
+ a: number;
42
+ b: number;
43
+ }): Calibrator;
44
+ export declare function isIdentityCalibrator(c: Calibrator): boolean;
45
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/calibration/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,WAAW,UAAU;IACzB,yEAAyE;IACzE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,CAAC,SAAS,MAAM,EAAE,CAAC,EAAE,YAAY,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAAC;CAC9D;AAED,eAAO,MAAM,QAAQ,EAAE,UAKtB,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,EAAE,MAAM,GAAG,UAAU,CA4BxD;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,UAAU,CAuCzE;AAMD,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,UAAU,GAAG,OAAO,CAE3D"}