Documentation
¶
Overview ¶
Package monitor loads, merges, and aggregates agent session data from multiple sources (v2 file store, v1 SQLite, IDE sessions, hook logs) and presents it via TUI or JSON output.
Index ¶
- Constants
- func AggregateToolsFromTimeline(sessions []SessionDetail) ([]ToolDetail, []ToolMetric)
- func CanonicalToolNameForAggregation(name string) string
- func DiffLineCounts(fc FileChange) (adds, dels int, ok bool)
- func FormatDuration(d time.Duration) string
- func HasShellEvent(s SessionDetail) bool
- func LoadAll(ctx context.Context, sessionsDir, hookLogsDir, ideBaseDir, sqliteDBPath string, ...) ([]MergedRecord, *SessionCache, error)
- func LoadIDEExecutions(ctx context.Context, ideBaseDir string, executionIDs map[string]struct{}) (map[string]IDEExecutionResult, error)
- func LoadSessions(ctx context.Context, sessionsDir string, since time.Time, cwdFilter string, ...) ([]ParsedSession, *SessionCache, error)
- func MergeSessionDetails(details []SessionDetail) (SessionDetail, []AgentRef)
- func NewModel(ctx context.Context, sessionsDir, hookLogsDir, ideBaseDir, cwdFilter string, ...) *model
- func ParseDuration(s string) (time.Duration, error)
- func RunJSON(ctx context.Context, ...) error
- func RunTUI(ctx context.Context, ...) error
- func RunTUIWithKiroUsage(ctx context.Context, ...) error
- type AgentDetail
- type AgentMetric
- type AgentRef
- type AssistantData
- type Column
- type ContentItem
- type ConversationMetadata
- type DetailedMetrics
- type EventEntry
- type FileChange
- type HookRecord
- type HourlyMetric
- type IDEAction
- type IDEExecutionEntry
- type IDEExecutionIndex
- type IDEExecutionLog
- type IDEExecutionResult
- type IDEHistoryEntry
- type IDEMessage
- type IDEParsedSession
- type IDESessionEntry
- type IDESessionHistory
- type IDEUsageEntry
- type JSONDuration
- type KiroUsageReadFunc
- type MergedRecord
- func AppendIDEHookRecords(records []MergedRecord, sessions []IDEParsedSession, hooks []HookRecord) []MergedRecord
- func BuildIDEMergedRecords(sessions []IDEParsedSession, execResults map[string]IDEExecutionResult) []MergedRecord
- func MergeSessions(sessions []ParsedSession, hookLogs []HookRecord) []MergedRecord
- type MeteringEntry
- type Metrics
- type ParsedSession
- type PathGroup
- type PatternCount
- type PromptData
- type PromptMeta
- type SQLiteCache
- type SessionCache
- type SessionDetail
- type SessionMessage
- type SessionMeta
- type SessionMetric
- type SessionState
- type SessionToolSummary
- type SkillUsage
- type SubAgentCall
- type TimeseriesPoint
- type ToolAliasMetric
- type ToolCall
- type ToolDetail
- type ToolMetric
- type ToolResultData
- type ToolUseData
- type TurnDuration
- type UserTurnMetadata
Constants ¶
const ( ActionReadFiles = "readFiles" ActionRunCommand = "runCommand" ActionWrite = "write" ActionCreate = "create" ActionDelete = "delete" ActionSearch = "search" ActionInvokeSubAgent = "invokeSubAgent" ActionSubAgentResponse = "subagentResponse" // ToolNameShell is the display name for ActionRunCommand. ToolNameShell = "shell" )
IDE action type constants (wire format values from IDE execution logs).
const ( RecordKindPrompt = "prompt" RecordKindToolUse = "toolUse" RecordKindToolResult = "toolResult" RecordKindAssistantText = "assistantText" RecordKindSessionMeta = "sessionMeta" RecordKindAgentSpawn = "agentSpawn" RecordKindStop = "stop" RecordKindHookEvent = "hookEvent" )
Kind values of MergedRecord. These are internal but flow into aggregation and WebUI payloads; wire-format stability is desirable. RecordKind* values use camelCase to match the JSONL record format (wire format; do not change).
const ( MessageKindPrompt = "Prompt" MessageKindAssistantMessage = "AssistantMessage" MessageKindToolResults = "ToolResults" )
SessionMessage.Kind values (wire format from Kiro; do not change).
const ( ContentKindText = "text" ContentKindJSON = "json" ContentKindToolUse = "toolUse" ContentKindToolResult = "toolResult" )
ContentItem.Kind values (wire format from Kiro; do not change).
const ( ToolStatusSuccess = "success" ToolStatusError = "error" )
ToolResultData.Status values (wire format from Kiro).
const ( CommandCreate = "create" CommandStrReplace = "strReplace" CommandInsert = "insert" CommandDelete = "delete" )
FileChange command constants.
Variables ¶
This section is empty.
Functions ¶
func AggregateToolsFromTimeline ¶
func AggregateToolsFromTimeline(sessions []SessionDetail) ([]ToolDetail, []ToolMetric)
AggregateToolsFromTimeline recomputes per-tool details and overview metrics from a subset of SessionDetails. Used by API filters (by session/agent) to produce Tools data consistent with the filtered session set.
Each SessionDetail's Timeline is walked: preToolUse events increment CallCount, flagged IsError events increment ErrorCount (and append to Errors), and matched pairs (with non-zero Duration on the preToolUse entry) append to RecentCalls. Session and Agent attribution on each ToolCall is taken from the enclosing SessionDetail, since EventEntry does not preserve those fields.
Skills are not re-aggregated here (raw Record access is required) and must be populated separately.
func CanonicalToolNameForAggregation ¶ added in v0.11.2
CanonicalToolNameForAggregation returns the canonical aggregation name for a known exact alias, or name unchanged when no exact alias match exists.
func DiffLineCounts ¶ added in v0.6.0
func DiffLineCounts(fc FileChange) (adds, dels int, ok bool)
DiffLineCounts returns the number of added and deleted lines for a FileChange. ok=false when counts cannot be computed (Oversized, non-UTF8, unknown command).
func FormatDuration ¶
FormatDuration formats d as "-" for missing/zero durations, then as "500ms", "12s", "1m03s", "1h02m", or "2d3h".
func HasShellEvent ¶ added in v0.5.0
func HasShellEvent(s SessionDetail) bool
HasShellEvent reports whether the session used any shell tool invocation. The result is precomputed during aggregation; this wrapper exists for template function registration in serve/templates.go.
func LoadAll ¶ added in v0.7.0
func LoadAll(ctx context.Context, sessionsDir, hookLogsDir, ideBaseDir, sqliteDBPath string, since time.Time, cwdFilter string, cache *SessionCache, sqliteCache *SQLiteCache) ([]MergedRecord, *SessionCache, error)
LoadAll loads sessions + hook logs, merges them, and returns MergedRecords. hookLogsDir may be empty or non-existent (sessions-only mode). ideBaseDir, when non-empty, loads IDE sessions and appends them. sqliteDBPath, when non-empty, loads v1 SQLite sessions and merges them (v2 priority). cwdFilter limits sessions to those whose cwd starts with the given path; empty means no filter (global mode). cache and sqliteCache may be nil (no caching). Returns a new cache for reuse.
func LoadIDEExecutions ¶ added in v0.8.0
func LoadIDEExecutions(ctx context.Context, ideBaseDir string, executionIDs map[string]struct{}) (map[string]IDEExecutionResult, error)
LoadIDEExecutions scans ideBaseDir for profileHash directories and aggregates execution logs matching the given executionIDs set. Returns a map keyed by chatSessionId.
func LoadSessions ¶ added in v0.7.0
func LoadSessions(ctx context.Context, sessionsDir string, since time.Time, cwdFilter string, cache *SessionCache) ([]ParsedSession, *SessionCache, error)
LoadSessions scans sessionsDir for .json metadata files, filters by updated_at >= since and optionally by cwd prefix, and parses the corresponding .jsonl for matching sessions. cwdFilter limits to sessions whose cwd starts with the given path; empty means no filter. cache may be nil (no caching). Returns a fresh *SessionCache that callers should pass on the next invocation. The caller is responsible for serializing LoadSessions calls that share the same cache pointer; see SessionCache documentation.
func MergeSessionDetails ¶
func MergeSessionDetails(details []SessionDetail) (SessionDetail, []AgentRef)
MergeSessionDetails merges all SessionDetail entries sharing the same ID into a single synthetic SessionDetail and returns the agents participating in the sid (in input order). Entries with a differing ID are ignored.
Merge rules (see plan §D2):
- ID = first element's ID
- Agent = "(all)"
- AgentKey = ID + "|(all)"
- Title = first non-empty Title by LastActivity desc
- StartTime = min, EndTime / LastActivity = max
- Duration = EndTime - StartTime
- Active = any input Active
- ToolCalls = sum, Prompts = sum
- Cwd = most recent (by LastActivity desc) non-empty Cwd
- PromptHistory = concat of all inputs' PromptHistory (each is newest first per-agent), globally sorted newest-first by paired timestamp
- Timeline = concat of all Timelines, stably sorted by Ts ascending
func NewModel ¶
func NewModel(ctx context.Context, sessionsDir, hookLogsDir, ideBaseDir, cwdFilter string, since time.Duration) *model
NewModel creates a new TUI model.
func ParseDuration ¶
ParseDuration parses a duration string with suffix s, m, h, d, or w.
func RunJSON ¶
func RunJSON(ctx context.Context, sessionsDir, logsDir, ideBaseDir, cwdFilter, sqliteDBPath string, since time.Duration, session, agent string, w io.Writer) error
RunJSON loads records, aggregates, optionally filters, and writes JSON to w.
func RunTUI ¶
func RunTUI(ctx context.Context, sessionsDir, hookLogsDir, ideBaseDir, cwdFilter, sqliteDBPath string, since time.Duration) error
RunTUI creates and runs the bubbletea program.
func RunTUIWithKiroUsage ¶ added in v0.12.0
func RunTUIWithKiroUsage(ctx context.Context, sessionsDir, hookLogsDir, ideBaseDir, cwdFilter, sqliteDBPath string, since time.Duration, usageRead KiroUsageReadFunc) error
RunTUIWithKiroUsage creates and runs the bubbletea program with an optional account-level Kiro usage reader.
Types ¶
type AgentDetail ¶
type AgentDetail struct {
AgentMetric
Sessions []SessionMetric // sessions owned by this agent, newest first
ToolSummary []SessionToolSummary // per-tool breakdown, sorted by CallCount desc
ToolErrorCnt int // total error tool calls across all its sessions
}
AgentDetail is the per-agent drill-down payload.
type AgentMetric ¶
type AgentMetric struct {
Name string
SessionCount int
ToolCalls int
Prompts int
FilesChanged int
TotalInputTokens int
TotalOutputTokens int
TotalCredits float64
}
AgentMetric is an overview-level agent activity summary retained for backwards compatibility.
type AgentRef ¶
AgentRef names an agent that participated in a session. URL construction lives in the Web layer; this package stays URL-free.
type AssistantData ¶ added in v0.7.0
type AssistantData struct {
MessageID string `json:"message_id"`
Content []ContentItem `json:"content"`
}
AssistantData is the data field when Kind=="AssistantMessage".
type ContentItem ¶ added in v0.7.0
type ContentItem struct {
Kind string `json:"kind"` // "text", "toolUse", "toolResult"
Data json.RawMessage `json:"data"`
}
ContentItem is one element of a content array.
type ConversationMetadata ¶ added in v0.7.0
type ConversationMetadata struct {
UserTurnMetadatas []UserTurnMetadata `json:"user_turn_metadatas"`
}
ConversationMetadata holds per-turn metadata.
type DetailedMetrics ¶
type DetailedMetrics struct {
Overview Metrics
Sessions []SessionDetail
Agents []AgentDetail
Tools []ToolDetail
Skills []SkillUsage
}
DetailedMetrics is the full aggregation result.
func AggregateDetail ¶
func AggregateDetail(ctx context.Context, records []MergedRecord, now time.Time) (DetailedMetrics, error)
AggregateDetail walks the record stream once and builds everything the TUI needs. Returns ctx.Err() if ctx is cancelled during record processing or session finalization. Returns a zero DetailedMetrics when there are no records.
type EventEntry ¶
type EventEntry struct {
Ts time.Time
Event string // agentSpawn | userPromptSubmit | preToolUse | postToolUse | stop
Tool string
IsError bool // preToolUse without matching postToolUse
ErrorDetail string // exit code + stderr excerpt (max 256 chars), empty if no error
InputSummary string // short human-readable summary of tool_input (preToolUse only)
ToolInput string // full tool input text for expand view
ToolResult string // full tool result text for expand view, when available
Duration JSONDuration // postToolUse.Ts - preToolUse.Ts (preToolUse only, 0 for errors)
// contains filtered or unexported fields
}
EventEntry is one log event for timeline display.
type FileChange ¶ added in v0.5.0
type FileChange struct {
Path string // normalized (filepath.Clean + cwd if relative) at extraction time
Ts time.Time
Command string // "create" | "strReplace" | "insert"
Purpose string // optional, from tool_input.__tool_use_purpose
Content string // for create/insert (empty if Oversized)
OldStr string // for strReplace (empty if Oversized)
NewStr string // for strReplace (empty if Oversized)
Oversized bool // true when any content field was truncated due to size cap
}
FileChange captures a single file modification via the write tool. Diff is NOT stored — rendered on demand by template helper to avoid re-computing on every AggregateDetail call.
type HookRecord ¶ added in v0.7.0
type HookRecord struct {
Ts time.Time `json:"ts"`
Session string `json:"session,omitempty"`
Event string `json:"event,omitempty"`
Agent string `json:"agent,omitempty"`
Tool string `json:"tool,omitempty"`
Cwd string `json:"cwd,omitempty"`
ShellExitStatus string `json:"shell_exit_status,omitempty"`
}
HookRecord is one line of a hook log in the new minimal format.
type HourlyMetric ¶
HourlyMetric is an hourly event count for activity chart display.
type IDEAction ¶ added in v0.8.0
type IDEAction struct {
ActionType string `json:"actionType"`
ActionID string `json:"actionId"`
ActionState string `json:"actionState"` // Success, Accepted, Rejected, Error
EmittedAt int64 `json:"emittedAt"` // unix ms
EndTime int64 `json:"endTime"` // unix ms, optional
ErrorMessage string `json:"errorMessage"`
Input json.RawMessage `json:"input"`
Output json.RawMessage `json:"output"`
EstimatedDuration time.Duration // computed from gap to next action
}
IDEAction is one entry in the actions array of an execution log.
type IDEExecutionEntry ¶ added in v0.8.0
type IDEExecutionEntry struct {
ExecutionID string `json:"executionId"`
Type string `json:"type"` // "chat-agent"
Status string `json:"status"` // "succeed" | "aborted"
StartTime int64 `json:"startTime"` // unix ms
EndTime int64 `json:"endTime"` // unix ms
}
IDEExecutionEntry is one execution in the index.
type IDEExecutionIndex ¶ added in v0.8.0
type IDEExecutionIndex struct {
Executions []IDEExecutionEntry `json:"executions"`
}
IDEExecutionIndex is the top-level structure of {profileHash}/{indexHash}.
type IDEExecutionLog ¶ added in v0.8.0
type IDEExecutionLog struct {
ExecutionID string `json:"executionId"`
WorkflowType string `json:"workflowType"`
Status string `json:"status"`
StartTime int64 `json:"startTime"`
EndTime int64 `json:"endTime"`
ChatSessionID string `json:"chatSessionId"`
Actions []IDEAction `json:"actions"`
UsageSummary []IDEUsageEntry `json:"usageSummary"`
ContextUsagePercentage float64 `json:"contextUsagePercentage"`
}
IDEExecutionLog is the top-level structure of {profileHash}/{sessionHash}/{executionHash}.
type IDEExecutionResult ¶ added in v0.8.0
type IDEExecutionResult struct {
TotalCredits float64
StartTime time.Time
EndTime time.Time
Executions int
ToolCalls int
ToolActions []IDEAction // tool-type actions for timeline
}
IDEExecutionResult holds aggregated execution data for one session.
type IDEHistoryEntry ¶ added in v0.8.0
type IDEHistoryEntry struct {
Message IDEMessage `json:"message"`
ExecutionID string `json:"executionId,omitempty"` // assistant entries only
}
IDEHistoryEntry is one element of the history array.
type IDEMessage ¶ added in v0.8.0
type IDEMessage struct {
Role string `json:"role"` // "user" | "assistant"
Content json.RawMessage `json:"content"` // string or []ContentItem
ID string `json:"id"`
}
IDEMessage is a conversation message.
type IDEParsedSession ¶ added in v0.8.0
type IDEParsedSession struct {
SessionID string
Title string
WorkspaceDirectory string
CreatedAt time.Time
ExecutionIDs []string
Prompts int // number of user turns
PromptTexts []string
}
IDEParsedSession is the parsed result of one IDE session.
func LoadIDESessions ¶ added in v0.8.0
func LoadIDESessions(ctx context.Context, ideBaseDir string, since time.Time, cwdFilter string) ([]IDEParsedSession, error)
LoadIDESessions scans ideBaseDir/workspace-sessions, filters by since and cwdFilter, and returns parsed sessions with their executionId lists. Returns nil, nil if ideBaseDir is empty or does not exist.
type IDESessionEntry ¶ added in v0.8.0
type IDESessionEntry struct {
SessionID string `json:"sessionId"`
Title string `json:"title"`
DateCreated string `json:"dateCreated"` // unix ms as string
WorkspaceDirectory string `json:"workspaceDirectory"`
}
IDESessionEntry is one entry in workspace-sessions/{base64}/sessions.json.
type IDESessionHistory ¶ added in v0.8.0
type IDESessionHistory struct {
History []IDEHistoryEntry `json:"history"`
}
IDESessionHistory is the top-level structure of {sessionId}.json.
type IDEUsageEntry ¶ added in v0.8.0
type IDEUsageEntry struct {
Unit string `json:"unit"` // "credit"
Usage float64 `json:"usage"`
UsedTools []string `json:"usedTools,omitempty"`
}
IDEUsageEntry is one entry in usageSummary.
type JSONDuration ¶
JSONDuration wraps time.Duration for human-readable JSON serialization.
func (JSONDuration) MarshalJSON ¶
func (d JSONDuration) MarshalJSON() ([]byte, error)
func (JSONDuration) String ¶
func (d JSONDuration) String() string
String returns the Go standard duration string (e.g. "5m0s") so templates render it as a readable value instead of the underlying int64 nanoseconds.
func (*JSONDuration) UnmarshalJSON ¶
func (d *JSONDuration) UnmarshalJSON(b []byte) error
type KiroUsageReadFunc ¶ added in v0.12.0
KiroUsageReadFunc reads optional account-level Kiro usage. ok=false means usage is unavailable and should be omitted from the TUI.
type MergedRecord ¶ added in v0.7.0
type MergedRecord struct {
// sessions-derived
SessionID string
Kind string // "prompt", "toolUse", "toolResult", "assistantText"
EventName string // raw lifecycle hook event name for Kind=="hookEvent"
ToolUseID string // toolUse/toolResult pairing
ToolName string
ToolInput json.RawMessage // raw JSON from toolUse.input
ToolStatus string // toolResult status ("success"/"error")
ErrorDetail string // toolResult status=="error": content[0].data
ToolResult string // toolResult content/output when available
ActionState string // IDE action state, when available
PromptText string
AssistantText string
TurnResponse string // final assistant text for the preceding turn (file-order)
PromptTs time.Time // Prompt.meta.timestamp (unix seconds)
// hook-supplemented (zero if no hook match)
PreToolTs time.Time
PostToolTs time.Time
Agent string
ShellExitStatus string
// sessions meta-derived
Title string
Cwd string
CreatedAt time.Time
UpdatedAt time.Time
// sessions meta-derived (token/credit totals, emitted once per session as Kind=="sessionMeta")
TotalInputTokens int
TotalOutputTokens int
TotalCredits float64
// IDE-only: pre-aggregated counts (CLI derives these from individual records)
PromptTexts []string
ToolCalls int
// sub-agent invocation data (IDE invokeSubAgent or CLI use_subagent records)
SubAgent *SubAgentCall
SubAgents []SubAgentCall
}
MergedRecord combines sessions (primary) and hook log (supplementary) data for one event.
func AppendIDEHookRecords ¶ added in v0.11.0
func AppendIDEHookRecords(records []MergedRecord, sessions []IDEParsedSession, hooks []HookRecord) []MergedRecord
AppendIDEHookRecords folds minimal IDE hook records into IDE session and execution records. Hook logs provide lifecycle timestamps only; prompts, tool inputs, and tool results remain sourced from IDE session/execution logs.
func BuildIDEMergedRecords ¶ added in v0.8.0
func BuildIDEMergedRecords(sessions []IDEParsedSession, execResults map[string]IDEExecutionResult) []MergedRecord
BuildIDEMergedRecords combines IDEParsedSession list with execution results into MergedRecord slices (Kind="sessionMeta"). A record is always generated even when TotalCredits is zero.
func MergeSessions ¶ added in v0.7.0
func MergeSessions(sessions []ParsedSession, hookLogs []HookRecord) []MergedRecord
MergeSessions merges ParsedSession slices with hook log records into MergedRecord slices. When hookLogs is nil or empty, sessions-only mode is used and hook fields are zero values.
type MeteringEntry ¶ added in v0.7.0
MeteringEntry is one metering value with a unit.
type Metrics ¶
type Metrics struct {
Sessions []SessionMetric
Tools []ToolMetric
Agents []AgentMetric
HourlyActivity []HourlyMetric
}
Metrics is the aggregated overview metrics retained for backwards compatibility.
type ParsedSession ¶ added in v0.7.0
type ParsedSession struct {
Meta SessionMeta
Messages []SessionMessage
}
ParsedSession holds the metadata and messages for one session.
func LoadSessionsSQLite ¶ added in v0.9.0
func LoadSessionsSQLite(ctx context.Context, dbPath string, since time.Time, cwdFilter string) ([]ParsedSession, error)
LoadSessionsSQLite reads sessions from a v1 SQLite database. Returns empty slice (no error) if dbPath is empty or the file does not exist.
type PathGroup ¶ added in v0.8.0
type PathGroup struct {
Path string
Edits []FileChange
LastTs time.Time
TotalAdds int
TotalDels int
OversizedCount int
}
PathGroup holds aggregated change data for a single file path, ready for rendering.
type PatternCount ¶
type PatternCount struct {
Summary string `json:"summary"`
Count int `json:"count"`
LastTs time.Time `json:"lastTs"`
}
PatternCount is one InputSummary pattern with its call count.
func AggregateToolInputPatterns ¶
func AggregateToolInputPatterns(calls []ToolCall, topN int) []PatternCount
AggregateToolInputPatterns groups calls by InputSummary and returns the top-N sorted by Count desc, LastTs desc, Summary asc.
type PromptData ¶ added in v0.7.0
type PromptData struct {
MessageID string `json:"message_id"`
Content []ContentItem `json:"content"`
Meta PromptMeta `json:"meta"`
}
PromptData is the data field when Kind=="Prompt".
type PromptMeta ¶ added in v0.7.0
type PromptMeta struct {
Timestamp int64 `json:"timestamp"` // unix seconds
AdditionalContext string `json:"additionalContext,omitempty"`
}
PromptMeta holds per-message metadata for a Prompt.
type SQLiteCache ¶ added in v0.9.0
type SQLiteCache struct {
// contains filtered or unexported fields
}
SQLiteCache caches v1 SQLite sessions, invalidated by file mtime.
func NewSQLiteCache ¶ added in v0.9.0
func NewSQLiteCache() *SQLiteCache
NewSQLiteCache returns an initialized *SQLiteCache.
func (*SQLiteCache) Load ¶ added in v0.9.0
func (c *SQLiteCache) Load(ctx context.Context, dbPath string) ([]ParsedSession, error)
Load returns cached v1 sessions, re-reading only when the DB file mtime changes. Returns ALL sessions (unfiltered). Caller applies since/cwdFilter post-cache.
type SessionCache ¶ added in v0.7.0
type SessionCache struct {
// contains filtered or unexported fields
}
SessionCache caches parsed session files keyed by path, invalidated by mtime+size. It is populated by LoadSessions, which returns a new *SessionCache; callers pass the returned cache back on the next call to reuse parse results.
Concurrency: a single *SessionCache must not be shared by concurrent LoadSessions calls. The serve package synchronizes calls through golang.org/x/sync/singleflight (see internal/serve/server.go loadMetrics). The internal mu field guards the short window where LoadSessions snapshots the previous cache into local variables, but callers must not rely on it for higher-level coordination.
func NewSessionCache ¶ added in v0.7.0
func NewSessionCache() *SessionCache
NewSessionCache returns an initialized *SessionCache.
type SessionDetail ¶
type SessionDetail struct {
SessionMetric
HasShell bool // true if any timeline entry used the shell tool
PromptHistory []string // raw prompts, oldest first
Timeline []EventEntry // full ordered event list for this session
ToolSummary []SessionToolSummary // per-tool breakdown, sorted by CallCount desc
AssistantResponse string // LLM final response from stop event (max 2KB); kept for backward compat
AssistantResponses []string // all assistant responses per turn, oldest first
Changes []FileChange // chronological order (sorted by Ts ascending)
SubAgentCalls []SubAgentCall // IDE sub-agent invocations
}
SessionDetail is the per-session drill-down payload.
type SessionMessage ¶ added in v0.7.0
type SessionMessage struct {
Version string `json:"version"`
Kind string `json:"kind"` // "Prompt", "AssistantMessage", "ToolResults"
Data json.RawMessage `json:"data"`
}
SessionMessage is one line of a sessions .jsonl file.
func ParseSessionJSONL ¶ added in v0.7.0
func ParseSessionJSONL(r io.Reader) ([]SessionMessage, int, error)
ParseSessionJSONL reads a sessions .jsonl file and returns the parsed messages. Unknown kind values and malformed lines are silently skipped; skipped counts the number of skipped lines.
type SessionMeta ¶ added in v0.7.0
type SessionMeta struct {
SessionID string `json:"session_id"`
Title string `json:"title"`
Cwd string `json:"cwd"`
CreatedAt rfc3339Time `json:"created_at"`
UpdatedAt rfc3339Time `json:"updated_at"`
SessionState SessionState `json:"session_state"`
}
SessionMeta is the top-level structure of a {uuid}.json file.
func ParseSessionMeta ¶ added in v0.7.0
func ParseSessionMeta(r io.Reader) (SessionMeta, error)
ParseSessionMeta reads a {uuid}.json file and returns the parsed SessionMeta.
type SessionMetric ¶
type SessionMetric struct {
ID string
AgentKey string // composite key sid + "|" + agent; unique per (session, agent)
Agent string
Title string // first userPromptSubmit prompt, cleaned; may be empty
Cwd string
StartTime time.Time
EndTime time.Time
LastActivity time.Time
Duration JSONDuration
Active bool // last event within 5min of now
ToolCalls int
Prompts int
FilesChanged int
TotalInputTokens int // sessions meta derived
TotalOutputTokens int // sessions meta derived
TotalCredits float64 // sessions meta derived (metering_usage sum)
TurnDurationSecs float64 // sessions meta derived (turn_duration sum)
}
SessionMetric is an overview-level session summary retained for backwards compatibility.
type SessionState ¶ added in v0.7.0
type SessionState struct {
AgentName string `json:"agent_name"`
ConversationMetadata ConversationMetadata `json:"conversation_metadata"`
}
SessionState holds agent and conversation metadata.
type SessionToolSummary ¶
type SessionToolSummary struct {
Tool string
CallCount int
ErrorCount int
SuccessRate float64 // (CallCount - ErrorCount) / CallCount
AvgDuration JSONDuration
}
SessionToolSummary is a per-tool breakdown within a single session.
type SkillUsage ¶
SkillUsage counts how many times a skill's SKILL.md was read.
type SubAgentCall ¶ added in v0.8.0
type SubAgentCall struct {
AgentName string
Explanation string
Prompt string
Response string
Duration JSONDuration
Ts time.Time
}
SubAgentCall represents a sub-agent invocation from an IDE session.
type TimeseriesPoint ¶
type TimeseriesPoint struct {
Bucket time.Time `json:"bucket"`
Count int `json:"count"`
AvgDuration JSONDuration `json:"avgDuration"`
ErrorCount int `json:"errorCount"`
}
TimeseriesPoint is one time-bucket of aggregated tool calls.
func AggregateToolTimeseries ¶
func AggregateToolTimeseries(calls []ToolCall, now time.Time) []TimeseriesPoint
AggregateToolTimeseries groups calls into time buckets (1min if window ≤ 2h, else 5min). Returns nil if fewer than 2 distinct buckets.
type ToolAliasMetric ¶ added in v0.11.2
ToolAliasMetric summarizes one observed raw alias within a tool detail.
type ToolCall ¶
type ToolCall struct {
Ts time.Time // preToolUse timestamp
Session string
Agent string
Tool string
Duration JSONDuration // postToolUse.Ts - preToolUse.Ts (0 for errors)
IsError bool // no matching postToolUse
InputSummary string // short human-readable summary of tool_input
ToolInput string // full tool input text
}
ToolCall is one completed tool invocation (preToolUse matched with postToolUse) or an unmatched preToolUse marked as error.
type ToolDetail ¶
type ToolDetail struct {
ToolMetric
AvgDuration JSONDuration // average pre→post across matched calls
Aliases []ToolAliasMetric
RecentCalls []ToolCall // newest first, matched calls with duration
Errors []ToolCall // unmatched preToolUse samples
}
ToolDetail is the per-tool drill-down payload.
type ToolMetric ¶
type ToolMetric struct {
Name string
CallCount int
ErrorCount int // preToolUse without matching postToolUse, or non-zero exit_status
ErrorRate float64
}
ToolMetric is an overview-level tool usage summary retained for backwards compatibility.
type ToolResultData ¶ added in v0.7.0
type ToolResultData struct {
ToolUseID string `json:"toolUseId"`
Content []ContentItem `json:"content"`
Status string `json:"status"` // "success" or "error"
}
ToolResultData is ContentItem.Data when Kind=="toolResult".
type ToolUseData ¶ added in v0.7.0
type ToolUseData struct {
ToolUseID string `json:"toolUseId"`
Name string `json:"name"`
Input json.RawMessage `json:"input"`
}
ToolUseData is ContentItem.Data when Kind=="toolUse".
type TurnDuration ¶ added in v0.7.0
TurnDuration is a duration split into seconds and nanoseconds.
type UserTurnMetadata ¶ added in v0.7.0
type UserTurnMetadata struct {
TurnDuration TurnDuration `json:"turn_duration"`
EndTimestamp string `json:"end_timestamp,omitempty"`
EndReason string `json:"end_reason,omitempty"`
InputTokenCount int `json:"input_token_count"`
OutputTokenCount int `json:"output_token_count"`
ContextUsagePct float64 `json:"context_usage_percentage"`
MeteringUsage []MeteringEntry `json:"metering_usage"`
}
UserTurnMetadata holds metrics for one user turn.
Source Files
¶
- aggregate.go
- changes.go
- classify.go
- doc.go
- duration.go
- events.go
- format.go
- ide_executions.go
- ide_hooks.go
- ide_sessions.go
- ide_types.go
- json.go
- json_output.go
- list_view.go
- merge.go
- parse.go
- session_store.go
- session_store_sqlite.go
- sessions.go
- shell_event.go
- slices.go
- store.go
- summary_formatters.go
- tui.go
- tui_views.go
- tui_views_agents.go
- tui_views_overview.go
- tui_views_sessions.go
- tui_views_tools.go
- types.go
- v1_convert.go
- v1_types.go