command

package
v0.2.49 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: GPL-2.0, GPL-3.0 Imports: 25 Imported by: 0

Documentation

Overview

Package command implements the POST /api/command dispatch table. Hub registers concrete handler functions; the Dispatcher routes incoming commands by type and handles envelope-level concerns (body parsing, idempotency, validation).

Index

Constants

View Source
const MaxDocumentBytes = 10 * 1024 * 1024

MaxDocumentBytes caps the size of a document attachment (10 MiB).

View Source
const MaxHookField = 8 * 1024

MaxHookField caps the per-field size for CmdCreateHook payloads.

View Source
const ShellOutputCap = 1 * 1024 * 1024

ShellOutputCap bounds the captured stdout+stderr of a `!cmd` shell interception.

View Source
const ShellTimeout = 30 * time.Second

ShellTimeout is the default timeout for user-initiated `!cmd` shell interceptions. Exposed as a package-level constant so tests and future settings overrides can reference the default.

Variables

View Source
var (
	ErrMissingChatID  = errors.New("missing chat_id")
	ErrInvalidPayload = errors.New("invalid payload")

	ErrChatNotFound = errors.New("chat not found")
)

Static command errors returned to the client.

Functions

func AsyncRenameChat

func AsyncRenameChat(deps Dependencies, prompter api.UtilityPrompter, chatID api.ChatID, firstPrompt, placeholder string)

AsyncRenameChat generates a better chat title via the utility bridge. placeholder is the truncated-first-prompt name appendUserMessage set; the generated title only lands while the chat still carries it. If the name changed meanwhile — the agent published a focus title via update_session_information (translate/focus handling), which is richer than a 2-3 word summary of the first message — the utility title is discarded rather than clobbering it.

func BuildPromptBlocks

func BuildPromptBlocks(ctx context.Context, text string, attachments []api.Attachment, resolve func(string) (string, error)) []map[string]any

BuildPromptBlocks constructs the ACP prompt content array: a leading text block followed by one block per attachment.

On v3 (KAS) the agent always advertises promptCapabilities.embeddedContext:true, so a supported document type (documentExts) is always inlined as an ACP embedded `resource` content block; everything else becomes a text path reference the agent reads with its file tools.

func BuildPromptParams

func BuildPromptParams(ctx context.Context, deps Dependencies, sb Bridge, p *api.PromptCommand) map[string]any

BuildPromptParams constructs the full session/prompt parameter map.

func CmdCancel

func CmdCancel(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdCancel cancels the active turn, if any.

func CmdClearPendingTrust

func CmdClearPendingTrust(d *Dispatcher, _ context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdClearPendingTrust clears the per-turn trust flag.

func CmdCreateChat

func CmdCreateChat(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdCreateChat creates a new chat with the given metadata.

func CmdCreateHook

func CmdCreateHook(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdCreateHook creates a hook file from chat context.

func CmdDeleteChat

func CmdDeleteChat(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdDeleteChat removes a chat and cascades to rewind children via the store's DeleteFamily transition (children first, parent last, per- record side-effect teardown through the prepare hook). The response is truthful on partial failure: surviving children are reported instead of the old unconditional OK, and a failed parent delete is a 500 (its children are already gone at that point — retrying deletes the parent alone).

func CmdDiscardRewindChat

func CmdDiscardRewindChat(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdDiscardRewindChat discards a rewind chat and returns to the parent. Deletes the rewind chat; the parent is unaffected (it was never frozen).

func CmdElicitationResponse added in v0.1.39

func CmdElicitationResponse(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdElicitationResponse forwards the user's elicitation form answer to kiro-cli as the elicitation/create response.

func CmdPermission

func CmdPermission(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdPermission forwards the user's permission dialog choice to kiro-cli.

func CmdPromoteRewindChat

func CmdPromoteRewindChat(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdPromoteRewindChat promotes a rewind chat to replace its parent via the store's PromoteRewind transition (validated + cleared under one per-chat lock), then deletes the parent. The transition's order is crash-safe: an interruption between the clear and the parent delete leaves a promoted top-level chat plus a surviving parent (benign — the user can delete it) rather than a chat whose ParentChatID references a deleted parent. A failed clear aborts the promote with an error instead of reporting success while the relationship is intact.

func CmdPrompt

func CmdPrompt(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdPrompt handles the prompt command.

func CmdResolveAllPendingChanges

func CmdResolveAllPendingChanges(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdResolveAllPendingChanges settles every op in the chat.

func CmdResolvePendingChange

func CmdResolvePendingChange(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdResolvePendingChange settles one staged op.

func CmdResolvePendingChangePartial

func CmdResolvePendingChangePartial(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdResolvePendingChangePartial settles one staged op with merged text.

func CmdRestoreCheckpoint

func CmdRestoreCheckpoint(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdRestoreCheckpoint rolls the workspace back to the given tag.

func CmdRewindChat

func CmdRewindChat(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdRewindChat creates a new chat branched from a specific turn of the current chat. Uses kiro-cli's native `session/fork` ACP method to fork the ACP session at the given turn index, then persists a new vibekit chat with truncated history and `parent_chat_id` set.

Unlike the old tangent system, the parent is NOT frozen — both chats continue independently.

func CmdSetEffort

func CmdSetEffort(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdSetEffort applies a reasoning-effort level to the active session. On v3 (KAS) effort is a session config option, so this dispatches session/set_config_option (configId "effortLevel"). Vibekit owns persistence of the effort level; a new session's initial effort is seeded at acp launch via StartOpts.Effort instead.

func CmdSetMode added in v0.1.165

func CmdSetMode(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdSetMode switches the chat's active session mode. If a live bridge exists the switch is applied immediately via session/set_mode; the chosen mode is then persisted on the chat and broadcast so every connected client's pill flips. For a chat whose bridge hasn't started yet (empty chat, first prompt not sent) there is nothing to switch live — the mode is persisted and applied when the bridge's session/new completes (spawnBridge threads chat.CurrentModeID into StartOpts.Mode).

func CmdSetSupervisedMode

func CmdSetSupervisedMode(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdSetSupervisedMode toggles the chat's SupervisedMode flag.

func CmdTrustPendingChanges

func CmdTrustPendingChanges(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdTrustPendingChanges enables per-turn trust and accepts all outstanding ops.

func CmdUndoEdit

func CmdUndoEdit(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdUndoEdit restores a single file to its contents at the given tag.

func CmdUserInputResponse added in v0.2.43

func CmdUserInputResponse(d *Dispatcher, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

CmdUserInputResponse forwards the user's answer to kiro-cli as the _kiro/userInput response.

func HandleShellInterception

func HandleShellInterception(d *Dispatcher, deps Dependencies, ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand, p *api.PromptCommand)

HandleShellInterception runs a "!" prefixed prompt as a local shell command.

func IsRetryablePromptError

func IsRetryablePromptError(err error) bool

IsRetryablePromptError returns true for errors that indicate kiro-cli is temporarily busy or hit a transient internal error.

func RegisterDefaults

func RegisterDefaults(d *Dispatcher)

RegisterDefaults populates the dispatcher with the standard command handlers. Called once from Hub construction.

func SessionParams

func SessionParams(b Bridge, extra ...map[string]any) map[string]any

SessionParams builds the base ACP parameter map with the "sessionId" key set from the bridge. Extra key-value pairs from extra maps are merged in (last-wins).

func TruncateRunes

func TruncateRunes(s string, n int) string

TruncateRunes truncates s to at most n runes, returning a valid byte-prefix of s (preserving original bytes, not re-encoding).

func ValidIdent

func ValidIdent(s string) bool

ValidIdent reports whether s is a safe agent or model identifier.

func ValidMessageID

func ValidMessageID(id string) bool

ValidMessageID reports whether id is safe to echo on SSE and store on disk as the ID field of a message. Delegates to api.ValidMessageID.

Types

type Bridge

type Bridge = api.CommandBridge

Bridge is the per-chat ACP bridge contract for command handlers. The canonical definition lives in api.CommandBridge; this alias preserves backward compatibility within the command package.

type BridgeAccess

type BridgeAccess interface {
	GetBridge(chatID api.ChatID) Bridge
	GetOrCreateBridge(ctx context.Context, chatID api.ChatID, model string) (Bridge, error)
	CloseBridge(chatID api.ChatID)
	PrimeIfNeeded(ctx context.Context, chatID api.ChatID, b Bridge)
}

BridgeAccess provides bridge lifecycle operations needed by prompt, cancel, subagent, slash, and permission handlers.

type ChatAccess

type ChatAccess interface {
	ChatStore() api.ChatStore
	Broadcast(ctx context.Context, evt api.ServerEvent)
	CleanupChatState(ctx context.Context, chatID api.ChatID)
}

ChatAccess provides chat store and broadcast operations needed by create, delete, rewind, and supervised-mode handlers.

type CheckpointAccess

type CheckpointAccess interface {
	Checkpoints() api.CheckpointService
	AdvanceCheckpointTurn(ctx context.Context, chatID api.ChatID)
}

CheckpointAccess provides checkpoint operations needed by prompt, restore, and undo handlers.

type Dependencies

type Dependencies interface {
	BridgeAccess
	ChatAccess
	CheckpointAccess
	SupervisedAccess
	InfraDeps
	Draining() bool
	CheckDedup(reqID string) ([]byte, bool)
	RecordDedup(reqID string, result []byte)
}

Dependencies defines what the Dispatcher needs from its host (Hub). Composed from the role-based sub-interfaces declared in interfaces.go.

type Dispatcher

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

Dispatcher holds the command dispatch table and serves the POST /api/command HTTP endpoint.

func New

func New(deps Dependencies, opts ...Option) *Dispatcher

New constructs a Dispatcher with the given dependencies.

func (*Dispatcher) Bridge

func (d *Dispatcher) Bridge() BridgeAccess

Bridge returns the BridgeAccess subset of dependencies.

func (*Dispatcher) Chat

func (d *Dispatcher) Chat() ChatAccess

Chat returns the ChatAccess subset of dependencies.

func (*Dispatcher) Checkpoint

func (d *Dispatcher) Checkpoint() CheckpointAccess

Checkpoint returns the CheckpointAccess subset of dependencies.

func (*Dispatcher) Deps

func (d *Dispatcher) Deps() Dependencies

Deps returns the dependencies for use by handler functions.

func (*Dispatcher) Infra

func (d *Dispatcher) Infra() InfraDeps

Infra returns the InfraDeps subset of dependencies.

func (*Dispatcher) Prompter

func (d *Dispatcher) Prompter() api.UtilityPrompter

Prompter returns the utility prompter, or nil if not configured.

func (*Dispatcher) Register

func (d *Dispatcher) Register(t api.CommandType, h Handler)

Register adds a handler for the given command type.

func (*Dispatcher) RequireChatID

func (d *Dispatcher) RequireChatID(w http.ResponseWriter, cmd *api.ClientCommand) bool

RequireChatID validates that cmd.ChatID is non-empty and writes a 400 response if not. Returns true when the chat ID is present.

func (*Dispatcher) Respond

func (d *Dispatcher) Respond(w http.ResponseWriter, reqID string, body any)

Respond writes a JSON body and caches it for request_id idempotency.

func (*Dispatcher) RespondErr

func (d *Dispatcher) RespondErr(w http.ResponseWriter, code int, err error)

RespondErr writes a JSON error response with the given status code.

func (*Dispatcher) RespondOK

func (d *Dispatcher) RespondOK(w http.ResponseWriter, reqID string)

RespondOK writes the standard {"ok":true} success response and caches it for idempotent replay. Shorthand for the most common command success case.

func (*Dispatcher) ServeHTTP

func (d *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the POST /api/command HTTP handler.

func (*Dispatcher) Supervised

func (d *Dispatcher) Supervised() SupervisedAccess

Supervised returns the SupervisedAccess subset of dependencies.

type Handler

type Handler func(ctx context.Context, w http.ResponseWriter, cmd *api.ClientCommand)

Handler is the signature for a command handler function.

type InfraDeps

type InfraDeps interface {
	WorkDir() string
	ConfigDir() string
	ShutdownCtx() context.Context
	InflightAdd(delta int)
	InflightDone()
	InflightGo(fn func())
	MCPWaitForReady(ctx context.Context, timeout time.Duration) bool
	ResolveInsideWorkDir(rel string) (string, error)
	IsEmptyTurn(resp *api.RPCResponse, chatID api.ChatID) bool
	EmitTurnEndedWithStats(ctx context.Context, chatID api.ChatID, resp *api.RPCResponse, creditsDelta, elapsedMs float64)
}

InfraDeps provides shared infrastructure operations (workspace, lifecycle, dedup, MCP readiness) used across multiple handlers.

type Option

type Option func(*Dispatcher)

Option configures optional Dispatcher capabilities.

func WithBridge

func WithBridge(_ BridgeAccess) Option

WithBridge is a documentation-only option indicating the Dispatcher uses BridgeAccess from its Dependencies. Reserved for future use where bridge access may be injected independently.

func WithChat

func WithChat(_ ChatAccess) Option

WithChat is a documentation-only option indicating the Dispatcher uses ChatAccess from its Dependencies. Reserved for future use where chat access may be injected independently.

func WithPrompter

func WithPrompter(p api.UtilityPrompter) Option

WithPrompter injects the utility prompter used by AsyncRenameChat. If not provided, auto-rename is silently skipped.

type ShellCappedBuffer

type ShellCappedBuffer struct {
	Buf       bytes.Buffer
	Truncated bool
}

ShellCappedBuffer writes to an underlying bytes.Buffer, rejecting bytes past the cap.

func (*ShellCappedBuffer) Write

func (b *ShellCappedBuffer) Write(p []byte) (int, error)

type SupervisedAccess

type SupervisedAccess interface {
	PendingStore() *pending.Store
	SupervisedSetTrust(chatID api.ChatID)
	SupervisedClearTrust(chatID api.ChatID, reason api.ClearReason)
	ChatInSupervisedMode(ctx context.Context, chatID api.ChatID) bool
	FlushPendingForChat(ctx context.Context, chatID api.ChatID, reason api.ClearReason)
	ClearPendingPermsForChat(chatID api.ChatID)
	RemovePendingPerm(requestID int64)
}

SupervisedAccess provides supervised-mode and pending-permission operations needed by pending/trust handlers.

Jump to

Keyboard shortcuts

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