@cydm/pie 4.3.5 → 4.3.7

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 (27) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +4 -4
  2. package/dist/builtin/extensions/cron/index.js +7 -1
  3. package/dist/builtin/extensions/im-forward/index.js +101 -83
  4. package/dist/builtin/extensions/mcp-adapter/index.js +7 -1
  5. package/dist/builtin/extensions/memory/index.js +5 -5
  6. package/dist/builtin/extensions/pie-ipc/index.js +1 -1
  7. package/dist/builtin/extensions/pie-proc/index.js +3 -2
  8. package/dist/builtin/extensions/plan-mode/index.js +4 -4
  9. package/dist/builtin/extensions/subagent/index.js +5 -5
  10. package/dist/builtin/extensions/todo/index.js +4 -4
  11. package/dist/chunks/{chunk-J2LGVYH2.js → chunk-2SAFRLFJ.js} +28 -13
  12. package/dist/chunks/{chunk-JQRZLVPY.js → chunk-6JEYRAQM.js} +1898 -1692
  13. package/dist/chunks/{chunk-NCP264ZE.js → chunk-B4N5LJMD.js} +1 -1
  14. package/dist/chunks/{chunk-PFXSA2LK.js → chunk-BJ4XN5VX.js} +5 -5
  15. package/dist/chunks/{chunk-H5G55G3R.js → chunk-N3BWFAMZ.js} +11 -1
  16. package/dist/chunks/{chunk-QX6WS73C.js → chunk-VHKMWOG3.js} +1 -1
  17. package/dist/chunks/{chunk-PC6HUZAD.js → chunk-WZLO5V2X.js} +3 -3
  18. package/dist/chunks/{chunk-BK36Y35W.js → chunk-XMOWWL4B.js} +2 -2
  19. package/dist/chunks/{concierge-cli-MCHXTFBA.js → manager-cli-QNMCCIFG.js} +322 -44
  20. package/dist/chunks/{model-registry-YA6U366L.js → model-registry-NKE3BRSZ.js} +2 -2
  21. package/dist/chunks/{src-ODLT57PQ.js → src-46R5ZFOU.js} +2 -2
  22. package/dist/chunks/{src-VPMIQGEW.js → src-4EQ7PBEI.js} +3 -3
  23. package/dist/chunks/{src-XSLD2IQ2.js → src-BHIH4VLE.js} +1 -1
  24. package/dist/chunks/{src-AQ4H43UM.js → src-UVULNQOO.js} +4 -4
  25. package/dist/chunks/{test-stream-GIUD5JWS.js → test-stream-FC6ZRENI.js} +1 -1
  26. package/dist/cli.js +347 -208
  27. package/package.json +3 -3
@@ -4535,139 +4535,145 @@ function logEmptyAssistantContentError(error, model, options) {
4535
4535
  });
4536
4536
  }
4537
4537
 
4538
- // ../../packages/ai/src/providers/openai-compat.ts
4539
- var DEFAULT_OPENAI_COMPAT_STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1e3;
4540
- var DEFAULT_OPENAI_COMPAT_FIRST_BYTE_TIMEOUT_MS = 3 * 60 * 1e3;
4541
- var OPENAI_COMPAT_FIRST_BYTE_MAX_ESCALATION_STEPS = 3;
4542
- var openAICompatFirstByteTimeoutsByEndpoint = /* @__PURE__ */ new Map();
4543
- var OPENAI_COMPAT_MAX_DUPLICATE_TOOL_CALLS = 3;
4544
- var OPENAI_COMPAT_PROTOCOL_ERROR_CODE = "provider_response_protocol_error";
4545
- var OpenAICompatProtocolError = class extends Error {
4546
- code = OPENAI_COMPAT_PROTOCOL_ERROR_CODE;
4538
+ // ../../packages/ai/src/providers/responses/responses-wire.ts
4539
+ var RESPONSES_PROTOCOL_ERROR_CODE = "responses_protocol_error";
4540
+ var ResponsesProtocolError = class extends Error {
4541
+ code = RESPONSES_PROTOCOL_ERROR_CODE;
4547
4542
  constructor(message) {
4548
- super(`${OPENAI_COMPAT_PROTOCOL_ERROR_CODE}: ${message}`);
4549
- this.name = "OpenAICompatProtocolError";
4543
+ super(`${RESPONSES_PROTOCOL_ERROR_CODE}: ${message}`);
4544
+ this.name = "ResponsesProtocolError";
4550
4545
  }
4551
4546
  };
4552
- function getOpenAICompatStreamTimeoutMs() {
4553
- const value = Number(process.env.PIE_OPENAI_COMPAT_STREAM_TIMEOUT_MS || "");
4554
- return Number.isFinite(value) && value > 0 ? value : DEFAULT_OPENAI_COMPAT_STREAM_IDLE_TIMEOUT_MS;
4555
- }
4556
- function getOpenAICompatFirstByteTimeoutBaseMs() {
4557
- const value = Number(process.env.PIE_OPENAI_COMPAT_FIRST_BYTE_TIMEOUT_MS || "");
4558
- return Number.isFinite(value) && value > 0 ? value : DEFAULT_OPENAI_COMPAT_FIRST_BYTE_TIMEOUT_MS;
4559
- }
4560
- function firstByteEscalationKey(model) {
4561
- return `${model.provider}|${model.baseUrl}|${model.id}`;
4562
- }
4563
- function getOpenAICompatFirstByteTimeoutMs(model) {
4564
- const base = getOpenAICompatFirstByteTimeoutBaseMs();
4565
- const consecutive = openAICompatFirstByteTimeoutsByEndpoint.get(firstByteEscalationKey(model)) ?? 0;
4566
- return base * 2 ** Math.min(consecutive, OPENAI_COMPAT_FIRST_BYTE_MAX_ESCALATION_STEPS);
4567
- }
4568
- function noteOpenAICompatFirstByteTimeout(model) {
4569
- const key = firstByteEscalationKey(model);
4570
- openAICompatFirstByteTimeoutsByEndpoint.set(key, (openAICompatFirstByteTimeoutsByEndpoint.get(key) ?? 0) + 1);
4571
- }
4572
- function resetOpenAICompatFirstByteTimeoutEscalation(model) {
4573
- openAICompatFirstByteTimeoutsByEndpoint.delete(firstByteEscalationKey(model));
4574
- }
4575
- function normalizeTokenCount(value) {
4576
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
4577
- return void 0;
4578
- }
4579
- return Math.floor(value);
4580
- }
4581
- function mergeOpenAIUsage(previous, usage) {
4582
- return {
4583
- promptTokens: normalizeTokenCount(usage?.prompt_tokens) ?? previous.promptTokens,
4584
- completionTokens: normalizeTokenCount(usage?.completion_tokens) ?? previous.completionTokens,
4585
- cachedTokens: normalizeTokenCount(usage?.prompt_tokens_details?.cached_tokens) ?? previous.cachedTokens,
4586
- reasoningTokens: normalizeTokenCount(usage?.completion_tokens_details?.reasoning_tokens) ?? previous.reasoningTokens,
4587
- totalTokens: normalizeTokenCount(usage?.total_tokens) ?? previous.totalTokens
4588
- };
4547
+ function isRecord(value) {
4548
+ return value !== null && typeof value === "object" && !Array.isArray(value);
4589
4549
  }
4590
- function normalizeOpenAIUsage(usage) {
4591
- const reportedPromptTokens = usage.promptTokens;
4592
- const reportedCachedTokens = usage.cachedTokens;
4593
- const reportedCompletionTokens = usage.completionTokens;
4594
- const reportedReasoningTokens = usage.reasoningTokens;
4595
- const reportedTotalTokens = usage.totalTokens;
4596
- const cachedTokens = reportedCachedTokens ?? 0;
4597
- const promptTokens = reportedPromptTokens ?? (reportedTotalTokens !== void 0 && reportedCompletionTokens !== void 0 ? Math.max(cachedTokens, reportedTotalTokens - reportedCompletionTokens) : cachedTokens);
4598
- const cacheRead = Math.min(cachedTokens, promptTokens);
4599
- const input = promptTokens - cacheRead;
4600
- const output = reportedCompletionTokens ?? (reportedTotalTokens !== void 0 ? Math.max(reportedReasoningTokens ?? 0, reportedTotalTokens - promptTokens) : reportedReasoningTokens ?? 0);
4601
- const partitionTotal = promptTokens + output;
4602
- return {
4603
- input,
4604
- output,
4605
- cacheRead,
4606
- totalTokens: Math.max(reportedTotalTokens ?? 0, partitionTotal)
4607
- };
4550
+ function isResponsesEventLike(value) {
4551
+ return isRecord(value) && typeof value.type === "string";
4608
4552
  }
4609
- function formatOpenAIStreamError(error) {
4610
- if (!error || typeof error !== "object") {
4611
- return typeof error === "string" ? error : "OpenAI-compatible stream returned an error";
4612
- }
4613
- const message = typeof error.message === "string" && error.message.length > 0 ? error.message : "OpenAI-compatible stream returned an error";
4553
+ function formatResponsesErrorEvent(event) {
4554
+ const source = isRecord(event.error) ? event.error : event;
4555
+ const message = typeof source.message === "string" && source.message.length > 0 ? source.message : "Responses stream returned an error";
4614
4556
  const metadata = [];
4615
- if (typeof error.type === "string" && error.type.length > 0) {
4616
- metadata.push(`type=${error.type}`);
4557
+ if (typeof source.code === "string" && source.code.length > 0) {
4558
+ metadata.push(`code=${source.code}`);
4617
4559
  }
4618
- if (typeof error.code === "string" && error.code.length > 0) {
4619
- metadata.push(`code=${error.code}`);
4560
+ if (typeof source.param === "string" && source.param.length > 0) {
4561
+ metadata.push(`param=${source.param}`);
4562
+ }
4563
+ if (typeof event.status === "number") {
4564
+ metadata.push(`status=${event.status}`);
4620
4565
  }
4621
4566
  return metadata.length > 0 ? `${message} (${metadata.join(", ")})` : message;
4622
4567
  }
4623
- function isRecord(value) {
4624
- return value !== null && typeof value === "object" && !Array.isArray(value);
4625
- }
4626
- function createProtocolError(message) {
4627
- return new OpenAICompatProtocolError(message);
4568
+
4569
+ // ../../packages/ai/src/providers/responses/responses-remote-failure.ts
4570
+ var MAX_TEXT = 4096;
4571
+ var transientCodes = /* @__PURE__ */ new Set(["server_error", "rate_limit_exceeded", "slow_down", "rate_limit_error", "server_is_overloaded", "service_unavailable_error"]);
4572
+ function responsesRemoteFailure(value, status, headers) {
4573
+ const root = isRecord(value) ? value : {};
4574
+ const response = isRecord(root.response) ? root.response : {};
4575
+ const error = isRecord(root.error) ? root.error : isRecord(response.error) ? response.error : root;
4576
+ const code = typeof error.code === "string" ? error.code.slice(0, 128).toLowerCase() : "";
4577
+ const type = typeof error.type === "string" ? error.type.slice(0, 128).toLowerCase() : "";
4578
+ const message = (typeof value === "string" ? value : typeof error.message === "string" ? error.message : "").slice(0, MAX_TEXT).toLowerCase();
4579
+ const httpStatus = status ?? root.status ?? root.statusCode;
4580
+ const fields = `${code} ${type}`;
4581
+ let category = "other";
4582
+ if (/context_length_exceeded|context_window_exceeded|context_overflow/.test(fields) || /context (?:length|window).{0,60}(?:exceed|too (?:long|large))|maximum context length|exceeds.{0,30}context window/.test(message)) category = "context_overflow";
4583
+ else if (/billing|insufficient_quota|insufficient_balance|credit|usage_limit|spend_limit/.test(fields) || /billing|(?:account|monthly) quota|exceeded your current quota|insufficient (?:credit|balance)|credit balance|spend(?:ing)? limit/.test(message)) category = "other";
4584
+ else if (typeof httpStatus === "number" && httpStatus >= 400 && httpStatus < 500 && httpStatus !== 429) category = "other";
4585
+ else if (httpStatus === 429 || typeof httpStatus === "number" && httpStatus >= 500 && httpStatus <= 599 || transientCodes.has(code) || transientCodes.has(type) || /server (?:is )?overloaded|temporarily unavailable|internal server error|rate limit (?:exceeded|reached)/.test(message)) category = "transient";
4586
+ const retryAfterMs = parseRetryAfter(headers ?? root.headers);
4587
+ return { category, ...retryAfterMs !== void 0 ? { retryAfterMs } : {} };
4628
4588
  }
4629
- function parseSSEDataLine(line) {
4630
- const trimmed = line.trim();
4631
- if (!trimmed || trimmed.startsWith(":")) return null;
4632
- if (!trimmed.startsWith("data:")) return null;
4633
- const data = trimmed.slice(5);
4634
- return data.startsWith(" ") ? data.slice(1) : data;
4589
+ function parseRetryAfter(headers) {
4590
+ if (!headers || typeof headers !== "object") return void 0;
4591
+ let raw;
4592
+ if ("get" in headers && typeof headers.get === "function") raw = headers.get("retry-after");
4593
+ else for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === "retry-after") raw = value;
4594
+ if (typeof raw !== "string" || raw.length > 128) return void 0;
4595
+ const text = raw.trim();
4596
+ if (/^\d+(?:\.\d+)?$/.test(text)) {
4597
+ const delay = Number(text) * 1e3;
4598
+ return Number.isFinite(delay) ? delay : Number.MAX_VALUE;
4599
+ }
4600
+ if (!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(text)) return void 0;
4601
+ const date = Date.parse(text);
4602
+ if (!Number.isFinite(date) || new Date(date).toUTCString() !== text) return void 0;
4603
+ return Math.max(0, date - Date.now());
4635
4604
  }
4636
- function parseFinalToolArguments(partialArgs, toolName) {
4637
- const text = partialArgs.trim();
4638
- if (!text) return {};
4639
- let parsed;
4605
+ async function readResponsesErrorBody(read, signal) {
4606
+ let timer;
4607
+ let onAbort;
4640
4608
  try {
4641
- parsed = JSON.parse(text);
4642
- } catch (error) {
4643
- const message = error instanceof Error ? error.message : String(error);
4644
- throw createProtocolError(`OpenAI-compatible stream returned incomplete or invalid JSON arguments for tool "${toolName || "unknown"}": ${message}`);
4645
- }
4646
- if (!isRecord(parsed)) {
4647
- throw createProtocolError(`OpenAI-compatible stream returned non-object JSON arguments for tool "${toolName || "unknown"}".`);
4609
+ return await Promise.race([
4610
+ Promise.resolve().then(read).then((text) => text.slice(0, MAX_TEXT)).catch(() => ""),
4611
+ new Promise((resolve) => {
4612
+ onAbort = () => resolve("");
4613
+ if (signal.aborted) resolve("");
4614
+ else signal.addEventListener("abort", onAbort, { once: true });
4615
+ timer = setTimeout(() => resolve(""), 250);
4616
+ })
4617
+ ]);
4618
+ } finally {
4619
+ if (timer !== void 0) clearTimeout(timer);
4620
+ if (onAbort) signal.removeEventListener("abort", onAbort);
4648
4621
  }
4649
- return parsed;
4650
4622
  }
4651
- function tryParseFinalToolArguments(partialArgs) {
4652
- const text = partialArgs.trim();
4653
- if (!text) return null;
4623
+ function parseResponsesErrorBody(text) {
4654
4624
  try {
4655
- const parsed = JSON.parse(text);
4656
- return isRecord(parsed) ? parsed : null;
4625
+ return JSON.parse(text);
4657
4626
  } catch {
4658
- return null;
4627
+ return text;
4659
4628
  }
4660
4629
  }
4661
- var streamOpenAICompletions = (model, context, options) => {
4662
- if ((options?.transport ?? model.transport) === "websocket") throw new Error(`API ${model.api} does not support WebSocket transport.`);
4663
- const stream2 = new AssistantMessageEventStream();
4664
- (async () => {
4665
- const output = {
4630
+
4631
+ // ../../packages/ai/src/providers/responses/responses-usage.ts
4632
+ function tokenCount(value) {
4633
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
4634
+ return Math.floor(value);
4635
+ }
4636
+ function normalizeResponsesUsage(model, usage) {
4637
+ const inputTokens = tokenCount(usage?.input_tokens);
4638
+ const cachedTokens = tokenCount(usage?.input_tokens_details?.cached_tokens) ?? 0;
4639
+ const cacheWriteTokens = tokenCount(usage?.input_tokens_details?.cache_write_tokens) ?? 0;
4640
+ const outputTokens = tokenCount(usage?.output_tokens);
4641
+ const reasoningTokens = tokenCount(usage?.output_tokens_details?.reasoning_tokens);
4642
+ const totalTokens = tokenCount(usage?.total_tokens);
4643
+ const input = inputTokens ?? (totalTokens !== void 0 && outputTokens !== void 0 ? Math.max(cachedTokens + cacheWriteTokens, totalTokens - outputTokens) : cachedTokens + cacheWriteTokens);
4644
+ const output = outputTokens ?? (totalTokens !== void 0 ? Math.max(reasoningTokens ?? 0, totalTokens - input) : reasoningTokens ?? 0);
4645
+ const cacheRead = Math.min(cachedTokens, input);
4646
+ const cacheWrite = Math.min(cacheWriteTokens, input - cacheRead);
4647
+ const inputExclusive = input - cacheRead - cacheWrite;
4648
+ const partitionTotal = input + output;
4649
+ const base = {
4650
+ input: inputExclusive,
4651
+ output,
4652
+ cacheRead,
4653
+ cacheWrite,
4654
+ totalTokens: Math.max(totalTokens ?? 0, partitionTotal)
4655
+ };
4656
+ return { ...base, cost: calculateCost(model, base) };
4657
+ }
4658
+
4659
+ // ../../packages/ai/src/providers/responses/responses-events.ts
4660
+ var ResponsesEventReducer = class {
4661
+ output;
4662
+ model;
4663
+ started = false;
4664
+ terminal = null;
4665
+ items = /* @__PURE__ */ new Map();
4666
+ toolCallStates = [];
4667
+ diagnostics = { unknownEventTypes: /* @__PURE__ */ new Set(), ignoredItemTypes: /* @__PURE__ */ new Set(), terminalType: null };
4668
+ constructor(model) {
4669
+ this.model = model;
4670
+ this.output = {
4666
4671
  role: "assistant",
4667
4672
  content: [],
4668
4673
  api: model.api,
4669
4674
  provider: model.provider,
4670
4675
  model: model.id,
4676
+ usageReported: false,
4671
4677
  usage: {
4672
4678
  input: 0,
4673
4679
  output: 0,
@@ -4679,694 +4685,802 @@ var streamOpenAICompletions = (model, context, options) => {
4679
4685
  stopReason: "stop",
4680
4686
  timestamp: Date.now()
4681
4687
  };
4688
+ }
4689
+ get message() {
4690
+ return this.output;
4691
+ }
4692
+ get isTerminal() {
4693
+ return this.terminal !== null;
4694
+ }
4695
+ /** Terminal response object (present on completed/incomplete/failed). */
4696
+ get terminalResponse() {
4697
+ return this.terminal?.response;
4698
+ }
4699
+ /** Feed one raw wire event; returns the AssistantMessageEvents to emit. */
4700
+ feed(raw) {
4701
+ if (this.terminal) return [];
4682
4702
  try {
4683
- const apiKey = options?.apiKey || getEnvApiKey(model.provider, model.apiKeyEnv) || "";
4684
- if (!apiKey) {
4685
- throw new Error(`No API key for provider: ${model.provider}`);
4703
+ const events = this.feedInbound(raw);
4704
+ if (this.isTerminal && this.output.stopReason === "error") {
4705
+ this.output.remoteFailure = responsesRemoteFailure(raw);
4686
4706
  }
4687
- const compat = getCompat(model);
4688
- const params = buildOpenAIChatCompletionsPayload(model, context, options, compat);
4689
- options?.onPayload?.(params);
4690
- const headers = {
4691
- "Content-Type": "application/json",
4692
- Authorization: `Bearer ${apiKey}`,
4693
- // Some OpenAI-compatible providers require caller-supplied SSE headers.
4694
- ...model.headers || {},
4695
- ...options?.headers || {}
4696
- };
4697
- const response = await httpRequest(`${model.baseUrl}/chat/completions`, {
4698
- method: "POST",
4699
- headers,
4700
- body: JSON.stringify(params),
4701
- signal: options?.signal,
4702
- // Tiered timeouts unless the caller pinned a total budget: a first-byte
4703
- // budget (escalates across consecutive timeouts so slow-thinking
4704
- // providers with hidden reasoning are not killed repeatedly) plus a
4705
- // stream-idle budget that any traffic resets.
4706
- ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {
4707
- firstByteTimeoutMs: getOpenAICompatFirstByteTimeoutMs(model),
4708
- streamIdleTimeoutMs: getOpenAICompatStreamTimeoutMs()
4709
- },
4710
- // Log attribution only (never sent over the wire).
4711
- label: `${model.provider}/${model.id}`
4712
- });
4713
- if (!response.ok) {
4714
- const errorBody = await response.text().catch(() => "");
4715
- throw new Error(`API error ${response.status}: ${errorBody}`);
4716
- }
4717
- stream2.push({ type: "start", partial: output });
4718
- let currentBlock = null;
4719
- const blocks = output.content;
4720
- const blockIndex = () => blocks.length - 1;
4721
- const toolCallEntries = [];
4722
- const toolCallsByIndex = /* @__PURE__ */ new Map();
4723
- const toolCallsById = /* @__PURE__ */ new Map();
4724
- let usageSnapshot = {};
4725
- let sawDone = false;
4726
- let sawFinishReason = false;
4727
- let rawFinishReason = null;
4728
- const createToolCallEntry = (toolCall, index) => {
4729
- const block = {
4730
- type: "toolCall",
4731
- id: toolCall.id || "",
4732
- name: toolCall.function?.name || "",
4733
- arguments: {}
4734
- };
4735
- output.content.push(block);
4736
- const entry = { block, partialArgs: "", contentIndex: blockIndex(), index };
4737
- toolCallEntries.push(entry);
4738
- stream2.push({
4739
- type: "toolcall_start",
4740
- contentIndex: entry.contentIndex,
4741
- partial: output
4742
- });
4743
- return entry;
4744
- };
4745
- const bindToolCallIndex = (index, entry) => {
4746
- const existing = toolCallsByIndex.get(index);
4747
- if (existing && existing !== entry) {
4748
- throw createProtocolError(`OpenAI-compatible stream reused tool call index ${index} for multiple calls.`);
4749
- }
4750
- if (entry.index !== void 0 && entry.index !== index) {
4751
- throw createProtocolError(`OpenAI-compatible stream moved tool call "${entry.block.id || entry.block.name || "unknown"}" from index ${entry.index} to ${index}.`);
4752
- }
4753
- entry.index = index;
4754
- toolCallsByIndex.set(index, entry);
4755
- };
4756
- const rememberToolCallId = (id, entry) => {
4757
- const existing = toolCallsById.get(id);
4758
- if (existing && existing !== entry) {
4759
- throw createProtocolError(`OpenAI-compatible stream reused tool call id "${id}" for multiple calls.`);
4760
- }
4761
- if (entry.block.id && entry.block.id !== id) {
4762
- throw createProtocolError(`OpenAI-compatible stream changed tool call id from "${entry.block.id}" to "${id}".`);
4763
- }
4764
- entry.block.id = id;
4765
- toolCallsById.set(id, entry);
4766
- };
4767
- const resolveToolCallEntry = (toolCall, toolCallCount) => {
4768
- const id = typeof toolCall.id === "string" && toolCall.id.length > 0 ? toolCall.id : "";
4769
- if (Number.isInteger(toolCall.index) && toolCall.index >= 0) {
4770
- let entry = toolCallsByIndex.get(toolCall.index);
4771
- if (entry && id && entry.block.id && entry.block.id !== id) {
4772
- throw createProtocolError(`OpenAI-compatible stream changed tool call id at index ${toolCall.index} from "${entry.block.id}" to "${id}".`);
4773
- }
4774
- if (!entry && id) {
4775
- entry = toolCallsById.get(id);
4776
- if (entry) bindToolCallIndex(toolCall.index, entry);
4777
- }
4778
- if (!entry) {
4779
- entry = createToolCallEntry(toolCall, toolCall.index);
4780
- bindToolCallIndex(toolCall.index, entry);
4781
- }
4782
- if (id) rememberToolCallId(id, entry);
4783
- return entry;
4784
- }
4785
- if (id) {
4786
- let entry = toolCallsById.get(id);
4787
- if (!entry) {
4788
- const unpaired = toolCallEntries.filter((candidate) => !candidate.block.id);
4789
- if (unpaired.length === 1) {
4790
- rememberToolCallId(id, unpaired[0]);
4791
- return unpaired[0];
4792
- }
4793
- if (unpaired.length > 1) {
4794
- throw createProtocolError(`OpenAI-compatible stream returned tool call id "${id}" without an index while multiple unnamed calls are in flight; the call cannot be disambiguated.`);
4795
- }
4796
- entry = createToolCallEntry(toolCall);
4797
- rememberToolCallId(id, entry);
4798
- }
4799
- return entry;
4800
- }
4801
- if (toolCallEntries.length === 1) {
4802
- return toolCallEntries[0];
4803
- }
4804
- if (toolCallEntries.length === 0 && toolCallCount === 1) {
4805
- return createToolCallEntry(toolCall);
4806
- }
4807
- throw createProtocolError("OpenAI-compatible stream returned tool call deltas without index or id and the call could not be disambiguated.");
4808
- };
4809
- const finishCurrentBlock = (block) => {
4810
- if (block) {
4811
- if (block.type === "text") {
4812
- stream2.push({
4813
- type: "text_end",
4814
- contentIndex: blocks.indexOf(block),
4815
- content: block.text,
4816
- partial: output
4817
- });
4818
- } else if (block.type === "thinking") {
4819
- stream2.push({
4820
- type: "thinking_end",
4821
- contentIndex: blocks.indexOf(block),
4822
- content: block.thinking,
4823
- partial: output
4824
- });
4825
- }
4826
- }
4827
- };
4828
- if (!response.readSSELines) {
4829
- throw new Error("SSE streaming not supported on this platform");
4830
- }
4831
- for await (const line of response.readSSELines(options?.signal)) {
4832
- {
4833
- const data = parseSSEDataLine(line);
4834
- if (data === null) continue;
4835
- if (data === "[DONE]") {
4836
- sawDone = true;
4837
- break;
4838
- }
4839
- let chunk;
4840
- try {
4841
- chunk = JSON.parse(data);
4842
- } catch (error) {
4843
- const message = error instanceof Error ? error.message : String(error);
4844
- throw createProtocolError(`OpenAI-compatible stream returned malformed SSE JSON: ${message}`);
4845
- }
4846
- if (chunk?.error) {
4847
- throw new Error(formatOpenAIStreamError(chunk.error));
4848
- }
4849
- if (chunk.usage) {
4850
- usageSnapshot = mergeOpenAIUsage(usageSnapshot, chunk.usage);
4851
- output.usageReported = [usageSnapshot.promptTokens, usageSnapshot.completionTokens].every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
4852
- const normalizedUsage = normalizeOpenAIUsage(usageSnapshot);
4853
- output.usage = {
4854
- input: normalizedUsage.input,
4855
- output: normalizedUsage.output,
4856
- cacheRead: normalizedUsage.cacheRead,
4857
- cacheWrite: 0,
4858
- totalTokens: normalizedUsage.totalTokens,
4859
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
4860
- };
4861
- output.usage.cost = calculateCost(model, output.usage);
4862
- if (process.env.PIE_DEBUG_CACHE) {
4863
- const normalizedPromptTokens = normalizedUsage.input + normalizedUsage.cacheRead;
4864
- console.error("[CACHE DEBUG] Response usage:", JSON.stringify({
4865
- input_tokens: normalizedUsage.input,
4866
- output_tokens: normalizedUsage.output,
4867
- cached_tokens: normalizedUsage.cacheRead,
4868
- cache_hit_rate: normalizedPromptTokens > 0 ? `${(normalizedUsage.cacheRead / normalizedPromptTokens * 100).toFixed(1)}%` : "N/A"
4869
- }, null, 2));
4870
- }
4871
- }
4872
- const choice = chunk.choices?.[0];
4873
- if (!choice) continue;
4874
- if (choice.finish_reason) {
4875
- sawFinishReason = true;
4876
- rawFinishReason = String(choice.finish_reason);
4877
- output.stopReason = mapOpenAIStopReason(choice.finish_reason);
4878
- }
4879
- if (choice.delta) {
4880
- if (choice.delta.content !== null && choice.delta.content !== void 0 && choice.delta.content.length > 0) {
4881
- if (!currentBlock || currentBlock.type !== "text") {
4882
- finishCurrentBlock(currentBlock);
4883
- currentBlock = { type: "text", text: "" };
4884
- output.content.push(currentBlock);
4885
- stream2.push({
4886
- type: "text_start",
4887
- contentIndex: blockIndex(),
4888
- partial: output
4889
- });
4890
- }
4891
- if (currentBlock.type === "text") {
4892
- currentBlock.text += choice.delta.content;
4893
- stream2.push({
4894
- type: "text_delta",
4895
- contentIndex: blockIndex(),
4896
- delta: choice.delta.content,
4897
- partial: output
4898
- });
4899
- }
4900
- }
4901
- const reasoningFields = [
4902
- "reasoning_content",
4903
- "reasoning",
4904
- "reasoning_text"
4905
- ];
4906
- let foundReasoningField = null;
4907
- for (const field of reasoningFields) {
4908
- if (choice.delta[field] !== null && choice.delta[field] !== void 0 && choice.delta[field].length > 0) {
4909
- foundReasoningField = field;
4910
- break;
4911
- }
4912
- }
4913
- if (foundReasoningField) {
4914
- if (!currentBlock || currentBlock.type !== "thinking") {
4915
- finishCurrentBlock(currentBlock);
4916
- currentBlock = {
4917
- type: "thinking",
4918
- thinking: "",
4919
- thinkingSignature: foundReasoningField
4920
- };
4921
- output.content.push(currentBlock);
4922
- stream2.push({
4923
- type: "thinking_start",
4924
- contentIndex: blockIndex(),
4925
- partial: output
4926
- });
4927
- }
4928
- if (currentBlock.type === "thinking") {
4929
- const delta = choice.delta[foundReasoningField];
4930
- currentBlock.thinking += delta;
4931
- stream2.push({
4932
- type: "thinking_delta",
4933
- contentIndex: blockIndex(),
4934
- delta,
4935
- partial: output
4936
- });
4937
- }
4938
- }
4939
- if (choice.delta.tool_calls) {
4940
- const deltaToolCalls = choice.delta.tool_calls;
4941
- for (const toolCall of deltaToolCalls) {
4942
- finishCurrentBlock(currentBlock);
4943
- currentBlock = null;
4944
- const entry = resolveToolCallEntry(toolCall, deltaToolCalls.length);
4945
- if (entry) {
4946
- if (toolCall.id) rememberToolCallId(toolCall.id, entry);
4947
- if (toolCall.function?.name) {
4948
- if (entry.block.name && entry.block.name !== toolCall.function.name) {
4949
- throw createProtocolError(`OpenAI-compatible stream changed tool call name from "${entry.block.name}" to "${toolCall.function.name}".`);
4950
- }
4951
- entry.block.name = toolCall.function.name;
4952
- }
4953
- let delta = "";
4954
- if (toolCall.function?.arguments) {
4955
- delta = toolCall.function.arguments;
4956
- entry.partialArgs += delta;
4957
- entry.block.arguments = parseStreamingJson(entry.partialArgs);
4958
- }
4959
- stream2.push({
4960
- type: "toolcall_delta",
4961
- contentIndex: entry.contentIndex,
4962
- delta,
4963
- partial: output
4964
- });
4965
- }
4966
- }
4967
- }
4968
- }
4969
- }
4970
- }
4971
- finishCurrentBlock(currentBlock);
4972
- if (compat.streamRequiresDone && !sawDone) {
4973
- throw createProtocolError(`OpenAI-compatible stream ended without data: [DONE]${rawFinishReason ? ` (last finish_reason=${rawFinishReason})` : ""}. Set compat.streamRequiresDone=false for gateways that legitimately omit the terminator.`);
4974
- }
4975
- if (compat.streamRequiresFinishReason && !sawFinishReason) {
4976
- throw createProtocolError("OpenAI-compatible stream ended without finish_reason. Set compat.streamRequiresFinishReason=false for endpoints that omit it.");
4977
- }
4978
- if (output.stopReason === "toolUse" && toolCallEntries.length === 0) {
4979
- throw createProtocolError(`OpenAI-compatible stream ended with finish_reason=${rawFinishReason} but did not include any tool calls.`);
4980
- }
4981
- if (output.stopReason === "length" && toolCallEntries.length > 0) {
4982
- const truncatedEntries = toolCallEntries.filter(
4983
- ({ partialArgs }) => tryParseFinalToolArguments(partialArgs) === null
4984
- );
4985
- if (truncatedEntries.length > 0) {
4986
- const truncatedBlocks = new Set(truncatedEntries.map((entry) => entry.block));
4987
- for (let i = toolCallEntries.length - 1; i >= 0; i--) {
4988
- if (truncatedBlocks.has(toolCallEntries[i].block)) {
4989
- toolCallEntries.splice(i, 1);
4990
- }
4991
- }
4992
- output.content = output.content.filter(
4993
- (block) => block.type !== "toolCall" || !truncatedBlocks.has(block)
4994
- );
4995
- const dropped = truncatedEntries.map((entry) => entry.block.name || "unnamed").sort().map((name) => `"${name}"`).join(", ");
4996
- output.content.push({
4997
- type: "text",
4998
- text: `[output truncated: finish_reason=length cut ${truncatedEntries.length === 1 ? "a tool call" : `${truncatedEntries.length} tool calls`} mid-arguments (${dropped}); the call${truncatedEntries.length === 1 ? " was" : "s were"} dropped. Re-issue the call or continue with fewer/smaller requests.]`
4999
- });
5000
- }
5001
- }
5002
- const knownToolNames = new Set((context.tools ?? []).map((tool) => tool.name));
5003
- const droppedToolCallBlocks = /* @__PURE__ */ new Set();
5004
- const unknownNameSamples = [];
5005
- if (knownToolNames.size > 0) {
5006
- for (let i = toolCallEntries.length - 1; i >= 0; i--) {
5007
- const entry = toolCallEntries[i];
5008
- if (entry.block.name.trim() && !knownToolNames.has(entry.block.name)) {
5009
- if (unknownNameSamples.length < 3) unknownNameSamples.push(JSON.stringify(entry.block.name));
5010
- droppedToolCallBlocks.add(entry.block);
5011
- toolCallEntries.splice(i, 1);
5012
- }
4707
+ return events;
4708
+ } catch (error) {
4709
+ this.terminal = null;
4710
+ throw error;
4711
+ }
4712
+ }
4713
+ feedInbound(raw) {
4714
+ const events = [];
4715
+ if (!isResponsesEventLike(raw)) {
4716
+ throw new ResponsesProtocolError("Responses stream returned an event without a string type.");
4717
+ }
4718
+ if (this.terminal) return events;
4719
+ switch (raw.type) {
4720
+ case "response.created":
4721
+ case "response.in_progress":
4722
+ case "response.queued":
4723
+ if (!this.started) {
4724
+ this.started = true;
4725
+ events.push({ type: "start", partial: this.output });
5013
4726
  }
4727
+ break;
4728
+ case "response.output_item.added":
4729
+ events.push(...this.onOutputItemAdded(raw));
4730
+ break;
4731
+ case "response.output_item.done":
4732
+ events.push(...this.onOutputItemDone(raw));
4733
+ break;
4734
+ case "response.content_part.added":
4735
+ events.push(...this.onContentPartAdded(raw));
4736
+ break;
4737
+ case "response.content_part.done":
4738
+ break;
4739
+ case "response.output_text.delta":
4740
+ events.push(...this.appendTextDelta(raw, "text"));
4741
+ break;
4742
+ case "response.output_text.done":
4743
+ this.validateTextDone(raw);
4744
+ break;
4745
+ case "response.refusal.delta":
4746
+ events.push(...this.appendTextDelta(raw, "refusal"));
4747
+ break;
4748
+ case "response.refusal.done":
4749
+ break;
4750
+ case "response.reasoning_summary_text.delta":
4751
+ case "response.reasoning_text.delta":
4752
+ events.push(...this.appendReasoningDelta(raw));
4753
+ break;
4754
+ case "response.reasoning_summary_text.done":
4755
+ case "response.reasoning_text.done":
4756
+ break;
4757
+ case "response.reasoning_summary_part.added":
4758
+ case "response.reasoning_summary_part.done":
4759
+ break;
4760
+ case "response.function_call_arguments.delta":
4761
+ events.push(...this.appendFunctionCallArgsDelta(raw));
4762
+ break;
4763
+ case "response.function_call_arguments.done":
4764
+ this.onFunctionCallArgsDone(raw);
4765
+ break;
4766
+ case "response.completed":
4767
+ events.push(...this.onTerminal(raw, "response.completed"));
4768
+ break;
4769
+ case "response.incomplete":
4770
+ events.push(...this.onIncomplete(raw));
4771
+ break;
4772
+ case "response.failed":
4773
+ events.push(...this.onTerminal(raw, "response.failed", "error", this.failedText(raw)));
4774
+ break;
4775
+ case "error":
4776
+ events.push(...this.onTerminal(raw, "error", "error", formatResponsesErrorEvent(raw)));
4777
+ break;
4778
+ default:
4779
+ this.diagnostics.unknownEventTypes.add(raw.type);
4780
+ break;
4781
+ }
4782
+ return events;
4783
+ }
4784
+ /** Stream ended without a terminal event. Caller decides how to fail. */
4785
+ finishWithoutTerminal() {
4786
+ return new ResponsesProtocolError(
4787
+ `Responses stream ended without a terminal event (${this.diagnostics.terminalType ?? "none"} seen).`
4788
+ );
4789
+ }
4790
+ // ─── item lifecycle ─────────────────────────────────────────────────────
4791
+ ensureStarted() {
4792
+ if (this.started) return [];
4793
+ this.started = true;
4794
+ return [{ type: "start", partial: this.output }];
4795
+ }
4796
+ requireItemIndex(raw) {
4797
+ const index = raw.output_index;
4798
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0) {
4799
+ throw new ResponsesProtocolError(`Responses event "${raw.type}" is missing a valid output_index.`);
4800
+ }
4801
+ return index;
4802
+ }
4803
+ onOutputItemAdded(raw) {
4804
+ const outputIndex = this.requireItemIndex(raw);
4805
+ const item = raw.item;
4806
+ if (!isRecord(item)) {
4807
+ throw new ResponsesProtocolError(`response.output_item.added at index ${outputIndex} is missing the item.`);
4808
+ }
4809
+ if (this.items.has(outputIndex)) {
4810
+ throw new ResponsesProtocolError(`Responses stream reused output_index ${outputIndex}.`);
4811
+ }
4812
+ const itemId = typeof item.id === "string" ? item.id : "";
4813
+ if (item.type === "message") {
4814
+ this.items.set(outputIndex, { kind: "message", itemId, blocks: /* @__PURE__ */ new Map() });
4815
+ return this.ensureStarted();
4816
+ }
4817
+ if (item.type === "reasoning") {
4818
+ const block = { type: "thinking", thinking: "" };
4819
+ this.output.content.push(block);
4820
+ this.items.set(outputIndex, { kind: "reasoning", itemId, block, lastSummaryIndex: null });
4821
+ const startEvents = this.ensureStarted();
4822
+ return [
4823
+ ...startEvents,
4824
+ { type: "thinking_start", contentIndex: this.output.content.length - 1, partial: this.output }
4825
+ ];
4826
+ }
4827
+ if (item.type === "function_call") {
4828
+ const callId = typeof item.call_id === "string" ? item.call_id : "";
4829
+ if (!callId) {
4830
+ throw new ResponsesProtocolError(`function_call output item at index ${outputIndex} is missing call_id.`);
5014
4831
  }
5015
- const emittedCallCounts = /* @__PURE__ */ new Map();
5016
- const excessDuplicateEntries = /* @__PURE__ */ new Set();
5017
- const repeatExempt = new Set(
5018
- (context.tools ?? []).filter((tool) => tool.allowIdenticalRepeatCalls === true).map((tool) => tool.name)
4832
+ const name = typeof item.name === "string" ? item.name : "";
4833
+ if (!name || !itemId) throw new ResponsesProtocolError("function_call requires name and item id.");
4834
+ const block = { type: "toolCall", id: callId, name, arguments: {} };
4835
+ this.output.content.push(block);
4836
+ const state = {
4837
+ kind: "function_call",
4838
+ itemId,
4839
+ block,
4840
+ partialArgs: "",
4841
+ finalArgs: null,
4842
+ completed: false,
4843
+ contentIndex: this.output.content.length - 1
4844
+ };
4845
+ this.items.set(outputIndex, state);
4846
+ this.toolCallStates.push(state);
4847
+ const startEvents = this.ensureStarted();
4848
+ return [
4849
+ ...startEvents,
4850
+ { type: "toolcall_start", contentIndex: state.contentIndex, partial: this.output }
4851
+ ];
4852
+ }
4853
+ this.items.set(outputIndex, { kind: "ignored", itemType: String(item.type) });
4854
+ this.diagnostics.ignoredItemTypes.add(String(item.type));
4855
+ return [];
4856
+ }
4857
+ lookupItem(raw, kinds, label) {
4858
+ const outputIndex = this.requireItemIndex(raw);
4859
+ let state = this.items.get(outputIndex);
4860
+ if (!state || !kinds.includes(state.kind)) {
4861
+ throw new ResponsesProtocolError(
4862
+ `Responses event "${raw.type ?? label}" references ${label} output_index ${outputIndex} that was never added (or is of the wrong item type).`
5019
4863
  );
5020
- for (const entry of toolCallEntries) {
5021
- if (repeatExempt.has(entry.block.name)) continue;
5022
- const key = `${entry.block.name}
5023
- ${entry.partialArgs}`;
5024
- const seen = (emittedCallCounts.get(key) ?? 0) + 1;
5025
- emittedCallCounts.set(key, seen);
5026
- if (seen > OPENAI_COMPAT_MAX_DUPLICATE_TOOL_CALLS) excessDuplicateEntries.add(entry);
4864
+ }
4865
+ if (state.kind !== "ignored" && raw.item_id !== void 0 && raw.item_id !== state.itemId) throw new ResponsesProtocolError("Response item identity changed.");
4866
+ return { state, outputIndex };
4867
+ }
4868
+ onContentPartAdded(raw) {
4869
+ const part = raw.part;
4870
+ const partType = isRecord(part) ? part.type : void 0;
4871
+ const kind = partType === "reasoning_text" ? "reasoning" : "message";
4872
+ const { state } = this.lookupItem(raw, [kind], kind);
4873
+ const partIndex = raw.content_index;
4874
+ if (typeof partIndex !== "number" || !Number.isInteger(partIndex) || partIndex < 0) {
4875
+ throw new ResponsesProtocolError("response.content_part.added is missing a valid content_index.");
4876
+ }
4877
+ if (state.kind !== "message") return [];
4878
+ if (state.blocks.has(partIndex)) {
4879
+ throw new ResponsesProtocolError(`Responses stream reused content_index ${partIndex} on one message item.`);
4880
+ }
4881
+ if (partType !== "output_text" && partType !== "refusal") {
4882
+ return [];
4883
+ }
4884
+ const block = { type: "text", text: "" };
4885
+ this.output.content.push(block);
4886
+ state.blocks.set(partIndex, { block, contentIndex: this.output.content.length - 1 });
4887
+ return [{ type: "text_start", contentIndex: this.output.content.length - 1, partial: this.output }];
4888
+ }
4889
+ messageBlockFor(raw) {
4890
+ const { state } = this.lookupItem(raw, ["message"], "message");
4891
+ if (state.kind !== "message") throw new ResponsesProtocolError("internal: expected message item");
4892
+ const partIndex = raw.content_index;
4893
+ if (typeof partIndex !== "number" || !Number.isInteger(partIndex) || partIndex < 0) {
4894
+ throw new ResponsesProtocolError(`Responses event "${raw.type}" is missing a valid content_index.`);
4895
+ }
4896
+ const entry = state.blocks.get(partIndex);
4897
+ if (!entry) {
4898
+ throw new ResponsesProtocolError(
4899
+ `Responses event "${raw.type}" references content_index ${partIndex} that was never added.`
4900
+ );
4901
+ }
4902
+ return entry;
4903
+ }
4904
+ appendTextDelta(raw, kind) {
4905
+ const delta = raw.delta;
4906
+ if (typeof delta !== "string" || delta.length === 0) return [];
4907
+ const entry = this.messageBlockFor(raw);
4908
+ entry.block.text += delta;
4909
+ return [{ type: "text_delta", contentIndex: entry.contentIndex, delta, partial: this.output }];
4910
+ }
4911
+ validateTextDone(raw) {
4912
+ this.messageBlockFor(raw);
4913
+ }
4914
+ appendReasoningDelta(raw) {
4915
+ const delta = raw.delta;
4916
+ if (typeof delta !== "string" || delta.length === 0) return [];
4917
+ const { state } = this.lookupItem(raw, ["reasoning"], "reasoning");
4918
+ if (state.kind !== "reasoning") return [];
4919
+ let text = delta;
4920
+ const summaryIndex = raw.summary_index;
4921
+ if (typeof summaryIndex === "number" && Number.isInteger(summaryIndex)) {
4922
+ if (state.lastSummaryIndex !== null && summaryIndex !== state.lastSummaryIndex) {
4923
+ text = `
4924
+
4925
+ ${delta}`;
5027
4926
  }
5028
- if (excessDuplicateEntries.size > 0) {
5029
- for (let i = toolCallEntries.length - 1; i >= 0; i--) {
5030
- if (excessDuplicateEntries.has(toolCallEntries[i])) {
5031
- droppedToolCallBlocks.add(toolCallEntries[i].block);
5032
- toolCallEntries.splice(i, 1);
5033
- }
4927
+ state.lastSummaryIndex = summaryIndex;
4928
+ }
4929
+ state.block.thinking += text;
4930
+ return [{ type: "thinking_delta", contentIndex: this.output.content.indexOf(state.block), delta: text, partial: this.output }];
4931
+ }
4932
+ appendFunctionCallArgsDelta(raw) {
4933
+ const delta = raw.delta ?? raw.arguments;
4934
+ if (typeof delta !== "string" || delta.length === 0) return [];
4935
+ const { state } = this.lookupItem(raw, ["function_call"], "function_call");
4936
+ if (state.kind !== "function_call") return [];
4937
+ state.partialArgs += delta;
4938
+ state.block.arguments = parseStreamingJson(state.partialArgs);
4939
+ return [{ type: "toolcall_delta", contentIndex: state.contentIndex, delta, partial: this.output }];
4940
+ }
4941
+ onFunctionCallArgsDone(raw) {
4942
+ const { state } = this.lookupItem(raw, ["function_call"], "function_call");
4943
+ if (state.kind !== "function_call") return;
4944
+ if (typeof raw.arguments === "string") {
4945
+ state.finalArgs = raw.arguments;
4946
+ }
4947
+ }
4948
+ onOutputItemDone(raw) {
4949
+ const outputIndex = this.requireItemIndex(raw);
4950
+ const item = raw.item;
4951
+ if (!isRecord(item)) {
4952
+ throw new ResponsesProtocolError(`response.output_item.done at index ${outputIndex} is missing the item.`);
4953
+ }
4954
+ const state = this.items.get(outputIndex);
4955
+ if (!state) {
4956
+ throw new ResponsesProtocolError(`response.output_item.done references output_index ${outputIndex} that was never added.`);
4957
+ }
4958
+ if (state.kind !== "ignored" && (item.id !== state.itemId || item.type !== state.kind)) throw new ResponsesProtocolError("Response done item identity changed.");
4959
+ switch (state.kind) {
4960
+ case "message": {
4961
+ const events = [];
4962
+ for (const { block, contentIndex } of state.blocks.values()) {
4963
+ events.push({ type: "text_end", contentIndex, content: block.text, partial: this.output });
5034
4964
  }
4965
+ return events;
5035
4966
  }
5036
- if (droppedToolCallBlocks.size > 0) {
5037
- const unknownCount = droppedToolCallBlocks.size - excessDuplicateEntries.size;
5038
- output.content = output.content.filter(
5039
- (block) => block.type !== "toolCall" || !droppedToolCallBlocks.has(block)
5040
- );
5041
- const reasons = [];
5042
- if (unknownCount > 0) {
5043
- reasons.push(`${unknownCount} named tools that are not part of this request (samples: ${unknownNameSamples.join(", ")})`);
5044
- }
5045
- if (excessDuplicateEntries.size > 0) {
5046
- reasons.push(`${excessDuplicateEntries.size} were exact duplicates of an earlier call in the same message`);
4967
+ case "reasoning": {
4968
+ const events = [];
4969
+ const encrypted = typeof item.encrypted_content === "string" ? item.encrypted_content : null;
4970
+ const itemId = typeof item.id === "string" && item.id.length > 0 ? item.id : state.itemId;
4971
+ if (itemId) {
4972
+ state.block.thinkingSignature = JSON.stringify({ v: 1, id: itemId, encrypted_content: encrypted });
5047
4973
  }
5048
- output.content.push({
5049
- type: "text",
5050
- text: `[dropped ${droppedToolCallBlocks.size} tool call${droppedToolCallBlocks.size === 1 ? "" : "s"}: ${reasons.join("; ")}. Re-issue only the intended calls.]`
4974
+ events.push({
4975
+ type: "thinking_end",
4976
+ contentIndex: this.output.content.indexOf(state.block),
4977
+ content: state.block.thinking,
4978
+ partial: this.output
5051
4979
  });
4980
+ return events;
5052
4981
  }
5053
- for (const { block, partialArgs, contentIndex } of toolCallEntries) {
5054
- if (!block.name.trim()) {
5055
- throw createProtocolError("OpenAI-compatible stream returned a tool call without a function name.");
4982
+ case "function_call": {
4983
+ const finalText = typeof item.arguments === "string" && item.arguments.length > 0 ? item.arguments : state.finalArgs ?? state.partialArgs;
4984
+ if (typeof item.call_id === "string" && item.call_id.length > 0 && item.call_id !== state.block.id) {
4985
+ throw new ResponsesProtocolError(`function_call item changed call_id from "${state.block.id}" to "${item.call_id}".`);
5056
4986
  }
5057
- block.arguments = parseFinalToolArguments(partialArgs, block.name);
5058
- stream2.push({ type: "toolcall_end", contentIndex, toolCall: block, partial: output });
5059
- }
5060
- const hasToolCallBlocks = output.content.some((block) => block.type === "toolCall");
5061
- if (output.stopReason !== "error" && output.stopReason !== "aborted" && hasToolCallBlocks) {
5062
- output.stopReason = "toolUse";
5063
- } else if (output.stopReason === "toolUse" && !hasToolCallBlocks) {
5064
- output.stopReason = "stop";
4987
+ if (typeof item.name === "string" && item.name.length > 0 && item.name !== state.block.name) {
4988
+ throw new ResponsesProtocolError(`function_call item changed name from "${state.block.name}" to "${item.name}".`);
4989
+ }
4990
+ state.completed = true;
4991
+ state.finalArgs = finalText;
4992
+ if (this.canParseArgs(state)) {
4993
+ return this.finalizeFunctionCall(state, finalText);
4994
+ }
4995
+ return [];
5065
4996
  }
5066
- if (options?.signal?.aborted) {
5067
- throw new Error("Request was aborted");
4997
+ case "ignored":
4998
+ return [];
4999
+ }
5000
+ }
5001
+ finalizeFunctionCall(state, argsText) {
5002
+ const text = argsText.trim();
5003
+ let parsed;
5004
+ if (text.length === 0) {
5005
+ parsed = {};
5006
+ } else {
5007
+ try {
5008
+ const value = JSON.parse(text);
5009
+ if (!isRecord(value)) {
5010
+ throw new ResponsesProtocolError(`function_call "${state.block.name || "unknown"}" arguments are not a JSON object.`);
5011
+ }
5012
+ parsed = value;
5013
+ } catch (error) {
5014
+ if (error instanceof ResponsesProtocolError) throw error;
5015
+ const message = error instanceof Error ? error.message : String(error);
5016
+ throw new ResponsesProtocolError(
5017
+ `function_call "${state.block.name || "unknown"}" returned incomplete or invalid JSON arguments: ${message}`
5018
+ );
5068
5019
  }
5069
- if (output.stopReason === "aborted" || output.stopReason === "error") {
5070
- throw new Error("An unknown error occurred");
5020
+ }
5021
+ state.block.arguments = parsed;
5022
+ return [{ type: "toolcall_end", contentIndex: state.contentIndex, toolCall: state.block, partial: this.output }];
5023
+ }
5024
+ // ─── terminals ──────────────────────────────────────────────────────────
5025
+ requireTerminalResponse(raw) {
5026
+ const response = raw.response;
5027
+ const expected = raw.type.slice("response.".length);
5028
+ if (!isRecord(response) || typeof response.id !== "string" || !response.id || response.status !== expected) {
5029
+ throw new ResponsesProtocolError(`Malformed ${raw.type}: requires response id and status ${expected}.`);
5030
+ }
5031
+ return response;
5032
+ }
5033
+ onTerminal(raw, type, reason = "stop", errorText) {
5034
+ this.diagnostics.terminalType = type;
5035
+ const response = type === "error" ? void 0 : this.requireTerminalResponse(raw);
5036
+ this.terminal = { reason, response, errorText };
5037
+ return this.closeResponse(type);
5038
+ }
5039
+ onIncomplete(raw) {
5040
+ this.diagnostics.terminalType = "response.incomplete";
5041
+ const response = this.requireTerminalResponse(raw);
5042
+ const reason = response?.incomplete_details?.reason;
5043
+ if (reason === "content_filter" || reason === "steered" || reason === void 0) {
5044
+ this.terminal = {
5045
+ reason: "error",
5046
+ response,
5047
+ errorText: reason === "steered" ? "Response ended incomplete with reason 'steered' but no steering was sent." : `Response ended incomplete${reason ? ` (${reason})` : " without a reason"}.`
5048
+ };
5049
+ return this.closeResponse("response.incomplete");
5050
+ }
5051
+ this.terminal = { reason: "length", response };
5052
+ return this.closeResponse("response.incomplete");
5053
+ }
5054
+ failedText(raw) {
5055
+ const response = isRecord(raw.response) ? raw.response : void 0;
5056
+ const error = isRecord(response?.error) ? response?.error : void 0;
5057
+ const message = typeof error?.message === "string" && error.message.length > 0 ? error.message : "Response failed";
5058
+ const code = typeof error?.code === "string" && error.code.length > 0 ? ` (code=${error.code})` : "";
5059
+ return `${message}${code}`;
5060
+ }
5061
+ /** Apply terminal semantics and produce the final event. */
5062
+ closeResponse(terminalType) {
5063
+ const terminal = this.terminal;
5064
+ const response = terminal.response;
5065
+ if (response && isRecord(response.usage)) {
5066
+ this.output.usage = normalizeResponsesUsage(this.model, response.usage);
5067
+ this.output.usageReported = [response.usage.input_tokens, response.usage.output_tokens].every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
5068
+ }
5069
+ if (terminal.reason === "error") {
5070
+ this.output.stopReason = "error";
5071
+ this.output.errorMessage = terminal.errorText ?? "Response failed";
5072
+ return [{ type: "error", reason: "error", error: this.output }];
5073
+ }
5074
+ let stopReason = terminal.reason === "length" ? "length" : "stop";
5075
+ if (this.toolCallStates.length > 0) {
5076
+ stopReason = "toolUse";
5077
+ }
5078
+ if (terminal.reason === "length") {
5079
+ const truncated = this.toolCallStates.filter((state) => !state.completed || !this.canParseArgs(state));
5080
+ if (truncated.length > 0) {
5081
+ const dropped = new Set(truncated.map((state) => state.block));
5082
+ this.output.content = this.output.content.filter(
5083
+ (block) => block.type !== "toolCall" || !dropped.has(block)
5084
+ );
5085
+ this.toolCallStates = this.toolCallStates.filter((state) => !dropped.has(state.block));
5086
+ this.output.content.push({
5087
+ type: "text",
5088
+ text: `[output truncated: max_output_tokens cut ${truncated.length === 1 ? "a tool call" : `${truncated.length} tool calls`} mid-arguments (${summarizeTruncatedCallNames(truncated.map((state) => state.block.name))}); the call${truncated.length === 1 ? " was" : "s were"} dropped. Re-issue the call or continue with fewer/smaller requests.]`
5089
+ });
5090
+ if (this.toolCallStates.length === 0) {
5091
+ stopReason = "length";
5092
+ }
5071
5093
  }
5072
- assertAssistantHasContent(output);
5073
- resetOpenAICompatFirstByteTimeoutEscalation(model);
5074
- stream2.push({ type: "done", reason: output.stopReason, message: output });
5075
- stream2.end();
5076
- } catch (error) {
5077
- logEmptyAssistantContentError(error, model, options);
5078
- if (error instanceof Error && error.message.includes("Request timeout (first byte)")) {
5079
- noteOpenAICompatFirstByteTimeout(model);
5094
+ } else if (terminal.reason === "stop") {
5095
+ const brokenCalls = this.toolCallStates.filter((state) => !state.completed || !this.canParseArgs(state));
5096
+ if (brokenCalls.length > 0) {
5097
+ const first = brokenCalls[0];
5098
+ this.output.stopReason = "error";
5099
+ this.output.errorMessage = `function_call "${first.block.name || "unknown"}" returned incomplete or invalid JSON arguments on a completed response.`;
5100
+ return [{ type: "error", reason: "error", error: this.output }];
5080
5101
  }
5081
- output.stopReason = options?.signal?.aborted ? "aborted" : "error";
5082
- output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
5083
- stream2.push({ type: "error", reason: output.stopReason, error: output });
5084
- stream2.end();
5085
5102
  }
5086
- })();
5087
- return stream2;
5088
- };
5089
- var streamSimpleOpenAICompletions = (model, context, options) => {
5090
- const apiKey = options?.apiKey || getEnvApiKey(model.provider, model.apiKeyEnv);
5091
- if (!apiKey) {
5092
- throw new Error(`No API key for provider: ${model.provider}`);
5093
- }
5094
- const base = buildBaseOptions(model, options, apiKey);
5095
- const reasoningEffort = clampReasoning(options?.reasoning);
5096
- const needsThinkingAllowance = Boolean(model.reasoning) && options?.reasoning !== void 0;
5097
- const adjusted = needsThinkingAllowance ? adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options?.thinkingBudgets) : void 0;
5098
- let maxTokens = adjusted ? adjusted.maxTokens : base.maxTokens;
5099
- if (maxTokens === void 0) {
5100
- maxTokens = DEFAULT_MAX_TOKENS;
5103
+ if (stopReason === "toolUse" && this.toolCallStates.length === 0) {
5104
+ stopReason = "stop";
5105
+ }
5106
+ this.output.stopReason = stopReason;
5107
+ void terminalType;
5108
+ return [{ type: "done", reason: stopReason, message: this.output }];
5101
5109
  }
5102
- if (options?.maxTokens === void 0) {
5103
- maxTokens = Math.min(maxTokens, DEFAULT_MAX_TOKENS);
5110
+ canParseArgs(state) {
5111
+ const text = (state.finalArgs ?? state.partialArgs).trim();
5112
+ if (text.length === 0) return false;
5113
+ try {
5114
+ return isRecord(JSON.parse(text));
5115
+ } catch {
5116
+ return false;
5117
+ }
5104
5118
  }
5105
- return streamOpenAICompletions(model, context, {
5106
- ...base,
5107
- maxTokens,
5108
- reasoningEffort
5109
- });
5110
5119
  };
5111
-
5112
- // ../../packages/ai/src/providers/anthropic.ts
5113
- import Anthropic from "@anthropic-ai/sdk";
5114
- function sanitizeSurrogates(text) {
5115
- return text.replace(/[\uD800-\uDFFF]/g, "");
5116
- }
5117
- function applyAnthropicUsageUpdate(model, usage, payload) {
5118
- if (payload.input_tokens != null) usage.input = Math.max(0, payload.input_tokens);
5119
- if (payload.output_tokens != null) usage.output = Math.max(0, payload.output_tokens);
5120
- if (payload.cache_read_input_tokens != null) usage.cacheRead = Math.max(0, payload.cache_read_input_tokens);
5121
- const reportedWriteTotal = payload.cache_creation_input_tokens;
5122
- const breakdown = payload.cache_creation ?? void 0;
5123
- const breakdownTotal = (breakdown?.ephemeral_5m_input_tokens ?? 0) + (breakdown?.ephemeral_1h_input_tokens ?? 0);
5124
- if (reportedWriteTotal == null && breakdown !== void 0 && breakdownTotal === 0) {
5125
- usage.cacheWrite = Math.max(0, usage.cacheWrite);
5126
- } else if (reportedWriteTotal != null || breakdown !== void 0) {
5127
- const previousLong = usage.cacheWriteLong ?? 0;
5128
- const previousTotal = usage.cacheWrite + previousLong;
5129
- const writeTotal = Math.max(
5130
- 0,
5131
- reportedWriteTotal != null ? reportedWriteTotal : breakdownTotal > 0 ? breakdownTotal : previousTotal
5132
- );
5133
- const longTokens = breakdown?.ephemeral_1h_input_tokens ?? 0;
5134
- if (longTokens > 0) {
5135
- const long = Math.min(longTokens, writeTotal);
5136
- usage.cacheWriteLong = long;
5137
- usage.cacheWrite = writeTotal - long;
5138
- } else {
5139
- delete usage.cacheWriteLong;
5140
- usage.cacheWrite = writeTotal;
5120
+ var TRUNCATED_NAME_LIST_LIMIT = 8;
5121
+ var TRUNCATED_NAME_CLIP_BYTES = 48;
5122
+ var TRUNCATED_NAME_SUMMARY_BUDGET_BYTES = 512;
5123
+ function utf8Size(value) {
5124
+ let bytes = 0;
5125
+ for (const character of value) {
5126
+ const point = character.codePointAt(0);
5127
+ bytes += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
5128
+ }
5129
+ return bytes;
5130
+ }
5131
+ function clipUtf8(value, maxBytes) {
5132
+ if (utf8Size(value) <= maxBytes) return { text: value, clipped: false };
5133
+ const ellipsisBytes = utf8Size("\u2026");
5134
+ let bytes = 0;
5135
+ let cut = 0;
5136
+ for (const character of value) {
5137
+ const size = character.codePointAt(0) <= 127 ? 1 : character.codePointAt(0) <= 2047 ? 2 : character.codePointAt(0) <= 65535 ? 3 : 4;
5138
+ if (bytes + size > maxBytes - ellipsisBytes) break;
5139
+ bytes += size;
5140
+ cut += character.length;
5141
+ }
5142
+ return { text: value.slice(0, cut) + "\u2026", clipped: true };
5143
+ }
5144
+ function summarizeTruncatedCallNames(names) {
5145
+ const counts = /* @__PURE__ */ new Map();
5146
+ let unnamed = 0;
5147
+ for (const name of names) {
5148
+ if (typeof name !== "string" || name.length === 0) {
5149
+ unnamed += 1;
5150
+ continue;
5141
5151
  }
5152
+ counts.set(name, (counts.get(name) ?? 0) + 1);
5142
5153
  }
5143
- usage.totalTokens = usage.input + usage.output + usage.cacheRead + usage.cacheWrite + (usage.cacheWriteLong ?? 0);
5144
- usage.cost = calculateCost(model, usage);
5154
+ const render = (name, count) => {
5155
+ const clipped = clipUtf8(name, TRUNCATED_NAME_CLIP_BYTES);
5156
+ const shown = JSON.stringify(clipped.text);
5157
+ return count === 1 ? shown : `${shown}\xD7${count}`;
5158
+ };
5159
+ const entries = [...counts.entries()].sort(([a], [b]) => a.localeCompare(b));
5160
+ const parts = entries.length <= TRUNCATED_NAME_LIST_LIMIT ? entries.map(([name, count]) => render(name, count)) : [`${entries.length} distinct names`, `(${render(entries[0][0], entries[0][1])}, \u2026)`];
5161
+ if (unnamed > 0) parts.push(`${unnamed} unnamed call${unnamed === 1 ? "" : "s"}`);
5162
+ let summary = parts.join(", ");
5163
+ if (utf8Size(summary) > TRUNCATED_NAME_SUMMARY_BUDGET_BYTES) {
5164
+ summary = `${entries.length} distinct names, ${unnamed} unnamed calls`;
5165
+ }
5166
+ return summary;
5145
5167
  }
5146
- var ANTHROPIC_PROVIDER_HEADERS = {
5147
- accept: "application/json",
5148
- "anthropic-dangerous-direct-browser-access": "true",
5149
- "anthropic-version": "2023-06-01"
5168
+
5169
+ // ../../packages/ai/src/providers/responses/sse-dump.ts
5170
+ var CAPTURE_ENABLED_VALUES = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
5171
+ var MAX_CAPTURE_BYTES = 4 * 1024 * 1024;
5172
+ var DUMP_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
5173
+ var MAX_DUMP_FILES = 400;
5174
+ var MAX_PRUNE_STAT = 200;
5175
+ var MAX_PRUNE_UNLINK = 50;
5176
+ function isSseDumpEnabled(env = readEnv()) {
5177
+ try {
5178
+ return CAPTURE_ENABLED_VALUES.has((env.PIE_DEBUG_SSE ?? "").trim().toLowerCase());
5179
+ } catch {
5180
+ return false;
5181
+ }
5182
+ }
5183
+ function readEnv() {
5184
+ const proc = globalThis.process;
5185
+ return proc?.env ?? {};
5186
+ }
5187
+ var NullSseDumpSink = class {
5188
+ record() {
5189
+ }
5190
+ async flush() {
5191
+ }
5150
5192
  };
5151
- function buildAnthropicHeaders(modelHeaders, runtimeHeaders, includeLongCacheBeta) {
5152
- const merged = /* @__PURE__ */ new Map();
5153
- for (const layer of [ANTHROPIC_PROVIDER_HEADERS, modelHeaders, runtimeHeaders]) {
5154
- for (const [key, value] of Object.entries(layer ?? {})) {
5155
- const normalizedKey = key.toLowerCase();
5156
- if (normalizedKey && normalizedKey !== "anthropic-beta") {
5157
- merged.set(normalizedKey, value);
5193
+ var NULL_SSE_DUMP_SINK = new NullSseDumpSink();
5194
+ var BoundedSseDumpSink = class {
5195
+ constructor(directory, fileName, fs) {
5196
+ this.directory = directory;
5197
+ this.fileName = fileName;
5198
+ this.fs = fs;
5199
+ }
5200
+ directory;
5201
+ fileName;
5202
+ fs;
5203
+ lines = [];
5204
+ bytes = 0;
5205
+ truncated = false;
5206
+ flushed = false;
5207
+ record(event) {
5208
+ if (this.flushed || this.truncated) return;
5209
+ try {
5210
+ const line = JSON.stringify(event) + "\n";
5211
+ const size = utf8Length(line);
5212
+ if (this.bytes + size > MAX_CAPTURE_BYTES) {
5213
+ this.truncated = true;
5214
+ return;
5158
5215
  }
5216
+ this.bytes += size;
5217
+ this.lines.push(line);
5218
+ } catch {
5219
+ this.truncated = true;
5159
5220
  }
5160
5221
  }
5161
- const betaFeatures = includeLongCacheBeta ? ["extended-cache-ttl-2025-04-11"] : [];
5162
- for (const layer of [modelHeaders, runtimeHeaders]) {
5163
- for (const [key, value] of Object.entries(layer ?? {})) {
5164
- if (key.toLowerCase() !== "anthropic-beta") continue;
5165
- for (const feature of value.split(",")) {
5166
- const trimmed = feature.trim();
5167
- if (trimmed) betaFeatures.push(trimmed);
5222
+ async flush() {
5223
+ if (this.flushed) return;
5224
+ this.flushed = true;
5225
+ try {
5226
+ if (this.lines.length === 0) return;
5227
+ await this.fs.mkdir(this.directory, { recursive: true });
5228
+ await this.fs.writeFile(this.path(), this.header() + this.lines.join(""));
5229
+ await this.pruneOld();
5230
+ } catch {
5231
+ }
5232
+ }
5233
+ path() {
5234
+ return this.fs.join(this.directory, this.fileName);
5235
+ }
5236
+ header() {
5237
+ const meta = JSON.stringify({
5238
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
5239
+ truncated: this.truncated,
5240
+ events: this.lines.length,
5241
+ bytes: this.bytes
5242
+ });
5243
+ return `# ${meta}
5244
+ `;
5245
+ }
5246
+ async pruneOld() {
5247
+ try {
5248
+ const names = await this.fs.readdir(this.directory);
5249
+ const eligible = names.filter((name) => name.endsWith(".ndjson"));
5250
+ if (eligible.length <= MAX_DUMP_FILES && eligible.length === 0) return;
5251
+ const sample = eligible.slice(0, MAX_PRUNE_STAT);
5252
+ const dated = [];
5253
+ for (const name of sample) {
5254
+ try {
5255
+ const stat = await this.fs.stat(this.fs.join(this.directory, name));
5256
+ dated.push({ name, mtimeMs: stat.mtime.getTime() });
5257
+ } catch {
5258
+ }
5259
+ }
5260
+ dated.sort((a, b) => a.mtimeMs - b.mtimeMs);
5261
+ const expired = dated.filter((entry) => Date.now() - entry.mtimeMs > DUMP_TTL_MS);
5262
+ const excessCount = Math.max(0, eligible.length - MAX_DUMP_FILES);
5263
+ const excess = excessCount > 0 ? dated.slice(0, Math.min(excessCount, dated.length)) : [];
5264
+ let removed = 0;
5265
+ for (const entry of /* @__PURE__ */ new Set([...expired, ...excess])) {
5266
+ if (removed >= MAX_PRUNE_UNLINK) break;
5267
+ try {
5268
+ await this.fs.unlink(this.fs.join(this.directory, entry.name));
5269
+ removed += 1;
5270
+ } catch {
5271
+ }
5168
5272
  }
5273
+ } catch {
5169
5274
  }
5170
5275
  }
5171
- if (betaFeatures.length > 0) {
5172
- merged.set("anthropic-beta", [...new Set(betaFeatures)].join(","));
5276
+ };
5277
+ function openSseDumpSink(requestId, modelLabel) {
5278
+ try {
5279
+ if (!isSseDumpEnabled()) return NULL_SSE_DUMP_SINK;
5280
+ let fs;
5281
+ try {
5282
+ fs = getFileSystem();
5283
+ } catch {
5284
+ return NULL_SSE_DUMP_SINK;
5285
+ }
5286
+ if (!fs || typeof fs.writeFile !== "function") return NULL_SSE_DUMP_SINK;
5287
+ const dir = sseDumpDirectory();
5288
+ if (!dir) return NULL_SSE_DUMP_SINK;
5289
+ const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
5290
+ return new BoundedSseDumpSink(dir, `${stamp}__${sanitize(modelLabel)}__${sanitize(requestId)}.ndjson`, fs);
5291
+ } catch {
5292
+ return NULL_SSE_DUMP_SINK;
5173
5293
  }
5174
- return Object.fromEntries(merged);
5175
5294
  }
5176
- function normalizeToolCallId(id) {
5177
- return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
5295
+ function sanitize(token) {
5296
+ const cleaned = token.replace(/[^A-Za-z0-9._-]+/g, "_").slice(0, 80);
5297
+ return cleaned || "unknown";
5178
5298
  }
5179
- function mapStopReason(reason) {
5180
- switch (reason) {
5181
- case "end_turn":
5182
- return "stop";
5183
- case "max_tokens":
5184
- return "length";
5185
- case "tool_use":
5186
- return "toolUse";
5187
- default:
5188
- return "stop";
5299
+ function sseDumpDirectory() {
5300
+ const env = readEnv();
5301
+ const custom = env.PIE_DEBUG_SSE_DIR;
5302
+ if (custom && custom.trim()) {
5303
+ return custom.trim();
5189
5304
  }
5305
+ const proc = globalThis.process;
5306
+ const home = proc?.env?.HOME;
5307
+ if (!home) return void 0;
5308
+ return `${home}/.pie/logs/sse-dump`;
5190
5309
  }
5191
- function convertContentBlocks(content) {
5192
- const hostBlock = content.find((block) => block.type === "hostContext");
5193
- if (hostBlock) {
5194
- throw new Error(`Unprojected hostContext block reached anthropic conversion (${hostBlock.kind}); the request path must project host envelopes to text first.`);
5310
+ function utf8Length(value) {
5311
+ let bytes = 0;
5312
+ for (const character of value) {
5313
+ const point = character.codePointAt(0);
5314
+ bytes += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
5195
5315
  }
5196
- const supportedBlocks = content.map((block) => block.type === "text" || block.type === "image" ? block : { type: "text", text: `[${block.type} attachment omitted: unsupported by this provider. Re-read with a compatible model.]` });
5197
- const hasImages = supportedBlocks.some((c) => c.type === "image");
5198
- if (!hasImages) {
5199
- const text = supportedBlocks.filter((c) => c.type === "text").map((c) => c.text).join("\n");
5200
- return sanitizeSurrogates(text || "(unsupported tool result omitted)");
5316
+ return bytes;
5317
+ }
5318
+
5319
+ // ../../packages/ai/src/providers/responses/responses-diagnostics.ts
5320
+ function reportSubmission(options, body, details) {
5321
+ if (!options?.onTransportDiagnostic) return;
5322
+ let requestBytes = 0;
5323
+ for (const character of body) {
5324
+ const point = character.codePointAt(0);
5325
+ requestBytes += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
5201
5326
  }
5202
- const blocks = supportedBlocks.map((block) => {
5203
- if (block.type === "text") {
5204
- return { type: "text", text: sanitizeSurrogates(block.text) };
5205
- }
5206
- return {
5207
- type: "image",
5208
- source: {
5209
- type: "base64",
5210
- media_type: block.mimeType,
5211
- data: block.data
5212
- }
5213
- };
5214
- });
5215
- const hasText = blocks.some((b) => b.type === "text");
5216
- if (!hasText) {
5217
- blocks.unshift({ type: "text", text: "(see attached image)" });
5327
+ try {
5328
+ options.onTransportDiagnostic({ ...details, requestBytes });
5329
+ } catch {
5218
5330
  }
5219
- return blocks;
5220
5331
  }
5221
- function convertUserContentBlocks(content) {
5222
- const hostBlock = content.find((block) => block.type === "hostContext");
5223
- if (hostBlock) {
5224
- throw new Error(`Unprojected hostContext block reached anthropic user-message conversion (${hostBlock.kind}); the request path must project host envelopes to text first.`);
5332
+ function reportLifecycle(options, event) {
5333
+ if (!options?.onTransportLifecycle) return;
5334
+ try {
5335
+ options.onTransportLifecycle({ ...event });
5336
+ } catch {
5225
5337
  }
5226
- const blocks = [];
5227
- for (const item of content) {
5228
- if (item.type === "text") {
5229
- blocks.push({ type: "text", text: sanitizeSurrogates(item.text) });
5230
- continue;
5231
- }
5232
- if (item.type === "image") {
5233
- blocks.push({
5234
- type: "image",
5235
- source: {
5236
- type: "base64",
5237
- media_type: item.mimeType,
5238
- data: item.data
5239
- }
5240
- });
5241
- continue;
5242
- }
5243
- if (item.type === "video") {
5244
- const video = item;
5245
- blocks.push({
5246
- type: "text",
5247
- text: sanitizeSurrogates(`(video attachment omitted for anthropic provider: ${video.mimeType})`)
5248
- });
5249
- continue;
5250
- }
5251
- if (item.type === "fileRef") {
5252
- const ref = item;
5253
- blocks.push({
5254
- type: "text",
5255
- text: sanitizeSurrogates(`(file reference omitted for anthropic provider: ${ref.url})`)
5256
- });
5257
- }
5338
+ }
5339
+ var localRequestCounter = 0;
5340
+ function nextLocalRequestId(prefix = "req") {
5341
+ localRequestCounter += 1;
5342
+ return `${prefix}-${localRequestCounter}-${Math.random().toString(36).slice(2, 8)}`;
5343
+ }
5344
+ function timeoutSuffix(budgetMs, lagMs) {
5345
+ const budget = budgetMs && budgetMs > 0 ? ` (budget ${Math.round(budgetMs / 1e3)}s)` : "";
5346
+ if (lagMs > 1e3) {
5347
+ return `${budget} \u2014 timer fired ${Math.round(lagMs / 1e3)}s late (system sleep or suspended process)`;
5258
5348
  }
5259
- return blocks;
5349
+ return budget;
5260
5350
  }
5261
- function convertMessages2(messages, model) {
5262
- const params = [];
5263
- const transformedMessages = transformMessages(messages, model, normalizeToolCallId);
5264
- for (let i = 0; i < transformedMessages.length; i++) {
5265
- const msg = transformedMessages[i];
5266
- if (msg.role === "user") {
5267
- if (typeof msg.content === "string") {
5268
- if (msg.content.trim().length > 0) {
5269
- params.push({ role: "user", content: sanitizeSurrogates(msg.content) });
5270
- }
5271
- } else {
5272
- const blocks = convertUserContentBlocks(msg.content);
5273
- let filteredBlocks = !model?.input.includes("image") ? blocks.filter((b) => b.type !== "image") : blocks;
5274
- filteredBlocks = filteredBlocks.filter((b) => b.type === "text" ? b.text.trim().length > 0 : true);
5275
- if (filteredBlocks.length === 0) continue;
5276
- params.push({ role: "user", content: filteredBlocks });
5277
- }
5278
- } else if (msg.role === "assistant") {
5279
- const blocks = [];
5280
- for (const block of msg.content) {
5281
- if (block.type === "text") {
5282
- if (block.text.trim().length === 0) continue;
5283
- blocks.push({ type: "text", text: sanitizeSurrogates(block.text) });
5284
- } else if (block.type === "thinking") {
5285
- if (block.thinking.trim().length === 0) continue;
5286
- if (!block.thinkingSignature || block.thinkingSignature.trim().length === 0) {
5287
- blocks.push({ type: "text", text: sanitizeSurrogates(block.thinking) });
5288
- } else {
5289
- blocks.push({
5290
- type: "thinking",
5291
- thinking: sanitizeSurrogates(block.thinking),
5292
- signature: block.thinkingSignature
5293
- });
5294
- }
5295
- } else if (block.type === "toolCall") {
5296
- blocks.push({ type: "tool_use", id: block.id, name: block.name, input: block.arguments ?? {} });
5297
- }
5298
- }
5299
- if (blocks.length === 0) continue;
5300
- params.push({ role: "assistant", content: blocks });
5301
- } else if (msg.role === "toolResult") {
5302
- const toolResults = [];
5303
- toolResults.push({
5304
- type: "tool_result",
5305
- tool_use_id: msg.toolCallId,
5306
- content: convertContentBlocks(msg.content),
5307
- is_error: msg.isError
5308
- });
5309
- let j = i + 1;
5310
- while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
5311
- const nextMsg = transformedMessages[j];
5312
- toolResults.push({
5313
- type: "tool_result",
5314
- tool_use_id: nextMsg.toolCallId,
5315
- content: convertContentBlocks(nextMsg.content),
5316
- is_error: nextMsg.isError
5317
- });
5318
- j++;
5319
- }
5320
- i = j - 1;
5321
- params.push({ role: "user", content: toolResults });
5322
- }
5351
+ function monotonicNow() {
5352
+ const perf = globalThis.performance;
5353
+ return typeof perf?.now === "function" ? perf.now() : Date.now();
5354
+ }
5355
+
5356
+ // ../../packages/ai/src/providers/openai-compat.ts
5357
+ var DEFAULT_OPENAI_COMPAT_STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1e3;
5358
+ var DEFAULT_OPENAI_COMPAT_FIRST_BYTE_TIMEOUT_MS = 3 * 60 * 1e3;
5359
+ var OPENAI_COMPAT_FIRST_BYTE_MAX_ESCALATION_STEPS = 3;
5360
+ var openAICompatFirstByteTimeoutsByEndpoint = /* @__PURE__ */ new Map();
5361
+ var OPENAI_COMPAT_MAX_DUPLICATE_TOOL_CALLS = 3;
5362
+ var OPENAI_COMPAT_PROTOCOL_ERROR_CODE = "provider_response_protocol_error";
5363
+ var OpenAICompatProtocolError = class extends Error {
5364
+ code = OPENAI_COMPAT_PROTOCOL_ERROR_CODE;
5365
+ constructor(message) {
5366
+ super(`${OPENAI_COMPAT_PROTOCOL_ERROR_CODE}: ${message}`);
5367
+ this.name = "OpenAICompatProtocolError";
5368
+ }
5369
+ };
5370
+ function getOpenAICompatStreamTimeoutMs() {
5371
+ const value = Number(process.env.PIE_OPENAI_COMPAT_STREAM_TIMEOUT_MS || "");
5372
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_OPENAI_COMPAT_STREAM_IDLE_TIMEOUT_MS;
5373
+ }
5374
+ function getOpenAICompatFirstByteTimeoutBaseMs() {
5375
+ const value = Number(process.env.PIE_OPENAI_COMPAT_FIRST_BYTE_TIMEOUT_MS || "");
5376
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_OPENAI_COMPAT_FIRST_BYTE_TIMEOUT_MS;
5377
+ }
5378
+ function firstByteEscalationKey(model) {
5379
+ return `${model.provider}|${model.baseUrl}|${model.id}`;
5380
+ }
5381
+ function getOpenAICompatFirstByteTimeoutMs(model) {
5382
+ const base = getOpenAICompatFirstByteTimeoutBaseMs();
5383
+ const consecutive = openAICompatFirstByteTimeoutsByEndpoint.get(firstByteEscalationKey(model)) ?? 0;
5384
+ return base * 2 ** Math.min(consecutive, OPENAI_COMPAT_FIRST_BYTE_MAX_ESCALATION_STEPS);
5385
+ }
5386
+ function noteOpenAICompatFirstByteTimeout(model) {
5387
+ const key = firstByteEscalationKey(model);
5388
+ openAICompatFirstByteTimeoutsByEndpoint.set(key, (openAICompatFirstByteTimeoutsByEndpoint.get(key) ?? 0) + 1);
5389
+ }
5390
+ function resetOpenAICompatFirstByteTimeoutEscalation(model) {
5391
+ openAICompatFirstByteTimeoutsByEndpoint.delete(firstByteEscalationKey(model));
5392
+ }
5393
+ function normalizeTokenCount(value) {
5394
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
5395
+ return void 0;
5396
+ }
5397
+ return Math.floor(value);
5398
+ }
5399
+ function mergeOpenAIUsage(previous, usage) {
5400
+ return {
5401
+ promptTokens: normalizeTokenCount(usage?.prompt_tokens) ?? previous.promptTokens,
5402
+ completionTokens: normalizeTokenCount(usage?.completion_tokens) ?? previous.completionTokens,
5403
+ cachedTokens: normalizeTokenCount(usage?.prompt_tokens_details?.cached_tokens) ?? previous.cachedTokens,
5404
+ reasoningTokens: normalizeTokenCount(usage?.completion_tokens_details?.reasoning_tokens) ?? previous.reasoningTokens,
5405
+ totalTokens: normalizeTokenCount(usage?.total_tokens) ?? previous.totalTokens
5406
+ };
5407
+ }
5408
+ function normalizeOpenAIUsage(usage) {
5409
+ const reportedPromptTokens = usage.promptTokens;
5410
+ const reportedCachedTokens = usage.cachedTokens;
5411
+ const reportedCompletionTokens = usage.completionTokens;
5412
+ const reportedReasoningTokens = usage.reasoningTokens;
5413
+ const reportedTotalTokens = usage.totalTokens;
5414
+ const cachedTokens = reportedCachedTokens ?? 0;
5415
+ const promptTokens = reportedPromptTokens ?? (reportedTotalTokens !== void 0 && reportedCompletionTokens !== void 0 ? Math.max(cachedTokens, reportedTotalTokens - reportedCompletionTokens) : cachedTokens);
5416
+ const cacheRead = Math.min(cachedTokens, promptTokens);
5417
+ const input = promptTokens - cacheRead;
5418
+ const output = reportedCompletionTokens ?? (reportedTotalTokens !== void 0 ? Math.max(reportedReasoningTokens ?? 0, reportedTotalTokens - promptTokens) : reportedReasoningTokens ?? 0);
5419
+ const partitionTotal = promptTokens + output;
5420
+ return {
5421
+ input,
5422
+ output,
5423
+ cacheRead,
5424
+ totalTokens: Math.max(reportedTotalTokens ?? 0, partitionTotal)
5425
+ };
5426
+ }
5427
+ function formatOpenAIStreamError(error) {
5428
+ if (!error || typeof error !== "object") {
5429
+ return typeof error === "string" ? error : "OpenAI-compatible stream returned an error";
5323
5430
  }
5324
- return params;
5431
+ const message = typeof error.message === "string" && error.message.length > 0 ? error.message : "OpenAI-compatible stream returned an error";
5432
+ const metadata = [];
5433
+ if (typeof error.type === "string" && error.type.length > 0) {
5434
+ metadata.push(`type=${error.type}`);
5435
+ }
5436
+ if (typeof error.code === "string" && error.code.length > 0) {
5437
+ metadata.push(`code=${error.code}`);
5438
+ }
5439
+ return metadata.length > 0 ? `${message} (${metadata.join(", ")})` : message;
5325
5440
  }
5326
- function convertTools2(tools) {
5327
- if (!tools) return [];
5328
- return tools.map((tool) => {
5329
- const jsonSchema = tool.parameters;
5330
- return {
5331
- name: tool.name,
5332
- description: tool.description,
5333
- input_schema: {
5334
- type: "object",
5335
- properties: jsonSchema.properties || {},
5336
- required: jsonSchema.required || []
5337
- }
5338
- };
5339
- });
5441
+ function isRecord2(value) {
5442
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5340
5443
  }
5341
- function applyCacheBreakpoints(params, retention) {
5342
- if (retention === "none") return;
5343
- const cacheControl = {
5344
- type: "ephemeral",
5345
- ...retention === "long" ? { ttl: "1h" } : {}
5346
- };
5347
- if (Array.isArray(params.system) && params.system.length > 0) {
5348
- const last = params.system[params.system.length - 1];
5349
- last.cache_control = { ...cacheControl };
5444
+ function createProtocolError(message) {
5445
+ return new OpenAICompatProtocolError(message);
5446
+ }
5447
+ function parseSSEDataLine(line) {
5448
+ const trimmed = line.trim();
5449
+ if (!trimmed || trimmed.startsWith(":")) return null;
5450
+ if (!trimmed.startsWith("data:")) return null;
5451
+ const data = trimmed.slice(5);
5452
+ return data.startsWith(" ") ? data.slice(1) : data;
5453
+ }
5454
+ function parseFinalToolArguments(partialArgs, toolName) {
5455
+ const text = partialArgs.trim();
5456
+ if (!text) return {};
5457
+ let parsed;
5458
+ try {
5459
+ parsed = JSON.parse(text);
5460
+ } catch (error) {
5461
+ const message = error instanceof Error ? error.message : String(error);
5462
+ throw createProtocolError(`OpenAI-compatible stream returned incomplete or invalid JSON arguments for tool "${toolName || "unknown"}": ${message}`);
5350
5463
  }
5351
- if (Array.isArray(params.tools) && params.tools.length > 0) {
5352
- const last = params.tools[params.tools.length - 1];
5353
- last.cache_control = { ...cacheControl };
5464
+ if (!isRecord2(parsed)) {
5465
+ throw createProtocolError(`OpenAI-compatible stream returned non-object JSON arguments for tool "${toolName || "unknown"}".`);
5354
5466
  }
5355
- for (let i = params.messages.length - 1; i >= 0; i--) {
5356
- const msg = params.messages[i];
5357
- if (msg.role !== "user") continue;
5358
- if (typeof msg.content === "string") {
5359
- msg.content = [{ type: "text", text: msg.content, cache_control: { ...cacheControl } }];
5360
- } else if (Array.isArray(msg.content) && msg.content.length > 0) {
5361
- msg.content[msg.content.length - 1].cache_control = { ...cacheControl };
5362
- }
5363
- break;
5467
+ return parsed;
5468
+ }
5469
+ function tryParseFinalToolArguments(partialArgs) {
5470
+ const text = partialArgs.trim();
5471
+ if (!text) return null;
5472
+ try {
5473
+ const parsed = JSON.parse(text);
5474
+ return isRecord2(parsed) ? parsed : null;
5475
+ } catch {
5476
+ return null;
5364
5477
  }
5365
5478
  }
5366
- var streamAnthropic = (model, context, options) => {
5479
+ var streamOpenAICompletions = (model, context, options) => {
5367
5480
  if ((options?.transport ?? model.transport) === "websocket") throw new Error(`API ${model.api} does not support WebSocket transport.`);
5368
5481
  const stream2 = new AssistantMessageEventStream();
5369
5482
  (async () => {
5483
+ const sseDump = openSseDumpSink(`compat-${nextLocalRequestId("compat")}`, `${model.provider}/${model.id}`);
5370
5484
  const output = {
5371
5485
  role: "assistant",
5372
5486
  content: [],
@@ -5385,1020 +5499,1106 @@ var streamAnthropic = (model, context, options) => {
5385
5499
  timestamp: Date.now()
5386
5500
  };
5387
5501
  try {
5388
- const apiKey = options?.apiKey ?? getEnvApiKey(model.provider, model.apiKeyEnv) ?? "";
5389
- const cacheCapability = getModelCacheCapability(model);
5390
- const promptCacheSupported = cacheCapability.supported && isPromptCacheCapability(cacheCapability);
5391
- const headers = buildAnthropicHeaders(
5392
- model.headers,
5393
- options?.headers,
5394
- promptCacheSupported && options?.cacheRetention === "long"
5395
- );
5396
- const client = new Anthropic({
5397
- apiKey,
5398
- baseURL: model.baseUrl,
5399
- dangerouslyAllowBrowser: true,
5400
- defaultHeaders: headers
5401
- });
5402
- const params = {
5403
- model: model.id,
5404
- messages: convertMessages2(context.messages, model),
5405
- max_tokens: options?.maxTokens || Math.floor(model.maxTokens / 3) || 1024,
5406
- stream: true
5407
- };
5408
- if (context.systemPrompt) {
5409
- params.system = [{ type: "text", text: sanitizeSurrogates(context.systemPrompt) }];
5410
- }
5411
- if (options?.temperature !== void 0) {
5412
- params.temperature = options.temperature;
5502
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider, model.apiKeyEnv) || "";
5503
+ if (!apiKey) {
5504
+ throw new Error(`No API key for provider: ${model.provider}`);
5413
5505
  }
5414
- if (context.tools?.length) {
5415
- params.tools = convertTools2(context.tools);
5506
+ const compat = getCompat(model);
5507
+ const params = buildOpenAIChatCompletionsPayload(model, context, options, compat);
5508
+ options?.onPayload?.(params);
5509
+ const headers = {
5510
+ "Content-Type": "application/json",
5511
+ Authorization: `Bearer ${apiKey}`,
5512
+ // Some OpenAI-compatible providers require caller-supplied SSE headers.
5513
+ ...model.headers || {},
5514
+ ...options?.headers || {}
5515
+ };
5516
+ const response = await httpRequest(`${model.baseUrl}/chat/completions`, {
5517
+ method: "POST",
5518
+ headers,
5519
+ body: JSON.stringify(params),
5520
+ signal: options?.signal,
5521
+ // Tiered timeouts unless the caller pinned a total budget: a first-byte
5522
+ // budget (escalates across consecutive timeouts so slow-thinking
5523
+ // providers with hidden reasoning are not killed repeatedly) plus a
5524
+ // stream-idle budget that any traffic resets.
5525
+ ...options?.timeoutMs !== void 0 ? { timeoutMs: options.timeoutMs } : {
5526
+ firstByteTimeoutMs: getOpenAICompatFirstByteTimeoutMs(model),
5527
+ streamIdleTimeoutMs: getOpenAICompatStreamTimeoutMs()
5528
+ },
5529
+ // Log attribution only (never sent over the wire).
5530
+ label: `${model.provider}/${model.id}`
5531
+ });
5532
+ if (!response.ok) {
5533
+ const errorBody = await response.text().catch(() => "");
5534
+ throw new Error(`API error ${response.status}: ${errorBody}`);
5416
5535
  }
5417
- if (options?.thinkingEnabled && model.reasoning) {
5418
- params.thinking = {
5419
- type: "enabled",
5420
- budget_tokens: options.thinkingBudgetTokens || 1024
5536
+ stream2.push({ type: "start", partial: output });
5537
+ let currentBlock = null;
5538
+ const blocks = output.content;
5539
+ const blockIndex = () => blocks.length - 1;
5540
+ const toolCallEntries = [];
5541
+ const toolCallsByIndex = /* @__PURE__ */ new Map();
5542
+ const toolCallsById = /* @__PURE__ */ new Map();
5543
+ let usageSnapshot = {};
5544
+ let sawDone = false;
5545
+ let sawFinishReason = false;
5546
+ let rawFinishReason = null;
5547
+ const createToolCallEntry = (toolCall, index) => {
5548
+ const block = {
5549
+ type: "toolCall",
5550
+ id: toolCall.id || "",
5551
+ name: toolCall.function?.name || "",
5552
+ arguments: {}
5421
5553
  };
5422
- }
5423
- if (options?.toolChoice) {
5424
- if (typeof options.toolChoice === "string") {
5425
- params.tool_choice = { type: options.toolChoice };
5426
- } else {
5427
- params.tool_choice = options.toolChoice;
5554
+ output.content.push(block);
5555
+ const entry = { block, partialArgs: "", contentIndex: blockIndex(), index };
5556
+ toolCallEntries.push(entry);
5557
+ stream2.push({
5558
+ type: "toolcall_start",
5559
+ contentIndex: entry.contentIndex,
5560
+ partial: output
5561
+ });
5562
+ return entry;
5563
+ };
5564
+ const bindToolCallIndex = (index, entry) => {
5565
+ const existing = toolCallsByIndex.get(index);
5566
+ if (existing && existing !== entry) {
5567
+ throw createProtocolError(`OpenAI-compatible stream reused tool call index ${index} for multiple calls.`);
5568
+ }
5569
+ if (entry.index !== void 0 && entry.index !== index) {
5570
+ throw createProtocolError(`OpenAI-compatible stream moved tool call "${entry.block.id || entry.block.name || "unknown"}" from index ${entry.index} to ${index}.`);
5571
+ }
5572
+ entry.index = index;
5573
+ toolCallsByIndex.set(index, entry);
5574
+ };
5575
+ const rememberToolCallId = (id, entry) => {
5576
+ const existing = toolCallsById.get(id);
5577
+ if (existing && existing !== entry) {
5578
+ throw createProtocolError(`OpenAI-compatible stream reused tool call id "${id}" for multiple calls.`);
5579
+ }
5580
+ if (entry.block.id && entry.block.id !== id) {
5581
+ throw createProtocolError(`OpenAI-compatible stream changed tool call id from "${entry.block.id}" to "${id}".`);
5582
+ }
5583
+ entry.block.id = id;
5584
+ toolCallsById.set(id, entry);
5585
+ };
5586
+ const resolveToolCallEntry = (toolCall, toolCallCount) => {
5587
+ const id = typeof toolCall.id === "string" && toolCall.id.length > 0 ? toolCall.id : "";
5588
+ if (Number.isInteger(toolCall.index) && toolCall.index >= 0) {
5589
+ let entry = toolCallsByIndex.get(toolCall.index);
5590
+ if (entry && id && entry.block.id && entry.block.id !== id) {
5591
+ throw createProtocolError(`OpenAI-compatible stream changed tool call id at index ${toolCall.index} from "${entry.block.id}" to "${id}".`);
5592
+ }
5593
+ if (!entry && id) {
5594
+ entry = toolCallsById.get(id);
5595
+ if (entry) bindToolCallIndex(toolCall.index, entry);
5596
+ }
5597
+ if (!entry) {
5598
+ entry = createToolCallEntry(toolCall, toolCall.index);
5599
+ bindToolCallIndex(toolCall.index, entry);
5600
+ }
5601
+ if (id) rememberToolCallId(id, entry);
5602
+ return entry;
5603
+ }
5604
+ if (id) {
5605
+ let entry = toolCallsById.get(id);
5606
+ if (!entry) {
5607
+ const unpaired = toolCallEntries.filter((candidate) => !candidate.block.id);
5608
+ if (unpaired.length === 1) {
5609
+ rememberToolCallId(id, unpaired[0]);
5610
+ return unpaired[0];
5611
+ }
5612
+ if (unpaired.length > 1) {
5613
+ throw createProtocolError(`OpenAI-compatible stream returned tool call id "${id}" without an index while multiple unnamed calls are in flight; the call cannot be disambiguated.`);
5614
+ }
5615
+ entry = createToolCallEntry(toolCall);
5616
+ rememberToolCallId(id, entry);
5617
+ }
5618
+ return entry;
5619
+ }
5620
+ if (toolCallEntries.length === 1) {
5621
+ return toolCallEntries[0];
5622
+ }
5623
+ if (toolCallEntries.length === 0 && toolCallCount === 1) {
5624
+ return createToolCallEntry(toolCall);
5428
5625
  }
5429
- }
5430
- if (promptCacheSupported) {
5431
- applyCacheBreakpoints(params, options?.cacheRetention);
5432
- }
5433
- options?.onPayload?.(params);
5434
- const anthropicStream = client.messages.stream({ ...params, stream: true }, { signal: options?.signal });
5435
- stream2.push({ type: "start", partial: output });
5436
- const blocks = output.content;
5437
- let hasReportedInputUsage = false;
5438
- for await (const event of anthropicStream) {
5439
- if (event.type === "message_start") {
5440
- applyAnthropicUsageUpdate(model, output.usage, event.message.usage);
5441
- hasReportedInputUsage = typeof event.message.usage.input_tokens === "number" && Number.isFinite(event.message.usage.input_tokens) && event.message.usage.input_tokens >= 0;
5442
- output.usageReported = false;
5443
- } else if (event.type === "content_block_start") {
5444
- if (event.content_block.type === "text") {
5445
- const block = { type: "text", text: "", index: event.index };
5446
- output.content.push(block);
5447
- stream2.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output });
5448
- } else if (event.content_block.type === "thinking") {
5449
- const block = { type: "thinking", thinking: "", thinkingSignature: "", index: event.index };
5450
- output.content.push(block);
5626
+ throw createProtocolError("OpenAI-compatible stream returned tool call deltas without index or id and the call could not be disambiguated.");
5627
+ };
5628
+ const finishCurrentBlock = (block) => {
5629
+ if (block) {
5630
+ if (block.type === "text") {
5451
5631
  stream2.push({
5452
- type: "thinking_start",
5453
- contentIndex: output.content.length - 1,
5632
+ type: "text_end",
5633
+ contentIndex: blocks.indexOf(block),
5634
+ content: block.text,
5454
5635
  partial: output
5455
5636
  });
5456
- } else if (event.content_block.type === "tool_use") {
5457
- const block = {
5458
- type: "toolCall",
5459
- id: event.content_block.id,
5460
- name: event.content_block.name,
5461
- arguments: event.content_block.input ?? {},
5462
- partialJson: "",
5463
- index: event.index
5464
- };
5465
- output.content.push(block);
5637
+ } else if (block.type === "thinking") {
5466
5638
  stream2.push({
5467
- type: "toolcall_start",
5468
- contentIndex: output.content.length - 1,
5639
+ type: "thinking_end",
5640
+ contentIndex: blocks.indexOf(block),
5641
+ content: block.thinking,
5469
5642
  partial: output
5470
5643
  });
5471
5644
  }
5472
- } else if (event.type === "content_block_delta") {
5473
- if (event.delta.type === "text_delta") {
5474
- const index = blocks.findIndex((b) => b.index === event.index);
5475
- const block = blocks[index];
5476
- if (block?.type === "text") {
5477
- block.text += event.delta.text;
5478
- stream2.push({ type: "text_delta", contentIndex: index, delta: event.delta.text, partial: output });
5645
+ }
5646
+ };
5647
+ if (!response.readSSELines) {
5648
+ throw new Error("SSE streaming not supported on this platform");
5649
+ }
5650
+ for await (const line of response.readSSELines(options?.signal)) {
5651
+ {
5652
+ const data = parseSSEDataLine(line);
5653
+ if (data === null) continue;
5654
+ if (data === "[DONE]") {
5655
+ sawDone = true;
5656
+ break;
5657
+ }
5658
+ let chunk;
5659
+ try {
5660
+ chunk = JSON.parse(data);
5661
+ } catch (error) {
5662
+ const message = error instanceof Error ? error.message : String(error);
5663
+ throw createProtocolError(`OpenAI-compatible stream returned malformed SSE JSON: ${message}`);
5664
+ }
5665
+ sseDump.record(chunk);
5666
+ if (chunk?.error) {
5667
+ throw new Error(formatOpenAIStreamError(chunk.error));
5668
+ }
5669
+ if (chunk.usage) {
5670
+ usageSnapshot = mergeOpenAIUsage(usageSnapshot, chunk.usage);
5671
+ output.usageReported = [usageSnapshot.promptTokens, usageSnapshot.completionTokens].every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
5672
+ const normalizedUsage = normalizeOpenAIUsage(usageSnapshot);
5673
+ output.usage = {
5674
+ input: normalizedUsage.input,
5675
+ output: normalizedUsage.output,
5676
+ cacheRead: normalizedUsage.cacheRead,
5677
+ cacheWrite: 0,
5678
+ totalTokens: normalizedUsage.totalTokens,
5679
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
5680
+ };
5681
+ output.usage.cost = calculateCost(model, output.usage);
5682
+ if (process.env.PIE_DEBUG_CACHE) {
5683
+ const normalizedPromptTokens = normalizedUsage.input + normalizedUsage.cacheRead;
5684
+ console.error("[CACHE DEBUG] Response usage:", JSON.stringify({
5685
+ input_tokens: normalizedUsage.input,
5686
+ output_tokens: normalizedUsage.output,
5687
+ cached_tokens: normalizedUsage.cacheRead,
5688
+ cache_hit_rate: normalizedPromptTokens > 0 ? `${(normalizedUsage.cacheRead / normalizedPromptTokens * 100).toFixed(1)}%` : "N/A"
5689
+ }, null, 2));
5479
5690
  }
5480
- } else if (event.delta.type === "thinking_delta") {
5481
- const index = blocks.findIndex((b) => b.index === event.index);
5482
- const block = blocks[index];
5483
- if (block?.type === "thinking") {
5484
- block.thinking += event.delta.thinking;
5485
- stream2.push({
5486
- type: "thinking_delta",
5487
- contentIndex: index,
5488
- delta: event.delta.thinking,
5489
- partial: output
5490
- });
5691
+ }
5692
+ const choice = chunk.choices?.[0];
5693
+ if (!choice) continue;
5694
+ if (choice.finish_reason) {
5695
+ sawFinishReason = true;
5696
+ rawFinishReason = String(choice.finish_reason);
5697
+ output.stopReason = mapOpenAIStopReason(choice.finish_reason);
5698
+ }
5699
+ if (choice.delta) {
5700
+ if (choice.delta.content !== null && choice.delta.content !== void 0 && choice.delta.content.length > 0) {
5701
+ if (!currentBlock || currentBlock.type !== "text") {
5702
+ finishCurrentBlock(currentBlock);
5703
+ currentBlock = { type: "text", text: "" };
5704
+ output.content.push(currentBlock);
5705
+ stream2.push({
5706
+ type: "text_start",
5707
+ contentIndex: blockIndex(),
5708
+ partial: output
5709
+ });
5710
+ }
5711
+ if (currentBlock.type === "text") {
5712
+ currentBlock.text += choice.delta.content;
5713
+ stream2.push({
5714
+ type: "text_delta",
5715
+ contentIndex: blockIndex(),
5716
+ delta: choice.delta.content,
5717
+ partial: output
5718
+ });
5719
+ }
5491
5720
  }
5492
- } else if (event.delta.type === "input_json_delta") {
5493
- const index = blocks.findIndex((b) => b.index === event.index);
5494
- const block = blocks[index];
5495
- if (block?.type === "toolCall") {
5496
- block.partialJson += event.delta.partial_json;
5497
- block.arguments = parseStreamingJson(block.partialJson);
5498
- stream2.push({
5499
- type: "toolcall_delta",
5500
- contentIndex: index,
5501
- delta: event.delta.partial_json,
5502
- partial: output
5503
- });
5721
+ const reasoningFields = [
5722
+ "reasoning_content",
5723
+ "reasoning",
5724
+ "reasoning_text"
5725
+ ];
5726
+ let foundReasoningField = null;
5727
+ for (const field of reasoningFields) {
5728
+ if (choice.delta[field] !== null && choice.delta[field] !== void 0 && choice.delta[field].length > 0) {
5729
+ foundReasoningField = field;
5730
+ break;
5731
+ }
5504
5732
  }
5505
- } else if (event.delta.type === "signature_delta") {
5506
- const index = blocks.findIndex((b) => b.index === event.index);
5507
- const block = blocks[index];
5508
- if (block?.type === "thinking") {
5509
- block.thinkingSignature = (block.thinkingSignature || "") + event.delta.signature;
5733
+ if (foundReasoningField) {
5734
+ if (!currentBlock || currentBlock.type !== "thinking") {
5735
+ finishCurrentBlock(currentBlock);
5736
+ currentBlock = {
5737
+ type: "thinking",
5738
+ thinking: "",
5739
+ thinkingSignature: foundReasoningField
5740
+ };
5741
+ output.content.push(currentBlock);
5742
+ stream2.push({
5743
+ type: "thinking_start",
5744
+ contentIndex: blockIndex(),
5745
+ partial: output
5746
+ });
5747
+ }
5748
+ if (currentBlock.type === "thinking") {
5749
+ const delta = choice.delta[foundReasoningField];
5750
+ currentBlock.thinking += delta;
5751
+ stream2.push({
5752
+ type: "thinking_delta",
5753
+ contentIndex: blockIndex(),
5754
+ delta,
5755
+ partial: output
5756
+ });
5757
+ }
5758
+ }
5759
+ if (choice.delta.tool_calls) {
5760
+ const deltaToolCalls = choice.delta.tool_calls;
5761
+ for (const toolCall of deltaToolCalls) {
5762
+ finishCurrentBlock(currentBlock);
5763
+ currentBlock = null;
5764
+ const entry = resolveToolCallEntry(toolCall, deltaToolCalls.length);
5765
+ if (entry) {
5766
+ if (toolCall.id) rememberToolCallId(toolCall.id, entry);
5767
+ if (toolCall.function?.name) {
5768
+ if (entry.block.name && entry.block.name !== toolCall.function.name) {
5769
+ throw createProtocolError(`OpenAI-compatible stream changed tool call name from "${entry.block.name}" to "${toolCall.function.name}".`);
5770
+ }
5771
+ entry.block.name = toolCall.function.name;
5772
+ }
5773
+ let delta = "";
5774
+ if (toolCall.function?.arguments) {
5775
+ delta = toolCall.function.arguments;
5776
+ entry.partialArgs += delta;
5777
+ entry.block.arguments = parseStreamingJson(entry.partialArgs);
5778
+ }
5779
+ stream2.push({
5780
+ type: "toolcall_delta",
5781
+ contentIndex: entry.contentIndex,
5782
+ delta,
5783
+ partial: output
5784
+ });
5785
+ }
5786
+ }
5510
5787
  }
5511
5788
  }
5512
- } else if (event.type === "content_block_stop") {
5513
- const index = blocks.findIndex((b) => b.index === event.index);
5514
- const block = blocks[index];
5515
- if (block) {
5516
- delete block.index;
5517
- if (block.type === "text") {
5518
- stream2.push({
5519
- type: "text_end",
5520
- contentIndex: index,
5521
- content: block.text,
5522
- partial: output
5523
- });
5524
- } else if (block.type === "thinking") {
5525
- stream2.push({
5526
- type: "thinking_end",
5527
- contentIndex: index,
5528
- content: block.thinking,
5529
- partial: output
5530
- });
5531
- } else if (block.type === "toolCall") {
5532
- block.arguments = parseStreamingJson(block.partialJson);
5533
- delete block.partialJson;
5534
- stream2.push({
5535
- type: "toolcall_end",
5536
- contentIndex: index,
5537
- toolCall: block,
5538
- partial: output
5539
- });
5789
+ }
5790
+ }
5791
+ finishCurrentBlock(currentBlock);
5792
+ if (compat.streamRequiresDone && !sawDone) {
5793
+ throw createProtocolError(`OpenAI-compatible stream ended without data: [DONE]${rawFinishReason ? ` (last finish_reason=${rawFinishReason})` : ""}. Set compat.streamRequiresDone=false for gateways that legitimately omit the terminator.`);
5794
+ }
5795
+ if (compat.streamRequiresFinishReason && !sawFinishReason) {
5796
+ throw createProtocolError("OpenAI-compatible stream ended without finish_reason. Set compat.streamRequiresFinishReason=false for endpoints that omit it.");
5797
+ }
5798
+ if (output.stopReason === "toolUse" && toolCallEntries.length === 0) {
5799
+ throw createProtocolError(`OpenAI-compatible stream ended with finish_reason=${rawFinishReason} but did not include any tool calls.`);
5800
+ }
5801
+ if (output.stopReason === "length" && toolCallEntries.length > 0) {
5802
+ const truncatedEntries = toolCallEntries.filter(
5803
+ ({ partialArgs }) => tryParseFinalToolArguments(partialArgs) === null
5804
+ );
5805
+ if (truncatedEntries.length > 0) {
5806
+ const truncatedBlocks = new Set(truncatedEntries.map((entry) => entry.block));
5807
+ for (let i = toolCallEntries.length - 1; i >= 0; i--) {
5808
+ if (truncatedBlocks.has(toolCallEntries[i].block)) {
5809
+ toolCallEntries.splice(i, 1);
5540
5810
  }
5541
5811
  }
5542
- } else if (event.type === "message_delta") {
5543
- if (event.delta.stop_reason) {
5544
- output.stopReason = mapStopReason(event.delta.stop_reason);
5812
+ output.content = output.content.filter(
5813
+ (block) => block.type !== "toolCall" || !truncatedBlocks.has(block)
5814
+ );
5815
+ output.content.push({
5816
+ type: "text",
5817
+ text: `[output truncated: finish_reason=length cut ${truncatedEntries.length === 1 ? "a tool call" : `${truncatedEntries.length} tool calls`} mid-arguments (${summarizeTruncatedCallNames(truncatedEntries.map((entry) => entry.block.name))}); the call${truncatedEntries.length === 1 ? " was" : "s were"} dropped. Re-issue the call or continue with fewer/smaller requests.]`
5818
+ });
5819
+ }
5820
+ }
5821
+ const knownToolNames = new Set((context.tools ?? []).map((tool) => tool.name));
5822
+ const droppedToolCallBlocks = /* @__PURE__ */ new Set();
5823
+ const unknownNameSamples = [];
5824
+ if (knownToolNames.size > 0) {
5825
+ for (let i = toolCallEntries.length - 1; i >= 0; i--) {
5826
+ const entry = toolCallEntries[i];
5827
+ if (entry.block.name.trim() && !knownToolNames.has(entry.block.name)) {
5828
+ if (unknownNameSamples.length < 3) unknownNameSamples.push(JSON.stringify(entry.block.name));
5829
+ droppedToolCallBlocks.add(entry.block);
5830
+ toolCallEntries.splice(i, 1);
5545
5831
  }
5546
- applyAnthropicUsageUpdate(model, output.usage, event.usage);
5547
- if (hasReportedInputUsage && typeof event.usage.output_tokens === "number" && Number.isFinite(event.usage.output_tokens) && event.usage.output_tokens >= 0) output.usageReported = true;
5548
5832
  }
5549
5833
  }
5550
- if (options?.signal?.aborted) {
5551
- throw new Error("Request was aborted");
5834
+ const emittedCallCounts = /* @__PURE__ */ new Map();
5835
+ const excessDuplicateEntries = /* @__PURE__ */ new Set();
5836
+ const repeatExempt = new Set(
5837
+ (context.tools ?? []).filter((tool) => tool.allowIdenticalRepeatCalls === true).map((tool) => tool.name)
5838
+ );
5839
+ for (const entry of toolCallEntries) {
5840
+ if (repeatExempt.has(entry.block.name)) continue;
5841
+ const key = `${entry.block.name}
5842
+ ${entry.partialArgs}`;
5843
+ const seen = (emittedCallCounts.get(key) ?? 0) + 1;
5844
+ emittedCallCounts.set(key, seen);
5845
+ if (seen > OPENAI_COMPAT_MAX_DUPLICATE_TOOL_CALLS) excessDuplicateEntries.add(entry);
5552
5846
  }
5553
- assertAssistantHasContent(output);
5554
- stream2.push({ type: "done", reason: output.stopReason, message: output });
5555
- stream2.end();
5556
- } catch (error) {
5557
- logEmptyAssistantContentError(error, model, options);
5558
- for (const block of output.content) delete block.index;
5559
- output.stopReason = options?.signal?.aborted ? "aborted" : "error";
5560
- output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
5561
- stream2.push({ type: "error", reason: output.stopReason, error: output });
5562
- stream2.end();
5563
- }
5564
- })();
5565
- return stream2;
5566
- };
5567
- var streamSimpleAnthropic = (model, context, options) => {
5568
- const apiKey = options?.apiKey || getEnvApiKey(model.provider, model.apiKeyEnv);
5569
- if (!apiKey) {
5570
- throw new Error(`No API key for provider: ${model.provider}`);
5571
- }
5572
- const base = buildBaseOptions(model, options, apiKey);
5573
- if (!options?.reasoning) {
5574
- return streamAnthropic(model, context, { ...base, thinkingEnabled: false });
5575
- }
5576
- const adjusted = adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options.thinkingBudgets);
5577
- return streamAnthropic(model, context, {
5578
- ...base,
5579
- maxTokens: adjusted.maxTokens,
5580
- thinkingEnabled: true,
5581
- thinkingBudgetTokens: adjusted.thinkingBudget
5582
- });
5583
- };
5584
-
5585
- // ../../packages/ai/src/providers/responses/responses-compat.ts
5586
- function getResponsesCompat(model) {
5587
- const compat = model.compat ?? {};
5588
- return {
5589
- store: compat.store ?? false,
5590
- supportsStore: compat.supportsStore ?? true,
5591
- supportsReasoningEffort: compat.supportsReasoningEffort ?? true,
5592
- supportsEncryptedReasoning: compat.supportsEncryptedReasoning ?? true,
5593
- responsesContinuation: compat.responsesContinuation ?? false,
5594
- supportsReasoningSummary: compat.supportsReasoningSummary ?? false,
5595
- reasoningSummary: compat.reasoningSummary ?? "auto",
5596
- timeoutReplay: compat.timeoutReplay ?? false
5597
- };
5598
- }
5599
-
5600
- // ../../packages/ai/src/providers/responses/responses-wire.ts
5601
- var RESPONSES_PROTOCOL_ERROR_CODE = "responses_protocol_error";
5602
- var ResponsesProtocolError = class extends Error {
5603
- code = RESPONSES_PROTOCOL_ERROR_CODE;
5604
- constructor(message) {
5605
- super(`${RESPONSES_PROTOCOL_ERROR_CODE}: ${message}`);
5606
- this.name = "ResponsesProtocolError";
5607
- }
5608
- };
5609
- function isRecord2(value) {
5610
- return value !== null && typeof value === "object" && !Array.isArray(value);
5611
- }
5612
- function isResponsesEventLike(value) {
5613
- return isRecord2(value) && typeof value.type === "string";
5614
- }
5615
- function formatResponsesErrorEvent(event) {
5616
- const source = isRecord2(event.error) ? event.error : event;
5617
- const message = typeof source.message === "string" && source.message.length > 0 ? source.message : "Responses stream returned an error";
5618
- const metadata = [];
5619
- if (typeof source.code === "string" && source.code.length > 0) {
5620
- metadata.push(`code=${source.code}`);
5621
- }
5622
- if (typeof source.param === "string" && source.param.length > 0) {
5623
- metadata.push(`param=${source.param}`);
5624
- }
5625
- if (typeof event.status === "number") {
5626
- metadata.push(`status=${event.status}`);
5627
- }
5628
- return metadata.length > 0 ? `${message} (${metadata.join(", ")})` : message;
5629
- }
5630
-
5631
- // ../../packages/ai/src/providers/responses/responses-request.ts
5632
- var MAX_REASONING_ENVELOPE_BYTES = 512 * 1024;
5633
- function decodeReasoningEnvelope(signature) {
5634
- if (typeof signature !== "string" || signature.length === 0 || signature.length > MAX_REASONING_ENVELOPE_BYTES) {
5635
- return null;
5636
- }
5637
- let parsed;
5638
- try {
5639
- parsed = JSON.parse(signature);
5640
- } catch {
5641
- return null;
5642
- }
5643
- if (!isRecord2(parsed) || parsed.v !== 1 || typeof parsed.id !== "string" || parsed.id.length === 0) {
5644
- return null;
5645
- }
5646
- const encrypted = parsed.encrypted_content;
5647
- if (encrypted !== void 0 && encrypted !== null && typeof encrypted !== "string") {
5648
- return null;
5649
- }
5650
- return { v: 1, id: parsed.id, encrypted_content: encrypted };
5651
- }
5652
- function buildResponsesInput(model, context) {
5653
- const items = [];
5654
- const isSameModel = (msg) => msg.provider === model.provider && msg.api === model.api && msg.model === model.id;
5655
- const transformed = transformMessages(context.messages, model);
5656
- for (const msg of transformed) {
5657
- if (msg.role === "user") {
5658
- items.push(encodeUserMessage(msg.content, model));
5659
- } else if (msg.role === "assistant") {
5660
- encodeAssistantMessage(msg, isSameModel, items);
5661
- } else if (msg.role === "toolResult") {
5662
- items.push(encodeToolResult(msg, model));
5663
- }
5664
- }
5665
- return items;
5666
- }
5667
- function encodeUserMessage(content, model) {
5668
- if (typeof content === "string") {
5669
- return { role: "user", type: "message", content };
5670
- }
5671
- const parts = [];
5672
- for (const block of content) {
5673
- parts.push(...encodeUserContentBlock(block, model));
5674
- }
5675
- if (parts.length === 0) {
5676
- return { role: "user", type: "message", content: "" };
5677
- }
5678
- return { role: "user", type: "message", content: parts };
5679
- }
5680
- function omittedAttachmentNote(modality, reason) {
5681
- return { type: "input_text", text: `[${modality} attachment omitted: ${reason} Re-read with a compatible model.]` };
5682
- }
5683
- function encodeUserContentBlock(block, model) {
5684
- if (block.type === "hostContext") {
5685
- throw new ResponsesProtocolError(`Unprojected hostContext block reached Responses conversion (${block.kind}); the request path must project host envelopes to text first.`);
5686
- }
5687
- const modality = block.type === "fileRef" ? block.modality : block.type;
5688
- if (modality !== "text" && !model.input.includes(modality)) {
5689
- return [omittedAttachmentNote(modality, "current model does not support this modality.")];
5690
- }
5691
- switch (block.type) {
5692
- case "text":
5693
- return [{ type: "input_text", text: block.text }];
5694
- case "image":
5695
- return [{ type: "input_image", image_url: `data:${block.mimeType};base64,${block.data}` }];
5696
- case "video":
5697
- case "audio":
5698
- return [omittedAttachmentNote(block.type, `the Responses provider does not deliver ${block.type} input.`)];
5699
- case "fileRef": {
5700
- const ref = block;
5701
- if (ref.modality === "image") {
5702
- return [{ type: "input_image", image_url: ref.url }];
5847
+ if (excessDuplicateEntries.size > 0) {
5848
+ for (let i = toolCallEntries.length - 1; i >= 0; i--) {
5849
+ if (excessDuplicateEntries.has(toolCallEntries[i])) {
5850
+ droppedToolCallBlocks.add(toolCallEntries[i].block);
5851
+ toolCallEntries.splice(i, 1);
5852
+ }
5853
+ }
5703
5854
  }
5704
- return [omittedAttachmentNote(ref.modality, `the Responses provider does not deliver ${ref.modality} file references.`)];
5705
- }
5706
- default:
5707
- throw new ResponsesProtocolError("Unsupported Responses content block.");
5708
- }
5709
- }
5710
- function encodeAssistantMessage(msg, isSameModel, items) {
5711
- for (const block of msg.content) {
5712
- if (block.type === "thinking") {
5713
- const thinking = block;
5714
- if (isSameModel(msg)) {
5715
- const envelope = decodeReasoningEnvelope(thinking.thinkingSignature);
5716
- if (thinking.thinkingSignature && !envelope) {
5717
- throw new ResponsesProtocolError("Invalid Responses reasoning signature.");
5855
+ if (droppedToolCallBlocks.size > 0) {
5856
+ const unknownCount = droppedToolCallBlocks.size - excessDuplicateEntries.size;
5857
+ output.content = output.content.filter(
5858
+ (block) => block.type !== "toolCall" || !droppedToolCallBlocks.has(block)
5859
+ );
5860
+ const reasons = [];
5861
+ if (unknownCount > 0) {
5862
+ reasons.push(`${unknownCount} named tools that are not part of this request (samples: ${unknownNameSamples.join(", ")})`);
5718
5863
  }
5719
- if (envelope) {
5720
- items.push({
5721
- type: "reasoning",
5722
- id: envelope.id,
5723
- summary: thinking.thinking.trim() ? [{ type: "summary_text", text: thinking.thinking }] : [],
5724
- ...envelope.encrypted_content ? { encrypted_content: envelope.encrypted_content } : {}
5725
- });
5726
- continue;
5864
+ if (excessDuplicateEntries.size > 0) {
5865
+ reasons.push(`${excessDuplicateEntries.size} were exact duplicates of an earlier call in the same message`);
5866
+ }
5867
+ output.content.push({
5868
+ type: "text",
5869
+ text: `[dropped ${droppedToolCallBlocks.size} tool call${droppedToolCallBlocks.size === 1 ? "" : "s"}: ${reasons.join("; ")}. Re-issue only the intended calls.]`
5870
+ });
5871
+ }
5872
+ for (const { block, partialArgs, contentIndex } of toolCallEntries) {
5873
+ if (!block.name.trim()) {
5874
+ throw createProtocolError("OpenAI-compatible stream returned a tool call without a function name.");
5727
5875
  }
5876
+ block.arguments = parseFinalToolArguments(partialArgs, block.name);
5877
+ stream2.push({ type: "toolcall_end", contentIndex, toolCall: block, partial: output });
5878
+ }
5879
+ const hasToolCallBlocks = output.content.some((block) => block.type === "toolCall");
5880
+ if (output.stopReason !== "error" && output.stopReason !== "aborted" && hasToolCallBlocks) {
5881
+ output.stopReason = "toolUse";
5882
+ } else if (output.stopReason === "toolUse" && !hasToolCallBlocks) {
5883
+ output.stopReason = "stop";
5728
5884
  }
5729
- if (thinking.thinking && thinking.thinking.trim().length > 0) {
5730
- items.push({ role: "assistant", type: "message", content: thinking.thinking });
5885
+ if (options?.signal?.aborted) {
5886
+ throw new Error("Request was aborted");
5731
5887
  }
5732
- continue;
5733
- }
5734
- if (block.type === "text") {
5735
- const text = block;
5736
- if (text.text && text.text.trim().length > 0) {
5737
- items.push({ role: "assistant", type: "message", content: text.text });
5888
+ if (output.stopReason === "aborted" || output.stopReason === "error") {
5889
+ throw new Error("An unknown error occurred");
5738
5890
  }
5739
- continue;
5740
- }
5741
- if (block.type === "toolCall") {
5742
- const call = block;
5743
- items.push({
5744
- type: "function_call",
5745
- call_id: call.id,
5746
- name: call.name,
5747
- arguments: JSON.stringify(call.arguments ?? {})
5748
- });
5891
+ assertAssistantHasContent(output);
5892
+ resetOpenAICompatFirstByteTimeoutEscalation(model);
5893
+ stream2.push({ type: "done", reason: output.stopReason, message: output });
5894
+ stream2.end();
5895
+ } catch (error) {
5896
+ logEmptyAssistantContentError(error, model, options);
5897
+ if (error instanceof Error && error.message.includes("Request timeout (first byte)")) {
5898
+ noteOpenAICompatFirstByteTimeout(model);
5899
+ }
5900
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
5901
+ output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
5902
+ stream2.push({ type: "error", reason: output.stopReason, error: output });
5903
+ stream2.end();
5904
+ } finally {
5905
+ await sseDump.flush();
5749
5906
  }
5907
+ })();
5908
+ return stream2;
5909
+ };
5910
+ var streamSimpleOpenAICompletions = (model, context, options) => {
5911
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider, model.apiKeyEnv);
5912
+ if (!apiKey) {
5913
+ throw new Error(`No API key for provider: ${model.provider}`);
5750
5914
  }
5751
- }
5752
- function buildResponsesOutput(message) {
5753
- const items = [];
5754
- encodeAssistantMessage(message, () => true, items);
5755
- return items;
5756
- }
5757
- function encodeToolResult(msg, model) {
5758
- const output = msg.content.every((block) => block.type === "text") ? msg.content.map((block) => block.text).join("\n") || "(empty result)" : msg.content.flatMap((block) => encodeUserContentBlock(block, model));
5759
- return { type: "function_call_output", call_id: msg.toolCallId, output };
5760
- }
5761
- function encodeTools(tools) {
5762
- return tools.map((tool) => ({
5763
- type: "function",
5764
- name: tool.name,
5765
- description: tool.description,
5766
- parameters: tool.parameters ?? { type: "object", properties: {} },
5767
- strict: false
5768
- }));
5769
- }
5770
- function buildResponsesRequest(model, context, options, compat = getResponsesCompat(model)) {
5771
- const params = {
5772
- model: model.id,
5773
- input: buildResponsesInput(model, context)
5774
- };
5775
- if (context.systemPrompt !== void 0 && context.systemPrompt !== null && context.systemPrompt.length > 0) {
5776
- params.instructions = context.systemPrompt;
5777
- }
5778
- if (compat.supportsStore) {
5779
- params.store = compat.store;
5780
- }
5781
- if (options?.maxTokens !== void 0 && options.maxTokens > 0) {
5782
- params.max_output_tokens = options.maxTokens;
5783
- }
5784
- if (options?.temperature !== void 0) params.temperature = options.temperature;
5785
- if (options?.topP !== void 0) params.top_p = options.topP;
5786
- if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
5787
- params.reasoning = { effort: options.reasoningEffort };
5788
- }
5789
- if (model.reasoning && compat.supportsReasoningSummary && compat.reasoningSummary !== "none") {
5790
- params.reasoning = params.reasoning ?? {};
5791
- params.reasoning.summary = compat.reasoningSummary;
5792
- }
5793
- if (compat.supportsEncryptedReasoning && model.reasoning) {
5794
- params.include = ["reasoning.encrypted_content"];
5795
- }
5796
- if (context.tools && context.tools.length > 0) {
5797
- params.tools = encodeTools(context.tools);
5798
- params.parallel_tool_calls = true;
5799
- }
5800
- if (options?.toolChoice !== void 0) {
5801
- params.tool_choice = options.toolChoice === "required" ? "required" : options.toolChoice;
5802
- }
5803
- return params;
5804
- }
5805
- function buildResponsesSSEPayload(model, context, options) {
5806
- return { ...buildResponsesRequest(model, context, options), stream: true };
5807
- }
5808
- function buildResponsesCreateEvent(model, context, options) {
5809
- const params = buildResponsesRequest(model, context, options);
5810
- delete params.stream;
5811
- return { type: "response.create", ...params };
5812
- }
5813
-
5814
- // ../../packages/ai/src/providers/responses/responses-remote-failure.ts
5815
- var MAX_TEXT = 4096;
5816
- var transientCodes = /* @__PURE__ */ new Set(["server_error", "rate_limit_exceeded", "slow_down", "rate_limit_error", "server_is_overloaded", "service_unavailable_error"]);
5817
- function responsesRemoteFailure(value, status, headers) {
5818
- const root = isRecord2(value) ? value : {};
5819
- const response = isRecord2(root.response) ? root.response : {};
5820
- const error = isRecord2(root.error) ? root.error : isRecord2(response.error) ? response.error : root;
5821
- const code = typeof error.code === "string" ? error.code.slice(0, 128).toLowerCase() : "";
5822
- const type = typeof error.type === "string" ? error.type.slice(0, 128).toLowerCase() : "";
5823
- const message = (typeof value === "string" ? value : typeof error.message === "string" ? error.message : "").slice(0, MAX_TEXT).toLowerCase();
5824
- const httpStatus = status ?? root.status ?? root.statusCode;
5825
- const fields = `${code} ${type}`;
5826
- let category = "other";
5827
- if (/context_length_exceeded|context_window_exceeded|context_overflow/.test(fields) || /context (?:length|window).{0,60}(?:exceed|too (?:long|large))|maximum context length|exceeds.{0,30}context window/.test(message)) category = "context_overflow";
5828
- else if (/billing|insufficient_quota|insufficient_balance|credit|usage_limit|spend_limit/.test(fields) || /billing|(?:account|monthly) quota|exceeded your current quota|insufficient (?:credit|balance)|credit balance|spend(?:ing)? limit/.test(message)) category = "other";
5829
- else if (typeof httpStatus === "number" && httpStatus >= 400 && httpStatus < 500 && httpStatus !== 429) category = "other";
5830
- else if (httpStatus === 429 || typeof httpStatus === "number" && httpStatus >= 500 && httpStatus <= 599 || transientCodes.has(code) || transientCodes.has(type) || /server (?:is )?overloaded|temporarily unavailable|internal server error|rate limit (?:exceeded|reached)/.test(message)) category = "transient";
5831
- const retryAfterMs = parseRetryAfter(headers ?? root.headers);
5832
- return { category, ...retryAfterMs !== void 0 ? { retryAfterMs } : {} };
5833
- }
5834
- function parseRetryAfter(headers) {
5835
- if (!headers || typeof headers !== "object") return void 0;
5836
- let raw;
5837
- if ("get" in headers && typeof headers.get === "function") raw = headers.get("retry-after");
5838
- else for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === "retry-after") raw = value;
5839
- if (typeof raw !== "string" || raw.length > 128) return void 0;
5840
- const text = raw.trim();
5841
- if (/^\d+(?:\.\d+)?$/.test(text)) {
5842
- const delay = Number(text) * 1e3;
5843
- return Number.isFinite(delay) ? delay : Number.MAX_VALUE;
5844
- }
5845
- if (!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(text)) return void 0;
5846
- const date = Date.parse(text);
5847
- if (!Number.isFinite(date) || new Date(date).toUTCString() !== text) return void 0;
5848
- return Math.max(0, date - Date.now());
5849
- }
5850
- async function readResponsesErrorBody(read, signal) {
5851
- let timer;
5852
- let onAbort;
5853
- try {
5854
- return await Promise.race([
5855
- Promise.resolve().then(read).then((text) => text.slice(0, MAX_TEXT)).catch(() => ""),
5856
- new Promise((resolve) => {
5857
- onAbort = () => resolve("");
5858
- if (signal.aborted) resolve("");
5859
- else signal.addEventListener("abort", onAbort, { once: true });
5860
- timer = setTimeout(() => resolve(""), 250);
5861
- })
5862
- ]);
5863
- } finally {
5864
- if (timer !== void 0) clearTimeout(timer);
5865
- if (onAbort) signal.removeEventListener("abort", onAbort);
5915
+ const base = buildBaseOptions(model, options, apiKey);
5916
+ const reasoningEffort = clampReasoning(options?.reasoning);
5917
+ const needsThinkingAllowance = Boolean(model.reasoning) && options?.reasoning !== void 0;
5918
+ const adjusted = needsThinkingAllowance ? adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options?.thinkingBudgets) : void 0;
5919
+ let maxTokens = adjusted ? adjusted.maxTokens : base.maxTokens;
5920
+ if (maxTokens === void 0) {
5921
+ maxTokens = DEFAULT_MAX_TOKENS;
5866
5922
  }
5867
- }
5868
- function parseResponsesErrorBody(text) {
5869
- try {
5870
- return JSON.parse(text);
5871
- } catch {
5872
- return text;
5923
+ if (options?.maxTokens === void 0) {
5924
+ maxTokens = Math.min(maxTokens, DEFAULT_MAX_TOKENS);
5873
5925
  }
5874
- }
5926
+ return streamOpenAICompletions(model, context, {
5927
+ ...base,
5928
+ maxTokens,
5929
+ reasoningEffort
5930
+ });
5931
+ };
5875
5932
 
5876
- // ../../packages/ai/src/providers/responses/responses-usage.ts
5877
- function tokenCount(value) {
5878
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
5879
- return Math.floor(value);
5880
- }
5881
- function normalizeResponsesUsage(model, usage) {
5882
- const inputTokens = tokenCount(usage?.input_tokens);
5883
- const cachedTokens = tokenCount(usage?.input_tokens_details?.cached_tokens) ?? 0;
5884
- const cacheWriteTokens = tokenCount(usage?.input_tokens_details?.cache_write_tokens) ?? 0;
5885
- const outputTokens = tokenCount(usage?.output_tokens);
5886
- const reasoningTokens = tokenCount(usage?.output_tokens_details?.reasoning_tokens);
5887
- const totalTokens = tokenCount(usage?.total_tokens);
5888
- const input = inputTokens ?? (totalTokens !== void 0 && outputTokens !== void 0 ? Math.max(cachedTokens + cacheWriteTokens, totalTokens - outputTokens) : cachedTokens + cacheWriteTokens);
5889
- const output = outputTokens ?? (totalTokens !== void 0 ? Math.max(reasoningTokens ?? 0, totalTokens - input) : reasoningTokens ?? 0);
5890
- const cacheRead = Math.min(cachedTokens, input);
5891
- const cacheWrite = Math.min(cacheWriteTokens, input - cacheRead);
5892
- const inputExclusive = input - cacheRead - cacheWrite;
5893
- const partitionTotal = input + output;
5894
- const base = {
5895
- input: inputExclusive,
5896
- output,
5897
- cacheRead,
5898
- cacheWrite,
5899
- totalTokens: Math.max(totalTokens ?? 0, partitionTotal)
5900
- };
5901
- return { ...base, cost: calculateCost(model, base) };
5933
+ // ../../packages/ai/src/providers/anthropic.ts
5934
+ import Anthropic from "@anthropic-ai/sdk";
5935
+ function sanitizeSurrogates(text) {
5936
+ return text.replace(/[\uD800-\uDFFF]/g, "");
5902
5937
  }
5903
-
5904
- // ../../packages/ai/src/providers/responses/responses-events.ts
5905
- var ResponsesEventReducer = class {
5906
- output;
5907
- model;
5908
- started = false;
5909
- terminal = null;
5910
- items = /* @__PURE__ */ new Map();
5911
- toolCallStates = [];
5912
- diagnostics = { unknownEventTypes: /* @__PURE__ */ new Set(), ignoredItemTypes: /* @__PURE__ */ new Set(), terminalType: null };
5913
- constructor(model) {
5914
- this.model = model;
5915
- this.output = {
5916
- role: "assistant",
5917
- content: [],
5918
- api: model.api,
5919
- provider: model.provider,
5920
- model: model.id,
5921
- usageReported: false,
5922
- usage: {
5923
- input: 0,
5924
- output: 0,
5925
- cacheRead: 0,
5926
- cacheWrite: 0,
5927
- totalTokens: 0,
5928
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
5929
- },
5930
- stopReason: "stop",
5931
- timestamp: Date.now()
5932
- };
5938
+ function applyAnthropicUsageUpdate(model, usage, payload) {
5939
+ if (payload.input_tokens != null) usage.input = Math.max(0, payload.input_tokens);
5940
+ if (payload.output_tokens != null) usage.output = Math.max(0, payload.output_tokens);
5941
+ if (payload.cache_read_input_tokens != null) usage.cacheRead = Math.max(0, payload.cache_read_input_tokens);
5942
+ const reportedWriteTotal = payload.cache_creation_input_tokens;
5943
+ const breakdown = payload.cache_creation ?? void 0;
5944
+ const breakdownTotal = (breakdown?.ephemeral_5m_input_tokens ?? 0) + (breakdown?.ephemeral_1h_input_tokens ?? 0);
5945
+ if (reportedWriteTotal == null && breakdown !== void 0 && breakdownTotal === 0) {
5946
+ usage.cacheWrite = Math.max(0, usage.cacheWrite);
5947
+ } else if (reportedWriteTotal != null || breakdown !== void 0) {
5948
+ const previousLong = usage.cacheWriteLong ?? 0;
5949
+ const previousTotal = usage.cacheWrite + previousLong;
5950
+ const writeTotal = Math.max(
5951
+ 0,
5952
+ reportedWriteTotal != null ? reportedWriteTotal : breakdownTotal > 0 ? breakdownTotal : previousTotal
5953
+ );
5954
+ const longTokens = breakdown?.ephemeral_1h_input_tokens ?? 0;
5955
+ if (longTokens > 0) {
5956
+ const long = Math.min(longTokens, writeTotal);
5957
+ usage.cacheWriteLong = long;
5958
+ usage.cacheWrite = writeTotal - long;
5959
+ } else {
5960
+ delete usage.cacheWriteLong;
5961
+ usage.cacheWrite = writeTotal;
5962
+ }
5933
5963
  }
5934
- get message() {
5935
- return this.output;
5964
+ usage.totalTokens = usage.input + usage.output + usage.cacheRead + usage.cacheWrite + (usage.cacheWriteLong ?? 0);
5965
+ usage.cost = calculateCost(model, usage);
5966
+ }
5967
+ var ANTHROPIC_PROVIDER_HEADERS = {
5968
+ accept: "application/json",
5969
+ "anthropic-dangerous-direct-browser-access": "true",
5970
+ "anthropic-version": "2023-06-01"
5971
+ };
5972
+ function buildAnthropicHeaders(modelHeaders, runtimeHeaders, includeLongCacheBeta) {
5973
+ const merged = /* @__PURE__ */ new Map();
5974
+ for (const layer of [ANTHROPIC_PROVIDER_HEADERS, modelHeaders, runtimeHeaders]) {
5975
+ for (const [key, value] of Object.entries(layer ?? {})) {
5976
+ const normalizedKey = key.toLowerCase();
5977
+ if (normalizedKey && normalizedKey !== "anthropic-beta") {
5978
+ merged.set(normalizedKey, value);
5979
+ }
5980
+ }
5936
5981
  }
5937
- get isTerminal() {
5938
- return this.terminal !== null;
5982
+ const betaFeatures = includeLongCacheBeta ? ["extended-cache-ttl-2025-04-11"] : [];
5983
+ for (const layer of [modelHeaders, runtimeHeaders]) {
5984
+ for (const [key, value] of Object.entries(layer ?? {})) {
5985
+ if (key.toLowerCase() !== "anthropic-beta") continue;
5986
+ for (const feature of value.split(",")) {
5987
+ const trimmed = feature.trim();
5988
+ if (trimmed) betaFeatures.push(trimmed);
5989
+ }
5990
+ }
5939
5991
  }
5940
- /** Terminal response object (present on completed/incomplete/failed). */
5941
- get terminalResponse() {
5942
- return this.terminal?.response;
5992
+ if (betaFeatures.length > 0) {
5993
+ merged.set("anthropic-beta", [...new Set(betaFeatures)].join(","));
5943
5994
  }
5944
- /** Feed one raw wire event; returns the AssistantMessageEvents to emit. */
5945
- feed(raw) {
5946
- if (this.terminal) return [];
5947
- try {
5948
- const events = this.feedInbound(raw);
5949
- if (this.isTerminal && this.output.stopReason === "error") {
5950
- this.output.remoteFailure = responsesRemoteFailure(raw);
5951
- }
5952
- return events;
5953
- } catch (error) {
5954
- this.terminal = null;
5955
- throw error;
5995
+ return Object.fromEntries(merged);
5996
+ }
5997
+ function normalizeToolCallId(id) {
5998
+ return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
5999
+ }
6000
+ function mapStopReason(reason) {
6001
+ switch (reason) {
6002
+ case "end_turn":
6003
+ return "stop";
6004
+ case "max_tokens":
6005
+ return "length";
6006
+ case "tool_use":
6007
+ return "toolUse";
6008
+ default:
6009
+ return "stop";
6010
+ }
6011
+ }
6012
+ function convertContentBlocks(content) {
6013
+ const hostBlock = content.find((block) => block.type === "hostContext");
6014
+ if (hostBlock) {
6015
+ throw new Error(`Unprojected hostContext block reached anthropic conversion (${hostBlock.kind}); the request path must project host envelopes to text first.`);
6016
+ }
6017
+ const supportedBlocks = content.map((block) => block.type === "text" || block.type === "image" ? block : { type: "text", text: `[${block.type} attachment omitted: unsupported by this provider. Re-read with a compatible model.]` });
6018
+ const hasImages = supportedBlocks.some((c) => c.type === "image");
6019
+ if (!hasImages) {
6020
+ const text = supportedBlocks.filter((c) => c.type === "text").map((c) => c.text).join("\n");
6021
+ return sanitizeSurrogates(text || "(unsupported tool result omitted)");
6022
+ }
6023
+ const blocks = supportedBlocks.map((block) => {
6024
+ if (block.type === "text") {
6025
+ return { type: "text", text: sanitizeSurrogates(block.text) };
5956
6026
  }
6027
+ return {
6028
+ type: "image",
6029
+ source: {
6030
+ type: "base64",
6031
+ media_type: block.mimeType,
6032
+ data: block.data
6033
+ }
6034
+ };
6035
+ });
6036
+ const hasText = blocks.some((b) => b.type === "text");
6037
+ if (!hasText) {
6038
+ blocks.unshift({ type: "text", text: "(see attached image)" });
5957
6039
  }
5958
- feedInbound(raw) {
5959
- const events = [];
5960
- if (!isResponsesEventLike(raw)) {
5961
- throw new ResponsesProtocolError("Responses stream returned an event without a string type.");
6040
+ return blocks;
6041
+ }
6042
+ function convertUserContentBlocks(content) {
6043
+ const hostBlock = content.find((block) => block.type === "hostContext");
6044
+ if (hostBlock) {
6045
+ throw new Error(`Unprojected hostContext block reached anthropic user-message conversion (${hostBlock.kind}); the request path must project host envelopes to text first.`);
6046
+ }
6047
+ const blocks = [];
6048
+ for (const item of content) {
6049
+ if (item.type === "text") {
6050
+ blocks.push({ type: "text", text: sanitizeSurrogates(item.text) });
6051
+ continue;
5962
6052
  }
5963
- if (this.terminal) return events;
5964
- switch (raw.type) {
5965
- case "response.created":
5966
- case "response.in_progress":
5967
- case "response.queued":
5968
- if (!this.started) {
5969
- this.started = true;
5970
- events.push({ type: "start", partial: this.output });
6053
+ if (item.type === "image") {
6054
+ blocks.push({
6055
+ type: "image",
6056
+ source: {
6057
+ type: "base64",
6058
+ media_type: item.mimeType,
6059
+ data: item.data
5971
6060
  }
5972
- break;
5973
- case "response.output_item.added":
5974
- events.push(...this.onOutputItemAdded(raw));
5975
- break;
5976
- case "response.output_item.done":
5977
- events.push(...this.onOutputItemDone(raw));
5978
- break;
5979
- case "response.content_part.added":
5980
- events.push(...this.onContentPartAdded(raw));
5981
- break;
5982
- case "response.content_part.done":
5983
- break;
5984
- case "response.output_text.delta":
5985
- events.push(...this.appendTextDelta(raw, "text"));
5986
- break;
5987
- case "response.output_text.done":
5988
- this.validateTextDone(raw);
5989
- break;
5990
- case "response.refusal.delta":
5991
- events.push(...this.appendTextDelta(raw, "refusal"));
5992
- break;
5993
- case "response.refusal.done":
5994
- break;
5995
- case "response.reasoning_summary_text.delta":
5996
- case "response.reasoning_text.delta":
5997
- events.push(...this.appendReasoningDelta(raw));
5998
- break;
5999
- case "response.reasoning_summary_text.done":
6000
- case "response.reasoning_text.done":
6001
- break;
6002
- case "response.reasoning_summary_part.added":
6003
- case "response.reasoning_summary_part.done":
6004
- break;
6005
- case "response.function_call_arguments.delta":
6006
- events.push(...this.appendFunctionCallArgsDelta(raw));
6007
- break;
6008
- case "response.function_call_arguments.done":
6009
- this.onFunctionCallArgsDone(raw);
6010
- break;
6011
- case "response.completed":
6012
- events.push(...this.onTerminal(raw, "response.completed"));
6013
- break;
6014
- case "response.incomplete":
6015
- events.push(...this.onIncomplete(raw));
6016
- break;
6017
- case "response.failed":
6018
- events.push(...this.onTerminal(raw, "response.failed", "error", this.failedText(raw)));
6019
- break;
6020
- case "error":
6021
- events.push(...this.onTerminal(raw, "error", "error", formatResponsesErrorEvent(raw)));
6022
- break;
6023
- default:
6024
- this.diagnostics.unknownEventTypes.add(raw.type);
6025
- break;
6061
+ });
6062
+ continue;
6063
+ }
6064
+ if (item.type === "video") {
6065
+ const video = item;
6066
+ blocks.push({
6067
+ type: "text",
6068
+ text: sanitizeSurrogates(`(video attachment omitted for anthropic provider: ${video.mimeType})`)
6069
+ });
6070
+ continue;
6071
+ }
6072
+ if (item.type === "fileRef") {
6073
+ const ref = item;
6074
+ blocks.push({
6075
+ type: "text",
6076
+ text: sanitizeSurrogates(`(file reference omitted for anthropic provider: ${ref.url})`)
6077
+ });
6078
+ }
6079
+ }
6080
+ return blocks;
6081
+ }
6082
+ function convertMessages2(messages, model) {
6083
+ const params = [];
6084
+ const transformedMessages = transformMessages(messages, model, normalizeToolCallId);
6085
+ for (let i = 0; i < transformedMessages.length; i++) {
6086
+ const msg = transformedMessages[i];
6087
+ if (msg.role === "user") {
6088
+ if (typeof msg.content === "string") {
6089
+ if (msg.content.trim().length > 0) {
6090
+ params.push({ role: "user", content: sanitizeSurrogates(msg.content) });
6091
+ }
6092
+ } else {
6093
+ const blocks = convertUserContentBlocks(msg.content);
6094
+ let filteredBlocks = !model?.input.includes("image") ? blocks.filter((b) => b.type !== "image") : blocks;
6095
+ filteredBlocks = filteredBlocks.filter((b) => b.type === "text" ? b.text.trim().length > 0 : true);
6096
+ if (filteredBlocks.length === 0) continue;
6097
+ params.push({ role: "user", content: filteredBlocks });
6098
+ }
6099
+ } else if (msg.role === "assistant") {
6100
+ const blocks = [];
6101
+ for (const block of msg.content) {
6102
+ if (block.type === "text") {
6103
+ if (block.text.trim().length === 0) continue;
6104
+ blocks.push({ type: "text", text: sanitizeSurrogates(block.text) });
6105
+ } else if (block.type === "thinking") {
6106
+ if (block.thinking.trim().length === 0) continue;
6107
+ if (!block.thinkingSignature || block.thinkingSignature.trim().length === 0) {
6108
+ blocks.push({ type: "text", text: sanitizeSurrogates(block.thinking) });
6109
+ } else {
6110
+ blocks.push({
6111
+ type: "thinking",
6112
+ thinking: sanitizeSurrogates(block.thinking),
6113
+ signature: block.thinkingSignature
6114
+ });
6115
+ }
6116
+ } else if (block.type === "toolCall") {
6117
+ blocks.push({ type: "tool_use", id: block.id, name: block.name, input: block.arguments ?? {} });
6118
+ }
6119
+ }
6120
+ if (blocks.length === 0) continue;
6121
+ params.push({ role: "assistant", content: blocks });
6122
+ } else if (msg.role === "toolResult") {
6123
+ const toolResults = [];
6124
+ toolResults.push({
6125
+ type: "tool_result",
6126
+ tool_use_id: msg.toolCallId,
6127
+ content: convertContentBlocks(msg.content),
6128
+ is_error: msg.isError
6129
+ });
6130
+ let j = i + 1;
6131
+ while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
6132
+ const nextMsg = transformedMessages[j];
6133
+ toolResults.push({
6134
+ type: "tool_result",
6135
+ tool_use_id: nextMsg.toolCallId,
6136
+ content: convertContentBlocks(nextMsg.content),
6137
+ is_error: nextMsg.isError
6138
+ });
6139
+ j++;
6140
+ }
6141
+ i = j - 1;
6142
+ params.push({ role: "user", content: toolResults });
6026
6143
  }
6027
- return events;
6028
6144
  }
6029
- /** Stream ended without a terminal event. Caller decides how to fail. */
6030
- finishWithoutTerminal() {
6031
- return new ResponsesProtocolError(
6032
- `Responses stream ended without a terminal event (${this.diagnostics.terminalType ?? "none"} seen).`
6033
- );
6145
+ return params;
6146
+ }
6147
+ function convertTools2(tools) {
6148
+ if (!tools) return [];
6149
+ return tools.map((tool) => {
6150
+ const jsonSchema = tool.parameters;
6151
+ return {
6152
+ name: tool.name,
6153
+ description: tool.description,
6154
+ input_schema: {
6155
+ type: "object",
6156
+ properties: jsonSchema.properties || {},
6157
+ required: jsonSchema.required || []
6158
+ }
6159
+ };
6160
+ });
6161
+ }
6162
+ function applyCacheBreakpoints(params, retention) {
6163
+ if (retention === "none") return;
6164
+ const cacheControl = {
6165
+ type: "ephemeral",
6166
+ ...retention === "long" ? { ttl: "1h" } : {}
6167
+ };
6168
+ if (Array.isArray(params.system) && params.system.length > 0) {
6169
+ const last = params.system[params.system.length - 1];
6170
+ last.cache_control = { ...cacheControl };
6034
6171
  }
6035
- // ─── item lifecycle ─────────────────────────────────────────────────────
6036
- ensureStarted() {
6037
- if (this.started) return [];
6038
- this.started = true;
6039
- return [{ type: "start", partial: this.output }];
6172
+ if (Array.isArray(params.tools) && params.tools.length > 0) {
6173
+ const last = params.tools[params.tools.length - 1];
6174
+ last.cache_control = { ...cacheControl };
6040
6175
  }
6041
- requireItemIndex(raw) {
6042
- const index = raw.output_index;
6043
- if (typeof index !== "number" || !Number.isInteger(index) || index < 0) {
6044
- throw new ResponsesProtocolError(`Responses event "${raw.type}" is missing a valid output_index.`);
6176
+ for (let i = params.messages.length - 1; i >= 0; i--) {
6177
+ const msg = params.messages[i];
6178
+ if (msg.role !== "user") continue;
6179
+ if (typeof msg.content === "string") {
6180
+ msg.content = [{ type: "text", text: msg.content, cache_control: { ...cacheControl } }];
6181
+ } else if (Array.isArray(msg.content) && msg.content.length > 0) {
6182
+ msg.content[msg.content.length - 1].cache_control = { ...cacheControl };
6045
6183
  }
6046
- return index;
6184
+ break;
6047
6185
  }
6048
- onOutputItemAdded(raw) {
6049
- const outputIndex = this.requireItemIndex(raw);
6050
- const item = raw.item;
6051
- if (!isRecord2(item)) {
6052
- throw new ResponsesProtocolError(`response.output_item.added at index ${outputIndex} is missing the item.`);
6053
- }
6054
- if (this.items.has(outputIndex)) {
6055
- throw new ResponsesProtocolError(`Responses stream reused output_index ${outputIndex}.`);
6056
- }
6057
- const itemId = typeof item.id === "string" ? item.id : "";
6058
- if (item.type === "message") {
6059
- this.items.set(outputIndex, { kind: "message", itemId, blocks: /* @__PURE__ */ new Map() });
6060
- return this.ensureStarted();
6061
- }
6062
- if (item.type === "reasoning") {
6063
- const block = { type: "thinking", thinking: "" };
6064
- this.output.content.push(block);
6065
- this.items.set(outputIndex, { kind: "reasoning", itemId, block, lastSummaryIndex: null });
6066
- const startEvents = this.ensureStarted();
6067
- return [
6068
- ...startEvents,
6069
- { type: "thinking_start", contentIndex: this.output.content.length - 1, partial: this.output }
6070
- ];
6071
- }
6072
- if (item.type === "function_call") {
6073
- const callId = typeof item.call_id === "string" ? item.call_id : "";
6074
- if (!callId) {
6075
- throw new ResponsesProtocolError(`function_call output item at index ${outputIndex} is missing call_id.`);
6186
+ }
6187
+ var streamAnthropic = (model, context, options) => {
6188
+ if ((options?.transport ?? model.transport) === "websocket") throw new Error(`API ${model.api} does not support WebSocket transport.`);
6189
+ const stream2 = new AssistantMessageEventStream();
6190
+ (async () => {
6191
+ const output = {
6192
+ role: "assistant",
6193
+ content: [],
6194
+ api: model.api,
6195
+ provider: model.provider,
6196
+ model: model.id,
6197
+ usage: {
6198
+ input: 0,
6199
+ output: 0,
6200
+ cacheRead: 0,
6201
+ cacheWrite: 0,
6202
+ totalTokens: 0,
6203
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
6204
+ },
6205
+ stopReason: "stop",
6206
+ timestamp: Date.now()
6207
+ };
6208
+ try {
6209
+ const apiKey = options?.apiKey ?? getEnvApiKey(model.provider, model.apiKeyEnv) ?? "";
6210
+ const cacheCapability = getModelCacheCapability(model);
6211
+ const promptCacheSupported = cacheCapability.supported && isPromptCacheCapability(cacheCapability);
6212
+ const headers = buildAnthropicHeaders(
6213
+ model.headers,
6214
+ options?.headers,
6215
+ promptCacheSupported && options?.cacheRetention === "long"
6216
+ );
6217
+ const client = new Anthropic({
6218
+ apiKey,
6219
+ baseURL: model.baseUrl,
6220
+ dangerouslyAllowBrowser: true,
6221
+ defaultHeaders: headers
6222
+ });
6223
+ const params = {
6224
+ model: model.id,
6225
+ messages: convertMessages2(context.messages, model),
6226
+ max_tokens: options?.maxTokens || Math.floor(model.maxTokens / 3) || 1024,
6227
+ stream: true
6228
+ };
6229
+ if (context.systemPrompt) {
6230
+ params.system = [{ type: "text", text: sanitizeSurrogates(context.systemPrompt) }];
6231
+ }
6232
+ if (options?.temperature !== void 0) {
6233
+ params.temperature = options.temperature;
6234
+ }
6235
+ if (context.tools?.length) {
6236
+ params.tools = convertTools2(context.tools);
6237
+ }
6238
+ if (options?.thinkingEnabled && model.reasoning) {
6239
+ params.thinking = {
6240
+ type: "enabled",
6241
+ budget_tokens: options.thinkingBudgetTokens || 1024
6242
+ };
6243
+ }
6244
+ if (options?.toolChoice) {
6245
+ if (typeof options.toolChoice === "string") {
6246
+ params.tool_choice = { type: options.toolChoice };
6247
+ } else {
6248
+ params.tool_choice = options.toolChoice;
6249
+ }
6250
+ }
6251
+ if (promptCacheSupported) {
6252
+ applyCacheBreakpoints(params, options?.cacheRetention);
6253
+ }
6254
+ options?.onPayload?.(params);
6255
+ const anthropicStream = client.messages.stream({ ...params, stream: true }, { signal: options?.signal });
6256
+ stream2.push({ type: "start", partial: output });
6257
+ const blocks = output.content;
6258
+ let hasReportedInputUsage = false;
6259
+ for await (const event of anthropicStream) {
6260
+ if (event.type === "message_start") {
6261
+ applyAnthropicUsageUpdate(model, output.usage, event.message.usage);
6262
+ hasReportedInputUsage = typeof event.message.usage.input_tokens === "number" && Number.isFinite(event.message.usage.input_tokens) && event.message.usage.input_tokens >= 0;
6263
+ output.usageReported = false;
6264
+ } else if (event.type === "content_block_start") {
6265
+ if (event.content_block.type === "text") {
6266
+ const block = { type: "text", text: "", index: event.index };
6267
+ output.content.push(block);
6268
+ stream2.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output });
6269
+ } else if (event.content_block.type === "thinking") {
6270
+ const block = { type: "thinking", thinking: "", thinkingSignature: "", index: event.index };
6271
+ output.content.push(block);
6272
+ stream2.push({
6273
+ type: "thinking_start",
6274
+ contentIndex: output.content.length - 1,
6275
+ partial: output
6276
+ });
6277
+ } else if (event.content_block.type === "tool_use") {
6278
+ const block = {
6279
+ type: "toolCall",
6280
+ id: event.content_block.id,
6281
+ name: event.content_block.name,
6282
+ arguments: event.content_block.input ?? {},
6283
+ partialJson: "",
6284
+ index: event.index
6285
+ };
6286
+ output.content.push(block);
6287
+ stream2.push({
6288
+ type: "toolcall_start",
6289
+ contentIndex: output.content.length - 1,
6290
+ partial: output
6291
+ });
6292
+ }
6293
+ } else if (event.type === "content_block_delta") {
6294
+ if (event.delta.type === "text_delta") {
6295
+ const index = blocks.findIndex((b) => b.index === event.index);
6296
+ const block = blocks[index];
6297
+ if (block?.type === "text") {
6298
+ block.text += event.delta.text;
6299
+ stream2.push({ type: "text_delta", contentIndex: index, delta: event.delta.text, partial: output });
6300
+ }
6301
+ } else if (event.delta.type === "thinking_delta") {
6302
+ const index = blocks.findIndex((b) => b.index === event.index);
6303
+ const block = blocks[index];
6304
+ if (block?.type === "thinking") {
6305
+ block.thinking += event.delta.thinking;
6306
+ stream2.push({
6307
+ type: "thinking_delta",
6308
+ contentIndex: index,
6309
+ delta: event.delta.thinking,
6310
+ partial: output
6311
+ });
6312
+ }
6313
+ } else if (event.delta.type === "input_json_delta") {
6314
+ const index = blocks.findIndex((b) => b.index === event.index);
6315
+ const block = blocks[index];
6316
+ if (block?.type === "toolCall") {
6317
+ block.partialJson += event.delta.partial_json;
6318
+ block.arguments = parseStreamingJson(block.partialJson);
6319
+ stream2.push({
6320
+ type: "toolcall_delta",
6321
+ contentIndex: index,
6322
+ delta: event.delta.partial_json,
6323
+ partial: output
6324
+ });
6325
+ }
6326
+ } else if (event.delta.type === "signature_delta") {
6327
+ const index = blocks.findIndex((b) => b.index === event.index);
6328
+ const block = blocks[index];
6329
+ if (block?.type === "thinking") {
6330
+ block.thinkingSignature = (block.thinkingSignature || "") + event.delta.signature;
6331
+ }
6332
+ }
6333
+ } else if (event.type === "content_block_stop") {
6334
+ const index = blocks.findIndex((b) => b.index === event.index);
6335
+ const block = blocks[index];
6336
+ if (block) {
6337
+ delete block.index;
6338
+ if (block.type === "text") {
6339
+ stream2.push({
6340
+ type: "text_end",
6341
+ contentIndex: index,
6342
+ content: block.text,
6343
+ partial: output
6344
+ });
6345
+ } else if (block.type === "thinking") {
6346
+ stream2.push({
6347
+ type: "thinking_end",
6348
+ contentIndex: index,
6349
+ content: block.thinking,
6350
+ partial: output
6351
+ });
6352
+ } else if (block.type === "toolCall") {
6353
+ block.arguments = parseStreamingJson(block.partialJson);
6354
+ delete block.partialJson;
6355
+ stream2.push({
6356
+ type: "toolcall_end",
6357
+ contentIndex: index,
6358
+ toolCall: block,
6359
+ partial: output
6360
+ });
6361
+ }
6362
+ }
6363
+ } else if (event.type === "message_delta") {
6364
+ if (event.delta.stop_reason) {
6365
+ output.stopReason = mapStopReason(event.delta.stop_reason);
6366
+ }
6367
+ applyAnthropicUsageUpdate(model, output.usage, event.usage);
6368
+ if (hasReportedInputUsage && typeof event.usage.output_tokens === "number" && Number.isFinite(event.usage.output_tokens) && event.usage.output_tokens >= 0) output.usageReported = true;
6369
+ }
6076
6370
  }
6077
- const name = typeof item.name === "string" ? item.name : "";
6078
- if (!name || !itemId) throw new ResponsesProtocolError("function_call requires name and item id.");
6079
- const block = { type: "toolCall", id: callId, name, arguments: {} };
6080
- this.output.content.push(block);
6081
- const state = {
6082
- kind: "function_call",
6083
- itemId,
6084
- block,
6085
- partialArgs: "",
6086
- finalArgs: null,
6087
- completed: false,
6088
- contentIndex: this.output.content.length - 1
6089
- };
6090
- this.items.set(outputIndex, state);
6091
- this.toolCallStates.push(state);
6092
- const startEvents = this.ensureStarted();
6093
- return [
6094
- ...startEvents,
6095
- { type: "toolcall_start", contentIndex: state.contentIndex, partial: this.output }
6096
- ];
6097
- }
6098
- this.items.set(outputIndex, { kind: "ignored", itemType: String(item.type) });
6099
- this.diagnostics.ignoredItemTypes.add(String(item.type));
6100
- return [];
6101
- }
6102
- lookupItem(raw, kinds, label) {
6103
- const outputIndex = this.requireItemIndex(raw);
6104
- let state = this.items.get(outputIndex);
6105
- if (!state || !kinds.includes(state.kind)) {
6106
- throw new ResponsesProtocolError(
6107
- `Responses event "${raw.type ?? label}" references ${label} output_index ${outputIndex} that was never added (or is of the wrong item type).`
6108
- );
6109
- }
6110
- if (state.kind !== "ignored" && raw.item_id !== void 0 && raw.item_id !== state.itemId) throw new ResponsesProtocolError("Response item identity changed.");
6111
- return { state, outputIndex };
6112
- }
6113
- onContentPartAdded(raw) {
6114
- const part = raw.part;
6115
- const partType = isRecord2(part) ? part.type : void 0;
6116
- const kind = partType === "reasoning_text" ? "reasoning" : "message";
6117
- const { state } = this.lookupItem(raw, [kind], kind);
6118
- const partIndex = raw.content_index;
6119
- if (typeof partIndex !== "number" || !Number.isInteger(partIndex) || partIndex < 0) {
6120
- throw new ResponsesProtocolError("response.content_part.added is missing a valid content_index.");
6121
- }
6122
- if (state.kind !== "message") return [];
6123
- if (state.blocks.has(partIndex)) {
6124
- throw new ResponsesProtocolError(`Responses stream reused content_index ${partIndex} on one message item.`);
6125
- }
6126
- if (partType !== "output_text" && partType !== "refusal") {
6127
- return [];
6128
- }
6129
- const block = { type: "text", text: "" };
6130
- this.output.content.push(block);
6131
- state.blocks.set(partIndex, { block, contentIndex: this.output.content.length - 1 });
6132
- return [{ type: "text_start", contentIndex: this.output.content.length - 1, partial: this.output }];
6133
- }
6134
- messageBlockFor(raw) {
6135
- const { state } = this.lookupItem(raw, ["message"], "message");
6136
- if (state.kind !== "message") throw new ResponsesProtocolError("internal: expected message item");
6137
- const partIndex = raw.content_index;
6138
- if (typeof partIndex !== "number" || !Number.isInteger(partIndex) || partIndex < 0) {
6139
- throw new ResponsesProtocolError(`Responses event "${raw.type}" is missing a valid content_index.`);
6140
- }
6141
- const entry = state.blocks.get(partIndex);
6142
- if (!entry) {
6143
- throw new ResponsesProtocolError(
6144
- `Responses event "${raw.type}" references content_index ${partIndex} that was never added.`
6145
- );
6371
+ if (options?.signal?.aborted) {
6372
+ throw new Error("Request was aborted");
6373
+ }
6374
+ assertAssistantHasContent(output);
6375
+ stream2.push({ type: "done", reason: output.stopReason, message: output });
6376
+ stream2.end();
6377
+ } catch (error) {
6378
+ logEmptyAssistantContentError(error, model, options);
6379
+ for (const block of output.content) delete block.index;
6380
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
6381
+ output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
6382
+ stream2.push({ type: "error", reason: output.stopReason, error: output });
6383
+ stream2.end();
6146
6384
  }
6147
- return entry;
6148
- }
6149
- appendTextDelta(raw, kind) {
6150
- const delta = raw.delta;
6151
- if (typeof delta !== "string" || delta.length === 0) return [];
6152
- const entry = this.messageBlockFor(raw);
6153
- entry.block.text += delta;
6154
- return [{ type: "text_delta", contentIndex: entry.contentIndex, delta, partial: this.output }];
6385
+ })();
6386
+ return stream2;
6387
+ };
6388
+ var streamSimpleAnthropic = (model, context, options) => {
6389
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider, model.apiKeyEnv);
6390
+ if (!apiKey) {
6391
+ throw new Error(`No API key for provider: ${model.provider}`);
6155
6392
  }
6156
- validateTextDone(raw) {
6157
- this.messageBlockFor(raw);
6393
+ const base = buildBaseOptions(model, options, apiKey);
6394
+ if (!options?.reasoning) {
6395
+ return streamAnthropic(model, context, { ...base, thinkingEnabled: false });
6158
6396
  }
6159
- appendReasoningDelta(raw) {
6160
- const delta = raw.delta;
6161
- if (typeof delta !== "string" || delta.length === 0) return [];
6162
- const { state } = this.lookupItem(raw, ["reasoning"], "reasoning");
6163
- if (state.kind !== "reasoning") return [];
6164
- let text = delta;
6165
- const summaryIndex = raw.summary_index;
6166
- if (typeof summaryIndex === "number" && Number.isInteger(summaryIndex)) {
6167
- if (state.lastSummaryIndex !== null && summaryIndex !== state.lastSummaryIndex) {
6168
- text = `
6397
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options.thinkingBudgets);
6398
+ return streamAnthropic(model, context, {
6399
+ ...base,
6400
+ maxTokens: adjusted.maxTokens,
6401
+ thinkingEnabled: true,
6402
+ thinkingBudgetTokens: adjusted.thinkingBudget
6403
+ });
6404
+ };
6169
6405
 
6170
- ${delta}`;
6171
- }
6172
- state.lastSummaryIndex = summaryIndex;
6173
- }
6174
- state.block.thinking += text;
6175
- return [{ type: "thinking_delta", contentIndex: this.output.content.indexOf(state.block), delta: text, partial: this.output }];
6176
- }
6177
- appendFunctionCallArgsDelta(raw) {
6178
- const delta = raw.delta ?? raw.arguments;
6179
- if (typeof delta !== "string" || delta.length === 0) return [];
6180
- const { state } = this.lookupItem(raw, ["function_call"], "function_call");
6181
- if (state.kind !== "function_call") return [];
6182
- state.partialArgs += delta;
6183
- state.block.arguments = parseStreamingJson(state.partialArgs);
6184
- return [{ type: "toolcall_delta", contentIndex: state.contentIndex, delta, partial: this.output }];
6406
+ // ../../packages/ai/src/providers/responses/responses-compat.ts
6407
+ function getResponsesCompat(model) {
6408
+ const compat = model.compat ?? {};
6409
+ return {
6410
+ store: compat.store ?? false,
6411
+ supportsStore: compat.supportsStore ?? true,
6412
+ supportsReasoningEffort: compat.supportsReasoningEffort ?? true,
6413
+ supportsEncryptedReasoning: compat.supportsEncryptedReasoning ?? true,
6414
+ responsesContinuation: compat.responsesContinuation ?? false,
6415
+ supportsReasoningSummary: compat.supportsReasoningSummary ?? false,
6416
+ reasoningSummary: compat.reasoningSummary ?? "auto",
6417
+ timeoutReplay: compat.timeoutReplay ?? false
6418
+ };
6419
+ }
6420
+
6421
+ // ../../packages/ai/src/providers/responses/responses-request.ts
6422
+ var MAX_REASONING_ENVELOPE_BYTES = 512 * 1024;
6423
+ function decodeReasoningEnvelope(signature) {
6424
+ if (typeof signature !== "string" || signature.length === 0 || signature.length > MAX_REASONING_ENVELOPE_BYTES) {
6425
+ return null;
6185
6426
  }
6186
- onFunctionCallArgsDone(raw) {
6187
- const { state } = this.lookupItem(raw, ["function_call"], "function_call");
6188
- if (state.kind !== "function_call") return;
6189
- if (typeof raw.arguments === "string") {
6190
- state.finalArgs = raw.arguments;
6191
- }
6427
+ let parsed;
6428
+ try {
6429
+ parsed = JSON.parse(signature);
6430
+ } catch {
6431
+ return null;
6192
6432
  }
6193
- onOutputItemDone(raw) {
6194
- const outputIndex = this.requireItemIndex(raw);
6195
- const item = raw.item;
6196
- if (!isRecord2(item)) {
6197
- throw new ResponsesProtocolError(`response.output_item.done at index ${outputIndex} is missing the item.`);
6198
- }
6199
- const state = this.items.get(outputIndex);
6200
- if (!state) {
6201
- throw new ResponsesProtocolError(`response.output_item.done references output_index ${outputIndex} that was never added.`);
6202
- }
6203
- if (state.kind !== "ignored" && (item.id !== state.itemId || item.type !== state.kind)) throw new ResponsesProtocolError("Response done item identity changed.");
6204
- switch (state.kind) {
6205
- case "message": {
6206
- const events = [];
6207
- for (const { block, contentIndex } of state.blocks.values()) {
6208
- events.push({ type: "text_end", contentIndex, content: block.text, partial: this.output });
6209
- }
6210
- return events;
6211
- }
6212
- case "reasoning": {
6213
- const events = [];
6214
- const encrypted = typeof item.encrypted_content === "string" ? item.encrypted_content : null;
6215
- const itemId = typeof item.id === "string" && item.id.length > 0 ? item.id : state.itemId;
6216
- if (itemId) {
6217
- state.block.thinkingSignature = JSON.stringify({ v: 1, id: itemId, encrypted_content: encrypted });
6218
- }
6219
- events.push({
6220
- type: "thinking_end",
6221
- contentIndex: this.output.content.indexOf(state.block),
6222
- content: state.block.thinking,
6223
- partial: this.output
6224
- });
6225
- return events;
6226
- }
6227
- case "function_call": {
6228
- const finalText = typeof item.arguments === "string" && item.arguments.length > 0 ? item.arguments : state.finalArgs ?? state.partialArgs;
6229
- if (typeof item.call_id === "string" && item.call_id.length > 0 && item.call_id !== state.block.id) {
6230
- throw new ResponsesProtocolError(`function_call item changed call_id from "${state.block.id}" to "${item.call_id}".`);
6231
- }
6232
- if (typeof item.name === "string" && item.name.length > 0 && item.name !== state.block.name) {
6233
- throw new ResponsesProtocolError(`function_call item changed name from "${state.block.name}" to "${item.name}".`);
6234
- }
6235
- state.completed = true;
6236
- state.finalArgs = finalText;
6237
- if (this.canParseArgs(state)) {
6238
- return this.finalizeFunctionCall(state, finalText);
6239
- }
6240
- return [];
6241
- }
6242
- case "ignored":
6243
- return [];
6244
- }
6433
+ if (!isRecord(parsed) || parsed.v !== 1 || typeof parsed.id !== "string" || parsed.id.length === 0) {
6434
+ return null;
6245
6435
  }
6246
- finalizeFunctionCall(state, argsText) {
6247
- const text = argsText.trim();
6248
- let parsed;
6249
- if (text.length === 0) {
6250
- parsed = {};
6251
- } else {
6252
- try {
6253
- const value = JSON.parse(text);
6254
- if (!isRecord2(value)) {
6255
- throw new ResponsesProtocolError(`function_call "${state.block.name || "unknown"}" arguments are not a JSON object.`);
6256
- }
6257
- parsed = value;
6258
- } catch (error) {
6259
- if (error instanceof ResponsesProtocolError) throw error;
6260
- const message = error instanceof Error ? error.message : String(error);
6261
- throw new ResponsesProtocolError(
6262
- `function_call "${state.block.name || "unknown"}" returned incomplete or invalid JSON arguments: ${message}`
6263
- );
6264
- }
6265
- }
6266
- state.block.arguments = parsed;
6267
- return [{ type: "toolcall_end", contentIndex: state.contentIndex, toolCall: state.block, partial: this.output }];
6436
+ const encrypted = parsed.encrypted_content;
6437
+ if (encrypted !== void 0 && encrypted !== null && typeof encrypted !== "string") {
6438
+ return null;
6268
6439
  }
6269
- // ─── terminals ──────────────────────────────────────────────────────────
6270
- requireTerminalResponse(raw) {
6271
- const response = raw.response;
6272
- const expected = raw.type.slice("response.".length);
6273
- if (!isRecord2(response) || typeof response.id !== "string" || !response.id || response.status !== expected) {
6274
- throw new ResponsesProtocolError(`Malformed ${raw.type}: requires response id and status ${expected}.`);
6440
+ return { v: 1, id: parsed.id, encrypted_content: encrypted };
6441
+ }
6442
+ function buildResponsesInput(model, context) {
6443
+ const items = [];
6444
+ const isSameModel = (msg) => msg.provider === model.provider && msg.api === model.api && msg.model === model.id;
6445
+ const transformed = transformMessages(context.messages, model);
6446
+ for (const msg of transformed) {
6447
+ if (msg.role === "user") {
6448
+ items.push(encodeUserMessage(msg.content, model));
6449
+ } else if (msg.role === "assistant") {
6450
+ encodeAssistantMessage(msg, isSameModel, items);
6451
+ } else if (msg.role === "toolResult") {
6452
+ items.push(encodeToolResult(msg, model));
6275
6453
  }
6276
- return response;
6277
6454
  }
6278
- onTerminal(raw, type, reason = "stop", errorText) {
6279
- this.diagnostics.terminalType = type;
6280
- const response = type === "error" ? void 0 : this.requireTerminalResponse(raw);
6281
- this.terminal = { reason, response, errorText };
6282
- return this.closeResponse(type);
6455
+ return items;
6456
+ }
6457
+ function encodeUserMessage(content, model) {
6458
+ if (typeof content === "string") {
6459
+ return { role: "user", type: "message", content };
6283
6460
  }
6284
- onIncomplete(raw) {
6285
- this.diagnostics.terminalType = "response.incomplete";
6286
- const response = this.requireTerminalResponse(raw);
6287
- const reason = response?.incomplete_details?.reason;
6288
- if (reason === "content_filter" || reason === "steered" || reason === void 0) {
6289
- this.terminal = {
6290
- reason: "error",
6291
- response,
6292
- errorText: reason === "steered" ? "Response ended incomplete with reason 'steered' but no steering was sent." : `Response ended incomplete${reason ? ` (${reason})` : " without a reason"}.`
6293
- };
6294
- return this.closeResponse("response.incomplete");
6295
- }
6296
- this.terminal = { reason: "length", response };
6297
- return this.closeResponse("response.incomplete");
6461
+ const parts = [];
6462
+ for (const block of content) {
6463
+ parts.push(...encodeUserContentBlock(block, model));
6298
6464
  }
6299
- failedText(raw) {
6300
- const response = isRecord2(raw.response) ? raw.response : void 0;
6301
- const error = isRecord2(response?.error) ? response?.error : void 0;
6302
- const message = typeof error?.message === "string" && error.message.length > 0 ? error.message : "Response failed";
6303
- const code = typeof error?.code === "string" && error.code.length > 0 ? ` (code=${error.code})` : "";
6304
- return `${message}${code}`;
6465
+ if (parts.length === 0) {
6466
+ return { role: "user", type: "message", content: "" };
6305
6467
  }
6306
- /** Apply terminal semantics and produce the final event. */
6307
- closeResponse(terminalType) {
6308
- const terminal = this.terminal;
6309
- const response = terminal.response;
6310
- if (response && isRecord2(response.usage)) {
6311
- this.output.usage = normalizeResponsesUsage(this.model, response.usage);
6312
- this.output.usageReported = [response.usage.input_tokens, response.usage.output_tokens].every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
6313
- }
6314
- if (terminal.reason === "error") {
6315
- this.output.stopReason = "error";
6316
- this.output.errorMessage = terminal.errorText ?? "Response failed";
6317
- return [{ type: "error", reason: "error", error: this.output }];
6318
- }
6319
- let stopReason = terminal.reason === "length" ? "length" : "stop";
6320
- if (this.toolCallStates.length > 0) {
6321
- stopReason = "toolUse";
6468
+ return { role: "user", type: "message", content: parts };
6469
+ }
6470
+ function omittedAttachmentNote(modality, reason) {
6471
+ return { type: "input_text", text: `[${modality} attachment omitted: ${reason} Re-read with a compatible model.]` };
6472
+ }
6473
+ function encodeUserContentBlock(block, model) {
6474
+ if (block.type === "hostContext") {
6475
+ throw new ResponsesProtocolError(`Unprojected hostContext block reached Responses conversion (${block.kind}); the request path must project host envelopes to text first.`);
6476
+ }
6477
+ const modality = block.type === "fileRef" ? block.modality : block.type;
6478
+ if (modality !== "text" && !model.input.includes(modality)) {
6479
+ return [omittedAttachmentNote(modality, "current model does not support this modality.")];
6480
+ }
6481
+ switch (block.type) {
6482
+ case "text":
6483
+ return [{ type: "input_text", text: block.text }];
6484
+ case "image":
6485
+ return [{ type: "input_image", image_url: `data:${block.mimeType};base64,${block.data}` }];
6486
+ case "video":
6487
+ case "audio":
6488
+ return [omittedAttachmentNote(block.type, `the Responses provider does not deliver ${block.type} input.`)];
6489
+ case "fileRef": {
6490
+ const ref = block;
6491
+ if (ref.modality === "image") {
6492
+ return [{ type: "input_image", image_url: ref.url }];
6493
+ }
6494
+ return [omittedAttachmentNote(ref.modality, `the Responses provider does not deliver ${ref.modality} file references.`)];
6322
6495
  }
6323
- if (terminal.reason === "length") {
6324
- const truncated = this.toolCallStates.filter((state) => !state.completed || !this.canParseArgs(state));
6325
- if (truncated.length > 0) {
6326
- const dropped = new Set(truncated.map((state) => state.block));
6327
- this.output.content = this.output.content.filter(
6328
- (block) => block.type !== "toolCall" || !dropped.has(block)
6329
- );
6330
- this.toolCallStates = this.toolCallStates.filter((state) => !dropped.has(state.block));
6331
- const names = truncated.map((state) => `"${state.block.name || "unnamed"}"`).sort().join(", ");
6332
- this.output.content.push({
6333
- type: "text",
6334
- text: `[output truncated: max_output_tokens cut ${truncated.length === 1 ? "a tool call" : `${truncated.length} tool calls`} mid-arguments (${names}); the call${truncated.length === 1 ? " was" : "s were"} dropped. Re-issue the call or continue with fewer/smaller requests.]`
6335
- });
6336
- if (this.toolCallStates.length === 0) {
6337
- stopReason = "length";
6496
+ default:
6497
+ throw new ResponsesProtocolError("Unsupported Responses content block.");
6498
+ }
6499
+ }
6500
+ function encodeAssistantMessage(msg, isSameModel, items) {
6501
+ for (const block of msg.content) {
6502
+ if (block.type === "thinking") {
6503
+ const thinking = block;
6504
+ if (isSameModel(msg)) {
6505
+ const envelope = decodeReasoningEnvelope(thinking.thinkingSignature);
6506
+ if (thinking.thinkingSignature && !envelope) {
6507
+ throw new ResponsesProtocolError("Invalid Responses reasoning signature.");
6508
+ }
6509
+ if (envelope) {
6510
+ items.push({
6511
+ type: "reasoning",
6512
+ id: envelope.id,
6513
+ summary: thinking.thinking.trim() ? [{ type: "summary_text", text: thinking.thinking }] : [],
6514
+ ...envelope.encrypted_content ? { encrypted_content: envelope.encrypted_content } : {}
6515
+ });
6516
+ continue;
6338
6517
  }
6339
6518
  }
6340
- } else if (terminal.reason === "stop") {
6341
- const brokenCalls = this.toolCallStates.filter((state) => !state.completed || !this.canParseArgs(state));
6342
- if (brokenCalls.length > 0) {
6343
- const first = brokenCalls[0];
6344
- this.output.stopReason = "error";
6345
- this.output.errorMessage = `function_call "${first.block.name || "unknown"}" returned incomplete or invalid JSON arguments on a completed response.`;
6346
- return [{ type: "error", reason: "error", error: this.output }];
6519
+ if (thinking.thinking && thinking.thinking.trim().length > 0) {
6520
+ items.push({ role: "assistant", type: "message", content: thinking.thinking });
6347
6521
  }
6522
+ continue;
6348
6523
  }
6349
- if (stopReason === "toolUse" && this.toolCallStates.length === 0) {
6350
- stopReason = "stop";
6524
+ if (block.type === "text") {
6525
+ const text = block;
6526
+ if (text.text && text.text.trim().length > 0) {
6527
+ items.push({ role: "assistant", type: "message", content: text.text });
6528
+ }
6529
+ continue;
6351
6530
  }
6352
- this.output.stopReason = stopReason;
6353
- void terminalType;
6354
- return [{ type: "done", reason: stopReason, message: this.output }];
6355
- }
6356
- canParseArgs(state) {
6357
- const text = (state.finalArgs ?? state.partialArgs).trim();
6358
- if (text.length === 0) return false;
6359
- try {
6360
- return isRecord2(JSON.parse(text));
6361
- } catch {
6362
- return false;
6531
+ if (block.type === "toolCall") {
6532
+ const call = block;
6533
+ items.push({
6534
+ type: "function_call",
6535
+ call_id: call.id,
6536
+ name: call.name,
6537
+ arguments: JSON.stringify(call.arguments ?? {})
6538
+ });
6363
6539
  }
6364
6540
  }
6365
- };
6366
-
6367
- // ../../packages/ai/src/providers/responses/responses-diagnostics.ts
6368
- function reportSubmission(options, body, details) {
6369
- if (!options?.onTransportDiagnostic) return;
6370
- let requestBytes = 0;
6371
- for (const character of body) {
6372
- const point = character.codePointAt(0);
6373
- requestBytes += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
6374
- }
6375
- try {
6376
- options.onTransportDiagnostic({ ...details, requestBytes });
6377
- } catch {
6378
- }
6379
6541
  }
6380
- function reportLifecycle(options, event) {
6381
- if (!options?.onTransportLifecycle) return;
6382
- try {
6383
- options.onTransportLifecycle({ ...event });
6384
- } catch {
6385
- }
6542
+ function buildResponsesOutput(message) {
6543
+ const items = [];
6544
+ encodeAssistantMessage(message, () => true, items);
6545
+ return items;
6386
6546
  }
6387
- var localRequestCounter = 0;
6388
- function nextLocalRequestId(prefix = "req") {
6389
- localRequestCounter += 1;
6390
- return `${prefix}-${localRequestCounter}-${Math.random().toString(36).slice(2, 8)}`;
6547
+ function encodeToolResult(msg, model) {
6548
+ const output = msg.content.every((block) => block.type === "text") ? msg.content.map((block) => block.text).join("\n") || "(empty result)" : msg.content.flatMap((block) => encodeUserContentBlock(block, model));
6549
+ return { type: "function_call_output", call_id: msg.toolCallId, output };
6391
6550
  }
6392
- function timeoutSuffix(budgetMs, lagMs) {
6393
- const budget = budgetMs && budgetMs > 0 ? ` (budget ${Math.round(budgetMs / 1e3)}s)` : "";
6394
- if (lagMs > 1e3) {
6395
- return `${budget} \u2014 timer fired ${Math.round(lagMs / 1e3)}s late (system sleep or suspended process)`;
6551
+ function encodeTools(tools) {
6552
+ return tools.map((tool) => ({
6553
+ type: "function",
6554
+ name: tool.name,
6555
+ description: tool.description,
6556
+ parameters: tool.parameters ?? { type: "object", properties: {} },
6557
+ strict: false
6558
+ }));
6559
+ }
6560
+ function buildResponsesRequest(model, context, options, compat = getResponsesCompat(model)) {
6561
+ const params = {
6562
+ model: model.id,
6563
+ input: buildResponsesInput(model, context)
6564
+ };
6565
+ if (context.systemPrompt !== void 0 && context.systemPrompt !== null && context.systemPrompt.length > 0) {
6566
+ params.instructions = context.systemPrompt;
6396
6567
  }
6397
- return budget;
6568
+ if (compat.supportsStore) {
6569
+ params.store = compat.store;
6570
+ }
6571
+ if (options?.maxTokens !== void 0 && options.maxTokens > 0) {
6572
+ params.max_output_tokens = options.maxTokens;
6573
+ }
6574
+ if (options?.temperature !== void 0) params.temperature = options.temperature;
6575
+ if (options?.topP !== void 0) params.top_p = options.topP;
6576
+ if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
6577
+ params.reasoning = { effort: options.reasoningEffort };
6578
+ }
6579
+ if (model.reasoning && compat.supportsReasoningSummary && compat.reasoningSummary !== "none") {
6580
+ params.reasoning = params.reasoning ?? {};
6581
+ params.reasoning.summary = compat.reasoningSummary;
6582
+ }
6583
+ if (compat.supportsEncryptedReasoning && model.reasoning) {
6584
+ params.include = ["reasoning.encrypted_content"];
6585
+ }
6586
+ if (context.tools && context.tools.length > 0) {
6587
+ params.tools = encodeTools(context.tools);
6588
+ params.parallel_tool_calls = true;
6589
+ }
6590
+ if (options?.toolChoice !== void 0) {
6591
+ params.tool_choice = options.toolChoice === "required" ? "required" : options.toolChoice;
6592
+ }
6593
+ return params;
6398
6594
  }
6399
- function monotonicNow() {
6400
- const perf = globalThis.performance;
6401
- return typeof perf?.now === "function" ? perf.now() : Date.now();
6595
+ function buildResponsesSSEPayload(model, context, options) {
6596
+ return { ...buildResponsesRequest(model, context, options), stream: true };
6597
+ }
6598
+ function buildResponsesCreateEvent(model, context, options) {
6599
+ const params = buildResponsesRequest(model, context, options);
6600
+ delete params.stream;
6601
+ return { type: "response.create", ...params };
6402
6602
  }
6403
6603
 
6404
6604
  // ../../packages/ai/src/providers/responses/responses-sse.ts
@@ -6466,6 +6666,7 @@ function streamResponsesSSE(model, context, options) {
6466
6666
  void (async () => {
6467
6667
  const reducer = new ResponsesEventReducer(model);
6468
6668
  const localRequestId = nextLocalRequestId("sse");
6669
+ const sseDump = openSseDumpSink(localRequestId, `${model.provider}/${model.id}`);
6469
6670
  const startedAt = monotonicNow();
6470
6671
  let lastReceiveAt = startedAt;
6471
6672
  let receivedMessageCount = 0;
@@ -6628,6 +6829,7 @@ function streamResponsesSSE(model, context, options) {
6628
6829
  const message = error instanceof Error ? error.message : String(error);
6629
6830
  throw new ResponsesProtocolError(`Responses SSE stream returned malformed JSON: ${message}`);
6630
6831
  }
6832
+ sseDump.record(event);
6631
6833
  if (!isResponsesEventLike(event)) {
6632
6834
  throw new ResponsesProtocolError("Responses SSE payload is not an event object with a string type.");
6633
6835
  }
@@ -6635,10 +6837,10 @@ function streamResponsesSSE(model, context, options) {
6635
6837
  sawModelContent = true;
6636
6838
  }
6637
6839
  const incomingResponse = event.response;
6638
- if (event.type === "response.created" && (!isRecord2(incomingResponse) || typeof incomingResponse.id !== "string" || !incomingResponse.id)) {
6840
+ if (event.type === "response.created" && (!isRecord(incomingResponse) || typeof incomingResponse.id !== "string" || !incomingResponse.id)) {
6639
6841
  throw new ResponsesProtocolError("response.created requires a response id.");
6640
6842
  }
6641
- if (isRecord2(incomingResponse) && typeof incomingResponse.id === "string") {
6843
+ if (isRecord(incomingResponse) && typeof incomingResponse.id === "string") {
6642
6844
  if (responseId && (incomingResponse.id !== responseId || event.type === "response.created")) {
6643
6845
  throw new ResponsesProtocolError("Response identity changed within a request.");
6644
6846
  }
@@ -6712,6 +6914,7 @@ function streamResponsesSSE(model, context, options) {
6712
6914
  } finally {
6713
6915
  clearTotalTimer();
6714
6916
  options?.signal?.removeEventListener("abort", onUserAbort);
6917
+ await sseDump.flush();
6715
6918
  }
6716
6919
  })();
6717
6920
  return stream2;
@@ -6947,6 +7150,7 @@ function streamResponsesWS(model, context, options) {
6947
7150
  }
6948
7151
  state.busy = true;
6949
7152
  const localRequestId = nextLocalRequestId("ws");
7153
+ const sseDump = openSseDumpSink(localRequestId, `${model.provider}/${model.id}`);
6950
7154
  const requestGeneration = ++state.requestGeneration;
6951
7155
  const startedAt = monotonicNow();
6952
7156
  let lastReceiveAt = startedAt;
@@ -7293,12 +7497,13 @@ function streamResponsesWS(model, context, options) {
7293
7497
  try {
7294
7498
  if (message.isBinary) throw new ResponsesProtocolError("Responses requires JSON text messages.");
7295
7499
  const event = JSON.parse(message.data);
7296
- if (!isRecord2(event)) throw new ResponsesProtocolError("Invalid Responses WebSocket event.");
7500
+ sseDump.record(event);
7501
+ if (!isRecord(event)) throw new ResponsesProtocolError("Invalid Responses WebSocket event.");
7297
7502
  if (typeof event.type === "string") {
7298
7503
  if (event.type === "response.created") sawResponseCreated = true;
7299
7504
  else if (event.type.startsWith("response.output") || event.type.startsWith("response.content") || event.type.startsWith("response.reasoning")) sawModelContent = true;
7300
7505
  }
7301
- if (!started && attempt === 0 && payload.previous_response_id && event.type === "error" && event.status === 400 && isRecord2(event.error) && event.error.code === "previous_response_not_found" && event.error.param === "previous_response_id") {
7506
+ if (!started && attempt === 0 && payload.previous_response_id && event.type === "error" && event.status === 400 && isRecord(event.error) && event.error.code === "previous_response_not_found" && event.error.param === "previous_response_id") {
7302
7507
  delete payload.previous_response_id;
7303
7508
  payload.input = fullInput;
7304
7509
  continuationReason = "previous_response_not_found";
@@ -7308,13 +7513,13 @@ function streamResponsesWS(model, context, options) {
7308
7513
  if (!started && typeof event.type === "string" && event.type !== "error" && !event.type.startsWith("response.")) continue;
7309
7514
  if (started && event.type === "response.created") throw new ResponsesProtocolError("Duplicate response.created within a request.");
7310
7515
  if (!started && event.type !== "error") {
7311
- if (event.type !== "response.created" || !isRecord2(event.response) || typeof event.response.id !== "string" || !event.response.id || event.response.id === state.lastResponseId) {
7516
+ if (event.type !== "response.created" || !isRecord(event.response) || typeof event.response.id !== "string" || !event.response.id || event.response.id === state.lastResponseId) {
7312
7517
  throw new ResponsesProtocolError("Expected a new response.created before output.");
7313
7518
  }
7314
7519
  started = true;
7315
7520
  responseId = event.response.id;
7316
7521
  }
7317
- if (responseId && isRecord2(event.response) && event.response.id !== responseId) throw new ResponsesProtocolError("Response identity changed within a request.");
7522
+ if (responseId && isRecord(event.response) && event.response.id !== responseId) throw new ResponsesProtocolError("Response identity changed within a request.");
7318
7523
  events = reducer.feed(event);
7319
7524
  } catch (error) {
7320
7525
  reducer.message.remoteFailure = { category: "other" };
@@ -7426,6 +7631,7 @@ function streamResponsesWS(model, context, options) {
7426
7631
  });
7427
7632
  for (const event of terminalEvents) stream2.push(event);
7428
7633
  stream2.end();
7634
+ await sseDump.flush();
7429
7635
  }
7430
7636
  })();
7431
7637
  return stream2;
@@ -11012,6 +11218,8 @@ export {
11012
11218
  assertAssistantHasContent,
11013
11219
  isEmptyAssistantContentError,
11014
11220
  logEmptyAssistantContentError,
11221
+ RESPONSES_PROTOCOL_ERROR_CODE,
11222
+ ResponsesProtocolError,
11015
11223
  OPENAI_COMPAT_PROTOCOL_ERROR_CODE,
11016
11224
  OpenAICompatProtocolError,
11017
11225
  streamOpenAICompletions,
@@ -11019,8 +11227,6 @@ export {
11019
11227
  streamAnthropic,
11020
11228
  streamSimpleAnthropic,
11021
11229
  getResponsesCompat,
11022
- RESPONSES_PROTOCOL_ERROR_CODE,
11023
- ResponsesProtocolError,
11024
11230
  disposeModelTransports,
11025
11231
  streamResponses,
11026
11232
  streamSimpleResponses,