@gobing-ai/ts-decision-clef 0.0.0-stage → 0.5.20

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,176 @@
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
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ @gobing-ai/ts-decision-clef
2
+ Copyright 2026 Robin Min and ts-libs contributors
3
+
4
+ This package bundles no third-party code and no model weights. It drives the
5
+ Cloudflare Workers AI REST API over the portable ts-infra APIClient seam.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # @gobing-ai/ts-decision-clef
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
+ Hosted Cloudflare Clef decision backend for the neutral decision surface
4
+ owned by `@gobing-ai/ts-ai-runner`: answers `choice` / `score` / `noul`
5
+ questions through Cloudflare Workers AI REST API over the portable
6
+ `@gobing-ai/ts-infra` `APIClient` seam ([ADR-037](../../docs/00_ADR.md)).
7
+
8
+ Part of the `@gobing-ai/ts-libs` monorepo and lockstep-versioned with it.
9
+
10
+ - **License:** Apache-2.0 (see [LICENSE](./LICENSE)).
11
+ - **No model weights or third-party SDKs are bundled.** It drives Cloudflare Workers AI
12
+ REST directly via `@gobing-ai/ts-infra`.
13
+
14
+ ---
15
+
16
+ ## Usage
17
+
18
+ ```ts
19
+ import { createDecisionMaker } from '@gobing-ai/ts-ai-runner';
20
+ import { createClefDriver } from '@gobing-ai/ts-decision-clef';
21
+
22
+ const driver = createClefDriver({
23
+ accountId: '0123456789abcdef0123456789abcdef',
24
+ apiToken: 'cf_api_token_secret',
25
+ model: 'clef-flash', // default; or 'clef'
26
+ });
27
+
28
+ const dm = createDecisionMaker({ driver });
29
+
30
+ const answers = await dm.ask({
31
+ state: 'Customer was billed twice for invoice INV-42.',
32
+ questions: {
33
+ sentiment: {
34
+ kind: 'choice',
35
+ prompt: 'Sentiment of the message',
36
+ labels: { positive: 'Praise', negative: 'Complaint' },
37
+ },
38
+ priority: {
39
+ kind: 'score',
40
+ prompt: 'Queue priority',
41
+ rubric: ['Routine — normal SLA', 'Critical — customer blocked'],
42
+ },
43
+ refund: { kind: 'noul', prompt: 'Refund the duplicate charge?' },
44
+ },
45
+ });
46
+ ```
47
+
48
+ ### Options
49
+
50
+ | Option | Default | Meaning |
51
+ |--------|---------|---------|
52
+ | `accountId` | required | Cloudflare Account ID (32-character hexadecimal string). |
53
+ | `apiToken` | required | Cloudflare API Token (no whitespace or control characters). |
54
+ | `model` | `'clef-flash'` | Default model selector (`'clef'` \| `'clef-flash'`). |
55
+ | `timeoutMs` | `30000` | Request timeout in milliseconds (positive integer). |
56
+ | `fetch` | `globalThis.fetch` | Custom fetch implementation (injected for tests). |
57
+
58
+ ---
59
+
60
+ ## Provider constraints
61
+
62
+ 1. **Question limits:** 1–64 questions per request.
63
+ 2. **Question IDs:** must match `/^[A-Za-z0-9_.-]{1,100}$/`.
64
+ 3. **Choice options:** 2–255 non-empty choice label keys per question.
65
+ 4. **Score levels:** 2–10 rubric levels per question.
66
+ 5. **JSON serializability:** `state` and question contents must be strict JSON values. Cycles, non-finite numbers (`NaN`, `Infinity`), `BigInt`, `undefined`, functions, symbols, sparse arrays, hidden or extra array properties, accessors, and custom object instances (e.g. `Date`) are rejected before transport with `DecisionRequestError`.
67
+ 6. **Payload bounds:** request bodies cannot exceed 13 MiB; responses exceeding 8 MiB are rejected with `DecisionBackendError`.
68
+ 7. **Instructions fallback:** when a question prompt is omitted, null, or empty whitespace, the question ID is used as the instructions field.
69
+
70
+ ---
71
+
72
+ ## Errors
73
+
74
+ All failures map to the `@gobing-ai/ts-ai-runner` decision error taxonomy:
75
+
76
+ | Condition | Class |
77
+ |-----------|-------|
78
+ | Invalid account ID, API token, timeout, or model at construction | `DecisionConfigError` |
79
+ | Invalid question structure, ID format, limits, un-serializable state, body > 13 MiB, or HTTP 4xx | `DecisionRequestError` |
80
+ | HTTP 401 / 403 | `DecisionAuthError` |
81
+ | HTTP 429 (preserves `Retry-After` hint in ms) | `DecisionRateLimitError` |
82
+ | Request timeout | `DecisionTimeoutError` |
83
+ | Network or connection failure | `DecisionConnectionError` |
84
+ | HTTP 5xx, redirects, malformed JSON, envelope failure, missing model, response > 8 MiB | `DecisionBackendError` |
85
+
86
+ Error messages are redacted: credentials, state, and untrusted upstream text are never exposed.
87
+
88
+ ---
89
+
90
+ ## Release and bootstrap
91
+
92
+ Releases are lockstep and automated via GitHub Actions OIDC Trusted Publishing.
93
+ For initial package bootstrap on npm, refer to [docs/PACKAGE_RELEASE.md](../../docs/PACKAGE_RELEASE.md#2-publish-the-first-version-manually):
94
+
95
+ ```bash
96
+ bun scripts/builder.ts publish-packages --bootstrap @gobing-ai/ts-decision-clef
97
+ ```
@@ -0,0 +1,22 @@
1
+ import { type DecisionDriver } from '@gobing-ai/ts-ai-runner';
2
+ /** The two hosted Workers AI Clef selectors this driver can route to. */
3
+ export type ClefModel = 'clef' | 'clef-flash';
4
+ /** Construction options for {@link createClefDriver}. Credentials are always explicit. */
5
+ export interface ClefDriverOptions {
6
+ /** Cloudflare account ID — 32 hexadecimal characters. */
7
+ accountId: string;
8
+ /** Cloudflare API token — non-blank, with no whitespace or control characters. */
9
+ apiToken: string;
10
+ /** Default model selector; per-call `ask({ model })` wins. Defaults to `clef-flash`. */
11
+ model?: ClefModel;
12
+ /** Request timeout in milliseconds; a positive integer. Defaults to `30000`. */
13
+ timeoutMs?: number;
14
+ /** Injected fetch, forwarded to the `APIClient` (tests use this instead of a socket). */
15
+ fetch?: typeof globalThis.fetch;
16
+ }
17
+ /**
18
+ * Build the hosted Clef driver: validates the configuration and constructs
19
+ * exactly one `APIClient`. No network call and no environment read happen here.
20
+ */
21
+ export declare function createClefDriver(options: ClefDriverOptions): DecisionDriver;
22
+ //# sourceMappingURL=driver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"driver.d.ts","sourceRoot":"","sources":["../src/driver.ts"],"names":[],"mappings":"AAAA,OAAO,EAMH,KAAK,cAAc,EAQtB,MAAM,yBAAyB,CAAC;AAGjC,yEAAyE;AACzE,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,YAAY,CAAC;AAE9C,0FAA0F;AAC1F,MAAM,WAAW,iBAAiB;IAC9B,yDAAyD;IACzD,SAAS,EAAE,MAAM,CAAC;IAClB,kFAAkF;IAClF,QAAQ,EAAE,MAAM,CAAC;IACjB,wFAAwF;IACxF,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB,gFAAgF;IAChF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,yFAAyF;IACzF,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CACnC;AAoJD;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB,GAAG,cAAc,CA2Q3E"}
package/dist/driver.js ADDED
@@ -0,0 +1,346 @@
1
+ import { DecisionAuthError, DecisionBackendError, DecisionConfigError, DecisionConnectionError, DecisionRateLimitError, DecisionRequestError, DecisionTimeoutError, validateAnswers, validateQuestions, } from '@gobing-ai/ts-ai-runner';
2
+ import { APIClient, APIError } from '@gobing-ai/ts-infra';
3
+ const ACCOUNT_ID_PATTERN = /^[0-9a-fA-F]{32}$/;
4
+ const QUESTION_ID_PATTERN = /^[A-Za-z0-9_.-]{1,100}$/;
5
+ const MAX_REQUEST_BODY_BYTES = 13 * 1024 * 1024;
6
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
7
+ function isRecord(value) {
8
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
9
+ }
10
+ /** Blank, whitespace and C0/DEL control characters cannot survive an HTTP header round-trip. */
11
+ function hasControlOrWhitespace(value) {
12
+ for (let i = 0; i < value.length; i++) {
13
+ const code = value.charCodeAt(i);
14
+ if (code <= 0x20 || code === 0x7f)
15
+ return true;
16
+ }
17
+ return false;
18
+ }
19
+ function assertJsonSerializable(value, context, ancestors = new Set()) {
20
+ if (value === null)
21
+ return;
22
+ if (typeof value === 'string' || typeof value === 'boolean')
23
+ return;
24
+ if (typeof value === 'number') {
25
+ if (!Number.isFinite(value)) {
26
+ throw new DecisionRequestError(`Non-finite number in ${context}`, undefined, undefined);
27
+ }
28
+ return;
29
+ }
30
+ if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol' || value === undefined) {
31
+ throw new DecisionRequestError(`Unserializable ${typeof value} in ${context}`, undefined, undefined);
32
+ }
33
+ if (typeof value === 'object') {
34
+ if (ancestors.has(value)) {
35
+ throw new DecisionRequestError(`Circular reference detected in ${context}`, undefined, undefined);
36
+ }
37
+ ancestors.add(value);
38
+ try {
39
+ if (Object.values(Object.getOwnPropertyDescriptors(value)).some((property) => !Object.hasOwn(property, 'value'))) {
40
+ throw new DecisionRequestError(`Accessor property in ${context}`, undefined, undefined);
41
+ }
42
+ if (Array.isArray(value)) {
43
+ // Extra own properties and holes are both dropped or coerced by JSON.stringify;
44
+ // only a dense, index-only array survives round-trip intact.
45
+ if (Object.keys(value).length !== value.length ||
46
+ Object.getOwnPropertyNames(value).length !== value.length + 1 ||
47
+ Object.getOwnPropertySymbols(value).length > 0) {
48
+ throw new DecisionRequestError(`Sparse or decorated array in ${context}`, undefined, undefined);
49
+ }
50
+ for (let i = 0; i < value.length; i++) {
51
+ assertJsonSerializable(value[i], context, ancestors);
52
+ }
53
+ }
54
+ else {
55
+ const proto = Object.getPrototypeOf(value);
56
+ if (proto !== null && proto !== Object.prototype) {
57
+ throw new DecisionRequestError(`Unsupported object instance in ${context}`, undefined, undefined);
58
+ }
59
+ // Symbol keys and non-enumerable own properties are invisible to Object.keys and are
60
+ // dropped by JSON.stringify, so they would otherwise be a silent loss.
61
+ const ownNames = Object.getOwnPropertyNames(value);
62
+ if (Object.getOwnPropertySymbols(value).length > 0 || ownNames.length !== Object.keys(value).length) {
63
+ throw new DecisionRequestError(`Unserializable own property in ${context}`, undefined, undefined);
64
+ }
65
+ for (const key of ownNames) {
66
+ assertJsonSerializable(value[key], context, ancestors);
67
+ }
68
+ }
69
+ }
70
+ finally {
71
+ ancestors.delete(value);
72
+ }
73
+ return;
74
+ }
75
+ throw new DecisionRequestError(`Unserializable value in ${context}`, undefined, undefined);
76
+ }
77
+ function resolveInstructions(prompt, questionId) {
78
+ if (prompt === undefined || prompt === null) {
79
+ return questionId;
80
+ }
81
+ if (typeof prompt === 'string' && prompt.trim().length === 0) {
82
+ return questionId;
83
+ }
84
+ return prompt;
85
+ }
86
+ function mapQuestion(name, q) {
87
+ const instructions = resolveInstructions(q.prompt, name);
88
+ switch (q.kind) {
89
+ case 'choice':
90
+ return {
91
+ type: 'choice',
92
+ instructions,
93
+ criteria: Object.fromEntries(Object.entries(q.labels)),
94
+ };
95
+ case 'score':
96
+ return {
97
+ type: 'score',
98
+ instructions,
99
+ criteria: q.rubric,
100
+ };
101
+ case 'noul': {
102
+ const mapped = {
103
+ type: 'noul',
104
+ instructions,
105
+ };
106
+ if (q.yes !== undefined || q.no !== undefined) {
107
+ const criteria = {};
108
+ if (q.yes !== undefined)
109
+ criteria.true = q.yes;
110
+ if (q.no !== undefined)
111
+ criteria.false = q.no;
112
+ mapped.criteria = criteria;
113
+ }
114
+ return mapped;
115
+ }
116
+ }
117
+ }
118
+ function getHeader(headers, name) {
119
+ const target = name.toLowerCase();
120
+ for (const [key, value] of Object.entries(headers)) {
121
+ if (key.toLowerCase() === target) {
122
+ return value;
123
+ }
124
+ }
125
+ return undefined;
126
+ }
127
+ function parseRetryAfter(header) {
128
+ if (!header)
129
+ return undefined;
130
+ const trimmed = header.trim();
131
+ if (/^\d+$/.test(trimmed)) {
132
+ const milliseconds = Number(trimmed) * 1000;
133
+ return Number.isFinite(milliseconds) ? milliseconds : undefined;
134
+ }
135
+ // HTTP dates start with a weekday; Date.parse also accepts invalid numeric hints as dates.
136
+ if (!/^[A-Za-z]+(?:,| )/.test(trimmed))
137
+ return undefined;
138
+ const timestamp = Date.parse(trimmed);
139
+ if (!Number.isNaN(timestamp)) {
140
+ return Math.max(0, timestamp - Date.now());
141
+ }
142
+ return undefined;
143
+ }
144
+ /**
145
+ * Build the hosted Clef driver: validates the configuration and constructs
146
+ * exactly one `APIClient`. No network call and no environment read happen here.
147
+ */
148
+ export function createClefDriver(options) {
149
+ if (!options || typeof options !== 'object') {
150
+ throw new DecisionConfigError('Options must be provided', 'options');
151
+ }
152
+ const { accountId, apiToken, model: configuredModel = 'clef-flash', timeoutMs = 30_000, fetch: customFetch, } = options;
153
+ if (typeof accountId !== 'string' || !ACCOUNT_ID_PATTERN.test(accountId)) {
154
+ throw new DecisionConfigError('Invalid accountId: must be a 32-character hexadecimal string', 'accountId');
155
+ }
156
+ if (typeof apiToken !== 'string' || apiToken.length === 0 || hasControlOrWhitespace(apiToken)) {
157
+ throw new DecisionConfigError('Invalid apiToken: cannot be blank or contain whitespace or control characters', 'apiToken');
158
+ }
159
+ if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs <= 0) {
160
+ throw new DecisionConfigError('Invalid timeoutMs: must be a positive integer', 'timeoutMs');
161
+ }
162
+ if (configuredModel !== 'clef' && configuredModel !== 'clef-flash') {
163
+ throw new DecisionConfigError('Invalid model: must be clef or clef-flash', 'model');
164
+ }
165
+ const client = new APIClient({
166
+ baseUrl: 'https://api.cloudflare.com/client/v4',
167
+ timeout: timeoutMs,
168
+ fetch: customFetch,
169
+ });
170
+ return {
171
+ name: 'clef',
172
+ async ask({ state, questions, model }) {
173
+ try {
174
+ validateQuestions(questions);
175
+ }
176
+ catch {
177
+ throw new DecisionRequestError('Invalid decision questions', undefined, undefined);
178
+ }
179
+ if (model !== undefined && model !== 'clef' && model !== 'clef-flash') {
180
+ throw new DecisionRequestError('Invalid model selector: must be clef or clef-flash', undefined, undefined);
181
+ }
182
+ const resolvedModel = model ?? configuredModel;
183
+ const questionEntries = Object.entries(questions);
184
+ if (questionEntries.length < 1 || questionEntries.length > 64) {
185
+ throw new DecisionRequestError(`Question count must be between 1 and 64, got ${questionEntries.length}`, undefined, undefined);
186
+ }
187
+ for (const [name, q] of questionEntries) {
188
+ if (!QUESTION_ID_PATTERN.test(name)) {
189
+ throw new DecisionRequestError('Question ID does not match pattern ^[A-Za-z0-9_.-]{1,100}$', undefined, undefined);
190
+ }
191
+ if (q.kind === 'choice') {
192
+ const labelKeys = Object.keys(q.labels);
193
+ if (labelKeys.length < 2 || labelKeys.length > 255) {
194
+ throw new DecisionRequestError(`Choice question must have between 2 and 255 choice IDs, got ${labelKeys.length}`, undefined, undefined);
195
+ }
196
+ for (const labelId of labelKeys) {
197
+ if (labelId.length === 0) {
198
+ throw new DecisionRequestError('Choice question contains empty choice ID', undefined, undefined);
199
+ }
200
+ }
201
+ }
202
+ else if (q.kind === 'score') {
203
+ const levels = q.rubric.length;
204
+ if (levels < 2 || levels > 10) {
205
+ throw new DecisionRequestError(`Score question must have between 2 and 10 score levels, got ${levels}`, undefined, undefined);
206
+ }
207
+ }
208
+ }
209
+ assertJsonSerializable(state, 'state');
210
+ const mappedQuestions = Object.fromEntries(questionEntries.map(([name, q]) => [name, mapQuestion(name, q)]));
211
+ const requestBody = {
212
+ model: resolvedModel,
213
+ state: state ?? null,
214
+ questions: mappedQuestions,
215
+ };
216
+ assertJsonSerializable(requestBody, 'request');
217
+ const bodyString = JSON.stringify(requestBody);
218
+ const bodyBytes = new TextEncoder().encode(bodyString).byteLength;
219
+ if (bodyBytes > MAX_REQUEST_BODY_BYTES) {
220
+ throw new DecisionRequestError('Request body exceeds maximum size of 13 MiB', undefined, undefined);
221
+ }
222
+ const path = `/accounts/${accountId}/ai/run/@cf/cloudflare/${resolvedModel}`;
223
+ let response;
224
+ try {
225
+ response = await client.rawRequest('POST', path, bodyString, {
226
+ headers: {
227
+ Authorization: `Bearer ${apiToken}`,
228
+ 'Content-Type': 'application/json',
229
+ },
230
+ redirect: 'manual',
231
+ maxResponseBytes: MAX_RESPONSE_BYTES,
232
+ });
233
+ }
234
+ catch (error) {
235
+ // The design forbids leaking untrusted transport error text/cause through public
236
+ // errors, so these stay generic: only the message and the timeoutMs field travel.
237
+ if (error instanceof APIError && error.status === 0) {
238
+ throw new DecisionTimeoutError('Request timed out', timeoutMs);
239
+ }
240
+ throw new DecisionConnectionError('Failed to connect to backend');
241
+ }
242
+ if (response.truncated) {
243
+ throw new DecisionBackendError('Response exceeded maximum allowed size of 8 MiB', response.status);
244
+ }
245
+ if (response.status >= 300 && response.status < 400) {
246
+ throw new DecisionBackendError(`HTTP ${response.status} redirect received`, response.status);
247
+ }
248
+ if (response.status === 401 || response.status === 403) {
249
+ throw new DecisionAuthError(`HTTP ${response.status} authentication failure`, response.status);
250
+ }
251
+ if (response.status === 429) {
252
+ const retryAfterHeader = getHeader(response.headers, 'retry-after');
253
+ const retryAfterMs = parseRetryAfter(retryAfterHeader);
254
+ throw new DecisionRateLimitError('HTTP 429 rate limit exceeded', response.status, retryAfterMs);
255
+ }
256
+ if (response.status >= 400 && response.status < 500) {
257
+ throw new DecisionRequestError(`HTTP ${response.status} request error`, response.status, undefined);
258
+ }
259
+ if (response.status >= 500 && response.status < 600) {
260
+ throw new DecisionBackendError(`HTTP ${response.status} backend error`, response.status);
261
+ }
262
+ if (response.status < 200 || response.status >= 300) {
263
+ throw new DecisionBackendError(`HTTP ${response.status} unexpected status`, response.status);
264
+ }
265
+ let json;
266
+ try {
267
+ json = JSON.parse(response.body);
268
+ }
269
+ catch {
270
+ throw new DecisionBackendError('Malformed JSON response from backend', response.status);
271
+ }
272
+ if (!isRecord(json) || json.success !== true) {
273
+ throw new DecisionBackendError('Backend returned failure envelope', response.status);
274
+ }
275
+ if (!isRecord(json.result)) {
276
+ throw new DecisionBackendError('Missing or invalid result in response', response.status);
277
+ }
278
+ const result = json.result;
279
+ if (typeof result.model !== 'string' || result.model.trim().length === 0) {
280
+ throw new DecisionBackendError('Invalid or missing model in response', response.status);
281
+ }
282
+ if (!isRecord(result.answers)) {
283
+ throw new DecisionBackendError('Invalid or missing answers in response', response.status);
284
+ }
285
+ const answers = Object.create(null);
286
+ for (const [name, rawAnswer] of Object.entries(result.answers)) {
287
+ if (!isRecord(rawAnswer)) {
288
+ throw new DecisionBackendError('Invalid answer in response', response.status);
289
+ }
290
+ switch (rawAnswer.type) {
291
+ case 'choice': {
292
+ if (typeof rawAnswer.choice !== 'string' ||
293
+ typeof rawAnswer.confidence !== 'number' ||
294
+ !isRecord(rawAnswer.probabilities)) {
295
+ throw new DecisionBackendError('Malformed choice answer in response', response.status);
296
+ }
297
+ answers[name] = {
298
+ kind: 'choice',
299
+ label: rawAnswer.choice,
300
+ confidence: rawAnswer.confidence,
301
+ // Cast: shared validateAnswers re-checks every entry's bounds and mass; this
302
+ // only reshapes the untyped wire record into the neutral answer shape.
303
+ probabilities: Object.fromEntries(Object.entries(rawAnswer.probabilities)),
304
+ };
305
+ break;
306
+ }
307
+ case 'score': {
308
+ if (typeof rawAnswer.score !== 'number' ||
309
+ typeof rawAnswer.confidence !== 'number' ||
310
+ !isRecord(rawAnswer.legend) ||
311
+ !isRecord(rawAnswer.probabilities)) {
312
+ throw new DecisionBackendError('Malformed score answer in response', response.status);
313
+ }
314
+ answers[name] = {
315
+ kind: 'score',
316
+ score: rawAnswer.score,
317
+ confidence: rawAnswer.confidence,
318
+ legend: Object.fromEntries(Object.entries(rawAnswer.legend)),
319
+ probabilities: Object.fromEntries(Object.entries(rawAnswer.probabilities)),
320
+ };
321
+ break;
322
+ }
323
+ case 'noul': {
324
+ if (typeof rawAnswer.noul !== 'number') {
325
+ throw new DecisionBackendError('Malformed noul answer in response', response.status);
326
+ }
327
+ answers[name] = {
328
+ kind: 'noul',
329
+ probability: rawAnswer.noul,
330
+ };
331
+ break;
332
+ }
333
+ default:
334
+ throw new DecisionBackendError('Unknown answer type in response', response.status);
335
+ }
336
+ }
337
+ try {
338
+ validateAnswers(questions, answers);
339
+ }
340
+ catch {
341
+ throw new DecisionBackendError('Invalid decision answers in response', response.status);
342
+ }
343
+ return answers;
344
+ },
345
+ };
346
+ }
@@ -0,0 +1,3 @@
1
+ export type { ClefDriverOptions, ClefModel } from './driver';
2
+ export { createClefDriver } from './driver';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { createClefDriver } from './driver.js';
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
- "name": "@gobing-ai/ts-decision-clef",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@gobing-ai/ts-decision-clef",
3
+ "version": "0.5.20",
4
+ "description": "@gobing-ai/ts-decision-clef — Hosted Clef decision backend driving Cloudflare Workers AI over the portable ts-infra APIClient seam.",
5
+ "keywords": [
6
+ "typescript",
7
+ "ai",
8
+ "decision",
9
+ "clef",
10
+ "cloudflare",
11
+ "workers-ai",
12
+ "hosted"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/gobing-ai/ts-libs.git",
17
+ "directory": "packages/decision-clef"
18
+ },
19
+ "author": "Robin Min <minlongbing@gmail.com>",
20
+ "contributors": [
21
+ "Robin Min <minlongbing@gmail.com>"
22
+ ],
23
+ "type": "module",
24
+ "private": false,
25
+ "sideEffects": false,
26
+ "license": "Apache-2.0",
27
+ "main": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js"
33
+ }
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "src",
38
+ "README.md",
39
+ "LICENSE",
40
+ "NOTICE"
41
+ ],
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.build.json && bun ../../scripts/builder.ts fix-dist-esm-extensions dist",
44
+ "test": "NODE_ENV=test bun test --coverage --coverage-dir=.coverage --reporter=dots",
45
+ "test:full": "NODE_ENV=test bun test --update-snapshots --coverage --coverage-dir=.coverage",
46
+ "typecheck": "tsc --noEmit",
47
+ "lint": "biome check . && bun run typecheck",
48
+ "format": "biome check . --write",
49
+ "check": "bun run lint && bun run test",
50
+ "prepublishOnly": "bun ../../scripts/builder.ts check-publish-manifest . && bun run build",
51
+ "release": "echo 'Manual publish is disabled. Releases go through GitHub Actions via Trusted Publishing — push a tag: git tag @gobing-ai/ts-decision-clef-v<version> && git push --tags' && exit 1"
52
+ },
53
+ "dependencies": {
54
+ "@gobing-ai/ts-ai-runner": "^0.5.20",
55
+ "@gobing-ai/ts-infra": "^0.5.20"
56
+ },
57
+ "devDependencies": {
58
+ "@gobing-ai/ts-ai-decision": "^0.5.20",
59
+ "@types/bun": "1.3.14"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ }
64
+ }
package/src/driver.ts ADDED
@@ -0,0 +1,452 @@
1
+ import {
2
+ type Answer,
3
+ DecisionAuthError,
4
+ DecisionBackendError,
5
+ DecisionConfigError,
6
+ DecisionConnectionError,
7
+ type DecisionDriver,
8
+ DecisionRateLimitError,
9
+ DecisionRequestError,
10
+ DecisionTimeoutError,
11
+ type Desc,
12
+ type Question,
13
+ validateAnswers,
14
+ validateQuestions,
15
+ } from '@gobing-ai/ts-ai-runner';
16
+ import { APIClient, APIError, type RawHttpResponse } from '@gobing-ai/ts-infra';
17
+
18
+ /** The two hosted Workers AI Clef selectors this driver can route to. */
19
+ export type ClefModel = 'clef' | 'clef-flash';
20
+
21
+ /** Construction options for {@link createClefDriver}. Credentials are always explicit. */
22
+ export interface ClefDriverOptions {
23
+ /** Cloudflare account ID — 32 hexadecimal characters. */
24
+ accountId: string;
25
+ /** Cloudflare API token — non-blank, with no whitespace or control characters. */
26
+ apiToken: string;
27
+ /** Default model selector; per-call `ask({ model })` wins. Defaults to `clef-flash`. */
28
+ model?: ClefModel;
29
+ /** Request timeout in milliseconds; a positive integer. Defaults to `30000`. */
30
+ timeoutMs?: number;
31
+ /** Injected fetch, forwarded to the `APIClient` (tests use this instead of a socket). */
32
+ fetch?: typeof globalThis.fetch;
33
+ }
34
+
35
+ const ACCOUNT_ID_PATTERN = /^[0-9a-fA-F]{32}$/;
36
+ const QUESTION_ID_PATTERN = /^[A-Za-z0-9_.-]{1,100}$/;
37
+ const MAX_REQUEST_BODY_BYTES = 13 * 1024 * 1024;
38
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
39
+
40
+ function isRecord(value: unknown): value is Record<string, unknown> {
41
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
42
+ }
43
+
44
+ /** Blank, whitespace and C0/DEL control characters cannot survive an HTTP header round-trip. */
45
+ function hasControlOrWhitespace(value: string): boolean {
46
+ for (let i = 0; i < value.length; i++) {
47
+ const code = value.charCodeAt(i);
48
+ if (code <= 0x20 || code === 0x7f) return true;
49
+ }
50
+ return false;
51
+ }
52
+
53
+ function assertJsonSerializable(value: unknown, context: string, ancestors = new Set<unknown>()): void {
54
+ if (value === null) return;
55
+ if (typeof value === 'string' || typeof value === 'boolean') return;
56
+ if (typeof value === 'number') {
57
+ if (!Number.isFinite(value)) {
58
+ throw new DecisionRequestError(`Non-finite number in ${context}`, undefined, undefined);
59
+ }
60
+ return;
61
+ }
62
+ if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol' || value === undefined) {
63
+ throw new DecisionRequestError(`Unserializable ${typeof value} in ${context}`, undefined, undefined);
64
+ }
65
+ if (typeof value === 'object') {
66
+ if (ancestors.has(value)) {
67
+ throw new DecisionRequestError(`Circular reference detected in ${context}`, undefined, undefined);
68
+ }
69
+ ancestors.add(value);
70
+ try {
71
+ if (
72
+ Object.values(Object.getOwnPropertyDescriptors(value)).some(
73
+ (property) => !Object.hasOwn(property, 'value'),
74
+ )
75
+ ) {
76
+ throw new DecisionRequestError(`Accessor property in ${context}`, undefined, undefined);
77
+ }
78
+ if (Array.isArray(value)) {
79
+ // Extra own properties and holes are both dropped or coerced by JSON.stringify;
80
+ // only a dense, index-only array survives round-trip intact.
81
+ if (
82
+ Object.keys(value).length !== value.length ||
83
+ Object.getOwnPropertyNames(value).length !== value.length + 1 ||
84
+ Object.getOwnPropertySymbols(value).length > 0
85
+ ) {
86
+ throw new DecisionRequestError(`Sparse or decorated array in ${context}`, undefined, undefined);
87
+ }
88
+ for (let i = 0; i < value.length; i++) {
89
+ assertJsonSerializable(value[i], context, ancestors);
90
+ }
91
+ } else {
92
+ const proto = Object.getPrototypeOf(value);
93
+ if (proto !== null && proto !== Object.prototype) {
94
+ throw new DecisionRequestError(`Unsupported object instance in ${context}`, undefined, undefined);
95
+ }
96
+ // Symbol keys and non-enumerable own properties are invisible to Object.keys and are
97
+ // dropped by JSON.stringify, so they would otherwise be a silent loss.
98
+ const ownNames = Object.getOwnPropertyNames(value);
99
+ if (Object.getOwnPropertySymbols(value).length > 0 || ownNames.length !== Object.keys(value).length) {
100
+ throw new DecisionRequestError(`Unserializable own property in ${context}`, undefined, undefined);
101
+ }
102
+ for (const key of ownNames) {
103
+ assertJsonSerializable((value as Record<string, unknown>)[key], context, ancestors);
104
+ }
105
+ }
106
+ } finally {
107
+ ancestors.delete(value);
108
+ }
109
+ return;
110
+ }
111
+ throw new DecisionRequestError(`Unserializable value in ${context}`, undefined, undefined);
112
+ }
113
+
114
+ function resolveInstructions(prompt: Desc | undefined, questionId: string): unknown {
115
+ if (prompt === undefined || prompt === null) {
116
+ return questionId;
117
+ }
118
+ if (typeof prompt === 'string' && prompt.trim().length === 0) {
119
+ return questionId;
120
+ }
121
+ return prompt;
122
+ }
123
+
124
+ function mapQuestion(name: string, q: Question): Record<string, unknown> {
125
+ const instructions = resolveInstructions(q.prompt, name);
126
+ switch (q.kind) {
127
+ case 'choice':
128
+ return {
129
+ type: 'choice',
130
+ instructions,
131
+ criteria: Object.fromEntries(Object.entries(q.labels)),
132
+ };
133
+ case 'score':
134
+ return {
135
+ type: 'score',
136
+ instructions,
137
+ criteria: q.rubric,
138
+ };
139
+ case 'noul': {
140
+ const mapped: Record<string, unknown> = {
141
+ type: 'noul',
142
+ instructions,
143
+ };
144
+ if (q.yes !== undefined || q.no !== undefined) {
145
+ const criteria: Record<string, unknown> = {};
146
+ if (q.yes !== undefined) criteria.true = q.yes;
147
+ if (q.no !== undefined) criteria.false = q.no;
148
+ mapped.criteria = criteria;
149
+ }
150
+ return mapped;
151
+ }
152
+ }
153
+ }
154
+
155
+ function getHeader(headers: Record<string, string>, name: string): string | undefined {
156
+ const target = name.toLowerCase();
157
+ for (const [key, value] of Object.entries(headers)) {
158
+ if (key.toLowerCase() === target) {
159
+ return value;
160
+ }
161
+ }
162
+ return undefined;
163
+ }
164
+
165
+ function parseRetryAfter(header: string | undefined): number | undefined {
166
+ if (!header) return undefined;
167
+ const trimmed = header.trim();
168
+ if (/^\d+$/.test(trimmed)) {
169
+ const milliseconds = Number(trimmed) * 1000;
170
+ return Number.isFinite(milliseconds) ? milliseconds : undefined;
171
+ }
172
+ // HTTP dates start with a weekday; Date.parse also accepts invalid numeric hints as dates.
173
+ if (!/^[A-Za-z]+(?:,| )/.test(trimmed)) return undefined;
174
+ const timestamp = Date.parse(trimmed);
175
+ if (!Number.isNaN(timestamp)) {
176
+ return Math.max(0, timestamp - Date.now());
177
+ }
178
+ return undefined;
179
+ }
180
+
181
+ /**
182
+ * Build the hosted Clef driver: validates the configuration and constructs
183
+ * exactly one `APIClient`. No network call and no environment read happen here.
184
+ */
185
+ export function createClefDriver(options: ClefDriverOptions): DecisionDriver {
186
+ if (!options || typeof options !== 'object') {
187
+ throw new DecisionConfigError('Options must be provided', 'options');
188
+ }
189
+ const {
190
+ accountId,
191
+ apiToken,
192
+ model: configuredModel = 'clef-flash',
193
+ timeoutMs = 30_000,
194
+ fetch: customFetch,
195
+ } = options;
196
+
197
+ if (typeof accountId !== 'string' || !ACCOUNT_ID_PATTERN.test(accountId)) {
198
+ throw new DecisionConfigError('Invalid accountId: must be a 32-character hexadecimal string', 'accountId');
199
+ }
200
+
201
+ if (typeof apiToken !== 'string' || apiToken.length === 0 || hasControlOrWhitespace(apiToken)) {
202
+ throw new DecisionConfigError(
203
+ 'Invalid apiToken: cannot be blank or contain whitespace or control characters',
204
+ 'apiToken',
205
+ );
206
+ }
207
+
208
+ if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs <= 0) {
209
+ throw new DecisionConfigError('Invalid timeoutMs: must be a positive integer', 'timeoutMs');
210
+ }
211
+
212
+ if (configuredModel !== 'clef' && configuredModel !== 'clef-flash') {
213
+ throw new DecisionConfigError('Invalid model: must be clef or clef-flash', 'model');
214
+ }
215
+
216
+ const client = new APIClient({
217
+ baseUrl: 'https://api.cloudflare.com/client/v4',
218
+ timeout: timeoutMs,
219
+ fetch: customFetch,
220
+ });
221
+
222
+ return {
223
+ name: 'clef',
224
+ async ask({ state, questions, model }) {
225
+ try {
226
+ validateQuestions(questions);
227
+ } catch {
228
+ throw new DecisionRequestError('Invalid decision questions', undefined, undefined);
229
+ }
230
+
231
+ if (model !== undefined && model !== 'clef' && model !== 'clef-flash') {
232
+ throw new DecisionRequestError(
233
+ 'Invalid model selector: must be clef or clef-flash',
234
+ undefined,
235
+ undefined,
236
+ );
237
+ }
238
+ const resolvedModel: ClefModel = model ?? configuredModel;
239
+
240
+ const questionEntries = Object.entries(questions);
241
+ if (questionEntries.length < 1 || questionEntries.length > 64) {
242
+ throw new DecisionRequestError(
243
+ `Question count must be between 1 and 64, got ${questionEntries.length}`,
244
+ undefined,
245
+ undefined,
246
+ );
247
+ }
248
+
249
+ for (const [name, q] of questionEntries) {
250
+ if (!QUESTION_ID_PATTERN.test(name)) {
251
+ throw new DecisionRequestError(
252
+ 'Question ID does not match pattern ^[A-Za-z0-9_.-]{1,100}$',
253
+ undefined,
254
+ undefined,
255
+ );
256
+ }
257
+ if (q.kind === 'choice') {
258
+ const labelKeys = Object.keys(q.labels);
259
+ if (labelKeys.length < 2 || labelKeys.length > 255) {
260
+ throw new DecisionRequestError(
261
+ `Choice question must have between 2 and 255 choice IDs, got ${labelKeys.length}`,
262
+ undefined,
263
+ undefined,
264
+ );
265
+ }
266
+ for (const labelId of labelKeys) {
267
+ if (labelId.length === 0) {
268
+ throw new DecisionRequestError(
269
+ 'Choice question contains empty choice ID',
270
+ undefined,
271
+ undefined,
272
+ );
273
+ }
274
+ }
275
+ } else if (q.kind === 'score') {
276
+ const levels = q.rubric.length;
277
+ if (levels < 2 || levels > 10) {
278
+ throw new DecisionRequestError(
279
+ `Score question must have between 2 and 10 score levels, got ${levels}`,
280
+ undefined,
281
+ undefined,
282
+ );
283
+ }
284
+ }
285
+ }
286
+
287
+ assertJsonSerializable(state, 'state');
288
+
289
+ const mappedQuestions = Object.fromEntries(
290
+ questionEntries.map(([name, q]) => [name, mapQuestion(name, q)]),
291
+ );
292
+
293
+ const requestBody = {
294
+ model: resolvedModel,
295
+ state: state ?? null,
296
+ questions: mappedQuestions,
297
+ };
298
+
299
+ assertJsonSerializable(requestBody, 'request');
300
+
301
+ const bodyString = JSON.stringify(requestBody);
302
+ const bodyBytes = new TextEncoder().encode(bodyString).byteLength;
303
+ if (bodyBytes > MAX_REQUEST_BODY_BYTES) {
304
+ throw new DecisionRequestError('Request body exceeds maximum size of 13 MiB', undefined, undefined);
305
+ }
306
+
307
+ const path = `/accounts/${accountId}/ai/run/@cf/cloudflare/${resolvedModel}`;
308
+ let response: RawHttpResponse;
309
+ try {
310
+ response = await client.rawRequest('POST', path, bodyString, {
311
+ headers: {
312
+ Authorization: `Bearer ${apiToken}`,
313
+ 'Content-Type': 'application/json',
314
+ },
315
+ redirect: 'manual',
316
+ maxResponseBytes: MAX_RESPONSE_BYTES,
317
+ });
318
+ } catch (error) {
319
+ // The design forbids leaking untrusted transport error text/cause through public
320
+ // errors, so these stay generic: only the message and the timeoutMs field travel.
321
+ if (error instanceof APIError && error.status === 0) {
322
+ throw new DecisionTimeoutError('Request timed out', timeoutMs);
323
+ }
324
+ throw new DecisionConnectionError('Failed to connect to backend');
325
+ }
326
+
327
+ if (response.truncated) {
328
+ throw new DecisionBackendError('Response exceeded maximum allowed size of 8 MiB', response.status);
329
+ }
330
+
331
+ if (response.status >= 300 && response.status < 400) {
332
+ throw new DecisionBackendError(`HTTP ${response.status} redirect received`, response.status);
333
+ }
334
+
335
+ if (response.status === 401 || response.status === 403) {
336
+ throw new DecisionAuthError(`HTTP ${response.status} authentication failure`, response.status);
337
+ }
338
+
339
+ if (response.status === 429) {
340
+ const retryAfterHeader = getHeader(response.headers, 'retry-after');
341
+ const retryAfterMs = parseRetryAfter(retryAfterHeader);
342
+ throw new DecisionRateLimitError('HTTP 429 rate limit exceeded', response.status, retryAfterMs);
343
+ }
344
+
345
+ if (response.status >= 400 && response.status < 500) {
346
+ throw new DecisionRequestError(`HTTP ${response.status} request error`, response.status, undefined);
347
+ }
348
+
349
+ if (response.status >= 500 && response.status < 600) {
350
+ throw new DecisionBackendError(`HTTP ${response.status} backend error`, response.status);
351
+ }
352
+
353
+ if (response.status < 200 || response.status >= 300) {
354
+ throw new DecisionBackendError(`HTTP ${response.status} unexpected status`, response.status);
355
+ }
356
+
357
+ let json: unknown;
358
+ try {
359
+ json = JSON.parse(response.body);
360
+ } catch {
361
+ throw new DecisionBackendError('Malformed JSON response from backend', response.status);
362
+ }
363
+
364
+ if (!isRecord(json) || json.success !== true) {
365
+ throw new DecisionBackendError('Backend returned failure envelope', response.status);
366
+ }
367
+
368
+ if (!isRecord(json.result)) {
369
+ throw new DecisionBackendError('Missing or invalid result in response', response.status);
370
+ }
371
+
372
+ const result = json.result;
373
+ if (typeof result.model !== 'string' || result.model.trim().length === 0) {
374
+ throw new DecisionBackendError('Invalid or missing model in response', response.status);
375
+ }
376
+
377
+ if (!isRecord(result.answers)) {
378
+ throw new DecisionBackendError('Invalid or missing answers in response', response.status);
379
+ }
380
+
381
+ const answers: Record<string, Answer> = Object.create(null);
382
+ for (const [name, rawAnswer] of Object.entries(result.answers)) {
383
+ if (!isRecord(rawAnswer)) {
384
+ throw new DecisionBackendError('Invalid answer in response', response.status);
385
+ }
386
+ switch (rawAnswer.type) {
387
+ case 'choice': {
388
+ if (
389
+ typeof rawAnswer.choice !== 'string' ||
390
+ typeof rawAnswer.confidence !== 'number' ||
391
+ !isRecord(rawAnswer.probabilities)
392
+ ) {
393
+ throw new DecisionBackendError('Malformed choice answer in response', response.status);
394
+ }
395
+ answers[name] = {
396
+ kind: 'choice',
397
+ label: rawAnswer.choice,
398
+ confidence: rawAnswer.confidence,
399
+ // Cast: shared validateAnswers re-checks every entry's bounds and mass; this
400
+ // only reshapes the untyped wire record into the neutral answer shape.
401
+ probabilities: Object.fromEntries(Object.entries(rawAnswer.probabilities)) as Record<
402
+ string,
403
+ number
404
+ >,
405
+ };
406
+ break;
407
+ }
408
+ case 'score': {
409
+ if (
410
+ typeof rawAnswer.score !== 'number' ||
411
+ typeof rawAnswer.confidence !== 'number' ||
412
+ !isRecord(rawAnswer.legend) ||
413
+ !isRecord(rawAnswer.probabilities)
414
+ ) {
415
+ throw new DecisionBackendError('Malformed score answer in response', response.status);
416
+ }
417
+ answers[name] = {
418
+ kind: 'score',
419
+ score: rawAnswer.score,
420
+ confidence: rawAnswer.confidence,
421
+ legend: Object.fromEntries(Object.entries(rawAnswer.legend)) as Record<number, Desc>,
422
+ probabilities: Object.fromEntries(Object.entries(rawAnswer.probabilities)) as Record<
423
+ number,
424
+ number
425
+ >,
426
+ };
427
+ break;
428
+ }
429
+ case 'noul': {
430
+ if (typeof rawAnswer.noul !== 'number') {
431
+ throw new DecisionBackendError('Malformed noul answer in response', response.status);
432
+ }
433
+ answers[name] = {
434
+ kind: 'noul',
435
+ probability: rawAnswer.noul,
436
+ };
437
+ break;
438
+ }
439
+ default:
440
+ throw new DecisionBackendError('Unknown answer type in response', response.status);
441
+ }
442
+ }
443
+
444
+ try {
445
+ validateAnswers(questions, answers);
446
+ } catch {
447
+ throw new DecisionBackendError('Invalid decision answers in response', response.status);
448
+ }
449
+ return answers;
450
+ },
451
+ };
452
+ }
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export type { ClefDriverOptions, ClefModel } from './driver';
2
+ export { createClefDriver } from './driver';