@gobing-ai/ts-decision-openai 0.0.0-stage → 0.8.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/src/driver.ts ADDED
@@ -0,0 +1,526 @@
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
+ type ScoreQuestion,
14
+ validateAnswers,
15
+ validateQuestions,
16
+ } from '@gobing-ai/ts-ai-runner';
17
+ import { APIClient, APIError, type RawHttpResponse } from '@gobing-ai/ts-infra';
18
+
19
+ /** The hosted GPT-6 Luna decision selector this driver routes to. */
20
+ export type OpenAIDecisionModel = 'gpt-6-luna';
21
+
22
+ /** Construction options for {@link createOpenAIDecisionDriver}. Credentials are always explicit. */
23
+ export interface OpenAIDecisionDriverOptions {
24
+ /** OpenAI API key — non-blank, with no whitespace or control characters. */
25
+ apiKey: string;
26
+ /** Default model selector; per-call `ask({ model })` wins. Defaults to `gpt-6-luna`. */
27
+ model?: OpenAIDecisionModel;
28
+ /** API origin, `http:`/`https:` only, no credentials/query/hash. Defaults to the OpenAI endpoint. */
29
+ baseURL?: string;
30
+ /** Request timeout in milliseconds; a positive integer. Defaults to `30000`. */
31
+ timeoutMs?: number;
32
+ /** Injected fetch, forwarded to the `APIClient` (tests use this instead of a socket). */
33
+ fetch?: typeof globalThis.fetch;
34
+ }
35
+
36
+ const DEFAULT_BASE_URL = 'https://api.openai.com';
37
+ const QUESTION_ID_PATTERN = /^[A-Za-z0-9_.-]{1,100}$/;
38
+ const MAX_QUESTIONS = 400;
39
+ const MAX_REQUEST_BODY_BYTES = 13 * 1024 * 1024;
40
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
41
+
42
+ function isRecord(value: unknown): value is Record<string, unknown> {
43
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
44
+ }
45
+
46
+ /** Blank, whitespace and C0/DEL control characters cannot survive an HTTP header round-trip. */
47
+ function hasControlOrWhitespace(value: string): boolean {
48
+ for (let i = 0; i < value.length; i++) {
49
+ const code = value.charCodeAt(i);
50
+ if (code <= 0x20 || code === 0x7f) return true;
51
+ }
52
+ return false;
53
+ }
54
+
55
+ function assertJsonSerializable(value: unknown, context: string, ancestors = new Set<unknown>()): void {
56
+ if (value === null) return;
57
+ if (typeof value === 'string' || typeof value === 'boolean') return;
58
+ if (typeof value === 'number') {
59
+ if (!Number.isFinite(value)) {
60
+ throw new DecisionRequestError(`Non-finite number in ${context}`, undefined, undefined);
61
+ }
62
+ return;
63
+ }
64
+ if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol' || value === undefined) {
65
+ throw new DecisionRequestError(`Unserializable ${typeof value} in ${context}`, undefined, undefined);
66
+ }
67
+ if (typeof value === 'object') {
68
+ if (ancestors.has(value)) {
69
+ throw new DecisionRequestError(`Circular reference detected in ${context}`, undefined, undefined);
70
+ }
71
+ ancestors.add(value);
72
+ try {
73
+ if (
74
+ Object.values(Object.getOwnPropertyDescriptors(value)).some(
75
+ (property) => !Object.hasOwn(property, 'value'),
76
+ )
77
+ ) {
78
+ throw new DecisionRequestError(`Accessor property in ${context}`, undefined, undefined);
79
+ }
80
+ if (Array.isArray(value)) {
81
+ // Extra own properties and holes are both dropped or coerced by JSON.stringify;
82
+ // only a dense, index-only array survives round-trip intact.
83
+ if (
84
+ Object.keys(value).length !== value.length ||
85
+ Object.getOwnPropertyNames(value).length !== value.length + 1 ||
86
+ Object.getOwnPropertySymbols(value).length > 0
87
+ ) {
88
+ throw new DecisionRequestError(`Sparse or decorated array in ${context}`, undefined, undefined);
89
+ }
90
+ for (let i = 0; i < value.length; i++) {
91
+ assertJsonSerializable(value[i], context, ancestors);
92
+ }
93
+ } else {
94
+ const proto = Object.getPrototypeOf(value);
95
+ if (proto !== null && proto !== Object.prototype) {
96
+ throw new DecisionRequestError(`Unsupported object instance in ${context}`, undefined, undefined);
97
+ }
98
+ // Symbol keys and non-enumerable own properties are invisible to Object.keys and are
99
+ // dropped by JSON.stringify, so they would otherwise be a silent loss.
100
+ const ownNames = Object.getOwnPropertyNames(value);
101
+ if (Object.getOwnPropertySymbols(value).length > 0 || ownNames.length !== Object.keys(value).length) {
102
+ throw new DecisionRequestError(`Unserializable own property in ${context}`, undefined, undefined);
103
+ }
104
+ for (const key of ownNames) {
105
+ assertJsonSerializable((value as Record<string, unknown>)[key], context, ancestors);
106
+ }
107
+ }
108
+ } finally {
109
+ ancestors.delete(value);
110
+ }
111
+ return;
112
+ }
113
+ throw new DecisionRequestError(`Unserializable value in ${context}`, undefined, undefined);
114
+ }
115
+
116
+ function resolveInstructions(prompt: Desc | undefined, questionId: string): unknown {
117
+ if (prompt === undefined || prompt === null) {
118
+ return questionId;
119
+ }
120
+ if (typeof prompt === 'string' && prompt.trim().length === 0) {
121
+ return questionId;
122
+ }
123
+ return prompt;
124
+ }
125
+
126
+ function mapQuestion(name: string, q: Question): Record<string, unknown> {
127
+ const instructions = resolveInstructions(q.prompt, name);
128
+ switch (q.kind) {
129
+ case 'choice':
130
+ return {
131
+ type: 'choice',
132
+ instructions,
133
+ criteria: Object.fromEntries(Object.entries(q.labels)),
134
+ };
135
+ case 'score':
136
+ return {
137
+ type: 'score',
138
+ instructions,
139
+ criteria: q.rubric,
140
+ };
141
+ case 'noul': {
142
+ const mapped: Record<string, unknown> = {
143
+ type: 'noul',
144
+ instructions,
145
+ };
146
+ if (q.yes !== undefined || q.no !== undefined) {
147
+ const criteria: Record<string, unknown> = {};
148
+ if (q.yes !== undefined) criteria.true = q.yes;
149
+ if (q.no !== undefined) criteria.false = q.no;
150
+ mapped.criteria = criteria;
151
+ }
152
+ return mapped;
153
+ }
154
+ }
155
+ }
156
+
157
+ function getHeader(headers: Record<string, string>, name: string): string | undefined {
158
+ const target = name.toLowerCase();
159
+ for (const [key, value] of Object.entries(headers)) {
160
+ if (key.toLowerCase() === target) {
161
+ return value;
162
+ }
163
+ }
164
+ return undefined;
165
+ }
166
+
167
+ function parseRetryAfter(header: string | undefined): number | undefined {
168
+ if (!header) return undefined;
169
+ const trimmed = header.trim();
170
+ if (/^\d+$/.test(trimmed)) {
171
+ const milliseconds = Number(trimmed) * 1000;
172
+ return Number.isFinite(milliseconds) ? milliseconds : undefined;
173
+ }
174
+ // HTTP dates start with a weekday; Date.parse also accepts invalid numeric hints as dates.
175
+ if (!/^[A-Za-z]+(?:,| )/.test(trimmed)) return undefined;
176
+ const timestamp = Date.parse(trimmed);
177
+ if (!Number.isNaN(timestamp)) {
178
+ return Math.max(0, timestamp - Date.now());
179
+ }
180
+ return undefined;
181
+ }
182
+
183
+ /**
184
+ * Normalize a wire probability distribution into a string-keyed record. The Decisions API
185
+ * accepts both a keyed object (`{ "0": 0.9 }` / `{ bug: 0.9 }`) and an array of
186
+ * `{ value, probability }` entries; `validateAnswers` needs the record form.
187
+ */
188
+ function normalizeDistribution(raw: unknown, status: number): Record<string, number> {
189
+ if (isRecord(raw)) {
190
+ return Object.fromEntries(Object.entries(raw)) as Record<string, number>;
191
+ }
192
+ if (Array.isArray(raw)) {
193
+ const out: Record<string, number> = Object.create(null);
194
+ for (const entry of raw) {
195
+ if (!isRecord(entry) || !('value' in entry) || typeof entry.probability !== 'number') {
196
+ throw new DecisionBackendError('Malformed probability distribution in response', status);
197
+ }
198
+ const key = String(entry.value);
199
+ if (Object.hasOwn(out, key)) {
200
+ throw new DecisionBackendError('Duplicate probability entry in response', status);
201
+ }
202
+ out[key] = entry.probability;
203
+ }
204
+ return Object.fromEntries(Object.entries(out));
205
+ }
206
+ throw new DecisionBackendError('Malformed probability distribution in response', status);
207
+ }
208
+
209
+ /**
210
+ * Build the hosted GPT-6 Luna decision driver: validates the configuration and constructs
211
+ * exactly one `APIClient`. No network call and no environment read happen here.
212
+ */
213
+ export function createOpenAIDecisionDriver(options: OpenAIDecisionDriverOptions): DecisionDriver {
214
+ if (!options || typeof options !== 'object') {
215
+ throw new DecisionConfigError('Options must be provided', 'options');
216
+ }
217
+ const { apiKey, model: configuredModel = 'gpt-6-luna', baseURL, timeoutMs = 30_000, fetch: customFetch } = options;
218
+
219
+ if (typeof apiKey !== 'string' || apiKey.length === 0 || hasControlOrWhitespace(apiKey)) {
220
+ throw new DecisionConfigError(
221
+ 'Invalid apiKey: cannot be blank or contain whitespace or control characters',
222
+ 'apiKey',
223
+ );
224
+ }
225
+
226
+ let baseUrl = DEFAULT_BASE_URL;
227
+ if (baseURL !== undefined) {
228
+ let parsed: URL;
229
+ try {
230
+ parsed = new URL(baseURL);
231
+ } catch {
232
+ throw new DecisionConfigError('Invalid baseURL: must be a valid http(s) URL', 'baseURL');
233
+ }
234
+ if (
235
+ (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') ||
236
+ parsed.username.length > 0 ||
237
+ parsed.password.length > 0 ||
238
+ parsed.search.length > 0 ||
239
+ parsed.hash.length > 0
240
+ ) {
241
+ throw new DecisionConfigError(
242
+ 'Invalid baseURL: must be an http(s) URL without credentials, query or hash',
243
+ 'baseURL',
244
+ );
245
+ }
246
+ baseUrl = baseURL.replace(/\/+$/, '');
247
+ }
248
+
249
+ if (typeof timeoutMs !== 'number' || !Number.isInteger(timeoutMs) || timeoutMs <= 0) {
250
+ throw new DecisionConfigError('Invalid timeoutMs: must be a positive integer', 'timeoutMs');
251
+ }
252
+
253
+ if (configuredModel !== 'gpt-6-luna') {
254
+ throw new DecisionConfigError('Invalid model: must be gpt-6-luna', 'model');
255
+ }
256
+
257
+ const client = new APIClient({
258
+ baseUrl,
259
+ timeout: timeoutMs,
260
+ fetch: customFetch,
261
+ });
262
+
263
+ return {
264
+ name: 'openai-luna',
265
+ async ask({ state, questions, model }) {
266
+ try {
267
+ validateQuestions(questions);
268
+ } catch {
269
+ throw new DecisionRequestError('Invalid decision questions', undefined, undefined);
270
+ }
271
+
272
+ if (model !== undefined && model !== 'gpt-6-luna') {
273
+ throw new DecisionRequestError('Invalid model selector: must be gpt-6-luna', undefined, undefined);
274
+ }
275
+ const resolvedModel: OpenAIDecisionModel = model ?? configuredModel;
276
+
277
+ const questionEntries = Object.entries(questions);
278
+ if (questionEntries.length < 1 || questionEntries.length > MAX_QUESTIONS) {
279
+ throw new DecisionRequestError(
280
+ `Question count must be between 1 and ${MAX_QUESTIONS}, got ${questionEntries.length}`,
281
+ undefined,
282
+ undefined,
283
+ );
284
+ }
285
+
286
+ for (const [name, q] of questionEntries) {
287
+ if (!QUESTION_ID_PATTERN.test(name)) {
288
+ throw new DecisionRequestError(
289
+ 'Question ID does not match pattern ^[A-Za-z0-9_.-]{1,100}$',
290
+ undefined,
291
+ undefined,
292
+ );
293
+ }
294
+ if (q.kind === 'choice') {
295
+ const labelKeys = Object.keys(q.labels);
296
+ if (labelKeys.length < 2 || labelKeys.length > 255) {
297
+ throw new DecisionRequestError(
298
+ `Choice question must have between 2 and 255 choice IDs, got ${labelKeys.length}`,
299
+ undefined,
300
+ undefined,
301
+ );
302
+ }
303
+ for (const labelId of labelKeys) {
304
+ if (labelId.length === 0) {
305
+ throw new DecisionRequestError(
306
+ 'Choice question contains empty choice ID',
307
+ undefined,
308
+ undefined,
309
+ );
310
+ }
311
+ }
312
+ } else if (q.kind === 'score') {
313
+ const levels = q.rubric.length;
314
+ if (levels < 2 || levels > 255) {
315
+ throw new DecisionRequestError(
316
+ `Score question must have between 2 and 255 score levels, got ${levels}`,
317
+ undefined,
318
+ undefined,
319
+ );
320
+ }
321
+ }
322
+ }
323
+
324
+ // `undefined` means "no caller context" exactly as `null` does — the neutral contract
325
+ // has one absent state, so validate it as such rather than rejecting it as unserializable.
326
+ assertJsonSerializable(state ?? null, 'state');
327
+
328
+ const mappedQuestions = Object.fromEntries(
329
+ questionEntries.map(([name, q]) => [name, mapQuestion(name, q)]),
330
+ );
331
+
332
+ const requestBody = {
333
+ model: resolvedModel,
334
+ // The Decisions API requires `input` to be present: the neutral contract's absent
335
+ // state maps to the empty string, exactly like the clef, laya and fm drivers.
336
+ input: state ?? '',
337
+ questions: mappedQuestions,
338
+ };
339
+
340
+ assertJsonSerializable(requestBody, 'request');
341
+
342
+ const bodyString = JSON.stringify(requestBody);
343
+ const bodyBytes = new TextEncoder().encode(bodyString).byteLength;
344
+ if (bodyBytes > MAX_REQUEST_BODY_BYTES) {
345
+ throw new DecisionRequestError('Request body exceeds maximum size of 13 MiB', undefined, undefined);
346
+ }
347
+
348
+ let response: RawHttpResponse;
349
+ try {
350
+ response = await client.rawRequest('POST', '/v1/decisions', bodyString, {
351
+ headers: {
352
+ Authorization: `Bearer ${apiKey}`,
353
+ 'Content-Type': 'application/json',
354
+ },
355
+ redirect: 'manual',
356
+ maxResponseBytes: MAX_RESPONSE_BYTES,
357
+ });
358
+ } catch (error) {
359
+ // The design forbids leaking untrusted transport error text/cause through public
360
+ // errors, so these stay generic: only the message and the timeoutMs field travel.
361
+ if (error instanceof APIError && error.status === 0) {
362
+ throw new DecisionTimeoutError('Request timed out', timeoutMs);
363
+ }
364
+ throw new DecisionConnectionError('Failed to connect to backend');
365
+ }
366
+
367
+ if (response.truncated) {
368
+ throw new DecisionBackendError('Response exceeded maximum allowed size of 8 MiB', response.status);
369
+ }
370
+
371
+ if (response.status >= 300 && response.status < 400) {
372
+ throw new DecisionBackendError(`HTTP ${response.status} redirect received`, response.status);
373
+ }
374
+
375
+ if (response.status === 408) {
376
+ throw new DecisionTimeoutError('HTTP 408 request timeout', response.status);
377
+ }
378
+
379
+ if (response.status === 401 || response.status === 403) {
380
+ throw new DecisionAuthError(`HTTP ${response.status} authentication failure`, response.status);
381
+ }
382
+
383
+ if (response.status === 429) {
384
+ const retryAfterHeader = getHeader(response.headers, 'retry-after');
385
+ const retryAfterMs = parseRetryAfter(retryAfterHeader);
386
+ throw new DecisionRateLimitError('HTTP 429 rate limit exceeded', response.status, retryAfterMs);
387
+ }
388
+
389
+ if (response.status >= 400 && response.status < 500) {
390
+ throw new DecisionRequestError(`HTTP ${response.status} request error`, response.status, undefined);
391
+ }
392
+
393
+ if (response.status >= 500 && response.status < 600) {
394
+ throw new DecisionBackendError(`HTTP ${response.status} backend error`, response.status);
395
+ }
396
+
397
+ if (response.status < 200 || response.status >= 300) {
398
+ throw new DecisionBackendError(`HTTP ${response.status} unexpected status`, response.status);
399
+ }
400
+
401
+ let json: unknown;
402
+ try {
403
+ json = JSON.parse(response.body);
404
+ } catch {
405
+ throw new DecisionBackendError('Malformed JSON response from backend', response.status);
406
+ }
407
+
408
+ if (!isRecord(json)) {
409
+ throw new DecisionBackendError('Malformed response envelope from backend', response.status);
410
+ }
411
+
412
+ // The Decisions API answers either at the top level (`{ answers }`) or wrapped
413
+ // (`{ result: { answers } }`); `answers` itself is a keyed object or an array of
414
+ // named entries. Unknown envelopes fail closed.
415
+ let rawAnswers: unknown;
416
+ if (json.answers !== undefined) {
417
+ rawAnswers = json.answers;
418
+ } else if (isRecord(json.result) && json.result.answers !== undefined) {
419
+ rawAnswers = json.result.answers;
420
+ } else {
421
+ throw new DecisionBackendError('Invalid or missing answers in response', response.status);
422
+ }
423
+
424
+ let rawEntries: [string, unknown][];
425
+ if (Array.isArray(rawAnswers)) {
426
+ rawEntries = rawAnswers.map((entry) => {
427
+ if (!isRecord(entry) || typeof entry.name !== 'string') {
428
+ throw new DecisionBackendError('Invalid answer entry in response', response.status);
429
+ }
430
+ return [entry.name, entry] as [string, unknown];
431
+ });
432
+ } else if (isRecord(rawAnswers)) {
433
+ rawEntries = Object.entries(rawAnswers);
434
+ } else {
435
+ throw new DecisionBackendError('Invalid or missing answers in response', response.status);
436
+ }
437
+
438
+ const answers: Record<string, Answer> = Object.create(null);
439
+ for (const [name, rawAnswer] of rawEntries) {
440
+ if (Object.hasOwn(answers, name)) {
441
+ throw new DecisionBackendError('Duplicate answer entry in response', response.status);
442
+ }
443
+ if (!isRecord(rawAnswer)) {
444
+ throw new DecisionBackendError('Invalid answer in response', response.status);
445
+ }
446
+ switch (rawAnswer.type) {
447
+ case 'choice': {
448
+ const label = rawAnswer.choice ?? rawAnswer.label;
449
+ if (
450
+ typeof label !== 'string' ||
451
+ typeof rawAnswer.confidence !== 'number' ||
452
+ rawAnswer.probabilities === undefined
453
+ ) {
454
+ throw new DecisionBackendError('Malformed choice answer in response', response.status);
455
+ }
456
+ answers[name] = {
457
+ kind: 'choice',
458
+ label,
459
+ confidence: rawAnswer.confidence,
460
+ // Cast: shared validateAnswers re-checks every entry's bounds and mass; this
461
+ // only reshapes the untyped wire record into the neutral answer shape.
462
+ probabilities: normalizeDistribution(rawAnswer.probabilities, response.status) as Record<
463
+ string,
464
+ number
465
+ >,
466
+ };
467
+ break;
468
+ }
469
+ case 'score': {
470
+ if (
471
+ typeof rawAnswer.score !== 'number' ||
472
+ typeof rawAnswer.confidence !== 'number' ||
473
+ rawAnswer.probabilities === undefined
474
+ ) {
475
+ throw new DecisionBackendError('Malformed score answer in response', response.status);
476
+ }
477
+ const rubric =
478
+ questions[name]?.kind === 'score' ? (questions[name] as ScoreQuestion).rubric : undefined;
479
+ const legend =
480
+ rawAnswer.legend !== undefined
481
+ ? (normalizeDistribution(rawAnswer.legend, response.status) as unknown)
482
+ : // Legend omitted on wire: fall back to the request's rubric, indexed
483
+ // 0-based to match the neutral ScoreAnswer key contract.
484
+ Object.fromEntries((rubric ?? []).map((desc, index) => [String(index), desc]));
485
+ if (!isRecord(legend)) {
486
+ throw new DecisionBackendError('Malformed score legend in response', response.status);
487
+ }
488
+ answers[name] = {
489
+ kind: 'score',
490
+ score: rawAnswer.score,
491
+ confidence: rawAnswer.confidence,
492
+ legend: Object.fromEntries(Object.entries(legend)) as Record<number, Desc>,
493
+ probabilities: normalizeDistribution(rawAnswer.probabilities, response.status) as Record<
494
+ number,
495
+ number
496
+ >,
497
+ };
498
+ break;
499
+ }
500
+ case 'noul': {
501
+ // Only the bare probability travels; a wire `confidence` is ignored — the
502
+ // neutral contract refuses to fabricate calibration data.
503
+ const probability = rawAnswer.noul ?? rawAnswer.probability;
504
+ if (typeof probability !== 'number') {
505
+ throw new DecisionBackendError('Malformed noul answer in response', response.status);
506
+ }
507
+ answers[name] = {
508
+ kind: 'noul',
509
+ probability,
510
+ };
511
+ break;
512
+ }
513
+ default:
514
+ throw new DecisionBackendError('Unknown answer type in response', response.status);
515
+ }
516
+ }
517
+
518
+ try {
519
+ validateAnswers(questions, answers);
520
+ } catch {
521
+ throw new DecisionBackendError('Invalid decision answers in response', response.status);
522
+ }
523
+ return answers;
524
+ },
525
+ };
526
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { createOpenAIDecisionDriver, type OpenAIDecisionDriverOptions, type OpenAIDecisionModel } from './driver';
2
+
3
+ export type { OpenAIDecisionDriverOptions, OpenAIDecisionModel };
4
+ export { createOpenAIDecisionDriver };