@namzu/openai 1.0.2 → 1.0.3

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/CHANGELOG.md CHANGED
@@ -1,5 +1,35 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 3fd2524: Normalize request-start and mid-stream failures across all seven provider
8
+ drivers with the new public `ProviderRequestError` taxonomy. Errors expose
9
+ `kind` (`throttle`, `network`, `auth`, `context_overflow`, `bad_request`, or
10
+ `server`), `providerId`, and optional `status` / `retryAfterMs`, with
11
+ `isProviderRequestError` available for structural narrowing across package
12
+ copies.
13
+
14
+ Provider error messages and metadata deliberately omit vendor response bodies,
15
+ URLs, messages, and causes because upstream errors can echo credentials. HTTP
16
+ dialect-mismatch diagnostics now keep only the endpoint origin and status.
17
+ Caller-owned aborts remain unchanged instead of being reclassified.
18
+
19
+ The runtime preserves the classified error through streaming and publishes its
20
+ safe metadata as `Run.lastProviderError` and
21
+ `run_failed.providerError`. Bedrock stream-exception events and provider
22
+ iterator/SSE failures no longer appear as clean end-of-stream.
23
+
24
+ `retryAfterMs` is metadata only; this change does not add retries or alter vendor
25
+ SDK retry settings. Provider packages now require `@namzu/sdk >=1.3.0`, the
26
+ first SDK release containing these runtime helpers and types.
27
+
28
+ Ollama now maps `done_reason: "length"` truthfully so runtime continuation can
29
+ run. LM Studio treats content-free `contextLengthReached` as context overflow,
30
+ while preserving `"length"` after partial content, and creates its WebSocket
31
+ client lazily on first use.
32
+
3
33
  ## 1.0.2
4
34
 
