claudecode

package
v0.4.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package claudecode implements the Agent interface for Claude Code.

Index

Constants

View Source
const (
	HookNameSessionStart     = "session-start"
	HookNameSessionEnd       = "session-end"
	HookNameStop             = "stop"
	HookNameUserPromptSubmit = "user-prompt-submit"
	HookNamePreTask          = "pre-task"
	HookNamePostTask         = "post-task"
	HookNamePostTodo         = "post-todo"
)

Claude Code hook names - these become subcommands under `entire hooks claude-code`

View Source
const (
	ToolWrite        = "Write"
	ToolEdit         = "Edit"
	ToolNotebookEdit = "NotebookEdit"
	ToolMCPWrite     = "mcp__acp__Write" //nolint:gosec // G101: This is a tool name, not a credential
	ToolMCPEdit      = "mcp__acp__Edit"
)

Tool names used in Claude Code transcripts

View Source
const ClaudeSettingsFileName = "settings.json"

ClaudeSettingsFileName is the settings file used by Claude Code. This is Claude-specific and not shared with other agents.

Variables

FileModificationTools lists tools that create or modify files

Functions

func CalculateTokenUsage

func CalculateTokenUsage(transcript []TranscriptLine) *agent.TokenUsage

CalculateTokenUsage calculates token usage from a Claude Code transcript. This is specific to Claude/Anthropic's API format where each assistant message contains a usage object with input_tokens, output_tokens, and cache tokens.

Due to streaming, multiple transcript rows may share the same message.id. We deduplicate by taking the row with the highest output_tokens for each message.id.

func CalculateTokenUsageFromFile

func CalculateTokenUsageFromFile(path string, startLine int) (*agent.TokenUsage, error)

CalculateTokenUsageFromFile calculates token usage from a Claude Code transcript file. If startLine > 0, only considers lines from startLine onwards.

func CalculateTotalTokenUsage

func CalculateTotalTokenUsage(transcriptPath string, startLine int, subagentsDir string) (*agent.TokenUsage, error)

CalculateTotalTokenUsage calculates token usage for a turn, including subagents. It parses the main transcript from startLine, extracts spawned agent IDs, and calculates their token usage from transcripts in subagentsDir.

func ExtractAllModifiedFiles added in v0.4.5

func ExtractAllModifiedFiles(transcriptPath string, startLine int, subagentsDir string) ([]string, error)

ExtractAllModifiedFiles extracts files modified by both the main agent and any subagents spawned via the Task tool. It parses the main transcript from startLine, collects modified files from the main agent, then reads each subagent's transcript from subagentsDir to collect their modified files too. The result is a deduplicated list of all modified file paths.

func ExtractLastUserPrompt

func ExtractLastUserPrompt(lines []TranscriptLine) string

ExtractLastUserPrompt extracts the last user message from transcript

func ExtractModifiedFiles

func ExtractModifiedFiles(lines []TranscriptLine) []string

ExtractModifiedFiles extracts files modified by tool calls from transcript

func ExtractSpawnedAgentIDs

func ExtractSpawnedAgentIDs(transcript []TranscriptLine) map[string]string

ExtractSpawnedAgentIDs extracts agent IDs from Task tool results in a transcript. When a Task tool completes, the tool_result contains "agentId: <id>" in its content. Returns a map of agentID -> toolUseID for all spawned agents.

func FindCheckpointUUID

func FindCheckpointUUID(lines []TranscriptLine, toolUseID string) (string, bool)

FindCheckpointUUID finds the UUID of the message containing the tool_result for the given tool_use_id

func NewClaudeCodeAgent

func NewClaudeCodeAgent() agent.Agent

NewClaudeCodeAgent creates a new Claude Code agent instance.

func SanitizePathForClaude

func SanitizePathForClaude(path string) string

func SerializeTranscript

func SerializeTranscript(lines []TranscriptLine) ([]byte, error)

SerializeTranscript converts transcript lines back to JSONL bytes

Types

type ClaudeCodeAgent

type ClaudeCodeAgent struct{}

ClaudeCodeAgent implements the Agent interface for Claude Code.

func (*ClaudeCodeAgent) AreHooksInstalled

func (c *ClaudeCodeAgent) AreHooksInstalled() bool

AreHooksInstalled checks if Entire hooks are installed.

func (*ClaudeCodeAgent) CalculateTokenUsage added in v0.4.6

func (c *ClaudeCodeAgent) CalculateTokenUsage(sessionRef string, fromOffset int) (*agent.TokenUsage, error)

CalculateTokenUsage computes token usage from the transcript starting at the given line offset.

func (*ClaudeCodeAgent) CalculateTotalTokenUsage added in v0.4.6

func (c *ClaudeCodeAgent) CalculateTotalTokenUsage(sessionRef string, fromOffset int, subagentsDir string) (*agent.TokenUsage, error)

