@opengeni/decisions 0.0.0-stage → 4.3.1

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,190 @@
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
+ Copyright 2026 Cloudgeni-ai
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,55 @@
1
- # Temporary Holding Version
1
+ # `@opengeni/decisions`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A decision model is a fast typed judge, not a conversational agent. It evaluates
4
+ shared input against named questions and returns predicate probabilities, a choice,
5
+ or a score. Consumers own the rubric and thresholds; adapters own the provider wire
6
+ protocol, cancellation, answer validation and usage receipt.
7
+
8
+ ```ts
9
+ import { createHttpDecisionModel, predicate } from "@opengeni/decisions";
10
+
11
+ const model = createHttpDecisionModel({
12
+ provider: "openrouter",
13
+ model: "typesafe/jev-1.13",
14
+ apiKey, // explicitly supplied by the application
15
+ });
16
+ const result = await model.decide(
17
+ { message: "The checkout page is blank" },
18
+ {
19
+ defect: predicate("Does this describe broken behavior?"),
20
+ team: { type: "choice", instructions: "Which team owns it?", criteria: { ui: "Rendering", billing: "Payments" } },
21
+ urgency: { type: "score", instructions: "How urgent?", criteria: ["Cosmetic", "Blocking"] },
22
+ },
23
+ { signal, onUsage: recordUsage },
24
+ );
25
+ if (result.answers.defect.type === "predicate") {
26
+ console.log(result.answers.defect.probability);
27
+ }
28
+ ```
29
+
30
+ `DecisionModel.decide(input, questions, options?)` returns `{answers, usage}`.
31
+ Answers may be typed refusals. Choice values must be declared keys; a score ranges
32
+ from zero through `criteria.length - 1` and may be fractional. Probabilities are
33
+ finite values in `[0,1]`, not a claim of calibration. The complete named answer set
34
+ is validated; consumers must explicitly handle refusals. Neither tool discovery
35
+ nor code search treats a refusal as a valid score.
36
+
37
+ The OpenAI adapter calls `/v1/decisions`; OpenRouter calls
38
+ `/api/alpha/decisions`. They are distinct typed protocols, not chat-completions
39
+ requests. There is no prose fallback, credential discovery, retry policy or new
40
+ timeout. The optional `endpoint` is a full URL; caller cancellation is forwarded.
41
+ The existing `@opengeni/jev` package exports `createJevDecisionModel(client)` and
42
+ retains its established chunking/retry policy. The dependency points from Jev to
43
+ this package, not both ways.
44
+
45
+ Usage includes actual model/provider identity when returned, successful request
46
+ chunks, nullable token counts and nullable USD cost. `costSource` distinguishes
47
+ provider-reported charges, explicit estimates and unknown cost. HTTP adapters call
48
+ `onUsage` before answer validation; an invalid answer can still have a charge.
49
+ Missing usage is never invented. The legacy Jev client supplies its existing
50
+ input-cost estimate and may fail before an aggregate receipt exists; unknown
51
+ failed-call charges are not proof of zero spend. The hook is application-owned
52
+ accounting, not a built-in customer debit.
53
+
54
+ See [deployment configuration and verified backend boundaries](../../docs/decision-models.md)
55
+ and [tool-discovery evaluation](../../scripts/tool-discovery-eval/README.md).
package/dist/http.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { type DecisionModel, type DecisionQuestion } from "./types.js";
2
+ export type HttpDecisionModelOptions = {
3
+ provider: "openai" | "openrouter";
4
+ model: string;
5
+ apiKey: string;
6
+ /** Full typed endpoint; never a chat-completions fallback. */
7
+ endpoint?: string;
8
+ fetch?: typeof fetch;
9
+ /** Optional deployment rate, explicitly an estimate, not a billed receipt. */
10
+ inputUsdPerMillion?: number;
11
+ };
12
+ export declare const OPENAI_DECISIONS_ENDPOINT = "https://api.openai.com/v1/decisions";
13
+ export declare const OPENROUTER_DECISIONS_ENDPOINT = "https://openrouter.ai/api/alpha/decisions";
14
+ export declare function openAiDecisionRequest(model: string, input: unknown, questions: Record<string, DecisionQuestion>): {
15
+ model: string;
16
+ input: string;
17
+ questions: ({
18
+ name: string;
19
+ type: "predicate";
20
+ instructions: string;
21
+ choices?: never;
22
+ levels?: never;
23
+ } | {
24
+ name: string;
25
+ type: "choice";
26
+ instructions: string;
27
+ choices: {
28
+ value: string;
29
+ description: string;
30
+ }[];
31
+ levels?: never;
32
+ } | {
33
+ choices?: never;
34
+ name: string;
35
+ type: "score";
36
+ instructions: string;
37
+ levels: {
38
+ label: string;
39
+ description: string;
40
+ }[];
41
+ })[];
42
+ };
43
+ export declare function openRouterDecisionRequest(model: string, input: unknown, questions: Record<string, DecisionQuestion>): {
44
+ model: string;
45
+ state: unknown;
46
+ questions: {
47
+ [k: string]: {
48
+ instructions: import("./types.js").DecisionInstructions;
49
+ criteria: Record<string, import("./types.js").DecisionInstructions | null>;
50
+ type: string;
51
+ } | {
52
+ instructions: import("./types.js").DecisionInstructions;
53
+ criteria?: {
54
+ true?: import("./types.js").DecisionInstructions;
55
+ false?: import("./types.js").DecisionInstructions;
56
+ };
57
+ type: string;
58
+ } | {
59
+ instructions: import("./types.js").DecisionInstructions;
60
+ criteria: import("./types.js").DecisionInstructions[];
61
+ type: string;
62
+ };
63
+ };
64
+ };
65
+ /** Real typed endpoints only. Caller cancellation is forwarded; no new timeout/retry policy. */
66
+ export declare function createHttpDecisionModel(config: HttpDecisionModelOptions): DecisionModel;
@@ -0,0 +1,2 @@
1
+ export * from "./types.js";
2
+ export * from "./http.js";
package/dist/index.js ADDED
@@ -0,0 +1,213 @@
1
+ // src/types.ts
2
+ function predicate(instructions, criteria) {
3
+ return criteria ? { type: "predicate", instructions, criteria } : { type: "predicate", instructions };
4
+ }
5
+ var DecisionError = class extends Error {
6
+ status;
7
+ code;
8
+ constructor(message, options = {}) {
9
+ super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
10
+ this.name = new.target.name;
11
+ this.status = options.status;
12
+ this.code = options.code;
13
+ }
14
+ };
15
+ var DecisionUnavailableError = class extends DecisionError {
16
+ };
17
+ var DecisionRequestError = class extends DecisionError {
18
+ };
19
+ var isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
20
+ var probability = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
21
+ function validateDecisionAnswers(questions, answers) {
22
+ const invalid = () => {
23
+ throw new DecisionUnavailableError("Decision model returned invalid typed answers");
24
+ };
25
+ if (!isRecord(answers)) return invalid();
26
+ const names = Object.keys(questions);
27
+ if (Object.keys(answers).length !== names.length) return invalid();
28
+ for (const name of names) {
29
+ const answer = answers[name];
30
+ const question = questions[name];
31
+ if (!isRecord(answer)) return invalid();
32
+ if (answer.type === "refusal") {
33
+ if (answer.reason !== void 0 && typeof answer.reason !== "string") return invalid();
34
+ continue;
35
+ }
36
+ if (answer.type !== question.type) return invalid();
37
+ if (question.type === "predicate" && !probability(answer.probability)) return invalid();
38
+ if (question.type === "choice" && (typeof answer.choice !== "string" || !Object.hasOwn(question.criteria, answer.choice)))
39
+ return invalid();
40
+ if (question.type === "score" && (typeof answer.score !== "number" || !Number.isFinite(answer.score) || answer.score < 0 || answer.score > question.criteria.length - 1))
41
+ return invalid();
42
+ if (answer.confidence !== void 0 && !probability(answer.confidence)) return invalid();
43
+ if (answer.probabilities !== void 0) {
44
+ if (!isRecord(answer.probabilities) || Object.values(answer.probabilities).some((p) => !probability(p)))
45
+ return invalid();
46
+ const allowed = question.type === "choice" ? Object.keys(question.criteria) : question.type === "score" ? question.criteria.map((_, i) => String(i)) : [];
47
+ if (Object.keys(answer.probabilities).some((key) => !allowed.includes(key))) return invalid();
48
+ }
49
+ }
50
+ return answers;
51
+ }
52
+
53
+ // src/http.ts
54
+ var OPENAI_DECISIONS_ENDPOINT = "https://api.openai.com/v1/decisions";
55
+ var OPENROUTER_DECISIONS_ENDPOINT = "https://openrouter.ai/api/alpha/decisions";
56
+ var text = (value) => typeof value === "string" ? value : JSON.stringify(value);
57
+ var count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
58
+ function openAiDecisionRequest(model, input, questions) {
59
+ return {
60
+ model,
61
+ input: text(input),
62
+ questions: Object.entries(questions).map(([name, question]) => {
63
+ if (question.type === "predicate")
64
+ return {
65
+ name,
66
+ type: question.type,
67
+ instructions: question.criteria ? text({ instructions: question.instructions, criteria: question.criteria }) : text(question.instructions)
68
+ };
69
+ if (question.type === "choice")
70
+ return {
71
+ name,
72
+ type: question.type,
73
+ instructions: text(question.instructions),
74
+ choices: Object.entries(question.criteria).map(([value, description]) => ({
75
+ value,
76
+ description: description === null ? value : text(description)
77
+ }))
78
+ };
79
+ return {
80
+ name,
81
+ type: question.type,
82
+ instructions: text(question.instructions),
83
+ levels: question.criteria.map((description, index) => ({
84
+ label: String(index),
85
+ description: text(description)
86
+ }))
87
+ };
88
+ })
89
+ };
90
+ }
91
+ function openRouterDecisionRequest(model, input, questions) {
92
+ return {
93
+ model,
94
+ state: input,
95
+ questions: Object.fromEntries(
96
+ Object.entries(questions).map(([name, question]) => [
97
+ name,
98
+ { ...question, type: question.type === "predicate" ? "noul" : question.type }
99
+ ])
100
+ )
101
+ };
102
+ }
103
+ function normalizeAnswers(raw, provider) {
104
+ if (provider === "openrouter") {
105
+ if (!isRecord(raw))
106
+ throw new DecisionUnavailableError("Decision response has no named answers");
107
+ return Object.fromEntries(
108
+ Object.entries(raw).map(([name, answer]) => [
109
+ name,
110
+ isRecord(answer) && answer.type === "noul" ? { type: "predicate", probability: answer.noul } : answer
111
+ ])
112
+ );
113
+ }
114
+ if (!Array.isArray(raw))
115
+ throw new DecisionUnavailableError("Decision response has no answer array");
116
+ const answers = /* @__PURE__ */ Object.create(null);
117
+ for (const value of raw) {
118
+ if (!isRecord(value) || typeof value.name !== "string" || Object.hasOwn(answers, value.name))
119
+ throw new DecisionUnavailableError("Decision response has invalid or duplicate answer names");
120
+ const { name, probabilities, ...answer } = value;
121
+ if (probabilities !== void 0) {
122
+ if (!Array.isArray(probabilities))
123
+ throw new DecisionUnavailableError("Decision response has invalid probabilities");
124
+ const mapped = /* @__PURE__ */ Object.create(null);
125
+ for (const entry of probabilities) {
126
+ if (!isRecord(entry) || typeof entry.value !== "string" && typeof entry.value !== "number" || Object.hasOwn(mapped, String(entry.value)))
127
+ throw new DecisionUnavailableError("Decision response has invalid probability labels");
128
+ mapped[String(entry.value)] = entry.probability;
129
+ }
130
+ answer.probabilities = mapped;
131
+ }
132
+ answers[name] = answer;
133
+ }
134
+ return answers;
135
+ }
136
+ function createHttpDecisionModel(config) {
137
+ if (!config.apiKey || !config.model)
138
+ throw new DecisionRequestError("Decision model and credential must be configured");
139
+ const endpoint = config.endpoint ?? (config.provider === "openai" ? OPENAI_DECISIONS_ENDPOINT : OPENROUTER_DECISIONS_ENDPOINT);
140
+ return {
141
+ async decide(input, questions, options = {}) {
142
+ options.signal?.throwIfAborted();
143
+ if (!Object.keys(questions).length)
144
+ throw new DecisionRequestError("A decision request needs named questions");
145
+ const request = config.provider === "openai" ? openAiDecisionRequest(config.model, input, questions) : openRouterDecisionRequest(config.model, input, questions);
146
+ let response;
147
+ try {
148
+ response = await (config.fetch ?? fetch)(endpoint, {
149
+ method: "POST",
150
+ headers: { Authorization: `Bearer ${config.apiKey}`, "Content-Type": "application/json" },
151
+ body: JSON.stringify(request),
152
+ ...options.signal ? { signal: options.signal } : {}
153
+ });
154
+ } catch (cause) {
155
+ options.signal?.throwIfAborted();
156
+ throw new DecisionUnavailableError("Decision provider request failed", { cause });
157
+ }
158
+ if (!response.ok) {
159
+ await response.body?.cancel();
160
+ const ErrorType = [401, 402, 403, 408, 429].includes(response.status) || response.status >= 500 ? DecisionUnavailableError : DecisionRequestError;
161
+ throw new ErrorType(`Decision provider returned HTTP ${response.status}`, {
162
+ status: response.status
163
+ });
164
+ }
165
+ let result;
166
+ try {
167
+ result = await response.json();
168
+ } catch (cause) {
169
+ options.signal?.throwIfAborted();
170
+ throw new DecisionUnavailableError("Decision provider returned invalid JSON", { cause });
171
+ }
172
+ if (!isRecord(result))
173
+ throw new DecisionUnavailableError("Decision provider returned an invalid response");
174
+ const rawUsage = isRecord(result.usage) ? result.usage : {};
175
+ const inputTokens = count(rawUsage.input_tokens);
176
+ const reportedCost = typeof rawUsage.cost === "number" && Number.isFinite(rawUsage.cost) && rawUsage.cost >= 0 ? rawUsage.cost : null;
177
+ const estimatedCost = inputTokens !== null && config.inputUsdPerMillion !== void 0 ? inputTokens * config.inputUsdPerMillion / 1e6 : null;
178
+ const usage = {
179
+ model: typeof result.model === "string" ? result.model : config.model,
180
+ provider: typeof result.provider === "string" ? result.provider : config.provider,
181
+ ...typeof result.id === "string" ? { requestId: result.id } : {},
182
+ requests: 1,
183
+ inputTokens,
184
+ outputTokens: count(rawUsage.output_tokens),
185
+ costUsd: reportedCost ?? estimatedCost,
186
+ costSource: reportedCost !== null ? "provider-reported" : estimatedCost !== null ? "estimate" : "unknown"
187
+ };
188
+ await options.onUsage?.(usage);
189
+ options.signal?.throwIfAborted();
190
+ return {
191
+ usage,
192
+ answers: validateDecisionAnswers(
193
+ questions,
194
+ normalizeAnswers(result.answers, config.provider)
195
+ )
196
+ };
197
+ }
198
+ };
199
+ }
200
+ export {
201
+ DecisionError,
202
+ DecisionRequestError,
203
+ DecisionUnavailableError,
204
+ OPENAI_DECISIONS_ENDPOINT,
205
+ OPENROUTER_DECISIONS_ENDPOINT,
206
+ createHttpDecisionModel,
207
+ isRecord,
208
+ openAiDecisionRequest,
209
+ openRouterDecisionRequest,
210
+ predicate,
211
+ validateDecisionAnswers
212
+ };
213
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types.ts","../src/http.ts"],"sourcesContent":["/** Shared typed judgments. Consumers own rubrics and thresholds; providers own inference. */\nexport type DecisionInstructions = string | Record<string, unknown> | unknown[];\nexport type DecisionPredicateQuestion = {\n type: \"predicate\";\n instructions: DecisionInstructions;\n criteria?: { true?: DecisionInstructions; false?: DecisionInstructions };\n};\nexport type DecisionChoiceQuestion = {\n type: \"choice\";\n instructions: DecisionInstructions;\n criteria: Record<string, DecisionInstructions | null>;\n};\nexport type DecisionScoreQuestion = {\n type: \"score\";\n instructions: DecisionInstructions;\n criteria: DecisionInstructions[];\n};\nexport type DecisionQuestion =\n | DecisionPredicateQuestion\n | DecisionChoiceQuestion\n | DecisionScoreQuestion;\nexport type DecisionRefusal = { type: \"refusal\"; reason?: string };\nexport type DecisionPredicateAnswer = { type: \"predicate\"; probability: number };\nexport type DecisionChoiceAnswer = {\n type: \"choice\";\n choice: string;\n probabilities?: Record<string, number>;\n confidence?: number;\n};\nexport type DecisionScoreAnswer = {\n type: \"score\";\n score: number;\n probabilities?: Record<string, number>;\n confidence?: number;\n};\nexport type DecisionAnswer =\n | DecisionPredicateAnswer\n | DecisionChoiceAnswer\n | DecisionScoreAnswer\n | DecisionRefusal;\nexport type DecisionAnswerFor<Q> =\n | DecisionRefusal\n | (Q extends DecisionPredicateQuestion\n ? DecisionPredicateAnswer\n : Q extends DecisionChoiceQuestion\n ? DecisionChoiceAnswer\n : DecisionScoreAnswer);\n\nexport type DecisionUsage = {\n model: string;\n provider: string;\n requestId?: string;\n inputTokens: number | null;\n outputTokens: number | null;\n /** Successful chunks, not retry attempts. */\n requests: number;\n costUsd: number | null;\n costSource: \"provider-reported\" | \"estimate\" | \"unknown\";\n};\nexport type DecisionOptions = {\n signal?: AbortSignal;\n tag?: string;\n /** Called even when a received answer is invalid. Never reconstructed on history replay. */\n onUsage?: (usage: DecisionUsage) => void | Promise<void>;\n};\nexport type DecisionResult<\n Q extends Record<string, DecisionQuestion> = Record<string, DecisionQuestion>,\n> = {\n answers: { [K in keyof Q]: DecisionAnswerFor<Q[K]> };\n usage: DecisionUsage;\n};\nexport interface DecisionModel {\n decide<Q extends Record<string, DecisionQuestion>>(\n input: unknown,\n questions: Q,\n options?: DecisionOptions,\n ): Promise<DecisionResult<Q>>;\n /** Optional provider preparation; existing code-search behavior, not required by callers. */\n warmUp?(connections: number): void;\n}\n\nexport function predicate(\n instructions: DecisionInstructions,\n criteria?: DecisionPredicateQuestion[\"criteria\"],\n): DecisionPredicateQuestion {\n return criteria\n ? { type: \"predicate\", instructions, criteria }\n : { type: \"predicate\", instructions };\n}\n\nexport class DecisionError extends Error {\n readonly status: number | undefined;\n readonly code: string | undefined;\n constructor(message: string, options: { status?: number; code?: string; cause?: unknown } = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = new.target.name;\n this.status = options.status;\n this.code = options.code;\n }\n}\nexport class DecisionUnavailableError extends DecisionError {}\nexport class DecisionRequestError extends DecisionError {}\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\nconst probability = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0 && value <= 1;\n\n/** Validate the complete named answer set, not a convenient partial selection. */\nexport function validateDecisionAnswers<Q extends Record<string, DecisionQuestion>>(\n questions: Q,\n answers: unknown,\n): DecisionResult<Q>[\"answers\"] {\n const invalid = () => {\n throw new DecisionUnavailableError(\"Decision model returned invalid typed answers\");\n };\n if (!isRecord(answers)) return invalid();\n const names = Object.keys(questions);\n if (Object.keys(answers).length !== names.length) return invalid();\n for (const name of names) {\n const answer = answers[name];\n const question = questions[name]!;\n if (!isRecord(answer)) return invalid();\n if (answer.type === \"refusal\") {\n if (answer.reason !== undefined && typeof answer.reason !== \"string\") return invalid();\n continue;\n }\n if (answer.type !== question.type) return invalid();\n if (question.type === \"predicate\" && !probability(answer.probability)) return invalid();\n if (\n question.type === \"choice\" &&\n (typeof answer.choice !== \"string\" || !Object.hasOwn(question.criteria, answer.choice))\n )\n return invalid();\n if (\n question.type === \"score\" &&\n (typeof answer.score !== \"number\" ||\n !Number.isFinite(answer.score) ||\n answer.score < 0 ||\n answer.score > question.criteria.length - 1)\n )\n return invalid();\n if (answer.confidence !== undefined && !probability(answer.confidence)) return invalid();\n if (answer.probabilities !== undefined) {\n if (\n !isRecord(answer.probabilities) ||\n Object.values(answer.probabilities).some((p) => !probability(p))\n )\n return invalid();\n const allowed =\n question.type === \"choice\"\n ? Object.keys(question.criteria)\n : question.type === \"score\"\n ? question.criteria.map((_, i) => String(i))\n : [];\n if (Object.keys(answer.probabilities).some((key) => !allowed.includes(key))) return invalid();\n }\n }\n return answers as DecisionResult<Q>[\"answers\"];\n}\n","import {\n DecisionRequestError,\n DecisionUnavailableError,\n isRecord,\n validateDecisionAnswers,\n type DecisionModel,\n type DecisionQuestion,\n type DecisionUsage,\n} from \"./types\";\n\nexport type HttpDecisionModelOptions = {\n provider: \"openai\" | \"openrouter\";\n model: string;\n apiKey: string;\n /** Full typed endpoint; never a chat-completions fallback. */\n endpoint?: string;\n fetch?: typeof fetch;\n /** Optional deployment rate, explicitly an estimate, not a billed receipt. */\n inputUsdPerMillion?: number;\n};\nexport const OPENAI_DECISIONS_ENDPOINT = \"https://api.openai.com/v1/decisions\";\nexport const OPENROUTER_DECISIONS_ENDPOINT = \"https://openrouter.ai/api/alpha/decisions\";\nconst text = (value: unknown) => (typeof value === \"string\" ? value : JSON.stringify(value));\nconst count = (value: unknown) =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : null;\n\nexport function openAiDecisionRequest(\n model: string,\n input: unknown,\n questions: Record<string, DecisionQuestion>,\n) {\n return {\n model,\n input: text(input),\n questions: Object.entries(questions).map(([name, question]) => {\n if (question.type === \"predicate\")\n return {\n name,\n type: question.type,\n instructions: question.criteria\n ? text({ instructions: question.instructions, criteria: question.criteria })\n : text(question.instructions),\n };\n if (question.type === \"choice\")\n return {\n name,\n type: question.type,\n instructions: text(question.instructions),\n choices: Object.entries(question.criteria).map(([value, description]) => ({\n value,\n description: description === null ? value : text(description),\n })),\n };\n return {\n name,\n type: question.type,\n instructions: text(question.instructions),\n levels: question.criteria.map((description, index) => ({\n label: String(index),\n description: text(description),\n })),\n };\n }),\n };\n}\nexport function openRouterDecisionRequest(\n model: string,\n input: unknown,\n questions: Record<string, DecisionQuestion>,\n) {\n return {\n model,\n state: input,\n questions: Object.fromEntries(\n Object.entries(questions).map(([name, question]) => [\n name,\n { ...question, type: question.type === \"predicate\" ? \"noul\" : question.type },\n ]),\n ),\n };\n}\n\nfunction normalizeAnswers(raw: unknown, provider: HttpDecisionModelOptions[\"provider\"]) {\n if (provider === \"openrouter\") {\n if (!isRecord(raw))\n throw new DecisionUnavailableError(\"Decision response has no named answers\");\n return Object.fromEntries(\n Object.entries(raw).map(([name, answer]) => [\n name,\n isRecord(answer) && answer.type === \"noul\"\n ? { type: \"predicate\", probability: answer.noul }\n : answer,\n ]),\n );\n }\n if (!Array.isArray(raw))\n throw new DecisionUnavailableError(\"Decision response has no answer array\");\n const answers = Object.create(null) as Record<string, unknown>;\n for (const value of raw) {\n if (!isRecord(value) || typeof value.name !== \"string\" || Object.hasOwn(answers, value.name))\n throw new DecisionUnavailableError(\"Decision response has invalid or duplicate answer names\");\n const { name, probabilities, ...answer } = value;\n if (probabilities !== undefined) {\n if (!Array.isArray(probabilities))\n throw new DecisionUnavailableError(\"Decision response has invalid probabilities\");\n const mapped = Object.create(null) as Record<string, unknown>;\n for (const entry of probabilities) {\n if (\n !isRecord(entry) ||\n (typeof entry.value !== \"string\" && typeof entry.value !== \"number\") ||\n Object.hasOwn(mapped, String(entry.value))\n )\n throw new DecisionUnavailableError(\"Decision response has invalid probability labels\");\n mapped[String(entry.value)] = entry.probability;\n }\n answer.probabilities = mapped;\n }\n answers[name] = answer;\n }\n return answers;\n}\n\n/** Real typed endpoints only. Caller cancellation is forwarded; no new timeout/retry policy. */\nexport function createHttpDecisionModel(config: HttpDecisionModelOptions): DecisionModel {\n if (!config.apiKey || !config.model)\n throw new DecisionRequestError(\"Decision model and credential must be configured\");\n const endpoint =\n config.endpoint ??\n (config.provider === \"openai\" ? OPENAI_DECISIONS_ENDPOINT : OPENROUTER_DECISIONS_ENDPOINT);\n return {\n async decide(input, questions, options = {}) {\n options.signal?.throwIfAborted();\n if (!Object.keys(questions).length)\n throw new DecisionRequestError(\"A decision request needs named questions\");\n const request =\n config.provider === \"openai\"\n ? openAiDecisionRequest(config.model, input, questions)\n : openRouterDecisionRequest(config.model, input, questions);\n let response: Response;\n try {\n response = await (config.fetch ?? fetch)(endpoint, {\n method: \"POST\",\n headers: { Authorization: `Bearer ${config.apiKey}`, \"Content-Type\": \"application/json\" },\n body: JSON.stringify(request),\n ...(options.signal ? { signal: options.signal } : {}),\n });\n } catch (cause) {\n options.signal?.throwIfAborted();\n throw new DecisionUnavailableError(\"Decision provider request failed\", { cause });\n }\n if (!response.ok) {\n await response.body?.cancel();\n const ErrorType =\n [401, 402, 403, 408, 429].includes(response.status) || response.status >= 500\n ? DecisionUnavailableError\n : DecisionRequestError;\n throw new ErrorType(`Decision provider returned HTTP ${response.status}`, {\n status: response.status,\n });\n }\n let result: unknown;\n try {\n result = await response.json();\n } catch (cause) {\n options.signal?.throwIfAborted();\n throw new DecisionUnavailableError(\"Decision provider returned invalid JSON\", { cause });\n }\n if (!isRecord(result))\n throw new DecisionUnavailableError(\"Decision provider returned an invalid response\");\n const rawUsage = isRecord(result.usage) ? result.usage : {};\n const inputTokens = count(rawUsage.input_tokens);\n const reportedCost =\n typeof rawUsage.cost === \"number\" && Number.isFinite(rawUsage.cost) && rawUsage.cost >= 0\n ? rawUsage.cost\n : null;\n const estimatedCost =\n inputTokens !== null && config.inputUsdPerMillion !== undefined\n ? (inputTokens * config.inputUsdPerMillion) / 1_000_000\n : null;\n const usage: DecisionUsage = {\n model: typeof result.model === \"string\" ? result.model : config.model,\n provider: typeof result.provider === \"string\" ? result.provider : config.provider,\n ...(typeof result.id === \"string\" ? { requestId: result.id } : {}),\n requests: 1,\n inputTokens,\n outputTokens: count(rawUsage.output_tokens),\n costUsd: reportedCost ?? estimatedCost,\n costSource:\n reportedCost !== null\n ? \"provider-reported\"\n : estimatedCost !== null\n ? \"estimate\"\n : \"unknown\",\n };\n await options.onUsage?.(usage);\n options.signal?.throwIfAborted();\n return {\n usage,\n answers: validateDecisionAnswers(\n questions,\n normalizeAnswers(result.answers, config.provider),\n ),\n };\n },\n };\n}\n"],"mappings":";AAiFO,SAAS,UACd,cACA,UAC2B;AAC3B,SAAO,WACH,EAAE,MAAM,aAAa,cAAc,SAAS,IAC5C,EAAE,MAAM,aAAa,aAAa;AACxC;AAEO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EACT,YAAY,SAAiB,UAA+D,CAAC,GAAG;AAC9F,UAAM,SAAS,QAAQ,UAAU,SAAY,SAAY,EAAE,OAAO,QAAQ,MAAM,CAAC;AACjF,SAAK,OAAO,WAAW;AACvB,SAAK,SAAS,QAAQ;AACtB,SAAK,OAAO,QAAQ;AAAA,EACtB;AACF;AACO,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QAC1C,SAAS,gBAAgB;AAAA,QACzB,YACE,iBAAiB,OACb,sBACA,kBAAkB,OAChB,aACA;AAAA,MACV;AACA,YAAM,QAAQ,UAAU,KAAK;AAC7B,cAAQ,QAAQ,eAAe;AAC/B,aAAO;AAAA,QACL;AAAA,QACA,SAAS;AAAA,UACP;AAAA,UACA,iBAAiB,OAAO,SAAS,OAAO,QAAQ;AAAA,QAClD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,88 @@
1
+ /** Shared typed judgments. Consumers own rubrics and thresholds; providers own inference. */
2
+ export type DecisionInstructions = string | Record<string, unknown> | unknown[];
3
+ export type DecisionPredicateQuestion = {
4
+ type: "predicate";
5
+ instructions: DecisionInstructions;
6
+ criteria?: {
7
+ true?: DecisionInstructions;
8
+ false?: DecisionInstructions;
9
+ };
10
+ };
11
+ export type DecisionChoiceQuestion = {
12
+ type: "choice";
13
+ instructions: DecisionInstructions;
14
+ criteria: Record<string, DecisionInstructions | null>;
15
+ };
16
+ export type DecisionScoreQuestion = {
17
+ type: "score";
18
+ instructions: DecisionInstructions;
19
+ criteria: DecisionInstructions[];
20
+ };
21
+ export type DecisionQuestion = DecisionPredicateQuestion | DecisionChoiceQuestion | DecisionScoreQuestion;
22
+ export type DecisionRefusal = {
23
+ type: "refusal";
24
+ reason?: string;
25
+ };
26
+ export type DecisionPredicateAnswer = {
27
+ type: "predicate";
28
+ probability: number;
29
+ };
30
+ export type DecisionChoiceAnswer = {
31
+ type: "choice";
32
+ choice: string;
33
+ probabilities?: Record<string, number>;
34
+ confidence?: number;
35
+ };
36
+ export type DecisionScoreAnswer = {
37
+ type: "score";
38
+ score: number;
39
+ probabilities?: Record<string, number>;
40
+ confidence?: number;
41
+ };
42
+ export type DecisionAnswer = DecisionPredicateAnswer | DecisionChoiceAnswer | DecisionScoreAnswer | DecisionRefusal;
43
+ export type DecisionAnswerFor<Q> = DecisionRefusal | (Q extends DecisionPredicateQuestion ? DecisionPredicateAnswer : Q extends DecisionChoiceQuestion ? DecisionChoiceAnswer : DecisionScoreAnswer);
44
+ export type DecisionUsage = {
45
+ model: string;
46
+ provider: string;
47
+ requestId?: string;
48
+ inputTokens: number | null;
49
+ outputTokens: number | null;
50
+ /** Successful chunks, not retry attempts. */
51
+ requests: number;
52
+ costUsd: number | null;
53
+ costSource: "provider-reported" | "estimate" | "unknown";
54
+ };
55
+ export type DecisionOptions = {
56
+ signal?: AbortSignal;
57
+ tag?: string;
58
+ /** Called even when a received answer is invalid. Never reconstructed on history replay. */
59
+ onUsage?: (usage: DecisionUsage) => void | Promise<void>;
60
+ };
61
+ export type DecisionResult<Q extends Record<string, DecisionQuestion> = Record<string, DecisionQuestion>> = {
62
+ answers: {
63
+ [K in keyof Q]: DecisionAnswerFor<Q[K]>;
64
+ };
65
+ usage: DecisionUsage;
66
+ };
67
+ export interface DecisionModel {
68
+ decide<Q extends Record<string, DecisionQuestion>>(input: unknown, questions: Q, options?: DecisionOptions): Promise<DecisionResult<Q>>;
69
+ /** Optional provider preparation; existing code-search behavior, not required by callers. */
70
+ warmUp?(connections: number): void;
71
+ }
72
+ export declare function predicate(instructions: DecisionInstructions, criteria?: DecisionPredicateQuestion["criteria"]): DecisionPredicateQuestion;
73
+ export declare class DecisionError extends Error {
74
+ readonly status: number | undefined;
75
+ readonly code: string | undefined;
76
+ constructor(message: string, options?: {
77
+ status?: number;
78
+ code?: string;
79
+ cause?: unknown;
80
+ });
81
+ }
82
+ export declare class DecisionUnavailableError extends DecisionError {
83
+ }
84
+ export declare class DecisionRequestError extends DecisionError {
85
+ }
86
+ export declare const isRecord: (value: unknown) => value is Record<string, unknown>;
87
+ /** Validate the complete named answer set, not a convenient partial selection. */
88
+ export declare function validateDecisionAnswers<Q extends Record<string, DecisionQuestion>>(questions: Q, answers: unknown): DecisionResult<Q>["answers"];
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@opengeni/decisions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.3.1",
4
+ "description": "Provider-neutral typed decision models for application judgments, not prose generation.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Cloudgeni-ai/opengeni.git",
9
+ "directory": "packages/decisions"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "src",
14
+ "README.md"
15
+ ],
16
+ "type": "module",
17
+ "sideEffects": false,
18
+ "main": "./dist/index.js",
19
+ "module": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js"
25
+ }
26
+ },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "provenance": true
30
+ },
31
+ "scripts": {
32
+ "build": "bun ../../scripts/build-typescript-package.ts",
33
+ "typecheck": "tsrs --noEmit",
34
+ "prepublishOnly": "bash ../../scripts/prepublish-guard"
35
+ },
36
+ "engines": {
37
+ "node": ">=18"
38
+ }
39
+ }
package/src/http.ts ADDED
@@ -0,0 +1,206 @@
1
+ import {
2
+ DecisionRequestError,
3
+ DecisionUnavailableError,
4
+ isRecord,
5
+ validateDecisionAnswers,
6
+ type DecisionModel,
7
+ type DecisionQuestion,
8
+ type DecisionUsage,
9
+ } from "./types";
10
+
11
+ export type HttpDecisionModelOptions = {
12
+ provider: "openai" | "openrouter";
13
+ model: string;
14
+ apiKey: string;
15
+ /** Full typed endpoint; never a chat-completions fallback. */
16
+ endpoint?: string;
17
+ fetch?: typeof fetch;
18
+ /** Optional deployment rate, explicitly an estimate, not a billed receipt. */
19
+ inputUsdPerMillion?: number;
20
+ };
21
+ export const OPENAI_DECISIONS_ENDPOINT = "https://api.openai.com/v1/decisions";
22
+ export const OPENROUTER_DECISIONS_ENDPOINT = "https://openrouter.ai/api/alpha/decisions";
23
+ const text = (value: unknown) => (typeof value === "string" ? value : JSON.stringify(value));
24
+ const count = (value: unknown) =>
25
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
26
+
27
+ export function openAiDecisionRequest(
28
+ model: string,
29
+ input: unknown,
30
+ questions: Record<string, DecisionQuestion>,
31
+ ) {
32
+ return {
33
+ model,
34
+ input: text(input),
35
+ questions: Object.entries(questions).map(([name, question]) => {
36
+ if (question.type === "predicate")
37
+ return {
38
+ name,
39
+ type: question.type,
40
+ instructions: question.criteria
41
+ ? text({ instructions: question.instructions, criteria: question.criteria })
42
+ : text(question.instructions),
43
+ };
44
+ if (question.type === "choice")
45
+ return {
46
+ name,
47
+ type: question.type,
48
+ instructions: text(question.instructions),
49
+ choices: Object.entries(question.criteria).map(([value, description]) => ({
50
+ value,
51
+ description: description === null ? value : text(description),
52
+ })),
53
+ };
54
+ return {
55
+ name,
56
+ type: question.type,
57
+ instructions: text(question.instructions),
58
+ levels: question.criteria.map((description, index) => ({
59
+ label: String(index),
60
+ description: text(description),
61
+ })),
62
+ };
63
+ }),
64
+ };
65
+ }
66
+ export function openRouterDecisionRequest(
67
+ model: string,
68
+ input: unknown,
69
+ questions: Record<string, DecisionQuestion>,
70
+ ) {
71
+ return {
72
+ model,
73
+ state: input,
74
+ questions: Object.fromEntries(
75
+ Object.entries(questions).map(([name, question]) => [
76
+ name,
77
+ { ...question, type: question.type === "predicate" ? "noul" : question.type },
78
+ ]),
79
+ ),
80
+ };
81
+ }
82
+
83
+ function normalizeAnswers(raw: unknown, provider: HttpDecisionModelOptions["provider"]) {
84
+ if (provider === "openrouter") {
85
+ if (!isRecord(raw))
86
+ throw new DecisionUnavailableError("Decision response has no named answers");
87
+ return Object.fromEntries(
88
+ Object.entries(raw).map(([name, answer]) => [
89
+ name,
90
+ isRecord(answer) && answer.type === "noul"
91
+ ? { type: "predicate", probability: answer.noul }
92
+ : answer,
93
+ ]),
94
+ );
95
+ }
96
+ if (!Array.isArray(raw))
97
+ throw new DecisionUnavailableError("Decision response has no answer array");
98
+ const answers = Object.create(null) as Record<string, unknown>;
99
+ for (const value of raw) {
100
+ if (!isRecord(value) || typeof value.name !== "string" || Object.hasOwn(answers, value.name))
101
+ throw new DecisionUnavailableError("Decision response has invalid or duplicate answer names");
102
+ const { name, probabilities, ...answer } = value;
103
+ if (probabilities !== undefined) {
104
+ if (!Array.isArray(probabilities))
105
+ throw new DecisionUnavailableError("Decision response has invalid probabilities");
106
+ const mapped = Object.create(null) as Record<string, unknown>;
107
+ for (const entry of probabilities) {
108
+ if (
109
+ !isRecord(entry) ||
110
+ (typeof entry.value !== "string" && typeof entry.value !== "number") ||
111
+ Object.hasOwn(mapped, String(entry.value))
112
+ )
113
+ throw new DecisionUnavailableError("Decision response has invalid probability labels");
114
+ mapped[String(entry.value)] = entry.probability;
115
+ }
116
+ answer.probabilities = mapped;
117
+ }
118
+ answers[name] = answer;
119
+ }
120
+ return answers;
121
+ }
122
+
123
+ /** Real typed endpoints only. Caller cancellation is forwarded; no new timeout/retry policy. */
124
+ export function createHttpDecisionModel(config: HttpDecisionModelOptions): DecisionModel {
125
+ if (!config.apiKey || !config.model)
126
+ throw new DecisionRequestError("Decision model and credential must be configured");
127
+ const endpoint =
128
+ config.endpoint ??
129
+ (config.provider === "openai" ? OPENAI_DECISIONS_ENDPOINT : OPENROUTER_DECISIONS_ENDPOINT);
130
+ return {
131
+ async decide(input, questions, options = {}) {
132
+ options.signal?.throwIfAborted();
133
+ if (!Object.keys(questions).length)
134
+ throw new DecisionRequestError("A decision request needs named questions");
135
+ const request =
136
+ config.provider === "openai"
137
+ ? openAiDecisionRequest(config.model, input, questions)
138
+ : openRouterDecisionRequest(config.model, input, questions);
139
+ let response: Response;
140
+ try {
141
+ response = await (config.fetch ?? fetch)(endpoint, {
142
+ method: "POST",
143
+ headers: { Authorization: `Bearer ${config.apiKey}`, "Content-Type": "application/json" },
144
+ body: JSON.stringify(request),
145
+ ...(options.signal ? { signal: options.signal } : {}),
146
+ });
147
+ } catch (cause) {
148
+ options.signal?.throwIfAborted();
149
+ throw new DecisionUnavailableError("Decision provider request failed", { cause });
150
+ }
151
+ if (!response.ok) {
152
+ await response.body?.cancel();
153
+ const ErrorType =
154
+ [401, 402, 403, 408, 429].includes(response.status) || response.status >= 500
155
+ ? DecisionUnavailableError
156
+ : DecisionRequestError;
157
+ throw new ErrorType(`Decision provider returned HTTP ${response.status}`, {
158
+ status: response.status,
159
+ });
160
+ }
161
+ let result: unknown;
162
+ try {
163
+ result = await response.json();
164
+ } catch (cause) {
165
+ options.signal?.throwIfAborted();
166
+ throw new DecisionUnavailableError("Decision provider returned invalid JSON", { cause });
167
+ }
168
+ if (!isRecord(result))
169
+ throw new DecisionUnavailableError("Decision provider returned an invalid response");
170
+ const rawUsage = isRecord(result.usage) ? result.usage : {};
171
+ const inputTokens = count(rawUsage.input_tokens);
172
+ const reportedCost =
173
+ typeof rawUsage.cost === "number" && Number.isFinite(rawUsage.cost) && rawUsage.cost >= 0
174
+ ? rawUsage.cost
175
+ : null;
176
+ const estimatedCost =
177
+ inputTokens !== null && config.inputUsdPerMillion !== undefined
178
+ ? (inputTokens * config.inputUsdPerMillion) / 1_000_000
179
+ : null;
180
+ const usage: DecisionUsage = {
181
+ model: typeof result.model === "string" ? result.model : config.model,
182
+ provider: typeof result.provider === "string" ? result.provider : config.provider,
183
+ ...(typeof result.id === "string" ? { requestId: result.id } : {}),
184
+ requests: 1,
185
+ inputTokens,
186
+ outputTokens: count(rawUsage.output_tokens),
187
+ costUsd: reportedCost ?? estimatedCost,
188
+ costSource:
189
+ reportedCost !== null
190
+ ? "provider-reported"
191
+ : estimatedCost !== null
192
+ ? "estimate"
193
+ : "unknown",
194
+ };
195
+ await options.onUsage?.(usage);
196
+ options.signal?.throwIfAborted();
197
+ return {
198
+ usage,
199
+ answers: validateDecisionAnswers(
200
+ questions,
201
+ normalizeAnswers(result.answers, config.provider),
202
+ ),
203
+ };
204
+ },
205
+ };
206
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from "./types";
2
+ export * from "./http";
package/src/types.ts ADDED
@@ -0,0 +1,160 @@
1
+ /** Shared typed judgments. Consumers own rubrics and thresholds; providers own inference. */
2
+ export type DecisionInstructions = string | Record<string, unknown> | unknown[];
3
+ export type DecisionPredicateQuestion = {
4
+ type: "predicate";
5
+ instructions: DecisionInstructions;
6
+ criteria?: { true?: DecisionInstructions; false?: DecisionInstructions };
7
+ };
8
+ export type DecisionChoiceQuestion = {
9
+ type: "choice";
10
+ instructions: DecisionInstructions;
11
+ criteria: Record<string, DecisionInstructions | null>;
12
+ };
13
+ export type DecisionScoreQuestion = {
14
+ type: "score";
15
+ instructions: DecisionInstructions;
16
+ criteria: DecisionInstructions[];
17
+ };
18
+ export type DecisionQuestion =
19
+ | DecisionPredicateQuestion
20
+ | DecisionChoiceQuestion
21
+ | DecisionScoreQuestion;
22
+ export type DecisionRefusal = { type: "refusal"; reason?: string };
23
+ export type DecisionPredicateAnswer = { type: "predicate"; probability: number };
24
+ export type DecisionChoiceAnswer = {
25
+ type: "choice";
26
+ choice: string;
27
+ probabilities?: Record<string, number>;
28
+ confidence?: number;
29
+ };
30
+ export type DecisionScoreAnswer = {
31
+ type: "score";
32
+ score: number;
33
+ probabilities?: Record<string, number>;
34
+ confidence?: number;
35
+ };
36
+ export type DecisionAnswer =
37
+ | DecisionPredicateAnswer
38
+ | DecisionChoiceAnswer
39
+ | DecisionScoreAnswer
40
+ | DecisionRefusal;
41
+ export type DecisionAnswerFor<Q> =
42
+ | DecisionRefusal
43
+ | (Q extends DecisionPredicateQuestion
44
+ ? DecisionPredicateAnswer
45
+ : Q extends DecisionChoiceQuestion
46
+ ? DecisionChoiceAnswer
47
+ : DecisionScoreAnswer);
48
+
49
+ export type DecisionUsage = {
50
+ model: string;
51
+ provider: string;
52
+ requestId?: string;
53
+ inputTokens: number | null;
54
+ outputTokens: number | null;
55
+ /** Successful chunks, not retry attempts. */
56
+ requests: number;
57
+ costUsd: number | null;
58
+ costSource: "provider-reported" | "estimate" | "unknown";
59
+ };
60
+ export type DecisionOptions = {
61
+ signal?: AbortSignal;
62
+ tag?: string;
63
+ /** Called even when a received answer is invalid. Never reconstructed on history replay. */
64
+ onUsage?: (usage: DecisionUsage) => void | Promise<void>;
65
+ };
66
+ export type DecisionResult<
67
+ Q extends Record<string, DecisionQuestion> = Record<string, DecisionQuestion>,
68
+ > = {
69
+ answers: { [K in keyof Q]: DecisionAnswerFor<Q[K]> };
70
+ usage: DecisionUsage;
71
+ };
72
+ export interface DecisionModel {
73
+ decide<Q extends Record<string, DecisionQuestion>>(
74
+ input: unknown,
75
+ questions: Q,
76
+ options?: DecisionOptions,
77
+ ): Promise<DecisionResult<Q>>;
78
+ /** Optional provider preparation; existing code-search behavior, not required by callers. */
79
+ warmUp?(connections: number): void;
80
+ }
81
+
82
+ export function predicate(
83
+ instructions: DecisionInstructions,
84
+ criteria?: DecisionPredicateQuestion["criteria"],
85
+ ): DecisionPredicateQuestion {
86
+ return criteria
87
+ ? { type: "predicate", instructions, criteria }
88
+ : { type: "predicate", instructions };
89
+ }
90
+
91
+ export class DecisionError extends Error {
92
+ readonly status: number | undefined;
93
+ readonly code: string | undefined;
94
+ constructor(message: string, options: { status?: number; code?: string; cause?: unknown } = {}) {
95
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
96
+ this.name = new.target.name;
97
+ this.status = options.status;
98
+ this.code = options.code;
99
+ }
100
+ }
101
+ export class DecisionUnavailableError extends DecisionError {}
102
+ export class DecisionRequestError extends DecisionError {}
103
+
104
+ export const isRecord = (value: unknown): value is Record<string, unknown> =>
105
+ value !== null && typeof value === "object" && !Array.isArray(value);
106
+ const probability = (value: unknown): value is number =>
107
+ typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
108
+
109
+ /** Validate the complete named answer set, not a convenient partial selection. */
110
+ export function validateDecisionAnswers<Q extends Record<string, DecisionQuestion>>(
111
+ questions: Q,
112
+ answers: unknown,
113
+ ): DecisionResult<Q>["answers"] {
114
+ const invalid = () => {
115
+ throw new DecisionUnavailableError("Decision model returned invalid typed answers");
116
+ };
117
+ if (!isRecord(answers)) return invalid();
118
+ const names = Object.keys(questions);
119
+ if (Object.keys(answers).length !== names.length) return invalid();
120
+ for (const name of names) {
121
+ const answer = answers[name];
122
+ const question = questions[name]!;
123
+ if (!isRecord(answer)) return invalid();
124
+ if (answer.type === "refusal") {
125
+ if (answer.reason !== undefined && typeof answer.reason !== "string") return invalid();
126
+ continue;
127
+ }
128
+ if (answer.type !== question.type) return invalid();
129
+ if (question.type === "predicate" && !probability(answer.probability)) return invalid();
130
+ if (
131
+ question.type === "choice" &&
132
+ (typeof answer.choice !== "string" || !Object.hasOwn(question.criteria, answer.choice))
133
+ )
134
+ return invalid();
135
+ if (
136
+ question.type === "score" &&
137
+ (typeof answer.score !== "number" ||
138
+ !Number.isFinite(answer.score) ||
139
+ answer.score < 0 ||
140
+ answer.score > question.criteria.length - 1)
141
+ )
142
+ return invalid();
143
+ if (answer.confidence !== undefined && !probability(answer.confidence)) return invalid();
144
+ if (answer.probabilities !== undefined) {
145
+ if (
146
+ !isRecord(answer.probabilities) ||
147
+ Object.values(answer.probabilities).some((p) => !probability(p))
148
+ )
149
+ return invalid();
150
+ const allowed =
151
+ question.type === "choice"
152
+ ? Object.keys(question.criteria)
153
+ : question.type === "score"
154
+ ? question.criteria.map((_, i) => String(i))
155
+ : [];
156
+ if (Object.keys(answer.probabilities).some((key) => !allowed.includes(key))) return invalid();
157
+ }
158
+ }
159
+ return answers as DecisionResult<Q>["answers"];
160
+ }