protocol

package
v0.107.39 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package protocol defines the versioned JSON contract between K-brain and clients such as LiveAgent. Provider-specific wire shapes stay in internal/ai.

Index

Constants

View Source
const (
	ProtocolName  = "kbrain.agent"
	ProtocolMajor = 1
	// ProtocolMinor counts additive revisions inside major 1. It is for logs
	// only; clients gate features on capabilities, never on this number.
	ProtocolMinor = 1

	// StartupContract versions the `kn backend` flags, ready line and exit
	// conventions independently of the HTTP protocol.
	StartupContract = 1
)

Structured handshake fields defined by docs/compatibility.md section 2. The legacy Version string stays the primary v1 marker; Name/Major must agree with it or clients reject the health response as a broken contract.

View Source
const (
	Version = "kbrain.agent.v1"

	RoleSystem    = "system"
	RoleDeveloper = "developer"
	RoleUser      = "user"
	RoleAssistant = "assistant"
	RoleTool      = "tool"

	ContentText       = "text"
	ContentThinking   = "thinking"
	ContentImage      = "image"
	ContentFile       = "file"
	ContentToolCall   = "tool_call"
	ContentToolResult = "tool_result"

	EventRunAccepted       = "run.accepted"
	EventRunProgress       = "run.progress"
	EventUserMessage       = "user.message.appended"
	EventAssistantMessage  = "assistant.message.created"
	EventTextDelta         = "assistant.text.delta"
	EventThinkingDelta     = "assistant.thinking.delta"
	EventHostedSearch      = "assistant.sources"
	EventToolCall          = "tool.call"
	EventToolResult        = "tool.result"
	EventToolStatus        = "tool.status"
	EventPermissionRequest = "permission.requested"
	EventPermissionResult  = "permission.resolved"
	EventQuestionRequested = "question.requested"
	EventQuestionResolved  = "question.resolved"
	// EventElicitationRequested asks the client to show an MCP server's form
	// (ElicitationRequest); EventElicitationResolved reports how it ended
	// (ElicitationResolution). Only runs started with options.mcp_elicitation
	// receive them.
	EventElicitationRequested = "elicitation.requested"
	EventElicitationResolved  = "elicitation.resolved"
	EventClientToolRequested  = "client_tool.requested"
	EventClientToolResolved   = "client_tool.resolved"
	EventSubagentStarted      = "subagent.started"
	EventSubagentUpdate       = "subagent.updated"
	EventSubagentCompleted    = "subagent.completed"
	EventSubagentFailed       = "subagent.failed"
	EventUsage                = "usage.updated"
	EventHistoryUpdated       = "history.updated"
	EventCompactionStarted    = "compaction.started"
	EventCompactionCompleted  = "compaction.completed"
	EventRunCompleted         = "run.completed"
	EventRunFailed            = "run.failed"
	EventRunCancelled         = "run.cancelled"
	EventHookWarning          = "hook.warning"
	EventGoalUpdated          = "goal.updated"
)
View Source
const (
	EventChildText      = "trajectory.child.text"
	EventChildThinking  = "trajectory.child.thinking"
	EventChildSteer     = "trajectory.child.steer"
	EventChildToolStart = "trajectory.child.tool_start"
	EventChildToolEnd   = "trajectory.child.tool_end"
)

Child events record a subagent's own transcript on the parent session's event stream. Every payload carries task_id (the Subagent id). Text and thinking arrive in coalesced chunks; clients that do not know these types ignore them.

View Source
const EventPermissionAutoResolved = "permission.auto_resolved"

EventPermissionAutoResolved says a gated call ran without asking because a remembered rule or the read-only allowance covered it (capability permission_rules).

Variables

This section is empty.

Functions

This section is empty.

Types

type BranchSessionRequest

type BranchSessionRequest struct {
	ExpectedRevision string            `json:"expected_revision,omitempty"`
	MessageRef       HistoryMessageRef `json:"message_ref"`
	Title            string            `json:"title,omitempty"`
}

type Build added in v0.107.6

type Build struct {
	Version  string `json:"version"`
	Revision string `json:"revision,omitempty"`
	Channel  string `json:"channel"`
}

Build is the immutable identity of the running binary as injected at link time. releaseSequence is deliberately absent until signed release metadata (S3) gives it a trustworthy source.

func NewBuild added in v0.107.6

func NewBuild(version, revision string) Build

NewBuild normalizes link-time values. Release tags containing "-" are prereleases, matching the existing release workflow convention.

type CancelRequest

type CancelRequest struct {
	ConversationID string `json:"conversation_id"`
	RunID          string `json:"run_id"`
}

type ChildTextEvent added in v0.107.19

type ChildTextEvent struct {
	TaskID string `json:"task_id"`
	Text   string `json:"text"`
}

ChildTextEvent is the payload of trajectory.child.text, .thinking and .steer.

type ClientTool added in v0.107.3

type ClientTool struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Parameters  json.RawMessage `json:"parameters"`
}

type ClientToolImage added in v0.107.3

type ClientToolImage struct {
	MimeType string `json:"mime_type"`
	Data     string `json:"data"`
}

type ClientToolRequest added in v0.107.3

type ClientToolRequest struct {
	CallID     string          `json:"call_id"`
	ToolCallID string          `json:"tool_call_id"`
	RunID      string          `json:"run_id"`
	Tool       string          `json:"tool"`
	Arguments  json.RawMessage `json:"arguments"`
	DeadlineAt int64           `json:"deadline_at"`
}

type ClientToolResolution added in v0.107.3

type ClientToolResolution struct {
	CallID     string `json:"call_id"`
	ToolCallID string `json:"tool_call_id"`
	RunID      string `json:"run_id"`
	Tool       string `json:"tool"`
	Text       string `json:"text"`
	ImageCount int    `json:"image_count,omitempty"`
	IsError    bool   `json:"is_error,omitempty"`
	TimedOut   bool   `json:"timed_out,omitempty"`
	Cancelled  bool   `json:"cancelled,omitempty"`
}

type ClientToolResultRequest added in v0.107.3

type ClientToolResultRequest struct {
	ConversationID string            `json:"conversation_id"`
	RunID          string            `json:"run_id"`
	Text           string            `json:"text"`
	Images         []ClientToolImage `json:"images,omitempty"`
	IsError        bool              `json:"is_error,omitempty"`
}

type CompactAccepted

type CompactAccepted struct {
	Version        string `json:"version"`
	ConversationID string `json:"conversation_id"`
	RunID          string `json:"run_id"`
	AcceptedSeq    int64  `json:"accepted_seq"`
	Status         string `json:"status"`
	Revision       string `json:"revision,omitempty"`
}

type CompactRequest

type CompactRequest struct {
	ConversationID   string `json:"conversation_id,omitempty"`
	ClientRequestID  string `json:"client_request_id"`
	ExpectedRevision string `json:"expected_revision"`
}

type ContentBlock

type ContentBlock struct {
	Type       string      `json:"type"`
	Text       string      `json:"text,omitempty"`
	ImageURL   string      `json:"image_url,omitempty"`
	FileURL    string      `json:"file_url,omitempty"`
	Filename   string      `json:"filename,omitempty"`
	MimeType   string      `json:"mime_type,omitempty"`
	ToolCall   *ToolCall   `json:"tool_call,omitempty"`
	ToolResult *ToolResult `json:"tool_result,omitempty"`
}

func (ContentBlock) Validate

func (b ContentBlock) Validate() error

type CreateSessionRequest

type CreateSessionRequest struct {
	CWD      string    `json:"cwd,omitempty"`
	Model    ModelRef  `json:"model"`
	Title    string    `json:"title,omitempty"`
	Messages []Message `json:"messages,omitempty"`
}

type EditSessionRequest

type EditSessionRequest struct {
	ExpectedRevision string            `json:"expected_revision"`
	MessageRef       HistoryMessageRef `json:"message_ref"`
	Replacement      Message           `json:"replacement"`
}

type ElicitField added in v0.107.26

type ElicitField = ai.ElicitField

ElicitField is one input of an MCP elicitation form; ElicitOption one choice of a choice field. See ai.ElicitField for the meaning of each key.

type ElicitOption added in v0.107.26

type ElicitOption = ai.ElicitOption

ElicitField is one input of an MCP elicitation form; ElicitOption one choice of a choice field. See ai.ElicitField for the meaning of each key.

type Elicitation added in v0.107.26

type Elicitation = ai.Elicitation

Elicitation is one elicitation in a tool call's history and tool.result (ToolRunInfo.Elicitations).

type ElicitationAnswerRequest added in v0.107.26

type ElicitationAnswerRequest struct {
	ConversationID string         `json:"conversation_id"`
	RunID          string         `json:"run_id"`
	ElicitationID  string         `json:"elicitation_id"`
	Action         string         `json:"action"`
	Content        map[string]any `json:"content,omitempty"`
}

ElicitationAnswerRequest is the body of POST /v1/sessions/{id}/elicitations/{elicitation_id}. Action is "accept", "decline" or "cancel"; Content, with accept only, maps field names to values (string, number, boolean, or an array of option values for a multiple choice) and is validated against the fields.

type ElicitationRequest added in v0.107.26

type ElicitationRequest struct {
	ElicitationID string `json:"elicitation_id"`
	ToolCallID    string `json:"tool_call_id"`
	RunID         string `json:"run_id"`
	DeadlineAt    int64  `json:"deadline_at"`
	// Source is empty when an MCP server asks and "ssh" when an SSH server
	// asks during an SSHManager login (keyboard-interactive, for example a
	// one-time code). For "ssh", Server is "ssh:<host name>" and names an
	// SSH host, not an MCP server; Fields marked sensitive are prompts the
	// server does not echo.
	Source          string          `json:"source,omitempty"`
	Server          string          `json:"server"`
	Tool            string          `json:"tool"`
	Message         string          `json:"message"`
	Fields          []ElicitField   `json:"fields"`
	RequestedSchema json.RawMessage `json:"requested_schema,omitempty"`
}

ElicitationRequest is the payload of elicitation.requested: an MCP server (Server, the name it is configured under) asks the user to fill in Fields while its tool Tool runs. The client shows Server prominently, renders Fields (or RequestedSchema, the schema as the server sent it), and answers with ElicitationAnswerRequest before DeadlineAt (Unix milliseconds).

type ElicitationResolution added in v0.107.26

type ElicitationResolution struct {
	ElicitationID string         `json:"elicitation_id"`
	ToolCallID    string         `json:"tool_call_id"`
	RunID         string         `json:"run_id"`
	Source        string         `json:"source,omitempty"`
	Server        string         `json:"server"`
	Tool          string         `json:"tool"`
	Message       string         `json:"message"`
	Action        string         `json:"action"`
	Reason        string         `json:"reason"`
	Content       map[string]any `json:"content,omitempty"`
	Redacted      []string       `json:"redacted,omitempty"`
}

ElicitationResolution is the payload of elicitation.resolved. Action is what the MCP server received; Reason is "user" (the client answered), "timeout" (cancel at the deadline) or "cancelled" (cancel: the run stopped or the server withdrew the request). Content is the accepted answer without the values of sensitive fields, which Redacted names.

type Event

type Event struct {
	Version        string          `json:"version"`
	Seq            int64           `json:"seq"`
	ID             string          `json:"id,omitempty"`
	ConversationID string          `json:"conversation_id"`
	RunID          string          `json:"run_id"`
	ParentRunID    string          `json:"parent_run_id,omitempty"`
	Type           string          `json:"type"`
	CreatedAt      time.Time       `json:"created_at"`
	Payload        json.RawMessage `json:"payload,omitempty"`
}

func NewEvent

func NewEvent(seq int64, conversationID, runID, typ string, payload any) (Event, error)

func (Event) Validate

func (e Event) Validate() error

type GenerateEvent added in v0.107.6

type GenerateEvent struct {
	Version  string            `json:"version"`
	Type     string            `json:"type"`
	Text     string            `json:"text,omitempty"`
	Response *GenerateResponse `json:"response,omitempty"`
	Error    string            `json:"error,omitempty"`
}

type GenerateRequest added in v0.107.6

type GenerateRequest struct {
	Model           ModelRef         `json:"model"`
	Messages        []Message        `json:"messages"`
	Tools           []ToolDefinition `json:"tools,omitempty"`
	MaxOutputTokens int              `json:"max_output_tokens,omitempty"`
	Reasoning       string           `json:"reasoning,omitempty"`
	CacheKey        string           `json:"cache_key,omitempty"`
	Stream          bool             `json:"stream,omitempty"`
}

GenerateRequest is one model inference, not an agent/tool execution loop. Clients select a configured route; credentials and upstream URLs remain local.

type GenerateResponse added in v0.107.6

type GenerateResponse struct {
	Version string   `json:"version"`
	Model   ModelRef `json:"model"`
	Message Message  `json:"message"`
	Usage   *Usage   `json:"usage,omitempty"`
}

type GoalRequest added in v0.107.6

type GoalRequest struct {
	Action string         `json:"action"`
	Goal   string         `json:"goal,omitempty"`
	Run    *PromptRequest `json:"run,omitempty"`
}

GoalRequest manages the session goal. Set and resume start a run with Run's request identity, model and options; later rounds reuse that run's options. Pause stops the running round and keeps the goal; update replaces the goal text without starting a run; clear drops the goal.

type GoalState added in v0.107.6

type GoalState struct {
	Version             string `json:"version"`
	ConversationID      string `json:"conversation_id"`
	Goal                string `json:"goal"`
	Status              string `json:"status"`
	Round               int    `json:"round"`
	MaxRounds           int    `json:"max_rounds"`
	Reason              string `json:"reason,omitempty"`
	NextClientRequestID string `json:"next_client_request_id,omitempty"`
	NextPrompt          string `json:"next_prompt,omitempty"`
	// StartedAt is when the current goal was set or last resumed (RFC 3339); the
	// desktop goal bar shows the elapsed time from it.
	StartedAt string       `json:"started_at,omitempty"`
	Run       *RunAccepted `json:"run,omitempty"`
}

GoalState is the session goal snapshot returned by the goal route and carried by goal.updated events. Status is none, active, continuing, met, paused or cleared. A continuing event names the request id of the round the backend starts next. Reason explains a pause: user, restored, max_rounds, busy, start_failed, cancelled, failed, or awaiting_input when a round asked the user for input; the user's next plain run then resumes the goal as its round.

type HistoryMessageRef

type HistoryMessageRef struct {
	SegmentIndex int    `json:"segment_index,omitempty"`
	MessageIndex int    `json:"message_index,omitempty"`
	SegmentID    string `json:"segment_id,omitempty"`
	MessageID    string `json:"message_id,omitempty"`
	Role         string `json:"role,omitempty"`
	ContentHash  string `json:"content_hash,omitempty"`
}

type HostedSearch

type HostedSearch struct {
	Type     string               `json:"type"`
	ID       string               `json:"id"`
	Provider string               `json:"provider,omitempty"`
	Status   string               `json:"status"`
	Queries  []string             `json:"queries"`
	Sources  []HostedSearchSource `json:"sources"`
	Error    string               `json:"error,omitempty"`
}

type HostedSearchSource

type HostedSearchSource struct {
	URL        string `json:"url"`
	Title      string `json:"title,omitempty"`
	SourceType string `json:"sourceType,omitempty"`
}

type Message

type Message struct {
	ID           string         `json:"id,omitempty"`
	Role         string         `json:"role"`
	Content      []ContentBlock `json:"content,omitempty"`
	ToolCalls    []ToolCall     `json:"tool_calls,omitempty"`
	ToolCallID   string         `json:"tool_call_id,omitempty"`
	Name         string         `json:"name,omitempty"`
	Model        string         `json:"model,omitempty"`
	Provider     string         `json:"provider,omitempty"`
	Usage        *Usage         `json:"usage,omitempty"`
	HostedSearch []HostedSearch `json:"hosted_search,omitempty"`
	StopReason   string         `json:"stop_reason,omitempty"`
	CreatedAt    *time.Time     `json:"created_at,omitempty"`
	// Origin is "background" on a user-role notice the runtime delivered on its
	// own (a wait result, a process exit, a background task report, a goal
	// continuation round, the new-context notice, the output-limit continuation
	// reminder); it is absent on messages the user wrote.
	Origin string `json:"origin,omitempty"`
	// Authored exposes persisted user provenance for history display. It is
	// output metadata; ToAIMessage does not trust clients to assign authorship.
	Authored bool `json:"authored,omitempty"`
}

func FromAIMessage

func FromAIMessage(m ai.Message) Message

FromAIMessage converts the provider-neutral message into the canonical protocol shape. Use FromAIMessageValidated when malformed provider data must be rejected instead of returned for inspection. FromAIMessage converts a provider message into the canonical protocol shape.

func FromAIMessageValidated

func FromAIMessageValidated(m ai.Message) (Message, error)

func (Message) ToAIMessage

func (m Message) ToAIMessage() (ai.Message, error)

func (Message) Validate

func (m Message) Validate() error

type ModelRef

type ModelRef struct {
	Provider string `json:"provider"`
	Model    string `json:"model"`
}

type PageCursor

type PageCursor struct {
	UpdatedAt time.Time `json:"updated_at"`
	ID        string    `json:"id"`
}

type PermissionAutoResolved added in v0.107.6

type PermissionAutoResolved struct {
	ToolCallID string `json:"tool_call_id,omitempty"`
	Tool       string `json:"tool"`
	Command    string `json:"command,omitempty"`
	// Source is "rule" or "read_only".
	Source string `json:"source"`
	Rule   string `json:"rule,omitempty"`
	Scope  string `json:"scope,omitempty"`
}

PermissionAutoResolved is the payload of permission.auto_resolved.

type PermissionDecision

type PermissionDecision struct {
	PermissionID string `json:"permission_id"`
	Decision     string `json:"decision"`
	Reason       string `json:"reason,omitempty"`
	// Scope picks where allow_always stores the suggested rules: session, project
	// or user. Empty keeps the pre-rules meaning, this session only.
	Scope string `json:"scope,omitempty"`
}

type PermissionDecisionRequest

type PermissionDecisionRequest struct {
	ConversationID string             `json:"conversation_id"`
	RunID          string             `json:"run_id"`
	Decision       PermissionDecision `json:"decision"`
}

type PermissionOption

type PermissionOption struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	Kind  string `json:"kind"`
}

type PermissionPreview added in v0.107.21

type PermissionPreview struct {
	Path string `json:"path"`
	// Diff lists the changed lines as "<line> <mark> <text>", mark one of ' ',
	// '-', '+': the format of the diff block in edit and write results. It holds
	// at most 200 rows and 32 KiB; empty when the change is too large to preview.
	Diff string `json:"diff,omitempty"`
	// NewFile marks a write that creates the file.
	NewFile bool `json:"new_file,omitempty"`
	// Truncated marks a Diff cut to those limits or left out.
	Truncated bool `json:"truncated,omitempty"`
}

PermissionPreview shows a pending file change while the user decides.

type PermissionRequest

type PermissionRequest struct {
	PermissionID string `json:"permission_id"`
	Tool         string `json:"tool"`
	Command      string `json:"command,omitempty"`
	// Shell runs Command, when the tool runs one.
	Shell       string             `json:"shell,omitempty"`
	Rule        string             `json:"rule,omitempty"`
	Description string             `json:"description,omitempty"`
	Options     []PermissionOption `json:"options,omitempty"`
	// Suggestion is what allow_always would remember; absent when the action can
	// only be allowed once (capability permission_rules).
	Suggestion *PermissionSuggestion `json:"suggestion,omitempty"`
	// Scope "session" means approving also grants this kind of action for the
	// rest of the session, so clients can say so before the user decides.
	Scope string `json:"scope,omitempty"`
	// ToolCallID is the model tool call awaiting this decision, when known, so
	// clients can show the prompt beside that call.
	ToolCallID string `json:"tool_call_id,omitempty"`
	// Preview is the change a file tool (write, edit, Write, Edit) will make;
	// absent for other tools and when there is nothing to show.
	Preview *PermissionPreview `json:"preview,omitempty"`
}

type PermissionRule added in v0.107.6

type PermissionRule struct {
	ID            string `json:"id"`
	Rule          string `json:"rule"`
	Effect        string `json:"effect"`
	Scope         string `json:"scope"`
	CreatedAt     string `json:"created_at,omitempty"`
	SourceSession string `json:"source_session,omitempty"`
}

PermissionRule is one remembered rule as the rules API returns it.

type PermissionRuleCreate added in v0.107.6

type PermissionRuleCreate struct {
	Rule      string `json:"rule"`
	Effect    string `json:"effect"`
	Scope     string `json:"scope"`
	Workspace string `json:"workspace,omitempty"`
	SessionID string `json:"session_id,omitempty"`
}

PermissionRuleCreate is the body of POST /v1/permissions/rules. Workspace names the project for project scope; SessionID the session for session scope.

type PermissionRulesResponse added in v0.107.6

type PermissionRulesResponse struct {
	ProjectRoot string           `json:"project_root,omitempty"`
	Rules       []PermissionRule `json:"rules"`
}

PermissionRulesResponse answers GET /v1/permissions/rules.

type PermissionSuggestion added in v0.107.6

type PermissionSuggestion struct {
	Rules        []string `json:"rules"`
	DefaultScope string   `json:"default_scope"`
}

PermissionSuggestion lists the rules allow_always stores, all of them together, and the scope a client should preselect.

type PromptRequest

type PromptRequest struct {
	ResumeMessageID string         `json:"resume_message_id,omitempty"`
	TurnID          string         `json:"turn_id,omitempty"`
	ConversationID  string         `json:"conversation_id"`
	ClientRequestID string         `json:"client_request_id"`
	Prompt          string         `json:"prompt,omitempty"`
	Content         []ContentBlock `json:"content,omitempty"`
	Model           *ModelRef      `json:"model,omitempty"`
	Options         *RunOptions    `json:"options,omitempty"`
	HookPolicy      string         `json:"hook_policy,omitempty"`
	HookScopeID     string         `json:"hook_scope_id,omitempty"`
	StopRequested   bool           `json:"stop_requested,omitempty"`
	// PromptCommand marks Prompt as "/name args" naming a prompt command. The backend
	// expands it for the model while history keeps the text the user typed.
	PromptCommand bool `json:"prompt_command,omitempty"`
	// Snapshot is request-only text resolved at acceptance; it is never part of the wire.
	Snapshot string `json:"-"`
}

type ProtocolInfo added in v0.107.6

type ProtocolInfo struct {
	Name  string `json:"name"`
	Major int    `json:"major"`
	Minor int    `json:"minor"`
}

func CurrentProtocol added in v0.107.6

func CurrentProtocol() ProtocolInfo

type Question

type Question struct {
	ID       string           `json:"id"`
	Header   string           `json:"header,omitempty"`
	Prompt   string           `json:"prompt"`
	Options  []QuestionOption `json:"options"`
	Multiple bool             `json:"multiple,omitempty"`
}

type QuestionAnswer

type QuestionAnswer = ai.QuestionAnswer

QuestionAnswer is one answer in a question answer request, a question.resolved event and a question tool call's history. A request sends selected_label (an option's label, or with custom the user's own words) or, where capabilities.question_selected_labels is 1, selected_labels (the chosen options; with custom, selected_label adds the user's own words).

type QuestionAnswerRequest

type QuestionAnswerRequest struct {
	ConversationID string           `json:"conversation_id"`
	RunID          string           `json:"run_id"`
	QuestionID     string           `json:"question_id"`
	Answers        []QuestionAnswer `json:"answers"`
}

type QuestionOption

type QuestionOption struct {
	Label       string `json:"label"`
	Description string `json:"description,omitempty"`
	Recommended bool   `json:"recommended,omitempty"`
}

type QuestionRequest

type QuestionRequest struct {
	QuestionID string     `json:"question_id"`
	ToolCallID string     `json:"tool_call_id"`
	RunID      string     `json:"run_id"`
	DeadlineAt int64      `json:"deadline_at"`
	Questions  []Question `json:"questions"`
}

type QuestionResolution

type QuestionResolution struct {
	QuestionID string           `json:"question_id"`
	ToolCallID string           `json:"tool_call_id"`
	RunID      string           `json:"run_id"`
	Kind       string           `json:"kind"`
	Questions  []Question       `json:"questions"`
	Answers    []QuestionAnswer `json:"answers"`
	Text       string           `json:"text"`
	TimedOut   bool             `json:"timed_out,omitempty"`
	Cancelled  bool             `json:"cancelled,omitempty"`
}

type ResumeRequest

type ResumeRequest struct {
	ConversationID string `json:"conversation_id"`
	AfterSeq       int64  `json:"after_seq,omitempty"`
}

type RunAccepted

type RunAccepted struct {
	Version        string `json:"version"`
	ConversationID string `json:"conversation_id"`
	RunID          string `json:"run_id"`
	AcceptedSeq    int64  `json:"accepted_seq"`
}

type RunOptions

type RunOptions struct {
	Reasoning      string `json:"reasoning,omitempty"`
	Mode           string `json:"mode,omitempty"`
	Search         string `json:"search,omitempty"`
	ApprovalPolicy string `json:"approval_policy,omitempty"`
	PermissionMode string `json:"permission_mode,omitempty"`
	// ReviewScope "per_run" (capability ai_review_per_run) lets the permission mode alone decide
	// AI review: only auto_review reviews, with the session's model when no reviewer is set.
	// Without it the global aiApproval mode keeps applying as before.
	ReviewScope     string          `json:"review_scope,omitempty"`
	WorkspaceRoots  []WorkspaceRoot `json:"workspace_roots,omitempty"`
	Tools           *ToolSelection  `json:"tools,omitempty"`
	PlanModeEnabled bool            `json:"plan_mode_enabled,omitempty"`
	MCPServerIDs    []string        `json:"mcp_server_ids,omitempty"`
	// ClientTools are tools the connected client executes itself (for example the LiveAgent
	// desktop Browser). They are offered to the model for this run only; a call is published
	// as client_tool.requested and completes when the client posts the result.
	ClientTools []ClientTool `json:"client_tools,omitempty"`
	// Sandbox (capability run_sandbox) confines the run's shell commands, hooks
	// and terminals with the platform sandbox. It can only tighten a sandbox the
	// server is configured with. The run is refused when the machine cannot
	// enforce it; it never falls back to running unconfined.
	Sandbox *RunSandbox `json:"sandbox,omitempty"`
	// MCPElicitation (capability mcp_elicitation) says the client can show MCP
	// elicitation forms: the run publishes elicitation.requested and waits for
	// an answer. Without it an MCP server's elicitation is declined at once.
	MCPElicitation bool `json:"mcp_elicitation,omitempty"`
}

type RunSandbox added in v0.107.16

type RunSandbox struct {
	Mode    string `json:"mode,omitempty"`
	Network bool   `json:"network"`
}

RunSandbox is a run's request for OS-level confinement. Mode "workspace" lets commands read the machine (credential and LiveAgent data directories masked) and write only the workspace roots and temporary directories. Network false blocks network access.

type RunTerminal

type RunTerminal struct {
	State   string `json:"state"`
	Message string `json:"message,omitempty"`
	Error   string `json:"error,omitempty"`
	Usage   *Usage `json:"usage,omitempty"`
}

type SandboxDenial added in v0.107.21

type SandboxDenial struct {
	// Kind is "write" (outside the writable roots), "protected" (git
	// configuration, hooks or agent settings inside the workspace), "masked"
	// (a hidden credential directory) or "network" (network access is off).
	Kind string `json:"kind"`
	// Path is the refused path, absolute and with symlinks resolved; absent for
	// "network".
	Path string `json:"path,omitempty"`
	// SuggestedRoot is set only for "write" when the command itself named the
	// path, and never for a directory holding the home directory, a credential
	// directory or a system top-level directory.
	SuggestedRoot string `json:"suggested_root,omitempty"`
}

SandboxDenial is a hint recognized from a failed command's output. Nothing is granted from it: a client may offer the user to add SuggestedRoot as a writable workspace root for a later run.

type Session

type Session struct {
	SessionSummary
	Revision     string     `json:"revision"`
	SyncEpoch    string     `json:"sync_epoch,omitempty"`
	SyncRevision string     `json:"sync_revision,omitempty"`
	Messages     []Message  `json:"messages"`
	Tasks        []Subagent `json:"tasks,omitempty"`
	LastSeq      int64      `json:"last_seq"`
}

type SessionChange added in v0.107.6

type SessionChange struct {
	ID       string          `json:"id"`
	Revision string          `json:"revision"`
	Kind     string          `json:"kind"`
	Listed   bool            `json:"listed"`
	Session  *SessionSummary `json:"session,omitempty"`
}

type SessionChanges added in v0.107.6

type SessionChanges struct {
	Epoch        string          `json:"epoch"`
	HeadRevision string          `json:"head_revision"`
	MinSince     string          `json:"min_since"`
	NextSince    *string         `json:"next_since"`
	Reset        bool            `json:"reset"`
	ResetReason  string          `json:"reset_reason,omitempty"`
	More         bool            `json:"more"`
	Changes      []SessionChange `json:"changes"`
}

type SessionExternalRun added in v0.107.30

type SessionExternalRun struct {
	Client    string    `json:"client"`
	PID       int       `json:"pid,omitempty"`
	StartedAt time.Time `json:"started_at"`
}

SessionExternalRun describes a turn running in another process.

type SessionPage

type SessionPage struct {
	Sessions   []SessionSummary `json:"sessions"`
	TotalCount int              `json:"total_count"`
	Next       *PageCursor      `json:"next,omitempty"`
	Version    string           `json:"version"`
	Epoch      string           `json:"epoch,omitempty"`
	Revision   string           `json:"revision,omitempty"`
}

type SessionSnapshotInfo added in v0.107.6

type SessionSnapshotInfo struct {
	Epoch            string           `json:"epoch"`
	Revision         string           `json:"revision"`
	SnapshotID       string           `json:"snapshot_id"`
	ExpiresInSeconds int              `json:"expires_in_seconds"`
	TotalCount       int              `json:"total_count"`
	Workdirs         []SessionWorkdir `json:"workdirs"`
}

type SessionSnapshotPage added in v0.107.6

type SessionSnapshotPage struct {
	Epoch      string           `json:"epoch"`
	Revision   string           `json:"revision"`
	SnapshotID string           `json:"snapshot_id"`
	TotalCount int              `json:"total_count"`
	Sessions   []SessionSummary `json:"sessions"`
	NextOffset *int             `json:"next_offset"`
}

type SessionSummary

type SessionSummary struct {
	ID           string    `json:"id"`
	Title        string    `json:"title,omitempty"`
	CWD          string    `json:"cwd,omitempty"`
	Model        ModelRef  `json:"model"`
	CreatedAt    time.Time `json:"created_at"`
	UpdatedAt    time.Time `json:"updated_at"`
	MessageCount int       `json:"message_count"`
	Shared       bool      `json:"shared"`
	Pinned       bool      `json:"pinned,omitempty"`
	// Archived is always present so clients can tell archived sessions apart in
	// lists requested with archived=include (capability session_archive).
	Archived bool `json:"archived"`
	// ForkedFrom names the session this one was branched from; ForkSeq is the last copied message.
	ForkedFrom string `json:"forked_from,omitempty"`
	ForkSeq    int    `json:"fork_seq,omitempty"`
	// ExternalRun is set while another process sharing the data root (the kn
	// terminal UI, kn run, or another backend) is running a turn in this session
	// (capability session_external_runs). This backend refuses runs and history
	// edits for the session until it is cleared.
	ExternalRun *SessionExternalRun `json:"external_run,omitempty"`
}

type SessionWorkdir added in v0.107.6

type SessionWorkdir struct {
	CWD       string    `json:"cwd"`
	Count     int       `json:"count"`
	UpdatedAt time.Time `json:"updated_at"`
}

type ShareStatus

type ShareStatus struct {
	ConversationID    string    `json:"conversation_id"`
	Enabled           bool      `json:"enabled"`
	Token             string    `json:"token,omitempty"`
	CreatedAt         time.Time `json:"created_at,omitempty"`
	UpdatedAt         time.Time `json:"updated_at,omitempty"`
	RedactToolContent bool      `json:"redact_tool_content"`
}

type ShareUpdateRequest

type ShareUpdateRequest struct {
	Enabled           bool  `json:"enabled"`
	RedactToolContent *bool `json:"redact_tool_content,omitempty"`
}

type SlashCommand added in v0.107.6

type SlashCommand struct {
	Name         string `json:"name"`
	Description  string `json:"description"`
	ArgumentHint string `json:"argument_hint,omitempty"`
	Kind         string `json:"kind"`
	Source       string `json:"source"`
}

SlashCommand is one entry of the desktop slash command catalog. Kind "action" is handled by the client by name; kind "prompt" is sent as a run with prompt_command.

type SlashCommandList added in v0.107.6

type SlashCommandList struct {
	Version  string         `json:"version"`
	Commands []SlashCommand `json:"commands"`
}

type Subagent

type Subagent struct {
	ID          string   `json:"id"`
	ParentID    string   `json:"parent_id,omitempty"`
	Description string   `json:"description"`
	Status      string   `json:"status"`
	Model       ModelRef `json:"model"`
	Attempt     int      `json:"attempt,omitempty"`
	Report      string   `json:"report,omitempty"`
	Error       string   `json:"error,omitempty"`
	// ParentToolCallID is the id of the parent's `subagent` tool call that
	// started this subagent, so a client can show both as one item.
	ParentToolCallID string `json:"parent_tool_call_id,omitempty"`
	// Background is true for subagents started with background=true.
	Background bool `json:"background,omitempty"`
	// Usage, ToolCount and DurationMS cover the subagent's own requests and
	// tool calls; DurationMS is set once it has ended.
	Usage      *Usage     `json:"usage,omitempty"`
	ToolCount  int        `json:"tool_count,omitempty"`
	DurationMS int64      `json:"duration_ms,omitempty"`
	StartedAt  *time.Time `json:"started_at,omitempty"`
	UpdatedAt  *time.Time `json:"updated_at,omitempty"`
	EndedAt    *time.Time `json:"ended_at,omitempty"`
	// External is true while the subagent runs in another process sharing the
	// session store (a kn terminal). Its events are not streamed; clients poll
	// the list and the transcript, which that process saves as it goes.
	External bool `json:"external,omitempty"`
}

type SubagentEvent

type SubagentEvent struct {
	Subagent Subagent `json:"subagent"`
}

type SubagentList added in v0.107.19

type SubagentList struct {
	Subagents []Subagent `json:"subagents"`
	LastSeq   int64      `json:"last_seq"`
}

SubagentList answers GET /v1/sessions/{id}/subagents.

type SubagentTranscript added in v0.107.19

type SubagentTranscript struct {
	Subagent Subagent  `json:"subagent"`
	Messages []Message `json:"messages"`
	LastSeq  int64     `json:"last_seq"`
	// Live is true while the subagent is still running in this backend.
	Live bool `json:"live"`
}

SubagentTranscript answers GET /v1/sessions/{id}/subagents/{task}: the subagent's transcript up to LastSeq. A client continues it live with the child events after LastSeq.

type TextDelta

type TextDelta struct {
	Text string `json:"text"`
}

type TextGenerateRequest

type TextGenerateRequest struct {
	Model    ModelRef  `json:"model"`
	Messages []Message `json:"messages"`
	Output   string    `json:"output,omitempty"`
}

TextGenerateRequest is the stateless, no-tools auxiliary generation contract. Messages use the same canonical model as session history but only text blocks and system/developer/user/assistant roles are accepted by the backend.

type TextGenerateResponse

type TextGenerateResponse struct {
	Version string   `json:"version"`
	Text    string   `json:"text"`
	Model   ModelRef `json:"model"`
	Usage   *Usage   `json:"usage,omitempty"`
}

type ToolCall

type ToolCall struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
	// ToolRunInfo is filled in history once the call has run; absent in
	// tool.call events and in messages a client sends.
	ToolRunInfo
}

type ToolCallEvent

type ToolCallEvent struct {
	ToolCall ToolCall `json:"tool_call"`
}

type ToolDefinition

type ToolDefinition struct {
	Name        string          `json:"name"`
	Description string          `json:"description,omitempty"`
	Parameters  json.RawMessage `json:"parameters,omitempty"`
}

type ToolResult

type ToolResult struct {
	Content   []ContentBlock `json:"content,omitempty"`
	ID        string         `json:"id"`
	Name      string         `json:"name,omitempty"`
	Output    string         `json:"output"`
	Failed    bool           `json:"failed,omitempty"`
	Cancelled bool           `json:"cancelled,omitempty"`
	ToolRunInfo
}

type ToolResultEvent

type ToolResultEvent struct {
	ToolResult ToolResult `json:"tool_result"`
}

type ToolRunInfo added in v0.107.21

type ToolRunInfo struct {
	// ExitCode is the exit status of the command a shell tool (bash, Bash,
	// ManagedProcess, ProcessWait, ProcessStop) ran or observed, 0 included;
	// absent for other tools and for a command that timed out, was cancelled,
	// was killed or is still running.
	ExitCode *int `json:"exit_code,omitempty"`
	// TimedOut marks a command killed when its timeout passed.
	TimedOut bool `json:"timed_out,omitempty"`
	// DurationMs is the tool's own wall-clock time in milliseconds, rounded
	// up, without time spent waiting for permission.
	DurationMs int64 `json:"duration_ms,omitempty"`
	// SandboxDenial explains a shell command the OS sandbox most likely
	// stopped. Only in tool.result events; history keeps the same explanation
	// in the output text alone.
	SandboxDenial *SandboxDenial `json:"sandbox_denial,omitempty"`
	// QuestionAnswers is what the user answered a question or AskUserQuestion
	// call, one entry per question, as question.resolved reports it.
	QuestionAnswers []QuestionAnswer `json:"question_answers,omitempty"`
	// Elicitations are the forms an MCP tool asked the user to fill in during
	// the call, in order, including those declined without asking (reason
	// no_client, unattended or limit). Sensitive values are left out.
	Elicitations []Elicitation `json:"elicitations,omitempty"`
}

ToolRunInfo describes how a tool call ran, for display. Every field is optional and absent when unknown; the model never sees them.

type ToolSelection

type ToolSelection struct {
	Policies map[string]string `json:"policies,omitempty"`
	Enabled  []string          `json:"enabled,omitempty"`
	Disabled []string          `json:"disabled,omitempty"`
}

type ToolStatus

type ToolStatus struct {
	ToolCallID string `json:"tool_call_id,omitempty"`
	Tool       string `json:"tool"`
	Status     string `json:"status"`
	Message    string `json:"message,omitempty"`
	Compaction bool   `json:"compaction,omitempty"`
}

type UpdateSessionRequest

type UpdateSessionRequest struct {
	Model           *ModelRef `json:"model,omitempty"`
	Title           *string   `json:"title,omitempty"`
	Pinned          *bool     `json:"pinned,omitempty"`
	Archived        *bool     `json:"archived,omitempty"`
	Shared          *bool     `json:"shared,omitempty"`
	ShareRedactTool *bool     `json:"share_redact_tool,omitempty"`
	// CWD moves the session to another workspace. It must be an absolute path to an
	// existing directory; tools in later turns run there.
	CWD *string `json:"cwd,omitempty"`
}

type Usage

type Usage struct {
	InputTokens      int `json:"input_tokens,omitempty"`
	OutputTokens     int `json:"output_tokens,omitempty"`
	CachedTokens     int `json:"cached_tokens,omitempty"`
	CacheWriteTokens int `json:"cache_write_tokens,omitempty"`
}

func FromAIUsage

func FromAIUsage(u *ai.Usage) *Usage

type WorkspaceRoot

type WorkspaceRoot struct {
	Path   string `json:"path"`
	Access string `json:"access"`
}

Jump to

Keyboard shortcuts

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