Documentation
¶
Overview ¶
Package api defines the internal contracts between vibekit components. All cross-component calls go through these interfaces, enabling testability (mock any component) and swappability.
This package contains two concern groups:
- Domain types and interfaces — the contract surface (interfaces.go, domain_chat.go, events.go, commands.go, domain_rpc.go, mcp.go, push_types.go, methods.go, strings.go).
- HTTP response/request helpers (httputil.go, decode.go) — WriteJSON, BadRequest, MethodNotAllowed, etc.
Atomic file I/O (SaveBytes, bounded reads) lives in the external cplieger/atomicfile package, not here.
Implementation packages import api, never the reverse. Domain types Tag, FileChange, and ConflictPayload live in checkpoint/types (a leaf package with zero internal dependencies).
Index ¶
- Constants
- Variables
- func BadRequest(w http.ResponseWriter, msg string)
- func Conflict(w http.ResponseWriter, msg string)
- func DecodeBody(w http.ResponseWriter, r *http.Request, v any, errMsg string) bool
- func DecodeBodyOptional(w http.ResponseWriter, r *http.Request, v any)
- func DecodeJSON(w http.ResponseWriter, r *http.Request, v any) bool
- func ErrorJSON(msg string) map[string]string
- func ErrorJSONWithCode(msg, code string) map[string]string
- func Forbidden(w http.ResponseWriter, msg string)
- func InternalError(w http.ResponseWriter, err error)
- func JSONHeaders(w http.ResponseWriter)
- func LimitBody(w http.ResponseWriter, r *http.Request, maxBytes int64)
- func MethodNotAllowed(w http.ResponseWriter)
- func NotFound(w http.ResponseWriter, msg string)
- func Ok(w http.ResponseWriter)
- func RequireMethod(w http.ResponseWriter, r *http.Request, method string) bool
- func SanitizeOutput(s string) string
- func SanitizeUnicode(s string) string
- func ServerError(w http.ResponseWriter, clientMsg string, err error)
- func StripANSI(s string) string
- func StripCodeFence(s string) string
- func TagExcluded(text string, tags []string) bool
- func TextBlock(content string) map[string]any
- func ValidChatID(id string) bool
- func ValidIdent(s string) bool
- func ValidMessageID(id string) bool
- func ValidRequestID(id string) bool
- func ValidSessionID(s string) bool
- func WorkingLabelForKind(kind ToolKind, title string) string
- func WriteJSON(w http.ResponseWriter, v any)
- func WriteJSONStatus(w http.ResponseWriter, code int, v any)
- func WriteRawJSON(w http.ResponseWriter, data []byte)
- type ACPBridge
- type ACPBridgeFactory
- type ACPUpdateKind
- type AccountUsage
- type AccountUsageBreakdown
- type AccountUsageProvider
- type Attachment
- type AuthHandler
- type AvailableCommand
- type Block
- type BlockType
- type Broadcaster
- type Chat
- type ChatDeletedPayload
- type ChatHeader
- type ChatID
- type ChatStatusPayload
- type ChatStore
- type CheckpointConflictsResponse
- type CheckpointDiffResponse
- type CheckpointRestorePreviewResponse
- type CheckpointRestoredPayload
- type CheckpointService
- type ClearReason
- type ClientCommand
- type CodeReference
- type CodeReferencesPayload
- type CommandBridge
- type CommandType
- type CommandsUpdatedPayload
- type CompactionStartedPayload
- type ConflictDetectedPayload
- type ConnectedPayload
- type CreateChatCommand
- type EffortLevel
- type ElicitationNeededPayload
- type ElicitationPropertySchema
- type ElicitationRequestSchema
- type ElicitationResponseCommand
- type ElicitationResult
- type ErrorCode
- type ErrorPayload
- type Event
- type EventKind
- type EventType
- type FileChange
- type FileHandler
- type ForgesChangedPayload
- type GitHandler
- type GovernanceFeatures
- type GovernanceStatePayload
- type HooksChangedPayload
- type Hub
- type KnowledgeIndexingPayload
- type LimitedWriter
- type MCPConfig
- type MCPConfigChangedPayload
- type MCPConnectedPayload
- type MCPDisconnectedPayload
- type MCPFailedPayload
- type MCPOAuthPayload
- type MCPPrewarmPayload
- type MCPPromptArg
- type MCPPromptInfo
- type MCPResourceInfo
- type MCPServerState
- type MCPSnapshotServer
- type Message
- type MessageChunkPayload
- type MeteringItem
- type ModeChangedPayload
- type ModelID
- type OpenExternalURLPayload
- type PendingAction
- type PendingChange
- type PendingChangeAddedPayload
- type PendingChangeKind
- type PendingChangeResolvedPayload
- type PendingChangesClearedPayload
- type PendingStore
- type PendingTrustClearedPayload
- type PendingTrustEnabledPayload
- type PermissionNeededPayload
- type PermissionOption
- type PermissionOutcome
- type PermissionOutcomeInner
- type PermissionResponseCommand
- type PermissionsChangedPayload
- type PlanEntry
- type PlanStatus
- type PolicyErrorItem
- type PolicyErrorPayload
- type PolicyExplainRequest
- type PolicyExplainResult
- type PolicyProvider
- type PolicyRule
- type PolicyRuleCore
- type PolicyView
- type PromptCommand
- type PushKind
- type PushService
- type PushSubscription
- type PushSubscriptionKeys
- type RPCError
- type RPCErrorOut
- type RPCNotification
- type RPCRequest
- type RPCResponse
- type RPCResponseOut
- type RefusalInfo
- type ResolveAllPendingChangesCommand
- type ResolvePendingChangeCommand
- type ResolvePendingChangePartialCommand
- type RewindChatCommand
- type Role
- type RouteHandler
- type SafetyPropertiesPayload
- type SafetyProperty
- type SafetyStatus
- type SafetyStatusPayload
- type ServerEvent
- type SessionID
- type SessionMode
- type SessionModel
- type SetEffortCommand
- type SetModeCommand
- type SetSupervisedModeCommand
- type SettingsUpdatedPayload
- type Spec
- type SpecTaskChange
- type SpecTaskChangedPayload
- type SpecTaskNode
- type SpecTaskPBT
- type SpecsResponse
- type StartOpts
- type SteeringGenerator
- type StopReason
- type SwitchModelCommand
- type SystemTool
- type TerminalCreatedPayload
- type TerminalExitedPayload
- type TerminalOutputPayload
- type ToolCall
- type ToolCallPayload
- type ToolCallUpdatePayload
- type ToolCatalogHit
- type ToolCatalogInfo
- type ToolDiff
- type ToolInfo
- type ToolJob
- type ToolJobAccepted
- type ToolJobChangedPayload
- type ToolJobOutputPayload
- type ToolKind
- type ToolLocation
- type ToolRemoveResponse
- type ToolStatus
- type ToolsJobsResponse
- type ToolsList
- type ToolsSearchResponse
- type TransportError
- type TurnEndedPayload
- type TurnStatePayload
- type Usage
- type UserInputNeededPayload
- type UserInputOption
- type UserInputResponseCommand
- type UserInputSubOption
- type UtilityPrompter
- type WorkingLabelPayload
Constants ¶
const ( UserInputActionAnswered = "answered" UserInputActionDismissed = "dismissed" )
UserInputActionAnswered and UserInputActionDismissed are the accepted actions for type="user_input_response". "answered" carries the user's answer text; "dismissed" (dialog closed / question skipped) makes the agent advance to its next phase — KAS treats anything non-answered that way, so no other action values exist.
const ( ElicitationActionAccept = "accept" ElicitationActionDecline = "decline" ElicitationActionCancel = "cancel" )
Elicitation actions per the MCP ElicitResult contract.
const ( WorkingLabelThinking = "Thinking" WorkingLabelApproval = "Waiting for approval" WorkingLabelInput = "Waiting for input" )
Working-label constants. Centralised so hub callers reference these instead of bare string literals; a future label rename lands in one place.
const ( // RPCCodeInternal is the JSON-RPC 2.0 "Internal error" code (-32603). RPCCodeInternal = -32603 // RPCCodeNotIdle indicates the session is still processing a prior turn. RPCCodeNotIdle = -32001 // RPCCodeBridgeExited is a server-defined code indicating the ACP bridge process exited. RPCCodeBridgeExited = -32000 )
RPC error code constants for typed dispatch in retry logic.
const ( MethodInitialize = "initialize" MethodSessionNew = "session/new" MethodSessionLoad = "session/load" MethodSetMode = "session/set_mode" MethodSessionFork = "session/fork" MethodCancel = "session/cancel" )
Bridge lifecycle methods — used by the bridge package to drive the kiro-cli subprocess through initialize → session/new|load. On v3 (KAS) model/mode/effort switches all route through session/set_config_option (session/set_model is gone), and session/fork branches a session at a message id (see command/rewind.go).
const ( MethodFSRead = "fs/read_text_file" MethodFSWrite = "fs/write_text_file" )
File-system protocol method names (ACP fs/* namespace). Exported so test files can reference the canonical string without bare literals.
const ( MethodSessionUpdate = "session/update" MethodRequestPermission = "session/request_permission" MethodSetConfigOption = "session/set_config_option" )
Session-level ACP method names — streaming updates, permissions, config.
const ( ConfigOptionModel = "model" ConfigOptionMode = "mode" ConfigOptionEffort = "effortLevel" )
Session config-option ids for session/set_config_option (v3/KAS). Model and reasoning-effort switches route through set_config_option with one of these configId values plus a matching value string. (Verified against the KAS 2.12 acp-server bundle: MODEL_CONFIG_ID / EFFORT_LEVEL_CONFIG_ID.) Mode switches use the dedicated session/set_mode method, not this path.
const ( ContentKeyType = "type" ContentKeyText = "text" )
ACP content-block JSON field name constants. These are the wire-format keys inside a content block object (distinct from ContentTypeText which is the field VALUE). Single source of truth for hub, command, and translate packages.
const ( PolicyEffectAllow = "allow" PolicyEffectDeny = "deny" PolicyEffectAsk = "ask" )
Policy effect values (3-valued). deny > ask > allow at evaluation time.
const ( PolicyScopeKiro = "kiro" PolicyScopeAdministration = "administration" PolicyScopeUser = "user" PolicyScopeWorkspace = "workspace" PolicyScopeAgent = "agent" PolicyScopeSession = "session" )
Policy scope values. Only user + workspace are file-editable by vibekit; kiro/administration are read-only baselines, agent comes from the agent profile, and session is runtime state.
const AgentEngineV3 = "v3"
AgentEngineV3 is the only agent engine vibekit speaks: `kiro-cli acp --agent-engine v3` (KAS). It requires the host to answer _kiro/auth/getAccessToken + _kiro/terminal/shell_type and emits the reshaped _kiro/* extension set. The legacy v1/v2 identifiers were removed with the v2 wire — vibekit is v3-only (resolveAgentEngine).
const ContentTypeText = "text"
ContentTypeText is the ACP content-block type discriminator for plain text content. Used across hub, command, and translate packages; declared here as a single source of truth so a protocol rename is one edit.
const DefaultChatName = "New conversation"
DefaultChatName is the fallback name for newly created chats when the client does not supply one.
const ErrMsgInvalidChatID = "invalid chat_id"
ErrMsgInvalidChatID is the single source of truth for the HTTP error message returned when a chat ID fails validation.
ErrMsgUtilityUnavailable is the canonical error message returned when the utility bridge (LLM prompt function) is not wired. Used by both the git and server packages to keep the error string in one place.
const JSONKeyError = "error"
JSONKeyError is the standard JSON error response key.
const JSONKeyName = "name"
JSONKeyName is the standard JSON field name for "name" in ACP wire format. Used in content blocks, command descriptors, and MCP entries.
const JSONKeyOutput = "output"
JSONKeyOutput is the standard JSON response key for successful command output. Used by git/ and server/ packages.
const KeySessionID = "sessionId"
KeySessionID is the ACP wire key for the session identifier in parameter maps. Single source of truth; hub and command packages reference this constant instead of bare "sessionId" literals.
const MIMETypeJSON = "application/json"
MIMETypeJSON is the standard MIME type for JSON content.
const MaxChatNameBytes = 512
MaxChatNameBytes caps the byte length of chat names at creation and rename boundaries. All code paths that set Chat.Name should enforce this limit.
const MaxJSONBody = 1024 * 1024
MaxJSONBody is the maximum size for JSON request bodies (1 MiB).
const (
MethodElicitationCreate = "_kiro/mcp/elicitation"
)
MCP elicitation method name. On v3 (KAS) an MCP server's structured-input request is forwarded to us as the extension request _kiro/mcp/elicitation (a JSON-RPC request with an id, delivered like fs/*). The params nest the elicitation body under an "elicitation" object with sessionId/toolCallId at the top level; we surface a form and reply with {action, content} on the request id. Gated by the clientCapabilities.elicitation capability advertised in bridge.initialize(). v3 has no elicitation-complete method.
const (
MethodKiroUserInput = "_kiro/userInput"
)
Agent user-input method name. On v3 (KAS, 2.14+) the agent's user_input tool (structured questions: plan-mode clarifications, spec gates) is forwarded to us as the extension request _kiro/userInput (a JSON-RPC request with an id, delivered like _kiro/mcp/elicitation) carrying {sessionId, toolCallId, question, options[{title, description, recommended, subOptionsLabel, subOptions[]}]}. We surface a question dialog and reply {action:"answered", answer:"<text>"} on the request id; any other action makes KAS advance to the next phase. Gated by the initialize capability _meta.kiro.userInput:true — without it KAS flattens the question into a session/request_permission and SKIPS free-form (no-options) questions entirely.
const (
MethodPrompt = "session/prompt"
)
Session-level ACP method name for prompts.
const ModelAuto = "auto"
ModelAuto is the sentinel model value meaning "keep current / use task-based selection". Used by bridge, hub, and model-switch logic.
const MsgInternalError = "internal error"
MsgInternalError is the standard client-facing message for 500 responses.
const SecretMask = "***"
SecretMask is the placeholder value returned for every secret on public reads. Clients send this unchanged on update to keep the stored value; any other value replaces it.
Variables ¶
var ErrChatNotFound = errors.New("chat not found")
ErrChatNotFound is the ChatStore sentinel for operations addressing a chat id with no record (see PromoteRewind).
var ErrNotIdle = errors.New("session not idle")
ErrNotIdle is the sentinel for "session not idle" errors from kiro-cli. Wraps the raw RPC error when the message contains "not idle" but the code isn't RPCCodeNotIdle, unifying the detection path for callers that need errors.Is classification.
var ErrNotRewind = errors.New("not a rewind chat")
ErrNotRewind is the ChatStore sentinel for rewind-family transitions invoked on a chat with no parent linkage (see PromoteRewind).
var HiddenTags = []string{
"[deprecated]",
"[legacy]",
}
HiddenTags are the bracketed markers used by the UI model picker and the bridge to hide end-of-life models from the user. This is a subset of the models package's excludedTags: [Internal] and [Experimental] models are shown in the picker but excluded from ambient-task selection.
Functions ¶
func BadRequest ¶
func BadRequest(w http.ResponseWriter, msg string)
BadRequest writes a 400 with {"error": msg}.
func Conflict ¶
func Conflict(w http.ResponseWriter, msg string)
Conflict writes a 409 with {"error": msg}.
func DecodeBody ¶
DecodeBody caps + decodes exactly one JSON value into v via webhttp.DecodeJSONInto (rejecting trailing data), returning true on success. On any decode failure it writes vibekit's bare {"error":errMsg} 400 and returns false.
func DecodeBodyOptional ¶
func DecodeBodyOptional(w http.ResponseWriter, r *http.Request, v any)
DecodeBodyOptional applies LimitBody and decodes JSON into v. Unlike DecodeBody, a decode failure is silently ignored (v keeps its zero value) because the caller accepts an empty request body.
func DecodeJSON ¶
DecodeJSON is the shared three-step JSON decode prelude: check Content-Type, cap body at MaxJSONBody via MaxBytesReader, and distinguish an oversize request (413) from a malformed body (400). Returns true when v was populated successfully; false when an error response has already been written to w.
func ErrorJSON ¶
ErrorJSON returns the canonical error response map for JSON encoding. Use with WriteJSONStatus to write error responses consistently.
func ErrorJSONWithCode ¶
ErrorJSONWithCode returns an error response map with an additional machine-readable "code" field. Used by forge handlers that surface a stable error code alongside the human-readable message.
func Forbidden ¶
func Forbidden(w http.ResponseWriter, msg string)
Forbidden writes a 403 with {"error": msg}.
func InternalError ¶
func InternalError(w http.ResponseWriter, err error)
InternalError writes a 500 with {"error": "internal error"} and logs the actual error at slog.Error for correlation. Never exposes internal error details to HTTP clients.
func JSONHeaders ¶
func JSONHeaders(w http.ResponseWriter)
JSONHeaders sets the standard JSON response headers (Content-Type and X-Content-Type-Options). Exported for use by internal/fileutil.
func LimitBody ¶
func LimitBody(w http.ResponseWriter, r *http.Request, maxBytes int64)
LimitBody wraps r.Body with MaxBytesReader to prevent oversized requests. It delegates to webhttp.LimitBody so the body-cap mechanism is shared fleet-wide.
func MethodNotAllowed ¶
func MethodNotAllowed(w http.ResponseWriter)
MethodNotAllowed writes a 405 with a standard message.
func NotFound ¶
func NotFound(w http.ResponseWriter, msg string)
NotFound writes a 404 with {"error": msg}.
func Ok ¶
func Ok(w http.ResponseWriter)
Ok writes a 200 with {"ok": true} — the standard "action succeeded" response used by the handful of endpoints that don't return data.
func RequireMethod ¶
RequireMethod returns true if r.Method matches method; otherwise it writes a 405 response and returns false.
func SanitizeOutput ¶
SanitizeOutput applies both ANSI stripping and Unicode sanitization, iterating to a fixed point. A single pass is not enough: removing a hidden Unicode char (e.g. a zero-width space inside "\x1b(\u200b0") can complete an escape sequence that the next StripANSI pass then strips. Iterating guarantees the result is fully sanitized — no residual escapes an attacker hid behind zero-width chars — and makes the function idempotent.
Termination: SanitizeUnicode normalizes any invalid UTF-8 byte to a single U+FFFD rune (via strings.Map), so after the first pass the string is valid UTF-8 and every subsequent pass only removes runes. The rune count is therefore non-increasing and the fixed point is reached in O(len(s)) passes. (Byte length is NOT monotone — an invalid byte expands to a 3-byte U+FFFD on the first pass — so the guarantee is stated in runes, not bytes.) The output is always valid UTF-8, safe to persist to JSON chat files or echo to clients.
func SanitizeUnicode ¶
SanitizeUnicode strips hidden Unicode characters that could be used for prompt injection via tool output. Covers TAG characters (U+E0000-E007F), zero-width spaces/joiners, format controls, and other invisible codepoints that Q Developer CLI's ExecuteCmd also strips. Apply alongside StripANSI on all tool output before persisting to chat files.
func ServerError ¶
func ServerError(w http.ResponseWriter, clientMsg string, err error)
ServerError writes a 500 with a caller-specified client-visible message and logs the actual error at slog.Error. Use when the handler wants to surface a safe, specific message (e.g. "save failed") while still logging the raw error for debugging.
func StripCodeFence ¶
StripCodeFence removes a single leading/trailing markdown code fence from model output. Models sometimes wrap their answer in ```lang ... ``` despite explicit instructions; this is a low-cost safety net that matters because the output goes straight into the editor buffer or commit message.
Semantics: strips one wrapping fence (the outermost). Intentional fences inside the content (e.g. a PR description containing code blocks) are preserved. This is the correct behaviour for both the git commit-message and server utility-bridge paths.
func TagExcluded ¶
TagExcluded returns true if text contains any of the given bracketed tags (case-insensitive).
func TextBlock ¶
TextBlock returns a canonical ACP text content block:
{"type": "text", "text": content}
Eliminates ad-hoc map construction across hub, command, and translate.
func ValidChatID ¶
ValidChatID reports whether id is a valid chat identifier. Accepts ULIDs, UUIDs, and the legacy "chat-<ms>" shape: alphanumerics, hyphens, and underscores only. Rejects empty, >128 chars, and anything containing path separators or traversal segments. This is the single source of truth for chat ID validation; hub/command.go and chat/store.go both delegate here.
func ValidIdent ¶
ValidIdent reports whether s is safe to use as an agent or model identifier. Empty strings pass (the field is optional); non-empty strings must match identRe AND must not start with '.' or '-' AND must not be all-dot strings. This is the single source of truth; bridge/bridge.go and hub/command.go both delegate here.
func ValidMessageID ¶
ValidMessageID reports whether id is safe to echo on SSE and store on disk as the ID field of a message. This is the single source of truth; hub and command packages delegate here.
func ValidRequestID ¶
ValidRequestID reports whether the given request_id is safe to use as an idempotency cache key. Empty is valid (field is optional).
Deliberately DISTINCT from webhttp.ValidRequestID despite the shared name: that one gates the inbound X-Request-ID header (1..64 chars, no dots or colons, empty invalid), while this one gates the optional client-supplied JSON request_id field on the message-ID charset (dots and colons allowed, up to 128 bytes). Do not unify them — adopting the header rule here would reject idempotency keys existing clients legitimately send.
func ValidSessionID ¶
ValidSessionID reports whether s is safe to use as an ACP session id. Rejects empty strings, strings over 128 bytes, path separators, NUL, and parent-dir references. Session ids (v3: `sess_`-prefixed) are concatenated into filesystem paths under $KIRO_HOME/sessions/; this function is the single source of truth for that safety gate. bridge/bridge.go delegates here.
func WorkingLabelForKind ¶
WorkingLabelForKind maps a tool kind to a human-readable label. Matches ASAI's VV() function from the frontend reducer.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, v any)
WriteJSON encodes v as JSON with status 200.
func WriteJSONStatus ¶
func WriteJSONStatus(w http.ResponseWriter, code int, v any)
WriteJSONStatus sets the JSON headers, writes the status code, and encodes v. An encode failure after the status is committed is logged at Warn (by webhttp) rather than returned, since the response line is already on the wire.
func WriteRawJSON ¶
func WriteRawJSON(w http.ResponseWriter, data []byte)
WriteRawJSON writes pre-marshalled JSON bytes with the standard Content-Type + X-Content-Type-Options headers. Use for pass-through of cached command replies and upstream JSON bodies (e.g. kiro-cli slash-command results) where json.Marshal would be a redundant round-trip. Write errors are best-effort (client may have hung up).
Types ¶
type ACPBridge ¶
type ACPBridge interface {
// Start launches a fresh kiro-cli ACP subprocess. If
// StartOpts.SessionID is empty, a new ACP session is created
// (session/new). If populated, the existing session is resumed
// (session/load). Exactly one call per bridge instance. ctx enables
// caller-driven cancellation of the startup handshake.
Start(ctx context.Context, opts *StartOpts) error
// Stop kills the subprocess. NotifCh closes. Must be called at most
// once per bridge instance.
Stop()
// Call sends a JSON-RPC request and waits for its matching response.
// The provided context enables caller-driven cancellation; if ctx is
// cancelled before the response arrives, Call returns ctx.Err().
Call(ctx context.Context, method string, params any) (*RPCResponse, error)
// Notify sends a JSON-RPC notification (no response expected). ctx
// enables cancellation before the write is attempted.
Notify(ctx context.Context, method string, params any) error
// Respond writes a JSON-RPC response to an incoming request from
// kiro-cli (e.g. fs/read_text_file). ctx enables cancellation before
// the write is attempted.
Respond(ctx context.Context, id int64, result any, err error) error
// SessionID returns the ACP session id after Start completes.
SessionID() SessionID
// ModelID returns the current model id after Start completes.
ModelID() ModelID
// CurrentMode returns the currently-active session mode id (empty
// if the agent doesn't expose modes).
CurrentMode() string
// Modes returns the set of session modes the running agent
// supports. Empty for agents that don't expose modes.
Modes() []SessionMode
// Models returns the set of models the agent can swap to, with
// deprecated/internal entries filtered out. Zero fallback: if
// kiro-cli returns nothing, the slice is empty.
Models() []SessionModel
// SetModel performs an in-session model swap via
// session/set_config_option (configId "model") — v3 has no
// session/set_model. ctx enables caller-driven cancellation of the
// RPC call.
SetModel(ctx context.Context, modelID string) error
// NotifCh yields incoming ACP notifications. Closes when the
// subprocess exits.
NotifCh() <-chan *RPCResponse
}
ACPBridge manages a single kiro-cli ACP subprocess for one chat. Methods are safe for concurrent use; Call and Notify serialize writes to the subprocess stdin internally. IsPrompting/SetPrompting are wrappers' state; the bridge itself has no "busy" concept.
type ACPBridgeFactory ¶
type ACPBridgeFactory func() ACPBridge
ACPBridgeFactory creates new ACPBridge instances. The hub calls it once per chat to spawn a fresh kiro-cli subprocess; each factory invocation is a new bridge.
type ACPUpdateKind ¶
type ACPUpdateKind string
ACPUpdateKind identifies the subtype of an ACP session/update notification. Using typed constants prevents typos in the dispatch map and makes the protocol surface discoverable.
const ( ACPUpdateAgentChunk ACPUpdateKind = "agent_message_chunk" ACPUpdateThoughtChunk ACPUpdateKind = "agent_thought_chunk" ACPUpdateToolCall ACPUpdateKind = "tool_call" ACPUpdateToolUpdate ACPUpdateKind = "tool_call_update" ACPUpdatePlan ACPUpdateKind = "plan" ACPUpdateModeChange ACPUpdateKind = "current_mode_update" // v3 (KAS) session/update sub-kinds. v3 moves context-usage stats and // the available-command catalog into session/update instead of the v2 // _kiro.dev/metadata and _kiro.dev/commands/available notifications. ACPUpdateSessionInfo ACPUpdateKind = "session_info_update" ACPUpdateCommandsAvailable ACPUpdateKind = "available_commands_update" // config_option_update carries the live model/mode/effort catalog; // usage_update carries context-window usage ({size, used, cost?}). // Both are v3-only session/update sub-kinds (KAS 2.12). ACPUpdateConfigOption ACPUpdateKind = "config_option_update" ACPUpdateUsage ACPUpdateKind = "usage_update" )
ACPUpdateAgentChunk and the following constants define the valid ACPUpdateKind values for ACP session notifications.
type AccountUsage ¶ added in v0.1.165
type AccountUsage struct {
// PlanName is the subscription title (e.g. "KIRO POWER").
PlanName string `json:"plan_name,omitempty"`
// BillingCycleReset is the YYYY-MM-DD reset date, or "" when unknown.
BillingCycleReset string `json:"billing_cycle_reset,omitempty"`
// FetchedAt is the RFC3339 timestamp of the fetch that produced this
// snapshot, so the client can show freshness.
FetchedAt string `json:"fetched_at,omitempty"`
// Note carries a human-readable status for degraded states (e.g. an
// admin-managed plan that returns no breakdowns).
Note string `json:"note,omitempty"`
// Breakdowns is the per-resource usage list (typically a single
// CREDIT entry).
Breakdowns []AccountUsageBreakdown `json:"breakdowns"`
// IsEnterprise reports whether the plan is an enterprise/managed plan.
IsEnterprise bool `json:"is_enterprise,omitempty"`
// OveragesEnabled reports whether overage billing is enabled.
OveragesEnabled bool `json:"overages_enabled,omitempty"`
// Stale is true when this snapshot was served from the last-known
// cache because a fresh fetch failed (no live bridge, rate limit).
Stale bool `json:"stale,omitempty"`
}
AccountUsage is the account/subscription usage snapshot for the signed-in identity.
type AccountUsageBreakdown ¶ added in v0.1.165
type AccountUsageBreakdown struct {
// ResourceType is the KAS resource key (e.g. "CREDIT").
ResourceType string `json:"resource_type,omitempty"`
// DisplayName is the human label (e.g. "Credits").
DisplayName string `json:"display_name,omitempty"`
// Currency is the ISO currency for monetary fields (e.g. "USD").
Currency string `json:"currency,omitempty"`
// Used is the amount consumed this cycle.
Used float64 `json:"used"`
// Limit is the plan allowance; meaningful only when HasLimit is true.
Limit float64 `json:"limit"`
// CurrentOverages is the amount consumed beyond Limit.
CurrentOverages float64 `json:"current_overages,omitempty"`
// OverageCharges is the monetary overage charge in Currency.
OverageCharges float64 `json:"overage_charges,omitempty"`
// Percentage is floor(Used/Limit*100); can exceed 100 on overage.
Percentage int `json:"percentage"`
// HasLimit reports whether Limit is a real cap (false = unlimited).
HasLimit bool `json:"has_limit,omitempty"`
}
AccountUsageBreakdown is one resource line of an AccountUsage (e.g. credits). Used/Limit are precision floats as reported by KAS.
type AccountUsageProvider ¶ added in v0.1.165
type AccountUsageProvider interface {
AccountUsage(ctx context.Context) (*AccountUsage, error)
}
AccountUsageProvider fetches account/subscription-level usage (plan, credits, quota) via the KAS _kiro/account/getUsage request on a live bridge. Narrow interface so the server can serve GET /api/account/usage without depending on the full Hub surface; the concrete *hub.Hub satisfies it via the utility bridge.
type Attachment ¶
type Attachment struct {
Path string `json:"path"` // workspace-relative path
Name string `json:"name"` // display name (filename.ext)
}
Attachment is a file attached to a prompt. The server reads the file and decides whether to send it as a document content block (PDF, DOCX, etc.) or a text path reference based on the extension.
type AuthHandler ¶
type AuthHandler interface {
RouteHandler
}
AuthHandler registers /api/whoami, /api/login, /api/logout.
type AvailableCommand ¶
type AvailableCommand struct {
Meta map[string]any `json:"meta,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
AvailableCommand is one entry in the slash-command catalogue surfaced by kiro-cli's _kiro.dev/commands/available notification. The wire shape carries opaque metadata; clients consume only Name and Description.
type Block ¶
type Block struct {
// Type is the discriminator: text | tool_use | thinking.
Type BlockType `json:"type"`
// Text carries the markdown text for Type=BlockText. Accumulated
// across MessageChunkPayload events targeting this block index.
Text string `json:"text,omitempty"`
// Thinking carries the reasoning text for Type=BlockThinking.
Thinking string `json:"thinking,omitempty"`
// ToolCallID references a tool by ID in Message.ToolCalls for
// Type=BlockToolUse. Empty for other types.
ToolCallID string `json:"tool_call_id,omitempty"`
// AgentSubtaskID is the subtask id of the agent that produced this
// block ("" = top-level agent). Set from the emitting event's
// _meta.kiro.agentSubtaskId; lets the client group a subagent's
// blocks and render them nested.
AgentSubtaskID string `json:"agent_subtask_id,omitempty"`
}
Block is one entry in an assistant message's chronological content array. Position in Message.Blocks IS the order in which the agent emitted the block — text → tool → text → tool, etc. — so the client renders them inline as they happened rather than concatenating all text into one bubble at the top with tools dumped below.
Replay-compatible: messages persisted before this field existed have Blocks=nil. Renderers fall back to the legacy Content + ToolCalls layout when Blocks is empty.
type BlockType ¶
type BlockType string
BlockType discriminates content blocks in an assistant message's chronological content array. Mirrors Anthropic's `content_block.type` from the Messages API streaming spec — the same model claude-code uses to render text, tool calls, and thinking traces inline as the agent emits them rather than splitting them into separate sections.
const ( // BlockText is a markdown text segment from the agent. BlockText BlockType = "text" // BlockToolUse is a tool invocation. Only the ToolCallID is carried // in the block; the full ToolCall lives in Message.ToolCalls so // status updates (pending → in_progress → completed) don't need // to touch the block array. BlockToolUse BlockType = "tool_use" // BlockThinking is an extended-thinking trace segment. BlockThinking BlockType = "thinking" )
type Broadcaster ¶
type Broadcaster interface {
Broadcast(ctx context.Context, evt ServerEvent)
}
Broadcaster sends events to all connected SSE clients.
type Chat ¶
type Chat struct {
Name string `json:"name"`
Model string `json:"model,omitempty"`
ACPSessionID string `json:"acp_session_id,omitempty"`
CurrentModeID string `json:"current_mode_id,omitempty"`
ParentChatID ChatID `json:"parent_chat_id,omitempty"`
CompactionWatermark string `json:"compaction_watermark,omitempty"`
Summary string `json:"summary,omitempty"`
OldestCheckpointTag string `json:"oldest_checkpoint_tag,omitempty"`
ID string `json:"id"`
AvailableModels []SessionModel `json:"available_models,omitempty"`
AvailableModes []SessionMode `json:"available_modes,omitempty"`
Messages []Message `json:"messages"`
CurrentPlan []PlanEntry `json:"current_plan,omitempty"`
Usage Usage `json:"usage"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
// ArchivedAt is the unix-milli timestamp recorded when the chat was
// moved to the archive dir. Purge ages from this, NOT the file mtime:
// a skipped/failed post-archive summary write leaves mtime at the
// chat's last-activity time, which would purge an old-but-just-archived
// chat almost immediately. Zero for active chats and for legacy archives
// written before this field existed (purge falls back to mtime then).
ArchivedAt int64 `json:"archived_at,omitempty"`
RewindFromTurn int `json:"rewind_from_turn,omitempty"`
MessageCount int `json:"message_count"`
SupervisedMode bool `json:"supervised_mode,omitempty"`
}
Chat is the full persisted chat. Serialized as <dir>/<id>.json.
func (*Chat) Header ¶
func (c *Chat) Header() ChatHeader
Header returns the chat's metadata without messages. Used for list endpoints and SSE broadcasts when messages are not needed.
type ChatDeletedPayload ¶
type ChatDeletedPayload struct {
ID string `json:"id"`
}
ChatDeletedPayload is the payload for type="chat_deleted".
type ChatHeader ¶
type ChatHeader struct {
ParentChatID ChatID `json:"parent_chat_id,omitempty"`
Name string `json:"name"`
Model string `json:"model,omitempty"`
ACPSessionID string `json:"acp_session_id,omitempty"`
CurrentModeID string `json:"current_mode_id,omitempty"`
ID string `json:"id"`
CompactionWatermark string `json:"compaction_watermark,omitempty"`
OldestCheckpointTag string `json:"oldest_checkpoint_tag,omitempty"`
Summary string `json:"summary,omitempty"`
AvailableModels []SessionModel `json:"available_models,omitempty"`
AvailableModes []SessionMode `json:"available_modes,omitempty"`
Usage Usage `json:"usage"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
MessageCount int `json:"message_count"`
SupervisedMode bool `json:"supervised_mode,omitempty"`
}
ChatHeader is the metadata-only view of a Chat. Field order is driven by fieldalignment packing, not Chat's field order; both structs serialise to JSON independently so the visual mismatch is harmless.
type ChatID ¶
type ChatID string
ChatID is a typed wrapper for chat identifiers. The underlying string marshals identically to JSON, preserving the wire contract.
type ChatStatusPayload ¶ added in v0.1.184
type ChatStatusPayload struct {
Status string `json:"status,omitempty"`
Description string `json:"description,omitempty"`
}
ChatStatusPayload is the payload for type="chat_status": the agent's self-declared activity for a chat, sourced from the KAS focus_update channel (the model's update_session_information tool). Status is one of in_progress | waiting_on_user | completed | idle; Description is a short "what I'm working on" line. Ephemeral by design — never persisted, so a restart or reconnect gap resets tabs to a neutral state instead of replaying a stale "in_progress".
type ChatStore ¶
type ChatStore interface {
RouteHandler
// SetBroadcaster wires the SSE broadcaster the store uses to emit
// chat_created / chat_updated / chat_deleted / message_* events.
// Called once after construction to break the init cycle with the hub.
SetBroadcaster(b Broadcaster)
// Get returns the full chat at id, or false if it does not exist.
Get(ctx context.Context, id ChatID) (*Chat, bool)
// List returns every chat's header (no messages) sorted by UpdatedAt
// descending. Checks ctx.Err() between per-file reads.
List(ctx context.Context) []ChatHeader
// ChildrenOf returns the IDs of chats whose ParentChatID equals
// parentID. Used by delete to cascade to rewind children without
// loading the full chat list.
ChildrenOf(ctx context.Context, parentID ChatID) []ChatID
// BuildHistory returns a plain-text transcript used for compress
// priming. Returns "" if the chat is missing or empty.
BuildHistory(ctx context.Context, id ChatID) string
// Mutate is the single write primitive: load → apply → save →
// broadcast chat_created / chat_updated.
Mutate(ctx context.Context, id ChatID, mutate func(c *Chat, exists bool) bool) error
// Delete removes the chat file and broadcasts chat_deleted.
Delete(ctx context.Context, id ChatID) error
// DeleteFamily removes a chat and its rewind children as one named
// transition with explicit ordering and truthful results: children
// are deleted FIRST (no crash window leaves a child referencing a
// deleted parent), the parent LAST. prepare (optional) runs before
// each record's deletion so the caller can tear down per-chat side
// effects (bridge, terminals, .partial) in the same order. Children
// whose deletion failed are returned — still listed, still
// deletable; a parent failure is the returned error (its children
// are already gone at that point).
DeleteFamily(ctx context.Context, parentID ChatID, prepare func(ChatID)) (failedChildren []ChatID, err error)
// PromoteRewind clears a rewind chat's parent linkage (ParentChatID
// + RewindFromTurn) as a single checked, per-chat-locked transition,
// returning the former parent id for the caller to clean up and
// delete. Errors: ErrChatNotFound when the chat does not exist,
// ErrNotRewind when it has no parent; on ANY error the linkage is
// untouched — a promote never reports success while the
// relationship is still intact.
PromoteRewind(ctx context.Context, childID ChatID) (parentID ChatID, err error)
// Archive moves a chat to the archive directory instead of deleting.
Archive(ctx context.Context, id ChatID) error
// ListArchived returns headers for all archived chats.
ListArchived(ctx context.Context) []ChatHeader
// RestoreArchived moves a chat from the archive back to active.
RestoreArchived(ctx context.Context, id ChatID) error
// UpdateArchivedSummary rewrites an archived chat's Summary field.
UpdateArchivedSummary(ctx context.Context, id ChatID, summary string) error
// LoadArchived returns the parsed archived chat.
LoadArchived(ctx context.Context, id ChatID) (*Chat, error)
// DeleteArchived permanently removes a single archived chat.
DeleteArchived(ctx context.Context, id ChatID) error
// AppendMessage appends msg to the chat's messages.
AppendMessage(ctx context.Context, chatID ChatID, msg *Message) error
// UpdateMessage mutates one message in place (by ID).
UpdateMessage(ctx context.Context, chatID ChatID, msgID string, mutate func(*Message)) error
}
ChatStore persists chat sessions as one JSON file per chat under <dir>/<chat_id>.json. The directory listing is the index; there is no separate index file. Mutations go through Mutate (atomic load → apply → save → broadcast); there is no event-sourcing replay.
type CheckpointConflictsResponse ¶
type CheckpointConflictsResponse struct {
Conflicts []checkpoint.ConflictPayload `json:"conflicts"`
}
CheckpointConflictsResponse is the typed response for the conflicts endpoint.
type CheckpointDiffResponse ¶
type CheckpointDiffResponse struct {
Files []checkpoint.FileChange `json:"files"`
}
CheckpointDiffResponse is the typed response for the checkpoint diff endpoint.
type CheckpointRestorePreviewResponse ¶
type CheckpointRestorePreviewResponse struct {
Files []string `json:"files"`
}
CheckpointRestorePreviewResponse is the typed response for restore-preview.
type CheckpointRestoredPayload ¶
type CheckpointRestoredPayload struct {
Tag string `json:"tag"`
MessageCount int `json:"message_count"`
}
CheckpointRestoredPayload is the payload for type="checkpoint_restored". Replaces the ad-hoc map[string]any so the wire shape is discoverable via IDE completion and typos in key names become compile errors.
type CheckpointService ¶
type CheckpointService interface {
Snapshot(ctx context.Context, chatID ChatID, relPath string, newContent []byte, messageCount int) (checkpoint.Tag, error)
// OwnerOf returns the chat whose agent most recently wrote relPath
// (the owner of the path's checkpoint lineage), or ok=false when no
// chat tracks the path. Warms the cross-chat index from disk on
// first use so a cold process answers correctly.
OwnerOf(ctx context.Context, relPath string) (ChatID, bool)
Restore(ctx context.Context, chatID ChatID, tag checkpoint.Tag) (int, error)
RestorePreview(ctx context.Context, chatID ChatID, tag checkpoint.Tag) ([]string, error)
CheckoutFile(ctx context.Context, chatID ChatID, tag checkpoint.Tag, relPath string) error
Diff(ctx context.Context, chatID ChatID, from, to checkpoint.Tag) ([]checkpoint.FileChange, error)
Conflicts(ctx context.Context, chatID ChatID) ([]checkpoint.ConflictPayload, error)
ReadBlob(ctx context.Context, chatID ChatID, sha string) ([]byte, error)
OldestTag(ctx context.Context, chatID ChatID) checkpoint.Tag
AdvanceTurn(ctx context.Context, chatID ChatID, messageCount int)
Cleanup(ctx context.Context, chatID ChatID)
StartBackgroundTasks(ctx context.Context)
Stop()
}
CheckpointService is the consumer-side interface for the checkpoint subsystem. Enables stub/mock injection in hub tests without constructing a real checkpoint.Store with filesystem state.
type ClearReason ¶
type ClearReason string
ClearReason identifies why pending changes or trust were cleared. Using a typed string prevents typos at construction sites and makes the valid set discoverable via IDE completion.
const ( ClearReasonTurnEnded ClearReason = "turn_ended" ClearReasonCancelled ClearReason = "cancelled" ClearReasonModeDisabled ClearReason = "mode_disabled" ClearReasonChatDeleted ClearReason = "chat_deleted" ClearReasonShutdown ClearReason = "shutdown" ClearReasonUserCleared ClearReason = "user_cleared" // ClearReasonBridgeExited flushes a chat's staged writes when its // kiro-cli bridge exits unexpectedly (crash, or a model-switch // CloseBridge). Cancel/delete/mode-disable already flush; this is the // bridge-exit sibling so a dead bridge can't leave a parked fs-handler // goroutine plus a phantom "awaiting approval" pending op. ClearReasonBridgeExited ClearReason = "bridge_exited" )
ClearReasonTurnEnded and the following constants define the valid ClearReason values for pending-change and trust clearance.
type ClientCommand ¶
type ClientCommand struct {
Type CommandType `json:"type"`
RequestID string `json:"request_id"`
ChatID ChatID `json:"chat_id,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
}
ClientCommand is the envelope for every command the browser posts. Type determines how Payload unmarshals.
type CodeReference ¶ added in v0.1.165
type CodeReference struct {
LicenseName string `json:"license_name"`
Repository string `json:"repository,omitempty"`
URL string `json:"url,omitempty"`
}
CodeReference is one licensed-code attribution surfaced by the agent (v3/KAS _kiro/code_references). KAS emits it when a completion reproduces a recognizable chunk of a referenced open-source file and the account's code-reference tracker is enabled. The KAS ACP layer maps every reference down to these three fields (licenseName + repository + url); the raw CodeWhisperer recommendationContentSpan and information fields are dropped upstream before we ever see them, so there is no span to map a reference to a specific message region — attributions are turn-scoped and persisted on the assistant Message they arrived during.
type CodeReferencesPayload ¶ added in v0.1.165
type CodeReferencesPayload struct {
MessageID string `json:"message_id"`
References []CodeReference `json:"references"`
}
CodeReferencesPayload is the payload for type="code_references". Carries the licensed-code attributions accumulated on the in-flight assistant turn (v3/KAS). MessageID targets that turn's assistant message so the client attaches the chip to it; References is the full deduped list so the client can render idempotently (a later notification replaces rather than appends). Also persisted on the Message so the chip survives reload.
type CommandBridge ¶
type CommandBridge interface {
// Call sends an RPC call to kiro-cli.
Call(ctx context.Context, method string, params any) (*RPCResponse, error)
// Notify sends a one-way notification to kiro-cli.
Notify(ctx context.Context, method string, params any) error
// Respond sends a permission response to kiro-cli.
Respond(ctx context.Context, requestID int64, result any, err error) error
// SessionID returns the current ACP session ID.
SessionID() SessionID
// TryAcquireForPrompt attempts to lock the bridge for prompting.
TryAcquireForPrompt() bool
// ReleaseAfterPrompt releases the prompt lock.
ReleaseAfterPrompt()
// SetLastActive updates the last-active timestamp.
SetLastActive()
// SetPrompting sets the bridge state to prompting (for recovery).
SetPrompting()
// IsPrimed reports whether the bridge has been primed.
IsPrimed() bool
// SetPrimed marks the bridge as primed.
SetPrimed()
}
CommandBridge abstracts the per-chat ACP bridge for command handlers. Declared here (consumer-side) so both command and hub can reference the same contract without circular imports.
type CommandType ¶
type CommandType string
CommandType identifies the kind of client command posted to /api/command. Using a typed string instead of bare literals makes typos a compile error and the full command vocabulary discoverable.
const ( CmdCreateChat CommandType = "create_chat" CmdPrompt CommandType = "prompt" CmdCancel CommandType = "cancel" CmdDeleteChat CommandType = "delete_chat" CmdSwitchModel CommandType = "switch_model" CmdPermissionResponse CommandType = "permission_response" CmdElicitationResponse CommandType = "elicitation_response" CmdUserInputResponse CommandType = "user_input_response" CmdRestoreCheckpoint CommandType = "restore_checkpoint" CmdUndoEdit CommandType = "undo_edit" CmdRewindChat CommandType = "rewind_chat" CmdPromoteRewindChat CommandType = "promote_rewind_chat" CmdDiscardRewindChat CommandType = "discard_rewind_chat" CmdSetEffort CommandType = "set_effort" CmdSetMode CommandType = "set_mode" CmdCreateHook CommandType = "create_hook" CmdResolvePendingChange CommandType = "resolve_pending_change" CmdResolvePendingPartial CommandType = "resolve_pending_change_partial" CmdResolveAllPendingChanges CommandType = "resolve_all_pending_changes" CmdSetSupervisedMode CommandType = "set_supervised_mode" CmdTrustPendingChanges CommandType = "trust_pending_changes" CmdClearPendingTrust CommandType = "clear_pending_trust" )
Command type constants. Every value here corresponds to a key in hub/command.go's registerCommandHandlers dispatch map.
type CommandsUpdatedPayload ¶
type CommandsUpdatedPayload struct {
Commands []AvailableCommand `json:"commands"`
Prompts []AvailableCommand `json:"prompts,omitempty"`
}
CommandsUpdatedPayload is the payload for type="commands_updated".
type CompactionStartedPayload ¶
type CompactionStartedPayload struct{}
CompactionStartedPayload is the payload for type="compaction_started".
type ConflictDetectedPayload ¶
type ConflictDetectedPayload = checkpoint.ConflictPayload
ConflictDetectedPayload is the payload for type="conflict_detected". Type alias to checkpoint/types.ConflictPayload — single source of truth.
type ConnectedPayload ¶
ConnectedPayload is the payload for type="connected", the SSE handshake event. Floor is the oldest event ID still in the replay ring; Head is the newest. Clients with last-seen-id < Floor know they missed events and should refetch authoritative state.
type CreateChatCommand ¶
type CreateChatCommand struct {
Name string `json:"name,omitempty"`
Model string `json:"model,omitempty"`
}
CreateChatCommand is the payload for type="create_chat".
Name is optional and capped at 512 bytes (maxChatNameBytes); empty values default to "New conversation". Model is optional; if non-empty it must match validIdent (ASCII alphanumerics plus `_.-`, 1-128 bytes). Validation failures return HTTP 400.
type EffortLevel ¶
type EffortLevel string
EffortLevel is a typed enum for reasoning effort levels.
const ( EffortLow EffortLevel = "low" EffortMedium EffortLevel = "medium" EffortHigh EffortLevel = "high" EffortXHigh EffortLevel = "xhigh" EffortMax EffortLevel = "max" )
Valid effort level constants.
func (EffortLevel) Valid ¶
func (e EffortLevel) Valid() bool
Valid reports whether e is a recognised effort level.
type ElicitationNeededPayload ¶ added in v0.1.39
type ElicitationNeededPayload struct {
RequestedSchema *ElicitationRequestSchema `json:"requested_schema,omitempty"`
Mode string `json:"mode,omitempty"`
Message string `json:"message,omitempty"`
URL string `json:"url,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
SubSessionID string `json:"sub_session_id,omitempty"`
RequestID int64 `json:"request_id"`
}
ElicitationNeededPayload is the SSE payload for type="elicitation_needed". Mirrors PermissionNeededPayload's role: it carries everything the client needs to render the dialog plus the RequestID to echo back in the elicitation_response command. Mode is "form" or "url"; URL-mode elicitations carry URL and no RequestedSchema.
type ElicitationPropertySchema ¶ added in v0.1.39
type ElicitationPropertySchema struct {
Default any `json:"default,omitempty"`
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
Type string `json:"type"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Format string `json:"format,omitempty"`
Pattern string `json:"pattern,omitempty"`
Enum []string `json:"enum,omitempty"`
}
ElicitationPropertySchema describes one field in an elicitation form. Type is the discriminator ("string" | "number" | "integer" | "boolean" | "array"); the other fields are populated as relevant to that type. Unset fields are omitted on the wire.
type ElicitationRequestSchema ¶ added in v0.1.39
type ElicitationRequestSchema struct {
Type string `json:"type,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Properties map[string]ElicitationPropertySchema `json:"properties,omitempty"`
Required []string `json:"required,omitempty"`
}
ElicitationRequestSchema is the JSON-schema-shaped object describing a form: a map of property name to its schema, plus the required set.
type ElicitationResponseCommand ¶ added in v0.1.39
type ElicitationResponseCommand struct {
Action string `json:"action"`
Content json.RawMessage `json:"content,omitempty"`
RequestID int64 `json:"request_id"`
}
ElicitationResponseCommand is the payload for type="elicitation_response". RequestID echoes the value from the elicitation_needed event. Action is "accept" | "decline" | "cancel"; Content carries the filled form values (an object) only on accept and is forwarded verbatim to kiro-cli.
type ElicitationResult ¶ added in v0.1.39
type ElicitationResult struct {
Action string `json:"action"`
Content json.RawMessage `json:"content,omitempty"`
}
ElicitationResult is the response we send back on elicitation/create. Action is one of accept/decline/cancel; Content carries the filled form values (object) only on accept.
type ErrorCode ¶
type ErrorCode string
ErrorCode identifies an SSE error event class. Using a typed string prevents typos at construction sites and makes the valid set discoverable via IDE completion.
const ( ErrCodeRecoveryFailed ErrorCode = "recovery_failed" ErrCodeBridgeStartFailed ErrorCode = "bridge_start_failed" ErrCodePromptFailed ErrorCode = "prompt_failed" ErrCodeAgentNotFound ErrorCode = "agent_not_found" ErrCodeAgentConfigError ErrorCode = "agent_config_error" ErrCodeRateLimit ErrorCode = "rate_limit" ErrCodeStreamTimeout ErrorCode = "stream_timeout" ErrCodeSpawnFailed ErrorCode = "spawn_failed" ErrCodeSwitchFailed ErrorCode = "switch_failed" ErrCodeCompactionFailed ErrorCode = "compaction_failed" )
ErrCodeRecoveryFailed and the following constants define the valid ErrorCode values for SSE error events.
type ErrorPayload ¶
ErrorPayload is the payload for type="error". Code lets clients react per-class without string-matching.
type Event ¶
type Event[T any] struct { Payload T `json:"payload,omitempty"` Type EventType `json:"type"` ChatID ChatID `json:"chat_id,omitempty"` }
Event is the server→client event envelope, generic over payload type. JSON serialization is identical to ServerEvent: {type, chat_id, payload}. Used as a construction helper via NewEvent to provide compile-time type safety at emit sites; the result is converted to ServerEvent for broadcast.
type EventKind ¶
type EventKind string
EventKind identifies subtypes of RoleEvent messages.
const ( EventInterrupted EventKind = "interrupted" EventCancelled EventKind = "cancelled" EventModelSwitched EventKind = "model_switched" // fresh ACP session with a new model EventCompacted EventKind = "compacted" // kiro-cli's native /compact, carries summary EventCompactFailed EventKind = "compaction_failed" // EventInfraSafetyBlocked marks an ENFORCE-mode Infrastructure-Safety // refusal: KAS blocked an infra-as-code write/shell tool call upstream // (it never issued the fs/write_text_file request, so nothing was // written). Persisted as a permanent inline event so the refusal is part // of the transcript rather than a fleeting banner. Content carries the // violated safety properties. See translate/safety.go. EventInfraSafetyBlocked EventKind = "infra_safety_blocked" )
EventInterrupted and the following constants define the valid EventKind values for inline event messages.
type EventType ¶
type EventType string
EventType identifies the kind of SSE event broadcast to clients. Using a typed string instead of bare literals makes typos a compile error and the full event vocabulary discoverable via IDE completion.
const ( EventChatCreated EventType = "chat_created" EventChatUpdated EventType = "chat_updated" EventChatDeleted EventType = "chat_deleted" EventChatStatus EventType = "chat_status" EventCheckpointRestored EventType = "checkpoint_restored" EventCodeReferences EventType = "code_references" EventCommandsUpdated EventType = "commands_updated" EventCompactionStarted EventType = "compaction_started" EventConflictDetected EventType = "conflict_detected" EventConnected EventType = "connected" EventError EventType = "error" EventElicitationNeeded EventType = "elicitation_needed" EventUserInputNeeded EventType = "user_input_needed" EventMCPConfigChanged EventType = "mcp_config_changed" EventMCPConnected EventType = "mcp_connected" EventMCPDisconnected EventType = "mcp_disconnected" EventMCPFailed EventType = "mcp_failed" EventMCPOAuthNeeded EventType = "mcp_oauth_needed" EventMCPPrewarm EventType = "mcp_prewarm" EventMessageAppended EventType = "message_appended" EventMessageChunk EventType = "message_chunk" EventMessageCreated EventType = "message_created" EventMessageUpdated EventType = "message_updated" EventModeChanged EventType = "mode_changed" EventOpenExternalURL EventType = "open_external_url" EventPendingChangeAdded EventType = "pending_change_added" EventPendingChangeResolved EventType = "pending_change_resolved" EventPendingChangesCleared EventType = "pending_changes_cleared" EventPendingTrustCleared EventType = "pending_trust_cleared" EventPendingTrustEnabled EventType = "pending_trust_enabled" EventPermissionNeeded EventType = "permission_needed" EventPermissionsChanged EventType = "permissions_changed" EventPolicyError EventType = "policy_error" EventForgesChanged EventType = "forges_changed" EventGovernanceState EventType = "governance_state" EventHooksChanged EventType = "hooks_changed" EventKnowledgeIndexing EventType = "knowledge_indexing" EventSafetyStatus EventType = "safety_status" EventSafetyProperties EventType = "safety_properties" EventSpecTaskChanged EventType = "spec_task_changed" EventSettingsUpdated EventType = "settings_updated" EventTerminalCreated EventType = "terminal_created" EventTerminalExited EventType = "terminal_exited" EventTerminalOutput EventType = "terminal_output" EventToolCall EventType = "tool_call" EventToolCallUpdate EventType = "tool_call_update" EventToolJobChanged EventType = "tool_job_changed" EventToolJobOutput EventType = "tool_job_output" EventTurnEnded EventType = "turn_ended" EventTurnState EventType = "turn_state" EventWorkingLabel EventType = "working_label" )
SSE event type constants. Using these instead of bare string literals makes typos a compile error and the full event vocabulary discoverable.
type FileChange ¶
type FileChange struct {
LinesAdded int `json:"lines_added"`
LinesRemoved int `json:"lines_removed"`
IsNewFile bool `json:"is_new_file,omitempty"`
}
FileChange tracks per-file change stats during a turn.
type FileHandler ¶
type FileHandler interface {
RouteHandler
}
FileHandler registers file browsing and editing routes under /api/file/* and /api/files/*.
type ForgesChangedPayload ¶
type ForgesChangedPayload struct{}
ForgesChangedPayload is the payload for type="forges_changed". Sent after a forge is connected, disconnected, or re-probed.
type GitHandler ¶
type GitHandler interface {
RouteHandler
}
GitHandler registers git-related HTTP routes under /api/git/*.
type GovernanceFeatures ¶ added in v0.1.165
type GovernanceFeatures struct {
// MCPEnabled reports whether the MCP subsystem is permitted. When false,
// enterprise governance has suppressed MCP entirely (vibekit disables the
// add-server affordance and shows a disabled state in Settings → Tools).
MCPEnabled bool `json:"mcp_enabled"`
// WebToolsEnabled reports whether built-in web tools are permitted.
WebToolsEnabled bool `json:"web_tools_enabled"`
// UsageAnalytics reports whether usage analytics collection is enabled.
UsageAnalytics bool `json:"usage_analytics"`
// ContentCollection reports whether content collection is enabled.
ContentCollection bool `json:"content_collection"`
// PromptLogging reports whether prompt logging is enabled.
PromptLogging bool `json:"prompt_logging"`
// CodeReferenceTracker reports whether licensed-code reference tracking is
// enabled — the flag that governs whether KAS emits _kiro/code_references
// (the attribution chip in code-refs.ts is dormant unless this is true).
CodeReferenceTracker bool `json:"code_reference_tracker"`
// AutonomousAgents reports whether autonomous agent runs are permitted.
AutonomousAgents bool `json:"autonomous_agents"`
}
GovernanceFeatures is the org/account feature-flag set carried by the v3 (KAS) _kiro/governance/state notification (KAS's GovernanceFeatures object, verified against the KAS 2.12 acp-server bundle + a live probe). Every field is the RESOLVED effective value: MCPEnabled/WebToolsEnabled/AutonomousAgents are the negation of a "…GovernanceDisabled" flag; the analytics/logging/ tracker fields are direct "…GovernanceEnabled" flags. On an individual / Builder-ID login these resolve to a permissive default (mcp/webTools/ autonomousAgents on; analytics/promptLogging/codeReferenceTracker off; contentCollection on) with isEnterprise=false and no disabledReason.
NOTE: Infrastructure-Safety (infraSafetyMonitor/infraSafetyEnforce) is NOT here — it is a separate modelConfigProvider.isFeatureEnabled channel, not a governance feature (verified: absent from _kiro/governance/state). So the safety banner (translate/safety.go) is gated by KAS's own emission, not by any field on this struct.
type GovernanceStatePayload ¶ added in v0.1.165
type GovernanceStatePayload struct {
// DisabledReason is a human-readable reason surfaced by enterprise
// governance (e.g. why MCP is off); empty/absent on a normal account.
DisabledReason string `json:"disabled_reason,omitempty"`
// Features is the resolved effective feature-flag set.
Features GovernanceFeatures `json:"features"`
// Known is true once the real policy has been observed (see the type doc).
Known bool `json:"known"`
// IsEnterprise reports whether this is an enterprise/managed account.
IsEnterprise bool `json:"is_enterprise,omitempty"`
}
GovernanceStatePayload is the payload for type="governance_state", translated from the v3 (KAS) _kiro/governance/state notification (buildNotification: {sessionId, isEnterprise, features, disabledReason}). The account/workspace feature-flag policy KAS pushes on every session/new + session/load, and re-pushes on a prompt when it changes; vibekit caches the latest hub-side and also serves it at GET /api/governance so a fresh page load can read it with no chat open. The wire sessionId is used only for subagent-copy dedup and is dropped from this payload — governance is account-global, so the SSE is broadcast with an empty chat id (every client receives it).
Known distinguishes "the server has told us the real policy" (Known=true, on every SSE broadcast and a warm REST snapshot) from "not yet observed" (Known=false, a cold REST snapshot before any bridge has started). Clients MUST only gate/annotate affordances when Known is true — the all-false zero value would otherwise read as "everything disabled" when we simply don't know yet.
type HooksChangedPayload ¶ added in v0.1.165
type HooksChangedPayload struct{}
HooksChangedPayload is the payload for type="hooks_changed". Emitted (empty, workspace-global — no chat_id) after a hook is created, toggled, or its .kiro/hooks/*.json file changes on disk (KAS _kiro/hooks/didChange on the utility bridge). The client refetches GET /api/hooks on receipt.
type Hub ¶
type Hub interface {
Broadcaster
RouteHandler
// Shutdown drains in-flight prompts and closes all bridges.
Shutdown()
}
Hub manages SSE connections and dispatches POST /api/command.
type KnowledgeIndexingPayload ¶ added in v0.1.165
type KnowledgeIndexingPayload struct {
Name string `json:"name"`
Status string `json:"status"`
FileCount int `json:"file_count,omitempty"`
ItemCount int `json:"item_count,omitempty"`
}
KnowledgeIndexingPayload is the payload for type="knowledge_indexing". Translated from the KAS _kiro/knowledge/indexingStarted (Status="started", carries FileCount) and _kiro/knowledge/indexingCompleted (Status="success" or a failure string, carries ItemCount on success) notifications. Emitted globally (no chat_id) because the knowledge store is workspace-global; the client refetches GET /api/knowledge on receipt. Note: these fire only for agent-declared knowledge_bases sync at session start — a user-initiated add reports progress through the `show` active-operations list instead (verified live), so the client also polls while an entry is still indexing.
type LimitedWriter ¶
LimitedWriter writes at most N bytes to W and silently drops the rest. Used for bounded stderr/stdout capture from subprocess handlers so a misbehaving or hostile subprocess can't OOM the container.
type MCPConfig ¶
type MCPConfig interface {
// ACPServers returns the enabled servers shaped for kiro-cli's
// session/new and session/load mcpServers parameter. Each entry
// is an opaque map whose shape follows the ACP spec's
// McpServerStdio / McpServerHttp / McpServerSse schema —
// internal/mcp populates per-transport fields; the hub passes
// through verbatim.
ACPServers(ctx context.Context) []map[string]any
// EnabledNames returns the set of enabled server names. Used by the
// hub to filter server_initialized notifications that belong to
// disabled entries (defensive — kiro-cli shouldn't send them, but
// we don't trust the boundary).
EnabledNames(ctx context.Context) map[string]struct{}
// SetKnownTools persists the tool list for a server so the UI can
// show suggestions in the per-tool deny section.
SetKnownTools(ctx context.Context, name string, tools []string)
}
MCPConfig is the hub's view of the user's configured MCP servers. The hub does not care about persistence or validation; it only needs to know which ACP server configs to pass on bridge spawn and which raw records to expose for pre-warm.
type MCPConfigChangedPayload ¶
type MCPConfigChangedPayload struct{}
MCPConfigChangedPayload is the payload for type="mcp_config_changed".
type MCPConnectedPayload ¶
type MCPConnectedPayload struct {
Server string `json:"server"`
}
MCPConnectedPayload is the payload for type="mcp_connected", emitted when kiro-cli reports _kiro.dev/mcp/server_initialized.
type MCPDisconnectedPayload ¶
type MCPDisconnectedPayload struct {
Server string `json:"server"`
}
MCPDisconnectedPayload is the payload for type="mcp_disconnected". Emitted when the hub's last bridge exits: kiro-cli's MCP subprocesses shut down with it, so no configured server is currently live. Clients use this to clear their runtime-state map.
type MCPFailedPayload ¶
MCPFailedPayload is the payload for type="mcp_failed", emitted when kiro-cli reports _kiro.dev/mcp/server_init_failure.
type MCPOAuthPayload ¶
MCPOAuthPayload is the payload for type="mcp_oauth_needed", emitted when kiro-cli reports _kiro.dev/mcp/oauth_request. URL is the provider's authorisation endpoint; the user completes the flow in a new tab.
type MCPPrewarmPayload ¶
type MCPPrewarmPayload struct {
Package string `json:"package"`
State string `json:"state"` // "installing", "done", "failed"
}
MCPPrewarmPayload is the payload for type="mcp_prewarm", emitted when a prewarm install starts, succeeds, or fails. The UI uses this to show "Installing..." next to the server name in the MCP panel.
type MCPPromptArg ¶ added in v0.1.165
type MCPPromptArg struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
}
MCPPromptArg describes one argument of an MCP prompt.
type MCPPromptInfo ¶ added in v0.1.165
type MCPPromptInfo struct {
Name string `json:"name"`
PromptName string `json:"prompt_name"`
Description string `json:"description,omitempty"`
Arguments []MCPPromptArg `json:"arguments,omitempty"`
}
MCPPromptInfo describes one prompt a connected MCP server advertises. PromptName is the machine id passed to _kiro/mcp/getPrompt; Name is the human-readable display title (they differ — e.g. "Simple Prompt" vs "simple-prompt"). Arguments lists the prompt's parameters, if any.
type MCPResourceInfo ¶ added in v0.1.165
type MCPResourceInfo struct {
Name string `json:"name"`
URI string `json:"uri"`
Description string `json:"description,omitempty"`
MimeType string `json:"mime_type,omitempty"`
}
MCPResourceInfo describes one resource a connected MCP server advertises. URI is the identifier passed to _kiro/mcp/getResource.
type MCPServerState ¶
type MCPServerState string
MCPServerState is the lifecycle status of one configured MCP server. Exported so the hub's mcpRegistry and the /api/mcp/status endpoint share a single typed enum with compile-time safety.
const ( MCPStateIdle MCPServerState = "idle" // configured but no bridge running MCPStateConnected MCPServerState = "connected" // kiro-cli reported server_initialized MCPStateOAuth MCPServerState = "needs_auth" // kiro-cli sent oauth_request MCPStateFailed MCPServerState = "failed" // kiro-cli sent server_init_failure )
MCPStateIdle and the following constants define the valid MCPServerState lifecycle values.
type MCPSnapshotServer ¶
type MCPSnapshotServer struct {
Name string `json:"name"`
}
MCPSnapshotServer is one entry in a hub-to-steering MCP registry snapshot. Defined here to keep the steering package decoupled from internal/hub.
type Message ¶
type Message struct {
// ChangedFiles is part of the per-turn summary (credits · elapsed · files
// changed) shown in the assistant turn's footer, set on the final assistant
// message at turn_ended so the footer survives reload. It was previously an
// un-keyed direct DOM write in the client, which double-rendered on SSE
// replay and vanished on refresh. Mirrors the turn_ended SSE payload shape.
// (Field order in this struct is govet-fieldalignment-optimal, not logical.)
ChangedFiles map[string]*FileChange `json:"changed_files,omitempty"`
Role Role `json:"role"`
Content string `json:"content,omitempty"`
// Reasoning is the agent's "thinking" trace for this turn —
// extended-thinking models emit it as a parallel stream alongside
// Content. Persisted on the same message so the one-message-per-turn
// invariant holds; rendered above the content bubble in the UI.
Reasoning string `json:"reasoning,omitempty"`
// CheckpointTag is the REAL checkpoint tag the server allocated for
// this turn (set only on the user message that started a turn whose
// agent produced at least one file snapshot). It is the turn-canonical
// tag ("N", never "N.K") the client passes verbatim to restore_checkpoint
// / undo_edit. Empty when the turn produced no snapshot; persisted so it
// survives reload.
CheckpointTag string `json:"checkpoint_tag,omitempty"`
EventKind EventKind `json:"event_kind,omitempty"`
ID string `json:"id"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
// Blocks is the chronologically-ordered content array — text / tool_use /
// thinking blocks in the order the agent emitted them, each stamped with an
// agent_subtask_id (empty for the parent agent, set for a subagent). It is
// the canonical render model; the client normalizes legacy Content/ToolCalls
// into Blocks on replay so there is a single render path.
Blocks []Block `json:"blocks,omitempty"`
// CodeReferences carries licensed-code attributions the agent flagged
// during this turn (v3/KAS _kiro/code_references). Turn-scoped: the wire
// carries no span, so it annotates the whole assistant turn. Persisted here
// so the chip survives reload.
CodeReferences []CodeReference `json:"code_references,omitempty"`
// Refusal marks this assistant turn as a model refusal (kiro-cli 2.13
// contract): the message content IS the refusal explanation, and this
// carries the category + recommended-model metadata the client uses to
// render the distinct refusal callout (chip + rewind / switch-model CTAs).
Refusal *RefusalInfo `json:"refusal,omitempty"`
Plan []PlanEntry `json:"plan,omitempty"`
// TurnCredits / TurnElapsedMs complete the turn footer summary alongside
// ChangedFiles (above). The values also ride the turn_ended SSE for the
// live render; omitempty drops the zero cases (a read-only turn has none).
TurnCredits float64 `json:"turn_credits,omitempty"`
TurnElapsedMs float64 `json:"turn_elapsed_ms,omitempty"`
Ts int64 `json:"ts"`
}
Message is one entry in a chat transcript. Tool calls are embedded in assistant messages (not standalone messages). Event messages carry an EventKind for inline rendering (compression, cancellation, restart).
type MessageChunkPayload ¶
type MessageChunkPayload struct {
// Refusal tags this delta as the model-refusal explanation (kiro-cli
// 2.13 _meta.kiro.refusal on the chunk). Set on at most one chunk per
// turn, right before the turn ends with stop_reason "refusal"; lets the
// live renderer style the refusal callout without waiting for
// turn_ended.
Refusal *RefusalInfo `json:"refusal,omitempty"`
MessageID string `json:"message_id"`
Delta string `json:"delta"`
AgentSubtaskID string `json:"agent_subtask_id,omitempty"`
BlockIndex int `json:"block_index"`
// Seq is the delta's 1-based sequence number within the turn
// (assigned by the buffer under its lock). A client that ingested
// a connect-time turn_state snapshot drops chunks with
// seq <= the snapshot's chunk_seq watermark — they are already
// folded into the snapshot — instead of double-appending them.
Seq int64 `json:"seq,omitempty"`
IsReasoning bool `json:"is_reasoning,omitempty"`
}
MessageChunkPayload is the payload for type="message_chunk" (assistant streaming deltas). IsReasoning distinguishes reasoning deltas from regular content deltas — both flow through the same SSE event but land on different fields client-side (Message.Reasoning vs Content). BlockIndex addresses the chronological content block this delta belongs to (Anthropic's content_block_delta.index): consecutive text chunks share an index; a tool_call between text segments bumps the next text chunk to a new index. Clients use this to accumulate deltas into the right block in Message.Blocks.
type MeteringItem ¶
type MeteringItem struct {
UnitSingular string `json:"unit_singular"`
UnitPlural string `json:"unit_plural"`
Value float64 `json:"value"`
}
MeteringItem is one usage dimension reported by kiro-cli's meteringUsage array. UnitPlural is the canonical identifier ("credits", "tokens", "requests"); UnitSingular is its singular form.
type ModeChangedPayload ¶
type ModeChangedPayload struct {
ModeID string `json:"mode_id"`
}
ModeChangedPayload is the payload for type="mode_changed".
type ModelID ¶
type ModelID string
ModelID is a typed wrapper for model identifiers. Values are validated via ValidIdent before assignment; the type makes invalid-state propagation a compile-time-visible decision.
type OpenExternalURLPayload ¶ added in v0.1.165
type OpenExternalURLPayload struct {
URL string `json:"url"`
}
OpenExternalURLPayload is the payload for type="open_external_url". The agent (v3/KAS) asks the client to open a URL for the user, most often an MCP server's OAuth authorization page. Browsers popup-block a window.open() not driven by a user gesture, so the client surfaces a clickable affordance (a banner link) the user activates rather than auto-opening. Only http/https URLs are broadcast (server-side scheme guard in hub/bridge_v3_auth.go; the client re-checks before rendering).
type PendingAction ¶
type PendingAction string
PendingAction discriminates between the two resolution outcomes for a staged pending change. Using a typed string prevents typos at construction sites and makes the valid set discoverable.
const ( PendingActionAccept PendingAction = "accept" PendingActionReject PendingAction = "reject" )
PendingActionAccept and the following constants define the valid PendingAction values for resolving staged changes.
func (PendingAction) Valid ¶
func (a PendingAction) Valid() bool
Valid reports whether a is one of the recognised pending actions.
type PendingChange ¶
type PendingChange struct {
ToolCallID string `json:"tool_call_id"`
ChatID ChatID `json:"chat_id"`
Path string `json:"path"`
Kind PendingChangeKind `json:"kind"` // "create" | "edit" | "delete"
OldText string `json:"old_text,omitempty"`
NewText string `json:"new_text,omitempty"`
CreatedAt int64 `json:"created_at"`
Truncated bool `json:"truncated,omitempty"`
}
PendingChange is one staged file operation awaiting user approval in Supervised mode. Key is ToolCallID (kiro-cli's id; unique per call); the Kind discriminates between writes, creates (no OldText), and deletes (no NewText).
OldText and NewText are capped at pendingTextCap on the server side (4 MiB). When truncated, the client's "View diff" tab falls back to a file fetch for the full content; the staged payload only carries enough for the pill-popover summary and the inline diff preview.
type PendingChangeAddedPayload ¶
type PendingChangeAddedPayload struct {
Change PendingChange `json:"change"`
}
PendingChangeAddedPayload is the payload for type="pending_change_added". Emitted when the Supervised-mode fs handler has received a write from kiro-cli and is blocking the agent until the user resolves it. Clients render a tool-card-level Accept/Reject pair and surface the op in the Supervised pill's popover.
type PendingChangeKind ¶
type PendingChangeKind string
PendingChangeKind discriminates between the three staged-file operations in Supervised mode. Using a typed string prevents typos at construction sites and makes the valid set discoverable.
const ( PendingKindCreate PendingChangeKind = "create" PendingKindEdit PendingChangeKind = "edit" PendingKindDelete PendingChangeKind = "delete" )
PendingKindCreate and the following constants define the valid PendingChangeKind values for supervised-mode file operations.
func (PendingChangeKind) Valid ¶
func (k PendingChangeKind) Valid() bool
Valid reports whether k is one of the recognised pending change kinds.
type PendingChangeResolvedPayload ¶
type PendingChangeResolvedPayload struct {
ToolCallID string `json:"tool_call_id"`
Action PendingAction `json:"action"` // "accept" | "reject"
Path string `json:"path,omitempty"`
}
PendingChangeResolvedPayload is the payload for type="pending_change_resolved". Emitted after the user accepts or rejects a staged change, after the fs handler has unblocked and the disk state reflects the decision. Clients drop the op from the pending pill and update the source tool card's status.
type PendingChangesClearedPayload ¶
type PendingChangesClearedPayload struct {
Reason ClearReason `json:"reason,omitempty"` // "cancelled" | "mode_disabled" | "chat_deleted"
}
PendingChangesClearedPayload is the payload for type="pending_changes_cleared". Emitted when a turn is cancelled or the chat's Supervised mode is disabled while ops are outstanding; every pending op for the chat is rejected server-side and the client flushes its pending list.
type PendingStore ¶
type PendingStore interface {
// ListForChat returns all pending changes for the given chat.
ListForChat(chatID ChatID) []PendingChange
// Get returns a single pending change by tool-call ID.
Get(toolCallID string) (PendingChange, bool)
// ChatIDs returns the IDs of all chats with pending changes.
ChatIDs() []ChatID
// RejectAllForChat rejects all pending changes for the given chat,
// returning the rejected snapshots.
RejectAllForChat(chatID ChatID) []PendingChange
// Resolve resolves a single pending change with the given action.
// chatID scopes the resolution: an op whose ChatID differs is treated
// as unknown, so a resolve command carrying a mismatched chat_id can
// never settle another chat's op.
Resolve(ctx context.Context, chatID ChatID, toolCallID string, action PendingAction) (PendingChange, error)
}
PendingStore is the consumer-side interface for the pending-change subsystem. The hub uses these methods for SSE replay, rejection on bridge teardown, and full-content retrieval. The concrete *pending.Store satisfies this interface implicitly.
type PendingTrustClearedPayload ¶
type PendingTrustClearedPayload struct {
Reason ClearReason `json:"reason,omitempty"` // "turn_ended" | "cancelled" | "mode_disabled" | "chat_deleted"
}
PendingTrustClearedPayload is the payload for type="pending_trust_cleared". Emitted when the perTurnTrust flag drops: end of turn, cancel, chat-delete, or supervised-mode toggle-off. The pill reverts to the standard Supervised state. Reason mirrors pending_changes_cleared's vocabulary so both events can share dispatch semantics on the client.
type PendingTrustEnabledPayload ¶
type PendingTrustEnabledPayload struct{}
PendingTrustEnabledPayload is the payload for type="pending_trust_enabled". Emitted when the user clicks "Trust remaining" in the Supervised pill, setting the chat's perTurnTrust flag so subsequent agent writes in the same turn bypass staging. The pill flips to a visibly-distinct "Trusted · this turn" state; the flag clears on turn_ended via the paired pending_trust_cleared event. Replayed on SSE reconnect so the UI state survives disconnects mid-turn.
type PermissionNeededPayload ¶
type PermissionNeededPayload struct {
ToolCallID string `json:"tool_call_id,omitempty"`
Title string `json:"title,omitempty"`
// Kind forwards the ACP toolCall.kind so the client can style
// distinctive permission prompts (switch_mode gets a different
// dialog vs an execute_bash prompt).
Kind ToolKind `json:"kind,omitempty"`
SubSessionID string `json:"sub_session_id,omitempty"`
Options []PermissionOption `json:"options"`
RequestID int64 `json:"request_id"`
}
PermissionNeededPayload is the payload for type="permission_needed".
type PermissionOption ¶
type PermissionOption struct {
OptionID string `json:"option_id"`
Name string `json:"name"`
Kind string `json:"kind"`
}
PermissionOption is one selectable response in a permission dialog.
type PermissionOutcome ¶
type PermissionOutcome struct {
Outcome PermissionOutcomeInner `json:"outcome"`
}
PermissionOutcome is the typed wire shape for ACP permission-outcome responses. Replaces anonymous map[string]any for compile-time safety.
func PermissionOutcomeCancelled ¶
func PermissionOutcomeCancelled() *PermissionOutcome
PermissionOutcomeCancelled builds the ACP permission-outcome response for a cancelled/denied permission. Single source of truth for the wire shape.
func PermissionOutcomeSelected ¶
func PermissionOutcomeSelected(optionID string) *PermissionOutcome
PermissionOutcomeSelected builds the ACP permission-outcome response for a selected option. Single source of truth for the wire shape.
type PermissionOutcomeInner ¶
type PermissionOutcomeInner struct {
Outcome string `json:"outcome"`
OptionID string `json:"optionId,omitempty"`
}
PermissionOutcomeInner is the nested outcome payload.
type PermissionResponseCommand ¶
type PermissionResponseCommand struct {
OptionID string `json:"option_id"`
RequestID int64 `json:"request_id"`
}
PermissionResponseCommand is the payload for type="permission_response".
type PermissionsChangedPayload ¶ added in v0.1.165
type PermissionsChangedPayload struct {
Status string `json:"status,omitempty"`
Errors []PolicyErrorItem `json:"errors,omitempty"`
}
PermissionsChangedPayload is the SSE payload for type="permissions_changed" (translated from _kiro/policy/changed). Clients refetch GET /api/permissions on receipt. Status is "success" or "failed"; Errors carries any non-fatal warnings or the fatal parse error.
type PlanEntry ¶
type PlanEntry struct {
Content string `json:"content"`
Priority string `json:"priority"`
Status PlanStatus `json:"status"`
}
PlanEntry is one item in an agent-authored plan.
type PlanStatus ¶
type PlanStatus string
PlanStatus is the lifecycle state of a plan entry.
const ( PlanPending PlanStatus = "pending" PlanInProgress PlanStatus = "in_progress" PlanCompleted PlanStatus = "completed" )
PlanPending and the following constants define the PlanStatus lifecycle states for a plan entry.
type PolicyErrorItem ¶ added in v0.1.165
type PolicyErrorItem struct {
Scope string `json:"scope,omitempty"`
Source string `json:"source,omitempty"`
Message string `json:"message"`
Fatal bool `json:"fatal,omitempty"`
}
PolicyErrorItem is one entry in a policy/changed or policy/error notification's errors array (from KAS).
type PolicyErrorPayload ¶ added in v0.1.165
type PolicyErrorPayload struct {
Errors []PolicyErrorItem `json:"errors,omitempty"`
}
PolicyErrorPayload is the SSE payload for type="policy_error" (translated from _kiro/policy/error). Surfaced as a banner so a bad hand-edit or a rejected rule is visible without hunting the logs.
type PolicyExplainRequest ¶ added in v0.1.165
type PolicyExplainRequest struct {
Capability string `json:"capability,omitempty"`
ToolID string `json:"tool_id,omitempty"`
Resource string `json:"resource,omitempty"`
}
PolicyExplainRequest is the POST /api/permissions/explain body. Exactly one of Capability / ToolID is required; Resource is the path (fs caps) or command (shell) being simulated. KAS requires a resource for the shell capability.
type PolicyExplainResult ¶ added in v0.1.165
type PolicyExplainResult struct {
Capability string `json:"capability"`
Resource string `json:"resource,omitempty"`
Effect string `json:"effect"`
MatchedRule *PolicyRuleCore `json:"matched_rule,omitempty"`
Scope string `json:"scope,omitempty"`
Source string `json:"source,omitempty"`
IsExplicitAsk bool `json:"is_explicit_ask"`
}
PolicyExplainResult mirrors _kiro/permissions/explain (a pure simulation).
type PolicyProvider ¶ added in v0.1.165
type PolicyProvider interface {
PolicyList(ctx context.Context, scope string) ([]PolicyRule, error)
PolicyExplain(ctx context.Context, req PolicyExplainRequest) (*PolicyExplainResult, error)
}
PolicyProvider reads the native Cedar policy via a live bridge (the utility bridge). Implemented by *hub.Hub so the server can serve GET /api/permissions + POST /api/permissions/explain without depending on the full Hub surface.
type PolicyRule ¶ added in v0.1.165
type PolicyRule struct {
Capability string `json:"capability"`
Effect string `json:"effect"`
Scope string `json:"scope"`
Source string `json:"source"`
Match []string `json:"match,omitempty"`
Exclude []string `json:"exclude,omitempty"`
}
PolicyRule is one native policy rule as reported by _kiro/permissions/list. Capability + effect are always present; match/exclude are optional glob lists; scope + source carry provenance (source is a file path for user/workspace rules, or a synthetic tag like "kiro-scope"/"agent-profile").
type PolicyRuleCore ¶ added in v0.1.165
type PolicyRuleCore struct {
Capability string `json:"capability"`
Effect string `json:"effect"`
Match []string `json:"match,omitempty"`
Exclude []string `json:"exclude,omitempty"`
}
PolicyRuleCore is the rule shape without provenance, used inside an explain result's matched_rule.
type PolicyView ¶ added in v0.1.165
type PolicyView struct {
Rules []PolicyRule `json:"rules"`
WritableScopes []string `json:"writable_scopes"`
Capabilities []string `json:"capabilities"`
Available bool `json:"available"`
}
PolicyView is the GET /api/permissions response: the native policy rule set plus the metadata the editor needs. Available is false when no bridge could answer (the view falls back to reading the editable files directly).
type PromptCommand ¶
type PromptCommand struct {
Text string `json:"text"`
MessageID string `json:"message_id"` // client-generated ULID
Model string `json:"model,omitempty"`
ActiveFile string `json:"active_file,omitempty"` // editor active file path
OpenFiles []string `json:"open_files,omitempty"` // all open editor tabs
Attachments []Attachment `json:"attachments,omitempty"` // files attached via pill row
}
PromptCommand is the payload for type="prompt".
Text is required, trimmed, and capped at 512 KiB; oversize returns HTTP 413. MessageID is required and must match the ULID/id character set enforced by the hub's validMessageID check (128-byte cap, no control chars). Model is optional; if non-empty it must match validIdent (ASCII alphanumerics plus `_.-`, 1-128 bytes). ActiveFile and OpenFiles are forwarded to kiro-cli as _meta.kiro metadata; they do not reach a filesystem sink directly in vibekit. Attachments are resolved via resolveInsideWorkDir before read.
type PushKind ¶
type PushKind string
PushKind identifies a push notification category. The underlying string is the wire value stored in settings and matched by the client's service worker.
const ( PushKindAgentFinished PushKind = "agent_finished" PushKindPermission PushKind = "permission" )
Push notification kind constants. These live in the api package so hub callers can reference them without importing the push package (eliminating the hub→push import that existed solely for constant access).
type PushService ¶
type PushService interface {
RouteHandler
Subscribe(sub PushSubscription)
Unsubscribe(endpoint string)
Send(ctx context.Context, title, body string, notifyType PushKind)
HasSubscribers() bool
SetPreferences(prefs map[PushKind]bool)
// ReloadPreferences re-reads notification toggles from disk,
// deduplicating concurrent calls via singleflight. Called on SSE
// reconnect so externally-edited config.json changes take effect
// without a container restart.
ReloadPreferences(ctx context.Context)
// Close cancels any in-flight pushes via context so the hub's
// shutdown path doesn't block on the 10s HTTP client timeout
// per pending subscriber.
Close()
}
PushService manages Web Push subscriptions and sends notifications.
type PushSubscription ¶
type PushSubscription struct {
Endpoint string `json:"endpoint"`
Keys PushSubscriptionKeys `json:"keys"`
}
PushSubscription is a Web Push subscription from the browser (RFC 8030).
type PushSubscriptionKeys ¶
PushSubscriptionKeys holds the client-side encryption keys.
type RPCErrorOut ¶
RPCErrorOut is the error object in an outbound JSON-RPC response.
type RPCNotification ¶
type RPCNotification struct {
Params any `json:"params,omitempty"`
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
}
RPCNotification is an outbound JSON-RPC 2.0 notification (no id, no response expected). Used by Bridge.Notify instead of ad-hoc map[string]any construction.
type RPCRequest ¶
type RPCRequest struct {
JSONRPC string `json:"jsonrpc"`
Params any `json:"params,omitempty"`
Method string `json:"method"`
ID int64 `json:"id"`
}
RPCRequest is an outbound JSON-RPC 2.0 request sent to kiro-cli.
type RPCResponse ¶
type RPCResponse struct {
Error *RPCError `json:"error,omitempty"`
ID *int64 `json:"id,omitempty"`
JSONRPC string `json:"jsonrpc"`
Method string `json:"method,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
}
RPCResponse is a JSON-RPC 2.0 message from kiro-cli. A populated ID with Result or Error is a response; an empty ID with Method and Params is a server-sent notification.
type RPCResponseOut ¶
type RPCResponseOut struct {
Result any `json:"result,omitempty"`
Error *RPCErrorOut `json:"error,omitempty"`
JSONRPC string `json:"jsonrpc"`
ID int64 `json:"id"`
}
RPCResponseOut is an outbound JSON-RPC 2.0 response to a request received from kiro-cli. Used by Bridge.Respond instead of ad-hoc map[string]any construction.
type RefusalInfo ¶ added in v0.2.8
type RefusalInfo struct {
Category string `json:"category,omitempty"`
RecommendedModel string `json:"recommended_model,omitempty"`
}
RefusalInfo is the structured refusal metadata KAS attaches when the model declines to continue a conversation (modelStopReason "content_filtered"; kiro-cli 2.13+). It rides the refusal explanation chunk's update-level _meta.kiro.refusal and the turn ends with stopReason "refusal". The explanation text itself streams as ordinary assistant content, so only the classification fields are kept here; persisted on the assistant Message so the refusal callout survives reload. RecommendedModel, when set, names a model the service suggests switching to.
type ResolveAllPendingChangesCommand ¶
type ResolveAllPendingChangesCommand struct {
Action PendingAction `json:"action"` // "accept" | "reject"
}
ResolveAllPendingChangesCommand is the payload for type="resolve_all_pending_changes". Bulk-resolve every outstanding staged op in the chat with the same action. Convenience for the Supervised pill's "Accept all" / "Reject all" buttons.
type ResolvePendingChangeCommand ¶
type ResolvePendingChangeCommand struct {
ToolCallID string `json:"tool_call_id"`
Action PendingAction `json:"action"` // "accept" | "reject"
}
ResolvePendingChangeCommand is the payload for type="resolve_pending_change". Accept or reject ONE staged file op. The ToolCallID identifies the op; Action is "accept" or "reject". Unknown actions or unknown ids produce a 400; idempotent re-resolve of an already-settled op produces a success no-op.
type ResolvePendingChangePartialCommand ¶
type ResolvePendingChangePartialCommand struct {
ToolCallID string `json:"tool_call_id"`
MergedText string `json:"merged_text"`
}
ResolvePendingChangePartialCommand is the payload for type="resolve_pending_change_partial". Applies a user-authored MergedText in place of the agent's proposed write — the fs handler unblocks with accept semantics but writes the caller-supplied text instead of the staged NewText. Used by per-hunk Accept/Reject in the editor: the client starts from OldText, splices in only the accepted hunks, and sends the result. Rejecting every hunk should use resolve_pending_change with action="reject" instead (no write).
MergedText is capped the same way staging is: 4 MiB max. Larger payloads are rejected at the JSON body limit layer.
type RewindChatCommand ¶
type RewindChatCommand struct {
TurnIndex int `json:"turn_index"` // 0-based index into parent's messages array
}
RewindChatCommand is the payload for type="rewind_chat". Creates a new chat branched from a specific turn of the current chat.
type RouteHandler ¶
RouteHandler is the minimal contract for any component that wires its own routes under a sub-tree of /api/*. Used by the MCP config store, the MCP runtime registry, and anything else that owns its own mux subset.
type SafetyPropertiesPayload ¶ added in v0.1.165
type SafetyPropertiesPayload struct {
Reason string `json:"reason,omitempty"`
Properties []SafetyProperty `json:"properties"`
}
SafetyPropertiesPayload is the payload for type="safety_properties", translated from the v3 (KAS) _kiro/safety/propertiesChanged notification. Reason is the KAS PropertyChangeReason (formalized/toggled/expired). Same gating + authoring caveats as SafetyStatusPayload.
type SafetyProperty ¶ added in v0.1.165
type SafetyProperty struct {
Description string `json:"description"`
Index int `json:"index,omitempty"`
Enabled bool `json:"enabled,omitempty"`
}
SafetyProperty is one formalized Infrastructure-Safety property. Properties are authored OUT-OF-BAND: KAS "formalizes" them via a remote MCP tool (evaluate_infrastructure_safety at runtime.us-east-1.kiro.dev) from the agent's own infrastructure work — there is no client RPC to create, set, or toggle one, so vibekit only ever displays them, never authors them.
type SafetyStatus ¶ added in v0.1.165
type SafetyStatus string
SafetyStatus is the v3 (KAS) Infrastructure-Safety gate state (GateStatus). The gate evaluates infrastructure-as-code tool calls (Terraform, CFN, CDK, Docker, k8s, …) against remotely-formalized safety properties. Typed so the valid set is discoverable and wiregen emits a TS union.
const ( SafetyStatusIdle SafetyStatus = "idle" SafetyStatusFormalizing SafetyStatus = "formalizing" SafetyStatusEvaluating SafetyStatus = "evaluating" SafetyStatusBlocked SafetyStatus = "blocked" SafetyStatusError SafetyStatus = "error" )
SafetyStatusIdle and the following constants are the v3 (KAS) GateStatus values carried on _kiro/safety/statusChanged.
type SafetyStatusPayload ¶ added in v0.1.165
type SafetyStatusPayload struct {
Status SafetyStatus `json:"status"`
Detail string `json:"detail,omitempty"`
ToolID string `json:"tool_id,omitempty"`
BlockedProperties []string `json:"blocked_properties,omitempty"`
}
SafetyStatusPayload is the payload for type="safety_status", translated from the v3 (KAS) _kiro/safety/statusChanged notification. It surfaces the Infrastructure-Safety gate's live state so the client can show a transient status banner. Defensive/forward-looking: KAS only installs the gate (and so only emits this) when the client declares the infrastructureSafety capability AND an AWS governance flag (infraSafetyMonitor/infraSafetyEnforce) is on — off by default on individual/Builder-ID accounts, so this normally never fires. Distinct from vibekit's own Supervised write-gate (see vibekit-supervised.md).
type ServerEvent ¶
ServerEvent is the envelope broadcast to every SSE client. Payload is the event-specific JSON object; handlers type-assert based on Type.
type SessionID ¶
type SessionID string
SessionID is a typed wrapper for ACP session identifiers. Values are validated via ValidSessionID before assignment; the type makes invalid-state propagation a compile-time-visible decision.
type SessionMode ¶
type SessionMode struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Source string `json:"source,omitempty"` // "bundled" | "workspace" (v3 _meta.kiro.source)
}
SessionMode describes one mode the running agent supports. Populated from the `modes.availableModes` field of kiro-cli's session/new or session/load response; kept on the chat so the UI can render a mode pill without re-querying the bridge.
On v3 (KAS) the availableModes list is unified: it carries both the bundled workflow modes (vibe/spec/quick-spec/bug-fix/plan/autonomous) AND every workspace custom agent (.kiro/agents/*), each switchable via session/set_mode. Source distinguishes them ("bundled" vs "workspace") so the picker can group built-in modes above custom agents.
type SessionModel ¶
type SessionModel struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
RateMultiplier float64 `json:"rate_multiplier,omitempty"`
// HasEffort reports whether this model supports a reasoning-effort level.
// KAS's config_option_update stamps _meta.kiro.hasEffort on each model
// choice (true when the model has effort levels). The model picker hides
// the effort row for the current model when the catalog carries
// has_effort:true on some model but not the current one; a catalog with no
// has_effort anywhere (e.g. the pre-session REST list) safely shows it. A
// non-effort model omits the field (client reads it as undefined), which is
// why the client's gate keys off "any model advertises effort" rather than
// a per-model false.
HasEffort bool `json:"has_effort,omitempty"`
}
SessionModel describes one model the running agent can swap to, as declared by kiro-cli's session/new response. Replaces our prior shell-out to `kiro-cli chat --list-models`.
type SetEffortCommand ¶
type SetEffortCommand struct {
Level EffortLevel `json:"level"` // "low" | "medium" | "high" | "xhigh" | "max"
}
SetEffortCommand is the payload for type="set_effort". Applies a reasoning effort level to the active session.
type SetModeCommand ¶ added in v0.1.165
type SetModeCommand struct {
ModeID string `json:"mode_id"`
}
SetModeCommand is the payload for type="set_mode". ModeID is the id of an entry in the chat's AvailableModes — on v3 that spans the bundled workflow modes (vibe/spec/plan/…) AND workspace custom agents, all switched via session/set_mode. Applied to the live session in place; for a chat whose bridge hasn't started yet the mode is persisted and applied when session/new completes (StartOpts.Mode).
type SetSupervisedModeCommand ¶
type SetSupervisedModeCommand struct {
Enabled bool `json:"enabled"`
}
SetSupervisedModeCommand is the payload for type="set_supervised_mode". Toggles the chat's SupervisedMode field. Disabling while ops are outstanding auto-rejects them (broadcast as pending_changes_cleared with reason="mode_disabled"); the agent unblocks with an error per op.
type SettingsUpdatedPayload ¶
type SettingsUpdatedPayload struct{}
SettingsUpdatedPayload is the payload for type="settings_updated".
type Spec ¶ added in v0.1.165
type Spec struct {
// Name is the spec directory name (the KAS featureName).
Name string `json:"name"`
// RequirementsPath / DesignPath / TasksPath are workspace-relative
// paths to each document, present only when the document exists (so
// the client can open it in the editor via the /file route).
RequirementsPath string `json:"requirements_path,omitempty"`
DesignPath string `json:"design_path,omitempty"`
TasksPath string `json:"tasks_path,omitempty"`
// Error carries a per-spec getTaskStatuses failure so one bad spec
// doesn't blank the whole board; the doc trio still renders.
Error string `json:"error,omitempty"`
// UpdatedAt is the RFC3339 mtime of tasks.md (freshness hint), or ""
// when there is no tasks.md.
UpdatedAt string `json:"updated_at,omitempty"`
// Tasks is the parsed task tree from getTaskStatuses. Empty when the
// spec has no tasks.md yet (sparse state) or a parse/read failed.
Tasks []SpecTaskNode `json:"tasks"`
// HasRequirements / HasDesign / HasTasks report document presence so
// the client renders the requirements→design→tasks trio with clear
// "not created yet" states.
HasRequirements bool `json:"has_requirements"`
HasDesign bool `json:"has_design"`
HasTasks bool `json:"has_tasks"`
}
Spec is one .kiro/specs/<name> entry surfaced on the board.
type SpecTaskChange ¶ added in v0.1.165
type SpecTaskChange struct {
TaskID string `json:"task_id"`
ExecutionStatus string `json:"execution_status,omitempty"`
MarkdownStatus string `json:"markdown_status,omitempty"`
LastSessionID string `json:"last_session_id,omitempty"`
LastExecutionID string `json:"last_execution_id,omitempty"`
}
SpecTaskChange is one entry in a SpecTaskChangedPayload. A single notification can carry several (e.g. an abort flips every in-flight task).
type SpecTaskChangedPayload ¶ added in v0.1.165
type SpecTaskChangedPayload struct {
FeatureName string `json:"feature_name"`
TasksFilePath string `json:"tasks_file_path,omitempty"`
Changes []SpecTaskChange `json:"changes"`
}
SpecTaskChangedPayload is the payload for type="spec_task_changed", translated from the KAS _kiro/spec/taskStatusChanged notification. It fires while a spec execution runs (executeTask / runAllTasks), carrying the task-level execution-status deltas. Broadcast globally (no chat_id) because the board is a workspace-global surface; the client refetches the affected spec by FeatureName. FeatureName is derived server-side from the notification's tasksFilePath (the basename of its parent directory).
type SpecTaskNode ¶ added in v0.1.165
type SpecTaskNode struct {
// TaskID is the KAS task identifier — the full parsed task line text
// (e.g. "2.1 Write property test for X"), not just the number.
TaskID string `json:"task_id"`
// MarkdownStatus is the checkbox state parsed from tasks.md:
// not_started | in_progress | completed | queued.
MarkdownStatus string `json:"markdown_status"`
// ExecutionStatus is the last execution outcome tracked by KAS:
// queued | running | succeed | failed | aborted. Empty when the task
// was never executed through the spec RPC.
ExecutionStatus string `json:"execution_status,omitempty"`
// PBTResult is the property-based-test status for the task, when one
// has been recorded.
PBTResult *SpecTaskPBT `json:"pbt_result,omitempty"`
// LastSessionID / LastExecutionID identify the most recent execution
// (informational; surfaced as provenance, not acted on).
LastSessionID string `json:"last_session_id,omitempty"`
LastExecutionID string `json:"last_execution_id,omitempty"`
// SubTasks is the nested child list (recursive).
SubTasks []SpecTaskNode `json:"sub_tasks"`
// IsLeaf is true when the task has no subtasks.
IsLeaf bool `json:"is_leaf"`
// IsOptional flags an optional task (KAS "*(Optional)*" marker).
IsOptional bool `json:"is_optional,omitempty"`
}
SpecTaskNode is one task in the tree. Mirrors the KAS getTaskStatuses node shape (snake_cased for the client). ExecutionStatus / LastSessionID / LastExecutionID / PBTResult are absent until an execution has run against the task (a hand-authored spec that was never executed carries only the markdown-derived fields), so they are all omitempty.
type SpecTaskPBT ¶ added in v0.1.165
type SpecTaskPBT struct {
// Status is the PBT outcome: passed | failed | not_run | unexpected_pass.
Status string `json:"status"`
// FailingExample is the counterexample the PBT library reported on a
// failed run (empty otherwise).
FailingExample string `json:"failing_example,omitempty"`
}
SpecTaskPBT is the property-based-test status recorded for a task.
type SpecsResponse ¶ added in v0.1.165
type SpecsResponse struct {
Specs []Spec `json:"specs"`
}
SpecsResponse is the GET /api/specs body.
type StartOpts ¶
type StartOpts struct {
SessionID string
Model string
Effort string
AgentEngine string
Mode string
MCPServers []map[string]any
// EnableHooks opts the session into KAS's v2 hook engine by
// declaring _meta.kiro.hooks={enabled,v2} in the initialize
// handshake. Set on BOTH the utility bridge (so the hooks-management
// dashboard's list|setEnabled|triggerHook work) AND chat bridges (so
// the workspace's .kiro/hooks/*.json hooks autofire on their triggers
// during a turn). In v2 mode KAS loads and runs the hooks itself; it
// does not call back the client to execute autofired hooks. See
// internal/hub/hooks.go and internal/hub/bridge_coord.go.
EnableHooks bool
}
StartOpts collects the parameters for ACPBridge.Start. All fields are optional; a zero-value StartOpts creates a new session with no model override and no MCP servers.
type SteeringGenerator ¶
SteeringGenerator generates steering files for kiro-cli.
type StopReason ¶
type StopReason string
StopReason identifies why a turn ended. The underlying string is the wire value sent over SSE; typed constants prevent typos at construction sites.
const ( StopReasonEndTurn StopReason = "end_turn" StopReasonCancelled StopReason = "cancelled" StopReasonInterrupted StopReason = "interrupted" // StopReasonRefusal is kiro-cli 2.13+'s core ACP stop reason for a model // refusal (content_filtered): the refusal explanation streamed as the last // assistant chunk, tagged with _meta.kiro.refusal (api.RefusalInfo). StopReasonRefusal StopReason = "refusal" )
StopReasonEndTurn and the following constants define the valid StopReason values for turn termination.
type SwitchModelCommand ¶
type SwitchModelCommand struct {
// Target model id. Empty or "auto" = keep current model (a bare
// restart of the bridge, useful when the session is wedged).
Model string `json:"model,omitempty"`
}
SwitchModelCommand is the payload for type="switch_model". Ends the current ACP session and starts a fresh one with a new model, priming the replacement with the chat transcript so kiro-cli has context. kiro-cli cannot swap models mid-session, so we rebuild the bridge. Agent changes are intentionally NOT part of this command — the agent itself is responsible for switching modes, and the user cannot force an agent change on a live chat from the client.
Model accepted forms: empty or "auto" keep the current model (a bare restart of the bridge, useful when the session is wedged); any other value must match validIdent (ASCII alphanumerics plus `_.-`, 1-128 bytes).
type SystemTool ¶ added in v0.1.184
type SystemTool = toolbelt.SystemTool
SystemTool is one image-baked binary surfaced read-only in the UI.
type TerminalCreatedPayload ¶
type TerminalCreatedPayload struct {
TerminalID string `json:"terminal_id"`
Command string `json:"command"`
Args []string `json:"args"`
}
TerminalCreatedPayload is the payload for type="terminal_created".
type TerminalExitedPayload ¶
type TerminalExitedPayload struct {
ExitCode *int `json:"exit_code,omitempty"`
TerminalID string `json:"terminal_id"`
Signal string `json:"signal,omitempty"`
}
TerminalExitedPayload is the payload for type="terminal_exited". A signal-killed process carries Signal (e.g. "killed") with ExitCode omitted; a normal exit carries ExitCode (>=0) with Signal empty. This mirrors KAS's zTerminalExitStatus, which requires exitCode>=0 and a separate signal string, so a signal death never reports exit_code:-1.
type TerminalOutputPayload ¶
type TerminalOutputPayload struct {
TerminalID string `json:"terminal_id"`
Data string `json:"data"`
}
TerminalOutputPayload is the payload for type="terminal_output".
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Title string `json:"title"`
Kind ToolKind `json:"kind"`
Status ToolStatus `json:"status"`
Output string `json:"output,omitempty"`
// SubSessionID is the v2 subagent-session attribution (inert on v3;
// all subagent updates ride the parent session id there).
SubSessionID string `json:"sub_session_id,omitempty"`
// AgentSubtaskID is set from a tool call's _meta.kiro.agentSubtaskId.
// On v3 (KAS) a subagent surfaces as an ordinary tool_call with
// _meta.kiro.kind=="agent-subtask"; this id links the subagent card
// to its nested agent_message_chunk / agent_thought_chunk deltas
// (which carry the same id) so the client can render them nested.
AgentSubtaskID string `json:"agent_subtask_id,omitempty"`
Input json.RawMessage `json:"input,omitempty"`
Locations []ToolLocation `json:"locations,omitempty"`
Diffs []ToolDiff `json:"diffs,omitempty"`
DurationMs int `json:"duration_ms,omitempty"`
Ts int64 `json:"ts"`
}
ToolCall is a tool invocation inside an assistant message. One assistant message may have multiple tool calls; each can be updated in place as status changes (pending → in_progress → completed/failed).
type ToolCallPayload ¶
type ToolCallPayload struct {
MessageID string `json:"message_id"`
ToolCall ToolCall `json:"tool_call"`
BlockIndex int `json:"block_index"`
}
ToolCallPayload is the payload for type="tool_call". BlockIndex is the position of the tool_use block in the assistant message's chronological Blocks array — the client uses it to insert the tool card at the right spot relative to surrounding text blocks.
type ToolCallUpdatePayload ¶
type ToolCallUpdatePayload struct {
MessageID string `json:"message_id"`
ToolCall ToolCall `json:"tool_call"`
}
ToolCallUpdatePayload is the payload for type="tool_call_update".
type ToolCatalogHit ¶ added in v0.1.184
ToolCatalogHit is one catalog search result (GET /api/tools/search).
type ToolCatalogInfo ¶ added in v0.2.31
type ToolCatalogInfo = toolbelt.CatalogInfo
ToolCatalogInfo is the GET /api/tools/catalog response body: the live catalog's provenance and freshness (refs, generation timestamp, source, last refresh outcome, schedule state).
type ToolDiff ¶
type ToolDiff struct {
Path string `json:"path"`
OldText string `json:"old_text,omitempty"`
NewText string `json:"new_text"`
}
ToolDiff is a before/after text change from a write tool call. Sent by kiro-cli in tool_call notifications for edit operations. Path is workspace-relative (absolute paths from kiro-cli are normalised via hub.relPath before being stored here); OldText/NewText are the changed fragments, not full-file contents.
type ToolInfo ¶ added in v0.1.184
ToolInfo is one tool row in GET /api/tools: the manifest entry joined with the engine's install state. Disabled marks a template (recorded intent, nothing installed); Lsp marks a language server.
type ToolJob ¶ added in v0.1.184
ToolJob is one tools-engine job: an install/uninstall/disable/ update/reconcile run on the single-flight queue. Terminal states are done, failed, and cancelled.
type ToolJobAccepted ¶ added in v0.1.184
type ToolJobAccepted = httpapi.JobResponse
ToolJobAccepted is the 202 response body for job-enqueuing tool mutations (add, install, update, patch). The job is null when the mutation needed none (e.g. adding a disabled template).
type ToolJobChangedPayload ¶ added in v0.1.184
type ToolJobChangedPayload struct {
Job *ToolJob `json:"job"`
}
ToolJobChangedPayload is the payload for type="tool_job_changed". Broadcast (workspace-global — no chat_id) on every tool-job state transition: enqueued, started, done, failed, cancelled. The job carries no output tail; output streams via tool_job_output.
type ToolJobOutputPayload ¶ added in v0.1.184
ToolJobOutputPayload is the payload for type="tool_job_output": a coalesced batch of output lines from the running tool job.
type ToolKind ¶
type ToolKind string
ToolKind identifies the category of a tool invocation. Values are assigned by kiro-cli and flow through the ACP protocol unchanged. The full set spans both the original ACP kinds and the richer classifications kiro-cli's translate layer emits for permission dialogs and tool-card rendering.
const ( ToolKindExecute ToolKind = "execute" ToolKindShell ToolKind = "shell" ToolKindRead ToolKind = "read" ToolKindSearch ToolKind = "search" ToolKindFetch ToolKind = "fetch" ToolKindEdit ToolKind = "edit" ToolKindThink ToolKind = "think" ToolKindHook ToolKind = "hook" ToolKindWrite ToolKind = "write" ToolKindDelete ToolKind = "delete" ToolKindMove ToolKind = "move" ToolKindCommand ToolKind = "command" ToolKindBrowser ToolKind = "browser" ToolKindSwitchMode ToolKind = "switch_mode" ToolKindMCP ToolKind = "mcp" ToolKindOther ToolKind = "other" )
ToolKindExecute and the following constants define the valid ToolKind values for classifying tool invocations. KAS v3's zToolKind enum emits only read/edit/delete/move/search/execute/think/fetch/switch_mode/other. The remaining kinds (shell, hook, write, command, browser, mcp) are never emitted on v3 but are retained: they still back WorkingLabelForKind's label table and keep older persisted chat files that recorded them renderable. Hook activity in particular arrives as kind "other" tagged _meta.kiro.hookAsk, NOT ToolKindHook (see translate.ACPKiroMeta).
type ToolLocation ¶
ToolLocation is a file path (and optional line) the agent is working with. Sent by kiro-cli in tool_call and tool_call_update notifications. Used by the editor to scroll to the file the agent is accessing or modifying.
type ToolRemoveResponse ¶ added in v0.1.206
type ToolRemoveResponse = httpapi.RemoveResponse
ToolRemoveResponse is the 202 response body for DELETE /api/tools/{name}; dependents is populated on forced cascades.
type ToolStatus ¶
type ToolStatus string
ToolStatus is the lifecycle state of a tool invocation.
const ( ToolPending ToolStatus = "pending" ToolInProgress ToolStatus = "in_progress" ToolCompleted ToolStatus = "completed" ToolFailed ToolStatus = "failed" )
ToolPending and the following constants define the ToolStatus lifecycle states for a tool invocation.
type ToolsJobsResponse ¶ added in v0.1.184
type ToolsJobsResponse = httpapi.JobsResponse
ToolsJobsResponse is the GET /api/tools/jobs response body.
type ToolsSearchResponse ¶ added in v0.1.184
type ToolsSearchResponse = httpapi.SearchResponse
ToolsSearchResponse is the GET /api/tools/search response body.
type TransportError ¶
TransportError wraps bridge-level transport failures (pipe closed, write timeout, process exited) with explicit retryability semantics. Callers use errors.As to classify without substring matching.
func (*TransportError) Error ¶
func (e *TransportError) Error() string
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error
type TurnEndedPayload ¶
type TurnEndedPayload struct {
ChangedFiles map[string]*FileChange `json:"changed_files,omitempty"`
// Refusal accompanies stop_reason "refusal": the model declined to
// continue and the final assistant chunk carried this metadata
// (also persisted on the message; here for the live render).
Refusal *RefusalInfo `json:"refusal,omitempty"`
StopReason StopReason `json:"stop_reason,omitempty"`
CreditsDelta float64 `json:"credits_delta,omitempty"`
ElapsedMs float64 `json:"elapsed_ms,omitempty"`
}
TurnEndedPayload is the payload for type="turn_ended".
type TurnStatePayload ¶ added in v0.2.8
type TurnStatePayload struct {
// Message is the in-flight assistant message as accumulated so
// far — the hub's turn mirror, byte-equivalent to what a
// never-disconnected client would have rendered. Omitted when the
// turn hasn't produced content yet (busy signal only).
Message *Message `json:"message,omitempty"`
// Status/Description replay the agent's last self-declared
// chat_status for the busy chat. Authoritative here — the turn is
// verifiably in flight — unlike the live event, which stays
// ephemeral and is cleared on gaps precisely because a bare
// replay could resurrect a stale "in_progress".
Status string `json:"status,omitempty"`
Description string `json:"description,omitempty"`
// ChunkSeq is the sequence number of the last delta folded into
// Message (see MessageChunkPayload.Seq).
ChunkSeq int64 `json:"chunk_seq,omitempty"`
}
TurnStatePayload is the payload for type="turn_state": the connect-time synthesis of a chat's in-flight turn (P6). Synthesized per busy chat in the SSE OnConnect replay — never broadcast live — so a reconnecting or freshly-loaded client renders the accumulated turn immediately instead of waiting for the next chunk or turn_ended, and learns authoritatively that the chat is busy (replacing the gap handler's eager thinking-clear guess).
type Usage ¶
type Usage struct {
MeteringItems []MeteringItem `json:"metering_items,omitempty"`
ContextPct float64 `json:"context_pct"`
ContextSize int `json:"context_size"`
Credits float64 `json:"credits"`
TurnCount int `json:"turn_count"`
LastTurnMs float64 `json:"last_turn_ms"`
HasRealData bool `json:"has_real_data"`
}
Usage is a chat's last-known context and billing snapshot.
type UserInputNeededPayload ¶ added in v0.2.43
type UserInputNeededPayload struct {
Question string `json:"question"`
ToolCallID string `json:"tool_call_id,omitempty"`
SubSessionID string `json:"sub_session_id,omitempty"`
Options []UserInputOption `json:"options,omitempty"`
RequestID int64 `json:"request_id"`
}
UserInputNeededPayload is the payload for type="user_input_needed": the agent asked a structured question and awaits an answer. An empty Options slice means a free-form question (the client renders a text field). RequestID is the JSON-RPC id the user_input_response command echoes back.
type UserInputOption ¶ added in v0.2.43
type UserInputOption struct {
Title string `json:"title"`
Description string `json:"description,omitempty"`
SubOptionsLabel string `json:"sub_options_label,omitempty"`
SubOptions []UserInputSubOption `json:"sub_options,omitempty"`
Recommended bool `json:"recommended,omitempty"`
}
UserInputOption is one selectable answer for a user-input question. Recommended marks the option the agent suggests (rendered as a badge).
type UserInputResponseCommand ¶ added in v0.2.43
type UserInputResponseCommand struct {
Action string `json:"action"`
Answer string `json:"answer,omitempty"`
RequestID int64 `json:"request_id"`
}
UserInputResponseCommand is the payload for type="user_input_response". RequestID echoes the value from the user_input_needed event. Answer is the user's answer TEXT (kiro-cli's contract is a plain string the model reads): a clicked option sends its title; an option with sub-options sends "Title [Sub1, Sub2]" (the TUI's format); free-form sends the typed text. Required (non-empty) when Action is "answered".
type UserInputSubOption ¶ added in v0.2.43
type UserInputSubOption struct {
Title string `json:"title"`
Description string `json:"description,omitempty"`
}
UserInputSubOption is one second-level choice under a UserInputOption. Sub-options render as a pre-checked multi-select (the TUI's behavior); the selected titles fold into the answer text as "Parent [Sub1, Sub2]".
type UtilityPrompter ¶
type UtilityPrompter interface {
UtilityPrompt(ctx context.Context, prompt string, effort EffortLevel) (string, error)
}
UtilityPrompter is the narrow interface for AI-backed prompt generation (error explanations, conflict resolution, commit messages). Declared here so both the server and git packages share a single typed contract. effort is the per-task reasoning-effort level: cheap tasks (titles, summaries, error explanations) pass EffortLow, tasks that read a diff or merge code (commit messages, PR descriptions, conflict resolution) pass EffortMedium; "" keeps the session's current level. Best-effort — a model with no effort config ignores it.
type WorkingLabelPayload ¶
type WorkingLabelPayload struct {
Label string `json:"label"`
}
WorkingLabelPayload is the payload for type="working_label". Sent when the agent starts or finishes a tool call so the client can show a contextual label ("Reading", "Searching", "Running <title>", etc.) instead of a generic "Thinking" indicator.