@gobing-ai/ts-decision-openai 0.0.0-stage → 0.8.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/dist/driver.js ADDED
@@ -0,0 +1,426 @@
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 DEFAULT_BASE_URL = 'https://api.openai.com';
4
+ const QUESTION_ID_PATTERN = /^[A-Za-z0-9_.-]{1,100}$/;
5
+ const MAX_QUESTIONS = 400;
6
+ const MAX_REQUEST_BODY_BYTES = 13 * 1024 * 1024;
7
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
8
+ function isRecord(value) {
9
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
10
+ }
11
+ /** Blank, whitespace and C0/DEL control characters cannot survive an HTTP header round-trip. */
12
+ function hasControlOrWhitespace(value) {
13
+ for (let i = 0; i < value.length; i++) {
14
+ const code = value.charCodeAt(i);
15
+ if (code <= 0x20 || code === 0x7f)
16
+ return true;
17
+ }
18
+ return false;
19
+ }
20
+ function assertJsonSerializable(value, context, ancestors = new Set()) {
21
+ if (value === null)
22
+ return;
23
+ if (typeof value === 'string' || typeof value === 'boolean')
24
+ return;
25
+ if (typeof value === 'number') {
26
+ if (!Number.isFinite(value)) {
27
+ throw new DecisionRequestError(`Non-finite number in ${context}`, undefined, undefined);
28
+ }
29
+ return;
30
+ }
31
+ if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol' || value === undefined) {
32
+ throw new DecisionRequestError(`Unserializable ${typeof value} in ${context}`, undefined, undefined);
33
+ }
34
+ if (typeof value === 'object') {
35
+ if (ancestors.has(value)) {
36
+ throw new DecisionRequestError(`Circular reference detected in ${context}`, undefined, undefined);
37
+ }
38
+ ancestors.add(value);
39
+ try {
40
+ if (Object.values(Object.getOwnPropertyDescriptors(value)).some((property) => !Object.hasOwn(property, 'value'))) {
41
+ throw new DecisionRequestError(`Accessor property in ${context}`, undefined, undefined);
42
+ }
43
+ if (Array.isArray(value)) {
44
+ // Extra own properties and holes are both dropped or coerced by JSON.stringify;
45
+ // only a dense, index-only array survives round-trip intact.
46
+ if (Object.keys(value).length !== value.length ||
47
+ Object.getOwnPropertyNames(value).length !== value.length + 1 ||
48
+ Object.getOwnPropertySymbols(value).length > 0) {
49
+ throw new DecisionRequestError(`Sparse or decorated array in ${context}`, undefined, undefined);
50
+ }
51
+ for (let i = 0; i < value.length; i++) {
52
+ assertJsonSerializable(value[i], context, ancestors);
53
+ }
54
+ }
55
+ else {
56
+ const proto = Object.getPrototypeOf(value);
57
+ if (proto !== null && proto !== Object.prototype) {
58
+ throw new DecisionRequestError(`Unsupported object instance in ${context}`, undefined, undefined);
59
+ }
60
+ // Symbol keys and non-enumerable own properties are invisible to Object.keys and are
61
+ // dropped by JSON.stringify, so they would otherwise be a silent loss.
62
+ const ownNames = Object.getOwnPropertyNames(value);
63
+ if (Object.getOwnPropertySymbols(value).length > 0 || ownNames.length !== Object.keys(value).length) {
64
+ throw new DecisionRequestError(`Unserializable own property in ${context}`, undefined, undefined);
65
+ }
66
+ for (const key of ownNames) {
67
+ assertJsonSerializable(value[key], context, ancestors);
68
+ }
69
+ }
70
+ }
71
+ finally {
72
+ ancestors.delete(value);
73
+ }
74
+ return;
75
+ }
76
+ throw new DecisionRequestError(`Unserializable value in ${context}`, undefined, undefined);
77
+ }
78
+ function resolveInstructions(prompt, questionId) {
79
+ if (prompt === undefined || prompt === null) {
80
+ return questionId;
81
+ }
82
+ if (typeof prompt === 'string' && prompt.trim().length === 0) {
83
+ return questionId;
84
+ }
85
+ return prompt;
86
+ }
87
+ function mapQuestion(name, q) {
88
+ const instructions = resolveInstructions(q.prompt, name);
89
+ switch (q.kind) {
90
+ case 'choice':
91
+ return {
92
+ type: 'choice',
93
+ instructions,
94
+ criteria: Object.fromEntries(Object.entries(q.labels)),
95
+ };
96
+ case 'score':
97
+ return {
98
+ type: 'score',
99
+ instructions,
100
+ criteria: q.rubric,
101
+ };
102
+ case 'noul': {
103
+ const mapped = {
104
+ type: 'noul',
105
+ instructions,
106
+ };
107
+ if (q.yes !== undefined || q.no !== undefined) {
108
+ const criteria = {};
109
+ if (q.yes !== undefined)
110
+ criteria.true = q.yes;
111
+ if (q.no !== undefined)
112
+ criteria.false = q.no;
113
+ mapped.criteria = criteria;
114
+ }
115
+ return mapped;
116
+ }
117
+ }
118
+ }
119
+ function getHeader(headers, name) {
120
+ const target = name.toLowerCase();
121
+ for (const [key, value] of Object.entries(headers)) {
122
+ if (key.toLowerCase() === target) {
123
+ return value;
124
+ }
125
+ }
126
+ return undefined;
127
+ }
128
+ function parseRetryAfter(header) {
129
+ if (!header)
130
+ return undefined;
131
+ const trimmed = header.trim();
132
+ if (/^\d+$/.test(trimmed)) {
133
+ const milliseconds = Number(trimmed) * 1000;
134
+ return Number.isFinite(milliseconds) ? milliseconds : undefined;
135
+ }
136
+ // HTTP dates start with a weekday; Date.parse also accepts invalid numeric hints as dates.
137
+ if (!/^[A-Za-z]+(?:,| )/.test(trimmed))
138
+ return undefined;
139
+ const timestamp = Date.parse(trimmed);
140
+ if (!Number.isNaN(timestamp)) {
141
+ return Math.max(0, timestamp - Date.now());
142
+ }
143
+ return undefined;
144
+ }
145
+ /**
146
+ * Normalize a wire probability distribution into a string-keyed record. The Decisions API
147
+ * accepts both a keyed object (`{ "0": 0.9 }` / `{ bug: 0.9 }`) and an array of
148
+ * `{ value, probability }` entries; `validateAnswers` needs the record form.
149
+ */
150
+ function normalizeDistribution(raw, status) {
151
+ if (isRecord(raw)) {
152
+ return Object.fromEntries(Object.entries(raw));
153
+ }
154
+ if (Array.isArray(raw)) {
155
+ const out = Object.create(null);
156
+ for (const entry of raw) {
157
+ if (!isRecord(entry) || !('value' in entry) || typeof entry.probability !== 'number') {
158
+ throw new DecisionBackendError('Malformed probability distribution in response', status);
159
+ }
160
+ const key = String(entry.value);
161
+ if (Object.hasOwn(out, key)) {
162
+ throw new DecisionBackendError('Duplicate probability entry in response', status);
163
+ }
164
+ out[key] = entry.probability;
165
+ }
166
+ return Object.fromEntries(Object.entries(out));
167
+ }
168
+ throw new DecisionBackendError('Malformed probability distribution in response', status);
169
+ }
170
+ /**
171
+ * Build the hosted GPT-6 Luna decision driver: validates the configuration and constructs
172
+ * exactly one `APIClient`. No network call and no environment read happen here.
173
+ */
174
+ export function createOpenAIDecisionDriver(options) {
175
+ if (!options || typeof options !== 'object') {
176
+ throw new DecisionConfigError('Options must be provided', 'options');
177
+ }
178
+ const { apiKey, model: configuredModel = 'gpt-6-luna', baseURL, timeoutMs = 30_000, fetch: customFetch } = options;
179
+ if (typeof apiKey !== 'string' || apiKey.length === 0 || hasControlOrWhitespace(apiKey)) {
180
+ throw new DecisionConfigError('Invalid apiKey: cannot be blank or contain whitespace or control characters', 'apiKey');
181
+ }
182
+ let baseUrl = DEFAULT_BASE_URL;
183
+ if (baseURL !== undefined) {
184
+ let parsed;
185
+ try {
186
+ parsed = new URL(baseURL);
187
+ }
188
+ catch {
189
+ throw new DecisionConfigError('Invalid baseURL: must be a valid http(s) URL', 'baseURL');
190
+ }
191
+ if ((parsed.protocol !== 'https:' && parsed.protocol !== 'http:') ||
192
+ parsed.username.length > 0 ||
193
+ parsed.password.length > 0 ||
194
+ parsed.search.length > 0 ||
195
+ parsed.hash.length > 0) {
196
+ throw new DecisionConfigError('Invalid baseURL: must be an http(s) URL without credentials, query or hash', 'baseURL');
197
+ }
198
+ baseUrl = baseURL.replace(/\/+$/, '');
199
+ }
200
+ if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs <= 0) {
201
+ throw new DecisionConfigError('Invalid timeoutMs: must be a positive integer', 'timeoutMs');
202
+ }
203
+ if (configuredModel !== 'gpt-6-luna') {
204
+ throw new DecisionConfigError('Invalid model: must be gpt-6-luna', 'model');
205
+ }
206
+ const client = new APIClient({
207
+ baseUrl,
208
+ timeout: timeoutMs,
209
+ fetch: customFetch,
210
+ });
211
+ return {
212
+ name: 'openai-luna',
213
+ async ask({ state, questions, model }) {
214
+ try {
215
+ validateQuestions(questions);
216
+ }
217
+ catch {
218
+ throw new DecisionRequestError('Invalid decision questions', undefined, undefined);
219
+ }
220
+ if (model !== undefined && model !== 'gpt-6-luna') {
221
+ throw new DecisionRequestError('Invalid model selector: must be gpt-6-luna', undefined, undefined);
222
+ }
223
+ const resolvedModel = model ?? configuredModel;
224
+ const questionEntries = Object.entries(questions);
225
+ if (questionEntries.length < 1 || questionEntries.length > MAX_QUESTIONS) {
226
+ throw new DecisionRequestError(`Question count must be between 1 and ${MAX_QUESTIONS}, got ${questionEntries.length}`, undefined, undefined);
227
+ }
228
+ for (const [name, q] of questionEntries) {
229
+ if (!QUESTION_ID_PATTERN.test(name)) {
230
+ throw new DecisionRequestError('Question ID does not match pattern ^[A-Za-z0-9_.-]{1,100}$', undefined, undefined);
231
+ }
232
+ if (q.kind === 'choice') {
233
+ const labelKeys = Object.keys(q.labels);
234
+ if (labelKeys.length < 2 || labelKeys.length > 255) {
235
+ throw new DecisionRequestError(`Choice question must have between 2 and 255 choice IDs, got ${labelKeys.length}`, undefined, undefined);
236
+ }
237
+ for (const labelId of labelKeys) {
238
+ if (labelId.length === 0) {
239
+ throw new DecisionRequestError('Choice question contains empty choice ID', undefined, undefined);
240
+ }
241
+ }
242
+ }
243
+ else if (q.kind === 'score') {
244
+ const levels = q.rubric.length;
245
+ if (levels < 2 || levels > 255) {
246
+ throw new DecisionRequestError(`Score question must have between 2 and 255 score levels, got ${levels}`, undefined, undefined);
247
+ }
248
+ }
249
+ }
250
+ // `undefined` means "no caller context" exactly as `null` does — the neutral contract
251
+ // has one absent state, so validate it as such rather than rejecting it as unserializable.
252
+ assertJsonSerializable(state ?? null, 'state');
253
+ const mappedQuestions = Object.fromEntries(questionEntries.map(([name, q]) => [name, mapQuestion(name, q)]));
254
+ const requestBody = {
255
+ model: resolvedModel,
256
+ // The Decisions API requires `input` to be present: the neutral contract's absent
257
+ // state maps to the empty string, exactly like the clef, laya and fm drivers.
258
+ input: state ?? '',
259
+ questions: mappedQuestions,
260
+ };
261
+ assertJsonSerializable(requestBody, 'request');
262
+ const bodyString = JSON.stringify(requestBody);
263
+ const bodyBytes = new TextEncoder().encode(bodyString).byteLength;
264
+ if (bodyBytes > MAX_REQUEST_BODY_BYTES) {
265
+ throw new DecisionRequestError('Request body exceeds maximum size of 13 MiB', undefined, undefined);
266
+ }
267
+ let response;
268
+ try {
269
+ response = await client.rawRequest('POST', '/v1/decisions', bodyString, {
270
+ headers: {
271
+ Authorization: `Bearer ${apiKey}`,
272
+ 'Content-Type': 'application/json',
273
+ },
274
+ redirect: 'manual',
275
+ maxResponseBytes: MAX_RESPONSE_BYTES,
276
+ });
277
+ }
278
+ catch (error) {
279
+ // The design forbids leaking untrusted transport error text/cause through public
280
+ // errors, so these stay generic: only the message and the timeoutMs field travel.
281
+ if (error instanceof APIError && error.status === 0) {
282
+ throw new DecisionTimeoutError('Request timed out', timeoutMs);
283
+ }
284
+ throw new DecisionConnectionError('Failed to connect to backend');
285
+ }
286
+ if (response.truncated) {
287
+ throw new DecisionBackendError('Response exceeded maximum allowed size of 8 MiB', response.status);
288
+ }
289
+ if (response.status >= 300 && response.status < 400) {
290
+ throw new DecisionBackendError(`HTTP ${response.status} redirect received`, response.status);
291
+ }
292
+ if (response.status === 408) {
293
+ throw new DecisionTimeoutError('HTTP 408 request timeout', response.status);
294
+ }
295
+ if (response.status === 401 || response.status === 403) {
296
+ throw new DecisionAuthError(`HTTP ${response.status} authentication failure`, response.status);
297
+ }
298
+ if (response.status === 429) {
299
+ const retryAfterHeader = getHeader(response.headers, 'retry-after');
300
+ const retryAfterMs = parseRetryAfter(retryAfterHeader);
301
+ throw new DecisionRateLimitError('HTTP 429 rate limit exceeded', response.status, retryAfterMs);
302
+ }
303
+ if (response.status >= 400 && response.status < 500) {
304
+ throw new DecisionRequestError(`HTTP ${response.status} request error`, response.status, undefined);
305
+ }
306
+ if (response.status >= 500 && response.status < 600) {
307
+ throw new DecisionBackendError(`HTTP ${response.status} backend error`, response.status);
308
+ }
309
+ if (response.status < 200 || response.status >= 300) {
310
+ throw new DecisionBackendError(`HTTP ${response.status} unexpected status`, response.status);
311
+ }
312
+ let json;
313
+ try {
314
+ json = JSON.parse(response.body);
315
+ }
316
+ catch {
317
+ throw new DecisionBackendError('Malformed JSON response from backend', response.status);
318
+ }
319
+ if (!isRecord(json)) {
320
+ throw new DecisionBackendError('Malformed response envelope from backend', response.status);
321
+ }
322
+ // The Decisions API answers either at the top level (`{ answers }`) or wrapped
323
+ // (`{ result: { answers } }`); `answers` itself is a keyed object or an array of
324
+ // named entries. Unknown envelopes fail closed.
325
+ let rawAnswers;
326
+ if (json.answers !== undefined) {
327
+ rawAnswers = json.answers;
328
+ }
329
+ else if (isRecord(json.result) && json.result.answers !== undefined) {
330
+ rawAnswers = json.result.answers;
331
+ }
332
+ else {
333
+ throw new DecisionBackendError('Invalid or missing answers in response', response.status);
334
+ }
335
+ let rawEntries;
336
+ if (Array.isArray(rawAnswers)) {
337
+ rawEntries = rawAnswers.map((entry) => {
338
+ if (!isRecord(entry) || typeof entry.name !== 'string') {
339
+ throw new DecisionBackendError('Invalid answer entry in response', response.status);
340
+ }
341
+ return [entry.name, entry];
342
+ });
343
+ }
344
+ else if (isRecord(rawAnswers)) {
345
+ rawEntries = Object.entries(rawAnswers);
346
+ }
347
+ else {
348
+ throw new DecisionBackendError('Invalid or missing answers in response', response.status);
349
+ }
350
+ const answers = Object.create(null);
351
+ for (const [name, rawAnswer] of rawEntries) {
352
+ if (Object.hasOwn(answers, name)) {
353
+ throw new DecisionBackendError('Duplicate answer entry in response', response.status);
354
+ }
355
+ if (!isRecord(rawAnswer)) {
356
+ throw new DecisionBackendError('Invalid answer in response', response.status);
357
+ }
358
+ switch (rawAnswer.type) {
359
+ case 'choice': {
360
+ const label = rawAnswer.choice ?? rawAnswer.label;
361
+ if (typeof label !== 'string' ||
362
+ typeof rawAnswer.confidence !== 'number' ||
363
+ rawAnswer.probabilities === undefined) {
364
+ throw new DecisionBackendError('Malformed choice answer in response', response.status);
365
+ }
366
+ answers[name] = {
367
+ kind: 'choice',
368
+ label,
369
+ confidence: rawAnswer.confidence,
370
+ // Cast: shared validateAnswers re-checks every entry's bounds and mass; this
371
+ // only reshapes the untyped wire record into the neutral answer shape.
372
+ probabilities: normalizeDistribution(rawAnswer.probabilities, response.status),
373
+ };
374
+ break;
375
+ }
376
+ case 'score': {
377
+ if (typeof rawAnswer.score !== 'number' ||
378
+ typeof rawAnswer.confidence !== 'number' ||
379
+ rawAnswer.probabilities === undefined) {
380
+ throw new DecisionBackendError('Malformed score answer in response', response.status);
381
+ }
382
+ const rubric = questions[name]?.kind === 'score' ? questions[name].rubric : undefined;
383
+ const legend = rawAnswer.legend !== undefined
384
+ ? normalizeDistribution(rawAnswer.legend, response.status)
385
+ : // Legend omitted on wire: fall back to the request's rubric, indexed
386
+ // 0-based to match the neutral ScoreAnswer key contract.
387
+ Object.fromEntries((rubric ?? []).map((desc, index) => [String(index), desc]));
388
+ if (!isRecord(legend)) {
389
+ throw new DecisionBackendError('Malformed score legend in response', response.status);
390
+ }
391
+ answers[name] = {
392
+ kind: 'score',
393
+ score: rawAnswer.score,
394
+ confidence: rawAnswer.confidence,
395
+ legend: Object.fromEntries(Object.entries(legend)),
396
+ probabilities: normalizeDistribution(rawAnswer.probabilities, response.status),
397
+ };
398
+ break;
399
+ }
400
+ case 'noul': {
401
+ // Only the bare probability travels; a wire `confidence` is ignored — the
402
+ // neutral contract refuses to fabricate calibration data.
403
+ const probability = rawAnswer.noul ?? rawAnswer.probability;
404
+ if (typeof probability !== 'number') {
405
+ throw new DecisionBackendError('Malformed noul answer in response', response.status);
406
+ }
407
+ answers[name] = {
408
+ kind: 'noul',
409
+ probability,
410
+ };
411
+ break;
412
+ }
413
+ default:
414
+ throw new DecisionBackendError('Unknown answer type in response', response.status);
415
+ }
416
+ }
417
+ try {
418
+ validateAnswers(questions, answers);
419
+ }
420
+ catch {
421
+ throw new DecisionBackendError('Invalid decision answers in response', response.status);
422
+ }
423
+ return answers;
424
+ },
425
+ };
426
+ }
@@ -0,0 +1,4 @@
1
+ import { createOpenAIDecisionDriver, type OpenAIDecisionDriverOptions, type OpenAIDecisionModel } from './driver';
2
+ export type { OpenAIDecisionDriverOptions, OpenAIDecisionModel };
3
+ export { createOpenAIDecisionDriver };
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,KAAK,2BAA2B,EAAE,KAAK,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAElH,YAAY,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,CAAC;AACjE,OAAO,EAAE,0BAA0B,EAAE,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import { createOpenAIDecisionDriver } from './driver.js';
2
+ export { createOpenAIDecisionDriver };
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
- "name": "@gobing-ai/ts-decision-openai",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@gobing-ai/ts-decision-openai",
3
+ "version": "0.8.1",
4
+ "description": "@gobing-ai/ts-decision-openai — OpenAI GPT-6 Luna decision backend driving the hosted Decisions API over the portable ts-infra APIClient seam.",
5
+ "keywords": [
6
+ "openai",
7
+ "gpt-6-luna",
8
+ "decision",
9
+ "decision-maker",
10
+ "ai-runner"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/gobing-ai/ts-libs.git",
15
+ "directory": "packages/decision-openai"
16
+ },
17
+ "author": "Robin Min <minlongbing@gmail.com>",
18
+ "contributors": [
19
+ "Robin Min <minlongbing@gmail.com>"
20
+ ],
21
+ "type": "module",
22
+ "private": false,
23
+ "sideEffects": false,
24
+ "license": "Apache-2.0",
25
+ "main": "./dist/index.js",
26
+ "types": "./dist/index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "import": "./dist/index.js"
31
+ }
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "src",
36
+ "README.md",
37
+ "LICENSE",
38
+ "NOTICE"
39
+ ],
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.build.json && bun ../../scripts/builder.ts fix-dist-esm-extensions dist",
42
+ "test": "NODE_ENV=test bun test --coverage --coverage-dir=.coverage --reporter=dots",
43
+ "test:full": "NODE_ENV=test bun test --update-snapshots --coverage --coverage-dir=.coverage",
44
+ "typecheck": "tsc --noEmit",
45
+ "lint": "biome check . && bun run typecheck",
46
+ "format": "biome check . --write",
47
+ "check": "bun run lint && bun run test",
48
+ "prepublishOnly": "bun ../../scripts/builder.ts check-publish-manifest . && bun run build",
49
+ "release": "echo 'Manual publish is disabled. Releases go through GitHub Actions via Trusted Publishing — push a tag: git tag @gobing-ai/ts-decision-openai-v<version> && git push --tags' && exit 1"
50
+ },
51
+ "dependencies": {
52
+ "@gobing-ai/ts-ai-runner": "^0.8.1",
53
+ "@gobing-ai/ts-infra": "^0.8.1"
54
+ },
55
+ "devDependencies": {
56
+ "@gobing-ai/ts-ai-decision": "^0.8.1",
57
+ "@types/bun": "1.4.3"
58
+ },
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }