@bastani/atomic 0.9.60 → 0.9.61-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/dist/builtin/intercom/index.bundle.mjs +3 -3
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/CHANGELOG.md +12 -0
  6. package/dist/builtin/subagents/package.json +1 -1
  7. package/dist/builtin/web-access/package.json +1 -1
  8. package/dist/builtin/workflows/CHANGELOG.md +14 -0
  9. package/dist/builtin/workflows/README.md +9 -7
  10. package/dist/builtin/workflows/builtin/{chunk-h6bt0r0g.js → chunk-a2j0x1a6.js} +1 -1
  11. package/dist/builtin/workflows/builtin/{chunk-g3b2zf8r.js → chunk-vzbec50q.js} +1 -1
  12. package/dist/builtin/workflows/builtin/goal.js +1 -1
  13. package/dist/builtin/workflows/builtin/index.js +2 -2
  14. package/dist/builtin/workflows/builtin/ralph.js +1 -1
  15. package/dist/builtin/workflows/package.json +1 -1
  16. package/dist/builtin/workflows/src/extension/index.bundle.mjs +922 -473
  17. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +1006 -484
  18. package/dist/builtin/workflows/src/index.js +892 -448
  19. package/dist/builtin/workflows/src/local-worker-entry.mjs +1006 -484
  20. package/dist/builtin/workflows/src/shared/workflow-infrastructure-error.d.ts +6 -0
  21. package/dist/core/agent-session-retry.d.ts.map +1 -1
  22. package/dist/core/agent-session-retry.js +12 -3
  23. package/dist/core/agent-session-retry.js.map +1 -1
  24. package/dist/core/model-fallback-failures.d.ts +14 -4
  25. package/dist/core/model-fallback-failures.d.ts.map +1 -1
  26. package/dist/core/model-fallback-failures.js +43 -15
  27. package/dist/core/model-fallback-failures.js.map +1 -1
  28. package/dist/core/settings-defaults.d.ts +1 -0
  29. package/dist/core/settings-defaults.d.ts.map +1 -1
  30. package/dist/core/settings-defaults.js +1 -0
  31. package/dist/core/settings-defaults.js.map +1 -1
  32. package/dist/core/settings-manager-basic-accessors.d.ts +1 -0
  33. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  34. package/dist/core/settings-manager-basic-accessors.js +2 -0
  35. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  36. package/dist/core/settings-schema.d.ts +2 -0
  37. package/dist/core/settings-schema.d.ts.map +1 -1
  38. package/dist/core/settings-schema.js +4 -0
  39. package/dist/core/settings-schema.js.map +1 -1
  40. package/dist/core/slash-commands.js +2 -2
  41. package/dist/core/slash-commands.js.map +1 -1
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js.map +1 -1
  45. package/dist/modes/interactive/interactive-startup-chat-container.d.ts +2 -0
  46. package/dist/modes/interactive/interactive-startup-chat-container.d.ts.map +1 -1
  47. package/dist/modes/interactive/interactive-startup-chat-container.js +6 -0
  48. package/dist/modes/interactive/interactive-startup-chat-container.js.map +1 -1
  49. package/dist/modes/interactive-engine/remote-renderer.d.ts +27 -5
  50. package/dist/modes/interactive-engine/remote-renderer.d.ts.map +1 -1
  51. package/dist/modes/interactive-engine/remote-renderer.js +76 -16
  52. package/dist/modes/interactive-engine/remote-renderer.js.map +1 -1
  53. package/docs/intercom/reference.md +1 -1
  54. package/docs/models/evals.md +30 -2
  55. package/docs/settings.md +3 -0
  56. package/docs/subagents/reference.md +3 -1
  57. package/docs/workflows/api-reference.md +9 -6
  58. package/docs/workflows/builtins.md +1 -1
  59. package/docs/workflows/operations.md +6 -4
  60. package/npm-shrinkwrap.json +32 -32
  61. package/package.json +3 -3
  62. package/schemas/settings.schema.json +5 -0
@@ -21,3 +21,9 @@ export declare function failedOnInfrastructureFault(result: {
21
21
  readonly failure?: unknown;
22
22
  readonly stages?: unknown;
23
23
  }): boolean;
24
+ /** The fault a result {@link failedOnInfrastructureFault} failed on: its error, or the error of its first faulted stage. */
25
+ export declare function infrastructureFaultMessage(result: {
26
+ readonly error?: unknown;
27
+ readonly failure?: unknown;
28
+ readonly stages?: unknown;
29
+ }): string;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-retry.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAO,gBAAgB,EAAS,MAAM,uBAAuB,CAAC;AAI1E,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AA+C9F,4EAA4E;AAC5E,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAS3F;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAexF;AAED;;;;;;;;;;;;;GAaG;AAEH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAsBzF;AAmCD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAsBvF;AAUD,2EAA2E;AAC3E,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQjE;AAiCD,2EAA2E;AAC3E,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAajE;AAED,wFAAwF;AACxF,wBAAsB,yBAAyB,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,CAgBpF;AAED,wDAAwD;AACxD,wBAAsB,yBAAyB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAyG/G;AAED,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CA+F3G;AAaD,w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CAgBpF;AAED,wDAAwD;AACxD,wBAAsB,yBAAyB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAyG/G;AAED,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CA+F3G;AAaD,wBAAgB,UAAU,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAInD;AAED;;;GAGG;AAEH,wBAAsB,YAAY,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAOpE;AAED,kDAAkD;AAElD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAE9E;AAMD;;;;;;;GAOG;AAEH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;CAapC,CAAC"}
@@ -3,7 +3,7 @@ import { sleep } from "../utils/sleep.js";
3
3
  import { isCodexTokenInvalidationError } from "./codex-errors.js";
4
4
  import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
5
5
  import { fallbackKey, resolveFallbackModel as resolveConfiguredFallbackModel } from "./fallback-models.js";
6
- import { isRetryableModelFailure, isRetryableSameModelFailure, isSafetyRefusalFailure, normalizeModelFailureSignal, } from "./model-fallback-failures.js";
6
+ import { isContentFilterRefusal, isRetryableModelFailure, isRetryableSameModelFailure, isSafetyRefusalFailure, normalizeModelFailureSignal, } from "./model-fallback-failures.js";
7
7
  import { nextRetryDecision } from "./retry-policy.js";
8
8
  import { settingsWriteOwner } from "./settings-write-ownership.js";
9
9
  function modelLabel(model) {
@@ -35,6 +35,10 @@ function containsCodexTokenInvalidation(provider, value, seen = new Set()) {
35
35
  function resolveFallbackModel(value) {
36
36
  return resolveConfiguredFallbackModel(value, this._modelRuntime, this.model?.provider ?? this.settingsManager.getDefaultProvider());
37
37
  }
38
+ /** `retry.fallbackOnContentFilter`: a content-filter refusal spends the next fallback candidate, not a retry. */
39
+ function fallsBackOnContentFilter() {
40
+ return this.settingsManager.getRetrySettings().fallbackOnContentFilter !== false;
41
+ }
38
42
  /** Whether an assistant error may advance the configured fallback chain. */
39
43
  export function _isFallbackableError(message) {
40
44
  if (message.stopReason !== "error")
@@ -48,6 +52,8 @@ export function _isFallbackableError(message) {
48
52
  const signal = normalizeModelFailureSignal(message);
49
53
  if (signal.kind === "cancelled" || signal.kind === "task_failure")
50
54
  return false;
55
+ if (signal.kind === "content_filter")
56
+ return fallsBackOnContentFilter.call(this);
51
57
  return isRetryableModelFailure(message);
52
58
  }
53
59
  /**
@@ -68,9 +74,12 @@ export function _isRetryableError(message) {
68
74
  const provider = message.provider || this.model?.provider;
69
75
  if (provider && containsCodexTokenInvalidation(provider, message))
70
76
  return false;
71
- // Safety/refusal errors remain bounded same-model retries, but do not spend
72
- // another provider candidate. The refusal grammar lives in the shared
77
+ // The same request gets the same content-filter refusal, so with `retry.fallbackOnContentFilter` it goes
78
+ // straight to the next fallback candidate. Otherwise safety/refusal errors remain bounded same-model
79
+ // retries that do not spend another provider candidate. The refusal grammar lives in the shared
73
80
  // classifier so this decision cannot drift from workflow fallback handling.
81
+ if (isContentFilterRefusal(message) && fallsBackOnContentFilter.call(this))
82
+ return false;
74
83
  if (isSafetyRefusalFailure(message))
75
84
  return true;
76
85
  return isRetryableSameModelFailure(message);
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-retry.js","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE9F,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C,OAAO,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,oBAAoB,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IAChC,IAAI,CAAC,aAAa,EAAE,CAAC;AACtB,CAAC;AAED;;;GAGG;AAEH,MAAM,CAAC,KAAK,UAAU,YAAY;IACjC,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;QACzB,OAAO;IACR,CAAC;IAED,MAAM,IAAI,CAAC,aAAa,CAAC;IACzB,MAAM,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;AAChC,CAAC;AAED,kDAAkD;AAElD,MAAM,UAAU,mBAAmB,CAAqB,OAAgB;IACvE,kBAAkB,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;AACnF,CAAC;AAED,4EAA4E;AAC5E,iBAAiB;AACjB,4EAA4E;AAE5E;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACvC,iBAAiB;IACjB,oBAAoB;IACpB,kBAAkB;IAClB,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,wBAAwB;IACxB,wBAAwB;IACxB,yBAAyB;IACzB,UAAU;IACV,YAAY;IACZ,mBAAmB;CACnB,CAAC","sourcesContent":["import type { Api, AssistantMessage, Model } from \"@bastani/pi-ai/compat\";\nimport { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { isCodexTokenInvalidationError } from \"./codex-errors.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { fallbackKey, resolveFallbackModel as resolveConfiguredFallbackModel } from \"./fallback-models.ts\";\nimport {\n\tisRetryableModelFailure,\n\tisRetryableSameModelFailure,\n\tisSafetyRefusalFailure,\n\tnormalizeModelFailureSignal,\n} from \"./model-fallback-failures.ts\";\nimport { nextRetryDecision } from \"./retry-policy.ts\";\nimport { settingsWriteOwner } from \"./settings-write-ownership.ts\";\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction containsCodexTokenInvalidation(provider: string, value: unknown, seen = new Set<unknown>()): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value === \"string\") return isCodexTokenInvalidationError(provider, value);\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tfor (const field of [record.errorMessage, record.message, record.statusText]) {\n\t\tif (typeof field === \"string\" && isCodexTokenInvalidationError(provider, field)) return true;\n\t}\n\tfor (const nested of [\n\t\trecord.error,\n\t\trecord.cause,\n\t\t...(Array.isArray(record.diagnostics) ? record.diagnostics : []),\n\t]) {\n\t\tif (containsCodexTokenInvalidation(provider, nested, seen)) return true;\n\t}\n\treturn false;\n}\n\nfunction resolveFallbackModel(\n\tthis: AgentSession,\n\tvalue: string,\n): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\treturn resolveConfiguredFallbackModel(\n\t\tvalue,\n\t\tthis._modelRuntime,\n\t\tthis.model?.provider ?? this.settingsManager.getDefaultProvider(),\n\t);\n}\n\n/** Whether an assistant error may advance the configured fallback chain. */\nexport function _isFallbackableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return true;\n\tconst signal = normalizeModelFailureSignal(message);\n\tif (signal.kind === \"cancelled\" || signal.kind === \"task_failure\") return false;\n\treturn isRetryableModelFailure(message);\n}\n\n/**\n * Whether the current model should be requested again.\n *\n * Fallback eligibility is broader than same-model retry eligibility. Auth and\n * request-incompatible failures should spend a fallback candidate, but cannot\n * be repaired by sending the same request again. Codex token invalidation is\n * also terminal for the current model while remaining fallbackable.\n */\nexport function _isRetryableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\n\t// Context overflow is handled by compaction, not retry.\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return false;\n\n\t// Safety/refusal errors remain bounded same-model retries, but do not spend\n\t// another provider candidate. The refusal grammar lives in the shared\n\t// classifier so this decision cannot drift from workflow fallback handling.\n\tif (isSafetyRefusalFailure(message)) return true;\n\treturn isRetryableSameModelFailure(message);\n}\n\n/**\n * Detect a degenerate empty completion: the provider ended the stream with no\n * usable content and zero output tokens. Seen with github-copilot Gemini models\n * that emit finish_reason \"stop\" (or a tool-use stop) with an empty content array\n * and 0 output tokens, leaving the turn dead instead of producing the next step.\n *\n * These are treated as retryable so the harness re-issues the request rather than\n * silently stopping mid-task. Guarded tightly (no text, no tool call, no thinking,\n * and output === 0) so legitimate non-empty turns are never matched.\n *\n * Intentionally provider-agnostic (not gated to Copilot Gemini): a degenerate\n * empty turn is a transient failure for any provider. It is bounded by\n * `maxRetries` and falls through to normal handling on exhaustion.\n */\n\nexport function _isEmptyCompletion(this: AgentSession, message: AssistantMessage): boolean {\n\t// Only \"completed\" stop reasons can be deceptively empty. Real errors are handled\n\t// by _isRetryableError; aborted/length turns are intentional outcomes.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"toolUse\") return false;\n\n\tconst content = message.content;\n\tif (Array.isArray(content)) {\n\t\tconst hasContent = content.some((part) => {\n\t\t\tif (part.type === \"text\") return part.text.trim().length > 0;\n\t\t\tif (part.type === \"toolCall\") return true;\n\t\t\tif (part.type === \"thinking\") return part.redacted === true || part.thinking.trim().length > 0;\n\t\t\treturn true; // unknown part types count as content\n\t\t});\n\t\tif (hasContent) return false;\n\t}\n\n\t// A turn that produced output tokens but no surfaced content is not \"empty\"\n\t// (e.g. reasoning-only responses); leave those alone. Note: a provider that\n\t// fails to report `usage` (output defaults to 0) would make every\n\t// content-less turn match here; the dual requirement (empty content AND zero\n\t// output) keeps that false-positive risk low in practice.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Detect a canned provider-side safety refusal that arrives as a *successful*\n * completion instead of an error. Seen with github-copilot GPT models under\n * heavy contexts: the endpoint intercepts the request and returns exactly\n * \"I'm sorry, but I cannot assist with that request.\" with zero usage and a\n * spurious stopReason of \"length\" (or \"stop\"), which the agent would otherwise\n * accept as the final answer and dead-end the turn (issue #1608).\n *\n * A text heuristic is unavoidable here: the OpenAI Responses API does signal\n * these interceptions structurally (`refusal` content parts plus\n * `incomplete_details.reason: \"content_filter\"`), but pi-ai's normalization\n * folds refusal parts into plain text blocks and collapses the `incomplete`\n * status to stopReason \"length\", discarding the reason — so no structured\n * refusal marker survives on the AssistantMessage. Providers whose safety\n * signals DO survive as structured errors (Anthropic refusal stops, OpenAI\n * `finish_reason: content_filter`) are matched in _isRetryableError instead.\n *\n * Guarded tightly so legitimate turns are never matched:\n * - only non-error completion stops (\"stop\" | \"length\" | \"toolUse\");\n * - content must be a single short canned refusal text — any tool call,\n * thinking block, or additional prose disqualifies the message;\n * - usage.output must be 0: a genuine model-authored refusal bills output\n * tokens, while the intercepted canned refusal reports zero usage.\n *\n * Treated as retryable so the harness re-requests the model call rather than\n * accepting the refusal; bounded by `maxRetries` like every other retry path.\n */\n\nconst CANNED_SAFETY_REFUSAL_PATTERN =\n\t/^(?:i['’]?m sorry[,.]?\\s+(?:but\\s+)?|sorry[,.]?\\s+(?:but\\s+)?)?i\\s+(?:cannot|can['’]?t|can\\s+not|am\\s+unable\\s+to|am\\s+not\\s+able\\s+to)\\s+(?:assist|help|comply|continue)(?:\\s+with)?(?:\\s+(?:that|this))?(?:\\s+(?:request|task))?\\.?$/i;\n\nconst CANNED_SAFETY_REFUSAL_MAX_LENGTH = 120;\n\nexport function _isSafetyRefusal(this: AgentSession, message: AssistantMessage): boolean {\n\t// Real errors are handled by _isRetryableError; aborts are user-initiated.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"length\" && message.stopReason !== \"toolUse\") {\n\t\treturn false;\n\t}\n\n\tconst content = message.content;\n\tif (!Array.isArray(content) || content.length === 0) return false;\n\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (part.type === \"toolCall\") return false;\n\t\tif (part.type === \"thinking\" && (part.redacted === true || part.thinking.trim().length > 0)) return false;\n\t\tif (part.type === \"text\") text += part.text;\n\t}\n\ttext = text.trim();\n\tif (text.length === 0 || text.length > CANNED_SAFETY_REFUSAL_MAX_LENGTH) return false;\n\tif (!CANNED_SAFETY_REFUSAL_PATTERN.test(text)) return false;\n\n\t// Zero billed output distinguishes a provider interception from legitimate\n\t// model-authored refusal prose, which is never auto-retried.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\nasync function applyFallbackThinkingLevel(this: AgentSession, level: ThinkingLevel): Promise<boolean> {\n\tconst previousLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tif (previousLevel === level) return false;\n\tawait this.sessionManager.appendThinkingLevelChange(level);\n\tthis.agent.state.thinkingLevel = level;\n\treturn true;\n}\n\n/** Capture the user-selected model before the first fallback in a turn. */\nexport function _beginFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackOriginModel !== undefined || currentModel === undefined) return;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tthis._fallbackOriginGeneration = this._fallbackScopeGeneration;\n\tthis._fallbackOriginModel = currentModel;\n\tthis._fallbackOriginThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis._fallbackRestoreError = undefined;\n}\n\nfunction clearFallbackModelScopeState(this: AgentSession): void {\n\tthis._fallbackOriginGeneration = undefined;\n\tthis._fallbackOriginModel = undefined;\n\tthis._fallbackOriginThinkingLevel = undefined;\n\tthis._fallbackRestoreError = undefined;\n\tthis._fallbackAttemptedKeys.clear();\n\tthis._fallbackBlockedModels.length = 0;\n}\n\nfunction finishFallbackModelScope(\n\tthis: AgentSession,\n\toptions: {\n\t\treadonly success: boolean;\n\t\treadonly from?: string;\n\t\treadonly to?: string;\n\t\treadonly finalError?: string;\n\t},\n): boolean {\n\tif (this._fallbackOriginModel === undefined || this._fallbackOriginGeneration === undefined) return false;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n\tthis._emit({\n\t\ttype: \"model_fallback_end\",\n\t\tsuccess: options.success,\n\t\t...(options.from === undefined ? {} : { from: options.from }),\n\t\t...(options.to === undefined ? {} : { to: options.to }),\n\t\t...(options.finalError === undefined ? {} : { finalError: options.finalError }),\n\t});\n\treturn true;\n}\n\n/** Finish an active fallback lifecycle before an explicit model choice. */\nexport function _clearFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tconst finalError = this._fallbackRestoreError;\n\tif (this._fallbackOriginModel !== undefined && this._fallbackOriginGeneration !== undefined) {\n\t\tfinishFallbackModelScope.call(this, {\n\t\t\tsuccess: finalError === undefined,\n\t\t\tfrom: modelLabel(currentModel),\n\t\t\t...(finalError === undefined ? {} : { finalError }),\n\t\t});\n\t\treturn;\n\t}\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n}\n\n/** Finish an active fallback lifecycle without changing the selected fallback model. */\nexport async function _settleFallbackModelScope(this: AgentSession): Promise<boolean> {\n\tconst originModel = this._fallbackOriginModel;\n\tconst originGeneration = this._fallbackOriginGeneration;\n\tconst finalError = this._fallbackRestoreError;\n\tif (originModel === undefined || originGeneration === undefined) {\n\t\tclearFallbackModelScopeState.call(this);\n\t\treturn false;\n\t}\n\tif (this._fallbackOriginGeneration !== originGeneration || this._fallbackOriginModel !== originModel) return false;\n\n\tconst currentModel = this.agent.state.model ?? this.model;\n\treturn finishFallbackModelScope.call(this, {\n\t\tsuccess: finalError === undefined,\n\t\tfrom: modelLabel(currentModel),\n\t\t...(finalError === undefined ? {} : { finalError }),\n\t});\n}\n\n/** Handle retryable errors with exponential backoff. */\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackModels.length === 0 || currentModel === undefined) return false;\n\n\t// A failure the chain may spend a candidate on, but that requesting the same\n\t// model again cannot repair — a rejected credential, an unavailable model, a\n\t// request this model cannot serve — condemns that model for the rest of the\n\t// turn. Reasoning level does not change any of those answers, so every\n\t// reasoning variant of it is blocked too. Transient rate-limit and transport\n\t// failures stay same-model retryable and keep their reasoning variants.\n\tif (isRetryableModelFailure(message) && !isRetryableSameModelFailure(message)) {\n\t\tif (!this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, currentModel))) {\n\t\t\tthis._fallbackBlockedModels.push(currentModel);\n\t\t}\n\t}\n\n\tconst currentThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tconst fromModel = currentModel;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst nextModel = candidate.model;\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ??\n\t\t\t\tthis.settingsManager.getDefaultThinkingLevel() ??\n\t\t\t\tcurrentThinkingLevel ??\n\t\t\t\tDEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tif (this._isFallbackModelAllowed && !this._isFallbackModelAllowed(nextModel, nextLevel)) continue;\n\t\tconst key = fallbackKey(nextModel, nextLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tif (modelsAreEqual(nextModel, fromModel) && nextLevel === currentThinkingLevel) continue;\n\t\t// Skipped before any lifecycle starts: a blocked variant emits no fallback\n\t\t// event and opens no scope.\n\t\tif (this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, nextModel))) continue;\n\n\t\t// Do not create a fallback lifecycle until a candidate can actually be\n\t\t// selected. An exhausted or unresolvable chain has no start to close.\n\n\t\t// Keep the failed attempt in raw history while durably omitting it from model projection.\n\t\tawait this._omitTrailingAssistantAttempt();\n\t\tawait this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\t\t_beginFallbackModelScope.call(this);\n\t\tthis.agent.state.model = nextModel;\n\t\tconst thinkingChanged = await applyFallbackThinkingLevel.call(this, nextLevel);\n\t\tthis._fallbackAttemptedKeys.add(fallbackKey(currentModel, currentThinkingLevel));\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: true,\n\t\t\t\tattempt: Math.max(0, this._retryAttempt - 1),\n\t\t\t});\n\t\t}\n\t\tthis._fallbackAttemptedKeys.add(key);\n\t\tthis._emit({\n\t\t\ttype: \"model_fallback_start\",\n\t\t\tfrom: modelLabel(fromModel),\n\t\t\tto: `${nextModel.provider}/${nextModel.id}`,\n\t\t\treason: message.errorMessage || \"Retryable model error\",\n\t\t\tattempt: this._fallbackAttemptedKeys.size - 1,\n\t\t});\n\t\tif (thinkingChanged) {\n\t\t\tthis._emit({ type: \"thinking_level_changed\", level: nextLevel });\n\t\t\tvoid this._extensionRunner?.emit({\n\t\t\t\ttype: \"thinking_level_select\",\n\t\t\t\tlevel: nextLevel,\n\t\t\t\tpreviousLevel: currentThinkingLevel,\n\t\t\t});\n\t\t}\n\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tthis._emitModelChanged(nextModel, fromModel, \"fallback\");\n\t\tawait this._emitModelSelect(nextModel, fromModel, \"fallback\");\n\t\tthis._retryAttempt = 0;\n\n\t\tconst fallbackGeneration = this._fallbackOriginGeneration;\n\t\tsetTimeout(() => {\n\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\tvoid this.agent.continue().catch(async (error: unknown) => {\n\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\tthis._fallbackRestoreError = finalError;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\t\t\tfinishFallbackModelScope.call(this, {\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tfrom: modelLabel(this.agent.state.model ?? this.model),\n\t\t\t\t\t\t\t\tfinalError,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\tthis._resolveRetry();\n\t\t\t});\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tif (this._fallbackOriginModel !== undefined) {\n\t\tthis._fallbackRestoreError = message.errorMessage || \"Model fallback exhausted\";\n\t}\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tif (this._agentRunAbortRequested) return false;\n\tconst settings = this.settingsManager.getRetrySettings();\n\tconst retryableError = this._isRetryableError?.(message) ?? true;\n\tconst fallbackableError = this._isFallbackableError?.(message) ?? retryableError;\n\tconst emptyCompletion = this._isEmptyCompletion?.(message) ?? false;\n\tconst safetyRefusal = this._isSafetyRefusal?.(message) ?? false;\n\tconst canRetrySameModel = retryableError || emptyCompletion || safetyRefusal;\n\t// Empty completions have historically been allowed to spend a fallback after\n\t// same-model retries. Provider safety refusals stay on the same model.\n\tconst canAdvanceToFallback = fallbackableError || emptyCompletion;\n\tif (!settings.enabled || !canRetrySameModel) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) return true;\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: false,\n\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\tfinalError: message.errorMessage,\n\t\t\t});\n\t\t}\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\n\t// Retry promise is created synchronously in _handleAgentEvent for agent_end.\n\t// Keep a defensive fallback here in case a future refactor bypasses that path.\n\tif (!this._retryPromise) {\n\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\tthis._retryResolve = resolve;\n\t\t});\n\t}\n\n\t// One shared policy decides the bounded same-model budget and its backoff, so\n\t// main chat and workflow stages cannot drift apart on the same settings. The\n\t// counter still advances on the exhausting attempt, so `_trySwitchToFallbackModel`\n\t// closes the retry lifecycle before the fallback lifecycle opens.\n\tconst decision = nextRetryDecision(settings, this._retryAttempt, canRetrySameModel, message);\n\tthis._retryAttempt += 1;\n\tif (decision === undefined) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) {\n\t\t\treturn true;\n\t\t}\n\t\t// Max retries exceeded, emit final failure and reset\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt: this._retryAttempt - 1,\n\t\t\tfinalError: message.errorMessage,\n\t\t});\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\treturn false;\n\t}\n\n\tconst delayMs = decision.delayMs;\n\n\tthis._retryAbortController = new AbortController();\n\tthis._emit({\n\t\ttype: \"auto_retry_start\",\n\t\tattempt: this._retryAttempt,\n\t\tmaxAttempts: settings.maxRetries,\n\t\tdelayMs,\n\t\terrorMessage: message.errorMessage || \"Unknown error\",\n\t});\n\n\t// Keep the failed attempt in raw history while durably omitting it from model projection.\n\tawait this._omitTrailingAssistantAttempt();\n\n\t// Wait with exponential backoff (abortable)\n\tif (this._agentRunAbortRequested) this._retryAbortController.abort();\n\ttry {\n\t\tawait sleep(delayMs, this._retryAbortController.signal);\n\t} catch {\n\t\t// Aborted during sleep - emit end event so UI can clean up\n\t\tfinishCancelledRetry.call(this);\n\t\tthis._retryAbortController = undefined;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\tthis._retryAbortController = undefined;\n\n\t// Retry via continue() - use setTimeout to break out of event handler chain\n\tsetTimeout(() => {\n\t\tif (this._agentRunAbortRequested) {\n\t\t\tfinishCancelledRetry.call(this);\n\t\t\treturn;\n\t\t}\n\t\tthis.agent.continue().catch(() => {\n\t\t\t// Retry failed - will be caught by next agent_end\n\t\t});\n\t}, 0);\n\n\treturn true;\n}\n\n/**\n * Cancel in-progress retry.\n */\n\nfunction finishCancelledRetry(this: AgentSession): void {\n\tif (this._retryAttempt === 0) return;\n\tconst attempt = this._retryAttempt;\n\tthis._retryAttempt = 0;\n\tthis._emit({ type: \"auto_retry_end\", success: false, attempt, finalError: \"Retry cancelled\" });\n}\n\nexport function abortRetry(this: AgentSession): void {\n\tthis._retryAbortController?.abort();\n\tfinishCancelledRetry.call(this);\n\tthis._resolveRetry();\n}\n\n/**\n * Wait for any in-progress retry to complete.\n * Returns immediately if no retry is in progress.\n */\n\nexport async function waitForRetry(this: AgentSession): Promise<void> {\n\tif (!this._retryPromise) {\n\t\treturn;\n\t}\n\n\tawait this._retryPromise;\n\tawait this.agent.waitForIdle();\n}\n\n/** Whether auto-retry is currently in progress */\n\nexport function setAutoRetryEnabled(this: AgentSession, enabled: boolean): void {\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setRetryEnabled(enabled));\n}\n\n// =========================================================================\n// Bash Execution\n// =========================================================================\n\n/**\n * Execute a bash command.\n * Adds result to agent context and session.\n * @param command The bash command to execute\n * @param onChunk Optional streaming callback for output\n * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)\n * @param options.operations Custom BashOperations for remote execution\n */\n\nexport const agentSessionRetryMethods = {\n\t_isRetryableError,\n\t_isFallbackableError,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\n\t_beginFallbackModelScope,\n\t_clearFallbackModelScope,\n\t_settleFallbackModelScope,\n\tabortRetry,\n\twaitForRetry,\n\tsetAutoRetryEnabled,\n};\n"]}
1
+ {"version":3,"file":"agent-session-retry.js","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE9F,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C,OAAO,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,oBAAoB,IAAI,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAC3G,OAAO,EACN,sBAAsB,EACtB,uBAAuB,EACvB,2BAA2B,EAC3B,sBAAsB,EACtB,2BAA2B,GAC3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE,SAAS,UAAU,CAAC,KAA6B;IAChD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC;AAClE,CAAC;AAED,SAAS,8BAA8B,CAAC,QAAgB,EAAE,KAAc,EAAE,IAAI,GAAG,IAAI,GAAG,EAAW;IAClG,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3E,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,6BAA6B,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;I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I,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,CAAC;AACnF,CAAC;AAED,4EAA4E;AAC5E,iBAAiB;AACjB,4EAA4E;AAE5E;;;;;;;GAOG;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACvC,iBAAiB;IACjB,oBAAoB;IACpB,kBAAkB;IAClB,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,wBAAwB;IACxB,wBAAwB;IACxB,yBAAyB;IACzB,UAAU;IACV,YAAY;IACZ,mBAAmB;CACnB,CAAC","sourcesContent":["import type { Api, AssistantMessage, Model } from \"@bastani/pi-ai/compat\";\nimport { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { isCodexTokenInvalidationError } from \"./codex-errors.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { fallbackKey, resolveFallbackModel as resolveConfiguredFallbackModel } from \"./fallback-models.ts\";\nimport {\n\tisContentFilterRefusal,\n\tisRetryableModelFailure,\n\tisRetryableSameModelFailure,\n\tisSafetyRefusalFailure,\n\tnormalizeModelFailureSignal,\n} from \"./model-fallback-failures.ts\";\nimport { nextRetryDecision } from \"./retry-policy.ts\";\nimport { settingsWriteOwner } from \"./settings-write-ownership.ts\";\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction containsCodexTokenInvalidation(provider: string, value: unknown, seen = new Set<unknown>()): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value === \"string\") return isCodexTokenInvalidationError(provider, value);\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tfor (const field of [record.errorMessage, record.message, record.statusText]) {\n\t\tif (typeof field === \"string\" && isCodexTokenInvalidationError(provider, field)) return true;\n\t}\n\tfor (const nested of [\n\t\trecord.error,\n\t\trecord.cause,\n\t\t...(Array.isArray(record.diagnostics) ? record.diagnostics : []),\n\t]) {\n\t\tif (containsCodexTokenInvalidation(provider, nested, seen)) return true;\n\t}\n\treturn false;\n}\n\nfunction resolveFallbackModel(\n\tthis: AgentSession,\n\tvalue: string,\n): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\treturn resolveConfiguredFallbackModel(\n\t\tvalue,\n\t\tthis._modelRuntime,\n\t\tthis.model?.provider ?? this.settingsManager.getDefaultProvider(),\n\t);\n}\n\n/** `retry.fallbackOnContentFilter`: a content-filter refusal spends the next fallback candidate, not a retry. */\nfunction fallsBackOnContentFilter(this: AgentSession): boolean {\n\treturn this.settingsManager.getRetrySettings().fallbackOnContentFilter !== false;\n}\n\n/** Whether an assistant error may advance the configured fallback chain. */\nexport function _isFallbackableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return true;\n\tconst signal = normalizeModelFailureSignal(message);\n\tif (signal.kind === \"cancelled\" || signal.kind === \"task_failure\") return false;\n\tif (signal.kind === \"content_filter\") return fallsBackOnContentFilter.call(this);\n\treturn isRetryableModelFailure(message);\n}\n\n/**\n * Whether the current model should be requested again.\n *\n * Fallback eligibility is broader than same-model retry eligibility. Auth and\n * request-incompatible failures should spend a fallback candidate, but cannot\n * be repaired by sending the same request again. Codex token invalidation is\n * also terminal for the current model while remaining fallbackable.\n */\nexport function _isRetryableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\n\t// Context overflow is handled by compaction, not retry.\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return false;\n\n\t// The same request gets the same content-filter refusal, so with `retry.fallbackOnContentFilter` it goes\n\t// straight to the next fallback candidate. Otherwise safety/refusal errors remain bounded same-model\n\t// retries that do not spend another provider candidate. The refusal grammar lives in the shared\n\t// classifier so this decision cannot drift from workflow fallback handling.\n\tif (isContentFilterRefusal(message) && fallsBackOnContentFilter.call(this)) return false;\n\tif (isSafetyRefusalFailure(message)) return true;\n\treturn isRetryableSameModelFailure(message);\n}\n\n/**\n * Detect a degenerate empty completion: the provider ended the stream with no\n * usable content and zero output tokens. Seen with github-copilot Gemini models\n * that emit finish_reason \"stop\" (or a tool-use stop) with an empty content array\n * and 0 output tokens, leaving the turn dead instead of producing the next step.\n *\n * These are treated as retryable so the harness re-issues the request rather than\n * silently stopping mid-task. Guarded tightly (no text, no tool call, no thinking,\n * and output === 0) so legitimate non-empty turns are never matched.\n *\n * Intentionally provider-agnostic (not gated to Copilot Gemini): a degenerate\n * empty turn is a transient failure for any provider. It is bounded by\n * `maxRetries` and falls through to normal handling on exhaustion.\n */\n\nexport function _isEmptyCompletion(this: AgentSession, message: AssistantMessage): boolean {\n\t// Only \"completed\" stop reasons can be deceptively empty. Real errors are handled\n\t// by _isRetryableError; aborted/length turns are intentional outcomes.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"toolUse\") return false;\n\n\tconst content = message.content;\n\tif (Array.isArray(content)) {\n\t\tconst hasContent = content.some((part) => {\n\t\t\tif (part.type === \"text\") return part.text.trim().length > 0;\n\t\t\tif (part.type === \"toolCall\") return true;\n\t\t\tif (part.type === \"thinking\") return part.redacted === true || part.thinking.trim().length > 0;\n\t\t\treturn true; // unknown part types count as content\n\t\t});\n\t\tif (hasContent) return false;\n\t}\n\n\t// A turn that produced output tokens but no surfaced content is not \"empty\"\n\t// (e.g. reasoning-only responses); leave those alone. Note: a provider that\n\t// fails to report `usage` (output defaults to 0) would make every\n\t// content-less turn match here; the dual requirement (empty content AND zero\n\t// output) keeps that false-positive risk low in practice.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Detect a canned provider-side safety refusal that arrives as a *successful*\n * completion instead of an error. Seen with github-copilot GPT models under\n * heavy contexts: the endpoint intercepts the request and returns exactly\n * \"I'm sorry, but I cannot assist with that request.\" with zero usage and a\n * spurious stopReason of \"length\" (or \"stop\"), which the agent would otherwise\n * accept as the final answer and dead-end the turn (issue #1608).\n *\n * A text heuristic is unavoidable here: the OpenAI Responses API does signal\n * these interceptions structurally (`refusal` content parts plus\n * `incomplete_details.reason: \"content_filter\"`), but pi-ai's normalization\n * folds refusal parts into plain text blocks and collapses the `incomplete`\n * status to stopReason \"length\", discarding the reason — so no structured\n * refusal marker survives on the AssistantMessage. Providers whose safety\n * signals DO survive as structured errors (Anthropic refusal stops, OpenAI\n * `finish_reason: content_filter`) are matched in _isRetryableError instead.\n *\n * Guarded tightly so legitimate turns are never matched:\n * - only non-error completion stops (\"stop\" | \"length\" | \"toolUse\");\n * - content must be a single short canned refusal text — any tool call,\n * thinking block, or additional prose disqualifies the message;\n * - usage.output must be 0: a genuine model-authored refusal bills output\n * tokens, while the intercepted canned refusal reports zero usage.\n *\n * Treated as retryable so the harness re-requests the model call rather than\n * accepting the refusal; bounded by `maxRetries` like every other retry path.\n */\n\nconst CANNED_SAFETY_REFUSAL_PATTERN =\n\t/^(?:i['’]?m sorry[,.]?\\s+(?:but\\s+)?|sorry[,.]?\\s+(?:but\\s+)?)?i\\s+(?:cannot|can['’]?t|can\\s+not|am\\s+unable\\s+to|am\\s+not\\s+able\\s+to)\\s+(?:assist|help|comply|continue)(?:\\s+with)?(?:\\s+(?:that|this))?(?:\\s+(?:request|task))?\\.?$/i;\n\nconst CANNED_SAFETY_REFUSAL_MAX_LENGTH = 120;\n\nexport function _isSafetyRefusal(this: AgentSession, message: AssistantMessage): boolean {\n\t// Real errors are handled by _isRetryableError; aborts are user-initiated.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"length\" && message.stopReason !== \"toolUse\") {\n\t\treturn false;\n\t}\n\n\tconst content = message.content;\n\tif (!Array.isArray(content) || content.length === 0) return false;\n\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (part.type === \"toolCall\") return false;\n\t\tif (part.type === \"thinking\" && (part.redacted === true || part.thinking.trim().length > 0)) return false;\n\t\tif (part.type === \"text\") text += part.text;\n\t}\n\ttext = text.trim();\n\tif (text.length === 0 || text.length > CANNED_SAFETY_REFUSAL_MAX_LENGTH) return false;\n\tif (!CANNED_SAFETY_REFUSAL_PATTERN.test(text)) return false;\n\n\t// Zero billed output distinguishes a provider interception from legitimate\n\t// model-authored refusal prose, which is never auto-retried.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\nasync function applyFallbackThinkingLevel(this: AgentSession, level: ThinkingLevel): Promise<boolean> {\n\tconst previousLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tif (previousLevel === level) return false;\n\tawait this.sessionManager.appendThinkingLevelChange(level);\n\tthis.agent.state.thinkingLevel = level;\n\treturn true;\n}\n\n/** Capture the user-selected model before the first fallback in a turn. */\nexport function _beginFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackOriginModel !== undefined || currentModel === undefined) return;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tthis._fallbackOriginGeneration = this._fallbackScopeGeneration;\n\tthis._fallbackOriginModel = currentModel;\n\tthis._fallbackOriginThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis._fallbackRestoreError = undefined;\n}\n\nfunction clearFallbackModelScopeState(this: AgentSession): void {\n\tthis._fallbackOriginGeneration = undefined;\n\tthis._fallbackOriginModel = undefined;\n\tthis._fallbackOriginThinkingLevel = undefined;\n\tthis._fallbackRestoreError = undefined;\n\tthis._fallbackAttemptedKeys.clear();\n\tthis._fallbackBlockedModels.length = 0;\n}\n\nfunction finishFallbackModelScope(\n\tthis: AgentSession,\n\toptions: {\n\t\treadonly success: boolean;\n\t\treadonly from?: string;\n\t\treadonly to?: string;\n\t\treadonly finalError?: string;\n\t},\n): boolean {\n\tif (this._fallbackOriginModel === undefined || this._fallbackOriginGeneration === undefined) return false;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n\tthis._emit({\n\t\ttype: \"model_fallback_end\",\n\t\tsuccess: options.success,\n\t\t...(options.from === undefined ? {} : { from: options.from }),\n\t\t...(options.to === undefined ? {} : { to: options.to }),\n\t\t...(options.finalError === undefined ? {} : { finalError: options.finalError }),\n\t});\n\treturn true;\n}\n\n/** Finish an active fallback lifecycle before an explicit model choice. */\nexport function _clearFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tconst finalError = this._fallbackRestoreError;\n\tif (this._fallbackOriginModel !== undefined && this._fallbackOriginGeneration !== undefined) {\n\t\tfinishFallbackModelScope.call(this, {\n\t\t\tsuccess: finalError === undefined,\n\t\t\tfrom: modelLabel(currentModel),\n\t\t\t...(finalError === undefined ? {} : { finalError }),\n\t\t});\n\t\treturn;\n\t}\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n}\n\n/** Finish an active fallback lifecycle without changing the selected fallback model. */\nexport async function _settleFallbackModelScope(this: AgentSession): Promise<boolean> {\n\tconst originModel = this._fallbackOriginModel;\n\tconst originGeneration = this._fallbackOriginGeneration;\n\tconst finalError = this._fallbackRestoreError;\n\tif (originModel === undefined || originGeneration === undefined) {\n\t\tclearFallbackModelScopeState.call(this);\n\t\treturn false;\n\t}\n\tif (this._fallbackOriginGeneration !== originGeneration || this._fallbackOriginModel !== originModel) return false;\n\n\tconst currentModel = this.agent.state.model ?? this.model;\n\treturn finishFallbackModelScope.call(this, {\n\t\tsuccess: finalError === undefined,\n\t\tfrom: modelLabel(currentModel),\n\t\t...(finalError === undefined ? {} : { finalError }),\n\t});\n}\n\n/** Handle retryable errors with exponential backoff. */\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackModels.length === 0 || currentModel === undefined) return false;\n\n\t// A failure the chain may spend a candidate on, but that requesting the same\n\t// model again cannot repair — a rejected credential, an unavailable model, a\n\t// request this model cannot serve — condemns that model for the rest of the\n\t// turn. Reasoning level does not change any of those answers, so every\n\t// reasoning variant of it is blocked too. Transient rate-limit and transport\n\t// failures stay same-model retryable and keep their reasoning variants.\n\tif (isRetryableModelFailure(message) && !isRetryableSameModelFailure(message)) {\n\t\tif (!this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, currentModel))) {\n\t\t\tthis._fallbackBlockedModels.push(currentModel);\n\t\t}\n\t}\n\n\tconst currentThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tconst fromModel = currentModel;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst nextModel = candidate.model;\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ??\n\t\t\t\tthis.settingsManager.getDefaultThinkingLevel() ??\n\t\t\t\tcurrentThinkingLevel ??\n\t\t\t\tDEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tif (this._isFallbackModelAllowed && !this._isFallbackModelAllowed(nextModel, nextLevel)) continue;\n\t\tconst key = fallbackKey(nextModel, nextLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tif (modelsAreEqual(nextModel, fromModel) && nextLevel === currentThinkingLevel) continue;\n\t\t// Skipped before any lifecycle starts: a blocked variant emits no fallback\n\t\t// event and opens no scope.\n\t\tif (this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, nextModel))) continue;\n\n\t\t// Do not create a fallback lifecycle until a candidate can actually be\n\t\t// selected. An exhausted or unresolvable chain has no start to close.\n\n\t\t// Keep the failed attempt in raw history while durably omitting it from model projection.\n\t\tawait this._omitTrailingAssistantAttempt();\n\t\tawait this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\t\t_beginFallbackModelScope.call(this);\n\t\tthis.agent.state.model = nextModel;\n\t\tconst thinkingChanged = await applyFallbackThinkingLevel.call(this, nextLevel);\n\t\tthis._fallbackAttemptedKeys.add(fallbackKey(currentModel, currentThinkingLevel));\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: true,\n\t\t\t\tattempt: Math.max(0, this._retryAttempt - 1),\n\t\t\t});\n\t\t}\n\t\tthis._fallbackAttemptedKeys.add(key);\n\t\tthis._emit({\n\t\t\ttype: \"model_fallback_start\",\n\t\t\tfrom: modelLabel(fromModel),\n\t\t\tto: `${nextModel.provider}/${nextModel.id}`,\n\t\t\treason: message.errorMessage || \"Retryable model error\",\n\t\t\tattempt: this._fallbackAttemptedKeys.size - 1,\n\t\t});\n\t\tif (thinkingChanged) {\n\t\t\tthis._emit({ type: \"thinking_level_changed\", level: nextLevel });\n\t\t\tvoid this._extensionRunner?.emit({\n\t\t\t\ttype: \"thinking_level_select\",\n\t\t\t\tlevel: nextLevel,\n\t\t\t\tpreviousLevel: currentThinkingLevel,\n\t\t\t});\n\t\t}\n\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tthis._emitModelChanged(nextModel, fromModel, \"fallback\");\n\t\tawait this._emitModelSelect(nextModel, fromModel, \"fallback\");\n\t\tthis._retryAttempt = 0;\n\n\t\tconst fallbackGeneration = this._fallbackOriginGeneration;\n\t\tsetTimeout(() => {\n\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\tvoid this.agent.continue().catch(async (error: unknown) => {\n\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\tthis._fallbackRestoreError = finalError;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\t\t\tfinishFallbackModelScope.call(this, {\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tfrom: modelLabel(this.agent.state.model ?? this.model),\n\t\t\t\t\t\t\t\tfinalError,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\tthis._resolveRetry();\n\t\t\t});\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tif (this._fallbackOriginModel !== undefined) {\n\t\tthis._fallbackRestoreError = message.errorMessage || \"Model fallback exhausted\";\n\t}\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tif (this._agentRunAbortRequested) return false;\n\tconst settings = this.settingsManager.getRetrySettings();\n\tconst retryableError = this._isRetryableError?.(message) ?? true;\n\tconst fallbackableError = this._isFallbackableError?.(message) ?? retryableError;\n\tconst emptyCompletion = this._isEmptyCompletion?.(message) ?? false;\n\tconst safetyRefusal = this._isSafetyRefusal?.(message) ?? false;\n\tconst canRetrySameModel = retryableError || emptyCompletion || safetyRefusal;\n\t// Empty completions have historically been allowed to spend a fallback after\n\t// same-model retries. Provider safety refusals stay on the same model.\n\tconst canAdvanceToFallback = fallbackableError || emptyCompletion;\n\tif (!settings.enabled || !canRetrySameModel) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) return true;\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: false,\n\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\tfinalError: message.errorMessage,\n\t\t\t});\n\t\t}\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\n\t// Retry promise is created synchronously in _handleAgentEvent for agent_end.\n\t// Keep a defensive fallback here in case a future refactor bypasses that path.\n\tif (!this._retryPromise) {\n\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\tthis._retryResolve = resolve;\n\t\t});\n\t}\n\n\t// One shared policy decides the bounded same-model budget and its backoff, so\n\t// main chat and workflow stages cannot drift apart on the same settings. The\n\t// counter still advances on the exhausting attempt, so `_trySwitchToFallbackModel`\n\t// closes the retry lifecycle before the fallback lifecycle opens.\n\tconst decision = nextRetryDecision(settings, this._retryAttempt, canRetrySameModel, message);\n\tthis._retryAttempt += 1;\n\tif (decision === undefined) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) {\n\t\t\treturn true;\n\t\t}\n\t\t// Max retries exceeded, emit final failure and reset\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt: this._retryAttempt - 1,\n\t\t\tfinalError: message.errorMessage,\n\t\t});\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\treturn false;\n\t}\n\n\tconst delayMs = decision.delayMs;\n\n\tthis._retryAbortController = new AbortController();\n\tthis._emit({\n\t\ttype: \"auto_retry_start\",\n\t\tattempt: this._retryAttempt,\n\t\tmaxAttempts: settings.maxRetries,\n\t\tdelayMs,\n\t\terrorMessage: message.errorMessage || \"Unknown error\",\n\t});\n\n\t// Keep the failed attempt in raw history while durably omitting it from model projection.\n\tawait this._omitTrailingAssistantAttempt();\n\n\t// Wait with exponential backoff (abortable)\n\tif (this._agentRunAbortRequested) this._retryAbortController.abort();\n\ttry {\n\t\tawait sleep(delayMs, this._retryAbortController.signal);\n\t} catch {\n\t\t// Aborted during sleep - emit end event so UI can clean up\n\t\tfinishCancelledRetry.call(this);\n\t\tthis._retryAbortController = undefined;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\tthis._retryAbortController = undefined;\n\n\t// Retry via continue() - use setTimeout to break out of event handler chain\n\tsetTimeout(() => {\n\t\tif (this._agentRunAbortRequested) {\n\t\t\tfinishCancelledRetry.call(this);\n\t\t\treturn;\n\t\t}\n\t\tthis.agent.continue().catch(() => {\n\t\t\t// Retry failed - will be caught by next agent_end\n\t\t});\n\t}, 0);\n\n\treturn true;\n}\n\n/**\n * Cancel in-progress retry.\n */\n\nfunction finishCancelledRetry(this: AgentSession): void {\n\tif (this._retryAttempt === 0) return;\n\tconst attempt = this._retryAttempt;\n\tthis._retryAttempt = 0;\n\tthis._emit({ type: \"auto_retry_end\", success: false, attempt, finalError: \"Retry cancelled\" });\n}\n\nexport function abortRetry(this: AgentSession): void {\n\tthis._retryAbortController?.abort();\n\tfinishCancelledRetry.call(this);\n\tthis._resolveRetry();\n}\n\n/**\n * Wait for any in-progress retry to complete.\n * Returns immediately if no retry is in progress.\n */\n\nexport async function waitForRetry(this: AgentSession): Promise<void> {\n\tif (!this._retryPromise) {\n\t\treturn;\n\t}\n\n\tawait this._retryPromise;\n\tawait this.agent.waitForIdle();\n}\n\n/** Whether auto-retry is currently in progress */\n\nexport function setAutoRetryEnabled(this: AgentSession, enabled: boolean): void {\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setRetryEnabled(enabled));\n}\n\n// =========================================================================\n// Bash Execution\n// =========================================================================\n\n/**\n * Execute a bash command.\n * Adds result to agent context and session.\n * @param command The bash command to execute\n * @param onChunk Optional streaming callback for output\n * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)\n * @param options.operations Custom BashOperations for remote execution\n */\n\nexport const agentSessionRetryMethods = {\n\t_isRetryableError,\n\t_isFallbackableError,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\n\t_beginFallbackModelScope,\n\t_clearFallbackModelScope,\n\t_settleFallbackModelScope,\n\tabortRetry,\n\twaitForRetry,\n\tsetAutoRetryEnabled,\n};\n"]}
@@ -6,7 +6,7 @@
6
6
  * module free of AgentSession and workflow imports so the published SDK can
7
7
  * expose it to the raw-TypeScript companion packages without a cycle.
8
8
  */
9
- export type ModelFallbackFailureKind = "auth_on_candidate_provider" | "rate_limit" | "quota_exhausted" | "provider_unavailable" | "network_timeout" | "transport_error" | "model_unavailable" | "request_incompatible" | "cancelled" | "task_failure" | "unknown";
9
+ export type ModelFallbackFailureKind = "auth_on_candidate_provider" | "rate_limit" | "quota_exhausted" | "provider_unavailable" | "network_timeout" | "transport_error" | "model_unavailable" | "request_incompatible" | "content_filter" | "cancelled" | "task_failure" | "unknown";
10
10
  export type ModelFallbackFailureSource = "assistant_message" | "diagnostic" | "throw" | "structured" | "string_fallback";
11
11
  export interface ModelFallbackFailureSignal {
12
12
  readonly kind: ModelFallbackFailureKind;
@@ -17,14 +17,24 @@ export interface ModelFallbackFailureSignal {
17
17
  readonly code?: string | number;
18
18
  readonly name?: string;
19
19
  }
20
+ /** How a caller treats a provider content-filter refusal; `retry.fallbackOnContentFilter` in settings. */
21
+ export interface ModelFallbackFailureOptions {
22
+ /** Whether a content-filter refusal may spend the next fallback candidate. Defaults to true. */
23
+ readonly fallbackOnContentFilter?: boolean;
24
+ }
20
25
  export declare function errorMessage(error: unknown): string;
21
26
  /** Alias used by the subagent package's older public helper name. */
22
27
  export declare const modelFailureMessage: typeof errorMessage;
23
28
  export declare function normalizeModelFailureSignal(error: unknown): ModelFallbackFailureSignal;
24
- /** Whether a task-failure signal is a provider safety/refusal response. */
29
+ /** Whether a failure is a provider safety/refusal response: a content-filter refusal, or a refused tool call. */
25
30
  export declare function isSafetyRefusalFailure(error: unknown): boolean;
26
- /** True when this failure may spend a configured model fallback candidate. */
27
- export declare function isRetryableModelFailure(error: unknown): boolean;
31
+ /** Whether a provider's content filter refused the request, as OpenAI's HTTP 422 `cyber_policy` does. */
32
+ export declare function isContentFilterRefusal(error: unknown): boolean;
33
+ /**
34
+ * True when this failure may spend a configured model fallback candidate. A content-filter refusal does unless
35
+ * `options.fallbackOnContentFilter` is false.
36
+ */
37
+ export declare function isRetryableModelFailure(error: unknown, options?: ModelFallbackFailureOptions): boolean;
28
38
  /** True when the same model may be requested again before fallback advances. */
29
39
  export declare function isRetryableSameModelFailure(error: unknown): boolean;
30
40
  //# sourceMappingURL=model-fallback-failures.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"model-fallback-failures.d.ts","sourceRoot":"","sources":["../../src/core/model-fallback-failures.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAmFH,MAAM,MAAM,wBAAwB,GACjC,4BAA4B,GAC5B,YAAY,GACZ,iBAAiB,GACjB,sBAAsB,GACtB,iBAAiB,GACjB,iBAAiB,GACjB,mBAAmB,GACnB,sBAAsB,GACtB,WAAW,GACX,cAAc,GACd,SAAS,CAAC;AAEb,MAAM,MAAM,0BAA0B,GACnC,mBAAmB,GACnB,YAAY,GACZ,OAAO,GACP,YAAY,GACZ,iBAAiB,CAAC;AAErB,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,CAAC,IAAI,EAAE,wBAAwB,CAAC;IACxC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,MAAM,EAAE,0BAA0B,CAAC;IAC5C,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAChC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;CACvB;AAijBD,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAKnD;AAED,qEAAqE;AACrE,eAAO,MAAM,mBAAmB,qBAAe,CAAC;AAEhD,wBAAgB,2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AO,GAAG,MAAM,CAKnD;AAED,qEAAqE;AACrE,eAAO,MAAM,mBAAmB,qBAAe,CAAC;AAEhD,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,OAAO,GAAG,0BAA0B,CAuBtF;AAED,iHAAiH;AACjH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAM9D;AAED,yGAAyG;AACzG,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAE9D;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,2BAA2B,GAAG,OAAO,CAKtG;AASD,gFAAgF;AAChF,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAcnE"}
@@ -212,10 +212,14 @@ function refusalKindFromCode(code) {
212
212
  const normalizedCode = normalizeCode(code);
213
213
  if (normalizedCode === undefined)
214
214
  return undefined;
215
- if (normalizedCode.includes("content_filter") || normalizedCode.includes("contentfilter"))
215
+ // A refused tool call, such as `tool_call_refusal` or `tool_use_refused_by_policy`, before the policy words.
216
+ if (/(?:^|_)tool(?:_|$)/.test(normalizedCode) && normalizedCode.includes("refus"))
216
217
  return "task_failure";
218
+ if (normalizedCode.includes("content_filter") || normalizedCode.includes("contentfilter"))
219
+ return "content_filter";
220
+ // Includes OpenAI's `cyber_policy`.
217
221
  if (normalizedCode.includes("safety") || normalizedCode.includes("policy"))
218
- return "task_failure";
222
+ return "content_filter";
219
223
  switch (normalizedCode) {
220
224
  case "blocked":
221
225
  case "blocked_by_provider":
@@ -223,10 +227,7 @@ function refusalKindFromCode(code) {
223
227
  case "blocked_by_policy":
224
228
  case "provider_refusal":
225
229
  case "refusal":
226
- case "tool_refusal":
227
- case "tool_call_refusal":
228
- case "tool_use_refusal":
229
- return "task_failure";
230
+ return "content_filter";
230
231
  default:
231
232
  return undefined;
232
233
  }
@@ -331,17 +332,27 @@ const REQUEST_INCOMPATIBLE_FAILURE_PATTERNS = [
331
332
  /\binvalid[_\s-]?request(?:[_\s-]?error)?\b/i,
332
333
  /\bbad[_\s-]?request\b/i,
333
334
  ];
334
- const PROVIDER_REFUSAL_FAILURE_PATTERNS = [
335
+ /** A provider declined the request's content under its usage policy: the model will refuse it again. */
336
+ const CONTENT_FILTER_FAILURE_PATTERNS = [
335
337
  /\bthe\s+model\s+refused\s+to\s+complete\s+the\s+request\b/i,
336
338
  /\bfinish[_\s-]?reason\b[^\n]*\bcontent[_\s-]?filter\b/i,
337
339
  /\bcontent[_\s-]?filter(?:ed|ing)?\b/i,
340
+ /\bcyber[_\s-]?policy\b/i,
341
+ // OpenAI's cyber safeguard: "This content was flagged for possible cybersecurity risk."
342
+ /\bflagged\s+for\s+(?:possible|potential(?:ly)?)\b[^\n]*\b(?:risk|harm(?:ful)?|safety|policy|cyber\w*)\b/i,
338
343
  /\b(?:safety|policy)\b[^\n]*\b(?:refus(?:e|al|ed|es|ing)?|block(?:ed|ing)?|filter(?:ed|ing)?|violat(?:e|ion|ed|ing)?|disallow(?:ed|ing)?|reject(?:ed|ion|ing)?)\b/i,
339
344
  /\b(?:refus(?:e|al|ed|es|ing)?|block(?:ed|ing)?|filter(?:ed|ing)?|violat(?:e|ion|ed|ing)?|disallow(?:ed|ing)?|reject(?:ed|ion|ing)?)\b[^\n]*\b(?:safety|policy)\b/i,
345
+ /\bprovider[_\s-]?refus(?:e|al|ed|es|ing)?\b/i,
346
+ /\bprovider\b[^\n]*\brefus(?:e|al|ed|es|ing)?\b[^\n]*\b(?:prompt|request|content|policy|safety)\b/i,
347
+ ];
348
+ const TOOL_REFUSAL_FAILURE_PATTERNS = [
340
349
  /\btool[_\s-]?(?:call|use)?[_\s-]?refus(?:e|al|ed|es|ing)?\b/i,
341
350
  /\btool(?:\s+call|\s+use)?\b[^\n]*\brefus(?:e|al|ed|es|ing)?\b/i,
342
351
  /\brefus(?:e|al|ed|es|ing)?\b[^\n]*\btool(?:\s+call|\s+use)?\b/i,
343
- /\bprovider[_\s-]?refus(?:e|al|ed|es|ing)?\b/i,
344
- /\bprovider\b[^\n]*\brefus(?:e|al|ed|es|ing)?\b[^\n]*\b(?:prompt|request|content|policy|safety)\b/i,
352
+ ];
353
+ const PROVIDER_REFUSAL_FAILURE_PATTERNS = [
354
+ ...CONTENT_FILTER_FAILURE_PATTERNS,
355
+ ...TOOL_REFUSAL_FAILURE_PATTERNS,
345
356
  ];
346
357
  const TRANSPORT_OUTAGE_FAILURE_PATTERNS = [
347
358
  /^connection\s+error\.?$/i,
@@ -379,8 +390,12 @@ function refusalKindFromMessage(message) {
379
390
  return "cancelled";
380
391
  if (NON_RETRYABLE_FAILURE_PATTERNS.some((pattern) => pattern.test(message)))
381
392
  return "task_failure";
382
- if (PROVIDER_REFUSAL_FAILURE_PATTERNS.some((pattern) => pattern.test(message)))
393
+ // A refused tool call is about that call, whatever policy the provider names: another model is asked the same
394
+ // tool call. So it is checked before the content-filter grammar, which "refused ... safety policy" also matches.
395
+ if (TOOL_REFUSAL_FAILURE_PATTERNS.some((pattern) => pattern.test(message)))
383
396
  return "task_failure";
397
+ if (CONTENT_FILTER_FAILURE_PATTERNS.some((pattern) => pattern.test(message)))
398
+ return "content_filter";
384
399
  return undefined;
385
400
  }
386
401
  function fallbackKindFromMessage(message, name) {
@@ -461,12 +476,13 @@ function classifyAssistantRefusalSignal(value, source) {
461
476
  return messageRefusalKind === undefined ? undefined : makeSignal(messageRefusalKind, value, source);
462
477
  }
463
478
  function isRefusalSignal(signal) {
464
- return signal.kind === "cancelled" || signal.kind === "task_failure";
479
+ return signal.kind === "cancelled" || signal.kind === "task_failure" || signal.kind === "content_filter";
465
480
  }
466
481
  function nestedSignalPriority(signal) {
467
482
  switch (signal.kind) {
468
483
  case "cancelled":
469
484
  case "task_failure":
485
+ case "content_filter":
470
486
  return 100;
471
487
  case "auth_on_candidate_provider":
472
488
  return 90;
@@ -640,19 +656,31 @@ export function normalizeModelFailureSignal(error) {
640
656
  ...(name !== undefined ? { name } : {}),
641
657
  };
642
658
  }
643
- /** Whether a task-failure signal is a provider safety/refusal response. */
659
+ /** Whether a failure is a provider safety/refusal response: a content-filter refusal, or a refused tool call. */
644
660
  export function isSafetyRefusalFailure(error) {
645
661
  const signal = normalizeModelFailureSignal(error);
662
+ if (signal.kind === "content_filter")
663
+ return true;
646
664
  if (signal.kind !== "task_failure")
647
665
  return false;
648
666
  const text = `${signal.message}\n${signal.code ?? ""}\n${signal.name ?? ""}`;
649
667
  return PROVIDER_REFUSAL_FAILURE_PATTERNS.some((pattern) => pattern.test(text));
650
668
  }
651
- /** True when this failure may spend a configured model fallback candidate. */
652
- export function isRetryableModelFailure(error) {
669
+ /** Whether a provider's content filter refused the request, as OpenAI's HTTP 422 `cyber_policy` does. */
670
+ export function isContentFilterRefusal(error) {
671
+ return normalizeModelFailureSignal(error).kind === "content_filter";
672
+ }
673
+ /**
674
+ * True when this failure may spend a configured model fallback candidate. A content-filter refusal does unless
675
+ * `options.fallbackOnContentFilter` is false.
676
+ */
677
+ export function isRetryableModelFailure(error, options) {
653
678
  if (error === undefined)
654
679
  return false;
655
- return FALLBACKABLE_FAILURE_KINDS.has(normalizeModelFailureSignal(error).kind);
680
+ const kind = normalizeModelFailureSignal(error).kind;
681
+ if (kind === "content_filter")
682
+ return options?.fallbackOnContentFilter !== false;
683
+ return FALLBACKABLE_FAILURE_KINDS.has(kind);
656
684
  }
657
685
  const SAME_MODEL_RETRYABLE_FAILURE_KINDS = new Set([
658
686
  "rate_limit",