Skip to content

refactor: move incomplete-turn recovery behind provider hooks - #66233

Closed
jalehman wants to merge 2 commits into
mainfrom
openclaw-3ed.1/provider-incomplete-turn-recovery-hook
Closed

jalehman wants to merge 2 commits into
mainfrom
openclaw-3ed.1/provider-incomplete-turn-recovery-hook

Conversation

@jalehman

Copy link
Copy Markdown
Contributor

Summary

  • Problem: reasoning-only and empty-response continuation recovery from fix: recover reasoning-only OpenAI turns #66167 lived directly in pi-embedded-runner, gated by an OpenAI-specific helper instead of the provider plugin boundary.
  • Why it matters: other providers could not opt into the same replay-safe recovery behavior without more runner special cases.
  • What changed: added a provider-owned incomplete-turn recovery hook, refactored the runner to consult provider policy, preserved OpenAI/OpenAI Codex behavior, and added Anthropic as a narrower reasoning-only consumer.
  • What did NOT change (scope boundary): core still owns attempt classification, replay-safety, retry-loop control, liveness, and incomplete-turn fallback behavior.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: provider-specific continuation policy for incomplete assistant turns was encoded directly in runner helpers instead of the provider plugin contract.
  • Missing detection / guardrail: no additive provider seam existed for model-family-specific reasoning-only or empty-response continuation.
  • Contributing context (if known): the runner already owned replay-safety and continuation control, so the easiest initial fix hardcoded the OpenAI lane.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/agents/pi-embedded-runner/run.incomplete-turn.test.ts, src/plugins/provider-runtime.test.ts, extensions/openai/index.test.ts, extensions/anthropic/index.test.ts
  • Scenario the test should lock in: provider-owned incomplete-turn recovery policy controls reasoning-only and empty-response retries without runner special cases, while OpenAI behavior stays intact and Anthropic can opt into reasoning-only recovery.
  • Why this is the smallest reliable guardrail: the change crosses the provider hook contract, runner control loop, and bundled provider registration, so the seam tests are the smallest end-to-end boundary coverage.
  • Existing test that already covers this (if any): the runner incomplete-turn suite already covered the OpenAI continuation path and was updated to use the new seam.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

  • Incomplete-turn continuation is now provider-owned instead of OpenAI-special-cased in the runner.
  • Anthropic Claude transports can now opt into replay-safe reasoning-only continuation through the same provider seam.

Diagram (if applicable)

Before:
[assistant reasoning-only/empty turn] -> [runner OpenAI-specific guard] -> [retry or incomplete-turn error]

After:
[assistant reasoning-only/empty turn] -> [provider recovery policy hook] -> [runner replay-safe retry loop] -> [visible answer or incomplete-turn error]

Security Impact (required)

  • New permissions/capabilities? (No)
  • Secrets/tokens handling changed? (No)
  • New/changed network calls? (No)
  • Command/tool execution surface changed? (No)
  • Data access scope changed? (No)
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: local Node 22 / pnpm
  • Model/provider: mocked OpenAI/OpenAI Codex/Anthropic provider registration plus embedded runner harness
  • Integration/channel (if any): none
  • Relevant config (redacted): default embedded runner config and bundled provider registrations

Steps

  1. Trigger a replay-safe reasoning-only or empty-response assistant turn in the embedded runner.
  2. Resolve provider incomplete-turn recovery policy for the active assistant provider/model.
  3. Verify the runner retries only when the provider policy enables that recovery mode.

Expected

  • OpenAI/OpenAI Codex keep the current continuation behavior.
  • Anthropic can opt into reasoning-only continuation through the provider seam.
  • Providers without policy do not get retries.

Actual

  • The runner now consults provider-owned policy and the focused tests/build pass.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

  • Verified scenarios: targeted provider-runtime, OpenAI plugin, Anthropic plugin, and runner incomplete-turn suites; Plugin SDK API baseline regeneration/check; full pnpm build.
  • Edge cases checked: side-effect guard still blocks retries, assistant error turns still do not retry, OpenAI GPT-5 lane preserves retry budgets, Anthropic empty-response remains disabled.
  • What you did not verify: live Anthropic/OpenAI account behavior outside the local harness.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (No)
  • Migration needed? (No)
  • If yes, exact upgrade steps:

Risks and Mitigations

  • Risk: a provider could opt into retries for a model family that should fail fast.
    • Mitigation: core still owns replay-safety checks, assistant-error rejection, and incomplete-turn fallback; provider policy only enables already-classified retry shapes.
  • Risk: provider hook drift could reintroduce runner special cases.
    • Mitigation: the new hook is centralized in ProviderPlugin/provider-runtime with focused boundary coverage.

Regeneration-Prompt: |
  Move the reasoning-only and empty-response retry behavior added in PR #66167 out of the OpenAI-specific runner guard and behind the provider plugin boundary. Keep replay-safety, liveness, retry-loop control, and incomplete-turn fallback behavior in core pi-embedded-runner code, but let provider plugins declare whether their model families support reasoning-only and/or empty-response continuation plus the retry budgets. Preserve the current OpenAI and OpenAI Codex behavior, add Anthropic as a second provider consumer for reasoning-only recovery, update the provider runtime tests and runner harness/tests, and refresh the public provider-plugin SDK docs and API baseline hash for the new hook.
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: anthropic extensions: openai size: M maintainer Maintainer-authored PR labels Apr 14, 2026
Regeneration-Prompt: |
  After opening PR #66233 for the provider-owned incomplete-turn recovery refactor, add the required changelog entry under ## Unreleased -> ### Fixes. Keep the entry append-only, reference the new PR number, and describe that replay-safe reasoning-only and empty-response continuation moved behind provider hooks so providers can opt in without runner special cases, with Anthropic using the same seam for reasoning-only recovery.
@greptile-apps

greptile-apps Bot commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR cleanly moves reasoning-only and empty-response incomplete-turn recovery out of the OpenAI-specific runner guard and behind the resolveIncompleteTurnRecoveryPolicy provider hook. OpenAI/OpenAI Codex behavior is preserved and Anthropic gains a narrower reasoning-only consumer through the same seam.

  • ProviderIncompleteTurnRetryRule is not re-exported from src/plugin-sdk/plugin-entry.ts; only ProviderIncompleteTurnRecoveryPolicy and ProviderIncompleteTurnRecoveryContext are. External plugin authors can still construct correct return values via structural typing, but cannot explicitly annotate intermediate rule variables.
  • stripProviderPrefix is duplicated identically between extensions/anthropic/incomplete-turn-policy.ts and extensions/openai/incomplete-turn-policy.ts. Per the repo guidelines on shared helpers, this is a candidate for extraction now that there are two consumers.

Confidence Score: 5/5

Safe to merge — all remaining findings are P2 style/ergonomics concerns with no correctness impact.

Core retry control flow, replay-safety guards, and liveness state are unchanged. Provider hooks correctly gate on recoveryRule?.enabled === true, so providers without a policy produce no retries. Both OpenAI and Anthropic policies are straightforward and well-tested. The two open findings (missing ProviderIncompleteTurnRetryRule re-export and duplicated stripProviderPrefix) are P2 style issues that do not affect runtime behavior.

No files require blocking attention; extensions/anthropic/incomplete-turn-policy.ts and extensions/openai/incomplete-turn-policy.ts share a duplicated helper worth tracking.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/anthropic/incomplete-turn-policy.ts
Line: 7-11

Comment:
**`stripProviderPrefix` duplicated across extension files**

This helper is identical to the one in `extensions/openai/incomplete-turn-policy.ts` (lines 9–13). The CLAUDE.md plugin boundary rules call for centralising shared helpers before a second consumer appears. Now that two consumers exist, extracting this to a shared SDK seam (or a small shared utility module both extensions can import) would prevent the two implementations from drifting.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/plugin-sdk/plugin-entry.ts
Line: 104-105

Comment:
**`ProviderIncompleteTurnRetryRule` not re-exported from public SDK**

`ProviderIncompleteTurnRecoveryPolicy` (which is exported) contains two fields typed as `ProviderIncompleteTurnRetryRule`, but the sub-type itself is not re-exported. TypeScript's structural typing means plugin authors can still construct correct return values without importing the type, but they can't explicitly annotate intermediate `ProviderIncompleteTurnRetryRule` variables. Adding it alongside the two already-exported types would complete the public surface and is consistent with how all fields of exported policy types are accessible.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "docs: note provider-owned incomplete-tur..." | Re-trigger Greptile

Comment on lines +7 to +11
function stripProviderPrefix(modelId: string): string {
const trimmed = modelId.trim();
const match = /^([^/:]+)[/:](.+)$/.exec(trimmed);
return normalizeLowercaseStringOrEmpty(match?.[2] ?? trimmed);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 stripProviderPrefix duplicated across extension files

This helper is identical to the one in extensions/openai/incomplete-turn-policy.ts (lines 9–13). The CLAUDE.md plugin boundary rules call for centralising shared helpers before a second consumer appears. Now that two consumers exist, extracting this to a shared SDK seam (or a small shared utility module both extensions can import) would prevent the two implementations from drifting.

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/anthropic/incomplete-turn-policy.ts
Line: 7-11

Comment:
**`stripProviderPrefix` duplicated across extension files**

This helper is identical to the one in `extensions/openai/incomplete-turn-policy.ts` (lines 9–13). The CLAUDE.md plugin boundary rules call for centralising shared helpers before a second consumer appears. Now that two consumers exist, extracting this to a shared SDK seam (or a small shared utility module both extensions can import) would prevent the two implementations from drifting.

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment on lines +104 to +105
ProviderIncompleteTurnRecoveryContext,
ProviderIncompleteTurnRecoveryPolicy,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 ProviderIncompleteTurnRetryRule not re-exported from public SDK

ProviderIncompleteTurnRecoveryPolicy (which is exported) contains two fields typed as ProviderIncompleteTurnRetryRule, but the sub-type itself is not re-exported. TypeScript's structural typing means plugin authors can still construct correct return values without importing the type, but they can't explicitly annotate intermediate ProviderIncompleteTurnRetryRule variables. Adding it alongside the two already-exported types would complete the public surface and is consistent with how all fields of exported policy types are accessible.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/plugin-sdk/plugin-entry.ts
Line: 104-105

Comment:
**`ProviderIncompleteTurnRetryRule` not re-exported from public SDK**

`ProviderIncompleteTurnRecoveryPolicy` (which is exported) contains two fields typed as `ProviderIncompleteTurnRetryRule`, but the sub-type itself is not re-exported. TypeScript's structural typing means plugin authors can still construct correct return values without importing the type, but they can't explicitly annotate intermediate `ProviderIncompleteTurnRetryRule` variables. Adding it alongside the two already-exported types would complete the public surface and is consistent with how all fields of exported policy types are accessible.

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cbc6276a4f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1673 to +1677
workspaceDir: params.workspaceDir,
context: {
config: params.config,
agentDir,
workspaceDir: params.workspaceDir,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pass resolved workspace into recovery-policy hook

This new hook call forwards params.workspaceDir, but runEmbeddedPiAgent normally derives a resolvedWorkspace when the caller omits that field. In those common runs, resolveIncompleteTurnRecoveryPolicy receives ctx.workspaceDir as undefined, so provider plugins that need workspace-scoped config/files to decide recovery behavior can silently return no policy and disable retries unexpectedly. Use the already-resolved workspace path here (both for hook resolution and the hook context) to keep this seam consistent with other provider-runtime hook calls.

Useful? React with 👍 / 👎.

@aisle-research-bot

aisle-research-bot Bot commented Apr 14, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 2 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Unhandled exception in provider plugin hook can crash run loop (incomplete turn recovery policy)
2 🟡 Medium Incomplete-turn auto-retry may replay side-effecting tool calls due to weak side-effect detection and provider-enabled recovery
1. 🟡 Unhandled exception in provider plugin hook can crash run loop (incomplete turn recovery policy)
Property Value
Severity Medium
CWE CWE-248
Location src/plugins/provider-runtime.ts:617-627

Description

resolveProviderIncompleteTurnRecoveryPolicyWithPlugin calls into a provider plugin hook without exception isolation. If a third-party/buggy provider plugin throws, the exception will propagate to callers (e.g., the embedded agent run loop), potentially aborting an in-progress run and causing availability issues.

  • Input/control: provider plugins are resolved dynamically (resolveProviderHookPlugin) and may be external/third-party code.
  • Sink: direct invocation of resolveIncompleteTurnRecoveryPolicy without try/catch.
  • Impact: a thrown error can take down the current request/turn, and in some hosting setups may crash the process if uncaught upstream.

Vulnerable code:

return (
  resolveProviderHookPlugin(params)?.resolveIncompleteTurnRecoveryPolicy?.(params.context) ??
  undefined
);

Recommendation

Wrap provider plugin hook execution in a defensive try/catch, log telemetry, and fall back to a safe default (typically undefined) so a plugin failure cannot break core execution.

Example:

export function resolveProviderIncompleteTurnRecoveryPolicyWithPlugin(params: {
  provider: string;
  config?: OpenClawConfig;
  workspaceDir?: string;
  env?: NodeJS.ProcessEnv;
  context: ProviderIncompleteTurnRecoveryContext;
}): ProviderIncompleteTurnRecoveryPolicy | undefined {
  try {
    return (
      resolveProviderHookPlugin(params)?.resolveIncompleteTurnRecoveryPolicy?.(params.context) ??
      undefined
    );
  } catch (err) {
    ​// TODO: replace with structured logging/telemetry
    log.warn(
      `[provider-hook] resolveIncompleteTurnRecoveryPolicy failed for provider=${params.provider}: ${String(err)}`,
    );
    return undefined;
  }
}

If the project has an established pattern for safe plugin execution (e.g., a shared wrapper), use it consistently across all provider hook invocations.

2. 🟡 Incomplete-turn auto-retry may replay side-effecting tool calls due to weak side-effect detection and provider-enabled recovery
Property Value
Severity Medium
CWE CWE-358
Location src/agents/pi-embedded-runner/run/incomplete-turn.ts:147-156

Description

The embedded runner decides whether an incomplete turn is replay-safe using a heuristic that only considers tool names plus a couple of special cases. With this change, providers can enable reasoning-only / empty-response recovery via resolveIncompleteTurnRecoveryPolicy, increasing the likelihood of an automatic retry.

If a tool causes external side effects but its name is not recognized by isLikelyMutatingToolName (and it isn't covered by didSendViaMessagingTool/successfulCronAdds), hadPotentialSideEffects may remain false. In that case, recovery can proceed and the run may be retried, potentially repeating side effects (double payments, duplicate tickets, repeated network calls, etc.).

Why this is security-relevant:

  • Inputs: tool invocations produced by the model during an attempt (params.toolMetas)
  • Classification: hadPotentialSideEffects is derived from isLikelyMutatingToolName(toolName) only
  • Sink: retry instructions (resolveReasoningOnlyRetryInstruction / resolveEmptyResponseRetryInstruction) are allowed when hadPotentialSideEffects is false and provider policy sets enabled: true

Vulnerable code (replay-safety classification):

const hadMutatingTools = params.toolMetas.some((t) => isLikelyMutatingToolName(t.toolName));
const hadPotentialSideEffects =
  hadMutatingTools || params.didSendViaMessagingTool || (params.successfulCronAdds ?? 0) > 0;

With provider-enabled recovery, any misclassification here can lead to duplicated real-world actions on retry.

Recommendation

Fail closed for replay safety and/or require explicit tool-side metadata.

Options (can be combined):

  1. Treat unknown tools as potentially mutating unless explicitly declared read-only in tool schema/registration.

  2. Use a stronger classifier than name-only heuristics, e.g. incorporate isMutatingToolCall(toolName, args) (or equivalent) and/or a tool-provided sideEffecting: true/false flag.

  3. Gate provider-enabled recovery on a stricter replay-safe signal (e.g., require attempt.replayMetadata.replaySafe === true computed from declared tool metadata, not heuristics).

Example approach (sketch):

​// during tool registration / schema normalization
type ToolSafety = { sideEffecting: boolean };

​// when building replay metadata
const hadPotentialSideEffects = params.toolMetas.some(t => t.safety?.sideEffecting ?? true);

This ensures automatic retries cannot occur after any tool that is not explicitly marked replay-safe.


Analyzed PR: #66233 at commit a96e857

Last updated on: 2026-04-14T00:33:58Z

@jalehman jalehman closed this Jun 3, 2026
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
Regeneration-Prompt: |
  After opening PR openclaw#66233 for the provider-owned incomplete-turn recovery refactor, add the required changelog entry under ## Unreleased -> ### Fixes. Keep the entry append-only, reference the new PR number, and describe that replay-safe reasoning-only and empty-response continuation moved behind provider hooks so providers can opt in without runner special cases, with Anthropic using the same seam for reasoning-only recovery.
@shakkernerd
shakkernerd deleted the openclaw-3ed.1/provider-incomplete-turn-recovery-hook branch October 19, 2026 23:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: anthropic extensions: openai maintainer Maintainer-authored PR size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant