@molecule/api-ai-decisions 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,115 @@
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
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,446 @@
1
+ <!--
2
+ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
+ Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
+ Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
+ To change this document, edit the module-level JSDoc in src/index.ts.
6
+ Generated: 2026-09-28T17:40:28.606Z
7
+ -->
8
+
9
+ # @molecule/api-ai-decisions
10
+
11
+ > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
12
+ > It is written to be read by coding agents as much as by people, and is generated from this
13
+ > package's source — edit `src/index.ts` JSDoc, not this file.
14
+
15
+ Typed AI decisions for molecule.dev.
16
+
17
+ Ask typed questions about a piece of text or JSON and get probabilities back,
18
+ not generated text: pick one option (`choice`), rate on an ordered scale
19
+ (`score`), or test a statement (`yesNo`). Use it for routing and triage
20
+ (which queue, how urgent), guardrails and moderation (is this spam, a
21
+ jailbreak, a refund request), and any branch in your code that needs a
22
+ judgment call about language. Many questions share one call.
23
+
24
+ This core defines the `AIDecisionsProvider` contract and its bond accessor
25
+ only. Bond one provider:
26
+
27
+ | Bond | What answers | When |
28
+ | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- |
29
+ | `@molecule/api-ai-decisions-laya` | the open-weights Laya model (Apache-2.0) on a `laya-serve` host you run — or any other self-hosted `/v1/systemone` server, such as Kev (Qwen-based, GPU/MLX) | self-hosted, ~30–40 ms/question on a GPU (Laya), data stays with you |
30
+ | `@molecule/api-ai-decisions-jev` | TypeSafe's hosted Jev API | no model to host; English-first |
31
+ | `@molecule/api-ai-decisions-llm` | whatever `ai` chat bond is bonded | no extra service; slower and costlier per call |
32
+
33
+ ## Quick Start
34
+
35
+ ```typescript
36
+ import { setProvider, requireProvider } from '@molecule/api-ai-decisions'
37
+ import { provider as laya } from '@molecule/api-ai-decisions-laya'
38
+
39
+ setProvider(laya) // at startup — reads LAYA_URL / LAYA_API_KEY on first use
40
+
41
+ const { answers } = await requireProvider().decide({
42
+ state: { subject: 'Charged twice', body: 'I was billed twice this month, I want my money back' },
43
+ questions: {
44
+ queue: {
45
+ type: 'choice',
46
+ instructions: 'Which team should handle this?',
47
+ criteria: {
48
+ billing: 'invoices, refunds, charges',
49
+ tech: 'bugs, login, outages',
50
+ other: 'anything else',
51
+ },
52
+ },
53
+ urgency: {
54
+ type: 'score',
55
+ instructions: 'How upset is the customer?',
56
+ criteria: ['calm', 'firm', 'angry', 'furious'],
57
+ },
58
+ refund: { type: 'yesNo', instructions: 'The customer is asking for a refund.' },
59
+ },
60
+ minConfidence: 0.7,
61
+ })
62
+
63
+ answers.queue.choice // 'billing'
64
+ answers.urgency.level // 2 (answers.urgency.score is the expected level, e.g. 2.64)
65
+ answers.refund.probability // 0.97
66
+ if (answers.queue.lowConfidence) {
67
+ // send to a human instead of auto-routing
68
+ }
69
+ ```
70
+
71
+ ## Type
72
+
73
+ `core`
74
+
75
+ ## Installation
76
+
77
+ ```bash
78
+ npm install @molecule/api-ai-decisions @molecule/api-bond @molecule/api-i18n
79
+ ```
80
+
81
+ ## API
82
+
83
+ ### Interfaces
84
+
85
+ #### `AIDecisionsProvider`
86
+
87
+ AI decisions provider interface. Implemented by the Laya, Jev and LLM bonds.
88
+
89
+ ```typescript
90
+ interface AIDecisionsProvider {
91
+ /** Provider identifier. */
92
+ readonly name: string
93
+
94
+ /**
95
+ * Answer every question about `state`.
96
+ *
97
+ * @param input - The state, the questions and options.
98
+ * @returns One typed answer per question id.
99
+ */
100
+ decide<Q extends Record<string, DecisionQuestion>>(
101
+ input: DecideInput<Q>,
102
+ ): Promise<DecideResult<Q>>
103
+ }
104
+ ```
105
+
106
+ #### `AnswerBase`
107
+
108
+ Fields every answer carries.
109
+
110
+ ```typescript
111
+ interface AnswerBase {
112
+ /**
113
+ * Probability mass on the reported answer (the highest option probability;
114
+ * `max(p, 1 - p)` for yes/no), in `0..1`. Every bond computes it this same
115
+ * way from the probabilities, so a threshold means the same thing whichever
116
+ * provider is bonded — it is NOT the vendor's own `confidence` field.
117
+ */
118
+ confidence: number
119
+ /** Set only when `minConfidence` was passed: `true` when `confidence` fell below it. */
120
+ lowConfidence?: boolean
121
+ }
122
+ ```
123
+
124
+ #### `ChoiceAnswer`
125
+
126
+ Answer to a {@link ChoiceQuestion}.
127
+
128
+ ```typescript
129
+ interface ChoiceAnswer extends AnswerBase {
130
+ type: 'choice'
131
+ /** The most likely option — always one of the question's `criteria` keys. */
132
+ choice: string
133
+ /** Probability per option (every `criteria` key present), summing to ~1. */
134
+ probabilities: Record<string, number>
135
+ }
136
+ ```
137
+
138
+ #### `ChoiceQuestion`
139
+
140
+ Pick exactly one option.
141
+
142
+ ```typescript
143
+ interface ChoiceQuestion {
144
+ type: 'choice'
145
+ /** What is being decided, e.g. `'Which team should handle this ticket?'`. */
146
+ instructions: string
147
+ /**
148
+ * The options, keyed by the label you want back, each with a short
149
+ * description of when it applies. `{ billing: 'invoices, refunds', tech: 'bugs, outages' }`.
150
+ */
151
+ criteria: Record<string, string>
152
+ }
153
+ ```
154
+
155
+ #### `DecideInput`
156
+
157
+ Input to one decision request.
158
+
159
+ ```typescript
160
+ interface DecideInput<
161
+ Q extends Record<string, DecisionQuestion> = Record<string, DecisionQuestion>,
162
+ > {
163
+ /** What the questions are about. */
164
+ state: DecisionState
165
+ /** The questions, keyed by an id you choose; answers come back under the same ids. */
166
+ questions: Q
167
+ /** Provider-specific model / checkpoint id (e.g. `'jev-latest'`, `'multilingual'`). */
168
+ model?: string
169
+ /** Mark answers whose `confidence` is below this (`0..1`) with `lowConfidence: true`. */
170
+ minConfidence?: number
171
+ /** Abort signal to cancel the in-flight request. */
172
+ signal?: AbortSignal
173
+ }
174
+ ```
175
+
176
+ #### `DecideResult`
177
+
178
+ Result of one decision request.
179
+
180
+ ```typescript
181
+ interface DecideResult<
182
+ Q extends Record<string, DecisionQuestion> = Record<string, DecisionQuestion>,
183
+ > {
184
+ /** One answer per question id. */
185
+ answers: AnswersFor<Q>
186
+ /** The model or checkpoint that answered, when the provider says. */
187
+ model?: string
188
+ /** Token usage, when reported. */
189
+ usage?: DecisionUsage
190
+ }
191
+ ```
192
+
193
+ #### `DecisionUsage`
194
+
195
+ Token usage, when the provider reports it.
196
+
197
+ ```typescript
198
+ interface DecisionUsage {
199
+ inputTokens: number
200
+ outputTokens: number
201
+ }
202
+ ```
203
+
204
+ #### `ScoreAnswer`
205
+
206
+ Answer to a {@link ScoreQuestion}.
207
+
208
+ ```typescript
209
+ interface ScoreAnswer extends AnswerBase {
210
+ type: 'score'
211
+ /** Expected level index — may fall between levels (e.g. `2.64`). */
212
+ score: number
213
+ /** The most likely level index (`0..criteria.length - 1`). */
214
+ level: number
215
+ /** Probability per level, indexed like `criteria`. */
216
+ probabilities: number[]
217
+ }
218
+ ```
219
+
220
+ #### `ScoreQuestion`
221
+
222
+ Place the state on an ordered scale.
223
+
224
+ ```typescript
225
+ interface ScoreQuestion {
226
+ type: 'score'
227
+ /** What is being rated, e.g. `'How urgent is this?'`. */
228
+ instructions: string
229
+ /**
230
+ * The levels, lowest first. Level `i` is described by `criteria[i]`:
231
+ * `['calm', 'firm', 'angry', 'furious']`.
232
+ */
233
+ criteria: string[]
234
+ }
235
+ ```
236
+
237
+ #### `YesNoAnswer`
238
+
239
+ Answer to a {@link YesNoQuestion}.
240
+
241
+ ```typescript
242
+ interface YesNoAnswer extends AnswerBase {
243
+ type: 'yesNo'
244
+ /** Probability that the statement is true, in `0..1`. */
245
+ probability: number
246
+ /** `probability >= 0.5`. Prefer thresholding `probability` yourself when the cost of each mistake differs. */
247
+ answer: boolean
248
+ }
249
+ ```
250
+
251
+ #### `YesNoQuestion`
252
+
253
+ How likely is a statement true. (Called `noul` on the Jev/Laya wire.)
254
+
255
+ ```typescript
256
+ interface YesNoQuestion {
257
+ type: 'yesNo'
258
+ /** The statement to test, e.g. `'The customer is asking for a refund.'`. */
259
+ instructions: string
260
+ /** Optional descriptions of what counts as yes and as no. */
261
+ criteria?: { yes?: string; no?: string }
262
+ }
263
+ ```
264
+
265
+ ### Types
266
+
267
+ #### `AnswersFor`
268
+
269
+ Maps a questions object to its answers object, so
270
+ `result.answers.department.choice` is typed when the questions are literal.
271
+
272
+ ```typescript
273
+ type AnswersFor<Q extends Record<string, DecisionQuestion>> = {
274
+ [K in keyof Q]: Q[K] extends ChoiceQuestion
275
+ ? ChoiceAnswer
276
+ : Q[K] extends ScoreQuestion
277
+ ? ScoreAnswer
278
+ : YesNoAnswer
279
+ }
280
+ ```
281
+
282
+ #### `DecisionAnswer`
283
+
284
+ Any answer. `answers[id].type` matches `questions[id].type`.
285
+
286
+ ```typescript
287
+ type DecisionAnswer = ChoiceAnswer | ScoreAnswer | YesNoAnswer
288
+ ```
289
+
290
+ #### `DecisionQuestion`
291
+
292
+ Any question a decision provider answers.
293
+
294
+ ```typescript
295
+ type DecisionQuestion = ChoiceQuestion | ScoreQuestion | YesNoQuestion
296
+ ```
297
+
298
+ #### `DecisionState`
299
+
300
+ What the questions are about: plain text, or a JSON object / array (an
301
+ email with headers, a ticket with metadata, a chat log).
302
+
303
+ ```typescript
304
+ type DecisionState = string | Record<string, unknown> | unknown[]
305
+ ```
306
+
307
+ ### Functions
308
+
309
+ #### `getAllProviders()`
310
+
311
+ Retrieves all named AI decisions providers as a Map keyed by name.
312
+
313
+ ```typescript
314
+ function getAllProviders(): Map<string, AIDecisionsProvider>
315
+ ```
316
+
317
+ **Returns:** Map of provider name → AIDecisionsProvider.
318
+
319
+ #### `getProvider()`
320
+
321
+ Retrieves the singleton AI decisions provider, or `null` if none is bonded.
322
+
323
+ Falls back to a single named provider when no singleton is bonded. When
324
+ multiple named providers are bonded the fallback declines (returns `null`)
325
+ because the choice is ambiguous — use `getProviderByName(name)` instead.
326
+
327
+ ```typescript
328
+ function getProvider(): AIDecisionsProvider | null
329
+ ```
330
+
331
+ **Returns:** The bonded AI decisions provider, or `null`.
332
+
333
+ #### `getProviderByName(name)`
334
+
335
+ Retrieves a named AI decisions provider, or `null` if not bonded.
336
+
337
+ ```typescript
338
+ function getProviderByName(name: string): AIDecisionsProvider | null
339
+ ```
340
+
341
+ - `name` — The provider name.
342
+
343
+ **Returns:** The named AI decisions provider, or `null`.
344
+
345
+ #### `hasProvider(name)`
346
+
347
+ Checks whether an AI decisions provider is currently bonded.
348
+
349
+ ```typescript
350
+ function hasProvider(name?: string): boolean
351
+ ```
352
+
353
+ - `name` — Optional provider name. If omitted, checks the singleton.
354
+
355
+ **Returns:** `true` if the provider is bonded.
356
+
357
+ #### `requireProvider()`
358
+
359
+ Retrieves the bonded AI decisions provider, throwing if none is bonded.
360
+
361
+ ```typescript
362
+ function requireProvider(): AIDecisionsProvider
363
+ ```
364
+
365
+ **Returns:** The bonded AI decisions provider.
366
+
367
+ #### `setProvider(provider)`
368
+
369
+ Registers an AI decisions provider in singleton mode.
370
+
371
+ ```typescript
372
+ function setProvider(provider: AIDecisionsProvider): void
373
+ ```
374
+
375
+ - `provider` — The default provider implementation for this process.
376
+
377
+ ## Available Providers
378
+
379
+ | Provider | Package |
380
+ | -------- | --------------------------------- |
381
+ | Jev | `@molecule/api-ai-decisions-jev` |
382
+ | Laya | `@molecule/api-ai-decisions-laya` |
383
+ | LLM | `@molecule/api-ai-decisions-llm` |
384
+
385
+ ## Injection Notes
386
+
387
+ ### Requirements
388
+
389
+ Peer dependencies:
390
+
391
+ - `@molecule/api-bond` ^1.0.1
392
+ - `@molecule/api-i18n` ^1.0.1
393
+
394
+ ### Runtime Dependencies
395
+
396
+ - `@molecule/api-bond`
397
+ - `@molecule/api-i18n`
398
+
399
+ - **Interface + accessor only.** Use the core's `setProvider(provider)` /
400
+ `setProvider('name', provider)`, then `requireProvider()` or
401
+ `getProviderByName('name')`.
402
+ - **`confidence` is the probability of the reported answer** (`max` of the
403
+ distribution), computed the same way by every bond. Vendors define their
404
+ own `confidence` differently (Jev: `(n·pmax − 1)/(n − 1)`; Laya: normalized
405
+ entropy), so a threshold copied from a vendor's docs does not transfer —
406
+ pick thresholds on your own data.
407
+ - **Base models are not a finished classifier for your domain.** Laya's own
408
+ benchmarks put its base checkpoints near chance (0.36) on the
409
+ typed-decisions set zero-shot; its fine-tuned checkpoint reaches 0.77.
410
+ Measure accuracy on a labelled sample of YOUR inputs before letting an
411
+ answer act unattended, and gate on `minConfidence` → a human or an LLM
412
+ fallback for the rest.
413
+ - **Probabilities ship over-confident** until calibrated on your traffic (Laya
414
+ reports ECE 0.47 → 0.08 after temperature fitting). A 0.95 is not "right 95%
415
+ of the time" until you have checked.
416
+ - **Keep option lists short.** Accuracy drops past ~20 `choice` options on
417
+ Laya (the option texts share a ~192-token window); Jev accepts up to 255,
418
+ `laya-serve` refuses >100. `score` takes 2–10 levels on Jev.
419
+ - **Keep state short.** Laya's English checkpoint reads 512 tokens (the
420
+ multilingual one 1,024); longer state is truncated, not refused. Put the
421
+ decisive text first.
422
+ - **Never use it to generate text** — there is no text output. For a
423
+ free-text label set that changes per request, use
424
+ `@molecule/api-ai-classification`.
425
+ - **Server-side only.** The provider key and the model host never belong in
426
+ browser code.
427
+
428
+ ## E2E Tests
429
+
430
+ Integration checklist — drive the real UI (live preview, no mocks), adapt
431
+ each item to this app's actual screens/flows, and check every box off one
432
+ by one. A box you can't check is an integration bug to fix — not a skip:
433
+
434
+ - [ ] Each flow that makes a decision (routing, triage, moderation, a
435
+ guardrail) runs it from the real UI, and the answer DRIVES what happens
436
+ next (the item lands in the chosen queue, the badge shows, the action is
437
+ blocked) — not just printed.
438
+ - [ ] Both directions: a clearly-billing input routes to billing AND a
439
+ clearly-technical one routes elsewhere. One label for every input is a
440
+ broken integration.
441
+ - [ ] A low-confidence answer takes the app's fallback path (human review,
442
+ "unsure" state) instead of being acted on.
443
+ - [ ] Provider errors (service down, bad key) show a visible, recoverable
444
+ state — never a blank screen or an unhandled rejection.
445
+ - [ ] The call runs server-side: no provider request or key in the browser's
446
+ Network tab.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-ai-decisions` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-ai-decisions is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
19
+ //# sourceMappingURL=browser-guard.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.js","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,GAAG,UAIT,CAAA;AACD,IAAI,CAAC,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,QAAQ,KAAK,SAAS,IAAI,CAAC,CAAC,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IACrF,MAAM,IAAI,KAAK,CACb,qGAAqG;QACnG,sFAAsF;QACtF,iFAAiF;QACjF,0CAA0C,CAC7C,CAAA;AACH,CAAC"}
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Typed AI decisions for molecule.dev.
3
+ *
4
+ * Ask typed questions about a piece of text or JSON and get probabilities back,
5
+ * not generated text: pick one option (`choice`), rate on an ordered scale
6
+ * (`score`), or test a statement (`yesNo`). Use it for routing and triage
7
+ * (which queue, how urgent), guardrails and moderation (is this spam, a
8
+ * jailbreak, a refund request), and any branch in your code that needs a
9
+ * judgment call about language. Many questions share one call.
10
+ *
11
+ * This core defines the `AIDecisionsProvider` contract and its bond accessor
12
+ * only. Bond one provider:
13
+ *
14
+ * | Bond | What answers | When |
15
+ * |---|---|---|
16
+ * | `@molecule/api-ai-decisions-laya` | the open-weights Laya model (Apache-2.0) on a `laya-serve` host you run — or any other self-hosted `/v1/systemone` server, such as Kev (Qwen-based, GPU/MLX) | self-hosted, ~30–40 ms/question on a GPU (Laya), data stays with you |
17
+ * | `@molecule/api-ai-decisions-jev` | TypeSafe's hosted Jev API | no model to host; English-first |
18
+ * | `@molecule/api-ai-decisions-llm` | whatever `ai` chat bond is bonded | no extra service; slower and costlier per call |
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * import { setProvider, requireProvider } from '@molecule/api-ai-decisions'
23
+ * import { provider as laya } from '@molecule/api-ai-decisions-laya'
24
+ *
25
+ * setProvider(laya) // at startup — reads LAYA_URL / LAYA_API_KEY on first use
26
+ *
27
+ * const { answers } = await requireProvider().decide({
28
+ * state: { subject: 'Charged twice', body: 'I was billed twice this month, I want my money back' },
29
+ * questions: {
30
+ * queue: {
31
+ * type: 'choice',
32
+ * instructions: 'Which team should handle this?',
33
+ * criteria: { billing: 'invoices, refunds, charges', tech: 'bugs, login, outages', other: 'anything else' },
34
+ * },
35
+ * urgency: { type: 'score', instructions: 'How upset is the customer?', criteria: ['calm', 'firm', 'angry', 'furious'] },
36
+ * refund: { type: 'yesNo', instructions: 'The customer is asking for a refund.' },
37
+ * },
38
+ * minConfidence: 0.7,
39
+ * })
40
+ *
41
+ * answers.queue.choice // 'billing'
42
+ * answers.urgency.level // 2 (answers.urgency.score is the expected level, e.g. 2.64)
43
+ * answers.refund.probability // 0.97
44
+ * if (answers.queue.lowConfidence) {
45
+ * // send to a human instead of auto-routing
46
+ * }
47
+ * ```
48
+ *
49
+ * @remarks
50
+ * - **Interface + accessor only.** Use the core's `setProvider(provider)` /
51
+ * `setProvider('name', provider)`, then `requireProvider()` or
52
+ * `getProviderByName('name')`.
53
+ * - **`confidence` is the probability of the reported answer** (`max` of the
54
+ * distribution), computed the same way by every bond. Vendors define their
55
+ * own `confidence` differently (Jev: `(n·pmax − 1)/(n − 1)`; Laya: normalized
56
+ * entropy), so a threshold copied from a vendor's docs does not transfer —
57
+ * pick thresholds on your own data.
58
+ * - **Base models are not a finished classifier for your domain.** Laya's own
59
+ * benchmarks put its base checkpoints near chance (0.36) on the
60
+ * typed-decisions set zero-shot; its fine-tuned checkpoint reaches 0.77.
61
+ * Measure accuracy on a labelled sample of YOUR inputs before letting an
62
+ * answer act unattended, and gate on `minConfidence` → a human or an LLM
63
+ * fallback for the rest.
64
+ * - **Probabilities ship over-confident** until calibrated on your traffic (Laya
65
+ * reports ECE 0.47 → 0.08 after temperature fitting). A 0.95 is not "right 95%
66
+ * of the time" until you have checked.
67
+ * - **Keep option lists short.** Accuracy drops past ~20 `choice` options on
68
+ * Laya (the option texts share a ~192-token window); Jev accepts up to 255,
69
+ * `laya-serve` refuses >100. `score` takes 2–10 levels on Jev.
70
+ * - **Keep state short.** Laya's English checkpoint reads 512 tokens (the
71
+ * multilingual one 1,024); longer state is truncated, not refused. Put the
72
+ * decisive text first.
73
+ * - **Never use it to generate text** — there is no text output. For a
74
+ * free-text label set that changes per request, use
75
+ * `@molecule/api-ai-classification`.
76
+ * - **Server-side only.** The provider key and the model host never belong in
77
+ * browser code.
78
+ *
79
+ * @e2e
80
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
81
+ * each item to this app's actual screens/flows, and check every box off one
82
+ * by one. A box you can't check is an integration bug to fix — not a skip:
83
+ * - [ ] Each flow that makes a decision (routing, triage, moderation, a
84
+ * guardrail) runs it from the real UI, and the answer DRIVES what happens
85
+ * next (the item lands in the chosen queue, the badge shows, the action is
86
+ * blocked) — not just printed.
87
+ * - [ ] Both directions: a clearly-billing input routes to billing AND a
88
+ * clearly-technical one routes elsewhere. One label for every input is a
89
+ * broken integration.
90
+ * - [ ] A low-confidence answer takes the app's fallback path (human review,
91
+ * "unsure" state) instead of being acted on.
92
+ * - [ ] Provider errors (service down, bad key) show a visible, recoverable
93
+ * state — never a blank screen or an unhandled rejection.
94
+ * - [ ] The call runs server-side: no provider request or key in the browser's
95
+ * Network tab.
96
+ *
97
+ * @module
98
+ */
99
+ export * from './browser-guard.js';
100
+ export * from './provider.js';
101
+ export * from './types.js';
102
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiGG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Typed AI decisions for molecule.dev.
3
+ *
4
+ * Ask typed questions about a piece of text or JSON and get probabilities back,
5
+ * not generated text: pick one option (`choice`), rate on an ordered scale
6
+ * (`score`), or test a statement (`yesNo`). Use it for routing and triage
7
+ * (which queue, how urgent), guardrails and moderation (is this spam, a
8
+ * jailbreak, a refund request), and any branch in your code that needs a
9
+ * judgment call about language. Many questions share one call.
10
+ *
11
+ * This core defines the `AIDecisionsProvider` contract and its bond accessor
12
+ * only. Bond one provider:
13
+ *
14
+ * | Bond | What answers | When |
15
+ * |---|---|---|
16
+ * | `@molecule/api-ai-decisions-laya` | the open-weights Laya model (Apache-2.0) on a `laya-serve` host you run — or any other self-hosted `/v1/systemone` server, such as Kev (Qwen-based, GPU/MLX) | self-hosted, ~30–40 ms/question on a GPU (Laya), data stays with you |
17
+ * | `@molecule/api-ai-decisions-jev` | TypeSafe's hosted Jev API | no model to host; English-first |
18
+ * | `@molecule/api-ai-decisions-llm` | whatever `ai` chat bond is bonded | no extra service; slower and costlier per call |
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * import { setProvider, requireProvider } from '@molecule/api-ai-decisions'
23
+ * import { provider as laya } from '@molecule/api-ai-decisions-laya'
24
+ *
25
+ * setProvider(laya) // at startup — reads LAYA_URL / LAYA_API_KEY on first use
26
+ *
27
+ * const { answers } = await requireProvider().decide({
28
+ * state: { subject: 'Charged twice', body: 'I was billed twice this month, I want my money back' },
29
+ * questions: {
30
+ * queue: {
31
+ * type: 'choice',
32
+ * instructions: 'Which team should handle this?',
33
+ * criteria: { billing: 'invoices, refunds, charges', tech: 'bugs, login, outages', other: 'anything else' },
34
+ * },
35
+ * urgency: { type: 'score', instructions: 'How upset is the customer?', criteria: ['calm', 'firm', 'angry', 'furious'] },
36
+ * refund: { type: 'yesNo', instructions: 'The customer is asking for a refund.' },
37
+ * },
38
+ * minConfidence: 0.7,
39
+ * })
40
+ *
41
+ * answers.queue.choice // 'billing'
42
+ * answers.urgency.level // 2 (answers.urgency.score is the expected level, e.g. 2.64)
43
+ * answers.refund.probability // 0.97
44
+ * if (answers.queue.lowConfidence) {
45
+ * // send to a human instead of auto-routing
46
+ * }
47
+ * ```
48
+ *
49
+ * @remarks
50
+ * - **Interface + accessor only.** Use the core's `setProvider(provider)` /
51
+ * `setProvider('name', provider)`, then `requireProvider()` or
52
+ * `getProviderByName('name')`.
53
+ * - **`confidence` is the probability of the reported answer** (`max` of the
54
+ * distribution), computed the same way by every bond. Vendors define their
55
+ * own `confidence` differently (Jev: `(n·pmax − 1)/(n − 1)`; Laya: normalized
56
+ * entropy), so a threshold copied from a vendor's docs does not transfer —
57
+ * pick thresholds on your own data.
58
+ * - **Base models are not a finished classifier for your domain.** Laya's own
59
+ * benchmarks put its base checkpoints near chance (0.36) on the
60
+ * typed-decisions set zero-shot; its fine-tuned checkpoint reaches 0.77.
61
+ * Measure accuracy on a labelled sample of YOUR inputs before letting an
62
+ * answer act unattended, and gate on `minConfidence` → a human or an LLM
63
+ * fallback for the rest.
64
+ * - **Probabilities ship over-confident** until calibrated on your traffic (Laya
65
+ * reports ECE 0.47 → 0.08 after temperature fitting). A 0.95 is not "right 95%
66
+ * of the time" until you have checked.
67
+ * - **Keep option lists short.** Accuracy drops past ~20 `choice` options on
68
+ * Laya (the option texts share a ~192-token window); Jev accepts up to 255,
69
+ * `laya-serve` refuses >100. `score` takes 2–10 levels on Jev.
70
+ * - **Keep state short.** Laya's English checkpoint reads 512 tokens (the
71
+ * multilingual one 1,024); longer state is truncated, not refused. Put the
72
+ * decisive text first.
73
+ * - **Never use it to generate text** — there is no text output. For a
74
+ * free-text label set that changes per request, use
75
+ * `@molecule/api-ai-classification`.
76
+ * - **Server-side only.** The provider key and the model host never belong in
77
+ * browser code.
78
+ *
79
+ * @e2e
80
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
81
+ * each item to this app's actual screens/flows, and check every box off one
82
+ * by one. A box you can't check is an integration bug to fix — not a skip:
83
+ * - [ ] Each flow that makes a decision (routing, triage, moderation, a
84
+ * guardrail) runs it from the real UI, and the answer DRIVES what happens
85
+ * next (the item lands in the chosen queue, the badge shows, the action is
86
+ * blocked) — not just printed.
87
+ * - [ ] Both directions: a clearly-billing input routes to billing AND a
88
+ * clearly-technical one routes elsewhere. One label for every input is a
89
+ * broken integration.
90
+ * - [ ] A low-confidence answer takes the app's fallback path (human review,
91
+ * "unsure" state) instead of being acted on.
92
+ * - [ ] Provider errors (service down, bad key) show a visible, recoverable
93
+ * state — never a blank screen or an unhandled rejection.
94
+ * - [ ] The call runs server-side: no provider request or key in the browser's
95
+ * Network tab.
96
+ *
97
+ * @module
98
+ */
99
+ export * from './browser-guard.js';
100
+ export * from './provider.js';
101
+ export * from './types.js';
102
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiGG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * AI decisions provider bond accessor (singleton + named, like the `ai` core).
3
+ *
4
+ * This core defines the `AIDecisionsProvider` contract only — bond a concrete
5
+ * implementation (`@molecule/api-ai-decisions-laya`, `-jev` or `-llm`).
6
+ *
7
+ * @module
8
+ */
9
+ import type { AIDecisionsProvider } from './types.js';
10
+ /**
11
+ * Registers an AI decisions provider in singleton mode.
12
+ *
13
+ * @param provider - The default provider implementation for this process.
14
+ */
15
+ export declare function setProvider(provider: AIDecisionsProvider): void;
16
+ /**
17
+ * Registers a named AI decisions provider under bond type `ai-decisions`.
18
+ *
19
+ * @param name - Provider identifier used when selecting the provider.
20
+ * @param provider - Concrete provider bound to `name`.
21
+ */
22
+ export declare function setProvider(name: string, provider: AIDecisionsProvider): void;
23
+ /**
24
+ * Retrieves the singleton AI decisions provider, or `null` if none is bonded.
25
+ *
26
+ * Falls back to a single named provider when no singleton is bonded. When
27
+ * multiple named providers are bonded the fallback declines (returns `null`)
28
+ * because the choice is ambiguous — use `getProviderByName(name)` instead.
29
+ *
30
+ * @returns The bonded AI decisions provider, or `null`.
31
+ */
32
+ export declare function getProvider(): AIDecisionsProvider | null;
33
+ /**
34
+ * Retrieves a named AI decisions provider, or `null` if not bonded.
35
+ *
36
+ * @param name - The provider name.
37
+ * @returns The named AI decisions provider, or `null`.
38
+ */
39
+ export declare function getProviderByName(name: string): AIDecisionsProvider | null;
40
+ /**
41
+ * Retrieves all named AI decisions providers as a Map keyed by name.
42
+ *
43
+ * @returns Map of provider name → AIDecisionsProvider.
44
+ */
45
+ export declare function getAllProviders(): Map<string, AIDecisionsProvider>;
46
+ /**
47
+ * Checks whether an AI decisions provider is currently bonded.
48
+ *
49
+ * @param name - Optional provider name. If omitted, checks the singleton.
50
+ * @returns `true` if the provider is bonded.
51
+ */
52
+ export declare function hasProvider(name?: string): boolean;
53
+ /**
54
+ * Retrieves the bonded AI decisions provider, throwing if none is bonded.
55
+ *
56
+ * @returns The bonded AI decisions provider.
57
+ * @throws {Error} When no provider is bonded.
58
+ */
59
+ export declare function requireProvider(): AIDecisionsProvider;
60
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAWH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AASrD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,mBAAmB,GAAG,IAAI,CAAA;AAChE;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,mBAAmB,GAAG,IAAI,CAAA;AAuB9E;;;;;;;;GAQG;AACH,wBAAgB,WAAW,IAAI,mBAAmB,GAAG,IAAI,CAKxD;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,mBAAmB,GAAG,IAAI,CAE1E;AAED;;;;GAIG;AACH,wBAAgB,eAAe,IAAI,GAAG,CAAC,MAAM,EAAE,mBAAmB,CAAC,CAElE;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAElD;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,IAAI,mBAAmB,CASrD"}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * AI decisions provider bond accessor (singleton + named, like the `ai` core).
3
+ *
4
+ * This core defines the `AIDecisionsProvider` contract only — bond a concrete
5
+ * implementation (`@molecule/api-ai-decisions-laya`, `-jev` or `-llm`).
6
+ *
7
+ * @module
8
+ */
9
+ import { bond, expectBond, get as bondGet, getAll as bondGetAll, isBonded, } from '@molecule/api-bond';
10
+ import { t } from '@molecule/api-i18n';
11
+ const BOND_TYPE = 'ai-decisions';
12
+ expectBond(BOND_TYPE);
13
+ /**
14
+ * Implementation that powers the `setProvider` overloads.
15
+ *
16
+ * @param nameOrProvider - Provider name (string) or the provider instance (singleton mode).
17
+ * @param provider - The provider instance (only when the first arg is a name).
18
+ */
19
+ export function setProvider(nameOrProvider, provider) {
20
+ if (typeof nameOrProvider === 'string') {
21
+ bond(BOND_TYPE, nameOrProvider, provider);
22
+ // Also register as singleton if none exists yet, so validateBonds() passes
23
+ // and getProvider() works as a fallback.
24
+ if (!isBonded(BOND_TYPE)) {
25
+ bond(BOND_TYPE, provider);
26
+ }
27
+ }
28
+ else {
29
+ bond(BOND_TYPE, nameOrProvider);
30
+ }
31
+ }
32
+ /**
33
+ * Retrieves the singleton AI decisions provider, or `null` if none is bonded.
34
+ *
35
+ * Falls back to a single named provider when no singleton is bonded. When
36
+ * multiple named providers are bonded the fallback declines (returns `null`)
37
+ * because the choice is ambiguous — use `getProviderByName(name)` instead.
38
+ *
39
+ * @returns The bonded AI decisions provider, or `null`.
40
+ */
41
+ export function getProvider() {
42
+ const singleton = bondGet(BOND_TYPE);
43
+ if (singleton)
44
+ return singleton;
45
+ const named = bondGetAll(BOND_TYPE);
46
+ return named.size === 1 ? (named.values().next().value ?? null) : null;
47
+ }
48
+ /**
49
+ * Retrieves a named AI decisions provider, or `null` if not bonded.
50
+ *
51
+ * @param name - The provider name.
52
+ * @returns The named AI decisions provider, or `null`.
53
+ */
54
+ export function getProviderByName(name) {
55
+ return bondGet(BOND_TYPE, name) ?? null;
56
+ }
57
+ /**
58
+ * Retrieves all named AI decisions providers as a Map keyed by name.
59
+ *
60
+ * @returns Map of provider name → AIDecisionsProvider.
61
+ */
62
+ export function getAllProviders() {
63
+ return bondGetAll(BOND_TYPE);
64
+ }
65
+ /**
66
+ * Checks whether an AI decisions provider is currently bonded.
67
+ *
68
+ * @param name - Optional provider name. If omitted, checks the singleton.
69
+ * @returns `true` if the provider is bonded.
70
+ */
71
+ export function hasProvider(name) {
72
+ return name ? isBonded(BOND_TYPE, name) : isBonded(BOND_TYPE);
73
+ }
74
+ /**
75
+ * Retrieves the bonded AI decisions provider, throwing if none is bonded.
76
+ *
77
+ * @returns The bonded AI decisions provider.
78
+ * @throws {Error} When no provider is bonded.
79
+ */
80
+ export function requireProvider() {
81
+ const found = getProvider();
82
+ if (found)
83
+ return found;
84
+ throw new Error(t('ai-decisions.error.noProvider', undefined, {
85
+ defaultValue: 'AI decisions provider not configured. Bond an ai-decisions provider (Laya, Jev or the LLM bond) first.',
86
+ }));
87
+ }
88
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EACL,IAAI,EACJ,UAAU,EACV,GAAG,IAAI,OAAO,EACd,MAAM,IAAI,UAAU,EACpB,QAAQ,GACT,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AAItC,MAAM,SAAS,GAAG,cAAc,CAAA;AAChC,UAAU,CAAC,SAAS,CAAC,CAAA;AAmBrB;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CACzB,c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,EAAE,CAAA;IAC3B,IAAI,KAAK;QAAE,OAAO,KAAK,CAAA;IACvB,MAAM,IAAI,KAAK,CACb,CAAC,CAAC,+BAA+B,EAAE,SAAS,EAAE;QAC5C,YAAY,EACV,wGAAwG;KAC3G,CAAC,CACH,CAAA;AACH,CAAC"}
@@ -0,0 +1,150 @@
1
+ /**
2
+ * AI decisions provider interface.
3
+ *
4
+ * A "decision" is a typed question about a piece of state (text, an email, a
5
+ * ticket, a JSON document) whose answer is a probability distribution, never
6
+ * generated text: pick one of N options (`choice`), place it on an ordered
7
+ * scale (`score`), or say how likely a statement is true (`yesNo`). One call
8
+ * asks any number of questions about the same state.
9
+ *
10
+ * The shape follows the `/v1/systemone` protocol spoken by TypeSafe's Jev and
11
+ * the open-weights Laya server, but it is provider-neutral: an LLM bond
12
+ * implements it too.
13
+ *
14
+ * @module
15
+ */
16
+ /**
17
+ * What the questions are about: plain text, or a JSON object / array (an
18
+ * email with headers, a ticket with metadata, a chat log).
19
+ */
20
+ export type DecisionState = string | Record<string, unknown> | unknown[];
21
+ /**
22
+ * Pick exactly one option.
23
+ */
24
+ export interface ChoiceQuestion {
25
+ type: 'choice';
26
+ /** What is being decided, e.g. `'Which team should handle this ticket?'`. */
27
+ instructions: string;
28
+ /**
29
+ * The options, keyed by the label you want back, each with a short
30
+ * description of when it applies. `{ billing: 'invoices, refunds', tech: 'bugs, outages' }`.
31
+ */
32
+ criteria: Record<string, string>;
33
+ }
34
+ /**
35
+ * Place the state on an ordered scale.
36
+ */
37
+ export interface ScoreQuestion {
38
+ type: 'score';
39
+ /** What is being rated, e.g. `'How urgent is this?'`. */
40
+ instructions: string;
41
+ /**
42
+ * The levels, lowest first. Level `i` is described by `criteria[i]`:
43
+ * `['calm', 'firm', 'angry', 'furious']`.
44
+ */
45
+ criteria: string[];
46
+ }
47
+ /**
48
+ * How likely is a statement true. (Called `noul` on the Jev/Laya wire.)
49
+ */
50
+ export interface YesNoQuestion {
51
+ type: 'yesNo';
52
+ /** The statement to test, e.g. `'The customer is asking for a refund.'`. */
53
+ instructions: string;
54
+ /** Optional descriptions of what counts as yes and as no. */
55
+ criteria?: {
56
+ yes?: string;
57
+ no?: string;
58
+ };
59
+ }
60
+ /** Any question a decision provider answers. */
61
+ export type DecisionQuestion = ChoiceQuestion | ScoreQuestion | YesNoQuestion;
62
+ /** Fields every answer carries. */
63
+ export interface AnswerBase {
64
+ /**
65
+ * Probability mass on the reported answer (the highest option probability;
66
+ * `max(p, 1 - p)` for yes/no), in `0..1`. Every bond computes it this same
67
+ * way from the probabilities, so a threshold means the same thing whichever
68
+ * provider is bonded — it is NOT the vendor's own `confidence` field.
69
+ */
70
+ confidence: number;
71
+ /** Set only when `minConfidence` was passed: `true` when `confidence` fell below it. */
72
+ lowConfidence?: boolean;
73
+ }
74
+ /** Answer to a {@link ChoiceQuestion}. */
75
+ export interface ChoiceAnswer extends AnswerBase {
76
+ type: 'choice';
77
+ /** The most likely option — always one of the question's `criteria` keys. */
78
+ choice: string;
79
+ /** Probability per option (every `criteria` key present), summing to ~1. */
80
+ probabilities: Record<string, number>;
81
+ }
82
+ /** Answer to a {@link ScoreQuestion}. */
83
+ export interface ScoreAnswer extends AnswerBase {
84
+ type: 'score';
85
+ /** Expected level index — may fall between levels (e.g. `2.64`). */
86
+ score: number;
87
+ /** The most likely level index (`0..criteria.length - 1`). */
88
+ level: number;
89
+ /** Probability per level, indexed like `criteria`. */
90
+ probabilities: number[];
91
+ }
92
+ /** Answer to a {@link YesNoQuestion}. */
93
+ export interface YesNoAnswer extends AnswerBase {
94
+ type: 'yesNo';
95
+ /** Probability that the statement is true, in `0..1`. */
96
+ probability: number;
97
+ /** `probability >= 0.5`. Prefer thresholding `probability` yourself when the cost of each mistake differs. */
98
+ answer: boolean;
99
+ }
100
+ /** Any answer. `answers[id].type` matches `questions[id].type`. */
101
+ export type DecisionAnswer = ChoiceAnswer | ScoreAnswer | YesNoAnswer;
102
+ /**
103
+ * Maps a questions object to its answers object, so
104
+ * `result.answers.department.choice` is typed when the questions are literal.
105
+ */
106
+ export type AnswersFor<Q extends Record<string, DecisionQuestion>> = {
107
+ [K in keyof Q]: Q[K] extends ChoiceQuestion ? ChoiceAnswer : Q[K] extends ScoreQuestion ? ScoreAnswer : YesNoAnswer;
108
+ };
109
+ /** Input to one decision request. */
110
+ export interface DecideInput<Q extends Record<string, DecisionQuestion> = Record<string, DecisionQuestion>> {
111
+ /** What the questions are about. */
112
+ state: DecisionState;
113
+ /** The questions, keyed by an id you choose; answers come back under the same ids. */
114
+ questions: Q;
115
+ /** Provider-specific model / checkpoint id (e.g. `'jev-latest'`, `'multilingual'`). */
116
+ model?: string;
117
+ /** Mark answers whose `confidence` is below this (`0..1`) with `lowConfidence: true`. */
118
+ minConfidence?: number;
119
+ /** Abort signal to cancel the in-flight request. */
120
+ signal?: AbortSignal;
121
+ }
122
+ /** Token usage, when the provider reports it. */
123
+ export interface DecisionUsage {
124
+ inputTokens: number;
125
+ outputTokens: number;
126
+ }
127
+ /** Result of one decision request. */
128
+ export interface DecideResult<Q extends Record<string, DecisionQuestion> = Record<string, DecisionQuestion>> {
129
+ /** One answer per question id. */
130
+ answers: AnswersFor<Q>;
131
+ /** The model or checkpoint that answered, when the provider says. */
132
+ model?: string;
133
+ /** Token usage, when reported. */
134
+ usage?: DecisionUsage;
135
+ }
136
+ /**
137
+ * AI decisions provider interface. Implemented by the Laya, Jev and LLM bonds.
138
+ */
139
+ export interface AIDecisionsProvider {
140
+ /** Provider identifier. */
141
+ readonly name: string;
142
+ /**
143
+ * Answer every question about `state`.
144
+ *
145
+ * @param input - The state, the questions and options.
146
+ * @returns One typed answer per question id.
147
+ */
148
+ decide<Q extends Record<string, DecisionQuestion>>(input: DecideInput<Q>): Promise<DecideResult<Q>>;
149
+ }
150
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;G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AAE,gBAAgB,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC;IAE7E,kCAAkC;IAClC,OAAO,EAAE,UAAU,CAAC,CAAC,CAAC,CAAA;IACtB,qEAAqE;IACrE,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,kCAAkC;IAClC,KAAK,CAAC,EAAE,aAAa,CAAA;CACtB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,2BAA2B;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IAErB;;;;;OAKG;IACH,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EAC/C,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,GACpB,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAA;CAC5B"}
package/dist/types.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * AI decisions provider interface.
3
+ *
4
+ * A "decision" is a typed question about a piece of state (text, an email, a
5
+ * ticket, a JSON document) whose answer is a probability distribution, never
6
+ * generated text: pick one of N options (`choice`), place it on an ordered
7
+ * scale (`score`), or say how likely a statement is true (`yesNo`). One call
8
+ * asks any number of questions about the same state.
9
+ *
10
+ * The shape follows the `/v1/systemone` protocol spoken by TypeSafe's Jev and
11
+ * the open-weights Laya server, but it is provider-neutral: an LLM bond
12
+ * implements it too.
13
+ *
14
+ * @module
15
+ */
16
+ export {};
17
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG"}
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@molecule/api-ai-decisions",
3
+ "version": "1.0.0",
4
+ "description": "Typed AI decisions for molecule.dev — answer choice, score and yes/no questions about text or JSON with calibrated probabilities, behind swappable bonds (Laya, Jev, any LLM)",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md"
22
+ ],
23
+ "keywords": [
24
+ "molecule",
25
+ "ai",
26
+ "decisions",
27
+ "classification",
28
+ "routing",
29
+ "triage",
30
+ "system-one"
31
+ ],
32
+ "license": "Apache-2.0",
33
+ "author": "Molecule Dev, Inc. (https://molecule.dev)",
34
+ "peerDependencies": {
35
+ "@molecule/api-bond": "^1.0.1",
36
+ "@molecule/api-i18n": "^1.0.1"
37
+ },
38
+ "devDependencies": {
39
+ "@molecule/api-bond": "1.0.2",
40
+ "@molecule/api-i18n": "1.0.3",
41
+ "@types/node": "26.1.2",
42
+ "typescript": "6.0.3",
43
+ "vitest": "4.1.11"
44
+ },
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "https://github.com/molecule-dev/molecule.git",
48
+ "directory": "packages/api/core/ai-decisions"
49
+ },
50
+ "homepage": "https://www.molecule.dev/packages/api-ai-decisions",
51
+ "bugs": "https://github.com/molecule-dev/molecule/issues",
52
+ "publishConfig": {
53
+ "access": "public"
54
+ }
55
+ }