@moduna/qcp 0.1.1-alpha.13 → 0.1.1-beta.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.
Files changed (3) hide show
  1. package/dist/index.js +663 -222
  2. package/dist/qcp.js +663 -222
  3. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -2373,7 +2373,7 @@ var package_default;
2373
2373
  var init_package = __esm(() => {
2374
2374
  package_default = {
2375
2375
  name: "@moduna/qcp",
2376
- version: "0.1.1-alpha.13",
2376
+ version: "0.1.1-beta.0",
2377
2377
  description: "AI-powered CLI for querying PostgreSQL in natural language",
2378
2378
  type: "module",
2379
2379
  bin: {
@@ -2429,7 +2429,7 @@ var init_package = __esm(() => {
2429
2429
  node: ">=18.0.0"
2430
2430
  },
2431
2431
  dependencies: {
2432
- "@anthropic-ai/sdk": "^0.105.0",
2432
+ "@anthropic-ai/sdk": "^0.106.0",
2433
2433
  "@google/generative-ai": "^0.24.0",
2434
2434
  "@types/uuid": "^11.0.0",
2435
2435
  archiver: "^8.0.0",
@@ -2438,11 +2438,11 @@ var init_package = __esm(() => {
2438
2438
  commander: "^15.0.0",
2439
2439
  dotenv: "^17.4.2",
2440
2440
  inquirer: "^14.0.2",
2441
- openai: "^6.0.0",
2441
+ openai: "^6.45.0",
2442
2442
  ora: "^9.4.1",
2443
2443
  "pgsql-ast-parser": "^12.0.2",
2444
2444
  postgres: "^3.4.9",
2445
- "posthog-node": "^5.0.0",
2445
+ "posthog-node": "^5.38.5",
2446
2446
  uuid: "^14.0.1",
2447
2447
  winston: "^3.17.0",
2448
2448
  zod: "^4.4.3"
@@ -33741,7 +33741,7 @@ var sleep = (ms, signal) => new Promise((resolve) => {
33741
33741
  });
33742
33742
 
33743
33743
  // node_modules/@anthropic-ai/sdk/version.mjs
33744
- var VERSION = "0.105.0";
33744
+ var VERSION = "0.106.0";
33745
33745
 
33746
33746
  // node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs
33747
33747
  function getDetectedPlatform() {
@@ -35328,7 +35328,7 @@ var init_streaming = __esm(() => {
35328
35328
  throw e;
35329
35329
  }
35330
35330
  }
35331
- if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop" || sse.event === "message" || sse.event === "user.message" || sse.event === "user.interrupt" || sse.event === "user.tool_confirmation" || sse.event === "user.custom_tool_result" || sse.event === "user.tool_result" || sse.event === "agent.message" || sse.event === "agent.thinking" || sse.event === "agent.tool_use" || sse.event === "agent.tool_result" || sse.event === "agent.mcp_tool_use" || sse.event === "agent.mcp_tool_result" || sse.event === "agent.custom_tool_use" || sse.event === "agent.thread_context_compacted" || sse.event === "session.status_running" || sse.event === "session.status_idle" || sse.event === "session.status_rescheduled" || sse.event === "session.status_terminated" || sse.event === "session.error" || sse.event === "session.deleted" || sse.event === "session.updated" || sse.event === "span.model_request_start" || sse.event === "span.model_request_end" || sse.event === "span.outcome_evaluation_start" || sse.event === "span.outcome_evaluation_ongoing" || sse.event === "span.outcome_evaluation_end" || sse.event === "user.define_outcome" || sse.event === "agent.thread_message_received" || sse.event === "agent.thread_message_sent" || sse.event === "agent.session_thread_message_received" || sse.event === "agent.session_thread_message_sent" || sse.event === "session.thread_created" || sse.event === "session.thread_status_created" || sse.event === "session.thread_status_running" || sse.event === "session.thread_status_idle" || sse.event === "session.thread_status_rescheduled" || sse.event === "session.thread_status_terminated") {
35331
+ if (sse.event === "message_start" || sse.event === "message_delta" || sse.event === "message_stop" || sse.event === "content_block_start" || sse.event === "content_block_delta" || sse.event === "content_block_stop" || sse.event === "message" || sse.event === "user.message" || sse.event === "user.interrupt" || sse.event === "user.tool_confirmation" || sse.event === "user.custom_tool_result" || sse.event === "user.tool_result" || sse.event === "agent.message" || sse.event === "agent.thinking" || sse.event === "agent.tool_use" || sse.event === "agent.tool_result" || sse.event === "agent.mcp_tool_use" || sse.event === "agent.mcp_tool_result" || sse.event === "agent.custom_tool_use" || sse.event === "agent.thread_context_compacted" || sse.event === "session.status_running" || sse.event === "session.status_idle" || sse.event === "session.status_rescheduled" || sse.event === "session.status_terminated" || sse.event === "session.error" || sse.event === "session.deleted" || sse.event === "session.updated" || sse.event === "span.model_request_start" || sse.event === "span.model_request_end" || sse.event === "span.outcome_evaluation_start" || sse.event === "span.outcome_evaluation_ongoing" || sse.event === "span.outcome_evaluation_end" || sse.event === "user.define_outcome" || sse.event === "agent.thread_message_received" || sse.event === "agent.thread_message_sent" || sse.event === "agent.session_thread_message_received" || sse.event === "agent.session_thread_message_sent" || sse.event === "session.thread_created" || sse.event === "session.thread_status_created" || sse.event === "session.thread_status_running" || sse.event === "session.thread_status_idle" || sse.event === "session.thread_status_rescheduled" || sse.event === "session.thread_status_terminated" || sse.event === "system.message") {
35332
35332
  try {
35333
35333
  yield JSON.parse(sse.data);
35334
35334
  } catch (e) {
@@ -35949,22 +35949,43 @@ function* iterateHeaders(headers) {
35949
35949
  continue;
35950
35950
  if (shouldClear && !didClear) {
35951
35951
  didClear = true;
35952
- yield [name, null];
35952
+ yield [name, clearSentinel];
35953
35953
  }
35954
35954
  yield [name, value2];
35955
35955
  }
35956
35956
  }
35957
35957
  }
35958
- var brand_privateNullableHeaders, buildHeaders = (newHeaders) => {
35958
+ var brand_privateNullableHeaders, clearSentinel, APPEND_HEADERS, appendHeaderValue = (existing, addition) => {
35959
+ const tokens = existing ? existing.split(",").map((t) => t.trim()).filter(Boolean) : [];
35960
+ for (const tok of addition.split(",").map((t) => t.trim())) {
35961
+ if (tok && !tokens.includes(tok))
35962
+ tokens.push(tok);
35963
+ }
35964
+ return tokens.join(", ");
35965
+ }, buildHeaders = (newHeaders) => {
35959
35966
  const targetHeaders = new Headers;
35960
35967
  const nullHeaders = new Set;
35961
35968
  for (const headers of newHeaders) {
35962
35969
  const seenHeaders = new Set;
35963
35970
  for (const [name, value2] of iterateHeaders(headers)) {
35964
35971
  const lowerName = name.toLowerCase();
35965
- if (!seenHeaders.has(lowerName)) {
35972
+ if (APPEND_HEADERS.has(lowerName)) {
35973
+ if (value2 === clearSentinel)
35974
+ continue;
35975
+ if (value2 === null) {
35976
+ targetHeaders.delete(name);
35977
+ nullHeaders.add(lowerName);
35978
+ } else {
35979
+ targetHeaders.set(name, appendHeaderValue(targetHeaders.get(name), value2));
35980
+ nullHeaders.delete(lowerName);
35981
+ }
35982
+ continue;
35983
+ }
35984
+ if (value2 === clearSentinel || !seenHeaders.has(lowerName)) {
35966
35985
  targetHeaders.delete(name);
35967
35986
  seenHeaders.add(lowerName);
35987
+ if (value2 === clearSentinel)
35988
+ continue;
35968
35989
  }
35969
35990
  if (value2 === null) {
35970
35991
  targetHeaders.delete(name);
@@ -35980,6 +36001,8 @@ var brand_privateNullableHeaders, buildHeaders = (newHeaders) => {
35980
36001
  var init_headers = __esm(() => {
35981
36002
  init_values();
35982
36003
  brand_privateNullableHeaders = Symbol.for("brand.privateNullableHeaders");
36004
+ clearSentinel = Symbol("clear");
36005
+ APPEND_HEADERS = new Set(["x-stainless-helper"]);
35983
36006
  });
35984
36007
 
35985
36008
  // node_modules/@anthropic-ai/sdk/internal/utils/path.mjs
@@ -36164,7 +36187,10 @@ var init_deployments = __esm(() => {
36164
36187
  };
36165
36188
  });
36166
36189
 
36167
- // node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs
36190
+ // node_modules/@anthropic-ai/sdk/internal/stainless-helper-header.mjs
36191
+ function helperHeader(value2) {
36192
+ return { [STAINLESS_HELPER_HEADER]: value2 };
36193
+ }
36168
36194
  function wasCreatedByStainlessHelper(value2) {
36169
36195
  return typeof value2 === "object" && value2 !== null && SDK_HELPER_SYMBOL in value2;
36170
36196
  }
@@ -36182,8 +36208,9 @@ function collectStainlessHelpers(tools, messages) {
36182
36208
  if (wasCreatedByStainlessHelper(message)) {
36183
36209
  helpers.add(message[SDK_HELPER_SYMBOL]);
36184
36210
  }
36185
- if (Array.isArray(message.content)) {
36186
- for (const block of message.content) {
36211
+ const content = message.content;
36212
+ if (Array.isArray(content)) {
36213
+ for (const block of content) {
36187
36214
  if (wasCreatedByStainlessHelper(block)) {
36188
36215
  helpers.add(block[SDK_HELPER_SYMBOL]);
36189
36216
  }
@@ -36197,15 +36224,15 @@ function stainlessHelperHeader(tools, messages) {
36197
36224
  const helpers = collectStainlessHelpers(tools, messages);
36198
36225
  if (helpers.length === 0)
36199
36226
  return {};
36200
- return { "x-stainless-helper": helpers.join(", ") };
36227
+ return { [STAINLESS_HELPER_HEADER]: helpers.join(", ") };
36201
36228
  }
36202
36229
  function stainlessHelperHeaderFromFile(file2) {
36203
36230
  if (wasCreatedByStainlessHelper(file2)) {
36204
- return { "x-stainless-helper": file2[SDK_HELPER_SYMBOL] };
36231
+ return { [STAINLESS_HELPER_HEADER]: file2[SDK_HELPER_SYMBOL] };
36205
36232
  }
36206
36233
  return {};
36207
36234
  }
36208
- var SDK_HELPER_SYMBOL;
36235
+ var STAINLESS_HELPER_HEADER = "x-stainless-helper", STAINLESS_HELPER_METHOD_HEADER = "x-stainless-helper-method", SDK_HELPER_SYMBOL;
36209
36236
  var init_stainless_helper_header = __esm(() => {
36210
36237
  SDK_HELPER_SYMBOL = Symbol("anthropic.sdk.stainlessHelper");
36211
36238
  });
@@ -37293,7 +37320,7 @@ function copyClientForHelper(client, { authToken, helper }) {
37293
37320
  const defaultHeaders = buildHeaders([
37294
37321
  inheritedAuthExtraHeaders,
37295
37322
  parentDefaults,
37296
- { "x-stainless-helper": helper }
37323
+ { [STAINLESS_HELPER_HEADER]: helper }
37297
37324
  ]);
37298
37325
  return client.withOptions({
37299
37326
  apiKey: null,
@@ -37306,6 +37333,7 @@ function copyClientForHelper(client, { authToken, helper }) {
37306
37333
  var init_helper_client = __esm(() => {
37307
37334
  init_error();
37308
37335
  init_headers();
37336
+ init_stainless_helper_header();
37309
37337
  });
37310
37338
 
37311
37339
  // node_modules/@anthropic-ai/sdk/lib/environments/poller.mjs
@@ -37557,7 +37585,7 @@ function toSessionContent(content) {
37557
37585
  });
37558
37586
  return out.length > 0 ? out : [{ type: "text", text: "(no output)" }];
37559
37587
  }
37560
- var _SessionToolRunner_instances, _SessionToolRunner_consumed, _SessionToolRunner_controller, _SessionToolRunner_detachExternal, _SessionToolRunner_requestOpts, _SessionToolRunner_toolByName, _SessionToolRunner_logger, _SessionToolRunner_seen, _SessionToolRunner_answered, _SessionToolRunner_results, _SessionToolRunner_inFlightCount, _SessionToolRunner_onIdle, _SessionToolRunner_idleTimer, _SessionToolRunner_requestOptions, _SessionToolRunner_streamLoop, _SessionToolRunner_reconcile, _SessionToolRunner_ingestHistory, _SessionToolRunner_handleStreamEvent, _SessionToolRunner_armIdleTimer, _SessionToolRunner_disarmIdleTimer, _SessionToolRunner_execute, _SessionToolRunner_sendResult, _SessionToolRunner_drain, HELPER_NAME = "SessionToolRunner", STREAM_BACKOFF_START_MS = 500, STREAM_BACKOFF_CAP_MS = 1e4, TOOL_TIMEOUT_MS = 120000, DRAIN_TIMEOUT_MS = 30000, SEND_RETRIES = 3, DEFAULT_MAX_IDLE_MS = 60000, SessionToolRunner;
37588
+ var _SessionToolRunner_instances, _SessionToolRunner_consumed, _SessionToolRunner_controller, _SessionToolRunner_detachExternal, _SessionToolRunner_requestOpts, _SessionToolRunner_toolByName, _SessionToolRunner_logger, _SessionToolRunner_seen, _SessionToolRunner_answered, _SessionToolRunner_results, _SessionToolRunner_inFlightCount, _SessionToolRunner_onIdle, _SessionToolRunner_idleTimer, _SessionToolRunner_requestOptions, _SessionToolRunner_streamLoop, _SessionToolRunner_reconcile, _SessionToolRunner_ingestHistory, _SessionToolRunner_handleStreamEvent, _SessionToolRunner_armIdleTimer, _SessionToolRunner_disarmIdleTimer, _SessionToolRunner_execute, _SessionToolRunner_sendResult, _SessionToolRunner_drain, STREAM_BACKOFF_START_MS = 500, STREAM_BACKOFF_CAP_MS = 1e4, TOOL_TIMEOUT_MS = 120000, DRAIN_TIMEOUT_MS = 30000, SEND_RETRIES = 3, DEFAULT_MAX_IDLE_MS = 60000, SessionToolRunner;
37561
37589
  var init_SessionToolRunner = __esm(() => {
37562
37590
  init_tslib();
37563
37591
  init_error();
@@ -37565,6 +37593,7 @@ var init_SessionToolRunner = __esm(() => {
37565
37593
  init_backoff();
37566
37594
  init_async_queue();
37567
37595
  init_headers();
37596
+ init_stainless_helper_header();
37568
37597
  init_BetaRunnableTool();
37569
37598
  SessionToolRunner = class SessionToolRunner {
37570
37599
  constructor(sessionId, opts) {
@@ -37648,7 +37677,7 @@ var init_SessionToolRunner = __esm(() => {
37648
37677
  _SessionToolRunner_requestOptions = function _SessionToolRunner_requestOptions2() {
37649
37678
  return {
37650
37679
  ...__classPrivateFieldGet(this, _SessionToolRunner_requestOpts, "f"),
37651
- headers: buildHeaders([{ "x-stainless-helper": HELPER_NAME }, __classPrivateFieldGet(this, _SessionToolRunner_requestOpts, "f")?.headers]),
37680
+ headers: buildHeaders([helperHeader("session-tool-runner"), __classPrivateFieldGet(this, _SessionToolRunner_requestOpts, "f")?.headers]),
37652
37681
  signal: __classPrivateFieldGet(this, _SessionToolRunner_controller, "f").signal
37653
37682
  };
37654
37683
  }, _SessionToolRunner_streamLoop = async function _SessionToolRunner_streamLoop2() {
@@ -39340,12 +39369,15 @@ var init_batches = __esm(() => {
39340
39369
  init_path();
39341
39370
  Batches = class Batches extends APIResource {
39342
39371
  create(params, options) {
39343
- const { betas, ...body } = params;
39372
+ const { betas, user_profile_id, ...body } = params;
39344
39373
  return this._client.post("/v1/messages/batches?beta=true", {
39345
39374
  body,
39346
39375
  ...options,
39347
39376
  headers: buildHeaders([
39348
- { "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString() },
39377
+ {
39378
+ "anthropic-beta": [...betas ?? [], "message-batches-2024-09-24"].toString(),
39379
+ ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : undefined
39380
+ },
39349
39381
  options?.headers
39350
39382
  ])
39351
39383
  });
@@ -39762,6 +39794,7 @@ function checkNever(x) {}
39762
39794
  var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage, _BetaMessageStream_toolInputParseError, BetaMessageStream;
39763
39795
  var init_BetaMessageStream = __esm(() => {
39764
39796
  init_tslib();
39797
+ init_stainless_helper_header();
39765
39798
  init_error2();
39766
39799
  init_streaming2();
39767
39800
  init_beta_parser();
@@ -39849,7 +39882,7 @@ var init_BetaMessageStream = __esm(() => {
39849
39882
  runner._addMessageParam(message);
39850
39883
  }
39851
39884
  __classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f");
39852
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
39885
+ runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, [STAINLESS_HELPER_METHOD_HEADER]: "stream" } }));
39853
39886
  return runner;
39854
39887
  }
39855
39888
  _run(executor) {
@@ -40405,11 +40438,14 @@ var init_BetaToolRunner = __esm(() => {
40405
40438
  messages: structuredClone(params.messages)
40406
40439
  }
40407
40440
  }, "f");
40408
- const helpers = collectStainlessHelpers(params.tools, params.messages);
40409
- const helperValue = ["BetaToolRunner", ...helpers].join(", ");
40441
+ const collected = collectStainlessHelpers(params.tools, params.messages);
40410
40442
  __classPrivateFieldSet(this, _BetaToolRunner_options, {
40411
40443
  ...options,
40412
- headers: buildHeaders([{ "x-stainless-helper": helperValue }, options?.headers])
40444
+ headers: buildHeaders([
40445
+ helperHeader("BetaToolRunner"),
40446
+ collected.length ? { [STAINLESS_HELPER_HEADER]: collected.join(", ") } : undefined,
40447
+ options?.headers
40448
+ ])
40413
40449
  }, "f");
40414
40450
  __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f");
40415
40451
  if (params.compactionControl?.enabled) {
@@ -40466,7 +40502,7 @@ var init_BetaToolRunner = __esm(() => {
40466
40502
  max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens
40467
40503
  }, {
40468
40504
  signal: __classPrivateFieldGet(this, _BetaToolRunner_options, "f").signal,
40469
- headers: buildHeaders([__classPrivateFieldGet(this, _BetaToolRunner_options, "f").headers, { "x-stainless-helper": "compaction" }])
40505
+ headers: buildHeaders([__classPrivateFieldGet(this, _BetaToolRunner_options, "f").headers, helperHeader("compaction")])
40470
40506
  });
40471
40507
  if (response.content[0]?.type !== "text") {
40472
40508
  throw new AnthropicError("Expected text response for compaction");
@@ -40659,7 +40695,7 @@ var init_messages = __esm(() => {
40659
40695
  }
40660
40696
  create(params, options) {
40661
40697
  const modifiedParams = transformOutputFormat(params);
40662
- const { betas, ...body } = modifiedParams;
40698
+ const { betas, user_profile_id, ...body } = modifiedParams;
40663
40699
  if (body.model in DEPRECATED_MODELS) {
40664
40700
  console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}
40665
40701
  Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
@@ -40672,14 +40708,17 @@ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resour
40672
40708
  const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;
40673
40709
  timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
40674
40710
  }
40675
- const helperHeader = stainlessHelperHeader(body.tools, body.messages);
40711
+ const helperHeader2 = stainlessHelperHeader(body.tools, body.messages);
40676
40712
  return this._client.post("/v1/messages?beta=true", {
40677
40713
  body,
40678
40714
  timeout: timeout ?? 600000,
40679
40715
  ...options,
40680
40716
  headers: buildHeaders([
40681
- { ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined },
40682
- helperHeader,
40717
+ {
40718
+ ...betas?.toString() != null ? { "anthropic-beta": betas?.toString() } : undefined,
40719
+ ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : undefined
40720
+ },
40721
+ helperHeader2,
40683
40722
  options?.headers
40684
40723
  ]),
40685
40724
  stream: modifiedParams.stream ?? false
@@ -41444,6 +41483,7 @@ function checkNever2(x) {}
41444
41483
  var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_params, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_logger, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage, MessageStream;
41445
41484
  var init_MessageStream = __esm(() => {
41446
41485
  init_tslib();
41486
+ init_stainless_helper_header();
41447
41487
  init_error2();
41448
41488
  init_streaming2();
41449
41489
  init_parser2();
@@ -41531,7 +41571,7 @@ var init_MessageStream = __esm(() => {
41531
41571
  runner._addMessageParam(message);
41532
41572
  }
41533
41573
  __classPrivateFieldSet(runner, _MessageStream_params, { ...params, stream: true }, "f");
41534
- runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, "X-Stainless-Helper-Method": "stream" } }));
41574
+ runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, [STAINLESS_HELPER_METHOD_HEADER]: "stream" } }));
41535
41575
  return runner;
41536
41576
  }
41537
41577
  _run(executor) {
@@ -41957,8 +41997,16 @@ var init_batches2 = __esm(() => {
41957
41997
  init_error2();
41958
41998
  init_path();
41959
41999
  Batches2 = class Batches2 extends APIResource {
41960
- create(body, options) {
41961
- return this._client.post("/v1/messages/batches", { body, ...options });
42000
+ create(params, options) {
42001
+ const { user_profile_id, ...body } = params;
42002
+ return this._client.post("/v1/messages/batches", {
42003
+ body,
42004
+ ...options,
42005
+ headers: buildHeaders([
42006
+ { ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : undefined },
42007
+ options?.headers
42008
+ ])
42009
+ });
41962
42010
  }
41963
42011
  retrieve(messageBatchID, options) {
41964
42012
  return this._client.get(path4`/v1/messages/batches/${messageBatchID}`, options);
@@ -42002,7 +42050,8 @@ var init_messages2 = __esm(() => {
42002
42050
  super(...arguments);
42003
42051
  this.batches = new Batches2(this._client);
42004
42052
  }
42005
- create(body, options) {
42053
+ create(params, options) {
42054
+ const { user_profile_id, ...body } = params;
42006
42055
  if (body.model in DEPRECATED_MODELS2) {
42007
42056
  console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS2[body.model]}
42008
42057
  Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
@@ -42015,13 +42064,17 @@ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resour
42015
42064
  const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined;
42016
42065
  timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens);
42017
42066
  }
42018
- const helperHeader = stainlessHelperHeader(body.tools, body.messages);
42067
+ const helperHeader2 = stainlessHelperHeader(body.tools, body.messages);
42019
42068
  return this._client.post("/v1/messages", {
42020
42069
  body,
42021
42070
  timeout: timeout ?? 600000,
42022
42071
  ...options,
42023
- headers: buildHeaders([helperHeader, options?.headers]),
42024
- stream: body.stream ?? false
42072
+ headers: buildHeaders([
42073
+ { ...user_profile_id != null ? { "anthropic-user-profile-id": user_profile_id } : undefined },
42074
+ helperHeader2,
42075
+ options?.headers
42076
+ ]),
42077
+ stream: params.stream ?? false
42025
42078
  });
42026
42079
  }
42027
42080
  parse(params, options) {
@@ -42758,6 +42811,8 @@ var encoder;
42758
42811
  var init_middleware2 = __esm(() => {
42759
42812
  init_error();
42760
42813
  init_streaming();
42814
+ init_headers();
42815
+ init_stainless_helper_header();
42761
42816
  init_values();
42762
42817
  encoder = new TextEncoder;
42763
42818
  });
@@ -46462,7 +46517,7 @@ var init_values2 = __esm(() => {
46462
46517
  var sleep3 = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
46463
46518
 
46464
46519
  // node_modules/openai/version.mjs
46465
- var VERSION2 = "6.44.0";
46520
+ var VERSION2 = "6.45.0";
46466
46521
 
46467
46522
  // node_modules/openai/internal/detect-platform.mjs
46468
46523
  function getDetectedPlatform2() {
@@ -47143,7 +47198,7 @@ var levelNumbers2, parseLogLevel2 = (maybeLevel, sourceName, client) => {
47143
47198
  if (details.headers) {
47144
47199
  details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value2]) => [
47145
47200
  name,
47146
- name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value2
47201
+ name.toLowerCase() === "authorization" || name.toLowerCase() === "api-key" || name.toLowerCase() === "x-api-key" || name.toLowerCase() === "x-amz-security-token" || name.toLowerCase() === "cookie" || name.toLowerCase() === "set-cookie" ? "***" : value2
47147
47202
  ]));
47148
47203
  }
47149
47204
  if ("retryOfRequestLogID" in details) {
@@ -47746,13 +47801,17 @@ class WorkloadIdentityAuth {
47746
47801
  throw APIError2.generate(response.status, body2, `Token exchange failed with status ${response.status}`, response.headers);
47747
47802
  }
47748
47803
  const tokenResponse = await response.json();
47749
- const expiresIn = tokenResponse.expires_in || 3600;
47804
+ if (typeof tokenResponse !== "object" || tokenResponse === null || !("access_token" in tokenResponse) || typeof tokenResponse.access_token !== "string" || tokenResponse.access_token.trim().length === 0) {
47805
+ throw new OpenAIError("Token exchange response missing 'access_token' field");
47806
+ }
47807
+ const accessToken = tokenResponse.access_token;
47808
+ const expiresIn = tokenResponse.expires_in ?? 3600;
47750
47809
  const expiresAt = Date.now() + expiresIn * 1000;
47751
47810
  this.cachedToken = {
47752
- token: tokenResponse.access_token,
47811
+ token: accessToken,
47753
47812
  expiresAt
47754
47813
  };
47755
- return tokenResponse.access_token;
47814
+ return accessToken;
47756
47815
  }
47757
47816
  isTokenExpired(cachedToken) {
47758
47817
  return Date.now() >= cachedToken.expiresAt;
@@ -48130,6 +48189,7 @@ class EventStream {
48130
48189
  _EventStream_resolveEndPromise.set(this, () => {});
48131
48190
  _EventStream_rejectEndPromise.set(this, () => {});
48132
48191
  _EventStream_listeners.set(this, {});
48192
+ _EventStream_abortListeners.set(this, []);
48133
48193
  _EventStream_ended.set(this, false);
48134
48194
  _EventStream_errored.set(this, false);
48135
48195
  _EventStream_aborted.set(this, false);
@@ -48171,6 +48231,17 @@ class EventStream {
48171
48231
  abort() {
48172
48232
  this.controller.abort();
48173
48233
  }
48234
+ _listenForAbort(signal) {
48235
+ if (!signal || this.ended)
48236
+ return;
48237
+ if (signal.aborted) {
48238
+ this.controller.abort();
48239
+ return;
48240
+ }
48241
+ const listener = () => this.controller.abort();
48242
+ signal.addEventListener("abort", listener, { once: true });
48243
+ __classPrivateFieldGet2(this, _EventStream_abortListeners, "f").push({ signal, listener });
48244
+ }
48174
48245
  on(event, listener) {
48175
48246
  const listeners = __classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] || (__classPrivateFieldGet2(this, _EventStream_listeners, "f")[event] = []);
48176
48247
  listeners.push({ listener });
@@ -48207,6 +48278,7 @@ class EventStream {
48207
48278
  return;
48208
48279
  }
48209
48280
  if (event === "end") {
48281
+ __classPrivateFieldGet2(this, _EventStream_instances, "m", _EventStream_removeAbortListeners).call(this);
48210
48282
  __classPrivateFieldSet2(this, _EventStream_ended, true, "f");
48211
48283
  __classPrivateFieldGet2(this, _EventStream_resolveEndPromise, "f").call(this);
48212
48284
  }
@@ -48237,11 +48309,15 @@ class EventStream {
48237
48309
  }
48238
48310
  _emitFinal() {}
48239
48311
  }
48240
- var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError;
48312
+ var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_abortListeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_removeAbortListeners, _EventStream_handleError;
48241
48313
  var init_EventStream = __esm(() => {
48242
48314
  init_tslib2();
48243
48315
  init_error4();
48244
- _EventStream_connectedPromise = new WeakMap, _EventStream_resolveConnectedPromise = new WeakMap, _EventStream_rejectConnectedPromise = new WeakMap, _EventStream_endPromise = new WeakMap, _EventStream_resolveEndPromise = new WeakMap, _EventStream_rejectEndPromise = new WeakMap, _EventStream_listeners = new WeakMap, _EventStream_ended = new WeakMap, _EventStream_errored = new WeakMap, _EventStream_aborted = new WeakMap, _EventStream_catchingPromiseCreated = new WeakMap, _EventStream_instances = new WeakSet, _EventStream_handleError = function _EventStream_handleError2(error54) {
48316
+ _EventStream_connectedPromise = new WeakMap, _EventStream_resolveConnectedPromise = new WeakMap, _EventStream_rejectConnectedPromise = new WeakMap, _EventStream_endPromise = new WeakMap, _EventStream_resolveEndPromise = new WeakMap, _EventStream_rejectEndPromise = new WeakMap, _EventStream_listeners = new WeakMap, _EventStream_abortListeners = new WeakMap, _EventStream_ended = new WeakMap, _EventStream_errored = new WeakMap, _EventStream_aborted = new WeakMap, _EventStream_catchingPromiseCreated = new WeakMap, _EventStream_instances = new WeakSet, _EventStream_removeAbortListeners = function _EventStream_removeAbortListeners2() {
48317
+ for (const { signal, listener } of __classPrivateFieldGet2(this, _EventStream_abortListeners, "f").splice(0)) {
48318
+ signal.removeEventListener("abort", listener);
48319
+ }
48320
+ }, _EventStream_handleError = function _EventStream_handleError2(error54) {
48245
48321
  __classPrivateFieldSet2(this, _EventStream_errored, true, "f");
48246
48322
  if (error54 instanceof Error && error54.name === "AbortError") {
48247
48323
  error54 = new APIUserAbortError2;
@@ -48357,12 +48433,7 @@ var init_AbstractChatCompletionRunner = __esm(() => {
48357
48433
  }
48358
48434
  }
48359
48435
  async _createChatCompletion(client, params, options) {
48360
- const signal = options?.signal;
48361
- if (signal) {
48362
- if (signal.aborted)
48363
- this.controller.abort();
48364
- signal.addEventListener("abort", () => this.controller.abort());
48365
- }
48436
+ this._listenForAbort(options?.signal);
48366
48437
  __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params);
48367
48438
  const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });
48368
48439
  this._connected();
@@ -48374,11 +48445,11 @@ var init_AbstractChatCompletionRunner = __esm(() => {
48374
48445
  }
48375
48446
  return await this._createChatCompletion(client, params, options);
48376
48447
  }
48377
- async _runTools(client, params, options) {
48448
+ async _runTools(client, params, runner, options) {
48378
48449
  const role = "tool";
48379
48450
  const { tool_choice = "auto", stream, ...restParams } = params;
48380
48451
  const singleFunctionToCall = typeof tool_choice !== "string" && tool_choice.type === "function" && tool_choice?.function?.name;
48381
- const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};
48452
+ const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS, afterCompletion } = options || {};
48382
48453
  const inputTools = params.tools.map((tool) => {
48383
48454
  if (isAutoParsableTool(tool)) {
48384
48455
  if (!tool.$callback) {
@@ -48416,6 +48487,36 @@ var init_AbstractChatCompletionRunner = __esm(() => {
48416
48487
  for (const message of params.messages) {
48417
48488
  this._addMessage(message, false);
48418
48489
  }
48490
+ const runToolCall = async (toolCall) => {
48491
+ if (toolCall.type !== "function")
48492
+ return { message: undefined, functionCalled: false };
48493
+ const tool_call_id = toolCall.id;
48494
+ const { name, arguments: args } = toolCall.function;
48495
+ const fn = functionsByName[name];
48496
+ if (!fn) {
48497
+ const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2) => JSON.stringify(name2)).join(", ")}. Please try again`;
48498
+ return { message: { role, tool_call_id, content: content2 }, functionCalled: false };
48499
+ }
48500
+ if (singleFunctionToCall && singleFunctionToCall !== name) {
48501
+ const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
48502
+ return { message: { role, tool_call_id, content: content2 }, functionCalled: false };
48503
+ }
48504
+ let rawContent;
48505
+ if (isRunnableFunctionWithParse(fn)) {
48506
+ let parsed;
48507
+ try {
48508
+ parsed = await fn.parse(args);
48509
+ } catch (error54) {
48510
+ const content2 = error54 instanceof Error ? error54.message : String(error54);
48511
+ return { message: { role, tool_call_id, content: content2 }, functionCalled: false };
48512
+ }
48513
+ rawContent = await fn.function(parsed, runner);
48514
+ } else {
48515
+ rawContent = await fn.function(args, runner);
48516
+ }
48517
+ const content = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
48518
+ return { message: { role, tool_call_id, content }, functionCalled: true };
48519
+ };
48419
48520
  for (let i = 0;i < maxChatCompletions; ++i) {
48420
48521
  const chatCompletion = await this._createChatCompletion(client, {
48421
48522
  ...restParams,
@@ -48428,38 +48529,32 @@ var init_AbstractChatCompletionRunner = __esm(() => {
48428
48529
  throw new OpenAIError(`missing message in ChatCompletion response`);
48429
48530
  }
48430
48531
  if (!message.tool_calls?.length) {
48532
+ await afterCompletion?.(chatCompletion, runner);
48431
48533
  return;
48432
48534
  }
48433
- for (const tool_call of message.tool_calls) {
48434
- if (tool_call.type !== "function")
48435
- continue;
48436
- const tool_call_id = tool_call.id;
48437
- const { name, arguments: args } = tool_call.function;
48438
- const fn = functionsByName[name];
48439
- if (!fn) {
48440
- const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName).map((name2) => JSON.stringify(name2)).join(", ")}. Please try again`;
48441
- this._addMessage({ role, tool_call_id, content: content2 });
48442
- continue;
48443
- } else if (singleFunctionToCall && singleFunctionToCall !== name) {
48444
- const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;
48445
- this._addMessage({ role, tool_call_id, content: content2 });
48446
- continue;
48447
- }
48448
- let parsed;
48449
- try {
48450
- parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;
48451
- } catch (error54) {
48452
- const content2 = error54 instanceof Error ? error54.message : String(error54);
48453
- this._addMessage({ role, tool_call_id, content: content2 });
48454
- continue;
48535
+ if (singleFunctionToCall || params.parallel_tool_calls === false) {
48536
+ for (const toolCall of message.tool_calls) {
48537
+ const result = await runToolCall(toolCall);
48538
+ if (result.message)
48539
+ this._addMessage(result.message);
48540
+ if (singleFunctionToCall && result.functionCalled) {
48541
+ await afterCompletion?.(chatCompletion, runner);
48542
+ return;
48543
+ }
48455
48544
  }
48456
- const rawContent = await fn.function(parsed, this);
48457
- const content = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);
48458
- this._addMessage({ role, tool_call_id, content });
48459
- if (singleFunctionToCall) {
48460
- return;
48545
+ } else {
48546
+ const results = await Promise.allSettled(message.tool_calls.map(runToolCall));
48547
+ for (const result of results) {
48548
+ if (result.status === "rejected")
48549
+ throw result.reason;
48550
+ }
48551
+ for (const result of results) {
48552
+ if (result.status === "fulfilled" && result.value.message) {
48553
+ this._addMessage(result.value.message);
48554
+ }
48461
48555
  }
48462
48556
  }
48557
+ await afterCompletion?.(chatCompletion, runner);
48463
48558
  }
48464
48559
  return;
48465
48560
  }
@@ -48535,7 +48630,7 @@ var init_ChatCompletionRunner = __esm(() => {
48535
48630
  ...options,
48536
48631
  headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
48537
48632
  };
48538
- runner._run(() => runner._runTools(client, params, opts));
48633
+ runner._run(() => runner._runTools(client, params, runner, opts));
48539
48634
  return runner;
48540
48635
  }
48541
48636
  _addMessage(message, emit = true) {
@@ -48882,12 +48977,7 @@ var init_ChatCompletionStream = __esm(() => {
48882
48977
  }
48883
48978
  async _createChatCompletion(client, params, options) {
48884
48979
  super._createChatCompletion;
48885
- const signal = options?.signal;
48886
- if (signal) {
48887
- if (signal.aborted)
48888
- this.controller.abort();
48889
- signal.addEventListener("abort", () => this.controller.abort());
48890
- }
48980
+ this._listenForAbort(options?.signal);
48891
48981
  __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
48892
48982
  const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });
48893
48983
  this._connected();
@@ -48900,12 +48990,7 @@ var init_ChatCompletionStream = __esm(() => {
48900
48990
  return this._addChatCompletion(__classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this));
48901
48991
  }
48902
48992
  async _fromReadableStream(readableStream, options) {
48903
- const signal = options?.signal;
48904
- if (signal) {
48905
- if (signal.aborted)
48906
- this.controller.abort();
48907
- signal.addEventListener("abort", () => this.controller.abort());
48908
- }
48993
+ this._listenForAbort(options?.signal);
48909
48994
  __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this);
48910
48995
  this._connected();
48911
48996
  const stream = Stream4.fromReadableStream(readableStream, this.controller);
@@ -49141,7 +49226,7 @@ var init_ChatCompletionStream = __esm(() => {
49141
49226
  if (content) {
49142
49227
  choice.message.content = (choice.message.content || "") + content;
49143
49228
  if (!choice.message.refusal && __classPrivateFieldGet2(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {
49144
- choice.message.parsed = partialParse2(choice.message.content);
49229
+ choice.message.parsed = choice.message.content.trim() ? partialParse2(choice.message.content) : null;
49145
49230
  }
49146
49231
  }
49147
49232
  if (tool_calls) {
@@ -49241,7 +49326,7 @@ var init_ChatCompletionStreamingRunner = __esm(() => {
49241
49326
  ...options,
49242
49327
  headers: { ...options?.headers, "X-Stainless-Helper-Method": "runTools" }
49243
49328
  };
49244
- runner._run(() => runner._runTools(client, params, opts));
49329
+ runner._run(() => runner._runTools(client, params, runner, opts));
49245
49330
  return runner;
49246
49331
  }
49247
49332
  };
@@ -50975,12 +51060,7 @@ var init_AssistantStream = __esm(() => {
50975
51060
  return runner;
50976
51061
  }
50977
51062
  async _fromReadableStream(readableStream, options) {
50978
- const signal = options?.signal;
50979
- if (signal) {
50980
- if (signal.aborted)
50981
- this.controller.abort();
50982
- signal.addEventListener("abort", () => this.controller.abort());
50983
- }
51063
+ this._listenForAbort(options?.signal);
50984
51064
  this._connected();
50985
51065
  const stream = Stream4.fromReadableStream(readableStream, this.controller);
50986
51066
  for await (const event of stream) {
@@ -51004,12 +51084,7 @@ var init_AssistantStream = __esm(() => {
51004
51084
  return runner;
51005
51085
  }
51006
51086
  async _createToolAssistantStream(run, runId, params, options) {
51007
- const signal = options?.signal;
51008
- if (signal) {
51009
- if (signal.aborted)
51010
- this.controller.abort();
51011
- signal.addEventListener("abort", () => this.controller.abort());
51012
- }
51087
+ this._listenForAbort(options?.signal);
51013
51088
  const body = { ...params, stream: true };
51014
51089
  const stream = await run.submitToolOutputs(runId, body, {
51015
51090
  ...options,
@@ -51067,12 +51142,7 @@ var init_AssistantStream = __esm(() => {
51067
51142
  return __classPrivateFieldGet2(this, _AssistantStream_finalRun, "f");
51068
51143
  }
51069
51144
  async _createThreadAssistantStream(thread, params, options) {
51070
- const signal = options?.signal;
51071
- if (signal) {
51072
- if (signal.aborted)
51073
- this.controller.abort();
51074
- signal.addEventListener("abort", () => this.controller.abort());
51075
- }
51145
+ this._listenForAbort(options?.signal);
51076
51146
  const body = { ...params, stream: true };
51077
51147
  const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });
51078
51148
  this._connected();
@@ -51085,12 +51155,7 @@ var init_AssistantStream = __esm(() => {
51085
51155
  return this._addRun(__classPrivateFieldGet2(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this));
51086
51156
  }
51087
51157
  async _createAssistantStream(run, threadId, params, options) {
51088
- const signal = options?.signal;
51089
- if (signal) {
51090
- if (signal.aborted)
51091
- this.controller.abort();
51092
- signal.addEventListener("abort", () => this.controller.abort());
51093
- }
51158
+ this._listenForAbort(options?.signal);
51094
51159
  const body = { ...params, stream: true };
51095
51160
  const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });
51096
51161
  this._connected();
@@ -52343,7 +52408,7 @@ var init_realtime2 = __esm(() => {
52343
52408
  // node_modules/openai/lib/ResponsesParser.mjs
52344
52409
  function maybeParseResponse(response, params) {
52345
52410
  if (!params || !hasAutoParseableInput2(params)) {
52346
- return {
52411
+ const parsed = {
52347
52412
  ...response,
52348
52413
  output_parsed: null,
52349
52414
  output: response.output.map((item) => {
@@ -52366,15 +52431,20 @@ function maybeParseResponse(response, params) {
52366
52431
  }
52367
52432
  })
52368
52433
  };
52434
+ if (needsOutputText(response, parsed)) {
52435
+ addOutputText(parsed);
52436
+ }
52437
+ return parsed;
52369
52438
  }
52370
52439
  return parseResponse(response, params);
52371
52440
  }
52372
52441
  function parseResponse(response, params) {
52442
+ const shouldParse = !response.status || response.status === "completed";
52373
52443
  const output = response.output.map((item) => {
52374
52444
  if (item.type === "function_call") {
52375
52445
  return {
52376
52446
  ...item,
52377
- parsed_arguments: parseToolCall2(params, item)
52447
+ parsed_arguments: shouldParse ? parseToolCall2(params, item) : null
52378
52448
  };
52379
52449
  }
52380
52450
  if (item.type === "message") {
@@ -52382,7 +52452,7 @@ function parseResponse(response, params) {
52382
52452
  if (content2.type === "output_text") {
52383
52453
  return {
52384
52454
  ...content2,
52385
- parsed: parseTextFormat(params, content2.text)
52455
+ parsed: shouldParse ? parseTextFormat(params, content2.text) : null
52386
52456
  };
52387
52457
  }
52388
52458
  return content2;
@@ -52395,7 +52465,7 @@ function parseResponse(response, params) {
52395
52465
  return item;
52396
52466
  });
52397
52467
  const parsed = Object.assign({}, response, { output });
52398
- if (!Object.getOwnPropertyDescriptor(response, "output_text")) {
52468
+ if (needsOutputText(response, parsed)) {
52399
52469
  addOutputText(parsed);
52400
52470
  }
52401
52471
  Object.defineProperty(parsed, "output_parsed", {
@@ -52446,6 +52516,9 @@ function parseToolCall2(params, toolCall) {
52446
52516
  parsed_arguments: isAutoParsableTool2(inputTool) ? inputTool.$parseRaw(toolCall.arguments) : inputTool?.strict ? JSON.parse(toolCall.arguments) : null
52447
52517
  };
52448
52518
  }
52519
+ function needsOutputText(response, target) {
52520
+ return !Object.getOwnPropertyDescriptor(response, "output_text") || target.output_text == null;
52521
+ }
52449
52522
  function addOutputText(rsp) {
52450
52523
  const texts = [];
52451
52524
  for (const output of rsp.output) {
@@ -52465,15 +52538,408 @@ var init_ResponsesParser = __esm(() => {
52465
52538
  init_parser3();
52466
52539
  });
52467
52540
 
52541
+ // node_modules/openai/lib/responses/ResponseAccumulator.mjs
52542
+ function accumulateResponse(event, snapshot) {
52543
+ if (!snapshot) {
52544
+ if (event.type !== "response.created") {
52545
+ throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
52546
+ }
52547
+ return cloneResponse(event.response);
52548
+ }
52549
+ switch (event.type) {
52550
+ case "response.output_item.added": {
52551
+ snapshot.output.push(structuredClone(event.item));
52552
+ if (event.item.type === "message") {
52553
+ addOutputText(snapshot);
52554
+ }
52555
+ break;
52556
+ }
52557
+ case "response.output_item.done": {
52558
+ getOutput(snapshot, event.output_index);
52559
+ snapshot.output[event.output_index] = structuredClone(event.item);
52560
+ if (event.item.type === "message") {
52561
+ addOutputText(snapshot);
52562
+ }
52563
+ break;
52564
+ }
52565
+ case "response.content_part.added": {
52566
+ const output = getOutput(snapshot, event.output_index);
52567
+ const type = output.type;
52568
+ const part = event.part;
52569
+ if (type === "message" && part.type !== "reasoning_text") {
52570
+ output.content.push(structuredClone(part));
52571
+ if (part.type === "output_text") {
52572
+ addOutputText(snapshot);
52573
+ }
52574
+ } else if (type === "reasoning" && part.type === "reasoning_text") {
52575
+ if (!output.content) {
52576
+ output.content = [];
52577
+ }
52578
+ output.content.push(structuredClone(part));
52579
+ }
52580
+ break;
52581
+ }
52582
+ case "response.content_part.done": {
52583
+ const output = getOutput(snapshot, event.output_index);
52584
+ const part = event.part;
52585
+ if (output.type === "message" && part.type !== "reasoning_text") {
52586
+ getContent(output.content, event.content_index);
52587
+ output.content[event.content_index] = structuredClone(part);
52588
+ if (part.type === "output_text") {
52589
+ addOutputText(snapshot);
52590
+ }
52591
+ } else if (output.type === "reasoning" && part.type === "reasoning_text") {
52592
+ const content = output.content;
52593
+ if (!content) {
52594
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
52595
+ }
52596
+ getContent(content, event.content_index);
52597
+ content[event.content_index] = structuredClone(part);
52598
+ }
52599
+ break;
52600
+ }
52601
+ case "response.output_text.delta": {
52602
+ const output = getOutput(snapshot, event.output_index);
52603
+ if (output.type === "message") {
52604
+ const content = getContent(output.content, event.content_index);
52605
+ if (content.type !== "output_text") {
52606
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
52607
+ }
52608
+ content.text += event.delta;
52609
+ snapshot.output_text += event.delta;
52610
+ }
52611
+ break;
52612
+ }
52613
+ case "response.output_text.done": {
52614
+ const output = getOutput(snapshot, event.output_index);
52615
+ if (output.type === "message") {
52616
+ const content = getContent(output.content, event.content_index);
52617
+ if (content.type !== "output_text") {
52618
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
52619
+ }
52620
+ content.text = event.text;
52621
+ addOutputText(snapshot);
52622
+ }
52623
+ break;
52624
+ }
52625
+ case "response.output_text.annotation.added": {
52626
+ const output = getOutput(snapshot, event.output_index);
52627
+ if (output.type === "message") {
52628
+ const content = getContent(output.content, event.content_index);
52629
+ if (content.type !== "output_text") {
52630
+ throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
52631
+ }
52632
+ content.annotations[event.annotation_index] = structuredClone(event.annotation);
52633
+ }
52634
+ break;
52635
+ }
52636
+ case "response.refusal.delta": {
52637
+ const output = getOutput(snapshot, event.output_index);
52638
+ if (output.type === "message") {
52639
+ const content = getContent(output.content, event.content_index);
52640
+ if (content.type !== "refusal") {
52641
+ throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
52642
+ }
52643
+ content.refusal += event.delta;
52644
+ }
52645
+ break;
52646
+ }
52647
+ case "response.refusal.done": {
52648
+ const output = getOutput(snapshot, event.output_index);
52649
+ if (output.type === "message") {
52650
+ const content = getContent(output.content, event.content_index);
52651
+ if (content.type !== "refusal") {
52652
+ throw new OpenAIError(`expected content to be 'refusal', got ${content.type}`);
52653
+ }
52654
+ content.refusal = event.refusal;
52655
+ }
52656
+ break;
52657
+ }
52658
+ case "response.function_call_arguments.delta": {
52659
+ const output = getOutput(snapshot, event.output_index);
52660
+ if (output.type === "function_call") {
52661
+ output.arguments += event.delta;
52662
+ }
52663
+ break;
52664
+ }
52665
+ case "response.function_call_arguments.done": {
52666
+ const output = getOutput(snapshot, event.output_index);
52667
+ if (output.type === "function_call") {
52668
+ output.arguments = event.arguments;
52669
+ }
52670
+ break;
52671
+ }
52672
+ case "response.reasoning_text.delta": {
52673
+ const output = getOutput(snapshot, event.output_index);
52674
+ if (output.type === "reasoning") {
52675
+ if (!output.content) {
52676
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
52677
+ }
52678
+ const content = getContent(output.content, event.content_index);
52679
+ if (content.type !== "reasoning_text") {
52680
+ throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
52681
+ }
52682
+ content.text += event.delta;
52683
+ }
52684
+ break;
52685
+ }
52686
+ case "response.reasoning_text.done": {
52687
+ const output = getOutput(snapshot, event.output_index);
52688
+ if (output.type === "reasoning") {
52689
+ if (!output.content) {
52690
+ throw new OpenAIError(`missing content at index ${event.content_index}`);
52691
+ }
52692
+ const content = getContent(output.content, event.content_index);
52693
+ if (content.type !== "reasoning_text") {
52694
+ throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
52695
+ }
52696
+ content.text = event.text;
52697
+ }
52698
+ break;
52699
+ }
52700
+ case "response.reasoning_summary_part.added": {
52701
+ const output = getOutput(snapshot, event.output_index);
52702
+ if (output.type === "reasoning") {
52703
+ output.summary.push(structuredClone(event.part));
52704
+ }
52705
+ break;
52706
+ }
52707
+ case "response.reasoning_summary_part.done": {
52708
+ const output = getOutput(snapshot, event.output_index);
52709
+ if (output.type === "reasoning") {
52710
+ getContent(output.summary, event.summary_index);
52711
+ output.summary[event.summary_index] = structuredClone(event.part);
52712
+ }
52713
+ break;
52714
+ }
52715
+ case "response.reasoning_summary_text.delta": {
52716
+ const output = getOutput(snapshot, event.output_index);
52717
+ if (output.type === "reasoning") {
52718
+ const part = getContent(output.summary, event.summary_index);
52719
+ part.text += event.delta;
52720
+ }
52721
+ break;
52722
+ }
52723
+ case "response.reasoning_summary_text.done": {
52724
+ const output = getOutput(snapshot, event.output_index);
52725
+ if (output.type === "reasoning") {
52726
+ const part = getContent(output.summary, event.summary_index);
52727
+ part.text = event.text;
52728
+ }
52729
+ break;
52730
+ }
52731
+ case "response.custom_tool_call_input.delta": {
52732
+ const output = getOutput(snapshot, event.output_index);
52733
+ if (output.type === "custom_tool_call") {
52734
+ output.input += event.delta;
52735
+ }
52736
+ break;
52737
+ }
52738
+ case "response.custom_tool_call_input.done": {
52739
+ const output = getOutput(snapshot, event.output_index);
52740
+ if (output.type === "custom_tool_call") {
52741
+ output.input = event.input;
52742
+ }
52743
+ break;
52744
+ }
52745
+ case "response.mcp_call_arguments.delta": {
52746
+ const output = getOutput(snapshot, event.output_index);
52747
+ if (output.type === "mcp_call") {
52748
+ output.arguments += event.delta;
52749
+ }
52750
+ break;
52751
+ }
52752
+ case "response.mcp_call_arguments.done": {
52753
+ const output = getOutput(snapshot, event.output_index);
52754
+ if (output.type === "mcp_call") {
52755
+ output.arguments = event.arguments;
52756
+ }
52757
+ break;
52758
+ }
52759
+ case "response.code_interpreter_call_code.delta": {
52760
+ const output = getOutput(snapshot, event.output_index);
52761
+ if (output.type === "code_interpreter_call") {
52762
+ output.code = (output.code ?? "") + event.delta;
52763
+ }
52764
+ break;
52765
+ }
52766
+ case "response.code_interpreter_call_code.done": {
52767
+ const output = getOutput(snapshot, event.output_index);
52768
+ if (output.type === "code_interpreter_call") {
52769
+ output.code = event.code;
52770
+ }
52771
+ break;
52772
+ }
52773
+ case "response.code_interpreter_call.in_progress": {
52774
+ const output = getOutput(snapshot, event.output_index);
52775
+ if (output.type === "code_interpreter_call") {
52776
+ output.status = "in_progress";
52777
+ }
52778
+ break;
52779
+ }
52780
+ case "response.code_interpreter_call.interpreting": {
52781
+ const output = getOutput(snapshot, event.output_index);
52782
+ if (output.type === "code_interpreter_call") {
52783
+ output.status = "interpreting";
52784
+ }
52785
+ break;
52786
+ }
52787
+ case "response.code_interpreter_call.completed": {
52788
+ const output = getOutput(snapshot, event.output_index);
52789
+ if (output.type === "code_interpreter_call") {
52790
+ output.status = "completed";
52791
+ }
52792
+ break;
52793
+ }
52794
+ case "response.file_search_call.in_progress": {
52795
+ const output = getOutput(snapshot, event.output_index);
52796
+ if (output.type === "file_search_call") {
52797
+ output.status = "in_progress";
52798
+ }
52799
+ break;
52800
+ }
52801
+ case "response.file_search_call.searching": {
52802
+ const output = getOutput(snapshot, event.output_index);
52803
+ if (output.type === "file_search_call") {
52804
+ output.status = "searching";
52805
+ }
52806
+ break;
52807
+ }
52808
+ case "response.file_search_call.completed": {
52809
+ const output = getOutput(snapshot, event.output_index);
52810
+ if (output.type === "file_search_call") {
52811
+ output.status = "completed";
52812
+ }
52813
+ break;
52814
+ }
52815
+ case "response.web_search_call.in_progress": {
52816
+ const output = getOutput(snapshot, event.output_index);
52817
+ if (output.type === "web_search_call") {
52818
+ output.status = "in_progress";
52819
+ }
52820
+ break;
52821
+ }
52822
+ case "response.web_search_call.searching": {
52823
+ const output = getOutput(snapshot, event.output_index);
52824
+ if (output.type === "web_search_call") {
52825
+ output.status = "searching";
52826
+ }
52827
+ break;
52828
+ }
52829
+ case "response.web_search_call.completed": {
52830
+ const output = getOutput(snapshot, event.output_index);
52831
+ if (output.type === "web_search_call") {
52832
+ output.status = "completed";
52833
+ }
52834
+ break;
52835
+ }
52836
+ case "response.image_generation_call.in_progress": {
52837
+ const output = getOutput(snapshot, event.output_index);
52838
+ if (output.type === "image_generation_call") {
52839
+ output.status = "in_progress";
52840
+ }
52841
+ break;
52842
+ }
52843
+ case "response.image_generation_call.generating": {
52844
+ const output = getOutput(snapshot, event.output_index);
52845
+ if (output.type === "image_generation_call") {
52846
+ output.status = "generating";
52847
+ }
52848
+ break;
52849
+ }
52850
+ case "response.image_generation_call.completed": {
52851
+ const output = getOutput(snapshot, event.output_index);
52852
+ if (output.type === "image_generation_call") {
52853
+ output.status = "completed";
52854
+ }
52855
+ break;
52856
+ }
52857
+ case "response.mcp_call.in_progress": {
52858
+ const output = getOutput(snapshot, event.output_index);
52859
+ if (output.type === "mcp_call") {
52860
+ output.status = "in_progress";
52861
+ }
52862
+ break;
52863
+ }
52864
+ case "response.mcp_call.completed": {
52865
+ const output = getOutput(snapshot, event.output_index);
52866
+ if (output.type === "mcp_call") {
52867
+ output.status = "completed";
52868
+ }
52869
+ break;
52870
+ }
52871
+ case "response.mcp_call.failed": {
52872
+ const output = getOutput(snapshot, event.output_index);
52873
+ if (output.type === "mcp_call") {
52874
+ output.status = "failed";
52875
+ }
52876
+ break;
52877
+ }
52878
+ case "response.created":
52879
+ case "response.queued":
52880
+ case "response.in_progress":
52881
+ case "response.completed":
52882
+ case "response.failed":
52883
+ case "response.incomplete": {
52884
+ snapshot = cloneResponse(event.response);
52885
+ break;
52886
+ }
52887
+ case "response.audio.delta":
52888
+ case "response.audio.done":
52889
+ case "response.audio.transcript.delta":
52890
+ case "response.audio.transcript.done":
52891
+ case "response.image_generation_call.partial_image":
52892
+ case "response.mcp_list_tools.in_progress":
52893
+ case "response.mcp_list_tools.completed":
52894
+ case "response.mcp_list_tools.failed":
52895
+ case "error": {
52896
+ break;
52897
+ }
52898
+ default: {
52899
+ assertNever4(event);
52900
+ }
52901
+ }
52902
+ return snapshot;
52903
+ }
52904
+ function cloneResponse(response) {
52905
+ const snapshot = structuredClone(response);
52906
+ if (!Object.getOwnPropertyDescriptor(snapshot, "output_text") || snapshot.output_text == null) {
52907
+ addOutputText(snapshot);
52908
+ }
52909
+ return snapshot;
52910
+ }
52911
+ function getOutput(snapshot, outputIndex) {
52912
+ const output = snapshot.output[outputIndex];
52913
+ if (!output) {
52914
+ throw new OpenAIError(`missing output at index ${outputIndex}`);
52915
+ }
52916
+ return output;
52917
+ }
52918
+ function getContent(content, contentIndex) {
52919
+ const part = content[contentIndex];
52920
+ if (!part) {
52921
+ throw new OpenAIError(`missing content at index ${contentIndex}`);
52922
+ }
52923
+ return part;
52924
+ }
52925
+ function assertNever4(value2) {
52926
+ throw new OpenAIError(`Unhandled response stream event: ${JSON.stringify(value2)}`);
52927
+ }
52928
+ var init_ResponseAccumulator = __esm(() => {
52929
+ init_error4();
52930
+ init_ResponsesParser();
52931
+ });
52932
+
52468
52933
  // node_modules/openai/lib/responses/ResponseStream.mjs
52469
52934
  function finalizeResponse(snapshot, params) {
52470
52935
  return maybeParseResponse(snapshot, params);
52471
52936
  }
52472
- var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse, ResponseStream;
52937
+ var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, ResponseStream;
52473
52938
  var init_ResponseStream = __esm(() => {
52474
52939
  init_tslib2();
52475
52940
  init_error4();
52476
52941
  init_EventStream();
52942
+ init_ResponseAccumulator();
52477
52943
  init_ResponsesParser();
52478
52944
  ResponseStream = class ResponseStream extends EventStream {
52479
52945
  constructor(params) {
@@ -52493,12 +52959,7 @@ var init_ResponseStream = __esm(() => {
52493
52959
  return runner;
52494
52960
  }
52495
52961
  async _createOrRetrieveResponse(client, params, options) {
52496
- const signal = options?.signal;
52497
- if (signal) {
52498
- if (signal.aborted)
52499
- this.controller.abort();
52500
- signal.addEventListener("abort", () => this.controller.abort());
52501
- }
52962
+ this._listenForAbort(options?.signal);
52502
52963
  __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this);
52503
52964
  let stream;
52504
52965
  let starting_after = null;
@@ -52529,7 +52990,8 @@ var init_ResponseStream = __esm(() => {
52529
52990
  this._emit(name, event2);
52530
52991
  }
52531
52992
  };
52532
- const response = __classPrivateFieldGet2(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event);
52993
+ const response = accumulateResponse(event, __classPrivateFieldGet2(this, _ResponseStream_currentResponseSnapshot, "f"));
52994
+ __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, response, "f");
52533
52995
  maybeEmit("event", event);
52534
52996
  switch (event.type) {
52535
52997
  case "response.output_text.delta": {
@@ -52581,87 +53043,6 @@ var init_ResponseStream = __esm(() => {
52581
53043
  const parsedResponse = finalizeResponse(snapshot, __classPrivateFieldGet2(this, _ResponseStream_params, "f"));
52582
53044
  __classPrivateFieldSet2(this, _ResponseStream_finalResponse, parsedResponse, "f");
52583
53045
  return parsedResponse;
52584
- }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse2(event) {
52585
- let snapshot = __classPrivateFieldGet2(this, _ResponseStream_currentResponseSnapshot, "f");
52586
- if (!snapshot) {
52587
- if (event.type !== "response.created") {
52588
- throw new OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`);
52589
- }
52590
- snapshot = __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
52591
- return snapshot;
52592
- }
52593
- switch (event.type) {
52594
- case "response.output_item.added": {
52595
- snapshot.output.push(event.item);
52596
- break;
52597
- }
52598
- case "response.content_part.added": {
52599
- const output = snapshot.output[event.output_index];
52600
- if (!output) {
52601
- throw new OpenAIError(`missing output at index ${event.output_index}`);
52602
- }
52603
- const type = output.type;
52604
- const part = event.part;
52605
- if (type === "message" && part.type !== "reasoning_text") {
52606
- output.content.push(part);
52607
- } else if (type === "reasoning" && part.type === "reasoning_text") {
52608
- if (!output.content) {
52609
- output.content = [];
52610
- }
52611
- output.content.push(part);
52612
- }
52613
- break;
52614
- }
52615
- case "response.output_text.delta": {
52616
- const output = snapshot.output[event.output_index];
52617
- if (!output) {
52618
- throw new OpenAIError(`missing output at index ${event.output_index}`);
52619
- }
52620
- if (output.type === "message") {
52621
- const content = output.content[event.content_index];
52622
- if (!content) {
52623
- throw new OpenAIError(`missing content at index ${event.content_index}`);
52624
- }
52625
- if (content.type !== "output_text") {
52626
- throw new OpenAIError(`expected content to be 'output_text', got ${content.type}`);
52627
- }
52628
- content.text += event.delta;
52629
- }
52630
- break;
52631
- }
52632
- case "response.function_call_arguments.delta": {
52633
- const output = snapshot.output[event.output_index];
52634
- if (!output) {
52635
- throw new OpenAIError(`missing output at index ${event.output_index}`);
52636
- }
52637
- if (output.type === "function_call") {
52638
- output.arguments += event.delta;
52639
- }
52640
- break;
52641
- }
52642
- case "response.reasoning_text.delta": {
52643
- const output = snapshot.output[event.output_index];
52644
- if (!output) {
52645
- throw new OpenAIError(`missing output at index ${event.output_index}`);
52646
- }
52647
- if (output.type === "reasoning") {
52648
- const content = output.content?.[event.content_index];
52649
- if (!content) {
52650
- throw new OpenAIError(`missing content at index ${event.content_index}`);
52651
- }
52652
- if (content.type !== "reasoning_text") {
52653
- throw new OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`);
52654
- }
52655
- content.text += event.delta;
52656
- }
52657
- break;
52658
- }
52659
- case "response.completed": {
52660
- __classPrivateFieldSet2(this, _ResponseStream_currentResponseSnapshot, event.response, "f");
52661
- break;
52662
- }
52663
- }
52664
- return snapshot;
52665
53046
  }, Symbol.asyncIterator)]() {
52666
53047
  const pushQueue = [];
52667
53048
  const readQueue = [];
@@ -53440,9 +53821,28 @@ var init_resources3 = __esm(() => {
53440
53821
  init_shared2();
53441
53822
  });
53442
53823
 
53824
+ // node_modules/openai/internal/provider.mjs
53825
+ function configureProvider(provider) {
53826
+ const definition = providerDefinitions.get(provider);
53827
+ if (!definition) {
53828
+ throw new Error("Invalid provider. Providers must be created with createProvider().");
53829
+ }
53830
+ return definition.configure();
53831
+ }
53832
+ var providerDefinitionsKey, providerGlobal, existingProviderDefinitions, providerDefinitions;
53833
+ var init_provider = __esm(() => {
53834
+ providerDefinitionsKey = Symbol.for("openai.node.providerDefinitions.v1");
53835
+ providerGlobal = globalThis;
53836
+ existingProviderDefinitions = providerGlobal[providerDefinitionsKey];
53837
+ providerDefinitions = existingProviderDefinitions ?? new WeakMap;
53838
+ if (!existingProviderDefinitions) {
53839
+ Object.defineProperty(providerGlobal, providerDefinitionsKey, { value: providerDefinitions });
53840
+ }
53841
+ });
53842
+
53443
53843
  // node_modules/openai/client.mjs
53444
53844
  class OpenAI {
53445
- constructor({ baseURL = readEnv2("OPENAI_BASE_URL"), apiKey = readEnv2("OPENAI_API_KEY") ?? null, adminAPIKey = readEnv2("OPENAI_ADMIN_KEY") ?? null, organization = readEnv2("OPENAI_ORG_ID") ?? null, project = readEnv2("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv2("OPENAI_WEBHOOK_SECRET") ?? null, workloadIdentity, ...opts } = {}) {
53845
+ constructor(clientOptions = {}) {
53446
53846
  _OpenAI_instances.add(this);
53447
53847
  _OpenAI_encoder.set(this, undefined);
53448
53848
  this.completions = new Completions3(this);
@@ -53468,6 +53868,15 @@ class OpenAI {
53468
53868
  this.containers = new Containers(this);
53469
53869
  this.skills = new Skills2(this);
53470
53870
  this.videos = new Videos(this);
53871
+ const provider = clientOptions.provider;
53872
+ if (provider) {
53873
+ const conflictingOptions = ["apiKey", "adminAPIKey", "workloadIdentity", "baseURL"].filter((key) => clientOptions[key] != null);
53874
+ if (conflictingOptions.length) {
53875
+ throw new OpenAIError(`The \`provider\` option cannot be used with ${conflictingOptions.map((key) => `\`${key}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`);
53876
+ }
53877
+ }
53878
+ const { baseURL = provider ? null : readEnv2("OPENAI_BASE_URL"), apiKey = provider ? null : readEnv2("OPENAI_API_KEY") ?? null, adminAPIKey = provider ? null : readEnv2("OPENAI_ADMIN_KEY") ?? null, organization = provider ? null : readEnv2("OPENAI_ORG_ID") ?? null, project = provider ? null : readEnv2("OPENAI_PROJECT_ID") ?? null, webhookSecret = readEnv2("OPENAI_WEBHOOK_SECRET") ?? null, workloadIdentity, ...opts } = clientOptions;
53879
+ const providerRuntime = provider ? configureProvider(provider) : undefined;
53471
53880
  const options = {
53472
53881
  apiKey,
53473
53882
  adminAPIKey,
@@ -53475,13 +53884,14 @@ class OpenAI {
53475
53884
  project,
53476
53885
  webhookSecret,
53477
53886
  workloadIdentity,
53887
+ provider,
53478
53888
  ...opts,
53479
- baseURL: baseURL || `https://api.openai.com/v1`
53889
+ baseURL: providerRuntime?.baseURL ?? (baseURL || `https://api.openai.com/v1`)
53480
53890
  };
53481
53891
  if (apiKey && workloadIdentity) {
53482
53892
  throw new OpenAIError("The `apiKey` and `workloadIdentity` options are mutually exclusive");
53483
53893
  }
53484
- if (!apiKey && !adminAPIKey && !workloadIdentity) {
53894
+ if (!providerRuntime && !apiKey && !adminAPIKey && !workloadIdentity) {
53485
53895
  throw new OpenAIError("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");
53486
53896
  }
53487
53897
  if (!options.dangerouslyAllowBrowser && isRunningInBrowser2()) {
@@ -53506,7 +53916,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
53506
53916
  this.maxRetries = options.maxRetries ?? 2;
53507
53917
  this.fetch = options.fetch ?? getDefaultFetch2();
53508
53918
  __classPrivateFieldSet2(this, _OpenAI_encoder, FallbackEncoder2, "f");
53509
- const customHeadersEnv = readEnv2("OPENAI_CUSTOM_HEADERS");
53919
+ const customHeadersEnv = provider ? undefined : readEnv2("OPENAI_CUSTOM_HEADERS");
53510
53920
  if (customHeadersEnv) {
53511
53921
  const parsed = {};
53512
53922
  for (const line of customHeadersEnv.split(`
@@ -53519,6 +53929,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
53519
53929
  options.defaultHeaders = buildHeaders2([parsed, options.defaultHeaders]);
53520
53930
  }
53521
53931
  this._options = options;
53932
+ this._provider = providerRuntime;
53522
53933
  if (workloadIdentity) {
53523
53934
  this._workloadIdentityAuth = new WorkloadIdentityAuth(workloadIdentity, this.fetch);
53524
53935
  }
@@ -53529,7 +53940,9 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
53529
53940
  this.webhookSecret = webhookSecret;
53530
53941
  }
53531
53942
  withOptions(options) {
53532
- const client = new this.constructor({
53943
+ const inheritedProvider = this._options.provider;
53944
+ const provider = options.provider ?? inheritedProvider;
53945
+ const inheritedOptions = {
53533
53946
  ...this._options,
53534
53947
  baseURL: this.baseURL,
53535
53948
  maxRetries: this.maxRetries,
@@ -53543,8 +53956,23 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
53543
53956
  workloadIdentity: this._options.workloadIdentity,
53544
53957
  organization: this.organization,
53545
53958
  project: this.project,
53546
- webhookSecret: this.webhookSecret,
53547
- ...options
53959
+ webhookSecret: this.webhookSecret
53960
+ };
53961
+ if (provider) {
53962
+ delete inheritedOptions.apiKey;
53963
+ delete inheritedOptions.adminAPIKey;
53964
+ delete inheritedOptions.workloadIdentity;
53965
+ delete inheritedOptions.baseURL;
53966
+ if (provider !== inheritedProvider) {
53967
+ delete inheritedOptions.organization;
53968
+ delete inheritedOptions.project;
53969
+ delete inheritedOptions.defaultHeaders;
53970
+ }
53971
+ }
53972
+ const client = new this.constructor({
53973
+ ...inheritedOptions,
53974
+ ...options,
53975
+ provider
53548
53976
  });
53549
53977
  return client;
53550
53978
  }
@@ -53603,6 +54031,8 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
53603
54031
  return APIError2.generate(status, error54, message, headers);
53604
54032
  }
53605
54033
  async _callApiKey() {
54034
+ if (this._provider)
54035
+ return false;
53606
54036
  const apiKey = this._options.apiKey;
53607
54037
  if (typeof apiKey !== "function")
53608
54038
  return false;
@@ -53634,6 +54064,8 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
53634
54064
  return url2.toString();
53635
54065
  }
53636
54066
  async prepareOptions(options) {
54067
+ if (this._provider)
54068
+ return;
53637
54069
  const security = options.__security ?? { bearerAuth: true };
53638
54070
  if (security.bearerAuth) {
53639
54071
  await this._callApiKey();
@@ -53674,6 +54106,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
53674
54106
  retryCount: maxRetries - retriesRemaining
53675
54107
  });
53676
54108
  await this.prepareRequest(req, { url: url2, options });
54109
+ await this._provider?.prepareRequest?.(req, { url: url2, options });
53677
54110
  const requestLogID = "log_" + (Math.random() * (1 << 24) | 0).toString(16).padStart(6, "0");
53678
54111
  const retryLogStr = retryOfRequestLogID === undefined ? "" : `, retryOf: ${retryOfRequestLogID}`;
53679
54112
  const startTime = Date.now();
@@ -53916,19 +54349,25 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
53916
54349
  "OpenAI-Organization": this.organization,
53917
54350
  "OpenAI-Project": this.project
53918
54351
  },
53919
- await this.authHeaders(options, options.__security ?? { bearerAuth: true }),
54352
+ this._provider ? undefined : await this.authHeaders(options, options.__security ?? { bearerAuth: true }),
53920
54353
  this._options.defaultHeaders,
53921
54354
  bodyHeaders,
53922
54355
  options.headers
53923
54356
  ]);
53924
- this.validateHeaders(headers, options.__security ?? { bearerAuth: true });
54357
+ if (!this._provider) {
54358
+ this.validateHeaders(headers, options.__security ?? { bearerAuth: true });
54359
+ }
53925
54360
  return headers.values;
53926
54361
  }
53927
54362
  _makeAbort(controller) {
53928
54363
  return () => controller.abort();
53929
54364
  }
53930
- buildBody({ options: { body, headers: rawHeaders } }) {
54365
+ buildBody({ options }) {
54366
+ const { body, headers: rawHeaders } = options;
53931
54367
  if (!body) {
54368
+ if (body === undefined && "body" in options) {
54369
+ return { ...__classPrivateFieldGet2(this, _OpenAI_encoder, "f").call(this, { body, headers: buildHeaders2([rawHeaders]) }), isStreamingBody: false };
54370
+ }
53932
54371
  return { bodyHeaders: undefined, body: undefined, isStreamingBody: false };
53933
54372
  }
53934
54373
  const headers = buildHeaders2([rawHeaders]);
@@ -54008,10 +54447,11 @@ var init_client2 = __esm(() => {
54008
54447
  init_webhooks2();
54009
54448
  init_detect_platform2();
54010
54449
  init_headers2();
54450
+ init_provider();
54011
54451
  init_log2();
54012
54452
  init_values2();
54013
54453
  _a5 = OpenAI, _OpenAI_encoder = new WeakMap, _OpenAI_instances = new WeakSet, _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden2() {
54014
- return this.baseURL !== "https://api.openai.com/v1";
54454
+ return this._provider !== undefined || this.baseURL !== "https://api.openai.com/v1";
54015
54455
  };
54016
54456
  OpenAI.OpenAI = _a5;
54017
54457
  OpenAI.DEFAULT_TIMEOUT = 600000;
@@ -57314,7 +57754,7 @@ function createRelativePathModifier(basePath = process.cwd()) {
57314
57754
  var init_relative_path_node = () => {};
57315
57755
 
57316
57756
  // node_modules/posthog-node/dist/version.mjs
57317
- var version2 = "5.38.4";
57757
+ var version2 = "5.38.5";
57318
57758
  var init_version2 = () => {};
57319
57759
 
57320
57760
  // node_modules/posthog-node/dist/types.mjs
@@ -59298,6 +59738,7 @@ var init_client3 = __esm(() => {
59298
59738
  try {
59299
59739
  return await super._shutdown(shutdownTimeoutMs);
59300
59740
  } finally {
59741
+ this.distinctIdHasSentFlagCalls = {};
59301
59742
  resolve4?.();
59302
59743
  }
59303
59744
  }