@howaboua/pi-durable-openai-responses 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,7 @@ export interface GrammarToolInputJsonBuffer {
12
12
  closed: boolean;
13
13
  }
14
14
  export declare function getGrammarToolInput(toolName: string, arguments_: Record<string, unknown>, inputProperty: string): string;
15
- export declare function appendGrammarToolInputJsonDelta(buffer: GrammarToolInputJsonBuffer, inputProperty: string, nextInput: string, close: boolean): string | undefined;
15
+ export declare function appendGrammarToolInputJsonDelta(buffer: GrammarToolInputJsonBuffer, inputProperty: string, inputDelta: string): string | undefined;
16
+ export declare function closeGrammarToolInputJson(buffer: GrammarToolInputJsonBuffer, inputProperty: string, finalInput: string | undefined): string | undefined;
16
17
  export declare function resolveGrammarConstrainedSampling(tool: Tool, supportsOpenAIGrammarTools: boolean): GrammarConstrainedSampling | undefined;
17
18
  export declare function createGrammarToolInputProperties(tools: Tool[] | undefined, supportsOpenAIGrammarTools: boolean): ReadonlyMap<string, string>;
package/dist/index.js CHANGED
@@ -244,30 +244,35 @@ function getGrammarToolInput(toolName, arguments_, inputProperty) {
244
244
  }
245
245
  return input;
246
246
  }
247
- function appendGrammarToolInputJsonDelta(buffer, inputProperty, nextInput, close) {
247
+ function appendGrammarToolInputJsonDelta(buffer, inputProperty, inputDelta) {
248
248
  if (buffer.closed) {
249
- if (close && nextInput === buffer.input)
250
- return;
251
249
  throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);
252
250
  }
253
- if (!nextInput.startsWith(buffer.input)) {
254
- throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);
255
- }
256
- const inputDelta = nextInput.slice(buffer.input.length);
257
- if (!close && inputDelta.length === 0)
251
+ if (inputDelta.length === 0)
258
252
  return;
259
- let delta = "";
260
- if (!buffer.started) {
261
- delta += `{${JSON.stringify(inputProperty)}:"`;
262
- buffer.started = true;
253
+ buffer.input += inputDelta;
254
+ return grammarToolInputJsonStart(buffer, inputProperty) + JSON.stringify(inputDelta).slice(1, -1);
255
+ }
256
+ function closeGrammarToolInputJson(buffer, inputProperty, finalInput) {
257
+ if (buffer.closed) {
258
+ if (finalInput === undefined || finalInput === buffer.input)
259
+ return;
260
+ throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);
263
261
  }
264
- delta += JSON.stringify(inputDelta).slice(1, -1);
265
- buffer.input = nextInput;
266
- if (close) {
267
- delta += '"}';
268
- buffer.closed = true;
262
+ if (finalInput !== undefined && !finalInput.startsWith(buffer.input)) {
263
+ throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);
269
264
  }
270
- return delta;
265
+ const rest = finalInput === undefined ? "" : finalInput.slice(buffer.input.length);
266
+ if (finalInput !== undefined)
267
+ buffer.input = finalInput;
268
+ buffer.closed = true;
269
+ return `${grammarToolInputJsonStart(buffer, inputProperty)}${JSON.stringify(rest).slice(1, -1)}"}`;
270
+ }
271
+ function grammarToolInputJsonStart(buffer, inputProperty) {
272
+ if (buffer.started)
273
+ return "";
274
+ buffer.started = true;
275
+ return `{${JSON.stringify(inputProperty)}:"`;
271
276
  }
