platform

package
v0.0.12 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GenAIOperationName    = attribute.Key("gen_ai.operation.name")
	GenAISystem           = attribute.Key("gen_ai.system")
	GenAIRequestModel     = attribute.Key("gen_ai.request.model")
	GenAIProviderName     = attribute.Key("gen_ai.provider.name")
	GenAIResponseModel    = attribute.Key("gen_ai.response.model")
	GenAIResponseID       = attribute.Key("gen_ai.response.id")
	GenAIFinishReasons    = attribute.Key("gen_ai.response.finish_reasons")
	GenAIInputTokens      = attribute.Key("gen_ai.usage.input_tokens")
	GenAIOutputTokens     = attribute.Key("gen_ai.usage.output_tokens")
	GenAICacheCreate      = attribute.Key("gen_ai.usage.cache_creation.input_tokens")
	GenAICacheRead        = attribute.Key("gen_ai.usage.cache_read.input_tokens")
	GenAIToolName         = attribute.Key("gen_ai.tool.name")
	GenAIToolCallID       = attribute.Key("gen_ai.tool.call.id")
	GenAIToolType         = attribute.Key("gen_ai.tool.type")
	GenAIAgentName        = attribute.Key("gen_ai.agent.name")
	GenAIAgentID          = attribute.Key("gen_ai.agent.id")
	GenAISessionID        = attribute.Key("gen_ai.session.id")
	GenAIToolParentCallID = attribute.Key("gen_ai.tool.parent_call.id")
	GenAIToolInput        = attribute.Key("gen_ai.tool.input")
	GenAIToolOutput       = attribute.Key("gen_ai.tool.output")
)

GenAI semantic convention attribute keys. See: https://opentelemetry.io/docs/specs/semconv/gen-ai/

View Source
const (
	WeaveThreadID  = attribute.Key("wandb.thread_id")
	WeaveIsTurn    = attribute.Key("wandb.is_turn")
	WeaveInputVal  = attribute.Key("input.value")
	WeaveOutputVal = attribute.Key("output.value")
)

Weave thread attribute keys. See: https://docs.wandb.ai/guides/weave/guides/tracking/tracing/#organize-traces-into-threads

View Source
const DefaultContextBudgetThreshold = 20000

DefaultContextBudgetThreshold is the default warning threshold in estimated tokens. 20K tokens leaves reasonable headroom in a 200K context window.

View Source
const DefaultMaxValueLen = 512

DefaultMaxValueLen is the default truncation limit for raw event values.

Variables

View Source
var ErrCircuitOpen = errors.New("circuit breaker open: rate limit or server error")

ErrCircuitOpen is returned by Allow when the circuit breaker is open due to rate limiting or server errors.

View Source
var Meter metric.Meter = metricnoop.NewMeterProvider().Meter("sightjack")

Meter is the package-level OTel meter. Initialized to noop so library consumers can use sightjack without calling initMeter. The cmd layer replaces this with a recording meter when a metrics endpoint is configured.

View Source
var SkillsFS embed.FS
View Source
var Tracer trace.Tracer = noop.NewTracerProvider().Tracer("sightjack")

Tracer is the package-level OTel tracer. Initialized to noop so library consumers can use sightjack without calling initTracer. The cmd layer replaces this with a recording tracer when an OTLP endpoint is configured.

Functions

func ExpandTilde added in v0.0.4

func ExpandTilde(s string) string

ExpandTilde expands a leading ~ to the user's home directory. Also handles KEY=~/value patterns in environment variable assignments.

func FilterEnv added in v0.0.7

func FilterEnv(env []string, name string) []string

isEnvKey checks if s is a valid environment variable name ([A-Za-z_][A-Za-z0-9_]*). FilterEnv returns a copy of env with all entries matching "name=..." removed. Used to strip environment variables (e.g. CLAUDECODE) before invoking subprocesses.

func FormatRawEvent added in v0.0.3

func FormatRawEvent(eventType, jsonData string, maxValueLen int) string

FormatRawEvent formats a stream event as "type:truncated_json" for storage in the stream.raw_events span attribute.

func GenAIAgentAttrs added in v0.0.3

func GenAIAgentAttrs(agentName, agentID string) []attribute.KeyValue

GenAIAgentAttrs returns span attributes for an invoke_agent child span.

func GenAIResultAttrs

func GenAIResultAttrs(result *StreamMessage, responseModel, responseID string) []attribute.KeyValue

GenAIResultAttrs returns span attributes from a stream-json result message.

func GenAISessionAttrs added in v0.0.3

func GenAISessionAttrs(sessionID string) []attribute.KeyValue

GenAISessionAttrs returns the session ID attribute.

func GenAISpanAttrs

func GenAISpanAttrs(model string) []attribute.KeyValue

GenAISpanAttrs returns the standard GenAI semantic convention attributes for an Anthropic Claude invocation.

func GenAIToolAttrs

func GenAIToolAttrs(toolName, callID string) []attribute.KeyValue

GenAIToolAttrs returns span attributes for a tool_use child span.

func IsNDJSON added in v0.0.7

func IsNDJSON(s string) bool

IsNDJSON returns true if the first non-empty line of s starts with '{', indicating the content is likely NDJSON (newline-delimited JSON).

func IsProcessAlive added in v0.0.7

func IsProcessAlive(pid int) bool

IsProcessAlive checks whether a process with the given PID is still running. On Unix, it sends signal 0 to the process. Returns false for invalid PIDs.

func LookPathShell added in v0.0.4

func LookPathShell(cmdLine string) (string, error)

LookPathShell extracts the binary from a shell-like command string (ignoring leading KEY=VALUE env vars) and runs exec.LookPath on it.

func NewShellCmd added in v0.0.4

func NewShellCmd(ctx context.Context, cmdLine string, args ...string) *exec.Cmd

NewShellCmd creates an exec.Cmd from a command string that may contain leading KEY=VALUE environment variables and tilde paths. Additional args are appended after any args parsed from cmdLine.

func OtelEnvContent

func OtelEnvContent(backend, entity, project string) (string, error)

OtelEnvContent returns the .otel.env file content for the given backend. Supported backends: "jaeger" (local OTLP HTTP), "weave" (Weights & Biases). Empty backend returns empty content (no-op). Unknown backends return an error.

func ParseShellCommand added in v0.0.4

func ParseShellCommand(cmdLine string) (env []string, bin string, extraArgs []string)

ParseShellCommand splits a command string that may contain leading KEY=VALUE environment variables and tilde (~) paths into components.

Example: "CLAUDE_CONFIG_DIR=~/.claude-work-b ~/.local/bin/claude" → env=["CLAUDE_CONFIG_DIR=/Users/x/.claude-work-b"], bin="/Users/x/.local/bin/claude"

func RecordWave

func RecordWave(ctx context.Context, status string)

RecordWave increments the sightjack.wave.total OTel counter.

func RenderArchitectDiscussPrompt

func RenderArchitectDiscussPrompt(lang string, data domain.ArchitectDiscussPromptData) (string, error)

RenderArchitectDiscussPrompt renders the architect discussion prompt for the given language.

func RenderAutoDiscussArchitectPrompt added in v0.0.3

func RenderAutoDiscussArchitectPrompt(lang string, data domain.AutoDiscussArchitectPromptData) (string, error)

RenderAutoDiscussArchitectPrompt renders the auto-discuss architect prompt.

func RenderAutoDiscussDevilsAdvocatePrompt added in v0.0.3

func RenderAutoDiscussDevilsAdvocatePrompt(lang string, data domain.AutoDiscussDevilsAdvocatePromptData) (string, error)

RenderAutoDiscussDevilsAdvocatePrompt renders the auto-discuss Devil's Advocate prompt.

func RenderClassifyPrompt

func RenderClassifyPrompt(lang string, data domain.ClassifyPromptData) (string, error)

RenderClassifyPrompt renders the cluster classification prompt for the given language.

func RenderDeepScanPrompt

func RenderDeepScanPrompt(lang string, data domain.DeepScanPromptData) (string, error)

RenderDeepScanPrompt renders the deep scan prompt for the given language.

func RenderInitConfig

func RenderInitConfig(team, project, lang, strictness string) string

RenderInitConfig generates a minimal config.yaml content string. Only user-specified values are written; remaining fields are filled by DefaultConfig when LoadConfig reads the file.

func RenderNextGenPrompt

func RenderNextGenPrompt(lang string, data domain.NextGenPromptData) (string, error)

RenderNextGenPrompt renders the next-gen wave generation prompt.

func RenderReadyLabelPrompt

func RenderReadyLabelPrompt(lang string, data domain.ReadyLabelPromptData) (string, error)

RenderReadyLabelPrompt renders the ready label prompt for the given language.

func RenderScribeADRPrompt

func RenderScribeADRPrompt(lang string, data domain.ScribeADRPromptData) (string, error)

RenderScribeADRPrompt renders the scribe ADR generation prompt for the given language.

func RenderWaveApplyPrompt

func RenderWaveApplyPrompt(lang string, data domain.WaveApplyPromptData) (string, error)

RenderWaveApplyPrompt renders the wave apply prompt for the given language.

func RenderWaveGeneratePrompt

func RenderWaveGeneratePrompt(lang string, data domain.WaveGeneratePromptData) (string, error)

RenderWaveGeneratePrompt renders the wave generation prompt for the given language.

func SanitizeUTF8 added in v0.0.5

func SanitizeUTF8(s string) string

SanitizeUTF8 replaces invalid UTF-8 bytes with the Unicode replacement character. Use this before passing strings from external sources (Claude output, file system, error messages) to OTel span attributes, which require valid UTF-8.

func SanitizeUTF8Slice added in v0.0.5

func SanitizeUTF8Slice(ss []string) []string

SanitizeUTF8Slice sanitizes each element of a string slice for OTel safety.

func StatusColor added in v0.0.7

func StatusColor(s domain.CheckStatus) string

StatusColor returns the ANSI color code for a doctor check status.

func SummarizeNDJSON added in v0.0.7

func SummarizeNDJSON(s string) string

SummarizeNDJSON returns a human-readable summary indicating the number of non-empty lines in the NDJSON content, directing the user to --verbose.

func SyntheticToolID added in v0.0.3

func SyntheticToolID(seq int) string

SyntheticToolID generates a fallback tool ID when the stream does not provide one.

func TruncateValue added in v0.0.3

func TruncateValue(s string, maxLen int) string

TruncateValue truncates s to maxLen characters, appending "..." if truncated.

func WeaveThreadNestedAttrs added in v0.0.5

func WeaveThreadNestedAttrs(threadID string) []attribute.KeyValue

WeaveThreadNestedAttrs returns Weave thread attributes for a nested (non-turn) span.

func WeaveThreadTurnAttrs added in v0.0.5

func WeaveThreadTurnAttrs(threadID string) []attribute.KeyValue

WeaveThreadTurnAttrs returns Weave thread attributes for a turn (outermost) span.

Types

type AssistantMessage

type AssistantMessage struct {
	ID         string         `json:"id,omitempty"`
	Role       string         `json:"role,omitempty"`
	Model      string         `json:"model,omitempty"`
	Content    []ContentBlock `json:"content,omitempty"`
	StopReason string         `json:"stop_reason,omitempty"`
	Usage      *Usage         `json:"usage,omitempty"`
}

AssistantMessage is the nested message inside SDKAssistantMessage.

type BudgetItem added in v0.0.7

type BudgetItem struct {
	Category string
	Count    int
	Bytes    int // only for hooks
	Tokens   int
	Heaviest bool
}

BudgetItem represents one category in the context budget breakdown.

type BusSubscriber added in v0.0.12

type BusSubscriber struct {
	// contains filtered or unexported fields
}

BusSubscriber receives session stream events from an InProcessSessionBus.

func (*BusSubscriber) C added in v0.0.12

func (s *BusSubscriber) C() <-chan domain.SessionStreamEvent

C returns a read-only channel of events.

func (*BusSubscriber) Close added in v0.0.12

func (s *BusSubscriber) Close()

Close unsubscribes and drains the channel.

type CircuitBreaker added in v0.0.12

type CircuitBreaker struct {
	// contains filtered or unexported fields
}

CircuitBreaker prevents cascading failures when AI coding tool providers hit rate limits or server errors. Provider-agnostic: error classification is handled by domain.ClassifyProviderError before calling RecordProviderError.

func NewCircuitBreaker added in v0.0.12

func NewCircuitBreaker(logger domain.Logger) *CircuitBreaker

NewCircuitBreaker creates a circuit breaker in the closed state.

func (*CircuitBreaker) Allow added in v0.0.12

func (cb *CircuitBreaker) Allow(ctx context.Context) error

Allow checks if a call is permitted. When the circuit is OPEN, it blocks until the reset time or backoff period elapses, then transitions to HALF_OPEN and returns nil. Returns context error if cancelled while waiting.

func (*CircuitBreaker) IsOpen added in v0.0.12

func (cb *CircuitBreaker) IsOpen() bool

IsOpen returns true if the circuit breaker is in the open state.

func (*CircuitBreaker) RecordProviderError added in v0.0.12

func (cb *CircuitBreaker) RecordProviderError(info domain.ProviderErrorInfo)

RecordProviderError updates the circuit breaker state based on a classified provider error. Callers should use domain.ClassifyProviderError to produce the ProviderErrorInfo before calling this method.

func (*CircuitBreaker) RecordSuccess added in v0.0.12

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess resets the circuit breaker to closed state.

func (*CircuitBreaker) ResetAt added in v0.0.12

func (cb *CircuitBreaker) ResetAt() time.Time

ResetAt returns the parsed reset time (zero if unknown).

func (*CircuitBreaker) String added in v0.0.12

func (cb *CircuitBreaker) String() string

String returns a human-readable state description.

type ContentBlock

type ContentBlock struct {
	Type      string          `json:"type"`
	Text      string          `json:"text,omitempty"`
	Thinking  string          `json:"thinking,omitempty"`
	Signature string          `json:"signature,omitempty"`
	ID        string          `json:"id,omitempty"`
	Name      string          `json:"name,omitempty"`
	Input     json.RawMessage `json:"input,omitempty"`
}

ContentBlock represents a content block (text, tool_use, thinking).

type ContextBudgetReport added in v0.0.5

type ContextBudgetReport struct {
	ToolCount        int
	SkillCount       int
	PluginCount      int
	MCPServerCount   int
	HookContextBytes int
	EstimatedTokens  int
}

ContextBudgetReport summarises the estimated context consumption from Claude Code hooks, plugins, skills, and MCP servers.

func CalculateContextBudget added in v0.0.5

func CalculateContextBudget(messages []*StreamMessage) ContextBudgetReport

CalculateContextBudget analyses stream messages to estimate context consumption from init metadata and hook responses.

func (ContextBudgetReport) Attrs added in v0.0.5

Attrs returns OTel span attributes for the context budget report.

func (ContextBudgetReport) DetailedBreakdown added in v0.0.7

func (r ContextBudgetReport) DetailedBreakdown() []BudgetItem

DetailedBreakdown returns per-category token breakdown with heaviest marker.

func (ContextBudgetReport) Exceeds added in v0.0.5

func (r ContextBudgetReport) Exceeds(threshold int) bool

Exceeds returns true if EstimatedTokens exceeds the given threshold.

func (ContextBudgetReport) WarningMessage added in v0.0.5

func (r ContextBudgetReport) WarningMessage(threshold int) string

WarningMessage returns a human-readable warning if the budget exceeds the threshold, or an empty string if within budget.

type InProcessSessionBus added in v0.0.12

type InProcessSessionBus struct {
	// contains filtered or unexported fields
}

