orchajs 0.27.1 → 0.27.2

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.
@@ -33,20 +33,28 @@ const RELEVANT_EVENTS = /* @__PURE__ */ new Set([
33
33
  "evaluation.completed",
34
34
  "evaluation.failed"
35
35
  ]);
36
+ const PROGRESS_EVENTS = /* @__PURE__ */ new Set([
37
+ "message.created",
38
+ "action.completed",
39
+ "action.failed",
40
+ "subagent.completed",
41
+ "subagent.failed"
42
+ ]);
36
43
  const MAX_BATCH_RUNS = 100;
37
44
  const MAX_KEEPALIVE_BYTES = 48 * 1024;
38
45
  const HEARTBEAT_INTERVAL_MS = 3e4;
39
- const EVALUATION_FLUSH_TIMEOUT_MS = 5e3;
46
+ const MAX_CONCURRENT_FLUSHES = 2;
40
47
  class AmarsiaTelemetryClient {
41
48
  #key;
42
49
  #baseUrl;
43
50
  #queue = /* @__PURE__ */ new Map();
44
51
  #activeRuns = /* @__PURE__ */ new Map();
52
+ #terminalRuns = /* @__PURE__ */ new Set();
45
53
  #pendingProjections = /* @__PURE__ */ new Set();
54
+ #inFlightFlushes = /* @__PURE__ */ new Set();
46
55
  #timer;
47
56
  #heartbeatTimer;
48
57
  #attempt = 0;
49
- #flushPromise;
50
58
  constructor(options) {
51
59
  this.#key = options.key;
52
60
  this.#baseUrl = (0, import_endpoint.resolveAmarsiaEndpoint)(options.endpoint);
@@ -54,24 +62,38 @@ class AmarsiaTelemetryClient {
54
62
  enqueue(fact) {
55
63
  this.#queue.set(fact.event_id, fact);
56
64
  if (fact.status === "running") {
65
+ this.#terminalRuns.delete(fact.event_id);
57
66
  this.#activeRuns.set(fact.event_id, fact);
58
67
  this.#scheduleHeartbeat();
59
- } else {
60
- this.#activeRuns.delete(fact.event_id);
61
- if (this.#activeRuns.size === 0 && this.#heartbeatTimer) {
62
- clearTimeout(this.#heartbeatTimer);
63
- this.#heartbeatTimer = void 0;
68
+ if (this.#queue.size >= 20) {
69
+ void this.#flush();
70
+ return;
64
71
  }
65
- }
66
- if (fact.status !== "running") {
67
- this.#scheduleTerminal();
72
+ this.#schedule(250);
68
73
  return;
69
74
  }
70
- if (this.#queue.size >= 20) {
71
- void this.#flush();
75
+ this.#terminalRuns.add(fact.event_id);
76
+ this.#activeRuns.delete(fact.event_id);
77
+ if (this.#activeRuns.size === 0 && this.#heartbeatTimer) {
78
+ clearTimeout(this.#heartbeatTimer);
79
+ this.#heartbeatTimer = void 0;
80
+ }
81
+ if (this.#timer) {
82
+ clearTimeout(this.#timer);
83
+ this.#timer = void 0;
84
+ }
85
+ void this.#flush();
86
+ }
87
+ updateActiveRun(fact) {
88
+ if (fact.status !== "running" || this.#terminalRuns.has(fact.event_id)) {
72
89
  return;
73
90
  }
74
- this.#schedule(250);
91
+ if (this.#activeRuns.has(fact.event_id)) {
92
+ this.#activeRuns.set(fact.event_id, fact);
93
+ }
94
+ if (this.#queue.has(fact.event_id)) {
95
+ this.#queue.set(fact.event_id, fact);
96
+ }
75
97
  }
76
98
  #schedule(delay) {
77
99
  if (this.#timer) return;
@@ -89,19 +111,14 @@ class AmarsiaTelemetryClient {
89
111
  this.#pendingProjections.delete(projection);
90
112
  });
91
113
  }
92
- #scheduleTerminal() {
93
- if (this.#timer) clearTimeout(this.#timer);
94
- this.#timer = setTimeout(() => {
95
- this.#timer = void 0;
96
- void this.#flush();
97
- }, 0);
98
- }
99
114
  #scheduleHeartbeat() {
100
115
  if (this.#heartbeatTimer || this.#activeRuns.size === 0) return;
101
116
  this.#heartbeatTimer = setTimeout(() => {
102
117
  this.#heartbeatTimer = void 0;
103
118
  for (const fact of this.#activeRuns.values()) {
104
- this.#queue.set(fact.event_id, fact);
119
+ if (!this.#terminalRuns.has(fact.event_id)) {
120
+ this.#queue.set(fact.event_id, fact);
121
+ }
105
122
  }
106
123
  void this.#flush();
107
124
  this.#scheduleHeartbeat();
@@ -112,7 +129,7 @@ class AmarsiaTelemetryClient {
112
129
  async drain(options = {}) {
113
130
  const timeoutMs = Math.max(0, options.timeoutMs ?? 2e3);
114
131
  const deadline = Date.now() + timeoutMs;
115
- while (this.#pendingProjections.size > 0 || this.#queue.size > 0 || this.#flushPromise) {
132
+ while (this.#pendingProjections.size > 0 || this.#queue.size > 0 || this.#inFlightFlushes.size > 0) {
116
133
  const remaining = deadline - Date.now();
117
134
  if (remaining <= 0) return;
118
135
  if (this.#pendingProjections.size > 0) {
@@ -126,10 +143,19 @@ class AmarsiaTelemetryClient {
126
143
  clearTimeout(this.#timer);
127
144
  this.#timer = void 0;
128
145
  }
129
- await Promise.race([
130
- this.#flush(),
131
- new Promise((resolve) => setTimeout(resolve, remaining))
132
- ]);
146
+ if (this.#queue.size > 0) {
147
+ await Promise.race([
148
+ this.#flush(),
149
+ new Promise((resolve) => setTimeout(resolve, remaining))
150
+ ]);
151
+ continue;
152
+ }
153
+ if (this.#inFlightFlushes.size > 0) {
154
+ await Promise.race([
155
+ Promise.allSettled([...this.#inFlightFlushes]).then(() => void 0),
156
+ new Promise((resolve) => setTimeout(resolve, remaining))
157
+ ]);
158
+ }
133
159
  }
134
160
  }
135
161
  async close(options = {}) {
@@ -146,20 +172,33 @@ class AmarsiaTelemetryClient {
146
172
  this.#activeRuns.clear();
147
173
  }
148
174
  async #flush() {
149
- if (this.#flushPromise) return this.#flushPromise;
150
- if (this.#queue.size === 0) return;
151
- this.#flushPromise = this.#performFlush();
175
+ if (this.#queue.size === 0) {
176
+ if (this.#inFlightFlushes.size > 0) {
177
+ await Promise.allSettled([...this.#inFlightFlushes]);
178
+ }
179
+ return;
180
+ }
181
+ const hasTerminalFact = [...this.#queue.values()].some(
182
+ (fact) => fact.status !== "running"
183
+ );
184
+ const maxConcurrent = hasTerminalFact ? MAX_CONCURRENT_FLUSHES : 1;
185
+ if (this.#inFlightFlushes.size >= maxConcurrent) {
186
+ await Promise.allSettled([...this.#inFlightFlushes]);
187
+ return;
188
+ }
189
+ const flushPromise = this.#performFlush();
190
+ this.#inFlightFlushes.add(flushPromise);
152
191
  try {
153
- await this.#flushPromise;
192
+ await flushPromise;
154
193
  } finally {
155
- this.#flushPromise = void 0;
194
+ this.#inFlightFlushes.delete(flushPromise);
156
195
  if (this.#queue.size > 0 && !this.#timer) {
157
- const hasTerminalFact = [...this.#queue.values()].some(
196
+ const remainingHasTerminal = [...this.#queue.values()].some(
158
197
  (fact) => fact.status !== "running"
159
198
  );
160
- if (hasTerminalFact) {
199
+ if (remainingHasTerminal) {
161
200
  void this.#flush();
162
- } else {
201
+ } else if (this.#inFlightFlushes.size === 0) {
163
202
  this.#schedule(250);
164
203
  }
165
204
  }
@@ -194,6 +233,9 @@ class AmarsiaTelemetryClient {
194
233
  this.#attempt += 1;
195
234
  if (this.#attempt <= 6) {
196
235
  for (const fact of batch) {
236
+ if (fact.status === "running" && this.#terminalRuns.has(fact.event_id)) {
237
+ continue;
238
+ }
197
239
  if (!this.#queue.has(fact.event_id)) {
198
240
  this.#queue.set(fact.event_id, fact);
199
241
  }
@@ -233,19 +275,48 @@ function withAmarsiaTelemetry(options) {
233
275
  async append(sessionId, events) {
234
276
  await store.append(sessionId, events);
235
277
  const runs = relevantRuns(events);
236
- if (runs.size === 0 && !projections.has(sessionId) && !pending.has(sessionId)) {
278
+ const progressRuns = progressOnlyRuns(events, runs);
279
+ const hasSessionCreated = events.some(
280
+ (event) => event.type === "session.created"
281
+ );
282
+ if (runs.size === 0 && progressRuns.size === 0 && !hasSessionCreated && !projections.has(sessionId) && !pending.has(sessionId)) {
237
283
  return;
238
284
  }
285
+ if (!pending.has(sessionId)) {
286
+ let projection = projections.get(sessionId);
287
+ let hasNewEvents = false;
288
+ if (!projection && hasSessionCreated) {
289
+ projection = createProjection(events);
290
+ projections.set(sessionId, projection);
291
+ hasNewEvents = projection.seenSequences.size > 0;
292
+ } else if (projection) {
293
+ hasNewEvents = appendToProjection(projection, events);
294
+ }
295
+ if (projection) {
296
+ if (projection.isTest || !hasNewEvents) return;
297
+ for (const run of runs) {
298
+ const fact = projectRunFact(manifest, sessionId, run, projection);
299
+ if (fact) client.enqueue(fact);
300
+ }
301
+ for (const run of progressRuns) {
302
+ const fact = projectRunFact(manifest, sessionId, run, projection);
303
+ if (fact) client.updateActiveRun(fact);
304
+ }
305
+ return;
306
+ }
307
+ }
239
308
  const previous = pending.get(sessionId) ?? Promise.resolve();
240
309
  const processing = previous.then(async () => {
241
310
  let projection = projections.get(sessionId);
311
+ let hasNewEvents = false;
242
312
  if (!projection) {
243
313
  projection = createProjection(await store.read(sessionId));
244
314
  projections.set(sessionId, projection);
315
+ hasNewEvents = projection.seenSequences.size > 0;
245
316
  } else {
246
- appendToProjection(projection, events);
317
+ hasNewEvents = appendToProjection(projection, events);
247
318
  }
248
- if (projection.isTest) return;
319
+ if (projection.isTest || !hasNewEvents) return;
249
320
  for (const run of runs) {
250
321
  const fact = projectRunFact(
251
322
  manifest,
@@ -255,6 +326,15 @@ function withAmarsiaTelemetry(options) {
255
326
  );
256
327
  if (fact) client.enqueue(fact);
257
328
  }
329
+ for (const run of progressRuns) {
330
+ const fact = projectRunFact(
331
+ manifest,
332
+ sessionId,
333
+ run,
334
+ projection
335
+ );
336
+ if (fact) client.updateActiveRun(fact);
337
+ }
258
338
  }).catch(() => void 0);
259
339
  pending.set(sessionId, processing);
260
340
  client.trackProjection(processing);
@@ -263,18 +343,6 @@ function withAmarsiaTelemetry(options) {
263
343
  pending.delete(sessionId);
264
344
  }
265
345
  });
266
- const hasTerminalRunEvent = events.some(
267
- (event) => event.type === "run.completed" || event.type === "run.failed" || event.type === "run.paused"
268
- );
269
- const hasEvaluationResult = events.some(
270
- (event) => event.type === "evaluation.completed" || event.type === "evaluation.failed"
271
- );
272
- if (hasTerminalRunEvent || hasEvaluationResult) {
273
- await processing;
274
- }
275
- if (hasEvaluationResult) {
276
- await client.drain({ timeoutMs: EVALUATION_FLUSH_TIMEOUT_MS });
277
- }
278
346
  }
279
347
  };
280
348
  }
@@ -288,9 +356,11 @@ function createProjection(events) {
288
356
  return projection;
289
357
  }
290
358
  function appendToProjection(projection, events) {
359
+ let added = false;
291
360
  for (const event of events) {
292
361
  if (projection.seenSequences.has(event.sequence)) continue;
293
362
  projection.seenSequences.add(event.sequence);
363
+ added = true;
294
364
  if (event.type === "session.created") {
295
365
  projection.sessionCreated = event;
296
366
  const metadata = asRecord(event.data.metadata);
@@ -304,6 +374,7 @@ function appendToProjection(projection, events) {
304
374
  projection.runs.set(event.run, [event]);
305
375
  }
306
376
  }
377
+ return added;
307
378
  }
308
379
  function relevantRuns(events) {
309
380
  const runs = /* @__PURE__ */ new Set();
@@ -314,6 +385,15 @@ function relevantRuns(events) {
314
385
  }
315
386
  return runs;
316
387
  }
388
+ function progressOnlyRuns(events, relevant) {
389
+ const runs = /* @__PURE__ */ new Set();
390
+ for (const event of events) {
391
+ if (typeof event.run === "number" && !relevant.has(event.run) && PROGRESS_EVENTS.has(event.type)) {
392
+ runs.add(event.run);
393
+ }
394
+ }
395
+ return runs;
396
+ }
317
397
  function projectRunFact(manifest, sessionId, run, projection) {
318
398
  const runEvents = projection.runs.get(run);
319
399
  if (!runEvents) return void 0;
@@ -309,18 +309,21 @@ function toProviderResponse(request, response) {
309
309
  );
310
310
  const textOutput = response.output_text ?? content.filter((block) => block.type === "text").map((block) => block.text).join("");
311
311
  const stopReason = normalizeStopReason(response, toolCalls, refused);
312
- const output = request.outputType === "json" && toolCalls.length === 0 && stopReason !== "max_tokens" ? (0, import_structured_output.parseStructuredOutput)(textOutput, request.outputSchema ?? {}) : textOutput;
313
312
  if (textOutput) {
314
313
  request.publishOutput?.(textOutput);
315
314
  }
316
- return {
317
- output,
318
- responseId: response.id,
319
- stopReason,
320
- content,
321
- toolCalls,
322
- usage: normalizeUsage(response.usage)
323
- };
315
+ return (0, import_structured_output.resolveProviderStructuredOutput)(
316
+ request,
317
+ {
318
+ output: textOutput,
319
+ responseId: response.id,
320
+ stopReason,
321
+ content,
322
+ toolCalls,
323
+ usage: normalizeUsage(response.usage)
324
+ },
325
+ textOutput
326
+ );
324
327
  }
325
328
  function replay(item) {
326
329
  const value = {
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var errors_exports = {};
21
21
  __export(errors_exports, {
22
22
  OrchaError: () => OrchaError,
23
+ createProviderHttpError: () => createProviderHttpError,
23
24
  describeProviderError: () => describeProviderError,
24
25
  isRetryableProviderConnectionError: () => isRetryableProviderConnectionError
25
26
  });
@@ -36,18 +37,74 @@ class OrchaError extends Error {
36
37
  this.details = options.details;
37
38
  }
38
39
  }
40
+ const NON_RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([400, 401, 403, 404, 413, 422]);
41
+ const NON_RETRYABLE_ERROR_NAMES = /* @__PURE__ */ new Set([
42
+ "ValidationException",
43
+ "AccessDeniedException",
44
+ "ResourceNotFoundException",
45
+ "UnrecognizedClientException",
46
+ "InvalidSignatureException",
47
+ "ExpiredTokenException"
48
+ ]);
49
+ async function createProviderHttpError(response, providerLabel) {
50
+ const status = response.status;
51
+ const requestId = response.headers.get("request-id") ?? response.headers.get("x-request-id") ?? response.headers.get("x-amzn-requestid") ?? void 0;
52
+ let rawText = "";
53
+ try {
54
+ rawText = (await response.text()).trim();
55
+ } catch {
56
+ rawText = "";
57
+ }
58
+ let parsedMessage;
59
+ let errorCode;
60
+ if (rawText) {
61
+ try {
62
+ const parsed = JSON.parse(rawText);
63
+ const nestedError = typeof parsed.error === "object" && parsed.error !== null ? parsed.error : void 0;
64
+ if (typeof nestedError?.message === "string" && nestedError.message.trim()) {
65
+ parsedMessage = nestedError.message.trim();
66
+ } else if (typeof parsed.message === "string" && parsed.message.trim()) {
67
+ parsedMessage = parsed.message.trim();
68
+ } else if (typeof parsed.detail === "string" && parsed.detail.trim()) {
69
+ parsedMessage = parsed.detail.trim();
70
+ }
71
+ errorCode = stringOrNumberField(nestedError, "code") ?? stringOrNumberField(nestedError, "type") ?? stringOrNumberField(parsed, "code");
72
+ } catch {
73
+ const compact = rawText.replace(/\s+/g, " ").trim();
74
+ if (compact) {
75
+ parsedMessage = compact.length > 300 ? `${compact.slice(0, 300)}...` : compact;
76
+ }
77
+ }
78
+ }
79
+ const message = parsedMessage ?? `${providerLabel} request failed with HTTP ${status}.`;
80
+ const error = new Error(message);
81
+ error.statusCode = status;
82
+ if (requestId) {
83
+ error.requestId = requestId;
84
+ }
85
+ if (errorCode !== void 0) {
86
+ error.code = errorCode;
87
+ }
88
+ return error;
89
+ }
39
90
  function describeProviderError(error) {
40
91
  const rootMessage = errorMessage(error);
92
+ const statusCode = extractStatusCode(error);
93
+ const requestId = extractRequestId(error);
94
+ const errorName = extractErrorName(error);
95
+ const errorCode = stringOrNumberField(error, "code") ?? stringOrNumberField(error, "type");
96
+ const retryable = isProviderErrorRetryable(statusCode, errorName);
41
97
  const cause = deepestUsefulCause(error);
42
- if (!cause) {
43
- return { message: rootMessage };
44
- }
45
- const causeMessage = errorMessage(cause);
46
- const causeCode = stringOrNumberField(cause, "code");
47
- const syscall = stringField(cause, "syscall");
48
- const hostname = stringField(cause, "hostname");
49
- const explanation = causeMessage !== rootMessage ? causeMessage : causeCode ? String(causeCode) : void 0;
98
+ const causeMessage = cause ? errorMessage(cause) : void 0;
99
+ const causeCode = cause ? stringOrNumberField(cause, "code") : void 0;
100
+ const syscall = cause ? stringField(cause, "syscall") : void 0;
101
+ const hostname = cause ? stringField(cause, "hostname") : void 0;
102
+ const explanation = causeMessage && causeMessage !== rootMessage ? causeMessage : causeCode !== void 0 ? String(causeCode) : void 0;
50
103
  const details = {
104
+ ...statusCode !== void 0 ? { statusCode } : {},
105
+ ...requestId ? { requestId } : {},
106
+ ...errorName ? { errorName } : {},
107
+ ...errorCode !== void 0 ? { errorCode } : {},
51
108
  ...causeCode !== void 0 ? { causeCode } : {},
52
109
  ...syscall ? { syscall } : {},
53
110
  ...hostname ? { hostname } : {},
@@ -55,6 +112,7 @@ function describeProviderError(error) {
55
112
  };
56
113
  return {
57
114
  message: explanation ? `${rootMessage}: ${explanation}` : rootMessage,
115
+ retryable,
58
116
  ...Object.keys(details).length > 0 ? { details } : {}
59
117
  };
60
118
  }
@@ -83,6 +141,45 @@ function isRetryableProviderConnectionError(error) {
83
141
  }
84
142
  return false;
85
143
  }
144
+ function isProviderErrorRetryable(statusCode, errorName) {
145
+ if (errorName && NON_RETRYABLE_ERROR_NAMES.has(errorName)) {
146
+ return false;
147
+ }
148
+ if (statusCode !== void 0 && NON_RETRYABLE_STATUS_CODES.has(statusCode)) {
149
+ return false;
150
+ }
151
+ return true;
152
+ }
153
+ function extractStatusCode(error) {
154
+ if (typeof error !== "object" || error === null) return void 0;
155
+ const record = error;
156
+ if (typeof record.statusCode === "number") return record.statusCode;
157
+ if (typeof record.status === "number") return record.status;
158
+ const metadata = typeof record.$metadata === "object" && record.$metadata !== null ? record.$metadata : void 0;
159
+ if (typeof metadata?.httpStatusCode === "number") {
160
+ return metadata.httpStatusCode;
161
+ }
162
+ return void 0;
163
+ }
164
+ function extractRequestId(error) {
165
+ if (typeof error !== "object" || error === null) return void 0;
166
+ const record = error;
167
+ if (typeof record.requestId === "string" && record.requestId.trim()) {
168
+ return record.requestId.trim();
169
+ }
170
+ const metadata = typeof record.$metadata === "object" && record.$metadata !== null ? record.$metadata : void 0;
171
+ if (typeof metadata?.requestId === "string" && metadata.requestId.trim()) {
172
+ return metadata.requestId.trim();
173
+ }
174
+ return void 0;
175
+ }
176
+ function extractErrorName(error) {
177
+ if (!(error instanceof Error)) return void 0;
178
+ if (error.name && error.name !== "Error" && error.name !== "OrchaError") {
179
+ return error.name;
180
+ }
181
+ return void 0;
182
+ }
86
183
  function deepestUsefulCause(error) {
87
184
  let current = error;
88
185
  let useful;
@@ -125,6 +222,7 @@ function stringOrNumberField(value, key) {
125
222
  // Annotate the CommonJS export names for ESM import in node:
126
223
  0 && (module.exports = {
127
224
  OrchaError,
225
+ createProviderHttpError,
128
226
  describeProviderError,
129
227
  isRetryableProviderConnectionError
130
228
  });
@@ -24,6 +24,7 @@ __export(file_content_exports, {
24
24
  readLocalFileContent: () => readLocalFileContent
25
25
  });
26
26
  module.exports = __toCommonJS(file_content_exports);
27
+ var import_errors = require("./errors.js");
27
28
  const MIME_TYPES = {
28
29
  ".csv": "text/csv",
29
30
  ".doc": "application/msword",
@@ -72,7 +73,21 @@ function normalizeUrlContent(url, mimeType) {
72
73
  async function readLocalFileContent(content) {
73
74
  const fsModule = "fs/promises";
74
75
  const { readFile } = await import(fsModule);
75
- const bytes = await readFile(content.filePath);
76
+ let bytes;
77
+ try {
78
+ bytes = await readFile(content.filePath);
79
+ } catch (error) {
80
+ const reason = error instanceof Error ? error.message : String(error);
81
+ throw new import_errors.OrchaError(
82
+ "invalid_input",
83
+ `Failed to read local file "${content.filePath}": ${reason}`,
84
+ {
85
+ retryable: false,
86
+ cause: error,
87
+ details: { filePath: content.filePath }
88
+ }
89
+ );
90
+ }
76
91
  const base64 = bytes.toString("base64");
77
92
  return {
78
93
  bytes,
@@ -82,10 +82,7 @@ ${JSON.stringify(request.outputSchema)}` : request.systemPrompt;
82
82
  }
83
83
  );
84
84
  if (!response.ok) {
85
- const body2 = await response.json();
86
- throw new Error(
87
- body2.error?.message ?? `Anthropic request failed with HTTP ${response.status}.`
88
- );
85
+ throw await (0, import_errors.createProviderHttpError)(response, "Anthropic");
89
86
  }
90
87
  const body = response.headers.get("content-type")?.includes("text/event-stream") ? await readAnthropicStream(response, request.publishOutput) : await response.json();
91
88
  return toProviderResponse(request, body);
@@ -97,24 +94,27 @@ function toProviderResponse(request, body) {
97
94
  (item) => item.type === "tool_call"
98
95
  );
99
96
  const stopReason = normalizeStopReason(body.stop_reason);
100
- const output = request.outputType === "json" && toolCalls.length === 0 && stopReason !== "max_tokens" ? (0, import_structured_output.parseStructuredOutput)(textOutput, request.outputSchema ?? {}) : textOutput;
101
97
  if (textOutput && request.publishOutput) {
102
98
  request.publishOutput(textOutput);
103
99
  }
104
- return {
105
- output,
106
- responseId: body.id,
107
- stopReason,
108
- content,
109
- toolCalls,
110
- usage: {
111
- inputTokens: body.usage?.input_tokens ?? 0,
112
- outputTokens: body.usage?.output_tokens ?? 0,
113
- reasoningTokens: null,
114
- cacheReadTokens: body.usage?.cache_read_input_tokens ?? 0,
115
- cacheWriteTokens: body.usage?.cache_creation_input_tokens ?? 0
116
- }
117
- };
100
+ return (0, import_structured_output.resolveProviderStructuredOutput)(
101
+ request,
102
+ {
103
+ output: textOutput,
104
+ responseId: body.id,
105
+ stopReason,
106
+ content,
107
+ toolCalls,
108
+ usage: {
109
+ inputTokens: body.usage?.input_tokens ?? 0,
110
+ outputTokens: body.usage?.output_tokens ?? 0,
111
+ reasoningTokens: null,
112
+ cacheReadTokens: body.usage?.cache_read_input_tokens ?? 0,
113
+ cacheWriteTokens: body.usage?.cache_creation_input_tokens ?? 0
114
+ }
115
+ },
116
+ textOutput
117
+ );
118
118
  }
119
119
  function normalizeStopReason(reason) {
120
120
  if (reason === void 0 || reason === null) {
@@ -497,23 +497,24 @@ function toProviderResponse(request, response) {
497
497
  (block) => block.type === "tool_call"
498
498
  );
499
499
  const stopReason = normalizeStopReason(response.stopReason);
500
- return {
501
- output: request.outputType === "json" && toolCalls.length === 0 && stopReason !== "max_tokens" ? (0, import_structured_output.parseStructuredOutput)(
502
- textOutput,
503
- request.outputSchema ?? {}
504
- ) : textOutput,
505
- responseId: response.requestId,
506
- stopReason,
507
- content: response.blocks,
508
- toolCalls,
509
- usage: {
510
- inputTokens: response.usage?.inputTokens ?? 0,
511
- outputTokens: response.usage?.outputTokens ?? 0,
512
- reasoningTokens: null,
513
- cacheReadTokens: response.usage?.cacheReadInputTokens ?? 0,
514
- cacheWriteTokens: response.usage?.cacheWriteInputTokens ?? 0
515
- }
516
- };
500
+ return (0, import_structured_output.resolveProviderStructuredOutput)(
501
+ request,
502
+ {
503
+ output: textOutput,
504
+ responseId: response.requestId,
505
+ stopReason,
506
+ content: response.blocks,
507
+ toolCalls,
508
+ usage: {
509
+ inputTokens: response.usage?.inputTokens ?? 0,
510
+ outputTokens: response.usage?.outputTokens ?? 0,
511
+ reasoningTokens: null,
512
+ cacheReadTokens: response.usage?.cacheReadInputTokens ?? 0,
513
+ cacheWriteTokens: response.usage?.cacheWriteInputTokens ?? 0
514
+ }
515
+ },
516
+ textOutput
517
+ );
517
518
  }
518
519
  function normalizeStopReason(reason) {
519
520
  if (!reason) {
@@ -86,10 +86,7 @@ async function generateDeepSeek(configuration, request) {
86
86
  }
87
87
  );
88
88
  if (!response.ok) {
89
- const error = await response.json();
90
- throw new Error(
91
- error.error?.message ?? `DeepSeek request failed with HTTP ${response.status}.`
92
- );
89
+ throw await (0, import_errors.createProviderHttpError)(response, "DeepSeek");
93
90
  }
94
91
  const collected = await collectDeepSeekStream(
95
92
  response,
@@ -259,18 +256,18 @@ function toProviderResponse(request, response) {
259
256
  (block) => block.type === "tool_call"
260
257
  );
261
258
  const stopReason = normalizeStopReason(response.finishReason, toolCalls);
262
- const output = request.outputType === "json" && toolCalls.length === 0 && stopReason !== "max_tokens" ? (0, import_structured_output.parseStructuredOutput)(
263
- response.content,
264
- request.outputSchema ?? {}
265
- ) : response.content;
266
- return {
267
- output,
268
- responseId: response.id,
269
- stopReason,
270
- content,
271
- toolCalls,
272
- usage: normalizeUsage(response.usage)
273
- };
259
+ return (0, import_structured_output.resolveProviderStructuredOutput)(
260
+ request,
261
+ {
262
+ output: response.content,
263
+ responseId: response.id,
264
+ stopReason,
265
+ content,
266
+ toolCalls,
267
+ usage: normalizeUsage(response.usage)
268
+ },
269
+ response.content
270
+ );
274
271
  }
275
272
  function parseToolArguments(value, toolName) {
276
273
  let parsed;