Documentation
¶
Overview ¶
Package harness provides the reusable agent runtime.
Index ¶
- Constants
- Variables
- func BashPermissionSubjects(command string) []string
- func CallKey(turnID, callID string) string
- func CheckNestedPermission(ctx context.Context, toolName, permission, subject string, args map[string]any) error
- func CheckNestedToolCall(ctx context.Context, toolName string, tool *looperTool, args json.RawMessage) error
- func CodeModeOnlyHostTool(name string) bool
- func CompactionCheckpointText(compaction *responses.ResponseCompactionItemParam) string
- func EasyRoot(shell *CustomShell, name string) (root *os.Root, rel string, err error)
- func InterpolatePermissions(agent *Agent, env []string)
- func ParseModelRef(ref string) (model, effort string)
- func RemapReplayAttribution(ranges []ReplayAttribution, boundaries []int)
- func ReplayInputFromParams(items []responses.ResponseInputItemUnionParam) ([]json.RawMessage, error)
- func ReplayInputRawKind(raw json.RawMessage) string
- func ReplayInputToParams(raw []json.RawMessage) ([]responses.ResponseInputItemUnionParam, error)
- func ReviewKey(turnID, callID string) string
- func ReviewTurn(callKey string) string
- func SweepRetainedResults(root *os.Root, dir string)
- func TaskResult(answer string) string
- func ToolCallKey(ctx context.Context) string
- type Agent
- type AgentLoadConfig
- type AgentLoadResult
- type AgentMaxRecursionError
- type AgentMode
- type AgentRoutine
- type Agents
- type Attachment
- type BackgroundJob
- type BackgroundJobs
- type BackgroundKind
- type BackgroundResult
- type BackgroundWork
- type BashResult
- type ChatResponse
- type ChildKey
- type ChildSessions
- type CodeModeCall
- type Config
- type ContinueMode
- type CustomShell
- type DefaultShellCommand
- type InertBackgroundJobs
- type InertChildSessions
- type InertJournal
- func (InertJournal) CodeModeCalls(context.Context, string) ([]json.RawMessage, error)
- func (InertJournal) Items(context.Context, string, TurnList) ([]json.RawMessage, error)
- func (InertJournal) Load(context.Context, string) (value json.RawMessage, found bool, err error)
- func (InertJournal) Save(context.Context, string, json.RawMessage) error
- func (InertJournal) SaveCodeModeCall(context.Context, string, string, json.RawMessage) error
- func (InertJournal) SaveTrace(context.Context, string, []json.RawMessage) error
- func (InertJournal) SaveTurn(context.Context, string, json.RawMessage, []TurnItems) error
- type InertSteerDrain
- type Journal
- type Looper
- type ModelResolver
- type ObservabilityConfig
- type PermissionAction
- type PermissionBucket
- type PermissionReview
- type PermissionRule
- type PermissionSet
- func (ps *PermissionSet) Allow(permission, pattern string) error
- func (ps *PermissionSet) Deny(permission, pattern string) error
- func (ps PermissionSet) Enabled(permission, subject string) bool
- func (ps PermissionSet) Evaluate(permission, subject string) (action PermissionAction, matched bool)
- func (ps *PermissionSet) Set(permission, pattern string, action PermissionAction) error
- type PromptInput
- type PromptInputDirectSkill
- type PromptInputRole
- type PromptShellCommandExpansion
- type ProviderDiagnostic
- type ProviderOrigin
- type Providers
- type PublicProgress
- type PublicProgressKind
- type PublicProgressState
- type ReplayAttribution
- type ReplayDecodeError
- type Runtime
- type SessionEntry
- type Skill
- type SkillLoadResult
- type Skills
- type SteerDrain
- type SubagentDiagnostic
- type SubagentWrite
- type TokenUsage
- type Tool
- type ToolDiagnostic
- type ToolResult
- type TracelessJournal
- func (TracelessJournal) CodeModeCalls(context.Context, string) ([]json.RawMessage, error)
- func (j TracelessJournal) Items(ctx context.Context, turnID string, list TurnList) ([]json.RawMessage, error)
- func (j TracelessJournal) Load(ctx context.Context, key string) (value json.RawMessage, found bool, err error)
- func (j TracelessJournal) Save(ctx context.Context, key string, value json.RawMessage) error
- func (TracelessJournal) SaveCodeModeCall(context.Context, string, string, json.RawMessage) error
- func (TracelessJournal) SaveTrace(context.Context, string, []json.RawMessage) error
- func (j TracelessJournal) SaveTurn(ctx context.Context, turnID string, step json.RawMessage, lists []TurnItems) error
- type TurnItems
- type TurnList
- type TurnPhase
Constants ¶
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" )
const (
// AllowBackgroundSubject is the rocketclaw permission subject that allows Background Jobs.
AllowBackgroundSubject = "allow_background"
)
const (
// MaxCodeModeCalls bounds an Execute call's records, which History loads with the turn.
MaxCodeModeCalls = 200
)
const ( // TurnBoundRefused is what a turn-bound tool, named by its format argument, returns in background work. TurnBoundRefused = "" /* 288-byte string literal not displayed */ )
Model-facing background text follows OpenCode packages/core/src/tool/plugin/shell.ts (BACKGROUND_INSTRUCTION, backgroundResult, Input.background) and subagent.ts (backgroundResult, Input.background), adapted to Background Jobs and Completion Notes.
Variables ¶
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.
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 ¶
BashPermissionSubjects returns independently authorized shell operations. Unparseable syntax and unresolved executable names deny the entire script.
func CheckNestedPermission ¶
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 ¶
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 ¶
CodeModeOnlyHostTool reports whether name is a sandbox host tool available only inside execute (not as a top-level model tool).
func CompactionCheckpointText ¶
func CompactionCheckpointText(compaction *responses.ResponseCompactionItemParam) string
CompactionCheckpointText returns portable text for compaction replay that cannot be rehydrated natively.
func EasyRoot ¶ added in v0.2.20
EasyRoot opens the folder of an easy agent's shell that holds name, a host path or one relative to the shell's folder, and returns name relative to it.
func InterpolatePermissions ¶
InterpolatePermissions resolves ${ROCKETCLAW_*} references in agent's permission rules against env, a list of KEY=VALUE entries: a rule whose variable is absent or empty is dropped, except that a deny rule matches as if the variable were *.
func ParseModelRef ¶ added in v0.2.20
ParseModelRef splits a "model#effort" reference into its trimmed model and its effort, empty without "#".
func RemapReplayAttribution ¶
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 ReplayInputRawKind ¶
func ReplayInputRawKind(raw json.RawMessage) string
ReplayInputRawKind returns the stored item's type, or an empty string on decode failure.
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 ¶
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 ReviewTurn ¶
ReviewTurn is the turn under which the automatic permission review of the call keyed callKey (see ToolCallKey) saves its answer in the review's Delegation History. It has no slash, so the review's retained results never nest under another turn's.
func SweepRetainedResults ¶
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 TaskResult ¶
TaskResult is the task call result of answer, a subagent session's answer.
func ToolCallKey ¶
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
CustomShell CustomShell
Space string
Prompt string
Location string
Permission PermissionSet
OutputSchema map[string]any
Frontmatter map[string]any
FrontmatterNode *yaml.Node
FileMode fs.FileMode
Mode AgentMode
// Easy-only fields, compiled from an easy file's sections; advanced agents leave them zero.
// Model entries keep their text as written, provider prefix and #effort included.
WorkingDirectory string
Commands map[string]string
SecretsARN []string
Subagents []string
ApproverModel string
ApproverPrompt string
Routines []AgentRoutine
TagGroups [][]string
// DelegatedFrom lists the agents that may write into this agent's sessions; nil means any agent.
DelegatedFrom []string
// NetworkTargets lists the emulated shell's allowed network targets; nil means public addresses only.
NetworkTargets []string
// Tools, set by the embedder for an easy agent's subagent session, names the only tools it has: tool names
// and MCP server.tool subjects. Nil means every tool.
Tools []string
}
Agent contains a single preloaded markdown agent definition.
type AgentLoadConfig ¶ added in v0.2.20
type AgentLoadConfig struct {
// MCPToolGroups maps every configured MCP server to its tool groups (read, write) of tool-name patterns.
MCPToolGroups map[string]map[string][]string
// Providers names every configured model provider, openai included.
Providers []string
// Skills is the skills root; easy skills entries name folders in it.
Skills fs.FS
}
AgentLoadConfig is the runtime configuration easy agents are checked and compiled against.
type AgentLoadResult ¶
AgentLoadResult contains loaded agents and any non-fatal load errors.
func LoadAgents ¶
func LoadAgents(fsys fs.FS, cfg AgentLoadConfig) AgentLoadResult
LoadAgents loads top-level Markdown agents and immediate shadows in each matching directory. Shadow names retain their parent path. Easy agents are checked and compiled against cfg.
type AgentMaxRecursionError ¶
AgentMaxRecursionError reports invalid maxRecursion frontmatter.
func (*AgentMaxRecursionError) Error ¶
func (e *AgentMaxRecursionError) Error() string
func (*AgentMaxRecursionError) Unwrap ¶
func (e *AgentMaxRecursionError) Unwrap() error
type AgentRoutine ¶ added in v0.2.20
AgentRoutine is one easy-agent routine: a schedule and the instruction it sends, empty for a bare entry.
type Agents ¶
Agents contains all discovered agents keyed by name.
func (Agents) PrimaryNames ¶
PrimaryNames returns sorted top-level agents, excluding comparison shadows.
func (Agents) ShadowNames ¶
ShadowNames returns sorted immediate shadow names for a top-level parent.
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.
type BackgroundJob ¶
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
// 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 ¶
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)
}
BackgroundJobs runs the execute and task calls of agents allowed to use background mode.
type BackgroundKind ¶
type BackgroundKind string
BackgroundKind is the tool that started a Background Job.
const ( BackgroundKindExecute BackgroundKind = "execute" BackgroundKindTask BackgroundKind = "task" )
Background Job kinds.
type BackgroundResult ¶
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 ¶
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 BashResult ¶
BashResult is the result of running a workspace bash command.
func (BashResult) String ¶
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 ChildKey ¶
type ChildKey struct {
Path, Parent, Turn, Call string
}
ChildKey names a child session by Path, its key under the embedder's session, which an empty Path names. A new child starts under the child at key Parent, by call Call of turn Turn there.
type ChildSessions ¶
type ChildSessions interface {
AppendChildEntry(ctx context.Context, key ChildKey, entry *SessionEntry) error
// WriteSubagent delivers write to its subagent session, which it starts when new, and reports
// whether write joined the session's running turn. A replayed write delivers nothing again.
WriteSubagent(ctx context.Context, write *SubagentWrite) (steered bool, err error)
// AwaitSubagent waits for the turn of the subagent session at key that runs the write of the task
// call callKey, and returns its answer and the agent type and model it ended as.
AwaitSubagent(ctx context.Context, key, callKey string) (string, ReplayAttribution, error)
}
ChildSessions stores finished permission review turns, and runs Task subagents as sessions of the embedder, on the turn runner its other sessions use.
type CodeModeCall ¶
type CodeModeCall struct {
Type string `json:"type"`
ParentCallID string `json:"parent_call_id"`
Key string `json:"key,omitempty"`
Name string `json:"name,omitempty"`
Arguments string `json:"arguments,omitempty"`
Status codeModeCallStatus `json:"status,omitempty"`
Summary string `json:"summary,omitempty"`
Outcome permissionReviewOutcome `json:"outcome,omitempty"`
Reason string `json:"reason,omitempty"`
}
CodeModeCall is a call an Execute script made, as saved on its own while its turn runs, then in the turn trace, and shown in history. It keeps no output beyond Summary. Key is the call's ToolCallKey; Outcome and Reason are set only when the approver ran. A review record, with no Name, holds the approver's decision on the whole script under its Execute call's key.
func CodeModeCallsFromTrace ¶
func CodeModeCallsFromTrace(traces []json.RawMessage) []CodeModeCall
CodeModeCallsFromTrace decodes a turn trace's Code Mode records in trace order.
func (*CodeModeCall) String ¶
func (r *CodeModeCall) String() string
String renders the record on one line for an agent reading a session: the call, its status and output summary, and the approver's decision when it ran. A whole-script review has only the decision.
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 permission reviewers.
ChildContext []SessionEntry
// OriginHeader is the embedder's trusted statement of who started the turn, which permission
// reviewers read ahead of the untrusted transcript.
OriginHeader string
// 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 shell frontmatter overrides it for that agent.
ShellCommand shellCommander
// Sandbox runs emulated shells. The zero value refuses them.
Sandbox sandbox.Runtime
MCPServers map[string]mcpclient.ServerConfig
MCPWorkspace string
}
Config contains runtime settings supplied by the embedding application.
type ContinueMode ¶
type ContinueMode string
ContinueMode is how a task continue's prompt reaches a subagent session, as rocketclaw_sessions_write's mode.
const ( // ContinueStop stops the subagent's running turn and runs the prompt next, ahead of its queued prompts. ContinueStop ContinueMode = "stop" // ContinueSteer joins the running turn at its next step, or else queues the prompt. ContinueSteer ContinueMode = "steer" // ContinueEnqueue runs the prompt as a new turn after the subagent's queued prompts. ContinueEnqueue ContinueMode = "enqueue" )
Task continue modes.
type CustomShell ¶
type CustomShell struct {
// Path is a program that runs as <Path> <command>.
Path string
// Emulated means real Bash in the sandbox (shell: emulated, and every easy agent). The embedder sets Dir
// for each turn; until it does, the agent's shell commands do not run.
Emulated bool
// Dir is the emulated shell's writable folder, shown at its host path. A bash call runs there, or in its
// workdir taken from there, and skips the workspace path check: the sandbox does the confining.
Dir string
// ReadOnly are folders, none inside another, the emulated shell shows read-only at their host paths besides
// Dir. An easy agent's file tools see Dir and these, as its shell does.
ReadOnly []string
// Commands are the emulated shell's host commands: a name and the command line host bash runs, with the
// guest's arguments appended.
Commands map[string]string
// NetworkTargets limit the emulated shell's curl as they limit webfetch; nil means public addresses only.
NetworkTargets []string
// Secrets are environment variables only host programs get: the emulated shell's host commands, and an
// easy agent's prompt and skill expansion in host bash.
Secrets map[string]string
}
CustomShell is what runs an agent's shell commands instead of host bash, from the agent's shell frontmatter: a program, or the emulated shell (internal/rocketclaw/sandbox).
type DefaultShellCommand ¶
type DefaultShellCommand struct{}
DefaultShellCommand uses Bash to match the permission parser's grammar.
type InertBackgroundJobs ¶
type InertBackgroundJobs struct{}
InertBackgroundJobs offers no background mode and runs work inline.
func (InertBackgroundJobs) Enabled ¶
func (InertBackgroundJobs) Enabled() bool
Enabled reports false.
func (InertBackgroundJobs) Run ¶
func (InertBackgroundJobs) Run(ctx context.Context, _ *BackgroundJob, work BackgroundWork) (BackgroundResult, error)
Run runs work inline; it never moves.
type InertChildSessions ¶
type InertChildSessions struct{}
InertChildSessions discards child session entries and runs no subagents.
func (InertChildSessions) AppendChildEntry ¶
func (InertChildSessions) AppendChildEntry(context.Context, ChildKey, *SessionEntry) error
AppendChildEntry discards one child session entry.
func (InertChildSessions) AwaitSubagent ¶
func (InertChildSessions) AwaitSubagent(context.Context, string, string) (string, ReplayAttribution, error)
AwaitSubagent refuses to run a subagent.
func (InertChildSessions) WriteSubagent ¶
func (InertChildSessions) WriteSubagent(context.Context, *SubagentWrite) (bool, error)
WriteSubagent refuses to run a subagent.
type InertJournal ¶
type InertJournal struct{}
InertJournal records nothing and never finds a recorded step.
func (InertJournal) CodeModeCalls ¶
func (InertJournal) CodeModeCalls(context.Context, string) ([]json.RawMessage, error)
CodeModeCalls never finds a Code Mode record.
func (InertJournal) Items ¶
func (InertJournal) Items(context.Context, string, TurnList) ([]json.RawMessage, error)
Items never finds a turn's item.
func (InertJournal) Load ¶
func (InertJournal) Load(context.Context, string) (value json.RawMessage, found bool, err error)
Load never finds a recorded step.
func (InertJournal) Save ¶
func (InertJournal) Save(context.Context, string, json.RawMessage) error
Save discards one step.
func (InertJournal) SaveCodeModeCall ¶
func (InertJournal) SaveCodeModeCall(context.Context, string, string, json.RawMessage) error
SaveCodeModeCall discards a Code Mode record.
func (InertJournal) SaveTrace ¶
func (InertJournal) SaveTrace(context.Context, string, []json.RawMessage) error
SaveTrace discards display-only progress.
func (InertJournal) SaveTurn ¶
func (InertJournal) SaveTurn(context.Context, string, json.RawMessage, []TurnItems) error
SaveTurn discards a turn's step.
type InertSteerDrain ¶
type InertSteerDrain struct{}
InertSteerDrain never supplies additional input.
func (InertSteerDrain) Drain ¶
func (InertSteerDrain) Drain(context.Context, string, TurnPhase, []string) ([]PromptInput, error)
Drain does not wait or supply input.
type Journal ¶
type Journal interface {
Load(ctx context.Context, key string) (json.RawMessage, bool, error)
Save(ctx context.Context, key string, value json.RawMessage) error
// SaveTurn saves turn turnID's step under its key and, in the same write, each of lists: its
// items replace the list's saved items from index From on. A running turn writes each item once.
SaveTurn(ctx context.Context, turnID string, step json.RawMessage, lists []TurnItems) error
// Items returns the items SaveTurn saved in turn turnID's list, in order.
Items(ctx context.Context, turnID string, list TurnList) ([]json.RawMessage, error)
// SaveTrace persists display-only public progress for the root turn.
SaveTrace(ctx context.Context, turnID string, trace []json.RawMessage) error
// SaveCodeModeCall persists one Code Mode record of the root turn under its key, apart from the
// trace, so a record is written when its call starts and finishes and never with other progress.
SaveCodeModeCall(ctx context.Context, turnID, key string, record json.RawMessage) error
// CodeModeCalls returns the root turn's saved Code Mode records in the order they were first saved.
CodeModeCalls(ctx context.Context, turnID string) ([]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 sessionWriter, interrupts <-chan os.Signal) error
}
Looper processes prompt input streams with a configured runtime.
type ModelResolver ¶
type ModelResolver interface {
Resolve(model string) (*openai.Client, ProviderOrigin, error)
}
ModelResolver selects an SDK client and API model for a model selector.
type ObservabilityConfig ¶
type ObservabilityConfig struct {
Enabled bool
Tracer trace.Tracer
TraceConfig instrumentation.TraceConfig
}
ObservabilityConfig controls OpenInference-compatible tracing for the harness.
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 PermissionReview ¶
type PermissionReview struct {
Outcome permissionReviewOutcome
Rationale string
}
PermissionReview is the decision a saved permission review reached.
func (PermissionReview) CodeModeCall ¶
func (r PermissionReview) CodeModeCall(e *SessionEntry) (CodeModeCall, bool)
CodeModeCall returns the review as an Execute script's calls are recorded: the whole-script decision with an empty Name, or a call the script made, with clipped arguments. The action comes from the planned action that ends the review's prompt, as written by permissionReviewPrompt; false means the prompt has none. Only the prompt's tail is decoded: the transcript before it can be hundreds of kilobytes.
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
Sudo bool
Easy bool
// contains filtered or unexported fields
}
PermissionSet contains all permission buckets configured for an agent. Sudo makes every subject no rule matches require automatic approval. Easy marks an easy agent's compiled rules: features that need an allow also count automatic approval as on, as under Sudo.
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) Enabled ¶
func (ps PermissionSet) Enabled(permission, subject string) bool
Enabled reports whether a feature that needs an exact allow is on for subject: it evaluates to allow, or to automatic approval under Sudo or for an easy agent.
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, or PermissionAuto under Sudo, except that rocketclaw.load_agents_md and, without Sudo, rocketclaw.code_mode_approve default to PermissionAllow. Only exact rules match rocketclaw subjects.
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
// TurnID, when set, is the turn's stable identity and journal key across restarts.
TurnID string
// Role defaults to PromptInputRoleUser when empty.
Role PromptInputRole
// Texts are the prompt's text pieces. The prompt text is their concatenation;
// each piece carries its own separators. More than one piece is sent as
// separate text parts, which a provider's prompt cache marker can target.
Texts []string
// ExpandShellCommands enables !`command` expansion for this trusted input,
// even when input expansion is disabled for the runtime as a whole.
ExpandShellCommands bool `json:",omitempty"`
// Header is the exact generated prefix of the first piece, saved only in local replay.
Header string
Attachments []Attachment
DirectSkill *PromptInputDirectSkill
// Agent, on a steer drained into a running subagent turn, is the agent type that turn runs as from
// its next step on.
Agent string
// 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 ¶
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 covers the agent prompt of every session, a Task subagent's included, since a
// subagent runs as a session of the embedder (ChildSessions).
PrimaryPrompts bool
// SubagentPrompts covers the prompts of permission review agents.
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 ¶
type ProviderOrigin struct {
Provider string
Model string
CompactThreshold int64
// PromptCacheMarkersRelativePosition, when set, is the negative index of the text
// piece in the last request message that carries an Anthropic cache_control marker.
PromptCacheMarkersRelativePosition *int
}
ProviderOrigin identifies the provider and API model selected by a resolver.
type PublicProgress ¶
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 key of the subagent a task call runs or continues under the history that
// holds the call, 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
type Runtime = looper
Runtime is the concrete harness loop runtime returned by NewWithModelResolver.
func NewWithModelResolver ¶
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 ¶
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) RestrictTools ¶
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 ¶
func (e *SessionEntry) AttributionAt(index int) ReplayAttribution
AttributionAt returns the execution that produced a replay item.
func (*SessionEntry) PermissionReviewDecision ¶
func (e *SessionEntry) PermissionReviewDecision() PermissionReview
PermissionReviewDecision returns the outcome and rationale of a saved review's last final answer that is an allow or deny decision, or the zero value. It never decodes the review prompt; CodeModeCall reads the action.
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 ¶
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 ¶
Available returns skills allowed for agent, sorted by name. Skills requiring permission review are not available for direct invocation or discovery.
type SteerDrain ¶
type SteerDrain interface {
Drain(ctx context.Context, responseID string, phase TurnPhase, applied []string) ([]PromptInput, error)
}
SteerDrain collects waiting steers and Completion Notes after a tool batch, or when a no-tool answer would otherwise end the turn. Each drain follows one provider response, named by responseID; a turn resumed after a restart drains its journaled response again under the same ID. Applied identities include replayed and compacted inputs. A final drain may wait for new input; errors must prevent accepting the pending final answer.
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 SubagentWrite ¶
type SubagentWrite struct {
// Key is the session's child key.
Key ChildKey
// CallKey is the task call's tool call key, which identifies the write.
CallKey string
// Agent is the subagent type that runs Prompt, and Delegator the agent that wrote it.
Agent, Delegator, Prompt string
// Mode is a continue's mode; empty for a new subagent.
Mode ContinueMode
// Model, an entry of Agent.Subagents as written, and Tools (Agent.Tools) are what an easy agent's
// subagent session, which runs that agent, runs with; an agent type's leaves them empty.
Model string
Tools []string
}
SubagentWrite is a task call's prompt to a subagent session.
type TokenUsage ¶
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 ¶
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) CodeModeCalls ¶
func (TracelessJournal) CodeModeCalls(context.Context, string) ([]json.RawMessage, error)
CodeModeCalls finds no Code Mode record, as SaveCodeModeCall keeps none.
func (TracelessJournal) Items ¶
func (j TracelessJournal) Items(ctx context.Context, turnID string, list TurnList) ([]json.RawMessage, error)
Items forwards to Parent.
func (TracelessJournal) Load ¶
func (j TracelessJournal) Load(ctx context.Context, key string) (value json.RawMessage, found bool, err error)
Load forwards to Parent.
func (TracelessJournal) Save ¶
func (j TracelessJournal) Save(ctx context.Context, key string, value json.RawMessage) error
Save forwards to Parent.
func (TracelessJournal) SaveCodeModeCall ¶
func (TracelessJournal) SaveCodeModeCall(context.Context, string, string, json.RawMessage) error
SaveCodeModeCall drops a Code Mode record, which is display-only like the trace.
func (TracelessJournal) SaveTrace ¶
func (TracelessJournal) SaveTrace(context.Context, string, []json.RawMessage) error
SaveTrace drops display-only progress.
func (TracelessJournal) SaveTurn ¶
func (j TracelessJournal) SaveTurn(ctx context.Context, turnID string, step json.RawMessage, lists []TurnItems) error
SaveTurn forwards to Parent.
type TurnItems ¶
type TurnItems struct {
List TurnList
From int
Items []json.RawMessage
}
TurnItems are the items of a turn's list from index From on.
type TurnList ¶
type TurnList string
TurnList names one of the item lists a turn's step is saved with.
const ( // TurnReplayInput lists the turn record's replay items. TurnReplayInput TurnList = "replay_input" // TurnOutputTrace lists the turn record's output trace items. TurnOutputTrace TurnList = "output_trace" // TurnTrace lists the turn's public progress as of its step. TurnTrace TurnList = "trace" )
type TurnPhase ¶
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 )
Source Files
¶
- active_turn.go
- agents.go
- attachments.go
- background.go
- bash_starlark.go
- checkpoint.go
- custom_tools.go
- easy.go
- easy_files.go
- emulated.go
- emulated_curl.go
- execute_results.go
- filesystem.go
- guardian.go
- looper.go
- mcp_tools.go
- models.go
- observability.go
- permission.go
- permission_gate.go
- permission_review.go
- prompts.go
- provider_replay.go
- public_progress.go
- replay.go
- responses_websocket.go
- rocketcode.go
- shell.go
- skills.go
- tasks.go
- tools.go
- webfetch.go