Documentation
¶
Overview ¶
Package harness orchestrates conversational and tool-augmented agent execution over a compiled github.com/masterkeysrd/loom/graph.Graph with durable SQLite-backed conversation state and permission checkpointing.
Strict Dependency Injection and Decoupling ¶
The harness is a pure workflow execution engine with zero coupling to workspace configuration or model provider routing. Higher-level orchestration layers (such as internal/daemon/session) resolve the active *github.com/masterkeysrd/loom/llm.Model, *github.com/masterkeysrd/tasksmith/internal/daemon/tools.Container, and rendered system prompt, injecting them directly into New via Config:
- Config.DB: Active SQLite connection used to initialize github.com/masterkeysrd/loom/checkpoint/sqlite.Checkpointer.
- [Config.Model]: Resolved *github.com/masterkeysrd/loom/llm.Model invoked by AgentNode.
- [Config.Tools]: Initialized *github.com/masterkeysrd/tasksmith/internal/daemon/tools.Container providing tool definitions, two-phase Prepare/Execute, and the permission github.com/masterkeysrd/tasksmith/internal/daemon/tools.Gate.
- [Config.SystemPrompt]: Optional rendered system instructions prepended transiently to each LLM call.
- Config.Logger: Structured github.com/masterkeysrd/tasksmith/internal/core/log.Interface scoped to the "harness" component.
Cyclic Agent-Tools Workflow Graph ¶
The harness compiles a cyclic workflow graph:
START -> agent -> (conditional: has tool calls?) -> tools -> agent
-> (otherwise) -> END
Conversation history is stored directly as a github.com/masterkeysrd/loom/message.MessageList on State.Messages, alongside any active State.PendingPermissions and State.PermissionDecisions.
Two-Phase Tool Execution and Permission Interrupts ¶
When AgentNode produces an *github.com/masterkeysrd/loom/message.Assistant message containing tool calls, the graph transitions to ToolsNode:
- Pre-flight Prepare & Evaluate: Every tool call is validated via github.com/masterkeysrd/tasksmith/internal/daemon/tools.Container.Prepare and evaluated against the permission gate via github.com/masterkeysrd/tasksmith/internal/daemon/permissions.SessionManager.Evaluate.
- Interrupt on AccessAsk: If one or more tool calls require user approval (github.com/masterkeysrd/tasksmith/internal/daemon/tools.AccessAsk), ToolsNode executes allowed calls and records denied calls before interrupting. It persists the pending github.com/masterkeysrd/tasksmith/internal/daemon/tools.PermissionRequest slice in State.PendingPermissions and returns a github.com/masterkeysrd/loom/graph.InterruptUpdate command. Harness.Stream yields an Interrupted notification carrying the pending permission requests.
- Strict All-or-Nothing Resume: Harness.Stream validates that every request in State.PendingPermissions has a corresponding decision before invoking the graph. If any pending request is missing a decision, Harness.Stream yields ErrPendingPermissionsUnresolved immediately without calling the graph.
- Canceled by New User Message: If the caller sends a new user message via Harness.Stream while a thread is paused at ToolsNode, ToolsNode automatically synthesizes canceled *github.com/masterkeysrd/loom/message.Tool error responses for all unfulfilled tool calls, inserts them immediately before the new user message to preserve strict LLM message ordering, clears State.PendingPermissions, and transitions directly to AgentNode.
System Prompt Isolation Invariant ¶
When [Config.SystemPrompt] is non-empty, AgentNode prepends it only to the transient message slice sent to github.com/masterkeysrd/loom/llm.Model.Invoke and never stores it inside checkpointed State.Messages.
Index ¶
- Constants
- Variables
- func AttachmentsOf(msg message.Message) []api.Attachment
- func CompactionTriggerTokens(limits models.Limits) (reserveTokens, triggerTokens int)
- func NewSystemReminder(items ...ReminderItem) *message.User
- func PermissionReviewOf(msg message.Message) *api.PermissionReview
- func SetAttachments(msg *message.User, atts []api.Attachment)
- func SetPermissionReview(msg *message.Tool, review *api.PermissionReview)
- func SetUserIntent(msg *message.User, intent string)
- func SystemKindOf(msg message.Message) string
- func UnsupportedMediaReason(mod media.Modality, label, modelID string) string
- func UserIntentOf(msg message.Message) string
- type AgentNode
- type AgentNodeConfig
- type AttachmentResolver
- func (r *AttachmentResolver) CheckFileAccess(ctx context.Context, mention FileMention) error
- func (r *AttachmentResolver) ResolveUserMessage(ctx context.Context, msg message.Message, state State) (State, *message.User, []RuleLoaded)
- func (r *AttachmentResolver) Validate(ctx context.Context, atts []api.Attachment) ([]api.Attachment, error)
- type AttachmentResolverConfig
- type BashRunner
- type CommandCompleted
- type CommandNode
- type CommandNodeConfig
- type CompactionCompleted
- type CompactionNode
- type CompactionNodeConfig
- type Completed
- type Config
- type DirectoryReminder
- type FileMention
- type FileReminder
- type GraphConfig
- type Harness
- type InboxNode
- type InboxNodeConfig
- type Input
- type Interrupted
- type MCPResourceReminder
- type MediaReminder
- type MessageUpdateOptions
- type ModeTransitionReminder
- type Node
- type NodeOptions
- type Queue
- type ReminderItem
- type RuleLoaded
- type RuleMatcher
- type RuleReminder
- type RuleSuggestion
- type RuleSuggestionsReminder
- type SkillReminder
- type State
- func (s State) ActiveModalities() []media.Modality
- func (s State) ActiveToolCalls() (int, *message.Assistant, []*message.ToolCall, bool)
- func (s State) AppendMessage(msg message.Message, opts MessageUpdateOptions) State
- func (s State) AppendMessages(msgs message.MessageList, opts MessageUpdateOptions) State
- func (s State) ApplyCompaction(static StaticContext, limits models.Limits) State
- func (s State) Copy() State
- func (s State) DeduplicateToolBlocks(msg message.Message) (message.Message, []string)
- func (s State) HasLeadingCompact() bool
- func (s State) HasLoadedRule(name string) bool
- func (s State) HasLoadedSkill(name string) bool
- func (s State) HasPendingToolCalls() bool
- func (s State) HasSuggestedRule(name string) bool
- func (s State) IsAutoCompacted() bool
- func (s State) LastUserIntentText() string
- func (s State) LastUserMessageID() string
- func (s State) PrependMessage(msg message.Message, opts MessageUpdateOptions) State
- func (s State) RecordLoadedRules(names ...string) State
- func (s State) RecordLoadedSkills(names ...string) State
- func (s State) RecordLoadedTools(names ...string) State
- func (s State) RecordSuggestedRules(names ...string) State
- func (s State) ShouldAutoCompact() bool
- func (s State) ShouldWakeAgent() bool
- type StaticContext
- type SystemReminder
- type ToolsNode
- type ToolsNodeConfig
Constants ¶
const ( MetaSystemKind = "tasksmith.system.kind" MetaCompactionTrigger = "tasksmith.compaction.trigger" MetaCompactionFocus = "tasksmith.compaction.focus" MetaCompactionRequests = "tasksmith.compaction.requests" // MetaRuleNames carries the list of rule names surfaced in a system reminder // (either auto-loaded or suggested) so consumers can correlate reminders with // the rules they reference. MetaRuleNames = "tasksmith.rule.names" MetaAttachments = "tasksmith.attachments" // MetaPermissionReview carries the *api.PermissionReview receipt attached // to a tool result message when the auto-mode permission reviewer // approved the card instead of interrupting the human. MetaPermissionReview = "tasksmith.permission_review" // MetaUserIntent records the originating human prompt on a user message // whose body was expanded from a slash command or synthesized for an // autonomous subagent, so permission reviews evaluate against what the // human actually asked for. MetaUserIntent = "tasksmith.user_intent" )
const ( SystemKindCommand = "command" SystemKindTask = "task" SystemKindCompaction = "compaction" SystemKindSubagent = "subagent" // SystemKindReminder marks a synthetic user message that carries an active or // suggested workspace rule inside <system_reminders>. SystemKindReminder = "reminder" )
Variables ¶
var ( ErrInvalidConfig = errors.New("harness: invalid configuration") ErrEmptyThreadID = errors.New("harness: thread ID must not be empty") ErrNilMessage = errors.New("harness: input message must not be nil") ErrNoPendingPermissions = errors.New("harness: no pending permissions for thread") ErrPendingPermissionsUnresolved = errors.New("harness: all pending permissions must be resolved before resuming") ErrNoPendingQuestions = errors.New("harness: no pending questions for thread") ErrPendingQuestionsUnresolved = errors.New("harness: all pending questions must be resolved before resuming") ErrNoPendingPlanReviews = errors.New("harness: no pending plan reviews for thread") ErrPendingPlanReviewsUnresolved = errors.New("harness: all pending plan reviews must be resolved before resuming") )
Sentinel errors returned by the harness package.
Functions ¶
func AttachmentsOf ¶
func AttachmentsOf(msg message.Message) []api.Attachment
AttachmentsOf retrieves structured api.Attachment references from a message, handling both in-memory []api.Attachment and JSON-deserialized []any (from SQLite journal/timeline).
func CompactionTriggerTokens ¶
CompactionTriggerTokens calculates the safety reserve and auto-compaction trigger threshold per compaction.md Section 2.4.
func NewSystemReminder ¶
func NewSystemReminder(items ...ReminderItem) *message.User
NewSystemReminder builds a synthetic reminder *message.User from items, returning nil when no items produce output.
func PermissionReviewOf ¶
func PermissionReviewOf(msg message.Message) *api.PermissionReview
PermissionReviewOf retrieves the reviewer receipt from a message, handling both the in-memory *api.PermissionReview and the JSON-deserialized map[string]any form restored from the SQLite journal.
func SetAttachments ¶
func SetAttachments(msg *message.User, atts []api.Attachment)
SetAttachments attaches structured api.Attachment references to a user message.
func SetPermissionReview ¶
func SetPermissionReview(msg *message.Tool, review *api.PermissionReview)
SetPermissionReview attaches the reviewer receipt to a tool result message. Any pre-existing value (e.g. a forged key echoed through structured tool content) is replaced, so a tool can never fabricate its own approval.
func SetUserIntent ¶
SetUserIntent stamps the originating human intent string on msg. Passing an empty or whitespace-only string clears any stored override.
func SystemKindOf ¶
SystemKindOf returns the "tasksmith.system.kind" metadata value on msg, or "" if unset.
func UnsupportedMediaReason ¶
UnsupportedMediaReason returns the standard omission reason for an unsupported media modality.
func UserIntentOf ¶
UserIntentOf returns the MetaUserIntent string recorded on msg, or "".
Types ¶
type AgentNode ¶
type AgentNode struct {
// contains filtered or unexported fields
}
AgentNode is the primary reasoning and completion node in the harness workflow graph. It implements github.com/masterkeysrd/loom/graph.Node.
func NewAgentNode ¶
func NewAgentNode(cfg AgentNodeConfig) *AgentNode
NewAgentNode constructs a new AgentNode bound to the resolved LLM model, tool container, system prompt, limits, static context, and structured logger.
func (*AgentNode) Configure ¶
func (n *AgentNode) Configure(opts NodeOptions)
func (*AgentNode) Execute ¶
Execute binds all registered tool definitions to the LLM model, invokes it with the transient system prompt prepended to the conversation state, emits the resulting assistant message to the stream, and appends it to State.Messages.
type AgentNodeConfig ¶
type AgentNodeConfig struct {
Permissions permissions.SessionManager
Logger log.Interface
}
type AttachmentResolver ¶
type AttachmentResolver struct {
// contains filtered or unexported fields
}
AttachmentResolver validates and resolves all structured user-message attachments (files, directories, rules, skills, MCP resources) alongside conditional rule suggestions into a single <system_reminders> block.
func NewAttachmentResolver ¶
func NewAttachmentResolver(cfg AttachmentResolverConfig) (*AttachmentResolver, error)
NewAttachmentResolver validates cfg and constructs a unified AttachmentResolver.
func (*AttachmentResolver) CheckFileAccess ¶
func (r *AttachmentResolver) CheckFileAccess(ctx context.Context, mention FileMention) error
CheckFileAccess verifies that mention stays within the sandbox root (including symlink resolution), is not sensitive or secret, and is permitted by explicit permission rules and policy ceilings.
func (*AttachmentResolver) ResolveUserMessage ¶
func (r *AttachmentResolver) ResolveUserMessage(ctx context.Context, msg message.Message, state State) (State, *message.User, []RuleLoaded)
ResolveUserMessage resolves all structured attachments and rule triggers on a genuine user message into a single <system_reminders> message, returning the updated state, the synthesized reminder (or nil when nothing matched), and any newly loaded rules.
func (*AttachmentResolver) Validate ¶
func (r *AttachmentResolver) Validate(ctx context.Context, atts []api.Attachment) ([]api.Attachment, error)
Validate normalizes incoming request attachments and enforces sandbox file policies and MCP resource policies upfront at turn submission time.
type AttachmentResolverConfig ¶
type AttachmentResolverConfig struct {
AgentName string
Workspace *workspace.Workspace
Tools tools.Container
Rules *RuleMatcher
Std *std.Std
Sandbox sandbox.Sandbox
Permissions permissions.SessionManager
WorkDir string
MCPCaller func() tools.MCPCaller
MediaStore *media.Store
SupportsModality func(media.Modality) (modelID string, supported bool)
Logger log.Interface
}
AttachmentResolverConfig configures a unified AttachmentResolver for user messages.
func (AttachmentResolverConfig) Validate ¶
func (c AttachmentResolverConfig) Validate() error
Validate ensures all required dependencies are present.
type BashRunner ¶
type BashRunner interface {
Bash(ctx context.Context, req std.BashRequest) (*std.BashResult, error)
}
BashRunner executes a shell command inside the session environment. Satisfied by *std.Std.
type CommandCompleted ¶
type CommandCompleted struct {
ID string
api.CommandRecord
}
type CommandNode ¶
type CommandNode struct {
// contains filtered or unexported fields
}
CommandNode executes shell commands and injects their outputs into the conversation state.
func NewCommandNode ¶
func NewCommandNode(cfg CommandNodeConfig) *CommandNode
func (*CommandNode) Configure ¶
func (n *CommandNode) Configure(opts NodeOptions)
type CommandNodeConfig ¶
type CompactionCompleted ¶
type CompactionCompleted struct {
ID string
api.CompactedRecord
}
type CompactionNode ¶
type CompactionNode struct {
// contains filtered or unexported fields
}
CompactionNode performs in-chat conversation summarization and state replacement.
func NewCompactionNode ¶
func NewCompactionNode(cfg CompactionNodeConfig) *CompactionNode
NewCompactionNode constructs a new CompactionNode bound to dependencies.
func (*CompactionNode) Configure ¶
func (n *CompactionNode) Configure(opts NodeOptions)
type CompactionNodeConfig ¶
type Config ¶
type Config struct {
ID string
DB *sql.DB
Bash BashRunner
Spiller tools.Spiller
Permissions permissions.SessionManager
Queue Queue
Logger log.Interface
// Metrics receives tool call metrics. A nil recorder disables them.
Metrics metrics.Recorder
// Reviewer, when non-nil, evaluates risky auto-mode permission cards
// once before the graph interrupts for a human decision.
Reviewer permreview.Reviewer
}
Config holds the mandatory dependencies required to construct a Harness.
type DirectoryReminder ¶
DirectoryReminder renders a <context_directory> block for a directory listing.
func (DirectoryReminder) FormatReminder ¶
func (d DirectoryReminder) FormatReminder() string
FormatReminder formats the directory listing as a <context_directory> block tag.
type FileMention ¶
FileMention represents an explicit file or directory reference attached to a user prompt.
type FileReminder ¶
type FileReminder struct {
api.Attachment
Path string
Content string
}
FileReminder renders a <context_file> block for a file or line-slice attachment.
func (FileReminder) FormatReminder ¶
func (f FileReminder) FormatReminder() string
FormatReminder formats the file reminder as a <context_file> block tag.
type GraphConfig ¶
type GraphConfig struct {
Checkpointer graph.Checkpointer
Permissions permissions.SessionManager
Queue Queue
Bash BashRunner
Spiller tools.Spiller
Logger log.Interface
Metrics metrics.Recorder
Reviewer permreview.Reviewer
}
type Harness ¶
type Harness interface {
Stream(ctx context.Context, input Input) iter.Seq2[any, error]
LoadState(ctx context.Context) (State, error)
Configure(opts NodeOptions) error
// ForkFrom copies the latest checkpoint (all state channels) from
// parentThreadID into this harness's thread as its initial checkpoint,
// recording fork provenance in checkpoint metadata.
ForkFrom(ctx context.Context, parentThreadID string) error
}
Harness orchestrates stateful, multi-turn agent conversations and tool execution over a compiled Loom workflow graph.
type InboxNode ¶
type InboxNode struct {
// contains filtered or unexported fields
}
InboxNode drains messages from the session queue and injects them into the conversation state. It implements github.com/masterkeysrd/loom/graph.Node.
func NewInboxNode ¶
func NewInboxNode(cfg InboxNodeConfig) *InboxNode
NewInboxNode constructs a new InboxNode bound to the queue and logger.
func (*InboxNode) Configure ¶
func (n *InboxNode) Configure(opts NodeOptions)
type InboxNodeConfig ¶
type Input ¶
type Input struct {
Message message.Message
Decisions map[string]api.PermissionDecision
Answers map[string]api.QuestionResponse
PlanReviews map[string]api.PlanReviewDecision
Compact *api.CompactRequest
// ModelOverride, when non-empty, temporarily overrides the session's model
// for the duration of this turn (used by commands declaring spec.models).
// The session restores its original model when the turn exits.
ModelOverride string
}
Input represents the conversational input to Harness.Stream. It can provide either a new user message, resolved permission decisions and question answers, or a compaction request.
func (Input) HasInteractiveContent ¶
func (Input) HasResponses ¶
type Interrupted ¶
type Interrupted struct {
Permissions []api.PermissionRequest
Questions []api.QuestionRequest
PlanReviews []api.PlanReviewRequest
}
type MCPResourceReminder ¶
type MCPResourceReminder struct {
api.Attachment
Server string
URI string
MIMEType string
Content string
}
MCPResourceReminder renders a <context_resource> block for an MCP resource attachment.
func (MCPResourceReminder) FormatReminder ¶
func (r MCPResourceReminder) FormatReminder() string
FormatReminder formats the MCP resource as a <context_resource> block tag.
type MediaReminder ¶
MediaReminder renders a <context_media> inline tag for an attached or omitted media payload.
func (MediaReminder) FormatReminder ¶
func (m MediaReminder) FormatReminder() string
FormatReminder formats the media reminder as a self-closing or inline <context_media> tag.
type MessageUpdateOptions ¶
type MessageUpdateOptions struct {
Static StaticContext
Limits models.Limits
SkipContextRecalculation bool
}
type ModeTransitionReminder ¶
type ModeTransitionReminder struct {
Prev api.PermissionMode
Next api.PermissionMode
PlansDir string
}
ModeTransitionReminder formats a behavioral mode transition prompt when entering or leaving non-act modes (plan or ask).
func (ModeTransitionReminder) FormatReminder ¶
func (m ModeTransitionReminder) FormatReminder() string
FormatReminder renders the mode transition template, returning "" when the transition is silent or a no-op.
type Node ¶
type Node interface {
graph.Node[State]
Configure(opts NodeOptions)
}
Node is a workflow graph node that can update its dynamic dependencies in place.
type NodeOptions ¶
type NodeOptions struct {
Model *llm.Model
Tools tools.Container
SystemPrompt string
Limits models.Limits
Static StaticContext
// Rules, when non-nil, drives smart rule matching on tool executions.
Rules *RuleMatcher
// Attachments, when non-nil, resolves all user-message attachments (files,
// directories, rules, skills, MCP resources) and rule triggers into <system_reminders>.
Attachments *AttachmentResolver
// Media, when non-nil, provides the session's content-addressed media store
// for hydrating media descriptors before invoking the LLM.
Media *media.Store
// ModelInfo carries the resolved model's modality and provider metadata so
// the harness can hydrate or degrade media blocks before calling the model.
ModelInfo models.Model
// PlansDir is the session-scoped safe plans directory (<session-dir>/plans/)
// surfaced in plan-mode system reminders.
PlansDir string
// IsSubagent reports whether this harness runs a delegated child session.
IsSubagent bool
}
NodeOptions holds the dynamic per-agent/model dependencies for harness graph nodes.
func (NodeOptions) Validate ¶
func (opts NodeOptions) Validate() error
Validate checks that required model and tools container dependencies are present.
type Queue ¶
type Queue interface {
HasItems() bool
HasLeadingCommand() bool
PopCommand() (id, command string, ok bool)
PopMessages() []message.Message
}
Queue is the consumer interface for the session's execution queue accessed by the harness execution graph.
type ReminderItem ¶
type ReminderItem interface {
FormatReminder() string
}
ReminderItem formats a single section inside a <system_reminders> block.
type RuleLoaded ¶
type RuleLoaded struct {
ID string `json:"id"`
Rule string `json:"rule"`
Trigger string `json:"trigger"` // "glob" | "tool" | "manual"
Matched string `json:"matched,omitempty"`
Path string `json:"path,omitempty"`
}
RuleLoaded is emitted when a conditional workspace rule is auto-injected into <system_reminders> (via an @rule: reference, a keyword trigger, or a tool/path trigger) or loaded on demand via the load_rule tool.
type RuleMatcher ¶
type RuleMatcher struct {
// contains filtered or unexported fields
}
RuleMatcher drives smart conditional rule matching for the active agent. It surfaces keyword-matched rule suggestions on user messages, auto-injects tool/path-triggered rules into <system_reminders>, and produces RuleLoaded events. Explicit @rule: and AttachmentRule resolution lives in AttachmentResolver. A nil RuleMatcher (or one built from a rule-free agent) is a no-op.
func NewRuleMatcher ¶
func NewRuleMatcher(resolved *warp.ResolvedAgent, workspace *warp.Workspace, project *warp.Project, globals map[string]any) *RuleMatcher
NewRuleMatcher constructs a RuleMatcher for the resolved agent. It returns nil when the agent resolves no rules, so callers can treat a nil matcher as a no-op without a separate guard.
func (*RuleMatcher) MatchToolBatch ¶
func (m *RuleMatcher) MatchToolBatch(calls []*message.ToolCall, plans map[string]*tools.Plan, results []*message.Tool, state State) (*message.User, []RuleLoaded)
MatchToolBatch inspects a batch of executed tool calls and their results for tool-name and path triggers, returning a <system_reminders> message (when anything auto-loaded) and the rules that were loaded.
func (*RuleMatcher) SuggestUserRules ¶
func (m *RuleMatcher) SuggestUserRules(msg message.Message, state State) (RuleSuggestionsReminder, []string)
SuggestUserRules inspects a genuine user message for keyword triggers on the agent's conditional rules, returning a RuleSuggestionsReminder and the names of the newly suggested rules.
type RuleReminder ¶
RuleReminder renders a <rule> block for an active or manually attached workspace rule.
func (RuleReminder) FormatReminder ¶
func (r RuleReminder) FormatReminder() string
FormatReminder formats the rule as a <rule> block tag.
type RuleSuggestion ¶
RuleSuggestion describes a single keyword-matched conditional rule suggestion.
type RuleSuggestionsReminder ¶
type RuleSuggestionsReminder struct {
Rules []RuleSuggestion
}
RuleSuggestionsReminder formats keyword-matched workspace rule suggestions.
func (RuleSuggestionsReminder) FormatReminder ¶
func (r RuleSuggestionsReminder) FormatReminder() string
FormatReminder formats the rule suggestions list, returning "" when empty.
type SkillReminder ¶
SkillReminder renders a <skill> block for a manually attached skill.
func (SkillReminder) FormatReminder ¶
func (s SkillReminder) FormatReminder() string
FormatReminder formats the skill as a <skill> block tag.
type State ¶
type State struct {
Messages message.MessageList `json:"messages"`
PendingCompaction *api.CompactRequest `json:"pending_compaction,omitempty"`
PendingPermissions []api.PermissionRequest `json:"pending_permissions,omitempty"`
PendingToolPlans map[string]tools.Plan `json:"pending_tool_plans,omitempty"`
PermissionDecisions map[string]api.PermissionDecision `json:"permission_decisions,omitempty"`
PendingQuestions []api.QuestionRequest `json:"pending_questions,omitempty"`
QuestionResponses map[string]api.QuestionResponse `json:"question_responses,omitempty"`
PendingPlanReviews []api.PlanReviewRequest `json:"pending_plan_reviews,omitempty"`
PlanReviewDecisions map[string]api.PlanReviewDecision `json:"plan_review_decisions,omitempty"`
Todos []api.TodoItem `json:"todos,omitempty"`
LoadedTools []string `json:"loaded_tools,omitempty"`
LoadedRules []string `json:"loaded_rules,omitempty"`
LoadedSkills []string `json:"loaded_skills,omitempty"`
SuggestedRules []string `json:"suggested_rules,omitempty"`
Mode api.PermissionMode `json:"mode,omitempty"`
PlanPath string `json:"plan_path,omitempty"`
Context api.ContextState `json:"context"`
}
State holds the checkpointed conversation and permission state for a thread. It implements github.com/masterkeysrd/loom/graph.State.
func (State) ActiveModalities ¶
ActiveModalities returns the sorted, deduplicated set of non-text input modalities ("image", "pdf", "audio") currently present in State.Messages (post-compaction live context).
func (State) ActiveToolCalls ¶
ActiveToolCalls locates the latest *message.Assistant message with tool calls and returns its index, the assistant message, any unfulfilled tool calls, and whether a new user message was appended after that assistant turn.
func (State) AppendMessage ¶
func (s State) AppendMessage(msg message.Message, opts MessageUpdateOptions) State
func (State) AppendMessages ¶
func (s State) AppendMessages(msgs message.MessageList, opts MessageUpdateOptions) State
func (State) ApplyCompaction ¶
func (s State) ApplyCompaction(static StaticContext, limits models.Limits) State
func (State) Copy ¶
Copy returns a deep copy of the State so graph transitions do not mutate previously captured snapshots.
func (State) DeduplicateToolBlocks ¶
DeduplicateToolBlocks filters *message.ToolReferenceBlock and *message.ToolDefinitionBlock entries out of msg when they reference a tool that is already present in s.LoadedTools (or already appears earlier in the same message), returning the (possibly filtered) message and the names of the tools newly activated by this message. Tool names are compared case-insensitively.
If msg contains no tool reference/definition blocks, it is returned unchanged with a nil slice. For a *message.Tool whose content becomes empty after filtering (i.e. every tool reference was already loaded), a text block informing the model that the tools are already active is appended so the tool result message remains non-empty.
func (State) HasLeadingCompact ¶
HasLeadingCompact reports whether there is a manual compaction request pending.
func (State) HasLoadedRule ¶
HasLoadedRule reports whether a rule with the given name is already in LoadedRules (case-insensitive).
func (State) HasLoadedSkill ¶
HasLoadedSkill reports whether a skill with the given name is already in LoadedSkills (case-insensitive).
func (State) HasPendingToolCalls ¶
HasPendingToolCalls reports whether the latest assistant message in the state has one or more unfulfilled tool calls.
func (State) HasSuggestedRule ¶
HasSuggestedRule reports whether a rule with the given name is already in SuggestedRules (case-insensitive).
func (State) IsAutoCompacted ¶
IsAutoCompacted reports whether the leading message was produced by auto-compaction.
func (State) LastUserIntentText ¶
LastUserIntentText returns a compact, token-budgeted projection of the most recent genuine user prompt (plus up to 1–2 cropped prior genuine user turns for follow-up context). Synthetic system messages (reminders, !cmd outputs, tasks, compactions, subagent traffic), assistant messages, tool results, and injected <system_reminders> blocks are excluded.
func (State) LastUserMessageID ¶
LastUserMessageID returns the ID of the latest genuine *message.User message, or "" if none.
func (State) PrependMessage ¶
func (s State) PrependMessage(msg message.Message, opts MessageUpdateOptions) State
func (State) RecordLoadedRules ¶
RecordLoadedRules returns a copy of s with the given rule names appended to LoadedRules, deduplicated case-insensitively against the existing entries.
func (State) RecordLoadedSkills ¶
RecordLoadedSkills returns a copy of s with the given skill names appended to LoadedSkills, deduplicated case-insensitively against the existing entries.
func (State) RecordLoadedTools ¶
RecordLoadedTools returns a copy of s with the given tool names appended to LoadedTools, deduplicated case-insensitively against the existing entries.
func (State) RecordSuggestedRules ¶
RecordSuggestedRules returns a copy of s with the given rule names appended to SuggestedRules, deduplicated case-insensitively against the existing entries.
func (State) ShouldAutoCompact ¶
ShouldAutoCompact reports whether the current conversation state qualifies for mid-turn or entry auto-compaction.
func (State) ShouldWakeAgent ¶
ShouldWakeAgent checks if the latest message warrants waking the agent node.
type StaticContext ¶
type StaticContext struct {
SystemPrompt int
ContextFiles int
SystemTools int
CustomTools int
MCPTools int
Skills int
Subagents int
Rules int
}
StaticContext represents the token cost of the static prefix (system prompt, workspace context files, tools, skills, and subagents) measured at harness init.
func StaticContextFromBreakdown ¶
func StaticContextFromBreakdown(b api.ContextBreakdown) StaticContext
StaticContextFromBreakdown creates a StaticContext from an api.ContextBreakdown.
func (StaticContext) Breakdown ¶
func (s StaticContext) Breakdown() api.ContextBreakdown
Breakdown converts StaticContext into an api.ContextBreakdown.
func (StaticContext) Total ¶
func (s StaticContext) Total() int
Total returns the sum of all static context token buckets.
type SystemReminder ¶
type SystemReminder struct {
Items []ReminderItem
RuleNames []string
ExtraBlocks []message.Block
}
SystemReminder assembles one or more ReminderItem sections and optional metadata/tool blocks into a synthetic <system_reminders> user message.
func (SystemReminder) Format ¶
func (r SystemReminder) Format() string
Format renders all non-empty reminder items wrapped in <system_reminders>, returning "" when no items produce output.
func (SystemReminder) Message ¶
func (r SystemReminder) Message() *message.User
Message builds a synthetic reminder *message.User, returning nil when Format produces no content.
type ToolsNode ¶
type ToolsNode struct {
// contains filtered or unexported fields
}
ToolsNode orchestrates pre-flight tool preparation, permission gate evaluation, interrupt/resume lifecycles, and tool execution. It implements github.com/masterkeysrd/loom/graph.Node.
func NewToolsNode ¶
func NewToolsNode(cfg ToolsNodeConfig) *ToolsNode
NewToolsNode constructs a new ToolsNode bound to the tool container, permission manager, and logger.
func (*ToolsNode) Configure ¶
func (n *ToolsNode) Configure(opts NodeOptions)
type ToolsNodeConfig ¶
type ToolsNodeConfig struct {
Metrics metrics.Recorder
Permissions permissions.SessionManager
Logger log.Interface
// Reviewer, when non-nil, evaluates risky auto-mode permission cards
// once before interrupting the human.
Reviewer permreview.Reviewer
}