5
35
  ### Patch Changes
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Provider error taxonomy — OpenAI driver.
3
+ *
4
+ * Like the Anthropic driver, this one lets the vendor SDK's own error type
5
+ * escape verbatim (`RateLimitError`, `BadRequestError`, …). Those carry a
6
+ * status but are vendor classes, so no caller can classify them without
7
+ * importing `openai` — and their `message` interpolates the response body.
8
+ *
9
+ * Transport seam: `OpenAIConfig.baseURL` — a loopback server answering
10
+ * with a scripted status/headers/body, so the REAL vendor client runs
11
+ * (including its internal retries, which this group must not disturb).
12
+ */
13
+ export {};
14
+ //# sourceMappingURL=error-taxonomy.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-taxonomy.test.d.ts","sourceRoot":"","sources":["../../src/__tests__/error-taxonomy.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG"}
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Provider error taxonomy — OpenAI driver.
3
+ *
4
+ * Like the Anthropic driver, this one lets the vendor SDK's own error type
5
+ * escape verbatim (`RateLimitError`, `BadRequestError`, …). Those carry a
6
+ * status but are vendor classes, so no caller can classify them without
7
+ * importing `openai` — and their `message` interpolates the response body.
8
+ *
9
+ * Transport seam: `OpenAIConfig.baseURL` — a loopback server answering
10
+ * with a scripted status/headers/body, so the REAL vendor client runs
11
+ * (including its internal retries, which this group must not disturb).
12
+ */
13
+ import { createServer } from 'node:http';
14
+ import { afterEach, describe, expect, it } from 'vitest';
15
+ import { OpenAIProvider } from '../client.js';
16
+ /** Obviously fake, non-functional token — present only as a leak probe. */
17
+ const FAKE_CREDENTIAL = 'sk-ant-FAKE-DO-NOT-USE-0000';
18
+ let server;
19
+ afterEach(async () => {
20
+ if (server) {
21
+ await new Promise((resolve) => server?.close(() => resolve()));
22
+ server = undefined;
23
+ }
24
+ });
25
+ async function startEndpoint(reply) {
26
+ server = createServer((_req, res) => {
27
+ res.writeHead(reply.status, {
28
+ 'Content-Type': 'application/json',
29
+ ...(reply.headers ?? {}),
30
+ });
31
+ res.end(reply.body);
32
+ });
33
+ await new Promise((resolve) => server?.listen(0, '127.0.0.1', () => resolve()));
34
+ const { port } = server.address();
35
+ return `http://127.0.0.1:${port}/v1`;
36
+ }
37
+ async function captureChatStreamError(reply) {
38
+ const baseURL = await startEndpoint(reply);
39
+ // maxRetries is deliberately NOT set: this group classifies errors and
40
+ // must leave the vendor SDK's own retry behaviour exactly as it is.
41
+ const provider = new OpenAIProvider({
42
+ apiKey: 'test-key',
43
+ model: 'gpt-4o-mini',
44
+ baseURL,
45
+ });
46
+ try {
47
+ for await (const _chunk of provider.chatStream({
48
+ model: 'gpt-4o-mini',
49
+ messages: [{ role: 'user', content: 'hi' }],
50
+ })) {
51
+ // drain
52
+ }
53
+ }
54
+ catch (err) {
55
+ return err;
56
+ }
57
+ throw new Error('expected chatStream to throw');
58
+ }
59
+ async function captureProviderError(provider, signal) {
60
+ try {
61
+ for await (const _chunk of provider.chatStream({
62
+ model: 'gpt-4o-mini',
63
+ messages: [{ role: 'user', content: 'hi' }],
64
+ signal,
65
+ })) {
66
+ // drain
67
+ }
68
+ }
69
+ catch (err) {
70
+ return err;
71
+ }
72
+ throw new Error('expected chatStream to throw');
73
+ }
74
+ describe('@namzu/openai — provider error taxonomy', () => {
75
+ it('(a) 429 with `retry-after: 2` throws a throttle-classified error carrying retryAfterMs', async () => {
76
+ const err = await captureChatStreamError({
77
+ status: 429,
78
+ headers: { 'retry-after': '2' },
79
+ body: JSON.stringify({
80
+ error: { message: 'Rate limit reached', type: 'rate_limit_error' },
81
+ }),
82
+ });
83
+ expect(err).toMatchObject({
84
+ name: 'ProviderRequestError',
85
+ kind: 'throttle',
86
+ status: 429,
87
+ retryAfterMs: 2000,
88
+ providerId: 'openai',
89
+ });
90
+ }, 60_000);
91
+ it("(c) 400 whose body reports a context-length overflow classifies as 'context_overflow'", async () => {
92
+ const err = await captureChatStreamError({
93
+ status: 400,
94
+ body: JSON.stringify({
95
+ error: {
96
+ message: "This model's maximum context length is 128000 tokens. However, your messages resulted in 190210 tokens.",
97
+ type: 'invalid_request_error',
98
+ code: 'context_length_exceeded',
99
+ },
100
+ }),
101
+ });
102
+ expect(err).toMatchObject({
103
+ name: 'ProviderRequestError',
104
+ kind: 'context_overflow',
105
+ status: 400,
106
+ providerId: 'openai',
107
+ });
108
+ }, 30_000);
109
+ it("(c) 400 that is not an overflow classifies as 'bad_request'", async () => {
110
+ const err = await captureChatStreamError({
111
+ status: 400,
112
+ body: JSON.stringify({
113
+ error: {
114
+ message: "Unrecognized request argument: 'temperture'",
115
+ type: 'invalid_request_error',
116
+ },
117
+ }),
118
+ });
119
+ expect(err).toMatchObject({
120
+ name: 'ProviderRequestError',
121
+ kind: 'bad_request',
122
+ status: 400,
123
+ providerId: 'openai',
124
+ });
125
+ }, 30_000);
126
+ it("(auth) 401 classifies as 'auth'", async () => {
127
+ const err = await captureChatStreamError({
128
+ status: 401,
129
+ body: JSON.stringify({
130
+ error: {
131
+ message: 'Incorrect API key provided',
132
+ type: 'invalid_request_error',
133
+ },
134
+ }),
135
+ });
136
+ expect(err).toMatchObject({
137
+ name: 'ProviderRequestError',
138
+ kind: 'auth',
139
+ status: 401,
140
+ providerId: 'openai',
141
+ });
142
+ }, 30_000);
143
+ it('(d) SECURITY: a credential echoed back in a 401 body never reaches the thrown message', async () => {
144
+ const err = await captureChatStreamError({
145
+ status: 401,
146
+ body: JSON.stringify({
147
+ error: { message: `Incorrect API key provided: ${FAKE_CREDENTIAL}` },
148
+ }),
149
+ });
150
+ expect(err.message).not.toContain(FAKE_CREDENTIAL);
151
+ expect(JSON.stringify(err)).not.toContain(FAKE_CREDENTIAL);
152
+ expect('cause' in err).toBe(false);
153
+ }, 30_000);
154
+ it('classifies and sanitizes an SDK failure thrown after streaming began', async () => {
155
+ const vendor = Object.assign(new Error(`overloaded_error ${FAKE_CREDENTIAL}`), {
156
+ name: 'APIError',
157
+ });
158
+ const provider = new OpenAIProvider({
159
+ apiKey: 'test-key',
160
+ model: 'gpt-4o-mini',
161
+ });
162
+ const stream = {
163
+ async *[Symbol.asyncIterator]() {
164
+ yield {
165
+ id: 'chatcmpl-1',
166
+ choices: [{ delta: { content: 'partial' }, finish_reason: null }],
167
+ usage: null,
168
+ };
169
+ throw vendor;
170
+ },
171
+ };
172
+ provider.client = {
173
+ chat: { completions: { create: async () => stream } },
174
+ };
175
+ const err = await captureProviderError(provider);
176
+ expect(err).toMatchObject({
177
+ name: 'ProviderRequestError',
178
+ kind: 'server',
179
+ providerId: 'openai',
180
+ });
181
+ expect(err.message).not.toContain(FAKE_CREDENTIAL);
182
+ expect('cause' in err).toBe(false);
183
+ });
184
+ it('preserves the caller abort reason when the SDK replaces the error object', async () => {
185
+ const controller = new AbortController();
186
+ const reason = new Error('user stopped');
187
+ const sdkAbort = Object.assign(new Error('request aborted'), {
188
+ name: 'APIUserAbortError',
189
+ });
190
+ controller.abort(reason);
191
+ const provider = new OpenAIProvider({
192
+ apiKey: 'test-key',
193
+ model: 'gpt-4o-mini',
194
+ });
195
+ provider.client = {
196
+ chat: { completions: { create: async () => Promise.reject(sdkAbort) } },
197
+ };
198
+ const err = await captureProviderError(provider, controller.signal);
199
+ expect(sdkAbort).not.toBe(reason);
200
+ expect(err).toBe(reason);
201
+ });
202
+ });
203
+ //# sourceMappingURL=error-taxonomy.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-taxonomy.test.js","sourceRoot":"","sources":["../../src/__tests__/error-taxonomy.test.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAe,YAAY,EAAE,MAAM,WAAW,CAAA;AAErD,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAA;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAE7C,2EAA2E;AAC3E,MAAM,eAAe,GAAG,6BAA6B,CAAA;AAQrD,IAAI,MAA0B,CAAA;AAE9B,SAAS,CAAC,KAAK,IAAI,EAAE;IACpB,IAAI,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;QACpE,MAAM,GAAG,SAAS,CAAA;IACnB,CAAC;AACF,CAAC,CAAC,CAAA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AAQ,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;QACjC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;IACzB,CAAC,CAAC,CAAA;AACH,CAAC,CAAC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,oBAAoB,EAEpB,WAAW,EACX,SAAS,EACT,oBAAoB,EACpB,WAAW,EAGX,MAAM,YAAY,CAAA;AAEnB,OAAO,KAAK,EAEX,0BAA0B,EAG1B,MAAM,mCAAmC,CAAA;AAC1C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE9C;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,EAAE,oBAKjC,CAAA;AAyDD,wBAAgB,gBAAgB,CAC/B,QAAQ,EAAE,oBAAoB,CAAC,UAAU,CAAC,GACxC,0BAA0B,EAAE,CAiD9B;AAcD,qBAAa,cAAe,YAAW,WAAW;IACjD,QAAQ,CAAC,EAAE,YAAW;IACtB,QAAQ,CAAC,IAAI,YAAW;IACxB,QAAQ,CAAC,YAAY,uBAAsB;IAE3C,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,YAAY,CAAC,CAAQ;gBAEjB,MAAM,EAAE,YAAY;IAkBhC,OAAO,CAAC,YAAY;IAUb,UAAU,CAAC,MAAM,EAAE,oBAAoB,GAAG,aAAa,CAAC,WAAW,CAAC;IAyErE,UAAU,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAclC,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAQrC"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,oBAAoB,EAEpB,WAAW,EACX,SAAS,EACT,oBAAoB,EACpB,WAAW,EAGX,MAAM,YAAY,CAAA;AAQnB,OAAO,KAAK,EAEX,0BAA0B,EAG1B,MAAM,mCAAmC,CAAA;AAC1C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAE9C;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,EAAE,oBAKjC,CAAA;AAyDD,wBAAgB,gBAAgB,CAC/B,QAAQ,EAAE,oBAAoB,CAAC,UAAU,CAAC,GACxC,0BAA0B,EAAE,CAiD9B;AAcD,qBAAa,cAAe,YAAW,WAAW;IACjD,QAAQ,CAAC,EAAE,YAAW;IACtB,QAAQ,CAAC,IAAI,YAAW;IACxB,QAAQ,CAAC,YAAY,uBAAsB;IAE3C,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,YAAY,CAAC,CAAQ;gBAEjB,MAAM,EAAE,YAAY;IAkBhC,OAAO,CAAC,YAAY;IAUb,UAAU,CAAC,MAAM,EAAE,oBAAoB,GAAG,aAAa,CAAC,WAAW,CAAC;IA4FrE,UAAU,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAclC,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAQrC"}
package/dist/client.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { ProviderRequestError, isCallerAbortError, isProviderRequestError, providerVendorError, } from '@namzu/sdk';
1
2
  import OpenAI from 'openai';
2
3
  /**
3
4
  * Full capability set — this driver maps tools (`toOpenAITools`), streams
@@ -151,68 +152,94 @@ export class OpenAIProvider {
151
152
  }
152
153
  async *chatStream(params) {
153
154
  const model = this.resolveModel(params);
154
- const stream = await this.client.chat.completions.create({
155
- model,
156
- messages: toOpenAIMessages(params.messages),
157
- stream: true,
158
- stream_options: { include_usage: true },
159
- tools: toOpenAITools(params),
160
- tool_choice: formatToolChoice(params.toolChoice),
161
- parallel_tool_calls: params.parallelToolCalls,
162
- temperature: params.temperature,
163
- max_tokens: params.maxTokens,
164
- top_p: params.topP,
165
- frequency_penalty: params.frequencyPenalty,
166
- presence_penalty: params.presencePenalty,
167
- stop: params.stop,
168
- response_format: params.responseFormat,
169
- },
170
- // Per-request abort: a Stop tears the in-flight SSE request down.
171
- { signal: params.signal });
172
- for await (const chunk of stream) {
173
- // Stop pulling promptly on abort; `for await` calls the stream's
174
- // `.return()` on this throw, releasing the connection.
175
- params.signal?.throwIfAborted();
176
- try {
177
- const choice = chunk.choices[0];
178
- const delta = choice?.delta;
179
- const toolCalls = delta?.tool_calls?.map((tc) => ({
180
- index: tc.index,
181
- id: tc.id,
182
- type: tc.type,
183
- function: tc.function
184
- ? {
185
- name: tc.function.name,
186
- arguments: tc.function.arguments,
187
- }
188
- : undefined,
189
- }));
190
- const hasDelta = (delta?.content !== undefined && delta.content !== null) ||
191
- (toolCalls && toolCalls.length > 0);
192
- const finishReason = choice?.finish_reason
193
- ? mapFinishReason(choice.finish_reason)
194
- : undefined;
195
- const usage = chunk.usage ? parseUsage(chunk.usage) : undefined;
196
- if (!hasDelta && !finishReason && !usage)
197
- continue;
198
- yield {
199
- id: chunk.id,
200
- delta: {
201
- content: delta?.content ?? undefined,
202
- toolCalls,
203
- },
204
- finishReason,
205
- usage,
206
- };
207
- }
208
- catch (parseErr) {
209
- yield {
210
- id: chunk.id ?? '',
211
- delta: {},
212
- error: `Stream parse error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
213
- };
155
+ let stream;
156
+ try {
157
+ stream = await this.client.chat.completions.create({
158
+ model,
159
+ messages: toOpenAIMessages(params.messages),
160
+ stream: true,
161
+ stream_options: { include_usage: true },
162
+ tools: toOpenAITools(params),
163
+ tool_choice: formatToolChoice(params.toolChoice),
164
+ parallel_tool_calls: params.parallelToolCalls,
165
+ temperature: params.temperature,
166
+ max_tokens: params.maxTokens,
167
+ top_p: params.topP,
168
+ frequency_penalty: params.frequencyPenalty,
169
+ presence_penalty: params.presencePenalty,
170
+ stop: params.stop,
171
+ response_format: params.responseFormat,
172
+ },
173
+ // Per-request abort: a Stop tears the in-flight SSE request down.
174
+ { signal: params.signal });
175
+ }
176
+ catch (err) {
177
+ // The vendor SDK builds its error message FROM the response body, so a
178
+ // credential the upstream echoed back is already inside `err.message`
179
+ // before this code runs (proven with a planted fake token). Classify from
180
+ // the status and drop the vendor error entirely — no re-throw, no
181
+ // `cause`, because a `cause` is exactly what a structured logger walks.
182
+ if (isCallerAbortError(err, params.signal))
183
+ throw params.signal?.reason ?? err;
184
+ if (isProviderRequestError(err))
185
+ throw err;
186
+ throw providerVendorError({ providerId: 'openai', error: err });
187
+ }
188
+ try {
189
+ for await (const chunk of stream) {
190
+ // Stop pulling promptly on abort; `for await` calls the stream's
191
+ // `.return()` on this throw, releasing the connection.
192
+ params.signal?.throwIfAborted();
193
+ try {
194
+ const choice = chunk.choices[0];
195
+ const delta = choice?.delta;
196
+ const toolCalls = delta?.tool_calls?.map((tc) => ({
197
+ index: tc.index,
198
+ id: tc.id,
199
+ type: tc.type,
200
+ function: tc.function
201
+ ? {
202
+ name: tc.function.name,
203
+ arguments: tc.function.arguments,
204
+ }
205
+ : undefined,
206
+ }));
207
+ const hasDelta = (delta?.content !== undefined && delta.content !== null) ||
208
+ (toolCalls && toolCalls.length > 0);
209
+ const finishReason = choice?.finish_reason
210
+ ? mapFinishReason(choice.finish_reason)
211
+ : undefined;
212
+ const usage = chunk.usage ? parseUsage(chunk.usage) : undefined;
213
+ if (!hasDelta && !finishReason && !usage)
214
+ continue;
215
+ yield {
216
+ id: chunk.id,
217
+ delta: {
218
+ content: delta?.content ?? undefined,
219
+ toolCalls,
220
+ },
221
+ finishReason,
222
+ usage,
223
+ };
224
+ }
225
+ catch (parseErr) {
226
+ if (isProviderRequestError(parseErr))
227
+ throw parseErr;
228
+ throw new ProviderRequestError({
229
+ kind: 'server',
230
+ providerId: 'openai',
231
+ detail: 'the provider stream returned malformed data',
232
+ });
233
+ }
214
234
  }
215
235
  }
236
+ catch (err) {
237
+ if (isCallerAbortError(err, params.signal))
238
+ throw params.signal?.reason ?? err;
239
+ if (isProviderRequestError(err))
240
+ throw err;
241
+ throw providerVendorError({ providerId: 'openai', error: err });
242
+ }
216
243
  }
217
244
  async listModels() {
218
245
  const page = await this.client.models.list();
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAUA,OAAO,MAAM,MAAM,QAAQ,CAAA;AAS3B;;;;GAIG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAyB;IACxD,aAAa,EAAE,IAAI;IACnB,iBAAiB,EAAE,IAAI;IACvB,uBAAuB,EAAE,IAAI;IAC7B,cAAc,EAAE,IAAI;CACpB,CAAA;AAMD,SAAS,eAAe,CAAC,MAA6C;IACrE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,QAAQ;YACZ,OAAO,QAAQ,CAAA;QAChB,KAAK,YAAY,CAAC;QAClB,KAAK,eAAe;YACnB,OAAO,YAAY,CAAA;QACpB,KAAK,gBAAgB;YACpB,OAAO,gBAAgB,CAAA;QACxB;YACC,OAAO,MAAM,CAAA;IACf,CAAC;AACF,CAAC;AASD,SAAS,UAAU,CAAC,GAA2B;IAC9C,IAAI,CAAC,GAAG,EAAE,CAAC;QACV,OAAO;YACN,YAAY,EAAE,CAAC;YACf,gBAAgB,EAAE,CAAC;YACnB,WAAW,EAAE,CAAC;YACd,YAAY,EAAE,CAAC;YACf,gBAAgB,EAAE,CAAC;SACnB,CAAA;IACF,CAAC;IACD,MAAM,YAAY,GAAG,GAAG,CAAC,aAAa,IAAI,CAAC,CAAA;IAC3C,MAAM,gBAAgB,GAAG,GAAG,CAAC,iBAAiB,IAAI,CAAC,CAAA;IACnD,OAAO;QACN,YAAY;QACZ,gBAAgB;QAChB,WAAW,EAAE,GAAG,CAAC,YAAY,IAAI,YAAY,GAAG,gBAAgB;QAChE,YAAY,EAAE,GAAG,CAAC,qBAAqB,EAAE,aAAa,IAAI,CAAC;QAC3D,gBAAgB,EAAE,CAAC;KACnB,CAAA;AACF,CAAC;AAED,SAAS,gBAAgB,CAAC,EAA0B;IACnD,IAAI,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YACd,eAAe,EAAE,IAAI;YACrB,iBAAiB,EAAE,IAAI;SACvB,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,KAAK,CAAC,WAAW;QAChB,IAAI,CAAC;YACJ,MAAM,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAA;YAC/B,OAAO,IAAI,CAAA;QACZ,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,KAAK,CAAA;QACb,CAAC;IACF,CAAC;CACD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@namzu/openai",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "OpenAI LLM provider for @namzu/sdk via the official `openai` npm SDK. Chat Completions API with streaming + tool-use.",
5
5
  "license": "FSL-1.1-MIT",
6
6
  "type": "module",
@@ -37,14 +37,14 @@
37
37
  "openai": "^6.0.0"
38
38
  },
39
39
  "peerDependencies": {
40
- "@namzu/sdk": ">=1.0.0"
40
+ "@namzu/sdk": ">=1.3.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@biomejs/biome": "^1.9.4",
44
44
  "@types/node": "^22.19.17",
45
45
  "typescript": "^5.5.0",
46
46
  "vitest": "^2.0.0",
47
- "@namzu/sdk": "^1.2.0"
47
+ "@namzu/sdk": "^1.4.0"
48
48
  },
49
49
  "scripts": {
50
50
  "build": "tsc --build",
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Provider error taxonomy — OpenAI driver.
3
+ *
4
+ * Like the Anthropic driver, this one lets the vendor SDK's own error type
5
+ * escape verbatim (`RateLimitError`, `BadRequestError`, …). Those carry a
6
+ * status but are vendor classes, so no caller can classify them without
7
+ * importing `openai` — and their `message` interpolates the response body.
8
+ *
9
+ * Transport seam: `OpenAIConfig.baseURL` — a loopback server answering
10
+ * with a scripted status/headers/body, so the REAL vendor client runs
11
+ * (including its internal retries, which this group must not disturb).
12
+ */
13
+
14
+ import { type Server, createServer } from 'node:http'
15
+ import type { AddressInfo } from 'node:net'
16
+ import { afterEach, describe, expect, it } from 'vitest'
17
+ import { OpenAIProvider } from '../client.js'
18
+
19
+ /** Obviously fake, non-functional token — present only as a leak probe. */
20
+ const FAKE_CREDENTIAL = 'sk-ant-FAKE-DO-NOT-USE-0000'
21
+
22
+ interface ScriptedReply {
23
+ status: number
24
+ body: string
25
+ headers?: Record<string, string>
26
+ }
27
+
28
+ let server: Server | undefined
29
+
30
+ afterEach(async () => {
31
+ if (server) {
32
+ await new Promise<void>((resolve) => server?.close(() => resolve()))
33
+ server = undefined
34
+ }
35
+ })
36
+
37
+ async function startEndpoint(reply: ScriptedReply): Promise<string> {
38
+ server = createServer((_req, res) => {
39
+ res.writeHead(reply.status, {
40
+ 'Content-Type': 'application/json',
41
+ ...(reply.headers ?? {}),
42
+ })
43
+ res.end(reply.body)
44
+ })
45
+ await new Promise<void>((resolve) => server?.listen(0, '127.0.0.1', () => resolve()))
46
+ const { port } = server.address() as AddressInfo
47
+ return `http://127.0.0.1:${port}/v1`
48
+ }
49
+
50
+ async function captureChatStreamError(reply: ScriptedReply): Promise<unknown> {
51
+ const baseURL = await startEndpoint(reply)
52
+ // maxRetries is deliberately NOT set: this group classifies errors and
53
+ // must leave the vendor SDK's own retry behaviour exactly as it is.
54
+ const provider = new OpenAIProvider({
55
+ apiKey: 'test-key',
56
+ model: 'gpt-4o-mini',
57
+ baseURL,
58
+ })
59
+ try {
60
+ for await (const _chunk of provider.chatStream({
61
+ model: 'gpt-4o-mini',
62
+ messages: [{ role: 'user', content: 'hi' }],
63
+ })) {
64
+ // drain
65
+ }
66
+ } catch (err) {
67
+ return err
68
+ }
69
+ throw new Error('expected chatStream to throw')
70
+ }
71
+
72
+ async function captureProviderError(
73
+ provider: OpenAIProvider,
74
+ signal?: AbortSignal,
75
+ ): Promise<unknown> {
76
+ try {
77
+ for await (const _chunk of provider.chatStream({
78
+ model: 'gpt-4o-mini',
79
+ messages: [{ role: 'user', content: 'hi' }],
80
+ signal,
81
+ })) {
82
+ // drain
83
+ }
84
+ } catch (err) {
85
+ return err
86
+ }
87
+ throw new Error('expected chatStream to throw')
88
+ }
89
+
90
+ describe('@namzu/openai — provider error taxonomy', () => {
91
+ it('(a) 429 with `retry-after: 2` throws a throttle-classified error carrying retryAfterMs', async () => {
92
+ const err = await captureChatStreamError({
93
+ status: 429,
94
+ headers: { 'retry-after': '2' },
95
+ body: JSON.stringify({
96
+ error: { message: 'Rate limit reached', type: 'rate_limit_error' },
97
+ }),
98
+ })
99
+
100
+ expect(err).toMatchObject({
101
+ name: 'ProviderRequestError',
102
+ kind: 'throttle',
103
+ status: 429,
104
+ retryAfterMs: 2000,
105
+ providerId: 'openai',
106
+ })
107
+ }, 60_000)
108
+
109
+ it("(c) 400 whose body reports a context-length overflow classifies as 'context_overflow'", async () => {
110
+ const err = await captureChatStreamError({
111
+ status: 400,
112
+ body: JSON.stringify({
113
+ error: {
114
+ message:
115
+ "This model's maximum context length is 128000 tokens. However, your messages resulted in 190210 tokens.",
116
+ type: 'invalid_request_error',
117
+ code: 'context_length_exceeded',
118
+ },
119
+ }),
120
+ })
121
+
122
+ expect(err).toMatchObject({
123
+ name: 'ProviderRequestError',
124
+ kind: 'context_overflow',
125
+ status: 400,
126
+ providerId: 'openai',
127
+ })
128
+ }, 30_000)
129
+
130
+ it("(c) 400 that is not an overflow classifies as 'bad_request'", async () => {
131
+ const err = await captureChatStreamError({
132
+ status: 400,
133
+ body: JSON.stringify({
134
+ error: {
135
+ message: "Unrecognized request argument: 'temperture'",
136
+ type: 'invalid_request_error',
137
+ },
138
+ }),
139
+ })
140
+
141
+ expect(err).toMatchObject({
142
+ name: 'ProviderRequestError',
143
+ kind: 'bad_request',
144
+ status: 400,
145
+ providerId: 'openai',
146
+ })
147
+ }, 30_000)
148
+
149
+ it("(auth) 401 classifies as 'auth'", async () => {
150
+ const err = await captureChatStreamError({
151
+ status: 401,
152
+ body: JSON.stringify({
153
+ error: {
154
+ message: 'Incorrect API key provided',
155
+ type: 'invalid_request_error',
156
+ },
157
+ }),
158
+ })
159
+
160
+ expect(err).toMatchObject({
161
+ name: 'ProviderRequestError',
162
+ kind: 'auth',
163
+ status: 401,
164
+ providerId: 'openai',
165
+ })
166
+ }, 30_000)
167
+
168
+ it('(d) SECURITY: a credential echoed back in a 401 body never reaches the thrown message', async () => {
169
+ const err = await captureChatStreamError({
170
+ status: 401,
171
+ body: JSON.stringify({
172
+ error: { message: `Incorrect API key provided: ${FAKE_CREDENTIAL}` },
173
+ }),
174
+ })
175
+
176
+ expect((err as Error).message).not.toContain(FAKE_CREDENTIAL)
177
+ expect(JSON.stringify(err)).not.toContain(FAKE_CREDENTIAL)
178
+ expect('cause' in (err as object)).toBe(false)
179
+ }, 30_000)
180
+
181
+ it('classifies and sanitizes an SDK failure thrown after streaming began', async () => {
182
+ const vendor = Object.assign(new Error(`overloaded_error ${FAKE_CREDENTIAL}`), {
183
+ name: 'APIError',
184
+ })
185
+ const provider = new OpenAIProvider({
186
+ apiKey: 'test-key',
187
+ model: 'gpt-4o-mini',
188
+ })
189
+ const stream = {
190
+ async *[Symbol.asyncIterator]() {
191
+ yield {
192
+ id: 'chatcmpl-1',
193
+ choices: [{ delta: { content: 'partial' }, finish_reason: null }],
194
+ usage: null,
195
+ }
196
+ throw vendor
197
+ },
198
+ }
199
+ ;(provider as unknown as { client: unknown }).client = {
200
+ chat: { completions: { create: async () => stream } },
201
+ }
202
+
203
+ const err = await captureProviderError(provider)
204
+
205
+ expect(err).toMatchObject({
206
+ name: 'ProviderRequestError',
207
+ kind: 'server',
208
+ providerId: 'openai',
209
+ })
210
+ expect((err as Error).message).not.toContain(FAKE_CREDENTIAL)
211
+ expect('cause' in (err as object)).toBe(false)
212
+ })
213
+
214
+ it('preserves the caller abort reason when the SDK replaces the error object', async () => {
215
+ const controller = new AbortController()
216
+ const reason = new Error('user stopped')
217
+ const sdkAbort = Object.assign(new Error('request aborted'), {
218
+ name: 'APIUserAbortError',
219
+ })
220
+ controller.abort(reason)
221
+ const provider = new OpenAIProvider({
222
+ apiKey: 'test-key',
223
+ model: 'gpt-4o-mini',
224
+ })
225
+ ;(provider as unknown as { client: unknown }).client = {
226
+ chat: { completions: { create: async () => Promise.reject(sdkAbort) } },
227
+ }
228
+
229
+ const err = await captureProviderError(provider, controller.signal)
230
+
231
+ expect(sdkAbort).not.toBe(reason)
232
+ expect(err).toBe(reason)
233
+ })
234
+ })
package/src/client.ts CHANGED
@@ -8,6 +8,12 @@ import type {
8
8
  TokenUsage,
9
9
  ToolChoice,
10
10
  } from '@namzu/sdk'
11
+ import {
12
+ ProviderRequestError,
13
+ isCallerAbortError,
14
+ isProviderRequestError,
15
+ providerVendorError,
16
+ } from '@namzu/sdk'
11
17
  import OpenAI from 'openai'
12
18
  import type {
13
19
  ChatCompletionContentPart,
@@ -188,73 +194,92 @@ export class OpenAIProvider implements LLMProvider {
188
194
  async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
189
195
  const model = this.resolveModel(params)
190
196
 
191
- const stream = await this.client.chat.completions.create(
192
- {
193
- model,
194
- messages: toOpenAIMessages(params.messages),
195
- stream: true,
196
- stream_options: { include_usage: true },
197
- tools: toOpenAITools(params),
198
- tool_choice: formatToolChoice(params.toolChoice),
199
- parallel_tool_calls: params.parallelToolCalls,
200
- temperature: params.temperature,
201
- max_tokens: params.maxTokens,
202
- top_p: params.topP,
203
- frequency_penalty: params.frequencyPenalty,
204
- presence_penalty: params.presencePenalty,
205
- stop: params.stop,
206
- response_format: params.responseFormat,
207
- },
208
- // Per-request abort: a Stop tears the in-flight SSE request down.
209
- { signal: params.signal },
210
- )
197
+ let stream: Awaited<ReturnType<typeof this.client.chat.completions.create>>
198
+ try {
199
+ stream = await this.client.chat.completions.create(
200
+ {
201
+ model,
202
+ messages: toOpenAIMessages(params.messages),
203
+ stream: true,
204
+ stream_options: { include_usage: true },
205
+ tools: toOpenAITools(params),
206
+ tool_choice: formatToolChoice(params.toolChoice),
207
+ parallel_tool_calls: params.parallelToolCalls,
208
+ temperature: params.temperature,
209
+ max_tokens: params.maxTokens,
210
+ top_p: params.topP,
211
+ frequency_penalty: params.frequencyPenalty,
212
+ presence_penalty: params.presencePenalty,
213
+ stop: params.stop,
214
+ response_format: params.responseFormat,
215
+ },
216
+ // Per-request abort: a Stop tears the in-flight SSE request down.
217
+ { signal: params.signal },
218
+ )
219
+ } catch (err) {
220
+ // The vendor SDK builds its error message FROM the response body, so a
221
+ // credential the upstream echoed back is already inside `err.message`
222
+ // before this code runs (proven with a planted fake token). Classify from
223
+ // the status and drop the vendor error entirely — no re-throw, no
224
+ // `cause`, because a `cause` is exactly what a structured logger walks.
225
+ if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
226
+ if (isProviderRequestError(err)) throw err
227
+ throw providerVendorError({ providerId: 'openai', error: err })
228
+ }
211
229
 
212
- for await (const chunk of stream) {
213
- // Stop pulling promptly on abort; `for await` calls the stream's
214
- // `.return()` on this throw, releasing the connection.
215
- params.signal?.throwIfAborted()
216
- try {
217
- const choice = chunk.choices[0]
218
- const delta = choice?.delta
230
+ try {
231
+ for await (const chunk of stream) {
232
+ // Stop pulling promptly on abort; `for await` calls the stream's
233
+ // `.return()` on this throw, releasing the connection.
234
+ params.signal?.throwIfAborted()
235
+ try {
236
+ const choice = chunk.choices[0]
237
+ const delta = choice?.delta
219
238
 
220
- const toolCalls = delta?.tool_calls?.map((tc) => ({
221
- index: tc.index,
222
- id: tc.id,
223
- type: tc.type,
224
- function: tc.function
225
- ? {
226
- name: tc.function.name,
227
- arguments: tc.function.arguments,
228
- }
229
- : undefined,
230
- }))
239
+ const toolCalls = delta?.tool_calls?.map((tc) => ({
240
+ index: tc.index,
241
+ id: tc.id,
242
+ type: tc.type,
243
+ function: tc.function
244
+ ? {
245
+ name: tc.function.name,
246
+ arguments: tc.function.arguments,
247
+ }
248
+ : undefined,
249
+ }))
231
250
 
232
- const hasDelta =
233
- (delta?.content !== undefined && delta.content !== null) ||
234
- (toolCalls && toolCalls.length > 0)
235
- const finishReason = choice?.finish_reason
236
- ? mapFinishReason(choice.finish_reason)
237
- : undefined
238
- const usage = chunk.usage ? parseUsage(chunk.usage) : undefined
251
+ const hasDelta =
252
+ (delta?.content !== undefined && delta.content !== null) ||
253
+ (toolCalls && toolCalls.length > 0)
254
+ const finishReason = choice?.finish_reason
255
+ ? mapFinishReason(choice.finish_reason)
256
+ : undefined
257
+ const usage = chunk.usage ? parseUsage(chunk.usage) : undefined
239
258
 
240
- if (!hasDelta && !finishReason && !usage) continue
259
+ if (!hasDelta && !finishReason && !usage) continue
241
260
 
242
- yield {
243
- id: chunk.id,
244
- delta: {
245
- content: delta?.content ?? undefined,
246
- toolCalls,
247
- },
248
- finishReason,
249
- usage,
250
- }
251
- } catch (parseErr) {
252
- yield {
253
- id: chunk.id ?? '',
254
- delta: {},
255
- error: `Stream parse error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
261
+ yield {
262
+ id: chunk.id,
263
+ delta: {
264
+ content: delta?.content ?? undefined,
265
+ toolCalls,
266
+ },
267
+ finishReason,
268
+ usage,
269
+ }
270
+ } catch (parseErr) {
271
+ if (isProviderRequestError(parseErr)) throw parseErr
272
+ throw new ProviderRequestError({
273
+ kind: 'server',
274
+ providerId: 'openai',
275
+ detail: 'the provider stream returned malformed data',
276
+ })
256
277
  }
257
278
  }
279
+ } catch (err) {
280
+ if (isCallerAbortError(err, params.signal)) throw params.signal?.reason ?? err
281
+ if (isProviderRequestError(err)) throw err
282
+ throw providerVendorError({ providerId: 'openai', error: err })
258
283
  }
259
284
  }
260
285