InProcessSessionBus is a fan-out pub/sub hub for session stream events. Publish is best-effort with a short timeout per subscriber.

func NewInProcessSessionBus added in v0.0.12

func NewInProcessSessionBus() *InProcessSessionBus

NewInProcessSessionBus creates a new bus.

func (*InProcessSessionBus) Close added in v0.0.12

func (b *InProcessSessionBus) Close()

Close closes all subscriber channels and prevents further publishes.

func (*InProcessSessionBus) Publish added in v0.0.12

Publish sends an event to all subscribers. Non-blocking: if a subscriber channel is full after publishTimeout, the event is dropped for that subscriber. This is an observation stream — drops do not affect domain event persistence.

func (*InProcessSessionBus) Subscribe added in v0.0.12

func (b *InProcessSessionBus) Subscribe(bufSize int) *BusSubscriber

Subscribe creates a new subscriber with a buffered channel.

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger provides structured, timestamped log output. All methods are safe for concurrent use.

func NewLogger

func NewLogger(out io.Writer, verbose bool) *Logger

NewLogger creates a new Logger. If out is nil, io.Discard is used. Color is enabled by default when writing to a terminal and NO_COLOR environment variable is not set.

func (*Logger) Banner added in v0.0.3

func (l *Logger) Banner(dir domain.BannerDirection, kind, name, description string)

Banner prints an inverted-color full-line banner for D-Mail intent logging. SEND uses green inversion, RECV uses cyan inversion. In no-color mode, uses >>> / <<< prefix as fallback.

func (*Logger) Colorize added in v0.0.7

func (l *Logger) Colorize(text, color string) string

Colorize wraps text with the given ANSI color code if color output is enabled. Returns plain text when color is disabled (NO_COLOR env or non-terminal output).

func (*Logger) Debug

func (l *Logger) Debug(format string, args ...any)

Debug prints a debug message only when verbose mode is enabled.

func (*Logger) Error

func (l *Logger) Error(format string, args ...any)

Error prints an error message.

func (*Logger) Header added in v0.0.10

func (l *Logger) Header(toolName, version string)

Header prints a single-line startup header with tool name and version. Uses bold inverted text for maximum visibility.

func (*Logger) Info

func (l *Logger) Info(format string, args ...any)

Info prints an informational message.

func (*Logger) OK

func (l *Logger) OK(format string, args ...any)

OK prints a success message.

func (*Logger) Section added in v0.0.10

func (l *Logger) Section(title string)

Section prints a single-line section separator for phase transitions. Uses blue inverted text.

func (*Logger) SetExtraWriter

func (l *Logger) SetExtraWriter(w io.Writer)

SetExtraWriter sets an additional writer for dual-write logging. The caller is responsible for closing the writer when done. Extra writer always receives plain text (no ANSI color codes).

func (*Logger) SetNoColor added in v0.0.3

func (l *Logger) SetNoColor(v bool)

SetNoColor explicitly enables or disables color output. This overrides the auto-detection performed at construction time.

func (*Logger) Warn

func (l *Logger) Warn(format string, args ...any)

Warn prints a warning message.

func (*Logger) Writer

func (l *Logger) Writer() io.Writer

Writer returns the underlying io.Writer.

type MCPServerInfo added in v0.0.5

type MCPServerInfo struct {
	Name   string `json:"name"`
	Status string `json:"status"`
}

MCPServerInfo represents a connected MCP server from system:init.

type OTelPolicyMetrics

type OTelPolicyMetrics struct{}

OTelPolicyMetrics implements port.PolicyMetrics using OTel counters.

func (*OTelPolicyMetrics) RecordPolicyEvent

func (*OTelPolicyMetrics) RecordPolicyEvent(ctx context.Context, eventType, status string)

type PluginInfo added in v0.0.7

type PluginInfo struct {
	Name string `json:"name"`
	Path string `json:"path,omitempty"`
}

PluginInfo represents a loaded plugin from system:init.

type RateLimitInfo added in v0.0.5

