@loomwork/reasoning 0.0.0-stage → 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.
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +82 -2
- package/dist/ReasoningRuntime.d.ts +22 -0
- package/dist/ReasoningRuntime.d.ts.map +1 -0
- package/dist/ReasoningRuntime.js +200 -0
- package/dist/ReasoningRuntime.js.map +1 -0
- package/dist/confidence.d.ts +5 -0
- package/dist/confidence.d.ts.map +1 -0
- package/dist/confidence.js +38 -0
- package/dist/confidence.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/router.d.ts +39 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +173 -0
- package/dist/router.js.map +1 -0
- package/dist/routing.bench.d.ts +2 -0
- package/dist/routing.bench.d.ts.map +1 -0
- package/dist/routing.bench.js +48 -0
- package/dist/routing.bench.js.map +1 -0
- package/dist/types.d.ts +134 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +54 -3
- package/src/ReasoningRuntime.ts +244 -0
- package/src/confidence.ts +37 -0
- package/src/index.ts +24 -0
- package/src/router.ts +225 -0
- package/src/routing.bench.ts +54 -0
- package/src/types.ts +178 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
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 reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and 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 Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
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 [yyyy] [name of copyright owner]
|
|
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 implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,83 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @loomwork/reasoning — model routing and elevation
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`ReasoningRuntime` picks a model from a set of tiered routes, scores the answer, and moves to a stronger
|
|
4
|
+
tier when the score is below a threshold. The stages are separate and replaceable: a `Router` chooses the
|
|
5
|
+
first route, a `ConfidenceSignal` scores each answer, and `elevateThreshold` (default 0.5) decides whether
|
|
6
|
+
to climb to the next tier. Pass `ctx.decide` and each routing and elevation choice is recorded, so a replay
|
|
7
|
+
makes the same choices. Use it when cheap-first routing with escalation is worth the extra calls.
|
|
8
|
+
`IntentRuntime` and `PlannerRuntime` accept it as `reasoning`, and `agentLoop$` calls it through an
|
|
9
|
+
`invoke` that runs each model call as a journaled effect.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import type { LlmProvider, LlmResponse } from "@loomwork/llm";
|
|
13
|
+
import { ReasoningRuntime, validatorConfidence } from "@loomwork/reasoning";
|
|
14
|
+
|
|
15
|
+
// Stand-ins for real providers: the cheap model answers badly, the strong one answers well.
|
|
16
|
+
const provider = (content: string): LlmProvider => ({
|
|
17
|
+
complete: async (): Promise<LlmResponse> => ({ content, stopReason: "end_turn" }),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
const reasoning = new ReasoningRuntime({
|
|
21
|
+
routes: [
|
|
22
|
+
{ id: "small", provider: provider("not json"), tier: 0 },
|
|
23
|
+
{ id: "large", provider: provider('{"ok":true}'), tier: 1 },
|
|
24
|
+
],
|
|
25
|
+
// Elevate until the output validates, instead of trusting the model's stop reason.
|
|
26
|
+
confidence: validatorConfidence((text) => {
|
|
27
|
+
try {
|
|
28
|
+
JSON.parse(text);
|
|
29
|
+
return true;
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const result = await reasoning.reason({ messages: [{ role: "user", content: "Reply with JSON." }] });
|
|
37
|
+
console.log(result.modelId, result.elevated); // "large" true; result.trace has one entry per call
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Surface
|
|
41
|
+
|
|
42
|
+
- **Runtime.** `new ReasoningRuntime({ routes, router?, confidence?, elevateThreshold?, cache? })`,
|
|
43
|
+
`reason(request, { decide?, invoke?, wrapCall?, decisionKey?, cacheScope?, signal? })` and
|
|
44
|
+
`availableRoutes`. A `ReasoningResult` carries `content`, `toolCalls`, `stopReason`, `usage`, `modelId`,
|
|
45
|
+
`confidence`, `elevated` and a `trace` of every call.
|
|
46
|
+
- **Routers.** `tagRouter` (default: the lowest tier whose `tags` include `strategy`, else the lowest
|
|
47
|
+
tier), `fixedRouter(id)`, `rankedRouter(rankings, { minSamples?, fallback? })`, `ucb1(stats, ...)` and
|
|
48
|
+
`epsilonGreedy(inner, { epsilon })`. The learned ones take per-route evidence such as
|
|
49
|
+
`outcomeAnalytics(events)` from `@loomwork/analytics`.
|
|
50
|
+
- **Confidence.** `stopReasonConfidence` (default: 0.9 for `end_turn` and `tool_use`, 0.3 for
|
|
51
|
+
`max_tokens`), `validatorConfidence(fn)` (1 or 0) and `constantConfidence(n)`.
|
|
52
|
+
- **Types.** `ModelRoute`, `ReasoningRequest` (with `strategy` and `maxTier`), `ModelInvoker`,
|
|
53
|
+
`ReasoningCache`, and `DecideFn`, which has the same shape as `ctx.decide`.
|
|
54
|
+
|
|
55
|
+
## Behaviour that surprises people
|
|
56
|
+
|
|
57
|
+
- **The direct path is outside the effect ring.** Without `invoke`, the runtime calls
|
|
58
|
+
`route.provider.complete` itself, so there is no authorization, metering or kill switch on that call. It
|
|
59
|
+
still runs `guardRequest`, so tainted content in an instruction position is refused. To make each model
|
|
60
|
+
call a journaled effect, supply an `invoke` (what `agentLoop$` does). With `invoke` the response cache is
|
|
61
|
+
bypassed, so whether a durable frame exists does not depend on a process-local cache.
|
|
62
|
+
- **Routing is recorded only if you pass `decide`.** Without it the choices run inline and are not
|
|
63
|
+
replay-stable.
|
|
64
|
+
- **Confidence is a pluggable signal, not a self-reported number.** The default reads only the stop
|
|
65
|
+
reason. `maxTier` caps elevation as a budget.
|
|
66
|
+
- **Elevation climbs one strictly higher tier at a time** and stops at the top tier or `maxTier`. A cache
|
|
67
|
+
is optional (`ReasoningCache` is just an interface) and, if you share one across tenants, scope it with
|
|
68
|
+
`cacheScope`.
|
|
69
|
+
- **`rankedRouter` can collapse onto what it already chose**, because arms it stops picking stop
|
|
70
|
+
generating outcomes. Wrap it in `epsilonGreedy` or use `ucb1`, which is deterministic (no RNG).
|
|
71
|
+
- **Captured reasoning is text-free here.** Reasoning parts leave this runtime in recorded form only;
|
|
72
|
+
readable text goes to a sidecar through `@loomwork/llm` (ADR 0133).
|
|
73
|
+
|
|
74
|
+
## Install
|
|
75
|
+
|
|
76
|
+
Unpublished for now: inside this repo use `workspace:*`; from a sibling checkout use a `link:` override (see [AGENTS.md](../../AGENTS.md)).
|
|
77
|
+
|
|
78
|
+
## See also
|
|
79
|
+
|
|
80
|
+
- API reference: section "`@loomwork/reasoning` — model routing & elevation" in [docs/api-reference.org](../../docs/api-reference.org).
|
|
81
|
+
- Guides: [user guide, section 15: reasoning runtime](../../docs/user-guide.md#15-reasoning-runtime--routing--elevation), [reasoning and memory](../../docs/loom-2.0/02-reasoning-and-memory.md).
|
|
82
|
+
- ADRs: [0016 execution runtime and decision seam](../../docs/adr/0016-loom-2.0-execution-runtime-and-decision-seam.md), [0121 one canonical agent loop](../../docs/adr/0121-one-canonical-agent-loop.md), [0133 model reasoning audit capture](../../docs/adr/0133-model-reasoning-audit-capture.md).
|
|
83
|
+
- Source: `packages/reasoning/src`.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ModelRoute, ReasonOptions, ReasoningRequest, ReasoningResult, ReasoningRuntimeConfig } from "./types";
|
|
2
|
+
export declare class ReasoningRuntime {
|
|
3
|
+
private readonly routes;
|
|
4
|
+
private readonly router;
|
|
5
|
+
private readonly confidence;
|
|
6
|
+
private readonly threshold;
|
|
7
|
+
private readonly cache;
|
|
8
|
+
private readonly indexById;
|
|
9
|
+
private readonly nextHigherIndex;
|
|
10
|
+
constructor(config: ReasoningRuntimeConfig);
|
|
11
|
+
/** Whether a response cache is configured (a host that shares it across tenants must scope it). */
|
|
12
|
+
get hasResponseCache(): boolean;
|
|
13
|
+
get availableRoutes(): ReadonlyArray<ModelRoute>;
|
|
14
|
+
reason(req: ReasoningRequest, opts?: ReasonOptions): Promise<ReasoningResult>;
|
|
15
|
+
private indexOf;
|
|
16
|
+
private call;
|
|
17
|
+
private callRaw;
|
|
18
|
+
/** Who the cached response belongs to: the explicit scope and the principal identity, if any. */
|
|
19
|
+
private scopeOf;
|
|
20
|
+
private keyFor;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=ReasoningRuntime.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ReasoningRuntime.d.ts","sourceRoot":"","sources":["../src/ReasoningRuntime.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAGV,UAAU,EACV,aAAa,EAEb,gBAAgB,EAChB,eAAe,EACf,sBAAsB,EAGvB,MAAM,SAAS,CAAC;AAqBjB,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAe;IACtC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAmB;IAC9C,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA6B;IAEnD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAsB;IAGhD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAW;gBAE/B,MAAM,EAAE,sBAAsB;IAyB1C,mGAAmG;IACnG,IAAI,gBAAgB,IAAI,OAAO,CAE9B;IAED,IAAI,eAAe,IAAI,aAAa,CAAC,UAAU,CAAC,CAE/C;IAEK,MAAM,CAAC,GAAG,EAAE,gBAAgB,EAAE,IAAI,GAAE,aAAkB,GAAG,OAAO,CAAC,eAAe,CAAC;IAiDvF,OAAO,CAAC,OAAO;YAQD,IAAI;YAUJ,OAAO;IAsErB,iGAAiG;IACjG,OAAO,CAAC,OAAO;IAUf,OAAO,CAAC,MAAM;CAQf"}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ReasoningRuntime = void 0;
|
|
4
|
+
const llm_1 = require("@loomwork/llm");
|
|
5
|
+
const confidence_1 = require("./confidence");
|
|
6
|
+
const router_1 = require("./router");
|
|
7
|
+
// No decision sink → run the decider inline (used by standalone callers outside a
|
|
8
|
+
// durable flow). When a flow passes ctx.decide, the choice is recorded instead.
|
|
9
|
+
const identityDecide = (_id, decider) => Promise.resolve(decider());
|
|
10
|
+
/**
|
|
11
|
+
* ADR 0133 - what leaves this runtime (a result a caller journals, a cache entry) carries reasoning
|
|
12
|
+
* only in its text-free recorded form: readable text goes to a sidecar through `createLlmEffect`, or
|
|
13
|
+
* nowhere. The same object when there is no reasoning (G2).
|
|
14
|
+
*/
|
|
15
|
+
function withTextFreeReasoning(res) {
|
|
16
|
+
return res.reasoning === undefined
|
|
17
|
+
? res
|
|
18
|
+
: { ...res, reasoning: (0, llm_1.textFreeReasoning)(res.reasoning) };
|
|
19
|
+
}
|
|
20
|
+
// The Reasoning Runtime (P3), built as composable stages: route → call → score →
|
|
21
|
+
// elevate. Each route/elevation is a logged decision (P9), so replay is deterministic
|
|
22
|
+
// while routing can improve run-to-run. The kernel stays untouched — this is an
|
|
23
|
+
// optional advisory module (P10).
|
|
24
|
+
class ReasoningRuntime {
|
|
25
|
+
routes;
|
|
26
|
+
router;
|
|
27
|
+
confidence;
|
|
28
|
+
threshold;
|
|
29
|
+
cache;
|
|
30
|
+
// id → position in the tier-sorted `routes`, so `byId` is O(1) not a linear scan.
|
|
31
|
+
indexById;
|
|
32
|
+
// For each route index, the index of the next route with a strictly higher tier
|
|
33
|
+
// (or -1). Precomputed once so elevation is an O(1) hop instead of an O(n) scan.
|
|
34
|
+
nextHigherIndex;
|
|
35
|
+
constructor(config) {
|
|
36
|
+
if (config.routes.length === 0) {
|
|
37
|
+
throw new Error("ReasoningRuntime requires at least one route");
|
|
38
|
+
}
|
|
39
|
+
// Sorted by tier once so elevation is a simple forward hop.
|
|
40
|
+
this.routes = [...config.routes].sort((a, b) => a.tier - b.tier);
|
|
41
|
+
this.router = config.router ?? router_1.tagRouter;
|
|
42
|
+
this.confidence = config.confidence ?? confidence_1.stopReasonConfidence;
|
|
43
|
+
this.threshold = config.elevateThreshold ?? 0.5;
|
|
44
|
+
this.cache = config.cache;
|
|
45
|
+
const n = this.routes.length;
|
|
46
|
+
this.indexById = new Map(this.routes.map((r, i) => [r.id, i]));
|
|
47
|
+
// Right-to-left pass (O(n)): the next strictly-higher tier for i is either its
|
|
48
|
+
// neighbour i+1 (if that neighbour's tier is greater) or, when i+1 shares i's
|
|
49
|
+
// tier, whatever the next-higher of i+1 already resolved to.
|
|
50
|
+
this.nextHigherIndex = new Array(n).fill(-1);
|
|
51
|
+
for (let i = n - 2; i >= 0; i--) {
|
|
52
|
+
this.nextHigherIndex[i] =
|
|
53
|
+
this.routes[i + 1].tier > this.routes[i].tier
|
|
54
|
+
? i + 1
|
|
55
|
+
: this.nextHigherIndex[i + 1];
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** Whether a response cache is configured (a host that shares it across tenants must scope it). */
|
|
59
|
+
get hasResponseCache() {
|
|
60
|
+
return this.cache !== undefined;
|
|
61
|
+
}
|
|
62
|
+
get availableRoutes() {
|
|
63
|
+
return this.routes;
|
|
64
|
+
}
|
|
65
|
+
async reason(req, opts = {}) {
|
|
66
|
+
const decide = opts.decide ?? identityDecide;
|
|
67
|
+
const key = opts.decisionKey ?? req.strategy ?? "default";
|
|
68
|
+
const signal = opts.signal ?? req.signal;
|
|
69
|
+
const maxTier = req.maxTier ?? this.routes[this.routes.length - 1].tier;
|
|
70
|
+
// Stage 1 — route (a logged decision).
|
|
71
|
+
const initialId = await decide(`reason:${key}:route`, () => this.router.select(req, this.routes).id);
|
|
72
|
+
let currentIdx = this.indexOf(initialId);
|
|
73
|
+
let current = this.routes[currentIdx];
|
|
74
|
+
const trace = [];
|
|
75
|
+
let res = await this.call(current, req, signal, opts);
|
|
76
|
+
let confidence = await this.confidence.score(req, res);
|
|
77
|
+
trace.push({ modelId: current.id, tier: current.tier, confidence, elevated: false });
|
|
78
|
+
// Stage 2 — elevate while low-confidence and a higher tier is within budget.
|
|
79
|
+
let step = 0;
|
|
80
|
+
while (confidence < this.threshold) {
|
|
81
|
+
const nextIdx = this.nextHigherIndex[currentIdx];
|
|
82
|
+
if (nextIdx === -1)
|
|
83
|
+
break;
|
|
84
|
+
const next = this.routes[nextIdx];
|
|
85
|
+
if (next.tier > maxTier)
|
|
86
|
+
break;
|
|
87
|
+
step += 1;
|
|
88
|
+
const chosenId = await decide(`reason:${key}:elevate:${step}`, () => next.id);
|
|
89
|
+
currentIdx = this.indexOf(chosenId);
|
|
90
|
+
current = this.routes[currentIdx];
|
|
91
|
+
res = await this.call(current, req, signal, opts);
|
|
92
|
+
confidence = await this.confidence.score(req, res);
|
|
93
|
+
trace.push({ modelId: current.id, tier: current.tier, confidence, elevated: true });
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
content: res.content,
|
|
97
|
+
...(res.toolCalls !== undefined && { toolCalls: res.toolCalls }),
|
|
98
|
+
stopReason: res.stopReason,
|
|
99
|
+
...(res.usage !== undefined && { usage: res.usage }),
|
|
100
|
+
...(res.reasoning !== undefined && { reasoning: res.reasoning }),
|
|
101
|
+
...(res.layout !== undefined && { layout: res.layout }),
|
|
102
|
+
modelId: current.id,
|
|
103
|
+
confidence,
|
|
104
|
+
elevated: trace.length > 1,
|
|
105
|
+
trace,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
indexOf(id) {
|
|
109
|
+
const idx = this.indexById.get(id);
|
|
110
|
+
if (idx === undefined) {
|
|
111
|
+
throw new Error(`ReasoningRuntime: unknown route "${id}"`);
|
|
112
|
+
}
|
|
113
|
+
return idx;
|
|
114
|
+
}
|
|
115
|
+
async call(route, req, signal, opts) {
|
|
116
|
+
// Every path (an invoker, a wrapper serving a record, the cache, the provider) is text-free on exit.
|
|
117
|
+
return withTextFreeReasoning(await this.callRaw(route, req, signal, opts));
|
|
118
|
+
}
|
|
119
|
+
async callRaw(route, req, signal, opts) {
|
|
120
|
+
const invoke = opts.invoke;
|
|
121
|
+
if (invoke !== undefined) {
|
|
122
|
+
// R9 — the host makes the call (as an effect, inside the ring). No cache: see ModelInvoker.
|
|
123
|
+
// `guardRequest` still runs here, so a custom invoker that is NOT an effect cannot
|
|
124
|
+
// receive tainted content either; the effect it resolves to guards again, harmlessly
|
|
125
|
+
// (a guarded request is untainted, and guarding it is the identity).
|
|
126
|
+
const guarded = (0, llm_1.guardRequest)({
|
|
127
|
+
messages: req.messages,
|
|
128
|
+
...(req.system !== undefined && { system: req.system }),
|
|
129
|
+
...(req.tools !== undefined && { tools: req.tools }),
|
|
130
|
+
...(req.maxTokens !== undefined && { maxTokens: req.maxTokens }),
|
|
131
|
+
...(req.temperature !== undefined && { temperature: req.temperature }),
|
|
132
|
+
});
|
|
133
|
+
return invoke(route, {
|
|
134
|
+
messages: guarded.messages,
|
|
135
|
+
...(guarded.system !== undefined && { system: guarded.system }),
|
|
136
|
+
...(guarded.tools !== undefined && { tools: guarded.tools }),
|
|
137
|
+
...(guarded.maxTokens !== undefined && { maxTokens: guarded.maxTokens }),
|
|
138
|
+
...(guarded.temperature !== undefined && { temperature: guarded.temperature }),
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
// R2 — the prompt boundary, on the reasoning path. This is the single site where
|
|
142
|
+
// this runtime hands a request to a provider, so it is the one place the check
|
|
143
|
+
// belongs. `ReasoningRequest` types its content as `string`, but a `string`
|
|
144
|
+
// annotation is a claim, not a check: a tainted MCP tool description reaches
|
|
145
|
+
// here through exactly such a field. `guardRequest` refuses taint in every
|
|
146
|
+
// instruction position and returns an untainted request unchanged.
|
|
147
|
+
const guarded = (0, llm_1.guardRequest)({
|
|
148
|
+
messages: req.messages,
|
|
149
|
+
...(req.system !== undefined && { system: req.system }),
|
|
150
|
+
...(req.tools !== undefined && { tools: req.tools }),
|
|
151
|
+
...(req.maxTokens !== undefined && { maxTokens: req.maxTokens }),
|
|
152
|
+
...(req.temperature !== undefined && { temperature: req.temperature }),
|
|
153
|
+
...(signal !== undefined && { signal }),
|
|
154
|
+
});
|
|
155
|
+
// R5 — a third-party provider may not check its own modalities; this runtime does.
|
|
156
|
+
(0, llm_1.assertRequestSupported)(guarded, route.provider.capabilities);
|
|
157
|
+
// The cache key is the request AS WRITTEN (addresses, not bytes); computed before the host's
|
|
158
|
+
// wrapper so a journaled call and an unjournaled one share the same entries.
|
|
159
|
+
const cacheKey = this.cache !== undefined ? this.keyFor(route.id, req, this.scopeOf(opts)) : undefined;
|
|
160
|
+
const run = async () => {
|
|
161
|
+
if (cacheKey !== undefined) {
|
|
162
|
+
const hit = this.cache?.get(cacheKey);
|
|
163
|
+
if (hit !== undefined)
|
|
164
|
+
return hit;
|
|
165
|
+
}
|
|
166
|
+
// R5 — refs become bytes only now: after the capability check (a refusal must precede any
|
|
167
|
+
// fetch) and after the cache lookup, whose key is the request as written.
|
|
168
|
+
// ADR 0133: reasoning is reduced BEFORE the cache sees it, so a shared cache never holds text.
|
|
169
|
+
const res = withTextFreeReasoning(await route.provider.complete(await (0, llm_1.resolveRequestContent)(guarded, opts.resolveContent, {
|
|
170
|
+
...(signal !== undefined && { signal }),
|
|
171
|
+
// Absent only when there is no resolver; a ref then fails before any fetch.
|
|
172
|
+
context: opts.resolveContext ?? { executionId: "" },
|
|
173
|
+
})));
|
|
174
|
+
if (cacheKey !== undefined)
|
|
175
|
+
this.cache?.set(cacheKey, res);
|
|
176
|
+
return res;
|
|
177
|
+
};
|
|
178
|
+
return opts.wrapCall !== undefined ? opts.wrapCall(route, run) : run();
|
|
179
|
+
}
|
|
180
|
+
/** Who the cached response belongs to: the explicit scope and the principal identity, if any. */
|
|
181
|
+
scopeOf(opts) {
|
|
182
|
+
const p = opts.resolveContext?.principal;
|
|
183
|
+
const who = p === undefined
|
|
184
|
+
? undefined
|
|
185
|
+
: JSON.stringify([p.tenant ?? null, p.actor ?? null, p.onBehalfOf ?? null]);
|
|
186
|
+
if (opts.cacheScope === undefined && who === undefined)
|
|
187
|
+
return undefined;
|
|
188
|
+
return JSON.stringify([opts.cacheScope ?? null, who ?? null]);
|
|
189
|
+
}
|
|
190
|
+
keyFor(modelId, req, scope) {
|
|
191
|
+
return JSON.stringify({
|
|
192
|
+
m: modelId,
|
|
193
|
+
s: req.system,
|
|
194
|
+
msgs: req.messages,
|
|
195
|
+
...(scope !== undefined && { c: scope }),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
exports.ReasoningRuntime = ReasoningRuntime;
|
|
200
|
+
//# sourceMappingURL=ReasoningRuntime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ReasoningRuntime.js","sourceRoot":"","sources":["../src/ReasoningRuntime.ts"],"names":[],"mappings":";;;AACA,uCAKuB;AACvB,6CAAoD;AACpD,qCAAqC;AAcrC,kFAAkF;AAClF,gFAAgF;AAChF,MAAM,cAAc,GAAa,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;AAE9E;;;;GAIG;AACH,SAAS,qBAAqB,CAAC,GAAgB;IAC7C,OAAO,GAAG,CAAC,SAAS,KAAK,SAAS;QAChC,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,EAAE,GAAG,GAAG,EAAE,SAAS,EAAE,IAAA,uBAAiB,EAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC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,IAAI,GAAG,KAAK,SAAS;YAAE,OAAO,SAAS,CAAC;QACzE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,UAAU,IAAI,IAAI,EAAE,GAAG,IAAI,IAAI,CAAC,CAAC,CAAC;IAChE,CAAC;IAEO,MAAM,CAAC,OAAe,EAAE,GAAqB,EAAE,KAAc;QACnE,OAAO,IAAI,CAAC,SAAS,CAAC;YACpB,CAAC,EAAE,OAAO;YACV,CAAC,EAAE,GAAG,CAAC,MAAM;YACb,IAAI,EAAE,GAAG,CAAC,QAAQ;YAClB,GAAG,CAAC,KAAK,KAAK,SAAS,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC;SACzC,CAAC,CAAC;IACL,CAAC;CACF;AA1MD,4CA0MC"}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { ConfidenceSignal } from "./types";
|
|
2
|
+
export declare const stopReasonConfidence: ConfidenceSignal;
|
|
3
|
+
export declare function validatorConfidence(validate: (content: string) => boolean): ConfidenceSignal;
|
|
4
|
+
export declare function constantConfidence(value: number): ConfidenceSignal;
|
|
5
|
+
//# sourceMappingURL=confidence.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"confidence.d.ts","sourceRoot":"","sources":["../src/confidence.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAoB,MAAM,SAAS,CAAC;AAKlE,eAAO,MAAM,oBAAoB,EAAE,gBAalC,CAAC;AAKF,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,GAAG,gBAAgB,CAM5F;AAID,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,gBAAgB,CAElE"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.stopReasonConfidence = void 0;
|
|
4
|
+
exports.validatorConfidence = validatorConfidence;
|
|
5
|
+
exports.constantConfidence = constantConfidence;
|
|
6
|
+
// Honest, pluggable confidence — NOT a magic self-reported number. The default uses
|
|
7
|
+
// the model's stop reason, the one signal every provider emits: a truncated answer
|
|
8
|
+
// (max_tokens) is low-confidence and should elevate; a clean finish is high.
|
|
9
|
+
exports.stopReasonConfidence = {
|
|
10
|
+
score(_req, res) {
|
|
11
|
+
switch (res.stopReason) {
|
|
12
|
+
case "end_turn":
|
|
13
|
+
return 0.9;
|
|
14
|
+
case "tool_use":
|
|
15
|
+
return 0.9;
|
|
16
|
+
case "max_tokens":
|
|
17
|
+
return 0.3;
|
|
18
|
+
default:
|
|
19
|
+
return 0.5;
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
// Confidence from a caller-supplied validator: pass → 1, fail → 0. Use for structured
|
|
24
|
+
// outputs ("did it parse as the expected JSON / a known capability id?"). This turns
|
|
25
|
+
// elevation into "retry on a stronger model until the output validates."
|
|
26
|
+
function validatorConfidence(validate) {
|
|
27
|
+
return {
|
|
28
|
+
score(_req, res) {
|
|
29
|
+
return validate(res.content) ? 1 : 0;
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
// Agreement across a fixed constant — always returns the given value. Useful to force
|
|
34
|
+
// (never elevate → 1) or always-elevate (→ 0) in tests and pins.
|
|
35
|
+
function constantConfidence(value) {
|
|
36
|
+
return { score: () => value };
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=confidence.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"confidence.js","sourceRoot":"","sources":["../src/confidence.ts"],"names":[],"mappings":";;;AAwBA,kDAMC;AAID,gDAEC;AAjCD,oFAAoF;AACpF,mFAAmF;AACnF,6EAA6E;AAChE,QAAA,oBAAoB,GAAqB;IACpD,KAAK,CAAC,IAAsB,EAAE,GAAgB;QAC5C,QAAQ,GAAG,CAAC,UAAU,EAAE,CAAC;YACvB,KAAK,UAAU;gBACb,OAAO,GAAG,CAAC;YACb,KAAK,UAAU;gBACb,OAAO,GAAG,CAAC;YACb,KAAK,YAAY;gBACf,OAAO,GAAG,CAAC;YACb;gBACE,OAAO,GAAG,CAAC;QACf,CAAC;IACH,CAAC;CACF,CAAC;AAEF,sFAAsF;AACtF,qFAAqF;AACrF,yEAAyE;AACzE,SAAgB,mBAAmB,CAAC,QAAsC;IACxE,OAAO;QACL,KAAK,CAAC,IAAsB,EAAE,GAAgB;YAC5C,OAAO,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,CAAC;KACF,CAAC;AACJ,CAAC;AAED,sFAAsF;AACtF,iEAAiE;AACjE,SAAgB,kBAAkB,CAAC,KAAa;IAC9C,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,KAAK,EAAE,CAAC;AAChC,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { ReasoningRuntime } from "./ReasoningRuntime";
|
|
2
|
+
export { tagRouter, fixedRouter, rankedRouter, ucb1, epsilonGreedy } from "./router";
|
|
3
|
+
export type { ArmStats, EpsilonGreedyOptions, RankedRouterOptions, Rankings, Ucb1Options, } from "./router";
|
|
4
|
+
export { stopReasonConfidence, validatorConfidence, constantConfidence } from "./confidence";
|
|
5
|
+
export type { ConfidenceSignal, DecideFn, ModelCallRequest, ModelInvoker, ModelRoute, ReasonOptions, ReasoningCache, ReasoningRequest, ReasoningResult, ReasoningRuntimeConfig, ReasoningTraceEntry, Router, } from "./types";
|
|
6
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACrF,YAAY,EACV,QAAQ,EACR,oBAAoB,EACpB,mBAAmB,EACnB,QAAQ,EACR,WAAW,GACZ,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAC7F,YAAY,EACV,gBAAgB,EAChB,QAAQ,EACR,gBAAgB,EAChB,YAAY,EACZ,UAAU,EACV,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,sBAAsB,EACtB,mBAAmB,EACnB,MAAM,GACP,MAAM,SAAS,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.constantConfidence = exports.validatorConfidence = exports.stopReasonConfidence = exports.epsilonGreedy = exports.ucb1 = exports.rankedRouter = exports.fixedRouter = exports.tagRouter = exports.ReasoningRuntime = void 0;
|
|
4
|
+
var ReasoningRuntime_1 = require("./ReasoningRuntime");
|
|
5
|
+
Object.defineProperty(exports, "ReasoningRuntime", { enumerable: true, get: function () { return ReasoningRuntime_1.ReasoningRuntime; } });
|
|
6
|
+
var router_1 = require("./router");
|
|
7
|
+
Object.defineProperty(exports, "tagRouter", { enumerable: true, get: function () { return router_1.tagRouter; } });
|
|
8
|
+
Object.defineProperty(exports, "fixedRouter", { enumerable: true, get: function () { return router_1.fixedRouter; } });
|
|
9
|
+
Object.defineProperty(exports, "rankedRouter", { enumerable: true, get: function () { return router_1.rankedRouter; } });
|
|
10
|
+
Object.defineProperty(exports, "ucb1", { enumerable: true, get: function () { return router_1.ucb1; } });
|
|
11
|
+
Object.defineProperty(exports, "epsilonGreedy", { enumerable: true, get: function () { return router_1.epsilonGreedy; } });
|
|
12
|
+
var confidence_1 = require("./confidence");
|
|
13
|
+
Object.defineProperty(exports, "stopReasonConfidence", { enumerable: true, get: function () { return confidence_1.stopReasonConfidence; } });
|
|
14
|
+
Object.defineProperty(exports, "validatorConfidence", { enumerable: true, get: function () { return confidence_1.validatorConfidence; } });
|
|
15
|
+
Object.defineProperty(exports, "constantConfidence", { enumerable: true, get: function () { return confidence_1.constantConfidence; } });
|
|
16
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,uDAAsD;AAA7C,oHAAA,gBAAgB,OAAA;AACzB,mCAAqF;AAA5E,mGAAA,SAAS,OAAA;AAAE,qGAAA,WAAW,OAAA;AAAE,sGAAA,YAAY,OAAA;AAAE,8FAAA,IAAI,OAAA;AAAE,uGAAA,aAAa,OAAA;AAQlE,2CAA6F;AAApF,kHAAA,oBAAoB,OAAA;AAAE,iHAAA,mBAAmB,OAAA;AAAE,gHAAA,kBAAkB,OAAA"}
|