tools

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 149 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package tools registers model callable tools and runs them inside a session environment

Index

Constants

View Source
const (
	AutoApproveAsk       = "ask"
	AutoApproveWorkspace = "workspace_session"
	AutoApproveSession   = "session"
)
View Source
const (
	ExitAllow = 0
	ExitUsage = 1
	ExitAsk   = 2
	ExitDeny  = 3
)
View Source
const (
	InvisibleUnicodeDescription       = "invisible or bidirectional Unicode control character (possible obfuscation)"
	ParserLimitDescription            = "command parser limit exceeded"
	MalformedExecDescription          = "command parser limit or malformed executable payload"
	GatewayLifecycleSpliceDescription = "stop/restart icebath gateway via shell-spliced verb (kills running agents)"
)
View Source
const (
	TranscriptTailLines = 20
	TranscriptTailChars = 2000
)
View Source
const (
	ReasonRuntimeOffline        = "runtime_offline"
	ReasonQueuedExpired         = "queued_expired"
	ReasonDeliveryTimeout       = "delivery_timeout"
	ReasonAgentBlocked          = "agent_blocked"
	ReasonCancelled             = "cancelled"
	ReasonProviderAuthOrAccess  = "provider_auth_or_access"
	ReasonProviderQuotaLimit    = "provider_quota_limit"
	ReasonProviderRateLimit     = "provider_rate_limit"
	ReasonProviderServerError   = "provider_server_error"
	ReasonContextOverflow       = "context_overflow"
	ReasonMissingConfig         = "missing_config"
	ReasonModelUnavailable      = "model_unavailable"
	ReasonTargetScopeUnresolved = "target_scope_unresolved"
	ReasonUnknown               = "unknown"
)

Platform side and agent side bot turn failure reason codes

View Source
const (
	RetryResume             = "resume"
	RetryCompressThenResume = "compress_then_resume"
	RetryNone               = "none"
)

Bot turn retry actions

View Source
const (
	BotRelayDirName = "bot_relay"

	TurnWaitSecondsFallback = 120
)
View Source
const (
	DefaultResultSizeChars    = 100000
	DefaultTurnBudgetChars    = 200000
	DefaultPreviewSizeChars   = 1500
	DefaultMCPResultSizeChars = 50000
	MCPToolPrefix             = "mcp_"
	// BudgetUnlimited is the infinite threshold that never persists a result
	BudgetUnlimited = math.MaxInt
)
View Source
const (
	ClarifyTextResolved          = "resolved"
	ClarifyTextRejectedProse     = "rejected_prose"
	ClarifyTextRejectedSelection = "rejected_selection"
	ClarifyTextNoPending         = "no_pending"
	ClarifySkipWord              = "skip"
	ClarifySkipped               = "\x00skipped"
	ClarifyCancelled             = "\x00cancelled"
)

Outcomes for typed clarify replies

View Source
const (
	ConnUnknownTarget  = "unknown_target"
	ConnMixedKinds     = "mixed_kinds"
	ConnLinkStillValid = "link_still_valid"
	ConnSettled        = "settled"
	ConnNotAllowed     = "not_allowed"
	ConnRefused        = "refused"
)

Refusals a card retry answers with, the connector_refusals copy keys

View Source
const (
	ContextFileMaxChars      = 20000
	ContextTruncateHeadRatio = 0.7
	ContextTruncateTailRatio = 0.2
)
View Source
const (
	DefaultMaxConcurrentChildren = 10
	DelegationMaxDepth           = 1
)
View Source
const (
	DiscordFlagsGuildMembers   = 1<<14 | 1<<15
	DiscordFlagsMessageContent = 1<<18 | 1<<19
)

Application flag bits of GET /applications/@me, each pairing an intent with its under 100 guild variant

View Source
const (
	PrunedToolArgumentsError = "suspected_pruned_tool_arguments"
	ReasonUserInterrupt      = "user interrupt"
)
View Source
const (
	DefaultReadOffset   = 1
	DefaultReadLimit    = 2000
	DefaultSearchOffset = 0
	DefaultSearchLimit  = 50
)

Pagination defaults for read_file and search_files

View Source
const (
	ImageUnsupportedScheme = "unsupported_scheme"
	ImageSourceUnsafe      = "source_unsafe"
	ImageSourceTooLarge    = "source_too_large"
	ImageSourceNotFound    = "source_not_found"
	ImageNotAnImage        = "not_an_image"
)

Failure classes of the media source resolver

View Source
const (
	MCPEmoji         = "🔌"
	SearchEmoji      = "🔎"
	DescribeEmoji    = "📖"
	DefaultToolEmoji = "⚡"
)
View Source
const (
	OnboardingBusyInputFlag    = "busy_input_prompt"
	OnboardingToolProgressFlag = "tool_progress_prompt"
	OnboardingProfileBuildFlag = "profile_build_offered"
)

Stable config.yaml keys under onboarding.seen

View Source
const (
	// MaxOutputChars is the rolling output buffer size per process
	MaxOutputChars = 200_000
	// CompletionOutputChars is the output tail a completion notification carries
	CompletionOutputChars = 2000
	// FinishedTTLSeconds keeps finished processes listed for 30 minutes
	FinishedTTLSeconds = 1800
	// MaxProcesses caps the tracked processes before LRU pruning
	MaxProcesses = 64
	// WatchMinIntervalSeconds spaces watch match notifications per session
	WatchMinIntervalSeconds = 15
	// WatchStrikeLimit is the consecutive rate limit windows that disable watching
	WatchStrikeLimit = 3
	// WatchLifetimeMaxHits caps delivered matches over a session's life
	WatchLifetimeMaxHits = 8
	// HeartbeatMinSeconds floors the heartbeat interval
	HeartbeatMinSeconds = 60
	// HeartbeatTickSeconds is the heartbeat loop period
	HeartbeatTickSeconds = 5
	// WatchGlobalMaxPerWindow caps watch matches across every session per window
	WatchGlobalMaxPerWindow = 15
	// WatchGlobalWindowSeconds is the global watch window
	WatchGlobalWindowSeconds = 10
	// WatchGlobalCooldownSeconds is the global breaker cooldown
	WatchGlobalCooldownSeconds = 30
)
View Source
const (
	RelaySessionScope             = "icebath.session"
	RelayTurnScope                = "icebath.turn"
	RelayLogicalLLMScope          = "icebath.logical_llm_call"
	RelayRuntimeSchemaKey         = "icebath.relay.schema_version"
	RelayRuntimeSchemaVersion     = "icebath.relay.runtime.v1"
	RelayRuntimeInstanceKey       = "icebath.relay.runtime_instance"
	RelayPluginsExecutionConsumer = "icebath.nemo_relay.plugins"
)
View Source
const (
	PersistedOutputTag        = "<persisted-output>"
	PersistedOutputClosingTag = "</persisted-output>"
	SpilloverSubdir           = "cache/spillover"
	// SpilloverMaxAgeHours is the legacy floor used when the retention config is unreadable
	SpilloverMaxAgeHours = 24

	// ThresholdResolve asks MaybePersistToolResult to resolve the tool's own threshold
	ThresholdResolve = -1
)
View Source
const (
	SpillDefaultMaxChars    = 10000
	SpillDefaultPreviewHead = 500
	SpillDefaultPreviewTail = 500
)

Hook output spill defaults

View Source
const (
	SubagentIDConfigKey     = "_subagent_id"
	LiveTranscriptConfigKey = "_live_transcript"
)

Model config keys of a child's session row naming its subagent id, live log and spawning session

View Source
const (
	MaxTodoContentChars = 4000
	MaxTodoItems        = 256
	MaxTodoResultChars  = state.MaxTodoResultChars

	// TodoInjectionHeader is the stable header the compressor keys on to tell the synthetic row from a user message
	TodoInjectionHeader = state.TodoInjectionHeader
	TodoToolName        = "todo_list"
)
View Source
const (
	ToolSearchName   = "tool_search"
	ToolDescribeName = "tool_describe"
	ToolCallName     = "tool_call"
)

Reserved bridge names no user, plugin, or MCP tool may take

View Source
const (
	MinQueryTermCoverage          = 0.5
	MinAnswerableTermsForCoverage = 4
)

Relevance floor so long hunts whose words exist only scattered across tools return nothing

View Source
const (
	DefaultMaxBytes      = 50000
	DefaultMaxLines      = 2000
	DefaultMaxLineLength = 2000
)
View Source
const (
	KanbanRateLimitExitCode        = 75
	KanbanTerminalProviderExitCode = 78
)

Exit codes of a kanban worker the dispatcher reads, a healable provider failure and one needing an operator

View Source
const (
	// DefaultExtractCharLimit is the per page character budget sent to the model
	DefaultExtractCharLimit = 15000
	// MaxStoredTextChars caps the full text file written to cache/web
	MaxStoredTextChars = 2_000_000
)
View Source
const (
	WorktreeExitKeep    = "keep"
	WorktreeExitArchive = "archive"
	WorktreeExitDiscard = "discard"
)
View Source
const (
	KeepUnarchivable   = "keep-unarchivable"
	KeepWorktreeRefs   = "keep-worktree-refs"
	KeepLargeUntracked = "keep-large-untracked"
	KeepSubmoduleWork  = "keep-submodule-work"
)

Keep actions a removal blocker reports

View Source
const (
	WriteApprovalMemory = "memory"
	WriteApprovalSkills = "skills"
)

Write approval subsystems gating cross session writes

View Source
const ArchivePrefix = "refs/icebath/archive/"

Ref namespace holding worktree archives

View Source
const AsyncMaxDeliveryAttempts = asyncMaxDeliveryAttempts

Delivery attempts after which a pending async delegation result is dropped

View Source
const BotModeProtocolHeading = "## Messaging other agents"

BotModeProtocolHeading opens the Bot Chat teammate section and the plugin era SOUL append

View Source
const BundlePrefix = "icebath-"

BundlePrefix is the prefix every platform bundle name carries

View Source
const CatalogSummaryMaxChars = 80

CatalogSummaryMaxChars caps one catalog line at its tool's first sentence

View Source
const CharsPerToken = 4.0

CharsPerToken slightly underestimates so activation errs toward fewer false triggers

View Source
const CodingAgentGuidance = "You are a coding agent pairing with the user inside their codebase. Operate like a careful senior engineer.\n" +
	"\n" +
	"Gather context first:\n" +
	"- Read the relevant files with `read_file` and locate code with `search_files` before changing anything. Trace a symbol to its definition and usages rather than guessing its shape.\n" +
	"- Batch independent lookups: when several reads/searches don't depend on each other, issue them together in one turn instead of one at a time.\n" +
	"- Never invent files, symbols, APIs, or imports. If you haven't seen it in the repo, go look. Don't assume a library is available — check the project manifest (pyproject.toml / package.json / Cargo.toml / go.mod) and how neighbouring files import it.\n" +
	"\n" +
	"Make changes through the tools, not the chat:\n" +
	"- Edit with `patch`/`write_file`. Do NOT print code blocks to the user as a substitute for editing — apply the change, then summarise it. Only show code when the user explicitly asks to see it.\n" +
	"- Match the project's existing style and conventions; AGENTS.md / CLAUDE.md / .cursorrules already in context win over your defaults. Touch only what the task needs — no drive-by refactors, renames, or reformatting — and add any imports/dependencies your code requires.\n" +
	"- If an edit fails to apply, re-read the file to get the current exact contents before retrying — don't repeat a stale patch. If the same region fails twice, rewrite the enclosing function or file with `write_file` instead of attempting a third patch.\n" +
	"\n" +
	"Verify, and know when to stop:\n" +
	"- Use `terminal` for git, builds, tests, and inspection. Run the relevant tests/linter/build and confirm they pass before claiming the work is done.\n" +
	"- Terminal state persists across calls: current directory and exported environment variables carry forward. Activate a virtualenv or export setup vars once, then reuse that state instead of re-sourcing it before every test command.\n" +
	"- Fix root causes, not symptoms: when you find a bug, check sibling call paths for the same flaw and fix the class, not just the reported site.\n" +
	"- When fixing linter/type errors on a file, stop after about three attempts on the same file and ask the user rather than looping.\n" +
	"- Track multi-step work with `todo_list`. Reference code as `path:line` instead of pasting whole files.\n" +
	"\n" +
	"Respect the user's repo: don't commit, push, or rewrite history unless asked, and never read, print, or commit secrets — leave `.env` and credential files alone unless the user explicitly asks. The Workspace block below is a snapshot from session start — re-run `git status`/`git branch` before relying on it. Be concise: lead with the change or answer, not a preamble."

CodingAgentGuidance is the coding posture brief prepended to the system prompt

View Source
const CodingToolset = "coding"

CodingToolset is the toolset the coding posture collapses to under focus

View Source
const CommitGraphRefreshEntry = "__icebath_commit_graph_refresh__"

Hidden first argument the detached refresh child carries, dispatched before any other parsing

View Source
const CompressionMarkerPrefix = "⟪ICEBATH-CONTEXT-COMPRESSION:"

CompressionMarkerPrefix opens the model visible context compression marker

View Source
const DDGSWorkerEntry = "__icebath_ddgs_worker__"

Hidden first argument a main or TestMain routes to the DDGS worker through DispatchDDGSWorkerEntry

View Source
const DefaultContainerBase = "/root/.icebath"

DefaultContainerBase is where container backends mount the profile home

View Source
const DefaultDelegationBackend = "default"

Backend a blank or unset delegation.backend selects

View Source
const DefaultReviewContextMessages = 10

Recent chat messages the reviewer gets

View Source
const DefaultXAIBaseURL = "https://api.x.ai/v1"

DefaultXAIBaseURL is the xAI REST origin for API key callers

View Source
const DelegatedChildEnvMarker = delegatedChildEnvMarker

Env marker carrying the delegate child fence across a spawn

View Source
const EffectDispositionKey = "effect_disposition"

EffectDispositionKey stores the interrupt disposition on a tool result message

View Source
const EstopSentinelName = "ESTOP"

File name of the emergency stop sentinel under a home

View Source
const FinishReasonLength = "length"

FinishReasonLength is the provider finish reason for an output length stop

View Source
const GatewayProfilePinEnv = "ICEBATH_GATEWAY_PROFILE_PIN"

GatewayProfilePinEnv keeps a child on the gateway's profile after its supervisor markers are dropped

View Source
const GeneratedSubdir = "generated"

GeneratedSubdir holds provider generated media under the cache directory

View Source
const GitFilterDiscoveryFailed = gitFilterDiscoveryFailed

GitFilterDiscoveryFailed is the stderr text of a refused git call whose repo filters could not be read

View Source
const GuardrailRefusalKey = "guardrail_refusal"

GuardrailRefusalKey marks a harness refusal of a redundant call that nothing failed

View Source
const HeartbeatDisplayKind = "hidden"

HeartbeatDisplayKind hides heartbeat rows, a wake rather than a message

View Source
const HeartbeatOutputChars = 2000

HeartbeatOutputChars caps the output a heartbeat tick carries

View Source
const HeldNotSent = "runtime_coordination_required"

Runtime refusal code a Bot Chat delivery id's settled not sent receipt carries

View Source
const HostInterpreterKillRejection = "Blocked: this command kills every process whose image/name matches the " +
	"interpreter hosting this gateway (and this command). " +
	"Stop only the process you own instead: process(action=\"kill\", session_id=\"proc_…\") " +
	"for a background job Icebath started, or kill/taskkill by its explicit PID."

HostInterpreterKillRejection is the text every surface shows for a kill aimed at the gateway image

View Source
const HumanWaitMarginSeconds = 60.0

HumanWaitMarginSeconds is added above approvals.timeout when clamping a window's contribution

View Source
const (

	// IdenticalResultStubMinChars is the smallest duplicate result worth replacing by a reference stub
	IdenticalResultStubMinChars = 512
)
View Source
const (
	LSPTurnEndWait = 5 * time.Second
)

Deferred verdict queue limits and the bounded turn end wait

View Source
const LedgerFilename = "spawn-ledger.json"

LedgerFilename is the spawn ledger file under the root home

View Source
const MaxReferencedScriptBytes = 1024 * 1024

MaxReferencedScriptBytes caps one referenced script read by the lifecycle walk

View Source
const MaxRetainedResults = 64

MaxRetainedResults caps the receipts kept per profile

View Source
const MaxScanChars = 65536

MaxScanChars caps scanned text because the scanners are advisory

View Source
const (
	MaxTaskImages = 8
)
View Source
const MediaCacheMaxAgeHours = 24

MediaCacheMaxAgeHours bounds how long generated media stays synced to remote backends

View Source
const (

	// Phrase of the memory tool failure for an add over the store limit
	MemoryOverLimitPhrase = "exceed the limit"
)
View Source
const ModelCharsPerToken = 4

Characters per token of every rough model estimate, the one ratio provider, media and agent derive theirs from

View Source
const OnboardingPlainIntroNote = "[System note: This is the user's very first message ever. " +
	OnboardingTaskFirstClause +
	"What this note asks: briefly introduce yourself and mention that /help shows " +
	"available commands, in one or two sentences.]"

First contact note when the profile build offer is off or already latched

View Source
const OnboardingTaskFirstClause = "If this message is itself a real request or task, DO THE TASK FIRST -- call " +
	"whatever tools it needs -- and only then, in the closing sentences of that same " +
	"reply, do what this note asks. Never let this note replace or skip work the user " +
	"actually asked for. "

Shared by both first contact notes so a real first message task is never replaced by the intro

View Source
const OneshotDescriptionDelivery = oneshotDescriptionDelivery

OneshotDescriptionDelivery exports the joined delivery paragraph of a one shot delegate_task

View Source
const OneshotSkillsLoadGuidance = "## Skills\n" +
	"Scan the skills below and load one with skill_view(name) only when it carries domain knowledge you lack " +
	"for THIS task (an API, a tool's commands, a project's conventions). Do not load general process skills " +
	"(testing, debugging, review methodology) for work you already know how to do.\n"

OneshotSkillsLoadGuidance replaces the skills coaching in a one shot session prompt

View Source
const (
	OrphanSweepIntervalS = 30.0
)
View Source
const PreExecGuardMinTimeoutS = preExecGuardMinTimeoutS

Minimum seconds the pre exec guard probe waits, the terminal tool floor execute_code shares

View Source
const ProcessCompleteDisplayKind = "process_complete"

ProcessCompleteDisplayKind names the UI row kind of a process completion

View Source
const RedactionUnavailable = "[redaction-unavailable]"

RedactionUnavailable replaces text whose redaction failed on the egress boundary

View Source
const RefusedKey = "refused"

Result key of a call the tool declined before doing anything

View Source
const RelayPluginsConfigEnv = "ICEBATH_NEMO_RELAY_PLUGINS_TOML"

Environment variable selecting an explicit Relay plugins toml file

View Source
const ResultRetentionSeconds = 7 * 24 * time.Hour

ResultRetentionSeconds is how long completed receipts are kept

View Source
const ReviewGoal = "Act as an independent senior reviewer. Thoroughly review the work presented in the conversation excerpt " +
	"provided in your context: investigate any code, pull request, branch, commit, documentation, design, or other " +
	"artifact it references (open the PR, read the diff, run the code or tests where feasible) rather than judging " +
	"from the excerpt alone. Produce a full, structured review: what the work does, whether it is correct and " +
	"complete, concrete defects or risks found (with file/line references where possible), what was verified vs. " +
	"only read, and a clear final verdict with recommended next steps."

Standing instruction of the reviewer subagent

View Source
const RollbackFailedMarker = "ROLLBACK FAILED"

Marker of a skill batch whose rollback failed, the one failure a completion line never hides

View Source
const ScreenshotsDetached = " Screenshots are not attached to this tool's results."

ScreenshotsDetached is the browser_exec description header that says screenshots are not attached

View Source
const SkillLockRecordRefusal = "skills/.usage.json holds the user's skill locks, so the agent cannot change it " +
	"while any skill is locked."

SkillLockRecordRefusal is shown when a command would change the lock record while a skill is locked

View Source
const SkillUnlockRefusal = "Only the user can unlock a skill. Ask them to run `icebath curator unlock <skill>` " +
	"themselves."

SkillUnlockRefusal is shown when the agent tries to unlock a skill itself

View Source
const SpawnEnvVar = "ICEBATH_SPAWN"

SpawnEnvVar carries the spawn tag a spawner stamps on every long lived child

View Source
const SpilloverSQLFilter = "(instr(content, 'spillover') > 0 OR instr(api_content, 'spillover') > 0)"

SpilloverSQLFilter selects transcript rows that may reference a spill archive

View Source
const SpokenTextDefaultMaxChars = 4000

Cap prepare_spoken_text applies when its caller passes no max_chars

View Source
const StaleLockMinAgeSeconds = 10 * 60

Age past which a lock is presumed abandoned, a healthy fetch completes in minutes

View Source
const StaleTmpPackMinAgeSeconds = StaleLockMinAgeSeconds

Age floor of the aborted transfer temp pack sweep

View Source
const StallGuardIdenticalCallThreshold = 3

StallGuardIdenticalCallThreshold is the consecutive identical call count that fires the notice

View Source
const SubmoduleReason = "submodule "

Reason prefix of every submodule verdict

View Source
const TerminalTempMaxIdleHours = 24.0

Hours a terminal temp artifact may sit idle before pruning

View Source
const ToolCallMaxBatchEntries = 10

ToolCallMaxBatchEntries bounds the entries one tool_call batch expands into

View Source
const ToolOutputRiskKey = "_tool_output_risk"

ToolOutputRiskKey stores the advisory risk classification on a tool result message

View Source
const ToolProgressEvent = "tool.progress"

Event kind a running tool's progress reaches the agent's progress callback as

View Source
const VercelSandboxDefaultCwd = "/vercel/sandbox"

VercelSandboxDefaultCwd is the working directory a Vercel sandbox starts in

View Source
const VisionEmbedMaxDimension = 1568

VisionEmbedMaxDimension is the long edge cap for history embeds, Anthropic downsamples to it anyway

View Source
const VisionMaxBase64Bytes = 20 * 1024 * 1024

VisionMaxBase64Bytes is the absolute ceiling for one vision payload, no major provider accepts more

View Source
const VoiceLiveTurnNote = "[Note: this message is a delegation from a live spoken conversation. The text is a voice " +
	"transcript (it may contain mis-hearings, hesitations and later corrections; use the latest " +
	"intent). Your reply will be spoken aloud by a voice model that paraphrases it: answer in plain " +
	"conversational sentences, keep it short (a few sentences unless the user asked for detail), no " +
	"markdown, no lists, no code blocks, no URLs read out character by character. Do the work with " +
	"your tools as usual; only the final facts need to be spoken. Do not claim an action succeeded " +
	"before it actually did.]"

VoiceLiveTurnNote is prepended to the model input of a turn delegated from the live voice layer

View Source
const WorkspaceBlockHeader = "Workspace (snapshot at session start — re-check with `git` before acting on it):"

WorkspaceBlockHeader opens the workspace snapshot in the system prompt

Variables

View Source
var (
	// SupervisedGatewayPid reports whether this launch is a supervised gateway and the live gateway pid, installed by the gateway
	SupervisedGatewayPid func() (supervisedLaunch bool, runningPid int, err error)
	// IsWorkerProcess reports whether this process is a registered per turn worker, installed by the agent runtime
	IsWorkerProcess func() bool
)

Hooks the gateway and the worker runtime install for the registry

View Source
var (
	// SubagentHandoffResolver finds the live subagent record of a task for process handoff, installed by the delegate slice
	SubagentHandoffResolver func(taskID string) SubagentHandoff
	// SubagentAttribution returns the goal and delegation_id of a subagent task for notification provenance
	SubagentAttribution func(taskID string) map[string]any
	// DelegationConfig returns the active delegation config section, installed by the delegate slice
	DelegationConfig func(env *Env) map[string]any
	// DelegationFallbackChain returns the configured fallback chain of a delegation config, installed by pkg/provider
	DelegationFallbackChain func(cfg map[string]any) []map[string]any
	// ModelNotFoundPatterns returns the failover classifier's model not found phrases, installed by provider wiring
	ModelNotFoundPatterns func() []string
	// AsyncDelegationLedger replays and marks durable delegation completions, installed by the delegate slice
	AsyncDelegationLedger AsyncDelegationCompletions
)

Hooks the delegation runtime and the gateway install for completion routing

View Source
var (
	// RuntimeProviderCredentials resolves a provider's live base URL and api key, installed by the provider wiring
	RuntimeProviderCredentials func(ctx context.Context, env *Env, requested, targetModel string) (baseURL, apiKey string, err error)
	// CachedContextLength reads the on disk model metadata cache, installed by the provider wiring
	CachedContextLength func(ctx context.Context, modelID, baseURL string) (int, bool)
	// ModelContextLength runs the full provider aware context window resolver, installed by the provider wiring
	ModelContextLength func(ctx context.Context, q ContextLengthQuery) int
)
View Source
var ActivePolicySource func(ctx context.Context) (source string, ok bool)

ActivePolicySource is the launch policy source of the turn bound to ctx, set by the gateway, false without a policy

View Source
var AgentLoopTools = map[string]bool{"todo_list": true, "memory": true, "session_search": true, "delegate_task": true}

Tools the agent loop intercepts because they need live agent state

Closed vocabulary of bot turn failure reasons

View Source
var ApprovalHookInvoker func(ctx context.Context, hookName string, payload map[string]any) error

ApprovalHookInvoker dispatches plugin lifecycle hooks such as pre_approval_request, set by the binary

View Source
var ArmProcessWatcher func(watcher map[string]any) bool

ArmProcessWatcher hands a watcher to the live gateway loop, installed by the gateway, false when it is not serving

View Source
var AsyncDelegationOwnerProbes struct {
	PidExists        func(pid int) bool
	ProcessStartTime func(pid int) (int64, bool)
}

Ledger owner liveness probes from gateway status, installed by pkg/gateway at init

Reasons a supervisor may retry automatically without human intervention

View Source
var AwakeSeconds = awakeClock()

Seconds the machine has spent awake, the unbiased interrupt time on Windows and the monotonic clock elsewhere

View Source
var BindProfileSecretScope func(ctx context.Context, profileHome string) context.Context

Context bound to the secret scope of a profile home, installed by pkg/provider

View Source
var BotDesktopPublishedEnv func(env *Env) map[string]string

BotDesktopPublishedEnv is the running Bot Desktop seat env of the profile, installed by the desktop package

View Source
var BoundSecretScope func(ctx context.Context) map[string]string

Reader of the secret mapping a context binds, nil when none, installed by pkg/provider

View Source
var BoundSecretScopeHome func(ctx context.Context) string

Home the context's bound secret scope was built for, installed by pkg/provider

View Source
var BuiltinToolNames = func() map[string]bool {
	out := map[string]bool{}
	for _, spec := range Toolsets {
		for _, t := range spec.Tools {
			out[t] = true
		}
	}
	return out
}()

BuiltinToolNames is every tool the static table names before runtime additions

View Source
var BuiltinToolsetNames = func() map[string]bool {
	out := map[string]bool{}
	for name := range Toolsets {
		out[name] = true
	}
	return out
}()

BuiltinToolsetNames is every static toolset name before runtime additions

View Source
var BundledPlatformNames func() []string

BundledPlatformNames lists bundled platform plugin directory names and aliases, installed by pkg/gateway

View Source
var BundledPlatformSecretEnvs func() []string

BundledPlatformSecretEnvs lists the bundled platform plugin manifests' secret names, installed by this package's init

View Source
var CleanupBrowser func(ctx context.Context, env *Env, taskID string) error

Closes the browser sessions serving a task, installed by the browser package init

View Source
var ClientSurfaceToolsets = map[string]bool{"project": true}

ClientSurfaceToolsets are folded in by the TUI for its own sessions, never by config

View Source
var CodingProfile = ContextProfile{Name: "coding", Toolset: CodingToolset, Guidance: CodingAgentGuidance, ModelHint: "coding", CompactSkillCategories: nonCodingSkillCategories}

CodingProfile is the posture inside a code workspace on an interactive surface

View Source
var CodingTools = coreWithout(false, "image_generate", "text_to_speech", "cronjob_manage", "computer_use")

CodingTools is the coding posture, core tools minus messaging, audio, cron, kanban, and computer use

View Source
var ConfigEnvTableKeys func() []string

ConfigEnvTableKeys lists the gateway env override table keys, installed by the gateway package

View Source
var ConfigOnlyToolsets = map[string]bool{"stt": true}

ConfigOnlyToolsets have provider setup but expose no model schemas

View Source
var ConfigurableToolsets = []ConfigurableToolset{
	{"web", "🔍 Web Search & Scraping", "web_search, web_extract"},
	{"browser", "🌐 Browser Automation", "navigate, click, type, scroll"},
	{"terminal", "💻 Terminal & Processes", "terminal, process"},
	{"file", "📁 File Operations", "read, write, patch, search"},
	{"code_execution", "⚡ Code Execution", "execute_code"},
	{"vision", "👁️  Vision / Image Analysis", "vision_analyze"},
	{"video", "🎬 Video Analysis", "video_analyze (requires video-capable model)"},
	{"image_gen", "🎨 Image Generation", "image_generate"},
	{"video_gen", "🎬 Video Generation", "video_generate (text/image/reference)"},
	{"x_search", "🐦 X (Twitter) Search", "x_search (requires xAI OAuth or XAI_API_KEY)"},
	{"tts", "🔊 Text-to-Speech", "text_to_speech"},
	{"stt", "🎙️ Speech-to-Text", "voice transcription (gateway voice messages + voice mode)"},
	{"skills", "📚 Skills", "list, view, manage"},
	{"todo", "📋 Task Planning", "todo_list"},
	{"kanban", "📌 Kanban", "opt-in task board tools for this platform"},
	{"memory", "💾 Memory", "persistent memory across sessions"},
	{"context_engine", "🧩 Context Engine", "runtime tools from the active context engine"},
	{"session_search", "🔎 Session Search", "search past conversations"},
	{"connections", "🔌 Connections", "MCP server install, enable and authorization"},
	{"clarify", "❓ Clarifying Questions", "clarify"},
	{"delegation", "👥 Task Delegation", "delegate_task"},
	{"cronjob", "⏰ Cron Jobs", "create/list/update/pause/resume/run, with optional attached skills"},
	{"discord", "💬 Discord (read/participate)", "fetch messages, search members, create thread"},
	{"discord_admin", "🛡️  Discord Server Admin", "list channels/roles, pin, assign roles"},
	{"yuanbao", "🤖 Yuanbao", "group info, member queries, DM"},
	{"computer_use", "🖱️  Computer Use (macOS/Windows/Linux)", "background desktop control via cua-driver"},
}

ConfigurableToolsets are the toolsets the configurator checklist offers

View Source
var ConnectorKinds = []string{"mcp", "plugin", "skill"}

ConnectorKinds lists every target kind a connection operation carries

View Source
var ContentRuleDescriptions = setOf(
	"upload a secret or credential file via curl/wget (possible exfiltration)",
	"pipe a credential file into a curl/wget upload (possible exfiltration)",
	InvisibleUnicodeDescription,
)

ContentRuleDescriptions describe what a command carries rather than which verb runs it

View Source
var CoreTools = []string{
	"web_search", "web_extract",
	"terminal", "process_manage",
	"read_file", "write_file", "patch", "search_files",
	"vision_analyze", "image_generate",
	"skills_list", "skill_view", "skill_manage",
	"browser_exec",
	"browser_cdp", "browser_dialog",
	"browser_vault",
	"text_to_speech",
	"todo_list", "memory",
	"session_search",
	"clarify",
	"execute_code", "delegate_task",
	"cronjob_manage",
	"kanban_show", "kanban_list",
	"kanban_complete", "kanban_block", "kanban_request_review",
	"kanban_request_changes",
	"kanban_heartbeat",
	"kanban_comment", "kanban_create", "kanban_link",
	"kanban_unblock",
	"kanban_attach", "kanban_attach_url", "kanban_attachments",
	"computer_use",
	"manage_connections",
}

CoreTools is the shared tool list every platform bundle inherits

View Source
var DangerousPatterns = []DangerPattern{}/* 110 elements not displayed */

DangerousPatterns require approval before the command runs

View Source
var Default = NewRegistry()

Default is the process wide registry every tool file registers into at init

View Source
var DefaultBudget = BudgetConfig{
	DefaultResultSize: DefaultResultSizeChars,
	TurnBudget:        DefaultTurnBudgetChars,
	PreviewSize:       DefaultPreviewSizeChars,
	MCPResultSize:     DefaultMCPResultSizeChars,
}

DefaultBudget matches the historical hardcoded behavior exactly

View Source
var DefaultDispatcher = NewDispatcher(Default)

DefaultDispatcher carries the process wide plugin hooks and middleware over the default registry

View Source
var DefaultOffToolsets = map[string]bool{"spotify": true, "discord": true, "discord_admin": true, "video": true, "video_gen": true, "x_search": true, "a2a": true, "kanban": true}

DefaultOffToolsets are off for new installs until a user enables them

View Source
var DelegateServiceTierHooks struct {
	ParseExactServiceTier    func(raw string) (string, error)
	IsStaticTier             func(tier string) bool
	ResolveFastModeOverrides func(model, providerName, baseURL, tier string) map[string]any
	UltrafastOffered         func(model, providerName, baseURL, accessToken string) (bool, error)
}

Provider side speed tier gates pkg/agent installs at init from pkg/provider

View Source
var DelegateTask func(ctx context.Context, env *Env, req DelegateTaskRequest) string

delegate_task entry point the tools delegation slice seven assigns at init

View Source
var DelegateTaskSchema = Dict(
	"name", "delegate_task",
	"description", "Spawn one or more subagents in isolated contexts. "+
		"Description is rebuilt at every get_definitions() call to reflect the user's current delegation limits.",
	"parameters", Dict(
		"type", "object",
		"properties", Dict(
			"tasks", Dict(
				"type", "array",
				"minItems", 1,
				"items", Dict(
					"type", "object",
					"properties", Dict(
						"goal", delegateParam("string",
							"What this subagent should accomplish. Be specific and self-contained — it knows "+
								"nothing about your conversation history.", nil),
						"context", delegateParam("string",
							"Background THIS child needs: file paths, error messages, constraints. Each child "+
								"sees only its own context — repeat shared background in every task that needs it.", nil),
						"output_schema", delegateParam("object",
							"Optional JSON Schema this child's final answer must validate against (told to the "+
								"child up front; parent validates with one bounded correction retry; result gains "+
								"schema_valid, plus schema_errors on failure — the child's raw text is still returned "+
								"as summary, never discarded). Keep it forgiving — require only fields you will read.", nil),
						"images", delegateParam("array",
							"Optional images this child must SEE (max 8): local file paths or http(s) URLs — e.g. a "+
								"screenshot the user sent, a design mock, a chart. Vision-capable children receive the "+
								"pixels on their first turn; non-vision children get path hints for vision_analyze. Text "+
								"files do NOT belong here — put paths in 'context' instead.",
							Dict("items", Dict("type", "string"))),
						"group", delegateParam("string",
							"Optional result-delivery bucket within this call (only when delegation.independent_completions "+
								"is enabled; otherwise the whole call returns as one message). Tasks sharing a group return "+
								"together in ONE message; ungrouped tasks return individually as each finishes. This does not "+
								"order execution; if B needs A's output, dispatch B after A returns.", nil),
					),
					"required", []any{"goal"},
				),
				"description", "(rebuilt at get_definitions() time)",
			),
			"action", delegateParam("string",
				"Default 'spawn'. Live control of running children: "+
					"'list' = ids/goals/status/transcripts; 'steer' = queue "+
					"course-correction text into one child (subagent_id + "+
					"message) without stopping it; 'stop' = end one child "+
					"early (subagent_id; partial result still returns). "+
					"Control actions return immediately; goal/tasks are ignored unless spawning.",
				Dict("enum", []any{"spawn", "list", "steer", "stop"})),
			"subagent_id", delegateParam("string", "Target for action='steer'/'stop' (ids from the spawn response or action='list').", nil),
			"message", delegateParam("string",
				"For action='steer': the course correction, appended to "+
					"the child's next tool result mid-run. Be directive and specific.", nil),
		),
		"required", []any{},
	),
)

Static delegate_task schema whose descriptions every definition build rewrites to the user limits

View Source
var DelegationBackendHooks struct {
	ListProviders        func(ctx context.Context) []DelegationProvider
	RefreshAgentMCPTools func(ctx context.Context, a DelegationRebuildAgent, quietMode, contentAware bool)
}

Wiring the provider and mcp lanes install, each panics when unassigned

View Source
var DelegationRegistryHooks struct {
	GetProvider     func(ctx context.Context, name string) DelegationProvider
	DisabledPlugins func(h string) map[string]bool
	LoadBundled     func(ctx context.Context, name string, register func(DelegationProvider)) bool
	DiscoverPlugins func(ctx context.Context, force bool)
	ListProviders   func(ctx context.Context) []DelegationProvider
}

Wiring the provider and plugins lanes install, each panics when unassigned

View Source
var DiscordAPIBase = "https://discord.com/api/v10"

Discord REST base URL, a seam tests point at a local stand in

View Source
var Distributions = map[string]Distribution{
	"default":        dist("All available tools, all the time", "web", 100, "vision", 100, "image_gen", 100, "terminal", 100, "file", 100, "browser", 100),
	"image_gen":      dist("Heavy focus on image generation with vision and web support", "image_gen", 90, "vision", 90, "web", 55, "terminal", 45),
	"research":       dist("Web research with vision analysis and reasoning", "web", 90, "browser", 70, "vision", 50, "terminal", 10),
	"science":        dist("Scientific research with web, terminal, file, and browser capabilities", "web", 94, "terminal", 94, "file", 94, "vision", 65, "browser", 50, "image_gen", 15),
	"development":    dist("Terminal, file tools, and reasoning with occasional web lookup", "terminal", 80, "file", 80, "web", 30, "vision", 10),
	"safe":           dist("All tools except terminal for safety", "web", 80, "browser", 70, "vision", 60, "image_gen", 60),
	"balanced":       dist("Equal probability of all toolsets", "web", 50, "vision", 50, "image_gen", 50, "terminal", 50, "file", 50, "browser", 50),
	"minimal":        dist("Only web tools for basic research", "web", 100),
	"terminal_only":  dist("Terminal and file tools for code execution tasks", "terminal", 100, "file", 100),
	"terminal_web":   dist("Terminal and file tools with web search for documentation lookup", "terminal", 100, "file", 100, "web", 100),
	"creative":       dist("Image generation and vision analysis focus", "image_gen", 90, "vision", 90, "web", 30),
	"reasoning":      dist("Heavy research/reasoning distribution with minimal other tools", "web", 90, "file", 60, "terminal", 20),
	"browser_use":    dist("Full browser-based web interaction with search, vision, and page control", "browser", 100, "web", 80, "vision", 70),
	"browser_only":   dist("Only browser automation tools for pure web interaction tasks", "browser", 100),
	"browser_tasks":  dist("Browser-focused distribution with web_search for finding URLs (Google blocks direct browser searches)", "browser+search", 97, "vision", 12, "terminal", 15),
	"terminal_tasks": dist("Terminal-focused distribution with high terminal/file availability, occasional other tools", "terminal", 97, "file", 97, "web", 97, "browser", 75, "vision", 50, "image_gen", 10),
	"mixed_tasks":    dist("Mixed distribution with high browser, terminal, and file availability for complex tasks", "browser", 92, "terminal", 92, "file", 92, "web", 35, "vision", 15, "image_gen", 15),
}

Distributions are the batch data generation toolset distributions

View Source
var EnsurePluginsDiscovered func(ctx context.Context) error

EnsurePluginsDiscovered runs idempotent plugin discovery for the profile home of a ctx, installed by the plugins package

View Source
var ErrBackendRequirementsNotMet = errors.New("backend requirements not met")

Error a backend requirements check returns when the provider contract answered False

View Source
var ErrCaptureTimeout = errors.New("command timed out")

ErrCaptureTimeout reports a captured CLI child that ran past its deadline

View Source
var ErrEventLoopClosed = errors.New("Event loop is closed")

Scheduling failure asyncio reports for a loop that already closed

View Source
var ErrFutureCancelled = errors.New("future cancelled")

ErrFutureCancelled is returned by a future that was cancelled before it ran

View Source
var ErrKeyboardInterrupt = errors.New("keyboard interrupt")

Cause the SIGINT handler cancels the turn context with, returned up the dispatch chain like Python KeyboardInterrupt

View Source
var ErrLoopIsNone = errors.New("loop is None")

Scheduling failure of a missing loop

View Source
var ErrOverrideDenied = errors.New("plugin override denied")

ErrOverrideDenied reports a plugin override attempt without operator opt in

View Source
var ErrPoolShutdown = errors.New("cannot schedule new futures after shutdown")

ErrPoolShutdown is returned by Submit once the pool was shut down

View Source
var ErrRegistrationRejected = errors.New("tool registration rejected")

ErrRegistrationRejected marks a registration the registry refused and already logged at error level

View Source
var ErrRelayBindingMissing = errors.New("the Relay runtime binding is not installed")

ErrRelayBindingMissing is the failure of a process that has no Relay runtime binding to load

View Source
var ErrUnscopedSecret = errors.New("secret read without a bound profile scope while profile multiplexing is active")

ErrUnscopedSecret is returned when a multiplexing process reads a secret without a bound profile scope

View Source
var FailureCauseGlossTable = map[string]string{
	"timeout":                 "the AI model service did not respond in time",
	"rate_limit":              "the AI model service was rate-limited (too many requests)",
	"upstream_rate_limit":     "the AI model service was rate-limited (too many requests)",
	"overloaded":              "the AI model service is overloaded right now",
	"server_error":            "the AI model service returned an internal error",
	"billing":                 "the AI model service says the account's usage or credit limit is reached",
	"billing_unverified":      "the AI model service says the account's usage or credit limit is reached",
	"auth":                    "the AI model service rejected the sign-in",
	"auth_permanent":          "the AI model service rejected the sign-in",
	"upstream_blocked":        "a firewall/CDN in front of the AI model service blocked the request",
	"model_not_found":         "the model {subject} uses was not found at the AI model service",
	"content_policy_blocked":  "the AI model service's safety filter rejected the request",
	"provider_policy_blocked": "the AI model service refused the request because of a policy on the account",
	"data_policy_denied":      "{possessive} context holds a connected-app result that needs a model that does not train on data",
	"context_overflow":        "{possessive} request grew too large for the model",
	"payload_too_large":       "{possessive} request grew too large for the model",
}

FailureCauseGlossTable maps a classified failure reason or site code to one plain clause naming what happened

View Source
var FailureTolerantToolNames = map[string]bool{
	"terminal": true, "execute_code": true, "process_manage": true, "process": true, "browser_navigate": true, "web_extract": true,
}

Tools whose failure is normal work output

View Source
var FileMutatingToolNames = map[string]bool{"write_file": true, "patch": true}
View Source
var FindSkillDir func(env *Env, name string) string

Installed skill directory lookup by name, registered by the skills package at init

View Source
var FiniteTurnRequired func(env *Env) (bool, bool) = FiniteTurnFlag

FiniteTurnRequired reports the admitted turn's finite flag and whether one is known, the env flag by default

View Source
var GatewayPluginToolsets func() ([]ConfigurableToolset, map[string]bool, bool)

GatewayPluginToolsets is the projected plugin toolsets and portable MCP servers a gateway backed CLI installs

View Source
var GeneralProfile = ContextProfile{Name: "general"}

GeneralProfile is the posture outside code workspaces

View Source
var GitlockRunGit func(ctx context.Context, gitCmd, args []string, o pysubprocess.Options) (*pysubprocess.Completed, error)

Updater git runner update_custody.run_git, pkg/selfupdate installs its RunGit here at init

View Source
var HardlinePatterns = []DangerPattern{
	{rmFlagPrefix + hardlineRmPath(`/(?:(?:\.\.?)?/)*(?:\.\.?)?\**|/ \*`), "recursive delete of root filesystem"},
	{rmFlagPrefix + hardlineRmPath(hardlineSystemDirs), "recursive delete of system directory"},
	{rmFlagPrefix + hardlineRmPath(`(?:~|\$\{?HOME\}?)(?:/?|/\*)?`), "recursive delete of home directory"},
	{cmdPos + `mkfs(\.[a-z0-9]+)?\b`, "format filesystem (mkfs)"},
	{cmdPos + `dd\b[^\n]*\bof=/dev/(sd|nvme|hd|mmcblk|vd|xvd)[a-z0-9]*`, "dd to raw block device"},
	{`>\s*/dev/(sd|nvme|hd|mmcblk|vd|xvd)[a-z0-9]*\b`, "redirect to raw block device"},
	{`:\(\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:`, "fork bomb"},
	{cmdPos + `kill\s+(-[^\s]+\s+)*-1\b`, "kill all processes"},
	{cmdPos + `(shutdown|reboot|halt|poweroff)\b`, "system shutdown/reboot"},
	{cmdPos + `init\s+[06]\b`, "init 0/6 (shutdown/reboot)"},
	{cmdPos + `systemctl\s+(poweroff|reboot|halt|kexec)\b`, "systemctl poweroff/reboot"},
	{cmdPos + `telinit\s+[06]\b`, "telinit 0/6 (shutdown/reboot)"},
}

HardlinePatterns never run through the agent regardless of yolo or approval mode

View Source
var HousekeepingTools = map[string]bool{"memory": true, "todo_list": true, "skill_manage": true, "session_search": true}

Rounds made only of these mute tool progress

View Source
var IdempotentToolNames = map[string]bool{
	"read_file": true, "search_files": true, "web_search": true, "web_extract": true, "session_search": true,
	"skill_view": true, "skills_list": true, "browser_snapshot": true, "browser_console": true,
	"browser_get_images": true, "mcp_filesystem_read_file": true, "mcp_filesystem_read_text_file": true,
	"mcp_filesystem_read_multiple_files": true, "mcp_filesystem_list_directory": true,
	"mcp_filesystem_list_directory_with_sizes": true, "mcp_filesystem_directory_tree": true,
	"mcp_filesystem_get_file_info": true, "mcp_filesystem_search_files": true,
}
View Source
var InvisibleChars = map[rune]bool{
	'\u200b': true,
	'\u200c': true,
	'\u200d': true,
	'\u2060': true,
	'\u2062': true,
	'\u2063': true,
	'\u2064': true,
	'\ufeff': true,
	'\u202a': true,
	'\u202b': true,
	'\u202c': true,
	'\u202d': true,
	'\u202e': true,
	'\u2066': true,
	'\u2067': true,
	'\u2068': true,
	'\u2069': true,
}

InvisibleChars are the zero width and bidirectional code points used in injection attacks

View Source
var IsHeadedMode func(env *Env) bool

Reports browser.headed, installed by the browser package init

View Source
var KanbanHomeResolver func(env *Env) string

KanbanHomeResolver names the board root this lineage lives under, installed by the kanban package

View Source
var LaunchBodySecretScope func(ctx context.Context) map[string]string

Launch mapping of a body entered before multiplexing began, nil outside one, installed by pkg/provider

View Source
var LeftCorePlatforms func() []string

LeftCorePlatforms lists the platforms that left core for a catalog plugin, installed by the provider slice

View Source
var LegacyRelayExportEnvVars = []string{
	"ICEBATH_NEMO_RELAY_ATOF_ENABLED",
	"ICEBATH_NEMO_RELAY_ATOF_OUTPUT_DIRECTORY",
	"ICEBATH_NEMO_RELAY_ATOF_FILENAME",
	"ICEBATH_NEMO_RELAY_ATOF_MODE",
	"ICEBATH_NEMO_RELAY_ATIF_ENABLED",
	"ICEBATH_NEMO_RELAY_ATIF_OUTPUT_DIRECTORY",
	"ICEBATH_NEMO_RELAY_ATIF_FILENAME_TEMPLATE",
	"ICEBATH_NEMO_RELAY_ATIF_AGENT_NAME",
	"ICEBATH_NEMO_RELAY_ATIF_AGENT_VERSION",
	"ICEBATH_NEMO_RELAY_ATIF_EXPORT_TIMEOUT_S",
	"ICEBATH_NEMO_RELAY_ATIF_MODEL_NAME",
	"ICEBATH_NEMO_RELAY_ATIF_SUBAGENT_EXPORT_MODE",
}

Exporter variables of the removed relay plugin that no longer configure Relay

View Source
var LegacyToolsetMap = map[string][]string{
	"web_tools":      {"web_search", "web_extract"},
	"terminal_tools": {"terminal"},
	"vision_tools":   {"vision_analyze"},
	"image_tools":    {"image_generate"},
	"skills_tools":   {"skills_list", "skill_view", "skill_manage"},
	"cronjob_tools":  {"cronjob_manage"},
	"file_tools":     {"read_file", "write_file", "patch", "search_files"},
	"tts_tools":      {"text_to_speech"},
}

LegacyToolsetMap maps retired tools suffixed names onto their tool lists

View Source
var LoadCLIConfig func(ctx context.Context) map[string]any

Process wide legacy CLI config, set by the binary, read only under ICEBATH_IGNORE_USER_CONFIG=1

View Source
var LockNames = []string{"shallow.lock", "index.lock", "HEAD.lock", "MERGE_HEAD.lock"}

Interrupted git operation locks the stale sweep removes from a checkout

View Source
var MCPActions = []string{"install", "enable", "authorize"}

MCPActions are the manage_connections actions, each over MCP servers of the bundled catalog or the config

View Source
var MCPOperationRunner func(ctx context.Context, env *Env, names []string, action string, opts MCPOperationOptions) string

MCPOperationRunner runs manage_connections over MCP servers, installed by pkg/mcp

View Source
var MCPToolParallelSafe = func(ctx context.Context, toolName string) bool { return false }

MCPToolParallelSafe reports whether an MCP tool's server opted into parallel calls, set by pkg/mcp

View Source
var MCPTransferSession func(oldKey, newKey string)

MCPTransferSession moves a chat's MCP spend total to a new session key, registered by the mcp package

View Source
var MCPUnavailableDetails func(server string) (sentence string, declared bool, ok bool)

MCPUnavailableDetails reports the unavailability sentence of a declared MCP server, set by pkg/mcp

View Source
var ManageConnectionsSchema = Dict(
	"name", "manage_connections",
	"description", "Connect the user to MCP servers: a server from the bundled catalog or one already in the user's "+
		"mcp_servers config, each with its own credentials and OAuth. 'install' adds a catalog entry, "+
		"'enable' re-enables a disabled configured server, 'authorize' runs its OAuth. Pass SEVERAL names in one call. "+
		"In the terminal UI the call shows the user an approval card and blocks until "+
		"every server is connected, skipped, or the deadline passes. Where no card exists (a one-shot run, a "+
		"scheduled job, a messaging platform) each target runs at once and the result says what happened, with a "+
		"link for the USER to open in a browser when one is needed (never open it yourself). Never hand-edit "+
		"mcp_servers config — always use this tool. After a skip or a timeout, do not re-ask on "+
		"your own: continue without the server or ask in chat. A later request from the USER for that "+
		"same server is not a re-ask — run it. A connected server's tools are named in the result and are "+
		"callable at once through tool_describe/tool_call. This tool can NOT remove a server or revoke its "+
		"authorization — that is deliberately user-only: direct the user to `icebath mcp`.",
	"parameters", Dict(
		"type", "object",
		"properties", Dict(
			"action", Dict(
				"type", "string",
				"enum", connActionEnum(),
				"description", "install takes catalog entry names; enable and authorize take configured server names.",
			),
			"connectors", Dict(
				"type", "array",
				"items", Dict(
					"anyOf", []any{
						Dict("type", "string"),
						Dict(
							"type", "object",
							"properties", Dict("name", Dict("type", "string")),
							"required", []any{"name"},
							"additionalProperties", false,
						),
					},
				),
				"description", "The MCP server names, e.g. [\"linear\", \"deepwiki\"].",
			),
		),
		"required", []any{"action", "connectors"},
	),
)

ManageConnectionsSchema is the manage_connections tool schema the model sees

View Source
var MarkBackgroundReviewSkillRead func(env *Env, resolved string)

Records a full skill file read for the review fork guard, registered by the skills package

View Source
var MaxSafeTimeoutSeconds = func() float64 {
	if runtime.GOOS == "windows" {
		return float64(0xFFFFFFFF-1000) / 1000.0
	}
	return 31536000.0
}()

Longest wait every platform can express, DWORD milliseconds on Windows and one year elsewhere

View Source
var MutatingToolNames = map[string]bool{
	"terminal": true, "execute_code": true, "write_file": true, "patch": true, "todo_list": true, "memory": true,
	"skill_manage": true, "browser_click": true, "browser_type": true, "browser_press": true,
	"browser_scroll": true, "browser_navigate": true, "send_message": true, "cronjob_manage": true,
	"delegate_task": true, "process_manage": true,
}
View Source
var NeutralFailureTools = map[string]bool{"skill_manage": true}

Tools whose refused calls render neutrally because the agent replans them itself

View Source
var NeverParallelTools = map[string]bool{"clarify": true, "manage_connections": true}

Interactive tools never run concurrently

View Source
var NoDriverDiffFlags = []string{"--no-ext-diff", "--no-textconv"}

NoDriverDiffFlags disable attribute scoped diff drivers on rendered diffs

View Source
var NoEffectToolNames = map[string]bool{
	"read_file": true, "search_files": true, "session_search": true, "skill_view": true, "skills_list": true,
	"web_extract": true, "web_search": true, "vision_analyze": true, "browser_snapshot": true,
	"browser_get_images": true, "browser_console": true,
}

Tools whose interrupted execution is safe to discard because they mutate nothing

View Source
var NonMessagingSessionSurfaces = map[string]bool{
	"": true, "api_server": true, "cli": true, "codex": true, state.ClientHistorySource: true, "gateway": true, "kanban": true,
	"local": true, "msgraph_webhook": true, "tool": true, "tui": true, "webhook": true,
}

Surfaces with no human chat thread, matching gateway session_context NON_MESSAGING_SESSION_SURFACES

View Source
var ObjectStoreLockNames = []string{
	"objects/info/commit-graph.lock",
	"objects/info/commit-graphs/commit-graph-chain.lock",
	"objects/pack/multi-pack-index.lock",
	"objects/pack/multi-pack-index.d/multi-pack-index-chain.lock",
}

Object store index locks a killed git leaves, each one failing every later write of its file

View Source
var OneshotDisabledToolsets = []string{"clarify"}

OneshotDisabledToolsets are the toolsets nobody is present to use in a one shot session

View Source
var OperationDeadlineSeconds = 600.0

OperationDeadlineSeconds bounds every connection operation, swapped by tests

View Source
var OperationOnChange func(op *ConnectionOperation, change, snapshot *pyjson.Object)

OperationOnChange receives every frame of every attached operation, the class level renderer hook

View Source
var OpusVoicePlatforms = map[string]bool{"telegram": true, "matrix": true, "feishu": true, "whatsapp": true, "signal": true}

Platforms whose native voice bubble delivery needs Ogg Opus because MP3 renders broken there

View Source
var OwnProcessGroupsFn = func(pgids []int) { ownProcessGroups(pgids) }

OwnProcessGroupsFn makes process groups die with this process, swappable so a test observes the call

View Source
var PackageRoot = config.GetProjectRoot()

PackageRoot is the running install tree the context discovery fallback guards, resolved once at startup

View Source
var ParallelSafeTools = map[string]bool{
	"connectors__execute": true, "image_generate": true, "read_file": true, "search_files": true, "session_search": true,
	"skill_view": true, "skills_list": true, "vision_analyze": true, "web_extract": true, "web_search": true,
}

Read only tools with no shared mutable session state

View Source
var PathScopedReaders = map[string]bool{"read_file": true, "search_files": true}
View Source
var PathScopedWriters = map[string]bool{"write_file": true, "patch": true}
View Source
var PinnedThresholds = map[string]int{"read_file": BudgetUnlimited}

Never overridden thresholds, read_file unlimited prevents persist read persist loops

View Source
var PlatformRegistered = func(name string) bool {
	return RegisteredPlatformNames != nil && containsString(RegisteredPlatformNames(), name)
}

PlatformRegistered reports whether a plugin platform of this name is loaded through the gateway names hook

View Source
var PlatformSecretEnvSuffixes = []string{"_TOKEN", "_SECRET", "_KEY", "_PASSWORD", "_JSON"}

PlatformSecretEnvSuffixes mark gateway env override keys that hold secrets

View Source
var Platforms = []struct {
	Key  string
	Info PlatformInfo
}{
	{"cli", PlatformInfo{"CLI", "icebath-cli"}},
	{"telegram", PlatformInfo{"Telegram", "icebath-telegram"}},
	{"discord", PlatformInfo{"Discord", "icebath-discord"}},
	{"slack", PlatformInfo{"Slack", "icebath-slack"}},
	{"whatsapp", PlatformInfo{"WhatsApp", "icebath-whatsapp"}},
	{"whatsapp_cloud", PlatformInfo{"WhatsApp Business (Cloud)", "icebath-whatsapp"}},
	{"signal", PlatformInfo{"Signal", "icebath-signal"}},
	{"bluebubbles", PlatformInfo{"BlueBubbles", "icebath-bluebubbles"}},
	{"email", PlatformInfo{"Email", "icebath-email"}},
	{"mattermost", PlatformInfo{"Mattermost", "icebath-mattermost"}},
	{"matrix", PlatformInfo{"Matrix", "icebath-matrix"}},
	{"dingtalk", PlatformInfo{"DingTalk", "icebath-dingtalk"}},
	{"feishu", PlatformInfo{"Feishu", "icebath-feishu"}},
	{"wecom", PlatformInfo{"WeCom", "icebath-wecom"}},
	{"wecom_callback", PlatformInfo{"WeCom Callback", "icebath-wecom-callback"}},
	{"weixin", PlatformInfo{"Weixin", "icebath-weixin"}},
	{"qqbot", PlatformInfo{"QQBot", "icebath-qqbot"}},
	{"yuanbao", PlatformInfo{"Yuanbao", "icebath-yuanbao"}},
	{"webhook", PlatformInfo{"Webhook", "icebath-webhook"}},
	{"api_server", PlatformInfo{"API Server", "icebath-api-server"}},
	{"cron", PlatformInfo{"Cron", "icebath-cron"}},
}

Platforms is the ordered platform registry the tool configurator serves

View Source
var PluginToolsetCatalog struct {
	Discover       func(ctx context.Context)
	Toolsets       func(ctx context.Context) []ConfigurableToolset
	KeysNowait     func(ctx context.Context) map[string]bool
	PortableNowait func(ctx context.Context) map[string]bool
}

PluginToolsetCatalog is the plugin toolset source pkg/plugins installs at init

View Source
var PrimaryArgs = map[string]string{
	"terminal": "command", "web_search": "query", "web_extract": "urls", "read_file": "path",
	"write_file": "path", "patch": "path", "search_files": "pattern", "browser_navigate": "url",
	"browser_click": "ref", "browser_type": "text", "image_generate": "prompt", "text_to_speech": "text",
	"vision_analyze": "question", "skill_view": "name", "skills_list": "category", "cronjob_manage": "action",
	"execute_code": "code", "browser_exec": "code", "delegate_task": "goal",
	"skill_manage": "name",
}

PrimaryArgs maps each core tool to the argument its preview shows

View Source
var ProcessSchema = Dict(
	"name", "process_manage",
	"description", "Poll, wait on, send input to, or kill terminal(background=true) processes. "+
		"Completed results remain retrievable by session_id when resuming their owning conversation "+
		"(up to 7 days, newest 64 results per profile; rolling output tail). "+
		"poll: status + new output. log: full output, paged. wait: block "+
		"until exit or timeout (partial output on timeout). write vs "+
		"submit: submit appends Enter — use it to answer prompts; write "+
		"sends raw bytes, no newline. close: EOF stdin. kill: terminate. "+
		"handoff (subagents only): transfer a running process you started to your parent agent, which then "+
		"receives its completion; `data` = one sentence on its purpose. Subagent-owned processes are otherwise "+
		"killed when the subagent finishes and their notifications never reach the parent.",
	"parameters", Dict(
		"type", "object",
		"properties", Dict(
			"action", Dict(
				"type", "string",
				"enum", []any{"list", "poll", "log", "wait", "kill", "write", "submit", "close", "handoff"},
			),
			"session_id", Dict(
				"type", "string",
				"description", "From terminal background output; any unique prefix works ('4dae' for proc_4dae56ca81f6). Required except for 'list'.",
			),
			"data", Dict(
				"type", "string",
				"description", "Stdin text for write/submit; purpose sentence for handoff.",
			),
			"timeout", Dict(
				"type", "integer",
				"description", "Max seconds for 'wait'.",
				"minimum", 1,
			),
			"offset", Dict(
				"type", "integer",
				"description", "Log line offset (default: last 200).",
			),
			"limit", Dict(
				"type", "integer",
				"description", "Max log lines.",
				"minimum", 1,
			),
		),
		"required", []any{"action"},
	),
)

ProcessSchema is the exact process_manage function schema

View Source
var ProfileStoreHooks struct {
	ActiveName func(ctx context.Context) string
	Normalize  func(name string) (string, error)
	Validate   func(name string) error
	Exists     func(name string) bool
	Dir        func(name string) (string, error)
}

ProfileStoreHooks resolve profile names and homes for cross profile reads, assigned by pkg/profiles at init

View Source
var ProgressResetToolNames = map[string]bool{
	"write_file": true, "patch": true, "terminal": true, "execute_code": true, "browser_click": true,
	"browser_type": true, "browser_press": true, "browser_navigate": true, "process_manage": true,
	"process": true, "delegate_task": true, "send_message": true, "cronjob": true, "cronjob_manage": true,
	"todo": true, "todo_list": true, "memory": true, "skill_manage": true,
}

A success on one of these marks progress for every failing signature this turn

View Source
var ProjectBoardWorkdirBinder func(ctx context.Context, board, primaryPath string) error

Points a bound kanban board's default workdir at a project's primary repo, installed by cmd/icebath over pkg/kanban

View Source
var PrunedToolArgumentsMessage = "Tool was not executed because effect-capable arguments contain an Icebath context-compression artifact. " +
	"Recover the exact content from its durable source or re-read it, then issue a complete new call; " +
	"do not retry these arguments. To remove a marker that already landed in a file, match it by its " +
	strings.Trim(CompressionMarkerPrefix, "⟪:") + " prefix (e.g. a terminal sed on that line) instead of quoting the full marker."

PrunedToolArgumentsMessage explains why a call carrying a compression marker was refused

View Source
var ReadContextFileText = readTextFile

File reader the timed context read runs, swapped by tests for a read that blocks

View Source
var RecentlyShippedToolsets = map[string]bool{}

RecentlyShippedToolsets ship on by default for saved lists that predate them

View Source
var RegisterChildFn = func(ctx context.Context, pid int, purpose, projectRoot string) bool {
	return RegisterChild(ctx, pid, purpose, projectRoot)
}

RegisterChildFn records an owned child in the spawn ledger, swappable so a test observes the record

View Source
var RegisteredAdapterSecretEnv func(env *Env) map[string]bool

RegisteredAdapterSecretEnv lists secrets declared by registered and profile installed platform plugins

View Source
var RegisteredPlatformNames func() []string

RegisteredPlatformNames lists plugin platforms loaded at runtime, installed by the gateway package

Process wide conversation and turn coordinator

View Source
var RelayHosts = NewRelayHostRegistry()

Process wide host registry

View Source
var RelayScopeOpTimeout = 10.0

Seconds a native scope op gating turn or session completion may run before it is abandoned

View Source
var ReleaseComputerUseSession func(ctx context.Context, sessionID string) bool

Releases one session owned computer_use backend, installed by the codeexec package init

View Source
var ReleaseProcessGroupsFn = func(pgids []int) { releaseProcessGroups(pgids) }

ReleaseProcessGroupsFn stops covering process groups this process stopped, swappable so a test observes the call

View Source
var RemovedBackends = map[string]map[string]string{}

RemovedBackends explains backends that used to ship in tree

View Source
var ReservedTaskParameters = map[string]bool{
	"goal": true, "context": true, "index": true, "output_schema": true, "images": true, "group": true, "role": true,
	"toolsets": true, "acp_command": true, "acp_args": true, "provider": true, "model": true, "base_url": true,
	"api_key": true, "api_mode": true,
}

Task fields core owns that a delegation provider may never declare as its own task parameter

View Source
var ResolveSkillDir func(env *Env, name, category string) string

Skill directory a create action targets, the skills package installs it

View Source
var RetainWorktreeForSession = retainWorktreeForSession

Relocks a tree an exiting launcher retains under the session that uses it, the name tests replace

View Source
var RoomApprovalMode func(env *Env) (string, bool)

RoomApprovalMode reports a hosted room execution policy's approval mode when one governs the turn

View Source
var RouteKeys = map[string]bool{
	"model": true, "provider": true, "base_url": true, "api_key": true, "api_mode": true, "request_overrides": true,
	"reasoning_effort": true, "service_tier": true, "fallback_providers": true, "profile": true, "label": true,
}

Keys a provider route may carry, every other key of its answer is dropped

View Source
var SearchPruneDirNames = setOf(
	".git", ".hg", ".svn",
	"node_modules", "venv", ".venv", "site-packages", "dist-packages",
	"vendor", "third_party",
	"build", "dist", "target", "out", "coverage",
	".next", ".turbo", ".parcel-cache", ".nuxt", ".svelte-kit",
	".archive",
	"__pycache__", ".cache", ".Trash", ".tox", ".nox", ".mypy_cache",
	".pytest_cache", ".ruff_cache", ".npm", ".yarn", ".pnpm-store",
	".gradle", ".m2", ".nuget",
	"backups", "backup", ".backups",
)

Directory names of dependency, build, cache, VCS and backup trees that broad recursive scans skip

View Source
var SecretHeaderNameList = []string{"x-api-key", "x-goog-api-key", "api-key", "apikey", "x-api-token", "x-auth-token", "x-access-token"}

Header names that carry API credentials and are redacted from MCP displays

View Source
var SessionContextEnvVars = []string{
	"ICEBATH_SESSION_PLATFORM", "ICEBATH_SESSION_SOURCE", "ICEBATH_SESSION_CHAT_ID",
	"ICEBATH_SESSION_CHAT_TYPE", "ICEBATH_SESSION_CHAT_NAME", "ICEBATH_SESSION_THREAD_ID",
	"ICEBATH_SESSION_USER_ID", "ICEBATH_SESSION_USER_ID_ALT", "ICEBATH_SESSION_USER_NAME",
	"ICEBATH_SESSION_SCOPE_ID", "ICEBATH_SESSION_KEY", "ICEBATH_SESSION_ID",
	"ICEBATH_UI_SESSION_ID", "ICEBATH_SESSION_MESSAGE_ID", "ICEBATH_SESSION_PROFILE",
	"ICEBATH_CRON_SESSION", "ICEBATH_SESSION_PARENT_CHAT_ID",
	"ICEBATH_CRON_AUTO_DELIVER_PLATFORM", "ICEBATH_CRON_AUTO_DELIVER_CHAT_ID", "ICEBATH_CRON_AUTO_DELIVER_THREAD_ID",
}

Session variables the gateway bridges freshly onto every command's process environment

View Source
var SessionToolEnv func(env *Env) map[string]string

Bound client tool environment for code execution children, installed by the agent package and nil until then

View Source
var SessionToolchainEnviron func(env *Env, base map[string]string) map[string]string

SessionToolchainEnviron replaces the daemon's toolchain with the bound client's, installed by the agent package

Every SettleReason member in declaration order

View Source
var SideAgentToolDrops = map[string]bool{"manage_connections": true}

SideAgentToolDrops are the tools a delegated side agent never sees, only the main agent draws connection cards

View Source
var SiteCopyTable = func() map[string]string {
	out := make(map[string]string, len(failureCodeCopy)+len(oneOffCopy))
	for k, v := range failureCodeCopy {
		out[k] = v
	}
	for k, v := range oneOffCopy {
		out[k] = v
	}
	return out
}()

SiteCopyTable is the chat copy for every failure code and one off loop outcome a loop site renders

View Source
var StallGuardRepeatableTools = map[string]bool{"process_manage": true}

Pollers legitimately re invoked with identical args

View Source
var SupportedVercelRuntimes = []string{"node24", "node22", "python3.13"}

SupportedVercelRuntimes lists the runtimes the Vercel sandbox backend accepts

Every TargetState member in declaration order

View Source
var TerminalOutputTransformHook func(ctx context.Context, payload map[string]any) []any

TerminalOutputTransformHook runs the transform_terminal_output lifecycle hook, set by the binary, first string wins

View Source
var TerminalProviderReasons = map[string]bool{
	"auth": true, "auth_permanent": true, "model_not_found": true, "ssl_cert_verification": true, "upstream_blocked": true,
}

TerminalProviderReasons are failure reasons needing an operator change, parking the task immediately

View Source
var (

	// TodoLegacyAliases are pre rename names that replay as the todo tool
	TodoLegacyAliases = []string{"todo"}
)
View Source
var ToolCategories = buildToolCategories()

ToolCategories is the ordered provider catalog of every configurable tool category

View Source
var ToolVerbs = map[string]string{
	"web_search":       "Searching the web",
	"web_extract":      "Reading",
	"browser_navigate": "Browsing",
	"browser_click":    "Clicking",
	"browser_type":     "Typing",
	"read_file":        "Reading",
	"write_file":       "Writing",
	"patch":            "Editing",
	"search_files":     "Searching files",
	"terminal":         "Running",
	"execute_code":     "Running code",
	"image_generate":   "Generating image",
	"video_generate":   "Generating video",
	"text_to_speech":   "Generating speech",
	"vision_analyze":   "Looking at the image",
	"session_search":   "Searching past sessions",
	"skill_view":       "Reading skill",
	"skills_list":      "Listing skills",
	"skill_manage":     "Updating skill",
	"delegate_task":    "Delegating",
	"cronjob_manage":   "Scheduling",
	"clarify":          "Asking",
	"memory":           "Updating memory",
	"todo_list":        "Updating tasks",
}

ToolVerbs are the curated friendly verbs of the built in tools

View Source
var ToolsCommandHooks struct {
	VisionClientReady func(ctx context.Context, h string) (bool, error)
	ConfigureMCPTools func(ctx context.Context, con *cliui.Console, cfg config.Tree) error
	ToolsAction       func(ctx context.Context, con *cliui.Console, action, platform string, names []string) error
}

ToolsCommandHooks are the provider, setup wizard and MCP entry points the tools command reaches, each installed by its package

View Source
var ToolsConfigHooks struct {
	AuxPickerRows          func(ctx context.Context, currentProvider, currentModel, currentBaseURL string, maxModels int) ([]map[string]any, error)
	AuxPickerLabels        func(rows []map[string]any, currentProvider, currentBaseURL string) []string
	XAIOAuthStatus         func(ctx context.Context, h string) map[string]any
	CodexAuthStatus        func(ctx context.Context, h string) map[string]any
	CodexDeviceCodeLogin   func(ctx context.Context, h string, out io.Writer) (map[string]any, error)
	SaveCodexTokens        func(ctx context.Context, h string, tokens map[string]any, lastRefresh string, setActive bool) error
	XAIOAuthLoginFromSetup func(ctx context.Context, h string) bool
	SetupPromptChoice      func(question string, choices []string, def int) int
	SetupPrompt            func(question, def string, password bool) string
	SetupIsNoninteractive  func() bool

	STTModelCatalog      func(provider string) ([]string, bool)
	STTModelConfigKey    func(provider string) (string, bool)
	STTDefaultLocalModel func() string
	// Voices of the local Piper engine by name, and the one used when none is configured
	PiperVoices       func() (voices []string, defaultVoice string)
	DeepInfraModelIDs func(ctx context.Context, env *Env, tag string) []string
	FALModels         func() (ids []string, catalog map[string]map[string]any, defaultModel string)
	ImageGenRegistry  *PickerRegistry
	VideoGenRegistry  *PickerRegistry
	TTSRegistry       *PickerRegistry

	BrowserRegistry       *PickerRegistry
	LightpandaBinary      func(env *Env) string
	LightpandaInstallHint func() string
	ChromiumExecutable    func(env *Env) string
	ChromiumMissingHint   func(env *Env) string
	BakedChromiumFile     func() string

	ComputerUseProviders      func(env *Env) ([][2]string, error)
	ComputerUseDefaultBackend func() string
	CuaDriverInstallReady     func(env *Env) (bool, error)
	InstallCuaDriver          func(ctx context.Context, env *Env, con *cliui.Console) (bool, error)
}

ToolsConfigHooks are the auth, media, browser and computer use facts the tools picker reads, each installed by its package

View Source
var ToolsetEnvRequirements = map[string][][2]string{"vision": {{"OPENROUTER_API_KEY", "https://openrouter.ai/keys"}}}

ToolsetEnvRequirements lists env var and key URL pairs a toolset prompts for

View Source
var ToolsetPlatformRestrictions = map[string]map[string]bool{"discord": {"discord": true}, "discord_admin": {"discord": true}}

ToolsetPlatformRestrictions limits a toolset to the platforms that can host it

View Source
var Toolsets = map[string]Toolset{
	"web":    ts("Web research and content extraction tools", []string{"web_search", "web_extract"}),
	"search": ts("Web search only (no content extraction/scraping)", []string{"web_search"}),
	"x_search": ts("Search X (Twitter) posts and threads via xAI's built-in x_search Responses tool. Read-only public X discovery; use the xurl skill for authenticated X API reads and account actions. Available when xAI credentials are configured (SuperGrok OAuth or XAI_API_KEY). Off by default; enable in `icebath tools` -> X (Twitter) Search.",
		[]string{"x_search"}),
	"vision":    ts("Image analysis and vision tools", []string{"vision_analyze"}),
	"video":     ts("Video analysis and understanding tools (opt-in, not in default toolset)", []string{"video_analyze"}),
	"image_gen": ts("Creative generation tools (images)", []string{"image_generate"}),
	"video_gen": ts("Video generation tools. Single ``video_generate`` tool covers text-to-video (prompt only) and image-to-video (prompt + image_url), plus reference-to-video. Provider-specific edit/extend workflows may appear as separate tools. Configure via ``icebath tools`` -> Video Generation.",
		[]string{"video_generate", "xai_video_edit", "xai_video_extend"}),
	"computer_use": ts("Background desktop control via cua-driver (macOS/Windows/Linux) - screenshots, mouse, keyboard, scroll, drag. Does NOT steal the user's cursor or keyboard focus. Works with any tool-capable model.",
		[]string{"computer_use"}),
	"terminal": ts("Terminal/command execution and process management tools", []string{"terminal", "process_manage"}),
	"skills":   ts("Access, create, edit, and manage skill documents with specialized instructions and knowledge", []string{"skills_list", "skill_view", "skill_manage"}),
	"browser": ts("Browser automation: icebath drives a real Chromium over CDP (navigate, click, type, extract, screenshots) from page scripts run on your Python, plus raw CDP, dialogs and vault logins",
		corePrefixed("browser_")),
	"cronjob":        ts("Cronjob management tool - create, list, update, pause, resume, remove, and trigger scheduled tasks", []string{"cronjob_manage"}),
	"file":           ts("File manipulation tools: read, write, patch (with fuzzy matching), and search (content + files)", []string{"read_file", "write_file", "patch", "search_files"}),
	"tts":            ts("Text-to-speech: convert text to audio with Edge TTS (free), ElevenLabs, OpenAI, or xAI", []string{"text_to_speech"}),
	"todo":           ts("Task planning and tracking for multi-step work", []string{"todo_list"}),
	"memory":         ts("Persistent memory across sessions (personal notes + user profile)", []string{"memory"}),
	"context_engine": ts("Runtime tools exposed by the active context engine", nil),
	"session_search": ts("Search and recall past conversations with summarization", []string{"session_search"}),
	"connections":    ts("MCP server install, enable and authorization from the bundled catalog or config", []string{"manage_connections"}),
	"project":        ts("Projects - create/switch named workspaces", []string{"desktop_project"}),
	"bot_room":       ts("Verified text-only Group Chat turn capabilities", nil),
	"clarify":        ts("Ask the user clarifying questions (multiple-choice or open-ended)", []string{"clarify"}),
	"code_execution": ts("Run Python scripts that call tools programmatically (reduces LLM round trips)", []string{"execute_code"}),
	"delegation":     ts("Spawn subagents with isolated context for complex subtasks", []string{"delegate_task"}),
	"kanban": ts("Kanban multi-agent coordination - only active when the agent is spawned by the kanban dispatcher (ICEBATH_KANBAN_TASK env set). The dispatcher runs inside the gateway by default; see `kanban.dispatch_in_gateway` in config.yaml. Lets workers mark tasks done with structured handoffs, enter first-class review (request_review - not a block), return review changes, block for human input, heartbeat during long ops, comment on threads, attach files, and (for orchestrators) list, unblock, and fan out tasks.",
		corePrefixed("kanban_")),
	"discord":       ts("Discord read and participate tools (fetch messages, search members, create threads)", []string{"discord"}),
	"discord_admin": ts("Discord server management (list channels/roles, pin messages, assign roles)", []string{"discord_admin"}),
	"yuanbao":       ts("Yuanbao platform tools - group info, member queries, DM, stickers", yuanbaoTools),
	"feishu_doc":    ts("Read Feishu/Lark document content", []string{"feishu_doc_read"}),
	"feishu_drive":  ts("Feishu/Lark document comment operations (list, reply, add)", feishuTools[1:]),
	"debugging":     ts("Debugging and troubleshooting toolkit", []string{"terminal", "process_manage"}, "web", "file"),
	"safe":          ts("Safe toolkit without terminal access", nil, "web", "vision", "image_gen"),
	"coding": {Description: "Coding-focused toolset: files, terminal, search, web docs, skills, todo, delegate, vision, browser",
		Tools: append([]string{}, CodingTools...), Posture: true},
	"icebath-acp":            ts("Editor integration (VS Code, Zed, JetBrains) - coding-focused tools without messaging, audio, or clarify UI", withoutName(CodingTools, "clarify")),
	"icebath-api-server":     ts("OpenAI-compatible API server - full agent tools accessible via HTTP (no interactive UI tools like clarify or send_message)", coreWithout(false, "text_to_speech", "clarify", "computer_use")),
	"icebath-cli":            bundle("Full terminal toolset - all default tools plus cronjob management"),
	"icebath-cron":           bundle("Default cron toolset - same core tools as icebath-cli; gated by `icebath tools`"),
	"icebath-telegram":       bundle("Telegram bot toolset - full access for personal use (terminal has safety checks)"),
	"icebath-discord":        bundle("Discord bot toolset - full access (terminal has safety checks via dangerous command approval)", "discord", "discord_admin"),
	"icebath-whatsapp":       bundle("WhatsApp bot toolset - similar to Telegram (personal messaging, more trusted)"),
	"icebath-slack":          bundle("Slack bot toolset - full access for workspace use (terminal has safety checks)"),
	"icebath-signal":         bundle("Signal bot toolset - encrypted messaging platform (full access)"),
	"icebath-bluebubbles":    bundle("BlueBubbles iMessage bot toolset - Apple iMessage via local BlueBubbles server"),
	"icebath-email":          bundle("Email bot toolset - interact with Icebath via email (IMAP/SMTP)"),
	"icebath-mattermost":     bundle("Mattermost bot toolset - self-hosted team messaging (full access)"),
	"icebath-matrix":         bundle("Matrix bot toolset - decentralized encrypted messaging (full access)"),
	"icebath-dingtalk":       bundle("DingTalk bot toolset - enterprise messaging platform (full access)"),
	"icebath-feishu":         bundle("Feishu/Lark bot toolset - enterprise messaging via Feishu/Lark (full access)", feishuTools...),
	"icebath-weixin":         bundle("Weixin bot toolset - personal WeChat messaging via iLink (full access)"),
	"icebath-qqbot":          bundle("QQBot toolset - QQ messaging via Official Bot API v2 (full access)"),
	"icebath-wecom":          bundle("WeCom bot toolset - enterprise WeChat messaging (full access)"),
	"icebath-wecom-callback": bundle("WeCom callback toolset - enterprise self-built app messaging (full access)"),
	"icebath-yuanbao": {Description: "Yuanbao Bot messaging platform toolset - group info, member queries, DM, stickers",
		Tools: concat(CoreTools, yuanbaoTools), Module: "tools.yuanbao_tools"},
	"icebath-sms":     bundle("SMS bot toolset - interact with Icebath via SMS (Twilio)"),
	"icebath-webhook": ts("Webhook toolset - receive and process external webhook events", WebhookSafeTools),
	"icebath-gateway": ts("Gateway toolset - union of all messaging platform tools", nil,
		"icebath-telegram", "icebath-discord", "icebath-whatsapp", "icebath-slack",
		"icebath-signal", "icebath-bluebubbles", "icebath-email",
		"icebath-sms", "icebath-mattermost", "icebath-matrix", "icebath-dingtalk",
		"icebath-feishu", "icebath-wecom", "icebath-wecom-callback", "icebath-weixin",
		"icebath-qqbot", "icebath-webhook", "icebath-yuanbao"),
}

Toolsets is the static toolset table, extended at runtime by CreateCustomToolset

View Source
var TransientProviderReasons = map[string]bool{
	"rate_limit": true, "upstream_rate_limit": true, "billing": true, "overloaded": true, "server_error": true, "timeout": true,
}

TransientProviderReasons are failure reasons a Kanban retry can heal, so they never spend the task's retry budget

View Source
var VerificationEvidenceRecorder func(env *Env, command, cwd, sessionID string, exitCode int, output string, pipelineStatus []int) map[string]any

VerificationEvidenceRecorder records a terminal result as verification evidence, installed by the agent

View Source
var ViewerTurnHasApprover func(ctx context.Context) bool

ViewerTurnHasApprover reports whether the viewer turn bound to ctx has a subscriber holding session approve, set by the gateway

View Source
var WatchIntervalSeconds = 5.0

WatchIntervalSeconds is the observe tick of a driven operation, swapped by tests

View Source
var WebhookSafeTools = []string{"web_search", "web_extract", "vision_analyze", "clarify"}

WebhookSafeTools are the tools untrusted webhook payloads may reach

View Source
var WorkerLedger = boundWorkerLedger

Ledger every delegation write resolves, the bound store ledger in production

View Source
var WorkingDiffModes = []string{"working", "staged", "all"}

Accepted diff modes in their documented order

View Source
var WorkspaceEditedMarker func(env *Env, sessionID, cwd string, paths []string) error

WorkspaceEditedMarker marks the verification ledger stale for edited paths, installed by the agent

View Source
var WorktreeCprint = func(text string) { fmt.Fprintln(pysys.Stdout, text) }

Colored CLI line printer of the worktree setup, the cli _cprint the app replaces with its renderer

View Source
var WorktreeCronStore struct {
	JobsFile  func() string
	ParseJobs func(path string) (any, error)
	JobActive func(job *pyjson.Object) bool
}

Installed by pkg/cron at init over the current store, the jobs.json path, its parsed payload and the runnable non terminal test

View Source
var WorktreeRecordRepo func(ctx context.Context, repoRoot string)

Installed by pkg/cron at init over RecordWorktreeRepo of the active home, panics when unassigned

View Source
var XAIOAuthTokensReader func(ctx context.Context, h string) error

XAIOAuthTokensReader reads the xAI OAuth tokens from a home's auth store, installed by the provider slice

Functions

func AckGatewayApproval

func AckGatewayApproval(sessionKey, requestID string) bool

AckGatewayApproval records that a client received a pending approval request

func AcquireFileLock

func AcquireFileLock(lockPath string, holder *FileLockHolder, timeout time.Duration, msg string) (func(), error)

Takes the advisory lock file within the timeout and returns its release

func AcquireTurnLock

func AcquireTurnLock(ctx context.Context, root, profile string, timeoutSeconds *float64) (release func(), err error)

Holds the profile's cross process turn lock until release, bounded by the configured or given wait

func ActivityCallbackOf

func ActivityCallbackOf(ctx context.Context) func(string)

ActivityCallbackOf returns the bound liveness callback or nil

func AgentIsOneshot

func AgentIsOneshot(ctx context.Context, o *OneshotSession, env *Env) bool

One shot fact frozen on the agent at first use so later tool and prompt builds answer the same

func AgentJoinsDelegation

func AgentJoinsDelegation(ctx context.Context, a DelegationInlineAgent) bool

Inline decision frozen on the agent at first read from the gateway build scope

func AllPassthrough

func AllPassthrough(env *Env) map[string]bool

AllPassthrough returns the union of skill registered and configured names minus managed credentials

func AllowAsyncDelegationsForSession

func AllowAsyncDelegationsForSession(token any)

Lifts one session's dispatch refusal

func AnnotateFailure

func AnnotateFailure(command string, exitCode int, output string) string

AnnotateFailure returns one recovery hint for a failed command or an empty string

func AnnotateMaskedSuccess

func AnnotateMaskedSuccess(command, output string) string

AnnotateMaskedSuccess warns when an exit zero result likely hides an upstream failure

func AppTitle

func AppTitle(slug string) string

AppTitle renders a connector or tool slug as a display title

func AppendOutputContract

func AppendOutputContract(context string, schema any) string

Child context with the machine validated output contract block appended

func AppendSubdirHintToMultimodal

func AppendSubdirHintToMultimodal(value map[string]any, hint string)

AppendSubdirHintToMultimodal appends a hint to the first text part and the summary in place

func AppendToolguardGuidance

func AppendToolguardGuidance(result string, d ToolGuardrailDecision) string

AppendToolguardGuidance appends runtime guidance to the current tool result content

func ApplyExitChoice

func ApplyExitChoice(ctx context.Context, info map[string]any, echo func(string)) bool

Carries out an archive or discard answer once, true when the tree was handled or a message printed

func ApplyLaunchYolo

func ApplyLaunchYolo(ctx context.Context, sessionKey string)

ApplyLaunchYolo seeds a gateway owned session's launch bypass once per session boundary

func ApplyProposals

func ApplyProposals(env *Env, proposals []*Proposal, indices []int) map[string]bool

ApplyProposals merges the chosen proposal patterns into command_allowlist and persists them

func ApplyRelayToolRequestIntercepts

func ApplyRelayToolRequestIntercepts(ctx context.Context, sessionID, toolName string, args map[string]any) (map[string]any, error)

Relay rewritten arguments at the icebath authorization boundary

func ApplyRequestedToolRebuild

func ApplyRequestedToolRebuild(ctx context.Context, a DelegationRebuildAgent) bool

Rebuilds the session tools at turn start when a switch asked for this session, true when the tool list changed

func ApprovalKeyAliases

func ApprovalKeyAliases(patternKey string) map[string]bool

ApprovalKeyAliases lists every approval key a pattern may be stored under

func ApprovalsCommand

func ApprovalsCommand(ctx context.Context, env *Env, ns map[string]any, w, errw io.Writer) (int, error)

Dispatches icebath approvals <subcommand>, the usage text and exit 1 without one

func ApprovePermanent

func ApprovePermanent(env *Env, patternKey string)

ApprovePermanent adds a pattern to the permanent allowlist in memory

func ApproveSession

func ApproveSession(sessionKey, patternKey string)

ApproveSession approves a pattern for this session only

func AskExitChoice

func AskExitChoice(ctx context.Context, info map[string]any) string

Asks what to do with a dirty or unpushed tree and records the answer as exit_choice, keep on every skip

func AsyncDelegationActiveCount

func AsyncDelegationActiveCount() int

Live async delegation units, one per completion message

func AsyncDelegationActiveTaskCount

func AsyncDelegationActiveTaskCount() int

Running child subagents, a batch of N counting N

func AsyncDelegationDisplayText

func AsyncDelegationDisplayText(evt map[string]any) string

AsyncDelegationDisplayText is the compact UI title of a delegation completion

func AsyncDelegationLive

func AsyncDelegationLive(status any) bool

Whether a delegation status is one of the live states a stop of the gateway interrupts

func AsyncTransaction

func AsyncTransaction(env *Env, body func(ctx context.Context, conn state.SQLiteConn) error) error

Runs body in one ledger transaction, exported for delegation lifecycle callers

func AttemptClarifyTextResponse

func AttemptClarifyTextResponse(sessionKey, response string) string

AttemptClarifyTextResponse tries to resolve the oldest pending clarify from typed text and reports the outcome

func AuthoritativeWorkspaceRoot

func AuthoritativeWorkspaceRoot(env *Env) (string, error)

Workspace root the session treats as authoritative

func AuthorityAmbiguity

func AuthorityAmbiguity(raw string, floor bool) (string, error)

Ambiguous authority reason of an http url, the floor form keeping only host moving checks, with the urlsplit ValueError

func AwaitEditorEditDecision

func AwaitEditorEditDecision(ctx context.Context, env *Env, data map[string]any) bool

Waits on the current session's gateway approval for one editor edit, approved only for a resolved one time grant

func AwaitGatewayDecisionForTests

func AwaitGatewayDecisionForTests(ctx context.Context, env *Env, sessionKey string, notify GatewayNotifyFunc, data map[string]any) (resolved bool, choice, cancelled string)

Runs the gateway approval wait of a session for a case of another package, the choice empty when withdrawn

func BeginInterpreterShutdown

func BeginInterpreterShutdown()

BeginInterpreterShutdown marks the process as finalizing so background schedulers stop producing noise

func BindFiniteTurn

func BindFiniteTurn(env *Env, finite any, unattended bool) (restore func())

Stores an admitted turn's finite and unattended flags on the session env, the returned func restoring the prior values

func BindRuntimeMain

func BindRuntimeMain(env *Env, runtime map[string]any)

Binds the live main runtime of a turn on the agent's env, a nil map clearing it

func BindSessionContext

func BindSessionContext(env *Env, vars map[string]string)

BindSessionContext stores the bound session variables and marks the session context engaged

func BindWorkerDelegationStore

func BindWorkerDelegationStore(store WorkerDelegationStore) error

Binds the worker process's runtime store as its delegation ledger, refusing a foreign process or a second store

func BlankSlateMinimalToolsets

func BlankSlateMinimalToolsets(ctx context.Context, cfg config.Tree) error

Writes the Blank Slate toolset state, only file, terminal, vision and skills left on through both suppression layers

func BlankSlateMinimizeConfig

func BlankSlateMinimizeConfig(cfg config.Tree) error

BlankSlateMinimizeConfig turns every optional config feature off, each one opting back in through /setup agent

func BotRelayRoot

func BotRelayRoot(root string) string

Relay directory under the root

func BoundErrorText

func BoundErrorText(text string) string

Error text clamped to the display bound

func BoundSessionKey

func BoundSessionKey(env *Env) string

Route key bound in this context, empty when none is, never read from the process environment

func BoundSessionVar

func BoundSessionVar(env *Env, name string) (string, bool)

Bound value of one session variable and whether this context ever set it

func BoundToolProgress

func BoundToolProgress(ctx context.Context, callback func(event, name, preview string, args map[string]any, extra map[string]any), toolName, toolCallID string) context.Context

Binds the call's relay for the dispatch, no reporter when the agent has no progress callback

func BoundedGitProbe

func BoundedGitProbe(argv []string, timeout time.Duration, env map[string]string) string

Stripped stdout of a bounded git probe, empty on failure, for callers outside this package

func BranchNameFor

func BranchNameFor(project *Project, taskID, title string) string

BranchNameFor is the deterministic <project-slug>/<task-id>[-<title-slug>] branch name for a project linked task

func BridgeGeneratingPhrase

func BridgeGeneratingPhrase(toolName string) string

BridgeGeneratingPhrase names what a bridge tool is generating while friendly labels are on

func BridgeToolSchemas

func BridgeToolSchemas(deferredCount int, listing, listingForm string) []map[string]any

BridgeToolSchemas returns the three bridge schemas injected in place of deferred tools

func BucketLimit

func BucketLimit(limit int) int

BucketLimit rounds a requested result count up to the nearest bucket

func BuildCatalogListingWithForm

func BuildCatalogListingWithForm(ctx context.Context, env *Env, deferrable []map[string]any, maxTokens int) (string, string)

BuildCatalogListingWithForm renders the deferred catalog manifest and reports its degradation form

func BuildCodingWorkspaceBlock

func BuildCodingWorkspaceBlock(cwd string) string

BuildCodingWorkspaceBlock renders the workspace snapshot, empty outside a workspace

func BuildDelegateDynamicSchemaOverrides

func BuildDelegateDynamicSchemaOverrides(env *Env) *pyjson.Object

Exported buildDelegateDynamicSchemaOverrides

func BuildNativeContentParts

func BuildNativeContentParts(env *Env, userText string, imagePaths, imageURLs []string) ([]any, []string, error)

BuildNativeContentParts returns the user turn content parts and the unreadable local paths

func BuildPersistedMessage

func BuildPersistedMessage(preview string, hasMore bool, originalSize int, filePath string) string

BuildPersistedMessage builds the persisted output replacement block

func BuildRetryMessage

func BuildRetryMessage(errs []string) string

Single bounded retry turn carrying the errors verbatim without re-pasting the schema

func BuildReviewTask

func BuildReviewTask(snapshot []map[string]string, userPrompt string, loadedSkills []string) (string, string)

Viewer friendly goal and the complete reviewer briefing

func BuildScaleNote

func BuildScaleNote(scale *ScaleInfo, crop map[string]int) string

BuildScaleNote is the coordinate mapping disclosure for a downscale and a region crop, empty when neither applied

func BuildStatusPhrase

func BuildStatusPhrase(env *Env, toolName string, args map[string]any, maxLen int) string

BuildStatusPhrase renders the lowercase is verb preview phrase that follows the bot's display name

func BuildSubprocessEnv

func BuildSubprocessEnv(ctx context.Context, env *Env, o SubprocessEnvOptions) (map[string]string, error)

BuildSubprocessEnv is the single factory for child process environments

func BuildToolLabel

func BuildToolLabel(env *Env, toolName string, args map[string]any, maxLen *int) string

BuildToolLabel renders the one line friendly label of a tool call

func BuildToolPreview

func BuildToolPreview(env *Env, toolName string, args map[string]any, maxLen *int) string

BuildToolPreview renders a short preview of a tool call's primary argument, nil max len uses the global cap

func BuiltinTerminalBackends

func BuiltinTerminalBackends() []string

Every shipped terminal backend name in sorted order

func BusyInputHintGateway

func BusyInputHintGateway(mode string) string

Markdown hint shown the first time a user messages while the agent is busy

func CallInFlight

func CallInFlight(keys ...string) func()

Exported face of the in flight hold for pkg/codeexec, the returned func releases

func CanonicalPath

func CanonicalPath(rawPath, executionCwd string) string

CanonicalPath resolves a path for overlap detection against the execution cwd

func CanonicalToolArgs

func CanonicalToolArgs(args map[string]any) string

CanonicalToolArgs returns sorted compact JSON for parsed tool arguments

func CanonicalToolName

func CanonicalToolName(name string) string

CanonicalToolName maps a legacy alias to the advertised name

func CanonicalToolsetName

func CanonicalToolsetName(name string) string

CanonicalToolsetName maps a pre rename bundle spelling onto its icebath name

func CanonicalURLParamName

func CanonicalURLParamName(name string) string

Exported canonicalURLParamName

func CarryGatewayProfilePin

func CarryGatewayProfilePin(child map[string]string) map[string]string

CarryGatewayProfilePin marks the env pinned while it still holds a pinning supervisor marker

func CheckCacheEpoch

func CheckCacheEpoch() int64

CheckCacheEpoch changes whenever InvalidateCheckCache drops the cached verdicts

func CheckFirecrawlAPIKey

func CheckFirecrawlAPIKey(env *Env) bool

CheckFirecrawlAPIKey reports whether a keyed, self hosted or explicitly selected keyless Firecrawl route is usable

func CheckFnCacheScope

func CheckFnCacheScope(env *Env) (scope string, bypass bool)

CheckFnCacheScope is the profile key availability verdicts are cached under, empty for the shared process cache

func CheckGatewayLifecycle

func CheckGatewayLifecycle(env *Env, prompt, script string) error

CheckGatewayLifecycle refuses a cron prompt or script holding a gateway lifecycle command

func CheckPaused

func CheckPaused(ctx context.Context, component string, log *slog.Logger) bool

True when engaged, logging once per engagement per component and rearming after a resume

func CheckSudoStdinGuard

func CheckSudoStdinGuard(env *Env, command string) (bool, string)

CheckSudoStdinGuard blocks an explicit sudo -S when no SUDO_PASSWORD is configured

func CheckTerminalRequirements

func CheckTerminalRequirements(env *Env) bool

CheckTerminalRequirements reports whether the configured backend can run, keeping the reason on failure

func CheckVercelSandboxRequirements

func CheckVercelSandboxRequirements(env *Env, cfg map[string]any) bool

Reports whether the vercel sandbox backend can run, recording the reason when not

func CheckWebAPIKey

func CheckWebAPIKey(env *Env) bool

CheckWebAPIKey is the check gate for web_search and web_extract, any usable backend lighting the tools

func CheckpointBase

func CheckpointBase(env *Env) string

The checkpoint root of the profile the env belongs to

func CheckpointFootprintNotice

func CheckpointFootprintNotice(env *Env) string

Names the opt out when checkpoints are on and the store sits at or above its cap, empty otherwise

func CheckpointLimit

func CheckpointLimit(value any) (int, error)

Python int of a checkpoint limit the way the manager converts it, clamped to the Go int range

func CheckpointProjectHash

func CheckpointProjectHash(workingDir string) string

Hash keying a working directory's checkpoint ref and ledger

func CheckpointRefName

func CheckpointRefName(dirHash string) string

Ref name a project hash is stored under

func CheckpointStoreLock

func CheckpointStoreLock(base string) (func(), error)

Takes the whole checkpoint store lock without waiting and returns its release, a busy store errors

func CheckpointStoreLockPath

func CheckpointStoreLockPath(base string) string

Lock file beside the resolved checkpoint base whose inode survives clearing the base

func CheckpointStorePath

func CheckpointStorePath(base string) string

Shadow store holding every project's checkpoints under a checkpoints base dir

func CheckpointsCommand

func CheckpointsCommand(ctx context.Context, env *Env, ns map[string]any, w io.Writer) (int, error)

CheckpointsCommand runs the icebath checkpoints subcommand named by checkpoints_command, status when bare

func ChildTimeout

func ChildTimeout(ctx context.Context) *float64

Inactivity cap for one child in seconds, nil for no cap

func ClaimCompletionDelivery

func ClaimCompletionDelivery(env *Env, delegationID, claimID string) (bool, error)

Claims one pending completion across competing consumers and processes

func ClaimEventDelivery

func ClaimEventDelivery(env *Env, evt map[string]any, consumer string) (string, bool, error)

Claims a durable delegation event, an empty token when none is needed and false when another consumer holds it

func ClarifyTool

func ClarifyTool(ctx context.Context, env *Env, questions any) string

Clarify result JSON through the session asker, the registry handler of the tool

func ClarifyToolWithCallback

func ClarifyToolWithCallback(ctx context.Context, env *Env, questions any, callback ClarifyCallback) string

Asks one to five questions through a surface callback and returns the result JSON, unavailable without one

func ClassicMode

func ClassicMode(s SweepConfig) bool

Whether the sweep must act exactly like the pre archive pruner

func ClassifyAgentError

func ClassifyAgentError(text any) string

Closed reason code of raw agent or provider error text, unknown when unmatched or empty

func ClassifyToolFailure

func ClassifyToolFailure(toolName string, result *string) (bool, string)

ClassifyToolFailure is the fallback classifier mirroring the display layer's error tag

func ClassifyTools

func ClassifyTools(ctx context.Context, env *Env, toolDefs []map[string]any, deferTools map[string]bool) (visible, deferrable []map[string]any)

ClassifyTools splits tool defs into visible and deferrable with bridge tools dropped

func CleanDelegationRoute

func CleanDelegationRoute(providerName string, route any) (map[string]any, error)

CleanDelegationRoute keeps the route keys of a provider answer, a route error when it is not a mapping

func CleanupAllEnvironments

func CleanupAllEnvironments(env *Env) int

CleanupAllEnvironments tears down every active environment at process exit, returning the count

func CleanupInactiveEnvs

func CleanupInactiveEnvs(env *Env, lifetime time.Duration)

Exported face of the inactive environment sweep for pkg/codeexec

func CleanupSafeSkillsCopy

func CleanupSafeSkillsCopy()

CleanupSafeSkillsCopy removes the sanitized skills temp copy at exit

func CleanupSpilloverCache

func CleanupSpilloverCache(env *Env, maxAgeHours int) int

CleanupSpilloverCache deletes expired unreferenced spill files and returns the count removed

func CleanupTerminalTempCache

func CleanupTerminalTempCache(env *Env, maxAgeHours float64) int

CleanupTerminalTempCache deletes managed temp artifacts idle for maxAgeHours and returns the count removed

func CleanupVM

func CleanupVM(env *Env, taskID string, forceRemove bool)

CleanupVM manually cleans up one environment by task id, force reaching backends that honour it

func ClearBackendProbeCache

func ClearBackendProbeCache()

Drops every cached backend probe so a changed backend is probed again

func ClearClarifySession

func ClearClarifySession(sessionKey string) int

ClearClarifySession drops every pending clarify for a session and returns how many were cancelled

func ClearCredentialFiles

func ClearCredentialFiles(env *Env)

ClearCredentialFiles resets the skill scoped registry of the session

func ClearCurrentInterrupt

func ClearCurrentInterrupt(ctx context.Context)

ClearCurrentInterrupt clears the interrupt bit on the context worker right before an approved spawn

func ClearEnvPassthrough

func ClearEnvPassthrough()

ClearEnvPassthrough resets the skill registered allowlist on session reset

func ClearFileOpsCache

func ClearFileOpsCache(taskID string)

ClearFileOpsCache drops every per task file tool state, all tasks when the id is empty

func ClearLogicalSessionCwd

func ClearLogicalSessionCwd(env *Env)

ClearLogicalSessionCwd drops the pinned logical cwd of the session

func ClearPlatformDeclarations

func ClearPlatformDeclarations()

Drops every registration

func ClearSession

func ClearSession(ctx context.Context, sessionKey string)

ClearSession removes every approval, yolo, and gateway state of a session

func ClearSessionCwd

func ClearSessionCwd(env *Env, sessionKey string)

ClearSessionCwd drops a session's cwd record at teardown

func ClearSessionVars

func ClearSessionVars(env *Env)

Blanks every session variable so reads stop falling back to the process env, capabilities back to undeclared

func ClearStaleGitLocks

func ClearStaleGitLocks(repoRoot string, minAge *int) []string

Removes abandoned locks under the checkout git dir older than the floor while no git runs, returning their paths

func ClearStaleObjectStoreLocks

func ClearStaleObjectStoreLocks(gitDir string) []string

Removes only the stale object store locks under a git dir icebath does not own

func ClearStaleTmpPacks

func ClearStaleTmpPacks(repoRoot string, minAge *int) []string

Removes aborted transfer temp packs older than the floor while no git runs, returning their paths

func ClearToolDefinitionsCache

func ClearToolDefinitionsCache()

ClearToolDefinitionsCache drops memoized definitions when a dynamic schema dependency changes

func ClearVaultRedactionValues

func ClearVaultRedactionValues(ctx context.Context)

ClearVaultRedactionValues drops the context profile's registered vault values

func CmdTools

func CmdTools(ctx context.Context, env *Env, ns map[string]any, w io.Writer) (int, error)

The icebath tools dispatcher, list enable and disable through the action command, post-setup through its hook runner

func CodexApprovalPrompt

func CodexApprovalPrompt(env *Env) func(command, description string, allowPermanent bool) (string, error)

Session asker as the codex approval prompt answering once, session, always or deny, nil without an asker

func CodingCompactSkillCategories

func CodingCompactSkillCategories(env *Env, platform, cwd string) map[string]bool

CodingCompactSkillCategories lists the categories the active posture demotes

func CodingSelection

func CodingSelection(env *Env, platform, cwd string) []string

CodingSelection returns the focus toolset selection or nil

func CodingSystemPromptParts

func CodingSystemPromptParts(env *Env, platform, cwd, model string, validToolNames map[string]bool, workspaceBlock *string) ([]string, []string, []string)

CodingSystemPromptParts returns the coding prefix, workspace snapshot, and trailing guidance

func CoerceCapabilityBool

func CoerceCapabilityBool(raw any) (bool, bool)

CoerceCapabilityBool is the image routing strict boolean of a capability override, ok false when unset

func CoerceOutputSchema

func CoerceOutputSchema(raw any) (any, string)

Schema object when usable, an error message when not, both empty when no schema was requested

func CoerceTaskImages

func CoerceTaskImages(taskList []map[string]any, images any) ([][]string, string)

Validated image list per task, the legacy top level images applying to a single task only

func CoerceTaskSchemas

func CoerceTaskSchemas(taskList []map[string]any, outputSchema any) ([]any, string)

Coerced output schema per task, a malformed one failing the whole call before any child spawns

func CoerceToolArgs

func CoerceToolArgs(ctx context.Context, r *Registry, env *Env, toolName string, args map[string]any) map[string]any

CoerceToolArgs repairs string typed args against the tool's JSON Schema keeping originals on failure

func CollapseConstUnions

func CollapseConstUnions(schema any) any

CollapseConstUnions turns unions of same typed consts into enum without mutating the input

func CollapseRepeatedInputArtifacts

func CollapseRepeatedInputArtifacts(text string, minRepeats int) string

Drops a trailing run of at least minRepeats paste corruption markers and their lead in

func CollectParentLoadedSkills

func CollectParentLoadedSkills(parent any, messages []map[string]any, limit int) []string

Skills the parent worked under, launch preloaded first then skill_view loads from history, deduped and capped

func CommandApprovalIdentity

func CommandApprovalIdentity(env *Env, call *Call) string

CommandApprovalIdentity is everything the approval path keys a decision on for the call's command

func CommandGateRefusalTexts

func CommandGateRefusalTexts() (cliDenied, transportDenied, cliTimeout string)

Command gate cli denied, transport denied and cli timeout texts with the description and breaker fields emptied

func CommandVariants

func CommandVariants(command string) []string

CommandVariants lists every detection spelling of a command in scan order

func CompleteCompletionDelivery

func CompleteCompletionDelivery(env *Env, delegationID, claimID string) (bool, error)

Acknowledges acceptance for the consumer holding the claim

func CompleteEventDelivery

func CompleteEventDelivery(env *Env, evt map[string]any, claimID string) error

Acknowledges the claimed delivery of a delegation event

func CompletionCopyID

func CompletionCopyID(evt map[string]any) string

Delegation id an event is the final result copy of, empty for other events and interim notices

func ConfigurableKeys

func ConfigurableKeys() map[string]bool

Keys of every configurable toolset as a fresh set

func ConfiguredBackend

func ConfiguredBackend(config map[string]any) string

Lowercased stripped delegation.backend, default when blank or not a string

func ConfiguredLegacyRelayEnvVars

func ConfiguredLegacyRelayEnvVars(env map[string]any) []string

Sorted legacy exporter variables set to a non blank value in env

func ConsumeYield

func ConsumeYield(id WorkerID) bool

ConsumeYield atomically takes the pending yield for the worker

func ContainerBackendForTask

func ContainerBackendForTask(env *Env, taskID string) string

Backend name of a task whose file paths belong to a container, empty otherwise

func ContainsGatewayLifecycleCommand

func ContainsGatewayLifecycleCommand(text string) bool

ContainsGatewayLifecycleCommand reports whether text holds a gateway lifecycle command shape

func ContainsHostInterpreterKill

func ContainsHostInterpreterKill(text string) bool

ContainsHostInterpreterKill reports a process killer aimed at the image hosting the gateway

func ContainsLaunchctlSubmitCommand

func ContainsLaunchctlSubmitCommand(command string) bool

ContainsLaunchctlSubmitCommand detects an executed launchctl submit or bootstrap

func ContextConfigReadonly

func ContextConfigReadonly(env *Env, what string) map[string]any

Readonly config of the env home, empty with a debug log when it cannot be read

func ContextFileMaxCharsFor

func ContextFileMaxCharsFor(env *Env, contextLength *int) int

Context file truncation limit, an explicit context_file_max_chars winning over the dynamic cap

func ContextPrunedArgumentPaths

func ContextPrunedArgumentPaths(toolName string, args any) []string

ContextPrunedArgumentPaths lists argument paths whose values carry a compression marker artifact

func ConvertBase64ImagesToLinks(text string) string

ConvertBase64ImagesToLinks replaces inline base64 image blobs with [IMAGE: alt] placeholders

func ConvertTreelessCheckout

func ConvertTreelessCheckout(ctx context.Context, repoRoot string, kw pysubprocess.Options) (bool, error)

Turns a treeless checkout into the blobless layout, recording the filter only once its history is whole

func ConvertTreelessCheckoutFirst

func ConvertTreelessCheckoutFirst(ctx context.Context, repoRoot string)

Runs the one time treeless conversion as the update's first new code step and prints its verdict, never failing

func CopyTruncationWarningsContext

func CopyTruncationWarningsContext(ctx context.Context) context.Context

Child context whose truncation warnings binding starts as a copy of the parent binding

func CredentialBundle

func CredentialBundle(model, providerName, baseURL, apiKey, apiMode, requestOverrides any, extra map[string]any) map[string]any

CredentialBundle builds the child credential map every delegation credential branch returns

func CurrentOrigin

func CurrentOrigin(env *Env) string

Foreground or background_review as tagged on the session by the review fork

func CurrentOriginSessionID

func CurrentOriginSessionID(env *Env) string

Raw session id of the originating api_server request, empty on push platforms

func CurrentRelayProfileKey

func CurrentRelayProfileKey(ctx context.Context) string

Canonical profile identity used for runtime isolation

func CurrentSessionKey

func CurrentSessionKey(env *Env) string

Session key of the call's session with the default fallback

func CurrentSessionKeyOr

func CurrentSessionKeyOr(env *Env, def string) string

Approval session key of the call's session with def as fallback, the exported face for pkg/cron and pkg/codeexec

func CurrentSessionToolScope

func CurrentSessionToolScope(ctx context.Context) string

CurrentSessionToolScope returns the session scope exactly as bound, empty when none is bound

func CurrentTerminalBackend

func CurrentTerminalBackend(env *Env) (string, error)

CurrentTerminalBackend names the terminal backend this process selected, local when unset

func CwdNamesNoDirectory

func CwdNamesNoDirectory(value string) bool

Whether a terminal cwd value carries no directory choice of its own

func DecideImageInputMode

func DecideImageInputMode(ctx context.Context, env *Env, provider, model, requestedProvider string) string

DecideImageInputMode returns native or text for a provider and model under the session config

func DecideImageInputModeWithConfig

func DecideImageInputModeWithConfig(ctx context.Context, env *Env, provider, model string, cfg map[string]any, requestedProvider string) string

Native or text for a provider and model under the config tree the caller loaded

func DecideSandboxImageSwitch

func DecideSandboxImageSwitch(ctx context.Context, env *Env, sw *SandboxImageSwitch, approve bool) (string, error)

Pins the target or the current image, re-bridges the process env and on approval evicts the cached sandbox

func DeclareStatelessChannel

func DeclareStatelessChannel(env *Env)

Marks the context unable to receive an async completion without latching the session context

func DeclaredDelegationParameters

func DeclaredDelegationParameters(p DelegationProvider, config map[string]any) map[string]map[string]any

DeclaredDelegationParameters lists a provider's task parameters minus malformed or reserved names

func DefaultDeferredTools

func DefaultDeferredTools() map[string]bool

DefaultDeferredTools is the curated deferral set kept in the config defaults so discovery and runtime agree

func DeferCompletionDelivery

func DeferCompletionDelivery(env *Env, delegationID, claimID string) (bool, error)

Returns an unadmitted completion to pending without spending a delivery attempt

func DeferredCallArguments

func DeferredCallArguments(toolCallArgs map[string]any) *pyjson.Object

Python valued arguments of the entry a tool_call resolves to, nil when the call holds no entry

func DeferredDirectCallReason

func DeferredDirectCallReason(name string) string

DeferredDirectCallReason answers a direct call of a deferred tool, whose schema the request does not carry

func DelegatedChildActive

func DelegatedChildActive(ctx context.Context, env *Env) bool

Reports whether code runs for a delegate_task child on this context or on an env bound for its checks

func DelegatedChildProcessActive

func DelegatedChildProcessActive(ctx context.Context, env *Env) bool

Reports a delegate_task child in this process or a subprocess one spawned

func DelegatedChildSubprocessEnv

func DelegatedChildSubprocessEnv(env *Env, child map[string]string) map[string]string

Child env for a delegated subprocess

func DelegationParamError

func DelegationParamError(index int, name string, value any, schema map[string]any) string

DelegationParamError returns the enum violation text of one task parameter, empty when allowed

func DeliveryFailureReason

func DeliveryFailureReason(err error) string

Typed reason of a delivery refusal, an error's own reason trusted only inside the vocabulary

func DenyCommandVariants

func DenyCommandVariants(command string) []string

DenyCommandVariants adds executable projections for user deny rules on top of the detection variants

func DeriveGlob

func DeriveGlob(normalized string) string

DeriveGlob derives a narrow command glob from a simple command, empty for compound or unsafe commands

func DetectContentRuleKeys

func DetectContentRuleKeys(command string) []string

DetectContentRuleKeys lists every content level rule the command matches in detection order

func DetectDangerousCommand

func DetectDangerousCommand(command string) (string, string, bool)

DetectDangerousCommand reports the first dangerous match as its pattern key and description

func DetectHardlineCommand

func DetectHardlineCommand(command string) (bool, string)

DetectHardlineCommand reports the never bypassable hardline match for a command

func DetectImageMimeTypeFromBytes

func DetectImageMimeTypeFromBytes(data []byte) string

DetectImageMimeTypeFromBytes sniffs an image MIME type from magic bytes, empty for unknown data and SVG

func DetectSelfRepoGitMutation

func DetectSelfRepoGitMutation(env *Env, command, cwd, sourceRoot string) (bool, string)

DetectSelfRepoGitMutation reports whether a command would rewrite the live source checkout

func DetectToolFailure

func DetectToolFailure(ctx context.Context, toolName string, result any) (bool, string)

Whether a tool result failed and the suffix its completion row shows

func DetectUpstreamElision

func DetectUpstreamElision(content any) bool

DetectUpstreamElision is true when a string result carries provider side elision markers

func DeterministicCallID

func DeterministicCallID(fnName, arguments string, index int) string

DeterministicCallID is the stable fallback id when the API omits one

func Dict

func Dict(kv ...any) *pyjson.Object

Dict builds a Python dict from alternating keys and values, kept in the order given

func DirectLifecycleScan

func DirectLifecycleScan(command string) bool

DirectLifecycleScan runs the pure string lifecycle scans, data exempted regex plus submit

func DisableSessionYolo

func DisableSessionYolo(ctx context.Context, sessionKey string)

DisableSessionYolo disables the approval bypass for one session key

func DisableTree0AutoMaintenance

func DisableTree0AutoMaintenance(ctx context.Context, repoRoot string)

Keeps git from writing a commit graph in a partial clone, idempotent and never failing

func DisabledToolReason

func DisabledToolReason(name, toolset string) string

DisabledToolReason answers a call of a tool whose toolset is switched off in this session

func DiscardPending

func DiscardPending(env *Env, subsystem, pendingID string) bool

Deletes a pending record and reports whether it existed

func DiscordRequest

func DiscordRequest(ctx context.Context, method, path, token string, params [][2]string, body any, timeout time.Duration) (any, error)

Calls the Discord REST API with a bot token, nil for 204 and the decoded JSON otherwise

func Disengage

func Disengage(ctx context.Context) bool

Removes every visible sentinel, true when at least one was removed

func DispatchAsyncDelegation

func DispatchAsyncDelegation(env *Env, req AsyncDelegationRequest) map[string]any

Dispatches a single background unit, status dispatched with its delegation_id, else rejected or error with the reason

func DispatchAsyncDelegationBatch

func DispatchAsyncDelegationBatch(ctx context.Context, env *Env, d AsyncDispatch) (map[string]any, error)

Dispatches a fan out unit as one background unit with one completion event carrying per task results

func DispatchAsyncDelegationUnit

func DispatchAsyncDelegationUnit(ctx context.Context, env *Env, d AsyncDispatch) (map[string]any, error)

Spawns one background child on the daemon executor and returns its handle immediately

func DispatchCommitGraphRefreshEntry

func DispatchCommitGraphRefreshEntry(ctx context.Context)

Runs the refresh and exits when argv carries the entry, otherwise records that this binary handles it

func DispatchDDGSWorkerEntry

func DispatchDDGSWorkerEntry()

DispatchDDGSWorkerEntry runs the worker and exits when argv carries the entry, otherwise records that this binary handles it

func DispatchForPlugin

func DispatchForPlugin(ctx context.Context, scope, toolName string, args, kwargs map[string]any) (string, error)

Executes a tool handler by name in a profile scope for a plugin, the context kwargs riding the call

func DispatchToolDescribe

func DispatchToolDescribe(ctx context.Context, env *Env, args map[string]any, currentToolDefs []map[string]any, cfg *ToolSearchConfig, call *Call) string

DispatchToolDescribe answers a tool_describe bridge call with full schemas for deferred tools

func DispatchToolSearch

func DispatchToolSearch(ctx context.Context, env *Env, args map[string]any, currentToolDefs []map[string]any, cfg *ToolSearchConfig, call *Call) string

DispatchToolSearch answers a tool_search bridge call over the session's deferrable catalog

func DispatcherOwnedWorkerActive

func DispatcherOwnedWorkerActive(ctx context.Context, env *Env) bool

False when a kanban identity is present but this execution does not own it

func DistributionNames

func DistributionNames() []string

DistributionNames lists every distribution name in declaration order, names outside the declared order sorted after them

func DockerHasHostAccess

func DockerHasHostAccess(cfg map[string]any) bool

Reports whether a docker sandbox config exposes host paths through bind mounts

func DockerRuntimeName

func DockerRuntimeName(executable string) string

DockerRuntimeName is the user facing runtime name for the CLI at a path

func DockerRuntimeStartHint

func DockerRuntimeStartHint(executable string) string

DockerRuntimeStartHint says how to bring the runtime back up

func DrainTruncationWarnings

func DrainTruncationWarnings(ctx context.Context) []string

Returns and clears the truncation warnings accumulated in this context

func DriveOperation

func DriveOperation(ctx context.Context, env *Env, op *ConnectionOperation, kind ConnKind, cb ConnCallback, tick *float64, withURLs bool) string

Prepares, emits the card, watches until settled and renders the settled result

func DropCompletionDelivery

func DropCompletionDelivery(env *Env, delegationID, claimID string) (bool, error)

Terminally drops a claimed completion whose target session is permanently gone

func DropUnlinkedToolsets

func DropUnlinkedToolsets()

DropUnlinkedToolsets removes the toolsets, configurator rows, provider categories and platforms of tiers this binary leaves out, run once before any entry

func Elide

func Elide(text string, limit int) string

Caps text at limit characters with the elision marker

func ElideMiddle

func ElideMiddle(text string, head, tail int) string

Text keeping head and tail code points around an elision marker when longer than both

func ElisionMarker

func ElisionMarker(omitted, total int) string

Intra record truncation marker naming the omitted and total character counts

func ElisionMarkerMaxLen

func ElisionMarkerMaxLen() int

Longest elision marker any count can render, in code points

func EnableSessionYolo

func EnableSessionYolo(ctx context.Context, sessionKey string)

EnableSessionYolo enables the approval bypass for one session key

func EnabledMCPServerNames

func EnabledMCPServerNames(cfg config.Tree, portable map[string]bool) map[string]bool

EnabledMCPServerNames lists MCP servers enabled in config plus portable plugin servers

func EnabledPluginToolsets

func EnabledPluginToolsets(cfg config.Tree, platform string, names []string, pluginKeys map[string]bool) map[string]bool

EnabledPluginToolsets is the exported plugin toolset resolver for the migration tests of other packages

func EnabledToolsOf

func EnabledToolsOf(ctx context.Context) ([]string, bool)

EnabledToolsOf returns the sandbox tool list bound to the context

func EnforceNoRefusal

func EnforceNoRefusal(ctx context.Context) error

Error when the context scope is a refusal so execution fails closed

func EnforceTurnBudget

func EnforceTurnBudget(ctx context.Context, env *Env, sandbox Environment, toolMessages []*state.Message, cfg BudgetConfig) []*state.Message

EnforceTurnBudget persists the largest non persisted results until the turn's aggregate fits

func Engage

func Engage(ctx context.Context, reason string) string

Creates the ESTOP sentinel with its reason and time, an empty sentinel still pausing when the body cannot be written

func EnsureSandboxImage

func EnsureSandboxImage(ctx context.Context, docker, image string, progress func(line string, headline bool)) error

Builds the default sandbox image from the embedded Dockerfile unless the local one already matches it, other images untouched

func EnsureSpillDir

func EnsureSpillDir(path string, private bool) error

EnsureSpillDir creates the directory refusing a symlinked leaf and tightening private leaves to 0700

func EnsureWebPluginsLoaded

func EnsureWebPluginsLoaded(ctx context.Context, env *Env)

Discovers plugins so plugin registered web providers exist before a readiness read

func EnterNonDispatcherOwnedContext

func EnterNonDispatcherOwnedContext(env *Env) func()

Marks the env a non dispatcher owned execution and returns the restore of the previous flag

func EntryStillRunning

func EntryStillRunning(entry map[string]any) bool

EntryStillRunning reports whether the entry's process is still the recorded incarnation

func EnvUsesHostFilesystem

func EnvUsesHostFilesystem(e Environment) bool

EnvUsesHostFilesystem reports whether the file tools may touch the files of an environment on the host

func EnvironMap

func EnvironMap() map[string]string

Copy of the current process environment, the first entry of a repeated name winning

func EnvironmentProbeLine

func EnvironmentProbeLine(env *Env, forceRefresh bool) string

EnvironmentProbeLine returns the cached toolchain line, empty for remote backends or a clean host

func ErrorResult

func ErrorResult(err error) string

ErrorResult formats an error as the JSON object the model reads

func EstimateTokensFromSchemas

func EstimateTokensFromSchemas(toolDefs []map[string]any) int

EstimateTokensFromSchemas estimates token cost through the chars per token rule

func ExecPrefix

func ExecPrefix(e Environment, user string, interactive bool) []string

ExecPrefix is the local argv that runs its remainder inside the environment, nil without one

func ExpandLocalToolBatches

func ExpandLocalToolBatches(toolCalls []state.ToolCall, providerData map[string]any) []state.ToolCall

ExpandLocalToolBatches splits a local tool_call batch into one call per entry before persistence

func ExpiredArchiveFields

func ExpiredArchiveFields(path string) map[string]any

ExpiredArchiveFields adds the expired hint for a pruned persisted tool result path

func ExplicitBoardIntentIsPinned

func ExplicitBoardIntentIsPinned(ctx context.Context) bool

Whether an explicit kanban board argument must still resolve through the dispatcher env pins

func ExtractCachePut

func ExtractCachePut(ctx context.Context, env *Env, u, content, title, format, provider string) bool

ExtractCachePut stores one successful extraction's clean text for TTL reuse, true when this call wrote it

func ExtractCacheRecordFinalURL

func ExtractCacheRecordFinalURL(ctx context.Context, env *Env, u, finalURL, content, format, provider string)

ExtractCacheRecordFinalURL remembers the post redirect URL behind a cached page, compare and set on the content

func ExtractDocumentBytes

func ExtractDocumentBytes(ctx context.Context, env *Env, data []byte, p string) (string, error)

Renders bytes fetched across a file backend boundary, the content naming the format before the extension

func ExtractEditDiff

func ExtractEditDiff(toolName, result string, args map[string]any, snapshot *LocalEditSnapshot) string

Unified diff of a file edit tool result, the patch tool's own diff first, else the snapshot diff

func ExtractErrorPreview

func ExtractErrorPreview(result any, maxLen int) string

ExtractErrorPreview is a one line error summary of a tool result for footer display

func ExtractFileMutationTargets

func ExtractFileMutationTargets(toolName string, args map[string]any) []string

ExtractFileMutationTargets lists the file paths a write_file or patch call targets

func ExtractImageRefs

func ExtractImageRefs(text string) ([]string, []string)

ExtractImageRefs returns ordered unique existing local image paths and image URLs found outside code spans

func ExtractJSONCandidate

func ExtractJSONCandidate(text string) string

Outermost parseable object or array span with code fences and surrounding prose stripped

func ExtractLandedFileMutationPaths

func ExtractLandedFileMutationPaths(toolName string, args map[string]any, result any) []string

ExtractLandedFileMutationPaths lists the paths a successful mutation reports or the declared targets

func ExtractParallelScopePaths

func ExtractParallelScopePaths(toolName string, functionArgs map[string]any, executionCwd string) []string

ExtractParallelScopePaths lists every canonical path a call reserves for overlap checks

func ExtractPersistedPath

func ExtractPersistedPath(content string) string

ExtractPersistedPath returns the file path from a persisted output block or empty

func FailedDelegationsForSession

func FailedDelegationsForSession(env *Env, originUISessionID, parentSessionID string, limit int, now *float64) ([]map[string]any, error)

Recently failed async delegation tasks a session owns from the durable rows, newest first

func FailureCauseGloss

func FailureCauseGloss(reason any, subject, possessive string) (string, bool)

Plain clause for a classified failure reason with the asker substituted, false when the reason has no gloss

func FalKeyIsConfigured

func FalKeyIsConfigured(env *Env) bool

FalKeyIsConfigured reports whether FAL_KEY holds a non blank value in scope or .env

func FetchFullCommitGraph

func FetchFullCommitGraph(ctx context.Context, repoRoot string, extraRefspecs []string, kw pysubprocess.Options) (shallow bool, err error)

Refreshes release tags and fills shallow history keeping the clone's mode, reporting whether it unshallowed

func FetchWithPartialCloneRecovery

func FetchWithPartialCloneRecovery(runner func(gitCmd, args []string) (*pysubprocess.Completed, error), gitCmd, fetchArgs []string,
	repoRoot string) (*pysubprocess.Completed, error)

Runs a fetch and on the pack-objects BUG marks the unmarked packs and retries it once

func FileMutationResultLanded

func FileMutationResultLanded(toolName string, result any) bool

FileMutationResultLanded is true when a file mutation result proves the write landed

func FileToDataURL

func FileToDataURL(env *Env, path string) (string, bool, error)

FileToDataURL is the native size base64 data URL of a local image, false when the attachment is skipped

func FindBash

func FindBash(ctx context.Context) (string, error)

Bash executable the local backend runs

func FindDocker

func FindDocker(env *Env) string

FindDocker locates the docker or podman CLI once per process

func FindShell

func FindShell(ctx context.Context) (string, error)

FindShell is the user's login shell for background spawning when it is an sh family shell, else bash

func FinishProcessForTests

func FinishProcessForTests(ctx context.Context, r *ProcessRegistry, s *ProcessSession, exitCode int)

Records an exit and publishes the completion the way tests call mark_exited then move to finished

func FinishedSubagentTranscript

func FinishedSubagentTranscript(ctx context.Context, db any, ownerSessionID, subagentID string) (string, error)

Log a delegated child of the conversation wrote at any depth, empty when no child of it stored one

func FiniteTurnFlag

func FiniteTurnFlag(env *Env) (bool, bool)

FiniteTurnFlag reports the recorded finite flag and whether the env carries one

func FirstContactTurnNote

func FirstContactTurnNote(ctx context.Context, cfg any, configPath string, sessionHistoryEmpty, installHasPriorSessions bool) *string

One shot sidecar note for the install's first ever message, nil when this is not first contact

func FlattenNewlinesForPayload

func FlattenNewlinesForPayload(text string) string

Newlines collapsed into sentence breaks for providers that truncate at the first newline

func FocusToolsets

func FocusToolsets(env *Env) []string

FocusToolsets returns the coding posture toolsets under focus mode, nil otherwise

func ForgetThreadSudoPassword

func ForgetThreadSudoPassword(id WorkerID)

Drops the sudo password a reused worker cached under its thread scope

func FormatApprovalWindow

func FormatApprovalWindow(seconds int) string

Human wording of an approval timeout window for the gateway approval prompt

func FormatCheckpointList

func FormatCheckpointList(checkpoints []CheckpointEntry, directory string) string

Renders checkpoints as the numbered rollback listing with its usage footer

func FormatDispatchNote

func FormatDispatchNote(result *pyjson.Object, userPrompt string) string

Human facing one liner for a successful dispatch, shared by every surface

func FormatNoMatchHint

func FormatNoMatchHint(errText string, matchCount int, oldString, content string) string

Did you mean hint for a plain no match error

func FormatProcessNotification

func FormatProcessNotification(evt map[string]any) string

IMPORTANT message a background process completion queue event injects into the conversation

func FormatUptimeShort

func FormatUptimeShort(seconds int) string

FormatUptimeShort renders seconds as 45s, 3m 2s or 2h 5m

func ForwardFailures

func ForwardFailures(e Environment, remotePort int, remoteHost string) int

ForwardFailures counts connections through the forward of a port that never reached the target

func ForwardPort

func ForwardPort(e Environment, remotePort int, remoteHost, user string) (int, error)

ForwardPort returns a local loopback port reaching the remote port inside the environment, one listener per key

func FromAgentVisibleCachePath

func FromAgentVisibleCachePath(env *Env, containerPath, containerBase string) string

FromAgentVisibleCachePath maps a docker cache path back to the host path

func FuzzyFindAndReplace

func FuzzyFindAndReplace(content, oldString, newString string, replaceAll bool, correctionNotes *[]string) (string, int, string, string)

Finds and replaces through the strategy chain, returning new content, count, strategy and error

func GatewayDelegationInline

func GatewayDelegationInline(userConfig any, platformKey string, interimEnabled bool) bool

Whether a gateway session joins top level delegations in the turn per delegation.gateway_mode

func GatewayDelegationInlineScope

func GatewayDelegationInlineScope(ctx context.Context, inline bool) context.Context

Context whose agent build carries the joined delegate_task variant

func GeneratePreview

func GeneratePreview(content string, maxChars int) (string, bool)

GeneratePreview truncates at the last newline within maxChars and reports whether more follows

func GetApprovalMode

func GetApprovalMode(env *Env) string

Exported getApprovalMode for the approvals command of other packages

func GetApprovalTimeout

func GetApprovalTimeout(env *Env) int

Configured approvals timeout in seconds for the gateway approval prompt

func GetClarifyTimeout

func GetClarifyTimeout(env *Env) int

GetClarifyTimeout is the clarify timeout from config.yaml, zero or negative meaning unlimited

func GetCuteToolMessage

func GetCuteToolMessage(ctx context.Context, env *Env, toolName string, args map[string]any, duration float64, result any) (message string)

Completion line of one tool call, a plain completed row when rendering raises

func GetDurableDelegation

func GetDurableDelegation(env *Env, delegationID string) (map[string]any, error)

Durable row of a delegation with its result redacted, nil when unknown

func GetEnabledPlatforms

func GetEnabledPlatforms(ctx context.Context, h string) ([]string, error)

Platform keys with a configured token, cli always first

func GetEnvConfig

func GetEnvConfig(env *Env) (map[string]any, error)

Resolves the terminal backend config the terminal and file tools share

func GetPending

func GetPending(env *Env, subsystem, pendingID string) map[string]any

One pending record by id, nil when absent or unreadable

func GetPendingGatewayApproval

func GetPendingGatewayApproval(sessionKey string) map[string]any

GetPendingGatewayApproval copies the oldest unresolved approval for reconnecting clients

func GetSearchBackend

func GetSearchBackend(env *Env) string

Legacy web_search backend probe for env

func GetSessionCwd

func GetSessionCwd(env *Env, sessionKey string) (string, bool)

GetSessionCwd is the recorded cwd of a session, false when none was recorded

func GetSessionEnv

func GetSessionEnv(env *Env, name, def string) string

Session variable by its ICEBATH_SESSION name, the bound value even when empty, then the process env, then def

func GetSkinToolPrefix

func GetSkinToolPrefix(ctx context.Context) any

The active skin's tool output prefix, the dotted bar without a skin

func GetSudoPromptCommand

func GetSudoPromptCommand(ctx context.Context) string

Original command of the sudo prompt being answered, empty outside its callback

func GetToolEmoji

func GetToolEmoji(ctx context.Context, env *Env, toolName, def string) string

GetToolEmoji resolves a tool's display emoji, skin override then registry then the default

func GetToolPreviewMaxLen

func GetToolPreviewMaxLen() int

GetToolPreviewMaxLen returns the configured max preview length, zero means unlimited

func GetToolVerb

func GetToolVerb(toolName string) string

GetToolVerb returns the friendly verb for a built in tool, empty when labels are off or none is curated

func GitProbeBranch

func GitProbeBranch(cwd string) string

GitProbeBranch is the current branch name, else the short HEAD hash

func GitProbeCommonRepoRoot

func GitProbeCommonRepoRoot(cwd string) string

GitProbeCommonRepoRoot is the main checkout root folding linked worktrees, in forward slash spelling

func GitProbeInvalidate

func GitProbeInvalidate()

GitProbeInvalidate drops cached roots after a known mutation such as a new worktree

func GitProbeRepoRoot

func GitProbeRepoRoot(cwd string) string

GitProbeRepoRoot is the top level repository root of cwd, empty outside a repository

func GitRepoRoot

func GitRepoRoot() string

GitRepoRoot returns the repository root of the working directory, empty outside a repository

func GitRepoRootOf

func GitRepoRootOf(cwd string) string

Repository root of a directory in Git Bash normalized form, the working directory when empty, empty outside a repo

func GitStateHint

func GitStateHint(cwd string) string

Branch, short head and dirty count of the owner checkout through hardened git, empty when not a checkout

func GitlockStdoutLines

func GitlockStdoutLines(ctx context.Context, repoRoot string, args []string) []string

Nonblank stripped stdout lines of a read only git query in repo, empty on any failure

func HandleFunctionCall

func HandleFunctionCall(ctx context.Context, call *Call) string

HandleFunctionCall routes one tool call through hooks and middleware to the registry and returns its JSON result

func HardenGitArgv

func HardenGitArgv(args []string) []string

HardenGitArgv prefixes internal git arguments with the hook and fsmonitor disabling overrides

func HasBlockingApproval

func HasBlockingApproval(sessionKey string) bool

HasBlockingApproval reports whether the session has a gateway approval waiting

func HasCompressionMarker

func HasCompressionMarker(text string) bool

Whether the text carries a minted compression marker first sentence

func HasDirectModalCredentials

func HasDirectModalCredentials(env *Env) bool

HasDirectModalCredentials reports whether a Modal token pair or ~/.modal.toml exists

func HasFailureMarker

func HasFailureMarker(result string) bool

HasFailureMarker is the last resort text test for a failed tool result

func HasLiveForSession

func HasLiveForSession(sessionKey, originUISessionID, parentSessionID string) bool

Whether a session still owns any running, stalling or finalizing delegation

func HasPendingClarify

func HasPendingClarify(sessionKey string) bool

HasPendingClarify is true when the session has at least one pending clarify entry

func HasTraversalComponent

func HasTraversalComponent(p string) bool

Reports a literal parent directory component

func HasUnsafePathChars

func HasUnsafePathChars(path string) bool

HasUnsafePathChars reports control characters or line separators in a path

func HeadTailSplit

func HeadTailSplit(budget int) (int, int)

Head and tail character budgets for a total budget, 40 percent head

func HealShallowHistory

func HealShallowHistory(ctx context.Context, repoRoot, branch string, kw pysubprocess.Options) (bool, error)

Unshallows a stale installer checkout before the bounded fetch, reporting whether it was shallow

func HeartbeatDisplayText

func HeartbeatDisplayText(evt map[string]any) string

HeartbeatDisplayText is the one line CLI receipt of a heartbeat wake

func HeartbeatOutputText

func HeartbeatOutputText(evt map[string]any) string

HeartbeatOutputText renders a tick's output with its cut marker

func HiddenIndexEdits

func HiddenIndexEdits(wtPath string, env map[string]string) ([]string, error)

Skip worktree and assume unchanged paths whose disk state differs from the index, a missing sparse file is no edit

func HomeAdapterSecretEnv

func HomeAdapterSecretEnv(h string) (map[string]bool, error)

Secrets the home's user platform plugins declare, recached when the manifest stamp moves, a partial scan keeps known names

func HomeCredentialDirs

func HomeCredentialDirs() []string

HomeCredentialDirs exports the credential directories under the user home the read guards refuse

func HomeOverride

func HomeOverride(env *Env) string

Profile home the env is scoped to, empty for an env of the launch home

func HostGatewayChildEnv

func HostGatewayChildEnv(ctx context.Context, env *Env, base map[string]string) (map[string]string, error)

HostGatewayChildEnv is the env of the host gateway with the default profile's secrets

func HostedOCRAvailable

func HostedOCRAvailable(env *Env) bool

HostedOCRAvailable reports whether scanned PDF pages can go to Firecrawl Parse

func HumanWaitSeconds

func HumanWaitSeconds(env *Env, sessionKey string) float64

HumanWaitSeconds returns the total human wait recorded for the session including the open window

func IcebathDirs

func IcebathDirs(env *Env) []string

IcebathDirs exports the resolved active home and root pair for the context reference guards

func IcebathSubprocessEnv

func IcebathSubprocessEnv(env *Env, inheritCredentials bool, base map[string]string) map[string]string

IcebathSubprocessEnv sanitizes a non terminal child environment and panics with the damaged runtime record error

func IcebathSubprocessEnvChecked

func IcebathSubprocessEnvChecked(env *Env, inheritCredentials bool, base map[string]string) (map[string]string, error)

IcebathSubprocessEnvChecked returns the sanitized child environment or the damaged runtime record error

func IcebathXAIUserAgent

func IcebathXAIUserAgent() string

Stable icebath user agent for direct xAI HTTP calls

func IdentifyBinaryBytes

func IdentifyBinaryBytes(sample []byte) string

IdentifyBinaryBytes names binary content from its magic bytes, the ISO media entry also needing ftyp at offset 4

func InFocusWorkspace

func InFocusWorkspace(env *Env, platform, cwd string) bool

InFocusWorkspace reports whether the cwd selects the coding toolsets under focus

func IndependentCompletions

func IndependentCompletions(ctx context.Context) bool

Whether a background call splits into per task or per group completion messages

func InheritMCPToolsets

func InheritMCPToolsets(ctx context.Context) bool

Whether narrowed child toolsets keep the parent MCP toolsets

func InstallID

func InstallID(projectRoot string) string

InstallID is the stable 12 hex identifier of this install derived from its path

func InterpreterImageMatch

func InterpreterImageMatch(name string) bool

True when a lower cased image name is a Python interpreter name, one trailing newline allowed as re.match does

func InterpreterShuttingDown

func InterpreterShuttingDown(err error) bool

InterpreterShuttingDown reports finalization, treating a pool scheduling error as the shutdown signal

func InterruptAllAsyncDelegations

func InterruptAllAsyncDelegations(reason string) int

Signals every running async delegation to stop, the child still emits its completion event

func InterruptAsyncDelegationsForSession

func InterruptAsyncDelegationsForSession(sessionKey, originUISessionID, parentSessionID, reason string) int

Signals the running async delegations one ending session owns to stop

func InterruptReason

func InterruptReason(ctx context.Context) string

InterruptReason returns the user safe interrupt cause for the context worker

func InterruptSkipWording

func InterruptSkipWording(reason string) string

InterruptSkipWording words why a call was skipped from the recorded reason

func InvalidToolNameErrorContent

func InvalidToolNameErrorContent(name string, validToolNames map[string]bool) string

InvalidToolNameErrorContent is the error content for an unknown tool name

func InvalidateCheckCache

func InvalidateCheckCache()

InvalidateCheckCache drops every cached availability verdict

func IsAlwaysBlockedIP

func IsAlwaysBlockedIP(ip netip.Addr) bool

Address in the always blocked ranges such as cloud metadata and link local, independent of opt ins

func IsAlwaysBlockedURL

func IsAlwaysBlockedURL(env *Env, raw string) bool

Url the browser and media tools refuse whatever the private url opt in says, metadata and fake ip floors included

func IsApprovalBypassActive

func IsApprovalBypassActive(env *Env) bool

IsApprovalBypassActive reports whether the current approval context bypasses prompts

func IsApprovalBypassActiveForSession

func IsApprovalBypassActiveForSession(env *Env, sessionKey string) bool

IsApprovalBypassActiveForSession is the three source bypass check without floors

func IsApproved

func IsApproved(env *Env, sessionKey, patternKey string) bool

IsApproved reports a session scoped or permanent approval, accepting legacy key aliases

func IsBlockedHostname

func IsBlockedHostname(host string) bool

Hostname on the cloud metadata blocklist the browser floor refuses before any resolution

func IsBridgeTool

func IsBridgeTool(name string) bool

IsBridgeTool reports whether the name is one of the three bridge tools

func IsCodingContext

func IsCodingContext(env *Env, platform, cwd string) bool

IsCodingContext reports whether the coding posture applies right now

func IsCurrentSessionYoloEnabled

func IsCurrentSessionYoloEnabled(env *Env) bool

IsCurrentSessionYoloEnabled reports the bypass flag of the active approval session

func IsDeclaredFakeIP

func IsDeclaredFakeIP(env *Env, ip netip.Addr) bool

Address inside a fake ip range the proxy configuration declares for the env

func IsDefaultSandboxImage

func IsDefaultSandboxImage(image string) bool

Whether the image is the sandbox icebath builds itself

func IsDeferrableToolName

func IsDeferrableToolName(ctx context.Context, env *Env, name string, deferTools map[string]bool) bool

IsDeferrableToolName reports whether a tool is eligible for deferral under the given defer set

func IsDelegatedChildContext

func IsDelegatedChildContext(ctx context.Context) bool

IsDelegatedChildContext reports whether code runs for a delegate_task child

func IsDestructiveCommand

func IsDestructiveCommand(cmd string) bool

IsDestructiveCommand reports whether a terminal command looks like it modifies or deletes files

func IsDispatcherOwnedWorkerContext

func IsDispatcherOwnedWorkerContext(env *Env) bool

False when a kanban identity is present but this execution does not own it

func IsEngaged

func IsEngaged(ctx context.Context) bool

True when any candidate sentinel exists, fail safe true on a stat error

func IsEnvDumpCommand

func IsEnvDumpCommand(command string) bool

IsEnvDumpCommand reports whether any segment starts with an environment dump command

func IsEnvPassthrough

func IsEnvPassthrough(env *Env, varName string) bool

IsEnvPassthrough is true for a registered or configured name that is not a managed credential now

func IsExtractableDocument

func IsExtractableDocument(p string) bool

IsExtractableDocument reports whether read_file renders this path through a document extractor

func IsGatewayApprovalContext

func IsGatewayApprovalContext(env *Env) bool

Reports a gateway or API session that can answer an approval, never cron or unattended

func IsGlobalEnv

func IsGlobalEnv(name string) bool

IsGlobalEnv is true for process wide settings that are never profile secrets

func IsGuardrailRefusal

func IsGuardrailRefusal(result any) bool

IsGuardrailRefusal reports whether a JSON string or parsed object is a harness refusal

func IsIcebathInternalSecret

func IsIcebathInternalSecret(key string) bool

IsIcebathInternalSecret is true for dynamically named internal secrets the static list cannot enumerate

func IsInstallTree

func IsInstallTree(p string) bool

IsInstallTree reports whether a path, resolved without requiring it to exist, is the install tree or inside it

func IsInterimDelegationEvent

func IsInterimDelegationEvent(evt map[string]any) bool

Reports an early per task notice of a running batch, never the durable completion

func IsInterrupted

func IsInterrupted(ctx context.Context) bool

IsInterrupted reports whether the context's worker or the worker it acts for was interrupted

func IsKeyboardInterrupt

func IsKeyboardInterrupt(ctx context.Context, err error) bool

Reports a failed dispatch raised by a keyboard interrupt, either returned by the tool or set as the turn cause

func IsKnownPlatformBundle

func IsKnownPlatformBundle(platform, name string) bool

IsKnownPlatformBundle reports whether a name is the bundle of a platform icebath knows

func IsLockedSkill

func IsLockedSkill(env *Env, name string, lockedNames []string) bool

IsLockedSkill reports whether a directory, category path or frontmatter name is locked

func IsMultimodalToolResult

func IsMultimodalToolResult(value any) bool

IsMultimodalToolResult is true for the multimodal envelope with a content list

func IsNTNamespacePath

func IsNTNamespacePath(path string) bool

IsNTNamespacePath exports the raw Windows namespace check for callers that must never resolve the path

func IsNeutralFailure

func IsNeutralFailure(toolName string, result any) bool

Whether a failed call renders neutrally, a failed rollback always shows

func IsOwnerDeathSupervisor

func IsOwnerDeathSupervisor(argv []string) bool

IsOwnerDeathSupervisor reports whether a direct child's argv is this install's supervisor shell

func IsPartialClonePackObjectsCrash

func IsPartialClonePackObjectsCrash(stderr string) bool

Whether a fetch failure is the git 2.53 partial clone pack-objects BUG

func IsPersistentEnv

func IsPersistentEnv(env *Env, taskID string) (bool, error)

IsPersistentEnv reports whether a task's active env persists across turns

func IsProfileGateEnv

func IsProfileGateEnv(name string, prefixes map[string]bool) bool

IsProfileGateEnv reports whether a name is a platform authorization gate a routed child must not inherit

func IsProviderEnvBlocklisted

func IsProviderEnvBlocklisted(env *Env, name string) bool

IsProviderEnvBlocklisted matches exact and case folded names against the blocklist and registered adapters

func IsRateLimited

func IsRateLimited(result any) bool

IsRateLimited reports whether a failed result says the backend throttled the call

func IsRelayWrappedCallbackError

func IsRelayWrappedCallbackError(relayErr, callbackErr error) bool

Whether relayErr is the binding's wrapper around callbackErr rather than a policy error

func IsRemoteTerminalBackend

func IsRemoteTerminalBackend(backend string) bool

Whether backend names a built in remote or sandbox terminal backend

func IsRoutedHome

func IsRoutedHome(targetHome string) bool

Reports whether a target profile home is served away from the running process home

func IsSafeURL

func IsSafeURL(env *Env, raw string) bool

Reports whether a URL targets a public host

func IsSecretFieldName

func IsSecretFieldName(key string) bool

Reports whether a field name denotes a secret

func IsSeen

func IsSeen(cfg any, flag string) bool

True when the user has already been shown this first touch hint

func IsSessionYoloEnabled

func IsSessionYoloEnabled(sessionKey string) bool

IsSessionYoloEnabled reports the bypass flag of one session key

func IsSingleQuerySession

func IsSingleQuerySession(ctx context.Context, env *Env) bool

Finite single query session from the frozen gateway policy, else the session env marker

func IsStallGuardRepeatable

func IsStallGuardRepeatable(toolName string) bool

IsStallGuardRepeatable reports whether a tool is exempt from the identical call loop notice

func IsSupervisedGatewayProcess

func IsSupervisedGatewayProcess() bool

Reports whether this process runs as the supervised gateway

func IsSupportedVercelRuntime

func IsSupportedVercelRuntime(runtime string) bool

IsSupportedVercelRuntime reports whether a runtime name is empty or one the sandbox accepts

func IsTableDivider

func IsTableDivider(row string) bool

True when the row is a markdown table separator line

func IsTodoToolCall

func IsTodoToolCall(name string, rawArgs any) bool

IsTodoToolCall reports whether a transcript tool call invoked the todo tool directly or through the tool_call bridge

func IsTodoToolName

func IsTodoToolName(name string) bool

IsTodoToolName is true for the todo tool's current name or a legacy alias

func IsUnsafeClass

func IsUnsafeClass(description string) bool

IsUnsafeClass reports a dangerous class description that must never be proposed

func IsUntrustedTool

func IsUntrustedTool(name string) bool

IsUntrustedTool reports whether a tool's results carry attacker controllable content

func IsWorkerInterrupted

func IsWorkerInterrupted(id WorkerID) bool

IsWorkerInterrupted reports whether a worker has its interrupt bit set, zero never does

func IsWriteApprovalRequired

func IsWriteApprovalRequired(env *Env, path string) bool

IsWriteApprovalRequired reports a path whose write needs explicit approval

func IsWriteDenied

func IsWriteDenied(env *Env, path string) bool

IsWriteDenied reports a path on the protected credential and system write denylist

func IsolateOwnerDeathSupervisor

func IsolateOwnerDeathSupervisor() (restore func())

IsolateOwnerDeathSupervisor empties the supervisor slot with an immediate idle exit until the returned restore runs

func IsolateProcessRegistryForTests

func IsolateProcessRegistryForTests(r *ProcessRegistry) (restore func())

Empties the running and finished tables and the completion queue, returning the restore

func JSON

func JSON(v any) string

JSON encodes a tool result as json.dumps does with ensure_ascii off and its default separators

func JSONASCII

func JSONASCII(v any) string

JSONASCII encodes a tool result as json.dumps does with every default, non ASCII text escaped

func JoinHeartbeatOutputs

func JoinHeartbeatOutputs(earlier, later map[string]any) map[string]any

JoinHeartbeatOutputs merges two consecutive ticks' output and omitted counts as one tick's

func KanbanEnvKeys

func KanbanEnvKeys() []string

Worker identity keys scrubbed from the env of every descendant process

func KanbanPathIsFenced

func KanbanPathIsFenced(ctx context.Context, path string) bool

Whether kanban mutations at path are denied, always in a delegate child and under the fence otherwise

func KanbanResumeRefusal

func KanbanResumeRefusal(ctx context.Context, db any, sessionID string) string

Refusal text when the session is a Kanban worker transcript an ordinary session must not resume, else empty

func KanbanToolsetRequested

func KanbanToolsetRequested(env *Env) (requested bool, inAssembly bool)

KanbanToolsetRequested reports the explicit kanban selection and whether a schema build is in progress

func KeyHasSecretKeyword

func KeyHasSecretKeyword(key string) bool

Whether a mapping key names a secret by a word bounded secret keyword

func KillAndDrain

func KillAndDrain(proc DrainableChild, timeout time.Duration) (stdout, stderr []byte, ok bool)

KillAndDrain tree kills proc then returns what its pipes still hold within timeout, false when a survivor holds them

func KillChildTree

func KillChildTree(proc ChildProcess, grace time.Duration)

KillChildTree terminates proc and its descendants on both platforms and swallows every failure

func KillLiveForegroundProcesses

func KillLiveForegroundProcesses(now bool) int

KillLiveForegroundProcesses kills every in flight foreground command tree and returns how many were signalled

func KillProcessTree

func KillProcessTree(pid int)

KillProcessTree kills pid and every descendant through the shared deadline tree kill

func KnownReads

func KnownReads(taskID string) []string

KnownReads lists the resolved paths a task has read through the file tools

func LSPCommandContext

func LSPCommandContext(env *Env) lsp.CommandContext

LSPCommandContext is what icebath lsp reads from the session's profile

func LSPDeferredPost

func LSPDeferredPost(owner, path, text string, baseline *string)

LSPDeferredPost queues a finished verdict for the owner under the path

func LSPDeferredSettled

func LSPDeferredSettled(owner string, token any)

LSPDeferredSettled marks the owner check of the token finished and wakes waiters

func LSPDeferredTrackPending

func LSPDeferredTrackPending(owner string) any

LSPDeferredTrackPending marks a check running for the owner and returns its settle token

func LSPForwardToAgent

func LSPForwardToAgent(sessionID, taskID string, queuePluginNotice func(key, text string))

LSPForwardToAgent moves the agent's finished verdicts onto its live notes queue under lsp path keys

func LSPOwner

func LSPOwner(ctx context.Context) string

Session an edit under the context attributes its late LSP verdicts to, empty when unbound

func LSPRuntime

func LSPRuntime(env *Env) *lsp.Runtime

LSPRuntime wires the LSP layer to a session's profile, managed packages, child env and process ledger

func LSPServiceFor

func LSPServiceFor(env *Env) (*lsp.Service, error)

LSPServiceFor returns the active LSP service of the session's profile, built on first use, nil when disabled

func LastResolvedToolNames

func LastResolvedToolNames() []string

LastResolvedToolNames lists the names of the most recently computed definition list

func LedgerEntries

func LedgerEntries(opts LedgerOptions) []map[string]any

LedgerEntries lists the live rows of this install, or of every install when asked

func LifecycleScanRootWithinBudget

func LifecycleScanRootWithinBudget(text string) bool

LifecycleScanRootWithinBudget reports whether text may enter an optional tokenizer pass on a fresh budget

func LinkedTerminalBuiltins

func LinkedTerminalBuiltins() []string

LinkedTerminalBuiltins lists the built in backend names this binary carries, in menu order

func ListAsyncDelegations

func ListAsyncDelegations() []map[string]any

Snapshot of running and recently completed delegations with live progress fields and stall context

func ListCheckpointProjectRefs

func ListCheckpointProjectRefs(env *Env, store, workingDir string) []string

Refs in a store that belong to the working directory's project

func ListDistributions

func ListDistributions() map[string]Distribution

ListDistributions returns a copy of every distribution keyed by name

func ListGatewayApprovals

func ListGatewayApprovals(sessionKey string) []map[string]any

ListGatewayApprovals returns replay safe snapshots of the unresolved approvals of one session

func ListPending

func ListPending(env *Env, subsystem string) []map[string]any

Every readable pending record of the subsystem, oldest first

func ListingTokenBudget

func ListingTokenBudget(cfg ToolSearchConfig, contextLength int) int

ListingTokenBudget is the smaller of the listing cap and the threshold share of the context

func LiveClose

func LiveClose(op *ConnectionOperation)

Drops the operation from the live table when it is still the registered one

func LiveDelegationBatches

func LiveDelegationBatches(parentSessionID string) int

Number of live async delegation batches a parent session spawned

func LiveOpen

func LiveOpen(ctx context.Context, op *ConnectionOperation) error

Registers the operation as its profile session's open one, refusing while another is unsettled

func LiveProcessPids

func LiveProcessPids(paths []string, exclude []int) map[string][]int

Pids of live processes working in each path keyed by the path as given, excluded pids ignored

func LiveResetForTests

func LiveResetForTests()

Settles every live operation as interrupted so its driver ends, then empties the live table between tests

func LiveTranscriptDirReferenced

func LiveTranscriptDirReferenced(ctx context.Context, db any, dir string) (bool, error)

Whether a stored child session still names a log inside the delegation directory

func LoadCheckpointLedger

func LoadCheckpointLedger(store, dirHash string) map[string]any

Ledger of one project's checkpoints in a store, empty when absent

func LoadDelegationConfig

func LoadDelegationConfig(ctx context.Context) map[string]any

Delegation section of the effective config, the legacy CLI config when user config is ignored, empty on failure

func LoadPermanent

func LoadPermanent(env *Env, patterns map[string]bool)

LoadPermanent replaces the permanent allowlist entries in memory

func LoadPermanentAllowlist

func LoadPermanentAllowlist(env *Env) map[string]bool

LoadPermanentAllowlist syncs command_allowlist from config into the approval state

func LocalBatchError

func LocalBatchError(entries []ToolCallEntry) string

LocalBatchError rejects a multi entry batch naming a local tool while echoing the first entry

func LocateCommand

func LocateCommand(name string) []string

Argv of the first present PATH candidate for a command name, nil when it is not found

func LocateUserCommand

func LocateUserCommand(name string) []string

Argv of the first present candidate for a command on PATH and then in the per user bin directory, nil when it is not found

func LockedSkillDirs

func LockedSkillDirs(env *Env) []lockedSkill

LockedSkillDirs lists name and real path of every locked skill in the active profile

func LogScheduleFailure

func LogScheduleFailure(ctx context.Context, log *slog.Logger, logMessage string, level slog.Level, err error)

Logs why work could not be scheduled, the default logger and message standing in when none is given

func LooksLikeTableRow

func LooksLikeTableRow(row string) bool

True when the stripped row starts with a pipe or holds at least two pipes

func LookupSupportsVision

func LookupSupportsVision(ctx context.Context, env *Env, provider, model string) (bool, bool)

LookupSupportsVision reports the vision verdict for a provider and model under the session config and whether it is known

func MCPServerEnabled

func MCPServerEnabled(serverCfg map[string]any) bool

MCPServerEnabled reports whether an mcp_servers entry is enabled unless explicitly off

func MSYSToWindowsPath

func MSYSToWindowsPath(p string) string

Windows form of an MSYS style drive path, the exported form the binary uses for chat --in

func MaintainPackHealth

func MaintainPackHealth(ctx context.Context, repoRoot string)

MaintainPackHealth repacks a repository once its refs are final

func MakeRunEnv

func MakeRunEnv(ctx context.Context, env *Env, childEnv map[string]string) (map[string]string, error)

Run environment the local backend hands a child process, the backend's own env on top

func MakeToolResultMessage

func MakeToolResultMessage(name string, content any, toolCallID string, effectDisposition string) *state.Message

MakeToolResultMessage builds a tool result row with untrusted content wrapped in delimiters

func ManageConnections

func ManageConnections(ctx context.Context, env *Env, args map[string]any, opts ManageOptions) string

Runs one manage_connections call over the named MCP servers

func MapCachePathToContainer

func MapCachePathToContainer(env *Env, hostPath, containerBase string) string

MapCachePathToContainer returns the container path for a host path under a cache dir or empty

func MarkClarifyAwaitingText

func MarkClarifyAwaitingText(clarifyID string) bool

MarkClarifyAwaitingText flips an entry into text capture mode, false if unknown

func MarkCopyHeld

func MarkCopyHeld(delegationID string)

Records that a consumer holds one copy of a delegation off every queue

func MarkLaunchYoloApplied

func MarkLaunchYoloApplied(sessionKey string) bool

MarkLaunchYoloApplied records the launch yolo seed once per session, false when already seeded

func MarkRecommended

func MarkRecommended(choices []string) []string

MarkRecommended suffixes the first of two or more choices with the label, idempotently

func MarkSeen

func MarkSeen(ctx context.Context, configPath, flag string) bool

Persists onboarding.seen.flag as true atomically, false on any error

func MarkUnmarkedPacksPromisor

func MarkUnmarkedPacksPromisor(repoRoot string) int

Gives every pack without a promisor marker one and returns how many were marked

func MaskDisplaySecret

func MaskDisplaySecret(value string, head, tail, floor int) string

Exported maskSecret

func MaxAsyncChildren

func MaxAsyncChildren(ctx context.Context) int

Background delegation cap equal to the concurrent child limit, a legacy max_async_children key warned once

func MaxConcurrentChildren

func MaxConcurrentChildren(ctx context.Context) int

Parallel child limit from config, then DELEGATION_MAX_CONCURRENT_CHILDREN, then ten, floored at one

func MaxSpawnDepth

func MaxSpawnDepth(ctx context.Context) int

Spawn depth cap floored at one with a warning below the floor

func MaybeAppendElisionNotice

func MaybeAppendElisionNotice(name string, content any) any

MaybeAppendElisionNotice appends the incompleteness notice to untrusted results with elision markers

func MaybePersistToolResult

func MaybePersistToolResult(ctx context.Context, env *Env, sandbox Environment, content, toolName, toolUseID string, cfg BudgetConfig, threshold int) string

MaybePersistToolResult persists an oversized result and returns the preview plus path block

func MaybeRequireEditApproval

func MaybeRequireEditApproval(ctx context.Context, env *Env, toolName string, arguments map[string]any) (string, error)

Runs the bound ACP edit approval, a tool error JSON when the edit must be blocked and empty to continue

func MaybeSweepOrphanedCompletions

func MaybeSweepOrphanedCompletions(env *Env, q *EventQueue, now *float64) int

Runs the orphan sweep at most once per interval per home on the monotonic clock, never failing the loop

func MaybeWrapUntrusted

func MaybeWrapUntrusted(name string, content any) any

MaybeWrapUntrusted wraps high risk tool content in untrusted data delimiters

func MsysToWindowsPath

func MsysToWindowsPath(p string) string

Native Windows form of a Git Bash drive path, unchanged off Windows

func MultimodalTextSummary

func MultimodalTextSummary(value any) string

MultimodalTextSummary is the plain text view of a tool result

func MultiplexActive

func MultiplexActive() bool

MultiplexActive reports the process wide multiplex flag

func MultiplexActiveFor

func MultiplexActiveFor(ctx context.Context, env *Env) bool

Whether one call runs under multiplex semantics, from the process flag, the tool env or the context

func MustScanForThreats

func MustScanForThreats(content, scope string) []string

MustScanForThreats scans with a known scope and panics on an unknown one

func NTNamespaceError

func NTNamespaceError(path, verb string) string

NT or device namespace refusal for the verb, empty for an ordinary path

func NativeToolResultImages

func NativeToolResultImages(ctx context.Context, env *Env, provider, model string) bool

NativeToolResultImages reports whether a tool may hand the main model pixels inside its result

func NativeTurnImages

func NativeTurnImages(env *Env, userMessage any) func()

NativeTurnImages scopes the images natively attached to a user message to the running turn and returns the restore func

func NearestVercelProject

func NearestVercelProject(start string) (map[string]string, error)

Non blank projectId and orgId of the nearest .vercel/project.json at or above start, the working directory when start is empty

func NemoRelayReady

func NemoRelayReady() bool

Whether the registered binding finds its runtime provisioned

func NewDaytonaEnvironment

func NewDaytonaEnvironment(ctx context.Context, env *Env, o DaytonaOptions) (*daytonaEnv, error)

NewDaytonaEnvironment resumes the task's sandbox or creates one, resolves the home, seeds the sync and starts the session

func NewDelegationID

func NewDelegationID() string

NewDelegationID is a fresh async delegation id

func NewDockerEnvironment

func NewDockerEnvironment(ctx context.Context, env *Env, o DockerOptions) (*dockerEnv, error)

NewDockerEnvironment creates or reattaches the container and seeds the shell snapshot

func NewLocalEnvironment

func NewLocalEnvironment(ctx context.Context, env *Env, cwd string, timeout int, childEnv map[string]string, persistent bool) *localEnv

NewLocalEnvironment builds the host backend and captures its login shell snapshot

func NewModalEnvironment

func NewModalEnvironment(ctx context.Context, env *Env, o ModalOptions) (*modalEnv, error)

NewModalEnvironment creates the sandbox, restoring a stored snapshot when persistent, and seeds the sync

func NewParentCopy

func NewParentCopy(text, forced string) any

Text for the parent remembering the forced projection, the plain string when both match

func NewSSHEnvironment

func NewSSHEnvironment(ctx context.Context, env *Env, o SSHOptions) (*sshEnv, error)

NewSSHEnvironment connects, detects the remote home, seeds the remote icebath tree and starts the session

func NewSSRFSafeClient

func NewSSRFSafeClient(env *Env, timeout time.Duration, followRedirects bool) *http.Client

HTTP client that vets every connect address against SSRF rules

func NewVercelSandboxEnvironment

func NewVercelSandboxEnvironment(ctx context.Context, env *Env, o VercelOptions) (*vercelEnv, error)

NewVercelSandboxEnvironment creates or restores the sandbox, waits for it to run, wires the sync and starts the session

func NewWorkerPersistenceError

func NewWorkerPersistenceError(reason string) error

Builds the error a worker raises with the owner rpc reason code

func NoCacheCheck

func NoCacheCheck(fn func(*Env) bool) func(*Env) bool

NoCacheCheck marks a config backed availability check as never cached

func NoUserCanAnswer

func NoUserCanAnswer(env *Env) bool

Reports single query, cron and unattended platform sessions where no user can answer

func NoninteractiveGitEnv

func NoninteractiveGitEnv(base map[string]string) map[string]string

Environment for internal git and gh runs that never prompt, page or read user git config

func NoninteractiveRepoGitEnv

func NoninteractiveRepoGitEnv(cwd string, base map[string]string) map[string]string

NoninteractiveRepoGitEnv hardens git for one repository, nil when filter discovery cannot be trusted

func NormalizeApprovalMode

func NormalizeApprovalMode(mode any) string

Configured approval mode normalized to manual, smart or off, unknown strings falling back to manual

func NormalizeBrowserCloudProvider

func NormalizeBrowserCloudProvider(value string) string

NormalizeBrowserCloudProvider returns the normalized browser provider key

func NormalizeCommand

func NormalizeCommand(command string) string

NormalizeCommand folds user and icebath home prefixes and collapses whitespace

func NormalizeHandlerResult

func NormalizeHandlerResult(env *Env, name string, result any) string

Bounds a str result, keeps the multimodal envelope as JSON and turns any other value into a contract error

func NormalizeProjectSlug

func NormalizeProjectSlug(slug string) (string, error)

NormalizeProjectSlug lowercases and validates a slug, empty for empty input

func NormalizeProviderToolCallIDs

func NormalizeProviderToolCallIDs(toolCalls []state.ToolCall) []state.ToolCall

NormalizeProviderToolCallIDs rewrites known provider ids a parallel batch replay would reject, id and call_id alike

func NormalizeQuery

func NormalizeQuery(query string) string

NormalizeQuery case folds and collapses whitespace so trivial variants share an entry

func NormalizeSymbolsForTTS

func NormalizeSymbolsForTTS(text string) string

Symbols, units, currencies and shorthand expanded into words a voice reads well

func NormalizeTargets

func NormalizeTargets(raw any) ([]string, string)

MCP server names of the connectors argument, or the reason it is malformed

func NormalizeTaskImages

func NormalizeTaskImages(task map[string]any, i int) ([]string, string)

Cleaned image list of one task with a bare string wrapped, nil when absent or empty

func NormalizeTaskList

func NormalizeTaskList(goal, context, tasks, outputSchema any, topRole string, maxChildren int) ([]map[string]any, string, error)

Task list from tasks or the legacy single goal, an error message for the model, an error where Python raises

func NormalizeToSupportedImage

func NormalizeToSupportedImage(env *Env, imagePath, detectedMime string) (string, string, string)

NormalizeToSupportedImage re-encodes formats providers reject as PNG, returning the path, MIME, and an error message

func NormalizeToolCallID

func NormalizeToolCallID(toolCallID string) string

NormalizeToolCallID reduces a composite bridge id to its canonical call id half

func NormalizeURLForRequest

func NormalizeURLForRequest(raw string) string

Url re quoted the way a request client sends it, path query and fragment percent encoded

func NotDeferrableError

func NotDeferrableError(ctx context.Context, env *Env, name string, sessionToolNames map[string]bool) string

NotDeferrableError rejects a tool_call naming something that is not a deferred tool

func NoteConfigPolicy

func NoteConfigPolicy(homeKey string, raw any)

Records the security.redact_secrets value a profile config holds

func NoteEnvPolicy

func NoteEnvPolicy(homeKey string, raw any)

Records the ICEBATH_REDACT_SECRETS value a profile dotenv holds

func NotifyOtherToolCall

func NotifyOtherToolCall(taskID string)

NotifyOtherToolCall resets the consecutive read counter, stub hits and not found cache of a task

func OSPathExpandVars

func OSPathExpandVars(p string) string

Expands environment references like os.path.expandvars

func ObserveGatewaySettle

func ObserveGatewaySettle(sessionKey, requestID string, observer func(reason string)) bool

ObserveGatewaySettle adds an observer without replacing the settle hook

func OneshotCompletionWaitSeconds

func OneshotCompletionWaitSeconds(env *Env) float64

OneshotCompletionWaitSeconds returns the configured one shot completion linger budget in seconds

func OneshotDelegateFunction

func OneshotDelegateFunction(function *pyjson.Object) *pyjson.Object

Built delegate_task definition without live control for a one shot session whose children join in the call

func OneshotMaxChildren

func OneshotMaxChildren(ctx context.Context) int

Total children one finite one shot session may spawn, zero for unlimited

func OpenAndDrive

func OpenAndDrive(ctx context.Context, env *Env, op *ConnectionOperation, kind ConnKind, cb ConnCallback, tick *float64, withURLs bool) string

Registers the operation as the session's open one and drives it, one open per session

func OpenExclusive

func OpenExclusive(path string, private, overwrite bool) (*os.File, error)

OpenExclusive creates the file exclusively never following a link, unlinking first when overwriting

func OperationSessionKey

func OperationSessionKey(env *Env, sessionID string) string

The key an operation registers under, the gateway session key else the agent session id

func OrchestratorEnabled

func OrchestratorEnabled(ctx context.Context) bool

Orchestrator kill switch, true unless a bool false or a falsy string turns it off

func OrderedStaticToolsetNames

func OrderedStaticToolsetNames() []string

OrderedStaticToolsetNames lists the static toolset table in definition order

func OutOfScopeReason

func OutOfScopeReason(ctx context.Context, env *Env, name string) string

OutOfScopeReason names the TUI as the only surface of a client surface tool outside this session

func OutputTail

func OutputTail(s *ProcessSession, n int) string

OutputTail is the last n characters of a session output buffer

func OwnProcessGroups

func OwnProcessGroups(pgids []int)

OwnProcessGroups makes these process groups die with this process however it dies

func OwnedKanbanTask

func OwnedKanbanTask(ctx context.Context) string

Board task this execution owns, ICEBATH_KANBAN_TASK for the dispatcher owned worker and empty otherwise

func OwnerDeathSupervisorPID

func OwnerDeathSupervisorPID() int

OwnerDeathSupervisorPID is the pid of the published supervisor, zero when none runs

func OwnsEvent

func OwnsEvent(evt map[string]any, sessionKey string, owns func(map[string]any) bool, isAsyncDelegation bool) bool

Routing verdict for one drained event under the owner predicate, false meaning requeue

func ParentAgentFrom

func ParentAgentFrom(ctx context.Context) any

Parent agent bound to the context, nil when none was bound

func ParseApplyIndices

func ParseApplyIndices(spec string, total int) ([]int, error)

ParseApplyIndices parses a selection like 1,3 into validated zero based indices

func ParseConfigStringList

func ParseConfigStringList(value any) []string

ParseConfigStringList reads a config value that may hold a list literal string into names

func ParseEnabledFlag

func ParseEnabledFlag(value any, def bool) bool

ParseEnabledFlag reads bool like tool and platform settings, the default for anything unrecognised

func ParsePlatformToolsetsValue

func ParsePlatformToolsetsValue(value any) ([]string, bool)

ParsePlatformToolsetsValue reads a saved platform_toolsets value as the list it encodes

func ParseToolArguments

func ParseToolArguments(raw string) (map[string]any, string)

ParseToolArguments parses model emitted arguments without repairing them

func PartialCloneFilter

func PartialCloneFilter(ctx context.Context, repoRoot string, kw pysubprocess.Options) (string, error)

The checkout's own partial clone filter, empty for a clone that is not partial

func PathsOverlap

func PathsOverlap(left, right string) bool

PathsOverlap is true when two canonical paths may refer to the same subtree

func PauseCommand

func PauseCommand(ctx context.Context, ns map[string]any, w io.Writer) (int, error)

Engages the emergency stop with an optional reason

func PausedReply

func PausedReply(ctx context.Context) string

Short notice for new gateway turns while paused, empty when not paused

func PeelBridgeCall

func PeelBridgeCall(ctx context.Context, env *Env, toolName string, functionArgs map[string]any) (string, map[string]any)

PeelBridgeCall resolves a tool_call bridge invocation to its underlying tool for admission

func PendingCount

func PendingCount(env *Env, subsystem string) int

Count of pending record files for notification badges

func PendingWriteDir

func PendingWriteDir(env *Env, subsystem string) string

Directory holding one subsystem's staged write records

func PersistCompletion

func PersistCompletion(env *Env, event, result map[string]any) error

Writes the terminal event and result of one delegation the way its completion path does

func PersistDispatch

func PersistDispatch(env *Env, record map[string]any) error

Writes the running row of a fresh dispatch, exported for delegation lifecycle callers

func PhysicalMemoryBytes

func PhysicalMemoryBytes() (int64, bool)

Physical memory of the host in bytes, false when the platform probe fails

func PidAliveMatches

func PidAliveMatches(pid int, createTime *float64, strict bool, boot *float64) (alive bool, known bool)

Tri state liveness proof of pid against a recorded birth, known false when the prober cannot say

func PidExistsStdlib

func PidExistsStdlib(pid int) (bool, error)

PidExistsStdlib reports pid alive without signalling it, a zombie dead, another user's process alive and pid zero alive

func PinChildServiceTier

func PinChildServiceTier(child DelegateRouteAgent, creds map[string]any)

Reapplies a task speed tier to the built child after construction merged provider extra_body back

func PinnedBackend

func PinnedBackend(a DelegationBackendAgent) string

Backend the agent delegate_task was built from, empty for no agent or one never built

func PlatformDefaultToolset

func PlatformDefaultToolset(platform string) string

PlatformDefaultToolset returns the composite a platform falls back to

func PlatformGPULabel

func PlatformGPULabel(gpu string) string

User facing phrase naming a requires.gpu value, empty for None

func PlatformSkillAppAvailability

func PlatformSkillAppAvailability(name string) (declared bool, offerable bool)

Skill requires_apps verdict of a name, declared only with an app block, offerable by availability

func PlatformTierRefusal

func PlatformTierRefusal(key string) (string, bool)

PlatformTierRefusal is the line naming the build that carries a tool configurator platform this binary leaves out

func PlatformToolsetsExplicitlySaved

func PlatformToolsetsExplicitlySaved(cfg config.Tree, platform string) bool

Whether platform_toolsets holds an explicitly saved list for the platform, a list literal string counting

func PlatformVersionAtLeast

func PlatformVersionAtLeast(found, minimum string) bool

Compares dot separated decimal components, failing closed on invalid input

func PluginBackendIsRemote

func PluginBackendIsRemote(backend string) bool

Whether a plugin registered backend declares itself remote

func PluginBackendNames

func PluginBackendNames(ctx context.Context, scope string) []string

Lower cased names of every plugin backend visible in scope, sorted

func PluginStripEnvKeys

func PluginStripEnvKeys() map[string]bool

Union of every registered plugin backend's strip_env_keys across every scope, a panicking provider contributing nothing

func PluginToolsetKeys

func PluginToolsetKeys(ctx context.Context) (keys map[string]bool)

Toolset keys plugins provide, empty when the plugin system fails

func PopRelayScope

func PopRelayScope(ctx context.Context, relay *NemoRelay, handle, output, metadata, timestamp any) (any, error)

Pops a Relay scope forwarding only the keyword arguments the live binding accepts

func PopRelayScopeIfTop

func PopRelayScopeIfTop(ctx context.Context, relay *NemoRelay, handle, output, metadata any) (bool, error)

Pops handle only while it tops the scope stack, reporting a scope pushed over it meanwhile as not popped

func PortableMCPServerSet

func PortableMCPServerSet(ctx context.Context) map[string]bool

PortableMCPServerSet lists the in memory portable plugin MCP servers, the projected set first

func PostToolCallHookSuppressed

func PostToolCallHookSuppressed(ctx context.Context) bool

PostToolCallHookSuppressed reports whether an outer executor owns the post tool event for this context

func PrepareSpokenText

func PrepareSpokenText(text string, maxChars *int) string

Spoken script of assistant text cut to maxChars code points, nil or non positive leaving it uncut

func PrepareSpokenTextUncapped

func PrepareSpokenTextUncapped(text string) string

Spoken script with no length cap, the name tts_tool and the voice paths call

func PrintDistributionInfo

func PrintDistributionInfo(w io.Writer, name string)

PrintDistributionInfo writes a distribution's description and toolset chances highest first

func PrivateWorktreeRefs

func PrivateWorktreeRefs(wtPath string, env map[string]string) ([]string, error)

Per worktree refs holding commits no branch, tag, remote or archive reaches

func ProbeRemoteBackend

func ProbeRemoteBackend(ctx context.Context, env *Env, envType string) (string, bool, error)

Cached live description of a non local backend, false when the probe failed or returned nothing

func ProcessAccountingLines

func ProcessAccountingLines(r map[string]any) []string

ProcessAccountingLines are the runtime truth lines about one result entry background processes

func ProcessBirth

func ProcessBirth(pid int) (float64, error)

ProcessBirth is the epoch birth of a managed worker, the same in every process

func ProcessChildren

func ProcessChildren(pid int) []int

ProcessChildren lists the direct children of pid from the process table

func ProcessCmdline

func ProcessCmdline(pid int) ([]string, error)

ProcessCmdline is the argv of a live process, an error once it is gone or unreadable

func ProcessCompletionDisplayText

func ProcessCompletionDisplayText(events []map[string]any) string

ProcessCompletionDisplayText is the compact UI title of one or more process completions

func ProcessCreateTime

func ProcessCreateTime(pid int) *float64

ProcessBirth of pid or of this process when pid is zero, nil when unreadable

func ProcessGroupSupervised

func ProcessGroupSupervised(pgid int) bool

Reports whether the owner death supervisor currently covers the process group

func ProcessStartTime

func ProcessStartTime(pid int) (int64, bool)

Start time fingerprint of a live process

func ProcessZombie

func ProcessZombie(pid int) bool

ProcessZombie reports whether pid exited and awaits its reaper

func ProfileBuildDirective

func ProfileBuildDirective() string

System note directive of the very first message, an opt in profile build that asks before any lookup

func ProfileBuildMode

func ProfileBuildMode(cfg any) string

off never offers the profile build, every other onboarding.profile_build value asks

func ProjectFactsFor

func ProjectFactsFor(cwd string) map[string]any

ProjectFactsFor exposes the structured project facts of a directory

func ProjectsCommand

func ProjectsCommand(ctx context.Context, env *Env, ns map[string]any, w, errw io.Writer) (int, error)

Entry point of icebath project, the bare command printing its usage

func ProjectsDBPath

func ProjectsDBPath(h string) string

ProjectsDBPath is the per profile projects database under the home

func PropagateContextToThread

func PropagateContextToThread(ctx context.Context, env *Env, target func(ctx context.Context, env *Env) (any, error)) func() (any, error)

Snapshots the caller's context vars and prompt callbacks now and returns a worker that runs target under them

func ProviderEnvBlocklist

func ProviderEnvBlocklist() map[string]bool

ProviderEnvBlocklist is the union of provider credentials and adapter secrets, built on first use

func ProvisionNemoRelay

func ProvisionNemoRelay(ctx context.Context, w io.Writer) error

Provisions the Relay runtime with progress on w through the registered step

func PruneExpiredArchives

func PruneExpiredArchives(repoRoot string, retentionDays float64, now float64, dryRun bool) ([]string, error)

Deletes archive refs older than the retention window, zero keeps them forever, dry run only lists them

func PruneIdentifierTokensForTTS

func PruneIdentifierTokensForTTS(text string) string

Identifier dense tokens silenced while ordinary prose stays verbatim

func PruneMissingRegistrations

func PruneMissingRegistrations(repoRoot string, dryRun bool) ([]string, error)

Drops registrations whose directory no longer exists, metadata only

func PruneStaleShallowGrafts

func PruneStaleShallowGrafts(ctx context.Context, repoRoot string) int

Drops shallow graft lines no live ref or reflog still points at, restoring the file when history stops walking

func PruneStaleWorktrees

func PruneStaleWorktrees(ctx context.Context, repoRoot string, maxAgeHours int) error

Removes stale worktrees and orphaned branches, then reclaims the dependency state of deleted checkouts

func PruneTierHours

func PruneTierHours(name string, maxAgeHours float64) float64

Idle hours before a tree may be reclaimed, the base tier for icebath made trees and three times that otherwise

func PushCompletionEvent

func PushCompletionEvent(env *Env, record, result map[string]any, status string)

Pushes the completion event and its durable row, exported for delegation lifecycle callers

func PushTaskFailureNotice

func PushTaskFailureNotice(env *Env, delegationID string, entry map[string]any, nTasks int)

Surfaces one failed child of a still running batch now, in process only so it honours the redaction opt out

func PyContainsKanban

func PyContainsKanban(v any) bool

PyContainsKanban reports Python membership of kanban in a toolsets config value

func PythonCallArgs

func PythonCallArgs(call *Call) map[string]any

Python values of a call's args for handlers outside the package, ints kept apart from floats

func QualifyTaskKey

func QualifyTaskKey(env *Env, key string) string

Session derived key prefixed with the routed profile home of env, unchanged without one

func RasterSize

func RasterSize(data []byte) (int, int, error)

Width and height of the first frame as Pillow Image.open reports size, an error for bombs and unreadable bytes

func ReadBlockError

func ReadBlockError(env *Env, path string) string

Refusal message for a read of a denied icebath path, empty when the read is allowed

func ReadSelection

func ReadSelection(env *Env, section string) string

ReadSelection returns the persisted tools selection for a section, a vendor, or empty

func ReadTextWithTimeout

func ReadTextWithTimeout(env *Env, path string, timeout *float64) (string, bool, error)

Reads path on its own goroutine, false after the timeout so a slow file cannot stall prompt building

func ReadWebCapabilitySelection

func ReadWebCapabilitySelection(env *Env, capability string) string

ReadWebCapabilitySelection returns the selection deciding one web capability

func RealignMarkdownTables

func RealignMarkdownTables(text string, availableWidth *int) string

Every pipe table under a divider rewritten with width aware padding, other lines verbatim

func ReclaimBranches

func ReclaimBranches(repoRoot string, dryRun bool, records []BranchRecord) ([]string, error)

Deletes every delete verdict branch of a frozen audit list

func ReclaimWorktrees

func ReclaimWorktrees(ctx context.Context, repoRoot string, dryRun bool, records []TreeRecord) ([]string, error)

Removes every reap verdict tree of a frozen audit list, archiving untracked scratch first

func RecordLaunchDotenvKeys

func RecordLaunchDotenvKeys(keys []string)

RecordLaunchDotenvKeys remembers names a non managed dotenv load put into the process environment

func RecordSessionCwd

func RecordSessionCwd(env *Env, sessionKey, cwd string)

RecordSessionCwd records the working directory a session finished in

func RecordTUIWorktree

func RecordTUIWorktree(ctx context.Context, wtInfo map[string]string)

Remembers a tree the TUI worktree launcher created or a worktree new moved a session into, never raising

func RecordUnitChild

func RecordUnitChild(env *Env, delegationID string, child any) error

Durably records one finished child of a running multi child unit so a crash loses only unfinished children

func RecoverAbandonedDelegations

func RecoverAbandonedDelegations(env *Env) (int, error)

Classifies rows whose owner process disappeared as outcome unknown, replaying recorded unit children

func RecreateTUIWorktree

func RecreateTUIWorktree(ctx context.Context, cwd, sessionID string) string

RecreateTUIWorktree brings back the launcher made tree a resumed session's missing cwd names, empty when it cannot

func RedactApprovalDisplay

func RedactApprovalDisplay(env *Env, text string, force bool) string

Secret redaction plus display sanitizing of approval text for the gateway's own prompts

func RedactCDPURL

func RedactCDPURL(value string) string

Cdp endpoint url safe to log, query credentials and userinfo passwords masked

func RedactChildResult

func RedactChildResult(env *Env, result any, outputSchema any, force bool) any

Projection of a result or batch keeping accounting and host owned identity, revalidating a summary redaction changed

func RedactChildResultAt

func RedactChildResultAt(env *Env, result any, outputSchema any, force bool, validateDepth int) any

RedactChildResult whose revalidation runs validateDepth Python frames deep, the depth of the reference call site it mirrors

func RedactChildText

func RedactChildText(env *Env, text any, force bool) (out string)

Scrubbed child produced string, force false honouring the user opt out while vault values stay scrubbed

func RedactChildValue

func RedactChildValue(env *Env, value any, force bool) any

Copy of JSON shaped child data with unsupported or overly deep values withheld

func RedactCompletionEvent

func RedactCompletionEvent(env *Env, event any, force bool) any

Completion event with child output scrubbed and parent instructions and routing left exact

func RedactEnabled

func RedactEnabled(ctx context.Context) bool

Whether secret redaction is on for the context profile under its live environment and recorded policy

func RedactForEgress

func RedactForEgress(env *Env, text string) (out string)

RedactForEgress scrubs text leaving the process for a remote reader, forced plus a bearer sweep

func RedactLiteralPrefix

func RedactLiteralPrefix(pattern string) string

Leading literal characters of a prefix pattern, the text a synthetic token starts with

func RedactPrefixPatterns

func RedactPrefixPatterns() []string

Every builtin and plugin prefix pattern the matcher runs in registration order, the corpus egress callers test against

func RedactPrefixSearch

func RedactPrefixSearch(text string) bool

Text carrying a known secret prefix the redaction patterns recognise, the browser url guard input

func RedactSensitiveText

func RedactSensitiveText(text string) string

RedactSensitiveText applies the default redaction passes to a block of text

func RedactSensitiveTextInProfile

func RedactSensitiveTextInProfile(ctx context.Context, text string) string

Default redaction of text under the redaction switch of the context profile, its vault secrets always scrubbed

func RedactSensitiveTextWith

func RedactSensitiveTextWith(env *Env, text string, o RedactOptions) string

RedactSensitiveTextWith applies every redaction pattern to a block of text under the given options

func RedactSummary

func RedactSummary(env *Env, summary any, structured, force bool) any

Summary redacted per value when structured, exported for the delegation result pipeline

func RedactTerminalCommandOutput

func RedactTerminalCommandOutput(env *Env, output, command string, force bool) string

RedactTerminalCommandOutput redacts terminal output with the assignment pass only for env dumps and secret file reads

func RedactToolArgsForDisplay

func RedactToolArgsForDisplay(env *Env, toolName string, args map[string]any) map[string]any

RedactToolArgsForDisplay copies tool args safe for logs and progress UI

func RefLockFiles

func RefLockFiles(gitDir string) []string

The packed-refs lock then every refs lock file in path component order

func RefSafe

func RefSafe(name string) string

A tree name as one valid ref component

func ReferencedSpilloverNames

func ReferencedSpilloverNames(spillDir string) (map[string]bool, bool)

ReferencedSpilloverNames returns basenames still referenced by any transcript row, nil when unknown

func RefuseAsyncDelegationsForSession

func RefuseAsyncDelegationsForSession(token any, sessionKey string, parentSessionIDs []string)

Refuses new dispatches for one closing session until its refusal is lifted

func RefusedResult

func RefusedResult(reason string) string

Error result of a call the tool declined before doing anything, the reason the model and the person read

func Register

func Register(d Def)

Register adds a builtin tool to the default registry

func RegisterApprovalTransportResolver

func RegisterApprovalTransportResolver(fn func(env *Env, name string) (*RegisteredApprovalTransport, error))

RegisterApprovalTransportResolver installs the plugin manager lookup for named transports

func RegisterChild

func RegisterChild(ctx context.Context, pid int, purpose, projectRoot string) bool

RegisterChild records a child this process just spawned with this process as its spawner

func RegisterContainerAlias

func RegisterContainerAlias(childTaskID, parentTaskID string)

RegisterContainerAlias makes a child task resolve to its parent's container

func RegisterCredentialFile

func RegisterCredentialFile(env *Env, relativePath, containerBase string) bool

RegisterCredentialFile registers a home relative credential file for mounting

func RegisterCredentialFiles

func RegisterCredentialFiles(env *Env, entries []any, containerBase string) []string

RegisterCredentialFiles registers skill frontmatter entries and returns the missing ones

func RegisterEnvPassthrough

func RegisterEnvPassthrough(env *Env, varNames []string)

RegisterEnvPassthrough allows env var names in sandboxed environments, refusing provider credentials

func RegisterGatewayNotify

func RegisterGatewayNotify(sessionKey string, cb GatewayNotifyFunc)

RegisterGatewayNotify installs the callback that sends approval requests for a session

func RegisterGatewaySettle

func RegisterGatewaySettle(sessionKey, requestID string, settle func(reason string)) bool

RegisterGatewaySettle attaches the hook run once when the wait ends by any path

func RegisterInlineToolExecutor

func RegisterInlineToolExecutor(name string, fn InlineToolExecutor)

RegisterInlineToolExecutor installs the agent level executor for a tool name

func RegisterNemoRelayBinding

func RegisterNemoRelayBinding(load func() (*NemoRelay, error))

Installs the native binding loader the runtime imports on first use, dropping the readiness check of the loader it replaces

func RegisterNemoRelayProvisioner

func RegisterNemoRelayProvisioner(provision func(ctx context.Context, w io.Writer) error)

Installs the step that provisions the Relay runtime with progress on a writer, the switch on of Relay plugins

func RegisterNemoRelayReadiness

func RegisterNemoRelayReadiness(ready func() bool)

Installs the check whether the registered binding finds its runtime provisioned

func RegisterPermissionModeReleaser

func RegisterPermissionModeReleaser(fn func(ctx context.Context, sessionKey string))

RegisterPermissionModeReleaser adds a hook run on both yolo edges and at session clear with the caller's context

func RegisterPlatformDeclaration

func RegisterPlatformDeclaration(serverName string, decl *PlatformDeclaration)

Records which declaration gates a server name

func RegisterRedactionPatterns

func RegisterRedactionPatterns(patterns any, source string) (int, error)

RegisterRedactionPatterns additively registers credential token regexes and returns how many were accepted

func RegisterSchemaRewriter

func RegisterSchemaRewriter(name string, fn SchemaRewriter)

RegisterSchemaRewriter installs a dynamic schema rewriter for one tool name and drops memoized definitions

func RegisterSelf

func RegisterSelf(ctx context.Context, purpose, projectRoot string) bool

RegisterSelf records this process in the machine spawn ledger

func RegisterSessionCloser

func RegisterSessionCloser(fn func(sessionKey string))

RegisterSessionCloser adds a hook run when a session's approval state is cleared

func RegisterTaskEnvOverrides

func RegisterTaskEnvOverrides(env *Env, taskID string, overrides map[string]any) error

RegisterTaskEnvOverrides registers per task sandbox overrides before the agent loop runs

func RegisterTaskEnvironment

func RegisterTaskEnvironment(effectiveTaskID string, e Environment)

Caches an environment under its effective task id with a fresh activity stamp

func RegisterTerminalBackend

func RegisterTerminalBackend(p BackendProvider) error

RegisterTerminalBackend adds a plugin backend to the global layer, refusing names reserved by the built in environments

func RegisterThreadCallback

func RegisterThreadCallback(cb ThreadCallback)

Adds a getter and setter pair every propagated worker installs for its lifetime and clears on exit

func RegisterVaultRedactionValueIn

func RegisterVaultRedactionValueIn(ctx context.Context, value string)

RegisterVaultRedactionValueIn registers a vault secret and its CR LF stripped form for the context profile

func RegisteredTaskCwdOverride

func RegisteredTaskCwdOverride(env *Env, taskID string) string

Cwd override registered for the raw task id, empty when none is registered

func RegisteredToolNames

func RegisteredToolNames(ctx context.Context, env *Env) map[string]bool

RegisteredToolNames lists every tool the registry holds for the session's profile scope

func RelayAtExit

func RelayAtExit()

Runs the Relay exit handlers newest first, every runtime shutdown then the final plugin cleanup retry

func RelayAttributeError

func RelayAttributeError(object, name string) error

Python AttributeError text for a binding attribute the native module lacks

func RelayCanonicalJSON

func RelayCanonicalJSON(value any, encode func(any) any) (string, error)

Sorted compact JSON of the encoded value, RelayJSONable when encode is nil

func RelayDemanded

func RelayDemanded(ctx context.Context) bool

Whether Relay has a consumer for this process, a plugin file Relay discovers, the plugins variable or a legacy exporter variable

func RelayDiscoveredPluginFiles

func RelayDiscoveredPluginFiles() []string

Existing plugins.toml files Relay 0.11 discovers for this process, the user file then the system file

func RelayExecuteTool

func RelayExecuteTool(ctx context.Context, toolName string, args map[string]any, callback func(ctx context.Context, args map[string]any) (any, error), sessionID, toolCallID string, metadata map[string]any) (any, map[string]any, error)

Runs one tool call through Relay returning its result and the final arguments the tool saw

func RelayHasRunningEventLoop

func RelayHasRunningEventLoop(ctx context.Context) bool

Whether ctx runs on an event loop, the Relay loop included

func RelayIdentical

func RelayIdentical(a, b any) bool

Python identity comparison of two scope handles

func RelayInstrumentationEnabled

func RelayInstrumentationEnabled(ctx context.Context) bool

Whether the inherited turn may create Relay instrumentation

func RelayJSONable

func RelayJSONable(value any) any

JSON shaped copy of a provider value with stringified keys, public attributes, or its str form

func RelayManagedCallbackGuard

func RelayManagedCallbackGuard(ctx context.Context) context.Context

Context of a managed Relay callback whose transitive work, forwarded copies included, runs unmanaged

func RelayRunAwaitable

func RelayRunAwaitable(ctx context.Context, value any, loopError string) (any, error)

Awaits a RelayAwaitable on a fresh loop, refusing when ctx already runs on one

func RelayRunOnDaemonThread

func RelayRunOnDaemonThread(fn func() (any, error), name string, timeout *float64, timeoutMessage string) (any, error)

Runs fn on a fresh goroutine and abandons it with a timeout error once timeout seconds pass

func RelayRuntimeMetadata

func RelayRuntimeMetadata(runtimeID string, extra map[string]any) map[string]any

Scope metadata stamping every icebath owned Relay scope

func RelayUnprovisionedNotice

func RelayUnprovisionedNotice(ctx context.Context) string

Warning for a session whose configured Relay plugins wait on an unprovisioned runtime, empty when Relay runs or has no consumer

func RelayWithRunningLoop

func RelayWithRunningLoop(ctx context.Context) context.Context

Context of code driven by a Relay event loop, the running loop every on loop check reports

func RelayWithoutRunningLoop

func RelayWithoutRunningLoop(ctx context.Context) context.Context

Context of a worker thread spawned off the loop, which has no running loop

func ReleaseCompletionDelivery

func ReleaseCompletionDelivery(env *Env, delegationID, claimID string) (bool, error)

Releases a failed claim for retry, converging to dropped once the attempt budget is spent

func ReleaseDeadFetchLocks

func ReleaseDeadFetchLocks(ctx context.Context, repoRoot string) ([]string, error)

Drops the shallow and ref locks a killed update's fetch left, returning the removed paths

func ReleaseDeadIndexLock

func ReleaseDeadIndexLock(ctx context.Context, repoRoot string) (bool, error)

Drops index.lock once the killed update run behind it is proven gone, whatever the lock's age

func ReleaseEventDelivery

func ReleaseEventDelivery(env *Env, evt map[string]any, claimID string) error

Releases a failed claim for a consumer that discards its copy, handing the row back to the orphan sweep

func ReleaseEvents

func ReleaseEvents(events []map[string]any)

ReleaseEvents ends the in flight hold TakeReady took for the events

func ReleaseLspClients

func ReleaseLspClients(wtPath string)

ReleaseLspClients stops the language servers rooted at a worktree before its removal

func ReleaseProcessGroupOnceEmpty

func ReleaseProcessGroupOnceEmpty(pgid int, poll func(), timeout time.Duration) bool

ReleaseProcessGroupOnceEmpty releases pgid once no member is left, polling the leader through poll

func ReleaseProcessGroups

func ReleaseProcessGroups(pgids []int)

ReleaseProcessGroups stops covering these groups because this process stopped them itself

func RemoteArgv

func RemoteArgv(prefix, argv []string, childEnv map[string]string, shellJoined bool) []string

RemoteArgv is prefix plus a bash -c that exports childEnv and execs argv

func RemoteCommand

func RemoteCommand(e Environment, argv []string, childEnv map[string]string, user string, interactive bool) []string

RemoteCommand is the full local argv running argv inside the environment, nil without an exec prefix

func RemovedBackendNote

func RemovedBackendNote(section, name string) string

RemovedBackendNote explains a removed backend or returns empty

func RenderEditDiffWithDelta

func RenderEditDiffWithDelta(ctx context.Context, toolName, result string, args map[string]any, snapshot *LocalEditSnapshot, printFn func(string)) bool

Renders an edit diff inline through the printer without taking over the terminal, false when nothing shown

func RenderVerdict

func RenderVerdict(v CommandVerdict) string

RenderVerdict formats a dry run verdict the way the approvals test command prints it

func RepairBrokenShallowBoundaries

func RepairBrokenShallowBoundaries(ctx context.Context, repoRoot string) int

Re-appends shallow boundaries for reflog reachable commits whose parents were never fetched, never failing

func RepeatRefusal

func RepeatRefusal(env *Env, sessionID, imageURL string) string

Refusal text for an image embedded past its repeat cap

func RepoIsShallow

func RepoIsShallow(repoPath string, timeout time.Duration) bool

RepoIsShallow reports a shallow clone whose unpushed verdict is unreliable

func RequestElicitationConsent

func RequestElicitationConsent(ctx context.Context, env *Env, message, description string, o ElicitationOptions) string

RequestElicitationConsent routes an MCP elicitation to the surface owning the session and returns accept, decline, or cancel

func RequestYield

func RequestYield(id WorkerID)

RequestYield asks the worker to hand its foreground command to the background instead of killing it

func RequeueAdmittedCompletion

func RequeueAdmittedCompletion(env *Env, delegationID string, q *EventQueue) (bool, error)

Reopens an acknowledged completion whose turn could not confirm the owner and offers it on q again

func RequirePinnedCommand

func RequirePinnedCommand(command, message string) error

RequirePinnedCommand refuses a pinned ACP transport command that is not on PATH

func ResetAsyncDelegationForTests

func ResetAsyncDelegationForTests()

Clears every registry, fence, offer and hold and tears down the executor and stale monitor

func ResetCurrentSessionKey

func ResetCurrentSessionKey(env *Env)

ResetCurrentSessionKey drops the bound approval session key

func ResetDelegationFirstUse

func ResetDelegationFirstUse()

Forgets every first use bundled strategy, the first use reset of tests

func ResetDockerExecutable

func ResetDockerExecutable()

Forgets the located docker CLI so the next lookup searches the PATH again

func ResetEnvPassthroughConfigCache

func ResetEnvPassthroughConfigCache()

ResetEnvPassthroughConfigCache drops the per home config allowlist cache

func ResetEnvironmentProbe

func ResetEnvironmentProbe()

ResetEnvironmentProbe clears the cache so the next read probes again

func ResetFileDedup

func ResetFileDedup(taskID string)

ResetFileDedup advances the read dedup generation after context compression for one task or all

func ResetForegroundExitFenceForTests

func ResetForegroundExitFenceForTests()

Lowers the foreground exit fence a hard exit kill raised, for tests that drive the exit path

func ResetRelayRuntimeForTests

func ResetRelayRuntimeForTests()

Resets every profile scoped Relay host for isolated tests

func ResetSessionVars

func ResetSessionVars(env *Env)

Returns every session variable of this context to never bound before a fresh task binds its own

func ResetTerminalScopeCache

func ResetTerminalScopeCache()

ResetTerminalScopeCache forgets every cached terminal policy

func ResizeImageForVision

func ResizeImageForVision(env *Env, path, mime string, o ResizeOptions) (string, error)

ResizeImageForVision returns a base64 data URL progressively downscaled while over the byte or long edge budget

func ResolveAgentCwd

func ResolveAgentCwd(env *Env) (string, error)

ResolveAgentCwd returns the configured cwd else the launch directory

func ResolveClarifyTimeout

func ResolveClarifyTimeout(cfg config.Tree) int

ResolveClarifyTimeout reads clarify.timeout when set, else agent.clarify_timeout, else 3600, non numeric gives 3600

func ResolveContainerTaskID

func ResolveContainerTaskID(env *Env, taskID string) (string, error)

Exported face of the cache key mapping for pkg/codeexec

func ResolveContextCwd

func ResolveContextCwd(env *Env, includeSessionOverride bool) (string, error)

ResolveContextCwd returns the configured cwd for context file discovery or empty for the launch dir

func ResolveEmbedTargetBytes

func ResolveEmbedTargetBytes(env *Env) int

ResolveEmbedTargetBytes exposes the history embed byte budget to other tool packages

func ResolveGatewayApproval

func ResolveGatewayApproval(sessionKey, choice string, resolveAll bool, reason, requestID string) int

ResolveGatewayApproval unblocks the oldest, the matching, or every pending approval and returns how many

func ResolveGatewayClarify

func ResolveGatewayClarify(clarifyID, response string) bool

ResolveGatewayClarify unblocks the waiter, false when already resolved, expired or unknown

func ResolveLifecycleScriptPath

func ResolveLifecycleScriptPath(h, scriptPath string) (string, bool)

Exported form for pkg/cron, same answer as the package resolver

func ResolveLocalSchemaRef

func ResolveLocalSchemaRef(schema, rootSchema any) any

ResolveLocalSchemaRef follows a document local $ref against the root with siblings kept

func ResolveLocalSourceToDataURL

func ResolveLocalSourceToDataURL(ctx context.Context, env *Env, src, taskID string, permitted ...string) (string, error)

ResolveLocalSourceToDataURL inlines a path like media source as a data URL, URLs pass through

func ResolveOpenAIAudioAPIKey

func ResolveOpenAIAudioAPIKey(env *Env) string

ResolveOpenAIAudioAPIKey prefers the voice tools key then the scoped OpenAI key with pool fallback

func ResolvePassthroughValue

func ResolvePassthroughValue(ctx context.Context, env *Env, name string, fallback *string) (*string, error)

Value of an allowlisted variable resolved through the bound profile secret scope

func ResolvePathForTaskID

func ResolvePathForTaskID(env *Env, taskID, filePath string) (string, error)

Resolves a model supplied path against the base directory of the named task

func ResolvePlaceholderTerminalCwd

func ResolvePlaceholderTerminalCwd(configuredCwd, terminalBackend, messagingCwd string, dockerMountCwdToWorkspace bool, homeFallback string) (string, bool)

TERMINAL_CWD for a configured cwd and backend, false when the sandbox default applies

func ResolveProfilePolicy

func ResolveProfilePolicy(profileHome string)

Records a profile's redaction policy from its own .env and config now so its routed records never wait

func ResolveProviderSecret

func ResolveProviderSecret(env *Env, envVar, providerID, configValue string, envGetter func(string) string) string

ResolveProviderSecret resolves a voice provider key through config, scope, .env, then the credential pool

func ResolveRelayExecutionContext

func ResolveRelayExecutionContext(ctx context.Context, sessionID string) (*RelayRuntime, *RelaySession, any, error)

Active turn or session parent for managed Relay execution, nothing inside a managed callback

func ResolveTaskOverrides

func ResolveTaskOverrides(env *Env, taskID string) (map[string]any, error)

ResolveTaskOverrides returns the env overrides for a task, raw key first then collapsed

func ResolveUnderlyingCall

func ResolveUnderlyingCall(ctx context.Context, env *Env, args map[string]any, sessionToolNames map[string]bool) (string, map[string]any, string)

ResolveUnderlyingCall parses tool_call args holding Python values into the underlying name, its handler args, and error

func ResolveXAIHTTPCredentials

func ResolveXAIHTTPCredentials(env *Env, preferAPIKey bool) (provider, apiKey, baseURL string)

Provider, bearer key and base url for direct xAI calls, OAuth first unless the API key is preferred

func ResolveXAIHTTPCredentialsRefreshed

func ResolveXAIHTTPCredentialsRefreshed(env *Env, apiKeyHint string) (provider, apiKey, baseURL string)

Provider, bearer key and base url after force refreshing the pool entry that issued the hinted key

func RestoreGatewayYolo

func RestoreGatewayYolo(ctx context.Context, sessionKey string, persisted *bool, launch bool)

RestoreGatewayYolo restores the authoritative routing value, including off, before launch seeding

func RestoreLastResolvedToolNames

func RestoreLastResolvedToolNames(names []string)

RestoreLastResolvedToolNames puts back a saved resolved tool name list after a child build replaced it

func RestoreManagedEnv

func RestoreManagedEnv(child map[string]string) map[string]string

RestoreManagedEnv re applies the administrator managed dotenv values over a routed child env

func RestoreSessionVar

func RestoreSessionVar(env *Env, name, prev string, had bool)

Sets one session variable to a value, or back to never set when had is false

func RestoreSessionYolo

func RestoreSessionYolo(ctx context.Context, sessionKey string, persisted bool) bool

RestoreSessionYolo re arms a persisted bypass in a fresh process, true when this call turned it on

func RestoreUndeliveredCompletions

func RestoreUndeliveredCompletions(env *Env, q *EventQueue) (int, error)

Enqueues durable pending completions of a previous process stamped restored, never creating the ledger

func ResultRetryAction

func ResultRetryAction(result any) (string, error)

Retry action of a finished in process turn result, none for anything that did not fail

func ResumeCommand

func ResumeCommand(ctx context.Context, h string, args []string, w io.Writer) (int, error)

Lifts the emergency stop icebath pause engaged

func RetainedTreeIsLive

func RetainedTreeIsLive(dbPath, worktreePath string, pendingOnly bool) bool

Whether a resumable session or pending gateway work still has its cwd inside a retained tree

func RetryAction

func RetryAction(reason string) string

Retry action of a failure reason, transient resuming, overflow compressing first, the rest never retried

func ReturnCompletionOffer

func ReturnCompletionOffer(evt map[string]any)

Hands a discarded offered completion back to the orphan sweep in every home

func RewriteCompoundBackground

func RewriteCompoundBackground(command string) string

RewriteCompoundBackground wraps A && B & as A && { B & } so bash never parks a subshell waiting on B

func RmtreeReadonly

func RmtreeReadonly(path string, ignoreErrors bool) error

Deletes a tree that plain rmtree refuses, read only files and directories included

func RunIfNotInterrupted

func RunIfNotInterrupted(ctx context.Context, callback func()) bool

RunIfNotInterrupted runs a state transition atomically against the context worker's interruption

func RunOnVisionCPU

func RunOnVisionCPU[T any](env *Env, fn func() T) T

RunOnVisionCPU runs a CPU heavy vision step inside the bounded vision worker pool

func RunOperation

func RunOperation(ctx context.Context, env *Env, targets []*ConnTarget, kind ConnKind, opts RunOptions) string

Blocks the tool goroutine until a fresh operation over targets settles and returns the tool JSON

func RunSweep

func RunSweep(ctx context.Context, repoRoot string, maxAgeHours int, s SweepConfig) error

Plans, executes and applies archive retention for one repository in archive mode

func RunTaskList

func RunTaskList(store *TodoStore, args map[string]any) string

Task list tool over the given store with the list and merge args of one call

func RunTerminalBackendSetup

func RunTerminalBackendSetup(ctx context.Context, env *Env, out io.Writer, backend string) bool

Prints a registered backend's name and setup lines and runs its post setup hook, a failure printed instead

func RunToolsFlow

func RunToolsFlow(ctx context.Context, env *Env, ask setupflow.Asker, hooks ToolsFlowHooks) error

Icebath setup tools asked through the asker, the platform menu until Done then the section save

func RunningSourceRoot

func RunningSourceRoot() string

RunningSourceRoot is the git checkout holding this binary's own source when one exists

func SamePath

func SamePath(left, right string) bool

Reports whether two path spellings name the same components under host filesystem case rules

func SandboxDir

func SandboxDir(env *Env) (string, error)

SandboxDir is the host side root for all sandbox storage, TERMINAL_SANDBOX_DIR over home/sandboxes

func SandboxTempDir

func SandboxTempDir(e Environment) string

SandboxTempDir is the sandbox side temp directory of an environment

func SanitizeDisplayText

func SanitizeDisplayText(text string) string

Strips escapes and bare control characters keeping newlines and tabs, CRs become newlines

func SanitizePropertyKey

func SanitizePropertyKey(key string) string

SanitizePropertyKey maps an arbitrary property key to one every provider accepts

func SanitizeSubprocessEnv

func SanitizeSubprocessEnv(ctx context.Context, env *Env, base, extra map[string]string) (map[string]string, error)

SanitizeSubprocessEnv filters managed secrets from a background, PTY, worker or script child environment

func SanitizeTaskIDForPath

func SanitizeTaskIDForPath(taskID string) string

SanitizeTaskIDForPath is the bind mountable directory name of a task sandbox, digest suffixed when rewritten

func SanitizeToolError

func SanitizeToolError(errorMsg string) string

SanitizeToolError strips structural framing tokens from an error before the model reads it

func SanitizeToolSchemas

func SanitizeToolSchemas(tools []map[string]any) []map[string]any

SanitizeToolSchemas returns deep copied OpenAI format tools with sanitized parameter schemas

func SanitizeUserPromptText

func SanitizeUserPromptText(text string) string

Normalizes user authored prompt text before persistence or model input

func SavePermanentAllowlist

func SavePermanentAllowlist(env *Env, patterns map[string]bool)

SavePermanentAllowlist writes the on disk list plus this process's grants back to config

func SavedDelegationBackend

func SavedDelegationBackend(ctx context.Context) string

Backend config.yaml selects now, what a tool build reads

func SavedToolsetResolver

func SavedToolsetResolver(ctx context.Context, cfg config.Tree) func(string) bool

SavedToolsetResolver judges a saved platform_toolsets name the way session tool resolution lets it through

func ScanContextContent

func ScanContextContent(content, filename string, userAuthored bool) string

Injection scanned content, a blocked notice for project files and a warning only for user authored files

func ScanForThreats

func ScanForThreats(content, scope string) ([]string, error)

ScanForThreats returns matched pattern ids for the scope with invisible code points reported first

func ScanGatewayLifecycle

func ScanGatewayLifecycle(command, cwd string, readRemote ReadRemoteScriptFunc) (unsafe bool, refusal string)

ScanGatewayLifecycle reports whether a command is unsafe and the non lifecycle refusal when the walk failed closed

func SchemaExtension

func SchemaExtension(ctx context.Context, config map[string]any) (*pyjson.Object, string)

Extra task properties and description addendum of the active provider, none when it cannot be resolved

func ScopeBlockReason

func ScopeBlockReason(ctx context.Context, env *Env, name string) string

ScopeBlockReason is the block message for a tool_call naming a tool outside the session's scope

func ScopeKey

func ScopeKey(path string) string

ScopeKey canonicalizes a profile home into the key scoped registrations live under

func ScopeTerminalCwd

func ScopeTerminalCwd(env *Env) (string, error)

Scope aware TERMINAL_CWD value for plugin sessions, read through the per turn terminal scope

func ScopedCredential

func ScopedCredential(env *Env, name string) string

Credential through the profile secret scope for availability checks outside the package

func ScopedCurrentSessionID

func ScopedCurrentSessionID(env *Env, sessionID *string) func()

Binds a task local session id, nil only saving, and returns the restore of the prior value

func ScopedDeferrableNames

func ScopedDeferrableNames(ctx context.Context, env *Env, toolDefs []map[string]any) map[string]bool

ScopedDeferrableNames is the universe tool_call may reach in this session's pre assembly defs

func ScopedPassthroughAdditions

func ScopedPassthroughAdditions(ctx context.Context, env *Env, present map[string]bool) map[string]string

Declared names the bound profile scope supplies but the filtered env lacks

func ScopedSessionCwd

func ScopedSessionCwd(env *Env) string

ScopedSessionCwd returns the declared session cwd without validating it locally

func ScopedSessionKey

func ScopedSessionKey(env *Env, sessionKey string) func()

Binds only the route key of the session a call works for and returns the restore of the prior value

func ScopedSpawnLostUserBus

func ScopedSpawnLostUserBus(spawnEnv map[string]string) bool

ScopedSpawnLostUserBus reports a vanished user bus after a scope wrapper exited early and forces a reprobe

func ScopedStderr

func ScopedStderr(ctx context.Context) io.Writer

Process stderr as seen by work under ctx, the null device inside a silenced context

func ScopedStdout

func ScopedStdout(ctx context.Context) io.Writer

Process stdout as seen by work under ctx, the null device inside a silenced context

func ScrubCredentials

func ScrubCredentials(child map[string]string, inheritCredentials bool) map[string]string

Strips tier one secrets always and tier two provider credentials unless inherited, in place, returning the env

func SecretThroughScope

func SecretThroughScope(ctx context.Context, env *Env, name string) (*string, error)

get_secret of one name through the call's bound scope, the tool env's secrets standing in when the context binds none

func SelectionConfigKeys

func SelectionConfigKeys() map[string]bool

SelectionConfigKeys lists the dotted config keys the selection readers honour

func SelectionError

func SelectionError(section, selectionName, failure string) string

SelectionError is the uniform message for a selected but broken provider

func SelectionExists

func SelectionExists(env *Env, section string) bool

SelectionExists reports whether any selection signal was ever written for a section

func SelfRepoGuardActive

func SelfRepoGuardActive() bool

SelfRepoGuardActive is true only on Windows where NTFS locks loaded modules of the live checkout

func SensitiveQueryParamNames

func SensitiveQueryParamNames() []string

Sorted names of the sensitive URL query parameters

func SentinelPath

func SentinelPath(ctx context.Context) string

Path of the ESTOP sentinel this process writes on icebath pause

func ServedProfileChildEnv

func ServedProfileChildEnv(ctx context.Context, env *Env, base map[string]string, targetHome string, inheritCredentials bool) (map[string]string, error)

ServedProfileChildEnv builds the env of a child acting for the active or a routed profile

func ServiceDefinitionHomes

func ServiceDefinitionHomes(definition string) []string

Every home a gateway service definition sets, for the service writers outside this package

func SessionAsyncDeliverySupported

func SessionAsyncDeliverySupported(env *Env) bool

Reports whether the bound session can receive async completion notices, the exported face for pkg/cron

func SessionContextEngaged

func SessionContextEngaged() bool

Whether any session has been bound through SetSessionVars in this process

func SessionDisabledToolsets

func SessionDisabledToolsets(disabled []string, oneshot bool) []string

SessionDisabledToolsets extends a disabled list with the one shot toolsets of a one shot session

func SessionEnv

func SessionEnv(env *Env, name string) string

Bound session context variable for plugin sessions, the engaged session map before session values and process env

func SessionEnvValue

func SessionEnvValue(env *Env, name string) string

Session context variable of the turn, the process env otherwise

func SessionHistoryDeliverySupported

func SessionHistoryDeliverySupported(env *Env) bool

Whether the request declared a server history consumer for detached results, undeclared failing closed

func SessionIsMessagingSurface

func SessionIsMessagingSurface(env *Env) bool

Whether the turn is delivered over a human messaging channel by platform override, session platform or source

func SessionScopeBlockReason

func SessionScopeBlockReason(ctx context.Context, env *Env, name string, enabled, disabled []string) string

SessionScopeBlockReason blocks a tool_call naming a tool outside the session scope, a TUI only tool before a switched off toolset

func SessionSearch

func SessionSearch(ctx context.Context, a SessionSearchArgs) string

SessionSearch runs one session_search call, closing every database it opened itself

func SessionToolNames

func SessionToolNames(toolDefs []map[string]any) map[string]bool

SessionToolNames returns every tool name in the session's tool defs

func SessionToolScope

func SessionToolScope(ctx context.Context) string

SessionToolScope returns the overlay slot key of the bound session scope, keyed per read like registry writes

func SessionUnavailableError

func SessionUnavailableError(ctx context.Context, env *Env, name string, sessionToolNames map[string]bool) string

SessionUnavailableError reports a core tool missing from the session's own tool list

func SetAsyncDelegationInterruptForTests

func SetAsyncDelegationInterruptForTests(delegationID string, interrupt func() error)

Gives a delegation record a case of another package installed the stop signal its child would hold

func SetAsyncDelegationRecordForTests

func SetAsyncDelegationRecordForTests(delegationID string, record map[string]any) func()

Installs one in memory delegation record for a case of another package and hands back the removal

func SetCheckpointDeleteRef

func SetCheckpointDeleteRef(fn func(env *Env, store, ref string) bool) (restore func())

Replaces the ref deleter a checkpoint rekey goes through and returns the func restoring the real one

func SetCodePromptCallback

func SetCodePromptCallback(ctx context.Context, cb CodePrompt)

Registers the surface's enter the code prompt in the per thread slot

func SetCurrentSessionID

func SetCurrentSessionID(ctx context.Context, env *Env, sessionID string)

Writes the session id into the bound session variables and the process env, delegated children only the bound copy

func SetCurrentSessionKey

func SetCurrentSessionKey(env *Env, sessionKey string)

SetCurrentSessionKey binds the active approval session key to the session

func SetFiniteTurn

func SetFiniteTurn(env *Env, finite bool)

SetFiniteTurn records the admitted turn's finite flag on the session env the tools read

func SetFriendlyToolLabels

func SetFriendlyToolLabels(enabled bool)

SetFriendlyToolLabels toggles friendly human phrased tool labels

func SetGlobalBackend

func SetGlobalBackend(ctx context.Context, name, sessionKey string, applyNow bool) error

Persists delegation.backend to the profile config, queueing a next turn rebuild of the session when asked

func SetInterrupt

func SetInterrupt(id WorkerID, active bool, reason string)

SetInterrupt sets or clears the interrupt for a worker with an optional user safe reason

func SetLogicalSessionCwd

func SetLogicalSessionCwd(env *Env, cwd string) string

SetLogicalSessionCwd pins the logical cwd of the session, returning the previous value for reset

func SetMultiplexActive

func SetMultiplexActive(active bool)

SetMultiplexActive marks this process as a profile multiplexer so unscoped secret reads fail closed

func SetPlatformDeclarationOnChange

func SetPlatformDeclarationOnChange(fn func())

Installs the single hook run after every registry mutation, nil removing it

func SetProjectWorkspaceCallback

func SetProjectWorkspaceCallback(fn ProjectWorkspaceCallback)

SetProjectWorkspaceCallback installs or clears the session workspace mover

func SetSaveLoginPromptCallback

func SetSaveLoginPromptCallback(ctx context.Context, cb SaveLoginPrompt)

Registers the surface's save this login prompt in the per thread slot

func SetSessionVars

func SetSessionVars(env *Env, v SessionVars)

Binds every session variable of the turn, latches the process session context and pins the logical cwd

func SetSkinToolEmojis

func SetSkinToolEmojis(hook func() map[string]string)

SetSkinToolEmojis registers the active skin's per tool emoji overrides

func SetSudoPasswordCallback

func SetSudoPasswordCallback(ctx context.Context, cb *SudoPasswordCallback)

Registers the surface's sudo password prompt in the per thread slot, nil clearing it

func SetTerminalScope

func SetTerminalScope(ctx context.Context, scope *TerminalScope) context.Context

Binds scope as the context terminal policy, nil unbinds it

func SetThreadSudoPassword

func SetThreadSudoPassword(ctx context.Context, password string)

Caches a sudo password under the executing worker's thread scope

func SetToolPreviewMaxLen

func SetToolPreviewMaxLen(n int)

SetToolPreviewMaxLen sets the global max length for tool call previews, zero means no limit

func SetUnlockPromptCallback

func SetUnlockPromptCallback(ctx context.Context, cb UnlockPrompt)

Registers the current surface's masked master password prompt in the per thread slot

func SetVaultSessionID

func SetVaultSessionID(ctx context.Context, sessionID *string)

Binds the session running on this thread so an unlock records its owner, nil clearing it

func SettlePartialCloneMaintenance

func SettlePartialCloneMaintenance(ctx context.Context, repoRoot string)

Persists the commit graph off keys on a partial clone while a full clone keeps stock maintenance, never failing

func SetupDockerRuntime

func SetupDockerRuntime(env *Env) (path, runtime string)

Docker or Podman CLI path with its runtime name, both empty when neither is installed

func SetupNeededReason

func SetupNeededReason(def *Def) string

SetupNeededReason answers a call of a selected tool whose requirements are not met, naming what the user sets up

func SetupTerminalBackend

func SetupTerminalBackend(ctx context.Context, env *Env, cfg map[string]any) error

SetupTerminalBackend runs the terminal backend wizard, persisting the choice to config and the home .env

func SetupWorktree

func SetupWorktree(ctx context.Context, repoRoot string, syncBase bool, name string, retainDB *string) map[string]string

Creates an isolated git worktree and returns its path, branch, repo root and base, nil on failure

func SetupWorktreeFor

func SetupWorktreeFor(ctx context.Context, repoRoot string, syncBase bool, name string, retainDB *string, ownerPid int, out io.Writer) map[string]string

Creates a worktree locked for the owner process, its lines written to out or the CLI printers when out is nil

func ShapeFailureError

func ShapeFailureError(data map[string]any) string

ShapeFailureError returns the error text when an object result failed by shape rather than error key

func ShlexSplitCommand

func ShlexSplitCommand(command string) ([]string, error)

ShlexSplitCommand splits a command line with POSIX shlex semantics

func ShouldActivate

func ShouldActivate(cfg ToolSearchConfig, deferrableTokens int, contextLength int) bool

ShouldActivate reports whether the bridge replaces deferrable tools for this assembly

func ShouldAutoApproveEdit

func ShouldAutoApproveEdit(proposal *EditProposal, policy, cwd string) bool

Whether an ACP edit may bypass the prompt under the session policy, sensitive paths always asking

func ShouldSurfaceNotification

func ShouldSurfaceNotification(cfg config.Tree, evt map[string]any) bool

Whether a process event surfaces as a notification under the config, subagent events only when enabled

func ShouldUseNativeVisionFastPath

func ShouldUseNativeVisionFastPath(ctx context.Context, env *Env) bool

ShouldUseNativeVisionFastPath applies the native image gate to the session main model

func ShutdownTerminalEnvironments

func ShutdownTerminalEnvironments(env *Env)

ShutdownTerminalEnvironments stops the reaper and tears down every remaining sandbox at exit

func SiteCopy

func SiteCopy(ctx context.Context, code string, fields map[string]any) (string, error)

Chat copy for a failure code or one off outcome with every field the caller omits rendered empty

func SizefmtBytes

func SizefmtBytes(n int64) string

SizefmtBytes exports the human readable byte count for the context reference blocks

func SkillGist

func SkillGist(action, name, content, filePath, oldString, newString string) string

One line heuristic description of a pending skill write without a model call

func SkillLockCommandRefusal

func SkillLockCommandRefusal(env *Env, command, cwd string) string

SkillLockCommandRefusal is the terminal guard, refusal text when a command writes into a locked skill

func SkillLockPathRefusal

func SkillLockPathRefusal(env *Env, paths []string) string

SkillLockPathRefusal is the write_file and patch guard over paths landing in a locked skill or the record

func SkillLockRefusal

func SkillLockRefusal(name string) string

SkillLockRefusal is the refusal text for a change to one locked skill

func SkillPendingDiff

func SkillPendingDiff(env *Env, record map[string]any, staged map[string]map[string]string) string

Full content or a unified diff against its base for a pending skill write

func SmoothWhitespaceForTTS

func SmoothWhitespaceForTTS(text string) string

Visual formatting collapsed into spoken paragraphs, marked headings folded into the next line as a lead in

func SnapshotRecentMessages

func SnapshotRecentMessages(messages []map[string]any, limit int) []map[string]string

Last limit user and assistant messages with text as role and text pairs, oldest first

func SniffImageMime

func SniffImageMime(raw []byte) string

Image MIME from magic bytes or an svg tag, empty when unrecognised

func SpawnCommitGraphRefresh

func SpawnCommitGraphRefresh(ctx context.Context, repoRoot string) (bool, error)

Starts the bounded commit graph refresh in a detached child when due, a failed spawn gives the slot back

func SpawnOwned

func SpawnOwned(ctx context.Context, cmd *exec.Cmd, purpose string) error

SpawnOwned starts a long lived child that dies with this process and records it in the ledger

func SpillIfOversized

func SpillIfOversized(env *Env, text, sessionID, source string, cfg *SpillConfig) string

SpillIfOversized writes hook text over the cap to disk and returns a preview pointing at it

func SpilloverDir

func SpilloverDir(env *Env) string

SpilloverDir returns the profile's cache/spillover path without creating it

func SpilloverNamesInText

func SpilloverNamesInText(texts ...string) map[string]bool

SpilloverNamesInText returns spill archive basenames referenced by transcript text

func SplitTableRow

func SplitTableRow(row string) []string

Cells of a pipe delimited table row with the outer pipes removed and each cell stripped

func StageWrite

func StageWrite(ctx context.Context, env *Env, subsystem string, payload map[string]any, summary, origin string) map[string]any

Persists a pending write and returns its record, a disk failure is logged and the write is lost

func StagedState

func StagedState(wtPath string) (string, error)

Digest of the semantic staged entries, unchanged by a stat only refresh and moved by any add or rm

func StartReview

func StartReview(ctx context.Context, env *Env, parent any, messages []map[string]any, userPrompt string) (*pyjson.Object, error)

Dispatches the reviewer subagent and returns the parsed delegate_task reply, an error when nothing can be reviewed

func StartTimeFingerprintsMatch

func StartTimeFingerprintsMatch(recorded, current int64) bool

Reports whether a recorded start time still names the same process

func StopCleanupThread

func StopCleanupThread()

StopCleanupThread stops the idle reaper and waits up to five seconds for its running pass to end

func StopOwnedGroupSurvivors

func StopOwnedGroupSurvivors(pgid int, poll func(), grace time.Duration) bool

StopOwnedGroupSurvivors stops what is left of owned group pgid after its leader exited, then releases it

func StorageDir

func StorageDir() string

StorageDir is the sandbox fallback results directory under the system temp root

func StripANSI

func StripANSI(text string) string

Removes ANSI escape sequences, clean text passes through unchanged

func StripIcebathOwnedPythonpath

func StripIcebathOwnedPythonpath(child map[string]string) error

Removes runtime owned PYTHONPATH entries in place, the error is a damaged runtime dependency record

func StripInertHeredocBodies

func StripInertHeredocBodies(command string) string

StripInertHeredocBodies masks heredoc bodies that are provably inert data, keeping their newline count

func StripLaunchProfileEnv

func StripLaunchProfileEnv(env *Env, child map[string]string, targetHome string) map[string]string

StripLaunchProfileEnv drops the launch profile's residue from a child env built for a routed profile

func StripLeakedBracketedPasteWrappers

func StripLeakedBracketedPasteWrappers(text string) string

Removes canonical paste wrappers everywhere and degraded visible forms only at word boundaries

func StripLegacyBotProtocol

func StripLegacyBotProtocol(text string) string

StripLegacyBotProtocol drops every plugin era teammate section from SOUL text, idempotent

func StripMarkdownForTTS

func StripMarkdownForTTS(text string) string

Markdown and Telegram formatting removed with the readable words kept and headings marked

func StripModelHiddenTaskFields

func StripModelHiddenTaskFields(tasks any) any

StripModelHiddenTaskFields exports stripModelHiddenTaskFields

func StripNonspokenBlocks

func StripNonspokenBlocks(text string) string

Think reasoning blocks, unterminated ones included, and the file mutation verifier footer removed

func StripNullableUnions

func StripNullableUnions(schema any, keepNullableHint bool) any

StripNullableUnions collapses anyOf or oneOf nullable unions to the single non null branch

func StripPatternAndFormat

func StripPatternAndFormat(tools []map[string]any) ([]map[string]any, int)

StripPatternAndFormat removes pattern and format keywords in place after a llama.cpp grammar rejection

func StripProfileGateEnv

func StripProfileGateEnv(child map[string]string) map[string]string

StripProfileGateEnv drops every authorization gate from the env in place

func StripRecommended

func StripRecommended(text string) string

StripRecommended removes the recommendation label so presentation never leaks into user_response

func StripSlashEnum

func StripSlashEnum(tools []map[string]any) ([]map[string]any, int)

StripSlashEnum removes enum keywords whose string values contain a slash after an xAI grammar rejection

func StripSupervisedProcessIdentity

func StripSupervisedProcessIdentity(child map[string]string) map[string]string

StripSupervisedProcessIdentity drops the supervisor identity vars in place keeping the profile pin

func StripUnicodeTags

func StripUnicodeTags(text string) string

Removes invisible Unicode TAG characters while keeping valid emoji tag sequences

func SubagentApprovalCallback

func SubagentApprovalCallback(ctx context.Context) func(command, description string, kwargs map[string]any) string

Non interactive approval callback for subagent workers chosen by delegation.subagent_auto_approve

func SubmoduleWork

func SubmoduleWork(wtPath string, gitlinks bool) (string, error)

Why a submodule keeps the tree, empty when nothing does, gitlinks refuses any gitlink at all

func SubprocessHome

func SubprocessHome(env *Env) string

HOME a tool subprocess gets under the home mode, empty when it keeps its own

func SummarizeShellCommand

func SummarizeShellCommand(command string) string

SummarizeShellCommand compacts shell wrapper plumbing for display while the raw command stays elsewhere

func SuppressPostToolCallHook

func SuppressPostToolCallHook(ctx context.Context, suppressed bool) context.Context

SuppressPostToolCallHook lets an outer executor own the terminal post tool event, false re-enables it

func SwapAsyncRecords

func SwapAsyncRecords(ids []string, records map[string]map[string]any) (restore func())

Installs plain delegation records in id order the way tests patch the records table, returning the restore

func SwapCheckpointsCommandFns

func SwapCheckpointsCommandFns(status func(*Env, string) (CheckpointStatus, error),
	prune func(*Env, CheckpointPruneOptions) (CheckpointPruneResult, error), input func(string) (string, error)) func()

Swaps the checkpoints command status, prune and input functions as tests patch them, returning the restore

func SwapGitProbeRunner

func SwapGitProbeRunner(fn func(cwd string, args ...string) string) (restore func())

SwapGitProbeRunner replaces the git command of the root probes with an empty cache and returns the restore

func SwapLookupHostIPs

func SwapLookupHostIPs(fn func(ctx context.Context, hostname string) ([]netip.Addr, error)) (restore func())

Installs a resolver for the safety checks and returns the restore, the getaddrinfo patch of tests

func SwapYoloModeFrozen

func SwapYoloModeFrozen(on bool) func()

Swaps the launch frozen yolo flag and returns its restore, the module attribute codex tests patch

func SweepBackendScratchAtExit

func SweepBackendScratchAtExit()

SweepBackendScratchAtExit removes the orphaned scratch entries every linked backend left in this process

func SweepOrphanedCompletions

func SweepOrphanedCompletions(env *Env, q *EventQueue, now *float64) (int, error)

Re-offers this home's pending completions that no live in memory copy will deliver

func SystemdUserBusEnv

func SystemdUserBusEnv(base map[string]string) map[string]string

SystemdUserBusEnv derives XDG_RUNTIME_DIR and the session bus address that reach this user's lingering systemd

func TakeReady

func TakeReady(q *EventQueue, timeout time.Duration) []map[string]any

TakeReady dequeues everything queued, waiting up to timeout for the first event, holding each owner in flight

func TargetResolves

func TargetResolves(kind string, state TargetState) bool

Reports whether the state ends the target, a failed catalog row counting as done for plugins and skills

func TaskCreationLock

func TaskCreationLock(env *Env, taskID string) (*sync.Mutex, error)

Creation lock of the task's environment cache key

func TaskServiceTier

func TaskServiceTier(word string, creds map[string]any, parent DelegateRouteAgent) (map[string]any, error)

Creds keys pinning a per task speed tier on the child route, an error for a tier the route cannot serve

func TaskXMLLeafValues

func TaskXMLLeafValues(text string) map[string]string

Namespace agnostic leaf path to text map of a task XML for the gateway drift check, nil when unparsable

func TerminalBackendNames

func TerminalBackendNames() []string

TerminalBackendNames lists every built in and active scope plugin backend name sorted

func TerminalBackendRefusal

func TerminalBackendRefusal(name string) (string, bool)

TerminalBackendRefusal is the line naming the build that carries a backend this binary lacks, false for a present or unknown name

func TerminalBackendUnavailableReason

func TerminalBackendUnavailableReason() string

TerminalBackendUnavailableReason is why the last terminal requirements check failed, empty when it passed

func TerminalEnvRead

func TerminalEnvRead(env *Env, name, def string) (string, error)

Terminal setting of the env profile, a refused terminal scope returned as the error

func TerminalEnvRegistryScoped

func TerminalEnvRegistryScoped() providerregistry.ScopedRegistry

Untyped view of the plugin terminal backend registry the plugin context register_terminal_environment_provider drives

func TerminalErrorJSON

func TerminalErrorJSON(errText, status string) string

Terminal error envelope with exit code minus one and the given status

func TerminalProviderFlag

func TerminalProviderFlag(ctx context.Context, name, attr string, def any, scope string) (value any)

Classification attribute of the plugin backend of a name, def for an unknown backend or a panicking attribute

func TerminalTool

func TerminalTool(ctx context.Context, env *Env, req TerminalRequest) (out string)

TerminalTool executes a command in the configured terminal environment and returns the JSON result

func TerminateHostPid

func TerminateHostPid(env *Env, pid int, expectedStart *int64)

Terminates a host pid and its descendants after revalidating its start time, a nil env reading the process home config

func TestSSHConnection

func TestSSHConnection(ctx context.Context, out io.Writer, host, user, port, key string) bool

Runs the ssh probe and prints its outcome, true when the remote echo succeeded

func ThreadLocalGet

func ThreadLocalGet(ctx context.Context, name string) any

Goroutine local value of name, nil when unset or the goroutine never entered local storage

func ThreadLocalSet

func ThreadLocalSet(ctx context.Context, name string, v any)

Stores name in the goroutine local storage, nil deletes it, a no op outside local storage

func ThreadScopedSilence

func ThreadScopedSilence(ctx context.Context) context.Context

Context under which stdout and stderr written through ScopedStdout and ScopedStderr go to the null device

func ThreadSudoPassword

func ThreadSudoPassword(ctx context.Context) string

Sudo password cached under the executing worker's thread scope, empty when none

func ToAgentVisibleCachePath

func ToAgentVisibleCachePath(env *Env, hostPath string) string

ToAgentVisibleCachePath exposes the host to sandbox cache path translation

func ToggleSessionYolo

func ToggleSessionYolo(ctx context.Context, sessionKey string, enabled *bool, persisted bool, persist func(enabled bool) error) bool

ToggleSessionYolo flips or sets the bypass for a session and returns the new state

func ToolAvailabilityWarningLines

func ToolAvailabilityWarningLines(unavailable []UnavailableToolset, terminalReason, terminalBackend string) []string

ToolAvailabilityWarningLines renders one session start notice per toolset problem, the toolsets missing only API keys sharing one

func ToolDefObject

func ToolDefObject(td map[string]any) *pyjson.Object

Envelope as an ordered dict in build order, keys added after the build following in sorted order

func ToolMayHaveSideEffect

func ToolMayHaveSideEffect(toolName string) bool

ToolMayHaveSideEffect is true for every tool outside the known read only set

func ToolOutcome

func ToolOutcome(ctx context.Context, toolName string, result any) (failed, refused bool, reason string)

Verdict of a finished call for a person, refused when the tool declined it, with its reason

func ToolOutputRiskMetadata

func ToolOutputRiskMetadata(name string, content any) map[string]any

ToolOutputRiskMetadata is the advisory classification of attacker controlled output or nil

func ToolProgressHintCLI

func ToolProgressHintCLI() string

Plain text CLI version of the tool progress hint

func ToolProgressHintGateway

func ToolProgressHintGateway() string

Markdown hint shown once after a long running tool streamed every step

func ToolProgressPayload

func ToolProgressPayload(name, message string, kwargs map[string]any) map[string]any

Wire payload every viewer surface publishes for tool.progress, percent 0 to 100 only when a total was sent

func ToolResult

func ToolResult(data any) string

ToolResult encodes the data object like json.dumps with ensure_ascii off

func ToolRowEmoji

func ToolRowEmoji(ctx context.Context, env *Env, toolName string, args map[string]any, def string) string

ToolRowEmoji picks the first label's emoji else the tool's own

func ToolSearchScopedNames

func ToolSearchScopedNames(ctx context.Context, host ExecutorHost) map[string]bool

ToolSearchScopedNames lists deferrable names the host session may invoke through tool_call over the default registry

func ToolSelectionKey

func ToolSelectionKey(enabled, disabled []string) string

ToolSelectionKey is the order free identity of one enabled and disabled toolset pair

func ToolTierRefusal

func ToolTierRefusal(name string) (string, bool)

ToolTierRefusal is the line naming the build that carries a tool this binary leaves out, false for a linked or unknown one

func ToolVerbConnector

func ToolVerbConnector(toolName string) string

ToolVerbConnector joins a verb and its preview with for or a space

func ToolguardSyntheticResult

func ToolguardSyntheticResult(d ToolGuardrailDecision) string

ToolguardSyntheticResult builds the synthetic tool content for a blocked call

func ToolsetAllowedForPlatform

func ToolsetAllowedForPlatform(key, platform string) bool

ToolsetAllowedForPlatform reports whether a toolset may run on a platform

func ToolsetHasKeys

func ToolsetHasKeys(ctx context.Context, tsKey string, cfg config.Tree) (bool, error)

Whether a toolset's required credentials are configured for the home of the context

func ToolsetTierRefusal

func ToolsetTierRefusal(name string) (string, bool)

ToolsetTierRefusal is the line naming the build that carries a toolset this binary leaves out, false for a linked or unknown one

func TrajectoryNormalizeContent

func TrajectoryNormalizeContent(content any) any

TrajectoryNormalizeContent returns the content for trajectory saving with images replaced by placeholders

func TranscriptTail

func TranscriptTail(path string, lines, chars int) string

Last lines of a live transcript bounded in characters, empty when unreadable or blank

func TranscriptTails

func TranscriptTails(paths map[string]string) map[string]string

Tail of every readable transcript keyed by task index

func TransferSessionYolo

func TransferSessionYolo(ctx context.Context, oldKey, newKey string)

TransferSessionYolo moves the live bypass and the MCP spend total to a continuation session id

func TransformMacosOpenCommand

func TransformMacosOpenCommand(command, system string) string

TransformMacosOpenCommand appends the frontmost raise ladder to a bare open command on the given system

func TransformProcessOutput

func TransformProcessOutput(env *Env, output, command string, returncode *int, taskID string) string

Background process output through the plugin transform seam, nil returncode while the process runs

func TreeSizeMB

func TreeSizeMB(path string, timeout time.Duration) *int

Directory size in megabytes through du with a bounded wait, nil on failure or timeout

func TreeStillServed

func TreeStillServed(dbPath, worktreePath string) string

Why the gateway still needs a retained tree, empty when nothing serves it

func TruncateContent

func TruncateContent(ctx context.Context, env *Env, content, filename string, o TruncateOptions) string

Head and tail kept with a marker naming omitted headings and the file to read for the full text

func TruncateHeadTail

func TruncateHeadTail(text string, maxChars int, label string) string

Keeps the head and tail of text around a truncation notice when it exceeds maxChars

func TruncateWithFooter

func TruncateWithFooter(env *Env, content, u string, charLimit int) (string, bool)

Head and tail window with a stored copy footer, exported for truncation footer callers

func TruncationNotice

func TruncationNotice(omitted, total int, label, unit string) string

Marker inserted between the kept head and tail of a truncated output

func TurnExitCode

func TurnExitCode(result map[string]any, o TurnExitOptions) int

TurnExitCode maps a turn result onto the process exit code, preserving completion, interruption and provider outcomes

func TurnFailureText

func TurnFailureText(stdout, stderr any) (string, error)

Failure text of a delivery turn, both non blank streams stripped and joined in the order written

func TurnLockPath

func TurnLockPath(root, profile string) string

Per profile lockfile path, short enough for macOS temp roots

func TurnWaitSeconds

func TurnWaitSeconds(ctx context.Context) (float64, error)

Wait budget of a queued delivery turn from config

func URLHostname

func URLHostname(raw string, percentDecode bool) (string, error)

Host a WHATWG client dials for the url, optionally percent decoded first, with the urlsplit ValueError

func UnattendedTurnFlag

func UnattendedTurnFlag(env *Env) bool

True while the bound turn is finite and unattended, so nobody can answer a prompt and approvals pass

func UnavailableInSessionReason

func UnavailableInSessionReason(name string) string

UnavailableInSessionReason explains why a registered tool absent from this session cannot be reached

func UnbindTurnWorkspace

func UnbindTurnWorkspace(env *Env, taskID string)

Drops the session workspace override registered for a task and the cwd record it seeded, keeping overrides others registered

func UnifiedDiff

func UnifiedDiff(a, b []string, fromfile, tofile string, n int) []string

Lines of difflib.unified_diff over lines that keep their terminators

func UniquifyToolCallIDs

func UniquifyToolCallIDs(toolCalls []state.ToolCall, taken map[string]bool) []state.ToolCall

UniquifyToolCallIDs renames duplicate ids within one turn with a deterministic _d suffix, keeping call_id in step

func UnmarkCopyHeld

func UnmarkCopyHeld(delegationID string)

Ends one hold on a delegation copy

func UnofferedToolReason

func UnofferedToolReason(ctx context.Context, env *Env, name string, deferred map[string]bool, enabled, disabled []string) string

UnofferedToolReason explains a call naming a registered tool the request did not offer, empty for an unregistered name

func UnregisterGatewayNotify

func UnregisterGatewayNotify(sessionKey string)

UnregisterGatewayNotify removes the callback and wakes every blocked waiter of the session

func UnregisterPlatformDeclaration

func UnregisterPlatformDeclaration(serverName string)

Removes the declaration registered for a server name

func UnrenameToolArgs

func UnrenameToolArgs(paramsSchema any, args any, rootSchema any) any

UnrenameToolArgs maps sanitized keys in model emitted args back to the registry wire names

func ValidateAction

func ValidateAction(action string, names []string) string

The reason action does not fit these targets, empty when it does

func ValidateDeferredCallArgs

func ValidateDeferredCallArgs(ctx context.Context, env *Env, name string, args any) string

Checks tool_call arguments, a dict as a map or ordered object, against the deferred tool schema, failing open

func ValidateDistribution

func ValidateDistribution(name string) bool

ValidateDistribution reports whether a distribution name exists

func ValidateOutput

func ValidateOutput(text string, schema any) (bool, []string, error)

Validity of a final answer against schema with retry ready error strings, at most ten

func ValidateOutputAt

func ValidateOutputAt(text string, schema any, validateDepth int) (bool, []string, error)

ValidateOutput whose validator runs validateDepth Python frames deep, the depth of the reference call site it mirrors

func ValidatePlatformToolsets

func ValidatePlatformToolsets(platformToolsets map[string]any, isValid func(string) bool) []string

ValidatePlatformToolsets returns the warnings for a platform_toolsets mapping judged with the platform scope rules

func ValidatePlatformToolsetsWith

func ValidatePlatformToolsetsWith(platformToolsets any, isValid func(string) bool, isAllowed func(string, string) bool) []string

ValidatePlatformToolsetsWith reports unknown, platform restricted, empty and non list entries of a platform_toolsets mapping

func ValidateRasterImageDecodable

func ValidateRasterImageDecodable(path string) string

ValidateRasterImageDecodable reports why an image file cannot be fully decoded, empty when every frame decodes

func ValidateWithinDir

func ValidateWithinDir(path, root string) string

Error text when a path does not resolve inside root with symlinks and dot dot followed, empty otherwise

func ValidateWorkdir

func ValidateWorkdir(workdir string) string

Workdir guard verdict, empty when the workdir is allowed

func ValidatedRuntimeVenv

func ValidatedRuntimeVenv(child map[string]string) (string, bool, error)

Producer owned runtime venv, the PM generation, a sealed payload venv, then a proven repo VIRTUAL_ENV

func VaultSessionID

func VaultSessionID(ctx context.Context) *string

The session bound on this thread, nil when none is bound

func VerbDropsPreview

func VerbDropsPreview(toolName string) bool

VerbDropsPreview reports whether the verb renders alone without the argument preview

func VerboseToolArgsText

func VerboseToolArgsText(args *pyjson.Object, maxLen int, codeBlock bool) string

VerboseToolArgsText renders the typed ordered args as json.dumps does, capped at maxLen, code blocked with real line breaks

func VisionAnalyzeTool

func VisionAnalyzeTool(ctx context.Context, env *Env, imageURL, userPrompt string) string

VisionAnalyzeTool describes an image with the default auxiliary vision model and returns the JSON result text

func VoiceLiveTurnNoteFor

func VoiceLiveTurnNoteFor(context string) string

Live voice turn note followed by the recent spoken exchange the client sent, the bare note without one

func WaitForAllBackendTeardowns

func WaitForAllBackendTeardowns(timeout time.Duration) bool

WaitForAllBackendTeardowns joins every in flight teardown worker within the timeout

func WaitForGatewayClarify

func WaitForGatewayClarify(ctx context.Context, env *Env, clarifyID string, timeout time.Duration) *string

WaitForGatewayClarify blocks until the entry resolves or the timeout elapses, nil on timeout or unknown id

func WarmEnvironmentProbeAsync

func WarmEnvironmentProbeAsync()

WarmEnvironmentProbeAsync starts the probe in the background ahead of the first prompt build

func WebExtractTool

func WebExtractTool(ctx context.Context, env *Env, items []any, format string, charLimit any) string

WebExtractTool extracts clean page content from URLs through the configured backend

func WebProviderIsReady

func WebProviderIsReady(env *Env, p WebProvider) bool

True when a web provider is keyed available or keyless capable without raising

func WebSearchRegistryScoped

func WebSearchRegistryScoped() providerregistry.ScopedRegistry

Untyped view of the web search registry the plugin context register_web_search_provider drives

func WebSearchTool

func WebSearchTool(ctx context.Context, env *Env, query string, limitArg any) string

WebSearchTool searches the web through the configured backend and returns the result JSON

func WindowsHideAttr

func WindowsHideAttr() *syscall.SysProcAttr

WindowsHideAttr is the console hiding attribute set, nil outside Windows

func WithActingFor

func WithActingFor(ctx context.Context, id WorkerID) context.Context

WithActingFor marks a deadline worker as acting for the tool worker that spawned it

func WithActivityCallback

func WithActivityCallback(ctx context.Context, cb func(string)) context.Context

WithActivityCallback binds the liveness callback long waits fire for the gateway inactivity timeout

func WithClarifyCallback

func WithClarifyCallback(ctx context.Context, cb ClarifyCallback) context.Context

Binds the session's clarify surface to the tool calls of a turn

func WithDelegatedChildContext

func WithDelegatedChildContext(ctx context.Context, active bool) context.Context

WithDelegatedChildContext marks a context as running for a delegate_task child

func WithDispatcher

func WithDispatcher(ctx context.Context, d *Dispatcher) context.Context

WithDispatcher binds the dispatcher whose hooks nested tool calls from a handler run through

func WithEditApprovalRequester

func WithEditApprovalRequester(ctx context.Context, requester EditApprovalRequester) context.Context

Binds an ACP edit approval requester for the calls made under ctx, nil leaving edits unguarded

func WithEnabledTools

func WithEnabledTools(ctx context.Context, names []string) context.Context

WithEnabledTools carries the sandbox tool list execute_code reads

func WithEnvHome

func WithEnvHome(ctx context.Context, env *Env) context.Context

Context whose home override is the profile home the env is bound to, ctx itself for an env naming none

func WithLSPOwner

func WithLSPOwner(ctx context.Context, owner string) context.Context

Attributes LSP verdicts of writes under the returned context to the owner session

func WithParentAgent

func WithParentAgent(ctx context.Context, agent any) context.Context

Binds the parent agent a dispatched tool may hand its children, the parent_agent handler kwarg

func WithProfileTerminalScope

func WithProfileTerminalScope(ctx context.Context, h string, envOverlay map[string]string) context.Context

Binds the profile policy of a home on the context, the refusal scope when it cannot be resolved

func WithPythonTaskSchemas

func WithPythonTaskSchemas(tasks, pyTasks any) any

Task list with each task's output_schema swapped for its Python valued copy, the dict delegate_task parsed

func WithSessionToolScope

func WithSessionToolScope(ctx context.Context, scope string) context.Context

WithSessionToolScope binds an execution owned tool overlay that reads merge over the profile registry

func WithSessionYolo

func WithSessionYolo(modelConfig map[string]any, sessionKey string) map[string]any

WithSessionYolo returns the model config of a session row being created carrying a live bypass

func WithThreadLocals

func WithThreadLocals(ctx context.Context) context.Context

Context with empty goroutine local storage, what a freshly started thread sees

func WithThreadLocalsOf

func WithThreadLocalsOf(ctx, from context.Context) context.Context

Context sharing the goroutine local storage of from, one thread running its next task

func WithToolEnv

func WithToolEnv(ctx context.Context, env *Env) context.Context

Binds the session tool environment so context only callers read its session flags

func WithWorker

func WithWorker(ctx context.Context, id WorkerID) context.Context

WithWorker binds the executing worker identity to the context

func WithdrawGatewayApproval

func WithdrawGatewayApproval(sessionKey, requestID, cause string) bool

WithdrawGatewayApproval cancels one pending approval nobody can answer, false when no longer pending

func WithoutServiceTier

func WithoutServiceTier(overrides any) map[string]any

Deep copy of overrides without a speed tier key at the top level or inside extra_body

func WorkspaceKeyFor

func WorkspaceKeyFor(cwd string) string

WorkspaceKeyFor is the digest of a host workspace computed once when the session binds it

func WorktreeCommand

func WorktreeCommand(ctx context.Context, env *Env, ns map[string]any, w io.Writer) (int, error)

Normalizes the ls and audit aliases to list, then runs the worktree command

func WorktreeGitQuiet

func WorktreeGitQuiet(args []string, cwd string, timeout time.Duration, log string, env map[string]string)

WorktreeGitQuiet runs git swallowing every error, logging it at debug under the given prefix

func WorktreeHasUnpushedCommits

func WorktreeHasUnpushedCommits(worktreePath string, timeout time.Duration) bool

WorktreeHasUnpushedCommits reports commits the worktree branch has not pushed

func WorktreeIsDirty

func WorktreeIsDirty(worktreePath, repoRoot string, timeout time.Duration) bool

WorktreeIsDirty reports uncommitted work in a worktree

func WorktreeIsolation

func WorktreeIsolation(ctx context.Context) bool

Whether each child gets its own git worktree off the parent HEAD

func WorktreeState

func WorktreeState(info map[string]any) string

Dirty, unpushed or empty for a clean and pushed or gone tree

func WorktreeStillInUse

func WorktreeStillInUse(path string, grace time.Duration) bool

Whether another live process still works in the tree after the grace period

func WorktreesSummary

func WorktreesSummary(repoRoot string, sizeBelowCount *int) (int, *int)

Tree count and total megabytes of the worktrees dir, size skipped once the count reaches sizeBelowCount

func WriteApprovalEnabled

func WriteApprovalEnabled(env *Env, subsystem string) bool

Subsystem write_approval flag from the live config, unset or invalid values leave the gate off

func WriteDeniedError

func WriteDeniedError(env *Env, path, verb string, entry bool) string

Model facing write block error for the verb, empty when the path may be written

func WriteFileTool

func WriteFileTool(ctx context.Context, env *Env, path, content, taskID string, crossProfile bool, sessionID string) string

WriteFileTool exposes the write_file tool entry to packages that drive it directly

func WriteTextExclusive

func WriteTextExclusive(path, text string, private, overwrite bool) error

WriteTextExclusive writes text through an exclusive create that refuses to follow symlinks

func WritesSince

func WritesSince(excludeTaskID string, sinceTs float64, paths []string) map[string][]string

WritesSince reports paths other agents wrote after a timestamp, keyed by writer task id

func XAIDefaultHeaders

func XAIDefaultHeaders() map[string]string

Headers for SDK and raw HTTP clients talking to xAI, replacing the SDK user agent

func YoloModeFrozen

func YoloModeFrozen() bool

Launch time yolo flag frozen from ICEBATH_YOLO_MODE that the agent records in its session model config

Types

type Answer

type Answer struct {
	Status   string
	Text     string
	Selected []string
}

Answer is one user response in question order

type ApprovalCallbackAsker

type ApprovalCallbackAsker interface {
	ApprovalCallback(ctx context.Context, command, description string, o ApprovalCallbackOptions) (string, error)
}

ApprovalCallbackAsker is an asker that is an approval callback, called with the redacted command and description and answering verbatim

type ApprovalCallbackOptions

type ApprovalCallbackOptions struct {
	AllowPermanent bool
	AllowSession   bool
	SmartDenied    bool
	Title          string
}

ApprovalCallbackOptions are the keywords an approval callback receives beside the command and its description

type ApprovalEntry

type ApprovalEntry struct {
	Data         map[string]any
	Acknowledged bool
	Settle       func(reason string)
	Observers    []func(reason string)
	Result       string
	Reason       string
	Cancelled    string
	Expired      bool
	// contains filtered or unexported fields
}

ApprovalEntry is one pending dangerous command approval inside a gateway session

func QueueGatewayApprovalForTests

func QueueGatewayApprovalForTests(sessionKey string, data map[string]any) *ApprovalEntry

Appends a pending gateway approval entry to a session queue the way a test seeds gateway queues

func (*ApprovalEntry) Done

func (e *ApprovalEntry) Done() <-chan struct{}

Channel closed when the entry is resolved, withdrawn, or expired

func (*ApprovalEntry) RequestID

func (e *ApprovalEntry) RequestID() string

RequestID of the entry as published to clients

type ApprovalGateOptions

type ApprovalGateOptions struct {
	PatternKey, Description, DisplayTarget string
	ApprovalCallback                       Asker
	Subject, Noun, Advice                  string
	CronDenyMessage                        string
	SingleQueryDenyMessage                 string
	UnattendedDenyMessage                  string
	AutoapproveLogPrefix                   string
	FailClosedWhenNoHuman                  bool
	NoHumanBlockMessage                    string
	PatternKeys                            []string
}

ApprovalGateOptions are the keyword arguments of the shared approval gate, ApprovalCallback overrides the session asker

type ApprovalPresentFunc

type ApprovalPresentFunc func(ctx context.Context, req ApprovalRequest) (ApprovalTransportDecision, error)

ApprovalPresentFunc shows one request through a plugin transport and returns the human decision

type ApprovalRecord

type ApprovalRecord struct {
	Command     string
	Description string
}

ApprovalRecord is one dangerous classified terminal command that actually ran

func ScanApprovalHistory

func ScanApprovalHistory(dbPath string, days int) ([]ApprovalRecord, error)

ScanApprovalHistory lists dangerous classified terminal commands that executed with implied consent

type ApprovalRequest

type ApprovalRequest struct {
	SchemaVersion  int
	RequestID      string
	Digest         string
	Command        string
	Description    string
	PatternKey     string
	PatternKeys    []string
	Surface        string
	TimeoutSeconds float64
	AllowedChoices []string
}

ApprovalRequest is the immutable display only request passed to a transport plugin

func (ApprovalRequest) Respond

Respond builds the correlated response a transport returns

type ApprovalTransportDecision

type ApprovalTransportDecision struct {
	RequestID     string
	RequestDigest string
	Choice        string
}

ApprovalTransportDecision is a transport response bound to one exact host created request

type Archive

type Archive struct {
	Ref     string
	Name    string
	Sha     string
	Created float64
	Meta    *pyjson.Object
	Staged  string
}

One archive ref with its metadata and the staged digest of the index it captured

func FindArchive

func FindArchive(repoRoot, name string) (*Archive, error)

Exact archive name or ref first, else the newest archive of the tree with that name

func ListArchives

func ListArchives(repoRoot string) ([]Archive, error)

Every archive of the repository newest first, empty when git fails, a malformed created stamp raises

func SnapshotWorktree

func SnapshotWorktree(repoRoot, wtPath, reason string, maxUntrackedMB float64) (*Archive, error)

Archives the full working state of the tree through a temporary index, never touching its real index or files

type ArchiveError

type ArchiveError struct{ Msg string }

Snapshot or restore failure after which callers must keep the tree

func (*ArchiveError) Error

func (e *ArchiveError) Error() string

type ArchiveRemoval

type ArchiveRemoval struct {
	Ref        string
	KeptBranch *string
	Removed    bool
	WhyKept    string
}

Outcome of archiving then removing one tree

func ArchiveThenRemove

func ArchiveThenRemove(repoRoot, path, reason string, maxUntrackedMB float64, unlock bool, remoteHeads func() (map[string]string, bool), keepBranch bool, excludePids []int) (*ArchiveRemoval, error)

Snapshots the tree then removes it unless it changed, is in use or holds what the archive lacks

type ArchivedTree

type ArchivedTree struct {
	Ref     string
	Removed bool
	WhyKept string
}

Archive ref of one archived tree with whether it was removed and why it was kept

func ExecutePlan

func ExecutePlan(repoRoot string, plan []*Decision, s SweepConfig) ([]string, map[string]bool, []ArchivedTree)

Applies a frozen plan re gating each tree right before it is archived or removed

type Asker

type Asker interface {
	Ask(ctx context.Context, questions []Question) (FormResult, error)
}

Asker is the human in the loop for approvals and clarifying questions

type AssemblyResult

type AssemblyResult struct {
	ToolDefs        []map[string]any
	Activated       bool
	DeferredCount   int
	DeferredTokens  int
	ThresholdTokens int
	// 0 passthrough, 1 bridge with per tool listing, 2 bare bridge or server summary only
	Tier        int
	ListingForm string
}

AssemblyResult is the outcome of one assembly for tests and observability

func AssembleToolDefs

func AssembleToolDefs(ctx context.Context, env *Env, toolDefs []map[string]any, contextLength int, cfg *ToolSearchConfig) AssemblyResult

AssembleToolDefs replaces deferrable tools by the bridge tools when active, stripping stale bridges first

type AsyncDelegationCompletions

type AsyncDelegationCompletions interface {
	RestoreUndelivered(q *EventQueue) (int, error)
	CopyID(evt map[string]any) string
	MarkCopyHeld(id string)
	UnmarkCopyHeld(id string)
}

AsyncDelegationCompletions is the durable delegation completion ledger

type AsyncDelegationRequest

type AsyncDelegationRequest struct {
	Goal, Context     string
	Toolsets          []string
	Role              string
	Model             *string
	SessionKey        string
	ParentSessionID   *string
	Runner            func() *pyjson.Object
	OriginUISessionID string
	OriginSessionID   string
	MaxAsyncChildren  int
}

One single background unit a caller outside pkg/tools dispatches

type AsyncDispatch

type AsyncDispatch struct {
	DelegationID      string
	Goal              string
	Goals             []string
	IsBatch           bool
	Context           *string
	Toolsets          []string
	Role              string
	Model             *string
	SessionKey        string
	ParentSessionID   *string
	Runner            func(ctx context.Context, env *Env) (map[string]any, error)
	OriginUISessionID string
	OriginSessionID   string
	InterruptFn       func() error
	MaxAsyncChildren  int
	ProgressFn        func() (any, bool, error)
	CapacityError     string
	SlotKey           string
	TaskIndexes       []int
	TaskTranscripts   map[string]string
}

AsyncDispatch is one single or batch unit handed to the async delegation executor

type AuthorizationGate

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

AuthorizationGate serializes policy prompts and excludes human approval waits from batch deadlines

func NewAuthorizationGate

func NewAuthorizationGate(env *Env, lockTimeout time.Duration) *AuthorizationGate

NewAuthorizationGate snapshots the session key and human wait baseline on the submitting side

func NewAuthorizationGateWith

func NewAuthorizationGateWith(env *Env, opts AuthorizationGateOptions) *AuthorizationGate

Builds a gate whose zero lock bound tries once and whose negative bound waits without limit

func (*AuthorizationGate) ExcludedSeconds

func (g *AuthorizationGate) ExcludedSeconds() float64

ExcludedSeconds is the human approval wait accrued since the batch started

func (*AuthorizationGate) Run

func (g *AuthorizationGate) Run(callback func())

Run executes the callback under the bounded serialization lock, unserialized once the bound expires

type AuthorizationGateOptions

type AuthorizationGateOptions struct {
	LockTimeout *time.Duration
	SessionKey  *string
}

Explicit lock bound and session key of a gate, nil fields resolving the configured bound and the current session

type Aux

type Aux interface {
	Complete(ctx context.Context, messages []*state.Message, opts AuxOptions) (string, error)
}

Aux performs auxiliary model completions for vision, summaries, and compression

var ProcessAux Aux

ProcessAux is the auxiliary client an Env without its own resolves every call through, set by pkg/provider

type AuxOptions

type AuxOptions struct {
	Task        string
	Model       string
	MaxTokens   int
	Temperature *float64
	JSONSchema  map[string]any
	Timeout     time.Duration
	// Routes the call through the async call_llm path the reference vision tools use
	Async bool
}

AuxOptions tunes one auxiliary model completion

type AuxTaskResolver

type AuxTaskResolver interface {
	ResolvesVision(ctx context.Context, provider string) (bool, error)
}

AuxTaskResolver is implemented by auxiliary routers that resolve the vision task to a client in probe mode without building it

type BackendInfo

type BackendInfo struct {
	Name        string
	Label       string
	Description string
	Available   bool
	Reason      string
}

One selectable delegation backend, Available false carrying the reason it cannot run

func ListDelegationBackends

func ListDelegationBackends(ctx context.Context) []BackendInfo

Default backend first, then every registered backend with unavailable ones carrying their reason

type BackendMissingError

type BackendMissingError struct{ Reason string }

BackendMissingError reports that a backend's SDK or helper is not installed

func (*BackendMissingError) Error

func (e *BackendMissingError) Error() string

type BackendProvider

type BackendProvider interface {
	Name() string
	DisplayName() string
	Description() string
	EnvDescription() string
	IsRemote() bool
	IsContainer() bool
	SkipContainerGuards() bool
	CachePathBase() string
	DefaultCwd() string
	StripEnvKeys() []string
	SessionIsolatedWhenNonpersistent() bool
	SupportsStreams() bool
	IsAvailable() bool
	CheckRequirements(env *Env, cfg map[string]any) error
	SetupInstructions(env *Env) []string
	DoctorChecks() []DoctorCheck
	CreateEnvironment(ctx context.Context, env *Env, opts CreateOptions) (Environment, error)
}

BackendProvider describes one pluggable terminal backend and creates its environments

func GetTerminalBackend

func GetTerminalBackend(name string) BackendProvider

GetTerminalBackend returns the built in backend of a name, else the plugin backend of the active scope, else nil

func GetTerminalBackendScoped

func GetTerminalBackendScoped(ctx context.Context, name, scope string) BackendProvider

Built in backend of a name, else the plugin backend registered in scope then globally, nil when absent

func PluginTerminalBackend

func PluginTerminalBackend(ctx context.Context, name, scope string) BackendProvider

Plugin terminal backend registered under a name in scope then globally, nil when absent

type BatchAdmission

type BatchAdmission struct {
	Name     string
	Paths    []string
	IsWriter bool
}

BatchAdmission classifies one call for the planner, nil for a sequential barrier

type BatchSegment

type BatchSegment struct {
	Mode  string
	Calls []state.ToolCall
}

BatchSegment is one ordered run of calls executed in parallel or sequentially

func PlanToolBatchSegments

func PlanToolBatchSegments(ctx context.Context, env *Env, toolCalls []state.ToolCall, executionCwd string) []BatchSegment

PlanToolBatchSegments splits a batch into ordered parallel or sequential segments preserving call order

type BlockedRedirectError

type BlockedRedirectError struct{ Target string }

HTTP client that re validates DNS at connect time and dials a vetted IP with the hostname kept for SNI Refusal of a redirect whose target is a private or internal address

func (*BlockedRedirectError) Error

func (e *BlockedRedirectError) Error() string

type BranchRecord

type BranchRecord struct {
	Name    string `json:"name"`
	Verdict string `json:"verdict"`
	Reason  string `json:"reason"`
}

One local branch with its delete or keep verdict

func AuditBranches

func AuditBranches(repoRoot string) ([]BranchRecord, error)

Classifies every local branch by content reachability, deletable when merged or patch equivalent upstream and not checked out

type BudgetConfig

type BudgetConfig struct {
	DefaultResultSize int
	TurnBudget        int
	PreviewSize       int
	MCPResultSize     int
	ToolOverrides     map[string]int
}

BudgetConfig holds the per result, per turn, and preview size budgets for tool result persistence

func BudgetForContextWindow

func BudgetForContextWindow(env *Env, contextLength int) BudgetConfig

BudgetForContextWindow scales the budget to the model's context window, capped at the defaults and floored

func (BudgetConfig) ResolveThreshold

func (c BudgetConfig) ResolveThreshold(env *Env, toolName string) int

Threshold for one tool, pinned then overrides then mcp prefix then registry then default

type Call

type Call struct {
	Name         string
	Args         map[string]any
	RawArgs      string // arguments JSON text as the model emitted it, the key order approval displays follow
	ToolCallID   string
	TaskID       string
	SessionID    string
	TurnID       string
	APIRequestID string
	UserTask     string
	Env          *Env
}

Call is one tool invocation with its arguments and session environment

type CaptureExitError

type CaptureExitError struct {
	Argv   []string
	Code   int
	Stderr string
}

CaptureExitError is a checked capture that exited nonzero

func (*CaptureExitError) Error

func (e *CaptureExitError) Error() string

Program, exit status and stderr first so a cut message keeps the cause, the full command last

type CaptureResult

type CaptureResult struct {
	Code   int
	Stdout string
	Stderr string
}

CaptureResult is a finished captured child process

type CatalogEntry

type CatalogEntry struct {
	Name        string
	Description string
	Schema      map[string]any
	Source      string
	SourceName  string
	Tokens      []string
}

CatalogEntry is one deferrable tool in the form the bridge tools search and serve

func BuildCatalog

func BuildCatalog(ctx context.Context, env *Env, toolDefs []map[string]any) []CatalogEntry

BuildCatalog builds the deferred tool catalog from the deferrable subset of tool defs

func SearchCatalog

func SearchCatalog(catalog []CatalogEntry, query string, limit int, stats *CorpusStats) []CatalogEntry

SearchCatalog returns the top limit entries by BM25 with exact name matches ranked first

type CheckpointAutoPruneOptions

type CheckpointAutoPruneOptions struct {
	RetentionDays    int
	MinIntervalHours int
	DeleteOrphans    bool
	Base             string
	MaxTotalSizeMB   int
}

The knobs of the idempotent startup prune

type CheckpointAutoPruneOutcome

type CheckpointAutoPruneOutcome struct {
	Skipped bool
	Result  *CheckpointPruneResult
	Error   string
}

Reports whether an auto prune ran, its counts and any failure text

func AutoPruneCheckpointsFromConfig

func AutoPruneCheckpointsFromConfig(env *Env) CheckpointAutoPruneOutcome

Runs the startup prune from the checkpoints config section, never deleting orphans unattended

func MaybeAutoPruneCheckpoints

func MaybeAutoPruneCheckpoints(env *Env, o CheckpointAutoPruneOptions) CheckpointAutoPruneOutcome

Prunes at most once per interval, claiming the interval in the marker before it runs

type CheckpointClearLegacyResult

type CheckpointClearLegacyResult struct {
	BytesFreed int64 `json:"bytes_freed"`
	Deleted    int   `json:"deleted"`
	Errors     int   `json:"errors"`
}

Reports the legacy archives deleted, bytes freed and failures

func ClearLegacyCheckpoints

func ClearLegacyCheckpoints(env *Env, base string) CheckpointClearLegacyResult

Deletes every legacy archive directory under the store lock and counts failures

type CheckpointClearResult

type CheckpointClearResult struct {
	BytesFreed int64 `json:"bytes_freed"`
	Deleted    bool  `json:"deleted"`
}

Reports what clearing the whole base freed

func ClearAllCheckpoints

func ClearAllCheckpoints(env *Env, base string) CheckpointClearResult

Deletes the entire checkpoint base, store and legacy archives, under the store lock

type CheckpointEntry

type CheckpointEntry struct {
	Hash         string `json:"hash"`
	ShortHash    string `json:"short_hash"`
	Timestamp    string `json:"timestamp"`
	Reason       string `json:"reason"`
	FilesChanged int    `json:"files_changed"`
	Insertions   int    `json:"insertions"`
	Deletions    int    `json:"deletions"`
	Workdir      string `json:"workdir,omitempty"`
}

One snapshot of a project, newest first in listings

type CheckpointLegacyArchive

type CheckpointLegacyArchive struct {
	Name      string  `json:"name"`
	SizeBytes int64   `json:"size_bytes"`
	Mtime     float64 `json:"mtime"`
}

One legacy archive directory left by the v2 migration

type CheckpointManager

type CheckpointManager struct {
	Enabled        bool
	MaxSnapshots   int
	MaxTotalSizeMB int
	MaxFileSizeMB  int
	// contains filtered or unexported fields
}

Takes transparent filesystem snapshots into the shared shadow store, at most once per directory per turn

func NewCheckpointManager

func NewCheckpointManager(env *Env, o CheckpointManagerOptions) *CheckpointManager

Builds a manager for the env's profile with the budgets clamped to sane minimums

func (*CheckpointManager) ChangedFilesSince

func (m *CheckpointManager) ChangedFilesSince(workingDir string, since float64) []string

ChangedFilesSince lists the files under a working directory that differ from the snapshot a span starting at an epoch second began from, tracked changes and deletions plus new files, read through a throwaway index so no object, ref or project index is written, none when checkpoints are off, no snapshot was taken in the span or git fails

func (*CheckpointManager) Diff

func (m *CheckpointManager) Diff(workingDir, commitHash string) map[string]any

Shows the stat and patch between a checkpoint and the current working tree under the store lock

func (*CheckpointManager) EnsureCheckpoint

func (m *CheckpointManager) EnsureCheckpoint(workingDir, reason string) (taken bool)

Snapshots the directory once per turn when enabled, true when a checkpoint was taken and never panicking

func (*CheckpointManager) EnsureFileCheckpoint

func (m *CheckpointManager) EnsureFileCheckpoint(name string, args map[string]any, taskID string)

Snapshots the workspace a write_file or patch call will mutate, resolved the way the file tools resolve it

func (*CheckpointManager) EnsureTerminalCheckpoint

func (m *CheckpointManager) EnsureTerminalCheckpoint(cwd, label, taskID string)

Snapshots the terminal working directory of a host backed task before a destructive command

func (*CheckpointManager) ListAllCheckpoints

func (m *CheckpointManager) ListAllCheckpoints() ([]CheckpointEntry, error)

Lists the snapshots of every registered project newest first, each labelled with its workdir

func (*CheckpointManager) ListCheckpoints

func (m *CheckpointManager) ListCheckpoints(workingDir string) []CheckpointEntry

Lists the directory's snapshots newest first with their shortstat counts

func (*CheckpointManager) NewTurn

func (m *CheckpointManager) NewTurn()

Resets the per turn dedup so the next mutation snapshots again

func (*CheckpointManager) RecordAgentWrite

func (m *CheckpointManager) RecordAgentWrite(filePath string)

Records the content hash of a file icebath just wrote so safe restores can spot later hand edits

func (*CheckpointManager) RecordLandedWrites

func (m *CheckpointManager) RecordLandedWrites(paths []string, taskID string)

Feeds the agent write ledger with every landed path of a host backed task

func (*CheckpointManager) Restore

func (m *CheckpointManager) Restore(workingDir, commitHash, filePath string, safe bool) map[string]any

Puts files back to a checkpoint under the store lock, safe mode keeping files the user edited after icebath

func (*CheckpointManager) SessionDiff

func (m *CheckpointManager) SessionDiff(workingDir string) map[string]any

Diffs the earliest retained checkpoint against the working tree, an empty success when none exists

func (*CheckpointManager) UnsupportedBackendReason

func (m *CheckpointManager) UnsupportedBackendReason(taskID string) string

Explains why host checkpoints are refused for a container backed task, empty otherwise

func (*CheckpointManager) UnsupportedBackendReasonIn

func (m *CheckpointManager) UnsupportedBackendReasonIn(env *Env, taskID string) string

Explains why host checkpoints are refused for a container backed task read through the given env, empty otherwise

func (*CheckpointManager) WorkingDirForPath

func (m *CheckpointManager) WorkingDirForPath(filePath string) (string, error)

Resolves a file to the directory that owns its checkpoints, the nearest registered root or marked project

type CheckpointManagerOptions

type CheckpointManagerOptions struct {
	Enabled        bool
	MaxSnapshots   int
	MaxTotalSizeMB int
	MaxFileSizeMB  int
}

The master switch and the snapshot count, store size and file size budgets

func CheckpointManagerOptionsFromKwargs

func CheckpointManagerOptionsFromKwargs(enabled bool, kwargs map[string]any) (CheckpointManagerOptions, error)

Manager options of the checkpoint_ prefixed agent keywords, a missing limit keeping the manager default

func DefaultCheckpointManagerOptions

func DefaultCheckpointManagerOptions() CheckpointManagerOptions

Disabled with twenty snapshots, a 500 MB store and a 10 MB file cap

type CheckpointPreV2Status

type CheckpointPreV2Status struct {
	Path    string  `json:"path"`
	Workdir *string `json:"workdir"`
	Exists  bool    `json:"exists"`
}

One pre v2 per project shadow repo still under the base

type CheckpointProjectStatus

type CheckpointProjectStatus struct {
	Hash      string `json:"hash"`
	Workdir   string `json:"workdir"`
	Exists    bool   `json:"exists"`
	CreatedAt any    `json:"created_at"`
	LastTouch any    `json:"last_touch"`
	Commits   int    `json:"commits"`
}

One v2 project of the store summary

type CheckpointPruneError

type CheckpointPruneError struct{ Msg string }

Stops a prune that has no permission to discard another snapshot

func (*CheckpointPruneError) Error

func (e *CheckpointPruneError) Error() string

type CheckpointPruneOptions

type CheckpointPruneOptions struct {
	RetentionDays  int
	DeleteOrphans  bool
	Base           string
	MaxTotalSizeMB int
	// Restricts orphan deletion to these project hashes and pre v2 repo paths, nil allows every orphan
	OrphanAllowlist map[string]bool
}

Selects the retention, orphan and size rules of one prune

type CheckpointPruneResult

type CheckpointPruneResult struct {
	Scanned       int   `json:"scanned"`
	DeletedOrphan int   `json:"deleted_orphan"`
	DeletedStale  int   `json:"deleted_stale"`
	Errors        int   `json:"errors"`
	BytesFreed    int64 `json:"bytes_freed"`
}

Counts what one prune scanned, deleted and reclaimed

func PruneCheckpoints

func PruneCheckpoints(env *Env, o CheckpointPruneOptions) (CheckpointPruneResult, error)

Deletes orphan and stale checkpoints and reclaims store space under the store lock

type CheckpointPruner

type CheckpointPruner struct {
	RunGit     checkpointGitFunc
	Store      string
	Cwd        string
	Timeout    int
	DirSize    func(string) int64
	RefsPrefix string
}

Rewrites checkpoint histories for the snapshot count and size budgets

func (*CheckpointPruner) DropOneRound

func (p *CheckpointPruner) DropOneRound(capBytes int64) (bool, error)

Drops the oldest snapshot of every project once when the store is over the cap, deferring the gc

func (*CheckpointPruner) EnforceSize

func (p *CheckpointPruner) EnforceSize(capBytes int64) (bool, error)

Runs gc then drops oldest snapshots round robin, remeasuring after each rewrite, for at most twenty rounds

func (*CheckpointPruner) GCPending

func (p *CheckpointPruner) GCPending() bool

Reports whether a deferred rewrite still waits for its gc

func (*CheckpointPruner) Reclaim

func (p *CheckpointPruner) Reclaim() error

Expires every reflog and runs a full gc, then restores the bare store directories and clears the marker

func (*CheckpointPruner) Trim

func (p *CheckpointPruner) Trim(ref string, keepCount int) error

Keeps the newest snapshots of the ref within the count budget and defers the gc

type CheckpointRenameResult

type CheckpointRenameResult struct {
	Scanned  int
	Migrated int
	Errors   int
}

Counts the checkpoint projects a profile rename scanned, rekeyed and failed

func MigrateProfileCheckpointProjects

func MigrateProfileCheckpointProjects(env *Env, oldProfileDir, newProfileDir string) CheckpointRenameResult

Rekeys checkpoint projects whose workdirs moved with a profile rename

type CheckpointStatus

type CheckpointStatus struct {
	Base            string                    `json:"base"`
	StoreSizeBytes  int64                     `json:"store_size_bytes"`
	LegacySizeBytes int64                     `json:"legacy_size_bytes"`
	TotalSizeBytes  int64                     `json:"total_size_bytes"`
	ProjectCount    int                       `json:"project_count"`
	Projects        []CheckpointProjectStatus `json:"projects"`
	PreV2Projects   []CheckpointPreV2Status   `json:"pre_v2_projects"`
	LegacyArchives  []CheckpointLegacyArchive `json:"legacy_archives"`
}

Summarises the shadow store, its projects, pre v2 repos and legacy archives

func CheckpointStoreStatus

func CheckpointStoreStatus(env *Env, base string) (CheckpointStatus, error)

Reports sizes, every project with its commit count, pre v2 repos and legacy archives

type ChildEnv

type ChildEnv struct {
	Keys []string
	Vars map[string]string
}

A child process environment with its names in the insertion order of the dict

func BuildSubprocessEnvOrdered

func BuildSubprocessEnvOrdered(ctx context.Context, env *Env, o SubprocessEnvOptions) (*ChildEnv, error)

BuildSubprocessEnvOrdered builds the child environment and keeps the insertion order of its names

func (*ChildEnv) Environ

func (c *ChildEnv) Environ() []string

Environ lists the entries as NAME=value in dict order, the order execve receives them

type ChildProcess

type ChildProcess interface {
	Pid() int
	Kill() error
	WaitExit(timeout time.Duration) bool
}

ChildProcess is a retained child handle the tree kill helpers signal, wait on and reap

type ClarifyCallback

type ClarifyCallback func(ctx context.Context, shown []any) (map[string]any, error)

The surface callback of the clarify tool, shown questions in and an answers outcome notice dict out

func ClarifyCallbackFrom

func ClarifyCallbackFrom(ctx context.Context) ClarifyCallback

Clarify surface bound to the turn, nil when the session has none

type ClarifyEntry

type ClarifyEntry struct {
	ClarifyID    string
	SessionKey   string
	Question     string
	Choices      []string
	MultiSelect  bool
	AwaitingText bool
	// contains filtered or unexported fields
}

ClarifyEntry is one pending clarify request inside a gateway session

func GetPendingClarify

func GetPendingClarify(clarifyID string) *ClarifyEntry

GetPendingClarify returns the entry while it still awaits an answer

func GetPendingClarifyForSession

func GetPendingClarifyForSession(sessionKey string, includeChoicePrompts bool) *ClarifyEntry

GetPendingClarifyForSession returns the oldest entry awaiting free text, or any unresolved entry when asked

func RegisterGatewayClarify

func RegisterGatewayClarify(clarifyID, sessionKey, question string, choices []string, multiSelect bool) *ClarifyEntry

RegisterGatewayClarify registers a pending clarify, open ended entries start in text mode

func (*ClarifyEntry) Resolved

func (e *ClarifyEntry) Resolved() bool

Whether a pending clarify was answered, cancelled or timed out

func (*ClarifyEntry) Response

func (e *ClarifyEntry) Response() *string

Answer the clarify settled with, nil while unanswered or after a timeout

type ClarifyReply

type ClarifyReply struct {
	Answers map[string]any
	Outcome string
	Notice  string
}

ClarifyReply is what a surface returns for one clarify call

type CleanupWaiter

type CleanupWaiter interface {
	WaitForCleanup(timeout time.Duration)
}

CleanupWaiter blocks until a backend's detached teardown worker finishes

type CmdChild

type CmdChild struct {
	Cmd *exec.Cmd
	// contains filtered or unexported fields
}

CmdChild is a started command reaped by one goroutine so its exit can be awaited with a timeout

func WatchCmd

func WatchCmd(cmd *exec.Cmd) *CmdChild

WatchCmd reaps an already started command in the background

func (*CmdChild) Done

func (c *CmdChild) Done() <-chan struct{}

Done is closed once the child has been reaped

func (*CmdChild) Err

func (c *CmdChild) Err() error

Err blocks until the child is reaped and returns what Wait returned

func (*CmdChild) Kill

func (c *CmdChild) Kill() error

Kill sends the child alone a kill, an already reaped child is no error as with Popen.kill

func (*CmdChild) Pid

func (c *CmdChild) Pid() int

Pid is the child process id

func (*CmdChild) WaitExit

func (c *CmdChild) WaitExit(timeout time.Duration) bool

WaitExit reports whether the child exited within timeout

type CodePrompt

type CodePrompt func(site, hint string) string

CodePrompt asks the one time code a site sent, empty when declined

func GetCodePromptCallback

func GetCodePromptCallback(ctx context.Context) CodePrompt

The one time code prompt of the current thread, nil in headless contexts

type CommandVerdict

type CommandVerdict struct {
	Command            string
	EnvType            string
	Verdict            string
	ExitCode           int
	Rule               string
	Detail             string
	NormalizedVariants []string
}

CommandVerdict is the dry run answer of EvaluateCommand

func EvaluateCommand

func EvaluateCommand(env *Env, command, envType string) CommandVerdict

EvaluateCommand composes the runtime evaluators in guard order without running, prompting, or persisting

type ConfigurableToolset

type ConfigurableToolset struct {
	Key, Label, Description string
}

ConfigurableToolset is one checklist row the configurator shows

func EffectiveConfigurableToolsets

func EffectiveConfigurableToolsets(ctx context.Context) (result []ConfigurableToolset)

Built in configurable toolsets then plugin toolsets whose keys are not built in

type ConnActor

type ConnActor string

ConnActor names who may cause a target transition

const (
	ActorUser           ConnActor = "user"
	ActorBackendWatcher ConnActor = "backend_watcher"
)

func AllowedTransition

func AllowedTransition(kind string, current, to TargetState) ConnActor

The only actor allowed to move a target of kind from current to to, empty when the move is illegal

type ConnCallback

type ConnCallback func(payload *pyjson.Object) string

ConnCallback hands the connection.request payload to the surface that draws the card

type ConnEvent

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

ConnEvent is a settable flag a waiter can block on with a timeout

func NewConnEvent

func NewConnEvent() *ConnEvent

func (*ConnEvent) Clear

func (e *ConnEvent) Clear()

func (*ConnEvent) IsSet

func (e *ConnEvent) IsSet() bool

func (*ConnEvent) Set

func (e *ConnEvent) Set()

func (*ConnEvent) Wait

func (e *ConnEvent) Wait(timeout time.Duration) bool

Blocks until the flag is set or the timeout passes and reports whether it was set

type ConnKind

type ConnKind struct {
	Prepare func(op *ConnectionOperation)
	Observe func(op *ConnectionOperation)
	Note    string
	Result  func(op *ConnectionOperation) *pyjson.Object
}

ConnKind holds the per kind hooks of a driven operation and the note appended to its result

type ConnTarget

type ConnTarget struct {
	Name         string
	Kind         string
	Action       string
	State        TargetState
	Detail       string
	Instructions string
	ConnectURL   string
	Attempt      string
	NextReadAt   float64
	RequiredEnv  []*pyjson.Object
	Extra        *pyjson.Object
	Phase        string
}

ConnTarget is one row of a connection operation

func NewConnTarget

func NewConnTarget(name, kind, action string) *ConnTarget

Pending target of kind running action

type ConnectionOperation

type ConnectionOperation struct {
	Targets    []*ConnTarget
	SessionKey string
	ProfileKey string
	ToolCallID string
	Call       any
	OpID       string
	CreatedAt  float64
	DeadlineAt float64
	Wake       *ConnEvent
	// contains filtered or unexported fields
}

ConnectionOperation is one card's set of targets with a server owned deadline and a frozen result

func LiveCurrent

func LiveCurrent(sessionKey, profileHome string) *ConnectionOperation

The session's unsettled open operation or nil

func LiveGet

func LiveGet(sessionKey, opID, profileHome string) *ConnectionOperation

The session's open operation when its id matches, settled or not

func NewConnectionOperation

func NewConnectionOperation(targets []*ConnTarget, sessionKey, toolCallID string, call any) *ConnectionOperation

Operation over targets with a fresh id and the deadline counted from now

func NewDetachedOperation

func NewDetachedOperation(targets []*ConnTarget, sessionKey string) *ConnectionOperation

Operation that never reaches the renderer hook, the no card path

func (*ConnectionOperation) AllResolved

func (o *ConnectionOperation) AllResolved() bool

Whether there is at least one target and every target is resolved

func (*ConnectionOperation) Refresh

func (o *ConnectionOperation) Refresh(name, connectURL, detail string, actor ConnActor, phase string) error

Replaces a target's link, detail and install phase with no state change

func (*ConnectionOperation) RemainingSeconds

func (o *ConnectionOperation) RemainingSeconds(now ...float64) float64

Seconds left until the deadline, at now when given else the wall clock, never negative

func (*ConnectionOperation) RequestPayload

func (o *ConnectionOperation) RequestPayload() *pyjson.Object

The connection.request payload and resume snapshot with live rows and the server deadline

func (*ConnectionOperation) ResolvedTarget

func (o *ConnectionOperation) ResolvedTarget(t *ConnTarget) bool

Whether the target is resolved, read under the operation lock

func (*ConnectionOperation) Result

func (o *ConnectionOperation) Result(ctx context.Context, env *Env, withURLs bool) *pyjson.Object

Model facing result, settled MCP rows carrying the catalog listing of their connected tools

func (*ConnectionOperation) Settle

func (o *ConnectionOperation) Settle(by SettleReason, now ...float64) bool

Freezes the result once, stamping every unresolved target not connected, false for a later caller

func (*ConnectionOperation) SettleIfAllResolved

func (o *ConnectionOperation) SettleIfAllResolved() bool

Settles with all_resolved when every target is resolved

func (*ConnectionOperation) Settled

func (o *ConnectionOperation) Settled() bool

func (*ConnectionOperation) SettledBy

func (o *ConnectionOperation) SettledBy() SettleReason

The reason the operation settled, empty while it is open

func (*ConnectionOperation) Snapshot

func (o *ConnectionOperation) Snapshot(withURLs bool) *pyjson.Object

Live snapshot, the frozen one once settled

func (*ConnectionOperation) StateOf

The target's state read under the operation lock

func (*ConnectionOperation) Target

func (o *ConnectionOperation) Target(name string) *ConnTarget

The target named name or nil

func (*ConnectionOperation) Transition

func (o *ConnectionOperation) Transition(name string, to TargetState, actor ConnActor, f TransitionFields) (*pyjson.Object, error)

Moves one target when the contract lets actor, nil change when it already sits in to

func (*ConnectionOperation) UpdateTarget

func (o *ConnectionOperation) UpdateTarget(t *ConnTarget, fn func(t *ConnTarget))

Runs fn on the target under the operation lock so readers never see a half written row

type ContextLengthQuery

type ContextLengthQuery struct {
	Model               string
	BaseURL             string
	APIKey              string
	Provider            string
	ConfigContextLength int
}

ContextLengthQuery carries the routing a provider aware context window lookup needs, zero ConfigContextLength means unset

type ContextProfile

type ContextProfile struct {
	Name                   string
	Toolset                string
	Guidance               string
	ModelHint              string
	CompactSkillCategories []string
}

ContextProfile is a named operating posture

type ConversationLease

type ConversationLease struct {
	ProfileKey      string
	SessionID       string
	Platform        string
	Host            RelayHost
	Session         *RelaySession
	ParentSessionID string
	TurnCwd         string
	// contains filtered or unexported fields
}

Resumable reference to one profile scoped conversation scope

func (*ConversationLease) LiveRuntime

func (l *ConversationLease) LiveRuntime() *RelayRuntime

Real Relay host when the lease owns an open session

func (*ConversationLease) Released

func (l *ConversationLease) Released() bool

Whether the caller released the lease

type CorpusStats

type CorpusStats struct {
	DocLengths []int
	AvgDL      float64
	DocFreq    map[string]int
	NDocs      int
}

CorpusStats holds the BM25 statistics shared by every query over a catalog

type CreateOptions

type CreateOptions struct {
	Cwd             string
	Timeout         int
	TaskID          string
	Image           string
	ContainerConfig map[string]any
	HostCwd         string
	ProbeOnly       bool
}

CreateOptions carries everything a backend needs to build an environment

type CreateProjectOptions

type CreateProjectOptions struct {
	Slug               string
	Folders            []string
	PrimaryPath        string
	Description        *string
	Icon               *string
	Color              *string
	BoardSlug          string
	AllowDuplicatePath bool
}

CreateProjectOptions are the optional fields of a new project

type CredentialPoolSource

type CredentialPoolSource interface {
	// Runtime bearer and base URL of the selected entry, expiring rows refreshed, ok false when none is usable
	SelectPooled(env *Env, provider string) (token, baseURL string, ok bool)
	// Force refreshes the entry that issued the rejected bearer, ok false when no entry matches or the refresh fails
	RefreshMatching(env *Env, provider, apiKeyHint string) (token, baseURL string, ok bool)
}

CredentialPoolSource selects credential pool entries, installed by the provider wiring

var CredentialPools CredentialPoolSource

CredentialPools is the credential pool source of the OAuth branch, assigned in cmd/icebath wiring

type CuteRow

type CuteRow struct {
	Text, Emoji, Verb, Detail string
}

Rendered completion row keeping its emoji, verb and detail for glyph layouts

type DaemonPool

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

DaemonPool is the shared executor for background work that must never block process exit

func NewDaemonPool

func NewDaemonPool(maxWorkers int, prefix string) *DaemonPool

NewDaemonPool builds a pool of at most maxWorkers workers named with prefix

func (*DaemonPool) Shutdown

func (p *DaemonPool) Shutdown(wait, cancelFutures bool)

Shutdown refuses new work, cancelling queued tasks when cancelFutures, and waits for running ones when wait

func (*DaemonPool) Submit

func (p *DaemonPool) Submit(ctx context.Context, fn func(ctx context.Context) (any, error)) (*PoolFuture, error)

Submit queues fn to run on a worker in the caller's context and returns its future

type DangerPattern

type DangerPattern struct {
	Pattern     string
	Description string
}

DangerPattern is one Python syntax regex and the description that doubles as its approval key

type DaytonaOptions

type DaytonaOptions struct {
	Image      string
	Cwd        string
	Timeout    int
	CPU        int
	Memory     int
	Disk       int
	Persistent bool
	TaskID     string
}

DaytonaOptions are the sandbox settings, memory and disk in MB

type DebugSession

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

DebugSession records tool calls to a JSON log when the tool's env var is true

func NewDebugSession

func NewDebugSession(env *Env, toolName, envVar string) *DebugSession

NewDebugSession enables recording when envVar is true

func (*DebugSession) LogCall

func (s *DebugSession) LogCall(callName string, callData map[string]any)

LogCall appends a tool call entry to the in memory log

func (*DebugSession) Save

func (s *DebugSession) Save(env *Env)

Save flushes the log to a JSON file in the logs directory

type Decision

type Decision struct {
	Name      string
	Path      string
	Action    string
	Reason    string
	AgeHours  float64
	Branch    *string
	Mtime     float64
	Force     bool
	Verdict   string
	LockState string
	SizeMB    *int
	TierHours float64
	PlannedAt float64
}

One planned sweep action for a tree with the facts it was decided on

func PlanSweep

func PlanSweep(ctx context.Context, repoRoot string, maxAgeHours int, s *SweepConfig, now float64, olderThanDays *float64) []*Decision

Read only decision for every tree under the worktrees dir, olderThanDays when positive only restricts removal

func (*Decision) AsDict

func (d *Decision) AsDict() *pyjson.Object

Field map of the decision in declaration order, absent branch, lock state and size as null

type Def

type Def struct {
	Name    string
	Toolset string
	// OpenAI function schema with name, description, and parameters in definition order
	Schema      *pyjson.Object
	Handler     Handler
	Check       func(env *Env) bool
	RequiresEnv []string
	Description string
	Emoji       string
	// Zero means the global tool output limit applies
	MaxResultChars int
	// Merged over Schema at every definition read so limits in descriptions stay current
	DynamicSchema func(env *Env) *pyjson.Object
	Timeout       time.Duration
	Override      bool
	Plugin        string
	// Builds Schema on the first registry read when Schema is nil, deferring config reads past init
	SchemaBuilder func() *pyjson.Object
	// contains filtered or unexported fields
}

Def is one registered tool with its schema, handler, and availability check

func (*Def) SchemaMap

func (d *Def) SchemaMap() map[string]any

Plain map view of the schema for readers that never write it

type DefinitionOptions

type DefinitionOptions struct {
	Enabled  []string
	Disabled []string
	// Quiet suppresses selection notices and enables memoization
	Quiet bool
	// SkipToolSearchAssembly returns raw schemas for every enabled tool, only the bridge uses it
	SkipToolSearchAssembly bool
	// ContextLength zero resolves the active model's window
	ContextLength int
}

DefinitionOptions selects and shapes one model facing tool definition list

type DelegateRouteAgent

type DelegateRouteAgent interface {
	Provider() string
	Model() string
	BaseURL() string
	APIKey() string
	RequestOverrides() map[string]any
	SetRequestOverrides(map[string]any)
}

Route facts of a delegating parent or built child the speed tier reads and pins

type DelegateTaskRequest

type DelegateTaskRequest struct {
	Goal, Context, Tasks, MaxIterations, Role         any
	Background                                        *bool
	OutputSchema, Images, Action, SubagentID, Message any
	ParentAgent                                       any
	CredentialsCfg                                    map[string]any
}

Arguments of tools/delegate_tool.py delegate_task, nil fields standing for Python None

type DelegationBackendAgent

type DelegationBackendAgent interface {
	Tools() []map[string]any
	DelegationBackend() (backend string, set bool)
	SetDelegationBackend(backend string)
}

Agent state recording which backend its delegate_task definition was built from

type DelegationBackendError

type DelegationBackendError struct{ Kind, Message string }

Refusal of a backend switch, Kind naming the Python exception class

func (*DelegationBackendError) Error

func (e *DelegationBackendError) Error() string

type DelegationBackends

type DelegationBackends struct{}

Plugin facing backend API as plain data

func (DelegationBackends) ListBackends

func (DelegationBackends) ListBackends(ctx context.Context) []map[string]any

Every backend as a field mapping

func (DelegationBackends) SetGlobalBackend

func (DelegationBackends) SetGlobalBackend(ctx context.Context, name, sessionKey string, applyNow bool) error

Saves the backend choice for the profile

type DelegationInlineAgent

type DelegationInlineAgent interface {
	DelegationInline() (inline, set bool)
	SetDelegationInline(inline bool)
}

Agent state holding the inline decision frozen at its first tool build

type DelegationProvider

type DelegationProvider interface {
	Name() string
	DisplayName() string
	GetSetupSchema() map[string]any
	Settings(config map[string]any) map[string]any
	Summary() string
	IsAvailable() bool
	TaskParameters(config map[string]any) *pyjson.Object
	Description(config map[string]any) string
	RouteTask(task, config map[string]any) (map[string]any, error)
}

Pluggable strategy turning one delegate_task task into a child route, selected by delegation.backend

func DelegationBackendStatus

func DelegationBackendStatus(ctx context.Context, name string) (DelegationProvider, string)

Provider and empty reason when the backend runs here, else the provider or nil with the user facing fix

func GetActiveDelegationProvider

func GetActiveDelegationProvider(ctx context.Context, config map[string]any) (DelegationProvider, error)

Provider the delegation section selects, a route error naming the backend and the fix otherwise

func LoadBundledDelegation

func LoadBundledDelegation(ctx context.Context, name string) DelegationProvider

Exported loadBundledDelegation

type DelegationProviderDefaults

type DelegationProviderDefaults struct{ Self DelegationProvider }

Domain method defaults a concrete provider embeds with Self bound to itself

func (DelegationProviderDefaults) Description

func (DelegationProviderDefaults) Description(map[string]any) string

No description addendum

func (DelegationProviderDefaults) IsAvailable

func (DelegationProviderDefaults) IsAvailable() bool

Always available

func (DelegationProviderDefaults) Settings

func (d DelegationProviderDefaults) Settings(config map[string]any) map[string]any

Backend block under delegation.backends keyed by the provider name, empty when unset or not a mapping

func (DelegationProviderDefaults) Summary

Empty picker line

func (DelegationProviderDefaults) TaskParameters

func (DelegationProviderDefaults) TaskParameters(map[string]any) *pyjson.Object

No extra task parameters

type DelegationRebuildAgent

type DelegationRebuildAgent interface {
	DelegationBackendAgent
	TurnOrigin() string
	DelegateDepth() int
	SessionID() string
	SessionEnv() *Env
}

Agent surface a turn start rebuild reads and refreshes

type DelegationRouteError

type DelegationRouteError struct{ Message string }

Refusal of one task whose message becomes the delegate_task tool error the model reads

func (*DelegationRouteError) Error

func (e *DelegationRouteError) Error() string

type DelegationValueError

type DelegationValueError struct{ Message string }

DelegationValueError is the ValueError a delegation credential or route resolver refuses a task with

func (*DelegationValueError) Error

func (e *DelegationValueError) Error() string

type DeliveryAuthor

type DeliveryAuthor struct {
	Author map[string]any
}

Relayed turn author as an in process value that only the relay builds and a JSON client never can

type DiscordAPIError

type DiscordAPIError struct {
	Status int
	Body   string
}

HTTP status and body of a Discord REST call that failed

func (*DiscordAPIError) Error

func (e *DiscordAPIError) Error() string

type DiscordOSError

type DiscordOSError struct{ Text string }

OSError of a Discord request that never got an answer, its text the Python str of the exception

func (*DiscordOSError) Error

func (e *DiscordOSError) Error() string

type DiscordValueError

type DiscordValueError struct{ Msg string }

ValueError of a Discord request, a header value http.client refuses or a body that is not JSON

func (*DiscordValueError) Error

func (e *DiscordValueError) Error() string

type DispatchOptions

type DispatchOptions struct {
	SkipPreToolCallHook         bool
	SkipToolRequestMiddleware   bool
	SkipToolExecutionMiddleware bool
	SuppressPostToolCallHook    bool
	Trace                       []map[string]any
	// EnabledTools picks execute_code's sandbox tools, nil means the last resolved definition names
	EnabledTools []string
	// Enabled and Disabled toolsets scope the bridge catalog, nil means the session environment's
	EnabledToolsets  []string
	DisabledToolsets []string
	// AllowedTools denies every other name with DeniedFormat, nil means no whitelist
	AllowedTools map[string]bool
	DeniedFormat string
}

DispatchOptions tune one call through the dispatcher

type Dispatcher

type Dispatcher struct {
	Registry *Registry

	PreToolCall             []PreToolCallHook
	PostToolCall            []PostToolCallHook
	TransformToolResult     []TransformToolResultHook
	ToolRequestMiddleware   []ToolRequestMiddleware
	ToolExecutionMiddleware []ToolExecutionMiddleware
	EditApproval            EditApprovalFunc
	Relay                   RelayFunc
	// SafeWorker disables every observer hook for a worker that must not run plugin code
	SafeWorker func() bool
	// contains filtered or unexported fields
}

Dispatcher routes tool calls through hooks and middleware to the registry

func DispatcherOf

func DispatcherOf(ctx context.Context) *Dispatcher

DispatcherOf returns the bound dispatcher, the process default when none is bound

func NewDispatcher

func NewDispatcher(r *Registry) *Dispatcher

NewDispatcher returns a dispatcher over the registry

func (*Dispatcher) ApplyToolRequestMiddleware

func (d *Dispatcher) ApplyToolRequestMiddleware(ctx context.Context, env *Env, name string, args, originalArgs map[string]any, ids ToolHookIDs) (map[string]any, map[string]any, []map[string]any)

ApplyToolRequestMiddleware feeds args through every request middleware, each may replace them

func (*Dispatcher) ApplyTransformToolResult

func (d *Dispatcher) ApplyTransformToolResult(ctx context.Context, env *Env, ev PostToolCallEvent) string

ApplyTransformToolResult lets plugins replace the final result string, first string wins

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(ctx context.Context, call *Call) string

Dispatch routes one tool call through hooks and middleware to the registry and returns its JSON result

func (*Dispatcher) DispatchWith

func (d *Dispatcher) DispatchWith(ctx context.Context, call *Call, opts DispatchOptions) string

DispatchWith is Dispatch with per call options for the executor and the bridge

func (*Dispatcher) EmitPostToolCall

func (d *Dispatcher) EmitPostToolCall(ctx context.Context, env *Env, ev PostToolCallEvent)

EmitPostToolCall fires the post tool call observers unless an outer executor owns the event

func (*Dispatcher) RegistryDispatch

func (d *Dispatcher) RegistryDispatch(ctx context.Context, call *Call) (result string)

RegistryDispatch runs a registered handler with every panic returned as a JSON error

func (*Dispatcher) RunToolExecutionMiddleware

func (d *Dispatcher) RunToolExecutionMiddleware(ctx context.Context, env *Env, name string, args, originalArgs map[string]any, ids ToolHookIDs, terminal func(map[string]any) (string, error)) (string, error)

RunToolExecutionMiddleware runs the terminal call through the execution chain with single use next frames

type Distribution

type Distribution struct {
	Description string
	Toolsets    map[string]int
	Order       []string
}

Distribution maps toolset entries to the percent chance each is enabled per prompt, Order keeping declaration order

type DockerOptions

type DockerOptions struct {
	Image                string
	Cwd                  string
	Timeout              int
	CPU                  float64
	Memory               int
	Disk                 int
	PersistentFilesystem bool
	TaskID               string
	Volumes              []string
	ForwardEnv           []string
	UserEnv              map[string]string
	Network              bool
	HostCwd              string
	AutoMountCwd         bool
	RunAsHostUser        bool
	ExtraArgs            []string
	PersistAcrossProcs   bool
	ShmSize              string
	SharedContainerKey   string
	SnapCompat           bool
	ImagePinned          bool
	SessionScoped        bool
}

DockerOptions are the resolved docker kwargs for one environment

type DoctorCheck

type DoctorCheck struct {
	OK     bool
	Label  string
	Detail string
}

DoctorCheck is one row of a backend health report

type DrainableChild

type DrainableChild interface {
	ChildProcess
	Communicate(timeout time.Duration) (stdout, stderr []byte, ok bool)
}

DrainableChild is a child handle that also hands back what its captured pipes still hold

type DrainedNotification

type DrainedNotification struct {
	Event map[string]any
	Text  string
}

DrainedNotification is one drained event with its formatted text

type EditApprovalFunc

type EditApprovalFunc func(ctx context.Context, env *Env, name string, args map[string]any) (string, error)

EditApprovalFunc blocks a file mutation until an editor client approves it

type EditApprovalRequester

type EditApprovalRequester func(ctx context.Context, env *Env, proposal *EditProposal) (bool, error)

Asks the editor whether a proposed edit may run

type EditProposal

type EditProposal struct {
	ToolName  string
	Path      string
	OldText   *string
	NewText   string
	Arguments map[string]any
	Paths     []string
}

One proposed file edit an ACP client can be shown, with every file it actually touches

func BuildEditProposal

func BuildEditProposal(env *Env, toolName string, arguments map[string]any) (*EditProposal, error)

Edit proposal of a supported file mutation call, nil for any other call

type EgressMapping

type EgressMapping struct {
	RealEnvName   string
	ProxyToken    string
	AliasEnvNames []string
}

EgressMapping is one provider credential the egress proxy swaps for a proxy token

type EgressProxySource

type EgressProxySource interface {
	Status(env *Env) EgressStatus
	Mappings(env *Env) []EgressMapping
}

EgressProxySource reports the egress proxy state and token mappings, installed by the egress package

var EgressProxy EgressProxySource

EgressProxy is the installed egress proxy source, nil meaning the proxy is unavailable

type EgressStatus

type EgressStatus struct {
	Configured bool
	Pid        int
	Listening  bool
	TunnelPort int
	CACertPath string
}

EgressStatus is the live state of the host side egress proxy

type ElicitationOptions

type ElicitationOptions struct {
	Timeout     time.Duration
	Surface     string
	Title       string
	RememberKey string
	URL         string
}

ElicitationOptions tunes one MCP elicitation consent request, URL naming the link an accept opens

type Env

type Env struct {
	Home     string
	Config   config.Tree
	Secrets  *config.Secrets
	State    *state.DB
	Cwd      string
	Platform string
	Enabled  []string
	Disabled []string
	Aux      Aux
	Ask      Asker
	Notify   func(Event)
	Log      *slog.Logger
	// Shared per-session values keyed by tool name
	Values *sync.Map
	// Profile terminal policy bound for this turn, nil resolves from Home
	TerminalScope *TerminalScope
	// contains filtered or unexported fields
}

Env is the per-session service surface every tool handler reads

func CopySessionContext

func CopySessionContext(src *Env) *Env

Context copy a spawned task inherits, sharing no session variable with the parent env afterwards

func EnvForProfileHome

func EnvForProfileHome(ctx context.Context, env *Env, h string) *Env

Copy of env re-homed at h with its config, secrets, the context terminal scope and shared session values

func EnvInTerminalScope

func EnvInTerminalScope(ctx context.Context, env *Env) *Env

Env of a call carrying the context terminal scope, the same env when none is bound

func ForkSessionContext

func ForkSessionContext(env *Env) *Env

Copy of the env whose session variables start as the bound ones and change apart from them afterwards

func ToolEnvFrom

func ToolEnvFrom(ctx context.Context) *Env

Session tool environment bound to the context, nil when none was bound

func WithKanbanToolsetSelection

func WithKanbanToolsetSelection(env *Env, toolsets []string) *Env

Env copy telling availability checks whether kanban was named explicitly in this schema build

func WithObservabilityContext

func WithObservabilityContext(env *Env, turnID, toolCallID, sessionID string) *Env

WithObservabilityContext copies env with its own tool correlation ids so concurrent calls never read each other's

func WithRuntimeMainSlot

func WithRuntimeMainSlot(env *Env) *Env

Copy of the env with its own slot for the live main runtime of the agent that owns it

func (*Env) AuxClient

func (e *Env) AuxClient() Aux

Auxiliary client of the env, its own when set else the process client that resolves the task from config per call

func (*Env) Emit

func (e *Env) Emit(ev Event)

Emit sends a progress event when the host registered a listener

type Environment

type Environment interface {
	Execute(ctx context.Context, command string, opts ExecOptions) (*ExecResult, error)
	Cleanup(forceRemove bool) error
	EnvType() string
	Cwd() string
	SetCwd(cwd string)
	TempDir() string
	HostCwd() string
	HostCwdMount() string
	SandboxHome() string
	IsPersistent() bool
	IsSessionScoped() bool
	UsesHostFilesystem() bool
	FetchFile(ctx context.Context, remotePath, localDest string, maxBytes int) error
	FetchRealpath(ctx context.Context, remotePath string) string
}

Environment is one terminal backend instance with a persistent shell snapshot and cwd

func CreateTaskEnvironment

func CreateTaskEnvironment(ctx context.Context, env *Env, cfg map[string]any, taskID string) (Environment, error)

Creates and caches the task environment execute_code shares with the terminal tool

func EnsureTaskEnv

func EnsureTaskEnv(ctx context.Context, env *Env, taskID string) (Environment, error)

EnsureTaskEnv lazily creates and caches the sandbox env of a task, nil on the local backend

func GetActiveEnv

func GetActiveEnv(env *Env, taskID string) (Environment, error)

GetActiveEnv returns the active environment of a task or nil

func TouchTaskActivity

func TouchTaskActivity(env *Env, taskID string) (Environment, error)

Active environment of the task's cache key with its activity stamped, nil when none

type EnvironmentConnectionError

type EnvironmentConnectionError struct {
	Reason    string
	RetryHint string
}

EnvironmentConnectionError is an infrastructure failure of a terminal backend, never a nonzero command exit

func NewEnvironmentConnectionError

func NewEnvironmentConnectionError(reason, retryHint string) *EnvironmentConnectionError

NewEnvironmentConnectionError builds the error with the default retry hint when none is given

func (*EnvironmentConnectionError) Error

Error returns the failure reason

type EstopState

type EstopState struct {
	Reason, EngagedAt string
}

Reason and engaged time of the active pause, nil when not engaged, both empty for an unreadable body

func GetState

func GetState(ctx context.Context) *EstopState

State of the pause, nil when not engaged, a corrupt body still reporting engaged with empty fields

type Event

type Event struct {
	Kind   string
	Tool   string
	TaskID string
	Text   string
	Data   map[string]any
}

Event is one progress notice a running tool emits to the host surface

type EventQueue

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

EventQueue is the unified background event queue the drain loops consume

func NewEventQueue

func NewEventQueue() *EventQueue

NewEventQueue is an empty completion queue for callers outside the package that restore events into one

func (*EventQueue) Empty

func (q *EventQueue) Empty() bool

Empty reports whether nothing is queued

func (*EventQueue) GetNowait

func (q *EventQueue) GetNowait() (map[string]any, bool)

GetNowait pops the oldest event, false when empty

func (*EventQueue) Len

func (q *EventQueue) Len() int

Len is the number of queued events

func (*EventQueue) Put

func (q *EventQueue) Put(evt map[string]any)

Put appends an event and wakes waiters

func (*EventQueue) Snapshot

func (q *EventQueue) Snapshot() []map[string]any

Snapshot copies the queued events in order

type ExecOptions

type ExecOptions struct {
	Cwd     string
	Timeout int
	Stdin   *string
	// Leaves A && B & alone for callers that already produce shell safe wrappers
	NoCompoundRewrite bool
	// Caps retention at tool_output.max_bytes while draining, foreground terminal tool only
	BoundedCapture bool
	// Hands a still running foreground process to the background registry when the host asks
	YieldHandler func(proc ProcessHandle, outputSoFar string) *ExecResult
}

ExecOptions tunes one command run inside an environment

type ExecProcess

type ExecProcess struct {
	Cmd *exec.Cmd
	// contains filtered or unexported fields
}

ExecProcess is the subprocess handle every backend spawning a host command returns

func StartExecProcess

func StartExecProcess(cmd *exec.Cmd, stdinData *string) (*ExecProcess, error)

StartExecProcess spawns a configured command with merged stdout and stderr on a pipe and optional stdin data

func (*ExecProcess) JoinStdin

func (p *ExecProcess) JoinStdin(timeout time.Duration) string

JoinStdin waits for the stdin writer and returns its recorded error

func (*ExecProcess) Kill

func (p *ExecProcess) Kill() error

Kill sends SIGKILL to the process itself

func (*ExecProcess) Pid

func (p *ExecProcess) Pid() int

Pid returns the child process id

func (*ExecProcess) Poll

func (p *ExecProcess) Poll() (int, bool)

Poll reports the exit code once the command finished

func (*ExecProcess) Stdout

func (p *ExecProcess) Stdout() *os.File

Stdout returns the read end of the merged output pipe

func (*ExecProcess) Wait

func (p *ExecProcess) Wait(timeoutSeconds float64) (int, error)

Wait blocks until the command finishes or the timeout passes

type ExecResult

type ExecResult struct {
	Output               string
	ReturnCode           int
	CwdObserved          bool
	Cwd                  string
	PipelineStatus       []int
	OutputTotalChars     int
	FullOutputPath       string
	TimedOut             bool
	Interrupted          bool
	EnvironmentRecreated bool
	StdinError           string
	YieldedSessionID     string
	Pid                  int
}

ExecResult is the outcome of one command run inside an environment

type ExecuteResult

type ExecuteResult struct {
	Stdout   string
	ExitCode int
	CwdError string
}

ExecuteResult is one fenced shell command outcome, CwdError set when the cd wrapper failed

type Executor

type Executor struct {
	Host       ExecutorHost
	Dispatcher *Dispatcher
	// contains filtered or unexported fields
}

func NewExecutor

func NewExecutor(host ExecutorHost, d *Dispatcher) *Executor

NewExecutor binds an executor to its host and dispatcher

func (*Executor) BeginToolExecution

func (e *Executor) BeginToolExecution(ref *ToolCallRef, displayIndex int)

Runs the progress line, activity stamp, start callbacks and checkpoint preflight of one call

func (*Executor) ExecuteToolCallsConcurrent

func (e *Executor) ExecuteToolCallsConcurrent(ctx context.Context, toolCalls []state.ToolCall, messages *[]*state.Message, taskID string, finalize bool) error

ExecuteToolCallsConcurrent runs calls concurrently and appends results in original order

func (*Executor) ExecuteToolCallsSegmented

func (e *Executor) ExecuteToolCallsSegmented(ctx context.Context, toolCalls []state.ToolCall, messages *[]*state.Message, taskID string, segments []BatchSegment) error

ExecuteToolCallsSegmented runs a mixed batch as ordered parallel and sequential segments

func (*Executor) ExecuteToolCallsSequential

func (e *Executor) ExecuteToolCallsSequential(ctx context.Context, toolCalls []state.ToolCall, messages *[]*state.Message, taskID string, finalize bool) error

ExecuteToolCallsSequential runs calls one at a time in runs of adjacent terminal and other calls

func (*Executor) InterruptWorkers

func (e *Executor) InterruptWorkers(reason string)

InterruptWorkers raises the interrupt bit on every tracked worker

func (*Executor) InvokeTool

func (e *Executor) InvokeTool(ctx context.Context, name string, args map[string]any, taskID, toolCallID string, opts InvokeToolOptions) (string, error)

Runs one inline or registry tool through every pipeline step the options do not skip

func (*Executor) ParseToolCall

func (e *Executor) ParseToolCall(ctx context.Context, tc state.ToolCall, flattenProbe bool) *ParsedCall

ParseToolCall canonicalizes the name, parses the arguments, and unwraps a bridge call

func (*Executor) TrackedWorkerIDs

func (e *Executor) TrackedWorkerIDs() []WorkerID

type ExecutorHost

type ExecutorHost interface {
	Env() *Env
	SessionID() string
	SessionDBForRecall(ctx context.Context) *state.DB
	TurnID() string
	APIRequestID() string
	ValidToolNames() map[string]bool
	EnabledToolsets() []string
	DisabledToolsets() []string
	ContextLength() int
	QuietMode() bool
	VerboseLogging() bool
	ToolProgressMode() string
	LogPrefix() string
	LogPrefixChars() int
	Print(text string)
	VPrint(text string, force bool)
	WrapVerbose(prefix, text string) string
	ShouldEmitQuietToolMessages() bool
	ShouldStartQuietSpinner() bool
	StartSpinner(label string) Spinner
	CuteToolMessage(name string, args map[string]any, duration float64, result any) string
	Interrupted() bool
	ToolInterruptReason() string
	Interrupt(message, toolReason string)
	TouchActivity(label string)
	SetCurrentTool(name string)
	Guardrails() *ToolCallGuardrailController
	GuardrailBlockResult(d ToolGuardrailDecision) string
	AppendGuardrailObservation(name string, args map[string]any, result string, failed bool, toolCallID string) string
	RecordFileMutationResult(name string, args map[string]any, result string, isError bool, taskID string)
	ToolResultCommitted()
	SubdirectoryHints(name string, args map[string]any) string
	ToolResultContentForActiveModel(name string, result string) any
	ToolProgressCallback() func(event, name, preview string, args map[string]any, extra map[string]any)
	ToolStartCallback() func(toolCallID, name string, args map[string]any)
	ToolCompleteCallback() func(toolCallID, name string, args map[string]any, result string)
	ToolResultMetadataCallback() func(toolCallID, name string, args map[string]any, result string) map[string]any
	CheckpointManager() *CheckpointManager
	FlushMessagesToSessionDB(messages []*state.Message) state.FlushOutcome
	BeforeToolFlush(messages *[]*state.Message)
	IncrementalPersistenceFailed() bool
	MarkIncrementalPersistenceFailed(cause string)
	NoteToolDispatched(name string)
	DispatchDelegateTask(ctx context.Context, args map[string]any) (string, error)
	ContextEngineTool(name string) (func(ctx context.Context, args map[string]any, messages *[]*state.Message) (string, error), bool)
	MemoryManager() MemoryToolManager
	GatewaySessionKey() string
	SetDelegateSpinner(spinner Spinner)
	ForwardDeferredLSPNotes()
	ActiveSandbox(taskID string) Environment
	AttachLiveNotes(msg *state.Message)
	KeepLiveNotesAfterTurnBudget(batch []*state.Message)
	SyncRewrittenToolRows(batch []*state.Message, contentsBefore []any)
	ApplyPendingSteer(messages *[]*state.Message, numTools int)
	MarkTrimAfterToolBatch()
	RedactToolArgsForDisplay(name string, args map[string]any) map[string]any
	BuildToolPreview(name string, args map[string]any) string
	ToolRowEmoji(ctx context.Context, name string, args map[string]any) string
	BuildToolLabel(name string, args map[string]any) string
}

ExecutorHost is the live agent state the executors read and mutate

type ExternalTreeRecord

type ExternalTreeRecord struct {
	Path    string `json:"path"`
	Branch  string `json:"branch"`
	Locked  bool   `json:"locked"`
	Missing bool   `json:"missing"`
}

A linked worktree registered outside .worktrees, reported for visibility and never touched

func AuditExternalTrees

func AuditExternalTrees(repoRoot string) ([]ExternalTreeRecord, error)

Linked worktrees registered outside .worktrees, read only, missing directories flagged

type ExtractionError

type ExtractionError struct{ Msg string }

Document whose bytes could not be rendered as text

func (*ExtractionError) Error

func (e *ExtractionError) Error() string

type FileFetchError

type FileFetchError struct {
	Msg string
}

FileFetchError reports a file that could not be extracted from the backend filesystem

func (*FileFetchError) Error

func (e *FileFetchError) Error() string

Error returns the fetch failure text

type FileLockHolder

type FileLockHolder = fileLockHolder

Reentrant cross process file lock holder

type FileLockTimeoutError

type FileLockTimeoutError struct{ Message string }

Lock file another holder kept past the timeout

func (*FileLockTimeoutError) Error

func (e *FileLockTimeoutError) Error() string

type FileSyncManager

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

FileSyncManager tracks host file changes and syncs them to a remote through backend transport callbacks

func EnvironmentSyncManager

func EnvironmentSyncManager(e Environment) *FileSyncManager

File sync manager of a remote backend environment, nil for backends that keep none

func NewFileSyncManager

func NewFileSyncManager(env *Env, getFiles func() []syncFile, upload func(string, string) error, delete func([]string) error,
	bulkUpload func([]syncFile) error, bulkDownload func(string) error) *FileSyncManager

NewFileSyncManager wires the transport callbacks, bulk callbacks being optional

func (*FileSyncManager) Sync

func (m *FileSyncManager) Sync(force bool)

Sync uploads changed files and deletes removed ones, rate limited unless forced, rolling back state on any failure

func (*FileSyncManager) SyncBack

func (m *FileSyncManager) SyncBack(icebathHome string)

SyncBack pulls remote changes to the host on teardown, SIGINT deferred and concurrent gateways serialized by a file lock

type FormResult

type FormResult struct {
	Outcome string
	Notice  string
	Answers []Answer
}

FormResult reports the form outcome and the answers in question order

type GateDecision

type GateDecision struct {
	Allow   bool
	Blocked bool
	Stage   bool
	Message string
}

Whether to write now, refuse after an inline denial, or stage for review

func CheckWriteApproval

func CheckWriteApproval(ctx context.Context, env *Env, subsystem, inlineSummary, inlineDetail string) GateDecision

Allows with the gate off, stages skills and background writes, and asks inline for foreground memory

type GatewayChildDispatch

type GatewayChildDispatch struct {
	Mode string
	Argv []string
}

GatewayChildDispatch says how a managed gateway child is launched

func RestartSafeGatewayChildArgv

func RestartSafeGatewayChildArgv(command []string, unitSuffix string, requireRestartSafeScope, outlivesParent bool) (GatewayChildDispatch, error)

RestartSafeGatewayChildArgv places a managed systemd gateway child outside the gateway cgroup

type GatewayLifecycleBlocked

type GatewayLifecycleBlocked struct{ Message string }

GatewayLifecycleBlocked is the refusal raised for a cron job holding a gateway lifecycle command

func (*GatewayLifecycleBlocked) Error

func (e *GatewayLifecycleBlocked) Error() string

type GatewayNotifyFunc

type GatewayNotifyFunc func(data map[string]any) error

GatewayNotifyFunc sends one approval request to the user through the gateway surface

func GatewayNotifyForTests

func GatewayNotifyForTests(sessionKey string) GatewayNotifyFunc

Notifier registered for a session, nil when none is

type GuardResult

type GuardResult struct {
	Approved        bool
	Message         string
	PatternKey      string
	Description     string
	Outcome         string
	UserSummary     string
	Status          string
	Command         string
	ApprovalPending bool
	SmartApproved   bool
	SmartDenied     bool
	UserApproved    bool
	AllowPermanent  bool
	DenyReason      string
}

The full approval verdict of one gate in the dict shape gates return

func CheckAllCommandGuards

func CheckAllCommandGuards(ctx context.Context, env *Env, command, envType string, hasHostAccess bool) GuardResult

CheckAllCommandGuards runs every pre exec security check and returns one approval decision

func CheckExecuteCodeGuard

func CheckExecuteCodeGuard(ctx context.Context, env *Env, code, envType string, hasHostAccess bool) GuardResult

CheckExecuteCodeGuard approves an execute_code script before its child process is spawned

func RequestToolApproval

func RequestToolApproval(ctx context.Context, env *Env, toolName, reason, ruleKey string) GuardResult

RequestToolApproval escalates an arbitrary tool call to the same human gate as dangerous commands

func RunApprovalGate

func RunApprovalGate(ctx context.Context, env *Env, o ApprovalGateOptions) GuardResult

RunApprovalGate decides a flagged action through yolo, grants, unattended policy and the human prompt

type Handler

type Handler func(ctx context.Context, call *Call) string

Handler runs one tool call and returns the JSON string result shown to the model

type HiddenDeclaredSource

type HiddenDeclaredSource struct {
	Name        string
	ToolCount   int
	Unavailable string
}

HiddenDeclaredSource summarizes one declared MCP server hidden by its availability check

func HiddenDeclaredSources

func HiddenDeclaredSources(ctx context.Context, env *Env) []HiddenDeclaredSource

HiddenDeclaredSources returns deterministic summaries for declared MCP servers hidden by their check

type IdenticalCallObservation

type IdenticalCallObservation struct {
	Notice string
	Stub   string
}

IdenticalCallObservation carries the notice appended after a result and the stub replacing a duplicate

type IdleStopper

type IdleStopper interface {
	StopIdle() error
}

IdleStopper is a persistent workspace container that stops instead of being removed when idle

type IllegalTransition

type IllegalTransition struct{ Msg string }

IllegalTransition is a target move the contract refuses

func (*IllegalTransition) Error

func (e *IllegalTransition) Error() string

type ImageResolutionError

type ImageResolutionError struct {
	Kind    string
	Message string
	Src     string
	Origin  string
}

ImageResolutionError is one refused media source with its failure class, source, and origin

func (*ImageResolutionError) Error

func (e *ImageResolutionError) Error() string

Error returns the user facing refusal text

type InlineToolContext

type InlineToolContext struct {
	TaskID     string
	ToolCallID string
	Messages   *[]*state.Message
}

InlineToolContext is the per call state an inline executor may need beyond its arguments

type InlineToolExecutor

type InlineToolExecutor func(ctx context.Context, host ExecutorHost, args map[string]any, ictx InlineToolContext) (string, error)

InlineToolExecutor runs an agent level tool that needs live agent state

func InlineToolExecutorOf

func InlineToolExecutorOf(name string) InlineToolExecutor

Agent level executor installed for a tool name, nil when none is

type InvokeToolOptions

type InvokeToolOptions struct {
	Messages                    *[]*state.Message
	PreToolBlockChecked         bool
	SkipToolRequestMiddleware   bool
	ToolRequestMiddlewareTrace  []map[string]any
	SkipToolExecutionMiddleware bool
}

Messages an inline tool reads and each pipeline step the caller already ran for one invoke

type KeylessMCPError

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

KeylessMCPError reports a failed keyless MCP call

func (*KeylessMCPError) Error

func (e *KeylessMCPError) Error() string

type LSPDeferredNote

type LSPDeferredNote struct {
	Path string
	Text string
}

LSPDeferredNote is one undelivered late verdict of a file

func LSPPopNotes

func LSPPopNotes(owners ...string) []LSPDeferredNote

LSPPopNotes returns and clears every queued note of the owners, oldest first

func LSPSettleForAgent

func LSPSettleForAgent(sessionID, taskID string, timeout time.Duration) []LSPDeferredNote

LSPSettleForAgent waits up to timeout for the agent's running checks, then pops every undelivered verdict

type LedgerEntry

type LedgerEntry struct {
	Pid           int      `json:"pid"`
	CreateTime    *float64 `json:"create_time"`
	Purpose       string   `json:"purpose"`
	Install       string   `json:"install"`
	SpawnerPid    *int     `json:"spawner_pid"`
	SpawnerCreate *float64 `json:"spawner_create"`
	RegisteredAt  float64  `json:"registered_at"`
	Argv          string   `json:"argv"`
	IcebathHome   string   `json:"icebath_home"`
	BootStart     *float64 `json:"boot_start"`
	SpawnerBoot   *float64 `json:"spawner_boot"`
	BootID        *string  `json:"boot_id"`
}

LedgerEntry is one spawn ledger row

type LedgerOptions

type LedgerOptions struct {
	ProjectRoot  string
	AllInstalls  bool
	VerifiedOnly bool
}

LedgerOptions narrows a ledger read

type LintResult

type LintResult struct {
	Success bool
	Skipped bool
	Output  string
	Message string
}

LintResult is one syntax check outcome, construct with newLintResult for the success default

type LocalEditSnapshot

type LocalEditSnapshot struct {
	Paths  []string
	Before map[string]*string
}

Pre tool filesystem snapshot used to render diffs locally after writes, nil content for an unreadable file

func CaptureLocalEditSnapshot

func CaptureLocalEditSnapshot(env *Env, toolName string, args map[string]any, taskID *string) *LocalEditSnapshot

Before state of the files a local write preview will diff, nil when the call targets none

type LoopCapConfig

type LoopCapConfig struct {
	MaxWebSearches int
	MaxSubagents   int
}

LoopCapConfig holds per turn ceilings on web searches and subagent spawns, zero disables a cap

func LoopCapConfigFromMap

func LoopCapConfigFromMap(data map[string]any) LoopCapConfig

LoopCapConfigFromMap builds the caps from the tool_loop_guardrails.loop_caps section

type MCPOperationOptions

type MCPOperationOptions struct {
	Callback   ConnCallback
	SessionID  string
	ToolCallID string
	Backend    any
}

MCPOperationOptions carries the card callback, session and backend of one MCP manage_connections call

type MagicSignature

type MagicSignature struct {
	Prefix []byte
	Name   string
}

MagicSignature is one binary file prefix and its human name

func FileMagicSignatures

func FileMagicSignatures() []MagicSignature

FileMagicSignatures is the shared binary signature table of the file and web tools

type ManageOptions

type ManageOptions struct {
	MCPBackend any
	SessionID  string
	ToolCallID string
	Callback   ConnCallback
}

ManageOptions are manage_connections' keyword arguments, empty strings standing for None

type ManagedToolResult

type ManagedToolResult struct {
	Result     string
	Args       map[string]any
	Trace      []map[string]any
	Blocked    bool
	Dispatched bool
	// TimedOut and Cancelled mark synthesized results whose terminal hook already fired
	TimedOut  bool
	Cancelled bool
}

ManagedToolResult is the outcome of one managed dispatch

type MemoryToolManager

type MemoryToolManager interface {
	HasTool(name string) bool
	HandleToolCall(ctx context.Context, name string, args map[string]any, callerGSK string) string
}

Memory provider tools of the agent's memory manager, nil interface when the agent has none

type ModalOptions

type ModalOptions struct {
	Image         string
	Cwd           string
	Timeout       int
	SandboxKwargs map[string]any
	Persistent    bool
	TaskID        string
}

ModalOptions are the direct Modal sandbox settings

type Mount

type Mount struct {
	HostPath      string
	ContainerPath string
}

Mount pairs a host path with the path the sandbox sees

func GetCacheDirectoryMounts

func GetCacheDirectoryMounts(env *Env, containerBase string) []Mount

GetCacheDirectoryMounts lists bind mount entries for each cache directory

func GetCredentialFileMounts

func GetCredentialFileMounts(env *Env) []Mount

GetCredentialFileMounts lists skill registered and config credential files that still exist

func GetSkillsDirectoryMount

func GetSkillsDirectoryMount(env *Env, containerBase string) []Mount

GetSkillsDirectoryMount lists directory mounts for every skills dir, sanitized when symlinked

func IterCacheFiles

func IterCacheFiles(env *Env, containerBase string) []Mount

IterCacheFiles lists per file cache entries, bounding generated media by age

func IterSkillsFiles

func IterSkillsFiles(env *Env, containerBase string) []Mount

IterSkillsFiles lists per file entries for every skills file

type NemoRelay

type NemoRelay struct {
	Scope               *NemoRelayScope
	ScopeType           NemoRelayScopeTypes
	GetScopeStack       func(ctx context.Context) (any, error)
	Plugin              *NemoRelayPlugin
	Subscribers         *NemoRelaySubscribers
	Tools               *NemoRelayTools
	LLM                 *NemoRelayLLM
	LLMRequest          func(headers, content map[string]any) (any, error)
	Codecs              *NemoRelayCodecs
	ToolExecutionResult func(result any) (*RelayToolExecutionResult, error)
}

Native Relay binding surface the runtime drives, a nil function is an attribute the binding lacks

func LoadNemoRelay

func LoadNemoRelay() (*NemoRelay, error)

Imports the registered native Relay binding, an error when none is registered

type NemoRelayCodec

type NemoRelayCodec struct {
	Decode func(ctx context.Context, request any) (any, error)
	Encode func(ctx context.Context, decoded, request any) (any, error)
}

Typed request codec instance with decode and encode

type NemoRelayCodecs

type NemoRelayCodecs struct {
	OpenAIChatCodec        func() (*NemoRelayCodec, error)
	OpenAIResponsesCodec   func() (*NemoRelayCodec, error)
	AnthropicMessagesCodec func() (*NemoRelayCodec, error)
}

nemo_relay.codecs classes, a nil constructor is a missing codec class

type NemoRelayLLM

type NemoRelayLLM struct {
	Execute       func(ctx context.Context, operation string, request any, callback RelayProviderCallback, kwargs map[string]any) (any, error)
	StreamExecute func(ctx context.Context, operation string, request any, provider RelayProviderStreamCallback, observe func(ctx context.Context, chunk any) error, finalizer func(ctx context.Context) (any, error), kwargs map[string]any) (any, error)
	Call          func(ctx context.Context, name string, request any, kwargs map[string]any) (any, error)
	CallEnd       func(ctx context.Context, handle, response any, kwargs map[string]any) error
}

Binding surface of nemo_relay.llm, each nil field a missing attribute

type NemoRelayPlugin

type NemoRelayPlugin struct {
	Initialize    func(ctx context.Context, config map[string]any, additionalPluginsTOML string) (any, error)
	Validate      func(ctx context.Context, config map[string]any, additionalPluginsTOML string) (map[string]any, error)
	ValidateExact func(ctx context.Context, config map[string]any) (map[string]any, error)
}

Plugin host operations of the binding

type NemoRelayScope

type NemoRelayScope struct {
	Push          func(ctx context.Context, name string, scopeType any, kwargs map[string]any) (any, error)
	Pop           func(ctx context.Context, handle any, kwargs map[string]any) (any, error)
	PopParameters func() ([]RelayParameter, error)
	GetHandle     func(ctx context.Context) (any, error)
	Event         func(ctx context.Context, name string, kwargs map[string]any) (any, error)
}

Scope stack operations of the binding

type NemoRelayScopeTypes

type NemoRelayScopeTypes struct {
	Agent    any
	Function any
}

Scope type members the runtime pushes

type NemoRelaySubscribers

type NemoRelaySubscribers struct {
	Register   func(name string, callback func(event *RelayEventView)) error
	Deregister func(name string) error
	Flush      func() error
	FlushAsync func(ctx context.Context) (any, error)
}

Subscriber operations of the binding, register, deregister, flush and flush_async

type NemoRelayTools

type NemoRelayTools struct {
	RequestIntercepts func(ctx context.Context, toolName string, args map[string]any) (any, error)
	Execute           func(ctx context.Context, toolName string, args any, callback RelayProviderCallback, kwargs map[string]any) (any, error)
	Call              func(ctx context.Context, name string, args map[string]any, kwargs map[string]any) (any, error)
	CallEnd           func(ctx context.Context, handle, result any, kwargs map[string]any) error
}

Tool pipeline operations of the binding, request intercepts, managed execution and the manual call and call_end pair

type NoopRelayRuntime

type NoopRelayRuntime struct {
	ProfileKey string
	Reason     string
	Retry      bool
}

Explicit reduced capability host while no Relay plugin is configured or the binding cannot load, Retry rebuilding it on the next first use

func (NoopRelayRuntime) ApplyToolRequestIntercepts

func (NoopRelayRuntime) ApplyToolRequestIntercepts(_ context.Context, _, _ string, args map[string]any) (map[string]any, error)

func (NoopRelayRuntime) ManagedExecutionEnabled

func (NoopRelayRuntime) ManagedExecutionEnabled() bool

func (NoopRelayRuntime) ReleaseManagedExecution

func (NoopRelayRuntime) ReleaseManagedExecution(string)

func (NoopRelayRuntime) RetainManagedExecution

func (NoopRelayRuntime) RetainManagedExecution(string) error

func (NoopRelayRuntime) Shutdown

func (NoopRelayRuntime) Shutdown()

type OneshotSession

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

OneshotSession is the one shot fact an agent freezes at its first tool build

func (*OneshotSession) Pinned

func (o *OneshotSession) Pinned() (value, pinned bool)

Frozen fact and whether it was pinned, the getattr of the cached flag

type OperationAlreadyOpen

type OperationAlreadyOpen struct {
	Existing *ConnectionOperation
	// contains filtered or unexported fields
}

OperationAlreadyOpen is the refusal to open a second live operation in one profile session

func (*OperationAlreadyOpen) Error

func (e *OperationAlreadyOpen) Error() string

type OutputLimits

type OutputLimits struct {
	MaxBytes      int
	MaxLines      int
	MaxLineLength int
}

OutputLimits holds the resolved tool_output caps from config.yaml

func ToolOutputLimits

func ToolOutputLimits(env *Env) OutputLimits

Resolved output caps cached per profile home so every profile keeps its own limits

type OwnerDeathSupervisor

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

OwnerDeathSupervisor is a supervisor shell spawned outside the shared slot, closed and reaped by its caller

func SpawnOwnerDeathSupervisor

func SpawnOwnerDeathSupervisor() (*OwnerDeathSupervisor, error)

SpawnOwnerDeathSupervisor starts a watched supervisor without publishing it as this process's shared one

func (*OwnerDeathSupervisor) CloseAndWait

func (s *OwnerDeathSupervisor) CloseAndWait() int

Closes the control pipe and waits for the shell to exit, returning its exit status

func (*OwnerDeathSupervisor) PID

func (s *OwnerDeathSupervisor) PID() int

Pid of the supervisor shell

type ParentCopy

type ParentCopy struct {
	Text   string
	Forced string
}

Parent facing text carrying the forced projection persistent sinks read, serialized as its text

func (*ParentCopy) MarshalJSON

func (p *ParentCopy) MarshalJSON() ([]byte, error)

JSON string of the parent text, the way json.dumps writes a str subclass

func (*ParentCopy) PyStr

func (p *ParentCopy) PyStr() string

type ParsedCall

type ParsedCall struct {
	ToolCall   state.ToolCall
	Name       string
	Args       map[string]any
	Trace      []map[string]any
	ParseError string
	ScopeBlock string
}

ParsedCall is one model tool call after alias canonicalization, arg parsing, and bridge unwrap

func (*ParsedCall) Ref

func (p *ParsedCall) Ref(taskID string) *ToolCallRef

Ref builds the call reference every hook and result message sees

type PartialStrip

type PartialStrip struct {
	Stripped []string
	Entries  []string
	Hint     string
}

PartialStrip reports the tools a disabled list cuts out of an enabled toolset without removing it

type PatchResult

type PatchResult struct {
	Success        bool           `json:"success"`
	NoChange       bool           `json:"no_change,omitempty"`
	Note           string         `json:"note,omitempty"`
	Diff           string         `json:"diff,omitempty"`
	FilesModified  []string       `json:"files_modified,omitempty"`
	FilesCreated   []string       `json:"files_created,omitempty"`
	FilesDeleted   []string       `json:"files_deleted,omitempty"`
	Lint           *pyjson.Object `json:"lint,omitempty"`
	LSPDiagnostics string         `json:"lsp_diagnostics,omitempty"`
	Error          string         `json:"error,omitempty"`
	// One entry per file write with the sha of the bytes read and the bytes written
	Writes []patchWrite `json:"-"`
}

PatchResult is one replace or V4A patch outcome in its pinned emission order

type PendingCompletionWait

type PendingCompletionWait struct {
	Waited    []string
	Completed []string
	TimedOut  []string
}

PendingCompletionWait reports which notify_on_complete processes a one shot exit waited for

type PickerProvider

type PickerProvider interface {
	Name() string
	DisplayName() string
	GetSetupSchema() map[string]any
}

PickerProvider is one plugin registered provider as the tools picker lists it

type PickerRegistry

type PickerRegistry struct {
	List         func(ctx context.Context, env *Env) []PickerProvider
	Get          func(ctx context.Context, env *Env, name string) PickerProvider
	BuiltinNames map[string]bool
}

PickerRegistry is one plugin provider registry the tools picker reads, nil Get results meaning unregistered

type PipedChild

type PipedChild struct {
	*CmdChild
	// contains filtered or unexported fields
}

PipedChild is a started command whose stdout and stderr pipes are read to EOF in the background

func StartPiped

func StartPiped(cmd *exec.Cmd) (*PipedChild, error)

StartPiped starts cmd with stdout and stderr on pipes that a surviving descendant can keep open

func (*PipedChild) Communicate

func (p *PipedChild) Communicate(timeout time.Duration) (stdout, stderr []byte, ok bool)

Communicate waits within timeout for both pipes to reach EOF and the child to exit

type PlatformAppDef

type PlatformAppDef struct {
	AppID            string
	OSFamily         string
	Presence         string
	Locations        []PlatformAppLocation
	VersionKind      string
	VersionArg       string
	LivenessKind     string
	LivenessPath     string
	LivenessPIDKey   string
	LivenessURLKey   string
	LivenessTokenKey string
	EndpointPath     string
}

PlatformAppDef is one application on one OS, paths expanded at lookup

type PlatformAppLocation

type PlatformAppLocation struct {
	Kind  string
	Value string
	File  string
}

PlatformAppLocation is one place to look, a path or a location kind value with an install relative file

type PlatformAppResolver

type PlatformAppResolver struct{ Definition PlatformAppDef }

PlatformAppResolver resolves a desktop application declared by a PlatformAppDef

func (PlatformAppResolver) Endpoint

Reads and validates the current runtime endpoint, false when the app is not live

func (PlatformAppResolver) Inspect

func (r PlatformAppResolver) Inspect(res commandResolution, ctx *commandLookupContext) resolverInspection

Reads the version source of the first present copy, not checked when missing

func (PlatformAppResolver) Locate

func (r PlatformAppResolver) Locate(ctx *commandLookupContext) commandResolution

Stats every declared location in order, the first present hit setting the resolution kind

func (PlatformAppResolver) Probe

func (r PlatformAppResolver) Probe(res commandResolution, effort ResolverEffort, deadline float64) (resolverProbe, error)

Rereads the runtime file, connecting only for network effort with a live pid and loopback endpoint

type PlatformAppSpec

type PlatformAppSpec struct {
	PerOS map[string]PlatformAppDef
	Order []string
}

PlatformAppSpec holds one app definition per OS family in declaration order

func ParsePlatformApp

func ParsePlatformApp(raw any, name, where string) (*PlatformAppSpec, error)

Parses an already decoded app block into one definition per OS, nil when absent

func (*PlatformAppSpec) ForOS

func (s *PlatformAppSpec) ForOS(osFamily string) (PlatformAppDef, bool)

App definition declared for an OS family

type PlatformAvailability

type PlatformAvailability struct {
	State      string
	Version    *string
	Path       *string
	MinVersion *string
}

PlatformAvailability is whether a declaration can be offered on this host

func PlatformAvailabilityOf

func PlatformAvailabilityOf(entry platformRequirements, osFamily string) PlatformAvailability

Offer time verdict from locate, inspect and the cached GPU fact, osFamily empty meaning this host

func (PlatformAvailability) Offerable

func (a PlatformAvailability) Offerable() bool

True for available and no_requirements

type PlatformDeclaration

type PlatformDeclaration struct {
	Name     string
	App      *PlatformAppSpec
	Requires PlatformRequiresSpec
}

PlatformDeclaration is a parsed app and requires declaration of one server or skill

func LookupPlatformDeclaration

func LookupPlatformDeclaration(serverName string) *PlatformDeclaration

Declaration registered for a server name, nil when none

func ParsePlatformDeclaration

func ParsePlatformDeclaration(name string, rawApp, rawRequires any, where string) (*PlatformDeclaration, error)

Parses both blocks of one declaration, where labelling every error message

func (*PlatformDeclaration) AppFor

func (d *PlatformDeclaration) AppFor(osFamily string) (PlatformAppDef, bool)

App definition for an OS family, false without an app block or a block for that OS

func (*PlatformDeclaration) MinVersion

func (d *PlatformDeclaration) MinVersion() *string

func (*PlatformDeclaration) RequiredGPU

func (d *PlatformDeclaration) RequiredGPU() *string

func (*PlatformDeclaration) RequiresApp

func (d *PlatformDeclaration) RequiresApp() bool

type PlatformDeclarationError

type PlatformDeclarationError struct{ Msg string }

PlatformDeclarationError is a declaration parse or validation failure

func (*PlatformDeclarationError) Error

func (e *PlatformDeclarationError) Error() string

type PlatformEndpoint

type PlatformEndpoint struct {
	URL   string
	Token string
}

PlatformEndpoint is a validated runtime endpoint whose token never prints

func (PlatformEndpoint) GoString

func (e PlatformEndpoint) GoString() string

func (PlatformEndpoint) String

func (e PlatformEndpoint) String() string

type PlatformInfo

type PlatformInfo struct {
	Label          string
	DefaultToolset string
}

PlatformInfo is one messaging or local platform with its default bundle

func PlatformInfoFor

func PlatformInfoFor(key string) (PlatformInfo, bool)

PlatformInfoFor returns a known platform's info

type PlatformRequiresSpec

type PlatformRequiresSpec struct {
	App        bool
	MinVersion *string
	GPU        *string
}

PlatformRequiresSpec is what a server needs before it is offered

func ParsePlatformRequires

func ParsePlatformRequires(raw any, app *PlatformAppSpec, where string) (PlatformRequiresSpec, error)

Parses the requires block, cross checking version policy against the parsed app

type PlatformToolsOptions

type PlatformToolsOptions struct {
	PluginToolsetKeys        map[string]bool
	PortableMCPServers       map[string]bool
	IncludeDefaultMCPServers bool
}

PlatformToolsOptions carries the plugin and MCP facts the platform resolver needs

type PlatformToolsetEntry

type PlatformToolsetEntry struct {
	Platform string
	Enabled  map[string]bool
}

PlatformToolsetEntry is one platform row of the enabled toolset summary in platform order

type PluginOverridePolicy

type PluginOverridePolicy struct {
	Allowed bool
}

PluginOverridePolicy is one identity bearing operator opt in for a plugin generation

type PoolFuture

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

PoolFuture is the pending result of a submitted task

func (*PoolFuture) Cancel

func (f *PoolFuture) Cancel() bool

Cancel refuses a task that has not started, false once it is running or finished

func (*PoolFuture) Cancelled

func (f *PoolFuture) Cancelled() bool

Cancelled reports whether Cancel won

func (*PoolFuture) Done

func (f *PoolFuture) Done() <-chan struct{}

Done is closed once the task finished or was cancelled

func (*PoolFuture) Result

func (f *PoolFuture) Result(timeout time.Duration) (any, error)

Result waits up to timeout for the outcome, zero waits forever

type PoolKeySource

type PoolKeySource interface {
	// Whether auth remove recorded the source as suppressed for the provider
	SourceSuppressed(env *Env, providerID, source string) bool
	// Runtime key else access token of the first pooled credential of the pool key, empty when none
	PoolAPIKey(env *Env, providerID string) string
}

PoolKeySource answers the credential pool reads of the provider key resolver, installed by the provider wiring

var PoolKeys PoolKeySource

PoolKeys is the installed credential pool reader, nil meaning no pool is consulted

type PortForward

type PortForward struct {
	Env        Environment
	RemoteHost string
	RemotePort int
	User       string
	LocalPort  int
	// contains filtered or unexported fields
}

PortForward is a local loopback listener whose connections land on a port inside the environment

func NewPortForward

func NewPortForward(e Environment, remoteHost string, remotePort int, user string) (*PortForward, error)

NewPortForward starts the listener and its accept loop

func (*PortForward) Failures

func (f *PortForward) Failures() int

Failures counts connections that never reached the target

type PostToolCallEvent

type PostToolCallEvent struct {
	ToolName        string
	Args            map[string]any
	Result          string
	IDs             ToolHookIDs
	DurationMS      int
	Status          string
	ErrorType       string
	ErrorMessage    string
	MiddlewareTrace []map[string]any
}

PostToolCallEvent describes one finished tool call for observers

type PostToolCallHook

type PostToolCallHook func(ctx context.Context, env *Env, ev PostToolCallEvent)

PostToolCallHook observes a finished tool call

type PreToolCallHook

type PreToolCallHook func(ctx context.Context, env *Env, name string, args map[string]any, ids ToolHookIDs, trace []map[string]any) PreToolDirective

PreToolCallHook inspects a call before dispatch

type PreToolDirective

type PreToolDirective struct {
	Action  string
	Message string
	RuleKey string
	Args    map[string]any
}

PreToolDirective is one pre tool call hook answer with block, approve, or modify semantics

type ProbeResult

type ProbeResult struct {
	Code   int
	Stdout string
	Stderr string
}

ProbeResult is the captured outcome of a bounded probe child

func BoundedProbeRun

func BoundedProbeRun(argv []string, timeout time.Duration, env map[string]string, cwd string, input *string) *ProbeResult

Runs a probe child with captured pipes, nil on spawn failure or timeout

type ProcessDockFields

type ProcessDockFields struct {
	ID           string
	Command      string
	StartedAt    float64
	ExitedAt     float64
	ExitCode     *int
	OutputBuffer string
}

Fields of a process the live work dock paints, copied under the session lock

type ProcessHandle

type ProcessHandle interface {
	// Exit code and whether the process has finished
	Poll() (int, bool)
	Kill() error
	// Exit code once the process finishes within the timeout, zero timeout waits forever
	Wait(timeoutSeconds float64) (int, error)
	// Read end of the merged stdout and stderr pipe, never passed through Fd on POSIX
	Stdout() *os.File
	Pid() int
}

ProcessHandle is the duck type every backend returns from runBash

type ProcessNotificationBatch

type ProcessNotificationBatch struct {
	Notifications []DrainedNotification
}

ProcessNotificationBatch keeps completion identity until the owning surface starts its turn

func (ProcessNotificationBatch) DisplayText

DisplayText is the compact UI title of the live completions

func (ProcessNotificationBatch) Render

Render joins the live notifications under a batch header, empty when none remain

type ProcessRegistry

type ProcessRegistry struct {

	// PendingWatchers is the side channel for check_interval watchers the gateway reads after a run
	PendingWatchers []map[string]any
	// CompletionQueue holds every background event, distinguished by type
	CompletionQueue *EventQueue

	// OnOutput streams live output chunks from reader goroutines to a driver installed sink
	OnOutput func(s *ProcessSession, chunk string)
	// contains filtered or unexported fields
}

ProcessRegistry tracks running and finished background processes across executor goroutines and the gateway

func DefaultProcessRegistry

func DefaultProcessRegistry() *ProcessRegistry

DefaultProcessRegistry is the process wide background process registry

func NewProcessRegistry

func NewProcessRegistry() *ProcessRegistry

NewProcessRegistry returns an empty registry

func (*ProcessRegistry) AdoptLocal

func (r *ProcessRegistry) AdoptLocal(ctx context.Context, env *Env, proc *ExecProcess, command, cwd, taskID, sessionKey, ownerTaskID, outputSoFar string, notifyOnComplete bool) *ProcessSession

AdoptLocal takes over a still running foreground process as a tracked background session

func (*ProcessRegistry) AnyRunning

func (r *ProcessRegistry) AnyRunning(pred func(*ProcessSession) bool) bool

AnyRunning reports whether any still running session satisfies the predicate

func (*ProcessRegistry) ArmHeartbeat

func (r *ProcessRegistry) ArmHeartbeat(s *ProcessSession, seconds int) int

ArmHeartbeat enables periodic heartbeat events for the session and returns the effective interval

func (*ProcessRegistry) AwaitsNotification

func (r *ProcessRegistry) AwaitsNotification(ownerTaskIDs []string) bool

AwaitsNotification reports whether a process spawned by one of the owners still has a notice on its way

func (*ProcessRegistry) CheckWatchPatterns

func (r *ProcessRegistry) CheckWatchPatterns(s *ProcessSession, newText string)

CheckWatchPatterns scans a freshly read chunk for watch patterns and queues rate limited notifications

func (*ProcessRegistry) CloseStdin

func (r *ProcessRegistry) CloseStdin(env *Env, sessionID string) map[string]any

CloseStdin sends EOF to a running process without killing it

func (*ProcessRegistry) CountRunning

func (r *ProcessRegistry) CountRunning() int

CountRunning is the running count for status bar polling

func (*ProcessRegistry) DrainNotifications

func (r *ProcessRegistry) DrainNotifications(env *Env, sessionKey string, owns func(map[string]any) bool, skipPollObserved bool) []DrainedNotification

DrainNotifications pops every pending event the caller owns and formats it, requeueing foreign ones

func (*ProcessRegistry) DrainedFor

func (r *ProcessRegistry) DrainedFor(owns func(map[string]any) bool, fn func(mine []map[string]any))

DrainedFor dequeues everything for a caller that consumes only the events owns accepts, requeueing the rest

func (*ProcessRegistry) ForgetFinished

func (r *ProcessRegistry) ForgetFinished(id string)

Drops a finished process from the registry so later listings no longer retain it

func (*ProcessRegistry) Get

func (r *ProcessRegistry) Get(env *Env, sessionID string) *ProcessSession

Get returns the session by full id or unique prefix, never a guess

func (*ProcessRegistry) HasActiveForSession

func (r *ProcessRegistry) HasActiveForSession(sessionKey string, maxActiveAge *float64) bool

HasActiveForSession reports active processes for a gateway session key younger than maxActiveAge

func (*ProcessRegistry) HasActiveProcesses

func (r *ProcessRegistry) HasActiveProcesses(taskID string) bool

HasActiveProcesses reports whether any process the task spawned is still running

func (*ProcessRegistry) HasAnyActive

func (r *ProcessRegistry) HasAnyActive() bool

HasAnyActive reports whether any background process is running

func (*ProcessRegistry) InsertFinished

func (r *ProcessRegistry) InsertFinished(s *ProcessSession)

InsertFinished records a session in the finished table under the registry lock

func (*ProcessRegistry) InsertRunning

func (r *ProcessRegistry) InsertRunning(s *ProcessSession)

InsertRunning records a session in the running table under the registry lock

func (*ProcessRegistry) IsCompletionConsumed

func (r *ProcessRegistry) IsCompletionConsumed(sessionID string) bool

IsCompletionConsumed reports a completion already consumed via wait or log

func (*ProcessRegistry) IsSessionWaiting

func (r *ProcessRegistry) IsSessionWaiting(sessionID string) bool

IsSessionWaiting reports whether a goal loop barrier should stay parked on the session

func (*ProcessRegistry) KillAll

func (r *ProcessRegistry) KillAll(ctx context.Context, env *Env, taskID string, excludeIDs map[string]bool, source string, consumeOutput bool) int

KillAll kills every running process, or only those the task spawned, returning how many it stopped

func (*ProcessRegistry) KillProcess

func (r *ProcessRegistry) KillProcess(ctx context.Context, env *Env, sessionID, source string, consumeOutput bool) map[string]any

KillProcess kills a background process and returns its output snapshot

func (*ProcessRegistry) KillStartedSince

func (r *ProcessRegistry) KillStartedSince(ctx context.Context, env *Env, taskID string, baselineIDs map[string]bool, source string) int

KillStartedSince kills the task's processes created after the baseline, consuming their output

func (*ProcessRegistry) ListSessions

func (r *ProcessRegistry) ListSessions(ctx context.Context, env *Env, taskID, sessionKey string, includeRetained bool) []map[string]any

ListSessions lists running and recently finished processes for a task and or session key

func (*ProcessRegistry) Poll

func (r *ProcessRegistry) Poll(ctx context.Context, env *Env, sessionID string) map[string]any

Poll checks status and returns the new output preview of a background process

func (*ProcessRegistry) ProcessViews

func (r *ProcessRegistry) ProcessViews(tailLength int) []ProcessView

Running then finished processes in spawn order, read under the registry lock and each session lock

func (*ProcessRegistry) ReadLog

func (r *ProcessRegistry) ReadLog(env *Env, sessionID string, offset *int, limit int) map[string]any

ReadLog returns the full output paged by lines

func (*ProcessRegistry) RecoverFromCheckpoint

func (r *ProcessRegistry) RecoverFromCheckpoint(ctx context.Context, env *Env) (int, error)

RecoverFromCheckpoint probes the checkpointed pids at startup and re adopts the live ones as detached sessions

func (*ProcessRegistry) RestoreCompletions

func (r *ProcessRegistry) RestoreCompletions() int

RestoreCompletions rehydrates durable delegation completions once per process

func (*ProcessRegistry) RunningOwnedBy

func (r *ProcessRegistry) RunningOwnedBy(ownerTaskID string) []*ProcessSession

RunningOwnedBy lists running processes whose raw spawning owner is ownerTaskID

func (*ProcessRegistry) SnapshotRunningIDs

func (r *ProcessRegistry) SnapshotRunningIDs(taskID string) map[string]bool

SnapshotRunningIDs is the set of running ids owned by the task, a turn boundary marker

func (*ProcessRegistry) SpawnLocal

func (r *ProcessRegistry) SpawnLocal(ctx context.Context, env *Env, command string, o SpawnLocalOptions) (*ProcessSession, error)

SpawnLocal starts a background process on the host, pipe mode or a PTY with pipe fallback

func (*ProcessRegistry) SpawnViaEnv

func (r *ProcessRegistry) SpawnViaEnv(ctx context.Context, env *Env, e Environment, command, cwd, taskID, sessionKey string, timeout int, ownerTaskID string, persistOnRelease bool) (*ProcessSession, error)

SpawnViaEnv starts a background process inside a non local backend's sandbox and polls its log

func (*ProcessRegistry) SubmitStdin

func (r *ProcessRegistry) SubmitStdin(env *Env, sessionID, data string) map[string]any

SubmitStdin sends data plus Enter, CR on a POSIX PTY, CRLF on a Windows PTY, LF on a pipe

func (*ProcessRegistry) TakePendingWatchers

func (r *ProcessRegistry) TakePendingWatchers() []map[string]any

Detaches the pending check interval watchers under the registry lock so concurrent appends are kept

func (*ProcessRegistry) TransferOwnership

func (r *ProcessRegistry) TransferOwnership(env *Env, sessionID, fromOwner, toOwner, toTaskID, toSessionKey, note string) *ProcessSession

TransferOwnership moves a running process from one owner to another, nil when the transfer cannot happen

func (*ProcessRegistry) UnreadCompletionEvent

func (r *ProcessRegistry) UnreadCompletionEvent(procID string, s *ProcessSession) (map[string]any, bool)

Blocks until a tracked process finished and builds its completion event, false once its outcome was read

func (*ProcessRegistry) UnreadCompletionsOwnedBy

func (r *ProcessRegistry) UnreadCompletionsOwnedBy(ownerTaskID string) []*ProcessSession

UnreadCompletionsOwnedBy lists exited notify_on_complete processes of the owner whose result nobody read

func (*ProcessRegistry) Wait

func (r *ProcessRegistry) Wait(ctx context.Context, env *Env, sessionID string, timeout *int) map[string]any

Wait blocks until the process exits, the timeout elapses, an interrupt lands or a yield releases it

func (*ProcessRegistry) WaitForPendingCompletions

func (r *ProcessRegistry) WaitForPendingCompletions(ctx context.Context, env *Env, taskID string, timeout *float64, pollInterval float64) PendingCompletionWait

WaitForPendingCompletions lingers at one shot exit for notify_on_complete background processes

func (*ProcessRegistry) WriteStdin

func (r *ProcessRegistry) WriteStdin(env *Env, sessionID, data string) map[string]any

WriteStdin sends raw data to a running process's stdin without a newline

type ProcessSession

type ProcessSession struct {
	ID                    string
	Command               string
	TaskID                string
	OwnerTaskID           string
	SessionKey            string
	Pid                   int
	Process               *ExecProcess
	EnvRef                Environment
	Cwd                   string
	StartedAt             float64
	HostStartTime         *int64
	Exited                bool
	ExitedAt              float64
	ExitCode              *int
	CompletionReason      string
	TerminationSource     string
	OutputBuffer          string
	MaxOutputChars        int
	Detached              bool
	PidScope              string
	SystemdUnit           string
	WslChain              bool
	HandoffNote           string
	PersistOnRelease      bool
	OutputLog             string
	PtyFallback           string
	WatcherPlatform       string
	WatcherChatID         string
	WatcherUserID         string
	WatcherUserName       string
	WatcherThreadID       string
	WatcherMessageID      string
	WatcherInterval       int
	ParentSessionID       string
	NotifyOnComplete      bool
	CompletionOutputChars int
	WatchPatterns         []string
	HeartbeatSeconds      int
	TotalOutputChars      int
	// contains filtered or unexported fields
}

ProcessSession is a tracked background process with output buffering

func NewProcessSession

func NewProcessSession(id, command string) *ProcessSession

Builds a session with the field defaults

func (*ProcessSession) AppendOutput

func (s *ProcessSession) AppendOutput(text string)

Appends to the rolling output buffer under the session lock

func (*ProcessSession) DockFields

func (s *ProcessSession) DockFields() ProcessDockFields

Snapshot of the dock fields read under the session lock

func (*ProcessSession) IsExited

func (s *ProcessSession) IsExited() bool

Whether the process recorded its exit, read under the session lock

func (*ProcessSession) WatchFields

func (s *ProcessSession) WatchFields() ProcessWatchFields

Snapshot of the watcher fields read under the session lock

type ProcessView

type ProcessView struct {
	ID               string
	Command          string
	SessionKey       string
	OwnerTaskID      string
	TaskID           string
	Exited           bool
	ExitCode         *int
	StartedAt        float64
	ExitedAt         float64
	CompletionReason string
	OutputTail       string
	ScopeStopPending bool
}

One tracked process as an owner projection reads it, its output trimmed to a tail

type ProcessWatchFields

type ProcessWatchFields struct {
	Command           string
	TaskID            string
	OwnerTaskID       string
	ParentSessionID   string
	StartedAt         float64
	Exited            bool
	ExitCode          *int
	CompletionReason  string
	TerminationSource string
	OutputBuffer      string
}

Fields of a background process the gateway watcher reads, copied under the session lock

type ProfileSecretSource

type ProfileSecretSource interface {
	ManagedDotenvKeys() []string
	SourceSuppliedNames() []string
	BuildProfileSecretScope(profileHome string) map[string]string
	CurrentSecretScope(ctx context.Context) map[string]string
}

ProfileSecretSource is the secret scope and dotenv bookkeeping of pkg/provider the child env builders read

var ProfileSecrets ProfileSecretSource

ProfileSecrets is installed by the provider wiring before any child environment is built

type ProgressReporter

type ProgressReporter func(progress float64, total *float64, message string)

Progress sink of one running tool call, total nil when the server sent none

func CurrentToolProgress

func CurrentToolProgress(ctx context.Context) ProgressReporter

The running call's reporter, nil outside a dispatched tool call

type Project

type Project struct {
	ID          string
	Slug        string
	Name        string
	CreatedAt   int64
	Description *string
	Icon        *string
	Color       *string
	BoardSlug   *string
	PrimaryPath *string
	Archived    bool
	Folders     []ProjectFolder
}

Project is one named workspace with its folders

func (*Project) PrimaryPathOf

func (p *Project) PrimaryPathOf() string

PrimaryPathOf is the explicit primary path, else the primary folder, else the first folder

type ProjectFacts

type ProjectFacts struct {
	Manifests       []string
	PackageManagers []string
	VerifyCommands  []string
	ContextFiles    []string
}

ProjectFacts are the detected manifests, package managers, verify commands, and context files

func DetectProjectFacts

func DetectProjectFacts(root string) ProjectFacts

DetectProjectFacts detects manifests, package managers, verify commands, and context files

type ProjectFolder

type ProjectFolder struct {
	Path      string
	Label     *string
	IsPrimary bool
	AddedAt   int64
}

ProjectFolder is one folder attached to a project

type ProjectWorkspaceCallback

type ProjectWorkspaceCallback func(taskID, primaryPath, projectName string)

ProjectWorkspaceCallback re anchors a live GUI session's workspace to a project path, installed by the GUI gateway

type ProjectsDB

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

ProjectsDB is an open per profile projects database

func OpenProjectsDB

func OpenProjectsDB(ctx context.Context, env *Env) (*ProjectsDB, error)

OpenProjectsDB opens and initializes the projects database of the env home

func OpenProjectsDBAt

func OpenProjectsDBAt(ctx context.Context, path, journalMode string) (*ProjectsDB, error)

OpenProjectsDBAt opens the database at a path with WAL or DELETE journaling, creating the parent and the schema

func (*ProjectsDB) AddFolder

func (p *ProjectsDB) AddFolder(projectID, path string, label *string, isPrimary bool) (string, error)

AddFolder attaches a folder and returns its normalized path, the first folder or an explicit primary becoming primary

func (*ProjectsDB) ArchiveProject

func (p *ProjectsDB) ArchiveProject(projectID string) (bool, error)

ArchiveProject hides a project from the default listing

func (*ProjectsDB) Close

func (p *ProjectsDB) Close() error

Close releases the connection

func (*ProjectsDB) CreateProject

func (p *ProjectsDB) CreateProject(name string, opts CreateProjectOptions) (string, error)

CreateProject inserts a project and returns its id, the primary path joining the folder set and marked primary

func (*ProjectsDB) FindByPrimaryPath

func (p *ProjectsDB) FindByPrimaryPath(path string, includeArchived bool) (*Project, error)

FindByPrimaryPath is the oldest project whose primary path matches, nil when none

func (*ProjectsDB) GetActiveID

func (p *ProjectsDB) GetActiveID() (string, error)

GetActiveID is the active project pointer, empty when unset

func (*ProjectsDB) GetProject

func (p *ProjectsDB) GetProject(idOrSlug string) (*Project, error)

GetProject looks a project up by id first, then by slug

func (*ProjectsDB) ListProjects

func (p *ProjectsDB) ListProjects(includeArchived bool) ([]*Project, error)

ListProjects returns projects oldest first, archived ones only when asked

func (*ProjectsDB) ProjectForPath

func (p *ProjectsDB) ProjectForPath(path string, includeArchived bool) (*Project, error)

ProjectForPath returns the innermost project whose folder equals or contains the path

func (*ProjectsDB) RemoveFolder

func (p *ProjectsDB) RemoveFolder(projectID, path string) (bool, error)

RemoveFolder detaches a folder and repoints the primary when it was primary

func (*ProjectsDB) RestoreProject

func (p *ProjectsDB) RestoreProject(projectID string) (bool, error)

RestoreProject unarchives a project

func (*ProjectsDB) SetActive

func (p *ProjectsDB) SetActive(projectID *string) error

SetActive sets or clears the active project pointer

func (*ProjectsDB) SetPrimary

func (p *ProjectsDB) SetPrimary(projectID, path string) (bool, error)

SetPrimary marks an attached folder primary, false when the folder is not attached

func (*ProjectsDB) UpdateProject

func (p *ProjectsDB) UpdateProject(projectID string, f UpdateProjectFields) (bool, error)

UpdateProject patches the provided fields and reports whether a row changed

type ProjectsValueError

type ProjectsValueError struct{ Msg string }

ProjectsValueError is a projects database argument rejection, the ValueError of projects_db

func (*ProjectsValueError) Error

func (e *ProjectsValueError) Error() string

type Proposal

type Proposal struct {
	Pattern  string
	Kind     string
	Count    int
	Classes  map[string]bool
	Examples []string
}

Proposal is one ranked allowlist proposal mined from approval history

func BuildProposals

func BuildProposals(records []ApprovalRecord, existing map[string]bool, minCount, limit int) []*Proposal

BuildProposals aggregates scan records into a ranked, safety filtered proposal list

type PtyQueryResponder

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

PtyQueryResponder strips the bounded set of terminal queries from PTY output and answers them

func NewPtyQueryResponder

func NewPtyQueryResponder(rows, cols int) *PtyQueryResponder

NewPtyQueryResponder answers window size queries with the given PTY dimensions

func (*PtyQueryResponder) Flush

func (r *PtyQueryResponder) Flush() []byte

Flush returns any incomplete trailing sequence the scanner held back

func (*PtyQueryResponder) Process

func (r *PtyQueryResponder) Process(data []byte) ([]byte, []byte)

Process scans a chunk and returns the output with handled queries removed plus the replies to write

type Question

type Question struct {
	Header      string
	Text        string
	Choices     []string
	MultiSelect bool
}

Question is one prompt the user answers inside a form

type ReadRemoteScriptFunc

type ReadRemoteScriptFunc func(path string) (string, bool)

ReadRemoteScriptFunc reads a script through a remote backend, false when nothing came back

type ReadResult

type ReadResult struct {
	Content        string `json:"content"`
	TotalLines     int    `json:"total_lines"`
	FileSize       int64  `json:"file_size"`
	Truncated      bool   `json:"truncated"`
	TruncatedLines *bool  `json:"truncated_lines,omitempty"`
	Hint           string `json:"hint,omitempty"`
	IsBinary       bool   `json:"is_binary"`
	IsImage        bool   `json:"is_image"`
	Base64Content  string `json:"base64_content,omitempty"`
	MimeType       string `json:"mime_type,omitempty"`
	Dimensions     string `json:"dimensions,omitempty"`
	Error          string `json:"error,omitempty"`
	NotFound       bool   `json:"not_found"`
	// Leading bytes of a binary file carry a document signature, read through the document extractor
	DocumentSignature bool     `json:"-"`
	SimilarFiles      []string `json:"similar_files,omitempty"`
	// Sha256 of the exact on disk bytes a raw read decoded, nil when unknown
	ContentSha256 *string `json:"-"`
}

ReadResult is one file read with the key order and omission rules the model reads

type ReasonedError

type ReasonedError interface {
	error
	Reason() string
}

Error that carries its own reason attribute

type RedactOptions

type RedactOptions struct {
	Force          bool
	CodeFile       bool
	FileRead       bool
	SecretFile     bool
	URLCredentials bool
}

RedactOptions selects the redaction passes redact_sensitive_text applies

type RedactingHandler

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

Log handler that redacts secrets from every record message and attribute

func NewRedactingHandler

func NewRedactingHandler(next slog.Handler, scopeOf func(context.Context) map[string]string) *RedactingHandler

Wraps next so records are redacted under the profile policy, scopeOf reading the live secret scope

func (*RedactingHandler) Enabled

func (h *RedactingHandler) Enabled(ctx context.Context, level slog.Level) bool

Defers the level decision to the wrapped handler

func (*RedactingHandler) Handle

func (h *RedactingHandler) Handle(ctx context.Context, r slog.Record) error

Redacts the message and every bound or record attribute when the context profile redacts

func (*RedactingHandler) WithAttrs

func (h *RedactingHandler) WithAttrs(attrs []slog.Attr) slog.Handler

Binds attributes that each record redacts under its own policy

func (*RedactingHandler) WithGroup

func (h *RedactingHandler) WithGroup(name string) slog.Handler

Opens a group replayed on the wrapped handler per record

type RegisteredApprovalTransport

type RegisteredApprovalTransport struct {
	Name        string
	Present     ApprovalPresentFunc
	PluginID    string
	ProfileHome string
}

RegisteredApprovalTransport is a plugin owned transport registration of one profile

type Registry

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

Registry holds every tool definition by name

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty registry

func (*Registry) AllToolNames

func (r *Registry) AllToolNames(ctx context.Context, scope string) []string

AllToolNames lists every visible tool name sorted

func (*Registry) AllToolsets

func (r *Registry) AllToolsets(ctx context.Context, scope string) map[string]Toolset

AllToolsets returns every static and plugin toolset keyed by display name

func (*Registry) AvailableToolsetNames

func (r *Registry) AvailableToolsetNames(ctx context.Context, env *Env) []string

AvailableToolsetNames lists visible toolsets in the order their first tool was registered

func (*Registry) AvailableToolsets

func (r *Registry) AvailableToolsets(ctx context.Context, env *Env) map[string]ToolsetInfo

AvailableToolsets reports availability, members, and requirements per visible toolset

func (*Registry) BundleNonCoreTools

func (r *Registry) BundleNonCoreTools(ctx context.Context, scope, name string) map[string]bool

BundleNonCoreTools returns a bundle's tools minus the core tools every toolset shares

func (*Registry) CheckCached

func (r *Registry) CheckCached(ctx context.Context, env *Env, fn func(*Env) bool) bool

Availability verdict of a probe through the TTL cache, running it when the cache is cold

func (*Registry) CheckToolAvailability

func (r *Registry) CheckToolAvailability(ctx context.Context, env *Env) ([]string, []UnavailableToolset)

CheckToolAvailability splits visible toolsets into exposable names and unavailable detail

func (*Registry) CheckToolsetRequirements

func (r *Registry) CheckToolsetRequirements(ctx context.Context, env *Env) map[string]bool

CheckToolsetRequirements maps every visible toolset to whether it exposes a tool

func (*Registry) Definitions

func (r *Registry) Definitions(ctx context.Context, env *Env, toolNames map[string]bool, quiet bool) []map[string]any

Definitions returns OpenAI format schemas for the named tools whose check passes

func (*Registry) Deregister

func (r *Registry) Deregister(name, scope, callerPlugin string) error

Deregister removes a tool from one scope under the plugin ownership rules

func (*Registry) DeregisterIn

func (r *Registry) DeregisterIn(ctx context.Context, name, scope, callerPlugin string) error

DeregisterIn removes a tool, judging toolset survivors through the home and session overlays of ctx

func (*Registry) DisabledEntryTools

func (r *Registry) DisabledEntryTools(ctx context.Context, scope, name string) map[string]bool

DisabledEntryTools lists the tools one agent.disabled_toolsets entry removes at runtime

func (*Registry) Emoji

func (r *Registry) Emoji(ctx context.Context, scope, name, fallback string) string

Emoji returns a tool's emoji or the fallback

func (*Registry) Entry

func (r *Registry) Entry(ctx context.Context, env *Env, name string) *Def

Entry resolves a tool for the environment's profile home

func (*Registry) ForgetPluginModuleScopeForTests

func (r *Registry) ForgetPluginModuleScopeForTests(namespace, scope string)

Drops the durable scope attribution of a plugin module namespace, for a case whose module is the test package itself

func (*Registry) Generation

func (r *Registry) Generation() int64

Generation changes on every registration, removal, alias, or scope move

func (*Registry) Get

func (r *Registry) Get(name string) *Def

Get returns the tool with this name or nil

func (*Registry) GetToolset

func (r *Registry) GetToolset(ctx context.Context, scope, name string, includeRegistry bool) (Toolset, bool)

GetToolset returns a toolset definition merged with registry additions, or false when unknown

func (*Registry) IsToolsetAvailable

func (r *Registry) IsToolsetAvailable(ctx context.Context, env *Env, toolset string) bool

IsToolsetAvailable reports whether a toolset has at least one exposable tool

func (*Registry) Lookup

func (r *Registry) Lookup(ctx context.Context, scope, name string) *Def

Lookup finds a tool through the session overlay, the profile overlay, then the global map

func (*Registry) MaxResultSize

func (r *Registry) MaxResultSize(ctx context.Context, scope, name string, fallback int) int

MaxResultSize returns the per tool result cap or the fallback when the tool sets none

func (*Registry) MoveToScope

func (r *Registry) MoveToScope(names []string, scope string)

MoveToScope hands process global registrations to one profile overlay

func (*Registry) Names

func (r *Registry) Names() []string

Names lists registered tool names sorted

func (*Registry) OrderedToolsetNames

func (r *Registry) OrderedToolsetNames(ctx context.Context, scope string) []string

OrderedToolsetNames lists static toolsets in table order then plugin display names like the all toolsets dict keys

func (*Registry) PlatformTools

func (r *Registry) PlatformTools(ctx context.Context, scope string, cfg config.Tree, platform string, opts PlatformToolsOptions) map[string]bool

PlatformTools resolves the enabled toolset names for one platform from config

func (*Registry) PlatformToolsetSummary

func (r *Registry) PlatformToolsetSummary(ctx context.Context, scope, h string, cfg config.Tree, platforms []string) ([]PlatformToolsetEntry, error)

Enabled toolsets per platform, the configured platforms when platforms is nil

func (*Registry) PluginScopeForModule

func (r *Registry) PluginScopeForModule(current, module string) (string, error)

PluginScopeForModule returns the one profile scope a loaded plugin module is bound to

func (*Registry) Register

func (r *Registry) Register(d Def)

Register adds a process global tool, panicking on a malformed schema and logging a refused shadow

func (*Registry) RegisterPluginOverridePolicy

func (r *Registry) RegisterPluginOverridePolicy(namespace string, allowed bool, scope string) *PluginOverridePolicy

RegisterPluginOverridePolicy records a plugin namespace's operator opt in for one scope

func (*Registry) RegisterScoped

func (r *Registry) RegisterScoped(scope string, d Def) error

RegisterScoped registers a plugin owned tool into a profile overlay under the override policy

func (*Registry) RegisterToolsetAlias

func (r *Registry) RegisterToolsetAlias(alias, toolset string)

RegisterToolsetAlias binds an alias to a canonical toolset, replacing a colliding target

func (*Registry) RegisteredToolsetNames

func (r *Registry) RegisteredToolsetNames(ctx context.Context, scope string) []string

RegisteredToolsetNames lists every toolset any visible entry belongs to

func (*Registry) Remove

func (r *Registry) Remove(name string) bool

Remove drops a tool and reports whether it existed

func (*Registry) ResolveStaticToolset

func (r *Registry) ResolveStaticToolset(ctx context.Context, scope, name string) []string

ResolveStaticToolset expands a toolset using the static table only

func (*Registry) ResolveToolset

func (r *Registry) ResolveToolset(ctx context.Context, scope, name string) []string

ResolveToolset expands a toolset and its includes into a sorted tool name list

func (*Registry) RestorePluginOverridePolicy

func (r *Registry) RestorePluginOverridePolicy(namespace string, current, previous *PluginOverridePolicy, scope string) bool

RestorePluginOverridePolicy swaps a policy back only while the current one is still installed

func (*Registry) RestoreRegistration

func (r *Registry) RestoreRegistration(name string, current, previous *Def, scope string) bool

RestoreRegistration puts a previous entry back only while the current one is still installed

func (*Registry) RestoreRegistrationIn

func (r *Registry) RestoreRegistrationIn(ctx context.Context, name string, current, previous *Def, scope string) bool

RestoreRegistrationIn restores like RestoreRegistration with survivors read through the overlays of ctx

func (*Registry) SampleToolsetsFromDistribution

func (r *Registry) SampleToolsetsFromDistribution(ctx context.Context, scope, name string, rng *rand.Rand) ([]string, []string, error)

SampleToolsetsFromDistribution rolls each entry independently, grouped entries roll once together

func (*Registry) SavePlatformTools

func (r *Registry) SavePlatformTools(ctx context.Context, scope string, cfg config.Tree, platform string, enabled map[string]bool, pluginKeys map[string]bool) error

SavePlatformTools writes a platform's selected toolset keys into the config tree

func (*Registry) Schema

func (r *Registry) Schema(ctx context.Context, scope, name string) *pyjson.Object

Schema returns a visible tool's raw schema bypassing availability checks

func (*Registry) SelectToolNames

func (r *Registry) SelectToolNames(ctx context.Context, env *Env, enabled, disabled []string, sel SelectionContext) (map[string]bool, []SelectionNotice)

SelectToolNames expands enabled toolsets then subtracts disabled ones at tool granularity

func (*Registry) Snapshot

func (r *Registry) Snapshot(ctx context.Context, scope string) []*Def

Snapshot returns every visible entry for this scope sorted by name

func (*Registry) SnapshotPluginOverridePolicy

func (r *Registry) SnapshotPluginOverridePolicy(namespace, scope string) *PluginOverridePolicy

SnapshotPluginOverridePolicy returns one scope's policy without fallback

func (*Registry) SnapshotRegistration

func (r *Registry) SnapshotRegistration(scope, name string) *Def

SnapshotRegistration returns one slot's own entry without any global fallback

func (*Registry) ToolDefinitions

func (r *Registry) ToolDefinitions(ctx context.Context, env *Env, opts DefinitionOptions) []map[string]any

ToolDefinitions returns the model facing definitions for a toolset selection with memoization when quiet

func (*Registry) ToolNamesForToolset

func (r *Registry) ToolNamesForToolset(ctx context.Context, scope, toolset string) []string

ToolNamesForToolset lists the visible tools registered under one toolset

func (*Registry) ToolToToolsetMap

func (r *Registry) ToolToToolsetMap(ctx context.Context, scope string) map[string]string

ToolToToolsetMap maps every visible tool to its toolset

func (*Registry) ToolsetAliasTarget

func (r *Registry) ToolsetAliasTarget(alias string) string

ToolsetAliasTarget returns the canonical toolset an alias points at or empty

func (*Registry) ToolsetAliases

func (r *Registry) ToolsetAliases() map[string]string

ToolsetAliases returns a copy of every alias

func (*Registry) ToolsetChecks

func (r *Registry) ToolsetChecks() map[string]func(*Env) bool

ToolsetChecks returns the first check function recorded per toolset

func (*Registry) ToolsetForTool

func (r *Registry) ToolsetForTool(ctx context.Context, scope, name string) string

ToolsetForTool returns the toolset a visible tool belongs to or empty

func (*Registry) ToolsetInfoFor

func (r *Registry) ToolsetInfoFor(ctx context.Context, scope, name string) (ToolsetDetail, bool)

ToolsetInfoFor returns a toolset's definition plus its resolved tools, or false when unknown

func (*Registry) ToolsetNames

func (r *Registry) ToolsetNames(ctx context.Context, scope string) []string

ToolsetNames lists every static and plugin toolset name sorted, aliases excluded

func (*Registry) ToolsetRequirements

func (r *Registry) ToolsetRequirements(ctx context.Context, scope string) map[string]map[string]any

ToolsetRequirements returns a TOOLSET_REQUIREMENTS compatible row per toolset from one consistent snapshot

func (*Registry) ToolsetsPartiallyStripped

func (r *Registry) ToolsetsPartiallyStripped(ctx context.Context, scope string, cfg config.Tree, enabled map[string]bool) map[string]PartialStrip

ToolsetsPartiallyStripped reports enabled toolsets that disabled entries cut down but leave enabled

func (*Registry) ValidateToolset

func (r *Registry) ValidateToolset(ctx context.Context, scope, name string) bool

ValidateToolset reports whether a name is a known static, plugin, alias, or wildcard toolset

type RelayActivation

type RelayActivation struct {
	Report func() (any, error)
	Close  func(ctx context.Context) (any, error)
}

Activation handle plugin initialization returns

type RelayAsyncIterator

type RelayAsyncIterator struct {
	Next   func(ctx context.Context) (any, error)
	Aclose func(ctx context.Context) error
}

Async iterator whose Next returns io.EOF when exhausted and whose nil Aclose is a missing aclose attribute

type RelayAwaitable

type RelayAwaitable func(ctx context.Context) (any, error)

Deferred result of the async plugin API, resolved synchronously by the host

type RelayConversation

type RelayConversation struct {
	ProfileKey      string
	SessionID       string
	Platform        string
	ParentSessionID string
	Model           string
	SessionCwd      *string
	TurnCwd         *string
}

Conversation identity and working directories of AcquireConversation

type RelayError

type RelayError struct {
	Class   string
	Message string
}

Error the binding raised with its Python exception class

func (*RelayError) Error

func (e *RelayError) Error() string

type RelayEventView

type RelayEventView struct {
	Kind, Name, Category, ScopeCategory, CategoryProfile, Metadata, Data any
}

One event a binding subscriber receives, each field the matching attribute of the binding's event object

type RelayFunc

type RelayFunc func(ctx context.Context, env *Env, name string, args map[string]any, ids ToolHookIDs, pipeline func(context.Context, map[string]any) (string, error)) (string, map[string]any, error)

RelayFunc lets a relay rewrite a call around the icebath pipeline, which runs under the context the relay hands it

type RelayHandleWithUUID

type RelayHandleWithUUID interface{ UUID() any }

Scope handle exposing the native uuid that identifies it

type RelayHost

type RelayHost interface {
	ApplyToolRequestIntercepts(ctx context.Context, sessionID, toolName string, args map[string]any) (map[string]any, error)
	RetainManagedExecution(consumer string) error
	ReleaseManagedExecution(consumer string)
	ManagedExecutionEnabled() bool
	Shutdown()
}

Profile scoped Relay host, the real runtime or the reduced capability no op host

type RelayHostRegistry

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

Exactly one Relay host for each canonical icebath profile, first creations running outside the lock

func NewRelayHostRegistry

func NewRelayHostRegistry() *RelayHostRegistry

Empty host registry

func (*RelayHostRegistry) ForProfile

func (g *RelayHostRegistry) ForProfile(ctx context.Context, profileKey string, create bool) RelayHost

Host of the profile, created on first use unless create is false, the no op host while Relay has no consumer or cannot start

func (*RelayHostRegistry) ShutdownAll

func (g *RelayHostRegistry) ShutdownAll()

Shuts down every host and empties the registry

type RelayHostSource

type RelayHostSource interface {
	ForProfile(ctx context.Context, profileKey string, create bool) RelayHost
}

Source of profile hosts the coordinator resolves through

type RelayLLMRequest

type RelayLLMRequest struct {
	Headers map[string]any
	Content any
}

nemo_relay.LLMRequest value with its headers and JSON content

type RelayModelDumper

type RelayModelDumper interface{ ModelDump() (any, error) }

Model dump hook of a value that serialises itself like a pydantic model

type RelayOperationLease

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

Keeps process wide Relay plugins alive across a deferred operation

func (*RelayOperationLease) Release

func (l *RelayOperationLease) Release()

Releases this lease exactly once

func (*RelayOperationLease) RunInSession

func (l *RelayOperationLease) RunInSession(ctx context.Context, session *RelaySession, callback func(ctx context.Context) (any, error), allowClosing bool, timeout *float64) (any, error)

Runs cleanup while this lease still owns the runtime lifetime

type RelayParameter

type RelayParameter struct {
	Name       string
	VarKeyword bool
}

One parameter of the binding pop signature

type RelayPluginConfigurationLoadError

type RelayPluginConfigurationLoadError struct {
	Message string
	Err     error
}

Explicitly selected Relay plugin configuration that could not be loaded

func (*RelayPluginConfigurationLoadError) Error

func (*RelayPluginConfigurationLoadError) Unwrap

type RelayPluginSources

type RelayPluginSources struct {
	ConfigPaths []string
	Enabled     bool
	Errors      []string
	Warnings    []string
}

Plugin configuration Relay resolves for this process as its validator reports it

func ResolveRelayPluginSources

func ResolveRelayPluginSources(ctx context.Context, relay *NemoRelay) (RelayPluginSources, error)

Resolves the plugins toml layers this process would load without loading plugin code

type RelayProviderCallback

type RelayProviderCallback func(ctx context.Context, request any) (any, error)

Provider callback Relay invokes with its possibly rewritten request, a RelayAwaitable result is awaited

type RelayProviderStreamCallback

type RelayProviderStreamCallback func(ctx context.Context, request any) (*RelayAsyncIterator, error)

Provider stream callback Relay invokes to open the async chunk generator

type RelayRuntime

type RelayRuntime struct {
	Relay      *NemoRelay
	ProfileKey string
	RuntimeID  string
	// contains filtered or unexported fields
}

Owns Relay session scopes and the process plugin configuration

func GetRelayRuntime

func GetRelayRuntime(ctx context.Context, create bool, profileKey string) *RelayRuntime

Relay runtime of the active profile, nil for the no op host or when create is false and none exists

func NewRelayRuntime

func NewRelayRuntime(ctx context.Context, relay *NemoRelay, profileKey string) (*RelayRuntime, error)

Builds a runtime over relay, loading the binding when nil, keyed by profileKey or the active profile

func (*RelayRuntime) AcquireOperationLease

func (r *RelayRuntime) AcquireOperationLease() (*RelayOperationLease, error)

Retains plugin lifetime for work that outlives one Relay call

func (*RelayRuntime) ApplyToolRequestIntercepts

func (r *RelayRuntime) ApplyToolRequestIntercepts(ctx context.Context, sessionID, toolName string, args map[string]any) (map[string]any, error)

Applies Relay request rewriting before icebath authorizes a tool call

func (*RelayRuntime) CloseSession

func (r *RelayRuntime) CloseSession(ctx context.Context, event map[string]any)

Closes one session scope and removes it from the registry, doing nothing once shutting down

func (*RelayRuntime) DeferScopeOutput

func (r *RelayRuntime) DeferScopeOutput(handle any, output map[string]any)

Keeps the output of a finished scope a concurrent scope still covers for the orphan drain to close it with

func (*RelayRuntime) EnsureSession

func (r *RelayRuntime) EnsureSession(ctx context.Context, event map[string]any, o RelaySessionOptions) (*RelaySession, error)

Existing session scope or one created once, nil for a missing id or a closing runtime or session

func (*RelayRuntime) GetSession

func (r *RelayRuntime) GetSession(sessionID string) *RelaySession

Active session without creating one

func (*RelayRuntime) LookupSession

func (r *RelayRuntime) LookupSession(sessionID string) *RelaySession

Registry lookup including closing sessions without creating one

func (*RelayRuntime) ManagedExecutionEnabled

func (r *RelayRuntime) ManagedExecutionEnabled() bool

Whether an icebath managed consumer needs the Relay pipeline

func (*RelayRuntime) RegisterSubagent

func (r *RelayRuntime) RegisterSubagent(ctx context.Context, event map[string]any, o RelaySessionOptions) (*RelaySession, error)

Opens a child agent scope under its spawning turn when one is live

func (*RelayRuntime) ReleaseManagedExecution

func (r *RelayRuntime) ReleaseManagedExecution(consumer string)

Releases a consumer's managed execution requirement

func (*RelayRuntime) RetainManagedExecution

func (r *RelayRuntime) RetainManagedExecution(consumer string) error

Keeps managed LLM and tool execution active for one consumer

func (*RelayRuntime) RotateSessionScope

func (r *RelayRuntime) RotateSessionScope(ctx context.Context, session *RelaySession, reason string)

Closes the current session scope and opens the next segment, called only at a turn boundary

func (*RelayRuntime) RunInSession

func (r *RelayRuntime) RunInSession(ctx context.Context, session *RelaySession, callback func(ctx context.Context) (any, error), allowClosing bool, timeout *float64) (any, error)

Runs a Relay operation on a session's scope stack, timeout seconds bounding it on the executor

func (*RelayRuntime) RunInSessionAsync

func (r *RelayRuntime) RunInSessionAsync(ctx context.Context, session *RelaySession, callback func(ctx context.Context) (any, error), allowClosing bool) (any, error)

Runs and awaits an operation inside the session's saved context

func (*RelayRuntime) Shutdown

func (r *RelayRuntime) Shutdown()

Closes core scopes and releases the process plugin configuration once operations drain

func (*RelayRuntime) ShutdownComplete

func (r *RelayRuntime) ShutdownComplete() bool

Whether shutdown finished closing scopes and releasing plugins

func (*RelayRuntime) UnregisterSubagent

func (r *RelayRuntime) UnregisterSubagent(ctx context.Context, event map[string]any)

Closes a delegated session and forgets its parent relationship

func (*RelayRuntime) WaitOperationsIdle

func (r *RelayRuntime) WaitOperationsIdle(timeout float64) bool

Waits up to timeout seconds for every operation lease to be released

type RelaySession

type RelaySession struct {
	SessionID       string
	ParentSessionID string
	Mu              sync.Mutex
	Closing         bool
	Handle          any
	Context         *pyctx.Context
	Segment         int
	SegmentTurns    int
	RotatePending   bool
	ClosePending    bool
	Cwd             string
}

One icebath session's isolated Relay scope stack

func (*RelaySession) CurrentHandle

func (s *RelaySession) CurrentHandle() any

Handle of the current session scope read under the session lock

type RelaySessionCoordinator

type RelaySessionCoordinator struct {
	Registry RelayHostSource
	// contains filtered or unexported fields
}

Semantic conversation and turn lifetimes of icebath core

func NewRelaySessionCoordinator

func NewRelaySessionCoordinator(registry RelayHostSource) *RelaySessionCoordinator

Coordinator over registry

func (*RelaySessionCoordinator) AcquireConversation

Opens or resumes the conversation scope of a session and returns the caller lease

func (*RelaySessionCoordinator) BeginTurn

func (c *RelaySessionCoordinator) BeginTurn(ctx context.Context, lease *ConversationLease, turnID, taskID string, metadata map[string]any) (*RelayTurnContext, error)

Starts a turn on the lease, pushing its scope unless a concurrent turn owns the session stack

func (*RelaySessionCoordinator) EndTurn

func (c *RelaySessionCoordinator) EndTurn(ctx context.Context, turn *RelayTurnContext, outcome string)

Closes the turn scope and its logical children, then unregisters and unwinds the turn

func (*RelaySessionCoordinator) FinalizeConversation

func (c *RelaySessionCoordinator) FinalizeConversation(ctx context.Context, profileKey, sessionID string)

Closes the session scope of a finished conversation

func (*RelaySessionCoordinator) FinishLogicalCalls

func (c *RelaySessionCoordinator) FinishLogicalCalls(ctx context.Context, turn *RelayTurnContext, outcome string)

Closes logical LLM children before sibling task aggregation scopes

func (*RelaySessionCoordinator) HasActiveTurn

func (c *RelaySessionCoordinator) HasActiveTurn(profileKey, sessionID string) bool

Whether a turn is still running for one profile session

func (*RelaySessionCoordinator) NotifySessionCompacted

func (c *RelaySessionCoordinator) NotifySessionCompacted(ctx context.Context, profileKey, sessionID, oldSessionID string)

Flags rotation for an in place compaction or closes the old session of a rotating one

func (*RelaySessionCoordinator) RegisterSessionInitializer

func (c *RelaySessionCoordinator) RegisterSessionInitializer(name string, callback RelaySessionInitializer)

Registers idempotent profile and session preparation before scope creation

func (*RelaySessionCoordinator) ReleaseConversation

func (c *RelaySessionCoordinator) ReleaseConversation(lease *ConversationLease)

Releases a caller lease without closing a resumable conversation

type RelaySessionInitializer

type RelaySessionInitializer func(ctx context.Context, host *RelayRuntime, context map[string]any) error

Session preparation run before scope creation

type RelaySessionOptions

type RelaySessionOptions struct {
	Data     any
	Metadata map[string]any
	Cwd      *string
}

Optional session scope inputs of EnsureSession and RegisterSubagent

type RelayTimeoutError

type RelayTimeoutError struct {
	Message string
	Err     error
}

Bounded native call the runtime abandoned

func (*RelayTimeoutError) Error

func (e *RelayTimeoutError) Error() string

func (*RelayTimeoutError) Unwrap

func (e *RelayTimeoutError) Unwrap() error

type RelayToolExecutionResult

type RelayToolExecutionResult struct{ Result any }

nemo_relay.ToolExecutionResult value carrying the JSON result of one tool dispatch

type RelayTurnContext

type RelayTurnContext struct {
	Lease           *ConversationLease
	TurnID          string
	TaskID          string
	Handle          any
	LogicalLLMCalls *pydict.Dict[string, any]
	LogicalLLMMu    sync.Mutex
	// contains filtered or unexported fields
}

Runtime only context of one icebath turn or top level task

func ActiveRelayTurn

func ActiveRelayTurn(ctx context.Context, sessionID *string) *RelayTurnContext

Live turn of the active profile, of sessionID when given

func CurrentRelayTurn

func CurrentRelayTurn(ctx context.Context) *RelayTurnContext

Turn context inherited by the current work

func (*RelayTurnContext) Closed

func (t *RelayTurnContext) Closed() bool

Whether the turn finished

func (*RelayTurnContext) FinalizeLock

func (t *RelayTurnContext) FinalizeLock() *sync.Mutex

Lock serialising logical call finalization against turn close

func (*RelayTurnContext) RelayEnabled

func (t *RelayTurnContext) RelayEnabled() bool

Whether this turn may create Relay instrumentation

type RemovalBlock

type RemovalBlock struct {
	Action string
	Reason string
}

Keep action and reason why a tree may not be removed

func ArchivePreflight

func ArchivePreflight(wtPath string, maxUntrackedMB float64) *RemovalBlock

Keep action and reason when archiving and removing the tree would lose something, nil when it is safe

func RemovalBlocked

func RemovalBlocked(path string) *RemovalBlock

Keep action and reason when deleting the clean tree would lose something no branch holds

func RemovalBlocker

func RemovalBlocker(wtPath string, skipped []SkippedUntracked, gitlinks bool) *RemovalBlock

Keep action and reason when removing the tree would lose something, any failure to verify blocks

type RequestMiddlewareDirective

type RequestMiddlewareDirective struct {
	Args   map[string]any
	Source string
	Reason string
	Name   string
	// Trace entries of a chain that ran inside this middleware, recorded as given in place of the single entry
	Trace []map[string]any
}

RequestMiddlewareDirective replaces the effective arguments when Args is set

type ResizeOptions

type ResizeOptions struct {
	MaxBase64Bytes int
	MaxDimension   int
	ForceJPEG      bool
	Scale          *ScaleInfo
}

ResizeOptions bounds one resize for vision

type ResolvedImage

type ResolvedImage struct {
	Data []byte
	Mime string
	// One of data, http, file, local, container
	Origin string
}

ResolvedImage is media bytes with the verified MIME type and where they came from

func ResolveImageSource

func ResolveImageSource(ctx context.Context, env *Env, src, taskID string, permitted ...string) (*ResolvedImage, error)

ResolveImageSource turns a data URL, http URL, file URI, or path into verified media bytes

type ResolvedReasoning

type ResolvedReasoning struct{ Config map[string]any }

ResolvedReasoning is a route's final reasoning config used as is, nil standing for the route's own default

type ResolverEffort

type ResolverEffort string

ResolverEffort is what a probe may do, network never implying a subprocess

const (
	EffortLocal      ResolverEffort = "local"
	EffortNetwork    ResolverEffort = "network"
	EffortDiagnostic ResolverEffort = "diagnostic"
)

type RestartSafeScopeUnavailable

type RestartSafeScopeUnavailable struct{ Detail string }

RestartSafeScopeUnavailable reports a required restart safe scope that could not be created

func (*RestartSafeScopeUnavailable) Error

type RestoredArchive

type RestoredArchive struct {
	Path             string
	Branch           any
	Detached         bool
	Head             string
	Ref              string
	SkippedUntracked any
}

Result of recreating an archived tree

func RestoreArchive

func RestoreArchive(ctx context.Context, repoRoot, name, target string) (*RestoredArchive, error)

Recreates the archived tree at its original path or target with its exact files and index

type RunInResult

type RunInResult struct {
	Stdout     []byte
	Stderr     []byte
	ReturnCode int
}

RunInResult is the captured outcome of one short command inside a backend

func RunIn

func RunIn(ctx context.Context, e Environment, argv []string, childEnv map[string]string, user string, timeout time.Duration, stdin []byte) (*RunInResult, error)

RunIn runs one short argv inside the environment capturing bytes output, retrying once on a recovered container

type RunOptions

type RunOptions struct {
	SessionKey       string
	ToolCallID       string
	Callback         ConnCallback
	TickSeconds      *float64
	WithURLsInResult bool
	Call             any
}

RunOptions carries the session, card callback and tick of one driven operation

type RuntimeMode

type RuntimeMode struct {
	Profile      ContextProfile
	Surface      string
	Cwd          string
	ConfigMode   string
	Model        string
	Instructions string
}

RuntimeMode is the resolved operating posture for a session

func ResolveRuntimeMode

func ResolveRuntimeMode(env *Env, platform, cwd, model string) RuntimeMode

ResolveRuntimeMode resolves the operating posture once for a session

func (RuntimeMode) CompactSkillCategories

func (m RuntimeMode) CompactSkillCategories() map[string]bool

CompactSkillCategories lists skill categories demoted to names only under focus

func (RuntimeMode) IsCoding

func (m RuntimeMode) IsCoding() bool

IsCoding reports whether the coding posture is active

func (RuntimeMode) SystemPromptParts

func (m RuntimeMode) SystemPromptParts(validToolNames map[string]bool, workspaceBlock *string) ([]string, []string, []string)

SystemPromptParts returns the prefix, workspace, and trailing posture blocks in order

func (RuntimeMode) ToolsetSelection

func (m RuntimeMode) ToolsetSelection(env *Env) []string

ToolsetSelection returns the focus toolset list or nil to keep the platform default

type SSHOptions

type SSHOptions struct {
	Host, User, Cwd, KeyPath string
	Port, Timeout            int
	ProbeOnly, SyncFiles     bool
	Persistent               bool
}

SSHOptions are the connection settings of one ssh environment

type SSRFConnectionBlocked

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

SSRFConnectionBlocked reports a connect time policy violation

func (*SSRFConnectionBlocked) Error

func (e *SSRFConnectionBlocked) Error() string

type SandboxImageSwitch

type SandboxImageSwitch struct {
	CurrentImage string
	TargetImage  string
	Containers   []string
}

SandboxImageSwitch is a default image change the persisted docker sandbox still has to decide

func PendingSandboxImageSwitch

func PendingSandboxImageSwitch(ctx context.Context, env *Env) (*SandboxImageSwitch, error)

Pending switch of the docker backend running an unpinned default with a labeled container on another image

type SandboxSyncer

type SandboxSyncer interface {
	SyncFiles(force bool)
}

SandboxSyncer is implemented by file synced backends that must push host files before a probe

type SaveLoginPrompt

type SaveLoginPrompt func(origin, site string) map[string]string

SaveLoginPrompt asks the identifier and password to save for a site, nil when the user declines

func GetSaveLoginPromptCallback

func GetSaveLoginPromptCallback(ctx context.Context) SaveLoginPrompt

The save login prompt of the current thread, nil in headless contexts

type ScaleInfo

type ScaleInfo struct {
	OrigWidth, OrigHeight int
	NewWidth, NewHeight   int
	// contains filtered or unexported fields
}

ScaleInfo records an applied downscale from the original dimensions to the embedded ones

func (*ScaleInfo) Applied

func (s *ScaleInfo) Applied() bool

Applied reports whether a downscale was recorded

type SchemaRewriter

type SchemaRewriter func(env *Env, td map[string]any, available map[string]bool) map[string]any

SchemaRewriter returns the possibly replaced definition or nil to drop the tool

func ComposeSchemaRewriters

func ComposeSchemaRewriters(fns ...SchemaRewriter) SchemaRewriter

ComposeSchemaRewriters runs rewriters in order stopping at the first drop

func LookupSchemaRewriter

func LookupSchemaRewriter(name string) SchemaRewriter

LookupSchemaRewriter returns the dynamic schema rewriter installed for a tool name, nil when none is

type SearchCount

type SearchCount struct {
	Path  string
	Count int
}

SearchCount is one path and its match count, kept in discovery order like a Python dict

type SearchMatch

type SearchMatch struct {
	Path       string
	LineNumber int
	// Decimal digits of a line number beyond the int range, exact as the Python int
	LineNumberOverflow string
	Content            string
	Mtime              float64
}

SearchMatch is one search hit with the modification time used for sorting

type SearchMemo

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

SearchMemo is the TTL memo and single flight coalescer for search responses

func NewSearchMemo

func NewSearchMemo() *SearchMemo

NewSearchMemo returns an empty memo

func (*SearchMemo) FlightLock

func (m *SearchMemo) FlightLock(provider, query string, limit int) *sync.Mutex

FlightLock is the per key lock held around miss, paid request and store

func (*SearchMemo) Lookup

func (m *SearchMemo) Lookup(env *Env, provider, query string, limit int) *WebSearchResponse

Lookup returns a copy of a fresh entry, nil on a miss

func (*SearchMemo) Store

func (m *SearchMemo) Store(env *Env, provider, query string, limit int, response *WebSearchResponse)

Store caches a successful response for the bucketed key, sweeping expired entries

type SearchResult

type SearchResult struct {
	Matches     []SearchMatch
	Files       []string
	Counts      []SearchCount
	TotalCount  int
	Truncated   bool
	LimitReason string
	Warning     string
	Error       string
	// Unreadable paths behind the skipped sentence in Warning, never serialized
	SkippedPaths   []string
	SkippedOmitted int
}

SearchResult is one search outcome with the key order and omission rules the model reads

type SelectionContext

type SelectionContext struct {
	KanbanTask            bool
	DelegatedChild        bool
	DispatcherOwnedWorker bool
}

SelectionContext carries the kanban worker facts that widen a toolset selection

type SelectionNotice

type SelectionNotice struct {
	Text string
}

SelectionNotice is one line the non quiet selection pass prints

type SessionSearchArgs

type SessionSearchArgs struct {
	Query             any
	RoleFilter        any
	Limit             any
	DB                SessionSearchStore
	CurrentSessionID  string
	SessionID         any
	AroundMessageID   any
	Window            any
	Sort              any
	Profile           any
	Detail            any
	After             any
	Before            any
	ExcludeSessionIDs any
}

The session_search keyword arguments in their order

type SessionSearchStore

type SessionSearchStore interface {
	GetSession(ctx context.Context, sessionID string) (*pyjson.Object, error)
	GetMessages(ctx context.Context, sessionID string, o state.GetMessagesOptions) ([]*pyjson.Object, error)
	SearchMessages(ctx context.Context, query string, o state.SearchMessagesOptions) ([]*pyjson.Object, error)
	GetAnchoredView(ctx context.Context, sessionID string, aroundMessageID int64, o state.AnchoredViewOptions) (*pyjson.Object, error)
	GetMessagesAround(ctx context.Context, sessionID string, aroundMessageID int64, window int) (*pyjson.Object, error)
	ResolveSessionByTitle(ctx context.Context, title string) (string, bool, error)
	FTSRebuildStatus(ctx context.Context) (*pyjson.Object, error)
	ReadCtx(ctx context.Context, fn func(conn state.SQLiteConn) error) error
	Close() error
}

SessionSearchStore is the session database surface the session_search shapes read

type SessionVars

type SessionVars struct {
	Platform, Source, ChatID, ChatType, ChatName, ThreadID string
	UserID, UserIDAlt, UserName, ScopeID, SessionKey       string
	SessionID, MessageID, Profile, Cwd, UISessionID        string
	ParentChatID                                           string
	NoAsyncDelivery                                        bool
	CronSession, SessionHistoryDelivery                    *string
}

Session identity SetSessionVars binds, nil CronSession left unset and nil SessionHistoryDelivery never declared

type SettleReason

type SettleReason string

SettleReason names why an operation froze its result

const (
	SettleAllResolved SettleReason = "all_resolved"
	SettleContinue    SettleReason = "continue"
	SettleDeadline    SettleReason = "deadline"
	SettleInterrupt   SettleReason = "interrupt"
)

type SetupConsole

type SetupConsole interface {
	Prompt(question, def string, password bool) string
	PromptYesNo(question string, def bool) bool
	PromptChoice(question string, choices []string, def int) int
	PrintHeader(title string)
	PrintInfo(text string)
	PrintSuccess(text string)
	PrintWarning(text string)
	Println()
}

SetupConsole is the prompt and print surface the terminal backend setup flow runs on

var SetupTerminalConsole SetupConsole

SetupTerminalConsole is the terminal setup console, installed by pkg/provider

type SiteCopyError

type SiteCopyError struct{ Code string }

SiteCopyError is the KeyError an unknown site copy code raises

func (*SiteCopyError) Error

func (e *SiteCopyError) Error() string

func (*SiteCopyError) PyTypeName

func (e *SiteCopyError) PyTypeName() string

PyTypeName names the Python exception class an unknown code raises

type SkillLockSource

type SkillLockSource interface {
	LockedSkillNames(env *Env) []string
	SkillsDir(env *Env) string
	AllSkillsDirs(env *Env) []string
	IsExcludedSkillPath(path, root string) bool
	FindSkillDirName(env *Env, name string) string
	ExternalSkillsDirs(env *Env) []string
	ProjectSkillsDirs(env *Env) []string
	IsExcludedSkillDir(name string) bool
}

SkillLockSource is what the skills package installs so the guards can see the user's skill locks

var SkillLocks SkillLockSource

SkillLocks is installed by pkg/skills before any terminal or file guard runs

type SkippedUntracked

type SkippedUntracked struct {
	Path  string
	Bytes int64
}

Untracked file left out of an archive for exceeding the size cap

type SleepWatch

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

Wall time a caller checking every interval seconds stood still past one interval

func NewSleepWatch

func NewSleepWatch(interval float64) *SleepWatch

Watch for a caller checking every interval seconds, its wall clock read now

func (*SleepWatch) Slept

func (w *SleepWatch) Slept() float64

Seconds stopped since the previous call, zero for gaps under five seconds

type SpawnLocalOptions

type SpawnLocalOptions struct {
	Cwd              string
	TaskID           string
	SessionKey       string
	EnvVars          map[string]string
	UsePty           bool
	OwnerTaskID      string
	PersistOnRelease bool
	RestoreLoginPath bool
}

SpawnLocalOptions tunes a local background spawn

type SpawnTag

type SpawnTag struct {
	Install       string
	Purpose       string
	SpawnerPid    int
	SpawnerCreate *float64
}

SpawnTag is the parsed value of the spawn env var

func ParseSpawnTag

func ParseSpawnTag(raw any) *SpawnTag

ParseSpawnTag parses a spawn env value, nil for anything malformed

type SpillConfig

type SpillConfig struct {
	Enabled     bool
	MaxChars    int
	PreviewHead int
	PreviewTail int
	Directory   string
}

SpillConfig is the resolved hooks.output_spill section

func SpillConfigFromEnv

func SpillConfigFromEnv(env *Env) SpillConfig

SpillConfigFromEnv reads hooks.output_spill with defaults for every missing or invalid field

type Spinner

type Spinner interface {
	Stop(text string)
}

Spinner is the quiet mode progress indicator a host may show for one call

type StartOrderGate

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

StartOrderGate serializes worker dispatch by submit order so prompts appear in call order

func (*StartOrderGate) Abandon

func (g *StartOrderGate) Abandon()

Abandon releases every parked worker so none dispatches a tool the turn already gave up on

type StreamExecPrefixer

type StreamExecPrefixer interface {
	ExecPrefix(user string, interactive bool) ([]string, error)
}

StreamExecPrefixer is implemented by backends whose commands run through a local argv prefix

type StreamProcess

type StreamProcess struct {
	Cmd    *exec.Cmd
	Stdin  *os.File
	Stdout *os.File
	// contains filtered or unexported fields
}

StreamProcess is a long lived process inside a backend with stdin and stdout as pipes

func OpenStream

func OpenStream(e Environment, argv []string, childEnv map[string]string, user string, stderr *os.File) (*StreamProcess, error)

OpenStream spawns argv inside the environment with byte pipes, stderr nil discards it

func (*StreamProcess) Kill

func (s *StreamProcess) Kill() error

Kill terminates the stream process

func (*StreamProcess) Wait

func (s *StreamProcess) Wait(timeout time.Duration) (int, error)

Wait blocks until the stream exits or the timeout passes

type SubagentHandoff

type SubagentHandoff interface {
	ParentOwner() string
	ParentSessionID() string
	HandedOff() []map[string]any
	AppendHandoff(entry map[string]any)
}

SubagentHandoff is the live subagent record a process handoff validates against

type SubdirectoryHintTracker

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

Directories the agent visits through tool calls, each first visit loading its project hint file

func NewSubdirectoryHintTrackerFor

func NewSubdirectoryHintTrackerFor(env *Env, workingDir string, enabled bool) *SubdirectoryHintTracker

Tracker anchored at workingDir or the process cwd, its deny list and read timeout from the home of env

func (*SubdirectoryHintTracker) CheckToolCall

func (t *SubdirectoryHintTracker) CheckToolCall(toolName string, toolArgs map[string]any) (string, bool)

Formatted hint text of directories this call visits for the first time, false when there is none

func (*SubdirectoryHintTracker) RebindWorkingDir

func (t *SubdirectoryHintTracker) RebindWorkingDir(workingDir string)

Anchors hint discovery at a real project directory the session adopted, a home or invalid path ignored

func (*SubdirectoryHintTracker) WorkingDir

func (t *SubdirectoryHintTracker) WorkingDir() string

WorkingDir is the directory the tracker treats as the session root

type SubprocessEnvOptions

type SubprocessEnvOptions struct {
	Base               map[string]string
	InheritProfileHome bool
	ScrubSecrets       bool
	Extra              map[string]string
	StripLaunchProfile bool
	// Builds as the separate single profile process the base belongs to, its values kept as given and no launch strip
	SeparateProcess bool
}

SubprocessEnvOptions tunes BuildSubprocessEnv

type SudoPasswordCallback

type SudoPasswordCallback struct {
	Prompt func(ctx context.Context) string
}

SudoPasswordCallback asks the surface for a sudo password, empty on skip, its address naming the cache scope

func GetSudoPasswordCallback

func GetSudoPasswordCallback(ctx context.Context) *SudoPasswordCallback

The sudo password prompt of the current thread, nil in headless contexts

type SweepConfig

type SweepConfig struct {
	ArchiveDirty         bool
	ArchiveMaxFileMB     float64
	ArchiveRetentionDays float64
	MaxTotalGB           float64
}

Worktrees section of the active profile config with every field coerced

func SweepSettings

func SweepSettings() SweepConfig

Worktrees settings of the active profile, defaults on any read failure and per field on a bad value

type TargetState

type TargetState string

TargetState is where one connection target stands in its operation

const (
	TargetPending      TargetState = "pending"
	TargetInitiated    TargetState = "initiated"
	TargetConnected    TargetState = "connected"
	TargetSkipped      TargetState = "skipped"
	TargetFailed       TargetState = "failed"
	TargetNotConnected TargetState = "not_connected"
)

type TaskRoute

type TaskRoute struct {
	Creds           map[string]any
	RoutingCfg      map[string]any
	ReasoningEffort any
	ProfileHome     string
	Label           string
	Backend         string
	Error           string
}

How core builds one child, a set Error refusing this task alone while its siblings still run

func (*TaskRoute) RefusedEntry

func (r *TaskRoute) RefusedEntry(index int) *pyjson.Object

Result entry for a task this route refused before any child was built

func (*TaskRoute) Report

func (r *TaskRoute) Report() *pyjson.Object

Route a backend routed result carries, nil for the default backend unlabelled route

type TerminalBackendPostSetup

type TerminalBackendPostSetup interface {
	PostSetup(ctx context.Context, env *Env) error
}

TerminalBackendPostSetup is the optional interactive hook a plugin backend runs after the wizard selects it

type TerminalBackendRow

type TerminalBackendRow struct {
	Name        string
	DisplayName string
	Description string
}

TerminalBackendRow is one registered backend the setup menu offers after the built in ones

func SetupTerminalBackendRows

func SetupTerminalBackendRows(ctx context.Context, env *Env) (rows []TerminalBackendRow)

Registered backends outside the reserved built in names sorted by name, the rows read before a failing provider kept

type TerminalEnvironmentProviderDefaults

type TerminalEnvironmentProviderDefaults struct{ Self BackendProvider }

Classification and picker defaults of the terminal environment provider contract, dispatching through Self

func (TerminalEnvironmentProviderDefaults) CachePathBase

Host paths remain correct for synced cache files

func (TerminalEnvironmentProviderDefaults) CheckRequirements

func (d TerminalEnvironmentProviderDefaults) CheckRequirements(*Env, map[string]any) error

Full requirements check reading as the availability probe

func (TerminalEnvironmentProviderDefaults) DefaultCwd

Commands start in the generic root

func (TerminalEnvironmentProviderDefaults) Description

One line description shown in backend pickers

func (TerminalEnvironmentProviderDefaults) DisplayName

Label shown in pickers, the provider name

func (TerminalEnvironmentProviderDefaults) DoctorChecks

One doctor row reflecting the availability probe, a panicking probe reading as not configured

func (TerminalEnvironmentProviderDefaults) EnvDescription

func (d TerminalEnvironmentProviderDefaults) EnvDescription() string

Prompt builder fallback for where commands run when the live probe fails

func (TerminalEnvironmentProviderDefaults) IsContainer

Own filesystem rooted away from the host unless overridden

func (TerminalEnvironmentProviderDefaults) IsRemote

Commands run off host unless overridden

func (TerminalEnvironmentProviderDefaults) SessionIsolatedWhenNonpersistent

func (TerminalEnvironmentProviderDefaults) SessionIsolatedWhenNonpersistent() bool

Ephemeral runs share one sandbox identity

func (TerminalEnvironmentProviderDefaults) SetupInstructions

func (TerminalEnvironmentProviderDefaults) SetupInstructions(*Env) []string

No lines after selection

func (TerminalEnvironmentProviderDefaults) SkipContainerGuards

func (d TerminalEnvironmentProviderDefaults) SkipContainerGuards() bool

Dangerous command approval is skipped exactly when the backend is a container

func (TerminalEnvironmentProviderDefaults) StripEnvKeys

No vendor credential env vars to strip

func (TerminalEnvironmentProviderDefaults) SupportsStreams

func (TerminalEnvironmentProviderDefaults) SupportsStreams() bool

No exec_prefix stream support

type TerminalPolicy

type TerminalPolicy map[string]string

TerminalPolicy is the complete TERMINAL_* policy of one profile, total by construction

func BuildProfileTerminalScope

func BuildProfileTerminalScope(ctx context.Context, h string, envOverlay map[string]string) (TerminalPolicy, error)

Builds the complete TERMINAL_* policy of a profile home over a trusted launch overlay, never the process env

func BuildTerminalScope

func BuildTerminalScope(h string, secrets *config.Secrets) (TerminalPolicy, error)

Builds the complete TERMINAL_* policy of a home with the process environment as the overlay layer

func DefaultTerminalScope

func DefaultTerminalScope() TerminalPolicy

DefaultTerminalScope is the tool level terminal policy with no profile config folded in

func (TerminalPolicy) Get

func (p TerminalPolicy) Get(name, def string) string

Get reads a policy value, the default when the key is absent

func (TerminalPolicy) GetBool

func (p TerminalPolicy) GetBool(name, def string) bool

GetBool reads a policy value as true, 1 or yes

type TerminalPolicyRefusal

type TerminalPolicyRefusal struct {
	Reason string
}

Refusal scope installed when a profile terminal policy cannot be resolved

type TerminalPolicyUnavailable

type TerminalPolicyUnavailable struct {
	Reason string
}

Error of a profile whose terminal policy could not be resolved

func (*TerminalPolicyUnavailable) Error

func (e *TerminalPolicyUnavailable) Error() string

Error names the unreadable policy source

type TerminalRequest

type TerminalRequest struct {
	Command               any
	Background            bool
	Timeout               *int
	TaskID                string
	SessionID             string
	Force                 bool
	Workdir               string
	Pty                   bool
	NotifyOnComplete      bool
	WatchPatterns         []string
	HostLocal             bool
	CompletionOutputChars int
	Heartbeat             int
	PersistOnRelease      bool
}

TerminalRequest is one terminal tool invocation

type TerminalScope

type TerminalScope struct {
	Policy  TerminalPolicy
	Refusal *TerminalPolicyRefusal
}

Terminal scope bound to a turn, a complete policy or a refusal

func GetTerminalScope

func GetTerminalScope(ctx context.Context) *TerminalScope

Active terminal scope of the context, nil when none is bound

func PrepareProfileTerminalScope

func PrepareProfileTerminalScope(ctx context.Context, h string, envOverlay map[string]string) *TerminalScope

Profile policy scope of a home, the refusal scope when the policy cannot be resolved

type ThreadCallback

type ThreadCallback struct {
	Get func(ctx context.Context) any
	Set func(ctx context.Context, cb any)
}

ThreadCallback is one per goroutine prompt callback a worker inherits from the goroutine that handed it work

type ThreadedProcessHandle

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

ThreadedProcessHandle adapts an SDK call with no real subprocess to the ProcessHandle contract

func NewThreadedProcessHandle

func NewThreadedProcessHandle(execFn func() (string, int), cancelFn func()) (*ThreadedProcessHandle, error)

NewThreadedProcessHandle runs execFn on a goroutine and serves its output through a pipe

func (*ThreadedProcessHandle) Kill

func (h *ThreadedProcessHandle) Kill() error

Kill invokes the backend cancellation

func (*ThreadedProcessHandle) Pid

func (h *ThreadedProcessHandle) Pid() int

Pid returns a synthetic identifier unique per handle

func (*ThreadedProcessHandle) Poll

func (h *ThreadedProcessHandle) Poll() (int, bool)

Poll reports the exit code once the exec function returned

func (*ThreadedProcessHandle) Stdout

func (h *ThreadedProcessHandle) Stdout() *os.File

Stdout returns the read end of the output pipe

func (*ThreadedProcessHandle) Wait

func (h *ThreadedProcessHandle) Wait(timeoutSeconds float64) (int, error)

Wait blocks until the exec function returned or the timeout passed

type TodoItem

type TodoItem struct {
	ID      string
	Content string
	Status  string
	Parent  string
}

TodoItem is one task list row, Parent empty for a top level item

type TodoStore

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

TodoStore is the in memory revisioned task list, one per agent session

func NewTodoStore

func NewTodoStore() *TodoStore

NewTodoStore returns an empty store at revision zero

func TodoStoreOf

func TodoStoreOf(env *Env) *TodoStore

TodoStoreOf returns the session store kept under env.Values["todo_list"], nil when absent

func (*TodoStore) FormatForInjection

func (s *TodoStore) FormatForInjection() string

FormatForInjection renders the active items for post compression injection, empty when nothing is active

func (*TodoStore) HasItems

func (s *TodoStore) HasItems() bool

HasItems reports whether the list is non empty

func (*TodoStore) Read

func (s *TodoStore) Read() []TodoItem

Read returns copies of the items in priority order

func (*TodoStore) Restore

func (s *TodoStore) Restore(todos []any, revision any) []TodoItem

Restore loads a trusted snapshot without manufacturing a new revision

func (*TodoStore) Revision

func (s *TodoStore) Revision() int

Revision is the monotonic write counter clients use to reject stale updates

func (*TodoStore) Snapshot

func (s *TodoStore) Snapshot() map[string]any

Snapshot is the full state clients reconcile atomically

func (*TodoStore) Write

func (s *TodoStore) Write(todos []any, merge bool) ([]TodoItem, error)

Write replaces the list or merges by id and returns the full list, an invalid item leaves the list untouched

type ToolCallEntry

type ToolCallEntry struct {
	Name      string
	Arguments *pyjson.Object
}

ToolCallEntry is one normalized tool_call batch entry, its arguments the dict Python holds

func NormalizeToolCallEntries

func NormalizeToolCallEntries(args map[string]any) ([]ToolCallEntry, string)

NormalizeToolCallEntries turns tool_call arguments holding Python values into entries, accepting the legacy single shape

func (ToolCallEntry) HandlerArgs

func (e ToolCallEntry) HandlerArgs() map[string]any

Arguments of an entry in the DecodeWTF8 shapes tool handlers read

type ToolCallGuardrailConfig

type ToolCallGuardrailConfig struct {
	WarningsEnabled               bool
	HardStopEnabled               bool
	NonInteractiveHardStopEnabled bool
	ExactFailureWarnAfter         int
	ExactFailureBlockAfter        int
	SameToolFailureWarnAfter      int
	SameToolFailureHaltAfter      int
	NoProgressWarnAfter           int
	NoProgressBlockAfter          int
	IdempotentTools               map[string]bool
	MutatingTools                 map[string]bool
	LoopCaps                      LoopCapConfig
}

ToolCallGuardrailConfig holds thresholds for per turn tool call loop detection

func DefaultToolCallGuardrailConfig

func DefaultToolCallGuardrailConfig() ToolCallGuardrailConfig

DefaultToolCallGuardrailConfig returns the warn only defaults

func ToolCallGuardrailConfigFromMap

func ToolCallGuardrailConfigFromMap(data map[string]any, platform string) ToolCallGuardrailConfig

ToolCallGuardrailConfigFromMap builds the config from tool_loop_guardrails with nested keys winning

type ToolCallGuardrailController

type ToolCallGuardrailController struct {
	Config ToolCallGuardrailConfig
	// contains filtered or unexported fields
}

ToolCallGuardrailController tracks per turn tool call observations and returns decisions

func NewToolCallGuardrailController

func NewToolCallGuardrailController(cfg *ToolCallGuardrailConfig) *ToolCallGuardrailController

NewToolCallGuardrailController returns a controller reset for a new turn

func (*ToolCallGuardrailController) AfterCall

func (c *ToolCallGuardrailController) AfterCall(toolName string, args map[string]any, result *string, failed *bool) ToolGuardrailDecision

AfterCall records the outcome and returns warnings or halts for repeated failures and no progress

func (*ToolCallGuardrailController) BeforeCall

func (c *ToolCallGuardrailController) BeforeCall(toolName string, args map[string]any) ToolGuardrailDecision

BeforeCall decides whether a call may execute given the turn's failure and progress history

func (*ToolCallGuardrailController) HaltDecision

HaltDecision is the block or halt recorded this turn or nil

func (*ToolCallGuardrailController) ObserveCall

func (c *ToolCallGuardrailController) ObserveCall(toolName string, args map[string]any, result any, toolCallID string, failed bool) IdenticalCallObservation

ObserveCall tracks consecutive identical calls returning the notice and dedupe stub

func (*ToolCallGuardrailController) RecordPersistedResult

func (c *ToolCallGuardrailController) RecordPersistedResult(toolCallID, filePath string)

RecordPersistedResult remembers the spillover path a persisted result was saved to

func (*ToolCallGuardrailController) ResetForTurn

func (c *ToolCallGuardrailController) ResetForTurn()

ResetForTurn clears every per turn counter and streak

type ToolCallRef

type ToolCallRef struct {
	Name    string
	Args    map[string]any
	RawArgs string
	TaskID  string
	CallID  string
	Trace   []map[string]any
}

ToolCallRef is the identity of one call as every hook and result message sees it

type ToolCallSignature

type ToolCallSignature struct {
	ToolName string
	ArgsHash string
}

ToolCallSignature is the stable non reversible identity of a tool name plus canonical args

func ToolCallSignatureFromCall

func ToolCallSignatureFromCall(toolName string, args map[string]any) ToolCallSignature

ToolCallSignatureFromCall hashes the canonical args for one call

func (ToolCallSignature) ToMetadata

func (s ToolCallSignature) ToMetadata() map[string]string

ToMetadata returns the public signature fields without raw argument values

type ToolExecutionMiddleware

type ToolExecutionMiddleware func(ctx context.Context, env *Env, name string, args, originalArgs map[string]any, ids ToolHookIDs, next func(map[string]any) (string, error)) (string, error)

ToolExecutionMiddleware wraps the one downstream execution and must call next at most once

type ToolGuardrailDecision

type ToolGuardrailDecision struct {
	Action    string
	Code      string
	Message   string
	ToolName  string
	Count     int
	Signature *ToolCallSignature
}

ToolGuardrailDecision is the verdict of the guardrail controller for one call

func (ToolGuardrailDecision) AllowsExecution

func (d ToolGuardrailDecision) AllowsExecution() bool

AllowsExecution is true for allow and warn

func (ToolGuardrailDecision) ShouldHalt

func (d ToolGuardrailDecision) ShouldHalt() bool

ShouldHalt is true for block and halt

func (ToolGuardrailDecision) ToMetadata

func (d ToolGuardrailDecision) ToMetadata() map[string]any

ToMetadata returns the decision fields with the signature omitted when absent

type ToolHookIDs

type ToolHookIDs struct {
	TaskID       string
	SessionID    string
	ToolCallID   string
	TurnID       string
	APIRequestID string
}

ToolHookIDs are the identity fields every hook and middleware call carries

type ToolLabel

type ToolLabel struct {
	Kind    string
	App     string
	Action  string
	Emoji   string
	Name    string
	Preview string
}

ToolLabel is the friendly app and action label of one tool call

func BridgeToolLabels

func BridgeToolLabels(ctx context.Context, env *Env, toolName string, args map[string]any) []ToolLabel

BridgeToolLabels lists the labels of a call when friendly labels are enabled

func LabelForToolName

func LabelForToolName(env *Env, name string, arguments any) (ToolLabel, bool)

LabelForToolName labels a connector, MCP, or local tool name, ok false for a blank name

func LabelsForCall

func LabelsForCall(env *Env, functionName string, functionArgs any) []ToolLabel

LabelsForCall lists the friendly labels of a tool call, one per bridged call

func ToolLabelsForCall

func ToolLabelsForCall(ctx context.Context, env *Env, toolName string, args map[string]any) []ToolLabel

ToolLabelsForCall applies the skin's emoji overrides to the labels of a call

func (ToolLabel) AsPayload

func (l ToolLabel) AsPayload() map[string]string

AsPayload renders the label as the string map gateway cards consume

func (ToolLabel) Text

func (l ToolLabel) Text() string

Text joins the app and action with a middle dot

type ToolPreview

type ToolPreview struct {
	Text      string
	Truncated bool
	URL       string
}

ToolPreview is a compact tool preview plus presentation facts lost to truncation

func PrepareToolPreview

func PrepareToolPreview(env *Env, toolName string, args map[string]any, fallback string, maxLen int) ToolPreview

PrepareToolPreview builds a compact preview plus explicit truncation and URL facts

type ToolRequestMiddleware

type ToolRequestMiddleware func(ctx context.Context, env *Env, name string, args, originalArgs map[string]any, ids ToolHookIDs) RequestMiddlewareDirective

ToolRequestMiddleware rewrites arguments before hooks, guardrails, approvals, and execution

type ToolRowPart

type ToolRowPart struct {
	Emoji, Verb, Detail string
	Failure             *string
}

One completed call row without padding, Failure nil when the row succeeded

func GetToolRowParts

func GetToolRowParts(ctx context.Context, env *Env, toolName string, args map[string]any, result any, isError bool) (parts []ToolRowPart)

The emoji, verb, detail and failure of each row one completed call shows

type ToolSearchConfig

type ToolSearchConfig struct {
	Enabled            string
	ThresholdPct       float64
	SearchDefaultLimit int
	MaxSearchLimit     int
	Listing            string
	ListingMaxTokens   int
	// Nil keeps the curated default while an explicit set replaces it wholesale
	DeferTools map[string]bool
}

ToolSearchConfig is the resolved and validated tool search configuration for one assembly

func LoadToolSearchConfig

func LoadToolSearchConfig(env *Env) ToolSearchConfig

LoadToolSearchConfig reads tools.tool_search from the session config with defaults on any failure

func ToolSearchConfigFromRaw

func ToolSearchConfigFromRaw(raw any) ToolSearchConfig

ToolSearchConfigFromRaw builds the config from a raw map, legacy bool, or nil with every field clamped

func (ToolSearchConfig) EffectiveDeferTools

func (c ToolSearchConfig) EffectiveDeferTools() map[string]bool

EffectiveDeferTools returns the curated default set unless the config named its own list

type ToolValidationVerdict

type ToolValidationVerdict struct {
	// Action is ok, continue, or return
	Action            string
	Result            map[string]any
	MixedInvalidBatch bool
}

ToolValidationVerdict is the outcome of ValidateToolCalls

func ValidateToolCalls

func ValidateToolCalls(host TurnValidationHost, toolCalls []state.ToolCall, finishReason string) ToolValidationVerdict

ValidateToolCalls repairs names, normalizes args, and applies the strike rules for one assistant turn

type ToolsFlowHooks

type ToolsFlowHooks struct {
	// Per server MCP tool selection
	ConfigureMCP func(ctx context.Context, cfg config.Tree, ask setupflow.Asker) error
	// xAI Grok OAuth device login saving tokens only
	XAILogin func(ctx context.Context, h string, out io.Writer) bool
}

Steps of the tools flow that live in packages above this one, installed by the gateway server

type ToolsSetup

type ToolsSetup struct {
	Ctx  context.Context
	Env  *Env
	Con  *cliui.Console
	Ask  setupflow.Asker
	Flow ToolsFlowHooks
}

One tools configuration run, its questions going through Ask and Flow when set else the console

func (*ToolsSetup) IsProviderActive

func (s *ToolsSetup) IsProviderActive(provider *pyjson.Object, cfg config.Tree) (bool, error)

Whether a provider row matches the active config

func (*ToolsSetup) PostSetupAlreadyInstalled

func (s *ToolsSetup) PostSetupAlreadyInstalled(postSetupKey string) (installed bool)

Whether a post setup install side effect is satisfied, true when no check is registered or the check fails

func (*ToolsSetup) RunPostSetupCommand

func (s *ToolsSetup) RunPostSetupCommand(ns map[string]any) int

Non interactive post-setup runner, 0 ok, 1 hook failure, 2 missing or unknown key

func (*ToolsSetup) ToolsCommand

func (s *ToolsSetup) ToolsCommand(ns map[string]any, firstInstall bool, cfg config.Tree) error

Entry of icebath tools and setup tools, first install skipping the menu, cfg receiving the saved platform lists

func (*ToolsSetup) ValidPostSetupKeys

func (s *ToolsSetup) ValidPostSetupKeys() map[string]bool

Post setup keys declared by any visible provider, the allowlist the post-setup command validates against

func (*ToolsSetup) VisibleProviders

func (s *ToolsSetup) VisibleProviders(cat *pyjson.Object) ([]*pyjson.Object, error)

Provider rows of a category, plugin rows after the catalog rows

type Toolset

type Toolset struct {
	Description string
	Tools       []string
	Includes    []string
	Posture     bool
	Module      string
}

Toolset is one named tool group with its includes

func StaticToolset

func StaticToolset(name string) (Toolset, bool)

StaticToolset is the static table entry of a toolset with copied tool and include lists

type ToolsetDetail

type ToolsetDetail struct {
	Name          string
	Description   string
	DirectTools   []string
	Includes      []string
	ResolvedTools []string
	ToolCount     int
	IsComposite   bool
}

ToolsetDetail is a toolset with its resolved members for display

type ToolsetInfo

type ToolsetInfo struct {
	Name         string
	Available    bool
	Tools        []string
	Description  string
	Requirements []string
	Check        func(*Env) bool
}

ToolsetInfo describes one toolset for display surfaces

type TransformToolResultHook

type TransformToolResultHook func(ctx context.Context, env *Env, ev PostToolCallEvent) (string, bool)

TransformToolResultHook may replace the result string before it enters context

type TransitionFields

type TransitionFields struct {
	Detail     *string
	ConnectURL *string
	Attempt    *string
	Extra      *pyjson.Object
}

TransitionFields carries the optional row fields a transition writes, nil leaves a field alone

type TreeRecord

type TreeRecord struct {
	Name      string   `json:"name"`
	Path      string   `json:"path"`
	Branch    string   `json:"branch"`
	AgeDays   float64  `json:"age_days"`
	SizeMB    *int     `json:"size_mb"`
	Verdict   string   `json:"verdict"`
	Reason    string   `json:"reason"`
	Untracked []string `json:"untracked"`
}

One tree under .worktrees with its reclaim verdict

func AuditWorktrees

func AuditWorktrees(ctx context.Context, repoRoot string, withSizes bool, olderThanDays *float64) ([]TreeRecord, error)

Classifies every tree under .worktrees without mutating anything, the age gate only ever keeping young trees

type TreeScan

type TreeScan struct {
	Embedded  []string
	Entries   int
	Truncated bool
}

Embedded repositories found in a tree, the walked entry count and whether the walk stopped at the cap

func ScanTree

func ScanTree(wtPath string) (*TreeScan, error)

Embedded repositories of the tree, ignored or not, walking collapsed ignored directories within the entry cap

type TruncateOptions

type TruncateOptions struct {
	MaxChars      *int
	ContextLength *int
	ReadPath      string
	NoQueue       bool
}

Options of TruncateContent, nil pointers being the Python None defaults

type TurnBusyError

type TurnBusyError struct {
	Profile       string
	WaitedSeconds float64
}

A delivery turn already running for the target profile, waited roughly the given seconds

func (*TurnBusyError) Error

func (e *TurnBusyError) Error() string

func (*TurnBusyError) PyTypeName

func (e *TurnBusyError) PyTypeName() string

Python class name of the refusal

func (*TurnBusyError) Reason

func (e *TurnBusyError) Reason() string

Structured refusal reason of the busy turn

type TurnExitOptions

type TurnExitOptions struct {
	KanbanWorker           bool
	CredentialsRateLimited bool
	CredentialsTerminal    bool
	TransientReasons       map[string]bool
	TerminalReasons        map[string]bool
}

TurnExitOptions carries the worker identity and credential failure flags for the exit code mapping

type TurnValidationHost

type TurnValidationHost interface {
	ValidToolNames() map[string]bool
	RepairToolName(name string) string
	// Tool result for a call whose name stays unresolved, known when it names a registered tool the request did not offer
	InvalidToolContent(name string) (content string, known bool)
	Messages() []*state.Message
	AppendAssistantMessage()
	AppendToolErrorResults(contentFor func(tc state.ToolCall) string)
	PartialExit(finalResponse string) map[string]any
	CleanupTaskResources()
	Print(text string, force bool)
	BufferPrint(text string)
	FlushStatusBuffer()
	SiteCopy(code string) string
	LogPrefix() string
	Retries() *TurnValidationRetries
}

TurnValidationHost is the agent state ValidateToolCalls reads and mutates

type TurnValidationRetries

type TurnValidationRetries struct {
	InvalidTool int
	InvalidJSON int
}

TurnValidationRetries holds the per session strike counters

type UnavailableToolset

type UnavailableToolset struct {
	Name    string
	EnvVars []string
	Tools   []string
}

UnavailableToolset is one toolset no session can expose and why

func FilterToEnabledToolsets

func FilterToEnabledToolsets(unavailable []UnavailableToolset, enabled []string, resolve func(string) ([]string, error)) []UnavailableToolset

FilterToEnabledToolsets keeps the unavailable entries whose name or tools fall inside the session toolset selection

type UnlockPrompt

type UnlockPrompt func(backendName, displayName string) string

UnlockPrompt asks the master password of an external password manager, empty when cancelled

func GetUnlockPromptCallback

func GetUnlockPromptCallback(ctx context.Context) UnlockPrompt

The master password prompt of the current thread, nil in headless contexts

type UpdateProjectFields

type UpdateProjectFields struct {
	Name        *string
	Description *string
	Icon        *string
	Color       *string
	BoardSlug   *string
}

UpdateProjectFields are the patchable top level fields, nil leaves a field untouched and empty clears icon, color and board slug

type VercelAuthStatus

type VercelAuthStatus struct {
	OK          bool
	Label       string
	DetailLines []string
}

VercelAuthStatus describes the Vercel auth configuration without exposing secret values

func DescribeVercelAuth

func DescribeVercelAuth(env *Env) VercelAuthStatus

DescribeVercelAuth reports the auth mode from the secret scope, OIDC first then the token tuple

type VercelOptions

type VercelOptions struct {
	Runtime, Image, Cwd string
	Timeout, Memory     int
	CPU                 float64
	Disk                int
	Persistent          bool
	TaskID              string
}

VercelOptions are the sandbox settings, memory and disk in MB

type VerdictWindow

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

VerdictWindow collects the earliest expiry of every cached verdict consulted inside it

func WithVerdictWindow

func WithVerdictWindow(ctx context.Context) (context.Context, *VerdictWindow)

WithVerdictWindow binds a window that definition reads stamp with their verdict deadlines

func (*VerdictWindow) Expiry

func (w *VerdictWindow) Expiry() (time.Time, bool)

Expiry returns the earliest consulted verdict deadline, zero when every verdict was uncached

type VisionCapabilitySource

type VisionCapabilitySource interface {
	// Vision flags of the provider profile registered under a name or alias, found false when none is
	ProviderVisionProfile(provider string) (supportsVision, supportsVisionToolMessages, found bool)
	// Reports whether the provider routes vendor prefixed model ids to other providers
	IsRoutingAggregator(provider string) bool
	// Catalog vision verdict with profile model capabilities and overrides applied, known false when nothing knows
	CatalogSupportsVision(ctx context.Context, provider, model string) (supported, known bool)
	// Base slug of a Codex context variant picker id
	StripCodexContextVariantSuffix(model string) string
	// Reports whether a base URL is the managed local server this install launched
	IsManagedEndpoint(baseURL string) bool
	// Ground truth vision support of a staged managed model, known false when the model is not staged
	ManagedModelSupportsVision(ctx context.Context, model string) (supported, known bool)
	// Reports whether a base URL points at a loopback or private network endpoint
	IsLocalEndpoint(baseURL string) bool
	// Server family behind a local endpoint such as ollama, empty when undetected
	DetectLocalServerType(ctx context.Context, baseURL, apiKey string) string
	// Ollama api show verdict for a model, known false when the server gave no answer
	QueryOllamaSupportsVision(ctx context.Context, model, baseURL, apiKey string) (supported, known bool)
}

VisionCapabilitySource answers model capability questions owned by pkg/provider, installed by the provider wiring

var VisionCapabilities VisionCapabilitySource

VisionCapabilities is the installed capability source, nil leaving every probe without a verdict

type WebPage

type WebPage struct {
	URL             string
	Title           string
	Content         string
	RawContent      string
	HasRaw          bool
	Error           string
	Metadata        map[string]any
	BlockedByPolicy map[string]any
	Cached          bool
	FinalURL        string
}

WebPage is one extract entry as providers report it before trimming

func ExtractCacheGet

func ExtractCacheGet(env *Env, u, format, provider string) *WebPage

ExtractCacheGet returns a fresh cached page as a WebPage with Cached set, nil on a miss

type WebProvider

type WebProvider interface {
	Name() string
	DisplayName() string
	// Cheap check only, no network, runs at registration and on every picker paint
	Available(env *Env) bool
	// Reports whether anonymous free tier calls can serve without credentials
	KeylessAvailable(env *Env) bool
	SupportsSearch() bool
	SupportsExtract() bool
	// Search returns the response or a pre flight error the dispatcher wraps
	Search(ctx context.Context, env *Env, query string, limit int) (*WebSearchResponse, error)
	// Extract returns one entry per url or a whole batch error eligible for rescue
	Extract(ctx context.Context, env *Env, urls []string, format string) ([]*WebPage, error)
}

WebProvider is one web search or extract backend

func ActiveExtractProvider

func ActiveExtractProvider(env *Env) WebProvider

Web extract provider the registry resolves for env, nil when none is available

func ActiveSearchProvider

func ActiveSearchProvider(env *Env) WebProvider

Web search provider the registry resolves for env, nil when none is available

func GetWebProvider

func GetWebProvider(env *Env, name string) WebProvider

GetWebProvider is the registry get_provider read of the env scope, nil when no loaded plugin registered it

func ListWebProviders

func ListWebProviders(env *Env) []WebProvider

ListWebProviders is the registry list_providers read of the env scope

func NewBraveFreeWebProvider

func NewBraveFreeWebProvider() WebProvider

Brave free tier search provider the web/brave_free plugin registers

func NewDDGSWebProvider

func NewDDGSWebProvider() WebProvider

DuckDuckGo search provider the web/ddgs plugin registers

func NewExaWebProvider

func NewExaWebProvider() WebProvider

Exa search and extract provider the web/exa plugin registers

func NewFirecrawlWebProvider

func NewFirecrawlWebProvider() WebProvider

Firecrawl search and extract provider the web/firecrawl plugin registers

func NewKeenableWebProvider

func NewKeenableWebProvider() WebProvider

Keenable search and fetch provider the web/keenable plugin registers

func NewOpenAINativeWebProvider

func NewOpenAINativeWebProvider() WebProvider

OpenAI native web search provider the web/openai_native plugin registers

func NewParallelWebProvider

func NewParallelWebProvider() WebProvider

Parallel search and extract provider the web/parallel plugin registers

func NewPerplexityWebProvider

func NewPerplexityWebProvider() WebProvider

Perplexity search and snippet provider the web/perplexity plugin registers

func NewSearXNGWebProvider

func NewSearXNGWebProvider() WebProvider

SearXNG search provider the web/searxng plugin registers

func NewTavilyWebProvider

func NewTavilyWebProvider() WebProvider

Tavily search and extract provider the web/tavily plugin registers

func NewXAIWebProvider

func NewXAIWebProvider() WebProvider

xAI Grok web search provider the web/xai plugin registers

type WebSearchData

type WebSearchData struct {
	Web          []WebSearchHit `json:"web"`
	ServedBy     string         `json:"served_by,omitempty"`
	RescuedFrom  string         `json:"rescued_from,omitempty"`
	FallbackFrom string         `json:"fallback_from,omitempty"`
	BackendError string         `json:"backend_error,omitempty"`
}

WebSearchData is the data block of a successful search

type WebSearchHit

type WebSearchHit struct {
	Title       string
	URL         string
	Description string
	Position    int
	TitleFirst  bool
}

WebSearchHit is one search row, title first for the brave, searxng, ddgs, tavily and xai wire shape

func (WebSearchHit) MarshalJSON

func (h WebSearchHit) MarshalJSON() ([]byte, error)

MarshalJSON keeps the historical key order of each wire shape

func (*WebSearchHit) UnmarshalJSON

func (h *WebSearchHit) UnmarshalJSON(data []byte) error

UnmarshalJSON reads either key order back into a hit

type WebSearchResponse

type WebSearchResponse struct {
	Success bool
	Data    *WebSearchData
	Error   string
}

WebSearchResponse is the search contract every provider returns

func SliceSearchResponse

func SliceSearchResponse(response *WebSearchResponse, limit int) *WebSearchResponse

SliceSearchResponse trims a bucketed response's result list down to the caller's limit

func (*WebSearchResponse) Clone

Clone returns an independent copy

func (*WebSearchResponse) MarshalJSON

func (r *WebSearchResponse) MarshalJSON() ([]byte, error)

MarshalJSON writes success, then data, then error

func (*WebSearchResponse) UnmarshalJSON

func (r *WebSearchResponse) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a response back from cached JSON

type WebsiteBlock

type WebsiteBlock struct {
	URL     string
	Host    string
	Rule    string
	Source  string
	Message string
}

WebsiteBlock describes why a URL was refused by the policy

func CheckWebsiteAccess

func CheckWebsiteAccess(env *Env, rawURL, configPath string) (*WebsiteBlock, error)

CheckWebsiteAccess returns nil when the URL is allowed else the block metadata, failing open on policy errors

type WebsitePolicy

type WebsitePolicy struct {
	Enabled bool
	Rules   []WebsiteRule
}

WebsitePolicy is the parsed blocklist of a config file

func LoadWebsiteBlocklist

func LoadWebsiteBlocklist(env *Env, configPath string) (*WebsitePolicy, error)

LoadWebsiteBlocklist parses the blocklist policy, caching the default config path for the TTL

type WebsitePolicyError

type WebsitePolicyError struct{ Msg string }

WebsitePolicyError reports a malformed website policy

func (*WebsitePolicyError) Error

func (e *WebsitePolicyError) Error() string

type WebsiteRule

type WebsiteRule struct {
	Pattern string
	Source  string
}

WebsiteRule is one normalized blocklist pattern with its source

type WorkerDelegationLedger

type WorkerDelegationLedger struct{ Store WorkerDelegationStore }

WorkerDelegationLedger forwards each ledger operation to the owner through the worker's store

func (*WorkerDelegationLedger) Ack

func (l *WorkerDelegationLedger) Ack(delegationID, claimID string) (any, error)

Acknowledges a claimed delivery

func (*WorkerDelegationLedger) Child

func (l *WorkerDelegationLedger) Child(delegationID string, entry map[string]any) (any, error)

Records one finished child of a running unit

func (*WorkerDelegationLedger) Claim

func (l *WorkerDelegationLedger) Claim(delegationID, claimID string) (any, error)

Claims a pending completion delivery

func (*WorkerDelegationLedger) Complete

func (l *WorkerDelegationLedger) Complete(event, result map[string]any) (any, error)

Persists a terminal event and result for the owner

func (*WorkerDelegationLedger) Defer

func (l *WorkerDelegationLedger) Defer(delegationID, claimID string) (any, error)

Returns an unadmitted claim without spending an attempt

func (*WorkerDelegationLedger) Dispatch

func (l *WorkerDelegationLedger) Dispatch(record map[string]any) (any, error)

Publishes a dispatch owned by the worker's own session, refusing foreign parents and routed producers

func (*WorkerDelegationLedger) Drop

func (l *WorkerDelegationLedger) Drop(delegationID, claimID string) (any, error)

Terminally drops a claimed delivery

func (*WorkerDelegationLedger) Read

func (l *WorkerDelegationLedger) Read(delegationID string) (any, error)

Reads a durable row the worker's session owns

func (*WorkerDelegationLedger) Release

func (l *WorkerDelegationLedger) Release(delegationID, claimID string) (any, error)

Releases a failed claim for retry

func (*WorkerDelegationLedger) Unscheduled

func (l *WorkerDelegationLedger) Unscheduled(delegationID string) (any, error)

Removes a dispatch whose worker could not be scheduled

type WorkerDelegationStore

type WorkerDelegationStore interface {
	ScopePID() int
	ScopeSessionID() string
	Apply(op string, payload map[string]any) (map[string]any, error)
}

WorkerDelegationStore is the worker's runtime session store whose durable outbox carries ledger writes to the owner

type WorkerID

type WorkerID int64

Identifies one tool execution worker like a thread ident

func NewWorkerID

func NewWorkerID() WorkerID

NewWorkerID allocates a fresh worker identity

func WorkerOf

func WorkerOf(ctx context.Context) WorkerID

WorkerOf returns the context's worker identity or zero

type WorkerPersistenceError

type WorkerPersistenceError struct{ Reason string }

Python WorkerPersistenceError raised when a worker process cannot persist through its owner

func (*WorkerPersistenceError) Error

func (e *WorkerPersistenceError) Error() string

func (*WorkerPersistenceError) PyTypeName

func (e *WorkerPersistenceError) PyTypeName() string

type WorkingDiff

type WorkingDiff struct {
	Success   bool
	Stat      string
	Diff      string
	Untracked []string
	Empty     bool
	Error     string
}

One collected working tree diff or the reason git could not produce it

func CollectWorkingDiff

func CollectWorkingDiff(cwd, mode string, paths []string) WorkingDiff

Stat, diff and untracked files for working, staged or all modes, optionally limited to pathspecs

type WriteResult

type WriteResult struct {
	BytesWritten   int            `json:"bytes_written"`
	DirsCreated    bool           `json:"dirs_created"`
	Verified       *bool          `json:"verified,omitempty"`
	Lint           *pyjson.Object `json:"lint,omitempty"`
	LSPDiagnostics string         `json:"lsp_diagnostics,omitempty"`
	Error          string         `json:"error,omitempty"`
	Warning        string         `json:"warning,omitempty"`
	// Sha256 of the bytes written, nil when the backend could not hash them
	ContentSha256 *string `json:"-"`
}

WriteResult is one file write with its verification, lint and LSP diagnostics

Source Files

Directories

Path Synopsis
Package anydoc converts documents to Markdown through the embedded anydoc 0.2.4 WebAssembly build
Package anydoc converts documents to Markdown through the embedded anydoc 0.2.4 WebAssembly build

Jump to

Keyboard shortcuts

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