CalculateTotalTokenUsage computes token usage including all spawned subagents. Claude Code spawns subagents via the Task tool; their transcripts are stored in subagentsDir.

func (*ClaudeCodeAgent) ChunkTranscript

func (c *ClaudeCodeAgent) ChunkTranscript(content []byte, maxSize int) ([][]byte, error)

ChunkTranscript splits a JSONL transcript at line boundaries. Claude Code uses JSONL format (one JSON object per line), so chunking is done at newline boundaries to preserve message integrity.

func (*ClaudeCodeAgent) Description

func (c *ClaudeCodeAgent) Description() string

Description returns a human-readable description.

func (*ClaudeCodeAgent) DetectPresence

func (c *ClaudeCodeAgent) DetectPresence() (bool, error)

DetectPresence checks if Claude Code is configured in the repository.

func (*ClaudeCodeAgent) ExtractAllModifiedFiles added in v0.4.6

func (c *ClaudeCodeAgent) ExtractAllModifiedFiles(sessionRef string, fromOffset int, subagentsDir string) ([]string, error)

ExtractAllModifiedFiles extracts files modified by both the main agent and any spawned subagents. Claude Code spawns subagents via the Task tool; their transcripts are stored in subagentsDir. Returns a deduplicated list of all modified file paths.

func (*ClaudeCodeAgent) ExtractModifiedFilesFromOffset

func (c *ClaudeCodeAgent) ExtractModifiedFilesFromOffset(path string, startOffset int) (files []string, currentPosition int, err error)

ExtractModifiedFilesFromOffset extracts files modified since a given line number. For Claude Code (JSONL format), offset is the starting line number. Uses bufio.Reader to handle arbitrarily long lines (no size limit). Returns:

  • files: list of file paths modified by Claude (from Write/Edit tools)
  • currentPosition: total number of lines in the file
  • error: any error encountered during reading

func (*ClaudeCodeAgent) ExtractPrompts added in v0.4.6

func (c *ClaudeCodeAgent) ExtractPrompts(sessionRef string, fromOffset int) ([]string, error)

ExtractPrompts extracts user prompts from the transcript starting at the given line offset.

func (*ClaudeCodeAgent) ExtractSummary added in v0.4.6

func (c *ClaudeCodeAgent) ExtractSummary(sessionRef string) (string, error)

ExtractSummary extracts the last assistant message as a session summary.

func (*ClaudeCodeAgent) FindCheckpointUUID

func (c *ClaudeCodeAgent) FindCheckpointUUID(session *agent.AgentSession, toolUseID string) (string, bool)

FindCheckpointUUID finds the UUID of the message containing the tool_result for the given tool use ID. Used for task checkpoint rewind. Returns the UUID and true if found, empty string and false otherwise.

func (*ClaudeCodeAgent) FormatResumeCommand

func (c *ClaudeCodeAgent) FormatResumeCommand(sessionID string) string

FormatResumeCommand returns the command to resume a Claude Code session.

func (*ClaudeCodeAgent) GetLastUserPrompt

func (c *ClaudeCodeAgent) GetLastUserPrompt(session *agent.AgentSession) string

GetLastUserPrompt extracts the last user prompt from the session. Requires NativeData to be populated (call ReadSession first).

func (*ClaudeCodeAgent) GetSessionDir

func (c *ClaudeCodeAgent) GetSessionDir(repoPath string) (string, error)

GetSessionDir returns the directory where Claude stores session transcripts.

func (*ClaudeCodeAgent) GetSessionID

func (c *ClaudeCodeAgent) GetSessionID(input *agent.HookInput) string

GetSessionID extracts the session ID from hook input.

func (*ClaudeCodeAgent) GetTranscriptPosition

func (c *ClaudeCodeAgent) GetTranscriptPosition(path string) (int, error)

GetTranscriptPosition returns the current line count of a Claude Code transcript. Claude Code uses JSONL format, so position is the number of lines. This is a lightweight operation that only counts lines without parsing JSON. Uses bufio.Reader to handle arbitrarily long lines (no size limit). Returns 0 if the file doesn't exist or is empty.

func (*ClaudeCodeAgent) HookNames added in v0.4.6

func (c *ClaudeCodeAgent) HookNames() []string

HookNames returns the hook verbs Claude Code supports. These become subcommands: entire hooks claude-code <verb>

func (*ClaudeCodeAgent) InstallHooks

func (c *ClaudeCodeAgent) InstallHooks(localDev bool, force bool) (int, error)

InstallHooks installs Claude Code hooks in .claude/settings.json. If force is true, removes existing Entire hooks before installing. Returns the number of hooks installed.

func (*ClaudeCodeAgent) IsPreview added in v0.4.6

func (c *ClaudeCodeAgent) IsPreview() bool

func (*ClaudeCodeAgent) Name

func (c *ClaudeCodeAgent) Name() agent.AgentName

