rocketcode

package
v0.1.30 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 58 Imported by: 0

Documentation

Overview

Package rocketcode provides the reusable RocketCode runtime.

Index

Constants

View Source
const (
	// ChatResponseAssistantMessage identifies final assistant message output.
	ChatResponseAssistantMessage = "assistant_message"
	// ChatResponseAssistantCommentary identifies assistant progress/commentary output.
	ChatResponseAssistantCommentary = "assistant_commentary"
	// ChatResponseAssistantTool identifies structured tool and subagent diagnostics.
	ChatResponseAssistantTool = "assistant_tool"
	// ChatResponseReasoningSummary identifies reasoning summary output.
	ChatResponseReasoningSummary = "reasoning_summary"
)
View Source
const (

	// AllowBackgroundSubject is the rocketclaw permission subject that allows Background Jobs.
	AllowBackgroundSubject = "allow_background"
)

Variables

View Source
var ErrBackgroundKilled = errors.New("background job killed")

ErrBackgroundKilled is wrapped by the cancellation cause that stops a Background Job's work, such as a user stop or shutdown. Unlike other causes it also kills the job's running bash.

View Source
var ErrShutdown = errors.New("shutdown")

ErrShutdown is the cancellation cause that stops a turn after its running calls finish and are journaled. Resumable calls, including task and execute, stop through their own steps instead, and resume when the turn runs again.

Functions

func BashPermissionSubjects added in v0.0.7

func BashPermissionSubjects(command string) []string

BashPermissionSubjects returns independently authorized shell operations. Unparseable syntax and unresolved executable names deny the entire script.

func CheckNestedPermission added in v0.0.45

func CheckNestedPermission(ctx context.Context, toolName, permission, subject string, args map[string]any) error

CheckNestedPermission is a single-subject helper used by MCP builtins.

func CheckNestedToolCall added in v0.0.45

func CheckNestedToolCall(ctx context.Context, toolName string, tool *looperTool, args json.RawMessage) error

CheckNestedToolCall runs the same allow/deny/auto(+reviewer) gate as a top-level tool call, including multi-subject tools (e.g. apply_patch). Must run inside a looper tool Call context.

func CodeModeOnlyHostTool added in v0.0.45

func CodeModeOnlyHostTool(name string) bool

CodeModeOnlyHostTool reports whether name is a sandbox host tool available only inside execute (not as a top-level model tool).

func CompactionCheckpointText added in v0.0.16

func CompactionCheckpointText(compaction *responses.ResponseCompactionItemParam) string

CompactionCheckpointText returns portable text for compaction replay that cannot be rehydrated natively.

func DefaultShellCommand added in v0.0.46

func DefaultShellCommand(command string) (path string, args []string)

DefaultShellCommand uses Bash to match the permission parser's grammar. Privileged mode disables startup files and inherited functions and shell options.

func LoadWorkspaceDefinitions added in v0.0.7

func LoadWorkspaceDefinitions(root *os.Root) (Agents, Skills, func(), error)

LoadWorkspaceDefinitions loads top-level workspace agents and recursive skills.

func RemapReplayAttribution added in v0.1.3

func RemapReplayAttribution(ranges []ReplayAttribution, boundaries []int)

RemapReplayAttribution moves overrides to projected replay boundaries in place.

func ReplayInputFromParams

func ReplayInputFromParams(items []responses.ResponseInputItemUnionParam) ([]json.RawMessage, error)

ReplayInputFromParams returns SDK-native durable replay JSON after each item round-trips through responses.ResponseInputItemUnionParam.

func ReplayInputToParams

func ReplayInputToParams(raw []json.RawMessage) ([]responses.ResponseInputItemUnionParam, error)

ReplayInputToParams decodes SDK-native durable replay JSON through the OpenAI SDK input union.

func ReviewKey added in v0.1.19

func ReviewKey(turnID, callID string) string

ReviewKey is the child-session key segment of every automatic permission review of call callID in turn turnID, before the call runs or during it, such as of a Code Mode script's tool calls.

func SplitPromptAttachmentTokens added in v0.0.7

func SplitPromptAttachmentTokens(text string) (prompt string, files []string, err error)

