Documentation
¶
Index ¶
- Constants
- Variables
- func ExpandTilde(s string) string
- func FilterEnv(env []string, name string) []string
- func FormatRawEvent(eventType, jsonData string, maxValueLen int) string
- func GenAIAgentAttrs(agentName, agentID string) []attribute.KeyValue
- func GenAIResultAttrs(result *StreamMessage, responseModel, responseID string) []attribute.KeyValue
- func GenAISessionAttrs(sessionID string) []attribute.KeyValue
- func GenAISpanAttrs(model string) []attribute.KeyValue
- func GenAIToolAttrs(toolName, callID string) []attribute.KeyValue
- func IsNDJSON(s string) bool
- func IsProcessAlive(pid int) bool
- func LookPathShell(cmdLine string) (string, error)
- func NewShellCmd(ctx context.Context, cmdLine string, args ...string) *exec.Cmd
- func OtelEnvContent(backend, entity, project string) (string, error)
- func ParseShellCommand(cmdLine string) (env []string, bin string, extraArgs []string)
- func RecordWave(ctx context.Context, status string)
- func RenderArchitectDiscussPrompt(lang string, data domain.ArchitectDiscussPromptData) (string, error)
- func RenderAutoDiscussArchitectPrompt(lang string, data domain.AutoDiscussArchitectPromptData) (string, error)
- func RenderAutoDiscussDevilsAdvocatePrompt(lang string, data domain.AutoDiscussDevilsAdvocatePromptData) (string, error)
- func RenderClassifyPrompt(lang string, data domain.ClassifyPromptData) (string, error)
- func RenderDeepScanPrompt(lang string, data domain.DeepScanPromptData) (string, error)
- func RenderInitConfig(team, project, lang, strictness string) string
- func RenderNextGenPrompt(lang string, data domain.NextGenPromptData) (string, error)
- func RenderReadyLabelPrompt(lang string, data domain.ReadyLabelPromptData) (string, error)
- func RenderScribeADRPrompt(lang string, data domain.ScribeADRPromptData) (string, error)
- func RenderWaveApplyPrompt(lang string, data domain.WaveApplyPromptData) (string, error)
- func RenderWaveGeneratePrompt(lang string, data domain.WaveGeneratePromptData) (string, error)
- func SanitizeUTF8(s string) string
- func SanitizeUTF8Slice(ss []string) []string
- func StatusColor(s domain.CheckStatus) string
- func SummarizeNDJSON(s string) string
- func SyntheticToolID(seq int) string
- func TruncateValue(s string, maxLen int) string
- func WeaveThreadNestedAttrs(threadID string) []attribute.KeyValue
- func WeaveThreadTurnAttrs(threadID string) []attribute.KeyValue
- type AssistantMessage
- type BudgetItem
- type BusSubscriber
- type CircuitBreaker
- func (cb *CircuitBreaker) Allow(ctx context.Context) error
- func (cb *CircuitBreaker) IsOpen() bool
- func (cb *CircuitBreaker) RecordProviderError(info domain.ProviderErrorInfo)
- func (cb *CircuitBreaker) RecordSuccess()
- func (cb *CircuitBreaker) ResetAt() time.Time
- func (cb *CircuitBreaker) String() string
- type ContentBlock
- type ContextBudgetReport
- type InProcessSessionBus
- type Logger
- func (l *Logger) Banner(dir domain.BannerDirection, kind, name, description string)
- func (l *Logger) Colorize(text, color string) string
- func (l *Logger) Debug(format string, args ...any)
- func (l *Logger) Error(format string, args ...any)
- func (l *Logger) Header(toolName, version string)
- func (l *Logger) Info(format string, args ...any)
- func (l *Logger) OK(format string, args ...any)
- func (l *Logger) Section(title string)
- func (l *Logger) SetExtraWriter(w io.Writer)
- func (l *Logger) SetNoColor(v bool)
- func (l *Logger) Warn(format string, args ...any)
- func (l *Logger) Writer() io.Writer
- type MCPServerInfo
- type OTelPolicyMetrics
- type PluginInfo
- type RateLimitInfo
- type SpanEmittingStreamReader
- func (s *SpanEmittingStreamReader) CollectAll() (*StreamMessage, []*StreamMessage, error)
- func (s *SpanEmittingStreamReader) InitAttrs() []attribute.KeyValue
- func (s *SpanEmittingStreamReader) RawEvents() []string
- func (s *SpanEmittingStreamReader) SetInput(prompt string)
- func (s *SpanEmittingStreamReader) SetStreamMessageHandler(fn func(*StreamMessage, json.RawMessage))
- func (s *SpanEmittingStreamReader) WeaveIOAttrs() []attribute.KeyValue
- func (s *SpanEmittingStreamReader) WeaveThreadAttrs() []attribute.KeyValue
- type StreamMessage
- type StreamNormalizer
- type StreamReader
- type Usage
Constants ¶
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/
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
const DefaultContextBudgetThreshold = 20000
DefaultContextBudgetThreshold is the default warning threshold in estimated tokens. 20K tokens leaves reasonable headroom in a 200K context window.
const DefaultMaxValueLen = 512
DefaultMaxValueLen is the default truncation limit for raw event values.
Variables ¶
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.
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.
var SkillsFS embed.FS
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
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
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
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
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
GenAISessionAttrs returns the session ID attribute.
func GenAISpanAttrs ¶
GenAISpanAttrs returns the standard GenAI semantic convention attributes for an Anthropic Claude invocation.
func GenAIToolAttrs ¶
GenAIToolAttrs returns span attributes for a tool_use child span.
func IsNDJSON ¶ added in v0.0.7
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
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
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
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 ¶
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
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 ¶
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 ¶
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
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
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
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
SyntheticToolID generates a fallback tool ID when the stream does not provide one.
func TruncateValue ¶ added in v0.0.3
TruncateValue truncates s to maxLen characters, appending "..." if truncated.
func WeaveThreadNestedAttrs ¶ added in v0.0.5
WeaveThreadNestedAttrs returns Weave thread attributes for a nested (non-turn) span.
func WeaveThreadTurnAttrs ¶ added in v0.0.5
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
func (r ContextBudgetReport) Attrs() []attribute.KeyValue
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
func (b *InProcessSessionBus) Publish(ctx context.Context, event domain.SessionStreamEvent)
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 ¶
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
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) Header ¶ added in v0.0.10
Header prints a single-line startup header with tool name and version. Uses bold inverted text for maximum visibility.
func (*Logger) Section ¶ added in v0.0.10
Section prints a single-line section separator for phase transitions. Uses blue inverted text.
func (*Logger) SetExtraWriter ¶
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
SetNoColor explicitly enables or disables color output. This overrides the auto-detection performed at construction time.
type MCPServerInfo ¶ added in v0.0.5
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
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
func (s *SpanEmittingStreamReader) CollectAll() (*StreamMessage, []*StreamMessage, error)
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
func (n *StreamNormalizer) Normalize(msg *StreamMessage, raw json.RawMessage) *domain.SessionStreamEvent
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.