claude

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: May 27, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CwdToProjectDir

func CwdToProjectDir(cwd string) string

CwdToProjectDir converts an absolute cwd to the Claude project subdir name. e.g. "/home/user/project" -> "-home-user-project"

func FormatMemory

func FormatMemory(mem *MemoryInfo) string

func FormatModelRows

func FormatModelRows(w io.Writer, summary *UsageSummary, grandTotal int) error

func FormatMultiUsage

func FormatMultiUsage(w io.Writer, instances []InstanceUsage, now time.Time) error

FormatMultiUsage writes per-instance and aggregated total usage.

func FormatTmuxPanes

func FormatTmuxPanes(w io.Writer, panes []TmuxPane) error

FormatTmuxPanes writes the tmux pane listing to w.

func FormatTokens

func FormatTokens(n int) string

FormatTokens formats a token count as a human-readable string (e.g. 1.5M, 2.3K).

func FormatUsage

func FormatUsage(w io.Writer, summary *UsageSummary, now time.Time) error

FormatUsage writes the usage summary to w.

func Install

func Install(w io.Writer, fw FileWriter, personal bool) error

Install writes the Claude Code skill and agent files to disk. When personal is true, files are written under ~/.claude/ instead of .claude/.

func InstallHooks

func InstallHooks(w io.Writer, fw FileWriter) error

InstallHooks registers hooks in ~/.claude/settings.json. The hooks invoke `human hook` directly — no script file needed.

func MergeUsage

func MergeUsage(dst, src *UsageSummary)

MergeUsage adds all model usage from src into dst. Both arguments may be nil; the call is a no-op when src is nil and the destination is left untouched.

func ShortProjectName

func ShortProjectName(cwd string) string

ShortProjectName returns the last two path components for a readable label. e.g. "/home/user/dev/myproject" -> "dev/myproject"

func WindowEnd

func WindowEnd(start time.Time) time.Time

WindowEnd returns the end of the current 5-hour usage window in UTC.

func WindowStart

func WindowStart(now time.Time) time.Time

WindowStart returns the start of the current 5-hour usage window in UTC.

Types

type ByteWalker

type ByteWalker struct {
	Data []byte
}

ByteWalker implements DirWalker over in-memory bytes (one JSONL line per text line).

func (*ByteWalker) WalkJSONL

func (b *ByteWalker) WalkJSONL(_ string, fn func(line []byte) error) error

type CombinedFinder

type CombinedFinder struct {
	Finders []InstanceFinder
}

CombinedFinder aggregates multiple InstanceFinders, logging and skipping failures.

func (*CombinedFinder) FindInstances

func (c *CombinedFinder) FindInstances(ctx context.Context) ([]Instance, error)

type CommChecker

type CommChecker func(pid int) bool

CommChecker verifies a process command name.

type CommandRunner

type CommandRunner interface {
	Run(ctx context.Context, name string, args ...string) ([]byte, error)
}

CommandRunner abstracts running external commands for testability.

type ContainerChecker

type ContainerChecker interface {
	IsContainerized(pid int) bool
}

ContainerChecker determines whether a process is running inside a container.

type ContainerInfo

type ContainerInfo struct {
	ID     string
	Name   string
	Labels map[string]string
}

ContainerInfo holds minimal container metadata.

type CwdResolver

type CwdResolver interface {
	ResolveCwd(pid int) (string, error)
}

CwdResolver resolves the current working directory for a process.

type DirWalker

type DirWalker interface {
	WalkJSONL(root string, fn func(line []byte) error) error
}

DirWalker abstracts walking JSONL files for testability.

type DockerClient

type DockerClient interface {
	ListContainers(ctx context.Context) ([]ContainerInfo, error)
	Exec(ctx context.Context, containerID string, cmd []string) (int, io.Reader, error)
	ContainerStats(ctx context.Context, containerID string) (*MemoryInfo, error)
	Close() error
}

DockerClient abstracts Docker operations for testability.

func NewEngineDockerClient

func NewEngineDockerClient() (DockerClient, error)

NewEngineDockerClient creates a DockerClient backed by the Docker Engine API.

type DockerFinder

type DockerFinder struct {
	Client   DockerClient
	CacheTTL time.Duration // TTL for container data cache; defaults to 2s
	// contains filtered or unexported fields
}

DockerFinder discovers Claude Code instances inside Docker containers.

func (*DockerFinder) FindInstances

func (d *DockerFinder) FindInstances(ctx context.Context) ([]Instance, error)

type FileSessionResolver

type FileSessionResolver struct {
	HomeDir string
}

FileSessionResolver reads session info from ~/.claude/sessions/<PID>.json.

func (FileSessionResolver) ResolveSessionID

func (r FileSessionResolver) ResolveSessionID(pid int) (string, error)

type FileWriter

type FileWriter interface {
	MkdirAll(path string, perm os.FileMode) error
	WriteFile(name string, data []byte, perm os.FileMode) error
	ReadFile(name string) ([]byte, error)
}

FileWriter abstracts filesystem operations for testability.

type HostFinder

type HostFinder struct {
	Runner           CommandRunner
	HomeDir          string           // override for testing; empty uses os.UserHomeDir result passed externally
	CwdResolver      CwdResolver      // nil defaults to ProcCwdResolver
	ContainerChecker ContainerChecker // nil defaults to ProcContainerChecker
	SessionResolver  SessionResolver  // nil defaults to FileSessionResolver{HomeDir: h.HomeDir}
	CommChecker      CommChecker      // nil defaults to verifyProcComm
	PPIDResolver     PPIDResolver     // nil defaults to ProcPPIDResolver
}

HostFinder discovers Claude Code instances on the local host via pgrep.

func (*HostFinder) FindInstances

func (h *HostFinder) FindInstances(ctx context.Context) ([]Instance, error)

type Instance

type Instance struct {
	Label           string      // e.g. "Host (PID 7046)" or `Container "dev-myapp" (abc123)`
	Source          string      // "host" or "container"
	Walker          DirWalker   // how to read its JSONL data
	Root            string      // JSONL root path (or virtual path for containers)
	Memory          *MemoryInfo // memory usage (containers only)
	ContainerID     string      // full Docker container ID (containers only)
	PID             int         // host PID of the claude process (0 for containers)
	Cwd             string      // working directory of the Claude process
	FilePath        string      // resolved JSONL path for fsnotify (host instances only)
	ProxyConfigured bool        // true if the instance is configured to use the daemon's HTTPS proxy
	DaemonConnected bool        // true if the instance has recently communicated with the daemon
}

Instance represents a discovered Claude Code instance.

type InstanceFinder

type InstanceFinder interface {
	FindInstances(ctx context.Context) ([]Instance, error)
}

InstanceFinder discovers running Claude Code instances.

type InstanceState

type InstanceState int

InstanceState represents whether a Claude Code instance is busy or ready.

const (
	StateUnknown InstanceState = iota
	StateBusy
	StateReady
	StateBlocked // waiting for permission approval
	StateWaiting // waiting for user input (AskUserQuestion, ExitPlanMode)
	StateError   // stopped due to API error or failure
	StateConfirm // waiting for destructive operation confirmation
)

func (InstanceState) String

func (s InstanceState) String() string

type InstanceUsage

type InstanceUsage struct {
	Instance Instance
	Summary  *UsageSummary
	State    InstanceState
}

InstanceUsage pairs an Instance with its calculated usage.

func CollectInstanceUsage

func CollectInstanceUsage(instances []Instance, now time.Time) []InstanceUsage

CollectInstanceUsage calculates usage for each instance and returns results.

type MemoryInfo

type MemoryInfo struct {
	Usage uint64 // current memory usage in bytes
	Limit uint64 // memory limit in bytes (0 = unlimited)
}

MemoryInfo holds memory usage and limit for a container.

type ModelUsage

type ModelUsage struct {
	InputTokens  int
	OutputTokens int
	CacheCreate  int
	CacheRead    int
}

ModelUsage holds aggregated token counts for one model class.

func (*ModelUsage) Total

func (mu *ModelUsage) Total() int

Total returns the sum of all token fields.

type OSCommandRunner

type OSCommandRunner struct{}

OSCommandRunner implements CommandRunner using os/exec.

func (OSCommandRunner) Run

func (OSCommandRunner) Run(ctx context.Context, name string, args ...string) ([]byte, error)

type OSDirWalker

type OSDirWalker struct{}

OSDirWalker implements DirWalker using the real filesystem.

func (OSDirWalker) WalkJSONL

func (OSDirWalker) WalkJSONL(root string, fn func(line []byte) error) error

type OSFileWriter

type OSFileWriter struct{}

OSFileWriter implements FileWriter using the os package.

func (OSFileWriter) MkdirAll

func (OSFileWriter) MkdirAll(path string, perm os.FileMode) error

func (OSFileWriter) ReadFile

func (OSFileWriter) ReadFile(name string) ([]byte, error)

func (OSFileWriter) WriteFile

func (OSFileWriter) WriteFile(name string, data []byte, perm os.FileMode) error

type OSProcessLister

type OSProcessLister struct {
	Runner CommandRunner
}

OSProcessLister implements ProcessLister using ps.

func (*OSProcessLister) ListProcesses

func (l *OSProcessLister) ListProcesses(ctx context.Context) ([]ProcessInfo, error)

ListProcesses returns all processes with their PID, PPID, command name, and args.

type OSTmuxClient

type OSTmuxClient struct {
	Runner CommandRunner
}

OSTmuxClient implements TmuxClient using the real tmux command.

func (*OSTmuxClient) ListPanes

func (c *OSTmuxClient) ListPanes(ctx context.Context) ([]TmuxPane, error)

ListPanes runs tmux list-panes and parses the output.

type PPIDResolver

type PPIDResolver interface {
	ResolvePPID(pid int) int
}

PPIDResolver resolves the parent PID for a process.

type ProcContainerChecker

type ProcContainerChecker struct{}

ProcContainerChecker reads /proc/<pid>/cgroup to detect containerized processes.

func (ProcContainerChecker) IsContainerized

func (ProcContainerChecker) IsContainerized(pid int) bool

type ProcCwdResolver

type ProcCwdResolver struct{}

ProcCwdResolver reads /proc/<pid>/cwd (Linux).

func (ProcCwdResolver) ResolveCwd

func (ProcCwdResolver) ResolveCwd(pid int) (string, error)

type ProcPPIDResolver

type ProcPPIDResolver struct{}

ProcPPIDResolver reads /proc/<pid>/status to get the parent PID.

func (ProcPPIDResolver) ResolvePPID

func (ProcPPIDResolver) ResolvePPID(pid int) int

type ProcessInfo

type ProcessInfo struct {
	PID  int
	PPID int
	Comm string
	Args string // full command line (may be empty)
}

ProcessInfo holds PID, parent PID, command name, and full argument line.

type ProcessLister

type ProcessLister interface {
	ListProcesses(ctx context.Context) ([]ProcessInfo, error)
}

ProcessLister abstracts listing all processes with PID, PPID, and command info.

type SessionResolver

type SessionResolver interface {
	ResolveSessionID(pid int) (string, error)
}

SessionResolver resolves the session ID for a Claude process.

type TmuxClient

type TmuxClient interface {
	ListPanes(ctx context.Context) ([]TmuxPane, error)
}

TmuxClient abstracts listing tmux panes for testability.

type TmuxPane

type TmuxPane struct {
	PID          int
	SessionName  string
	WindowIndex  int
	PaneIndex    int
	Cwd          string        // pane working directory
	Devcontainer bool          // true when claude runs inside a devcontainer in this pane
	ContainerID  string        // matched container ID (only set when Devcontainer is true)
	ClaudePID    int           // PID of the actual claude process (0 if unknown)
	State        InstanceState // busy/ready/unknown
}

TmuxPane represents a tmux pane with an active Claude process.

func FindClaudePanes

func FindClaudePanes(ctx context.Context, client TmuxClient, lister ProcessLister, claudeContainerIDs []string) ([]TmuxPane, error)

FindClaudePanes discovers tmux panes that have a Claude process running in them. It lists all tmux panes, builds a process tree from ps output, and checks each pane's descendant processes for a "claude" command or a "docker exec" into a container known to run Claude (identified by claudeContainerIDs).

type UsageSummary

type UsageSummary struct {
	Models map[string]*ModelUsage
}

UsageSummary holds the full usage breakdown for the current window.

func CalculateUsage

func CalculateUsage(walker DirWalker, root string, now time.Time) (*UsageSummary, error)

CalculateUsage scans JSONL files under root and returns usage broken down by model.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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