SplitPromptAttachmentTokens removes @attach:path tokens and returns the paths they name.

func SweepRetainedResults added in v0.1.19

func SweepRetainedResults(root *os.Root, dir string)

SweepRetainedResults sweeps every retained result directory in dir, such as the RetainedResultDir of each conversation, and removes those it empties. Nothing may retain a result in dir meanwhile, as an emptied directory goes away under it.

func ToolCallKey added in v0.1.14

func ToolCallKey(ctx context.Context) string

ToolCallKey returns the current tool call's journal key, stable across restarts; empty outside a call. Inside a Code Mode script each host call has its own key under the script's call.

Types

type Agent

type Agent struct {
	Name            string
	Description     string
	Model           string
	ReasoningEffort string
	Verbosity       string
	MaxRecursion    *int
	Guardrail       string
	CustomShell     string
	Prompt          string
	Location        string
	Permission      PermissionSet
	OutputSchema    map[string]any
	Frontmatter     map[string]any
	FileMode        fs.FileMode
}

Agent contains a single preloaded markdown agent definition.

func ToolCallAgent added in v0.1.12

func ToolCallAgent(ctx context.Context) (Agent, bool)

ToolCallAgent returns the active caller's definition inside a tool call. Its maps and slices are read-only and must not be mutated by consumers.

type AgentLoadResult

type AgentLoadResult struct {
	Agents Agents
	Errors []error
}

AgentLoadResult contains loaded agents and any non-fatal load errors.

func LoadAgents

func LoadAgents(fsys fs.FS, resolveModel func(string) (string, error)) AgentLoadResult

LoadAgents scans the top level of fsys for markdown agent files.

type AgentMaxRecursionError added in v0.0.7

type AgentMaxRecursionError struct {
	Location string
	Err      error
}

AgentMaxRecursionError reports invalid maxRecursion frontmatter.

func (*AgentMaxRecursionError) Error added in v0.0.7

func (e *AgentMaxRecursionError) Error() string

func (*AgentMaxRecursionError) Unwrap added in v0.0.7

func (e *AgentMaxRecursionError) Unwrap() error

type Agents

type Agents struct {
	Items map[string]Agent
}

Agents contains all discovered agents keyed by name.

type Attachment

type Attachment struct {
	MIME     string `json:"mime"`
	Filename string `json:"filename,omitempty"`
	URL      string `json:"url"`
}

Attachment is a model-visible file attachment encoded as a URL, usually a data URL.

func PromptAttachments added in v0.0.7

func PromptAttachments(root *os.Root, cwd string, files []string) ([]Attachment, error)

PromptAttachments loads prompt attachments from workspace-local files.

type BackgroundJob added in v0.1.19

type BackgroundJob struct {
	// ID is the call's turn-scoped tool call key (ToolCallKey), stable across resume.
	ID   string
	Kind BackgroundKind
	// Label is execute's description or task's description.
	Label string
	Agent string
	// ChildKey is the owning subagent's child-session key, empty for the main agent.
	ChildKey string
	// SubagentKey is the child-session key of the subagent a task call runs; empty for execute.
	SubagentKey string
	CallID      string
	// Detached reports that the call asked to start in the background.
	Detached bool
}

BackgroundJob describes one execute or task call of an agent allowed to run it in the background.

type BackgroundJobs added in v0.1.19

type BackgroundJobs interface {
	// Enabled reports whether background mode is offered at all.
	Enabled() bool
	// Run runs work and returns when it finishes attached to its call, or once it runs in the
	// background. Attached work stops with ctx and keeps its cancellation cause.
	Run(ctx context.Context, job *BackgroundJob, work BackgroundWork) (BackgroundResult, error)
	// DrainNotes returns the Completion Notes waiting for the running subagent at subagentKey
	// (BackgroundJob.SubagentKey); they enter its turn at the next step.
	DrainNotes(ctx context.Context, subagentKey string) []PromptInput
}

BackgroundJobs runs the execute and task calls of agents allowed to use background mode.

type BackgroundKind added in v0.1.19

type BackgroundKind string

BackgroundKind is the tool that started a Background Job.

const (
	BackgroundKindExecute BackgroundKind = "execute"
	BackgroundKindTask    BackgroundKind = "task"
)

Background Job kinds.

type BackgroundResult added in v0.1.19

type BackgroundResult struct {
	// Output is the finished work's output; empty when Moved.
	Output string
	// Moved reports that the work runs, or already ran, in the background.
	Moved bool
}

BackgroundResult is how a Background Job call ended for its turn.

type BackgroundWork added in v0.1.19

type BackgroundWork interface {
	RunBackground(ctx context.Context) (string, error)
	// Detach marks the work as running outside its turn, before Run reports the move. It reports
	// false, leaving the work attached, once the work stored its result for its turn.
	Detach() bool
}

BackgroundWork is the work of one execute or task call.

type BashCommand added in v0.0.7

type BashCommand struct {
	Command            string
	TimeoutMillisecond int
	Workdir            string
	Description        string
}

BashCommand is the public shape of the workspace bash tool input.

type BashResult added in v0.0.7

type BashResult struct {
	Output    string
	ErrorCode string
	Success   bool
}

BashResult is the result of running a workspace bash command.

func RunBash added in v0.0.7

func RunBash(ctx context.Context, root *os.Root, shellTempDir string, shellEnv map[string]string, customShell string, command BashCommand) (BashResult, error)

RunBash runs command through the same implementation used by RocketCode's bash tool. A non-empty customShell runs the command as <customShell> <command>.

func (BashResult) String added in v0.0.46

func (r BashResult) String() string

type ChatResponse

type ChatResponse struct {
	Kind     string
	Text     string
	Tool     *ToolDiagnostic
	Subagent *SubagentDiagnostic
	Provider *ProviderDiagnostic
}

ChatResponse is one user-visible response item emitted by the runtime.

type ChildRunStage added in v0.0.20

type ChildRunStage string

ChildRunStage identifies the operation being reviewed by a hidden child run.

const (
	// ChildRunStageDelegation identifies guardrail review before delegation.
	ChildRunStageDelegation ChildRunStage = "delegation"
	// ChildRunStageResponse identifies guardrail review after a child response.
	ChildRunStageResponse ChildRunStage = "response"
)

type ChildSessions added in v0.1.11

type ChildSessions interface {
	AppendChildEntry(ctx context.Context, key string, entry *SessionEntry) error
	// ChildEntries returns the entries saved under key, oldest first.
	ChildEntries(ctx context.Context, key string) ([]SessionEntry, error)
}

ChildSessions stores finished Task, guardrail, and permission review turns.

type Config

type Config struct {
	Model                      shared.ResponsesModel
	AutoApproverModel          shared.ResponsesModel
	ReasoningEffort            shared.ReasoningEffort
	Diagnostics                bool
	ExperimentalStrongerSkills bool
	ExpandPromptShellCommands  PromptShellCommandExpansion
	CompactThreshold           int64
	CompactionSteering         string
	ParallelToolCalls          int
	// ShellTempDir is the workspace-relative or absolute directory used as TMPDIR
	// for bash and prompt !`…` commands. Required; must exist inside the workspace.
	ShellTempDir string
	// SpillDir is the workspace-relative or absolute directory for oversized
	// execute output. Empty uses <workspace>/.rocketcode/spill.
	SpillDir string
	// RetainedResultDir is the directory, relative to SpillDir, that keeps oversized output of
	// background execute scripts readable for 7 days. Required; give each conversation its own.
	RetainedResultDir      string
	AutoApprovePermissions bool
	Observability          ObservabilityConfig
	ChildSessions          ChildSessions
	Journal                Journal
	BackgroundJobs         BackgroundJobs
	CustomTools            []Tool
	ShellEnv               map[string]string
	// ChildContext supplies host messages to guardrails and permission reviewers.
	ChildContext []SessionEntry
	// ShellCommand builds the executable used for bash tool (and prompt !`…`)
	// commands. Required; pass DefaultShellCommand to match permission validation.
	// Custom implementations must preserve the validated Bash syntax and semantics.
	// An agent's customShell overrides it for that agent.
	ShellCommand ShellCommandFunc
	MCPServers   map[string]mcpclient.ServerConfig
	MCPWorkspace string
}