Name returns the agent registry key.

func (*ClaudeCodeAgent) ParseHookEvent added in v0.4.6

func (c *ClaudeCodeAgent) ParseHookEvent(hookName string, stdin io.Reader) (*agent.Event, error)

ParseHookEvent translates a Claude Code hook into a normalized lifecycle Event. Returns nil if the hook has no lifecycle significance.

func (*ClaudeCodeAgent) PrepareTranscript added in v0.4.6

func (c *ClaudeCodeAgent) PrepareTranscript(sessionRef string) error

PrepareTranscript waits for Claude Code's async transcript flush to complete. Claude writes a hook_progress sentinel entry after flushing all pending writes.

func (*ClaudeCodeAgent) ProtectedDirs added in v0.4.3

func (c *ClaudeCodeAgent) ProtectedDirs() []string

ProtectedDirs returns directories that Claude uses for config/state.

func (*ClaudeCodeAgent) ReadSession

func (c *ClaudeCodeAgent) ReadSession(input *agent.HookInput) (*agent.AgentSession, error)

ReadSession reads a session from Claude's storage (JSONL transcript file). The session data is stored in NativeData as raw JSONL bytes. ModifiedFiles is computed by parsing the transcript.

func (*ClaudeCodeAgent) ReadSessionFromPath

func (c *ClaudeCodeAgent) ReadSessionFromPath(transcriptPath, sessionID string) (*agent.AgentSession, error)

ReadSessionFromPath is a convenience method that reads a session directly from a file path. This is useful when you have the path but not a HookInput.

func (*ClaudeCodeAgent) ReadTranscript added in v0.4.6

func (c *ClaudeCodeAgent) ReadTranscript(sessionRef string) ([]byte, error)

ReadTranscript reads the raw JSONL transcript bytes for a session.

func (*ClaudeCodeAgent) ReassembleTranscript

func (c *ClaudeCodeAgent) ReassembleTranscript(chunks [][]byte) ([]byte, error)

func (*ClaudeCodeAgent) ResolveSessionFile added in v0.4.3

func (c *ClaudeCodeAgent) ResolveSessionFile(sessionDir, agentSessionID string) string

ResolveSessionFile returns the path to a Claude session file. Claude names files directly as <id>.jsonl.

func (*ClaudeCodeAgent) TruncateAtUUID

func (c *ClaudeCodeAgent) TruncateAtUUID(session *agent.AgentSession, uuid string) (*agent.AgentSession, error)

TruncateAtUUID returns a new session truncated at the given UUID (inclusive). This is used for rewind operations to restore transcript state. Requires NativeData to be populated.

func (*ClaudeCodeAgent) Type

func (c *ClaudeCodeAgent) Type() agent.AgentType

Type returns the agent type identifier.

func (*ClaudeCodeAgent) UninstallHooks

func (c *ClaudeCodeAgent) UninstallHooks() error

UninstallHooks removes Entire hooks from Claude Code settings.

func (*ClaudeCodeAgent) WriteSession

func (c *ClaudeCodeAgent) WriteSession(session *agent.AgentSession) error

WriteSession writes a session to Claude's storage (JSONL transcript file). Uses the NativeData field which contains raw JSONL bytes. The session must have been created by Claude Code (AgentName check).

type ClaudeHookEntry

type ClaudeHookEntry struct {
	Type    string `json:"type"`
	Command string `json:"command"`
}

ClaudeHookEntry represents a single hook command

type ClaudeHookMatcher

type ClaudeHookMatcher struct {
	Matcher string            `json:"matcher"`
	Hooks   []ClaudeHookEntry `json:"hooks"`
}

ClaudeHookMatcher matches hooks to specific patterns

type ClaudeHooks

type ClaudeHooks struct {
	SessionStart     []ClaudeHookMatcher `json:"SessionStart,omitempty"`
	SessionEnd       []ClaudeHookMatcher `json:"SessionEnd,omitempty"`
	UserPromptSubmit []ClaudeHookMatcher `json:"UserPromptSubmit,omitempty"`
	Stop             []ClaudeHookMatcher `json:"Stop,omitempty"`
	PreToolUse       []ClaudeHookMatcher `json:"PreToolUse,omitempty"`
	PostToolUse      []ClaudeHookMatcher `json:"PostToolUse,omitempty"`
}

ClaudeHooks contains the hook configurations

type ClaudeSettings

type ClaudeSettings struct {
	Hooks ClaudeHooks `json:"hooks"`
}

ClaudeSettings represents the .claude/settings.json structure

type TranscriptLine

type TranscriptLine = transcript.Line

TranscriptLine is an alias to the shared transcript.Line type.

func TruncateAtUUID

func TruncateAtUUID(lines []TranscriptLine, uuid string) []TranscriptLine

TruncateAtUUID returns transcript lines up to and including the line with given UUID

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL