klient

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

klient

Lightweight Go client for the Kimi Agent Protocol served by Kimi Code 2.5.3 (kimi web), with acknowledged subscribe_v2 subscriptions, per-agent transcript resumption, lifecycle APIs, and trace event normalization.

Install

go get github.com/huangzheng2016/klient

Features

  • Session & lifecycle REST API:
    • Healthz(ctx) — probe /api/v1/healthz
    • CreateSession(ctx, cwd) — create a workspace session
    • GetSession(ctx, sessionID) — read session activity and metadata
    • GetSnapshot(ctx, sessionID) — read session state plus the main agent transcript and cursor
    • GetAgentSnapshot(ctx, sessionID, agentID) — read another agent transcript and cursor
    • RestoreSession(ctx, sessionID) / ReloadSession(ctx, sessionID) — run 2.5.3 lifecycle actions
    • ListMCPServers(ctx) — inspect configured MCP servers
    • PostPrompt(ctx, sessionID, PromptRequest) — submit a prompt
    • SteerPrompts(ctx, sessionID, promptIDs) — steer queued prompts into an active turn
    • Abort(ctx, sessionID) — abort an active session turn
    • CloseSession(sessionID) — cancel the active local subscription and release cached transcript state without deleting the server session
  • WebSocket event subscription (/api/v1/ws):
    • Performs client_hello and subscribe_v2 handshakes and waits for both corresponding acknowledgements.
    • Rejects non-zero acknowledgements, missing sessions, unsupported protocol versions, and handshake timeouts.
    • Subscribes to all agents at delta grade and resumes with transcript_since from Cursor.TranscriptSince; a cursor returned by Snapshot.Cursor() also carries a private transcript baseline.
    • Maps transcript.reset and transcript.ops into assistant, thinking, tool, turn, prompt, error, and subagent events.
    • Tracks per-agent sequence cursors, suppresses replay duplicates, and detects sequence and append gaps.
    • Numbers each mapped transcript event with EventIndex from zero within its WS reset/ops frame. (AgentID, Seq, EventIndex) is the batch-scoped deduplication key for transcript events; lifecycle events with Seq=0 do not use that key.
    • Applies external transcript.reset incrementally against cached state so old frames are not replayed, while explicit op=reset retains its clearing/undo semantics.
    • Reads raw frames and answers ping independently of transcript mapping and event delivery, so a slow consumer cannot block heartbeat responses.
    • Uses a bounded 64-frame raw queue. Saturation closes the connection and surfaces klient.read_error after already queued events, allowing replay from the last committed cursor without silently dropping frames.
    • Commits cursor and cache only after every mapped event in a transcript batch has been received. Closing mid-batch replays that batch on reconnect, favoring duplicates over event loss.
    • Preserves split UTF-16 surrogate pairs across transcript messages without emitting unpaired surrogates.
    • Preserves transcript state across reconnects on the same Client; Subscription.Cursor() returns the latest committed per-agent cursor.
    • Rejects concurrent subscriptions to the same session on one Client with ErrSessionSubscribed.
    • Exposes agent, usage, task.list, task, and task.output as lifecycle events. task.list contains currently running tasks, not historical tasks.
    • Automatically answers server ping frames with pong.
  • Normalized trace mapper (KAPMapper / TraceMapper):
    • Maps events into standard trace kinds (think, text, tool_call, tool_result, step_begin, turn_end, usage, error, end).
    • Uses actual per-step token usage and separate context-window updates.
    • Filters prompt completion by main prompt ID and main agent ID.

Quick start

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/huangzheng2016/klient"
)

func main() {
	ctx := context.Background()
	c := klient.New("http://127.0.0.1:54321", "")

	if err := c.Healthz(ctx); err != nil {
		log.Fatal(err)
	}

	sess, err := c.CreateSession(ctx, "/workspace")
	if err != nil {
		log.Fatal(err)
	}
	defer c.CloseSession(sess.ID)

	snap, err := c.GetSnapshot(ctx, sess.ID)
	if err != nil {
		log.Fatal(err)
	}

	sub, err := c.Subscribe(ctx, sess.ID, snap.Cursor())
	if err != nil {
		log.Fatal(err)
	}
	defer sub.Close()

	receipt, err := c.PostPrompt(ctx, sess.ID, klient.PromptRequest{
		Text:           "Explain the repository layout.",
		PermissionMode: "yolo",
	})
	if err != nil {
		log.Fatal(err)
	}

	mapper := &klient.KAPMapper{MainPromptID: receipt.PromptID}
	for ev := range sub.Events {
		if kind, payload, ok := mapper.Map(ev); ok {
			fmt.Printf("[%s] agent=%s seq=%d index=%d %s\n", kind, ev.AgentID, ev.Seq, ev.EventIndex, payload)
			if kind == "end" {
				break
			}
		}
	}
}

On reconnect, close the old subscription and pass sub.Cursor() back to Subscribe on the same Client. The cursor is batch-committed: after receiving one event from a multi-event batch, it may still refer to the preceding batch so that closing before the remaining events cannot skip them.

EventIndex is assigned after incremental mapping of each WS frame. Replaying an uncommitted frame starts from the same pre-frame state and therefore produces identical (AgentID, Seq, EventIndex) keys; it is not a cross-frame content identifier.

License

MIT

Documentation

Overview

Package klient implements the Kimi Code 2.5.3 REST and WebSocket client, including acknowledged subscribe_v2 streams, per-agent transcript resumption, session lifecycle operations, and trace normalization.

Index

Constants

View Source
const (
	TypeTurnStarted              = "turn.started"
	TypeTurnEnded                = "turn.ended"
	TypeAssistantDelta           = "assistant.delta"
	TypeThinkingDelta            = "thinking.delta"
	TypeToolCallStarted          = "tool.call.started"
	TypeToolCallDelta            = "tool.call.delta"
	TypeToolProgress             = "tool.progress"
	TypeToolResult               = "tool.result"
	TypeTurnStepStarted          = "turn.step.started"
	TypeTurnStepComplete         = "turn.step.completed"
	TypeTurnStepInterrupted      = "turn.step.interrupted"
	TypeTurnStepRetrying         = "turn.step.retrying"
	TypeAgentStatus              = "agent.status.updated"
	TypeUsage                    = "usage"
	TypePromptCompleted          = "prompt.completed"
	TypePromptAborted            = "prompt.aborted"
	TypeError                    = "error"
	TypeWarning                  = "warning"
	TypeWorkChanged              = "event.session.work_changed"
	TypeTaskStarted              = "task.started"
	TypeTaskTerminated           = "task.terminated"
	TypeTaskNotified             = "task.notified"
	TypeTaskList                 = "task.list"
	TypeTaskOutput               = "task.output"
	TypeBackgroundTaskStarted    = "background.task.started"
	TypeBackgroundTaskTerminated = "background.task.terminated"
	TypeSubagentSpawned          = "subagent.spawned"
)
View Source
const TypeProtocolError = "klient.protocol_error"
View Source
const TypeReadError = "klient.read_error"

Variables

View Source
var ErrAPI = errors.New("klient: api error")
View Source
var ErrSessionNotFound = errors.New("klient: session not found")
View Source
var ErrSessionSubscribed = errors.New("klient: session already subscribed")

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code      int
	Msg       string
	RequestID string
	Details   json.RawMessage
}

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

type AgentDescriptor added in v0.1.0

type AgentDescriptor struct {
	AgentID       string `json:"agentId"`
	Type          string `json:"type,omitempty"`
	ParentAgentID string `json:"parentAgentId,omitempty"`
	Label         string `json:"label,omitempty"`
	CreatedAt     string `json:"createdAt,omitempty"`
	DisposedAt    string `json:"disposedAt,omitempty"`
}

type AgentPhase

type AgentPhase struct {
	Kind   string `json:"kind"`
	TurnID string `json:"turnId,omitempty"`
	Step   int64  `json:"step,omitempty"`
	StepID string `json:"stepId,omitempty"`
}

type AgentStatusPayload

type AgentStatusPayload struct {
	EventIdentity
	Status         string      `json:"status,omitempty"`
	Model          string      `json:"model,omitempty"`
	ThinkingEffort string      `json:"thinkingEffort,omitempty"`
	Permission     string      `json:"permission,omitempty"`
	PlanMode       bool        `json:"planMode,omitempty"`
	SwarmMode      bool        `json:"swarmMode,omitempty"`
	TowerMode      bool        `json:"towerMode,omitempty"`
	Phase          *AgentPhase `json:"phase,omitempty"`
}

type AssistantDeltaPayload

type AssistantDeltaPayload struct {
	EventIdentity
	TurnID string `json:"turnId"`
	Delta  string `json:"delta"`
}

type Client

type Client struct {
	BaseURL       string
	Token         string
	HTTPClient    *http.Client
	DialTimeout   time.Duration
	MaxFrameBytes int64
	// contains filtered or unexported fields
}

func New

func New(baseURL, token string) *Client

func (*Client) Abort

func (c *Client) Abort(ctx context.Context, sessionID string) error

func (*Client) CloseSession added in v0.1.0

func (c *Client) CloseSession(sessionID string)

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, cwd string) (*Session, error)

func (*Client) GetAgentSnapshot added in v0.1.0

func (c *Client) GetAgentSnapshot(ctx context.Context, sessionID, agentID string) (*Snapshot, error)

func (*Client) GetSession added in v0.1.0

func (c *Client) GetSession(ctx context.Context, sessionID string) (*Session, error)

func (*Client) GetSnapshot

func (c *Client) GetSnapshot(ctx context.Context, sessionID string) (*Snapshot, error)

func (*Client) Healthz

func (c *Client) Healthz(ctx context.Context) error

func (*Client) ListMCPServers

func (c *Client) ListMCPServers(ctx context.Context) ([]MCPServer, error)

func (*Client) PostPrompt

func (c *Client) PostPrompt(ctx context.Context, sessionID string, preq PromptRequest) (*PromptReceipt, error)

func (*Client) ReloadSession added in v0.1.0

func (c *Client) ReloadSession(ctx context.Context, sessionID string) (*Session, error)

func (*Client) RestoreSession added in v0.1.0

func (c *Client) RestoreSession(ctx context.Context, sessionID string) (*Session, error)

func (*Client) SteerPrompts

func (c *Client) SteerPrompts(ctx context.Context, sessionID string, promptIDs []string) error

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, sessionID string, cursor Cursor) (*Subscription, error)

type Cursor

type Cursor struct {
	TranscriptSince map[string]int64 `json:"transcript_since,omitempty"`
	// contains filtered or unexported fields
}

type ErrorPayload

type ErrorPayload struct {
	EventIdentity
	Code      string `json:"code"`
	Message   string `json:"message"`
	Name      string `json:"name,omitempty"`
	Retryable bool   `json:"retryable"`
}

type Event

type Event struct {
	Type       string
	Seq        int64
	EventIndex int
	SessionID  string
	AgentID    string
	Payload    json.RawMessage
}

func (Event) Decode

func (e Event) Decode(v any) error

type EventIdentity added in v0.1.0

type EventIdentity struct {
	AgentID   string `json:"agentId,omitempty"`
	SessionID string `json:"sessionId,omitempty"`
}

type InFlightTurn

type InFlightTurn struct {
	TurnID          string `json:"turn_id"`
	CurrentPromptID string `json:"current_prompt_id"`
}

type KAPMapper

type KAPMapper struct {
	MainPromptID string
	// contains filtered or unexported fields
}

func (*KAPMapper) Map

func (m *KAPMapper) Map(ev Event) (string, json.RawMessage, bool)

type MCPServer

type MCPServer struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Transport   string `json:"transport,omitempty"`
	Status      string `json:"status"`
	LastError   string `json:"last_error,omitempty"`
	ToolCount   int    `json:"tool_count,omitempty"`
	NextRetryAt int64  `json:"next_retry_at,omitempty"`
}

type PromptAbortedPayload

type PromptAbortedPayload struct {
	EventIdentity
	PromptID  string `json:"promptId"`
	AbortedAt string `json:"abortedAt"`
}

type PromptCompletedPayload

type PromptCompletedPayload struct {
	EventIdentity
	PromptID   string `json:"promptId"`
	FinishedAt string `json:"finishedAt"`
	Reason     string `json:"reason,omitempty"`
}

type PromptOrigin

type PromptOrigin struct {
	Kind    string          `json:"kind"`
	TaskID  string          `json:"taskId,omitempty"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

type PromptReceipt

type PromptReceipt struct {
	PromptID string `json:"prompt_id"`
}

type PromptRequest

type PromptRequest struct {
	Text           string
	Model          string
	PermissionMode string
}

type ProtocolErrorPayload

type ProtocolErrorPayload struct {
	Code      int             `json:"code"`
	Msg       string          `json:"msg"`
	Fatal     bool            `json:"fatal"`
	RequestID string          `json:"request_id,omitempty"`
	Details   json.RawMessage `json:"details,omitempty"`
}

type Session

type Session struct {
	ID                 string         `json:"id"`
	WorkspaceID        string         `json:"workspace_id,omitempty"`
	Title              string         `json:"title,omitempty"`
	CreatedAt          string         `json:"created_at,omitempty"`
	UpdatedAt          string         `json:"updated_at,omitempty"`
	ArchivedAt         string         `json:"archived_at,omitempty"`
	Busy               bool           `json:"busy"`
	MainTurnActive     bool           `json:"main_turn_active,omitempty"`
	PendingInteraction string         `json:"pending_interaction,omitempty"`
	LastTurnReason     string         `json:"last_turn_reason,omitempty"`
	Archived           bool           `json:"archived,omitempty"`
	CurrentPromptID    string         `json:"current_prompt_id,omitempty"`
	LastPrompt         string         `json:"last_prompt,omitempty"`
	Metadata           map[string]any `json:"metadata,omitempty"`
	AgentConfig        struct {
		Model string `json:"model,omitempty"`
	} `json:"agent_config"`
	Usage        SessionUsage `json:"usage"`
	MessageCount int64        `json:"message_count,omitempty"`
}

type SessionUsage added in v0.1.0

type SessionUsage struct {
	InputTokens         int64   `json:"input_tokens"`
	OutputTokens        int64   `json:"output_tokens"`
	CacheReadTokens     int64   `json:"cache_read_tokens"`
	CacheCreationTokens int64   `json:"cache_creation_tokens"`
	TotalCostUSD        float64 `json:"total_cost_usd,omitempty"`
	ContextTokens       int64   `json:"context_tokens"`
	ContextLimit        int64   `json:"context_limit,omitempty"`
	TurnCount           int64   `json:"turn_count,omitempty"`
}

type Snapshot

type Snapshot struct {
	AgentID             string             `json:"agent_id"`
	Items               []TranscriptItem   `json:"items"`
	HasMore             bool               `json:"has_more"`
	Interactions        []json.RawMessage  `json:"interactions"`
	Attachments         []json.RawMessage  `json:"attachments"`
	Prompts             []TranscriptPrompt `json:"prompts"`
	Agents              []AgentDescriptor  `json:"agents"`
	PendingInteractions []string           `json:"pending_interactions"`
	Seq                 *int64             `json:"seq"`
	Session             Session            `json:"-"`
	InFlightTurn        *InFlightTurn      `json:"-"`
}

func (*Snapshot) Cursor

func (s *Snapshot) Cursor() Cursor

type SubagentSpawnedPayload added in v0.1.0

type SubagentSpawnedPayload struct {
	EventIdentity
	SubagentID       string `json:"subagentId"`
	ParentToolCallID string `json:"parentToolCallId,omitempty"`
	ParentAgentID    string `json:"parentAgentId,omitempty"`
	Role             string `json:"role,omitempty"`
}

type SubscribeError added in v0.1.0

type SubscribeError struct {
	Op       string
	Code     int
	Msg      string
	Accepted []string
	NotFound []string
}

func (*SubscribeError) Error added in v0.1.0

func (e *SubscribeError) Error() string

func (*SubscribeError) Unwrap added in v0.1.0

func (e *SubscribeError) Unwrap() error

type Subscription

type Subscription struct {
	Events <-chan Event
	// contains filtered or unexported fields
}

func (*Subscription) Close

func (s *Subscription) Close()

func (*Subscription) Cursor added in v0.1.0

func (s *Subscription) Cursor() Cursor

type Task

type Task struct {
	ID               string `json:"task_id"`
	Kind             string `json:"kind"`
	Status           string `json:"status"`
	Outcome          string `json:"outcome,omitempty"`
	Phase            string `json:"phase,omitempty"`
	Detached         bool   `json:"detached"`
	Description      string `json:"description,omitempty"`
	ChildAgentID     string `json:"child_agent_id,omitempty"`
	ParentToolCallID string `json:"parent_tool_call_id,omitempty"`
	SwarmIndex       *int64 `json:"swarm_index,omitempty"`
	Command          string `json:"command,omitempty"`
	StartedAt        string `json:"started_at,omitempty"`
	EndedAt          string `json:"ended_at,omitempty"`
	ResultSummary    string `json:"result_summary,omitempty"`
	Error            string `json:"error,omitempty"`
	StateReason      string `json:"state_reason,omitempty"`
	Model            string `json:"model,omitempty"`
	Thinking         string `json:"thinking,omitempty"`
}

type TaskEventPayload added in v0.1.0

type TaskEventPayload struct {
	EventIdentity
	Info TaskInfoPayload `json:"info"`
}

type TaskInfoPayload added in v0.1.0

type TaskInfoPayload struct {
	TaskID           string `json:"taskId"`
	Status           string `json:"status"`
	Detached         bool   `json:"detached"`
	RunInBackground  bool   `json:"runInBackground"`
	Kind             string `json:"kind,omitempty"`
	Description      string `json:"description,omitempty"`
	ChildAgentID     string `json:"childAgentId,omitempty"`
	ParentToolCallID string `json:"parentToolCallId,omitempty"`
	SwarmIndex       *int64 `json:"swarmIndex,omitempty"`
	Command          string `json:"command,omitempty"`
	StartedAt        string `json:"startedAt,omitempty"`
	EndedAt          string `json:"endedAt,omitempty"`
	ResultSummary    string `json:"resultSummary,omitempty"`
	Error            string `json:"error,omitempty"`
	StateReason      string `json:"stateReason,omitempty"`
	Model            string `json:"model,omitempty"`
	ThinkingEffort   string `json:"thinkingEffort,omitempty"`
}

type TaskListPayload added in v0.1.0

type TaskListPayload struct {
	EventIdentity
	Tasks []Task `json:"tasks"`
}

type TaskOutputPayload added in v0.1.0

type TaskOutputPayload struct {
	EventIdentity
	TaskID string `json:"taskId"`
	Offset int64  `json:"offset"`
	Text   string `json:"text"`
}

type ThinkingDeltaPayload

type ThinkingDeltaPayload struct {
	EventIdentity
	TurnID string `json:"turnId"`
	Delta  string `json:"delta"`
}

type ToolCallDeltaPayload

type ToolCallDeltaPayload struct {
	EventIdentity
	TurnID        string `json:"turnId"`
	ToolCallID    string `json:"toolCallId"`
	Name          string `json:"name,omitempty"`
	ArgumentsPart string `json:"argumentsPart,omitempty"`
}

type ToolCallStartedPayload

type ToolCallStartedPayload struct {
	EventIdentity
	TurnID      string          `json:"turnId"`
	ToolCallID  string          `json:"toolCallId"`
	Name        string          `json:"name"`
	Args        json.RawMessage `json:"args"`
	Description string          `json:"description,omitempty"`
	Display     json.RawMessage `json:"display,omitempty"`
}

type ToolProgressPayload

type ToolProgressPayload struct {
	EventIdentity
	TurnID     string     `json:"turnId"`
	ToolCallID string     `json:"toolCallId"`
	Update     ToolUpdate `json:"update"`
}

type ToolResultPayload

type ToolResultPayload struct {
	EventIdentity
	TurnID     string          `json:"turnId"`
	ToolCallID string          `json:"toolCallId"`
	Output     json.RawMessage `json:"output"`
	IsError    bool            `json:"isError,omitempty"`
	Synthetic  bool            `json:"synthetic,omitempty"`
}

type ToolUpdate

type ToolUpdate struct {
	Kind       string          `json:"kind"`
	Text       string          `json:"text,omitempty"`
	Percent    float64         `json:"percent,omitempty"`
	CustomKind string          `json:"customKind,omitempty"`
	CustomData json.RawMessage `json:"customData,omitempty"`
}

type TraceMapper

type TraceMapper = KAPMapper

type TranscriptAgentRef added in v0.1.0

type TranscriptAgentRef struct {
	AgentID string `json:"agentId"`
	Role    string `json:"role,omitempty"`
}

type TranscriptFrame added in v0.1.0

type TranscriptFrame struct {
	Kind    string `json:"kind"`
	FrameID string `json:"frameId"`

	Role          string               `json:"role,omitempty"`
	Text          string               `json:"text,omitempty"`
	TaskID        string               `json:"taskId,omitempty"`
	PromptIDs     []string             `json:"promptIds,omitempty"`
	AttachmentIDs []string             `json:"attachmentIds,omitempty"`
	ToolCallID    string               `json:"toolCallId,omitempty"`
	Name          string               `json:"name,omitempty"`
	View          string               `json:"view,omitempty"`
	State         string               `json:"state,omitempty"`
	Input         json.RawMessage      `json:"input,omitempty"`
	Output        json.RawMessage      `json:"output,omitempty"`
	Display       json.RawMessage      `json:"display,omitempty"`
	Error         string               `json:"error,omitempty"`
	InputText     string               `json:"inputText,omitempty"`
	Progress      *ToolUpdate          `json:"progress,omitempty"`
	ApprovalID    string               `json:"approvalId,omitempty"`
	AgentRefs     []TranscriptAgentRef `json:"agentRefs,omitempty"`
	Level         string               `json:"level,omitempty"`
	Source        string               `json:"source,omitempty"`
	Message       string               `json:"message,omitempty"`
	Detail        json.RawMessage      `json:"detail,omitempty"`
	// contains filtered or unexported fields
}

func (*TranscriptFrame) UnmarshalJSON added in v0.1.0

func (f *TranscriptFrame) UnmarshalJSON(data []byte) error

type TranscriptGapError added in v0.1.0

type TranscriptGapError struct {
	AgentID  string
	Expected int64
	Got      int64
	Detail   string
}

func (*TranscriptGapError) Error added in v0.1.0

func (e *TranscriptGapError) Error() string

type TranscriptItem added in v0.1.0

type TranscriptItem struct {
	Kind            string           `json:"kind"`
	TurnID          string           `json:"turnId,omitempty"`
	TriggerPromptID string           `json:"triggerPromptId,omitempty"`
	Ordinal         int64            `json:"ordinal,omitempty"`
	State           string           `json:"state,omitempty"`
	Origin          PromptOrigin     `json:"origin,omitempty"`
	Prompt          string           `json:"prompt,omitempty"`
	AttachmentIDs   []string         `json:"attachmentIds,omitempty"`
	Steps           []TranscriptStep `json:"steps,omitempty"`
	StartedAt       string           `json:"startedAt,omitempty"`
	EndedAt         string           `json:"endedAt,omitempty"`
	Usage           json.RawMessage  `json:"usage,omitempty"`
	DurationMs      int64            `json:"durationMs,omitempty"`
	Error           string           `json:"error,omitempty"`
	Wedged          bool             `json:"wedged,omitempty"`
	MarkerID        string           `json:"markerId,omitempty"`
	Marker          string           `json:"marker,omitempty"`
	Payload         json.RawMessage  `json:"payload,omitempty"`
	At              string           `json:"at,omitempty"`
}

type TranscriptPrompt added in v0.1.0

type TranscriptPrompt struct {
	PromptID       string           `json:"promptId"`
	Status         string           `json:"status"`
	UserMessageID  string           `json:"userMessageId,omitempty"`
	Content        json.RawMessage  `json:"content,omitempty"`
	ClientMetadata []map[string]any `json:"clientMetadata,omitempty"`
	CreatedAt      string           `json:"createdAt"`
	FinishedAt     string           `json:"finishedAt,omitempty"`
	SteeredAt      string           `json:"steeredAt,omitempty"`
}

type TranscriptStep added in v0.1.0

type TranscriptStep struct {
	Kind         string               `json:"kind"`
	StepID       string               `json:"stepId"`
	TurnID       string               `json:"turnId"`
	Ordinal      int64                `json:"ordinal"`
	State        string               `json:"state"`
	Frames       []TranscriptFrame    `json:"frames,omitempty"`
	StartedAt    string               `json:"startedAt,omitempty"`
	EndedAt      string               `json:"endedAt,omitempty"`
	Usage        *UsagePayload        `json:"usage,omitempty"`
	FinishReason string               `json:"finishReason,omitempty"`
	LLMTiming    json.RawMessage      `json:"llmTiming,omitempty"`
	Retry        *TranscriptStepRetry `json:"retry,omitempty"`
	EndReason    string               `json:"endReason,omitempty"`
	EndMessage   string               `json:"endMessage,omitempty"`
}

type TranscriptStepRetry added in v0.1.0

type TranscriptStepRetry struct {
	FailedAttempt int64  `json:"failedAttempt"`
	NextAttempt   int64  `json:"nextAttempt"`
	MaxAttempts   int64  `json:"maxAttempts"`
	DelayMs       int64  `json:"delayMs"`
	ErrorName     string `json:"errorName"`
	ErrorMessage  string `json:"errorMessage"`
	StatusCode    int64  `json:"statusCode,omitempty"`
}

type TranscriptTurn added in v0.1.0

type TranscriptTurn struct {
	Kind            string           `json:"kind"`
	TurnID          string           `json:"turnId"`
	TriggerPromptID string           `json:"triggerPromptId,omitempty"`
	Ordinal         int64            `json:"ordinal"`
	State           string           `json:"state"`
	Origin          PromptOrigin     `json:"origin"`
	Prompt          string           `json:"prompt,omitempty"`
	AttachmentIDs   []string         `json:"attachmentIds,omitempty"`
	Steps           []TranscriptStep `json:"steps,omitempty"`
	StartedAt       string           `json:"startedAt,omitempty"`
	EndedAt         string           `json:"endedAt,omitempty"`
	Usage           json.RawMessage  `json:"usage,omitempty"`
	DurationMs      int64            `json:"durationMs,omitempty"`
	Error           string           `json:"error,omitempty"`
	Wedged          bool             `json:"wedged,omitempty"`
}

type TurnEndedPayload

type TurnEndedPayload struct {
	EventIdentity
	TurnID          string        `json:"turnId"`
	PromptID        string        `json:"promptId,omitempty"`
	Reason          string        `json:"reason"`
	Error           *ErrorPayload `json:"error,omitempty"`
	DurationMs      int64         `json:"durationMs,omitempty"`
	InterruptReason string        `json:"interruptReason,omitempty"`
	TraceID         string        `json:"traceId,omitempty"`
}

type TurnStartedPayload

type TurnStartedPayload struct {
	EventIdentity
	TurnID   string       `json:"turnId"`
	PromptID string       `json:"promptId,omitempty"`
	Origin   PromptOrigin `json:"origin"`
	Prompt   string       `json:"prompt,omitempty"`
}

type TurnStepCompletedPayload

type TurnStepCompletedPayload struct {
	EventIdentity
	TurnID       string        `json:"turnId"`
	Step         int64         `json:"step"`
	StepID       string        `json:"stepId,omitempty"`
	Usage        *UsagePayload `json:"usage,omitempty"`
	FinishReason string        `json:"finishReason,omitempty"`
	EndReason    string        `json:"endReason,omitempty"`
	EndMessage   string        `json:"endMessage,omitempty"`
}

type TurnStepPayload

type TurnStepPayload struct {
	EventIdentity
	TurnID string `json:"turnId"`
	Step   int64  `json:"step"`
	StepID string `json:"stepId,omitempty"`
}

type TurnStepRetryingPayload added in v0.1.0

type TurnStepRetryingPayload struct {
	EventIdentity
	TurnID        string `json:"turnId"`
	Step          int64  `json:"step"`
	StepID        string `json:"stepId,omitempty"`
	FailedAttempt int64  `json:"failedAttempt"`
	NextAttempt   int64  `json:"nextAttempt"`
	MaxAttempts   int64  `json:"maxAttempts"`
	DelayMs       int64  `json:"delayMs"`
	ErrorName     string `json:"errorName"`
	ErrorMessage  string `json:"errorMessage"`
	StatusCode    int64  `json:"statusCode,omitempty"`
}

type UsageContextPayload added in v0.1.0

type UsageContextPayload struct {
	EventIdentity
	ContextTokens    int64 `json:"contextTokens"`
	MaxContextTokens int64 `json:"maxContextTokens,omitempty"`
}

type UsagePayload

type UsagePayload struct {
	InputOther         int64 `json:"inputOther"`
	Output             int64 `json:"output"`
	InputCacheRead     int64 `json:"inputCacheRead"`
	InputCacheCreation int64 `json:"inputCacheCreation"`
}

type WarningPayload

type WarningPayload struct {
	EventIdentity
	Message string `json:"message"`
	Code    string `json:"code,omitempty"`
}

type WorkChangedPayload

type WorkChangedPayload struct {
	EventIdentity
	Busy               bool   `json:"busy"`
	MainTurnActive     bool   `json:"main_turn_active"`
	PendingInteraction string `json:"pending_interaction,omitempty"`
	LastTurnReason     string `json:"last_turn_reason,omitempty"`
}

Jump to

Keyboard shortcuts

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