Config contains runtime settings supplied by the embedding application.

func StandaloneConfigFromEnv added in v0.0.7

func StandaloneConfigFromEnv() (Config, error)

StandaloneConfigFromEnv returns the shared default config for RocketCode commands.

type InertBackgroundJobs added in v0.1.19

type InertBackgroundJobs struct{}

InertBackgroundJobs offers no background mode and runs work inline.

func (InertBackgroundJobs) DrainNotes added in v0.1.19

DrainNotes returns no notes.

func (InertBackgroundJobs) Enabled added in v0.1.19

func (InertBackgroundJobs) Enabled() bool

Enabled reports false.

func (InertBackgroundJobs) Run added in v0.1.19

Run runs work inline; it never moves.

type InertChildSessions added in v0.1.11

type InertChildSessions struct{}

InertChildSessions discards child session entries.

func (InertChildSessions) AppendChildEntry added in v0.1.11

AppendChildEntry discards one child session entry.

func (InertChildSessions) ChildEntries added in v0.1.19

ChildEntries returns no entries.

type InertJournal added in v0.1.14

type InertJournal struct{}

InertJournal records nothing and never finds a recorded step.

func (InertJournal) Load added in v0.1.14

func (InertJournal) Load(context.Context, string) (value json.RawMessage, found bool, err error)

Load never finds a recorded step.

func (InertJournal) Save added in v0.1.14

Save discards one step.

func (InertJournal) SaveTrace added in v0.1.14

SaveTrace discards display-only progress.

type Journal added in v0.1.14

type Journal interface {
	Load(ctx context.Context, key string) (json.RawMessage, bool, error)
	Save(ctx context.Context, key string, value json.RawMessage) error
	// SaveTrace persists display-only public progress for the root turn.
	SaveTrace(ctx context.Context, turnID string, trace []json.RawMessage) error
}

Journal durably records completed steps of conversation work so an interrupted turn can resume.

type Looper

type Looper interface {
	Loop(ctx context.Context, input <-chan PromptInput, sessionIn iter.Seq2[SessionEntry, error], sessionOut func(SessionEntry) error, interrupts <-chan os.Signal) error
}

Looper processes prompt input streams with a configured runtime.

type ModelResolver added in v0.0.42

type ModelResolver interface {
	Resolve(model string) (*openai.Client, ProviderOrigin, error)
}

ModelResolver selects an SDK client and API model for a model selector.

type ObservabilityConfig added in v0.0.12

type ObservabilityConfig struct {
	Enabled     bool
	Tracer      trace.Tracer
	TraceConfig instrumentation.TraceConfig
}

ObservabilityConfig controls OpenInference-compatible tracing for RocketCode.

type Operation added in v0.0.7

type Operation string

Operation identifies a high-level command/runtime operation.

const (
	// OperationLoadConfig identifies standalone config loading.
	OperationLoadConfig Operation = "load config"
	// OperationLoadWorkspaceDefinitions identifies workspace-local agent/skill loading.
	OperationLoadWorkspaceDefinitions Operation = "load workspace definitions"
	// OperationParsePromptAttachments identifies prompt attachment token parsing.
	OperationParsePromptAttachments Operation = "parse prompt attachments"
	// OperationLoadPromptAttachments identifies workspace prompt attachment loading.
	OperationLoadPromptAttachments Operation = "load prompt attachments"
)

type OperationError added in v0.0.7

type OperationError struct {
	Operation Operation
	Err       error
}

OperationError adds typed operation context while preserving the wrapped error.

func (OperationError) Error added in v0.0.7

func (e OperationError) Error() string

func (OperationError) Unwrap added in v0.0.7

func (e OperationError) Unwrap() error

type PermissionAction

type PermissionAction string

PermissionAction determines whether a matched operation is allowed or denied.

const (
	// PermissionAllow allows a matching operation.
	PermissionAllow PermissionAction = "allow"
	// PermissionDeny denies a matching operation.
	PermissionDeny PermissionAction = "deny"
	// PermissionAuto requires automatic reviewer approval for a matching operation.
	PermissionAuto PermissionAction = "auto"
)

type PermissionBucket

type PermissionBucket struct {
	Name  string
	Rules []PermissionRule
}

PermissionBucket groups permission rules under a named permission category.

type PermissionRule

type PermissionRule struct {
	Pattern  string
	Action   PermissionAction
	Reviewer string
	// contains filtered or unexported fields
}

PermissionRule matches a subject pattern to a permission action.

type PermissionSet

type PermissionSet struct {
	Buckets []PermissionBucket
	// contains filtered or unexported fields
}

PermissionSet contains all permission buckets configured for an agent.

func (*PermissionSet) Allow

func (ps *PermissionSet) Allow(permission, pattern string) error

Allow appends an allow rule for permission and pattern.

func (*PermissionSet) Deny

func (ps *PermissionSet) Deny(permission, pattern string) error

Deny appends a deny rule for permission and pattern.

func (PermissionSet) Evaluate

func (ps PermissionSet) Evaluate(permission, subject string) (action PermissionAction, matched bool)

Evaluate returns the effective permission action for permission and subject. The matched result reports whether a configured rule explicitly matched. When matched is false, action defaults to PermissionDeny, except that rocketclaw.code_mode_approve and rocketclaw.load_agents_md default to PermissionAllow. Those two and rocketclaw.allow_background change only through an exact rule.

func (*PermissionSet) Set

func (ps *PermissionSet) Set(permission, pattern string, action PermissionAction) error

Set appends a permission rule for permission and pattern.

type PromptInput

type PromptInput struct {
	// ID identifies this input in local durable replay, not provider requests.
	ID string `json:"id,omitempty"`
	// TurnID, when set, is the turn's stable identity and journal key across restarts.
	TurnID string `json:"turn_id,omitempty"`
	// Role defaults to PromptInputRoleUser when empty.
	Role PromptInputRole `json:"role,omitempty"`
	Text string          `json:"text"`
	// Header is the exact generated prefix of Text, saved only in local replay.
	Header      string                  `json:"header,omitempty"`
	Attachments []Attachment            `json:"attachments,omitempty"`
	DirectSkill *PromptInputDirectSkill `json:"directSkill,omitempty"`
	// Responses receives user-visible response items for this prompt. The runtime
	// closes it after the prompt's turn reaches a terminal state.
	Responses chan<- ChatResponse `json:"-"`
}

PromptInput is one prompt plus optional model-visible attachments.

type PromptInputDirectSkill added in v0.0.24

type PromptInputDirectSkill struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments,omitempty"`
}

PromptInputDirectSkill requests a skill load before the model turn starts.

type PromptInputRole

type PromptInputRole string

PromptInputRole identifies the instruction hierarchy role for a prompt input.

const (
	// PromptInputRoleUser identifies ordinary user prompt input.
	PromptInputRoleUser PromptInputRole = "user"
	// PromptInputRoleDeveloper identifies developer instruction prompt input.
	PromptInputRoleDeveloper PromptInputRole = "developer"
)

type PromptShellCommandExpansion

type PromptShellCommandExpansion struct {
	PrimaryPrompts  bool
	SubagentPrompts bool
	SkillPrompts    bool
	InputPrompts    bool
}

PromptShellCommandExpansion controls which prompt sources expand !`command` snippets.

type ProviderDiagnostic

type ProviderDiagnostic struct {
	Provider       string            `json:"provider"`
	Model          string            `json:"model"`
	Phase          string            `json:"phase"`
	HTTPStatus     int               `json:"http_status,omitempty"`
	ResponseStatus string            `json:"response_status,omitempty"`
	Code           string            `json:"code,omitempty"`
	Type           string            `json:"type,omitempty"`
	Message        string            `json:"message,omitempty"`
	Attempt        int               `json:"attempt,omitempty"`
	RetryAfter     string            `json:"retry_after,omitempty"`
	ResponseID     string            `json:"response_id,omitempty"`
	Headers        map[string]string `json:"headers,omitempty"`
}

ProviderDiagnostic describes provider request diagnostics emitted when diagnostics are enabled.

type ProviderOrigin added in v0.0.42

type ProviderOrigin struct {
	Provider         string
	Model            string
	CompactThreshold int64
}

ProviderOrigin identifies the provider and API model selected by a resolver.

type Providers added in v0.0.7

type Providers struct {
	OpenAI *openai.Client
}

Providers contains model provider clients supplied by embedding applications.

func StandaloneProvidersFromEnv added in v0.0.7

func StandaloneProvidersFromEnv() (Providers, error)

StandaloneProvidersFromEnv returns model provider clients for RocketCode commands.

type PublicProgress added in v0.1.12

type PublicProgress struct {
	ID       string              `json:"id"`
	ParentID string              `json:"parent_id,omitempty"`
	Kind     PublicProgressKind  `json:"kind"`
	State    PublicProgressState `json:"state"`
	Text     string              `json:"text,omitempty"`
	Agent    string              `json:"agent,omitempty"`
	Model    string              `json:"model,omitempty"`
	// SubagentKey is the child-session key of the subagent a task call runs or continues, as
	// OpenCode keeps a task part's child session ID in its metadata.
	SubagentKey string `json:"subagent_key,omitempty"`
}

PublicProgress contains only explicitly public text and producer identity. ID is a response/item or call identity, qualified by ParentID when present. Slice order preserves the producer's original item/call order.

func PublicProgressFromTrace added in v0.1.12

func PublicProgressFromTrace(traces []json.RawMessage) []PublicProgress

PublicProgressFromTrace decodes only recognized public records. Legacy, malformed, and unknown future records remain stored but are never projected.

type PublicProgressKind added in v0.1.12

type PublicProgressKind string

PublicProgressKind identifies display-only root activity, never replay input.

const (
	PublicProgressText       PublicProgressKind = "text"
	PublicProgressTool       PublicProgressKind = "tool"
	PublicProgressDelegation PublicProgressKind = "delegation"
)

Public progress kinds distinguish text, tools, and delegated activity.

type PublicProgressState added in v0.1.12

type PublicProgressState string

PublicProgressState is a fixed public lifecycle label, not diagnostic text.

const (
	PublicProgressWorking   PublicProgressState = "working"
	PublicProgressReview    PublicProgressState = "review"
	PublicProgressCompleted PublicProgressState = "completed"
	PublicProgressBlocked   PublicProgressState = "blocked"
	PublicProgressFailed    PublicProgressState = "failed"
	PublicProgressStopped   PublicProgressState = "stopped"
	// PublicProgressBackground means the call returned while its work runs as a Background Job.
	PublicProgressBackground PublicProgressState = "background"
)

Public progress states describe execution and review outcomes.

type ReplayAttribution added in v0.1.3

type ReplayAttribution struct {
	Start           int     `json:"start"`
	End             int     `json:"end"`
	Agent           string  `json:"agent,omitempty"`
	Model           string  `json:"model,omitempty"`
	ReasoningEffort *string `json:"reasoning_effort,omitempty"`
}

ReplayAttribution overrides a recovered half-open replay range, including unknown values.

type ReplayDecodeError

type ReplayDecodeError struct {
	EntryIndex int
	ItemIndex  int
	Kind       string
	Cause      error
}

ReplayDecodeError describes one durable replay item that could not be decoded through the OpenAI SDK input union.

func (*ReplayDecodeError) Error

func (e *ReplayDecodeError) Error() string

func (*ReplayDecodeError) Unwrap

func (e *ReplayDecodeError) Unwrap() error

type Runtime added in v0.0.7

type Runtime = looper

Runtime is the concrete RocketCode loop runtime returned by New.

func New

func New(
	client *openai.Client,
	configInput *Config,
	root *os.Root,
	agents Agents,
	skills Skills,
	defaultAgent string,
	diagnosticsWriter io.Writer,
) (*Runtime, error)

New loads the supplied runtime dependencies and returns a configured looper.

func NewWithModelResolver added in v0.0.42

func NewWithModelResolver(
	resolver ModelResolver,
	configInput *Config,
	root *os.Root,
	agents Agents,
	skills Skills,
	defaultAgent string,
	diagnosticsWriter io.Writer,
) (*Runtime, error)

NewWithModelResolver loads the supplied model resolver and returns a configured looper.

func NewWithProviders added in v0.0.7

func NewWithProviders(
	providers Providers,
	configInput *Config,
	root *os.Root,
	agents Agents,
	skills Skills,
	defaultAgent string,
	diagnosticsWriter io.Writer,
) (*Runtime, error)

NewWithProviders loads the supplied runtime dependencies and returns a configured looper.

func (*Runtime) ContinueSubagent added in v0.1.19

func (r *Runtime) ContinueSubagent(ctx context.Context, jobID, subagentKey, agentName, input string) (string, error)

ContinueSubagent runs input as a new turn of the subagent saved at subagentKey (a BackgroundJob.SubagentKey), as agentName, journaled under jobID, and returns its final answer. The turn joins the subagent's saved history and never reaches its parent. Without input it instead resumes, as the agent that ran it, the turn journaled under jobID before a restart, which agentName delegated; its answer reaches agentName, so the subagent's guardrail reviews it as task does.

func (*Runtime) RestrictTools added in v0.0.41

func (r *Runtime) RestrictTools(names []string) error

RestrictTools limits the runtime to the exact supplied tool allowlist.

type SessionEntry

type SessionEntry struct {
	Version           int                 `json:"version"`
	Type              string              `json:"type"`
	Timestamp         time.Time           `json:"timestamp"`
	TurnID            string              `json:"turn_id,omitempty"`
	ResponseID        string              `json:"response_id,omitempty"`
	Model             string              `json:"model,omitempty"`
	Agent             string              `json:"agent,omitempty"`
	ReasoningEffort   *string             `json:"reasoning_effort,omitempty"`
	ReplayAttribution []ReplayAttribution `json:"replay_attribution,omitempty"`
	TokenUsage        *TokenUsage         `json:"token_usage,omitempty"`
	ReplayInput       []json.RawMessage   `json:"replay_input,omitempty"`
	OutputTrace       []json.RawMessage   `json:"output_trace,omitempty"`
}

SessionEntry is one denormalized persisted session record.

func (*SessionEntry) AttributionAt added in v0.1.3

func (e *SessionEntry) AttributionAt(index int) ReplayAttribution

AttributionAt returns the execution that produced a replay item.

type ShellCommandFunc added in v0.0.46

type ShellCommandFunc func(command string) (path string, args []string)

ShellCommandFunc selects the process used to run a bash tool command string. The returned path and args are passed to exec.Command (for example DefaultShellCommand returns "/bin/bash" with --noprofile --norc -p -c and the command).

type Skill

type Skill struct {
	Name          string
	Description   string
	License       string
	Compatibility string
	Metadata      map[string]any
	Location      string
	Content       string
}

Skill contains a single preloaded skill definition.

type SkillLoadResult

type SkillLoadResult struct {
	Skills Skills
	Errors []error
}

SkillLoadResult contains loaded skills and any non-fatal load errors.

func LoadSkills

func LoadSkills(fsys fs.FS, root string) SkillLoadResult

LoadSkills scans fsys for SKILL.md files and preloads valid skills.

type Skills

type Skills struct {
	Root  string
	Items map[string]Skill
	Dirs  []string
	// contains filtered or unexported fields
}

Skills contains all discovered skills keyed by name.

func (Skills) Available added in v0.1.0

func (s Skills) Available(agent *Agent) []Skill

Available returns skills allowed for agent, sorted by name. Skills requiring permission review are not available for direct invocation or discovery.

func (Skills) Find

func (s Skills) Find(query string) string

Find returns all matching skills ranked by relevance.

func (Skills) FindAvailable

func (s Skills) FindAvailable(query string, agent *Agent) string

FindAvailable returns visible skills matching query as user-facing text.

type SteerDrain added in v0.0.50

type SteerDrain struct {
	Fn func(context.Context, TurnPhase) []PromptInput
}

SteerDrain collects waiting steers and Completion Notes after a tool batch, or when a no-tool answer would otherwise end the turn. The zero value is inert.

func (SteerDrain) Drain added in v0.0.50

func (d SteerDrain) Drain(ctx context.Context, phase TurnPhase) []PromptInput