type RateLimitInfo struct {
	Status             string  `json:"status,omitempty"`
	ResetsAt           int64   `json:"resetsAt,omitempty"`
	RateLimitType      string  `json:"rateLimitType,omitempty"`
	Utilization        float64 `json:"utilization,omitempty"`
	IsUsingOverage     bool    `json:"isUsingOverage,omitempty"`
	SurpassedThreshold float64 `json:"surpassedThreshold,omitempty"`
}

RateLimitInfo holds rate limit details from Claude Code rate_limit_event.

type SpanEmittingStreamReader added in v0.0.3

type SpanEmittingStreamReader struct {
	// contains filtered or unexported fields
}

SpanEmittingStreamReader wraps StreamReader to emit OTel child spans for tool_use events in real-time.

func NewSpanEmittingStreamReader added in v0.0.3

func NewSpanEmittingStreamReader(reader *StreamReader, parentCtx context.Context, tracer trace.Tracer) *SpanEmittingStreamReader

NewSpanEmittingStreamReader creates a SpanEmittingStreamReader.

func (*SpanEmittingStreamReader) CollectAll added in v0.0.3

CollectAll reads all messages, emitting tool spans, and returns the result.

func (*SpanEmittingStreamReader) InitAttrs added in v0.0.5

func (s *SpanEmittingStreamReader) InitAttrs() []attribute.KeyValue

InitAttrs returns OTel attributes extracted from the system:init message. Returns nil if no init message was seen.

func (*SpanEmittingStreamReader) RawEvents added in v0.0.3

func (s *SpanEmittingStreamReader) RawEvents() []string

RawEvents returns the collected raw event strings.

func (*SpanEmittingStreamReader) SetInput added in v0.0.5

func (s *SpanEmittingStreamReader) SetInput(prompt string)

SetInput records the prompt text for Weave input.value mapping.

func (*SpanEmittingStreamReader) SetStreamMessageHandler added in v0.0.12

func (s *SpanEmittingStreamReader) SetStreamMessageHandler(fn func(*StreamMessage, json.RawMessage))

SetStreamMessageHandler registers a callback invoked for every parsed stream message. Used by the session event bus for live streaming. Nil by default (no-op).

func (*SpanEmittingStreamReader) WeaveIOAttrs added in v0.0.5

func (s *SpanEmittingStreamReader) WeaveIOAttrs() []attribute.KeyValue

WeaveIOAttrs returns Weave I/O attributes (input.value and output.value).

func (*SpanEmittingStreamReader) WeaveThreadAttrs added in v0.0.5

func (s *SpanEmittingStreamReader) WeaveThreadAttrs() []attribute.KeyValue

WeaveThreadAttrs returns Weave thread attributes for the parent (turn) span. The thread_id is derived from the Claude session_id seen in the stream.

type StreamMessage

type StreamMessage struct {
	Type            string          `json:"type"`
	Subtype         string          `json:"subtype,omitempty"`
	UUID            string          `json:"uuid,omitempty"`
	SessionID       string          `json:"session_id,omitempty"`
	Message         json.RawMessage `json:"message,omitempty"`
	Result          string          `json:"result,omitempty"`
	Usage           *Usage          `json:"usage,omitempty"`
	TotalCost       float64         `json:"total_cost_usd,omitempty"`
	NumTurns        int             `json:"num_turns,omitempty"`
	Duration        int64           `json:"duration_ms,omitempty"`
	IsError         bool            `json:"is_error,omitempty"`
	StopReason      string          `json:"stop_reason,omitempty"`
	ToolUseID       string          `json:"tool_use_id,omitempty"`
	ParentToolUseID string          `json:"parent_tool_use_id,omitempty"`
	DurationAPIMs   int64           `json:"duration_api_ms,omitempty"`

	// Hook fields (system subtype: hook_started / hook_response)
	HookID    string `json:"hook_id,omitempty"`
	HookName  string `json:"hook_name,omitempty"`
	HookEvent string `json:"hook_event,omitempty"`
	Command   string `json:"command,omitempty"`
	ExitCode  *int   `json:"exit_code,omitempty"`
	Stdout    string `json:"stdout,omitempty"`

	Outcome string `json:"outcome,omitempty"`

	// Rate limit fields (type: rate_limit_event)
	RateLimitInfo *RateLimitInfo `json:"rate_limit_info,omitempty"`

	// Init fields (system subtype: init)
	Model      string          `json:"model,omitempty"`
	MCPServers []MCPServerInfo `json:"mcp_servers,omitempty"`
	Tools      []string        `json:"tools,omitempty"`
	Skills     []string        `json:"skills,omitempty"`
	// Plugins is populated by ParseStreamMessage. Supports both []PluginInfo (new)
	// and []string (legacy Claude CLI) formats via custom unmarshalling.
	Plugins []PluginInfo `json:"-"`
}

StreamMessage represents a single NDJSON line from Claude Code --output-format stream-json.

func ParseStreamMessage

func ParseStreamMessage(data []byte) (*StreamMessage, error)

ParseStreamMessage parses a single NDJSON line.

func (*StreamMessage) ExtractText

func (m *StreamMessage) ExtractText() (string, error)

ExtractText concatenates all text content blocks from an assistant message.

func (*StreamMessage) ExtractToolUse

func (m *StreamMessage) ExtractToolUse() ([]ContentBlock, error)

ExtractToolUse returns all tool_use content blocks from an assistant message.

func (*StreamMessage) ParseAssistantMessage

func (m *StreamMessage) ParseAssistantMessage() (*AssistantMessage, error)

ParseAssistantMessage extracts the AssistantMessage from Message field.

type StreamNormalizer added in v0.0.12

type StreamNormalizer struct {
	// contains filtered or unexported fields
}

StreamNormalizer converts provider-specific StreamMessage into unified SessionStreamEvent.

func NewStreamNormalizer added in v0.0.12

func NewStreamNormalizer(toolName string, provider domain.Provider) *StreamNormalizer

NewStreamNormalizer creates a normalizer for the given tool and provider.

func (*StreamNormalizer) Normalize added in v0.0.12

Normalize converts a StreamMessage into a SessionStreamEvent. Returns nil for messages that should not be published.

func (*StreamNormalizer) SessionEnd added in v0.0.12

func (n *StreamNormalizer) SessionEnd(providerSessionID string, runErr error) domain.SessionStreamEvent

SessionEnd creates a session_end event for any exit path (normal or abnormal).

func (*StreamNormalizer) SetCodingSessionID added in v0.0.12

func (n *StreamNormalizer) SetCodingSessionID(id string)

SetCodingSessionID sets the tracking session ID for emitted events.

type StreamReader

type StreamReader struct {
	// contains filtered or unexported fields
}

StreamReader reads NDJSON lines from Claude Code --output-format stream-json. Invalid JSON lines and empty lines are skipped (forward-compatible). Uses bufio.Reader.ReadBytes to avoid line size limits.

func NewStreamReader

func NewStreamReader(r io.Reader) *StreamReader

NewStreamReader creates a StreamReader from an io.Reader.

func (*StreamReader) CollectAll

func (sr *StreamReader) CollectAll() (*StreamMessage, []*StreamMessage, error)

CollectAll reads all messages until EOF and returns the result message (type=="result") and the full list of messages.

func (*StreamReader) Next

func (sr *StreamReader) Next() (*StreamMessage, error)

Next returns the next parsed StreamMessage, skipping empty and invalid lines. Returns io.EOF when the stream ends cleanly. Returns the underlying read error for I/O failures (not io.EOF).

func (*StreamReader) SetLogger

func (sr *StreamReader) SetLogger(l interface{ Warn(string, ...any) })

SetLogger sets an optional logger for parse error warnings.

type Usage

type Usage struct {
	InputTokens              int `json:"input_tokens"`
	OutputTokens             int `json:"output_tokens"`
	CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
	CacheReadInputTokens     int `json:"cache_read_input_tokens,omitempty"`
}

Usage holds token usage from Claude Code.

Jump to

Keyboard shortcuts

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