מדריך קלוד קוד בעברית

תיעוד 187

שחזור שינויי קבצים עם נקודות ביקורת

מעקב אחרי שינויי קבצים במהלך סשנים של סוכן, ושחזור קבצים לכל מצב קודם

נקודות ביקורת לקבצים עוקבות אחרי שינויי קבצים שנעשים דרך הכלים Write, Edit ו-NotebookEdit במהלך סשן של סוכן, ומאפשרות להחזיר קבצים לכל מצב קודם. כדי לראות שחזור שמחזיר קובץ, עברו לדוגמה האינטראקטיבית.

[!WARNING]

rewindFiles() לא מבטל את מה ש-sed -i או פקודת Bash אחרת עשו לקובץ, אלא אם כלי כמו Write או Edit שינה את הקובץ הזה בשיחה הראשית. עריכות של סוכן משנה אינן במעקב, בעוד שעריכות מ-skill עם context: fork שרץ בחזית כן נמצאות במעקב.

#איך נקודות ביקורת עובדות

כשמפעילים נקודות ביקורת לקבצים, ה-SDK יוצר גיבויים של קבצים לפני שינוי שלהם דרך הכלים Write, Edit או NotebookEdit. הודעות משתמש בזרם התשובות כוללות UUID של נקודת ביקורת שאפשר להשתמש בו כנקודת שחזור.

[!NOTE]

שחזור קבצים מחזיר את הקבצים בדיסק למצב קודם. הוא לא מחזיר לאחור את השיחה עצמה. היסטוריית השיחה וההקשר נשארים שלמים אחרי קריאה ל-rewindFiles() (TypeScript) או ל-rewind_files() (Python).

כשחוזרים לנקודת ביקורת, Claude Code מוחק את הקבצים שהוא יצר ומשחזר את הקבצים שהוא שינה לתוכן שלהם בנקודה הזו. Claude Code מדלג על נתיב במעקב שהוא symlink, hard link, או קובץ אחר שאינו קובץ רגיל. הוא גם מדלג על קובץ במעקב שתיקיית האב שלו כבר לא נפתרת למיקום שלה בזמן נקודת הביקורת, או שאת הגיבוי שלו אי אפשר לקרוא בבטחה. RewindFilesResult סופר כל נתיב שדולג בשדה skippedLinks. הדילוג דורש את Claude Code בגרסה v2.1.216 או חדשה יותר. לפני v2.1.216, שחזור כתב ומחק דרך קישורים בנתיבים שבמעקב.

#מימוש נקודות ביקורת

כדי להשתמש בנקודות ביקורת לקבצים, הפעילו אותן באפשרויות, תפסו UUID של נקודות ביקורת מזרם התשובות, ואז קראו ל-rewindFiles() (TypeScript) או ל-rewind_files() (Python) כשצריך לשחזר.

הדוגמאות בסעיף הזה משתמשות בהנחיה "Refactor the authentication module". הריצו אותן בפרויקט שמכיל מודול אימות, או שנו את ההנחיה כך שתציין קבצים שקיימים בפרויקט, כדי שאפשר יהיה לראות את הקבצים משתנים ולראות את השחזור מחזיר אותם.

הדוגמה הזו מפעילה נקודות ביקורת, תופסת את ה-UUID של נקודת הביקורת ואת מזהה הסשן מזרם התשובות, ואז ממשיכה את הסשן מאוחר יותר כדי לשחזר קבצים. ההערות הממוספרות בדוגמה תואמות את השלבים שאחריה.

import asyncio
from claude_agent_sdk import (
    ClaudeSDKClient,
    ClaudeAgentOptions,
    UserMessage,
    ResultMessage,
)


async def main():
    # Step 1: Enable checkpointing
    options = ClaudeAgentOptions(
        enable_file_checkpointing=True,
        permission_mode="acceptEdits",  # Auto-accept file edits without prompting
        extra_args={
            "replay-user-messages": None
        },  # Required to receive checkpoint UUIDs in the response stream
    )

    checkpoint_id = None
    session_id = None

    # Run the query and capture checkpoint UUID and session ID
    async with ClaudeSDKClient(options) as client:
        await client.query("Refactor the authentication module")

        # Step 2: Capture checkpoint UUID from the first user message
        async for message in client.receive_response():
            if isinstance(message, UserMessage) and message.uuid and not checkpoint_id:
                checkpoint_id = message.uuid
            if isinstance(message, ResultMessage) and not session_id:
                session_id = message.session_id

    # Step 3: Later, rewind by resuming the session with an empty prompt
    if checkpoint_id and session_id:
        async with ClaudeSDKClient(
            ClaudeAgentOptions(enable_file_checkpointing=True, resume=session_id)
        ) as client:
            await client.query("")  # Empty prompt to open the connection
            async for message in client.receive_response():
                await client.rewind_files(checkpoint_id)
                break
        print(f"Rewound to checkpoint: {checkpoint_id}")


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