Drain returns the waiting inputs for phase. The zero value returns nil.

type SubagentDiagnostic

type SubagentDiagnostic struct {
	Name     string              `json:"name"`
	Label    string              `json:"label"`
	Index    int                 `json:"index,omitempty"`
	Total    int                 `json:"total,omitempty"`
	Text     string              `json:"text,omitempty"`
	Tool     *ToolDiagnostic     `json:"tool,omitempty"`
	Subagent *SubagentDiagnostic `json:"subagent,omitempty"`
	Provider *ProviderDiagnostic `json:"provider,omitempty"`
}

SubagentDiagnostic describes a subagent runtime diagnostic emitted when diagnostics are enabled.

type TokenUsage added in v0.0.13

type TokenUsage struct {
	PromptTokens              int64 `json:"prompt_tokens,omitempty"`
	CompletionTokens          int64 `json:"completion_tokens,omitempty"`
	TotalTokens               int64 `json:"total_tokens,omitempty"`
	PromptCacheReadTokens     int64 `json:"prompt_cache_read_tokens,omitempty"`
	PromptCacheWriteTokens    int64 `json:"prompt_cache_write_tokens,omitempty"`
	CompletionReasoningTokens int64 `json:"completion_reasoning_tokens,omitempty"`
}

TokenUsage records replay-neutral provider token counts for a completed turn.

type Tool

type Tool struct {
	Name               string
	Description        string
	Parameters         map[string]any
	Permission         string
	VisibilitySubjects []string
	Subjects           func(json.RawMessage) ([]string, error)
	Call               func(context.Context, json.RawMessage, chan<- ChatResponse) (ToolResult, error)
	// Resumable calls interrupted by a restart run again instead of being reported interrupted.
	Resumable bool
	// TurnBound calls refuse to run in background work, which has left the turn they act on.
	TurnBound bool
}

Tool is a custom function tool supplied by an embedding application.

type ToolDiagnostic

type ToolDiagnostic struct {
	Phase     string          `json:"phase"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments,omitempty"`
	Result    string          `json:"result,omitempty"`
	Status    string          `json:"status,omitempty"`
	Action    json.RawMessage `json:"action,omitempty"`
}

ToolDiagnostic describes a tool runtime diagnostic emitted when diagnostics are enabled.

type ToolResult

type ToolResult struct {
	Output      string
	Attachments []Attachment
	// Data is an optional structured payload for code-mode bindings (e.g. BashResult).
	Data any
}

ToolResult is the output of a tool call, including optional model-visible attachments.

func TextToolResult

func TextToolResult(output string) ToolResult

TextToolResult returns a text-only tool result.

type TracelessJournal added in v0.1.14

type TracelessJournal struct {
	Parent Journal
}

TracelessJournal records steps in Parent but drops traces, so nested work (Task children, workflow workers) never replaces its root turn's progress.

func (TracelessJournal) Load added in v0.1.14

func (j TracelessJournal) Load(ctx context.Context, key string) (value json.RawMessage, found bool, err error)

Load forwards to Parent.

func (TracelessJournal) Save added in v0.1.14

func (j TracelessJournal) Save(ctx context.Context, key string, value json.RawMessage) error

Save forwards to Parent.

func (TracelessJournal) SaveTrace added in v0.1.14

SaveTrace drops display-only progress.

type TurnPhase added in v0.0.50

type TurnPhase int

TurnPhase is whether the live turn is still in the tool loop.

const (
	// TurnPhaseUnclassified means no provider response has classified the turn yet.
	TurnPhaseUnclassified TurnPhase = iota
	// TurnPhaseToolLoop means the last provider response requested tools.
	TurnPhaseToolLoop
	// TurnPhaseFinalAnswer means the last provider response had no tools.
	TurnPhaseFinalAnswer
)

Directories

Path Synopsis
Package codemode runs Starlark scripts that call outbound MCP tools.
Package codemode runs Starlark scripts that call outbound MCP tools.
Package mcpclient connects to outbound MCP servers for RocketCode code mode.
Package mcpclient connects to outbound MCP servers for RocketCode code mode.

Jump to

Keyboard shortcuts

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