Skip to content

Add support for graceful interruption/cancellation of running queries #8

@jasondk

Description

@jasondk

Feature Request

The Python SDK currently doesn't appear to have a mechanism for gracefully interrupting/cancelling a running Claude Code query while preserving context. This feature would be valuable for building automation and oversight systems.

Use Case

We're building a system where another LLM oversees Claude Code's execution to ensure it stays on track. When Claude Code starts going in an unintended direction, we need to:

  1. Interrupt the current execution gracefully
  2. Preserve the conversation context and Claude's understanding of the codebase
  3. Redirect with new instructions without starting over

Currently, killing the process would lose all context, making it impractical for complex, multi-step tasks.

Current Behavior

  • The CLI supports interruption via the Escape key, which preserves context
  • The TypeScript SDK supports this via abortController
  • The Python SDK doesn't appear to expose this capability

Proposed Solution

Add an interruption mechanism to the Python SDK, possibly through:

# Option 1: Cancellable task
task = asyncio.create_task(query(prompt="..."))
# Later:
await task.cancel()  # Gracefully interrupts while preserving context

# Option 2: Abort controller pattern (similar to TypeScript)
controller = AbortController()
async for message in query(prompt="...", abort_controller=controller):
    if need_to_interrupt:
        controller.abort()

# Option 3: Query handle with methods
query_handle = await start_query(prompt="...")
async for message in query_handle.messages():
    if need_to_interrupt:
        await query_handle.interrupt()

Additional Context

This would enable sophisticated automation workflows where Claude Code can be dynamically guided and corrected without losing progress. It would bring the Python SDK to feature parity with the TypeScript SDK and match the CLI's existing capabilities.

Would this be something you'd consider adding? Thanks!

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions