@cartanova/qgrid-cli 2.21.0 → 2.22.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.
Files changed (86) hide show
  1. package/README.ko.md +5 -4
  2. package/README.md +5 -4
  3. package/bundle/dist/application/monit/monit.frame.js +1 -1
  4. package/bundle/dist/application/qgrid/expired-token-reminder.js +1 -1
  5. package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +2 -2
  6. package/bundle/dist/application/qgrid/qgrid.dispatcher.js +3 -3
  7. package/bundle/dist/application/qgrid/qgrid.frame.js +130 -24
  8. package/bundle/dist/application/qgrid/qgrid.types.js +205 -2
  9. package/bundle/dist/application/qgrid/token-death.js +1 -1
  10. package/bundle/dist/application/qgrid/token-window-keepalive.js +1 -1
  11. package/bundle/dist/application/request-log/request-log.model.js +2 -2
  12. package/bundle/dist/application/sonamu.generated.js +5 -3
  13. package/bundle/dist/i18n/en.js +2 -1
  14. package/bundle/dist/i18n/ko.js +2 -1
  15. package/bundle/dist/i18n/sd.generated.js +3 -2
  16. package/bundle/dist/sonamu.config.js +2 -2
  17. package/bundle/dist/utils/providers/anthropic/anthropic-dispatcher.js +1 -1
  18. package/bundle/dist/utils/providers/common/model-cost.js +15 -2
  19. package/bundle/dist/utils/providers/grok/grok-dispatcher.js +2 -2
  20. package/bundle/dist/utils/providers/openai/openai-backend-protocol.js +6 -2
  21. package/bundle/dist/utils/providers/openai/openai-decisions.js +178 -0
  22. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +61 -677
  23. package/bundle/dist/utils/providers/openai/openai-image-generation.js +1 -1
  24. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +1 -1
  25. package/bundle/dist/utils/providers/openai/openai-refresh.js +2 -2
  26. package/bundle/dist/utils/providers/openai/openai-responses-runtime.js +430 -0
  27. package/bundle/dist/utils/providers/openai/openai-token-pool.js +291 -0
  28. package/bundle/dist/utils/providers/openai/openai-voice-client.js +2 -6
  29. package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +1 -1
  30. package/bundle/src/application/qgrid/qgrid.dispatcher.test.ts +2 -1
  31. package/bundle/src/application/qgrid/qgrid.dispatcher.ts +2 -4
  32. package/bundle/src/application/qgrid/qgrid.frame.test.ts +100 -1
  33. package/bundle/src/application/qgrid/qgrid.frame.ts +146 -7
  34. package/bundle/src/application/qgrid/qgrid.types.ts +242 -0
  35. package/bundle/src/application/request-log/request-log.entity.json +3 -2
  36. package/bundle/src/application/sonamu.generated.http +31 -0
  37. package/bundle/src/application/sonamu.generated.ts +2 -1
  38. package/bundle/src/i18n/en.ts +1 -0
  39. package/bundle/src/i18n/ko.ts +1 -0
  40. package/bundle/src/i18n/sd.generated.ts +2 -1
  41. package/bundle/src/utils/providers/common/model-cost.ts +20 -0
  42. package/bundle/src/utils/providers/openai/openai-backend-protocol.ts +5 -0
  43. package/bundle/src/utils/providers/openai/openai-decisions.test.ts +240 -0
  44. package/bundle/src/utils/providers/openai/openai-decisions.ts +266 -0
  45. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +133 -7
  46. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +90 -1083
  47. package/bundle/src/utils/providers/openai/openai-responses-runtime.ts +677 -0
  48. package/bundle/src/utils/providers/openai/openai-token-pool.ts +481 -0
  49. package/bundle/src/utils/providers/openai/openai-voice-client.ts +0 -5
  50. package/bundle/web-dist/client/assets/{index-NGqKa5_C.js → index-BSjyOyOc.js} +17 -17
  51. package/bundle/web-dist/client/assets/{logs-BLhlxqoB.js → logs-CFyeyR7u.js} +1 -1
  52. package/bundle/web-dist/client/assets/{monit-C3stGFEK.js → monit-N3gBNCXy.js} +1 -1
  53. package/bundle/web-dist/client/assets/{routes-Dgh-_yS5.js → routes-UbYa5WQL.js} +1 -1
  54. package/bundle/web-dist/client/assets/{settings-DiOZwvRj.js → settings-CTZGAJjl.js} +1 -1
  55. package/bundle/web-dist/client/assets/{show-DucEoTrr.js → show-oNGv2jAJ.js} +2 -2
  56. package/bundle/web-dist/client/assets/{tokens-DvCT1bbk.js → tokens-BrhEjJ3t.js} +1 -1
  57. package/bundle/web-dist/client/assets/{use-oauth-login-flow-DazQfaBL.js → use-oauth-login-flow-Ca1Sn84P.js} +1 -1
  58. package/bundle/web-dist/client/assets/{use-update-token-mutation-CfGbUel6.js → use-update-token-mutation-DMy7Pw8U.js} +1 -1
  59. package/bundle/web-dist/client/assets/{voice-zPre2iO8.js → voice-CVXYbgBN.js} +1 -1
  60. package/bundle/web-dist/client/index.html +1 -1
  61. package/bundle/web-dist/server/assets/{TimedPlayer-CcClBzGi.js → TimedPlayer-mpJpP5tQ.js} +1 -1
  62. package/bundle/web-dist/server/assets/{logs-CxAwuDKc.js → logs-CFa_xamY.js} +6 -3
  63. package/bundle/web-dist/server/assets/{monit-Bl2kSkSF.js → monit-BF6osfj5.js} +2 -2
  64. package/bundle/web-dist/server/assets/{plus-CQ8AHpih.js → plus-DwQFfeid.js} +1 -1
  65. package/bundle/web-dist/server/assets/{refresh-cw-pYSuvt4c.js → refresh-cw-Bj-Jxeb6.js} +1 -1
  66. package/bundle/web-dist/server/assets/{request-model-ZulJMbGm.js → request-model-D_iYrudl.js} +1 -1
  67. package/bundle/web-dist/server/assets/{routes-W-pd1Hps.js → routes-B6be8sJP.js} +3 -3
  68. package/bundle/web-dist/server/assets/{services.generated-C3b31_vt.js → services.generated-D0995hJr.js} +14 -2
  69. package/bundle/web-dist/server/assets/{settings-CFdTg1_f.js → settings-DAle7AgI.js} +3 -3
  70. package/bundle/web-dist/server/assets/{show-DVEIHsXh.js → show-BTSdMDoM.js} +4 -4
  71. package/bundle/web-dist/server/assets/{tokens-BO1hyBuB.js → tokens-Bc9flfLz.js} +4 -4
  72. package/bundle/web-dist/server/assets/{use-oauth-login-flow-CCc8LEmn.js → use-oauth-login-flow-C7c0gCjf.js} +1 -1
  73. package/bundle/web-dist/server/assets/{use-update-token-mutation-Ba-sEhq1.js → use-update-token-mutation-DLJDGdxu.js} +1 -1
  74. package/bundle/web-dist/server/assets/{voice-BCF-Pkzo.js → voice-CEQT57xZ.js} +2 -2
  75. package/bundle/web-dist/server/entry-server.generated.js +214 -10
  76. package/package.json +1 -1
  77. package/skills/qgrid/SKILL.md +2 -2
  78. package/skills/qgrid/references/ai-sdk-provider-contract.md +10 -0
  79. package/skills/qgrid/references/cli-env-and-server-boot.md +2 -3
  80. package/skills/qgrid/references/decision-rationale.md +9 -3
  81. package/skills/qgrid/references/openai-codex-runtime.md +9 -2
  82. package/skills/qgrid/references/provider-runtime-differences.md +2 -2
  83. package/skills/qgrid/references/request-log-run-lifecycle.md +5 -3
  84. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  85. package/skills/qgrid/references/token-auth-quota-lifecycle.md +5 -3
  86. package/skills/qgrid/references/verification-and-debugging.md +3 -3
@@ -0,0 +1,240 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+
3
+ import { OpenAIDecisionRequest } from "../../../application/qgrid/qgrid.types";
4
+ import {
5
+ createOpenAIDecision,
6
+ fromOpenAIDecisionResult,
7
+ toOpenAIDecisionRequest,
8
+ } from "./openai-decisions";
9
+
10
+ const credentials = { accessToken: "subscription-token", accountId: "account" };
11
+
12
+ const request = {
13
+ model: "gpt-6-luna" as const,
14
+ input: "An apple is a fruit.",
15
+ questions: [
16
+ {
17
+ type: "choice" as const,
18
+ name: "category",
19
+ instructions: "Classify the object.",
20
+ choices: [{ value: "fruit" }, { value: "vehicle" }],
21
+ },
22
+ ],
23
+ };
24
+
25
+ const answer = {
26
+ model: "gpt-6-luna",
27
+ answers: [
28
+ {
29
+ type: "choice",
30
+ name: "category",
31
+ choice: "fruit",
32
+ probabilities: [
33
+ { value: "fruit", probability: 1 },
34
+ { value: "vehicle", probability: 0 },
35
+ ],
36
+ confidence: 1,
37
+ },
38
+ ],
39
+ usage: {
40
+ input_tokens: 115,
41
+ input_tokens_details: { cached_tokens: 10, cache_write_tokens: 0 },
42
+ output_tokens: 0,
43
+ },
44
+ };
45
+
46
+ describe("createOpenAIDecision", () => {
47
+ it("calls the public endpoint with the OAuth token and returns typed answers", async () => {
48
+ const fetcher = vi.fn(async () => Response.json(answer));
49
+ const result = await createOpenAIDecision(credentials, request, undefined, fetcher);
50
+ const [url, init] = fetcher.mock.calls[0] as unknown as [string, RequestInit];
51
+
52
+ expect(url).toBe("https://api.openai.com/v1/decisions");
53
+ expect(new Headers(init.headers).get("authorization")).toBe("Bearer subscription-token");
54
+ expect(JSON.parse(String(init.body))).toEqual(request);
55
+ expect(result).toEqual(answer);
56
+ });
57
+
58
+ it("rejects requests outside API limits before sending", () => {
59
+ const [question] = request.questions;
60
+
61
+ expect(() =>
62
+ OpenAIDecisionRequest.parse({ ...request, questions: [question, question] }),
63
+ ).toThrow();
64
+ expect(() =>
65
+ OpenAIDecisionRequest.parse({
66
+ ...request,
67
+ questions: [{ ...question, choices: [{ value: "only" }] }],
68
+ }),
69
+ ).toThrow();
70
+ expect(() =>
71
+ OpenAIDecisionRequest.parse({
72
+ ...request,
73
+ questions: [{ ...question, instructions: "" }],
74
+ }),
75
+ ).toThrow("requires instructions");
76
+ });
77
+
78
+ it("maps HTTP errors to OpenAIProtocolError with status for the dispatcher's 401 refresh", async () => {
79
+ const fetcher = vi.fn(async () =>
80
+ Response.json({ error: { message: "Token expired", code: "invalid_token" } }, { status: 401 }),
81
+ );
82
+
83
+ await expect(
84
+ createOpenAIDecision(credentials, request, undefined, fetcher),
85
+ ).rejects.toMatchObject({
86
+ name: "OpenAIProtocolError",
87
+ status: 401,
88
+ code: "invalid_token",
89
+ message: "Token expired",
90
+ });
91
+ expect(fetcher).toHaveBeenCalledTimes(1);
92
+ });
93
+
94
+ it("rejects a response missing an answer", async () => {
95
+ const fetcher = vi.fn(async () => Response.json({ ...answer, answers: [] }));
96
+
97
+ await expect(createOpenAIDecision(credentials, request, undefined, fetcher)).rejects.toThrow(
98
+ "exactly one answer per question",
99
+ );
100
+ });
101
+ });
102
+
103
+ describe("createOpenAIDecision response handling", () => {
104
+ it("accepts a null usage on a served response", async () => {
105
+ const fetcher = vi.fn(async () => Response.json({ ...answer, usage: null }));
106
+ const result = await createOpenAIDecision(credentials, request, undefined, fetcher);
107
+
108
+ expect(result.answers).toHaveLength(1);
109
+ expect(fromOpenAIDecisionResult({ category: { type: "choice", criteria: { fruit: null, vehicle: null } } }, result).usage).toEqual({
110
+ inputTokens: 0,
111
+ outputTokens: 0,
112
+ cachedInputTokens: 0,
113
+ cacheWriteTokens: 0,
114
+ });
115
+ });
116
+
117
+ it("rejects a refusal that names no question as an invalid response", async () => {
118
+ const fetcher = vi.fn(async () =>
119
+ Response.json({ ...answer, answers: [{ type: "refusal", name: null }] }),
120
+ );
121
+
122
+ await expect(createOpenAIDecision(credentials, request, undefined, fetcher)).rejects.toThrow(
123
+ "Invalid OpenAI Decisions response",
124
+ );
125
+ });
126
+
127
+ it("reports a cancel while reading the body as the cancel, not a malformed response", async () => {
128
+ const controller = new AbortController();
129
+ const reason = new Error("caller went away");
130
+
131
+ const fetcher = vi.fn(async () => {
132
+ const body = new ReadableStream<Uint8Array>({
133
+ pull() {
134
+ controller.abort(reason);
135
+ throw reason;
136
+ },
137
+ });
138
+
139
+ return new Response(body, { status: 200 });
140
+ });
141
+
142
+ await expect(
143
+ createOpenAIDecision(credentials, request, controller.signal, fetcher),
144
+ ).rejects.toBe(reason);
145
+ });
146
+
147
+ it("carries Retry-After from a 429 for the caller-facing error", async () => {
148
+ const fetcher = vi.fn(async () =>
149
+ Response.json(
150
+ { error: { message: "Rate limit reached", code: "rate_limit_exceeded" } },
151
+ { status: 429, headers: { "retry-after": "7" } },
152
+ ),
153
+ );
154
+
155
+ await expect(
156
+ createOpenAIDecision(credentials, request, undefined, fetcher),
157
+ ).rejects.toMatchObject({ status: 429, retryAfterMs: 7_000 });
158
+ });
159
+ });
160
+
161
+ describe("qgrid neutral shape <-> OpenAI wire", () => {
162
+ it("maps state parts, question IDs, and criteria as @ai-sdk/openai does", () => {
163
+ const wire = toOpenAIDecisionRequest({
164
+ model: "openai/gpt-6-luna",
165
+ state: [
166
+ { type: "text", text: "ticket" },
167
+ { type: "json", value: { orderId: 7 } },
168
+ { type: "json", value: [1, 2] },
169
+ { type: "image", url: "https://example.com/a.png" },
170
+ ],
171
+ questions: {
172
+ severity: { type: "score", criteria: ["Cosmetic", null] },
173
+ refund: { type: "boolean", criteria: { true: "asks for money back", false: { kind: "other" } } },
174
+ },
175
+ });
176
+
177
+ expect(wire.input).toEqual([
178
+ {
179
+ role: "user",
180
+ content: [
181
+ { type: "input_text", text: "ticket" },
182
+ { type: "input_json", data: { orderId: 7 } },
183
+ { type: "input_text", text: "[1,2]" },
184
+ { type: "input_image", image_url: "https://example.com/a.png" },
185
+ ],
186
+ },
187
+ ]);
188
+ expect(wire.questions).toEqual([
189
+ {
190
+ type: "score",
191
+ name: "severity",
192
+ instructions: "",
193
+ levels: [{ label: "0", description: "Cosmetic" }, { label: "1" }],
194
+ },
195
+ {
196
+ type: "predicate",
197
+ name: "refund",
198
+ instructions: 'Criteria for true:\nasks for money back\n\nCriteria for false:\n{"kind":"other"}',
199
+ },
200
+ ]);
201
+ });
202
+
203
+ it("returns answers keyed by question ID and rejects a mismatched answer type", () => {
204
+ const questions = {
205
+ severity: { type: "score" as const, criteria: ["low", "high"] },
206
+ refund: { type: "boolean" as const, instructions: "Refund?" },
207
+ };
208
+
209
+ const neutral = fromOpenAIDecisionResult(questions, {
210
+ model: "gpt-6-luna",
211
+ answers: [
212
+ {
213
+ type: "score",
214
+ name: "severity",
215
+ score: 0.3,
216
+ probabilities: [
217
+ { value: 0, probability: 0.7 },
218
+ { value: 1, probability: 0.3 },
219
+ ],
220
+ confidence: null,
221
+ },
222
+ { type: "refusal", name: "refund" },
223
+ ],
224
+ });
225
+
226
+ expect(neutral.answers).toEqual({
227
+ severity: { type: "score", score: 0.3, probabilities: { "0": 0.7, "1": 0.3 } },
228
+ refund: { type: "refusal" },
229
+ });
230
+ expect(() =>
231
+ fromOpenAIDecisionResult(questions, {
232
+ model: "gpt-6-luna",
233
+ answers: [
234
+ { type: "predicate", name: "severity", probability: 1 },
235
+ { type: "predicate", name: "refund", probability: 1 },
236
+ ],
237
+ }),
238
+ ).toThrow("answered a score question with predicate");
239
+ });
240
+ });
@@ -0,0 +1,266 @@
1
+ import { z } from "zod";
2
+
3
+ import {
4
+ type DecideInput,
5
+ type DecideOutput,
6
+ type DecisionAnswer,
7
+ type DecisionQuestion,
8
+ OPENAI_DECISION_MODEL,
9
+ type OpenAIDecisionAnswer,
10
+ type OpenAIDecisionQuestion,
11
+ OpenAIDecisionRequest,
12
+ OpenAIDecisionResult,
13
+ } from "../../../application/qgrid/qgrid.types";
14
+ import { OpenAIProtocolError } from "./openai-backend-protocol";
15
+ import { type OpenAIDirectCredentials } from "./openai-direct-client";
16
+
17
+ /**
18
+ * Public API endpoint, not the Codex private backend: it accepts the ChatGPT OAuth access token
19
+ * as a plain Bearer token (live probe 2026-11-13; chatgpt.com/backend-api/codex/decisions is 404).
20
+ */
21
+ export const OPENAI_DECISIONS_URL = "https://api.openai.com/v1/decisions";
22
+
23
+ const DECISIONS_TIMEOUT_MS = 60_000;
24
+
25
+ const errorBody = z.object({
26
+ error: z.object({ message: z.string(), code: z.string().nullish() }),
27
+ });
28
+
29
+ /** `Retry-After` in seconds (the form OpenAI sends); an HTTP date or junk yields undefined. */
30
+ function retryAfterMs(header: string | null): number | undefined {
31
+ const seconds = header === null ? Number.NaN : Number(header);
32
+
33
+ return Number.isFinite(seconds) && seconds > 0 ? Math.ceil(seconds * 1000) : undefined;
34
+ }
35
+
36
+ /** One native Decisions call. Token selection and 401 refresh belong to `OpenAITokenPool.runWithToken`. */
37
+ export async function createOpenAIDecision(
38
+ credentials: OpenAIDirectCredentials,
39
+ input: OpenAIDecisionRequest,
40
+ signal?: AbortSignal,
41
+ fetcher: typeof fetch = fetch,
42
+ ): Promise<OpenAIDecisionResult> {
43
+ const request = OpenAIDecisionRequest.parse(input);
44
+ const timeout = AbortSignal.timeout(DECISIONS_TIMEOUT_MS);
45
+ const active = signal ? AbortSignal.any([signal, timeout]) : timeout;
46
+
47
+ const response = await fetcher(OPENAI_DECISIONS_URL, {
48
+ method: "POST",
49
+ headers: {
50
+ Authorization: `Bearer ${credentials.accessToken}`,
51
+ "Content-Type": "application/json",
52
+ Accept: "application/json",
53
+ },
54
+ body: JSON.stringify(request),
55
+ redirect: "error",
56
+ signal: active,
57
+ });
58
+
59
+ // An unreadable body is a malformed response, but a timeout or cancel while reading is not.
60
+ const data: unknown = await response.json().catch(() => {
61
+ active.throwIfAborted();
62
+
63
+ return undefined;
64
+ });
65
+
66
+ if (!response.ok) {
67
+ const error = errorBody.safeParse(data);
68
+
69
+ throw new OpenAIProtocolError(
70
+ error.success
71
+ ? error.data.error.message
72
+ : `OpenAI Decisions returned HTTP ${response.status}`,
73
+ (error.success ? error.data.error.code : undefined) ?? "decisions_http_error",
74
+ response.status,
75
+ retryAfterMs(response.headers.get("retry-after")),
76
+ );
77
+ }
78
+
79
+ const parsed = OpenAIDecisionResult.safeParse(data);
80
+
81
+ if (!parsed.success) {
82
+ throw new OpenAIProtocolError(
83
+ "Invalid OpenAI Decisions response",
84
+ "decisions_response_invalid",
85
+ );
86
+ }
87
+
88
+ // Refusals carry the question name too, so every question must map to exactly one answer.
89
+ const answered = parsed.data.answers.map((answer) => answer.name);
90
+
91
+ if (
92
+ answered.length !== request.questions.length ||
93
+ request.questions.some((question) => !answered.includes(question.name))
94
+ ) {
95
+ throw new OpenAIProtocolError(
96
+ "OpenAI Decisions must return exactly one answer per question",
97
+ "decisions_response_invalid",
98
+ );
99
+ }
100
+
101
+ return parsed.data;
102
+ }
103
+
104
+ // ---- qgrid neutral shape <-> OpenAI wire ------------------------------------
105
+
106
+ const jsonObject = z.record(z.string(), z.json());
107
+ const jsonObjects = z.array(jsonObject).min(1);
108
+ const plainText = z.string();
109
+
110
+ /** Text content stays as is; JSON content is serialized for OpenAI's text fields. */
111
+ function contentText(content: z.infer<ReturnType<typeof z.json>>): string {
112
+ const text = plainText.safeParse(content);
113
+
114
+ return text.success ? text.data : JSON.stringify(content);
115
+ }
116
+
117
+ function stateParts(state: DecideInput["state"]) {
118
+ return state.map((part) => {
119
+ if (part.type === "text") return { type: "input_text" as const, text: part.text };
120
+
121
+ if (part.type === "image") return { type: "input_image" as const, image_url: part.url };
122
+
123
+ // input_json takes an object or a nonempty array of objects; other JSON goes as text.
124
+ const data = jsonObject.or(jsonObjects).safeParse(part.value);
125
+
126
+ return data.success
127
+ ? { type: "input_json" as const, data: data.data }
128
+ : { type: "input_text" as const, text: JSON.stringify(part.value) };
129
+ });
130
+ }
131
+
132
+ /**
133
+ * Same mapping as @ai-sdk/openai's native decision model (4.0.116). Missing instructions become
134
+ * "" so `OpenAIDecisionRequest` rejects them with 400 instead of OpenAI's error.
135
+ */
136
+ function openaiQuestion(name: string, question: DecisionQuestion): OpenAIDecisionQuestion {
137
+ const instructions = question.instructions == null ? "" : contentText(question.instructions);
138
+
139
+ switch (question.type) {
140
+ case "choice":
141
+ return {
142
+ type: "choice",
143
+ name,
144
+ instructions,
145
+ choices: Object.entries(question.criteria).map(([value, description]) =>
146
+ description == null ? { value } : { value, description: contentText(description) },
147
+ ),
148
+ };
149
+ case "score":
150
+ return {
151
+ type: "score",
152
+ name,
153
+ instructions,
154
+ levels: question.criteria.map((description, index) =>
155
+ description == null
156
+ ? { label: String(index) }
157
+ : { label: String(index), description: contentText(description) },
158
+ ),
159
+ };
160
+ case "boolean": {
161
+ const parts = [
162
+ instructions || undefined,
163
+ question.criteria?.true == null
164
+ ? undefined
165
+ : `Criteria for true:\n${contentText(question.criteria.true)}`,
166
+ question.criteria?.false == null
167
+ ? undefined
168
+ : `Criteria for false:\n${contentText(question.criteria.false)}`,
169
+ ].filter((part) => part !== undefined);
170
+
171
+ return { type: "predicate", name, instructions: parts.join("\n\n") };
172
+ }
173
+ }
174
+ }
175
+
176
+ /** Unvalidated OpenAI request; the caller parses it so limit violations surface as 400. */
177
+ export function toOpenAIDecisionRequest(input: DecideInput): z.input<typeof OpenAIDecisionRequest> {
178
+ return {
179
+ model: OPENAI_DECISION_MODEL,
180
+ input: [{ role: "user", content: stateParts(input.state) }],
181
+ questions: Object.entries(input.questions).map(([name, question]) =>
182
+ openaiQuestion(name, question),
183
+ ),
184
+ prompt_cache_key: input.promptCacheKey,
185
+ safety_identifier: input.safetyIdentifier,
186
+ };
187
+ }
188
+
189
+ /**
190
+ * Validation issues for the converted request, with `questions.<index>` rewritten to the caller's
191
+ * question ID (the neutral request keys questions by ID; OpenAI's wire format is an array).
192
+ */
193
+ export function decisionIssues(error: z.ZodError, questionIds: readonly string[]): string {
194
+ return error.issues
195
+ .map((issue) => {
196
+ const [head, index, ...rest] = issue.path;
197
+
198
+ const id =
199
+ head === "questions" && Number.isInteger(index) ? questionIds[Number(index)] : undefined;
200
+
201
+ const path = id === undefined ? issue.path : [head, id, ...rest];
202
+
203
+ return `${path.join(".") || "input"}: ${issue.message}`;
204
+ })
205
+ .join("; ");
206
+ }
207
+
208
+ function neutralAnswer(question: DecisionQuestion, answer: OpenAIDecisionAnswer): DecisionAnswer {
209
+ if (answer.type === "refusal") return { type: "refusal" };
210
+
211
+ const confidence = answer.type !== "predicate" ? (answer.confidence ?? undefined) : undefined;
212
+
213
+ if (question.type === "choice" && answer.type === "choice") {
214
+ return {
215
+ type: "choice",
216
+ choice: answer.choice,
217
+ probabilities: Object.fromEntries(answer.probabilities.map((p) => [p.value, p.probability])),
218
+ ...(confidence !== undefined && { confidence }),
219
+ };
220
+ }
221
+
222
+ if (question.type === "score" && answer.type === "score") {
223
+ return {
224
+ type: "score",
225
+ score: answer.score,
226
+ probabilities: Object.fromEntries(
227
+ answer.probabilities.map((p) => [String(p.value), p.probability]),
228
+ ),
229
+ ...(confidence !== undefined && { confidence }),
230
+ };
231
+ }
232
+
233
+ if (question.type === "boolean" && answer.type === "predicate") {
234
+ return { type: "boolean", probability: answer.probability };
235
+ }
236
+
237
+ throw new OpenAIProtocolError(
238
+ `OpenAI Decisions answered a ${question.type} question with ${answer.type}`,
239
+ "decisions_response_invalid",
240
+ );
241
+ }
242
+
243
+ /** Answers keyed by question ID. `createOpenAIDecision` already checked one answer per question. */
244
+ export function fromOpenAIDecisionResult(
245
+ questions: DecideInput["questions"],
246
+ result: OpenAIDecisionResult,
247
+ ): Pick<DecideOutput, "answers" | "usage"> {
248
+ const byName = new Map(result.answers.map((answer) => [answer.name, answer]));
249
+
250
+ const answers = Object.fromEntries(
251
+ Object.entries(questions).map(([id, question]) => [
252
+ id,
253
+ neutralAnswer(question, byName.get(id)!),
254
+ ]),
255
+ );
256
+
257
+ return {
258
+ answers,
259
+ usage: {
260
+ inputTokens: result.usage?.input_tokens ?? 0,
261
+ outputTokens: result.usage?.output_tokens ?? 0,
262
+ cachedInputTokens: result.usage?.input_tokens_details?.cached_tokens ?? 0,
263
+ cacheWriteTokens: result.usage?.input_tokens_details?.cache_write_tokens ?? 0,
264
+ },
265
+ };
266
+ }