async function main() {
  // Step 1: Enable checkpointing
  const opts = {
    enableFileCheckpointing: true,
    permissionMode: "acceptEdits" as const, // Auto-accept file edits without prompting
    extraArgs: { "replay-user-messages": null } // Required to receive checkpoint UUIDs in the response stream
  };

  const response = query({
    prompt: "Refactor the authentication module",
    options: opts
  });

  let checkpointId: string | undefined;
  let sessionId: string | undefined;

  // Step 2: Capture checkpoint UUID from the first user message
  try {
    for await (const message of response) {
      if (message.type === "user" && message.uuid && !checkpointId) {
        checkpointId = message.uuid;
      }
      if ("session_id" in message && !sessionId) {
        sessionId = message.session_id;
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result. If the
    // failure was an error result, sessionId and checkpointId were already
    // captured by the loop above; connection or process failures yield no
    // result message.
    console.error(`Session ended with an error: ${error}`);
  }

  // Step 3: Later, rewind by resuming the session with an empty prompt
  if (checkpointId && sessionId) {
    const rewindQuery = query({
      prompt: "", // Empty prompt to open the connection
      options: { ...opts, resume: sessionId }
    });

    for await (const msg of rewindQuery) {
      await rewindQuery.rewindFiles(checkpointId);
      break;
    }
    console.log(`Rewound to checkpoint: ${checkpointId}`);
  }
}

main();

1. הפעלת נקודות ביקורת

הגדירו את אפשרויות ה-SDK כדי להפעיל נקודות ביקורת ולקבל UUID של נקודות ביקורת:

אפשרותPythonTypeScriptתיאור
הפעלת נקודות ביקורתenable_file_checkpointing=TrueenableFileCheckpointing: trueעוקב אחרי שינויי קבצים לצורך שחזור
קבלת UUID של נקודות ביקורתextra_args={"replay-user-messages": None}extraArgs: { 'replay-user-messages': null }נדרש כדי לקבל UUID של הודעות משתמש בזרם

הדוגמה הראשית תחת מימוש נקודות ביקורת מגדירה גם את מצב ההרשאות ל-acceptEdits, שמאשר את עריכות הקבצים של הסוכן בלי הנחיה. למידע נוסף, ראו מצבי הרשאה.

2. תפיסת UUID של נקודת ביקורת ומזהה סשן

כשהאפשרות replay-user-messages מוגדרת, לכל הודעת משתמש בזרם התשובות יש UUID שמשמש כנקודת ביקורת.

ברוב מקרי השימוש, תפסו את ה-UUID של הודעת המשתמש הראשונה (message.uuid). שחזור אליו מחזיר את הקבצים שבמעקב למצבם המקורי. כדי לשמור כמה נקודות ביקורת ולשחזר למצבי ביניים, ראו כמה נקודות שחזור.

תפיסת מזהה הסשן (message.session_id) היא אופציונלית. צריך אותו רק אם רוצים לשחזר מאוחר יותר, אחרי שהזרם מסתיים. אם קוראים ל-rewindFiles() מיד תוך כדי עיבוד ההודעות (כמו בדוגמה בנקודת ביקורת לפני פעולות מסוכנות), אפשר לדלג על תפיסת מזהה הסשן.

3. שחזור קבצים

כדי לשחזר אחרי שהזרם מסתיים, המשיכו את הסשן עם הנחיה ריקה וקראו ל-rewind_files() (Python) או ל-rewindFiles() (TypeScript) עם ה-UUID של נקודת הביקורת. הפעילו נקודות ביקורת גם באפשרויות של הסשן שממשיכים, וקראו לשחזור מתוך לולאת התשובות. אפשר גם לשחזר במהלך הזרם. ראו נקודת ביקורת לפני פעולות מסוכנות לדפוס הזה.

אם תופסים את מזהה הסשן ואת מזהה נקודת הביקורת, אפשר גם לשחזר מה-CLI. הפקודה הזו דורשת את קובץ ההרצה claude, שמגיע מהתקנת Claude Code. ה-SDK מפעיל עבורכם נקודות ביקורת, אבל כשמריצים claude -p ישירות חובה להגדיר את משתנה הסביבה CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING:

CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true claude -p --resume <session-id> --rewind-files <checkpoint-uuid>

הדגל --rewind-files לא מופיע בפלט של claude --help, אבל ה-CLI מקבל אותו כפי שמוצג. כשהשחזור מצליח, הפקודה מדפיסה Files rewound to state at message <checkpoint-uuid> ויוצאת בלי לשלוח הנחיה.

#דפוסים נפוצים

הדפוסים האלה מציגים דרכים שונות לתפוס UUID של נקודות ביקורת ולהשתמש בהם, לפי מקרה השימוש.

#נקודת ביקורת לפני פעולות מסוכנות

הדפוס הזה שומר רק את ה-UUID האחרון של נקודת ביקורת, ומעדכן אותו לפני כל תור של הסוכן. אם משהו משתבש במהלך העיבוד, אפשר מיד לשחזר למצב הבטוח האחרון ולצאת מהלולאה.

לפני הרצת הדוגמה הזו, החליפו את your_revert_condition (Python) או את yourRevertCondition (TypeScript) בבדיקה משלכם, למשל זיהוי שגיאה או כשל אימות. ממלא המקום לא מוגדר בדוגמה.

import asyncio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, UserMessage


async def main():
    options = ClaudeAgentOptions(
        enable_file_checkpointing=True,
        permission_mode="acceptEdits",
        extra_args={"replay-user-messages": None},
    )

    safe_checkpoint = None

    async with ClaudeSDKClient(options) as client:
        await client.query("Refactor the authentication module")

        async for message in client.receive_response():
            # Update checkpoint before each agent turn starts
            # This overwrites the previous checkpoint. Only keep the latest
            if isinstance(message, UserMessage) and message.uuid:
                safe_checkpoint = message.uuid

            # Decide when to revert based on your own logic
            # For example: error detection, validation failure, or user input
            if your_revert_condition and safe_checkpoint:
                await client.rewind_files(safe_checkpoint)
                # Exit the loop after rewinding, files are restored
                break


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

async function main() {
  const response = query({
    prompt: "Refactor the authentication module",
    options: {
      enableFileCheckpointing: true,
      permissionMode: "acceptEdits" as const,
      extraArgs: { "replay-user-messages": null }
    }
  });

  let safeCheckpoint: string | undefined;

  for await (const message of response) {
    // Update checkpoint before each agent turn starts
    // This overwrites the previous checkpoint. Only keep the latest
    if (message.type === "user" && message.uuid) {
      safeCheckpoint = message.uuid;
    }

    // Decide when to revert based on your own logic
    // For example: error detection, validation failure, or user input
    if (yourRevertCondition && safeCheckpoint) {
      await response.rewindFiles(safeCheckpoint);
      // Exit the loop after rewinding, files are restored
      break;
    }
  }
}

main();

#כמה נקודות שחזור

אם Claude עושה שינויים לאורך כמה תורות, אולי תרצו לשחזר לנקודה מסוימת ולא כל הדרך אחורה. לדוגמה, אם Claude משפץ קובץ בתור הראשון ומוסיף בדיקות בתור השני, אולי תרצו לשמור את השיפוץ אבל לבטל את הבדיקות.

הדפוס הזה שומר את כל ה-UUID של נקודות הביקורת במערך עם מטא-נתונים. אחרי שהסשן מסתיים, אפשר לשחזר לכל נקודת ביקורת קודמת:

import asyncio
from dataclasses import dataclass
from datetime import datetime
from claude_agent_sdk import (
    ClaudeSDKClient,
    ClaudeAgentOptions,
    UserMessage,
    ResultMessage,
)


# Store checkpoint metadata for better tracking
@dataclass
class Checkpoint:
    id: str
    description: str
    timestamp: datetime


async def main():
    options = ClaudeAgentOptions(
        enable_file_checkpointing=True,
        permission_mode="acceptEdits",
        extra_args={"replay-user-messages": None},
    )

    checkpoints = []
    session_id = None

    async with ClaudeSDKClient(options) as client:
        await client.query("Refactor the authentication module")

        async for message in client.receive_response():
            if isinstance(message, UserMessage) and message.uuid:
                checkpoints.append(
                    Checkpoint(
                        id=message.uuid,
                        description=f"After turn {len(checkpoints) + 1}",
                        timestamp=datetime.now(),
                    )
                )
            if isinstance(message, ResultMessage) and not session_id:
                session_id = message.session_id

    # Later: rewind to any checkpoint by resuming the session
    if checkpoints and session_id:
        target = checkpoints[0]  # Pick any checkpoint
        async with ClaudeSDKClient(
            ClaudeAgentOptions(enable_file_checkpointing=True, resume=session_id)
        ) as client:
            await client.query("")  # Empty prompt to open the connection
            async for message in client.receive_response():
                await client.rewind_files(target.id)
                break
        print(f"Rewound to: {target.description}")


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

// Store checkpoint metadata for better tracking
interface Checkpoint {
  id: string;
  description: string;
  timestamp: Date;
}

async function main() {
  const opts = {
    enableFileCheckpointing: true,
    permissionMode: "acceptEdits" as const,
    extraArgs: { "replay-user-messages": null }
  };

  const response = query({
    prompt: "Refactor the authentication module",
    options: opts
  });

  const checkpoints: Checkpoint[] = [];
  let sessionId: string | undefined;

  try {
    for await (const message of response) {
      if (message.type === "user" && message.uuid) {
        checkpoints.push({
          id: message.uuid,
          description: `After turn ${checkpoints.length + 1}`,
          timestamp: new Date()
        });
      }
      if ("session_id" in message && !sessionId) {
        sessionId = message.session_id;
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result. If the
    // failure was an error result, sessionId and the checkpoints array were
    // already populated by the loop above; connection or process failures
    // yield no result message.
    console.error(`Session ended with an error: ${error}`);
  }

  // Later: rewind to any checkpoint by resuming the session
  if (checkpoints.length > 0 && sessionId) {
    const target = checkpoints[0]; // Pick any checkpoint
    const rewindQuery = query({
      prompt: "", // Empty prompt to open the connection
      options: { ...opts, resume: sessionId }
    });

    for await (const msg of rewindQuery) {
      await rewindQuery.rewindFiles(target.id);
      break;
    }
    console.log(`Rewound to: ${target.description}`);
  }
}

main();

#נסו את זה

הדוגמה המלאה הזו יוצרת קובץ עזר קטן, מבקשת מהסוכן להוסיף הערות תיעוד, מציגה את השינויים, ואז שואלת אם תרצו לחזור אחורה.

לפני שמתחילים, ודאו שClaude Agent SDK מותקן.

1. צרו קובץ בדיקה

צרו קובץ חדש בשם utils.py (Python) או utils.ts (TypeScript) והדביקו את הקוד הבא:

def add(a, b):
    return a + b


def subtract(a, b):
    return a - b


def multiply(a, b):
    return a * b


def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b
export function add(a: number, b: number): number {
  return a + b;
}

export function subtract(a: number, b: number): number {
  return a - b;
}

export function multiply(a: number, b: number): number {
  return a * b;
}

export function divide(a: number, b: number): number {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }
  return a / b;
}

2. הריצו את הדוגמה האינטראקטיבית

צרו קובץ חדש בשם try_checkpointing.py (Python) או try_checkpointing.ts (TypeScript) באותה תיקייה שבה נמצא קובץ העזר, והדביקו את הקוד הבא.

הסקריפט הזה מבקש מ-Claude להוסיף הערות תיעוד לקובץ העזר, ואז נותן לכם אפשרות לחזור אחורה ולשחזר את המקור.

import asyncio
from claude_agent_sdk import (
    ClaudeSDKClient,
    ClaudeAgentOptions,
    UserMessage,
    ResultMessage,
)


async def main():
    # Configure the SDK with checkpointing enabled
    # - enable_file_checkpointing: Track file changes for rewinding
    # - permission_mode: Auto-accept file edits without prompting
    # - extra_args: Required to receive user message UUIDs in the stream
    options = ClaudeAgentOptions(
        enable_file_checkpointing=True,
        permission_mode="acceptEdits",
        extra_args={"replay-user-messages": None},
    )

    checkpoint_id = None  # Store the user message UUID for rewinding
    session_id = None  # Store the session ID for resuming

    print("Running agent to add doc comments to utils.py...\n")

    # Run the agent and capture checkpoint data from the response stream
    async with ClaudeSDKClient(options) as client:
        await client.query("Add doc comments to utils.py")

        async for message in client.receive_response():
            # Capture the first user message UUID - this is our restore point
            if isinstance(message, UserMessage) and message.uuid and not checkpoint_id:
                checkpoint_id = message.uuid
            # Capture the session ID so we can resume later
            if isinstance(message, ResultMessage):
                session_id = message.session_id

    print("Done! Open utils.py to see the added doc comments.\n")

    # Ask the user if they want to rewind the changes
    if checkpoint_id and session_id:
        response = input("Rewind to remove the doc comments? (y/n): ")

        if response.lower() == "y":
            # Resume the session with an empty prompt, then rewind
            async with ClaudeSDKClient(
                ClaudeAgentOptions(enable_file_checkpointing=True, resume=session_id)
            ) as client:
                await client.query("")  # Empty prompt opens the connection
                async for message in client.receive_response():
                    await client.rewind_files(checkpoint_id)  # Restore files
                    break

            print(
                "\n✓ File restored! Open utils.py to verify the doc comments are gone."
            )
        else:
            print("\nKept the modified file.")


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";
import * as readline from "readline";

async function main() {
  // Configure the SDK with checkpointing enabled
  // - enableFileCheckpointing: Track file changes for rewinding
  // - permissionMode: Auto-accept file edits without prompting
  // - extraArgs: Required to receive user message UUIDs in the stream
  const opts = {
    enableFileCheckpointing: true,
    permissionMode: "acceptEdits" as const,
    extraArgs: { "replay-user-messages": null }
  };

  let sessionId: string | undefined; // Store the session ID for resuming
  let checkpointId: string | undefined; // Store the user message UUID for rewinding

  console.log("Running agent to add doc comments to utils.ts...\n");

  // Run the agent and capture checkpoint data from the response stream
  const response = query({
    prompt: "Add doc comments to utils.ts",
    options: opts
  });

  try {
    for await (const message of response) {
      // Capture the first user message UUID - this is our restore point
      if (message.type === "user" && message.uuid && !checkpointId) {
        checkpointId = message.uuid;
      }
      // Capture the session ID so we can resume later
      if ("session_id" in message) {
        sessionId = message.session_id;
      }
    }
  } catch (error) {
    // A single-shot query() throws after yielding an error result. If the
    // failure was an error result, checkpointId and sessionId were already
    // captured by the loop above; connection or process failures yield no
    // result message.
    console.error(`Session ended with an error: ${error}`);
  }

  console.log("Done! Open utils.ts to see the added doc comments.\n");

  // Ask the user if they want to rewind the changes
  if (checkpointId && sessionId) {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    const answer = await new Promise<string>((resolve) => {
      rl.question("Rewind to remove the doc comments? (y/n): ", resolve);
    });
    rl.close();

    if (answer.toLowerCase() === "y") {
      // Resume the session with an empty prompt, then rewind
      const rewindQuery = query({
        prompt: "", // Empty prompt opens the connection
        options: { ...opts, resume: sessionId }
      });

      for await (const msg of rewindQuery) {
        await rewindQuery.rewindFiles(checkpointId); // Restore files
        break;
      }

      console.log("\n✓ File restored! Open utils.ts to verify the doc comments are gone.");
    } else {
      console.log("\nKept the modified file.");
    }
  }
}

main();

3. הריצו את הדוגמה

הריצו את הסקריפט מאותה תיקייה שבה נמצא קובץ העזר.

טיפ

פתחו את קובץ העזר (utils.py או utils.ts) ב-IDE או בעורך לפני הרצת הסקריפט. תראו את הקובץ מתעדכן בזמן אמת כשהסוכן מוסיף הערות תיעוד, ואז חוזר למקור כשתבחרו לחזור אחורה.

Python

python try_checkpointing.py

TypeScript

npx tsx try_checkpointing.ts

תראו שהסוכן מוסיף הערות תיעוד, ואז מופיעה בקשה ששואלת אם תרצו לחזור אחורה. אם תבחרו כן, הקובץ משוחזר למצבו המקורי.

#מגבלות

לשמירת נקודות ביקורת של קבצים יש המגבלות הבאות:

מגבלהתיאור
שינויים מפקודת Bashחזרה אחורה לא מבטלת שינויים שפקודת Bash ביצעה, חוץ מקבצים שהשיחה הראשית כבר ערכה עם כלי כמו Write או Edit
עריכות של תת-סוכןעריכות שתת-סוכן מחיל אינן במעקב, חוץ ממיומנות עם context: fork שרצה בחזית. חזרה אחורה מחזירה אותן רק בקבצים שהשיחה הראשית כבר ערכה. השתמשו ב-git כדי להחזיר את השאר
אותה הפעלהנקודות הביקורת קשורות להפעלה שיצרה אותן
תוכן קבצים בלבדיצירה, העברה או מחיקה של תיקיות לא מבוטלות בחזרה אחורה
קבצים מקומייםקבצים מרוחקים או קבצי רשת אינם במעקב

#פתרון בעיות

#אפשרויות שמירת נקודות ביקורת לא מזוהות

אם enableFileCheckpointing או rewindFiles() לא זמינים, ייתכן שאתם בגרסת SDK ישנה יותר.

פתרון: עדכנו לגרסת ה-SDK העדכנית:

  • Python: pip install --upgrade claude-agent-sdk
  • TypeScript: npm install @anthropic-ai/claude-agent-sdk@latest

#להודעות משתמש אין UUID

אם message.uuid הוא undefined או חסר, אינכם מקבלים מזהי UUID של נקודות ביקורת.

סיבה: האפשרות replay-user-messages לא מוגדרת.

פתרון: הוסיפו extra_args={"replay-user-messages": None} (Python) או extraArgs: { 'replay-user-messages': null } (TypeScript) לאפשרויות.

#שגיאת "No file checkpoint found for this message"

השגיאה הזו מתרחשת כשנתוני נקודת הביקורת לא קיימים עבור UUID של הודעת המשתמש שצוין.

סיבות נפוצות:

  • שמירת נקודות ביקורת של קבצים לא הופעלה בהפעלה המקורית (enable_file_checkpointing או enableFileCheckpointing לא הוגדר ל-true)
  • ההפעלה לא הושלמה כראוי לפני ניסיון לחדש ולחזור אחורה

פתרון: ודאו ש-enable_file_checkpointing=True (Python) או enableFileCheckpointing: true (TypeScript) הוגדר בהפעלה המקורית, ואז השתמשו בדפוס שמוצג בדוגמאות: תפסו את ה-UUID של הודעת המשתמש הראשונה, השלימו את ההפעלה במלואה, ואז חדשו עם בקשה ריקה וקראו ל-rewindFiles() פעם אחת.

#שגיאת "File rewinding is not enabled"

השגיאה הזו מתרחשת כשמנסים חזרה אחורה לא אינטראקטיבית בלי ששמירת נקודות ביקורת מופעלת: הרצה של claude -p לבדו עם --rewind-files, או הרצת הפעלת SDK, כולל הפעלה שחודשה, שהאפשרויות שלה לא מפעילות שמירת נקודות ביקורת. ה-SDK מגדיר את משתנה הסביבה CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING באופן פנימי רק כש-enable_file_checkpointing (Python) או enableFileCheckpointing (TypeScript) מופעל בהפעלה שמבצעת את החזרה אחורה. ה-CLI לבדו אף פעם לא מגדיר אותו.

פתרון: עבור ה-CLI לבדו, הגדירו את משתנה הסביבה בעת הרצת הפקודה:

CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING=true claude -p --resume <session-id> --rewind-files <checkpoint-uuid>

עבור ה-SDK, הגדירו enable_file_checkpointing=True (Python) או enableFileCheckpointing: true (TypeScript) בהפעלה שחודשה, כמו שהדוגמאות בדף הזה עושות.

#שגיאת "ProcessTransport is not ready for writing"

השגיאה הזו מתרחשת כשקוראים ל-rewindFiles() או ל-rewind_files() אחרי שסיימתם לעבור על התגובה. החיבור לתהליך ה-CLI נסגר כשהלולאה מסתיימת.

פתרון: חדשו את ההפעלה עם בקשה ריקה, ואז קראו לחזרה אחורה בשאילתה החדשה. הדוגמה המובילה תחת יישום שמירת נקודות ביקורת מציגה את הקריאה לחידוש ולחזרה אחורה בשתי השפות, בהערה שמסומנת Step 3.

#הצעדים הבאים

  • הפעלות: למדו איך לחדש הפעלות, דבר שנדרש לחזרה אחורה אחרי שהזרם מסתיים. מכסה מזהי הפעלה, חידוש שיחות, ופיצול הפעלות.
  • הרשאות: הגדירו באילו כלים Claude יכול להשתמש ואיך מאשרים שינויי קבצים. שימושי אם אתם רוצים יותר שליטה על מתי עריכות מתרחשות.
  • הפניה ל-TypeScript SDK: הפניה מלאה ל-API, כולל כל האפשרויות של query() והמתודה rewindFiles().
  • הפניה ל-Python SDK: הפניה מלאה ל-API, כולל כל האפשרויות של ClaudeAgentOptions והמתודה rewind_files().