272
277
  function inferGrammarInputProperty(tool) {
273
278
  const schema = tool.parameters;
@@ -808,8 +813,7 @@ function normalizeResponsesToolHistory(input) {
808
813
  // packages/openai-responses/src/openai-responses/stream.ts
809
814
  import {
810
815
  calculateCost,
811
- parseStreamingJson,
812
- parseToolCallArguments
816
+ ToolCallArgumentsStream
813
817
  } from "@earendil-works/pi-ai";
814
818
  async function processResponsesStream(openaiStream, output, stream, model, options) {
815
819
  const blocks = output.content;
@@ -820,12 +824,15 @@ async function processResponsesStream(openaiStream, output, stream, model, optio
820
824
  output.stopReason = "error";
821
825
  output.errorMessage = `Invalid Responses tool stream: ${message}`;
822
826
  };
823
- const appendCustomInput = (state, nextInput, close) => {
824
- const delta = appendGrammarToolInputJsonDelta(state.jsonBuffer, state.property, nextInput, close);
825
- state.input = nextInput;
826
- state.block.arguments = { [state.property]: nextInput };
827
- return delta;
827
+ const sendCustomInput = (state, delta) => {
828
+ state.block.arguments = { [state.property]: state.jsonBuffer.input };
829
+ if (state.unsent === "")
830
+ return delta;
831
+ const sent = state.unsent + (delta ?? "");
832
+ state.unsent = "";
833
+ return sent;
828
834
  };
835
+ const closeCustomInput = (state, finalInput) => sendCustomInput(state, closeGrammarToolInputJson(state.jsonBuffer, state.property, finalInput));
829
836
  const renderReasoningParts = (parts) => Array.from(parts.entries()).sort(([a], [b]) => a - b).map(([, part]) => part.text).join(`
830
837
 
831
838
  `);
@@ -871,7 +878,7 @@ async function processResponsesStream(openaiStream, output, stream, model, optio
871
878
  if (event.type === "response.custom_tool_call_input.delta") {
872
879
  const state = outputStates.get(event.output_index);
873
880
  if (state?.kind === "custom_tool_call") {
874
- const delta = appendCustomInput(state, state.input + event.delta, false);
881
+ const delta = sendCustomInput(state, appendGrammarToolInputJsonDelta(state.jsonBuffer, state.property, event.delta));
875
882
  if (delta !== undefined)
876
883
  stream.push({
877
884
  type: "toolcall_delta",
@@ -885,7 +892,7 @@ async function processResponsesStream(openaiStream, output, stream, model, optio
885
892
  if (event.type === "response.custom_tool_call_input.done") {
886
893
  const state = outputStates.get(event.output_index);
887
894
  if (state?.kind === "custom_tool_call") {
888
- const delta = appendCustomInput(state, event.input, true);
895
+ const delta = closeCustomInput(state, event.input);
889
896
  if (delta !== undefined)
890
897
  stream.push({
891
898
  type: "toolcall_delta",
@@ -913,13 +920,14 @@ async function processResponsesStream(openaiStream, output, stream, model, optio
913
920
  ...customItem.namespace !== undefined ? { namespace: customItem.namespace } : {}
914
921
  };
915
922
  output.content.push(currentBlock);
923
+ const jsonBuffer = { input: "", started: false, closed: false };
916
924
  outputStates.set(event.output_index, {
917
925
  kind: "custom_tool_call",
918
926
  blockIndex: blockIndex(),
919
927
  block: currentBlock,
920
- input,
921
928
  property,
922
- jsonBuffer: { input: "", started: false, closed: false }
929
+ jsonBuffer,
930
+ unsent: appendGrammarToolInputJsonDelta(jsonBuffer, property, input) ?? ""
923
931
  });
924
932
  stream.push({
925
933
  type: "toolcall_start",
@@ -956,20 +964,21 @@ async function processResponsesStream(openaiStream, output, stream, model, optio
956
964
  partial: output
957
965
  });
958
966
  } else if (item.type === "function_call") {
967
+ const args = new ToolCallArgumentsStream;
959
968
  const namespace = item.namespace;
960
969
  const currentBlock = {
961
970
  type: "toolCall",
962
971
  id: `${item.call_id}|${item.id ?? ""}`,
963
972
  name: item.name,
964
- arguments: {},
965
- ...namespace !== undefined ? { namespace } : {},
966
- partialJson: item.arguments || ""
973
+ arguments: item.arguments ? args.append(item.arguments) : {},
974
+ ...namespace !== undefined ? { namespace } : {}
967
975
  };
968
976
  output.content.push(currentBlock);
969
977
  outputStates.set(event.output_index, {
970
978
  kind: "function_call",
971
979
  blockIndex: blockIndex(),
972
- block: currentBlock
980
+ block: currentBlock,
981
+ arguments: args
973
982
  });
974
983
  stream.push({
975
984
  type: "toolcall_start",
@@ -1057,8 +1066,7 @@ async function processResponsesStream(openaiStream, output, stream, model, optio
1057
1066
  } else if (event.type === "response.function_call_arguments.delta") {
1058
1067
  const state = outputStates.get(event.output_index);
1059
1068
  if (state?.kind === "function_call") {
1060
- state.block.partialJson = (state.block.partialJson ?? "") + event.delta;
1061
- state.block.arguments = parseStreamingJson(state.block.partialJson);
1069
+ state.block.arguments = state.arguments.append(event.delta);
1062
1070
  stream.push({
1063
1071
  type: "toolcall_delta",
1064
1072
  contentIndex: state.blockIndex,
@@ -1069,31 +1077,26 @@ async function processResponsesStream(openaiStream, output, stream, model, optio
1069
1077
  } else if (event.type === "response.function_call_arguments.done") {
1070
1078
  const state = outputStates.get(event.output_index);
1071
1079
  if (state?.kind === "function_call") {
1072
- const previousPartialJson = state.block.partialJson ?? "";
1073
- state.block.partialJson = event.arguments;
1074
- state.block.arguments = parseStreamingJson(state.block.partialJson);
1075
- if (event.arguments.startsWith(previousPartialJson)) {
1076
- const delta = event.arguments.slice(previousPartialJson.length);
1077
- if (delta.length > 0) {
1078
- stream.push({
1079
- type: "toolcall_delta",
1080
- contentIndex: state.blockIndex,
1081
- delta,
1082
- partial: output
1083
- });
1084
- }
1085
- }
1080
+ const replaced = state.arguments.replace(event.arguments);
1081
+ state.block.arguments = replaced.arguments;
1082
+ if (replaced.delta)
1083
+ stream.push({
1084
+ type: "toolcall_delta",
1085
+ contentIndex: state.blockIndex,
1086
+ delta: replaced.delta,
1087
+ partial: output
1088
+ });
1086
1089
  }
1087
1090
  } else if (event.type === "response.output_item.done") {
1088
1091
  const item = event.item;
1089
1092
  const customItem = item.type === "custom_tool_call" ? item : undefined;
1090
1093
  const customState = customItem ? outputStates.get(event.output_index) : undefined;
1091
- const customInput = customItem?.input ?? (customState?.kind === "custom_tool_call" ? customState.input : "");
1094
+ const customInput = customItem?.input ?? (customState?.kind === "custom_tool_call" ? customState.jsonBuffer.input : "");
1092
1095
  options?.onOutputItemDone?.(customItem ? { ...customItem, input: customInput } : item);
1093
1096
  if (customItem) {
1094
1097
  const state = customState;
1095
1098
  if (state?.kind === "custom_tool_call") {
1096
- const delta = appendCustomInput(state, customInput, true);
1099
+ const delta = closeCustomInput(state, customItem.input);
1097
1100
  if (delta !== undefined)
1098
1101
  stream.push({
1099
1102
  type: "toolcall_delta",
@@ -1199,13 +1202,15 @@ async function processResponsesStream(openaiStream, output, stream, model, optio
1199
1202
  } else if (item.type === "function_call") {
1200
1203
  const state = outputStates.get(event.output_index);
1201
1204
  const namespace = item.namespace;
1202
- const parsed = parseToolCallArguments(item.arguments || (state?.kind === "function_call" ? state.block.partialJson : undefined));
1205
+ const args = state?.kind === "function_call" ? state.arguments : new ToolCallArgumentsStream;
1206
+ if (item.arguments)
1207
+ args.replace(item.arguments);
1208
+ const parsed = args.finish();
1203
1209
  let toolCall;
1204
1210
  if (state?.kind === "function_call") {
1205
1211
  Object.assign(state.block, parsed);
1206
1212
  if (namespace !== undefined)
1207
1213
  state.block.namespace = namespace;
1208
- delete state.block.partialJson;
1209
1214
  toolCall = state.block;
1210
1215
  } else {
1211
1216
  toolCall = {
@@ -3007,16 +3012,18 @@ function buildProviderErrorMessage(error) {
3007
3012
  if (usageLimitMessage)
3008
3013
  return usageLimitMessage;
3009
3014
  if (/^(?:WebSocket (?:error|closed|connect timeout|idle timeout)|WebSocket stream closed before response\.completed|Stream closed before response\.completed)/.test(message)) {
3010
- return `Connection error: ${message}`;
3015
+ return boundedProviderErrorText(`Connection error: ${message}`);
3011
3016
  }
3012
- return message;
3017
+ return boundedProviderErrorText(message);
3018
+ }
3019
+ function boundedProviderErrorText(text) {
3020
+ const maxChars = 4000;
3021
+ if (text.length <= maxChars)
3022
+ return text;
3023
+ const excerpt = `${text.slice(0, maxChars)} `.slice(0, -1);
3024
+ return `${excerpt}... [truncated ${text.length - maxChars} chars]`;
3013
3025
  }
3014
3026
  function createErrorMessage(message, error, aborted) {
3015
- for (const block of message.content) {
3016
- if (typeof block === "object" && block !== null && "partialJson" in block) {
3017
- delete block.partialJson;
3018
- }
3019
- }
3020
3027
  message.stopReason = aborted ? "aborted" : "error";
3021
3028
  message.errorMessage = buildProviderErrorMessage(error);
3022
3029
  return message;
@@ -3074,7 +3081,11 @@ async function parseErrorResponse(response, signal) {
3074
3081
  message = friendlyMessage || codexErrorMessage(code, err.message) || message;
3075
3082
  }
3076
3083
  } catch {}
3077
- return { message, friendlyMessage, ...code ? { code } : {} };
3084
+ return {
3085
+ message: boundedProviderErrorText(message),
3086
+ friendlyMessage,
3087
+ ...code ? { code } : {}
3088
+ };
3078
3089
  }
3079
3090
 
3080
3091
  // packages/openai-responses/src/openai-codex/model-catalog.ts
@@ -3088,157 +3099,6 @@ var UNKNOWN_SUBSCRIPTION_COST = {
3088
3099
  cacheWrite: 0
3089
3100
  };
3090
3101
  var SUPPLEMENTAL_MODELS = [
3091
- {
3092
- id: "gpt-6-astra",
3093
- name: "GPT-6 Astra",
3094
- api: "openai-codex-responses",
3095
- provider: "openai-codex",
3096
- baseUrl: DEFAULT_CODEX_BASE_URL,
3097
- reasoning: true,
3098
- input: ["text", "image"],
3099
- cost: {
3100
- input: 10,
3101
- output: 50,
3102
- cacheRead: 1,
3103
- cacheWrite: 12.5,
3104
- tiers: [
3105
- {
3106
- inputTokensAbove: 272000,
3107
- input: 20,
3108
- output: 75,
3109
- cacheRead: 2,
3110
- cacheWrite: 25
3111
- }
3112
- ]
3113
- },
3114
- contextWindow: 272000,
3115
- maxTokens: 128000,
3116
- thinkingLevelMap: { off: null, minimal: "low", xhigh: "xhigh", max: "max" },
3117
- compat: {
3118
- supportsOpenAIGrammarTools: true,
3119
- supportsMidConvoSystemMessages: true,
3120
- supportsAdditionalTools: true,
3121
- supportsToolSearch: true
3122
- }
3123
- },
3124
- {
3125
- id: "gpt-6.1-terra",
3126
- name: "GPT-6.1 Terra",
3127
- api: "openai-codex-responses",
3128
- provider: "openai-codex",
3129
- baseUrl: DEFAULT_CODEX_BASE_URL,
3130
- reasoning: true,
3131
- input: ["text", "image"],
3132
- cost: {
3133
- input: 1,
3134
- output: 5,
3135
- cacheRead: 0.05,
3136
- cacheWrite: 1.25,
3137
- tiers: [
3138
- {
3139
- inputTokensAbove: 272000,
3140
- input: 2,
3141
- output: 7.5,
3142
- cacheRead: 0.1,
3143
- cacheWrite: 2.5
3144
- }
3145
- ]
3146
- },
3147
- contextWindow: 500000,
3148
- maxTokens: 128000,
3149
- thinkingLevelMap: { off: null, minimal: null, xhigh: "xhigh", max: "max" },
3150
- compat: {
3151
- supportsOpenAIGrammarTools: true,
3152
- supportsMidConvoSystemMessages: true,
3153
- supportsAdditionalTools: true,
3154
- supportsToolSearch: true
3155
- }
3156
- },
3157
- {
3158
- id: "gpt-6.1-sol",
3159
- name: "GPT-6.1 Sol",
3160
- api: "openai-codex-responses",
3161
- provider: "openai-codex",
3162
- baseUrl: DEFAULT_CODEX_BASE_URL,
3163
- reasoning: true,
3164
- input: ["text", "image"],
3165
- cost: {
3166
- input: 2,
3167
- output: 10,
3168
- cacheRead: 0.1,
3169
- cacheWrite: 2.5,
3170
- tiers: [
3171
- {
3172
- inputTokensAbove: 272000,
3173
- input: 4,
3174
- output: 15,
3175
- cacheRead: 0.2,
3176
- cacheWrite: 5
3177
- }
3178
- ]
3179
- },
3180
- contextWindow: 500000,
3181
- maxTokens: 128000,
3182
- thinkingLevelMap: { off: null, minimal: null, xhigh: "xhigh", max: "max" },
3183
- compat: {
3184
- supportsOpenAIGrammarTools: true,
3185
- supportsMidConvoSystemMessages: true,
3186
- supportsAdditionalTools: true,
3187
- supportsToolSearch: true
3188
- }
3189
- },
3190
- ...["Sol", "Luna"].map((tier) => ({
3191
- id: `gpt-6-${tier.toLowerCase()}`,
3192
- name: `GPT-6 ${tier}`,
3193
- api: "openai-codex-responses",
3194
- provider: "openai-codex",
3195
- baseUrl: DEFAULT_CODEX_BASE_URL,
3196
- reasoning: true,
3197
- input: ["text", "image"],
3198
- cost: tier === "Sol" ? {
3199
- input: 2,
3200
- output: 10,
3201
- cacheRead: 0.2,
3202
- cacheWrite: 2.5,
3203
- tiers: [
3204
- {
3205
- inputTokensAbove: 272000,
3206
- input: 4,
3207
- output: 15,
3208
- cacheRead: 0.4,
3209
- cacheWrite: 5
3210
- }
3211
- ]
3212
- } : {
3213
- input: 0.1,
3214
- output: 0.5,
3215
- cacheRead: 0.01,
3216
- cacheWrite: 0.125,
3217
- tiers: [
3218
- {
3219
- inputTokensAbove: 272000,
3220
- input: 0.2,
3221
- output: 0.75,
3222
- cacheRead: 0.02,
3223
- cacheWrite: 0.25
3224
- }
3225
- ]
3226
- },
3227
- contextWindow: 272000,
3228
- maxTokens: 128000,
3229
- thinkingLevelMap: {
3230
- off: null,
3231
- minimal: "low",
3232
- xhigh: "xhigh",
3233
- max: "max"
3234
- },
3235
- compat: {
3236
- supportsOpenAIGrammarTools: true,
3237
- supportsMidConvoSystemMessages: true,
3238
- supportsAdditionalTools: true,
3239
- supportsToolSearch: true
3240
- }
3241
- })),
3242
3102
  {
3243
3103
  id: "gpt-daybreak-blue-latest",
3244
3104
  name: "Daybreak Blue",
@@ -3295,23 +3155,6 @@ function openAICodexProviderModels() {
3295
3155
  ...models,
3296
3156
  ...SUPPLEMENTAL_MODELS.filter(({ id }) => !existing.has(id))
3297
3157
  ].map((model) => {
3298
- if (model.id === "gpt-6.1-sol" || model.id === "gpt-6.1-terra") {
3299
- return {
3300
- ...model,
3301
- contextWindow: 500000,
3302
- thinkingLevelMap: {
3303
- ...model.thinkingLevelMap,
3304
- off: null,
3305
- minimal: null
3306
- }
3307
- };
3308
- }
3309
- if (/^gpt-6-(?:sol|luna)$/.test(model.id)) {
3310
- return {
3311
- ...model,
3312
- thinkingLevelMap: { ...model.thinkingLevelMap, off: null }
3313
- };
3314
- }
3315
3158
  return /^gpt-5\.6-(?:luna|terra|sol)$/i.test(model.id) && model.contextWindow > GPT_56_PRODUCTION_CONTEXT_WINDOW ? { ...model, contextWindow: GPT_56_PRODUCTION_CONTEXT_WINDOW } : model;
3316
3159
  });
3317
3160
  }
@@ -4401,6 +4244,7 @@ function retryAdviceRecoveryBudgetError(error) {
4401
4244
  }
4402
4245
 
4403
4246
  class CodexRecoveryBudget {
4247
+ lastTransportFailure;
4404
4248
  overloadRetryCount = 0;
4405
4249
  adviceStartedAt;
4406
4250
  adviceController;
@@ -4437,7 +4281,11 @@ class CodexRecoveryBudget {
4437
4281
  this.recoveryController = new AbortController;
4438
4282
  this.recoveryTimer = setTimeout(() => this.recoveryController?.abort(), DEFAULT_TRANSPORT_RECOVERY_BUDGET_MS);
4439
4283
  };
4440
- deadlineError = () => this.adviceExpired() ? retryAdviceRecoveryBudgetError(undefined) : new NonRetryableProviderError("Codex could not complete transport recovery within five minutes; the request was stopped before an answer completed. Retry the request.");
4284
+ recordTransportFailure = (error) => {
4285
+ this.lastTransportFailure = error === undefined ? undefined : buildProviderErrorMessage(error);
4286
+ };
4287
+ exhaustedError = (message) => new NonRetryableProviderError(this.lastTransportFailure ? `${message} Last transport failure: ${this.lastTransportFailure}` : message);
4288
+ deadlineError = () => this.adviceExpired() ? retryAdviceRecoveryBudgetError(undefined) : this.exhaustedError("Codex could not complete transport recovery within five minutes; the request was stopped before an answer completed. Retry the request.");
4441
4289
  adviceExpired = () => this.adviceController?.signal.aborted === true || this.adviceStartedAt !== undefined && performance.now() - this.adviceStartedAt >= DEFAULT_RATE_LIMIT_RECOVERY_BUDGET_MS;
4442
4290
  expired = () => this.adviceExpired() || this.recoveryController?.signal.aborted === true || this.recoveryDeadlineAt !== undefined && performance.now() >= this.recoveryDeadlineAt;
4443
4291
  planRetry = (error, retryCount) => {
@@ -4471,7 +4319,8 @@ class CodexRecoveryBudget {
4471
4319
  throw retryAdviceRecoveryBudgetError(error);
4472
4320
  }
4473
4321
  if (!switchingOnExpiry && this.recoveryDeadlineAt !== undefined && delayMs > Math.max(0, this.recoveryDeadlineAt - performance.now())) {
4474
- throw new NonRetryableProviderError("Codex retry advice exceeds the remaining transport recovery window; retry the request later.");
4322
+ const message = "Codex retry advice exceeds the remaining transport recovery window; retry the request later.";
4323
+ throw plan.serverDirected || plan.overload ? new NonRetryableProviderError(message) : this.exhaustedError(message);
4475
4324
  }
4476
4325
  const retrySignal = this.signal();
4477
4326
  try {
@@ -5848,10 +5697,10 @@ function createCodexTransportStream(model, context, options, deps) {
5848
5697
  }, (sent, id) => observe(sent, id, "websocket"));
5849
5698
  if (callerSignal?.aborted)
5850
5699
  throw new Error("Request was aborted");
5851
- if (recovery.expired())
5852
- throw recovery.deadlineError();
5853
5700
  finalizeUsage(output);
5854
5701
  assertSuccessfulCodexOutput(output);
5702
+ if (recovery.expired())
5703
+ throw recovery.deadlineError();
5855
5704
  recordUsage(diagnostics, lane, "websocket", output);
5856
5705
  await runCodexCompletionObserver("usage", () => deps.recordUsage?.(accountId, { ...model, id: body.model }, output.usage));
5857
5706
  stream.push({
@@ -5869,6 +5718,10 @@ function createCodexTransportStream(model, context, options, deps) {
5869
5718
  const unauthorized = isWebSocketUnauthorizedError(error);
5870
5719
  const retryableWebSocketError = !(error instanceof NonRetryableProviderError) && (allowFallback || !(upgradeRequired || messageTooBig || unauthorized)) && (isCodexApiError(error) || !isPermanentWebSocketError(error)) && isRetryableCodexStreamError(error);
5871
5720
  const connectionFailure = !isCodexApiError(error) && isWebSocketConnectionError(error);
5721
+ if (recovery.expired() && !retryableWebSocketError && (error instanceof CodexProtocolError || isCodexApiError(error)))
5722
+ throw error;
5723
+ if (!recovery.expired())
5724
+ recovery.recordTransportFailure(retryableWebSocketError && connectionFailure && !upgradeRequired && !messageTooBig && !unauthorized ? error : undefined);
5872
5725
  if (retryableWebSocketError && connectionFailure)
5873
5726
  recovery.start();
5874
5727
  const retryPlan = recovery.planRetry(error, attempt + 1);
@@ -6000,9 +5853,9 @@ function createCodexTransportStream(model, context, options, deps) {
6000
5853
  finalizeUsage(output);
6001
5854
  if (callerSignal?.aborted)
6002
5855
  throw new Error("Request was aborted");
5856
+ assertSuccessfulCodexOutput(output);
6003
5857
  if (recovery.expired())
6004
5858
  throw recovery.deadlineError();
6005
- assertSuccessfulCodexOutput(output);
6006
5859
  if (completedId && completedId === output.responseId)
6007
5860
  await observe(bodyJson, completedId, "sse");
6008
5861
  recordUsage(diagnostics, lane, "sse", output);
@@ -6031,12 +5884,18 @@ function createCodexTransportStream(model, context, options, deps) {
6031
5884
  } catch (error) {
6032
5885
  if (callerSignal?.aborted)
6033
5886
  throw error;
5887
+ const retryable = !(error instanceof NonRetryableProviderError) && isRetryableCodexStreamError(error);
5888
+ if (!recovery.expired() || isCodexApiError(error) || !retryable)
5889
+ recovery.recordTransportFailure(retryable && !isCodexApiError(error) ? error : undefined);
6034
5890
  if (recovery.expired()) {
5891
+ if (!retryable)
5892
+ throw error;
5893
+ if (toolOutputStarted)
5894
+ throw new NonRetryableProviderError("The response was interrupted while composing tool calls. Unfinished calls were discarded. Retry your request.");
6035
5895
  const deadlineError = recovery.deadlineError();
6036
5896
  recordFailure("sse", deadlineError);
6037
5897
  throw deadlineError;
6038
5898
  }
6039
- const retryable = !(error instanceof NonRetryableProviderError) && isRetryableCodexStreamError(error);
6040
5899
  if (retryable)
6041
5900
  recovery.start();
6042
5901
  const retryPlan = recovery.planRetry(error, attempt + 1);
@@ -6069,7 +5928,7 @@ function createCodexTransportStream(model, context, options, deps) {
6069
5928
  }
6070
5929
  recordFailure("sse", error);
6071
5930
  if (retryable)
6072
- throw new NonRetryableProviderError("Codex stream retry budget was exhausted before a response completed.");
5931
+ throw recovery.exhaustedError("Codex stream retry budget was exhausted before a response completed.");
6073
5932
  throw error;
6074
5933
  } finally {
6075
5934
  sseSignal?.cleanup();
@@ -6,6 +6,7 @@ export declare function codexErrorMessage(code: string | undefined, message: str
6
6
  export declare function codexRetryAfterDeadline(headers: Headers): number | undefined;
7
7
  export declare function isTerminalRateLimitError(errorText: string): boolean;
8
8
  export declare function isRetryableStreamStatus(status: number): boolean;
9
+ export declare function buildProviderErrorMessage(error: unknown): string;
9
10
  export declare function createErrorMessage(message: AssistantMessage, error: unknown, aborted: boolean): AssistantMessage;
10
11
  export declare function parseErrorResponse(response: Response, signal?: AbortSignal): Promise<{
11
12
  message: string;
@@ -3,6 +3,7 @@ import type { OpenAICodexStreamOptions } from "./types.ts";
3
3
  export declare function codexStreamMaxRetries(options: OpenAICodexStreamOptions | undefined): number;
4
4
  export declare function retryAdviceRecoveryBudgetError(error: unknown): NonRetryableProviderError;
5
5
  export declare class CodexRecoveryBudget {
6
+ private lastTransportFailure;
6
7
  private overloadRetryCount;
7
8
  private adviceStartedAt;
8
9
  private adviceController;
@@ -19,6 +20,8 @@ export declare class CodexRecoveryBudget {
19
20
  cleanup: () => void;
20
21
  } | undefined;
21
22
  start: (freshWindow?: boolean) => void;
23
+ recordTransportFailure: (error: unknown) => void;
24
+ exhaustedError: (message: string) => NonRetryableProviderError;
22
25
  deadlineError: () => NonRetryableProviderError;
23
26
  private adviceExpired;
24
27
  expired: () => boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@howaboua/pi-durable-openai-responses",
3
- "version": "0.9.1",
3
+ "version": "0.11.0",
4
4
  "description": "OpenAI and Codex Responses provider with cached WebSockets and explicit Worker support",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -19,6 +19,10 @@
19
19
  ".": {
20
20
  "types": "./dist/index.d.ts",
21
21
  "import": "./dist/index.js"
22
+ },
23
+ "./component": {
24
+ "types": "./dist/activation.d.ts",
25
+ "import": "./dist/activation.js"
22
26
  }
23
27
  },
24
28
  "files": [
@@ -32,13 +36,30 @@
32
36
  "openai": "7.19.0",
33
37
  "proxy-from-env": "2.1.0",
34
38
  "sharp": "0.35.5",
35
- "undici": "8.10.2"
39
+ "undici": "8.10.2",
40
+ "@howaboua/pi-durable-components": "0.11.0"
36
41
  },
37
42
  "peerDependencies": {
38
- "@earendil-works/pi-ai": "1.4.0",
39
- "@modelcontextprotocol/sdk": "1.25.2"
43
+ "@earendil-works/pi-ai": "1.5.0",
44
+ "@modelcontextprotocol/sdk": ">=1.25.2 <2"
40
45
  },
41
46
  "publishConfig": {
42
47
  "access": "public"
48
+ },
49
+ "durable": {
50
+ "schemaVersion": 1,
51
+ "kind": "provider",
52
+ "entry": "./component",
53
+ "runtimes": [
54
+ "node",
55
+ "workerd"
56
+ ],
57
+ "requires": [
58
+ "durable.network.v1"
59
+ ],
60
+ "permissions": [
61
+ "network",
62
+ "models"
63
+ ]
43
64
  }
44
65
  }