Documentation
¶
Overview ¶
Package claudecode implements the Agent interface for Claude Code.
Index ¶
- Constants
- Variables
- func CalculateTokenUsage(transcript []TranscriptLine) *agent.TokenUsage
- func CalculateTokenUsageFromFile(path string, startLine int) (*agent.TokenUsage, error)
- func ExtractLastUserPrompt(lines []TranscriptLine) string
- func ExtractModifiedFiles(lines []TranscriptLine) []string
- func ExtractSpawnedAgentIDs(transcript []TranscriptLine) map[string]string
- func FindCheckpointUUID(lines []TranscriptLine, toolUseID string) (string, bool)
- func NewClaudeCodeAgent() agent.Agent
- func SanitizePathForClaude(path string) string
- func SerializeTranscript(lines []TranscriptLine) ([]byte, error)
- type ClaudeCodeAgent
- func (c *ClaudeCodeAgent) AreHooksInstalled(ctx context.Context) bool
- func (c *ClaudeCodeAgent) CalculateTokenUsage(transcriptData []byte, fromOffset int) (*agent.TokenUsage, error)
- func (c *ClaudeCodeAgent) CalculateTotalTokenUsage(transcriptData []byte, startLine int, subagentsDir string) (*agent.TokenUsage, error)
- func (c *ClaudeCodeAgent) ChunkTranscript(_ context.Context, content []byte, maxSize int) ([][]byte, error)
- func (c *ClaudeCodeAgent) Description() string
- func (c *ClaudeCodeAgent) DetectPresence(ctx context.Context) (bool, error)
- func (c *ClaudeCodeAgent) ExtractAllModifiedFiles(transcriptData []byte, startLine int, subagentsDir string) ([]string, error)
- func (c *ClaudeCodeAgent) ExtractModifiedFilesFromOffset(path string, startOffset int) (files []string, currentPosition int, err error)
- func (c *ClaudeCodeAgent) ExtractPrompts(sessionRef string, fromOffset int) ([]string, error)
- func (c *ClaudeCodeAgent) ExtractSummary(sessionRef string) (string, error)
- func (c *ClaudeCodeAgent) FindCheckpointUUID(session *agent.AgentSession, toolUseID string) (string, bool)
- func (c *ClaudeCodeAgent) FormatResumeCommand(sessionID string) string
- func (c *ClaudeCodeAgent) GetLastUserPrompt(session *agent.AgentSession) string
- func (c *ClaudeCodeAgent) GetSessionDir(repoPath string) (string, error)
- func (c *ClaudeCodeAgent) GetSessionID(input *agent.HookInput) string
- func (c *ClaudeCodeAgent) GetTranscriptPosition(path string) (int, error)
- func (c *ClaudeCodeAgent) HookNames() []string
- func (c *ClaudeCodeAgent) InstallHooks(ctx context.Context, localDev bool, force bool) (int, error)
- func (c *ClaudeCodeAgent) IsPreview() bool
- func (c *ClaudeCodeAgent) Name() types.AgentName
- func (c *ClaudeCodeAgent) ParseHookEvent(_ context.Context, hookName string, stdin io.Reader) (*agent.Event, error)
- func (c *ClaudeCodeAgent) PrepareTranscript(ctx context.Context, sessionRef string) error
- func (c *ClaudeCodeAgent) ProtectedDirs() []string
- func (c *ClaudeCodeAgent) ReadSession(input *agent.HookInput) (*agent.AgentSession, error)
- func (c *ClaudeCodeAgent) ReadSessionFromPath(transcriptPath, sessionID string) (*agent.AgentSession, error)
- func (c *ClaudeCodeAgent) ReadTranscript(sessionRef string) ([]byte, error)
- func (c *ClaudeCodeAgent) ReassembleTranscript(chunks [][]byte) ([]byte, error)
- func (c *ClaudeCodeAgent) ResolveSessionFile(sessionDir, agentSessionID string) string
- func (c *ClaudeCodeAgent) TruncateAtUUID(session *agent.AgentSession, uuid string) (*agent.AgentSession, error)
- func (c *ClaudeCodeAgent) Type() types.AgentType
- func (c *ClaudeCodeAgent) UninstallHooks(ctx context.Context) error
- func (c *ClaudeCodeAgent) WriteHookResponse(message string) error
- func (c *ClaudeCodeAgent) WriteSession(_ context.Context, session *agent.AgentSession) error
- type ClaudeHookEntry
- type ClaudeHookMatcher
- type ClaudeHooks
- type ClaudeSettings
- type TranscriptLine
Constants ¶
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`
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
const ClaudeSettingsFileName = "settings.json"
ClaudeSettingsFileName is the settings file used by Claude Code. This is Claude-specific and not shared with other agents.
Variables ¶
var FileModificationTools = []string{ ToolWrite, ToolEdit, ToolNotebookEdit, ToolMCPWrite, ToolMCPEdit, }
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 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 ¶
NewClaudeCodeAgent creates a new Claude Code agent instance.
func SanitizePathForClaude ¶
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(ctx context.Context) bool
AreHooksInstalled checks if Entire hooks are installed.
func (*ClaudeCodeAgent) CalculateTokenUsage ¶ added in v0.4.6
func (c *ClaudeCodeAgent) CalculateTokenUsage(transcriptData []byte, 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(transcriptData []byte, startLine int, subagentsDir string) (*agent.TokenUsage, error)
CalculateTotalTokenUsage calculates token usage for a turn, including subagents. It parses the main transcript bytes from startLine, extracts spawned agent IDs, and calculates their token usage from transcript files in subagentsDir.
func (*ClaudeCodeAgent) ChunkTranscript ¶
func (c *ClaudeCodeAgent) ChunkTranscript(_ context.Context, 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(ctx context.Context) (bool, error)
DetectPresence checks if Claude Code is configured in the repository.
func (*ClaudeCodeAgent) ExtractAllModifiedFiles ¶ added in v0.4.6
func (c *ClaudeCodeAgent) ExtractAllModifiedFiles(transcriptData []byte, 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 bytes 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 (*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 ¶
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() types.AgentName
Name returns the agent registry key.
func (*ClaudeCodeAgent) ParseHookEvent ¶ added in v0.4.6
func (c *ClaudeCodeAgent) ParseHookEvent(_ context.Context, 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(ctx context.Context, 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() types.AgentType
Type returns the agent type identifier.
func (*ClaudeCodeAgent) UninstallHooks ¶
func (c *ClaudeCodeAgent) UninstallHooks(ctx context.Context) error
UninstallHooks removes Entire hooks from Claude Code settings.
func (*ClaudeCodeAgent) WriteHookResponse ¶ added in v0.4.9
func (c *ClaudeCodeAgent) WriteHookResponse(message string) error
WriteHookResponse outputs a JSON hook response to stdout. Claude Code reads this JSON and displays the systemMessage to the user.
func (*ClaudeCodeAgent) WriteSession ¶
func (c *ClaudeCodeAgent) WriteSession(_ context.Context, 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 ¶
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