{"modulePath":"github.com/GoCodeAlone/workflow-plugin-agent","version":"v0.7.2","isLatest":false,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package executor\n\nPackage executor provides the core autonomous agent execution loop.\n\n## Functions\n\n```go\nfunc EstimateTokens(messages []provider.Message) int\n```\nEstimateTokens estimates the number of tokens in a message slice. Uses a rough heuristic of 4 characters per token (standard for English text).\n\n## Types\n\n```go\ntype Action = policy.Action\n```\nAction is a type alias for policy.Action, providing compile-time parity between the executor and policy packages with no string duplication.\n\n```go\nconst (\n\tActionAllow Action = policy.Allow\n\tActionDeny  Action = policy.Deny\n\tActionAsk   Action = policy.Ask\n)\n```\n\n```go\ntype ApprovalRecord struct {\n\tID              string\n\tStatus          ApprovalStatus\n\tReviewerComment string\n}\n```\nApprovalRecord is a resolved approval request.\n\n```go\ntype ApprovalStatus string\n```\nApprovalStatus represents the resolution state of an approval.\n\n```go\nconst (\n\tApprovalPending  ApprovalStatus = \"pending\"\n\tApprovalApproved ApprovalStatus = \"approved\"\n\tApprovalRejected ApprovalStatus = \"rejected\"\n\tApprovalTimeout  ApprovalStatus = \"timeout\"\n)\n```\n\n```go\ntype Approver interface {\n\t// Request creates a pending approval for the given tool call and returns its ID.\n\t// Implementers should persist the pending approval so WaitForResolution can query it.\n\tRequest(ctx context.Context, toolName string, args map[string]any) (approvalID string, err error)\n\n\t// WaitForResolution blocks until the approval with the given ID is resolved\n\t// or the timeout elapses.\n\tWaitForResolution(ctx context.Context, approvalID string, timeout time.Duration) (*ApprovalRecord, error)\n}\n```\nApprover manages approval gate blocking.\n\n```go\ntype Config struct {\n\t// Provider is the AI backend. Required.\n\tProvider provider.Provider\n\n\t// ToolRegistry provides tool definitions and execution. Optional.\n\tToolRegistry *tools.Registry\n\n\t// Approver handles approval gates. Defaults to NullApprover.\n\tApprover Approver\n\n\t// HumanRequester handles blocking human-request gates. Defaults to NullHumanRequester.\n\tHumanRequester HumanRequester\n\n\t// SecretRedactor redacts secrets from messages. Defaults to NullSecretRedactor.\n\tSecretRedactor SecretRedactor\n\n\t// Transcript records conversation entries. Defaults to NullTranscript.\n\tTranscript TranscriptRecorder\n\n\t// Memory provides persistent agent memory. Defaults to NullMemoryStore.\n\tMemory MemoryStore\n\n\t// MaxIterations caps the agent loop. Default: 10.\n\tMaxIterations int\n\n\t// ApprovalTimeout is how long to wait for human approval. Default: 30m.\n\tApprovalTimeout time.Duration\n\n\t// RequestTimeout is how long to wait for human request response. Default: 60m.\n\tRequestTimeout time.Duration\n\n\t// LoopDetector config. Zero values use defaults.\n\tLoopDetection LoopDetectorConfig\n\n\t// CompactionThreshold is the fraction of context limit at which compaction triggers. Default: 0.80.\n\tCompactionThreshold float64\n\n\t// TaskID and ProjectID are used for transcript recording.\n\tTaskID    string\n\tProjectID string\n\n\t// Inbox receives external messages injected into the conversation\n\t// between loop iterations. Nil means no external messages.\n\tInbox \u003c-chan provider.Message\n\n\t// OnEvent is called for each executor event. Nil means no events emitted.\n\t// The callback must not block — use a buffered channel internally if needed.\n\tOnEvent func(Event)\n\n\t// ShouldStop is called after each tool execution round. If it returns\n\t// a non-empty string, the loop exits with status \"completed\" and that\n\t// string as the Result.Content. Nil means no custom termination.\n\tShouldStop func() (reason string)\n\n\t// TrustEngine evaluates trust rules before tool execution. Nil = no trust enforcement.\n\tTrustEngine TrustEvaluator\n\n\t// SandboxMode routes bash and file tool calls through ContainerManager.\n\tSandboxMode bool\n\n\t// ContainerMgr provides Docker container execution. Required when SandboxMode is true.\n\tContainerMgr ContainerExecutor\n\n\t// SandboxSpec is the container configuration for sandbox mode.\n\tSandboxSpec *SandboxConfig\n}\n```\nConfig holds all dependencies for the executor. Nil interface fields are replaced with their Null\\* implementations.\n\n```go\ntype ContainerExecutor interface {\n\tIsAvailable() bool\n\tEnsureContainer(ctx context.Context, projectID, workspacePath string, spec SandboxConfig) (string, error)\n\tExecInContainer(ctx context.Context, projectID, command, workDir string, timeout int) (stdout, stderr string, exitCode int, err error)\n}\n```\nContainerExecutor can run commands inside a Docker container.\n\n```go\ntype ContextManager struct {\n\t// contains filtered or unexported fields\n}\n```\nContextManager tracks token usage across a message array and compacts the conversation when it approaches the model's context limit.\n\n```go\nfunc NewContextManager(providerName string, compactionThreshold float64) *ContextManager\n```\nNewContextManager creates a ContextManager for the given provider. The model name is used to look up the context window size. compactionThreshold sets the fraction of the context limit that triggers compaction; pass 0 to use the default (0.80).\n\n```go\nfunc (cm *ContextManager) Compact(\n\tctx context.Context,\n\tmessages []provider.Message,\n\taiProvider provider.Provider,\n) []provider.Message\n```\nCompact compresses the conversation history by:\n\n 1. Keeping the system message (index 0) and the most recent 2 exchanges.\n 2. Summarising the middle portion using the LLM provider.\n 3. Injecting the summary as a system-level context note.\n\nIf summarisation fails, the middle messages are replaced with a placeholder rather than aborting. Returns the compacted message slice.\n\n```go\nfunc (cm *ContextManager) Compactions() int\n```\nCompactions returns how many times compaction has been applied.\n\n```go\nfunc (cm *ContextManager) ContextLimitTokens() int\n```\nContextLimitTokens returns the model's context window size in tokens.\n\n```go\nfunc (cm *ContextManager) NeedsCompaction(messages []provider.Message) bool\n```\nNeedsCompaction returns true if the estimated token count exceeds the threshold.\n\n```go\nfunc (cm *ContextManager) SetModelLimit(model string, limit int)\n```\nSetModelLimit overrides the context token limit for a specific model name pattern. This allows module config to adjust limits without modifying the built-in defaults.\n\n```go\nfunc (cm *ContextManager) TokenUsage(messages []provider.Message) (estimated, limit int)\n```\nTokenUsage returns the current estimated tokens and the context limit.\n\n```go\ntype DenyAllTrustEvaluator struct{}\n```\nDenyAllTrustEvaluator denies every tool call. Used as the default when no TrustEngine is configured, so missing configuration fails closed rather than open.\n\n```go\nfunc (d *DenyAllTrustEvaluator) Evaluate(_ context.Context, _ string, _ map[string]any) Action\n```\n\n```go\nfunc (d *DenyAllTrustEvaluator) EvaluateCommand(_ string) Action\n```\n\n```go\nfunc (d *DenyAllTrustEvaluator) EvaluatePath(_ string) Action\n```\n\n```go\ntype Event struct {\n\tType       EventType      `json:\"type\"`\n\tAgentID    string         `json:\"agent_id,omitempty\"`\n\tIteration  int            `json:\"iteration,omitempty\"`\n\tContent    string         `json:\"content,omitempty\"`      // text content or thinking trace\n\tToolName   string         `json:\"tool_name,omitempty\"`    // for tool_call_start/result\n\tToolCallID string         `json:\"tool_call_id,omitempty\"` // for tool_call_start/result\n\tToolArgs   map[string]any `json:\"tool_args,omitempty\"`    // for tool_call_start\n\tToolResult string         `json:\"tool_result,omitempty\"`  // for tool_call_result\n\tToolError  bool           `json:\"tool_error,omitempty\"`   // for tool_call_result\n\tError      string         `json:\"error,omitempty\"`        // for failed events\n}\n```\nEvent is emitted during execution for real-time observation.\n\n```go\ntype EventType string\n```\nEventType identifies what happened in the executor loop.\n\n```go\nconst (\n\tEventToolCallStart  EventType = \"tool_call_start\"\n\tEventToolCallResult EventType = \"tool_call_result\"\n\tEventThinking       EventType = \"thinking\"\n\tEventText           EventType = \"text\"\n\tEventIteration      EventType = \"iteration\"\n\tEventCompleted      EventType = \"completed\"\n\tEventFailed         EventType = \"failed\"\n\tEventTrustAllow     EventType = \"trust_allow\"\n\tEventTrustDeny      EventType = \"trust_deny\"\n\tEventTrustAsk       EventType = \"trust_ask\"\n)\n```\n\n```go\ntype HumanRequest struct {\n\tID              string\n\tRequestType     RequestType\n\tStatus          RequestStatus\n\tResponseData    string\n\tResponseComment string\n\tMetadata        string // JSON\n}\n```\nHumanRequest is a resolved human request record.\n\n```go\ntype HumanRequester interface {\n\t// WaitForResolution blocks until the request with the given ID is resolved\n\t// or the timeout elapses.\n\tWaitForResolution(ctx context.Context, requestID string, timeout time.Duration) (*HumanRequest, error)\n}\n```\nHumanRequester manages blocking human-request gates.\n\n```go\ntype LoopDetector struct {\n\t// contains filtered or unexported fields\n}\n```\nLoopDetector detects agent execution loops using multiple heuristics.\n\n```go\nfunc NewLoopDetector(cfg LoopDetectorConfig) *LoopDetector\n```\nNewLoopDetector creates a LoopDetector with the given config. Zero values in cfg are replaced with defaults (MaxConsecutive=3, MaxErrors=2, MaxAlternating=3, MaxNoProgress=3).\n\n```go\nfunc (ld *LoopDetector) Check() (LoopStatus, string)\n```\nCheck evaluates the recorded history for loop patterns and returns the current status along with a human-readable explanation. Checks are evaluated in priority order: hard breaks take precedence over warnings.\n\n```go\nfunc (ld *LoopDetector) Record(toolName string, args map[string]any, result string, isError bool)\n```\nRecord appends a tool invocation to the history.\n\n```go\nfunc (ld *LoopDetector) Reset()\n```\nReset clears recorded history.\n\n```go\ntype LoopDetectorConfig struct {\n\t// MaxConsecutive is the number of identical consecutive tool calls before a loop is detected.\n\t// Default: 3.\n\tMaxConsecutive int\n\t// MaxErrors is the number of times the same tool call can return the same error before a loop is detected.\n\t// Default: 2.\n\tMaxErrors int\n\t// MaxAlternating is the number of A/B alternating cycles before a loop is detected.\n\t// Default: 3.\n\tMaxAlternating int\n\t// MaxNoProgress is the number of identical (same args + same result) non-error calls before a loop is detected.\n\t// Default: 3.\n\tMaxNoProgress int\n}\n```\nLoopDetectorConfig holds configurable thresholds for loop detection.\n\n```go\ntype LoopStatus int\n```\nLoopStatus represents the result of a loop check.\n\n```go\nconst (\n\t// LoopStatusOK means no loop detected.\n\tLoopStatusOK LoopStatus = iota\n\t// LoopStatusWarning means a potential loop pattern is forming.\n\tLoopStatusWarning\n\t// LoopStatusBreak means a definitive loop is detected; execution should stop.\n\tLoopStatusBreak\n)\n```\n\n```go\ntype MemoryEntry struct {\n\tID       string\n\tAgentID  string\n\tContent  string\n\tCategory string\n}\n```\nMemoryEntry is a single piece of persistent agent memory.\n\n```go\ntype MemoryStore interface {\n\t// Search finds relevant memories for agentID using query text.\n\tSearch(ctx context.Context, agentID, query string, limit int) ([]MemoryEntry, error)\n\t// Save persists a memory entry.\n\tSave(ctx context.Context, entry MemoryEntry) error\n\t// ExtractAndSave extracts facts from a transcript and saves them.\n\tExtractAndSave(ctx context.Context, agentID, transcript string, embedder provider.Embedder) error\n}\n```\nMemoryStore provides persistent memory storage and retrieval.\n\n```go\ntype NullApprover struct{}\n```\nNullApprover is a no-op Approver for dev/testing — auto-approves every request.\n\n```go\nfunc (n *NullApprover) Request(_ context.Context, _ string, _ map[string]any) (string, error)\n```\n\n```go\nfunc (n *NullApprover) WaitForResolution(_ context.Context, _ string, _ time.Duration) (*ApprovalRecord, error)\n```\n\n```go\ntype NullHumanRequester struct{}\n```\nNullHumanRequester is a no-op HumanRequester — always returns expired.\n\n```go\nfunc (n *NullHumanRequester) WaitForResolution(_ context.Context, _ string, _ time.Duration) (*HumanRequest, error)\n```\n\n```go\ntype NullMemoryStore struct{}\n```\nNullMemoryStore is a no-op MemoryStore.\n\n```go\nfunc (n *NullMemoryStore) ExtractAndSave(_ context.Context, _ string, _ string, _ provider.Embedder) error\n```\n\n```go\nfunc (n *NullMemoryStore) Save(_ context.Context, _ MemoryEntry) error\n```\n\n```go\nfunc (n *NullMemoryStore) Search(_ context.Context, _, _ string, _ int) ([]MemoryEntry, error)\n```\n\n```go\ntype NullSecretRedactor struct{}\n```\nNullSecretRedactor is a no-op SecretRedactor.\n\n```go\nfunc (n *NullSecretRedactor) CheckAndRedact(_ *provider.Message)\n```\n\n```go\nfunc (n *NullSecretRedactor) Redact(text string) string\n```\n\n```go\ntype NullTranscript struct{}\n```\nNullTranscript is a no-op TranscriptRecorder.\n\n```go\nfunc (n *NullTranscript) Record(_ context.Context, _ TranscriptEntry) error\n```\n\n```go\ntype NullTrustEvaluator struct{}\n```\nNullTrustEvaluator allows everything — intended for dev/testing only. In production, configure a real TrustEvaluator. When Config.TrustEngine is nil, the executor defaults to DenyAllTrustEvaluator for fail-safe behavior.\n\n```go\nfunc (n *NullTrustEvaluator) Evaluate(_ context.Context, _ string, _ map[string]any) Action\n```\n\n```go\nfunc (n *NullTrustEvaluator) EvaluateCommand(_ string) Action\n```\n\n```go\nfunc (n *NullTrustEvaluator) EvaluatePath(_ string) Action\n```\n\n```go\ntype PolicyTrustBridge struct {\n\t// contains filtered or unexported fields\n}\n```\nPolicyTrustBridge adapts policy.TrustEngine to executor.TrustEvaluator. It provides a compile-time-safe mapping between policy.Action and executor.Action.\n\n```go\nfunc (b *PolicyTrustBridge) Evaluate(ctx context.Context, toolName string, args map[string]any) Action\n```\n\n```go\nfunc (b *PolicyTrustBridge) EvaluateCommand(cmd string) Action\n```\n\n```go\nfunc (b *PolicyTrustBridge) EvaluatePath(path string) Action\n```\n\n```go\ntype RequestStatus string\n```\nRequestStatus represents the resolution state of a human request.\n\n```go\nconst (\n\tRequestPending   RequestStatus = \"pending\"\n\tRequestResolved  RequestStatus = \"resolved\"\n\tRequestCancelled RequestStatus = \"cancelled\"\n\tRequestExpired   RequestStatus = \"expired\"\n)\n```\n\n```go\ntype RequestType string\n```\nRequestType categorizes what the agent needs from the human.\n\n```go\nconst (\n\tRequestTypeToken  RequestType = \"token\"\n\tRequestTypeBinary RequestType = \"binary\"\n\tRequestTypeAccess RequestType = \"access\"\n\tRequestTypeInfo   RequestType = \"info\"\n\tRequestTypeCustom RequestType = \"custom\"\n)\n```\n\n```go\ntype Result struct {\n\tContent    string\n\tThinking   string\n\tIterations int\n\tStatus     string // \"completed\", \"failed\", \"loop_detected\", \"approval_timeout\", \"request_expired\"\n\tError      string\n}\n```\nResult is the outcome of an Execute call.\n\n```go\nfunc Execute(ctx context.Context, cfg Config, systemPrompt, userTask, agentID string) (*Result, error)\n```\nExecute runs the autonomous agent loop with the given config. systemPrompt is the agent's system instructions; userTask is the task to complete; agentID is the agent's identifier used for memory and transcript recording.\n\n```go\ntype SandboxConfig struct {\n\tEnabled      bool           `json:\"enabled\" yaml:\"enabled\"`\n\tImage        string         `json:\"image\" yaml:\"image\"`\n\tNetwork      string         `json:\"network\" yaml:\"network\"`\n\tMemory       string         `json:\"memory\" yaml:\"memory\"`\n\tCPU          float64        `json:\"cpu\" yaml:\"cpu\"`\n\tMounts       []SandboxMount `json:\"mounts\" yaml:\"mounts\"`\n\tInitCommands []string       `json:\"init\" yaml:\"init\"`\n}\n```\nSandboxConfig holds per-agent Docker sandbox settings.\n\n```go\ntype SandboxMount struct {\n\tSrc      string `json:\"src\" yaml:\"src\"`\n\tDst      string `json:\"dst\" yaml:\"dst\"`\n\tReadOnly bool   `json:\"readonly\" yaml:\"readonly\"`\n}\n```\nSandboxMount is a bind mount for a sandbox container.\n\n```go\ntype SecretRedactor interface {\n\t// Redact returns the text with known secrets replaced.\n\tRedact(text string) string\n\t// CheckAndRedact redacts secrets from a message in place.\n\tCheckAndRedact(msg *provider.Message)\n}\n```\nSecretRedactor redacts secrets from text.\n\n```go\ntype TranscriptEntry struct {\n\tID         string\n\tAgentID    string\n\tTaskID     string\n\tProjectID  string\n\tIteration  int\n\tRole       provider.Role\n\tContent    string\n\tThinking   string\n\tToolCalls  []provider.ToolCall\n\tToolCallID string\n}\n```\nTranscriptEntry is a single recorded message in the agent conversation.\n\n```go\ntype TranscriptRecorder interface {\n\tRecord(ctx context.Context, entry TranscriptEntry) error\n}\n```\nTranscriptRecorder records agent interactions.\n\n```go\ntype TrustEvaluator interface {\n\t// Evaluate returns the trust action for a tool call.\n\tEvaluate(ctx context.Context, toolName string, args map[string]any) Action\n\t// EvaluateCommand returns the trust action for a bash command.\n\tEvaluateCommand(cmd string) Action\n\t// EvaluatePath returns the trust action for a file path.\n\tEvaluatePath(path string) Action\n}\n```\nTrustEvaluator checks whether a tool call is permitted.\n\n```go\nfunc NewPolicyTrustBridge(te *policy.TrustEngine) TrustEvaluator\n```\nNewPolicyTrustBridge creates a TrustEvaluator backed by a policy.TrustEngine.\n\n","path":"github.com/GoCodeAlone/workflow-plugin-agent/executor","name":"executor","synopsis":"Package executor provides the core autonomous agent execution loop.","isRedistributable":true}
