@itsoltech/basal-client 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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,39 @@
1
+ basal-rs
2
+ Copyright 2026 basal-rs contributors
3
+
4
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ This project reimplements in Rust the inference protocol of basal
7
+ (https://github.com/rkinas/basal, Copyright 2026 Remigiusz Kinas, Apache License 2.0) and ports parts of it:
8
+ the prompt format and letter readout (basal/prompt.py), the System One request handling and answer semantics
9
+ including multi and act (basal/server.py), facts injection (basal/facts.py -> crates/basal-core/src/facts.rs),
10
+ evidence spans (basal/evidence.py -> crates/basal-core/src/evidence.rs) and shared-prefix packing (basal/engine.py).
11
+ Reference requests in tools/reference include examples from basal/examples.
12
+
13
+ The basal model weights (Remek/basal-1.0-*, Remek/basal-1.5-*) are not part of this repository; they are released by
14
+ their author under the Apache License 2.0.
15
+
16
+ The NOTICE file of basal (v1.5.0) follows.
17
+
18
+ --------------------------------------------------------------------------------
19
+
20
+ basal
21
+ Copyright 2026 Remigiusz Kinas
22
+
23
+ This product includes models fine-tuned from the following works, licensed under the Apache License, Version 2.0:
24
+
25
+ basal-1.5-4.5B <- speakleash/Bielik-4.5B-v3.0-Instruct (https://huggingface.co/speakleash/Bielik-4.5B-v3.0-Instruct)
26
+ basal-1.5-max <- speakleash/Bielik-PL-11B-v3.0-Instruct (https://huggingface.co/speakleash/Bielik-PL-11B-v3.0-Instruct)
27
+ basal-1.5-mini <- speakleash/Bielik-1.5B-v3.0-Instruct (https://huggingface.co/speakleash/Bielik-1.5B-v3.0-Instruct)
28
+ basal-1.0-4.5B <- speakleash/Bielik-4.5B-v3.0-Instruct (https://huggingface.co/speakleash/Bielik-4.5B-v3.0-Instruct)
29
+ basal-1.0-1.5B <- speakleash/Bielik-1.5B-v3.0-Instruct (https://huggingface.co/speakleash/Bielik-1.5B-v3.0-Instruct)
30
+
31
+ The inference engine in this repository is original work licensed under the Apache License, Version 2.0.
32
+
33
+ Training data attribution (basal-1.0 models):
34
+ English decision items in the training data were converted from the public corpus
35
+ avbiswas/bev-decision-150K (https://huggingface.co/datasets/avbiswas/bev-decision-150K), which aggregates questions
36
+ derived from many upstream sources. Its maintainers ask users to check and attribute those upstream sources; row-level
37
+ source identifiers are not available, so the upstream sources of these items are not documented individually.
38
+
39
+ basal-1.5 models: released under the Apache License, Version 2.0.
package/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # @itsoltech/basal-client
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
+ TypeScript/JavaScript SDK for the native Basal API (`POST /v1/basal`). ESM and CommonJS, with type declarations.
4
+ Node.js 22+ or modern browsers with `fetch` and `AbortController`. No runtime dependencies or GPU requirement.
5
+
6
+ This package is versioned independently. Release tag: `sdk-typescript-vX.Y.Z`.
7
+ [Changelog](https://github.com/itsoltech/basal-rs/blob/main/sdk/typescript/CHANGELOG.md).
8
+
9
+ ```sh
10
+ npm i @itsoltech/basal-client
11
+ ```
12
+
13
+ ```typescript
14
+ import { BasalClient, choice, noul } from "@itsoltech/basal-client";
15
+
16
+ const client = new BasalClient({ baseUrl: "http://127.0.0.1:8000" });
17
+ const response = await client.decide("Klient prosi o zwrot pieniędzy za uszkodzony telefon.", {
18
+ department: choice("Do którego działu skierować zgłoszenie?", { returns: "Zwroty", support: "Wsparcie techniczne" }),
19
+ urgent: noul("Czy sprawa jest pilna?"),
20
+ });
21
+ console.log(response.answers.department.choice); // "returns" | "support"
22
+ console.log(response.answers.urgent.noul); // number
23
+ ```
24
+
25
+ CommonJS: `const { BasalClient } = require("@itsoltech/basal-client")`.
26
+
27
+ The transport uses the standard Web Fetch contract, in browsers and on the backend:
28
+
29
+ ```typescript
30
+ import { BasalClient, type Fetch, type RequestInput } from "@itsoltech/basal-client";
31
+
32
+ const transport: Fetch = async (input: RequestInput, init?: RequestInit): Promise<Response> => {
33
+ const request = new Request(input, init);
34
+ return fetch(request);
35
+ };
36
+ const client = new BasalClient({ baseUrl: "https://basal.example.com", fetch: transport });
37
+ ```
38
+
39
+ `RequestInput = string | URL | Request`. An adapter for another HTTP client must return a Web `Response`
40
+ with status, headers and a readable body, and honor cancellation, `redirect: "error"`, TLS verification,
41
+ and `credentials: "omit"`. Those requirements apply to the adapter's HTTP client too. The default is
42
+ native `fetch`; no adapter or polyfill dependency is installed by this package. A pre-aborted signal
43
+ rejects before dispatch; the SDK deadline rejects even if an adapter fails to honor cancellation,
44
+ but such an adapter may continue its own network I/O.
45
+
46
+ `models()` reads `/v1/models`. Each method optionally takes an `AbortSignal`.
47
+ `timeoutMs` includes response-body reading. `apiKey` optionally sends a bearer token to a reverse proxy.
48
+ Use the server root (possibly with a proxy prefix), without `/v1`. HTTPS is required except for loopback
49
+ HTTP (localhost, 127.0.0.1, ::1), suitable for a local server or SSH tunnel. URL credentials/query/fragment
50
+ are rejected. Requests omit cookies and use `cache: "no-store"`.
51
+ `maxResponseBytes` defaults to 8 MiB and limits the actual streamed body, including HTTP errors;
52
+ oversized responses raise `BasalResponseTooLargeError`.
53
+
54
+ `BasalHTTPError` provides `statusCode`, `body` and the raw `retryAfter` header. Transport failures raise
55
+ `BasalTransportError`; malformed successful JSON raises `BasalProtocolError`. Original causes are kept
56
+ in `cause`. `BasalHTTPError.body` remains directly accessible but is non-enumerable, so default Node
57
+ inspection and JSON.stringify do not log it. There are no automatic retries or redirects. Types describe the native contract; successful
58
+ responses are checked to be JSON objects without full schema validation. Unknown JSON fields are preserved.
59
+
60
+ Supports `choice`, `noul`, `score`, `multi`, `act`, `facts` and `evidence`. Native choice/score accepts 2–10
61
+ options. Criterion insertion order matters; JavaScript enumerates integer-like object keys numerically,
62
+ so use textual keys (e.g. `low`, `high`) or an ordered score array. Evidence offsets count Unicode code
63
+ points; use the returned text, or `Array.from(state).slice(start, end).join("")` for textual states.
64
+
65
+ In browsers, the server/proxy must support your origin through CORS. Basal-rs does not enable CORS by default.
66
+ Keep private API keys in server-side code.
67
+
68
+ Factories and concrete classes cover `choice`, `noul`, `score`, `multi`, `act`. The two-argument
69
+ `decide(state, questions, {model, facts, signal})` infers exact question IDs, answer types, choice keys
70
+ and selected-label keys. Keep the inferred object type instead of widening it to `QuestionSet`.
71
+ `response.answer("department")` also infers the answer from its request key. The same question
72
+ definition can be reused under different keys; each key retains its own answer. `answer()` takes
73
+ a key, not a question object (changed before the initial release). Required fields are
74
+ validated before the promise resolves. Typed evidence defaults to an empty array; `response.raw`
75
+ retains the native JSON without those defaults. The one-argument raw `decide(request, signal)` remains available.
76
+
77
+
78
+ [Full documentation and publication setup](https://github.com/itsoltech/basal-rs/blob/main/docs/SDK.md).
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.BasalClient = exports.BasalResponseTooLargeError = exports.BasalProtocolError = exports.BasalTransportError = exports.BasalHTTPError = exports.BasalError = void 0;
18
+ const questions_cjs_1 = require("./questions.cjs");
19
+ __exportStar(require("./questions.cjs"), exports);
20
+ class BasalError extends Error {
21
+ }
22
+ exports.BasalError = BasalError;
23
+ /** Non-2xx response. Server body and Retry-After are available without logging them. */
24
+ class BasalHTTPError extends BasalError {
25
+ statusCode;
26
+ body;
27
+ retryAfter;
28
+ constructor(statusCode, body, retryAfter) {
29
+ super(`Basal HTTP ${statusCode}`);
30
+ this.statusCode = statusCode;
31
+ this.body = body;
32
+ this.retryAfter = retryAfter;
33
+ this.name = "BasalHTTPError";
34
+ // Node's default inspection and JSON.stringify must not print reflected state or credentials.
35
+ Object.defineProperty(this, "body", { enumerable: false });
36
+ }
37
+ }
38
+ exports.BasalHTTPError = BasalHTTPError;
39
+ class BasalTransportError extends BasalError {
40
+ }
41
+ exports.BasalTransportError = BasalTransportError;
42
+ class BasalProtocolError extends BasalError {
43
+ }
44
+ exports.BasalProtocolError = BasalProtocolError;
45
+ class BasalResponseTooLargeError extends BasalError {
46
+ }
47
+ exports.BasalResponseTooLargeError = BasalResponseTooLargeError;
48
+ async function readBody(response, limit, signal) {
49
+ // Count bytes from the actual stream, including decompressed responses; never trust Content-Length alone.
50
+ const reader = response.body?.getReader();
51
+ if (!reader)
52
+ return "";
53
+ const cancel = () => { void reader.cancel().catch(() => { }); };
54
+ signal.addEventListener("abort", cancel, { once: true });
55
+ if (signal.aborted)
56
+ cancel();
57
+ const decoder = new TextDecoder("utf-8", { fatal: true });
58
+ const parts = [];
59
+ let bytes = 0;
60
+ let complete = false;
61
+ try {
62
+ for (;;) {
63
+ const { done, value } = await reader.read();
64
+ if (done) {
65
+ complete = true;
66
+ break;
67
+ }
68
+ bytes += value.byteLength;
69
+ if (bytes > limit) {
70
+ throw new BasalResponseTooLargeError(`Basal response exceeds ${limit} bytes`);
71
+ }
72
+ parts.push(decoder.decode(value, { stream: true }));
73
+ }
74
+ parts.push(decoder.decode());
75
+ return parts.join("");
76
+ }
77
+ finally {
78
+ signal.removeEventListener("abort", cancel);
79
+ // A decoder/read failure must also stop the underlying HTTP body, before releasing ownership.
80
+ if (!complete)
81
+ cancel();
82
+ reader.releaseLock();
83
+ }
84
+ }
85
+ /** Reusable fetch client. Server root URL, optional proxy prefix, without /v1.
86
+ * No automatic retries. AbortSignal cancels a request; timeout includes body reading.
87
+ */
88
+ class BasalClient {
89
+ baseUrl;
90
+ headers;
91
+ timeoutMs;
92
+ maxResponseBytes;
93
+ fetch;
94
+ constructor(options = {}) {
95
+ const url = new URL(options.baseUrl ?? "http://127.0.0.1:8000");
96
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.href.includes("?") || url.href.includes("#")) {
97
+ throw new TypeError("baseUrl must be an HTTP(S) server URL without credentials, query or fragment");
98
+ }
99
+ if (url.protocol !== "https:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
100
+ throw new TypeError("baseUrl requires HTTPS or loopback HTTP (e.g. an SSH tunnel)");
101
+ }
102
+ this.baseUrl = url.href.replace(/\/+$/, "") + "/";
103
+ this.timeoutMs = options.timeoutMs ?? 120_000;
104
+ if (!Number.isFinite(this.timeoutMs) || this.timeoutMs <= 0 || this.timeoutMs > 2_147_483_647) {
105
+ throw new TypeError("timeoutMs must be positive and at most 2147483647");
106
+ }
107
+ this.headers = { Accept: "application/json" };
108
+ this.maxResponseBytes = options.maxResponseBytes ?? 8 * 1024 * 1024;
109
+ if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) {
110
+ throw new TypeError("maxResponseBytes must be a positive safe integer");
111
+ }
112
+ this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
113
+ if (options.apiKey !== undefined) {
114
+ if (!options.apiKey || /[\r\n]/.test(options.apiKey))
115
+ throw new TypeError("apiKey must be a nonempty, single-line token");
116
+ this.headers.Authorization = `Bearer ${options.apiKey}`;
117
+ }
118
+ }
119
+ async request(method, path, body, signal) {
120
+ // Serialization errors are local input errors, not failures of the HTTP transport.
121
+ const encoded = body === undefined ? undefined : JSON.stringify(body);
122
+ const controller = new AbortController();
123
+ const abort = () => controller.abort(signal?.reason);
124
+ signal?.addEventListener("abort", abort, { once: true });
125
+ if (signal?.aborted)
126
+ abort();
127
+ const timer = setTimeout(() => controller.abort(new Error("Basal request timed out")), this.timeoutMs);
128
+ let onAbort = () => { };
129
+ const aborted = new Promise((_, reject) => {
130
+ onAbort = () => reject(new BasalTransportError("Basal HTTP request aborted", { cause: controller.signal.reason }));
131
+ controller.signal.addEventListener("abort", onAbort, { once: true });
132
+ if (controller.signal.aborted)
133
+ onAbort();
134
+ });
135
+ const work = async () => {
136
+ let response;
137
+ let raw;
138
+ try {
139
+ response = await this.fetch(this.baseUrl + path, {
140
+ method, headers: body === undefined ? this.headers : { ...this.headers, "Content-Type": "application/json" },
141
+ ...(encoded === undefined ? {} : { body: encoded }),
142
+ signal: controller.signal, redirect: "error", credentials: "omit", cache: "no-store",
143
+ });
144
+ if (response.redirected || ([301, 302, 303, 307, 308].includes(response.status) && response.headers.has("Location"))) {
145
+ await response.body?.cancel().catch(() => { });
146
+ throw new BasalTransportError("Basal transport returned a redirect");
147
+ }
148
+ raw = await readBody(response, this.maxResponseBytes, controller.signal);
149
+ }
150
+ catch (cause) {
151
+ if (cause instanceof BasalError)
152
+ throw cause;
153
+ throw new BasalTransportError("Basal HTTP transport failed", { cause });
154
+ }
155
+ let data;
156
+ try {
157
+ data = JSON.parse(raw);
158
+ }
159
+ catch (cause) {
160
+ if (response.ok)
161
+ throw new BasalProtocolError("Basal returned invalid JSON", { cause });
162
+ data = raw;
163
+ }
164
+ if (!response.ok)
165
+ throw new BasalHTTPError(response.status, data, response.headers.get("Retry-After"));
166
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
167
+ throw new BasalProtocolError("Basal returned a JSON value other than an object");
168
+ }
169
+ return data;
170
+ };
171
+ try {
172
+ if (controller.signal.aborted)
173
+ return await aborted;
174
+ return await Promise.race([work(), aborted]);
175
+ }
176
+ finally {
177
+ controller.signal.removeEventListener("abort", onAbort);
178
+ clearTimeout(timer);
179
+ signal?.removeEventListener("abort", abort);
180
+ }
181
+ }
182
+ async decide(state, questionsOrSignal, options = {}) {
183
+ if (questionsOrSignal === undefined || ("aborted" in questionsOrSignal && typeof questionsOrSignal.addEventListener === "function")) {
184
+ return this.request("POST", "v1/basal", state, questionsOrSignal);
185
+ }
186
+ const questions = { ...questionsOrSignal };
187
+ const response = await this.request("POST", "v1/basal", (0, questions_cjs_1.buildRequest)(state, questions, options), options.signal);
188
+ const parsed = new Map();
189
+ try {
190
+ if (typeof response.model !== "string" || !response.model || !response.usage || Array.isArray(response.usage)
191
+ || !Number.isSafeInteger(response.usage.input_tokens) || response.usage.input_tokens < 0
192
+ || !Number.isSafeInteger(response.usage.output_tokens) || response.usage.output_tokens < 0
193
+ || !response.answers || Array.isArray(response.answers))
194
+ throw new TypeError("invalid decision envelope");
195
+ for (const [id, question] of Object.entries(questions))
196
+ parsed.set(id, question.read(response, id));
197
+ }
198
+ catch (cause) {
199
+ throw new BasalProtocolError("Invalid typed Basal answer", { cause });
200
+ }
201
+ const typed = { ...response, answers: Object.fromEntries(parsed) };
202
+ Object.defineProperty(typed, "raw", { value: response });
203
+ Object.defineProperty(typed, "answer", { value: (key) => {
204
+ if (typeof key !== "string" && typeof key !== "number")
205
+ throw new TypeError("answer key must be a string or number");
206
+ const answer = parsed.get(String(key));
207
+ if (answer === undefined)
208
+ throw new TypeError("answer key was not part of this response");
209
+ return answer;
210
+ } });
211
+ return typed;
212
+ }
213
+ models(signal) { return this.request("GET", "v1/models", undefined, signal); }
214
+ }
215
+ exports.BasalClient = BasalClient;
@@ -0,0 +1,134 @@
1
+ import { type QuestionSet, type TypedDecisionResponse, type DecisionOptions } from "./questions.cjs";
2
+ export * from "./questions.cjs";
3
+ /** Native Basal wire types. Criterion order is significant; do not sort keys. */
4
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
5
+ [key: string]: JsonValue;
6
+ };
7
+ export interface Question {
8
+ type?: "choice" | "noul" | "score" | "multi" | "act";
9
+ instructions?: JsonValue;
10
+ criteria?: Record<string, JsonValue> | JsonValue[];
11
+ levels?: Record<string, JsonValue> | JsonValue[];
12
+ option_keys?: "show" | "hide";
13
+ evidence?: boolean;
14
+ threshold?: number;
15
+ min?: number;
16
+ max?: number;
17
+ base?: "noul" | "choice" | "score";
18
+ costs?: Record<string, number> | Record<string, Record<string, number>>;
19
+ defer_action?: string;
20
+ max_error?: number;
21
+ }
22
+ export interface DecisionRequest {
23
+ state: JsonValue;
24
+ questions: Record<string, Question>;
25
+ model?: string;
26
+ facts?: "off" | "auto";
27
+ }
28
+ export interface EvidenceSpan {
29
+ text: string;
30
+ start: number;
31
+ end: number;
32
+ probability: number;
33
+ }
34
+ interface BaseAnswer<K extends string = string> {
35
+ probabilities: Record<K, number>;
36
+ evidence?: EvidenceSpan[];
37
+ }
38
+ export interface ChoiceAnswer<K extends string = string> extends BaseAnswer<K> {
39
+ type: "choice";
40
+ choice: K;
41
+ confidence: number;
42
+ }
43
+ export interface NoulAnswer extends BaseAnswer<"true" | "false"> {
44
+ type: "noul";
45
+ noul: number;
46
+ confidence: number;
47
+ }
48
+ export interface ScoreAnswer extends BaseAnswer {
49
+ type: "score";
50
+ score: number;
51
+ legend: Record<string, string>;
52
+ confidence: number;
53
+ }
54
+ export interface MultiAnswer<K extends string = string> extends BaseAnswer<K> {
55
+ type: "multi";
56
+ selected: K[];
57
+ threshold: number;
58
+ set_confidence: number;
59
+ }
60
+ export interface ActAnswer<K extends string = string, A extends string = string> extends BaseAnswer<K> {
61
+ type: "act";
62
+ action: A;
63
+ answer: K;
64
+ expected_costs: Record<A, number>;
65
+ confidence: number;
66
+ calibration: "validated" | "unvalidated";
67
+ refused?: string;
68
+ max_error?: string;
69
+ }
70
+ export type Answer = ChoiceAnswer | NoulAnswer | ScoreAnswer | MultiAnswer | ActAnswer;
71
+ export interface Usage {
72
+ input_tokens: number;
73
+ output_tokens: number;
74
+ questions?: number;
75
+ branches?: number;
76
+ latency_ms?: number;
77
+ }
78
+ export interface DecisionResponse {
79
+ model: string;
80
+ answers: Record<string, Answer>;
81
+ usage: Usage;
82
+ }
83
+ export interface ModelMetadata {
84
+ name: string;
85
+ description?: string;
86
+ release_date?: string;
87
+ mode?: string;
88
+ early_exit?: JsonValue[];
89
+ }
90
+ export interface ModelsResponse {
91
+ models: ModelMetadata[];
92
+ }
93
+ export declare class BasalError extends Error {
94
+ }
95
+ /** Non-2xx response. Server body and Retry-After are available without logging them. */
96
+ export declare class BasalHTTPError extends BasalError {
97
+ readonly statusCode: number;
98
+ readonly body: unknown;
99
+ readonly retryAfter: string | null;
100
+ constructor(statusCode: number, body: unknown, retryAfter: string | null);
101
+ }
102
+ export declare class BasalTransportError extends BasalError {
103
+ }
104
+ export declare class BasalProtocolError extends BasalError {
105
+ }
106
+ export declare class BasalResponseTooLargeError extends BasalError {
107
+ }
108
+ /** Web Fetch input accepted by browsers and server runtimes. */
109
+ export type RequestInput = string | URL | Request;
110
+ /** A transport adapter must honor signal/redirect and return a standard Web Response. */
111
+ export type Fetch = (input: RequestInput, init?: RequestInit) => Promise<Response>;
112
+ export interface BasalClientOptions {
113
+ baseUrl?: string;
114
+ apiKey?: string;
115
+ timeoutMs?: number;
116
+ maxResponseBytes?: number;
117
+ /** Defaults to the runtime's native fetch; custom HTTP clients can supply a Fetch adapter. */
118
+ fetch?: Fetch;
119
+ }
120
+ /** Reusable fetch client. Server root URL, optional proxy prefix, without /v1.
121
+ * No automatic retries. AbortSignal cancels a request; timeout includes body reading.
122
+ */
123
+ export declare class BasalClient {
124
+ private readonly baseUrl;
125
+ private readonly headers;
126
+ private readonly timeoutMs;
127
+ private readonly maxResponseBytes;
128
+ private readonly fetch;
129
+ constructor(options?: BasalClientOptions);
130
+ private request;
131
+ decide(request: DecisionRequest, signal?: AbortSignal): Promise<DecisionResponse>;
132
+ decide<const Q extends QuestionSet>(state: JsonValue, questions: Q, options?: DecisionOptions): Promise<TypedDecisionResponse<Q>>;
133
+ models(signal?: AbortSignal): Promise<ModelsResponse>;
134
+ }